text
stringlengths
14
6.51M
unit DW.OSDevice.iOS; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // RTL System.Types; type /// <remarks> /// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS /// </remarks> TPlatformOSDevice = record public class function GetDeviceName: string; static; class function GetPackageID: string; static; class function GetPackageVersion: string; static; class function GetUniqueDeviceID: string; static; class function IsTouchDevice: Boolean; static; end; implementation uses // RTL System.SysUtils, // Mac Macapi.Helpers, // iOS iOSapi.Helpers, // DW DW.Macapi.Helpers; { TPlatformOSDevice } class function TPlatformOSDevice.GetDeviceName: string; begin Result := NSStrToStr(TiOSHelper.CurrentDevice.name); end; class function TPlatformOSDevice.GetUniqueDeviceID: string; begin Result := NSStrToStr(TiOSHelper.CurrentDevice.identifierForVendor.UUIDString); end; class function TPlatformOSDevice.IsTouchDevice: Boolean; begin Result := True; end; class function TPlatformOSDevice.GetPackageID: string; begin Result := GetBundleValue('CFBundleIdentifier'); end; class function TPlatformOSDevice.GetPackageVersion: string; begin Result := GetBundleValue('CFBundleVersion'); end; end.
unit dsdPivotGrid; interface uses Classes, cxCustomPivotGrid, cxDBPivotGrid; type TCalcFieldsType = (cfSumma, cfMultiplication, cfDivision, cfPercent, cfMulDiv); TdsdPivotGridField = class (TCollectionItem) private FField: TcxDBPivotGridField; protected procedure SetField(const Value: TcxDBPivotGridField); virtual; function GetDisplayName: string; override; public procedure Assign(Source: TPersistent); override; published property Field: TcxDBPivotGridField read FField write SetField; end; TdsdPivotGridFields = class (TOwnedCollection) private function GetItem(Index: Integer): TdsdPivotGridField; procedure SetItem(Index: Integer; const Value: TdsdPivotGridField); public function Add: TdsdPivotGridField; property Items[Index: Integer]: TdsdPivotGridField read GetItem write SetItem; default; end; TdsdPivotGridCalcFields = class (TComponent) private FDBPivotGrid: TcxDBPivotGrid; FCalcField: TcxDBPivotGridField; FPivotGridFields: TdsdPivotGridFields; FCalcFieldsType: TCalcFieldsType; protected procedure SetPivotGrid(const Value: TcxDBPivotGrid); virtual; procedure SetCalcField(const Value: TcxDBPivotGridField); virtual; function GetSpecification : string; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CalculateCustomSummary( Sender: TcxPivotGridField; ASummary: TcxPivotGridCrossCellSummary); published property PivotGrid: TcxDBPivotGrid read FDBPivotGrid write SetPivotGrid; property CalcField: TcxDBPivotGridField read FCalcField write SetCalcField; property GridFields: TdsdPivotGridFields read FPivotGridFields write FPivotGridFields; property CalcFieldsType: TCalcFieldsType read FCalcFieldsType write FCalcFieldsType default cfSumma; property Specification: string read GetSpecification; end; procedure Register; implementation uses Storage, TypInfo, System.SysUtils, cxTextEdit, VCL.Forms, XMLDoc, XMLIntf, StrUtils, cxCurrencyEdit, cxCheckBox, cxCalendar, Variants, UITypes, Windows, Dialogs; { TdsdPivotGridField } procedure TdsdPivotGridField.Assign(Source: TPersistent); begin if Source is TdsdPivotGridField then Self.Field := TdsdPivotGridField(Source).Field else inherited; //raises an exception end; function TdsdPivotGridField.GetDisplayName: string; begin if Assigned(FField) then Result := FField.Name else Result := inherited; end; procedure TdsdPivotGridField.SetField(const Value: TcxDBPivotGridField); begin if FField <> Value then begin if not (csLoading in TdsdPivotGridCalcFields(Collection.Owner).ComponentState) then begin if not Assigned(TdsdPivotGridCalcFields(Collection.Owner).PivotGrid) then begin FField := Nil; Exit; end; if TdsdPivotGridCalcFields(Collection.Owner).PivotGrid <> Value.PivotGrid then begin FField := Nil; Exit; end; end; if Assigned(Collection) and Assigned(Value) then Value.FreeNotification(TComponent(Collection.Owner)); FField := Value; end; end; { TdsdPivotGridFields } function TdsdPivotGridFields.Add: TdsdPivotGridField; begin result := TdsdPivotGridField(inherited Add); end; function TdsdPivotGridFields.GetItem(Index: Integer): TdsdPivotGridField; begin Result := TdsdPivotGridField(inherited GetItem(Index)); end; procedure TdsdPivotGridFields.SetItem(Index: Integer; const Value: TdsdPivotGridField); begin inherited SetItem(Index, Value); end; { TdsdPivotGridCalcFields } constructor TdsdPivotGridCalcFields.Create(AOwner: TComponent); begin inherited; FPivotGridFields:= TdsdPivotGridFields.Create(Self, TdsdPivotGridField); end; destructor TdsdPivotGridCalcFields.Destroy; begin FreeAndNil(FPivotGridFields); inherited; end; procedure TdsdPivotGridCalcFields.Notification(AComponent: TComponent; Operation: TOperation); var i: integer; begin inherited; if (csDestroying in ComponentState) then exit; if (Operation = opRemove) then begin if Assigned(FPivotGridFields) then begin for I := FPivotGridFields.Count - 1 downto 0 do if FPivotGridFields.Items[i].Field = AComponent then FPivotGridFields.Delete(I); end; if AComponent = PivotGrid then PivotGrid := Nil; if AComponent = CalcField then CalcField := nil; end; if (Operation = opInsert) and (AComponent = CalcField) then begin CalcField.SummaryType := stCustom; CalcField.OnCalculateCustomSummary := CalculateCustomSummary; end; end; procedure TdsdPivotGridCalcFields.SetPivotGrid(const Value: TcxDBPivotGrid); begin if FDBPivotGrid <> Value then begin if not (csLoading in ComponentState) then begin if Assigned(CalcField) then begin CalcField.OnCalculateCustomSummary := Nil; CalcField := nil; end; if FPivotGridFields.Count > 0 then FPivotGridFields.Clear; end; FDBPivotGrid := Value; end; end; procedure TdsdPivotGridCalcFields.SetCalcField(const Value: TcxDBPivotGridField); begin if FCalcField <> Value then begin if not (csLoading in ComponentState) then begin if not Assigned(FDBPivotGrid) or not Assigned(Value) then begin FCalcField := Nil; Exit; end; if FDBPivotGrid <> Value.PivotGrid then begin FCalcField := Nil; Exit; end; end; if not (csDesigning in ComponentState) and Assigned(FCalcField) then CalcField.OnCalculateCustomSummary := Nil; FCalcField := Value; if not (csDesigning in ComponentState) and Assigned(FCalcField) then begin CalcField.SummaryType := stCustom; CalcField.OnCalculateCustomSummary := CalculateCustomSummary; end; end; end; function TdsdPivotGridCalcFields.GetSpecification : string; begin case FCalcFieldsType of cfSumma : Result := '= F1 + F2 + ... + Fn'; cfMultiplication : Result := '= F1 * F2 * ... * Fn'; cfDivision : Result := '= F1 / F2'; cfPercent : Result := '= F1 / F2 * 100'; cfMulDiv : Result := '= F1 * F2 / F3'; end; end; procedure TdsdPivotGridCalcFields.CalculateCustomSummary( Sender: TcxPivotGridField; ASummary: TcxPivotGridCrossCellSummary); var Value1, Value2, Value3: Variant; I: integer; begin if not Assigned(FDBPivotGrid) then Exit; if not Assigned(FDBPivotGrid.DataSource) then Exit; if not Assigned(FDBPivotGrid.DataSource.DataSet) then Exit; if FDBPivotGrid.DataSource.DataSet.IsEmpty then Exit; if FPivotGridFields.Count <= 0 then Exit; case FCalcFieldsType of cfSumma : begin Value1 := 0.0; for I := 0 to FPivotGridFields.Count - 1 do if Assigned(FPivotGridFields.Items[I].Field) and (FPivotGridFields.Items[I].Field.Area = faData) then begin if ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[I].Field,stSum) <> Null then Value1 := Value1 + ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[I].Field,stSum); end; ASummary.Custom := Value1; end; cfMultiplication : begin if Assigned(FPivotGridFields.Items[0].Field) and (FPivotGridFields.Items[0].Field.Area = faData) then Value1 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[0].Field,stSum) else Value1 := 0; if Value1 = null then Value1 := 0; for I := 1 to FPivotGridFields.Count - 1 do begin if Assigned(FPivotGridFields.Items[I].Field) and (FPivotGridFields.Items[I].Field.Area = faData) then Value2 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[I].Field,stSum) else Value2 := 0; if Value2 = null then Value2 := 0; Value1 := Value1 * Value2; end; ASummary.Custom := Value1; end; cfDivision : if FPivotGridFields.Count >= 2 then begin if Assigned(FPivotGridFields.Items[0].Field) and (FPivotGridFields.Items[0].Field.Area = faData) then Value1 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[0].Field,stSum) else Value1 := 0; if Assigned(FPivotGridFields.Items[1].Field) and (FPivotGridFields.Items[1].Field.Area = faData) then Value2 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[1].Field,stSum) else Value2 := 0; if (Value1 = null) or (Value2 = null) or (Value2 = 0) then Exit; ASummary.Custom := Value1 / Value2; end; cfPercent : if FPivotGridFields.Count >= 2 then begin if Assigned(FPivotGridFields.Items[0].Field) and (FPivotGridFields.Items[0].Field.Area = faData) then Value1 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[0].Field,stSum) else Value1 := 0; if Assigned(FPivotGridFields.Items[1].Field) and (FPivotGridFields.Items[1].Field.Area = faData) then Value2 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[1].Field,stSum) else Value2 := 0; if (Value1 = null) or (Value2 = null) or (Value2 = 0) then Exit; ASummary.Custom := Value1 / Value2 * 100; end; cfMulDiv : if FPivotGridFields.Count >= 3 then begin if Assigned(FPivotGridFields.Items[0].Field) and (FPivotGridFields.Items[0].Field.Area = faData) then Value1 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[0].Field,stSum) else Value1 := 0; if Assigned(FPivotGridFields.Items[1].Field) and (FPivotGridFields.Items[1].Field.Area = faData) then Value2 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[1].Field,stSum) else Value2 := 0; if Assigned(FPivotGridFields.Items[2].Field) and (FPivotGridFields.Items[2].Field.Area = faData) then Value3 := ASummary.Owner.Row.GetCellByCrossItem(ASummary.Owner.Column).GetSummaryByField(FPivotGridFields.Items[2].Field,stSum) else Value3 := 0; if (Value1 = null) or (Value2 = null) or (Value3 = null) or (Value3 = 0) then Exit; ASummary.Custom := Value1 * Value2 / Value3; end; end; end; procedure Register; begin RegisterComponents('DSDComponent', [TdsdPivotGridCalcFields]); end; initialization Classes.RegisterClass(TdsdPivotGridCalcFields); end.
unit TNsRemotePublish.Infrastructure.Interfaces.Compression; interface uses {$IFNDEF FPC} System.Classes, System.SysUtils; {$ELSE} Classes, sysutils; {$ENDIF} type TOnProcessEvent = procedure(Sender : TObject; const Filename : string; Position: Int64) of object; ICompression = interface['{06475E05-906E-473F-8928-4A15B50955DE}'] function AddFileToCompressionBytesFromBytes(CompressionBytes : TBytes; FileBytes : TBytes) : TBytes; function AddFileToCompressionBytesFromDisk(const Path : string; CompressionBytes : TBytes) : TBytes; function AddDiskDirectoryToBytes(const Path : string) : TBytes; procedure AddDiskDirectoryToCompressionDisk(const Path: string; FilenamePath : string); function StreamCompressToBytes(Stream : TStream): TBytes; function StreamCompressToStream(Stream : TStream) : TStream; function StringCompressToBytes(const str : string): TBytes; function StringCompressToString(const str : string) : string; function ExtractFromDiskToBytes(const Path : string) : TBytes; function ExtractFromDiskToStream(const Path : string) : TStream; procedure ExtractFromStreamToDisk(Stream : TStream; const Destination : string); procedure ExtractFromBytesToDisk(CompressionBytes : TBytes; const Path : string); procedure ExtractFromDiskToDisk(const Source, Destination : string); procedure SubscribeOnProcess(Event: TOnProcessEvent); procedure CancelCurrentOperation; end; implementation end.
unit PnAjustaGrid; interface uses SysUtils, Classes, Controls, ExtCtrls, DBGrids, Buttons, Grids, Types, Forms; type tPanel1 = class(TPanel) private FtmbDBGrid: TDBGrid; FtmbCria: boolean; FAjusta: boolean; procedure SettmbDBGrid(const Value: TDBGrid); procedure SettmbCria(const Value: boolean); procedure SetAjusta(const Value: boolean); { Private declarations } protected { Protected declarations } public { Public declarations } i : array [0..99] of integer; SpeedButton : TSpeedButton; procedure Ajustar(Sender : TObject); {Ajusta Grid} procedure AjustarDinamic(Range : integer = 7); {Ajusta somente Fileds visiveis em um intervalo} procedure DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); published { Published declarations } constructor Create(AOwner : TComponent); override; destructor Destroy; override; property tmbDBGrid : TDBGrid read FtmbDBGrid write SettmbDBGrid; property tmbCria: boolean read FtmbCria write SettmbCria; property tmbAjusta: boolean read FAjusta write SetAjusta; end; procedure Register; implementation var PathBMP : String; procedure Register; begin RegisterComponents('CGLSOFT', [tPanel1]); end; { tPanel1 } procedure tPanel1.Ajustar(Sender: TObject); var y : integer; begin AjustarDinamic(); for y := 0 to FtmbDBGrid.Columns.Count -1 do begin FtmbDBGrid.Columns.Items[y].Width := (Length(Trim(FtmbDBGrid.Columns.Items[y].Title.Caption))* ( (Canvas.TextWidth('W') + Canvas.TextWidth('i') ) div 2)) + 8; if i[y] >= Length(Trim(FtmbDBGrid.Columns.Items[y].Title.Caption)) then FtmbDBGrid.Columns.Items[y].Width := ( ( (i[y])* ( ( Canvas.TextWidth('W') + Canvas.TextWidth('I') ) div 2) ) )+ 8; end; for y := Low(i) to high(i) do i[y] := 0; end; {Ajusta apenas registros visiveis} procedure tPanel1.AjustarDinamic(Range : integer = 7); var MinRec, MaxRec, yy, x : integer; Rec : integer; begin Rec := FtmbDBGrid.DataSource.DataSet.RecNo; MaxRec := Rec+Range; {consiste variaveis} try if Rec <= Range then Range := 0; if MaxRec > FtmbDBGrid.DataSource.DataSet.RecordCount then MaxRec := MaxRec - (MaxRec - FtmbDBGrid.DataSource.DataSet.RecordCount) ; {} MinRec := Rec-Range; FtmbDBGrid.DataSource.DataSet.RecNo := MinRec; {} for yy := MinRec to MaxRec do begin for x := 0 to FtmbDBGrid.Columns.Count-1 do if Length(FtmbDBGrid.Columns.Items[x].Field.AsString) > i[x] then i[x] := (Length(FtmbDBGrid.Columns.Items[x].Field.AsString)); FtmbDBGrid.DataSource.DataSet.RecNo := yy; end; {} FtmbDBGrid.DataSource.DataSet.RecNo := Rec; Except On E:Exception do Application.ProcessMessages; end; end; constructor tPanel1.Create(AOwner: TComponent); begin inherited; Caption := 'Alinha Grid'; AutoSize := true; PathBMP := ExtractFileDir( Application.ExeName )+ '\imagens'; end; destructor tPanel1.Destroy; begin inherited; end; procedure tPanel1.DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if Length(FtmbDBGrid.Columns.Items[DataCol].Field.AsString) > i[DataCol] then i[DataCol] := (Length(FtmbDBGrid.Columns.Items[DataCol].Field.AsString)); end; procedure tPanel1.SetAjusta(const Value: boolean); begin FAjusta := Value; if (FAjusta = true) and (FtmbDBGrid <> nil) and (FtmbCria = true ) then Ajustar(self); end; procedure tPanel1.SettmbCria(const Value: boolean); begin PathBMP := ExtractFileDir( Application.ExeName )+ '\imagens'; FtmbCria := Value; if FtmbCria = true then begin if SpeedButton = nil then begin Self.Caption := ''; SpeedButton := TSpeedButton.Create(self); with SpeedButton do begin Parent := self; Caption := '&Alinhar '; Glyph.LoadFromFile(PathBMP + '\ajusta.bmp'); height := 22; Width := 68; SpeedButton.NumGlyphs := 2; SpeedButton.OnClick := Ajustar; end; Autosize := true; Self.Caption := ''; SpeedButton.flat := TRUE; end; end; end; procedure tPanel1.SettmbDBGrid(const Value: TDBGrid); begin FtmbDBGrid := Value; //FtmbDBGrid.OnDrawColumnCell := DrawColumnCell; {desnecessario linkar o evento} end; end.
// --- Copyright © 2020 Matias A. P. // --- All rights reserved // --- maperx@gmail.com unit uConfigJson; interface uses JsonDataObjects, Variants, WinApi.Windows, System.SysUtils, System.Classes, uCipher; type TConfigJson = class; /// <remarks><remarks> TConfigElement = class private FConfigDB: TConfigJson; FElement: TJSONObject; FArrayID, FElementID: string; function GetCount: integer; function GetValueKey(const Index: integer): string; public property ArrayID: string read FArrayID; property ElementID: string read FElementID; property Count: integer read GetCount; property ValueKeys[const Index: integer]: string read GetValueKey; constructor Create(var ConfigDB: TConfigJson; const ArrayID, ElementID: string); overload; constructor Create(var ConfigDB: TConfigJson; const ArrayID: string; Element: TJSONObject); overload; function WriteValue(const ValueKey: string; const value: Variant): boolean; function WriteValueArray(const ValueKey: string; const value: array of Variant): boolean; function ReadValue(const ValueKey: string; out value: Variant): boolean; function ReadString(const ValueKey: string): string; function ReadValueArray(const ValueKey: string; out value: Variant): boolean; function ReadBool(const ValueKey: string; Def: boolean = False): boolean; function ReadInt64(const ValueKey: string; Default: int64 = 0): int64; function GetJSON: string; end; TConfigArray = class private FConfigDB: TConfigJson; FArray: TJSONArray; FArrayID: string; function GetCount: integer; function GetElement(const Index: integer): TConfigElement; public property ArrayID: string read FArrayID; property Count: integer read GetCount; property Elements[const Index: integer]: TConfigElement read GetElement; constructor Create(var ConfigDB: TConfigJson; const ArrayID: string); function WriteValue(const ElementID, ValueKey: string; const value: Variant): boolean; end; TConfigJson = class private JO: TJSONObject; FFileName, FPass: string; FCompressed, FEncrypted: boolean; function _InsertElemValue(var Element: TJSONObject; ValueKey: string; const value: Variant): boolean; function _InsertElemValueArray(var Element: TJSONObject; ValueKey: string; const value: array of Variant): boolean; function GetArray(const ID: string): TConfigArray; function GetSaveStream: TBytesStream; public property FileName: string read FFileName; property Compressed: boolean read FCompressed; property Encrypted: boolean read FEncrypted; property Arrays[const ID: string]: TConfigArray read GetArray; constructor Create; overload; constructor Create(var Stream: TBytesStream; const Compressed: boolean = False; const Encrypted: boolean = False; const Pass: string = ''); overload; constructor Create(const JSON: string; const Compressed: boolean = False; const Encrypted: boolean = False; const Pass: string = ''); overload; function GetJSON(Compact: boolean = True): string; function WriteValue(const ArrayID, ElementID, ValueKey: string; const value: Variant; Flush: boolean = False): boolean; function WriteValueArray(const ArrayID, ElementID, ValueKey: string; const value: array of Variant): boolean; function WriteString(const ArrayID, ElementID, ValueKey: string; const value: string; Cifrar: boolean = False): boolean; function ReadValue(const ArrayID, ElementID, ValueKey: string; out value: Variant): boolean; function ReadString(const ArrayID, ElementID, ValueKey: string; Cifrada: boolean = False): string; function ReadValueArray(const ArrayID, ElementID, ValueKey: string; out value: Variant): boolean; function ReadBool(const ArrayID, ElementID, ValueKey: string; Def: boolean = False): boolean; function ReadInt64(const ArrayID, ElementID, ValueKey: string; Default: int64 = 0): int64; function DeleteArray(const ArrayID: string): boolean; function DeleteElement(const ArrayID, ElementID: string): boolean; function DeleteValue(const ArrayID, ElementID, ValueKey: string): boolean; function Save(const FullPath: string = ''): boolean; // ; Compact: boolean = True function SaveToStream(var Stream: TBytesStream): boolean; procedure SetEncrypted(const Encrypted: boolean; const Pass: string = ''); procedure SetCompressed(const Compressed: boolean); function EstaVacio: boolean; function ExisteArray(const ArrayID: string): boolean; end; implementation uses System.Zip, REST.JSON, System.NetEncoding; const _id = '_id'; _pp = 'cWF9bWGyMTk7MQ'; type THeader = packed record Tag: string[3]; Compressed: boolean; Encrypted: boolean; end; constructor TConfigJson.Create; begin inherited; FPass := EmptyStr; FEncrypted := False; FCompressed := False; FFileName := EmptyStr; JO := TJSONObject.Create; end; constructor TConfigJson.Create(const JSON: string; const Compressed: boolean = False; const Encrypted: boolean = False; const Pass: string = ''); var FS: TBytesStream; SS: TStringStream; begin FS := TBytesStream.Create; try if FileExists(JSON) then begin FFileName := JSON; FS.LoadFromFile(FFileName); end else begin SS := TStringStream.Create; if JSON = '' then SS.WriteString('{}') else SS.WriteString(JSON); FS.LoadFromStream(SS); SS.Free; end; Create(FS, Compressed, Encrypted, Pass); finally FS.Free; end; end; constructor TConfigJson.Create(var Stream: TBytesStream; const Compressed: boolean = False; const Encrypted: boolean = False; const Pass: string = ''); var Cipher: TCipher; SS: TBytesStream; c, s: int64; Zip: TZipFile; bytes: TBytes; header: THeader; begin FPass := Pass; FEncrypted := Encrypted; FCompressed := Compressed; if (Stream = nil) then Exit; c := Stream.Size; s := sizeof(header); Stream.Position := 0; if c > s then Stream.Read(header, s); if (header.Tag <> 'CDB') then // si no tiene el header, es texto plano begin Stream.Position := 0; try JO := TJSONObject.ParseFromStream(Stream) as TJSONObject; except JO := TJSONObject.Create; end; Exit; end; // sacar el header SetLength(bytes, c); Stream.Position := s; c := Stream.Read(bytes, c); Stream.Clear; Stream.Write(bytes, c); Stream.Position := 0; if header.Encrypted then begin FEncrypted := True; Cipher := TCipher.Create; SS := TBytesStream.Create; try Cipher.DecryptStream(Stream, SS, FPass, haSHA1); c := SS.Size; SS.Position := 0; Stream.Clear; Stream.CopyFrom(SS, c); Stream.Position := 0; finally Cipher.Free; SS.Free; end; end; if header.Compressed then begin FCompressed := True; Zip := TZipFile.Create; try Zip.Open(Stream, zmRead); Zip.Read(0, bytes); c := Length(bytes); Stream.Clear; Stream.Write(bytes, c); Stream.Position := 0; finally Zip.Free; end; end; try JO := TJSONObject.ParseFromStream(Stream) as TJSONObject; except JO := TJSONObject.Create; end; end; function TConfigJson.DeleteArray(const ArrayID: string): boolean; var idx: integer; begin result := False; idx := JO.IndexOf(ArrayID); if idx >= 0 then begin JO.Delete(idx); result := True; end; end; function TConfigJson.DeleteElement(const ArrayID, ElementID: string): boolean; var i: integer; begin result := False; if ExisteArray(ArrayID) then for i := 0 to JO.A[ArrayID].Count - 1 do if JO.A[ArrayID].O[i].s[_id] = ElementID then begin JO.A[ArrayID].Delete(i); Break; end; end; function TConfigJson.DeleteValue(const ArrayID, ElementID, ValueKey: string): boolean; var i: integer; begin result := False; if ExisteArray(ArrayID) then for i := 0 to JO.A[ArrayID].Count - 1 do if JO.A[ArrayID].O[i].s[_id] = ElementID then begin JO.A[ArrayID].O[i].Delete(JO.A[ArrayID].O[i].IndexOf(ValueKey)); result := True; Break; end; end; function TConfigJson.GetArray(const ID: string): TConfigArray; begin result := TConfigArray.Create(self, ID); end; function TConfigJson.GetJSON(Compact: boolean): string; begin result := JO.ToJSON(Compact); end; function TConfigJson.EstaVacio: boolean; begin result := (JO.Count = 0) end; function TConfigJson.ExisteArray(const ArrayID: string): boolean; var idx: integer; begin result := False; idx := JO.IndexOf(ArrayID); result := (idx >= 0) and (JO.Items[idx].Typ = jdtArray); end; function TConfigJson._InsertElemValue(var Element: TJSONObject; ValueKey: string; const value: Variant): boolean; begin result := False; case VarType(value) of varInteger, varInt64, varByte, varWord: Element.L[ValueKey] := value; varSingle, varDouble, varCurrency: Element.F[ValueKey] := value; varBoolean: Element.B[ValueKey] := value; else Element.s[ValueKey] := value; end; result := True; end; function TConfigJson._InsertElemValueArray(var Element: TJSONObject; ValueKey: string; const value: array of Variant): boolean; var i: integer; begin result := False; if High(value) < 0 then Exit; Element.A[ValueKey].Clear; for i := Low(value) to High(value) do Element.A[ValueKey].Add(value[i]); result := True; end; function TConfigJson.WriteString(const ArrayID, ElementID, ValueKey, value: string; Cifrar: boolean): boolean; var str: string; ciph: TCipher; begin if Cifrar then begin ciph := TCipher.Create; try str := ciph.EncryptString(value, _pp, THashAlgorithm.haSHA1); str := TBase64Encoding.Base64.Encode(str); result := WriteValue(ArrayID, ElementID, ValueKey, str); finally ciph.Free; end; end else result := WriteValue(ArrayID, ElementID, ValueKey, value); end; function TConfigJson.WriteValue(const ArrayID, ElementID, ValueKey: string; const value: Variant; Flush: boolean = False): boolean; var elem: TJSONObject; i: integer; begin result := False; if ElementID = '' then Exit; elem := nil; for i := 0 to JO.A[ArrayID].Count - 1 do // buscar elemento de la coleccion que tenga _id=ElementID begin if JO.A[ArrayID].O[i].s[_id] = ElementID then begin elem := JO.A[ArrayID].O[i]; Break; end; end; if elem = nil then // si no existe el elemento agregarlo elem := JO.A[ArrayID].AddObject; elem.s[_id] := ElementID; if VarType(value) = varArray then result := _InsertElemValueArray(elem, ValueKey, value) else result := _InsertElemValue(elem, ValueKey, value); if Flush and result and (FFileName <> EmptyStr) then Save(FFileName); end; function TConfigJson.WriteValueArray(const ArrayID, ElementID, ValueKey: string; const value: array of Variant): boolean; var arr: TJSONArray; elem: TJSONObject; i: integer; begin elem := nil; result := False; arr := JO.A[ArrayID]; // buscar coleccion sino agregarla for i := 0 to arr.Count - 1 do // buscar elemento de la coleccion que tenga _id=ElementID begin if JO.A[ArrayID].O[i].s[_id] = ElementID then begin elem := arr.Items[i].ObjectValue; Break; end; end; if elem = nil then // si no existe el elemento agregarlo elem := JO.A[ArrayID].AddObject; elem.s[_id] := ElementID; result := _InsertElemValueArray(elem, ValueKey, value); end; function TConfigJson.ReadValue(const ArrayID, ElementID, ValueKey: string; out value: Variant): boolean; var i: integer; begin result := False; try if ExisteArray(ArrayID) then for i := 0 to JO.A[ArrayID].Count - 1 do begin if JO.A[ArrayID].O[i].s[_id] = ElementID then begin if not JO.A[ArrayID].O[i].Values[ValueKey].IsNull then begin value := JO.A[ArrayID].O[i].Values[ValueKey]; result := True; Break; end; end; end; except end; end; function TConfigJson.ReadString(const ArrayID, ElementID, ValueKey: string; Cifrada: boolean = False): string; var ciph: TCipher; v: Variant; begin result := EmptyStr; if ReadValue(ArrayID, ElementID, ValueKey, v) then result := v; if Cifrada then begin ciph := TCipher.Create; try result := TBase64Encoding.Base64.Decode(result); result := ciph.DecryptString(result, _pp, THashAlgorithm.haSHA1); finally ciph.Free; end; end; end; function TConfigJson.ReadValueArray(const ArrayID, ElementID, ValueKey: string; out value: Variant): boolean; var i, j: integer; arr: TJSONArray; begin result := False; try if ExisteArray(ArrayID) then for i := 0 to JO.A[ArrayID].Count - 1 do begin if JO.A[ArrayID].O[i].s[_id] = ElementID then begin arr := JO.A[ArrayID].O[i].Values[ValueKey].ArrayValue; value := VarArrayCreate([0, arr.Count - 1], varVariant); for j := 0 to arr.Count - 1 do value[j] := arr.Values[j]; result := True; end; Break; end; except end; end; function TConfigJson.ReadBool(const ArrayID, ElementID, ValueKey: string; Def: boolean = False): boolean; var value: Variant; begin result := Def; if ReadValue(ArrayID, ElementID, ValueKey, value) then result := value; end; function TConfigJson.ReadInt64(const ArrayID, ElementID, ValueKey: string; Default: int64 = 0): int64; var value: Variant; begin result := Default; if ReadValue(ArrayID, ElementID, ValueKey, value) then result := value; end; function TConfigJson.GetSaveStream: TBytesStream; var Cipher: TCipher; Zip: TZipFile; FS: TStringStream; TS, ZipStream: TBytesStream; header: THeader; c: int64; begin result := TBytesStream.Create(); FS := TStringStream.Create; FS.WriteString(GetJSON); FS.Position := 0; try if (not FCompressed) and (not FEncrypted) then begin result.CopyFrom(FS, 0); Exit; end; header.Tag := 'CDB'; header.Compressed := FCompressed; header.Encrypted := FEncrypted; if FCompressed then begin ZipStream := TBytesStream.Create; Zip := TZipFile.Create; try Zip.Open(ZipStream, zmWrite); Zip.Add(FS, ExtractFileName(FFileName)); Zip.Close; finally Zip.Free; end; ZipStream.Position := 0; end; TS := TBytesStream.Create; TS.Write(header, sizeof(header)); try if FEncrypted then begin Cipher := TCipher.Create; if FCompressed then Cipher.EncryptStream(ZipStream, TS, FPass, haSHA1) else Cipher.EncryptStream(FS, TS, FPass, haSHA1); result.CopyFrom(TS, 0); Cipher.Free; end else if FCompressed then begin c := ZipStream.Size; ZipStream.Position := 0; TS.Write(ZipStream.bytes, c); result.CopyFrom(TS, 0); end; finally TS.Free; if FCompressed then ZipStream.Free; end; finally FS.Free; end; end; function TConfigJson.Save(const FullPath: string = ''): boolean; var Stream: TBytesStream; begin result := False; if FullPath <> '' then FFileName := FullPath; if (FFileName = '') then Exit; Stream := GetSaveStream; Stream.SaveToFile(FFileName); result := True; end; function TConfigJson.SaveToStream(var Stream: TBytesStream): boolean; begin result := False; Stream := GetSaveStream; result := (Stream.Size > 0); end; procedure TConfigJson.SetCompressed(const Compressed: boolean); begin FCompressed := Compressed; end; procedure TConfigJson.SetEncrypted(const Encrypted: boolean; const Pass: string); begin FEncrypted := Encrypted; if Pass <> '' then FPass := Pass; end; { TConfigElement } constructor TConfigElement.Create(var ConfigDB: TConfigJson; const ArrayID, ElementID: string); var arr: TJSONArray; i: integer; begin FConfigDB := ConfigDB; FArrayID := ArrayID; FElementID := ElementID; FElement := nil; arr := FConfigDB.JO.A[ArrayID]; // buscar array sino agregarlo for i := 0 to arr.Count - 1 do // buscar elemento de la array que tenga _id=ElementID begin if FConfigDB.JO.A[ArrayID].O[i].s[_id] = ElementID then begin FElement := FConfigDB.JO.A[ArrayID].O[i]; Break; end; end; if FElement = nil then // si no existe el elemento agregarlo begin FElement := FConfigDB.JO.A[ArrayID].AddObject; FElement.s[_id] := ElementID; end; end; constructor TConfigElement.Create(var ConfigDB: TConfigJson; const ArrayID: string; Element: TJSONObject); begin FConfigDB := ConfigDB; FArrayID := ArrayID; FElement := Element; FElementID := Element.s[_id]; end; function TConfigElement.GetCount: integer; begin result := FElement.Count; end; function TConfigElement.GetJSON: string; begin result := FElement.ToJSON; end; function TConfigElement.GetValueKey(const Index: integer): string; begin result := FElement.Items[Index].value; end; function TConfigElement.WriteValue(const ValueKey: string; const value: Variant): boolean; begin result := FConfigDB._InsertElemValue(FElement, ValueKey, value); end; function TConfigElement.WriteValueArray(const ValueKey: string; const value: array of Variant): boolean; begin result := FConfigDB._InsertElemValueArray(FElement, ValueKey, value); end; function TConfigElement.ReadBool(const ValueKey: string; Def: boolean = False): boolean; var value: Variant; begin result := False; if ReadValue(ValueKey, value) then result := value; end; function TConfigElement.ReadInt64(const ValueKey: string; Default: int64 = 0): int64; var value: Variant; begin result := Default; if ReadValue(ValueKey, value) then result := value; end; function TConfigElement.ReadValue(const ValueKey: string; out value: Variant): boolean; begin result := False; if not FElement.Contains(ValueKey) then Exit; value := FElement.Values[ValueKey].VariantValue; result := True; end; function TConfigElement.ReadString(const ValueKey: string): string; var v: Variant; begin result := ''; if ReadValue(ValueKey, v) then result := v; end; function TConfigElement.ReadValueArray(const ValueKey: string; out value: Variant): boolean; var arr: TJSONArray; i: integer; begin result := False; if not FElement.Contains(ValueKey) then Exit; if FElement.Values[ValueKey].Typ = jdtArray then begin arr := FElement.Values[ValueKey].ArrayValue; value := VarArrayCreate([0, arr.Count - 1], varVariant); for i := 0 to arr.Count - 1 do value[i] := (arr.Items[i].value); result := True; end; end; { TConfigArray } constructor TConfigArray.Create(var ConfigDB: TConfigJson; const ArrayID: string); begin FConfigDB := ConfigDB; FArrayID := ArrayID; FArray := FConfigDB.JO.A[ArrayID]; // buscar array sino agregarlo end; function TConfigArray.GetCount: integer; begin result := FArray.Count; end; function TConfigArray.GetElement(const Index: integer): TConfigElement; begin if (Index >= 0) and (Index < FArray.Count) then result := TConfigElement.Create(FConfigDB, FArrayID, FArray.O[Index]); end; function TConfigArray.WriteValue(const ElementID, ValueKey: string; const value: Variant): boolean; begin result := FConfigDB.WriteValue(FArrayID, ElementID, ValueKey, value); end; end.
//--------------------------------------------------------------- // Demo written by Daniele Teti <d.teti@bittime.it> //--------------------------------------------------------------- unit SetOfStrU; interface uses System.SysUtils, System.Classes; type SetOfStr = record private fElements: TStringList; class procedure RemoveSetElement(const [ref] StringSet: SetOfStr; const Value: String); static; public /// Managed Record Requirements class operator Initialize(out Dest: SetOfStr); class operator Finalize(var Dest: SetOfStr); class operator Assign(var Dest: SetOfStr; const [ref] Src: SetOfStr); /// Operators class operator Implicit(Value: TArray<String>): SetOfStr; class operator In(a: string; b: SetOfStr): Boolean; class operator Add(a: SetOfStr; b: SetOfStr): SetOfStr; overload; class operator Add(a: SetOfStr; b: String): SetOfStr; overload; class operator Subtract(a: SetOfStr; b: SetOfStr): SetOfStr; overload; class operator Subtract(a: SetOfStr; b: String): SetOfStr; overload; class operator Multiply(a: SetOfStr; b: SetOfStr): SetOfStr; /// Methods function ToString: string; function ToArray: TArray<String>; end; implementation { SetOfStr } function SetOfStr.ToArray: TArray<String>; begin Result := fElements.ToStringArray; end; class operator SetOfStr.In(a: string; b: SetOfStr): Boolean; begin Result := b.fElements.IndexOf(a) > -1; end; class operator SetOfStr.Initialize(out Dest: SetOfStr); begin Dest.fElements := TStringList.Create(dupIgnore, True, False); end; class operator SetOfStr.Finalize(var Dest: SetOfStr); begin Dest.fElements.Free; end; class operator SetOfStr.Assign(var Dest: SetOfStr; const [ref] Src: SetOfStr); begin Dest.fElements.AddStrings(Src.fElements); end; class operator SetOfStr.Implicit(Value: TArray<String>): SetOfStr; begin Result.fElements.AddStrings(Value); end; function SetOfStr.ToString: string; begin Result := fElements.Text; end; class operator SetOfStr.Add(a: SetOfStr; b: SetOfStr): SetOfStr; begin Result.fElements.AddStrings(a.fElements); Result.fElements.AddStrings(b.fElements); end; class operator SetOfStr.Add(a: SetOfStr; b: String): SetOfStr; begin Result.fElements.AddStrings(a.fElements); Result.fElements.Add(b); end; class operator SetOfStr.Subtract(a: SetOfStr; b: SetOfStr): SetOfStr; begin Result := a; for var s in b.fElements do begin RemoveSetElement(Result,s); end; end; class operator SetOfStr.Subtract(a: SetOfStr; b: String): SetOfStr; begin Result := a; RemoveSetElement(a,b); end; class operator SetOfStr.Multiply(a: SetOfStr; b: SetOfStr): SetOfStr; begin for var s in a.fElements do begin if s in b then begin Result.fElements.Add(s); end; end; end; class procedure SetOfStr.RemoveSetElement(const [ref] StringSet: SetOfStr; const Value: String); begin var lIdx := StringSet.fElements.IndexOf(Value); if lIdx > -1 then begin StringSet.fElements.Delete(lIdx); end; end; end.
program listtest; Type List = ^Node; Node = record data: integer; next: List; end; var l: List; procedure print_list(l: List); begin while l <> nil do begin write(l^.data, ' '); l := l^.next; end; writeln(); end; procedure init_list(var head: List; x: integer); begin new(head); head^.data := x; end; procedure insert_after_pointer(p: List; x: integer); //вставка после элемента списка, на который указывает p //предполагается, что p указывает на существующий элемент var item: List; begin new(item); item^.next := p^.next; p^.next := item; item^.data := x; end; procedure insert_to_tail(var head: List; x: integer); //вставка в конец списка var i: integer; p: List; begin if head = nil then init_list(head, x) else begin p := head; while p^.next <> nil do p := p^.next; insert_after_pointer(p, x); end; end; procedure insert_to_head(var head: List; x: integer); var item: List; begin if head = nil then init_list(head, x) else begin new(item); item^.data := x; item^.next := head; head := item; end; end; procedure insert_after_index(head: List; x: integer; pos: integer); //вставка после элементом с номером pos //предпологается, что в списке есть хотя бы pos элементов var i: integer; begin for i := 1 to pos - 1 do head := head^.next; insert_after_pointer(head, x); end; procedure remove_head(var head: List); var copy: List; begin if head <> nil then begin copy := head^.next; dispose(head); head := copy; end; end; procedure remove_to_pointer(p: List); var copy: List; begin if p^.next <> nil then begin copy := p^.next^.next; dispose(p^.next); p^.next := copy; end; end; begin l := nil; insert_to_tail(l, 6); insert_to_head(l, 1); insert_to_head(l, 8); insert_to_tail(l, -4); remove_head(l); remove_to_pointer(l); print_list(l); end.
unit RepositorioLoteValidade; interface uses DB, Auditoria, Repositorio; type TRepositorioLoteValidade = class(TRepositorio) protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; function SQLGetExiste(campo: String): String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; protected procedure ExecutaDepoisDeSalvar (Objeto :TObject); override; protected procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override; end; implementation uses SysUtils, LoteValidade, FabricaRepositorio, ProdutoValidade; { TRepositorioLoteValidade } procedure TRepositorioLoteValidade.ExecutaDepoisDeSalvar(Objeto: TObject); var Lote :TLoteValidade; repositorio :TRepositorio; ProdutoValidade :TProdutoValidade; begin Lote := (Objeto as TLoteValidade); try { * * * salva itens do lote * * * } repositorio := TFabricaRepositorio.GetRepositorio(TProdutoValidade.ClassName); for ProdutoValidade in Lote.ItensDoLote do begin ProdutoValidade.codigo_lote := Lote.codigo; if Lote.movimentar_estoque then ProdutoValidade.movimentaEstoqueValidade; repositorio.Salvar( ProdutoValidade ); end; finally FreeAndNil(repositorio); end; end; function TRepositorioLoteValidade.Get(Dataset: TDataSet): TObject; var LoteValidade :TLoteValidade; begin LoteValidade:= TLoteValidade.Create; LoteValidade.codigo := self.FQuery.FieldByName('codigo').AsInteger; LoteValidade.criacao := self.FQuery.FieldByName('criacao').AsDateTime; LoteValidade.numero_doc := self.FQuery.FieldByName('numero_doc').AsInteger; LoteValidade.numero_nota := self.FQuery.FieldByName('numero_nota').AsInteger; result := LoteValidade; end; function TRepositorioLoteValidade.GetIdentificador(Objeto: TObject): Variant; begin result := TLoteValidade(Objeto).Codigo; end; function TRepositorioLoteValidade.GetNomeDaTabela: String; begin result := 'LOTES_VALIDADE'; end; function TRepositorioLoteValidade.GetRepositorio: TRepositorio; begin result := TRepositorioLoteValidade.Create; end; function TRepositorioLoteValidade.IsInsercao(Objeto: TObject): Boolean; begin result := (TLoteValidade(Objeto).Codigo <= 0); end; procedure TRepositorioLoteValidade.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); var LoteValidadeAntigo :TLoteValidade; LoteValidadeNovo :TLoteValidade; begin LoteValidadeAntigo := (AntigoObjeto as TLoteValidade); LoteValidadeNovo := (Objeto as TLoteValidade); if (LoteValidadeAntigo.criacao <> LoteValidadeNovo.criacao) then Auditoria.AdicionaCampoAlterado('criacao', DateTimeToStr(LoteValidadeAntigo.criacao), DateTimeToStr(LoteValidadeNovo.criacao)); if (LoteValidadeAntigo.numero_doc <> LoteValidadeNovo.numero_doc) then Auditoria.AdicionaCampoAlterado('numero_doc', IntToStr(LoteValidadeAntigo.numero_doc), IntToStr(LoteValidadeNovo.numero_doc)); if (LoteValidadeAntigo.numero_nota <> LoteValidadeNovo.numero_nota) then Auditoria.AdicionaCampoAlterado('numero_nota', IntToStr(LoteValidadeAntigo.numero_nota), IntToStr(LoteValidadeNovo.numero_nota)); end; procedure TRepositorioLoteValidade.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); var LoteValidade :TLoteValidade; begin LoteValidade := (Objeto as TLoteValidade); Auditoria.AdicionaCampoExcluido('codigo' , IntToStr(LoteValidade.codigo)); Auditoria.AdicionaCampoExcluido('criacao' , DateTimeToStr(LoteValidade.criacao)); Auditoria.AdicionaCampoExcluido('numero_doc' , IntToStr(LoteValidade.numero_doc)); Auditoria.AdicionaCampoExcluido('numero_nota', IntToStr(LoteValidade.numero_nota)); end; procedure TRepositorioLoteValidade.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); var LoteValidade :TLoteValidade; begin LoteValidade := (Objeto as TLoteValidade); Auditoria.AdicionaCampoIncluido('codigo' , IntToStr(LoteValidade.codigo)); Auditoria.AdicionaCampoIncluido('criacao' , DateTimeToStr(LoteValidade.criacao)); Auditoria.AdicionaCampoIncluido('numero_doc' , IntToStr(LoteValidade.numero_doc)); Auditoria.AdicionaCampoIncluido('numero_nota', IntToStr(LoteValidade.numero_nota)); end; procedure TRepositorioLoteValidade.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TLoteValidade(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioLoteValidade.SetParametros(Objeto: TObject); var LoteValidade :TLoteValidade; begin LoteValidade := (Objeto as TLoteValidade); self.FQuery.ParamByName('codigo').AsInteger := LoteValidade.codigo; self.FQuery.ParamByName('criacao').AsDateTime := LoteValidade.criacao; self.FQuery.ParamByName('numero_doc').AsInteger := LoteValidade.numero_doc; self.FQuery.ParamByName('numero_nota').AsInteger := LoteValidade.numero_nota; end; function TRepositorioLoteValidade.SQLGet: String; begin result := 'select * from LOTES_VALIDADE where codigo = :ncod'; end; function TRepositorioLoteValidade.SQLGetAll: String; begin result := 'select * from LOTES_VALIDADE'; end; function TRepositorioLoteValidade.SQLGetExiste(campo: String): String; begin result := 'select '+ campo +' from LOTES_VALIDADE where '+ campo +' = :ncampo'; end; function TRepositorioLoteValidade.SQLRemover: String; begin result := ' delete from LOTES_VALIDADE where codigo = :codigo '; end; function TRepositorioLoteValidade.SQLSalvar: String; begin result := 'update or insert into LOTES_VALIDADE (CODIGO ,CRIACAO ,NUMERO_DOC ,NUMERO_NOTA) '+ ' values ( :CODIGO , :CRIACAO , :NUMERO_DOC , :NUMERO_NOTA) '; end; end.
unit APIHookUtils; interface uses Windows; type TAPIHOOK32_ENTRY = record pszAPIName : PChar; // 要被钩住的API名称,注意大小写 pszCalleeModuleName : PChar; // 要被钩住的API所在的模块的名称 pfnOriginApiAddress : TFarProc; //要被钩住的API的地址 pfnDummyFuncAddress : TFarProc; //被钩住以后的地址 hModCallerModule : HMODULE; // 需要被钩住的模块。0表示对所有模块的指定API进行钩住处理。非0表示只对这个模块的指定API进行钩住处理。 end; PAPIHOOK32_ENTRY = ^TAPIHOOK32_ENTRY; // 建立API函数钩子 HookSelf表示是否对包含HookWindowsAPI的模块也进行钩子处理。返回是否成功 function HookWindowsAPI(const Entry : TAPIHOOK32_ENTRY; HookSelf : Boolean=False):BOOL; // 取消API函数钩子 HookSelf表示是否对包含HookWindowsAPI的模块也进行钩子处理。返回是否成功 function UnhookWindowsAPI(const Entry : TAPIHOOK32_ENTRY; HookSelf : Boolean=False):BOOL; implementation uses TLHelp32, Imagehlp; const IMAGE_DIRECTORY_ENTRY_EXPORT = 0; { Export Directory } IMAGE_DIRECTORY_ENTRY_IMPORT = 1; { Import Directory } IMAGE_DIRECTORY_ENTRY_RESOURCE = 2; { Resource Directory } IMAGE_DIRECTORY_ENTRY_EXCEPTION = 3; { Exception Directory } IMAGE_DIRECTORY_ENTRY_SECURITY = 4; { Security Directory } IMAGE_DIRECTORY_ENTRY_BASERELOC = 5; { Base Relocation Table } IMAGE_DIRECTORY_ENTRY_DEBUG = 6; { Debug Directory } IMAGE_DIRECTORY_ENTRY_COPYRIGHT = 7; { Description String } IMAGE_DIRECTORY_ENTRY_GLOBALPTR = 8; { Machine Value (MIPS GP) } IMAGE_DIRECTORY_ENTRY_TLS = 9; { TLS Directory } IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG = 10; { Load Configuration Directory } IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT = 11; { Bound Import Directory in headers } IMAGE_DIRECTORY_ENTRY_IAT = 12; { Import Address Table } IMAGE_NUMBEROF_DIRECTORY_ENTRIES = 16; type { Image format } PImageDosHeader = ^TImageDosHeader; TImageDosHeader = packed record e_magic: Word; // Magic number e_cblp: Word; // Bytes on last page of file e_cp: Word; // Pages in file e_crlc: Word; // Relocations e_cparhdr: Word; // Size of header in paragraphs e_minalloc: Word; // Minimum extra paragraphs needed e_maxalloc: Word; // Maximum extra paragraphs needed e_ss: Word; // Initial (relative) SS value e_sp: Word; // Initial SP value e_csum: Word; // Checksum e_ip: Word; // Initial IP value e_cs: Word; // Initial (relative) CS value e_lfarlc: Word; // File address of relocation table e_ovno: Word; // Overlay number e_res: array [ 0..3 ] of Word; // Reserved words e_oemid: Word; // OEM identifier (for e_oeminfo) e_oeminfo: Word; // OEM information; e_oemid specific e_res2: array [ 0..9 ] of Word; // Reserved words e_lfanew: Longint; // File address of new exe header end; PImageImportByName = ^TImageImportByName; TImageImportByName = packed record Hint: Word; Name: array [0..0] of Byte; end; PImageThunkData = ^TImageThunkData; TImageThunkData = packed record case Integer of 0: (ForwarderString: PByte); 1: (_Function: PDWORD); 2: (Ordinal: DWORD); 3: (AddressOfData: PImageImportByName); end; PIMAGE_THUNK_DATA = PImageThunkData; PImageImportDescriptor = ^TImageImportDescriptor; PIMAGE_IMPORT_DESCRIPTOR = PImageImportDescriptor; TImageImportDescriptor = packed record Union: record case Integer of 0: ( Characteristics: DWORD; // 0 for terminating null import descriptor ); 1: ( OriginalFirstThunk: PImageThunkData; // RVA to original unbound IAT ); end; TimeDateStamp: DWORD; // 0 if not bound, // -1 if bound, and real date\time stamp // in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND) // O.W. date/time stamp of DLL bound to (Old BIND) ForwarderChain: DWORD; // -1 if no forwarders Name: DWORD; FirstThunk: PImageThunkData; // RVA to IAT (if bound this IAT has actual addresses) end; PFarProc = ^TFarProc; function _SetApiHookUp(const phk : TAPIHOOK32_ENTRY):BOOL; var size : ULONG; pImportDesc : PIMAGE_IMPORT_DESCRIPTOR; pszDllName : PChar; pThunk : PIMAGE_THUNK_DATA; ppfn : PFarProc; lpNumberOfBytesWritten: DWORD; begin Result := False; //获取指向PE文件中的Import中IMAGE_DIRECTORY_DESCRIPTOR数组的指针 pImportDesc := PIMAGE_IMPORT_DESCRIPTOR( ImageDirectoryEntryToData(Pointer(phk.hModCallerModule),TRUE,IMAGE_DIRECTORY_ENTRY_IMPORT,size)); if (pImportDesc = nil) then Exit; //查找记录,看看有没有我们想要的DLL while (pImportDesc.Name<>0) do begin pszDllName := PChar(phk.hModCallerModule+pImportDesc^.Name); if (lstrcmpiA(pszDllName,phk.pszCalleeModuleName) = 0) then begin // 找到一个正确的DLL Import入口。注意一个DLL可能有多个入口 //寻找我们想要的函数 pThunk := PIMAGE_THUNK_DATA(phk.hModCallerModule+Longword(pImportDesc^.FirstThunk));//IAT while (pThunk^._Function<>nil) do begin //ppfn记录了与IAT表项相应的函数的地址 ppfn := PFarProc(@pThunk^._Function); if ( ppfn^ = phk.pfnOriginApiAddress) then begin //如果地址相同,也就是找到了我们想要的函数,进行改写,将其指向我们所定义的函数 WriteProcessMemory(GetCurrentProcess(),ppfn,@(phk.pfnDummyFuncAddress),sizeof(phk.pfnDummyFuncAddress),lpNumberOfBytesWritten); Result := True; Break; //完成一个入口 end; Inc(pThunk); end; end; Inc(pImportDesc); end; end; function HookWindowsAPI(const Entry : TAPIHOOK32_ENTRY; HookSelf : Boolean=False):BOOL; var mInfo : MEMORY_BASIC_INFORMATION; hModHookDLL : HMODULE; hSnapshot : THANDLE; me : MODULEENTRY32; bOk : BOOL; phk : TAPIHOOK32_ENTRY; begin phk := Entry; Result := False; if (phk.pszAPIName=nil) or (phk.pszCalleeModuleName=nil) or (phk.pfnOriginApiAddress=nil) then Exit; if (phk.hModCallerModule = 0) then begin me.dwSize := sizeof(me); VirtualQuery(@_SetApiHookUp,mInfo,sizeof(mInfo)); hModHookDLL := HMODULE(mInfo.AllocationBase); hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,0); bOk := Module32First(hSnapshot,me); while (bOk) do begin if HookSelf or (me.hModule<>hModHookDLL) then begin phk.hModCallerModule := me.hModule; if _SetApiHookUp(phk) then Result := TRUE; end; bOk := Module32Next(hSnapshot,me); end; end else begin Result := _SetApiHookUp(phk); end; end; function UnhookWindowsAPI(const Entry : TAPIHOOK32_ENTRY; HookSelf : Boolean=False):BOOL; var hk : TAPIHOOK32_ENTRY; begin hk := Entry; hk.pfnOriginApiAddress := Entry.pfnDummyFuncAddress; hk.pfnDummyFuncAddress := Entry.pfnOriginApiAddress; Result := HookWindowsAPI(hk,HookSelf); end; end.
unit uTesteExemplo7; interface uses DUnitX.TestFramework, Exemplo7_2, Exemplo7, Exemplo7_1, RTTI, System.SysUtils, System.TypInfo; type TestFabricaExportaFichaUsuarioAttribute = class(TestCaseAttribute) public constructor Create(const pTestName: String; const pTipoFicha: TTipoFicha; const pFichaUsuarioClass: TClass); overload; end; [TestFixture] TEmbConf2015Test = class(TObject) private public [Setup] procedure Setup; [TearDown] procedure TearDown; // Sample Methods // Simple single Test [Test] procedure Test1; // Test with TestCase Atribute to supply parameters. [Test] [TestCase('TestA','1,2')] [TestCase('TestB','3,4')] procedure Test2(const AValue1 : Integer;const AValue2 : Integer); [Test] procedure TesteFactoryFichaUsuarioXml; [TestFabricaExportaFichaUsuario('Teste Txt', tfTexto, TExportadorFichaUsuarioTxt)] [TestFabricaExportaFichaUsuario('Teste Xml', tfXml, TExportadorFichaUsuarioXML)] [TestFabricaExportaFichaUsuario('Teste Json',tfJson, TExportadorFichaUsuarioJson)] procedure TesteMuka(const pTipoFicha: TTipoFicha; const pFichaUsuarioClass: TClass); end; implementation uses System.Classes; procedure TEmbConf2015Test.Setup; begin end; procedure TEmbConf2015Test.TearDown; begin end; procedure TEmbConf2015Test.Test1; begin end; procedure TEmbConf2015Test.Test2(const AValue1 : Integer;const AValue2 : Integer); begin end; procedure TEmbConf2015Test.TesteFactoryFichaUsuarioXml; var lExportaFichaUsuario: IExportadorFichaUsuario; begin lExportaFichaUsuario := TExportaFichaUsuarioFactory.ObterExportador(tfXml); Assert.AreEqual(TObject(lExportaFichaUsuario).ClassType,TExportadorFichaUsuarioTxt,'esperando classe TExportaFichaUsuarioXML'); end; procedure TEmbConf2015Test.TesteMuka(const pTipoFicha: TTipoFicha; const pFichaUsuarioClass: TClass); var lExportaFichaUsuario: IExportadorFichaUsuario; begin lExportaFichaUsuario := TExportaFichaUsuarioFactory.ObterExportador(pTipoFicha); Assert.AreEqual(TObject(lExportaFichaUsuario).ClassType,pFichaUsuarioClass); end; { TestMuka } constructor TestFabricaExportaFichaUsuarioAttribute.Create(const pTestName: String; const pTipoFicha: TTipoFicha; const pFichaUsuarioClass: TClass); begin FCaseInfo.Name := pTestName; SetLength(FCaseInfo.Values,2); FCaseInfo.Values[0] := Ord(pTipoFicha); FCaseInfo.Values[1] := pFichaUsuarioClass; end; initialization TDUnitX.RegisterTestFixture(TEmbConf2015Test); end.
unit FMX.MultiView.CustomPresentation; interface uses System.Messaging, System.UITypes, System.Classes, FMX.MultiView, FMX.MultiView.Presentations, FMX.MultiView.Types, FMX.StdCtrls; type { TMultiViewAlertPresentation } TMultiViewAlertPresentation = class(TMultiViewPresentation) private FDetailOverlay: TShadowedOverlayLayout; FFrame: TPanel; { Messaging } procedure DoFormReleased(const Sender: TObject; const M: TMessage); protected function GetDisplayName: string; override; procedure DoOpen(const ASpeed: Single); override; procedure DoClose(const ASpeed: Single); override; procedure DoInstall; override; procedure DoUninstall; override; { Mouse events } procedure DoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); virtual; public constructor Create(AMultiView: TCustomMultiView); override; destructor Destroy; override; procedure UpdateSettings; override; procedure Realign; override; end; implementation uses FMX.Types, FMX.Forms, FMX.Ani, System.Types; { TMultiViewAlertPresentation } constructor TMultiViewAlertPresentation.Create(AMultiView: TCustomMultiView); begin inherited; TMessageManager.DefaultManager.SubscribeToMessage(TFormReleasedMessage, DoFormReleased); // Detail overlay layer for catching mouse events FDetailOverlay := TShadowedOverlayLayout.Create(nil); FDetailOverlay.Stored := False; FDetailOverlay.Mode := TCustomOverlayLayout.TOverlayMode.AllLocalArea; FDetailOverlay.EnabledShadow := MultiView.ShadowOptions.Enabled; FDetailOverlay.Color := MultiView.ShadowOptions.Color; FDetailOverlay.Opacity := 0; FDetailOverlay.Align := TAlignLayout.Contents; FDetailOverlay.Lock; FDetailOverlay.Visible := False; FDetailOverlay.OnMouseDown := DoMouseDown; FFrame := TPanel.Create(nil); FFrame.Padding.Rect := TRectF.Create(1, 1, 1, 1); end; destructor TMultiViewAlertPresentation.Destroy; begin inherited; TMessageManager.DefaultManager.Unsubscribe(TFormReleasedMessage, DoFormReleased); FDetailOverlay.Free; end; procedure TMultiViewAlertPresentation.DoClose(const ASpeed: Single); begin inherited; FFrame.Parent := nil; FDetailOverlay.Visible := False; MultiView.MasterContent.Parent := MultiView; end; procedure TMultiViewAlertPresentation.DoFormReleased(const Sender: TObject; const M: TMessage); begin if Sender = FDetailOverlay.Parent then FDetailOverlay.Parent := nil; end; procedure TMultiViewAlertPresentation.DoInstall; begin inherited; MultiView.Visible := False; MultiView.Align := TAlignLayout.None; if MultiView.Scene <> nil then FDetailOverlay.Parent := (MultiView.Scene.GetObject as TCommonCustomForm); if MultiView.HasMasterButton then MultiView.MasterButton.Visible := True; end; procedure TMultiViewAlertPresentation.DoMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin Close; end; procedure TMultiViewAlertPresentation.DoOpen(const ASpeed: Single); var SceneForm: TCommonCustomForm; begin inherited; // Install content into Alert Panel FFrame.Opacity := 0; FFrame.Width := MultiView.Width; FFrame.Height := MultiView.PopoverOptions.PopupHeight; if MultiView.Scene <> nil then begin SceneForm := MultiView.Scene.GetObject as TCommonCustomForm; FFrame.Parent := SceneForm; FFrame.Position.Point := TPointF.Create(SceneForm.Width / 2 - FFrame.Width / 2, SceneForm.Height / 2 - FFrame.Height / 2) end; MultiView.MasterContent.Parent := FFrame; FDetailOverlay.Visible := True; TAnimator.AnimateFloat(FDetailOverlay, 'opacity', MultiView.ShadowOptions.Opacity, MultiView.DrawerOptions.DurationSliding); TAnimator.AnimateFloat(FFrame, 'opacity', 1, MultiView.DrawerOptions.DurationSliding); end; procedure TMultiViewAlertPresentation.DoUninstall; begin MultiView.Visible := True; FDetailOverlay.Parent := nil; inherited; end; function TMultiViewAlertPresentation.GetDisplayName: string; begin Result := 'Alert window'; end; procedure TMultiViewAlertPresentation.Realign; var SceneForm: TCommonCustomForm; begin inherited; if MultiView.Scene <> nil then begin SceneForm := MultiView.Scene.GetObject as TCommonCustomForm; FFrame.Position.Point := TPointF.Create(SceneForm.Width / 2 - FFrame.Width / 2, SceneForm.Height / 2 - FFrame.Height / 2) end; end; procedure TMultiViewAlertPresentation.UpdateSettings; begin inherited; if not Opened then FDetailOverlay.Opacity := 0 else FDetailOverlay.Opacity := MultiView.ShadowOptions.Opacity; FDetailOverlay.EnabledShadow := MultiView.ShadowOptions.Enabled; FDetailOverlay.Color := MultiView.ShadowOptions.Color; end; end.
unit sha512; interface uses Windows, SysUtils; // #define SHA512_CBLOCK (SHA_LBLOCK*8) /* SHA-512 treats input data as a // * contiguous array of 64 bit // * wide big-endian values. */ // #define SHA512_DIGEST_LENGTH 64 const SHA512_CBLOCK = (16{SHA_LBLOCK} * 8); SHA512_DIGEST_LENGTH = 64; // typedef struct SHA512state_st // { // SHA_LONG64 h[8]; // SHA_LONG64 Nl,Nh; // union { // SHA_LONG64 d[SHA_LBLOCK]; // unsigned char p[SHA512_CBLOCK]; // } u; // unsigned int num,md_len; // } SHA512_CTX; type SHA512_CTX = record h: array [0..7] of Int64; N1, Nh: Int64; p: array [0..(16*8){SHA512_CBLOCK}-1] of Byte; num, md_len: integer; end; // int SHA512_Init(SHA512_CTX *c); function SHA512_Init(var c: SHA512_CTX): integer; cdecl; // int SHA512_Update(SHA512_CTX *c, const void *data, size_t len); function SHA512_Update(var c: SHA512_CTX; const data: PByte; len: LongWord): integer; cdecl; // int SHA512_Final(unsigned char *md, SHA512_CTX *c); function SHA512_Final(md: PByte; var c: SHA512_CTX): integer; cdecl; // unsigned char *SHA512(const unsigned char *d, size_t n,unsigned char *md); function hashSHA512(const d: PByte; n: LongWord; md: PByte): PByte; cdecl; function SHA512_hash_string(s: string): string; function SHA512_get_string(hash: PByte): string; function SHA512_hash_file( const fname: string; sha512: PByte ): boolean; implementation const sha512_dll = 'libeay32.dll'; function SHA512_Init; external sha512_dll name 'SHA512_Init'; function SHA512_Update; external sha512_dll name 'SHA512_Update'; function SHA512_Final; external sha512_dll name 'SHA512_Final'; function hashSHA512; external sha512_dll name 'SHA512'; function SHA512_hash_string(s: string): string; var sha512: array [0..SHA512_DIGEST_LENGTH-1] of byte; n: integer; begin Result := ''; FillChar(sha512, 0, sizeof(sha512)); hashSHA512(PByte(s), length(s), @sha512); for n := low(sha512) to high(sha512) do Result := Result + IntToHex(sha512[n], 2); end; function SHA512_get_string(hash: PByte): string; var n: integer; begin Result := ''; for n := 1 to SHA512_DIGEST_LENGTH do begin Result := Result + IntToHex(hash^, 2); Inc(hash); end; end; function SHA512_hash_file( const fname: string; sha512: PByte ): boolean; var h: THandle; dwSize, dwLeft, dwRW, dw: DWORD; shactx: SHA512_CTX; buf: array [0..4095] of byte; begin Result := False; FillChar(sha512^, SHA512_DIGEST_LENGTH, 0); h := INVALID_HANDLE_VALUE; try h := CreateFile(PChar(fname), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (INVALID_HANDLE_VALUE = h) then Exit; dwSize := GetFileSize(h, nil); if (INVALID_FILE_SIZE = dwSize) then Exit; SHA512_Init(shactx); dwLeft := dwSize; while dwLeft > 0 do begin if dwLeft > sizeof(buf) then dw := sizeof(buf) else dw := dwLeft; dwRW := 0; ReadFile(h, buf, dw, dwRW, nil); if (dw <> dwRW) then Exit; SHA512_Update(shactx, @buf, dw); dwLeft := dwLeft - dw; end; CloseHandle(h); h := INVALID_HANDLE_VALUE; SHA512_Final(sha512, shactx); Result := True; finally if (INVALID_HANDLE_VALUE <> h) then CloseHandle(h); FillChar(shactx, sizeof(shactx), 0); FillChar(buf, sizeof(buf), 0); end; end; end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2017 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { This unit authored by Uwe Rupprecht } { } {***************************************************************************} { } { 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 DUnitX.TestDataProvider; interface {$I DUnitX.inc} uses {$IFDEF USE_NS} System.Classes, System.Generics.Collections, {$ELSE} Classes, Generics.Collections, {$ENDIF} DUnitX.Types, DUnitX.InternalDataProvider; type TestDataProviderManager = class private class var FList : TDictionary<string, TClass>; public class constructor Create; class destructor Destroy; class procedure RegisterProvider(const name : string; const AClass : TTestDataProviderClass); class procedure UnregisterProvider(const name : string); class function GetProvider(const name : string) : ITestDataProvider;overload; class function GetProvider(const AClass:TTestDataProviderClass) : ITestDataProvider;overload; end; implementation { TestDataProviderManager } class constructor TestDataProviderManager.Create; begin FList := TDictionary<string, TClass>.Create; end; class Destructor TestDataProviderManager.Destroy; begin FList.Free; end; class function TestDataProviderManager.GetProvider(const AClass: TTestDataProviderClass) : ITestDataProvider; var key : string; begin result := nil; if (FList.ContainsValue(AClass)) then begin for key in flist.keys do begin if (flist[key] = AClass) then begin result := TTestDataProviderClass(flist[key]).Create; break; end; end; end; end; class function TestDataProviderManager.GetProvider(const name : string) : ITestDataProvider; begin result := nil; if (FList.ContainsKey(name)) then result := TTestDataProviderClass(FList[name]).Create; end; class procedure TestDataProviderManager.RegisterProvider(const name: string; const AClass: TTestDataProviderClass); begin if (not FList.ContainsKey(name)) then FList.add(name,AClass); end; class procedure TestDataProviderManager.UnregisterProvider(const name: string); begin if (FList.ContainsKey(name)) then FList.Remove(Name); end; end.
unit URepositorioPrescricao; interface uses UPrescricao , UEntidade , UFuncionario , UMedicamento , UCliente , URepositorioFuncionario , URepositorioMedicamento , URepositorioCliente , URepositorioDB , SqlExpr ; type TRepositorioPrescricao = class(TRepositorioDB<TPRESCRICAO>) private FRepositorioFuncionario: TRepositorioFuncionario; FRepositorioMedicamento: TRepositorioMedicamento; FRepositorioCLiente : TRepositorioCliente; public procedure AtribuiDBParaEntidade(const coPRESCRICAO: TPRESCRICAO); override; procedure AtribuiEntidadeParaDB(const coPRESCRICAO: TPRESCRICAO; const coSQLQuery: TSQLQuery); override; constructor Create; destructor Destroy; override; end; implementation { TRepositorioPrescricao } uses UDM , SysUtils ; procedure TRepositorioPrescricao.AtribuiDBParaEntidade(const coPRESCRICAO: TPRESCRICAO); var CodigoFuncionario: Integer; CodigoCliente : Integer; CodigoMedicamento: Integer; begin inherited; with dmProway.SQLSelect do begin coPRESCRICAO.DESCRICAO := FieldByName(FLD_PRESCRICAO_DESCRICAO).AsString; coPRESCRICAO.DATA_HORA_PRESCRITA := FieldByName(FLD_PRESCRICAO_DATA_HORA_PRESCRITA).AsDateTime; coPRESCRICAO.DATA_HORA_VENCIMENTO:= FieldByName(FLD_PRESCRICAO_DATA_HORA_VENCIMENTO).AsDateTime; CodigoFuncionario := FieldByName(FLD_PRESCRICAO_COD_FUNCIONARIO).AsInteger; CodigoCliente := FieldByName(FLD_PRESCRICAO_COD_CLIENTE).AsInteger; CodigoMedicamento := FieldByName(FLD_PRESCRICAO_COD_MEDICAMENTO).AsInteger; coPRESCRICAO.FUNCIONARIO := TFUNCIONARIO( FRepositorioFuncionario.Retorna(CodigoFuncionario)); coPRESCRICAO.CLIENTE := TCliente( FRepositorioCLiente.Retorna(CodigoCliente)); coPRESCRICAO.MEDICAMENTO := TMEDICAMENTO( FRepositorioMedicamento.Retorna(CodigoMedicamento)); end; end; procedure TRepositorioPrescricao.AtribuiEntidadeParaDB( const coPRESCRICAO: TPRESCRICAO; const coSQLQuery: TSQLQuery); begin inherited; with coSQLQuery do begin ParamByName(FLD_PRESCRICAO_COD_FUNCIONARIO).AsInteger := coPRESCRICAO.FUNCIONARIO.CODIGO ; ParamByName(FLD_PRESCRICAO_COD_CLIENTE).AsInteger := coPRESCRICAO.CLIENTE.CODIGO ; ParamByName(FLD_PRESCRICAO_COD_MEDICAMENTO).AsInteger := coPRESCRICAO.MEDICAMENTO.CODIGO ; ParamByName(FLD_PRESCRICAO_DESCRICAO).AsString := coPRESCRICAO.DESCRICAO ; ParamByName(FLD_PRESCRICAO_DATA_HORA_PRESCRITA).AsDateTime:= coPRESCRICAO.DATA_HORA_PRESCRITA ; ParamByName(FLD_PRESCRICAO_DATA_HORA_VENCIMENTO).AsDate := coPRESCRICAO.DATA_HORA_VENCIMENTO; end; end; constructor TRepositorioPrescricao.Create; begin Inherited Create(TPRESCRICAO, TBL_PRESCRICAO, FLD_ENTIDADE_CODIGO, STR_PRESCRICAO); FRepositorioFuncionario := TRepositorioFuncionario.Create; FRepositorioMedicamento := TRepositorioMedicamento.Create; FRepositorioCLiente := TRepositorioCliente.Create; end; destructor TRepositorioPrescricao.Destroy; begin FreeAndNil(FRepositorioFuncionario); FreeAndNil(FRepositorioMedicamento); FreeAndNil(FRepositorioCLiente); inherited; end; end.
unit UAbout; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, ShellApi, UzLogConst, UzLogGlobal, UzLogQSO, UzLogKeyer, JclFileUtils; type TAboutBox = class(TForm) Panel1: TPanel; ProgramIcon: TImage; ProductName: TLabel; Version: TLabel; Copyright: TLabel; Comments: TLabel; OKButton: TButton; Label1: TLabel; Label2: TLabel; Label4: TLabel; Panel2: TPanel; Label6: TLabel; Label7: TLabel; LinkLabel1: TLinkLabel; LinkLabel2: TLinkLabel; LinkLabel3: TLinkLabel; Memo1: TMemo; procedure OKButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); private { Private declarations } public { Public declarations } end; implementation {$R *.DFM} procedure TAboutBox.OKButtonClick(Sender: TObject); begin Close; end; procedure TAboutBox.FormShow(Sender: TObject); var ver: TJclFileVersionInfo; begin ver := TJclFileVersionInfo.Create(Self.Handle); Label6.Caption := 'zLog for Windows Version ' + ver.FileVersion + ' —ߘa Edition based on 2.2h'; ver.Free(); Label2.Caption := Log.QsoList[0].memo; end; procedure TAboutBox.LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); begin ShellExecute(Handle, 'open', PChar(Link), nil, nil, SW_SHOW); end; procedure TAboutBox.FormCreate(Sender: TObject); begin Label4.Caption := ''; if dmZLogKeyer.USBIF4CW_Detected then begin Label4.Caption := 'USBIF4CW detected'; Exit; end; if dmZLogGlobal.Settings._use_winkeyer = True then begin if dmZLogKeyer.WinKeyerRevision = 0 then begin Label4.Caption := 'WinKeyer not detected'; end else begin Label4.Caption := 'WinKeyer detected Rev. ' + IntToHex(dmZLogKeyer.WinKeyerRevision, 2); end; Exit; end; end; end.
unit chronometer; {$mode delphi} interface uses Classes, SysUtils, And_jni, AndroidWidget, systryparent; type TOnChronometerTick = procedure(Sender: TObject; elapsedTimeMillis: int64) of Object; {Draft Component code by "Lazarus Android Module Wizard" [6/18/2016 19:17:11]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jVisualControl template} jChronometer = class(jVisualControl) private FOnChronometerTick: TOnChronometerTick; procedure SetVisible(Value: Boolean); procedure SetColor(Value: TARGBColorBridge); //background public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; procedure Refresh; procedure UpdateLayout; override; procedure GenEvent_OnClick(Obj: TObject); procedure GenEvent_OnChronometerTick(Obj: TObject; elapsedTimeMillis: int64); function jCreate(): jObject; procedure jFree(); procedure SetViewParent(_viewgroup: jObject); override; procedure RemoveFromViewParent(); override; function GetView(): jObject; override; procedure SetLParamWidth(_w: integer); procedure SetLParamHeight(_h: integer); procedure SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure AddLParamsAnchorRule(_rule: integer); procedure AddLParamsParentRule(_rule: integer); procedure SetLayoutAll(_idAnchor: integer); procedure ClearLayout(); procedure SetBaseElapsedRealtime(); overload; procedure SetBaseElapsedRealtime(_elapsedMillis: int64); overload; function GetElapsedTimeMillis(): int64; function Start(): int64; function Stop(): int64; function Reset(): int64; procedure SetThresholdTick(_thresholdTickMillis: integer); function GetSystemElapsedRealtime(): int64; published property BackgroundColor: TARGBColorBridge read FColor write SetColor; //property FontSize: DWord read FFontSize write SetFontSize; //property FontColor: TARGBColorBridge read FFontColor write SetFontColor; //property FontSizeUnit: TFontSizeUnit read FFontSizeUnit write SetFontSizeUnit; property OnClick: TOnNotify read FOnClick write FOnClick; property OnChronometerTick: TOnChronometerTick read FOnChronometerTick write FOnChronometerTick; end; function jChronometer_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jChronometer_jFree(env: PJNIEnv; _jchronometer: JObject); procedure jChronometer_SetViewParent(env: PJNIEnv; _jchronometer: JObject; _viewgroup: jObject); procedure jChronometer_RemoveFromViewParent(env: PJNIEnv; _jchronometer: JObject); function jChronometer_GetView(env: PJNIEnv; _jchronometer: JObject): jObject; procedure jChronometer_SetLParamWidth(env: PJNIEnv; _jchronometer: JObject; _w: integer); procedure jChronometer_SetLParamHeight(env: PJNIEnv; _jchronometer: JObject; _h: integer); procedure jChronometer_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jchronometer: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); procedure jChronometer_AddLParamsAnchorRule(env: PJNIEnv; _jchronometer: JObject; _rule: integer); procedure jChronometer_AddLParamsParentRule(env: PJNIEnv; _jchronometer: JObject; _rule: integer); procedure jChronometer_SetLayoutAll(env: PJNIEnv; _jchronometer: JObject; _idAnchor: integer); procedure jChronometer_ClearLayoutAll(env: PJNIEnv; _jchronometer: JObject); procedure jChronometer_SetId(env: PJNIEnv; _jchronometer: JObject; _id: integer); procedure jChronometer_SetBaseElapsedRealtime(env: PJNIEnv; _jchronometer: JObject); overload; procedure jChronometer_SetBaseElapsedRealtime(env: PJNIEnv; _jchronometer: JObject; _elapsedMillis: int64);overload; function jChronometer_GetElapsedTimeMillis(env: PJNIEnv; _jchronometer: JObject): int64; function jChronometer_Start(env: PJNIEnv; _jchronometer: JObject): int64; function jChronometer_Stop(env: PJNIEnv; _jchronometer: JObject): int64; function jChronometer_Reset(env: PJNIEnv; _jchronometer: JObject): int64; procedure jChronometer_SetThresholdTick(env: PJNIEnv; _jchronometer: JObject; _thresholdTickMillis: integer); function jChronometer_GetSystemElapsedRealtime(env: PJNIEnv; _jchronometer: JObject): int64; implementation {--------- jChronometer --------------} constructor jChronometer.Create(AOwner: TComponent); begin inherited Create(AOwner); if gapp <> nil then FId := gapp.GetNewId(); FMarginLeft := 10; FMarginTop := 10; FMarginBottom := 10; FMarginRight := 10; FHeight := 48; //?? FWidth := 96; //?? FLParamWidth := lpWrapContent; //lpWrapContent FLParamHeight := lpWrapContent; //lpMatchParent FAcceptChildrenAtDesignTime:= False; //your code here.... end; destructor jChronometer.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jChronometer.Init; var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; begin if not FInitialized then begin inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject := jCreate(); if FjObject = nil then exit; if FParent <> nil then sysTryNewParent( FjPRLayout, FParent); FjPRLayoutHome:= FjPRLayout; jChronometer_SetViewParent(gApp.jni.jEnv, FjObject, FjPRLayout); jChronometer_SetId(gApp.jni.jEnv, FjObject, Self.Id); end; jChronometer_setLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject , FMarginLeft,FMarginTop,FMarginRight,FMarginBottom, sysGetLayoutParams( FWidth, FLParamWidth, Self.Parent, sdW, fmarginLeft + fmarginRight ), sysGetLayoutParams( FHeight, FLParamHeight, Self.Parent, sdH, fMargintop + fMarginbottom )); for rToA := raAbove to raAlignRight do begin if rToA in FPositionRelativeToAnchor then begin jChronometer_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToAnchor(rToA)); end; end; for rToP := rpBottom to rpCenterVertical do begin if rToP in FPositionRelativeToParent then begin jChronometer_AddLParamsParentRule(gApp.jni.jEnv, FjObject, GetPositionRelativeToParent(rToP)); end; end; if Self.Anchor <> nil then Self.AnchorId:= Self.Anchor.Id else Self.AnchorId:= -1; //dummy jChronometer_SetLayoutAll(gApp.jni.jEnv, FjObject, Self.AnchorId); if not FInitialized then begin FInitialized:= True; if FColor <> colbrDefault then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; end; procedure jChronometer.SetColor(Value: TARGBColorBridge); begin FColor:= Value; if (FInitialized = True) and (FColor <> colbrDefault) then View_SetBackGroundColor(gApp.jni.jEnv, FjObject, GetARGB(FCustomColor, FColor)); end; procedure jChronometer.SetVisible(Value : Boolean); begin FVisible:= Value; if FInitialized then View_SetVisible(gApp.jni.jEnv, FjObject, FVisible); end; procedure jChronometer.UpdateLayout; begin if not FInitialized then exit; ClearLayout(); inherited UpdateLayout; init; end; procedure jChronometer.Refresh; begin if FInitialized then View_Invalidate(gApp.jni.jEnv, FjObject); end; //Event : Java -> Pascal procedure jChronometer.GenEvent_OnClick(Obj: TObject); begin if Assigned(FOnClick) then FOnClick(Obj); end; procedure jChronometer.GenEvent_OnChronometerTick(Obj: TObject; elapsedTimeMillis: int64); begin if Assigned(FOnChronometerTick) then FOnChronometerTick(Obj, elapsedTimeMillis); end; function jChronometer.jCreate(): jObject; begin Result:= jChronometer_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jChronometer.jFree(); begin //in designing component state: set value here... if FInitialized then jChronometer_jFree(gApp.jni.jEnv, FjObject); end; procedure jChronometer.SetViewParent(_viewgroup: jObject); begin //in designing component state: set value here... if FInitialized then jChronometer_SetViewParent(gApp.jni.jEnv, FjObject, _viewgroup); end; procedure jChronometer.RemoveFromViewParent(); begin //in designing component state: set value here... if FInitialized then jChronometer_RemoveFromViewParent(gApp.jni.jEnv, FjObject); end; function jChronometer.GetView(): jObject; begin //in designing component state: result value here... if FInitialized then Result:= jChronometer_GetView(gApp.jni.jEnv, FjObject); end; procedure jChronometer.SetLParamWidth(_w: integer); begin //in designing component state: set value here... if FInitialized then jChronometer_SetLParamWidth(gApp.jni.jEnv, FjObject, _w); end; procedure jChronometer.SetLParamHeight(_h: integer); begin //in designing component state: set value here... if FInitialized then jChronometer_SetLParamHeight(gApp.jni.jEnv, FjObject, _h); end; procedure jChronometer.SetLeftTopRightBottomWidthHeight(_left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); begin //in designing component state: set value here... if FInitialized then jChronometer_SetLeftTopRightBottomWidthHeight(gApp.jni.jEnv, FjObject, _left ,_top ,_right ,_bottom ,_w ,_h); end; procedure jChronometer.AddLParamsAnchorRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jChronometer_AddLParamsAnchorRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jChronometer.AddLParamsParentRule(_rule: integer); begin //in designing component state: set value here... if FInitialized then jChronometer_AddLParamsParentRule(gApp.jni.jEnv, FjObject, _rule); end; procedure jChronometer.SetLayoutAll(_idAnchor: integer); begin //in designing component state: set value here... if FInitialized then jChronometer_SetLayoutAll(gApp.jni.jEnv, FjObject, _idAnchor); end; procedure jChronometer.ClearLayout(); var rToP: TPositionRelativeToParent; rToA: TPositionRelativeToAnchorID; begin //in designing component state: set value here... if FInitialized then begin jChronometer_clearLayoutAll(gApp.jni.jEnv, FjObject); for rToP := rpBottom to rpCenterVertical do if rToP in FPositionRelativeToParent then jChronometer_addlParamsParentRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToParent(rToP)); for rToA := raAbove to raAlignRight do if rToA in FPositionRelativeToAnchor then jChronometer_addlParamsAnchorRule(gApp.jni.jEnv, FjObject , GetPositionRelativeToAnchor(rToA)); end; end; procedure jChronometer.SetBaseElapsedRealtime(); begin //in designing component state: set value here... if FInitialized then jChronometer_SetBaseElapsedRealtime(gApp.jni.jEnv, FjObject); end; function jChronometer.GetElapsedTimeMillis(): int64; begin //in designing component state: result value here... if FInitialized then Result:= jChronometer_GetElapsedTimeMillis(gApp.jni.jEnv, FjObject); end; function jChronometer.Start(): int64; begin //in designing component state: result value here... if FInitialized then Result:= jChronometer_Start(gApp.jni.jEnv, FjObject); end; function jChronometer.Stop(): int64; begin //in designing component state: result value here... if FInitialized then Result:= jChronometer_Stop(gApp.jni.jEnv, FjObject); end; function jChronometer.Reset(): int64; begin //in designing component state: result value here... if FInitialized then Result:= jChronometer_Reset(gApp.jni.jEnv, FjObject); end; procedure jChronometer.SetThresholdTick(_thresholdTickMillis: integer); begin //in designing component state: set value here... if FInitialized then jChronometer_SetThresholdTick(gApp.jni.jEnv, FjObject, _thresholdTickMillis); end; procedure jChronometer.SetBaseElapsedRealtime(_elapsedMillis: int64); begin //in designing component state: set value here... if FInitialized then jChronometer_SetBaseElapsedRealtime(gApp.jni.jEnv, FjObject, _elapsedMillis); end; function jChronometer.GetSystemElapsedRealtime(): int64; begin //in designing component state: result value here... if FInitialized then Result:= jChronometer_GetSystemElapsedRealtime(gApp.jni.jEnv, FjObject); end; {-------- jChronometer_JNI_Bridge ----------} function jChronometer_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jChronometer_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; (* //Please, you need insert: public java.lang.Object jChronometer_jCreate(long _Self) { return (java.lang.Object)(new jChronometer(this,_Self)); } //to end of "public class Controls" in "Controls.java" *) procedure jChronometer_jFree(env: PJNIEnv; _jchronometer: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetViewParent(env: PJNIEnv; _jchronometer: JObject; _viewgroup: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].l:= _viewgroup; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'SetViewParent', '(Landroid/view/ViewGroup;)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_RemoveFromViewParent(env: PJNIEnv; _jchronometer: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'RemoveFromViewParent', '()V'); env^.CallVoidMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; function jChronometer_GetView(env: PJNIEnv; _jchronometer: JObject): jObject; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'GetView', '()Landroid/view/View;'); Result:= env^.CallObjectMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetLParamWidth(env: PJNIEnv; _jchronometer: JObject; _w: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _w; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'SetLParamWidth', '(I)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetLParamHeight(env: PJNIEnv; _jchronometer: JObject; _h: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _h; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'SetLParamHeight', '(I)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetLeftTopRightBottomWidthHeight(env: PJNIEnv; _jchronometer: JObject; _left: integer; _top: integer; _right: integer; _bottom: integer; _w: integer; _h: integer); var jParams: array[0..5] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _left; jParams[1].i:= _top; jParams[2].i:= _right; jParams[3].i:= _bottom; jParams[4].i:= _w; jParams[5].i:= _h; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'SetLeftTopRightBottomWidthHeight', '(IIIIII)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_AddLParamsAnchorRule(env: PJNIEnv; _jchronometer: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _rule; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsAnchorRule', '(I)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_AddLParamsParentRule(env: PJNIEnv; _jchronometer: JObject; _rule: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _rule; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'AddLParamsParentRule', '(I)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetLayoutAll(env: PJNIEnv; _jchronometer: JObject; _idAnchor: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _idAnchor; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'SetLayoutAll', '(I)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_ClearLayoutAll(env: PJNIEnv; _jchronometer: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'ClearLayoutAll', '()V'); env^.CallVoidMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetId(env: PJNIEnv; _jchronometer: JObject; _id: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'setId', '(I)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetBaseElapsedRealtime(env: PJNIEnv; _jchronometer: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'SetBaseElapsedRealtime', '()V'); env^.CallVoidMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; function jChronometer_GetElapsedTimeMillis(env: PJNIEnv; _jchronometer: JObject): int64; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'GetElapsedTimeMillis', '()J'); Result:= env^.CallLongMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; function jChronometer_Start(env: PJNIEnv; _jchronometer: JObject): int64; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'Start', '()J'); Result:= env^.CallLongMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; function jChronometer_Stop(env: PJNIEnv; _jchronometer: JObject): int64; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'Stop', '()J'); Result:= env^.CallLongMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; function jChronometer_Reset(env: PJNIEnv; _jchronometer: JObject): int64; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'Reset', '()J'); Result:= env^.CallLongMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetThresholdTick(env: PJNIEnv; _jchronometer: JObject; _thresholdTickMillis: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _thresholdTickMillis; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'SetThresholdTick', '(I)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jChronometer_SetBaseElapsedRealtime(env: PJNIEnv; _jchronometer: JObject; _elapsedMillis: int64); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _elapsedMillis; jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'SetBaseElapsedRealtime', '(J)V'); env^.CallVoidMethodA(env, _jchronometer, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; function jChronometer_GetSystemElapsedRealtime(env: PJNIEnv; _jchronometer: JObject): int64; var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jchronometer); jMethod:= env^.GetMethodID(env, jCls, 'GetSystemElapsedRealtime', '()J'); Result:= env^.CallLongMethod(env, _jchronometer, jMethod); env^.DeleteLocalRef(env, jCls); end; end.
EDIT COMPUTEGRADES.PAS C PROGRAM ComputeGrades(Scores,ClassList,Grades,Input,Output); {Takes information from the text file Scores.Dat, computes a final grade, puts the updated information into the record file ClassList.Dat, then creates a text file sorted by Student Name from ClassList.dat} CONST NameLength = 20; NumStudents = 20; TYPE String = PackedArray[1..NameLength] OF char; Marks = RECORD HW,MT,Final,Grd: integer; END; StuRec = RECORD Name: String; Mks: Marks; END; Class = FILE OF StuRec; HoldRecord = Array[1..NumStudents] of StuRec; VAR Scores,Grades: Text; ClassList: Class; Student: StuRec; StudentList: HoldRecord; Counter: Integer; (*************************************************************************) FUNCTION Calculate(Student: StuRec): integer; {Calculates grade according to given weight} BEGIN {Calculate} WITH Student.Mks DO Calculate = ((HW*0.2) + (MT*0.3) + (Final*0.5)); END; {Calculate} (*************************************************************************) PROCEDURE GetScores(VAR Scores: text; VAR Student: StuRec); {Reads contents of file Scores.Dat into the Record Student} BEGIN {GetScores} Readln(Scores,Student.Name); WITH Student.Mks DO BEGIN {WITH} Read(Scores,HW); Read(Scores,MT); Read(Scores,Final); END {WITH} Readln(Scores); END; {GetScores} (*************************************************************************) PROCEDURE UpdateClassList(VAR ClassList: Class; VAR StudentList: HoldRecord; VAR Counter: integer; Student: StuRec); {Computes final grade with function Calculate, posts this info to Classlist.Dat, then updates the record array with the info} BEGIN {UpdateClassList} Student.Mks.Grd = Calculate(Student); Write(ClassList,Student); Writeln(ClassList); StudentList[Counter] := Student; Counter := Counter + 1; END; {UpdateClassList} (*************************************************************************) PROCEDURE SortClassList(VAR ClassList: Class; StudentList: HoldRecord); VAR Counter: integer; NextCounter: integer; TempRecord: HoldRecord; BEGIN {SortClassList} FOR Counter := 1 TO NumStudents DO BEGIN {For Counter} Smallest := Counter; FOR NextCounter := Counter TO NumStudents DO IF StudentList[NextCounter].Name < StudentList[Smallest].Name THEN Smallest := NextCounter; TempRecord := StudentList[Counter]; StudentList[Counter] := StudentList[Smallest]; StudentList[Smallest] := TempRecord; END; {For Counter} REWRITE(ClassList); FOR Counter := 1 TO NumStudents DO Write(ClassList,StudentList); Writeln(ClassList); END; {SortClassList} (*************************************************************************) PROCEDURE CreateGrades(VAR ClassList: Class; VAR Grades: Text); {Creates the text file Grades.Dat} VAR Student: StuRec; BEGIN {CreateGrades} RESET(ClassList); REWRITE(Grades); WHILE NOT EOF(ClassList) DO BEGIN {While} Read(ClassList,Student); Write(Grades,Student.Name); Writeln(Grades); WITH Student.Mks DO BEGIN {WITH} Write(Grades,HW,' '); Write(Grades,MT,' '); Write(Grades,Final,' '); Write(Grades,Grd,' '); END; {WITH} Writeln(Grades); END; {While} END; {CreateGrades} (******************************* MAIN **********************************) BEGIN {ComputeGrades} RESET(Scores); REWRITE(Grades); REWRITE(ClassList); Counter := 1; WHILE NOT EOF(Scores) DO BEGIN {WHILE} GetScores(Scores,Student); UpdateClassList(ClassList,StudentList,Counter,Student); END; {While} SortClassList(ClassList,StudentList); CreatesGrades(ClassList,Grades); END. {ComputeGrades} 
unit DatsTime; interface procedure FindDate; procedure FindTime; procedure WriteTime (Exx, Why : integer; GetIt : integer); procedure WriteDate (Exx, Why : integer; GetIt : integer); function LeadingZero(w: Word) : string; const days : array [0..6] of String[9] = ('Sunday','Monday','Tuesday', 'Wednesday','Thursday','Friday','Saturday'); var h, min, sec, hund : Word; y, m, d, dow : Word; AmOrPm, s : String; implementation uses crt, dos; procedure FindDate; begin GetDate(y,m,d,dow); end; function LeadingZero; begin Str(w:0,s); if Length(s) = 1 then s := '0' + s; LeadingZero := s; end; procedure FindTime; begin GetTime(h,min,sec,hund); if h > 11 then begin if h <> 12 then h := h - 12; AmOrPm := 'pm'; end else AmOrPm := 'am'; end; procedure WriteDate; begin if GetIt = 1 then FindDate; GoToXY (Exx, Why); Write (days[dow],', ',d,'/',m,'/',y); end; procedure WriteTime; begin if GetIt = 1 then FindTime; if Hund <= 5 then begin GoToXY (Exx, Why); Write((h),':',leadingZero(min),':',LeadingZero(sec),' ',AmOrPm); end; end; end.
unit TNSRemotePublish.Infrastructure.Interfaces.FileOperations; interface type IFileOperations = interface procedure Copy(const src, dst : string); procedure Move(const src, dst : string); procedure Delete(const src : string); procedure Touch(const src : string); end; implementation end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://localhost/WSAreaSketch/AreaSketchService.asmx?wsdl // Encoding : utf-8 // Version : 1.0 // (9/12/2005 1:43:30 PM - 1.33.2.5) // ************************************************************************ // unit AreaSketchService; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:int - "http://www.w3.org/2001/XMLSchema" // !:string - "http://www.w3.org/2001/XMLSchema" // !:boolean - "http://www.w3.org/2001/XMLSchema" TrialCustomer = class; { "http://tempuri.org/" } // ************************************************************************ // // Namespace : http://tempuri.org/ // ************************************************************************ // TrialCustomer = class(TRemotable) private FFName: WideString; FLName: WideString; FCompanyName: WideString; FStreet: WideString; FCity: WideString; FState: WideString; FZip: WideString; FEmail: WideString; FPhone: WideString; FDeviceID: WideString; published property FName: WideString read FFName write FFName; property LName: WideString read FLName write FLName; property CompanyName: WideString read FCompanyName write FCompanyName; property Street: WideString read FStreet write FStreet; property City: WideString read FCity write FCity; property State: WideString read FState write FState; property Zip: WideString read FZip write FZip; property Email: WideString read FEmail write FEmail; property Phone: WideString read FPhone write FPhone; property DeviceID: WideString read FDeviceID write FDeviceID; end; // ************************************************************************ // // Namespace : http://tempuri.org/ // soapAction: http://tempuri.org/%operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : AreaSketchServiceSoap // service : AreaSketchService // port : AreaSketchServiceSoap // URL : http://localhost/WSAreaSketch/AreaSketchService.asmx // ************************************************************************ // AreaSketchServiceSoap = interface(IInvokable) ['{4CF6A4EF-5B51-0316-7268-CD38AC1BF74D}'] procedure EvaluateAreaSketch(const TrialCustRec: TrialCustomer; const iIsPPC: Integer; const sPassword: WideString; out EvaluateAreaSketchResult: WideString; out iMsgCode: Integer; out sMsgs: WideString); stdcall; procedure RegisterAreaSketch(const sPass: WideString; const iCustID: Integer; const sDeviceID: WideString; const iIsPPC: Integer; out RegisterAreaSketchResult: WideString; out iMsgCode: Integer; out sMsgs: WideString); stdcall; end; function GetAreaSketchServiceSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): AreaSketchServiceSoap; implementation function GetAreaSketchServiceSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): AreaSketchServiceSoap; const defWSDL = 'http://localhost/WSAreaSketch/AreaSketchService.asmx?wsdl'; defURL = 'http://localhost/WSAreaSketch/AreaSketchService.asmx'; defSvc = 'AreaSketchService'; defPrt = 'AreaSketchServiceSoap'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as AreaSketchServiceSoap); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization InvRegistry.RegisterInterface(TypeInfo(AreaSketchServiceSoap), 'http://tempuri.org/', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(AreaSketchServiceSoap), 'http://tempuri.org/%operationName%'); InvRegistry.RegisterInvokeOptions(TypeInfo(AreaSketchServiceSoap), ioDocument); RemClassRegistry.RegisterXSClass(TrialCustomer, 'http://tempuri.org/', 'TrialCustomer'); end.
{***************************************************************************} { } { DUnitX } { } { Copyright (C) 2015 Vincent Parrett & Contributors } { } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DUnitX.Loggers.XML.JUnit; interface {$I DUnitX.inc} uses {$IFDEF USE_NS} System.Classes, System.SysUtils, System.Generics.Collections, {$ELSE} Classes, SysUtils, Generics.Collections, {$ENDIF} DUnitX.TestFramework, DUnitX.Loggers.Null; type TDUnitXXMLJUnitLogger = class(TDUnitXNullLogger) private FOutputStream : TStream; FOwnsStream : boolean; FIndent : integer; FFormatSettings : TFormatSettings; protected procedure Indent; procedure Outdent; procedure WriteXMLLine(const value : string); procedure OnTestingEnds(const RunResults: IRunResults); override; procedure WriteCategoryNodes(const ACategoryList: TList<string>); procedure WriteFixtureResult(const fixtureResult : IFixtureResult); procedure WriteTestResult(const testResult : ITestResult); function Format(const Format: string; const Args: array of const): String; public constructor Create(const AOutputStream : TStream; const AOwnsStream : boolean = false); destructor Destroy;override; end; TDUnitXXMLJUnitFileLogger = class(TDUnitXXMLJUnitLogger) public constructor Create(const AFilename: string = ''); end; implementation uses DUnitX.Utils.XML, {$IFDEF USE_NS} System.TypInfo; {$ELSE} TypInfo; {$ENDIF} { TDUnitXXMLJUnitLogger } constructor TDUnitXXMLJUnitLogger.Create(const AOutputStream: TStream; const AOwnsStream : boolean = false); var preamble: TBytes; {$IFNDEF DELPHI_XE_UP} oldThousandSeparator: Char; oldDecimalSeparator: Char; {$ENDIF} begin inherited Create; {$IFDEF DELPHI_XE_UP } FFormatSettings := TFormatSettings.Create; {$ENDIF} FFormatSettings.ThousandSeparator := ','; FFormatSettings.DecimalSeparator := '.'; {$IFNDEF DELPHI_XE_UP} oldThousandSeparator := {$IFDEF USE_NS}System.{$ENDIF}SysUtils.ThousandSeparator; oldDecimalSeparator := {$IFDEF USE_NS}System.{$ENDIF}DecimalSeparator; try SysUtils.ThousandSeparator := ','; SysUtils.DecimalSeparator := '.'; {$ENDIF} FOutputStream := AOutputStream; FOwnsStream := AOwnsStream; Preamble := TEncoding.UTF8.GetPreamble; FOutputStream.WriteBuffer(preamble[0], Length(preamble)); {$IFNDEF DELPHI_XE_UP} finally {$IFDEF USE_NS}System.{$ENDIF}SysUtils.ThousandSeparator := oldThousandSeparator; {$IFDEF USE_NS}System.{$ENDIF}SysUtils.DecimalSeparator := oldDecimalSeparator; end; {$ENDIF} end; destructor TDUnitXXMLJUnitLogger.Destroy; begin if FOwnsStream then FOutputStream.Free; inherited; end; function TDUnitXXMLJUnitLogger.Format(const Format: string; const Args: array of const): String; begin Result := {$IFDEF USE_NS}System.{$ENDIF}SysUtils.Format(Format, Args, FFormatSettings); end; procedure TDUnitXXMLJUnitLogger.Indent; begin Inc(FIndent,2); end; procedure TDUnitXXMLJUnitLogger.OnTestingEnds(const RunResults: IRunResults); procedure LogFixture(const fixture : IFixtureResult; level : integer); var child : IFixtureResult; sLevel : string; begin sLevel := StringOfChar(' ', level * 2 ); System.WriteLn(sLevel + fixture.Fixture.NameSpace + ':' + fixture.Fixture.Name + Format(' [Tests: %d] [Children: %d] [Passed : %d]',[fixture.ResultCount,fixture.ChildCount,fixture.PassCount])); Inc(level); for child in fixture.Children do begin LogFixture(child,level); end; end; var fixtureRes : IFixtureResult; sExeName : string; sTime : string; //totalTests : integer; begin { first things first, rollup the namespaces. So, where parent fixtures have no tests, or only one child fixture, combine into a single fixture. } for fixtureRes in RunResults.FixtureResults do begin fixtureRes.Reduce; // LogFixture(fixtureRes,0); end; //JUnit reports the total without the Ignored. // totalTests := RunResults.TestCount - RunResults.IgnoredCount; sExeName := ParamStr(0); FIndent := 0; sTime := Format('%.3f',[RunResults.Duration.TotalSeconds]); WriteXMLLine('<?xml version="1.0" encoding="UTF-8"?>'); // Global overview // There is only a "disabled" attribute on the top level, but "disabled" and "skipped" on fixture level. Return ignored tests as "disabled" WriteXMLLine(Format('<testsuites name="%s" tests="%d" disabled="%d" errors="%d" failures="%d" time="%s">', [sExeName,RunResults.TestCount, RunResults.IgnoredCount, RunResults.ErrorCount, RunResults.FailureCount, sTime])); Indent; for fixtureRes in RunResults.FixtureResults do WriteFixtureResult(fixtureRes); Outdent; WriteXMLLine('</testsuites>'); end; procedure TDUnitXXMLJUnitLogger.Outdent; begin Dec(FIndent,2); end; procedure TDUnitXXMLJUnitLogger.WriteFixtureResult(const fixtureResult: IFixtureResult); var sTime : string; sDate : string; child : IFixtureResult; testResult : ITestResult; sExecuted : string; sName: string; begin //its a real fixture if the class is not TObject. if (not fixtureResult.Fixture.TestClass.ClassNameIs('TObject')) then begin //if there were no tests then just ignore this fixture. if fixtureResult.ResultCount = 0 then exit; sExecuted := BoolToStr(fixtureResult.ResultCount > 0,true); sExecuted := EscapeForXML(sExecuted); sName := StringReplace(fixtureResult.Fixture.FullName, '.' + fixtureResult.Fixture.Name, '' , []); sTime := Format('%.3f',[fixtureResult.Duration.TotalSeconds]); sName := EscapeForXML(sName); sTime := EscapeForXML(sTime); sDate := FormatDateTime('yyyy-MM-dd"T"hh:nn:ss', fixtureResult.StartTime); // There is only a "disabled" attribute on the top level, but "disabled" and "skipped" on fixture level. Return ignored tests as "disabled" WriteXMLLine(Format('<testsuite name="%s" tests="%d" disabled="%d" errors="%d" failures="%d" time="%s" timestamp="%s">', [sName, fixtureResult.TestResults.Count, fixtureResult.IgnoredCount, fixtureResult.ErrorCount, fixtureResult.FailureCount, sTime, sDate])); //WriteCategoryNodes(fixtureResult.Fixture.Categories); for testResult in fixtureResult.TestResults do begin WriteTestResult(testResult); end; WriteXMLLine('</testsuite>'); for child in fixtureResult.Children do begin WriteFixtureResult(child); end; end else begin //It's a Namespace. if fixtureResult.ChildCount > 0 then begin for child in fixtureResult.Children do begin WriteFixtureResult(child); end; end; end; end; procedure TDUnitXXMLJUnitLogger.WriteTestResult(const testResult: ITestResult); var sTime : string; sName : string; sClassName: string; begin Indent; try sTime := Format('%.3f',[testResult.Duration.TotalSeconds]); sName := EscapeForXML(testResult.Test.Name); sClassName := EscapeForXML(testResult.Test.Fixture.Name); sTime := EscapeForXML(sTime); WriteXMLLine(Format('<testcase classname="%s" name="%s" time="%s">', [sClassName, sName, sTime])); //WriteCategoryNodes(testResult.Test.Categories); case testResult.ResultType of TTestResultType.Failure: begin Indent; WriteXMLLine(Format('<failure message="%s">', [EscapeForXML(testResult.Message)])); Indent; WriteXMLLine(Format('<![CDATA[ %s ]]>', [EscapeForXML(testResult.Message, False, True)])); Outdent; WriteXMLLine('</failure>'); Outdent; end; TTestResultType.MemoryLeak, TTestResultType.Error: begin Indent; WriteXMLLine(Format('<error message="%s">', [EscapeForXML(testResult.Message)])); Indent; WriteXMLLine(Format('<![CDATA[ %s ]]>', [EscapeForXML(testResult.StackTrace, False, True)])); Outdent; WriteXMLLine('</error>'); Outdent; end; TTestResultType.Ignored: begin Indent; WriteXMLLine('<skipped/>'); Outdent; end; TTestResultType.Pass : begin // if testResult.Test.Categories.Count = 0 then // begin // exit; // end; // Indent; end; end; WriteXMLLine('</testcase>'); finally Outdent; end; end; procedure TDUnitXXMLJUnitLogger.WriteCategoryNodes(const ACategoryList: TList<string>); var sCategory: string; begin if ACategoryList.Count > 0 then begin Indent; WriteXMLLine('<categories>'); Indent; for sCategory in ACategoryList do WriteXMLLine(Format('<category name="%s" />', [sCategory])); Outdent; WriteXMLLine('</categories>'); Outdent; end; end; procedure TDUnitXXMLJUnitLogger.WriteXMLLine(const value: string); var bytes : TBytes; s : string; begin s := StringOfChar(' ',FIndent) + value + #13#10; bytes := TEncoding.UTF8.GetBytes(s); FOutputStream.Write(bytes[0],Length(bytes)); end; { TDUnitXXMLJUnitFileLogger } constructor TDUnitXXMLJUnitFileLogger.Create(const AFilename: string); var sXmlFilename : string; fileStream : TFileStream; lXmlDirectory: string; const DEFAULT_JUNIT_FILE_NAME = 'dunitx-results.xml'; begin sXmlFilename := AFilename; if sXmlFilename = '' then sXmlFilename := ExtractFilePath(ParamStr(0)) + DEFAULT_JUNIT_FILE_NAME; lXmlDirectory := ExtractFilePath(sXmlFilename); ForceDirectories(lXmlDirectory); fileStream := TFileStream.Create(sXmlFilename, fmCreate); //base class will destroy the stream; inherited Create(fileStream,true); end; end.
// Helper unit for Delphi FAR plugins. unit PluginEx; interface uses Windows, {$IFDEF UNICODE}PluginW{$ELSE}Plugin{$ENDIF}; type {$IFNDEF UNICODE} TFarChar = AnsiChar; PFarChar = PAnsiChar; FarString = AnsiString; {$ELSE} FarString = WideString; {$ENDIF} FarChar = TFarChar; TFarStringDynArray = array of FarString; function PToStr(P: PFarChar): FarString; inline; // work around Delphi's strict type declarations function CharToOemStr(S: FarString): FarString; function OemToCharStr(S: FarString): FarString; function NullStringsToArray(P: PFarChar): TFarStringDynArray; function ArrayToNullStrings(A: TFarStringDynArray): FarString; procedure CopyStrToBuf(S: FarString; Buf: PFarChar; BufSize: Integer); function IntToStr(I: Integer): FarString; inline; function TryLoadString(FileName: FarString; var Data: FarString): Boolean; function TryLoadText(FileName: FarString; var Data: FarString): Boolean; function TrySaveString(FileName, Data: FarString): Boolean; function TrySaveText(FileName, Data: FarString): Boolean; function StrReplace(Haystack, Source, Dest: FarString): FarString; function Trim(S: FarString): FarString; function Split(S: FarString; Delim: FarString): TFarStringDynArray; function SplitByAny(S, Delims: FarString): TFarStringDynArray; function SplitLines(S: FarString): TFarStringDynArray; function Join(S: TFarStringDynArray; Delim: FarString): FarString; function MakeStrings(const S: array of FarString): TFarStringDynArray; procedure AppendToStrings(var Strings: TFarStringDynArray; S: FarString); function ConcatStrings(const S: array of TFarStringDynArray): TFarStringDynArray; function GetTempFullFileName(PrefixString: FarString='Far'): FarString; // ANSI/UNICODE wrappers for WinAPI functions function RegCreateKeyExF(hKey: HKEY; lpSubKey: PFarChar; Reserved: DWORD; lpClass: PFarChar; dwOptions: DWORD; samDesired: REGSAM; lpSecurityAttributes: PSecurityAttributes; var phkResult: HKEY; lpdwDisposition: PDWORD): Longint; inline; function RegOpenKeyExF(hKey: HKEY; lpSubKey: PFarChar; ulOptions: DWORD; samDesired: REGSAM; var phkResult: HKEY): Longint; inline; function RegQueryValueExF(hKey: HKEY; lpValueName: PFarChar; lpReserved: Pointer; lpType: PDWORD; lpData: PByte; lpcbData: PDWORD): Longint; inline; function RegSetValueExF(hKey: HKEY; lpValueName: PFarChar; Reserved: DWORD; dwType: DWORD; lpData: Pointer; cbData: DWORD): Longint; inline; function RegDeleteKeyF(hKey: HKEY; lpSubKey: PFarChar): Longint; inline; function SetEnvironmentVariableF(lpName, lpValue: PFarChar): BOOL; inline; function GetEnvironmentStringsF: PFarChar; inline; function FreeEnvironmentStringsF(EnvBlock: PFarChar): BOOL; inline; function ExpandEnvironmentStringsF(lpSrc: PFarChar; lpDst: PFarChar; nSize: DWORD): DWORD; inline; function GetTempPathF(nBufferLength: DWORD; lpBuffer: PFarChar): DWORD; function GetTempFileNameF(lpPathName, lpPrefixString: PFarChar; uUnique: UINT; lpTempFileName: PFarChar): UINT; function DeleteFileF(lpFileName: PFarChar): BOOL; type TFarDialog = class Items: array of TFarDialogItem; function Add(ItemType, Flags: Integer; X1, Y1, X2, Y2: Integer; InitialData: FarString; MaxLen: Integer = 0): Integer; function Run(GUID: TGUID; W, H: Integer; HelpTopic: PFarChar = nil): Integer; function GetData(Index: Integer): FarString; function GetChecked(Index: Integer): Boolean; {$IFDEF UNICODE} destructor Destroy; override; {$ENDIF} private Data: TFarStringDynArray; {$IFDEF UNICODE} Handle: THandle; {$ENDIF} end; type TMessage = ( {$I lang.inc} M__Last // allow ending the list with a comma ); function GetMsg(MsgId: TMessage): PFarChar; function Message(GUID: TGUID; Flags: DWORD; const Lines: array of FarString; ButtonCount: Integer = 0; HelpTopic: PFarChar = nil): Integer; function EditString(var Data: FarString; Title: FarString): Boolean; {$IFNDEF UNICODE} const OPEN_FROMMACRO = $10000; // not in Plugin.pas {$ENDIF} const DIF_NONE = 0; var FARAPI: TPluginStartupInfo; {$IFDEF FAR3} PluginGUID: TGUID; {$ENDIF} type TSettings = class function GetString (Name: FarString; Default: FarString = ''): FarString; virtual; abstract; procedure SetString (Name: FarString; Value: FarString); virtual; abstract; function GetStrings (Name: FarString): TFarStringDynArray; virtual; abstract; procedure SetStrings (Name: FarString; Value: TFarStringDynArray); virtual; abstract; function GetInt (Name: FarString): Integer; virtual; abstract; procedure SetInt (Name: FarString; Value: Integer); virtual; abstract; function OpenKey (Name: FarString): TSettings; virtual; abstract; procedure DeleteKey (Name: FarString); virtual; abstract; function ValueExists(Name: FarString): Boolean; virtual; abstract; function KeyExists (Name: FarString): Boolean; virtual; abstract; end; TRegistrySettings = class(TSettings) constructor Create(Name: FarString); constructor CreateFrom(SubKey: HKEY); destructor Destroy; override; function GetString (Name: FarString; Default: FarString = ''): FarString; override; procedure SetString (Name: FarString; Value: FarString); override; function GetStrings(Name: FarString): TFarStringDynArray; override; procedure SetStrings(Name: FarString; Value: TFarStringDynArray); override; function GetInt (Name: FarString): Integer; override; procedure SetInt (Name: FarString; Value: Integer); override; function OpenKey (Name: FarString): TSettings; override; procedure DeleteKey (Name: FarString); override; function ValueExists(Name: FarString): Boolean; override; function KeyExists (Name: FarString): Boolean; override; private Key: HKEY; function GetStringRaw(Name: FarString; Default: FarString = ''): FarString; procedure SetStringRaw(Name: FarString; Value: FarString; RegType: Cardinal); end; implementation // ************************************************************************************************************************************************************ function PToStr(P: PFarChar): FarString; inline; begin {$IFNDEF UNICODE} Result := PChar(P); {$ELSE} Result := PWideChar(P); {$ENDIF} end; function CharToOemStr(S: FarString): FarString; begin {$IFNDEF UNICODE} SetLength(Result, Length(S)); CharToOem(PFarChar(S), @Result[1]); {$ELSE} Result := S; {$ENDIF} end; function OemToCharStr(S: FarString): FarString; begin {$IFNDEF UNICODE} SetLength(Result, Length(S)); OemToChar(PFarChar(S), @Result[1]); {$ELSE} Result := S; {$ENDIF} end; // Convert a zero-terminated string sequence (which itself is // doubly-zero-terminated) to a TStringDynArray. function NullStringsToArray(P: PFarChar): TFarStringDynArray; var P2: PFarChar; begin SetLength(Result, 0); while P^<>#0 do begin P2 := P; repeat Inc(P2); until P2^=#0; SetLength(Result, Length(Result)+1); Result[High(Result)] := Copy(P, 1, UINT_PTR(P2)-UINT_PTR(P)); P := P2; Inc(P); end; end; function ArrayToNullStrings(A: TFarStringDynArray): FarString; var I: Integer; begin Result := ''; for I:=0 to High(A) do if Length(A[I])>0 then Result := Result + A[I] + #0; Result := Result + #0; end; procedure CopyStrToBuf(S: FarString; Buf: PFarChar; BufSize: Integer); begin if Length(S)>BufSize-1 then S := Copy(S, 1, BufSize-1); S := S+#0; Move(S[1], Buf^, Length(S) * SizeOf(FarChar)); end; // To avoid pulling in heavy SysUtils unit function IntToStr(I: Integer): FarString; inline; begin Str(I, Result); end; function TryLoadString(FileName: FarString; var Data: FarString): Boolean; var F: File; OldFileMode: Integer; begin OldFileMode := FileMode; FileMode := {fmOpenRead}0; Assign(F, FileName); {$I-} Reset(F, SizeOf(FarChar)); {$I+} FileMode := OldFileMode; Result := False; if IOResult<>0 then Exit; SetLength(Data, FileSize(F)); if FileSize(F)>0 then BlockRead(F, Data[1], FileSize(F)); CloseFile(F); Result := True; end; function TryLoadText(FileName: FarString; var Data: FarString): Boolean; var F: File; OldFileMode: Integer; RawData: AnsiString; begin OldFileMode := FileMode; FileMode := {fmOpenRead}0; Assign(F, FileName); {$I-} Reset(F, 1); {$I+} FileMode := OldFileMode; Result := False; if IOResult<>0 then Exit; SetLength(RawData, FileSize(F)); if FileSize(F)>0 then BlockRead(F, RawData[1], FileSize(F)); CloseFile(F); {$IFDEF UNICODE} if (Copy(RawData, 1, 2)=#$FF#$FE) and (Length(RawData) mod 2 = 0) then begin SetLength(Data, Length(RawData) div 2 - 1); Move(RawData[3], Data[1], Length(RawData)-2); end else {$ENDIF} Data := RawData; Result := True; end; function TrySaveString(FileName, Data: FarString): Boolean; var F: File; begin Assign(F, FileName); {$I-} ReWrite(F, SizeOf(FarChar)); {$I+} Result := False; if IOResult<>0 then Exit; BlockWrite(F, Data[1], Length(Data)); CloseFile(F); Result := True; end; function TrySaveText(FileName, Data: FarString): Boolean; begin {$IFDEF UNICODE} Data := #$FEFF + Data; // add BOM {$ENDIF} Result := TrySaveString(Filename, Data); end; function StrReplace(Haystack, Source, Dest: FarString): FarString; var P: Integer; begin Result := Haystack; while true do begin P := Pos(Source, Result); if P=0 then Exit; Delete(Result, P, Length(Source)); Insert(Result, Dest, P); end; end; function Trim(S: FarString): FarString; begin while Copy(S, 1, 1)=' ' do Delete(S, 1, 1); while (Length(S)>0) and (Copy(S, Length(S), 1)=' ') do Delete(S, Length(S), 1); Result := S; end; function PosAny(Delims, S: FarString): Integer; var I, P: Integer; begin Result := 0; for I := 1 to Length(Delims) do begin P := Pos(Delims[I], S); if (Result=0) or ((P <> 0) and (P < Result)) then Result := P; end; end; function Split(S: FarString; Delim: FarString): TFarStringDynArray; var P: Integer; begin Result := nil; if S='' then Exit; S := S + Delim; while S<>'' do begin SetLength(Result, Length(Result)+1); P := Pos(Delim, S); Result[High(Result)] := Copy(S, 1, P-1); Delete(S, 1, P-1+Length(Delim)); end; end; function SplitByAny(S, Delims: FarString): TFarStringDynArray; var P: Integer; begin Result := nil; if S='' then Exit; S := S + Delims[1]; while S<>'' do begin SetLength(Result, Length(Result)+1); P := PosAny(Delims, S); Result[High(Result)] := Copy(S, 1, P-1); Delete(S, 1, P); end; end; function SplitLines(S: FarString): TFarStringDynArray; var I: Integer; begin Result := Split(S, #10); for I:=0 to High(Result) do begin while Copy(Result[I], 1, 1)=#13 do Delete(Result[I], 1, 1); while Copy(Result[I], Length(Result[I]), 1)=#13 do Delete(Result[I], Length(Result[I]), 1); end; end; function Join(S: TFarStringDynArray; Delim: FarString): FarString; var I: Integer; begin Result := ''; for I:=0 to High(S) do begin if I>0 then Result := Result + Delim; Result := Result + S[I]; end; end; function MakeStrings(const S: array of FarString): TFarStringDynArray; var I: Integer; begin SetLength(Result, Length(S)); for I:=0 to High(S) do Result[I] := S[I]; end; procedure AppendToStrings(var Strings: TFarStringDynArray; S: FarString); begin SetLength(Strings, Length(Strings)+1); Strings[High(Strings)] := S; end; function ConcatStrings(const S: array of TFarStringDynArray): TFarStringDynArray; var I, J, N: Integer; begin Result := nil; for I:=0 to High(S) do begin N := Length(Result); SetLength(Result, Length(Result)+Length(S[I])); for J:=0 to High(S[I]) do Result[N+J] := S[I][J]; end; end; function GetTempFullFileName(PrefixString: FarString='Far'): FarString; var Path: array[0..MAX_PATH] of FarChar; begin GetTempPathF(MAX_PATH, @Path[0]); GetTempFileNameF(@Path[0], PFarChar(PrefixString), 0, @Path[0]); Result := PFarChar(@Path[0]); end; // ************************************************************************************************************************************************************ function RegCreateKeyExF(hKey: HKEY; lpSubKey: PFarChar; Reserved: DWORD; lpClass: PFarChar; dwOptions: DWORD; samDesired: REGSAM; lpSecurityAttributes: PSecurityAttributes; var phkResult: HKEY; lpdwDisposition: PDWORD): Longint; inline; begin Result := {$IFNDEF UNICODE}RegCreateKeyExA{$ELSE}RegCreateKeyExW{$ENDIF}(hKey, lpSubKey, Reserved, lpClass, dwOptions, samDesired, lpSecurityAttributes, phkResult, lpdwDisposition); end; function RegOpenKeyExF(hKey: HKEY; lpSubKey: PFarChar; ulOptions: DWORD; samDesired: REGSAM; var phkResult: HKEY): Longint; inline; begin Result := {$IFNDEF UNICODE}RegOpenKeyExA{$ELSE}RegOpenKeyExW{$ENDIF}(hKey, lpSubKey, ulOptions, samDesired, phkResult); end; function RegQueryValueExF(hKey: HKEY; lpValueName: PFarChar; lpReserved: Pointer; lpType: PDWORD; lpData: PByte; lpcbData: PDWORD): Longint; inline; begin Result := {$IFNDEF UNICODE}RegQueryValueExA{$ELSE}RegQueryValueExW{$ENDIF}(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData); end; function RegSetValueExF(hKey: HKEY; lpValueName: PFarChar; Reserved: DWORD; dwType: DWORD; lpData: Pointer; cbData: DWORD): Longint; inline; begin Result := {$IFNDEF UNICODE}RegSetValueExA{$ELSE}RegSetValueExW{$ENDIF}(hKey, lpValueName, Reserved, dwType, lpData, cbData); end; function RegDeleteKeyF(hKey: HKEY; lpSubKey: PFarChar): Longint; inline; begin Result := {$IFNDEF UNICODE}RegDeleteKeyA{$ELSE}RegDeleteKeyW{$ENDIF}(hKey, lpSubKey); end; function SetEnvironmentVariableF(lpName, lpValue: PFarChar): BOOL; inline; begin Result := {$IFNDEF UNICODE}SetEnvironmentVariableA{$ELSE}SetEnvironmentVariableW{$ENDIF}(lpName, lpValue); end; function GetEnvironmentStringsF: PFarChar; inline; begin Result := {$IFNDEF UNICODE}GetEnvironmentStringsA{$ELSE}GetEnvironmentStringsW{$ENDIF}; end; function FreeEnvironmentStringsF(EnvBlock: PFarChar): BOOL; inline; begin Result := {$IFNDEF UNICODE}FreeEnvironmentStringsA{$ELSE}FreeEnvironmentStringsW{$ENDIF}(EnvBlock); end; function ExpandEnvironmentStringsF(lpSrc: PFarChar; lpDst: PFarChar; nSize: DWORD): DWORD; inline; begin Result := {$IFNDEF UNICODE}ExpandEnvironmentStringsA{$ELSE}ExpandEnvironmentStringsW{$ENDIF}(lpSrc, lpDst, nSize); end; function GetTempPathF(nBufferLength: DWORD; lpBuffer: PFarChar): DWORD; begin Result := {$IFNDEF UNICODE}GetTempPathA{$ELSE}GetTempPathW{$ENDIF}(nBufferLength, lpBuffer); end; function GetTempFileNameF(lpPathName, lpPrefixString: PFarChar; uUnique: UINT; lpTempFileName: PFarChar): UINT; begin Result := {$IFNDEF UNICODE}GetTempFileNameA{$ELSE}GetTempFileNameW{$ENDIF}(lpPathName, lpPrefixString, uUnique, lpTempFileName); end; function DeleteFileF(lpFileName: PFarChar): BOOL; begin Result := {$IFNDEF UNICODE}DeleteFileA{$ELSE}DeleteFileW{$ENDIF}(lpFileName); end; // ************************************************************************************************************************************************************ function TFarDialog.Add(ItemType, Flags: Integer; X1, Y1, X2, Y2: Integer; InitialData: FarString; MaxLen: Integer = 0): Integer; var NewItem: PFarDialogItem; begin SetLength(Items, Length(Items)+1); Result := High(Items); NewItem := @Items[Result]; FillChar(NewItem^, SizeOf(NewItem^), 0); NewItem.ItemType := ItemType; NewItem.Flags := Flags; NewItem.X1 := X1; NewItem.Y1 := Y1; NewItem.X2 := X2; NewItem.Y2 := Y2; {$IFNDEF UNICODE} if MaxLen < Length(InitialData)+1 then MaxLen := Length(InitialData)+1; if (MaxLen >= SizeOf(NewItem.Data.Data)) and ((ItemType=DI_COMBOBOX) or (ItemType=DI_EDIT)) then begin SetLength(Data, Length(Items)); Data[Result] := InitialData + #0; SetLength(Data[Result], MaxLen); NewItem.Data.Ptr.PtrFlags := 0; NewItem.Data.Ptr.PtrLength := MaxLen; NewItem.Data.Ptr.PtrData := @Data[Result][1]; NewItem.Flags := NewItem.Flags or DIF_VAREDIT; end else CopyStrToBuf(InitialData, NewItem.Data.Data, SizeOf(NewItem.Data.Data)); {$ELSE} SetLength(Data, Length(Items)); Data[Result] := InitialData; NewItem.{$IFDEF FAR3}Data {$ELSE}PtrData{$ENDIF} := @Data[Result][1]; NewItem.{$IFDEF FAR3}MaxLength{$ELSE}MaxLen {$ENDIF} := 0; {$ENDIF} end; function TFarDialog.Run(GUID: TGUID; W, H: Integer; HelpTopic: PFarChar = nil): Integer; begin {$IFNDEF UNICODE} Result := FARAPI.Dialog(FARAPI.ModuleNumber, -1, -1, W, H, HelpTopic, @Items[0], Length(Items)); {$ELSE} Handle := FARAPI.DialogInit({$IFDEF FAR3}PluginGUID, GUID{$ELSE}FARAPI.ModuleNumber{$ENDIF}, -1, -1, W, H, HelpTopic, @Items[0], Length(Items), 0, 0, nil, 0); Result := FARAPI.DialogRun(Handle); {$ENDIF} end; {$IFDEF UNICODE} destructor TFarDialog.Destroy; begin FARAPI.DialogFree(Handle); inherited; end; {$ENDIF} function TFarDialog.GetData(Index: Integer): FarString; begin {$IFNDEF UNICODE} if (Items[Index].Flags and DIF_VAREDIT)<>0 then Result := PFarChar(@Data[Index][1]) else Result := PFarChar(@Items[Index].Data.Data[0]); {$ELSE} Result := PFarChar(FARAPI.SendDlgMessage(Handle, DM_GETCONSTTEXTPTR, Index, {$IFDEF FAR3}nil{$ELSE}0{$ENDIF})); {$ENDIF} end; function TFarDialog.GetChecked(Index: Integer): Boolean; begin {$IFNDEF UNICODE} Result := Boolean(Items[Index].Param.Selected); {$ELSE} Result := Boolean(FARAPI.SendDlgMessage(Handle, DM_GETCHECK, Index, {$IFDEF FAR3}nil{$ELSE}0{$ENDIF})); {$ENDIF} end; // ************************************************************************************************************************************************************ function GetMsg(MsgId: TMessage): PFarChar; begin Result := FARAPI.GetMsg({$IFDEF FAR3}PluginGUID{$ELSE}FARAPI.ModuleNumber{$ENDIF}, Integer(MsgId)); end; function Message(GUID: TGUID; Flags: DWORD; const Lines: array of FarString; ButtonCount: Integer = 0; HelpTopic: PFarChar = nil): Integer; begin Result := FARAPI.Message({$IFDEF FAR3}GUID, PluginGUID{$ELSE}FARAPI.ModuleNumber{$ENDIF}, Flags, HelpTopic, PPCharArray(@Lines[0]), Length(Lines), ButtonCount); end; // Open an editor on a temporary file to edit given string function EditString(var Data: FarString; Title: FarString): Boolean; const FileCreateErrorGUID: TGUID = '{164559c7-1bb2-497e-b6eb-bdc431c121b6}'; FileLoadErrorGUID: TGUID = '{72955220-29c1-4493-8359-b0f91bd5592a}'; var FileName: FarString; begin Result := False; FileName := GetTempFullFileName('Env'); if not TrySaveText(FileName, Data) then begin Message(FileCreateErrorGUID, FMSG_WARNING or FMSG_MB_OK, [GetMsg(MError), GetMsg(MFileCreateError), FileName]); Exit; end; if FARAPI.Editor(PFarChar(FileName), PFarChar(Title), -1, -1, -1, -1, EF_DISABLEHISTORY, 0, 1{$IFDEF UNICODE}, CP_UNICODE{$ENDIF})=EEC_MODIFIED then begin Result := True; if not TryLoadText(FileName, Data) then begin Message(FileLoadErrorGUID, FMSG_WARNING or FMSG_MB_OK, [GetMsg(MError), GetMsg(MFileLoadError), FileName]); Exit; end; end; DeleteFileF(PFarChar(FileName)); end; // ************************************************************************************************************************************************************ constructor TRegistrySettings.Create(Name: FarString); var RegKey: FarString; begin {$IFDEF FAR3} RegKey := 'Software\Far2\Plugins\' + Name; {$ELSE} RegKey := FARAPI.RootKey + FarString('\') + Name; {$ENDIF} Key := 0; RegCreateKeyExF(HKEY_CURRENT_USER, PFarChar(RegKey), 0, nil, 0, KEY_ALL_ACCESS, nil, Key, nil); //if Key=0 then // raise Exception.Create('Can''t open registry key '+ RegKey); end; constructor TRegistrySettings.CreateFrom(SubKey: HKEY); begin Key := SubKey; end; destructor TRegistrySettings.Destroy; begin RegCloseKey(Key); end; function TRegistrySettings.GetStringRaw(Name: FarString; Default: FarString = ''): FarString; var R: Integer; Size: Cardinal; PName: PFarChar; begin Result := Default; if Name='' then PName := nil else PName := PFarChar(Name); Size := 0; R := RegQueryValueExF(Key, PName, nil, nil, nil, @Size); if R<>ERROR_SUCCESS then Exit; SetLength(Result, Size div SizeOf(FarChar)); if Size=0 then Exit; R := RegQueryValueExF(Key, PName, nil, nil, @Result[1], @Size); if R<>ERROR_SUCCESS then Result := Default; end; function TRegistrySettings.GetString(Name: FarString; Default: FarString = ''): FarString; begin Result := GetStringRaw(Name, Default {+ #0}); {$IFNDEF UNICODE} CharToOem(@Result[1], @Result[1]); {$ENDIF} Result := PFarChar(Result); // Reinterpret as null-terminated end; function TRegistrySettings.GetStrings(Name: FarString): TFarStringDynArray; {$IFNDEF UNICODE} var I: Integer; {$ENDIF} begin Result := NullStringsToArray(PFarChar(GetStringRaw(Name))); {$IFNDEF UNICODE} for I:=0 to High(Result) do CharToOem(PFarChar(Result[I]), PFarChar(Result[I])); {$ENDIF} end; function TRegistrySettings.GetInt(Name: FarString): Integer; var Size: Cardinal; begin Result := 0; Size := SizeOf(Result); RegQueryValueExF(Key, PFarChar(Name), nil, nil, @Result, @Size); end; procedure TRegistrySettings.SetStringRaw(Name: FarString; Value: FarString; RegType: Cardinal); begin RegSetValueExF(Key, PFarChar(Name), 0, RegType, @Value[1], Length(Value) * SizeOf(FarChar)); end; procedure TRegistrySettings.SetString(Name: FarString; Value: FarString); begin {$IFNDEF UNICODE} OemToChar(@Value[1], @Value[1]); {$ENDIF} SetStringRaw(Name, Value+#0, REG_SZ); end; procedure TRegistrySettings.SetStrings(Name: FarString; Value: TFarStringDynArray); {$IFNDEF UNICODE} var I: Integer; {$ENDIF} begin {$IFNDEF UNICODE} for I:=0 to High(Value) do OemToChar(@Value[I][1], @Value[I][1]); {$ENDIF} SetStringRaw(Name, ArrayToNullStrings(Value), REG_MULTI_SZ); end; procedure TRegistrySettings.SetInt(Name: FarString; Value: Integer); begin RegSetValueExF(Key, PFarChar(Name), 0, REG_DWORD, @Value, SizeOf(Value)); end; function TRegistrySettings.OpenKey(Name: FarString): TSettings; var SubKey: HKEY; begin SubKey := 0; RegCreateKeyExF(Key, PFarChar(Name), 0, nil, 0, KEY_ALL_ACCESS, nil, SubKey, nil); Result := TRegistrySettings.CreateFrom(SubKey); end; procedure TRegistrySettings.DeleteKey(Name: FarString); begin RegDeleteKeyF(Key, PFarChar(Name)); end; function TRegistrySettings.ValueExists(Name: FarString): Boolean; begin Result := RegQueryValueExF(Key, PFarChar(Name), nil, nil, nil, nil) = ERROR_SUCCESS; end; function TRegistrySettings.KeyExists(Name: FarString): Boolean; var SubKey: HKEY; begin SubKey := 0; RegOpenKeyExF(Key, PFarChar(Name), 0, KEY_ALL_ACCESS, SubKey); Result := SubKey <> 0; if SubKey<>0 then RegCloseKey(SubKey); end; end.
{ Sobre o autor: Guinther Pauli Delphi Certified Professional - 3,5,6,7,2005,2006,Delphi Web,Kylix,XE Microsoft Certified Professional - MCP,MCAD,MCSD.NET,MCTS,MCPD (C#, ASP.NET, Arquitetura) Colaborador Editorial Revistas .net Magazine e ClubeDelphi MVP (Most Valuable Professional) - Embarcadero Technologies - US http://gpauli.com http://www.facebook.com/guintherpauli http://www.twitter.com/guintherpauli http://br.linkedin.com/in/guintherpauli } unit uFramework; interface type // Abstract Class Correcao = class abstract public procedure Corrigir(); virtual; abstract; public procedure VerificarPrerequisitos(); virtual; abstract; public procedure EnviarDadosParaBancoDeDados(); virtual; abstract; public procedure LimparCorrecoesAnteriores(); virtual; abstract; public procedure Iniciar(); virtual; abstract; // Template Method public procedure Processar(); end; CorrecaoProva = class(Correcao) public procedure Corrigir(); override; public procedure VerificarPrerequisitos(); override; public procedure EnviarDadosParaBancoDeDados(); override; public procedure LimparCorrecoesAnteriores(); override; public procedure Iniciar(); override; end; CorrecaoRedacao = class(Correcao) public procedure Corrigir(); override; public procedure VerificarPrerequisitos(); override; public procedure EnviarDadosParaBancoDeDados(); override; public procedure LimparCorrecoesAnteriores(); override; public procedure Iniciar(); override; end; CorrecaoInscricao = class(Correcao) public procedure Corrigir(); override; public procedure VerificarPrerequisitos(); override; public procedure EnviarDadosParaBancoDeDados(); override; public procedure LimparCorrecoesAnteriores(); override; public procedure Iniciar(); override; end; implementation { Correcao } procedure Correcao.Processar; begin // orquesta a chama de métodos virtuais Iniciar(); VerificarPrerequisitos(); LimparCorrecoesAnteriores(); Corrigir(); EnviarDadosParaBancoDeDados(); end; { CorrecaoProva } procedure CorrecaoProva.Corrigir(); begin Writeln('Corrigindo prova...'); end; procedure CorrecaoProva.EnviarDadosParaBancoDeDados(); begin Writeln('Enviando dados da prova para o BD...'); end; procedure CorrecaoProva.Iniciar(); begin Writeln('Iniciando processo de correção da prova...'); end; procedure CorrecaoProva.LimparCorrecoesAnteriores(); begin Writeln('Limpando dados de correções anteriores de provas...'); end; procedure CorrecaoProva.VerificarPrerequisitos(); begin Writeln('Verificando pré-requisitos para correção da prova...'); end; { CorrecaoRedacao } procedure CorrecaoRedacao.Corrigir(); begin Writeln('Corrigindo redação pela nota...'); end; procedure CorrecaoRedacao.EnviarDadosParaBancoDeDados(); begin Writeln('Enviando dados da redação para o BD...'); end; procedure CorrecaoRedacao.Iniciar(); begin Writeln('Iniciando processo de correção da redação...'); end; procedure CorrecaoRedacao.LimparCorrecoesAnteriores(); begin Writeln('Limpando dados de correções anteriores de redação...'); end; procedure CorrecaoRedacao.VerificarPrerequisitos(); begin Writeln('Verificando pré-requisitos para correação da redação...'); end; { CorrecaoInscricao } procedure CorrecaoInscricao.Corrigir(); begin Writeln('Processando inscrição...'); end; procedure CorrecaoInscricao.EnviarDadosParaBancoDeDados(); begin Writeln('Enviando dados da inscrição para o BD...'); end; procedure CorrecaoInscricao.Iniciar(); begin Writeln('Iniciando processo de inscrição...'); end; procedure CorrecaoInscricao.LimparCorrecoesAnteriores(); begin Writeln('Limpando dados de inscrições anteriores...'); end; procedure CorrecaoInscricao.VerificarPrerequisitos(); begin Writeln('Verificando pré-requisitos para inscrição...'); end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit ServerContainerUnit; interface uses System.SysUtils, System.Classes, Datasnap.DSTCPServerTransport, Datasnap.DSHTTPCommon, Datasnap.DSHTTP, Datasnap.DSServer, Datasnap.DSCommonServer, Datasnap.DSAuth, IPPeerServer; type TServerContainer = class(TDataModule) DSServer: TDSServer; DSTCPServerTransport: TDSTCPServerTransport; DSServerClass: TDSServerClass; DSAuthenticationManager: TDSAuthenticationManager; DSHTTPService: TDSHTTPService; procedure DSServerClassGetClass(DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); procedure DataModuleCreate(Sender: TObject); procedure DSAuthenticationManagerUserAuthenticate(Sender: TObject; const Protocol, Context, User, Password: string; var valid: Boolean; UserRoles: TStrings); procedure DSAuthenticationManagerUserAuthorize(Sender: TObject; AuthorizeEventObject: TDSAuthorizeEventObject; var valid: Boolean); private { Private declarations } public end; var ServerContainer: TServerContainer; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses Winapi.Windows, ServerMethodsUnit; procedure TServerContainer.DataModuleCreate(Sender: TObject); begin DSHTTPService.Active := True; end; procedure TServerContainer.DSAuthenticationManagerUserAuthenticate( Sender: TObject; const Protocol, Context, User, Password: string; var valid: Boolean; UserRoles: TStrings); begin { TODO : Validate the client user and password. If role-based authorization is needed, add role names to the UserRoles parameter } valid := True; end; procedure TServerContainer.DSAuthenticationManagerUserAuthorize(Sender: TObject; AuthorizeEventObject: TDSAuthorizeEventObject; var valid: Boolean); begin { TODO : Authorize a user to execute a method. Use values from EventObject such as UserName, UserRoles, AuthorizedRoles and DeniedRoles. Use DSAuthenticationManager1.Roles to define Authorized and Denied roles for particular server methods. } valid := True; end; procedure TServerContainer.DSServerClassGetClass( DSServerClass: TDSServerClass; var PersistentClass: TPersistentClass); begin PersistentClass := ServerMethodsUnit.TServerMethods; end; end.
unit EnumEditController; interface uses Classes, SysUtils, tiObject, mapper, mvc_base, widget_controllers, AppModel, EnumEditViewFrm, BaseOkCancelDialogController; type // ----------------------------------------------------------------- // Class Objects // ----------------------------------------------------------------- {: Edit an enumeration. } TEnumEditController = class(TBaseOkCancelDialogController) protected procedure DoCreateMediators; override; procedure HandleOKClick(Sender: TObject); override; public constructor Create(AModel: TMapEnum; AView: TEnumEditView); reintroduce; overload; virtual; function Model: TMapEnum; reintroduce; function View: TEnumEditView; reintroduce; procedure Update(ASubject: TtiObject); override; end; implementation uses vcl_controllers, StdCtrls, Controls, Dialogs, EnumEditCommands; { TEnumEditController } constructor TEnumEditController.Create(AModel: TMapEnum; AView: TEnumEditView); begin inherited Create(AModel, AView); RegisterCommands(self); end; procedure TEnumEditController.DoCreateMediators; var lListCtrl: TListViewController; begin inherited; AddController(TEditController.Create(Model, View.eEnumName, 'TypeName')); lListCtrl := TListViewController.Create(Model.Values, View.lvValue, ''); lListCtrl.Name := 'enumvalues_ctl'; with lListCtrl.AddNewCol('EnumValueName') do begin Width := 140; ColCaption := 'Value Name'; end; with lListCtrl.AddNewCol('EnumValue') do begin Width := 100; ColCaption := 'Value'; end; AddController(lListCtrl); AddController(TCheckBoxController.Create(Model, View.ckCreateEnumerationSet, 'EnumerationSet')); AddController(TEditController.Create(Model, View.eEnumerationSetName, 'EnumerationSetName')); Model.NotifyObservers; end; procedure TEnumEditController.HandleOKClick(Sender: TObject); var lMsg: string; begin if not Model.IsValid(lMsg) then begin MessageDlg('Error(s): ' + sLineBreak + lMsg, mtError, [mbOK], 0); exit; end; View.ModalResult := mrOk; end; function TEnumEditController.Model: TMapEnum; begin result := inherited Model as TMapEnum; end; procedure TEnumEditController.Update(ASubject: TtiObject); begin inherited; View.eEnumerationSetName.Enabled := Model.EnumerationSet; end; function TEnumEditController.View: TEnumEditView; begin Result := inherited View as TEnumEditView; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Menus, FontStyles, StdCtrls; type TForm1 = class(TForm) ListBox1: TListBox; FontStyles1: TFontStyles; MainMenu1: TMainMenu; PopupMenu1: TPopupMenu; imStyle: TMenuItem; Exit1: TMenuItem; Button1: TButton; Label1: TLabel; lbFont: TLabel; btnAdd: TButton; btnDelete: TButton; FontDialog1: TFontDialog; btnModify: TButton; edStyleName: TEdit; Label2: TLabel; ChangeName: TButton; procedure Exit1Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure imStyleClick(Sender: TObject); procedure FontStyles1SelectFont(Sender: TObject; index: Integer; SelectFont: TFont); procedure btnAddClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnModifyClick(Sender: TObject); procedure ChangeNameClick(Sender: TObject); private { Private declarations } function CheckListBoxIndex:boolean; public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Exit1Click(Sender: TObject); begin close; end; procedure TForm1.Button1Click(Sender: TObject); var p : TPoint; begin P := Button1.ClientToScreen(Point(0,Button1.height)); PopupMenu1.Popup(p.x,p.y); end; procedure TForm1.imStyleClick(Sender: TObject); begin if MainMenu1.ownerDraw then label1.caption := 'true' else label1.caption := 'false' end; procedure TForm1.FontStyles1SelectFont(Sender: TObject; index: Integer; SelectFont: TFont); begin if SelectFont<>nil then begin lbFont.font := SelectFont; edStyleName.text := FontStyles1.Styles[index].StyleName; end else edStyleName.text := ''; end; procedure TForm1.btnAddClick(Sender: TObject); begin if FontDialog1.execute then FontStyles1.Styles.AddFont(FontDialog1.Font); end; procedure TForm1.btnDeleteClick(Sender: TObject); begin if CheckListBoxIndex then FontStyles1.Styles.delete(ListBox1.ItemIndex); end; procedure TForm1.btnModifyClick(Sender: TObject); begin if CheckListBoxIndex then begin FontDialog1.font := FontStyles1.Styles[ListBox1.ItemIndex].font; if FontDialog1.execute then FontStyles1.Styles[ListBox1.ItemIndex].font := FontDialog1.font; end; end; procedure TForm1.ChangeNameClick(Sender: TObject); begin if CheckListBoxIndex then FontStyles1.Styles[ListBox1.ItemIndex].StyleName := edStyleName.text; end; function TForm1.CheckListBoxIndex: boolean; begin result := (ListBox1.ItemIndex>=0) and (ListBox1.ItemIndex<FontStyles1.Styles.count); end; end.
unit q3timer; interface uses windows; type THiResTimer = class(TObject) private FFrequency : int64; FoldTime : int64; // last system time public TotalTime : double; // time since app started FrameTime : double; // time elapsed since last frame Frames : cardinal; // total number of frames ElapsedTime : Integer; constructor Create; function Refresh : cardinal; function GetFPS : integer; function GetAverageFPS : integer; function GetTime : int64; function DiffTime(start_time, end_time : int64) : double; end; implementation constructor THiResTimer.Create; begin frames := 0; QueryPerformanceFrequency(FFrequency); // get high-resolution Frequency QueryPerformanceCounter(FoldTime); end; function THiResTimer.Refresh : cardinal; var tmp : int64; t2 : double; begin QueryPerformanceCounter(tmp); t2 := tmp-FoldTime; frameTime := t2/FFrequency; TotalTime := TotalTime + frameTime; ElapsedTime := (FoldTime + tmp) div 2; FoldTime := tmp; inc(Frames); result := Frames; end; function THiResTimer.GetFPS : integer; begin result := Round(1 / frameTime); end; function THiResTimer.GetAverageFPS : integer; begin if TotalTime > 0 then begin try result := Round(Frames / TotalTime); except ; end; end else result := 0; end; function THiResTimer.GetTime : int64; var tmp : int64; begin QueryPerformanceCounter(tmp); result := tmp; end; function THiResTimer.DiffTime(start_time, end_time : int64) : double; begin result := (end_time - start_time) / FFrequency; end; end.
unit FastReportAddOn; interface {Принимает число, род существительного, и три формы, например male, рубль, рубля, рублей. Возвращает число прописью} //function SpellNumber(n:Int64; g:gender; wrd:wordForms):String; {Принимает сумму цифрами, вид валюты и необязательный параметр писать ли с большой буквы, по умолчанию не писать TStas} //function CurrencyToStr(x:Currency; d:denezhka; mode:Boolean=true):String; uses Classes; type TMyFunctions = class(TComponent); procedure Register; implementation uses SysUtils, fs_iinterpreter; procedure Register; begin RegisterNoIcon([TMyFunctions]); end; type gender = (male, fimale, gay); //Род существительного wordForms = Array[1..3] of String[20]; denezhka = (RUR, USD, EUR); digit = 0..9; plur = 1..3; thousand = 0..999; razr = record wrd:wordForms; //Формы слова gend:gender; //род слова end; money = record rublik:razr; kopeechka:wordForms; end; TFunctions = class(TfsRTTIModule) private function CallMethod(Instance: TObject; ClassType: TClass; const MethodName: String; var Params: Variant): Variant; public constructor Create(AScript: TfsScript); override; end; const handrids:Array[0..9] of String[10] = ('', 'сто', 'двести', 'триста', 'четыреста', 'пятьсот', 'шестьсот', 'семьсот', 'восемьсот', 'девятьсот'); tens:Array[2..9] of String[15] = ('двадцать', 'тридцать', 'сорок', 'пятьдесят', 'шестьдесят', 'семьдесят', 'восемьдесят', 'девяносто'); teens:Array[0..9] of String[15] = ('десять', 'одиннадцать', 'двенадцать', 'тринадцать', 'четырнадцать', 'пятнадцать', 'шестнадцать', 'семнадцать', 'восемнадцать', 'девятнадцать'); units:Array[3..9] of String[10] = ('три', 'четыре', 'пять', 'шесть', 'семь', 'восемь', 'девять'); tys:razr = (wrd:('тысяча', 'тысячи', 'тысяч'); gend:fimale); mln:razr = (wrd:('миллион', 'миллиона', 'миллионов'); gend:male); mlrd:razr = (wrd:('миллиард', 'миллиарда', 'миллиардов'); gend:male); trln:razr = (wrd:('триллион', 'триллиона', 'триллионов'); gend:male); quln:razr = (wrd:('квадриллион', 'квадриллиона', 'квадриллионов'); gend:male); rup:razr = (wrd:('рубль', 'рубля', 'рублей'); gend:male); buck:razr = (wrd:('доллар', 'доллара', 'долларов'); gend:male); evrik:razr = (wrd:('евро', 'евро', 'евро'); gend:gay); kopek:wordForms = ('копейка', 'копейки', 'копеек'); cent:wordForms = ('цент', 'цента', 'центов'); {------------------------------------------------------------------} nfFull = 0; // Полное название триад: тысяча, миллион, ... nfShort = 4; // Краткое название триад: тыс., млн., ... nfMale = 0; // Мужской род nfFemale = 1; // Женский род nfMiddle = 2; // Средний род { Эти константы можно объединять с помощью "or". Функция G_NumToStr возвращает номер формы, в которой должно стоять следующее за данным числом слово, т.е. одно из следующих значений: } rfFirst = 1; // Первая форма: "один слон" или "двадцать одна кошка" rfSecond = 2; // Вторая форма: "три слона" или "четыре кошки" rfThird = 3; // Третья форма: "шесть слонов" или "восемь кошек" //--------------------------- function G_ModDiv10(var V: LongWord): Integer; const Base10: Integer = 10; asm {$IFDEF CPUX64 } MOV EAX,[RCX].LongWord XOR EDX,EDX DIV Base10 MOV [RCX].LongWord,EAX MOV EAX,EDX {$ELSE } MOV ECX,EAX MOV EAX,[EAX] XOR EDX,EDX DIV Base10 MOV [ECX],EAX MOV EAX,EDX {$ENDIF } end; //---------------------------- function G_NumToStr(N: Int64; var S: string; FormatFlags: LongInt): Integer; const M_Ed: array [1..9] of string = ('один ','два ','три ','чотири ','п`ять ','шiсть ','сiм ','вiсiм ','дев`ять '); W_Ed: array [1..9] of string = ('одна ','двi ','три ','чотири ','п`ять ','шiсть ','сiм ','вiсiм ','дев`ять '); G_Ed: array [1..9] of string = ('одне ','два ','три ','чотири ','п`ять ','шiсть ','сiм ','вiсiм ','дев`ять '); E_Ds: array [0..9] of string = ('десять ','одиннадцять ','дванадцять ','тринадцять ','чотирнадцять ', 'п`ятнадцять ','шiстнадцять ','сiмнадцять ','вiсiмнадцять ','дев`ятнадцять '); D_Ds: array [2..9] of string = ('двадцять ','тридцять ','сорок ','п`ятдесят ','шiстдесят ','сiмдесят ', 'вiсiмдесят ','дев`яносто '); U_Hd: array [1..9] of string = ('сто ','двiстi ','триста ','чотириста ','п`ятсот ','шiстсот ','сiмсот ', 'вiсiмсот ','дев`ятсот '); M_Tr: array[1..6,0..3] of string = (('тис. ','тисяча ','тисячi ','тисяч '), ('млн. ','мiлiон ','мiлiона ','мiлiонiв '), ('млрд. ','мiлiард ','мiлiарда ','мiлiардiв '), ('трлн. ','трилiон ','трилiона ','трилiонiв '), ('квадр. ','квадрілліон ','квадрильйона ','квадрильйонів '), ('квінт. ','квінтильйон ','квінтильйони ','квінтильйонів ')); var V1: Int64; VArr: array[0..6] of Integer; I, E, D, H, Count: Integer; SB: TStringBuilder; begin Result := 3; if N = 0 then begin S := 'нуль '; Exit; end; if N > 0 then SB := TStringBuilder.Create(120) else if N <> $8000000000000000 then begin N := -N; SB := TStringBuilder.Create('мінус '); end else begin { -9.223.372.036.854.775.808 } if FormatFlags and nfShort = 0 then S := 'мінус дев`ять квінтильйонів двісті двадцять три квадрильйона'+ ' триста сімдесят два трильйони тридцять шість мільярдів'+ ' вісімсот п`ятьдесят чотири мільйони сімсот сімдесят п`ять'+ ' тисяч вісімсот вісім ' else S := 'мінус дев`ять квінт. двісті двадцять три квадр. триста'+ ' сімдесят два трлн. тридцять шість млрд. вісімсот п`ятьдесят'+ ' чотири млн. сімсот сімдесят п`ять тис. вісімсот вісім '; Exit; end; Count := 0; repeat V1 := N div 1000; VArr[Count] := N - (V1 * 1000); N := V1; Inc(Count); until V1 = 0; for I := Count - 1 downto 0 do begin H := VArr[I]; Result := 3; if H <> 0 then begin E := G_ModDiv10(LongWord(H)); D := G_ModDiv10(LongWord(H)); if D <> 1 then begin if E = 1 then Result := 1 else if (E >= 2) and (E <= 4) then Result := 2; if (H <> 0) and (D <> 0) then SB.Append(U_Hd[H]).Append(D_Ds[D]) else if H <> 0 then SB.Append(U_Hd[H]) else if D <> 0 then SB.Append(D_Ds[D]); if E <> 0 then if I = 0 then case FormatFlags and 3 of 0: SB.Append(M_Ed[E]); 1: SB.Append(W_Ed[E]); 2: SB.Append(G_Ed[E]); else SB.Append('#### '); end else if I = 1 then SB.Append(W_Ed[E]) else SB.Append(M_Ed[E]); end else if H = 0 then SB.Append(E_Ds[E]) else SB.Append(U_Hd[H]).Append(E_Ds[E]); if I <> 0 then begin if FormatFlags and nfShort = 0 then SB.Append(M_Tr[I, Result]) else SB.Append(M_Tr[I, 0]); end; end; end; S := SB.ToString; SB.Free; end; function NumToStr(N: Int64; FormatFlags: LongInt): string; var l_str: string; begin G_NumToStr(N, l_str, FormatFlags); Result := l_str; end; //-------------------------------------------------------------Сумма Евро function GetUnitString(n:digit; x:gender):String; begin case n of 0: Result:=''; 1: begin case x of male: Result:='один'; gay: Result:='одно'; fimale: Result:='одна'; end; end; 2: begin case x of male: Result:='два'; gay: Result:='два'; fimale: Result:='две'; end; end; else Result:=units[n] end; //of case end; function GetPlur(n:Byte):plur; var n1, n10:digit; begin n:=n mod 100; n1:=n mod 10; n10:=n div 10; if n10=1 then Result:=3 else //Если дворой разряд не 1 begin case n1 of 1: Result:=1; 2, 3, 4: Result:=2; else result:=3; end; //of case end; end; function GetThousands(n:thousand; g:Gender; ss:wordForms):String; var n1, n10, n100:Digit; pl:plur; begin if n=0 then begin Result:=''; Exit; end; n1:=digit(n mod 10); n:=n div 10; n10:=digit(n mod 10); n:=n div 10; n100:=digit(n mod 10); Result:=handrids[n100]+' '; if n10<>1 then begin if n10<>0 then Result:=Result+tens[n10]+' '+GetUnitString(n1, g) else Result:=Result+GetUnitString(n1, g); end else //Если 10..19 begin Result:=Result+teens[n1]; end; Result:=Result+' '; //Пробел перед словом pl:=GetPlur(10*n10+n1); Result:=Result+ss[pl]; end; function SpellNumber(n:Int64; g:gender; wrd:wordForms):String; var n1, n2, n3, n4, n5, n6, m:word; begin if n=0 then begin Result:='ноль '+wrd[3]; Exit; end; if n<0 then n:=-n; n1:=n mod 1000; n:=n div 1000; n2:=n mod 1000; n:=n div 1000; n3:=n mod 1000; n:=n div 1000; n4:=n mod 1000; n:=n div 1000; n5:=n mod 1000; n:=n div 1000; n6:=n mod 1000; Result:=GetThousands(n1, g, wrd); if Result='' then Result:=wrd[3]; Result:=GetThousands(n2, tys.gend, tys.wrd)+' '+Result; Result:=GetThousands(n3, mln.gend, mln.wrd)+' '+Result; Result:=GetThousands(n4, mlrd.gend, mlrd.wrd)+' '+Result; Result:=GetThousands(n5, trln.gend, trln.wrd)+' '+Result; Result:=GetThousands(n6, quln.gend, quln.wrd)+' '+Result; repeat //Удаление двойных пробелов begin m:=Pos(' ', Result); if m<>0 then Delete(Result, m, 1); end until m=0; while Result[1]=' ' do Delete(Result, 1, 1); //Удаление передних пробелов end; function CurrencyToStr(x:Currency; d:denezhka; mode:Boolean=true):String; var ar:Array[denezhka] of money; r:razr; w:wordForms; x1:Int64; b:Byte; s:String; plr:plur; begin ar[rur].rublik:=rup; ar[rur].kopeechka:=kopek; ar[usd].rublik:=buck; ar[usd].kopeechka:=cent; ar[EUR].rublik:=evrik; ar[EUR].kopeechka:=cent; r:=ar[d].rublik; w:=ar[d].kopeechka; x:=abs(x); x1:=Trunc(x); Result:=SpellNumber(x1, r.gend, r.wrd); Result:=Result+' '; //Получаю сумму прописью пока без копеек x:=frac(x)*100; b:=Byte(round(x)); //Двузначное число копеек s:=IntToStr(b); if length(s)=1 then s:='0'+s; s:=s+' '; //число копеек цифрами Result:=result+s; plr:=GetPlur(b); s:=w[plr]; //слово "копеек" Result:=result+s; if mode then begin s:=AnsiUppercase(Result[1]); Result[1]:=s[1]; end; end; //------------------------------------------------------------------------ function SummaToText(n: Double): string; const ed1 : array[1..9] of string = ('одна','двi','три','чотири','п`ять','шiсть','сiм','вiсiм','дев`ять'); ed2 : array[1..2] of string = ('одна','двi'); ed3 : array[1..9] of string = ('один','два','три','чотири','п`ять','шiсть','сiм','вiсiм','дев`ять'); des : array[1..18] of string = ('десять','одиннадцять','дванадцять','тринадцять','чотирнадцять', 'п`ятнадцять','шiстнадцять','сiмнадцять','вiсiмнадцять', 'дев`ятнадцять','двадцять','тридцять','сорок','п`ятдесят', 'шiстдесят','сiмдесят','вiсiмдесят','дев`яносто'); sot : array[1..9] of string = ('сто','двiстi','триста','чотириста','п`ятсот', 'шiстсот','сiмсот','вiсiмсот','дев`ятсот'); tis1 : array[1..4] of string = ('тисяча','мільйон' ,'мільярд' ,'трильйон' ); tis2 : array[1..4] of string = ('тисяч' ,'мільйонiв','мільярдiв','трильйонiв'); tis3 : array[1..4] of string = ('тисячi','мільйона' ,'мільярда' ,'трильйона' ); {ed1 : array[1..9] of string = ('одна','две','три','четыре','пять','шесть','семь','восемь','девять'); ed2 : array[1..2] of string = ('одна','две'); des : array[1..18] of string = ('десять','одиннадцать','двенадцать','тринадцать','четырнадцать', 'пятнадцать','шестнадцать','семнадцать','восемнадцать', 'девятнадцать','двадцать','тридцать','сорок','пятьдесят', 'шестьдесят','семдесят','восемдесят','девяносто'); sot : array[1..9] of string = ('сто','двести','триста','четыреста','пятьсот', 'шестьсот','семсот','восемсот','девятсот'); tis1 : array[1..4] of string = ('тысяча','милион' ,'милиард' ,'трилион' ); tis2 : array[1..4] of string = ('тысяч' ,'милионов','милиардов','трилионов'); tis3 : array[1..4] of string = ('тысячи','милиона' ,'милиарда' ,'трилиона' ); } {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} function _3toScript(n : Word; male : Boolean) : String; var _1, _2, _3 : Word; begin Result:= ''; if n = 0 then begin Result:= ' '; exit; end; _1:= n div 100; if _1 <> 0 then Result:= sot[_1]+' '; _2:= (n mod 100) div 10; if _2 >= 2 then Result:= Result+des[9+_2]+' ' else if _2 = 1 then begin _2:= n mod 100; Result:= Result+des[_2-9]+' '; exit; end; _3:= (n mod 100) mod 10; if _3 = 0 then exit; if (_3 <= 2) and not male then Result:= Result+ed2[_3]+' ' else Result:= Result+ed1[_3]+' '; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} function _3toScript_mln(n : Word; male : Boolean) : String; var _1, _2, _3 : Word; begin Result:= ''; if n = 0 then begin Result:= ' '; exit; end; _1:= n div 100; if _1 <> 0 then Result:= sot[_1]+' '; _2:= (n mod 100) div 10; if _2 >= 2 then Result:= Result+des[9+_2]+' ' else if _2 = 1 then begin _2:= n mod 100; Result:= Result+des[_2-9]+' '; exit; end; _3:= (n mod 100) mod 10; if _3 = 0 then exit; if (_3 <= 2) and not male then Result:= Result+ed3[_3]+' ' else Result:= Result+ed3[_3]+' '; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} var Male : Boolean; tmp, LastDig, _2dig : Word; Count : Byte; Str : String; TmpInt:String; SavTmp: Double; begin TmpInt:=IntTostr(Trunc(n)); SavTmp:=n; n:= Int(n); Result:= ''; Str:= ''; Count:= 0; while n > 0.1 do begin Inc(Count); if Count = 2 then Male:= False else Male:= True; tmp:= Round(Frac(n/1000)*1000); n:= Int(n/1000); LastDig:= tmp mod 10; _2dig:= tmp mod 100; if Count >= 2 then if (_2dig >= 11) and (_2dig <= 19) then Str:= tis2[Count-1] else if LastDig = 1 then Str:= tis1[Count-1] else if (LastDig >= 2) and (LastDig <= 4) then Str:= tis3[Count-1] else Str:= tis2[Count-1]; if Count > 2 then Result:= _3toScript_mln(tmp, Male)+Str+' '+Result else Result:= _3toScript(tmp, Male)+Str+' '+Result; end; if TmpInt = '0' then Result := 'ноль '; Result := Result+'грн.'; Result[1] := AnsiUpperCase(Result[1])[1]; Result := Result + ' ' + FormatFloat('00', Round(Frac(SavTmp)*100 ))+' коп.'; end; function SummaToTextRu(n: Double): string; const {ed1 : array[1..9] of string = ('одна','двi','три','чотири','п`ять','шiсть','сiм','вiсiм','дев`ять'); ed2 : array[1..2] of string = ('одна','двi'); des : array[1..18] of string = ('десять','одиннадцять','дванадцять','тринадцять','чотирнадцять', 'п`ятнадцять','шiстнадцять','сiмнадцять','вiсiмнадцять', 'дев`ятнадцять','двадцять','тридцять','сорок','п`ятдесят', 'шiстдесят','сiмдесят','вiсiмдесят','дев`яносто'); sot : array[1..9] of string = ('сто','двiстi','триста','чотириста','п`ятсот', 'шiстсот','сiмсот','вiсiмсот','дев`ятсот'); tis1 : array[1..4] of string = ('тисяча','мiлiон' ,'мiлiард' ,'трилiон' ); tis2 : array[1..4] of string = ('тисяч' ,'мiлiонiв','мiлiардiв','трилiонiв'); tis3 : array[1..4] of string = ('тисячi','мiлiона' ,'мiлiарда' ,'трилiона' );} ed1 : array[1..9] of string = ('одна','две','три','четыре','пять','шесть','семь','восемь','девять'); ed2 : array[1..2] of string = ('одна','две'); des : array[1..18] of string = ('десять','одиннадцать','двенадцать','тринадцать','четырнадцать', 'пятнадцать','шестнадцать','семнадцать','восемнадцать', 'девятнадцать','двадцать','тридцать','сорок','пятьдесят', 'шестьдесят','семдесят','восемдесят','девяносто'); sot : array[1..9] of string = ('сто','двести','триста','четыреста','пятьсот', 'шестьсот','семсот','восемсот','девятсот'); tis1 : array[1..4] of string = ('тысяча','милион' ,'милиард' ,'трилион' ); tis2 : array[1..4] of string = ('тысяч' ,'милионов','милиардов','трилионов'); tis3 : array[1..4] of string = ('тысячи','милиона' ,'милиарда' ,'трилиона' ); {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} function _3toScript(n : Word; male : Boolean) : String; var _1, _2, _3 : Word; begin Result:= ''; if n = 0 then begin Result:= ' '; exit; end; _1:= n div 100; if _1 <> 0 then Result:= sot[_1]+' '; _2:= (n mod 100) div 10; if _2 >= 2 then Result:= Result+des[9+_2]+' ' else if _2 = 1 then begin _2:= n mod 100; Result:= Result+des[_2-9]+' '; exit; end; _3:= (n mod 100) mod 10; if _3 = 0 then exit; if (_3 <= 2) and not male then Result:= Result+ed2[_3]+' ' else Result:= Result+ed1[_3]+' '; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} var Male : Boolean; tmp, LastDig, _2dig : Word; Count : Byte; Str : String; TmpInt:String; SavTmp: Double; begin TmpInt:=IntTostr(Trunc(n)); SavTmp:=n; n:= Int(n); Result:= ''; Str:= ''; Count:= 0; while n > 0.1 do begin Inc(Count); if Count = 2 then Male:= False else Male:= True; tmp:= Round(Frac(n/1000)*1000); n:= Int(n/1000); LastDig:= tmp mod 10; _2dig:= tmp mod 100; if Count >= 2 then if (_2dig >= 11) and (_2dig <= 19) then Str:= tis2[Count-1] else if LastDig = 1 then Str:= tis1[Count-1] else if (LastDig >= 2) and (LastDig <= 4) then Str:= tis3[Count-1] else Str:= tis2[Count-1]; Result:= _3toScript(tmp, Male)+Str+' '+Result; end; if TmpInt = '0' then Result := 'ноль '; Result := Result+'грн.'; Result[1] := AnsiUpperCase(Result[1])[1]; Result := Result + ' ' + FormatFloat('00', Round(Frac(SavTmp)*100 ))+' коп.'; end; function WeightToText(n: Double): string; const ed1 : array[1..9] of string = ('один','два','три','чотири','п`ять','шiсть','сiм','вiсiм','дев`ять'); ed2 : array[1..2] of string = ('один','два'); des : array[1..18] of string = ('десять','одиннадцять','дванадцять','тринадцять','чотирнадцять', 'п`ятнадцять','шiстнадцять','сiмнадцять','вiсiмнадцять', 'дев`ятнадцять','двадцять','тридцять','сорок','п`ятдесят', 'шiстдесят','сiмдесят','вiсiмдесят','дев`яносто'); sot : array[1..9] of string = ('сто','двiстi','триста','чотириста','п`ятсот', 'шiстсот','сiмсот','вiсiмсот','дев`ятсот'); tis1 : array[1..4] of string = ('тисяча','мiлiон' ,'мiлiард' ,'трилiон' ); tis2 : array[1..4] of string = ('тисяч' ,'мiлiонiв','мiлiардiв','трилiонiв'); tis3 : array[1..4] of string = ('тисячi','мiлiона' ,'мiлiарда' ,'трилiона' ); {ed1 : array[1..9] of string = ('одна','две','три','четыре','пять','шесть','семь','восемь','девять'); ed2 : array[1..2] of string = ('одна','две'); des : array[1..18] of string = ('десять','одиннадцать','двенадцать','тринадцать','четырнадцать', 'пятнадцать','шестнадцать','семнадцать','восемнадцать', 'девятнадцать','двадцать','тридцать','сорок','пятьдесят', 'шестьдесят','семдесят','восемдесят','девяносто'); sot : array[1..9] of string = ('сто','двести','триста','четыреста','пятьсот', 'шестьсот','семсот','восемсот','девятсот'); tis1 : array[1..4] of string = ('тысяча','милион' ,'милиард' ,'трилион' ); tis2 : array[1..4] of string = ('тысяч' ,'милионов','милиардов','трилионов'); tis3 : array[1..4] of string = ('тысячи','милиона' ,'милиарда' ,'трилиона' ); } {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} function _3toScript(n : Word; male : Boolean) : String; var _1, _2, _3 : Word; begin Result:= ''; if n = 0 then begin Result:= ' '; exit; end; _1:= n div 100; if _1 <> 0 then Result:= sot[_1]+' '; _2:= (n mod 100) div 10; if _2 >= 2 then Result:= Result+des[9+_2]+' ' else if _2 = 1 then begin _2:= n mod 100; Result:= Result+des[_2-9]+' '; exit; end; _3:= (n mod 100) mod 10; if _3 = 0 then exit; if (_3 <= 2) and not male then Result:= Result+ed2[_3]+' ' else Result:= Result+ed1[_3]+' '; end; {+++++++++++++++++++++++++++++++++++++++++++++++++++++++} var Male : Boolean; tmp, LastDig, _2dig : Word; Count : Byte; Str : String; TmpInt:String; SavTmp: Double; begin TmpInt:=IntTostr(Trunc(n)); SavTmp:=n; n:= Int(n); Result:= ''; Str:= ''; Count:= 0; while n > 0.1 do begin Inc(Count); if Count = 2 then Male:= False else Male:= True; tmp:= Round(Frac(n/1000)*1000); n:= Int(n/1000); LastDig:= tmp mod 10; _2dig:= tmp mod 100; if Count >= 2 then if (_2dig >= 11) and (_2dig <= 19) then Str:= tis2[Count-1] else if LastDig = 1 then Str:= tis1[Count-1] else if (LastDig >= 2) and (LastDig <= 4) then Str:= tis3[Count-1] else Str:= tis2[Count-1]; Result:= _3toScript(tmp, Male)+Str+' '+Result; end; if TmpInt = '0' then Result := 'ноль '; Result := Result+'кг.'; Result[1] := AnsiUpperCase(Result[1])[1]; Result := Result + ' ' + FormatFloat('000', Round(Frac(SavTmp)*1000 ))+' гр.'; end; function SummaCurToTextRu(n: Double; curr:string): string; const m1: array [1..9] of string =('один ','два ','три ','четыре ','пять ','шесть ','семь ','восемь ','девять '); const f1: array [1..9] of string =('одна ','две ','три ','четыре ','пять ','шесть ','семь ','восемь ','девять '); const n10: array [1..9] of string =('десять ','двадцать ','тридцать ','сорок ','пятьдесят ','шестьдесят ', 'семьдесят ','восемьдесят ','девяносто '); const first10: array [11..19] of string =('одиннадцать ','двенадцать ','тринадцать ','четырнадцать ','пятнадцать ', 'шестнадцать ','семнадцать ','восемнадцать ','девятнадцать '); const n100: array [1..9] of string = ('сто ','двести ','триста ', 'четыреста ','пятьсот ','шестьсот ','семьсот ', 'восемьсот ','девятьсот '); const kop: array [1..3] of string = ('копейка','копейки','копеек'); rub: array [1..3] of string = ('рубль ','рубля ','рублей '); tsd: array [1..3] of string = ('тысяча ','тысячи ','тысяч '); mln: array [1..3] of string = ('миллион ','миллиона ','миллионов '); mrd: array [1..3] of string = ('миллиapд ','миллиаpдa ','миллиapдoв '); trl: array [1..3] of string = ('триллион ','триллионa ','триллионoв '); cnt: array [1..3] of string = ('тысяча ','тысячи ','тысяч '); const cent: array [1..3] of string = ('цент','цента','центов'); doll: array [1..3] of string = ('доллар ','доллара ','долларов '); {-----------------------------------------------------------------------------} function Triada(I,n:Integer;k:boolean;usd:boolean):string; var a,gender,sfx:integer; begin Result:=''; sfx:=3; if n=2 then gender:=0 else gender:=1; a:= I div 100; if (a>0) then begin Result:=Result+n100[a]; I:=I-a*100; end; if (I>19) then begin a:= I div 10; if (a>0) then begin Result:=Result+n10[a]; I:=I-a*10; if I>0 then begin if k then gender:=0; if gender=1 then Result:=Result+m1[I] else Result:=Result+f1[I]; case I of 1: sfx:=1; 2..4: sfx:=2; 5..9: sfx:=3; end; end; end; end else begin case I of 1:begin if k then gender:=0; if gender=1 then Result:=Result+m1[I] else Result:=Result+f1[I]; sfx:=1; end; 2..4:begin if k then gender:=0; if gender=1 then Result:=Result+m1[I] else Result:=Result+f1[I]; sfx:=2; end; 5..9:begin if k then gender:=0; if gender=1 then Result:=Result+m1[I] else Result:=Result+f1[I]; sfx:=3; end; 10:begin Result:=Result+n10[1]; sfx:=3; end; 11..19:begin Result:=Result+first10[I]; sfx:=3; end; end; end; case n of 1: if not k then if usd then result:=result+doll[sfx] else Result:=Result+rub[sfx] else if usd then result:=result+cent[sfx] else Result:=Result+kop[sfx]; 2: if not k then Result:=Result+tsd[sfx] else if usd then result:=result+cent[sfx] else Result:=Result+kop[sfx]; 3: if not k then Result:=Result+mln[sfx] else if usd then result:=result+cent[sfx] else Result:=Result+kop[sfx]; 4: if not k then Result:=Result+mrd[sfx] else if usd then result:=result+cent[sfx] else Result:=Result+kop[sfx]; 5: if not k then Result:=Result+trl[sfx] else if usd then result:=result+cent[sfx] else Result:=Result+kop[sfx]; end; end; // function Triada(I,n:Integer;k:boolean;usd:boolean):string; function TriadaK(I:integer;kpk:boolean;usd:boolean):string; var sfx,H:integer; begin if kpk then begin Result:=''; sfx:=3; H:=(I mod 10); case H of 1: sfx:=1; 2..4: sfx:=2; end; if (I in [11..19]) then sfx:=3; if usd then begin if I<10 then Result:='0'+IntToStr(I)+' '+cent[sfx] else Result:=IntToStr(I)+' '+cent[sfx]; end else begin if I<10 then Result:='0'+IntToStr(I)+' '+kop[sfx] else Result:=IntToStr(I)+' '+kop[sfx]; end; end else begin if i=0 then if usd then result:='00 центов' else result:='00 копеек' else result:=triada(i,1,true,usd); end; end; // function TriadaK(I:integer;kpk:boolean;usd:boolean):string; function MoneyToString(S:Currency; kpk:boolean; usd:boolean):string; var I,H:LongInt; V:string; f,l:String; s1:Currency; dH: Currency; begin V:=''; s1:=S; dH:=1e12; I:=Trunc(S/dH); if (I>0) then begin V:=Triada(I,5,false,usd); S:=S-Trunc(S/dH)*dH; end; dH:=1000000000; I:=Trunc(S/dH); if (I>0) then begin V:=V+Triada(I,4,false,usd); S:=S-Trunc(S/dH)*dH; end; H:=1000000; I:=Trunc(S/H); if (I>0) then begin V:=V+Triada(I,3,false,usd); S:=S-Trunc(S/H)*H; end; H:=1000; I:=Trunc(S/H); if (I>0) then begin V:=V+Triada(I,2,false,usd); S:=S-Trunc(S/H)*H; end; H:=1; I:=Trunc(S/H); if (I>0) then begin V:=V+Triada(I,1,false,usd); S:=S-Trunc(S/H)*H; end else if usd then v:=v+doll[3] else V:=V+rub[3]; I:=Trunc(S*100); V:=V+TriadaK(I,kpk,usd); if s1 < 1 then V:='ноль '+V; f:=AnsiUpperCase(Copy(V,1,1)); l:=Copy(V,2,256); V:=f+l; Result:=V; end; // function MoneyToString(S:Currency; kpk:boolean; usd:boolean):string; {------------------------------------------------------------------------------} begin if Curr = 'USD' then Result := MoneyToString(n, true, true) else if (Curr = 'RUR') OR (Curr = 'RUB') then Result := MoneyToString(n, true, false) else if Curr = 'EUR' then Result := CurrencyToStr(n, EUR, false) else if Curr = 'UAH' then Result := SummaToTextRu(n); end; { TFunctions } constructor TFunctions.Create; begin inherited Create(AScript); with AScript do begin AddMethod('function SummaToText(Money: Double): String', CallMethod, 'Мои функции', 'Сумма прописью укр'); AddMethod('function SummaToTextRu(Money: Double): String', CallMethod, 'Мои функции', 'Сумма прописью рус'); AddMethod('function SummaCurToTextRu(Money: Double, Curr: String): String', CallMethod, 'Мои функции', 'Сумма вал прописью рус'); AddMethod('function NumToStr(N: Int64; FormatFlags: LongInt): String', CallMethod, 'Мои функции', 'Число прописью укр'); AddMethod('function WeightToText(Money: Double): String', CallMethod, 'Мои функции', 'Вес прописью укр'); end; end; function TFunctions.CallMethod(Instance: TObject; ClassType: TClass; const MethodName: String; var Params: Variant): Variant; begin if MethodName = 'SUMMATOTEXT' then Result := SummaToText(Params[0]); if MethodName = 'SUMMATOTEXTRU' then Result := SummaToTextRu(Params[0]); if MethodName = 'SUMMACURTOTEXTRU' then Result := SummaCurToTextRu(Params[0], Params[1]); if MethodName = 'NUMTOSTR' then Result := NumToStr(Params[0], Params[1]); if MethodName = 'WEIGHTTOTEXT' then Result := WEIGHTToText(Params[0]); end; initialization fsRTTIModules.Add(TFunctions); 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 Abbrevia * * The Initial Developer of the Original Code is * Robert Love * * Portions created by the Initial Developer are Copyright (C) 1997-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) unit AbUnzperTests; {$I AbDefine.inc} { The following define is unit specific it will build the files used in the tests here. Due to the potential problems of compress having a problem and uncompress not, I did not want to confuse the tests by having these created every time, but only when needed under a stable code base... Otherwise it would more difficult to determine which side the problem was on! WATCH out for hardcoding of paths, if you use this compiler define} {.$DEFINE BUILDTESTS} interface uses Windows, // Needed for CopyFile could be replaced if needed on Linux TestFrameWork, abTestFrameWork, AbUnzper, SysUtils, Classes, abMeter, AbZipTyp, AbDfBase, abExcept; type TAbUnZipperTests = class(TabCompTestCase) private Component : TAbUnZipper; protected procedure SetUp; override; procedure TearDown; override; procedure TestUserAbortProgress(Sender : TObject; Progress : Byte; var Abort : Boolean); published procedure TestDefaultStreaming; procedure TestComponentLinks; procedure TestBasicUnzip; procedure TestBasicUnGzip; procedure TestBasicUnGzipTar; procedure TestUserAbort; procedure TestWinZipOutput; procedure TestGZipDecompress; procedure TestZeroByteZipFile; procedure TestIncompleteZipFile; procedure TestArchiveNotFound; procedure TestZipCopiedFromFloppy; procedure DecompressSimplePW; procedure CheckBadPWOverwrite; procedure TestLocale1; procedure TestLocale2; procedure TestLocale3; procedure TestLocale4; {$IFDEF BUILDTESTS} procedure CreateTestFiles; {$ENDIF} end; implementation {$IFDEF BUILDTESTS} uses AbZipper; {$ENDIF} { TAbUnZipperTests } procedure TAbUnZipperTests.CheckBadPWOverwrite; var Ms : TMemoryStream; Fs : TFileStream; TestFile : String; Buffer,Buffer1 : Array[0..20] of Char; begin // 698162 Failed unzipping of password protected files clobbers original TestFile := TestTempDir + 'MPL-1_1.TXT'; if FileExists(TestFile) then DeleteFile(TestFile); // Create Dummy file to test with. FillChar(Buffer,SizeOf(Buffer),#0); Buffer := 'THIS IS A TEST'; Fs := TFileStream.Create(TestFile,fmCreate); FS.Write(Buffer,SizeOf(Buffer)); // Write something to file FS.Free; // Try to extract with wrong password Component.FileName := TestFileDir + 'simplepw.zip'; Component.Password := 'wrong password'; Component.BaseDirectory := TestTempDir; try Component.ExtractFiles('*.*'); // MPL-1_1.TXT except on EAbInflatePasswordError do // nothing Expected end; CheckFileExists(TestFile); // Test to make sure file matches dummy original Fs := TFileStream.Create(TestFile,fmOpenRead); try FS.Read(Buffer1,SizeOf(Buffer1)); CompareMem(@Buffer[0],@Buffer[1],SizeOf(Buffer)); finally Fs.free; DeleteFile(TestFile); end; end; {$IFDEF BUILDTESTS} procedure TAbUnZipperTests.CreateTestFiles; var Zip : TAbZipper; begin //Cheap and easy way to keep the code around that I use to build the tests //Hard Coded to Abbrevia path to keep things easy as this is one time only code Zip := TAbZipper.Create(nil); try Zip.FileName := TestFileDir + 'MPL.ZIP'; Zip.AddFiles('C:\TP\ABBREVIA\MPL-1_1.TXT',faAnyFile); Zip.Save; finally Zip.Free; end; Zip := TAbZipper.Create(nil); try Zip.FileName := TestFileDir + 'MPL.GZ'; Zip.AddFiles('C:\TP\ABBREVIA\MPL-1_1.TXT',faAnyFile); Zip.Save; finally Zip.Free; end; Zip := TAbZipper.Create(nil); try Zip.FileName := TestFileDir + 'MPL.TGZ'; Zip.AddFiles('C:\TP\ABBREVIA\MPL-1_1.TXT',faAnyFile); Zip.Save; finally Zip.Free; end; end; {$ENDIF} procedure TAbUnZipperTests.DecompressSimplePW; var Ms : TMemoryStream; Fs : TFileStream; begin Ms := TMemoryStream.create; try Component.FileName := TestFileDir + 'simplepw.zip'; Component.Password := 'simple'; Component.ExtractOptions := []; Component.ExtractToStream(Component.Items[0].FileName,MS); Fs := TFileStream.Create(TestFileDir + 'MPL-1_1.TXT',fmOpenRead); try CheckStreamMatch(MS,FS,'simplepw.zip MPL-1_1.TXT does not match original'); finally Fs.free; end; finally ms.free; end; end; procedure TAbUnZipperTests.SetUp; begin inherited; Component := TAbUnzipper.Create(TestForm); end; procedure TAbUnZipperTests.TearDown; begin inherited; end; procedure TAbUnZipperTests.TestArchiveNotFound; begin ExpectedException := EAbFileNotFound; // Delete File if it exists if FileExists(TestTempDir + 'nonexist.zip') then DeleteFile(TestTempDir + 'nonexist.zip'); // Try to set the filename to the open byte file. Component.FileName := TestTempDir + 'nonexist.zip'; end; procedure TAbUnZipperTests.TestBasicUnGzip; var TestFileName : string; begin TestFileName := TestTempDir + 'MPL-1_1.txt'; if FileExists(TestFileName) then DeleteFile(TestFileName); Component.BaseDirectory := TestTempDir; Component.FileName := TestFileDir + 'mpl.gz'; Component.ExtractFiles('*.*'); Check(FileExists(TestFileName),'Unzip Test File not Found'); DeleteFile(TestFileName) end; procedure TAbUnZipperTests.TestBasicUnGzipTar; var TestFileName : string; begin TestFileName := TestTempDir + 'MPL-1_1.txt'; if FileExists(TestFileName) then DeleteFile(TestFileName); Component.BaseDirectory := TestTempDir; Component.FileName := TestFileDir + 'mpl.tgz'; Component.ExtractFiles('*.*'); Check(FileExists(TestFileName),'Unzip Test File not Found'); DeleteFile(TestFileName) end; procedure TAbUnZipperTests.TestBasicUnzip; var TestFileName : string; begin TestFileName := TestTempDir + 'MPL-1_1.txt'; if FileExists(TestFileName) then DeleteFile(TestFileName); Component.BaseDirectory := TestTempDir; Component.FileName := TestFileDir + 'mpl.zip'; Component.ExtractFiles('*.*'); Check(FileExists(TestFileName),'Unzip Test File not Found'); DeleteFile(TestFileName); end; procedure TAbUnZipperTests.TestComponentLinks; var MLink1,MLink2 : TAbVCLMeterLink; begin MLink1 := TAbVCLMeterLink.Create(TestForm); MLink2 := TAbVCLMeterLink.Create(TestForm); Component.ArchiveProgressMeter := MLink1; Component.ItemProgressMeter := MLink2; MLink1.Free; MLink2.Free; Check(Component.ArchiveProgressMeter = nil,'Notification does not work for TabUnZipper.ArchiveProgressMeter'); Check(Component.ItemProgressMeter = nil,'Notification does not work for TabUnZipper.ItemProgressMeter'); end; procedure TAbUnZipperTests.TestDefaultStreaming; var CompStr : STring; CompTest : TAbUnZipper; begin RegisterClass(TAbUnZipper); CompStr := StreamComponent(Component); CompTest := (UnStreamComponent(CompStr) as TAbUnZipper); CompareComponentProps(Component,CompTest); UnRegisterClass(TAbUnZipper); end; procedure TAbUnZipperTests.TestGZipDecompress; var fs,fs2 : TFileStream; begin fs := TFileStream.Create(TestFileDir + 'dataland.txt',fmOpenRead); try // [ 822243 ] GZip decompress problem component.FileName := TestFileDir + 'download[1].datalandsoftware.com-Aug-2003.gz'; Component.BaseDirectory:= TestTempDir; {$IFDEF UseLogging} Component.LogFile := TestTempDir + 'dataland.log'; Component.Logging := True; {$ENDIF} Component.ExtractAt(0,TestTempDir + 'dataland.txt'); fs2 := TFileStream.Create(TestTempDir + 'dataland.txt',fmOpenRead); try Check(fs2.Size > 0,'Extracted File is 0 bytes in size'); CheckStreamMatch(fs,fs2,'Extracted File does not match original file'); finally fs2.free; end; finally fs.free; end; end; procedure TAbUnZipperTests.TestIncompleteZipFile; var FS : TFileStream; begin // Since file only contains initial sig and not Central Directory Tail Struct // It should not be recogonized. ExpectedException := EAbUnhandledType; // Delete File if it exists if FileExists(TestTempDir + 'dummy.zip') then DeleteFile(TestTempDir + 'dummy.zip'); // Create Zero Byte File FS := TFileStream.Create(TestTempDir + 'dummy.zip',fmCreate); FS.Write(Ab_ZipLocalFileHeaderSignature,sizeof(Ab_ZipLocalFileHeaderSignature)); FS.Free; // Try to set the filename to the open byte file. Component.FileName := TestTempDir + 'zerobyte.zip'; end; procedure TAbUnZipperTests.TestLocale1; var ltestdir, ltestzip, ltestfile : string; begin // This test verifies use Ability to use Charactes such as ãëíõú // In the Archive Directory Name // Create New Directory //236 changes into a ? on my machine in the delphi editor // so I thought it would be a good character to test with ltestdir := TestTempDir + chr(236) + 'ãëíõú\'; ForceDirectories(ltestDir); // copy fresh MPL.ZIP to locale1.zip in the new directory ltestFile := lTestdir + 'locale1.zip'; if FileExists(lTestFile) then DeleteFile(lTestFile); ltestzip := TestFileDir + 'MPL.ZIP'; CopyFile(pchar(ltestzip),pchar(ltestFile),false); Component.FileName := lTestFile; Component.BaseDirectory := TestTempDir; // Delete File to be extract if it exists if FileExists(TestTempDir + 'MPL-1_1.txt') then DeleteFile(TestTempDir + 'MPL-1_1.txt'); Component.ExtractFiles('*.*'); Component.CloseArchive; CheckFileExists(TestTempDir + 'MPL-1_1.txt'); end; procedure TAbUnZipperTests.TestLocale2; var ltestdir, ltestzip, ltestfile : string; begin // This test verifies use Ability to use Charactes such as ãëíõú // In the Base Directory Name // Create New Directory //236 changes into a ? on my machine in the delphi editor // so I thought it would be a good character to test with ltestdir := TestTempDir + chr(236) + 'ãëíõú\'; ForceDirectories(ltestDir); ltestFile := TestFileDir + 'MPL.ZIP'; Component.FileName := lTestFile; Component.BaseDirectory := lTestDir; // Delete File to be extract if it exists if FileExists(lTestDir + 'MPL-1_1.txt') then DeleteFile(lTestDir + 'MPL-1_1.txt'); Component.ExtractFiles('*.*'); Component.CloseArchive; CheckFileExists(lTestDir + 'MPL-1_1.txt'); end; procedure TAbUnZipperTests.TestLocale3; var ltestzip, ltestfile : string; begin // This test verifies use Ability to use Charactes such as ãëíõú // In the Archive File Name // copy fresh MPL.ZIP to localeãëíõú3.zip in the temp directory ltestFile := TestTempDir + 'localeãëíõú3.zip'; if FileExists(lTestFile) then DeleteFile(lTestFile); ltestzip := TestFileDir + 'MPL.ZIP'; CopyFile(pchar(ltestzip),pchar(ltestFile),false); Component.FileName := lTestFile; Component.BaseDirectory := TestTempDir; // Delete File to be extract if it exists if FileExists(TestTempDir + 'MPL-1_1.txt') then DeleteFile(TestTempDir + 'MPL-1_1.txt'); Component.ExtractFiles('*.*'); Component.CloseArchive; CheckFileExists(TestTempDir + 'MPL-1_1.txt'); end; procedure TAbUnZipperTests.TestLocale4; var ltestzip, ltestfile : string; begin // This test verifies use Ability to use Charactes such as ãëíõú // In the Files contained in the Archive. Component.FileName := TestFileDir + 'LocaleTests.zip'; Component.BaseDirectory := TestTempDir; // Delete Files in Temp Directory if they exist if FileExists(TestTempDir + 'testãëíõú1.lc4') then DeleteFile(TestTempDir + 'testãëíõú1.lc4'); if FileExists(TestTempDir + 'testãëíõú2.lc4') then DeleteFile(TestTempDir + 'testãëíõú2.lc4'); if FileExists(TestTempDir + 'testãëíõú3.lc4') then DeleteFile(TestTempDir + 'testãëíõú3.lc4'); Component.ExtractFiles('*.lc4'); Component.CloseArchive; CheckFileExists(TestTempDir + 'testãëíõú1.lc4'); CheckFileExists(TestTempDir + 'testãëíõú2.lc4'); CheckFileExists(TestTempDir + 'testãëíõú3.lc4'); end; procedure TAbUnZipperTests.TestUserAbort; var FUnZipper : TAbUnZipper; begin // This test needs to create and free the component as the problem is in the FREE // Inspired by, but not testing for the same thing as SF.Net Tracker ID [ 785269 ] // Expecting this exception don't fail if it occurs. ExpectedException := EAbUserAbort; FUnZipper := TAbUnZipper.Create(Nil); TRY FUnZipper.BaseDirectory := TestTempDir; FUnZipper.OnArchiveProgress:=TestUserAbortProgress; FUnZipper.FileName:=TestFileDir + 'MPL.ZIP'; FUnZipper.ExtractFiles('*.*'); Finally FUnZipper.Free; end; end; procedure TAbUnZipperTests.TestUserAbortProgress(Sender: TObject; Progress: Byte; var Abort: Boolean); begin Abort := (Progress > 25); end; procedure TAbUnZipperTests.TestWinZipOutput; begin // This compares a known problem archive with the results that were extracted from // WinZip. Component.BaseDirectory := TestTempDir; Component.Filename := TestFileDir + '20030328.ZIP'; Component.ExtractFiles('*.*'); CheckDirMatch(TestFileDir + '20030328\',TestTempDir,true); end; procedure TAbUnZipperTests.TestZeroByteZipFile; var FS : TFileStream; begin ExpectedException := EAbBadStream; // Delete File if it exists if FileExists(TestTempDir + 'zerobyte.zip') then DeleteFile(TestTempDir + 'zerobyte.zip'); // Create Zero Byte File FS := TFileStream.Create(TestTempDir + 'zerobyte.zip',fmCreate); FS.Free; // Try to set the filename to the open byte file. Component.FileName := TestTempDir + 'zerobyte.zip'; end; procedure TAbUnZipperTests.TestZipCopiedFromFloppy; begin //[ 858945 ] copy of File saved to floppy cannot be opened // Error of File Not Found appears if it fails. Component.FileName := TestFileDir + 'cpFromFloppy.zip'; Component.BaseDirectory := TestTempDir; ChDir(TestTempDir); Component.ExtractFiles('*.*'); end; initialization TestFramework.RegisterTest('Abbrevia.Component Level Test Suite', TAbUnZipperTests.Suite); end.
unit dhtBootStatic; { Bootstrap the dht from set of static nodes from file. } INTERFACE IMPLEMENTATION uses NetAddr,ServerLoop,DHT,SysUtils; type t=object procedure Boot; procedure BootCmdline; end; procedure t.BootCmdline; var addr:tNetAddr; var oi:word; var cnt:word; const opt='-boot'; begin oi:=OptIndex(opt); if oi>0 then begin cnt:=OptParamCount(oi); assert(cnt>=1,opt+'(addr+)'); for oi:=oi+1 to cnt do begin addr.FromString(paramstr(oi+1)); DHT.NodeBootstrap(addr); end; end; end; procedure t.Boot; var bs:TextFile; const bsfn='bootstrap.txt'; var line:string; var addr:tNetAddr; begin BootCmdLine; assign(bs,bsfn); try reset(bs); except writeln('BootStatic: Error opening file '+bsfn); exit; end; try while not eof(bs) do begin readln(bs,line); try addr.FromString(line); except on eConvertError do begin writeln('BootStatic: ConvertError ',line,' to tNetAddr'); continue; end end; DHT.NodeBootstrap(addr); end; finally close(bs); end; end; var o:t; BEGIN Shedule(700,@o.boot); END.
unit Consttipos; interface uses Sysutils; type TOperacao = (opIncluir, opAlterar, opExcluir, opVisualizar); const Meses : Array[1..12] of String = ( 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro' ) ; // //Servidor Mysql do Acadesc // _Hostname = 'mysql.acadesc.com.br'; // _Username = 'acadesc'; // _Password = 'root1234'; // Campos que podem ser usados nos critérios de aprovação MAXCAMPOSCRITERIO = 5 ; cpNotaPeriodo = 0 ; cpMediaBimestres = 1 ; cpMediaRecuperacao = 2 ; cpFreqPeriodo = 3 ; cpFreqTotal = 4 ; cpMediaPrimeiroExame = 5 ; // // Para o Espião - Constantes que representam as operações que podem ser realizadas. // oper_Inclusao = 'Inclusão'; // oper_Alteracao = 'Alteração'; // oper_visualizacao = 'Visualização'; // oper_Exclusao = 'Exclusão'; // oper_Listagem = 'Listagem'; // oper_Logar = 'Logar no sistema'; // oper_Processar = 'Processar'; // oper_abertura = 'Abertura do item'; // oper_fechamento = 'Fechamento de item'; // oper_visualizarelatorio = 'Visualiza Relatórios'; // oper_imprimerelatorio = 'Imprime Relatórios'; // Oper_excel = 'Exportação para o Excel'; // Oper_backup = 'Geração de Backup'; // Oper_exportar = 'Exportação'; // // //Telas para auditoria // Tela_Login = 'Logon do sistema' ; // Tela_Auditoria = 'Auditoria' ; // Tela_Alunos = 'Cadastro de Alunos' ; // Tela_Grupos = 'Cadastro de Grupos' ; // // /////////////////////////////////// 24/11 ///////////////////////////////// // /////////////////////////////////// 24/11 ///////////////////////////////// // // Tela_Usuarios = 'Cadastro de Usuários' ; // Tela_Cursos = 'Cadastro de Cursos' ; // Tela_Classes = 'Cadastro de Classes' ; // Tela_Turmas = 'Cadastro de Turmas' ; // Tela_Numera = 'Tela de Numerar Classes' ; // Tela_Disciplina = 'Cadastro de Disciplinas' ; // Tela_NotasFaltas = 'Notas e Faltas' ; // Tela_ConsultaBoletim = 'Consulta de Boletim' ; // Tela_ImprimeBoletim = 'Impressão' ; // Tela_ConsultaAlunos = 'Consulta de Alunos' ; // Tela_Quadro = 'Quadro de Alunos' ; // Tela_qListagemAlfabetica = 'Listagem Alfabética de Alunos' ; // Tela_qNListagemAlfabetica = 'Listagem Alfabética de Alunos - Numérica' ; // Tela_qQuadro = 'Quadro de Alunos - Analítico' ; // Tela_qSQuadro = 'Quadro de Alunos - Sintético' ; // Tela_qfmIdadeAnalitico = 'Lista de Idade dos Alunos - Analítico' ; // Tela_qfmIdadeSintetico = 'Lista de Idade dos Alunos - Sintético' ; // // // Já modificados, Falta preencher caption // Tela_qfmPorIdade = 'Listagem de alunos por idade' ; // Tela_qfmListagemGeral = 'Listagem geral de alunos' ; // Tela_qfmTransferidos = 'Alunos Por Situação' ; // Tela_qfmLivroMatricula = 'Livro Matrícula' ; // Tela_qfmAniversariantes = 'Relatório de aniversariantes' ; // Tela_qfmAnoNascimento = 'Listagem de alunos por ano de nascimento' ; // Tela_qfmsuplementares = 'Listagem de alunos suplementares' ; // Tela_qfmPorAno = 'Listagem de alunos por ano' ; // Tela_qfmTermoAbertura = 'Livro de Mat. - Termo de abertura' ; // Tela_qfmTermoFechamento = 'Livro de mat. - termo de encerramento' ; // Tela_qfmResponsavel = 'Relatório de Responsáveis' ; // Tela_qfmNotasFaltasFR = 'Listagem de notas e faltas' ; // Tela_FqfmNotasFaltasFR = 'Listagem de faltas' ; // Tela_NqfmNotasFaltasFR = 'Listagem de notas' ; // Tela_fmGeraCSV = 'Geração de lista de alunos' ; // Tela_fmCadCriterios = 'Cadastro de Critérios de aprovação' ; // Tela_qfmEstatistica = 'Relatório de Estatística de notas' ; // Tela_qfmMelhoresAlunos = 'Listagem de Melhores Alunos' ; // Tela_qfmAprovados = 'Listagem de alunos por situação' ; // Tela_fmCadNotasFaltas = 'Cadastro de notas e faltas' ; // Tela_qfmAtaResultados = 'Ata de resultados finais' ; // Tela_qfmNotasMinimas = 'Listagem de Notas Mínimas' ; // Tela_fmCadAnoLetivo = 'Cadastro de anos letivos' ; // Tela_fmCenso = 'Meninos & Meninas' ; // Tela_fmPassagemAno = 'Passagem de ano' ; // Tela_fmCadDispensa = 'Dispensa de componente curricular' ; // Tela_fmCadConselho = 'Conselho de classe' ; // Tela_qfmNotasFaltas = 'Listagem de Atrasos' ; // Tela_qfmGraficoAproveitamento = 'Gráfico de aproveitamento' ; // Tela_qfmGraficoAlunoDisc = 'Gráfico de alunos por Componente curricular' ; // Tela_qfmDisciplinas = 'Relatório de Disciplinas' ; // Tela_fmCadAtrasos = 'Cadastro de atrasos' ; // Tela_fmCadObserv = 'Cadastro de Observações pedagógicas' ; // Tela_qfmCarometro = 'Carômetro' ; // // Tela_qfmAcumuloNotasFaltas = 'Listagem de Acúmulo de notas' ; // Tela_FqfmAcumuloNotasFaltas = 'Listagem de Acúmulo de faltas' ; // Tela_qfmEntregaCarnes = 'Lista de assinaturas' ; // Tela_qfmAtaConselho = 'Ata de conselho' ; // Tela_qfmCarteirinha = 'Impressão de Carteirinha' ; // Tela_fmCadAbono = 'Cadastro de Abono de faltas' ; // Tela_fmTransferencia = 'Transferência de alunos' ; // Tela_fmDesfazerTransferencia = 'Desfazer transferência de alunos' ; // Tela_fmDigitaHistorico = 'Digitação Histórico' ; // Tela_fmImprimeHistorico = 'Imprimir Histórico' ; // Tela_fmAulasDadasAluno = 'Aulas dadas por Alunos' ; // // Tela_fmRegistrar = 'Registrar Software' ; // Tela_fmConfiguraMenus = 'Configurar Menus e Botões' ; // Tela_fmConfigModulos = 'Configuração de módulos' ; // Tela_qfmAtaQuartoBimestre = 'Ata do último período' ; // Tela_fmCadCandidatos = 'Cadastro de candidatos' ; // Tela_fmMontagem = 'Montagem de classe' ; // Tela_fmCadArredondamento = 'Cadastro de Tabelas de Arredondamento' ; // Tela_qfmRelAtrasos = 'Listagem de atrasos' ; // Tela_fmExportacao = 'Exportação de arquivos' ; // // Tela_qfmNotasPendentes = 'Listagem de Notas Pendentes' ; // Tela_qfmRecuperacao = 'Relatório de recuperação por período' ; // Tela_qfmNotasGeral = 'Listagem de notas geral' ; // Tela_fmCapitalizarAlunos = 'Capitular nomes de Alunos' ; // Tela_fmMsgTesouraria = 'Mensagem na Tesouraria' ; // Tela_qfmAniversarioResponsaveis = 'Relatório de Aniversariantes por Responsáveis' ; // Tela_qfmQuadroPrevisao = 'Previsão de Alunos e Candidatos' ; // Tela_fmGeraSenha = 'Gerar senha para alunos' ; // Tela_qfmSenhas = 'Relação de Senhas' ; // Tela_fmDocente = 'Cadastro Docente - Professores' ; // Tela_fmDocenteGeral = 'Grade de Horários'; // Tela_fmEspecializacao = 'Cadastro de Especialização' ; // Tela_qfmRelListaProf = 'Relatório de Ficha de Dados' ; // Tela_qfmAniversario = 'Relatório de Aniversariantes' ; // Tela_qfmEspecializacao = 'Listagem de Especializações' ; // Tela_qfmRelEditora = 'Listagem para Editoras' ; // Tela_qfmDeclaracao = 'Declaração' ; // Tela_fmexplibwin = 'Exportação para LibWin' ; // Tela_fmCadDocumentos = 'Cadastro de Documentos' ; // Tela_fmDependentes = 'Cadastro de Dependentes'; // Tela_fmCadVeiculos = 'Cadastro de Veículos de comunicação'; // Tela_fmDocProfessores = 'Cadastro de Documentos de professores'; // Tela_fmParametros = 'Parâmetros do sistema'; // Tela_fmLancarNotas = 'Lançar Notas'; // Tela_qfmControleAtrasos = 'Controle de atrasos'; // // // Para as Telas Ref. ao Modulo Financeiro utilizar o simbolo de "@" antes do nome. // Tela_fmCadCartas = '@Cadastro de Cartas de Cobrança'; //01 // Tela_fmCadJuros = '@Cadastro de Juros e Multa'; //02 // Tela_fmCadContas = '@Cadastro de Contas'; //03 // Tela_fmCadFeriados = '@Cadastro de Feriados'; //04 // Tela_fmCadFamilias = '@Cadastro de Famílias'; //05 // Tela_fmArquivoMorto = '@Arquivo Morto'; //06 // Tela_fmConfigFinanc = '@Configurações Gerais'; //07 // Tela_fmCadEventos = '@Cadastro de Eventos'; //08 // Tela_fmCadTabPreco = '@Tabela de Preços'; //09 // // Tela_fmCadPlanos = '@Planos de Pagamento'; //10 // // //const // Telas_Financ : Array[1..8] of String = ( Tela_fmCadCartas,Tela_fmCadJuros,Tela_fmCadContas,Tela_fmCadFeriados,Tela_fmArquivoMorto,Tela_fmConfigFinanc,Tela_fmCadEventos,Tela_fmCadTabPreco);//,Tela_fmCadPlanos); // // //{Atenção! Para cada nova tela criada para o FINANCEIRO adcinar no array TelasFinanceiro // da funcao atualizatela() da auditoria. // Para as Telas Ref. ao Modulo Financeiro utilizar o simbolo de "@" antes do nome. // } // // // /////////////////////////////////// 24/11 ///////////////////////////////// // Situação do Aluno SIT_APROVADO = 'A'; SIT_CONSELHO = 'C'; // Aprovado por conselho SIT_RECUPERACAO = 'D'; // D de Dependencia - Sei que o termo só se aplica a // Faculdades, mas o R já está sendo utilizado no Reprovado SIT_REPROVADO = 'R'; SIT_DEPENDENCIA = 'P'; // P DE DP PARA DEPENDENCIA function DescSituacao_(Situacao : char) : String; function SituacaoPrioritaria(Sit1, Sit2 : char) : char; // Campos para configuração do Boletim const cmpLetivo = 0; cmpNomeAluno = 1; cmpTurno = 2; cmpCurso = 3; cmpTurma = 4; cmpNumero = 5; cmpBimestre = 6; cmpNomeDisc = 7; cmpNota = 7; // Cuidado, cmpNota está correto, apesar de estar repetido. A idéia é que cmpNota1 = 8; // cmpNota1 = cmpNota + 1, cmpNota2 = cmpNota + 2 e assim por diante. cmpNota2 = 9; // O mesmo vale para cmpFalta cmpNota3 = 10; cmpNota4 = 11; cmpMediaBim = 12; cmpSituacao = 13; cmpNotaRec = 14; cmpMediaRec = 15; cmpFalta = 15; // Aqui vale o mesmo comentário acima cmpFalta1 = 16; cmpFalta2 = 17; cmpFalta3 = 18; cmpFalta4 = 19; cmpTotFaltas = 20; cmpDiasAtraso = 21; cmpObservacoes = 22; MaxCampoBoletim = 22; DescCampoBoletim : array[0..MaxCampoBoletim] of String = ( 'Ano Letivo', 'Nome do Aluno', 'Turno', 'Curso', 'Turma e série', 'Número', 'Bimestre', 'Nome do componente curricular', 'Nota 1° Bimestre', 'Nota 2° Bimestre', 'Nota 3° Bimestre', 'Nota 4° Bimestre', 'Média dos Bimestres', 'Situação', 'Nota de Recuperação', 'Média Final', 'Falta 1° Bimestre', 'Falta 2° Bimestre', 'Falta 3° Bimestre', 'Falta 4° Bimestre', 'Total de faltas', 'Dias de Atraso', 'Observações' ); // Tipo de Disciplina no Histórico TP_COMUM = 'C'; TP_DIVERSIFICADA = 'D'; TP_OUTROS = 'O'; // Tipos de responsável TR_PAI = 0; TR_MAE = 1; TR_OUTRO = 2; TR_ALUNO = 3; ALFABETO = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; MSGEXCLUSAO = 'Deseja mesmo excluir esse registro?'; // Tipo de Atraso AT_NUMERO = 'N'; AT_MINUTOS = 'M'; // Tipos de Impressora IMP_DESKJET = 0; IMP_MATRICIAL = 1; IMP_NAO_IMPRIME = 2; // Tipo de boletim BOL_PADRAO = 0; BOL_MATRICIAL = 1; BOL_REC_BIMESTRAL = 2; BOL_REC_SEMESTRAL = 3; BOL_SEMESTRAL = 4; BOL_REC_TRIMESTRAL = 5; BOL_REC_SEMESTRAL2 = 6; BOL_REC_BIMESTRAL2 = 7; BOL_MEDIA_SEMESTRAL = 8; // Cursos com Código Fixo Ensino_Fundamental = '10'; Ensino_Medio = '20'; // Estado Civil dos pais - Cadastro de alunos EC_CASADOS = 0; EC_SOLTEIROS = 1; EC_SEPARADOS = 2; EC_PAI_VIUVO = 3; EC_MAE_VIUVA = 4; EC_AMBOS_FALECIDOS = 5; function DescEstadoCivil (ind : Integer) : String; { DescEstadoCivil : array[0..5] of String = ('Casados', 'Solteiros', 'Separados', 'Pai Viúvo', 'Mãe Viúva', 'Ambos falecidos');} const // Ordem de numeração de classes ORD_ALFABETICA = 0; ORD_SEXO = 1; ORD_SEXOF = 2; // Limite de alunos para versão Demo (Quando entrarem com usuário DEMO e // Senha DEMO LIMITE_ALUNOS_DEMO = 100; // Tipo de pagamento (Financeiro) pag_Matricula = 0; pag_Parcela = 1; pag_Evento = 2; pag_Reserva = 3; // Reserva de vaga pag_Renegociacao = 4; // Renegociação de dívida no jurídico pag_Vendas = 5; // Venda de produtos aos alunos pag_pagparcial = 6; // Restante de pagamento parcial // Tipo de Boleto bol_Familia = 0; // Boleto impresso por família bol_Aluno = 1; // Boleto impresso por aluno // Tipo de movimento de caixa mov_Boleto = 0; mov_Pagamento = 1; mov_Lancamento = 2; // Lançamento Manual mov_CPag = 3; // Conta Paga //Log tag_IgnorarLog = 8; // Tela usada para baixa manual frm_BaixaManual = 0; frm_BaixaPagamentos = 1; NEGRITO = 1; ITALICO = 2; SUBLINHADO = 4; RISCADO = 8; // Tipos de formato CNAB suportados cnabSemGeracao = 0; cnabBradesco = 1; cnabItau = 2; cnabTribanco = 3; Campo_Matricula = 'Matrícula'; Campo_Nome_do_aluno = 'Nome_do_aluno'; Campo_Responsavel_financeiro= 'Responsavel_financeiro'; Campo_Endereco = 'Endereço'; Campo_Bairro = 'Bairro'; Campo_Cidade = 'Cidade'; Campo_Estado = 'Estado'; Campo_CEP = 'CEP'; Campo_Valor_Devido = 'Valor_Devido'; Campo_N_de_parcelas = 'N_de_parcelas'; Campo_Extrato_de_Atraso = 'Extrato_de_Atraso'; Campo_Data_Atual = 'Data_Atual'; Campo_Curso = 'Curso'; Campo_Serie = 'Série'; Campo_Turma = 'Turma'; Campo_Anuidade = 'Anuidade'; Campo_Valor_Unitario = 'valor_unitario'; Campo_datainicio = 'datainicio'; Campo_responsavel = 'responsavel'; Campo_conjuge = 'conjuge'; Campo_rg_responsavel = 'rg_responsavel'; Campo_cpf_responsavel = 'cpf_responsavel'; Campo_end_responsavel = 'end_responsavel'; Campo_bai_responsavel = 'Bairro_Responsável'; Campo_cid_responsavel = 'cid_responsavel'; Campo_est_responsavel = 'est_responsavel'; Campo_Total_Juros = 'Total_Juros'; Campo_Extrato_detalhado = 'Extrato_analitico'; Campo_Nome_do_Pai = 'Nome_do_Pai'; Campo_Nome_da_Mae = 'Nome_da_Mae'; Campo_CPF_Pai = 'CPF_do_Pai'; Campo_CPF_Mae = 'CPF_da_Mae'; Data_nasc = 'Data_nasc'; Rg_aluno = 'Rg_aluno'; Cpf_aluno = 'Cpf_aluno'; bairro_aluno = 'bairro_aluno'; tel_aluno = 'tel_aluno'; email_aluno = 'email_aluno'; tel_pai = 'tel_pai'; tel_celular_pai = 'tel_celular_pai'; rg_pai = 'RG_Pai'; end_pai = 'end_pai'; bairro_pai = 'bairro_pai'; cep_pai = 'cep_pai'; cidade_pai = 'cidade_pai'; UF_pai = 'UF_pai'; tel_mae = 'tel_mae'; tel_celular_mae = 'tel_celular_mae'; rg_mae = 'RG_mae'; end_mae = 'end_mae'; bairro_mae = 'bairro_mae'; cep_mae = 'cep_mae'; cidade_mae = 'cidade_mae'; UF_mae = 'UF_mae'; bairro_responsavel = 'bairro_responsavel'; cep_responsavel = 'cep_responsavel'; email_pai = 'email_pai'; email_mae = 'email_mae'; email_responsavel = 'email_responsavel'; Ra_aluno = 'Ra_aluno'; Nacionalidade_Resp = 'Nascionalidade_responsavel'; Turno = 'Turno'; DtNasc_pai = 'Dt_Nascimento_Pai'; DtNasc_mae = 'Dt_Nascimento_Mae'; Responsavel_Pedagogico = 'ResponsavelPedagogico'; turno_aluno = 'turno'; Estado_civil = 'Estado_Civil'; Responsavel_Financeiro = 'Responsavel_Financeiro'; Tel_resp_finan = 'Tel_Resp_Financeiro'; Prof_resp_finan = 'Prof_Resp_Financeiro'; Dt_Nasc_RespFinan = 'Dt_Nasc_RespFinan'; Cel_Resp_Finan = 'Cel_resp_Finan'; Anuidade_extenso= 'Anuidade_extenso'; Valor_Unitario_extenso= 'valor_unitario_extenso'; Data_Atual_extenso= 'Data_Atual_extenso'; CepResp ='CepResp'; numero ='numero'; Prof_pai ='Prof_pai'; Prof_mae ='Prof_mae'; TelEmpresa_Resp = 'TelEmpresa_Resp'; RgPai = 'RgPai'; RgMae = 'RgMae'; email_resp = 'email_resp'; AnuidadeComDesconto_extenso = 'AnuidadeComDesconto_extenso'; Valor_Bolsa1 = 'Valor_Bolsa1'; Percentual_Bolsa1 = 'Percentual_Bolsa1'; Dt_Inic_PerBolsa1 = 'Dt_Inic_PerBolsa1'; Dt_Fim_PerBolsa1 = 'Dt_Fim_PerBolsa1'; Valor_Bolsa2 = 'Valor_Bolsa2'; Percentual_Bolsa2 = 'Percentual_Bolsa2'; Dt_Inic_PerBolsa2 = 'Dt_Inic_PerBolsa2'; Dt_Fim_PerBolsa2 = 'Dt_Fim_PerBolsa2'; Valor_Bolsa3 = 'Valor_Bolsa3'; Percentual_Bolsa3 = 'Percentual_Bolsa3'; Dt_Inic_PerBolsa3 = 'Dt_Inic_PerBolsa3'; Dt_Fim_PerBolsa3 = 'Dt_Fim_PerBolsa3'; CpfPai = 'CpfPai'; CpfMae = 'CpfMae'; MAX_CAMPOS_SECRETARIA = 56; // Não mudar a ordem dos campos abaixo, sempre colocar no final os campos novos CamposSecretaria : array[1..MAX_CAMPOS_SECRETARIA] of String = ( 'Matricula', 'Nome_do_Aluno', 'Endereco', 'Bairro', 'Cidade', 'Estado', 'CEP', 'Data_Atual', 'Curso', 'Serie', 'Turma', 'Responsavel', 'Conjuge', 'RG_do_Responsavel', 'CPF_do_Responsavel', 'Endereco_do_Responsavel', 'Bairro_do_Responsavel', 'Cidade_do_Responsavel', 'UF_do_Responsavel', 'Nome_do_Pai', 'Nome_da_Mae', 'Data_de_nascimento', 'Rg_Aluno', 'Data_atual', 'RA_Aluno', 'Nacionalidade_Resp', 'tel_aluno', 'tel_pai', 'tel_celular_pai', 'tel_mae', 'tel_celular_mae', 'tel_celular_aluno', 'end_pai', 'bairro_pai', 'cep_pai', 'cidade_pai', 'UF_pai', 'end_mae', 'bairro_mae', 'cep_mae', 'cidade_mae', 'UF_mae', 'email_aluno', 'email_pai', 'email_mae', 'turno_aluno', 'CidadeNasc', 'UfNasc', 'CepResp', 'Numero', 'RgPai', 'RgMae', 'email_resp', 'Proximo_Ano_Curso', 'CpfPai', 'CpfMae' ); // Campos disponíveis para Cartas de cobrança MAX_CAMPOS_COBRANCA = 88; //75 CamposCobranca : array[1..MAX_CAMPOS_COBRANCA] of String = ( Campo_Matricula, // 1 Campo_Nome_do_aluno, // 2 Campo_Responsavel_financeiro, // 3 Campo_Endereco, // 4 Campo_Cidade, // 5 Campo_Estado, // 6 Campo_CEP, // 7 Campo_Valor_Devido, // 8 Campo_N_de_parcelas, // 9 Campo_Extrato_de_Atraso, //10 Campo_Data_Atual, //11 Campo_Curso, //12 Campo_Serie, //13 Campo_Turma, //14 Campo_Anuidade, //15 Campo_valor_unitario, //16 Campo_datainicio, //17 Campo_responsavel, //18 Campo_conjuge, //19 Campo_rg_responsavel, //20 Campo_cpf_responsavel, //21 Campo_end_responsavel, //22 Campo_cid_responsavel, //23 Campo_est_responsavel, //24 Campo_Total_juros, //25 Campo_Extrato_detalhado, //26 Campo_Nome_do_Pai, //27 Campo_Nome_da_Mae, //28 Campo_CPF_Pai, //29 Campo_CPF_Mae, //30 Data_nasc, //31 Rg_aluno, //32 Cpf_aluno, //33 bairro_aluno, //34 tel_aluno, //35 email_aluno, //36 tel_pai, //37 tel_celular_pai, //38 rg_pai, //39 end_pai, //40 bairro_pai, //41 cep_pai, //42 cidade_pai, //43 UF_pai, //44 tel_mae, //45 tel_celular_mae, //46 rg_mae, //47 end_mae, //48 bairro_mae, //49 cep_mae, //50 cidade_mae, //51 UF_mae, //52 bairro_responsavel, //53 cep_responsavel, //54 email_pai, //55 email_mae, //56 email_responsavel, //57 Nacionalidade_Resp, //58 Ra_aluno, //59 Turno, //60 DtNasc_pai, //61 DtNasc_mae, //62 Responsavel_Pedagogico, //63 Estado_civil, //64 Responsavel_Financeiro, //65 Tel_resp_finan, //66 Dt_Nasc_RespFinan, //67 Cel_Resp_Finan, //68 Prof_resp_Finan, //69 Anuidade_extenso, //70 valor_unitario_extenso, //71 Data_Atual_extenso //72 ,Prof_pai //73 ,Prof_mae //74 ,TelEmpresa_Resp //75 ,AnuidadeComDesconto_extenso //76 ,Valor_Bolsa1 //77 ,Percentual_Bolsa1 //78 -- ,Dt_Inic_PerBolsa1 //79 ,Dt_Fim_PerBolsa1 //80 ,Valor_Bolsa2 //81 ,Percentual_Bolsa2 //82 ,Dt_Inic_PerBolsa2 //83 ,Dt_Fim_PerBolsa2 //84 ,Valor_Bolsa3 //85 ,Percentual_Bolsa3 //86 ,Dt_Inic_PerBolsa3 //87 ,Dt_Fim_PerBolsa3 //88 ); ntSemNota = -1; ntDispensa = -2; // Avisos de eventos que podem ser trocados entre o prog. Principal // e os módulos. // Quando é incluido um aluno, importando os dados de um candidato existente. EV_ImportaCandidato = 0; EV_IncluirAluno = 1; EV_PassagemInicial = 2; // Tipo de cálculo da nota final calc_Media = 'M'; calc_Soma = 'S'; frq_Presente = 'P'; frq_Ausente = 'A'; frq_EmBranco = ' '; type // Tipos usados nos eventos acima TEventoImportaCandidato = class LetivoCandidato : String; Inscricao : String; Matricula : String; end; type TUser = record idUsuario : Integer; idGrupo : Integer; NomeGrupo : String; AnoLetivo : String; Nome : String; Iniciais : string; Usuario : string; Senha : string; end; TAcaoRegistro = (arInserir, arAlterar, arVisualizar); TSituacaoMedias = record Situacao : Char; MediaBim : Double; MediaFinal : Double; Valores : array[0..MAXCAMPOSCRITERIO] of Single; end; TTipoRelatorio = (trAnalitico, trSintetico); TTipoRecibo = (recMatricial, recJatoTinta, recNaoImprimir, recCupom); TIdentEvento = record Letivo : String; Codigo : Integer; end; TEventoArray = array of TIdentEvento; function NomeTurno(Turno : String) : String; implementation function NomeTurno(Turno : String) : String; begin if Trim(Turno) = '' then Result := '' else case Turno[1] of 'M' : Result := 'Manhã'; 'T' : Result := 'Tarde'; 'N' : Result := 'Noite'; 'I' : Result := 'Integral'; end; end; function DescSituacao_(Situacao : Char): String; begin case Situacao of SIT_APROVADO : Result := 'Aprovado'; SIT_CONSELHO : Result := 'Aprov.Consel.'; SIT_REPROVADO : Result := 'Reprovado'; SIT_RECUPERACAO : Result := 'Recuperação'; SIT_DEPENDENCIA : Result := 'Dependencia'; else Result := ''; // raise Exception.Create('Situação inválida : ' + Situacao); end; end; function SituacaoPrioritaria(Sit1, Sit2 : char) : char; const Prioridade = SIT_CONSELHO + SIT_APROVADO + SIT_RECUPERACAO + SIT_REPROVADO; var ind1 : Integer; ind2 : Integer; begin ind1 := Pos(Sit1, Prioridade); ind2 := Pos(Sit2, Prioridade); if (ind1 > ind2) then Result := Sit1 else Result := Sit2; end; function DescEstadoCivil (ind : Integer) : String; begin case ind of 0 : Result := 'Casados'; 1 : Result := 'Solteiros'; 2 : Result := 'Separados'; 3 : Result := 'Pai Viúvo'; 4 : Result := 'Mãe Viúva'; 5 : Result := 'Ambos falecidos'; else Result := ''; end; end; end.
// see ISC_license.txt {$I genLL.inc} unit SchrodingerLexer; interface uses SysUtils, Runtime; const MaskHi = 1 shl 31; //fro Schrodinger comparison LEX_ID = MaskHi; LEX_IF = MaskHi + 1; LEX_THEN = MaskHi + 2; LEX_ASSIGNMENT = 1; LEX_EQUALS = 2; LEX_NOT_EQUALS = 3; LEX_SEMI = 4; LEX_INT = 5; LEX_WS = 6; LEX_COMMENT = 7; type TSchrodingerLexer = class(TLexer) protected procedure Tokens(); override; function GetTokenName(tokenType: integer): string; override; function fENDL(): boolean; function fLETTER(): boolean; function fDIGIT(): boolean; procedure mWS(); procedure mCOMMENT(); procedure mID(); procedure mINT(); procedure mIF(); procedure mTHEN(); end; implementation uses Tokens; procedure TSchrodingerLexer.Tokens; var LA1: integer; lextype: integer; begin LA1 := LA(1); if LA1 = LEX_EOF then begin ApproveTokenBuf(LEX_EOF, ceDefault); exit; end; case LA1 of 9 .. 10, 13, ord(' '): mWS(); ord('A') .. ord('Z'), ord('a') .. ord('z'), ord('_'): begin if LA1 = ord('i') then begin if CompareLatin('if') then mIF() else mID(); end else if LA1 = ord('t') then begin if CompareLatin('then') then mTHEN() else mID(); end else mID(); end; ord('0') .. ord('9'): mINT(); ord('/'): if LA(2) = ord('/') then mCOMMENT() else raise ENoViableAltException.Create(''); ord(';'), ord('='), ord('!'): begin case LA1 of ord(';'): lextype := LEX_SEMI; ord('='): if LA(2) = ord('=') then begin lextype := LEX_EQUALS; Consume(); end else lextype := LEX_ASSIGNMENT; ord('!'): if LA(2) = ord('=') then begin lextype := LEX_NOT_EQUALS; Consume(); end else raise ENoViableAltException.Create(''); end; Consume; ApproveTokenBuf(lextype, ceDefault); end; end; end; function TSchrodingerLexer.GetTokenName(tokenType: integer): string; begin case tokenType of LEX_ID: result := 'Ident'; LEX_IF: result := 'if'; LEX_THEN: result := 'then'; LEX_ASSIGNMENT: result := '='; LEX_EQUALS: result := '=='; LEX_NOT_EQUALS: result := '!='; LEX_SEMI: result := ';'; LEX_INT: result := 'int'; LEX_WS: result := 'whitespace'; LEX_COMMENT: result := 'comment'; end; end; function TSchrodingerLexer.fENDL(): boolean; begin result := (LA(1) = 13) and (LA(2) = 10) or (LA(1) = 10); end; function TSchrodingerLexer.fLETTER(): boolean; var ch: integer; begin ch := LA(1); result := (ch >= ord('A')) and (ch <= ord('Z')) or (ch >= ord('a')) and (ch <= ord('z')) end; function TSchrodingerLexer.fDIGIT(): boolean; var ch: integer; begin ch := LA(1); result := (ch >= ord('0')) and (ch <= ord('9')); end; procedure TSchrodingerLexer.mWS(); var LA1: integer; begin repeat LA1 := LA(1); if (LA1 = 9) or fENDL() or (LA1 = ord(' ')) then Consume() else break; until false; ApproveTokenBuf(LEX_WS, ceHidden); end; procedure TSchrodingerLexer.mCOMMENT; var LA1: integer; begin MatchLatin('\\'); repeat LA1 := LA(1); if (LA1 <> -1) and not fENDL() then Consume() else break; until false; ApproveTokenBuf(LEX_COMMENT, ceHidden); end; procedure TSchrodingerLexer.mID(); var LA1: integer; begin if fLETTER() or (LA(1) = ord('_')) then Consume; repeat LA1 := LA(1); if fLETTER() or (LA(1) = ord('_')) or fDIGIT() then Consume() else break; until false; ApproveTokenBuf(LEX_ID, ceDefault); end; procedure TSchrodingerLexer.mINT(); var LA1: integer; begin if LA(1) = ord('0') then Consume() else begin Consume(); // 1..9 while fDIGIT() do Consume(); end; ApproveTokenBuf(LEX_INT, ceDefault); end; procedure TSchrodingerLexer.mIF; begin MatchLatin('if'); ApproveTokenBuf(LEX_IF, ceDefault); end; procedure TSchrodingerLexer.mTHEN; begin MatchLatin('then'); ApproveTokenBuf(LEX_THEN, ceDefault); end; end.
(******************************************************************************* When people log into your app with Facebook, they can grant permissions to your app so you can retrieve information or perform actions on Facebook on their behalf. Setup (ANDROID) --------------- https://developers.facebook.com/docs/android/getting-started 1) https://developers.facebook.com/docs/android/getting-started https://developers.facebook.com/docs/facebook-login/android/ Open your /app/res/values/strings.xml file. Add string elements with the names facebook_app_id, fb_login_protocol_scheme and facebook_client_token, and set the values to your App ID and Client Token. For example, if your app ID is 1234 and your client token is 56789 your code looks like the following: <string name="facebook_app_id">1234</string> <string name="fb_login_protocol_scheme">fb1234</string> <string name="facebook_client_token">56789</string> You can merge this strings.xml with the help of AndroidMerger. You can see an exemple in <Alcinoe>\Demos\ALFacebookLogin\_source\android\MergeLibraries.bat 2) https://developers.facebook.com/docs/android/getting-started Open the /app/manifest/AndroidManifest.xml file. Add meta-data elements to the application element for your app ID and client token: <application> ... <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/> <meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_client_token"/> ... </application> 3) https://developers.facebook.com/docs/app-events/getting-started-app-events-android To disable automatically logged events add the following to your AndroidManifest.xml file: <application> ... <meta-data android:name="com.facebook.sdk.AutoLogAppEventsEnabled" android:value="false"/> ... </application> 4) https://developers.facebook.com/docs/app-events/getting-started-app-events-android To disable collection of advertiser-id, add the following to your AndroidManifest.xml file: <application> ... <meta-data android:name="com.facebook.sdk.AdvertiserIDCollectionEnabled" android:value="false"/> ... </application> 5) To disable automatic SDK initialization (the alcinoe framework will do it for you when you will use any facebook functions below), you can replace the following in your AndroidManifest.xml file: <provider android:name="com.facebook.internal.FacebookInitProvider" android:authorities="%package%.FacebookInitProvider" android:exported="false"/> by <!-- !! <provider android:name="com.facebook.internal.FacebookInitProvider" android:authorities="%package%.FacebookInitProvider" android:exported="false"/> !! --> Setup (IOS) ----------- https://developers.facebook.com/docs/ios/getting-started 1) follow the step bescribed described for FIREBASE in Alcinoe.FMX.Firebase.Messaging.pas 1) : LD linker add -ObjC 3) : Add the libswift frameworks for ios64 and Ios64 simulator 4) : LD linker add -rpath /usr/lib/swift 2) in LD linker add add -w to remove the warning "was built for newer iOS version (12.0) than being linked (11.0)" 2) In project > option > Building > Delphi Compiler > FRAMEWORK search path you need to add the following path: <Alcinoe>\Libraries\ios\facebook\FBSDKLoginKit.xcframework\ios-arm64 <Alcinoe>\Libraries\ios\facebook\FBSDKShareKit.xcframework\ios-arm64 <Alcinoe>\Libraries\ios\facebook\FBSDKCoreKit_Basics.xcframework\ios-arm64 <Alcinoe>\Libraries\ios\facebook\FBSDKCoreKit.xcframework\ios-arm64 <Alcinoe>\Libraries\ios\facebook\FBAEMKit.xcframework\ios-arm64 3) https://developers.facebook.com/docs/ios/getting-started Configure the Info.plist file with an XML snippet that contains data about your app. <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>fbAPP-ID</string> </array> </dict> </array> <key>FacebookAppID</key> <string>APP-ID</string> <key>FacebookClientToken</key> <string>CLIENT-TOKEN</string> <key>FacebookDisplayName</key> <string>APP-NAME</string> 4) https://developers.facebook.com/docs/ios/getting-started To use any of the Facebook dialogs (e.g., Login, Share, App Invites, etc.) that can perform an app switch to Facebook apps, your application's Info.plist also needs to include the following: <key>LSApplicationQueriesSchemes</key> <array> <string>fbapi</string> <string>fb-messenger-share-api</string> </array> 5) https://developers.facebook.com/docs/app-events/getting-started-app-events-ios/ Disable Automatically Logged Events To disable automatic event logging, open the application's Info.plist as code in Xcode and add the following XML to the property dictionary: <key>FacebookAutoLogAppEventsEnabled</key> <false/> 6) https://developers.facebook.com/docs/app-events/getting-started-app-events-ios/ Disable Collection of Advertiser IDs To disable collection of advertiser-id, open the application's .plist as code in Xcode and add the following XML to the property dictionary: <key>FacebookAdvertiserIDCollectionEnabled</key> <false/> 7) To disable automatic SDK initialization (the alcinoe framework will do it for you when you will use any facebook functions below), you can set ALInitFacebookSDKAtStartup := false in the begin .. end section of your dpr *******************************************************************************) unit Alcinoe.FMX.Facebook.Core; interface {$I Alcinoe.inc} {***********************} procedure ALInitFacebook; {*} var ALInitFacebookSDKAtStartup: Boolean = true; implementation uses system.Messaging, {$IF defined(android)} Alcinoe.AndroidApi.Facebook, Androidapi.Helpers, {$ELSEIF defined(IOS)} iOSapi.Foundation, Macapi.Helpers, iOSapi.Helpers, FMX.Platform, FMX.Platform.iOS, Alcinoe.iOSApi.FacebookCoreKit, {$ENDIF} Alcinoe.StringUtils, Alcinoe.Common; {*} var _ALFacebookInitialised: Boolean; {***********************} procedure ALInitFacebook; begin if not _ALFacebookInitialised then begin {$REGION 'ANDROID'} {$IF defined(android)} {$IFDEF DEBUG} allog('ALInitFacebook', 'sdkInitialize | isInitialized: '+ALBoolToStrW(TJFacebookSdk.JavaClass.isInitialized), TalLogType.VERBOSE); {$ENDIF} TJFacebookSdk.JavaClass.sdkInitialize(TAndroidHelper.Context); {$ENDIF} {$ENDREGION} {$REGION 'IOS'} {$IF defined(ios)} {$IFDEF DEBUG} allog('ALInitFacebook', 'initializeSDK', TalLogType.VERBOSE); {$ENDIF} //https://github.com/facebook/facebook-ios-sdk/issues/1731 //those monkey facebook developpers made 2 initialization procedures // *TFBSDKApplicationDelegate.OCClass.sharedInstance.initializeSDK // *TFBSDKApplicationDelegate.OCClass.sharedInstance.applicationDidFinishLaunchingWithOptions //but their is a notable difference between thoses 2 procedure. the first //(initializeSDK) will not persist the token on restart (token will be empty //and you must call again the login procedure to retrieve it again) //where the 2nd (applicationDidFinishLaunchingWithOptions) will persist the //token between app restart TFBSDKApplicationDelegate.OCClass.sharedInstance.initializeSDK; {$ENDIF} {$ENDREGION} _ALFacebookInitialised := True; end; end; {$REGION ' IOS'} {$IF defined(IOS)} {*******************************************************************************************} procedure ALFmxFacebookCoreApplicationEventHandler(const Sender: TObject; const M: TMessage); begin if M is TApplicationEventMessage then begin var LValue := (M as TApplicationEventMessage).value; if LValue.Event = TApplicationEvent.OpenURL then begin var Lcontext := TiOSOpenApplicationContext(LValue.Context); {$IFDEF DEBUG} ALLog( 'ALFmxFacebookCoreApplicationEventHandler', 'Event: OpenURL | '+ 'ALFacebookInitialised: '+ALBoolToStrW(_ALFacebookInitialised)+' | '+ 'Url: ' + Lcontext.URL, TalLogType.VERBOSE); {$ENDIF} if not _ALFacebookInitialised then exit; {$IFNDEF ALCompilerVersionSupported} //Ios doc say iOS 13 moved opening URL functionality to the SceneDelegate. If you are //using iOS 13, add the following method to your SceneDelegate so that operations like //logging in or sharing function as intended (https://developers.facebook.com/docs/ios/getting-started) //but actually their is no implementation in delphi for the SceneDelegate and also it's //seam that the event is still called in ios 13+ //(https://stackoverflow.com/questions/75062913/applicationopenurloptions-vs-sceneopenurlcontexts) //so for now I simply skip it and I add this warn to verify if one day //SceneDelegate will be implemented in delphi {$MESSAGE WARN 'Check if SceneDelegate is implemented in Delphi source code'} {$ENDIF} TFBSDKApplicationDelegate.OCClass.sharedInstance.applicationOpenURLOptions( TiOSHelper.SharedApplication, // application: UIApplication StrToNSUrl(Lcontext.Url), // openURL: NSURL; TNSDictionary.Wrap(Lcontext.Context)); // options: NSDictionary end else if LValue.Event = TApplicationEvent.FinishedLaunching then begin if not ALInitFacebookSDKAtStartup then exit; if _ALFacebookInitialised then exit; {$IFDEF DEBUG} ALLog( 'ALFmxFacebookCoreApplicationEventHandler', 'Event: FinishedLaunching', TalLogType.VERBOSE); {$ENDIF} {$IFNDEF ALCompilerVersionSupported} {$MESSAGE WARN 'Check if https://quality.embarcadero.com/browse/RSP-40351 is implemented like expected (With TiOSOpenApplicationContext)'} {$ENDIF} var LdidFinishLaunchingWithOptions: NSDictionary; if LValue.Context <> nil then LdidFinishLaunchingWithOptions := TNSDictionary.Wrap(TiOSOpenApplicationContext(LValue.Context).Context) else LdidFinishLaunchingWithOptions := nil; //see note in ALInitFacebook regarding initializeSDK in ALInitFacebook TFBSDKApplicationDelegate.OCClass.sharedInstance.applicationDidFinishLaunchingWithOptions( TiOSHelper.SharedApplication, // application: UIApplication LdidFinishLaunchingWithOptions); // options: NSDictionary _ALFacebookInitialised := True; end; end; end; {$ENDIF} {$ENDREGION} initialization _ALFacebookInitialised := False; {$REGION 'IOS'} {$IF defined(IOS)} TMessageManager.DefaultManager.SubscribeToMessage(TApplicationEventMessage, ALFmxFacebookCoreApplicationEventHandler); {$ENDIF} {$ENDREGION} finalization {$REGION 'IOS'} {$IF defined(IOS)} TMessageManager.DefaultManager.Unsubscribe(TApplicationEventMessage, ALFmxFacebookCoreApplicationEventHandler); {$ENDIF} {$ENDREGION} end.
(* ENUNCIADO Faça um programa em Free Pascal que leia dois inteiros positivos m e n, sendo 1 ≤ m, n ≤ 100, e uma matriz A m×n . O programa deve imprimir o números de linhas e o número de colunas que são nulas, ou seja, quando todos os elementos de uma linha ou coluna são iguais a 0 (zero). Nos casos de teste cada elemento x da matriz A é definido por 0 ≤ x ≤ 100. Exemplo de entrada: 4 4 1 0 2 3 4 0 5 6 0 0 0 0 0 0 0 0 Saı́da esperada para o exemplo acima: linhas: 2 colunas: 1 *) program 2elementosnulos; const max=100; type mat=array [1 .. max, 1 .. max] of integer; function verlin(matriz:mat; lin,n:integer):boolean; var col:integer; begin verlin:=true; col:=0; while(verlin=true)and(col<n) do begin col:=col+1; if (matriz[lin,col]<>0) then verlin:=false; end; end; function vercol(matriz:mat; col,m:integer):boolean; var lin:integer; begin vercol:=true; lin:=0; while(vercol=true)and(lin<m)do begin lin:=lin+1; if (matriz[lin,col]<>0) then vercol:=false; end; end; procedure ler(var matriz:mat;var m,n:integer); var cont,cont1:integer; begin read(m,n); for cont:=1 to m do for cont1:=1 to n do read(matriz[cont,cont1]); end; var matriz:mat; m,n,lin,col,cont,cont2:integer; flag:boolean; begin cont:=0; cont2:=0; ler(matriz,m,n); for lin:=1 to m do begin flag:=false; flag:=verlin(matriz,lin,n); if flag=true then cont:=cont+1; end; for col:=1 to n do begin flag:=false; flag:=vercol(matriz,col,m); if flag=true then cont2:=cont2+1; end; writeln('linhas: ',cont); writeln('colunas: ',cont2); end.
unit uCrypt; interface uses Windows, SysUtils, Classes; const password = 'q23RvA7.zp/3'; function EnCrypt(text: string): string; function DeCrypt(text: string): string; implementation procedure Code(var text: string; decode: boolean); var i, PasswordLength: integer; sign: shortint; begin PasswordLength := length(password); if PasswordLength = 0 then Exit; if decode then sign := -1 else sign := 1; for i := 1 to Length(text) do text[i] := chr(ord(text[i]) + sign*ord(password[i mod PasswordLength + 1])); end; function EnCrypt(text: string): string; var res: string; begin res := text; Code(res, false); Result := res; end; function DeCrypt(text: string): string; var res: string; begin res := text; Code(res, true); Result := res; end; end.
unit Nathan.Tuple.Basics; interface uses System.SysUtils, System.Generics.Collections, DUnitX.TestFramework, Nathan.Tuple; type TMyReturn = record MyInteger: Integer; MyFirstString: string; MySecondString: string; end; TDemoTupleClass = class(TObject) function GetEmployee(): TList<ITuple<Integer, string, string>>; function GetSomethingWithMakeTuple(): ITuple<Integer, string>; function GetSomethingWithoutTuple(): TMyReturn; end; [TestFixture] TTestNathanTupleBasics = class(TObject) public [Test] procedure Test_ToString(); [Test] procedure Test_ListOfTupleDemo_ToString(); [Test] procedure Test_make_tuple_WithHelper(); [Test] procedure Test_make_tuple_FromReturnValue(); [Test] procedure Test_make_tuple_WithoutHelper(); [Test] procedure Test_make_tuple_WithHelper_WrongArgumentList(); end; implementation function TDemoTupleClass.GetEmployee(): TList<ITuple<Integer, string, string>>; begin Result := TList<ITuple<Integer, string, string>>.Create(); Result.Add(TTuple<Integer, string, string>.Create(1, 'Zürich', 'Switzerland')); Result.Add(TTuple<Integer, string, string>.Create(2, 'Ravensburg', 'Germany')); end; function TDemoTupleClass.GetSomethingWithMakeTuple(): ITuple<Integer, string>; begin Result := TTuple<Integer, string>.make_tuple([4712, 'Nathan']); end; function TDemoTupleClass.GetSomethingWithoutTuple(): TMyReturn; begin Result.MyInteger := 4711; Result.MyFirstString := '1.'; Result.MySecondString := '2.'; end; procedure TTestNathanTupleBasics.Test_ToString(); var Actual: string; Cut: ITuple<String, Integer>; begin // Arrange... // Create a three item tuple... Cut := TTuple<String, Integer>.Create('California', 29760021); // Act... Actual := Cut.ToString; // Assert... Assert.AreEqual('California', Cut.Item1); Assert.AreEqual(29760021, Cut.Item2); Assert.AreEqual('(California, 29760021)', Actual); end; procedure TTestNathanTupleBasics.Test_ListOfTupleDemo_ToString(); var Actual: string; ActualDemo: TDemoTupleClass; ActualList: TList<ITuple<Integer, string, string>>; Cut: ITuple<Integer, string, string>; begin ActualDemo := TDemoTupleClass.Create; try ActualList := ActualDemo.GetEmployee; try Assert.AreEqual(2, ActualList.Count); Actual := ''; for Cut in ActualList do Actual := Actual + Cut.ToString + sLineBreak; Assert.AreEqual('(1, Zürich, Switzerland)'#$D#$A'(2, Ravensburg, Germany)'#$D#$A, Actual); finally ActualList.Free; end; finally ActualDemo.Free; end; end; procedure TTestNathanTupleBasics.Test_make_tuple_FromReturnValue(); var ActualDemoClass: TDemoTupleClass; ActualReturn: ITuple<Integer, string>; begin ActualDemoClass := TDemoTupleClass.Create; try ActualReturn := ActualDemoClass.GetSomethingWithMakeTuple(); Assert.AreEqual(4712, ActualReturn.Item1); Assert.AreEqual('Nathan', ActualReturn.Item2); finally ActualDemoClass.Free; end; end; procedure TTestNathanTupleBasics.Test_make_tuple_WithHelper(); var Cut: ITuple<Integer, String>; begin Cut := TTuple<Integer, String>.make_tuple([4711, 'Hello world']); Assert.IsNotNull(Cut); Assert.AreEqual(4711, Cut.Item1); Assert.AreEqual('Hello world', Cut.Item2); Cut.Item2 := ''; Assert.AreEqual('', Cut.Item2); end; procedure TTestNathanTupleBasics.Test_make_tuple_WithoutHelper(); var Cut: ITuple<Integer, String>; begin Cut := TTuple<Integer, String>.Create(4711, 'Hello world'); Assert.IsNotNull(Cut); Assert.AreEqual(4711, Cut.Item1); Assert.AreEqual('Hello world', Cut.Item2); Cut.Item2 := ''; Assert.AreEqual('', Cut.Item2); end; procedure TTestNathanTupleBasics.Test_make_tuple_WithHelper_WrongArgumentList(); var Cut: ITuple<Integer, String>; begin {$REGION 'Info'} // http://www.delphipraxis.net/185937-e2232-interface-x-besitzt-keine-interface-identifikation.html // // How to get an Interface // if LMy.QueryInterface(IMyIntfA, LIMyA) = S_OK then // // or // if Supports(LMy, IMyIntfA, LIMyA) then {$ENDREGION} Assert.WillRaise(procedure begin Cut := TTuple<Integer, String>.make_tuple([4711, 25.88]); end, EInvalidCast); Assert.IsNull(Cut); end; initialization TDUnitX.RegisterTestFixture(TTestNathanTupleBasics, 'Basics'); end.
program SalesFileReader; uses Crt; const TopTitle = ' MULTI-DISK COMPUTER COMPANY'; Title2 = ' SALES REPORT'; TitleLineOne = 'SALESPERSON SALESPERSON PRODUCT QTY PRICE EXTENSION'; TitleLineTwo = 'NUMBER NAME CODE SOLD AMOUNT'; TotalFor = ' TOTAL FOR '; TotalForReport = 'TOTAL FOR REPORT'; FileName = 'saledata.dat'; Type EmployeeID = 1000 .. 9999; ProductCode = 1000 .. 9999; SalesRecord = Record SalespersonNo : EmployeeID; SalespersonName : String [11]; ProductNo : ProductCode; QuantitySold : Integer; UnitPrice : Real; End {SalesRecord}; var Sale: SalesRecord; PageNo, CurrentNo, PrevNo: integer; PrevName: string; Extension, SalesTotal, SubTotal: real; SalesFile: file of SalesRecord; Day, Month, Year: shortint; procedure Setup; begin SalesTotal:= 0; SubTotal:= 0; Assign(SalesFile, FileName); Reset(SalesFile); Write('Date: '); Readln(Day, Month, Year); ClrScr; Writeln(TopTitle); Write(Day,'/', Month,'/', Year); Writeln(Title2); Writeln(TitleLineOne); Writeln(TitleLineTwo); Writeln; end; procedure ReadFromFile; begin Read(SalesFile, Sale); end; procedure PrintDetails; begin Write(Sale.SalesPersonNo); GoToXY(14, WhereY); Write(Sale.SalesPersonName); GoToXY(31, WhereY); Write(Sale.ProductNo); GoToXY(39, WhereY); Write(Sale.QuantitySold:2); GoToXY(47, WhereY); Write(Sale.UnitPrice:6:2); GoToXY(59, WhereY); Writeln(Extension:8:2); end; procedure DoTheMaths; begin Extension:= Sale.UnitPrice * Sale.QuantitySold; SubTotal:= SubTotal + Extension; CurrentNo:= Sale.SalesPersonNo; end; procedure WriteTheSubTotal; begin Writeln; Write(TotalFor); Write(PrevName); GoToXY(59, WhereY); Writeln(SubTotal:8:2); Writeln; end; procedure CleanUp; begin Close(SalesFile); end; begin Setup; ReadFromFile; PrevNo:= Sale.SalesPersonNo; CurrentNo:= Sale.SalesPersonNo; PrevName:= Sale.SalesPersonName; While not Eof(SalesFile) do begin If PrevNo <> CurrentNo then begin WriteTheSubTotal; SubTotal:= 0; PrevNo:= CurrentNo; PrevName:= Sale.SalesPersonName; end; PrintDetails; SalesTotal:= SalesTotal + SubTotal; ReadFromFile; DoTheMaths; end; { WHILE } WriteTheSubTotal; SalesTotal:= SalesTotal + SubTotal; GoToXY(59, WhereY); Writeln; Write(SalesTotal:10:2); CleanUp; end.
unit CHelpers; {$MODE OBJFPC}{$H+} // --------------------------------------------------------------------------- // Edit Date $ Entry // --------------------------------------------------------------------------- // 2015-08-27 $ Use out parameters instead of var to shut up compiler hints. // 2015-08-26 $ SetAndGet() // 2015-08-04 $ initial release // $ SetAndTest() // --------------------------------------------------------------------------- interface function SetAndTest(Out OldValue: pointer; NewValue: pointer) : boolean; overload; inline; function SetAndTest(Out OldValue: LongWord; NewValue: LongWord): boolean; overload; inline; function SetAndTest(Out OldValue: LongInt; NewValue: LongInt) : boolean; overload; inline; function SetAndGet(Out Variable: pointer; Value: pointer) : pointer; overload; inline; function SetAndGet(Out Variable: LongWord; Value: LongWord) : LongWord; overload; inline; function SetAndGet(Out Variable: LongInt; Value: LongInt) : LongInt; overload; inline; Implementation function SetAndTest(Out OldValue: pointer; NewValue: pointer): boolean; begin OldValue := NewValue; result := (NewValue <> nil) end; function SetAndTest(Out OldValue: LongWord; NewValue: LongWord): boolean; begin OldValue := NewValue; result := (NewValue <> 0) end; function SetAndTest(Out OldValue: LongInt; NewValue: LongInt): boolean; begin OldValue := NewValue; result := (NewValue <> 0) end; function SetAndGet(Out Variable: pointer; Value: pointer) : pointer; overload; begin Variable := Value; result := Value; end; function SetAndGet(Out Variable: LongWord; Value: LongWord) : LongWord; overload; begin Variable := Value; result := Value; end; function SetAndGet(Out Variable: LongInt; Value: LongInt) : LongInt; overload; begin Variable := Value; result := Value; end; end.
unit History; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, manuals, FIBQuery, pFIBQuery, ActnList, Menus, DB, FIBDataSet, pFIBDataSet, ComCtrls, StdCtrls, Buttons, Grids, DBGrids, acDBGrid, ExtCtrls, sPanel, frxClass, frxDBSet, frxExportODF, frxExportTXT, frxExportCSV, frxExportImage, frxExportXML, frxExportXLS, frxExportPDF, ToolWin, frxpngimage; type TfrmHistory = class(Tfrm_manuals) manDSUSER_: TFIBStringField; manDSTIME_: TFIBDateTimeField; manDSFIELD_NAME_: TFIBStringField; manDSOLD_FIELD_VALUE_: TFIBStringField; manDSNEW_FIELD_VALUE_: TFIBStringField; manDSTYPE_CHAGED_: TFIBIntegerField; manDSSHORT_TYPE_CHANGED_: TFIBStringField; manDSIDS_: TFIBIntegerField; actMarkOfTypeOperation: TAction; actRollBack: TAction; mntmCDORactRollBack: TMenuItem; manDSCHG_ID_: TFIBIntegerField; procedure actMarkOfTypeOperationExecute(Sender: TObject); procedure dataGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure actRollBackExecute(Sender: TObject); procedure timerFormShowTimer(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmHistory: TfrmHistory; IS_MACK_COLOR_OF_TYPE_OPERATION : Boolean = False; implementation uses global; {$R *.dfm} procedure TfrmHistory.actMarkOfTypeOperationExecute(Sender: TObject); begin inherited; IS_MACK_COLOR_OF_TYPE_OPERATION := (Sender as TAction).Checked; dataGrid.Repaint; end; procedure TfrmHistory.actRollBackExecute(Sender: TObject); begin inherited; if _QMessageBox( 'Восстановить запись ?', Application.Title, @pnlDataGrid) then begin try manQuery.Close; manQuery.SQL.Text := Format('SELECT p.RES FROM ROLLBACK_OBJECT_FROM_HYSTORY(%d) p;',[manDS.FieldByName('CHG_ID_').AsInteger]); manQuery.Transaction.Active :=True; manQuery.ExecQuery; manQuery.Transaction.Commit; manDS.Close; manDS.Open; Application.MessageBox(PAnsiChar('Операция успешно выполнена.'),PAnsiChar('Восстановление записи...'),MB_OK+MB_ICONINFORMATION); except on e: Exception do Application.MessageBox(PAnsiChar('Ошибка выполнения операции: '+e.Message),PAnsiChar('Восстановление записи...'),MB_OK+MB_ICONERROR); end; end; end; procedure TfrmHistory.dataGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin inherited; if IS_MACK_COLOR_OF_TYPE_OPERATION then begin with dataGrid.Canvas do begin if not (gdFocused in State) then begin case (dataGrid.DataSource.DataSet.FieldByName('TYPE_CHAGED_').AsInteger ) of 0 : begin // insert Font.Color := $008AFD8F; end; 1: begin // update Font.Color := $00FFFF80; end; 2: begin // remove Font.Color := $009B9DFB; end; end; FillRect(Rect); TextOut(Rect.Left +2, Rect.Top +2 , Column.Field.Text); end else dataGrid.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; end; end; procedure TfrmHistory.timerFormShowTimer(Sender: TObject); begin inherited; self.SortDS(manDS, 1); end; end.
unit UFormMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdContext, ExtCtrls, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, ComCtrls, StdCtrls, UTrayIcon, SyncObjs; type TfFormMain = class(TForm) GroupBox1: TGroupBox; CheckSrv: TCheckBox; EditPort: TLabeledEdit; CheckAuto: TCheckBox; CheckLoged: TCheckBox; BtnConn: TButton; MemoLog: TMemo; StatusBar1: TStatusBar; IdTCPServer1: TIdTCPServer; Timer1: TTimer; Timer2: TTimer; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Timer1Timer(Sender: TObject); procedure CheckSrvClick(Sender: TObject); procedure CheckLogedClick(Sender: TObject); procedure IdTCPServer1Execute(AContext: TIdContext); procedure BtnConnClick(Sender: TObject); private { Private declarations } FTrayIcon: TTrayIcon; {*状态栏图标*} FSyncLock: TCriticalSection; //同步锁 procedure ShowLog(const nStr: string); //显示日志 procedure DoExecute(const nContext: TIdContext); //执行动作 public { Public declarations } end; var fFormMain: TfFormMain; implementation {$R *.dfm} uses IniFiles, Registry, ULibFun, UDataModule, UFormConn, USysLoger, U02NReader, UMgrLEDDisp, UBusinessConst, USysConst, USysDB, UMemDataPool; resourcestring sHint = '提示'; sConfig = 'Config.Ini'; sForm = 'FormInfo.Ini'; sDB = 'DBConn.Ini'; sAutoStartKey = 'PrepareReader'; procedure WriteLog(const nEvent: string); begin gSysLoger.AddLog(TfFormMain, '预读服务主单元', nEvent); end; //Desc: 测试nConnStr是否有效 function ConnCallBack(const nConnStr: string): Boolean; begin FDM.ADOConn.Close; FDM.ADOConn.ConnectionString := nConnStr; FDM.ADOConn.Open; Result := FDM.ADOConn.Connected; end; //Desc: 数据库配置 procedure TfFormMain.BtnConnClick(Sender: TObject); begin if ShowConnectDBSetupForm(ConnCallBack) then begin FDM.ADOConn.Close; FDM.ADOConn.ConnectionString := BuildConnectDBStr; //数据库连接 end; end; procedure TfFormMain.ShowLog(const nStr: string); var nIdx: Integer; begin MemoLog.Lines.BeginUpdate; try MemoLog.Lines.Insert(0, nStr); if MemoLog.Lines.Count > 100 then for nIdx:=MemoLog.Lines.Count - 1 downto 50 do MemoLog.Lines.Delete(nIdx); finally MemoLog.Lines.EndUpdate; end; end; procedure TfFormMain.FormCreate(Sender: TObject); var nIni: TIniFile; nReg: TRegistry; nMap: string; nInt: Integer; nList: TStrings; begin gPath := ExtractFilePath(Application.ExeName); InitGlobalVariant(gPath, gPath+sConfig, gPath+sForm, gPath+sDB); gSysLoger := TSysLoger.Create(gPath + 'Logs\'); gSysLoger.LogEvent := ShowLog; gMemDataManager := TMemDataManager.Create; //内存池 g02NReader := T02NReader.Create; g02NReader.LoadConfig(gPath + 'Readers.xml'); g02NReader.OnCardIn := WhenReaderCardIn; g02NReader.OnCardOut:= WhenReaderCardOut; gDisplayManager.LoadConfig(gPath + 'LEDDisp.xml'); FTrayIcon := TTrayIcon.Create(Self); FTrayIcon.Hint := Caption; FTrayIcon.Visible := True; nIni := nil; nReg := nil; nList:= nil; try nList:= TStringList.Create; nIni := TIniFile.Create(gPath + 'Config.ini'); EditPort.Text := nIni.ReadString('Config', 'Port', '8000'); Timer1.Enabled := nIni.ReadBool('Config', 'Enabled', False); gSysParam.FStockFlag := nIni.ReadString('STOCKTYPE', 'FromIni', '0')='1'; nMap := nIni.ReadString('STOCKTYPE', 'StockList', ''); if SplitStr(nMap,nList,0,',',False) then begin SetLength(gSysParam.FStockMaps, nList.Count); for nInt:=0 to nList.Count-1 do with gSysParam.FStockMaps[nInt] do begin FStockType := nList[nInt]; FStockContext := nIni.ReadString('STOCKTYPE', FStockType, ''); end; end; nReg := TRegistry.Create; nReg.RootKey := HKEY_CURRENT_USER; nReg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', True); CheckAuto.Checked := nReg.ValueExists(sAutoStartKey); finally nIni.Free; nReg.Free; nList.Free; end; FSyncLock := TCriticalSection.Create; //new item FDM.ADOConn.Close; FDM.ADOConn.ConnectionString := BuildConnectDBStr; //数据库连接 InitSystemObject; end; procedure TfFormMain.FormClose(Sender: TObject; var Action: TCloseAction); var nIni: TIniFile; nReg: TRegistry; begin nIni := nil; nReg := nil; try nIni := TIniFile.Create(gPath + 'Config.ini'); nIni.WriteBool('Config', 'Enabled', CheckSrv.Checked); nReg := TRegistry.Create; nReg.RootKey := HKEY_CURRENT_USER; nReg.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', True); if CheckAuto.Checked then nReg.WriteString(sAutoStartKey, Application.ExeName) else if nReg.ValueExists(sAutoStartKey) then nReg.DeleteValue(sAutoStartKey); //xxxxx finally nIni.Free; nReg.Free; end; g02NReader.StopReader; gDisplayManager.StopDisplay; FSyncLock.Free; //lock SetLength(gSysParam.FStockMaps, 0); FreeSystemObject; end; procedure TfFormMain.Timer1Timer(Sender: TObject); begin Timer1.Enabled := False; CheckSrv.Checked := True; end; procedure TfFormMain.CheckSrvClick(Sender: TObject); begin BtnConn.Enabled := not CheckSrv.Checked; EditPort.Enabled := not CheckSrv.Checked; FSyncLock.Enter; try Timer2.Enabled := CheckSrv.Checked; finally FSyncLock.Leave; end; if CheckSrv.Checked then begin RunSystemObject; //当服务启动时,获取系统参数 g02NReader.StartReader; gDisplayManager.StartDisplay; end else begin g02NReader.StopReader; gDisplayManager.StopDisplay; end; end; procedure TfFormMain.CheckLogedClick(Sender: TObject); begin gSysLoger.LogSync := CheckLoged.Checked; end; procedure TfFormMain.IdTCPServer1Execute(AContext: TIdContext); begin try DoExecute(AContext); except on E:Exception do begin AContext.Connection.IOHandler.WriteBufferClear; WriteLog(E.Message); end; end; end; procedure TfFormMain.DoExecute(const nContext: TIdContext); begin with nContext.Connection do begin end; end; end.
{ -------------------------------------------------------------------------- Raspberry Pi IO library - GPIO Copyright (c) Michael Nixon 2016 - 2017. Distributed under the MIT license, please see the LICENSE file. Thanks to Gabor Szollosi for PiGpio which heavily inspired this unit. -------------------------------------------------------------------------- } unit rpigpio; interface uses sysutils, classes; const { fpmap uses page offsets, each page is 4KB. BCM2385 GPIO register map starts at $20000000, but we want to use the page offset here } RPIGPIO_FPMAP_PAGE_SIZE = $1000; RPIGPIO_PI1_REG_START = $20000; { Actually $20000000 but page offsets... } RPIGPIO_PI2_REG_START = $3F000; { Actually $3F000000 but page offsets... } RPIGPIO_INPUT = 0; RPIGPIO_OUTPUT = 1; RPIGPIO_PWM_OUTPUT = 2; RPIGPIO_LOW = false; RPIGPIO_HIGH = true; RPIGPIO_PUD_OFF = 0; RPIGPIO_PUD_DOWN = 1; RPIGPIO_PUD_UP = 2; // PWM RPIGPIO_PWM_CONTROL = 0; RPIGPIO_PWM_STATUS = 4; RPIGPIO_PWM0_RANGE = 16; RPIGPIO_PWM0_DATA = 20; RPIGPIO_PWM1_RANGE = 32; RPIGPIO_PWM1_DATA = 36; RPIGPIO_PWMCLK_CNTL = 160; RPIGPIO_PWMCLK_DIV = 164; RPIGPIO_PWM1_MS_MODE = $8000; // Run in MS mode RPIGPIO_PWM1_USEFIFO = $2000; // Data from FIFO RPIGPIO_PWM1_REVPOLAR = $1000; // Reverse polarity RPIGPIO_PWM1_OFFSTATE = $0800; // Ouput Off state RPIGPIO_PWM1_REPEATFF = $0400; // Repeat last value if FIFO empty RPIGPIO_PWM1_SERIAL = $0200; // Run in serial mode RPIGPIO_PWM1_ENABLE = $0100; // Channel Enable RPIGPIO_PWM0_MS_MODE = $0080; // Run in MS mode RPIGPIO_PWM0_USEFIFO = $0020; // Data from FIFO RPIGPIO_PWM0_REVPOLAR = $0010; // Reverse polarity RPIGPIO_PWM0_OFFSTATE = $0008; // Ouput Off state RPIGPIO_PWM0_REPEATFF = $0004; // Repeat last value if FIFO empty RPIGPIO_PWM0_SERIAL = $0002; // Run in serial mode RPIGPIO_PWM0_ENABLE = $0001; // Channel Enable type trpiGPIO = class(tobject) private protected { GPIO file fd } gpiofd: integer; { Pointers into GPIO memory space } gpioptr: ^longword; clkptr: ^longword; pwmptr: ^longword; { Initialised? } initialised: boolean; public constructor Create; destructor Destroy; override; function initialise(newPi: boolean): boolean; procedure shutdown; procedure setPinMode(pin, mode: byte); function readPin(pin: byte): boolean; inline; procedure clearPin(pin: byte); inline; procedure setPin(pin: byte); inline; procedure setPullupMode(pin, mode: byte); procedure PWMWrite(pin: byte; value: longword); inline; end; procedure delayNanoseconds(delaytime: longword); implementation uses baseunix, unix; { --------------------------------------------------------------------------- Delay for <delaytime> nanoseconds --------------------------------------------------------------------------- } procedure delayNanoseconds(delaytime: longword); var sleeper, dummy: timespec; begin sleeper.tv_sec := 0; sleeper.tv_nsec := delaytime; fpnanosleep(@sleeper, @dummy); end; { --------------------------------------------------------------------------- trpiGPIO constructor --------------------------------------------------------------------------- } constructor trpiGPIO.Create; begin inherited Create; self.initialised := false; end; { --------------------------------------------------------------------------- trpiGPIO destructor --------------------------------------------------------------------------- } destructor trpiGPIO.Destroy; begin self.shutdown; inherited Destroy; end; { --------------------------------------------------------------------------- Try to initialise the GPIO driver. Pass True to <newPi> for Pi 2 or 3. Returns true on success, false on failure. --------------------------------------------------------------------------- } function trpiGPIO.initialise(newPi: boolean): boolean; var gpio_base, clock_base, gpio_pwm: int64; begin if self.initialised then begin raise exception.create('trpiGPIO.initialise: Already initialised'); end; { Open the GPIO memory file, this should work as non root as long as the account is a member of the gpio group } result := false; self.gpiofd := fpopen('/dev/gpiomem', O_RDWR or O_SYNC); if self.gpiofd < 0 then begin exit; end; if newPi then begin clock_base := RPIGPIO_PI2_REG_START + $101; gpio_base := RPIGPIO_PI2_REG_START + $200; gpio_pwm := RPIGPIO_PI2_REG_START + $20C; end else begin clock_base := RPIGPIO_PI1_REG_START + $101; gpio_base := RPIGPIO_PI1_REG_START + $200; gpio_pwm := RPIGPIO_PI1_REG_START + $20C; end; gpioptr := fpmmap(nil, RPIGPIO_FPMAP_PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, self.gpiofd, gpio_base); if not assigned(gpioptr) then begin exit; end; clkptr := fpmmap(nil, RPIGPIO_FPMAP_PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, self.gpiofd, clock_base); if not assigned(clkptr) then begin exit; end; pwmptr := fpmmap(nil, RPIGPIO_FPMAP_PAGE_SIZE, PROT_READ or PROT_WRITE, MAP_SHARED, self.gpiofd, gpio_pwm); if not assigned(pwmptr) then begin exit; end; self.initialised := true; result := true; end; { --------------------------------------------------------------------------- Shut down the GPIO driver. --------------------------------------------------------------------------- } procedure trpiGPIO.shutdown; begin if not self.initialised then begin exit; end; if assigned(self.gpioptr) then begin fpmunmap(self.gpioptr, RPIGPIO_FPMAP_PAGE_SIZE); self.gpioptr := nil; end; if assigned(self.clkptr) then begin fpmunmap(self.clkptr, RPIGPIO_FPMAP_PAGE_SIZE); self.clkptr := nil; end; if assigned(self.pwmptr) then begin fpmunmap(self.pwmptr, RPIGPIO_FPMAP_PAGE_SIZE); self.pwmptr := nil; end; self.initialised := false; end; { --------------------------------------------------------------------------- Set pin mode. <mode> can be one of: RPIGPIO_INPUT RPIGPIO_OUTPUT RPIGPIO_PWM_OUTPUT --------------------------------------------------------------------------- } procedure trpiGPIO.setPinMode(pin, mode: byte); var fsel, shift, alt: byte; gpiof, clkf, pwmf: ^longword; begin fsel := (pin div 10) * 4; shift := (pin mod 10) * 3; gpiof := pointer(longword(self.gpioptr) + fsel); if (mode = RPIGPIO_INPUT) then begin gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)); end else if (mode = RPIGPIO_OUTPUT) then begin gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) or (1 shl shift); end else if (mode = RPIGPIO_PWM_OUTPUT) then begin { Take care of the correct alternate pin mode } case pin of 12, 13, 40, 41, 45: begin alt := 4; end; 18, 19: begin alt := 2; end; else begin alt := 0; { Should throw an error here really as PWM is not allowed on this pin } end; end; If alt > 0 then begin gpiof^ := gpiof^ and ($FFFFFFFF - (7 shl shift)) or (alt shl shift); clkf := pointer(longword(self.clkptr) + RPIGPIO_PWMCLK_CNTL); clkf^ := $5A000011 or (1 shl 5); delayNanoseconds(200); clkf := pointer(longword(self.clkptr) + RPIGPIO_PWMCLK_DIV); clkf^ := $5A000000 or (32 shl 12); clkf := pointer(longword(self.clkptr) + RPIGPIO_PWMCLK_CNTL); clkf^ := $5A000011; self.clearPin(pin); pwmf := pointer(longword(self.pwmptr) + RPIGPIO_PWM_CONTROL); pwmf^ := 0; delayNanoseconds(200); pwmf := pointer(longword(self.pwmptr) + RPIGPIO_PWM0_RANGE); pwmf^ := $400; delayNanoseconds(200); pwmf := pointer(longword(self.pwmptr) + RPIGPIO_PWM1_RANGE); pwmf^ := $400; delayNanoseconds(200); { Enable PWMs } pwmf := pointer(longword(self.pwmptr) + RPIGPIO_PWM0_DATA); pwmf^ := 0; pwmf := pointer(longWord(self.pwmptr) + RPIGPIO_PWM1_DATA); pwmf^ := 0; pwmf := pointer(longword(self.pwmptr) + RPIGPIO_PWM_CONTROL); pwmf^ := RPIGPIO_PWM0_ENABLE or RPIGPIO_PWM1_ENABLE; end; end; end; { --------------------------------------------------------------------------- Read the state of <pin>. Returns true if it is high, false if it is low. --------------------------------------------------------------------------- } function trpiGPIO.readPin(pin: byte): boolean; inline; var gpiof: ^longword; begin gpiof := pointer(longword(self.gpioptr) + 52 + (pin shr 5) shl 2); if (gpiof^ and (1 shl pin)) = 0 then begin result := false; end else begin result := true; end; end; { --------------------------------------------------------------------------- Set the state of <pin> to cleared (low). --------------------------------------------------------------------------- } procedure trpiGPIO.clearPin(pin: byte); inline; var gpiof : ^longword; begin gpiof := pointer(longword(self.gpioptr) + 40 + (pin shr 5) shl 2); gpiof^ := 1 shl pin; end; { --------------------------------------------------------------------------- Set the state of <pin> to set (high). --------------------------------------------------------------------------- } procedure trpiGPIO.setPin(pin: byte); inline; var gpiof: ^longword; begin gpiof := pointer(longword(self.gpioptr) + 28 + (pin shr 5) shl 2); gpiof^ := 1 shl pin; end; { --------------------------------------------------------------------------- Set pullup / pulldown mode. <mode> can be one of: RPIGPIO_PUD_OFF - no pullup or pulldown RPIGPIO_PUD_DOWN - weak pulldown RPIGPIO_PUD_UP - weak pullup --------------------------------------------------------------------------- } procedure trpiGPIO.setPullupMode(pin, mode: byte); var pudf, pudclkf: ^longword; begin pudf := pointer(longword(self.gpioptr) + 148); pudf^ := mode; delayNanoseconds(200); pudclkf := pointer(longword(self.gpioptr) + 152 + (pin shr 5) shl 2); pudclkf^ := 1 shl pin; delayNanoseconds(200); pudf^ := 0; pudclkf^ := 0; end; { --------------------------------------------------------------------------- Set the PWM value for <pin>. <value> is from 0 - 1023. --------------------------------------------------------------------------- } procedure trpiGPIO.PWMWrite(pin: byte; value: longword); inline; var pwmf : ^longword; port : byte; begin case pin of 12, 18, 40: begin port := RPIGPIO_PWM0_DATA; end; 13, 19, 41, 45: begin port := RPIGPIO_PWM1_DATA; end; else begin { Should throw an exception here really } exit; end; end; pwmf := pointer(longword(self.pwmptr) + port); pwmf^ := value and $FFFFFBFF; // $400 complemens end; { --------------------------------------------------------------------------- --------------------------------------------------------------------------- } end.
library lib; {$mode objfpc}{$H+} uses ShareMem, SysUtils, Classes, uBase, ulibrary, uLibraryCls, uSaxBase, uLibrarySaxParser, uLibraryBuilder, uModuleBuilder, uLibrarySerializer; var L: ILibrary; function GetLibrary(const aFileNames: array of string): ILibrary; export; begin if L = nil then with TLibraryFactory.Create do try L := GetLibrary(aFileNames); finally Free; end; Result := L; end; procedure CloseLibrary; export; begin L := nil; end; function GetNewGuid: String; export; var Guid: TGuid; StartChar: Integer; EndChar: Integer; Count: Integer; begin CreateGuid(Guid); Result := GuidToString(Guid); StartChar := Pos('{', Result) + 1; EndChar := Pos('}', Result) - 1; Count := EndChar - StartChar + 1; Result := Copy(Result, StartChar, Count); end; procedure SaveLibrary(const aLibrary: ILibrary); export; var Serializer: TLibrarySerializer; begin Serializer := TLibrarySerializer.Create; try Serializer.Serialize(aLibrary); finally Serializer.Free; end; end; exports GetLibrary, SaveLibrary, CloseLibrary, GetNewGuid; {$R *.res} begin end.
{============================================================================== Iris Model Editor - Copyright by Alexander Oster, tensor@ultima-iris.de 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. ==============================================================================} unit Unit_TileDataLoader; interface uses Classes, Contnrs, SysUtils; type TTileDataFileEntry = packed record Flags: Cardinal; Weight: Byte; Quality: Byte; Unknown1: SmallInt; Unknown2: Byte; Quantity: Byte; Animation: SmallInt; Unknown3: Byte; Hue: Byte; Unknown4: Byte; Unknown5: Byte; Height: Byte; Name: array[0..19] of Char; end; TTileDataEntryBuffer = packed record Header: Integer; Entries: array[0..31] of TTileDataFileEntry; end; TTileDataEntry = class (TObject) private FFlags: Cardinal; FWeight: Byte; FQuality: Byte; FAnimation: SmallInt; FHue: Byte; FQuantity: Byte; FHeight: Byte; FName: String; public property Flags: Cardinal read FFlags; property Weight: Byte read FWeight; property Quality: Byte read FQuality; property Animation: SmallInt read FAnimation; property Hue: Byte read FHue; property Height: Byte read FHeight; property Name: String read FName; property Quantity: Byte read FQuantity; constructor Create (AFileEntry: TTileDataFileEntry); end; TTileDataLoader = class (TObject) private FEntries: TObjectList; function GetCount: Integer; function Get (Index: Integer): TTileDataEntry; public property Count: Integer read GetCount; property Items[Index: Integer]: TTileDataEntry read Get; default; constructor Create (FileName: String); destructor Destroy; override; end; var pTileDataLoader: TTileDataLoader; implementation constructor TTileDataEntry.Create (AFileEntry: TTileDataFileEntry); var AArray: array[0..21] of Char; begin FillChar (AArray, 21, 0); Move (AFileEntry.Name, AArray, 20); FFlags := AFileEntry.Flags; FWeight := AFileEntry.Weight; FQuality := AFileEntry.Quality; FAnimation := AFileEntry.Animation; FHue := AFileEntry.Hue; FHeight := AFileEntry.Height; FQuantity := AFileEntry.Quantity; SetString(FName, AArray, StrLen (AArray)); end; constructor TTileDataLoader.Create (FileName: String); var Stream: TStream; Index, EntryIndex: Integer; Count: Integer; Buffer: TTileDataEntryBuffer; begin FEntries := TObjectList.Create; Stream := TFileStream.Create (FileName, fmOpenRead or fmShareDenyWrite); try Stream.Position := 512 * (4 + 32 * 26); if (Stream.Size - Stream.Position) <> 512 * sizeof (TTileDataEntryBuffer) then raise Exception.Create ('Invalid TileData File'); Count := (Stream.Size - Stream.Position) div sizeof (TTileDataEntryBuffer); FEntries.Capacity := Count * 32; For Index := 0 to Count - 1 do begin Stream.Read (Buffer, sizeof (Buffer)); For EntryIndex := 0 to 31 do FEntries.Add (TTileDataEntry.Create (Buffer.Entries[EntryIndex])); end; finally Stream.Free; end; end; destructor TTileDataLoader.Destroy; begin FEntries.Free; FEntries := nil; end; function TTileDataLoader.GetCount: Integer; begin result := FEntries.Count; end; function TTileDataLoader.Get (Index: Integer): TTileDataEntry; begin result := FEntries[Index] as TTileDataEntry; end; initialization pTileDataLoader := nil; finalization pTileDataLoader.Free; pTileDataLoader := nil; end.
unit uBitsWinAPI; interface /// <summary> /// Register custom URI Handler by writing to the Registry. /// Writing requires elevated user rights. /// (Writing will only occur if its actually needed). /// <param name="sScheme">URI scheme (without ":")</param> /// <param name="sName"> scheme name "URL:" + sName </param> /// <param name="sFullAppPath">Full path to the target application</param> /// </summary> function RegisterURIScheme(const sScheme, sName, sFullAppPath:string): boolean; /// <summary> /// Execute a CMD command and wait for the process to finish /// </summary> function ExecAndWait(const CommandLine: string) : Boolean; implementation uses Registry, SysUtils, Windows; function RegisterURIScheme(const sScheme, sName, sFullAppPath:string): boolean; var Reg : TRegistry; bOK : Boolean; i : integer; paths : TArray<string>; procedure WriteIfNeeded(sKey, sValue:string); begin if Reg.ValueExists(sKey) then begin if Reg.ReadString(sKey).Equals(sValue) then exit; end; reg.Access := KEY_WRITE; Reg.WriteString(sKey, sValue); end; { HKEY_CLASSES_ROOT alert (Default) = "URL:Alert Protocol" URL Protocol = "" DefaultIcon (Default) = "alert.exe,1" shell open command (Default) = "C:\Program Files\Alert\alert.exe" "%1" as per: https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85) } begin result := false; // first subkey (scheme name, without ":") paths := [lowercase(sScheme)] + ['shell','open','command']; Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := HKEY_CLASSES_ROOT; for i := 0 to high(paths) do begin if (not reg.KeyExists(paths[i])) then begin // write if needed reg.Access := KEY_WRITE; bOK := reg.OpenKey(paths[i], True); end else begin // open otherwise bOK := reg.OpenKey(paths[i], false); end; if not bOK then exit; case i of 0: begin // default value WriteIfNeeded('', 'URL:' + sName); // declares custom pluggable protocol handler. // Without this key, the handler application will not launch. // The value should be an empty string. WriteIfNeeded('URL Protocol', ''); // optional add an icon of target application try if (not reg.KeyExists('DefaultIcon')) then reg.Access := KEY_WRITE; reg.OpenKey('DefaultIcon', true); WriteIfNeeded('', 'shell32.dll,26'); finally reg.CloseKey; reg.OpenKey(paths[0], True); end; end; 3: begin WriteIfNeeded('', '"' + sFullAppPath + '" "%1"'); end; end; end; result := true; reg.CloseKey(); finally Reg.Free; end; end; {******************************************************************************} function ExecAndWait(const CommandLine: string) : Boolean; var StartupInfo : TStartupInfo; // start-up info passed to process ProcessInfo : TProcessInformation; // info about the process ProcessExitCode : DWord; // process's exit code begin // Set default error result Result := False; // Initialise startup info structure to 0, and record length FillChar(StartupInfo, SizeOf(StartupInfo), 0); StartupInfo.cb := SizeOf(StartupInfo); // Execute application commandline if CreateProcess(nil, PChar('C:\\windows\\system32\\cmd.exe /C ' + CommandLine), nil, nil, False, 0, nil, nil, StartupInfo, ProcessInfo) then begin try // Wait for application to complete if WaitForSingleObject(ProcessInfo.hProcess, INFINITE) = WAIT_OBJECT_0 then // It's completed - get its exit code if GetExitCodeProcess(ProcessInfo.hProcess, ProcessExitCode) then // Check exit code is zero => successful completion if ProcessExitCode = 0 then Result := True; finally // Tidy up CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); end; end; end; end.
// Fit4Delphi Copyright (C) 2008. Sabre Inc. // This program is free software; you can redistribute it and/or modify it under // the terms of the GNU General Public License as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along with this program; // if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // Ported to Delphi by Michal Wojcik. // // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under the terms of the GNU General Public License version 2 or later. unit ResponseParserTest; interface uses classes, TestFramework, InputStream; type TResponseParserTest = class(TTestCase) private input : TInputStream; response : string; public class procedure main(args : TStringList); published procedure testParsing(); procedure testChunkedResponse(); end; implementation uses ResponseParser, TestRunner, ByteArrayInputStream; { TResponseParserTest } class procedure TResponseParserTest.main(args : TStringList); var arg : TStringList; begin arg := TStringList.Create; arg.Add('ResponseParserTest'); TTestRunner.main(arg); arg.Free; end; procedure TResponseParserTest.testParsing(); var parser : TResponseParser; begin response := 'HTTP/1.1 200 OK'#13#10 + 'Content-Type: text/html'#13#10 + 'Content-Length: 12'#13#10 + 'Cache-Control: max-age=0'#13#10 + #13#10 + 'some content'; input := TByteArrayInputStream.Create(response {.getBytes()}); parser := TResponseParser.Create(input); CheckEquals(200, parser.getStatus()); CheckEquals('text/html', parser.getHeader('Content-Type')); CheckEquals('some content', parser.getBody()); end; procedure TResponseParserTest.testChunkedResponse(); var parser : TResponseParser; begin response := 'HTTP/1.1 200 OK'#13#10 + 'Content-Type: text/html'#13#10 + 'Transfer-Encoding: chunked'#13#10 + #13#10 + '3'#13#10 + '123'#13#10 + '7'#13#10 + '4567890'#13#10 + '0'#13#10 + 'Tail-Header: TheEnd!'#13#10; input := TByteArrayInputStream.Create(response {.getBytes()}); parser := TResponseParser.Create(input); CheckEquals(200, parser.getStatus()); CheckEquals('text/html', parser.getHeader('Content-Type')); CheckEquals('1234567890', parser.getBody()); CheckEquals('TheEnd!', parser.getHeader('Tail-Header')); end; initialization TestFramework.RegisterTest(TResponseParserTest.Suite); end.
namespace com.remobjects.beta; interface uses java.util, android.app, android.content, android.os, android.support.v4.app, android.util, android.view, android.widget, com.remobjects.dataabstract.data, com.remobjects.dataabstract.util; type ClientEditActivity = public class(Activity) public class CLIENT_ROWID: String := '_id'; readonly; class ACTIVITY_ACTION: String := 'action'; readonly; class ACTIVITY_ACTION_CREATE: Integer := RESULT_FIRST_USER +1; readonly; class ACTIVITY_ACTION_EDIT: Integer := RESULT_FIRST_USER + 2; readonly; private fAction: Integer := - 1; fRowId: nullable Long; fDataAccess: DataAccess; fRow: DataRow; etName, etPhone: EditText; etAddress: EditText; etDiscount: EditText; etInfo: EditText; method populateFields; method saveState; method getStringValueFromCell(aColumnName: String): String; method getStringValueFromCell(aColumnName: String; aDefaultValue: String): String; method setStringValueToCell(aColumnName: String; aValue: String); public method onCreate(aSavedInstanceState: Bundle); override; method btConfirmClick(view: View); method onCreateOptionsMenu(aMenu: Menu): Boolean; override; method onMenuItemSelected(featureId: Integer; item: MenuItem): Boolean; override; end; implementation method ClientEditActivity.onCreate(aSavedInstanceState: Bundle); begin inherited onCreate(aSavedInstanceState); setContentView(R.layout.activity_edit); fDataAccess := DataAccess.getInstance; var lSubTitleId: Integer; var extras: Bundle := self.Intent.Extras; fAction := extras.getInt(ACTIVITY_ACTION, - 1); if ((fAction <> ACTIVITY_ACTION_CREATE) and (fAction <> ACTIVITY_ACTION_EDIT)) then begin Toast.makeText(self, java.lang.String.format('wrong activity action: %s', fAction), Toast.LENGTH_LONG).show(); setResult(RESULT_CANCELED); exit; end else lSubTitleId := (if (fAction = ACTIVITY_ACTION_CREATE) then R.string.activity_subtitle_edit_add else R.string.activity_subtitle_edit_update); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) then begin self.ActionBar.DisplayHomeAsUpEnabled := true; self.ActionBar.setSubtitle(lSubTitleId); end else self.Title := java.lang.String.format('%s: %s', self.String[R.string.activity_title], self.String[lSubTitleId]); fRowId := iif(assigned(aSavedInstanceState), nullable Long(aSavedInstanceState.getSerializable(CLIENT_ROWID)), nil); if (fRowId = nil) then fRowId := iif(assigned(extras), Long.valueOf(extras.getLong(CLIENT_ROWID)), nil); etName := EditText(findViewById(R.id.edit_et_name)); etPhone := EditText(findViewById(R.id.edit_et_phone)); etAddress := EditText(findViewById(R.id.edit_et_address)); etDiscount := EditText(findViewById(R.id.edit_et_discount)); etInfo := EditText(findViewById(R.id.edit_et_additionalinfo)); populateFields; end; method ClientEditActivity.onCreateOptionsMenu(aMenu: Menu): Boolean; begin MenuInflater.inflate(R.menu.edit, aMenu); exit (true); end; method ClientEditActivity.onMenuItemSelected(featureId: Integer; item: MenuItem): Boolean; begin case (item.ItemId) of android.R.id.home: begin NavUtils.navigateUpTo(self, new Intent(self, typeOf(MainActivity))); exit (true); end; R.id.menu_settings: begin self.startActivity(new Intent(self, typeOf(SettingsActivity))); exit (true); end else exit inherited onMenuItemSelected(featureId, item); end end; method ClientEditActivity.populateFields; begin case (fAction) of ACTIVITY_ACTION_EDIT: begin try fRow := fDataAccess.data.viewClients.Row[fRowId.intValue()]; except on ex: Exception do begin Log.e(self.Class.SimpleName, ex.Message); end end; etName.setText(getStringValueFromCell('ClientName')); etPhone.setText(getStringValueFromCell('ContactPhone')); etAddress.setText(getStringValueFromCell('ContactAddress')); etDiscount.setText(getStringValueFromCell('ClientDiscount')); etInfo.setText(getStringValueFromCell('AdditionalInfo')); end; ACTIVITY_ACTION_CREATE: begin var lData: array of Object := [(('{' + UUID.randomUUID().toString()) + '}'), '<new client name here>', nil, nil, nil, 0.0]; fRow := fDataAccess.data.tableClients.loadDataRow(lData); end; end; etName.setText(getStringValueFromCell('ClientName')); etPhone.setText(getStringValueFromCell('ContactPhone', nil)); etAddress.setText(getStringValueFromCell('ContactAddress', nil)); etDiscount.setText(getStringValueFromCell('ClientDiscount')); etInfo.setText(getStringValueFromCell('AdditionalInfo', nil)); end; method ClientEditActivity.saveState; begin setStringValueToCell('ClientName', etName.getText().toString()); setStringValueToCell('ContactPhone', etPhone.getText().toString()); setStringValueToCell('ContactAddress', etAddress.getText().toString()); setStringValueToCell('ClientDiscount', etDiscount.getText().toString()); setStringValueToCell('AdditionalInfo', etInfo.getText().toString()) end; method ClientEditActivity.getStringValueFromCell(aColumnName: String): String; begin exit getStringValueFromCell(aColumnName, '') end; method ClientEditActivity.getStringValueFromCell(aColumnName: String; aDefaultValue: String): String; begin var lValue: Object := fRow.Field[aColumnName]; exit (iif(assigned(lValue), lValue.toString, aDefaultValue)); end; method ClientEditActivity.setStringValueToCell(aColumnName: String; aValue: String); begin var lType: &Class; try lType := fDataAccess.data.tableClients.Columns.Column[aColumnName].DataType; except on ex: Exception do begin Log.wtf(self.Class.SimpleName, ex.Message + ' Stack: ' + ex.StackTrace); lType := typeOf(Object); end end; var lOriginalValue: Object := fRow.Field[aColumnName]; if (lType = typeOf(String)) then begin if (not StringUtils.isNullOrEmpty(java.lang.String(lOriginalValue)) or (not StringUtils.isNullOrEmpty(aValue))) then begin fRow.Field[aColumnName] := aValue; end; exit; end; if (lType = typeOf(java.lang.Double)) then begin fRow.Field[aColumnName] := java.lang.Double.valueOf(aValue); exit; end; if (lType = typeOf(java.lang.Float)) then begin fRow.Field[aColumnName] := java.lang.Float.valueOf(aValue); exit; end end; method ClientEditActivity.btConfirmClick(view: View); begin saveState(); self.setResult(RESULT_OK); finish(); end; end.
unit ConfigVoz; interface type TConfigVoz = class private function GetActiva: integer; function GetVelocidad: integer; function GetVolumen: integer; procedure SetActiva(const Value: integer); procedure SetVelocidad(const Value: integer); procedure SetVolumen(const Value: integer); public property Velocidad: integer read GetVelocidad write SetVelocidad; property Volumen: integer read GetVolumen write SetVolumen; property Activa: integer read GetActiva write SetActiva; end; implementation uses dmConfiguracion; const SECCION: string = 'Configuracion.Voz'; { TConfigVoz } function TConfigVoz.GetActiva: integer; begin result := Configuracion.ReadInteger(SECCION, 'Activa', 0); end; function TConfigVoz.GetVelocidad: integer; begin result := Configuracion.ReadInteger(SECCION, 'Velocidad', 0); end; function TConfigVoz.GetVolumen: integer; begin result := Configuracion.ReadInteger(SECCION, 'Volumen', 100); end; procedure TConfigVoz.SetActiva(const Value: integer); begin Configuracion.WriteInteger(SECCION, 'Activa', Value); end; procedure TConfigVoz.SetVelocidad(const Value: integer); begin Configuracion.WriteInteger(SECCION, 'Velocidad', Value); end; procedure TConfigVoz.SetVolumen(const Value: integer); begin Configuracion.WriteInteger(SECCION, 'Volumen', Value); end; end.
unit FeCFDv32; interface uses Xmldom, XMLDoc, XMLIntf, FeCFD, FeCFDv2, FeCFDv22, FETimbreFiscalDigital; type // Creamos el comprobante que hereda la v2.2 IFEXMLComprobanteV32 = interface(IFEXMLComprobanteV22) ['{E00E28F4-899F-4236-8AF4-897FF5C973E6}'] { Property Accessors } end; { TXMLIFEXMLComprobante } TXMLIFEXMLComprobanteV32 = class(TXMLIFEXMLComprobanteBaseV22, IFEXMLComprobanteV32) public end; function GetComprobanteV32(Doc: IXMLDocument): IFEXMLComprobanteV32; function LoadComprobanteV32(const FileName: string): IFEXMLComprobanteV32; function NewComprobanteV32: IFEXMLComprobanteV32; const TargetNamespace = 'http://www.sat.gob.mx/cfd/3'; implementation { Global Functions } function GetComprobanteV32(Doc: IXMLDocument): IFEXMLComprobanteV32; begin Result := Doc.GetDocBinding('cfdi:Comprobante', TXMLIFEXMLComprobanteV32, TargetNamespace) as IFEXMLComprobanteV32; end; function LoadComprobanteV32(const FileName: string): IFEXMLComprobanteV32; begin Result := LoadXMLDocument(FileName).GetDocBinding('Comprobante', TXMLIFEXMLComprobanteV32, TargetNamespace) as IFEXMLComprobanteV32; end; function NewComprobanteV32: IFEXMLComprobanteV32; begin Result := NewXMLDocument.GetDocBinding('Comprobante', TXMLIFEXMLComprobanteV32, TargetNamespace) as IFEXMLComprobanteV32; end; end.
unit CABFile; interface uses SysUtils, Classes; type ECABError = class (Exception); TCabinet = class (TComponent) private fCABFileName: String; fFileList: TStringList; fFileCount: Integer; procedure Clear; function GetFileName (Index: Integer): String; function GetFileSize (Index: Integer): String; function GetFileDate (Index: Integer): String; procedure SetCABFileName (const Value: String); public constructor Create (AOwner: TComponent); override; destructor Destroy; override; property CABFileName: String read fCABFileName write SetCABFileName; property FileCount: Integer read fFileCount; property FileName [Index: Integer]: string read GetFileName; default; property FileSize [Index: Integer]: string read GetFileSize; property FileDate [Index: Integer]: string read GetFileDate; end; implementation uses CABAPI; // TCabinet function GetField (S: String; Num: Integer): String; var Idx: Integer; begin while Num > 0 do begin Idx := Pos ('|', S); if Idx > 0 then Delete (S, 1, Idx); Dec (Num); end; Idx := Pos ('|', S); if Idx > 0 then Delete (S, Idx, MaxInt); Result := S; end; constructor TCabinet.Create (AOwner: TComponent); begin Inherited Create (AOwner); fFileList := TStringList.Create; end; destructor TCabinet.Destroy; begin Clear; fFileList.Free; Inherited Destroy; end; procedure TCabinet.Clear; begin fCABFileName := ''; fFileList.Clear; end; procedure TCabinet.SetCABFileName (const Value: String); begin Clear; if not FileExists (Value) then raise ECABError.Create ('Specified CAB file not found') else if not CABIsFile (Value) then raise ECABError.Create ('Not a valid CAB file') else if CABIsMultiPart (Value) then raise ECABError.Create ('Multi-part CAB files not supported') else begin fCABFileName := Value; fFileCount := CABGetFileCount (fCABFileName); CABGetFileList (fCABFileName, fFileList); end; end; function TCabinet.GetFileName (Index: Integer): String; begin if (Index >= 0) and (Index <= fFileCount) then Result := GetField (fFileList [Index], 0); end; function TCabinet.GetFileSize (Index: Integer): String; begin if (Index >= 0) and (Index <= fFileCount) then Result := GetField (fFileList [Index], 1); end; function TCabinet.GetFileDate (Index: Integer): String; begin if (Index >= 0) and (Index <= fFileCount) then Result := FormatDateTime ('', FileDateToDateTime (StrToInt (GetField (fFileList [Index], 2)))); end; end.
unit BoardSettings; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Project; type TBoardSettingsForm = class(TForm) OKTButton: TButton; CancelTButton: TButton; Label1: TLabel; WidthTEdit: TEdit; MinWidthTLabel: TLabel; MinHeightTLabel: TLabel; HeightTEdit: TEdit; Label6: TLabel; WarningTLabel: TLabel; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FProject : TveProject; RequiredLeft, RequiredRight, RequiredTop, RequiredBottom : integer; public { Public declarations } property Project : TveProject read FProject write FProject; end; var BoardSettingsForm: TBoardSettingsForm; implementation {$R *.DFM} uses ProjectCheck, BoardSize, Math, Board; procedure TBoardSettingsForm.FormShow(Sender: TObject); var TrackMinWidth, TrackMinHeight : integer; Board : TbrBoard; begin // hide warning label WarningTLabel.Caption := ''; // Board := FProject.Board; // display current width and height WidthTEdit.Text := IntToStr( Board.Width ); HeightTEdit.Text := IntToStr( Board.Height ); // find minimum board size required to hold tracks RequiredStripArea( Project, TrackMinWidth, TrackMinHeight ); // find rectangle holding all components CalcRequiredBoardRectangle( Project, RequiredLeft, RequiredRight, RequiredTop, RequiredBottom ); // combine track and component required dimensions RequiredRight := Max( RequiredRight, TrackMinWidth ); RequiredBottom := Max( RequiredBottom, TrackMinHeight ); // display minimum board size required to hold components and tracks MinWidthTLabel.Caption := Format( '(Min %d)', [RequiredRight] ); MinHeightTLabel.Caption := Format( '(Min %d)', [RequiredBottom] ); end; procedure TBoardSettingsForm.FormClose(Sender: TObject; var Action: TCloseAction); var Width, Height : integer; Board : TbrBoard; begin // if escaping form if ModalResult <> mrOK then begin exit; end; // remove any previous warning WarningTLabel.Caption := ''; // Board := FProject.Board; // read user entered board dimensions try Width := StrToInt( WidthTEdit.Text ); Height := StrToInt( HeightTEdit.Text ); except WarningTLabel.Caption := 'Only numerals allowed!'; Action := caNone; exit; end; // check if board wide enough to fit components if Width < RequiredRight then begin WarningTLabel.Caption := Format('X must be at least %d', [RequiredRight]); Action := caNone; exit; end; // check if board high enough to fit components if Height < RequiredBottom then begin WarningTLabel.Caption := Format('Y must be at least %d', [RequiredBottom]); Action := caNone; exit; end; // implement user entered values - FProject may reduce these values // if too big. Board.Width := StrToInt( WidthTEdit.Text ); Board.Height := StrToInt( HeightTEdit.Text ); // built-in patterns always fill the board area, so recalculate strips if Board.Pattern <> ptDefined then begin FProject.Board.Clear; FProject.Board.Prepare; end; // Move any off board components back onto board so fully inside // board boundaries - these components will be left of or above // 0,0 board origin or possibly beyond max allowable height or width // of board. RescueOffBoardItems( FProject ); // undo is no longer possible, because it may move a component off board FProject.ClearUndo; end; end.
unit FH.DeckLink.Input; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Generics.Collections, Winapi.ActiveX, System.syncobjs, DeckLinkAPI_TLB_10_5, FH.DeckLink.InputFrame, FH.DeckLink.Utils; const MSG_ONDEBUG = 701; MSG_ONDROPFRAME = 702; MSG_ONDROPVIDEOFRAME = 703; Type TfhVer = record name : string; version : cardinal; versionStr : string; dateRelease : TDateTime; end; Const FH_DeckLink_Input_ver : TfhVer = (Name : 'FH.DeckLink.Input'; version : $01000011; versionStr : ''; dateRelease : 41534.0); type TFrameArrivedCall = reference to procedure(const videoFrame: TDeckLinkVideoInputFrame; const audioPacket: TDeckLinkAudioInputPacket; const frameIndex : Int64); type TDeckLinkInput = class(TInterfacedObject, IDeckLinkInputCallback) private FRefCount : integer; FDeckLink : IDeckLink; FDeckLinkInput : IDeckLinkInput; FDeckLinkConfiguration : IDeckLinkConfiguration; FDeckLinkAttributes : IDeckLinkAttributes; FDeckLinkStatus : IDeckLinkStatus; FCapturing : boolean; (* video *) FInputFlags : _BMDVideoInputFlags; FDisplayMode : _BMDDisplayMode; FPixelFormat : _BMDPixelFormat; (* audio *) FSampleRate : _BMDAudioSampleRate; FSampleType : _BMDAudioSampleType; FChannelCount : integer; (* Main *) FDetectionInputMode : boolean; FLock : TCriticalSection; FOnFrameArrived : TFrameArrivedCall; FOnStartCapture : TNotifyEvent; FOnStopCapture : TNotifyEvent; FOnDropVideoFrame : TNotifyEvent; FOnDropFrame : TNotifyEvent; FOnDebug : TGetStrProc; FLastDebugStr : string; procedure OnDebugEvents(var msg: dword); message MSG_ONDEBUG; procedure DoDebug(const str: string); procedure DoDropFrame; procedure OnDropFrameEvents(var msg: dword); message MSG_ONDROPFRAME; procedure DoDropVideoFrame; procedure OnDropVideoFrameEvents(var msg: dword); message MSG_ONDROPVIDEOFRAME; Function GetVersion : TfhVer; Procedure DoFrameArrived(const videoFrame: TDeckLinkVideoInputFrame; const audioPacket: TDeckLinkAudioInputPacket; const frameIndex : Int64); function GetDeckLinkDisplayMode: IDeckLinkDisplayMode; Function GetModeList: TArray<IDeckLinkDisplayMode>; Function GetPixelFormatList: TArray<_BMDPixelFormat>; function GetVideoConnections: TArray<_BMDVideoConnection>; function GetAudioConnections: TArray<_BMDAudioConnection>; function GetSampleRates: TArray<_BMDAudioSampleRate>; function GetSampleTypes: TArray<_BMDAudioSampleType>; function GetChannelCounts: TArray<integer>; public constructor Create(ADevie: IDeckLink = nil); overload; destructor Destroy; override; procedure SetParams(AName: string; AValue: integer); overload; procedure SetParams(AName: string; AValue: string); overload; procedure SetParams(AName: string; AValue: boolean); overload; function GetParams(const AName: string; Out AValue: boolean): boolean; overload; function GetParams(const AName: string; Out AValue: integer): boolean; overload; function GetParams(const AName: string; Out AValue: string): boolean; overload; (* Decklink *) function SupportsFormatDetection: boolean; function GetVideoSignalLocked: boolean; function GetDetectedVideoFlags: boolean; function GetDetectedVideoMode: boolean; function GetCurrentVideoFlags: _BMDVideoInputFlags; function GetCurrentVideoPixelFormat: _BMDPixelFormat; function GetCurrentVideoMode: _BMDDisplayMode; function SupportVideoConnection(AVideoConnection: _BMDVideoConnection): boolean; function GetVideoConnection: _BMDVideoConnection; procedure SetVideoConnection(AValue: _BMDVideoConnection); function SupportAudioConnection(AAudioConnection: _BMDAudioConnection): boolean; procedure SetAudioConnection(AValue: _BMDAudioConnection); function GetAudioConnection: _BMDAudioConnection; function Init(ADeckLink: IDeckLink): boolean; function StartCapture(AScreenPreviewCallback: IDeckLinkScreenPreviewCallback = nil): boolean; procedure StopCapture(); procedure ParamsChanged(); function GetDisplayMode: _BMDDisplayMode; function GetPixelFormat: _BMDPixelFormat; (* VIDEO PROPERTY SUPPORT LIST *) property VideoConnections : TArray<_BMDVideoConnection> read GetVideoConnections; property DisplayModes : TArray<IDeckLinkDisplayMode> read GetModeList; property PixelFormats : TArray<_BMDPixelFormat> read GetPixelFormatList; (* AUDIO PROPERTY SUPPORT LIST *) property AudioConnections : TArray<_BMDAudioConnection> read GetAudioConnections; property SampleRates: TArray<_BMDAudioSampleRate> read GetSampleRates; property SampleTypes: TArray<_BMDAudioSampleType> read GetSampleTypes; property ChannelCounts: TArray<integer> read GetChannelCounts; property VideoConnection: _BMDVideoConnection read GetVideoConnection write SetVideoConnection; property DisplayMode : _BMDDisplayMode read GetDisplayMode write FDisplayMode; property PixelFormat : _BMDPixelFormat read GetPixelFormat write FPixelFormat; property AudioConnection: _BMDVideoConnection read GetAudioConnection write SetAudioConnection; property SampleRate : _BMDAudioSampleRate read FSampleRate write FSampleRate; property SampleType : _BMDAudioSampleType read FSampleType write FSampleType; property ChannelCount : integer read FChannelCount write FChannelCount; property DetectionInputMode : boolean read FDetectionInputMode write FDetectionInputMode; property IsCapturing : boolean read FCapturing; property DeckLinkInstance: IDeckLink read FDeckLink; property DeckLinkInputInstance: IDeckLinkInput read FDeckLinkInput; property DeckLinkDisplayModeInstance: IDeckLinkDisplayMode read GetDeckLinkDisplayMode; property OnFrameArrived : TFrameArrivedCall read FOnFrameArrived write FOnFrameArrived; property Version : TfhVer read GetVersion; (* Notify Event *) property OnStartCapture : TNotifyEvent read FOnStartCapture write FOnStartCapture; property OnStopCapture : TNotifyEvent read FOnStopCapture write FOnStopCapture; property OnDropFrame : TNotifyEvent read FOnDropFrame write FOnDropFrame; property OnDropVideoFrame : TNotifyEvent read FOnDropVideoFrame write FOnDropVideoFrame; property OnDebug : TGetStrProc read FOnDebug write FOnDebug; function _Release: Integer; stdcall; function _AddRef: Integer; stdcall; function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; (* IDeckLinkInputCallback methods *) function VideoInputFormatChanged(notificationEvents: _BMDVideoInputFormatChangedEvents; const newDisplayMode: IDeckLinkDisplayMode; detectedSignalFlags: _BMDDetectedVideoInputFormatFlags): HResult; stdcall; function VideoInputFrameArrived(const videoFrame: IDeckLinkVideoInputFrame; const audioPacket: IDeckLinkAudioInputPacket): HResult; stdcall; end; implementation (* TDeckLinkDevice *) constructor TDeckLinkInput.Create(ADevie: IDeckLink = nil); begin FRefCount := 1; FDeckLink := nil; FDeckLinkInput := nil; FCapturing := false; FDisplayMode := bmdModePAL; FPixelFormat := bmdFormat8BitYUV; SampleRate := bmdAudioSampleRate48kHz; SampleType := bmdAudioSampleType16bitInteger; ChannelCount := 8; FDetectionInputMode := false; FLock := TCriticalSection.Create; if ADevie <> nil then begin Init(ADevie); end; end; destructor TDeckLinkInput.Destroy; var i : integer; begin if assigned(FDeckLinkInput) then FDeckLinkInput := nil; if assigned(FDeckLink) then begin FDeckLink._Release; FDeckLink := nil; end; FreeAndNil(FLock); inherited; end; function TDeckLinkInput.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TDeckLinkInput._AddRef: Integer; begin result := InterlockedIncrement(FRefCount); end; function TDeckLinkInput._Release: Integer; var newRefValue : integer; begin newRefValue := InterlockedDecrement(FRefCount); if (newRefValue = 0) then begin result := 0; exit; end; result := newRefValue; end; procedure TDeckLinkInput.SetParams(AName: string; AValue: integer); begin if SameText('_BMDDisplayMode', AName) then begin DisplayMode := _BMDDisplayMode(AValue); end else if SameText('_BMDPixelFormat', AName) then begin PixelFormat := _BMDPixelFormat(AValue); end else if SameText('_BMDAudioSampleRate', AName) then begin SampleRate := _BMDAudioSampleRate(AValue) end else if SameText('_BMDAudioSampleType', AName) then begin SampleType := _BMDAudioSampleType(AValue); end else if SameText('ChannelCount', AName) then begin if ((AValue = 2) or (AValue = 8) or (AValue = 16)) then ChannelCount := AValue else raise Exception.Create('Incorect ChannelCount params'); end else if SameText('DetectionInputMode', AName) then begin FDetectionInputMode := boolean(AValue); end else raise Exception.Create('Error Message'); end; procedure TDeckLinkInput.SetParams(AName: string; AValue: string); begin if AValue.IsEmpty then exit; if SameText('bmdVideoConnection', AName) then begin VideoConnection := TBMDConverts.BMDVideoConnection(AValue).BMD; end else if SameText('bmdDisplayMode', AName) then begin DisplayMode := TBMDConverts.BMDDisplayMode(AValue).BMD; end else if SameText('bmdPixelFormat', AName) then begin PixelFormat := TBMDConverts.BMDPixelFormat(AValue).BMD; end else if SameText('bmdAudioConnection', AName) then begin AudioConnection := TBMDConverts.BMDAudioConnection(AValue).BMD; end else if SameText('bmdAudioSampleRate', AName) then begin SampleRate := TBMDConverts.BMDAudioSampleRate(AValue).BMD; end else if SameText('bmdAudioSampleType', AName) then begin SampleType := TBMDConverts.BMDAudioSampleType(AValue).BMD; end else if SameText('bmdChannelCount', AName) then begin ChannelCount := strtoint(AValue); end else if SameText('bmdVideoInputFlags', AName) then begin if SameText('true', AValue) then DetectionInputMode := true else DetectionInputMode := false end else raise Exception.Create('Error Message'); end; procedure TDeckLinkInput.SetParams(AName: string; AValue: boolean); begin if SameText('bmdVideoInputFlags', AName) then begin DetectionInputMode := AValue; end else raise Exception.Create('Error Message'); end; function TDeckLinkInput.GetParams(const AName: string; Out AValue: boolean): boolean; begin result := false; if SameText('DetectionInputMode', AName) then begin AValue := DetectionInputMode; result:= true; end else if SameText('SupportsDetectionInputMode', AName) then begin result:= true; end; end; function TDeckLinkInput.GetParams(const AName: string; Out AValue: integer): boolean; begin result := false; end; function TDeckLinkInput.GetParams(const AName: string; Out AValue: string): boolean; begin result := false; end; function TDeckLinkInput.GetVideoConnection: _BMDVideoConnection; var LHr : HResult; LValueInt : int64; begin (* Get current VideoInput Connection *) LHr := FDeckLinkConfiguration.GetInt(bmdDeckLinkConfigVideoInputConnection, LValueInt); case LHr of S_OK: begin result := _BMDVideoConnection(LValueInt); end; E_FAIL: raise Exception.CreateFmt('Could not get bmdDeckLinkConfigVideoInputConnection - result = %08x', [LHr]); end; end; procedure TDeckLinkInput.SetVideoConnection(AValue: _BMDVideoConnection); var LHr : HResult; begin (* Set current VideoInput Connection *) LHr := FDeckLinkConfiguration.SetInt(bmdDeckLinkConfigVideoInputConnection, AValue); case LHr of E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkConfigVideoInputConnection - result = %08x', [LHr]); end; end; function TDeckLinkInput.GetAudioConnection: _BMDAudioConnection; var LHr : HResult; LValueInt : int64; begin (* Get bmdDeckLinkConfigAudioInputConnection *) LHr := FDeckLinkConfiguration.GetInt(bmdDeckLinkConfigAudioInputConnection, LValueInt); case LHr of S_OK: begin result := _BMDAudioConnection(LValueInt); end; E_FAIL: raise Exception.CreateFmt('Could not get bmdDeckLinkConfigAudioInputConnection - result = %08x', [LHr]); end; end; procedure TDeckLinkInput.SetAudioConnection(AValue: _BMDAudioConnection); var LHr : HResult; begin (* Set bmdDeckLinkConfigAudioInputConnection *) LHr := FDeckLinkConfiguration.SetInt(bmdDeckLinkConfigAudioInputConnection, AValue); case LHr of E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkConfigAudioInputConnection - result = %08x', [LHr]); end; end; function TDeckLinkInput.SupportAudioConnection(AAudioConnection: _BMDAudioConnection): boolean; var LHr : HResult; LValueInt : int64; begin result := false; LHr := FDeckLinkAttributes.GetInt(BMDDeckLinkAudioInputConnections, LValueInt); case LHr of S_OK : begin if (LValueInt and AAudioConnection) > 0 then result := true; end; E_FAIL : begin ; end; end; end; function TDeckLinkInput.SupportVideoConnection(AVideoConnection: _BMDVideoConnection): boolean; var LHr : HResult; LValueInt : int64; begin result := false; LHr := FDeckLinkAttributes.GetInt(BMDDeckLinkVideoInputConnections, LValueInt); case LHr of S_OK : begin if (LValueInt and AVideoConnection) > 0 then result := true; end; E_FAIL : begin ; end; end; end; function TDeckLinkInput.SupportsFormatDetection: boolean; var LHr : HResult; LValueFlag : integer; begin result := false; (* Get BMDDeckLinkSupportsInputFormatDetection *) LHr := FDeckLinkAttributes.GetFlag(BMDDeckLinkSupportsInputFormatDetection, LValueFlag); case LHr of S_OK: result := Boolean(LValueFlag); E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkConfigVideoInputConnection - result = %08x', [LHr]); end; end; function TDeckLinkInput.GetVideoSignalLocked: boolean; var LHr : HResult; LValueFlag : integer; begin result := false; LHr := FDeckLinkStatus.GetFlag(bmdDeckLinkStatusVideoInputSignalLocked, LValueFlag); case LHr of S_OK: result := Boolean(LValueFlag); E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkStatusVideoInputSignalLocked - result = %08x', [LHr]); end; end; function TDeckLinkInput.GetDetectedVideoMode: boolean; var LHr : HResult; LValueFlag : integer; begin result := false; LHr := FDeckLinkStatus.GetFlag(bmdDeckLinkStatusDetectedVideoInputMode, LValueFlag); case LHr of S_OK: result := Boolean(LValueFlag); E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkStatusDetectedVideoInputMode - result = %08x', [LHr]); end; end; function TDeckLinkInput.GetDetectedVideoFlags: boolean; var LHr : HResult; LValueFlag : integer; begin result := false; LHr := FDeckLinkStatus.GetFlag(bmdDeckLinkStatusDetectedVideoInputFlags, LValueFlag); case LHr of S_OK: result := Boolean(LValueFlag); E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkStatusDetectedVideoInputFlags - result = %08x', [LHr]); end; end; function TDeckLinkInput.GetCurrentVideoMode: _BMDDisplayMode; var LHr : HResult; LValueInt : int64; begin result := 0; LHr := FDeckLinkStatus.GetInt(bmdDeckLinkStatusCurrentVideoInputMode, LValueInt); case LHr of S_OK: result := _BMDDisplayMode(LValueInt); E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkStatusCurrentVideoInputMode - result = %08x', [LHr]); end; end; function TDeckLinkInput.GetCurrentVideoPixelFormat: _BMDPixelFormat; var LHr : HResult; LValueInt : int64; begin result := 0; LHr := FDeckLinkStatus.GetInt(bmdDeckLinkStatusCurrentVideoInputPixelFormat, LValueInt); case LHr of S_OK: result := _BMDPixelFormat(LValueInt); E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkStatusCurrentVideoInputPixelFormat - result = %08x', [LHr]); end; end; function TDeckLinkInput.GetCurrentVideoFlags: _BMDVideoInputFlags; var LHr : HResult; LValueInt : int64; begin result := 0; LHr := FDeckLinkStatus.GetInt(bmdDeckLinkStatusCurrentVideoInputFlags, LValueInt); case LHr of S_OK: result := _BMDVideoInputFlags(LValueInt); E_FAIL: raise Exception.CreateFmt('Could not set bmdDeckLinkStatusCurrentVideoInputFlags - result = %08x', [LHr]); end; end; Function TDeckLinkInput.GetModeList: TArray<IDeckLinkDisplayMode>; var LDisplayModeIterator : IDeckLinkDisplayModeIterator; LDisplayMode : IDeckLinkDisplayMode; LArray : TArray<IDeckLinkDisplayMode>; begin LDisplayModeIterator := nil; LDisplayMode := nil; // GetDisplayModeIterator if (FDeckLinkInput.GetDisplayModeIterator(LDisplayModeIterator) = S_OK) then begin while (LDisplayModeIterator.Next(LDisplayMode) = S_OK) do begin SetLength(LArray, Length(LArray)+1); LArray[High(LArray)] := LDisplayMode; LDisplayMode := nil; end; if assigned(LDisplayModeIterator) then LDisplayModeIterator := nil; end; result := LArray; end; function TDeckLinkInput.GetSampleRates: TArray<_BMDAudioSampleRate>; var LAudioSampleRates : TArray<_BMDAudioSampleRate>; i : integer; begin SetLength(LAudioSampleRates, 0); for i := Low(_AudioSampleRateLinks) to High(_AudioSampleRateLinks) do begin SetLength(LAudioSampleRates, Length(LAudioSampleRates)+1); LAudioSampleRates[High(LAudioSampleRates)] := _AudioSampleRateLinks[i].BMD; end; result := LAudioSampleRates; end; function TDeckLinkInput.GetSampleTypes: TArray<_BMDAudioSampleType>; var LAudioSampleTypes : TArray<_BMDAudioSampleType>; i : integer; begin SetLength(LAudioSampleTypes, 0); for i := Low(_AudioSampleTypeLinks) to High(_AudioSampleTypeLinks) do begin SetLength(LAudioSampleTypes, Length(LAudioSampleTypes)+1); LAudioSampleTypes[High(LAudioSampleTypes)] := _AudioSampleTypeLinks[i].BMD; end; result := LAudioSampleTypes; end; function TDeckLinkInput.GetChannelCounts: TArray<integer>; var LAudioChannelCounts : TArray<integer>; i : integer; begin SetLength(LAudioChannelCounts, 4); LAudioChannelCounts[0] := 2; LAudioChannelCounts[1] := 4; LAudioChannelCounts[2] := 8; LAudioChannelCounts[3] := 16; result := LAudioChannelCounts; end; Function TDeckLinkInput.GetPixelFormatList: TArray<_BMDPixelFormat>; var LPixelFormat : _BMDPixelFormat; LDisplayModeSupport : _BMDDisplayModeSupport; LResultDisplayMode : IDeckLinkDisplayMode; LHr : HResult; i : integer; LArray : TArray<_BMDPixelFormat>; begin for i := Low(_PixelFormatLinks) to High(_PixelFormatLinks) do begin LHr := FDeckLinkInput.DoesSupportVideoMode(DisplayMode, _PixelFormatLinks[i].BMD, bmdVideoInputFlagDefault, LDisplayModeSupport, LResultDisplayMode); case LHr of S_OK: begin if LDisplayModeSupport = bmdDisplayModeSupported then begin SetLength(LArray, Length(LArray)+1); LArray[High(LArray)] := _PixelFormatLinks[i].BMD; end; end; end; end; result := LArray; end; function TDeckLinkInput.GetVideoConnections: TArray<_BMDVideoConnection>; var LConnectios : TArray<_BMDVideoConnection>; i : integer; begin SetLength(LConnectios, 0); for i := Low(_VideoConnectionLinks) to High(_VideoConnectionLinks) do begin if SupportVideoConnection(_VideoConnectionLinks[i].BMD) then begin SetLength(LConnectios, Length(LConnectios)+1); LConnectios[High(LConnectios)] := _VideoConnectionLinks[i].BMD; end; end; result := LConnectios; end; function TDeckLinkInput.GetAudioConnections: TArray<_BMDAudioConnection>; var LConnectios : TArray<_BMDAudioConnection>; i : integer; begin SetLength(LConnectios, 0); for i := Low(_AudioConnectionLinks) to High(_AudioConnectionLinks) do begin if SupportAudioConnection(_AudioConnectionLinks[i].BMD) then begin SetLength(LConnectios, Length(LConnectios)+1); LConnectios[High(LConnectios)] := _AudioConnectionLinks[i].BMD; end; end; result := LConnectios; end; function TDeckLinkInput.Init(ADeckLink: IDeckLink): boolean; var deviceName : wideString; modelName : wideString; value : Integer; begin result := false; (* Release and nil old device *) if assigned(FDeckLink) then begin FDeckLink._Release; FDeckLink := nil; end; (* Select new device *) if Assigned(ADeckLink) then begin FDeckLink := ADeckLink; FDeckLink._AddRef(); end; deviceName := ''; modelName := ''; // Get IDeckLinkAttributes interface if (FDeckLink.QueryInterface(IID_IDeckLinkAttributes, FDeckLinkAttributes) <> S_OK) then begin raise Exception.Create('IID_IDeckLinkAttributes'); end; // Get IDeckLinkConfiguration interface if (FDeckLink.QueryInterface(IID_IDeckLinkConfiguration, FDeckLinkConfiguration) <> S_OK) then begin raise Exception.Create('IID_IDeckLinkConfiguration'); end; // Get IDeckLinkConfiguration interface if (FDeckLink.QueryInterface(IID_IDeckLinkStatus, FDeckLinkStatus) <> S_OK) then begin raise Exception.Create('IID_IDeckLinkStatus'); end; // Get IDeckLinkInput interface if (FDeckLink.QueryInterface(IID_IDeckLinkInput, FDeckLinkInput) <> S_OK) then begin raise Exception.Create('IID_IDeckLinkInput'); end; result := true; end; function TDeckLinkInput.GetDisplayMode: _BMDDisplayMode; var LCurrentVideoMode : _BMDDisplayMode; begin LCurrentVideoMode := self.GetCurrentVideoMode; if LCurrentVideoMode <> bmdModeUnknown then begin FDisplayMode := LCurrentVideoMode; end; result := FDisplayMode end; function TDeckLinkInput.GetPixelFormat: _BMDPixelFormat; var LCurrentPixelFormat : _BMDPixelFormat; begin LCurrentPixelFormat := self.GetCurrentVideoPixelFormat; if LCurrentPixelFormat <> FPixelFormat then begin FPixelFormat := FPixelFormat; end; result := FPixelFormat end; function TDeckLinkInput.StartCapture(AScreenPreviewCallback: IDeckLinkScreenPreviewCallback = nil): boolean; var LDeckLinkDisplayMode : IDeckLinkDisplayMode; LHr : HResult; begin result := false; // Set the screen preview FDeckLinkInput.SetScreenPreviewCallback(AScreenPreviewCallback); // Set capture callback FDeckLinkInput.SetCallback(self); // Get DeckLinkDisplayMode LDeckLinkDisplayMode := GetDeckLinkDisplayMode; // Enable Video Input LHr := FDeckLinkInput.EnableVideoInput(LDeckLinkDisplayMode.GetDisplayMode, FPixelFormat, FInputFlags); case LHr of E_FAIL : raise Exception.CreateFmt('Failure - result = %08x', [LHr]); E_INVALIDARG : raise Exception.CreateFmt('Is returned on invalid mode or video flags - result = %08x', [LHr]); E_ACCESSDENIED : raise Exception.CreateFmt('Unable to access the hardware or input stream curently active - result = %08x', [LHr]); E_OUTOFMEMORY : raise Exception.CreateFmt('Unable to create new frame - result = %08x', [LHr]); end; // Enable Audio Input LHr := FDeckLinkInput.EnableAudioInput(FSampleRate, FSampleType, FChannelCount); case LHr of E_FAIL : raise Exception.CreateFmt('Failure - result = %08x', [LHr]); E_INVALIDARG : raise Exception.CreateFmt('Invalid number of channels requested - result = %08x', [LHr]); end; // Start the capture LHr := FDeckLinkInput.StartStreams(); case LHr of E_FAIL : raise Exception.CreateFmt('Failure - result = %08x', [LHr]); E_INVALIDARG : raise Exception.CreateFmt('Is returned on invalid mode or video flags - result = %08x', [LHr]); E_ACCESSDENIED : raise Exception.CreateFmt('Unable to access the hardware or input stream curently active - result = %08x', [LHr]); E_OUTOFMEMORY : raise Exception.CreateFmt('Unable to create new frame - result = %08x', [LHr]); end; FCapturing := true; result := true; end; procedure TDeckLinkInput.StopCapture(); var LHr : HResult; begin if assigned(FDeckLinkInput) then begin // Flush LHr := FDeckLinkInput.FlushStreams(); case LHr of E_FAIL : raise Exception.CreateFmt('Failure - result = %08x', [LHr]); end; // Stop the capture LHr := FDeckLinkInput.StopStreams(); case LHr of E_FAIL : raise Exception.CreateFmt('Failure - result = %08x', [LHr]); end; // Disable video input LHr := FDeckLinkInput.DisableVideoInput; case LHr of E_FAIL : raise Exception.CreateFmt('Failure - result = %08x', [LHr]); end; // Disable audio input LHr := FDeckLinkInput.DisableAudioInput; case LHr of E_FAIL : raise Exception.CreateFmt('Failure - result = %08x', [LHr]); end; // Delete preview callback FDeckLinkInput.SetScreenPreviewCallback(nil); // Delete capture callback FDeckLinkInput.SetCallback(nil); end; FCapturing := false; end; procedure TDeckLinkInput.ParamsChanged(); var LHr : HResult; LCapturing : boolean; begin LCapturing := FCapturing; // Stop the capture LHr := FDeckLinkInput.StopStreams(); case LHr of S_OK : begin FCapturing := false; if LCapturing then StartCapture(); end; E_FAIL : raise Exception.CreateFmt('Failure - result = %08x', [LHr]); end; end; function TDeckLinkInput.GetDeckLinkDisplayMode: IDeckLinkDisplayMode; var LModeSupport : _BMDDisplayModeSupport; LDisplayMode : IDeckLinkDisplayMode; begin result := nil; FInputFlags := bmdVideoInputFlagDefault; if SupportsFormatDetection and FDetectionInputMode then FInputFlags := FInputFlags or bmdVideoInputEnableFormatDetection; if (FDeckLinkInput.DoesSupportVideoMode(FDisplayMode, FPixelFormat, FInputFlags, LModeSupport, LDisplayMode) <> S_OK) then begin raise Exception.Create('DoesSupportVideoMode'); end; case LModeSupport of bmdDisplayModeNotSupported: raise Exception.Create('bmdDisplayModeNotSupported'); bmdDisplayModeSupported: result := LDisplayMode; bmdDisplayModeSupportedWithConversion: raise Exception.Create('bmdDisplayModeSupportedWithConversion'); end; end; function TDeckLinkInput.VideoInputFormatChanged(notificationEvents: _BMDVideoInputFormatChangedEvents; const newDisplayMode: IDeckLinkDisplayMode; detectedSignalFlags: _BMDDetectedVideoInputFormatFlags): HResult; var LFieldDominance : _BMDFieldDominance; begin case notificationEvents of bmdVideoInputDisplayModeChanged: begin FDisplayMode := newDisplayMode.GetDisplayMode; ParamsChanged; end; bmdVideoInputFieldDominanceChanged: begin LFieldDominance := newDisplayMode.GetFieldDominance; case LFieldDominance of bmdUnknownFieldDominance:; bmdLowerFieldFirst:; bmdUpperFieldFirst:; bmdProgressiveFrame:; bmdProgressiveSegmentedFrame:; end; end; bmdVideoInputColorspaceChanged: begin case detectedSignalFlags of bmdDetectedVideoInputYCbCr422:; bmdDetectedVideoInputRGB444:; bmdDetectedVideoInputDualStream3D:; end; end; end; RESULT:=S_OK; end; Procedure TDeckLinkInput.DoFrameArrived(const videoFrame: TDeckLinkVideoInputFrame; const audioPacket: TDeckLinkAudioInputPacket; const frameIndex : Int64); begin if assigned(FOnFrameArrived) then begin FOnFrameArrived(videoFrame, audioPacket, frameIndex); end; end; function TDeckLinkInput.VideoInputFrameArrived(const videoFrame: IDeckLinkVideoInputFrame; const audioPacket: IDeckLinkAudioInputPacket): HResult; var _videoFrame : TDeckLinkVideoInputFrame; _audioPacket : TDeckLinkAudioInputPacket; LTimecode : IDeckLinkTimecode; begin _videoFrame := nil; _audioPacket := nil; if assigned(videoFrame) then begin if (videoFrame.GetFlags() and bmdFrameHasNoInputSource) > 0 then begin //DoNoInputSource; end; if (videoFrame.GetTimecode(bmdTimecodeRP188VITC1, LTimecode) = S_OK) then begin //DoTimecodeRP188VITC1; end; if (videoFrame.GetTimecode(bmdTimecodeRP188VITC2, LTimecode) = S_OK) then begin //DoTimecodeRP188VITC2; end; if (videoFrame.GetTimecode(bmdTimecodeRP188LTC, LTimecode) = S_OK) then begin //DoTimecodeRP188LTC; end; if (videoFrame.GetTimecode(bmdTimecodeRP188Any, LTimecode) = S_OK) then begin //DoTimecodeRP188Any; end; if (videoFrame.GetTimecode(bmdTimecodeLTC, LTimecode) = S_OK) then begin //DoTimecodeLTC; end; if (videoFrame.GetTimecode(bmdTimecodeVITC, LTimecode) = S_OK) then begin //DoTimecodeVITC; end; if (videoFrame.GetTimecode(bmdTimecodeVITCField2, LTimecode) = S_OK) then begin //DoTimecodeVITCField2; end; if (videoFrame.GetTimecode(bmdTimecodeSerial, LTimecode) = S_OK) then begin //DoTimecodeSerial; end; if assigned(LTimecode) then LTimecode := nil; end else begin //DoDropVideoFrame; end; if assigned(videoFrame) then _videoFrame:=TDeckLinkVideoInputFrame.Create(videoFrame); if assigned(audioPacket) then _audioPacket:=TDeckLinkAudioInputPacket.Create(audioPacket); DoFrameArrived(_videoFrame, _audioPacket, 0); if assigned(_videoFrame) then _videoFrame.Destroy; if assigned(_audioPacket) then _audioPacket.Destroy; RESULT:=S_OK; end; Function TDeckLinkInput.GetVersion : TfhVer; begin result.name:=FH_DeckLink_Input_ver.name; result.version:=FH_DeckLink_Input_ver.version; result.versionStr:=format('%s-%d.%d.%d.%d', [FH_DeckLink_Input_ver.name, FH_DeckLink_Input_ver.version shr 24 and $FF, FH_DeckLink_Input_ver.version shr 16 and $FF, FH_DeckLink_Input_ver.version shr 8 and $FF, FH_DeckLink_Input_ver.version and $FF]); result.dateRelease:=FH_DeckLink_Input_ver.dateRelease; end; procedure TDeckLinkInput.OnDebugEvents(var msg: dword); begin if assigned(FOnDebug) then begin FOnDebug(FLastDebugStr); end; end; procedure TDeckLinkInput.DoDebug(const str: string); var FMSG : DWORD; begin FLastDebugStr:=str; FMSG:=MSG_ONDEBUG; self.Dispatch(FMSG); end; procedure TDeckLinkInput.OnDropVideoFrameEvents(var msg: dword); begin if assigned(FOnDropVideoFrame) then begin FOnDropVideoFrame(self); end; end; procedure TDeckLinkInput.DoDropVideoFrame; var FMSG : DWORD; begin FMSG:=MSG_ONDROPVIDEOFRAME; self.Dispatch(FMSG); end; procedure TDeckLinkInput.OnDropFrameEvents(var msg: dword); begin if assigned(FOnDropFrame) then begin FOnDropFrame(self); end; end; procedure TDeckLinkInput.DoDropFrame; var FMSG : DWORD; begin FMSG:=MSG_ONDROPFRAME; self.Dispatch(FMSG); end; end.
unit UPgProp; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2005 by Bradford Technologies, Inc. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UForms; type TPgProperty = class(TAdvancedForm) btnOK: TButton; btnCancel: TButton; edtTitle: TEdit; Label1: TLabel; chkBxIncludePgNum: TCheckBox; chkBxIncludeTC: TCheckBox; pnlProperties: TPanel; procedure FormShow(Sender: TObject); private { Private declarations } procedure AdjustDPISettings; public { Public declarations } procedure SetProperty(const Title: string; IncludePgNum, IncludeTC: Boolean); procedure GetProperty(var Title: String; var IncludePgNum, IncludeTC: Boolean); end; var PgProperty: TPgProperty; implementation {$R *.DFM} { TPgProperty } procedure TPgProperty.AdjustDPISettings; begin btnOK.Left := edtTitle.Left + edtTitle.Width + 30; btnOK.top := edtTitle.Top; btnCancel.Left := btnOK.Left; btnCancel.Top := btnOK.Top + btnOK.Height + 20; self.Width := btnCancel.Left + btnCancel.Width + 50; self.Height := btnCancel.Top + btnCancel.Height + 80; self.Constraints.MaxWidth := 0; self.Constraints.MinWidth := 0; self.Constraints.MaxHeight := 0; self.Constraints.MinHeight := 0; end; procedure TPgProperty.GetProperty(var Title: String; var IncludePgNum, IncludeTC: Boolean); begin Title := edtTitle.Text; IncludePgNum := chkBxIncludePgNum.checked; IncludeTC := chkBxIncludeTC.checked; end; procedure TPgProperty.SetProperty(const Title: string; IncludePgNum, IncludeTC: Boolean); begin edtTitle.Text := Title; chkBxIncludePgNum.checked := IncludePgNum; chkBxIncludeTC.checked := IncludeTC; end; procedure TPgProperty.FormShow(Sender: TObject); begin AdjustDPISettings; end; end.
unit BasicInterface; interface uses System.SysUtils, System.Classes; type ISimpleInterface = interface end; TSimpleClass = class(TInterfacedObject, ISimpleInterface) private FName: String; public constructor Create(AName: String); virtual; destructor Destroy; override; end; implementation constructor TSimpleClass.Create(AName: String); begin FName := AName; WriteLn(String.Format('Creating %s', [FName])); end; destructor TSimpleClass.Destroy; begin var LExceptionPointer := AcquireExceptionObject; if nil <> LExceptionPointer then WriteLn(String.Format('Got Exception Pointer in destructor. Destroying %s', [FName])) else WriteLn(String.Format('DID NOT GET EXCEPTION POINTER IN DESTRUCTOR!!! Destroying %s', [FName])); inherited Destroy; end; end.
unit mnNetworkTestCase; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework; type TmnNetworkTestCase = class(TTestCase) strict private public procedure SetUp; override; procedure TearDown; override; published procedure testHTTPGet; procedure testHTTPPost; procedure testThreadHTTPGet; procedure testThreadHTTPPost; end; implementation uses mnNetwork, UTestConsts, mnDebug, mnDialog, SysUtils; { TmnNetworkTestCase } procedure TmnNetworkTestCase.SetUp; begin end; procedure TmnNetworkTestCase.TearDown; begin end; procedure TmnNetworkTestCase.testHTTPGet; begin CheckEquals(mnHTTPGet(Url_Get+Params_Get), Content_Get); try mnHTTPGet(Url_Fake_Page, 3, 500); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, Error_Page_Not_Found); end; try mnHTTPGet(Url_Fake_Host, 3, 500); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, Error_Host_Not_Found); end; mnHTTPGet(Url_Https); end; procedure TmnNetworkTestCase.testHTTPPost; begin CheckEquals(mnHTTPPost(Url_Post, Params_Post), Content_Post); try mnHTTPPost(Url_Fake_Page, Params_Post, 3, 500); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, Error_Page_Not_Found); end; try mnHTTPPost(Url_Fake_Host, Params_Post, 3, 500); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, Error_Host_Not_Found); end; mnHTTPPost(Url_Https, ''); end; procedure TmnNetworkTestCase.testThreadHTTPGet; begin CheckEquals(mnThreadHTTPGet(Url_Get+Params_Get), Content_Get); try mnThreadHTTPGet(Url_Fake_Page, 3, 500); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, Error_Page_Not_Found); end; try mnThreadHTTPGet(Url_Fake_Host, 3, 500); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, Error_Host_Not_Found); end; mnThreadHTTPGet(Url_Https); end; procedure TmnNetworkTestCase.testThreadHTTPPost; begin CheckEquals(mnThreadHTTPPost(Url_Post, Params_Post), Content_Post); try mnThreadHTTPPost(Url_Fake_Page, Params_Post, 3, 500); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, Error_Page_Not_Found); end; try mnThreadHTTPPost(Url_Fake_Host, Params_Post, 3, 500); mnNeverGoesHere; except on E: Exception do CheckEquals(E.Message, Error_Host_Not_Found); end; mnThreadHTTPPost(Url_Https, ''); end; initialization // Register any test cases with the test runner RegisterTest(TmnNetworkTestCase.Suite); end.
unit aes; interface uses Windows; // #define AES_MAXNR 14 // #define AES_BLOCK_SIZE 16 const AES_MAXNR = 14; AES_BLOCK_SIZE = 16; // struct aes_key_st { // unsigned long rd_key[4 *(AES_MAXNR + 1)]; // int rounds; // }; // typedef struct aes_key_st AES_KEY; type AES_KEY = record rd_key: array [0..(4*(AES_MAXNR+1))-1] of LongWord; rounds: integer; end; PAES_KEY = ^AES_KEY; // int AES_set_encrypt_key( // const unsigned char *userKey, // const int bits, // AES_KEY *key // ); function AES_set_encrypt_key( const userKey: PByte; const bits: integer; var key: AES_KEY ): integer; cdecl; // int AES_set_decrypt_key( // const unsigned char *userKey, // const int bits, // AES_KEY *key // ); function AES_set_decrypt_key( const userKey: PByte; const bits: integer; var key: AES_KEY ): integer; cdecl; // void AES_encrypt( // const unsigned char *in, // unsigned char *out, // const AES_KEY *key // ); procedure AES_encrypt( const _in: PByte; _out: PByte; var key: AES_KEY ); cdecl; // void AES_decrypt( // const unsigned char *in, // unsigned char *out, // const AES_KEY *key // ); procedure AES_decrypt( const _in: PByte; _out: PByte; var key: AES_KEY ); cdecl; // void AES_cbc_encrypt( // const unsigned char *in, // unsigned char *out, // const unsigned long length, // const AES_KEY *key, // unsigned char *ivec, // const int enc // ); procedure AES_cbc_encrypt( const _in: PByte; _out: PByte; const length: LongWord; var key: AES_KEY; ivec: PByte; const enc: integer ); cdecl; implementation const aes_dll = 'libeay32.dll'; function AES_set_encrypt_key; external aes_dll name 'AES_set_encrypt_key'; function AES_set_decrypt_key; external aes_dll name 'AES_set_decrypt_key'; procedure AES_encrypt; external aes_dll name 'AES_encrypt'; procedure AES_decrypt; external aes_dll name 'AES_decrypt'; procedure AES_cbc_encrypt; external aes_dll name 'AES_cbc_encrypt'; end.
unit ConstantsU; interface resourcestring sPortInUse = '- Error: Port %s already in use'; sPortSet = '- Port set to %s'; sServerRunning = '- The Server is already running'; sStartingServer = '- Starting HTTP Server on port %d'; sStoppingServer = '- Stopping Server'; sServerStopped = '- Server Stopped'; sServerNotRunning = '- The Server is not running'; sInvalidCommand = '- Error: Invalid Command'; sIndyVersion = '- Indy Version: '; sActive = '- Active: '; sPort = '- Port: '; sSessionID = '- Session ID CookieName: '; sCommands = 'Enter a Command: ' + slineBreak + ' - "start" to start the server'+ slineBreak + ' - "stop" to stop the server'+ slineBreak + ' - "set port" to change the default port'+ slineBreak + ' - "status" for Server status'+ slineBreak + ' - "help" to show commands'+ slineBreak + ' - "exit" to close the application'; const cArrow = '->'; cCommandStart = 'start'; cCommandStop = 'stop'; cCommandStatus = 'status'; cCommandHelp = 'help'; cCommandSetPort = 'set port'; cCommandExit = 'exit'; implementation end.
unit UFileWatchThread; interface uses classes, dirnotify, ExtCtrls; type // 文件监听对象 TMyFileWatch = class public ControlPath, LocalPath : string; IsStop : Boolean; public LocalDirNotify : TDirNotify; // 目录监听器 Timer : TTimer; public constructor Create; procedure Stop; public procedure SetPath( _ControlPath, _LocalPath : string ); procedure SetLocalPath( _LocalPath : string ); private procedure LocalFolderChange(Sender: TObject); procedure OnTime( Sender: TObject ); end; var MyFileWatch : TMyFileWatch; implementation uses UMyUtils, SysUtils, UMyFaceThread; { TMyFileWatch } constructor TMyFileWatch.Create; begin LocalDirNotify := TDirNotify.Create( nil ); LocalDirNotify.OnChange := LocalFolderChange; Timer := TTimer.Create( nil ); Timer.Enabled := False; Timer.Interval := 1000; Timer.OnTimer := OnTime; IsStop := False; end; procedure TMyFileWatch.LocalFolderChange(Sender: TObject); begin Timer.Enabled := False; Timer.Enabled := True; end; procedure TMyFileWatch.OnTime(Sender: TObject); begin if LocalPath <> '' then MyFaceJobHandler.FileChange( ControlPath, LocalPath, True ); end; procedure TMyFileWatch.SetLocalPath(_LocalPath: string); begin if IsStop then Exit; LocalPath := _LocalPath; TThread.CreateAnonymousThread( procedure begin if ( LocalPath <> '' ) and MyFilePath.getIsFixedDriver( ExtractFileDrive( LocalPath ) ) then begin LocalDirNotify.Path := LocalPath; LocalDirNotify.Enabled := True; end else LocalDirNotify.Enabled := False end).Start; end; procedure TMyFileWatch.SetPath(_ControlPath, _LocalPath : string); begin if IsStop then Exit; ControlPath := _ControlPath; SetLocalPath( _LocalPath ); end; procedure TMyFileWatch.Stop; begin IsStop := True; Timer.Enabled := False; LocalDirNotify.Free; Timer.Free; end; end.
unit gdxsprite; {$mode delphi} interface uses Classes, SysUtils, And_jni, {And_jni_Bridge,} AndroidWidget; type {Draft Component code by "LAMW: Lazarus Android Module Wizard" [10/16/2019 0:46:07]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} jGdxSprite = class(jControl) private public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init; override; function jCreate(): jObject; procedure jFree(); procedure SetPosition(_x: single; _y: single); overload; procedure SetRotation(_degrees: single); overload; procedure SetSprite(_sprite: jObject); overload; procedure Translate(_offsetX: single; _offsetY: single); overload; procedure Rotate90(_clockwise: boolean); overload; procedure Rotate(_degrees: single); overload; procedure Draw(_batch: jObject; _x: single; _y: single); overload; procedure SetSprite(_sprite: jObject; _scale: single); overload; procedure SetSprites(_textureAtlas: jObject); overload; procedure SetSprites(_textureAtlas: jObject; _scale: single); overload; procedure Draw(_batch: jObject; _sprite: string; _x: single; _y: single); overload; procedure SetPosition(_sprite: string; _x: single; _y: single); overload; procedure SetRotation(_sprite: string; _degrees: single); overload; procedure Translate(_sprite: string; _offsetX: single; _offsetY: single); overload; procedure Rotate90(_sprite: string; _clockwise: boolean); overload; procedure Rotate(_sprite: string; _degrees: single); overload; procedure Dispose(); published end; function jGdxSprite_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jGdxSprite_jFree(env: PJNIEnv; _jgdxsprite: JObject); procedure jGdxSprite_SetPosition(env: PJNIEnv; _jgdxsprite: JObject; _x: single; _y: single); overload; procedure jGdxSprite_SetRotation(env: PJNIEnv; _jgdxsprite: JObject; _degrees: single); overload; procedure jGdxSprite_SetSprite(env: PJNIEnv; _jgdxsprite: JObject; _sprite: jObject); overload; procedure jGdxSprite_Translate(env: PJNIEnv; _jgdxsprite: JObject; _offsetX: single; _offsetY: single); overload; procedure jGdxSprite_Rotate90(env: PJNIEnv; _jgdxsprite: JObject; _clockwise: boolean); overload; procedure jGdxSprite_Rotate(env: PJNIEnv; _jgdxsprite: JObject; _degrees: single); overload; procedure jGdxSprite_Draw(env: PJNIEnv; _jgdxsprite: JObject; _batch: jObject; _x: single; _y: single); overload; procedure jGdxSprite_SetSprite(env: PJNIEnv; _jgdxsprite: JObject; _sprite: jObject; _scale: single); overload; procedure jGdxSprite_SetSprites(env: PJNIEnv; _jgdxsprite: JObject; _textureAtlas: jObject); overload; procedure jGdxSprite_SetSprites(env: PJNIEnv; _jgdxsprite: JObject; _textureAtlas: jObject; _scale: single); overload; procedure jGdxSprite_Draw(env: PJNIEnv; _jgdxsprite: JObject; _batch: jObject; _sprite: string; x: single; y: single); overload; procedure jGdxSprite_SetPosition(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _x: single; _y: single); overload; procedure jGdxSprite_SetRotation(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _degrees: single); overload; procedure jGdxSprite_Translate(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _offsetX: single; _offsetY: single); overload; procedure jGdxSprite_Rotate90(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _clockwise: boolean); overload; procedure jGdxSprite_Rotate(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _degrees: single); overload; procedure jGdxSprite_Dispose(env: PJNIEnv; _jgdxsprite: JObject); implementation {--------- jGdxSprite --------------} constructor jGdxSprite.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... end; destructor jGdxSprite.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jGdxSprite.Init; begin if FInitialized then Exit; inherited Init; //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject:= jCreate(); //jSelf ! FInitialized:= True; end; function jGdxSprite.jCreate(): jObject; begin Result:= jGdxSprite_jCreate(gApp.jni.jEnv, int64(Self), gApp.jni.jThis); end; procedure jGdxSprite.jFree(); begin //in designing component state: set value here... if FInitialized and (FjObject <> nil) then jGdxSprite_jFree(gApp.jni.jEnv, FjObject); end; procedure jGdxSprite.SetPosition(_x: single; _y: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_SetPosition(gApp.jni.jEnv, FjObject, _x ,_y); end; procedure jGdxSprite.SetRotation(_degrees: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_SetRotation(gApp.jni.jEnv, FjObject, _degrees); end; procedure jGdxSprite.SetSprite(_sprite: jObject); begin //in designing component state: set value here... if FInitialized then jGdxSprite_SetSprite(gApp.jni.jEnv, FjObject, _sprite); end; procedure jGdxSprite.Translate(_offsetX: single; _offsetY: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_Translate(gApp.jni.jEnv, FjObject, _offsetX ,_offsetY); end; procedure jGdxSprite.Rotate90(_clockwise: boolean); begin //in designing component state: set value here... if FInitialized then jGdxSprite_Rotate90(gApp.jni.jEnv, FjObject, _clockwise); end; procedure jGdxSprite.Rotate(_degrees: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_Rotate(gApp.jni.jEnv, FjObject, _degrees); end; procedure jGdxSprite.SetSprite(_sprite: jObject; _scale: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_SetSprite(gApp.jni.jEnv, FjObject, _sprite ,_scale); end; procedure jGdxSprite.SetSprites(_textureAtlas: jObject); begin //in designing component state: set value here... if FInitialized then jGdxSprite_SetSprites(gApp.jni.jEnv, FjObject, _textureAtlas); end; procedure jGdxSprite.SetSprites(_textureAtlas: jObject; _scale: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_SetSprites(gApp.jni.jEnv, FjObject, _textureAtlas ,_scale); end; procedure jGdxSprite.Draw(_batch: jObject; _x: single; _y: single); overload; begin //in designing component state: set value here... if FInitialized then jGdxSprite_Draw(gApp.jni.jEnv, FjObject, _batch,_x ,_y); end; procedure jGdxSprite.Draw(_batch: jObject; _sprite: string; _x: single; _y: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_Draw(gApp.jni.jEnv, FjObject, _batch ,_sprite ,_x ,_y); end; procedure jGdxSprite.SetPosition(_sprite: string; _x: single; _y: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_SetPosition(gApp.jni.jEnv, FjObject, _sprite ,_x ,_y); end; procedure jGdxSprite.SetRotation(_sprite: string; _degrees: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_SetRotation(gApp.jni.jEnv, FjObject, _sprite ,_degrees); end; procedure jGdxSprite.Translate(_sprite: string; _offsetX: single; _offsetY: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_Translate(gApp.jni.jEnv, FjObject, _sprite ,_offsetX ,_offsetY); end; procedure jGdxSprite.Rotate90(_sprite: string; _clockwise: boolean); begin //in designing component state: set value here... if FInitialized then jGdxSprite_Rotate90(gApp.jni.jEnv, FjObject, _sprite ,_clockwise); end; procedure jGdxSprite.Rotate(_sprite: string; _degrees: single); begin //in designing component state: set value here... if FInitialized then jGdxSprite_Rotate(gApp.jni.jEnv, FjObject, _sprite ,_degrees); end; procedure jGdxSprite.Dispose(); begin //in designing component state: set value here... if FInitialized then jGdxSprite_Dispose(gApp.jni.jEnv, FjObject); end; {-------- jGdxSprite_JNI_Bridge ----------} function jGdxSprite_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jGdxSprite_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; procedure jGdxSprite_jFree(env: PJNIEnv; _jgdxsprite: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jgdxsprite, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_SetPosition(env: PJNIEnv; _jgdxsprite: JObject; _x: single; _y: single); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].f:= _x; jParams[1].f:= _y; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'SetPosition', '(FF)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_SetRotation(env: PJNIEnv; _jgdxsprite: JObject; _degrees: single); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].f:= _degrees; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'SetRotation', '(F)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_SetSprite(env: PJNIEnv; _jgdxsprite: JObject; _sprite: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= _sprite; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'SetSprite', '(Lcom/badlogic/gdx/graphics/g2d/Sprite;)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Translate(env: PJNIEnv; _jgdxsprite: JObject; _offsetX: single; _offsetY: single); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].f:= _offsetX; jParams[1].f:= _offsetY; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Translate', '(FF)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Rotate90(env: PJNIEnv; _jgdxsprite: JObject; _clockwise: boolean); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].z:= JBool(_clockwise); jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Rotate90', '(Z)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Rotate(env: PJNIEnv; _jgdxsprite: JObject; _degrees: single); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].f:= _degrees; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Rotate', '(F)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Draw(env: PJNIEnv; _jgdxsprite: JObject; _batch: jObject; _x: single; _y: single); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= _batch; jParams[1].f:= _x; jParams[2].f:= _y; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Draw', '(Lcom/badlogic/gdx/graphics/g2d/SpriteBatch;FF)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_SetSprite(env: PJNIEnv; _jgdxsprite: JObject; _sprite: jObject; _scale: single); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= _sprite; jParams[1].f:= _scale; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'SetSprite', '(Lcom/badlogic/gdx/graphics/g2d/Sprite;F)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_SetSprites(env: PJNIEnv; _jgdxsprite: JObject; _textureAtlas: jObject); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= _textureAtlas; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'SetSprites', '(Lcom/badlogic/gdx/graphics/g2d/TextureAtlas;)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_SetSprites(env: PJNIEnv; _jgdxsprite: JObject; _textureAtlas: jObject; _scale: single); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= _textureAtlas; jParams[1].f:= _scale; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'SetSprites', '(Lcom/badlogic/gdx/graphics/g2d/TextureAtlas;F)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Draw(env: PJNIEnv; _jgdxsprite: JObject; _batch: jObject; _sprite: string; x: single; y: single); var jParams: array[0..3] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= _batch; jParams[1].l:= env^.NewStringUTF(env, PChar(_sprite)); jParams[2].f:= x; jParams[3].f:= y; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Draw', '(Lcom/badlogic/gdx/graphics/g2d/SpriteBatch;Ljava/lang/String;FF)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_SetPosition(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _x: single; _y: single); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= env^.NewStringUTF(env, PChar(_sprite)); jParams[1].f:= _x; jParams[2].f:= _y; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'SetPosition', '(Ljava/lang/String;FF)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_SetRotation(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _degrees: single); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= env^.NewStringUTF(env, PChar(_sprite)); jParams[1].f:= _degrees; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'SetRotation', '(Ljava/lang/String;F)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Translate(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _offsetX: single; _offsetY: single); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= env^.NewStringUTF(env, PChar(_sprite)); jParams[1].f:= _offsetX; jParams[2].f:= _offsetY; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Translate', '(Ljava/lang/String;FF)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Rotate90(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _clockwise: boolean); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= env^.NewStringUTF(env, PChar(_sprite)); jParams[1].z:= JBool(_clockwise); jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Rotate90', '(Ljava/lang/String;Z)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Rotate(env: PJNIEnv; _jgdxsprite: JObject; _sprite: string; _degrees: single); var jParams: array[0..1] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jParams[0].l:= env^.NewStringUTF(env, PChar(_sprite)); jParams[1].f:= _degrees; jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Rotate', '(Ljava/lang/String;F)V'); env^.CallVoidMethodA(env, _jgdxsprite, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[0].l); env^.DeleteLocalRef(env, jCls); end; procedure jGdxSprite_Dispose(env: PJNIEnv; _jgdxsprite: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin //gVM^.AttachCurrentThread(gVm,@env,nil); jCls:= env^.GetObjectClass(env, _jgdxsprite); jMethod:= env^.GetMethodID(env, jCls, 'Dispose', '()V'); env^.CallVoidMethod(env, _jgdxsprite, jMethod); env^.DeleteLocalRef(env, jCls); end; end.
unit DIOTA.Dto.Response.GetNewAddressesResponse; interface uses System.Classes, DIOTA.IotaAPIClasses; type TGetNewAddressesResponse = class(TIotaAPIResponse) private FAddresses: TArray<String>; function GetAddresses(Index: Integer): String; function GetAddressesCount: Integer; public constructor Create(AAddresses: TArray<String>); reintroduce; virtual; function AddressesList: TStringList; property AddressesCount: Integer read GetAddressesCount; property Addresses[Index: Integer]: String read GetAddresses; property AddressesArray: TArray<String> read FAddresses; end; implementation { TGetNewAddressesResponse } constructor TGetNewAddressesResponse.Create(AAddresses: TArray<String>); begin inherited Create; FAddresses := AAddresses; end; function TGetNewAddressesResponse.GetAddresses(Index: Integer): String; begin Result := FAddresses[Index]; end; function TGetNewAddressesResponse.GetAddressesCount: Integer; begin if Assigned(FAddresses) then Result := Length(FAddresses) else Result := 0; end; function TGetNewAddressesResponse.AddressesList: TStringList; var AAddress: String; begin Result := TStringList.Create; for AAddress in FAddresses do Result.Add(AAddress); end; end.
unit uBitsForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus, ExtCtrls, VirtualTrees, uLibrary, uLibraryData, uBitsEditor, uBitEditor; type { TBitsForm } TBitsForm = class(TEditingForm) BitPanel: TPanel; BitsPanel: TPanel; Splitter: TSplitter; procedure FormCreate(Sender: TObject); private fBitsEditor: TBitsEditor; fBitEditor: TBitEditor; private procedure BitsSelect(Sender: TObject; const aBits: IBits); public procedure Load(const aLibraryData : TLibraryData); override; procedure Unload; override; end; implementation {$R *.lfm} { TBitsForm } procedure TBitsForm.FormCreate(Sender: TObject); begin fBitsEditor := TBitsEditor.Create(Self); fBitsEditor.Parent := BitsPanel; fBitsEditor.Align := alClient; fBitsEditor.OnBitsSelect := @BitsSelect; fBitEditor := TBitEditor.Create(Self); fBitEditor.Parent := BitPanel; fBitEditor.Align := alClient; end; procedure TBitsForm.BitsSelect(Sender: TObject; const aBits: IBits); begin fBitEditor.Bits := aBits; end; procedure TBitsForm.Load(const aLibraryData: TLibraryData); begin if aLibraryData is uLibraryData.TBitsData then fBitsEditor.BitsSet := uLibraryData.TBitsData(aLibraryData).BitsSet; end; procedure TBitsForm.Unload; begin fBitsEditor.Clear; fBitEditor.Clear; end; end.
unit PaintUtils; interface uses SysUtils, DelphiGraph, PaintType; const FullDegree = 180; procedure ConnectPoints(const a, b : PaintType.TPoint; c : TColor = -1); procedure PaintPoint(const a : PaintType.TPoint; const r : Real; const c : TColor); function GetCartesianCoordinates(const l, a : Real) : PaintType.TPoint; procedure Circle(const r : Real); procedure Ray(const a : Real); procedure PaintPlane(const dR : Real; const k : Integer; const c : TColor); function ctr : PaintType.TPoint; procedure PaintPoints(const a : PaintType.TPoints; const r : Real; const c : TColor); procedure ClearScreen; procedure DrawRound(const p : PaintType.TPoint; const r : Real); function GetScreenMaxSize : Real; implementation function ctr : PaintType.TPoint; begin Result.x := GetMaxX / 2; Result.y := GetMaxY / 2; end; procedure ClearScreen; begin SetBrushColor(clWhite); SetBrushStyle(bsSolid); clrscr; end; procedure ConnectPoints(const a, b : PaintType.TPoint; c : TColor = -1); begin if c <> -1 then SetPenColor(c); MoveTo(round(a.x), round(a.y)); LineTo(round(b.x), round(b.y)); end; procedure PaintPoint(const a : PaintType.TPoint; const r : Real; const c : TColor); begin SetPenColor(c); SetPenStyle(psSolid); SetBrushColor(c); SetBrushStyle(bsSolid); Ellipse(round(a.x) - round(r), round(a.y) - round(r), round(a.x) + round(r), round(a.y) + round(r)); end; procedure PaintPoints(const a : PaintType.TPoints; const r : Real; const c : TColor); var i : Integer; begin for i := 0 to Length(a) - 1 do PaintPoint(a[i], r, c); end; function GetCartesianCoordinates(const l, a : Real) : PaintType.TPoint; begin Result.x := ctr.x + cos(a / FullDegree * pi) * l; Result.y := ctr.y - sin(a / FullDegree * pi) * l; end; procedure Circle(const r : Real); begin Ellipse(round(ctr.x) - round(r), round(ctr.y) - round(r), round(ctr.x) + round(r), round(ctr.y) + round(r)); end; procedure DrawRound(const p : PaintType.TPoint; const r : Real); begin Ellipse(round(p.x) - round(r), round(p.y) - round(r), round(p.x) + round(r), round(p.y) + round(r)); end; function GetScreenMaxSize : Real; begin Result := ord(GetMaxX >= GetMaxY) * GetMaxX + ord(GetMaxX < GetMaxY) * GetMaxY; end; procedure Ray(const a : Real); var r : TPoint; begin r := GetCartesianCoordinates(GetScreenMaxSize, a); ConnectPoints(ctr, r); end; procedure PaintPlane(const dR : Real; const k : Integer; const c : TColor); var i : Integer; begin SetPenColor(c); SetPenStyle(psSolid); SetBrushStyle(bsClear); for i := 1 to round(GetScreenMaxSize / dR + 1) do Circle(i * dR); for i := 0 to k - 1 do Ray(i * 2 * FullDegree / k); end; end.
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$endif} unit testcase.cwThreading.ExecuteForLoop; {$ifdef fpc} {$mode delphiunicode} {$modeswitch nestedprocvars} {$endif} {$M+} interface uses cwTest , cwTest.Standard ; type TTestExecuteForLoop = class(TTestCase) private fObjectNotifyDone: boolean; fObjectData: array of boolean; private procedure DoObjectNotify; procedure ObjectExecute( const start, stop: nativeuint ); published {$ifndef fpc} procedure ExecuteForAnonymousNotify; {$endif} procedure ExecuteForGlobalExecuteGlobalNotify; procedure ExecuteForGlobalExecuteObjectNotify; procedure ExecuteForGlobalExecuteNestedNotify; procedure ExecuteForGlobalExecuteWait; procedure ExecuteForObjectExecuteGlobalNotify; procedure ExecuteForObjectExecuteObjectNotify; procedure ExecuteForObjectExecuteNestedNotify; procedure ExecuteForObjectExecuteWait; procedure ExecuteForNestedExecuteGlobalNotify; procedure ExecuteForNestedExecuteObjectNotify; procedure ExecuteForNestedExecuteNestedNotify; procedure ExecuteForNestedExecuteWait; end; implementation uses sysutils // for sleep , cwThreading , cwThreading.Standard ; var GlobalNotifyDone: boolean; GlobalData: array of boolean; procedure GlobalNotify; begin GlobalNotifyDone := True; end; procedure GlobalExecute( const start, stop: nativeuint ); var idx: nativeuint; begin for idx := start to stop do begin GlobalData[idx] := not GlobalData[idx]; end; end; procedure TTestExecuteForLoop.DoObjectNotify; begin fObjectNotifyDone := True; end; procedure TTestExecuteForLoop.ObjectExecute( const start, stop: nativeuint ); var idx: nativeuint; begin for idx := start to stop do begin fObjectData[idx] := not fObjectData[idx]; end; end; {$ifndef fpc} procedure TTestExecuteForLoop.ExecuteForAnonymousNotify; const cLoopCount = 1000; var AnonymousNotifyDone: boolean; var idx: nativeuint; begin // Arrange: SetLength(GlobalData,cLoopCount); for idx := 0 to pred(Length(GlobalData)) do begin GlobalData[idx] := False; end; AnonymousNotifyDone := False; TaskCounter := 0; // Act: ThreadSystem.Execute(cLoopCount, procedure( const start, stop: nativeuint ); begin GlobalData[idx] := not GlobalData[idx]; end, procedure(); begin AnonymousNotifyDone := True; end ); while not AnonymousNotifyDone do Sleep(1); // Assert: TTest.IsTrue(AnonymousNotifyDone); for idx := 0 to pred(Length(GlobalData)) do begin TTest.Expect(GlobalData[idx],True); end; end; {$endif} procedure TTestExecuteForLoop.ExecuteForGlobalExecuteGlobalNotify; const cLoopCount = 1000; var idx: nativeuint; begin // Arrange: SetLength(GlobalData,cLoopCount); for idx := 0 to pred(Length(GlobalData)) do begin GlobalData[idx] := False; end; GlobalNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, GlobalExecute, GlobalNotify); while not GlobalNotifyDone do Sleep(1); // Assert: TTest.IsTrue(GlobalNotifyDone); for idx := 0 to pred(Length(GlobalData)) do begin TTest.Expect(GlobalData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForGlobalExecuteObjectNotify; const cLoopCount = 1000; var idx: nativeuint; begin // Arrange: SetLength(GlobalData,cLoopCount); for idx := 0 to pred(Length(GlobalData)) do begin GlobalData[idx] := False; end; fObjectNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, GlobalExecute, DoObjectNotify); while not fObjectNotifyDone do Sleep(1); // Assert: TTest.IsTrue(fObjectNotifyDone); for idx := 0 to pred(Length(GlobalData)) do begin TTest.Expect(GlobalData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForGlobalExecuteNestedNotify; const cLoopCount = 1000; var NestedNotifyDone: boolean; procedure DoNestedNotify; begin NestedNotifyDone := True; end; var idx: nativeuint; begin // Arrange: SetLength(GlobalData,cLoopCount); for idx := 0 to pred(Length(GlobalData)) do begin GlobalData[idx] := False; end; NestedNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, GlobalExecute, DoNestedNotify); while not NestedNotifyDone do Sleep(1); // Assert: TTest.IsTrue(NestedNotifyDone); for idx := 0 to pred(Length(GlobalData)) do begin TTest.Expect(GlobalData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForGlobalExecuteWait; const cLoopCount = 1000; var idx: nativeuint; begin // Arrange: SetLength(GlobalData,cLoopCount); for idx := 0 to pred(Length(GlobalData)) do begin GlobalData[idx] := False; end; // Act: ThreadSystem.Execute(cLoopCount, GlobalExecute, TRUE); // Assert: for idx := 0 to pred(Length(GlobalData)) do begin TTest.Expect(GlobalData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForObjectExecuteGlobalNotify; const cLoopCount = 1000; var idx: nativeuint; begin // Arrange: SetLength(fObjectData,cLoopCount); for idx := 0 to pred(Length(fObjectData)) do begin fObjectData[idx] := False; end; GlobalNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, ObjectExecute, GlobalNotify); while not GlobalNotifyDone do Sleep(1); // Assert: TTest.IsTrue(GlobalNotifyDone); for idx := 0 to pred(Length(fObjectData)) do begin TTest.Expect(fObjectData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForObjectExecuteObjectNotify; const cLoopCount = 1000; var idx: nativeuint; begin // Arrange: SetLength(fObjectData,cLoopCount); for idx := 0 to pred(Length(fObjectData)) do begin fObjectData[idx] := False; end; fObjectNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, ObjectExecute, DoObjectNotify); while not fObjectNotifyDone do Sleep(1); // Assert: TTest.IsTrue(fObjectNotifyDone); for idx := 0 to pred(Length(fObjectData)) do begin TTest.Expect(fObjectData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForObjectExecuteNestedNotify; const cLoopCount = 1000; var NestedNotifyDone: boolean; procedure DoNestedNotify; begin NestedNotifyDone := True; end; var idx: nativeuint; begin // Arrange: SetLength(fObjectData,cLoopCount); for idx := 0 to pred(Length(fObjectData)) do begin fObjectData[idx] := False; end; NestedNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, ObjectExecute, DoNestedNotify); while not NestedNotifyDone do Sleep(1); // Assert: TTest.IsTrue(NestedNotifyDone); for idx := 0 to pred(Length(fObjectData)) do begin TTest.Expect(fObjectData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForObjectExecuteWait; const cLoopCount = 1000; var idx: nativeuint; begin // Arrange: SetLength(fObjectData,cLoopCount); for idx := 0 to pred(Length(fObjectData)) do begin fObjectData[idx] := False; end; // Act: ThreadSystem.Execute(cLoopCount, ObjectExecute, TRUE); // Assert: for idx := 0 to pred(Length(fObjectData)) do begin TTest.Expect(fObjectData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForNestedExecuteGlobalNotify; const cLoopCount = 1000; var idx: nativeuint; NestedData: array of boolean; procedure NestedExecute( const start, stop: nativeuint ); var idx: nativeuint; begin for idx := start to stop do begin NestedData[idx] := not NestedData[idx]; end; end; begin // Arrange: {$hints off} SetLength(NestedData,cLoopCount); {$hints on} for idx := 0 to pred(Length(NestedData)) do begin NestedData[idx] := False; end; GlobalNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, NestedExecute, GlobalNotify); while not GlobalNotifyDone do Sleep(1); // Assert: TTest.IsTrue(GlobalNotifyDone); for idx := 0 to pred(Length(NestedData)) do begin TTest.Expect(NestedData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForNestedExecuteObjectNotify; const cLoopCount = 1000; var idx: nativeuint; NestedData: array of boolean; procedure NestedExecute( const start, stop: nativeuint ); var idx: nativeuint; begin for idx := start to stop do begin NestedData[idx] := not NestedData[idx]; end; end; begin // Arrange: {$hints off} SetLength(NestedData,cLoopCount); {$hints on} for idx := 0 to pred(Length(NestedData)) do begin NestedData[idx] := False; end; fObjectNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, NestedExecute, DoObjectNotify); while not fObjectNotifyDone do Sleep(1); // Assert: TTest.IsTrue(fObjectNotifyDone); for idx := 0 to pred(Length(NestedData)) do begin TTest.Expect(NestedData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForNestedExecuteNestedNotify; const cLoopCount = 1000; var NestedNotifyDone: boolean; NestedData: array of boolean; procedure NestedExecute( const start, stop: nativeuint ); var idx: nativeuint; begin for idx := start to stop do begin NestedData[idx] := not NestedData[idx]; end; end; procedure DoNestedNotify; begin NestedNotifyDone := True; end; var idx: nativeuint; begin // Arrange: {$hints off} SetLength(NestedData,cLoopCount); {$hints on} for idx := 0 to pred(Length(NestedData)) do begin NestedData[idx] := False; end; NestedNotifyDone := False; // Act: ThreadSystem.Execute(cLoopCount, NestedExecute, DoNestedNotify); while not NestedNotifyDone do Sleep(1); // Assert: TTest.IsTrue(NestedNotifyDone); for idx := 0 to pred(Length(NestedData)) do begin TTest.Expect(NestedData[idx],True); end; end; procedure TTestExecuteForLoop.ExecuteForNestedExecuteWait; const cLoopCount = 1000; var idx: nativeuint; NestedData: array of boolean; procedure NestedExecute( const start, stop: nativeuint ); var idx: nativeuint; begin for idx := start to stop do begin NestedData[idx] := not NestedData[idx]; end; end; begin // Arrange: {$hints off} SetLength(NestedData,cLoopCount); {$hints on} for idx := 0 to pred(Length(NestedData)) do begin NestedData[idx] := False; end; // Act: ThreadSystem.Execute(cLoopCount, NestedExecute, TRUE); // Assert: for idx := 0 to pred(Length(NestedData)) do begin TTest.Expect(NestedData[idx],True); end; end; initialization TestSuite.RegisterTestCase(TTestExecuteForLoop); end.
unit RepositorioEmpresa; interface uses DB, Auditoria, Repositorio; type TRepositorioEmpresa = class(TRepositorio) protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; function SQLGetExiste(campo: String): String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; protected procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override; end; implementation uses SysUtils, Empresa, Math, StrUtils; { TRepositorioEmpresa } function TRepositorioEmpresa.Get(Dataset: TDataSet): TObject; var Empresa :TEmpresa; begin Empresa:= TEmpresa.Create; Empresa.codigo := self.FQuery.FieldByName('codigo').AsInteger; Empresa.razao_social := self.FQuery.FieldByName('razao_social').AsString; Empresa.nome_fantasia := self.FQuery.FieldByName('nome_fantasia').AsString; Empresa.cnpj := self.FQuery.FieldByName('cnpj').AsString; Empresa.ie := self.FQuery.FieldByName('ie').AsString; Empresa.telefone := self.FQuery.FieldByName('telefone').AsString; Empresa.site := self.FQuery.FieldByName('site').AsString; Empresa.quantidade_mesas := self.FQuery.FieldByName('quantidade_mesas').AsInteger; Empresa.couvert := (self.FQuery.FieldByName('couvert').AsString = 'S'); Empresa.valor_couvert := self.FQuery.FieldByName('valor_couvert').AsFloat; Empresa.cidade := self.FQuery.FieldByName('cidade').AsString; Empresa.taxa_servico := self.FQuery.FieldByName('taxa_servico').AsFloat; Empresa.aliquota_couvert := self.FQuery.FieldByName('aliquota_couvert').AsFloat; Empresa.aliquota_txservico := self.FQuery.FieldByName('aliquota_txservico').AsFloat; Empresa.tributacao_couvert := self.FQuery.FieldByName('tributacao_couvert').AsString; Empresa.tributacao_txservico := self.FQuery.FieldByName('tributacao_txservico').AsString; Empresa.diretorio_boliche := self.FQuery.FieldByName('diretorio_boliche').AsString; Empresa.diretorio_dispensadora := self.FQuery.FieldByName('diretorio_dispensadora').AsString; Empresa.estado := self.FQuery.FieldByName('estado').AsString; Empresa.cep := self.FQuery.FieldByName('cep').AsInteger; Empresa.rua := self.FQuery.FieldByName('rua').AsString; Empresa.numero := self.FQuery.FieldByName('numero').AsString; Empresa.bairro := self.FQuery.FieldByName('bairro').AsString; Empresa.complemento := self.FQuery.FieldByName('complemento').AsString; Empresa.cod_municipio := self.FQuery.FieldByName('cod_municipio').AsInteger; Empresa.taxa_entrega := self.FQuery.FieldByName('taxa_entrega').AsFloat; result := Empresa; end; function TRepositorioEmpresa.GetIdentificador(Objeto: TObject): Variant; begin result := TEmpresa(Objeto).Codigo; end; function TRepositorioEmpresa.GetNomeDaTabela: String; begin result := 'EMPRESA'; end; function TRepositorioEmpresa.GetRepositorio: TRepositorio; begin result := TRepositorioEmpresa.Create; end; function TRepositorioEmpresa.IsInsercao(Objeto: TObject): Boolean; begin result := (TEmpresa(Objeto).Codigo <= 0); end; procedure TRepositorioEmpresa.SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); var EmpresaAntigo :TEmpresa; EmpresaNovo :TEmpresa; begin EmpresaAntigo := (AntigoObjeto as TEmpresa); EmpresaNovo := (Objeto as TEmpresa); if (EmpresaAntigo.razao_social <> EmpresaNovo.razao_social) then Auditoria.AdicionaCampoAlterado('razao_social', EmpresaAntigo.razao_social, EmpresaNovo.razao_social); if (EmpresaAntigo.nome_fantasia <> EmpresaNovo.nome_fantasia) then Auditoria.AdicionaCampoAlterado('nome_fantasia', EmpresaAntigo.nome_fantasia, EmpresaNovo.nome_fantasia); if (EmpresaAntigo.cnpj <> EmpresaNovo.cnpj) then Auditoria.AdicionaCampoAlterado('cnpj', EmpresaAntigo.cnpj, EmpresaNovo.cnpj); if (EmpresaAntigo.ie <> EmpresaNovo.ie) then Auditoria.AdicionaCampoAlterado('ie', EmpresaAntigo.ie, EmpresaNovo.ie); if (EmpresaAntigo.telefone <> EmpresaNovo.telefone) then Auditoria.AdicionaCampoAlterado('telefone', EmpresaAntigo.telefone, EmpresaNovo.telefone); if (EmpresaAntigo.site <> EmpresaNovo.site) then Auditoria.AdicionaCampoAlterado('site', EmpresaAntigo.site, EmpresaNovo.site); if (EmpresaAntigo.quantidade_mesas <> EmpresaNovo.quantidade_mesas) then Auditoria.AdicionaCampoAlterado('quantidade_mesas', IntToStr(EmpresaAntigo.quantidade_mesas), IntToStr(EmpresaNovo.quantidade_mesas)); if (EmpresaAntigo.couvert <> EmpresaNovo.couvert) then Auditoria.AdicionaCampoAlterado('couvert', IfThen(EmpresaAntigo.Couvert, 'S', 'N'), IfThen(EmpresaNovo.Couvert, 'S', 'N')); if (EmpresaAntigo.valor_couvert <> EmpresaNovo.valor_couvert) then Auditoria.AdicionaCampoAlterado('valor_couvert', FloatToStr(EmpresaAntigo.valor_couvert), FloatToStr(EmpresaNovo.valor_couvert)); if (EmpresaAntigo.cidade <> EmpresaNovo.cidade) then Auditoria.AdicionaCampoAlterado('cidade', EmpresaAntigo.cidade, EmpresaNovo.cidade); if (EmpresaAntigo.taxa_servico <> EmpresaNovo.taxa_servico) then Auditoria.AdicionaCampoAlterado('taxa_servico', FloatToStr(EmpresaAntigo.taxa_servico), FloatToStr(EmpresaNovo.taxa_servico)); if (EmpresaAntigo.aliquota_couvert <> EmpresaNovo.aliquota_couvert) then Auditoria.AdicionaCampoAlterado('aliquota_couvert', FloatToStr(EmpresaAntigo.aliquota_couvert), FloatToStr(EmpresaNovo.aliquota_couvert)); if (EmpresaAntigo.aliquota_txservico <> EmpresaNovo.aliquota_txservico) then Auditoria.AdicionaCampoAlterado('aliquota_txservico', FloatToStr(EmpresaAntigo.aliquota_txservico), FloatToStr(EmpresaNovo.aliquota_txservico)); if (EmpresaAntigo.tributacao_couvert <> EmpresaNovo.tributacao_couvert) then Auditoria.AdicionaCampoAlterado('tributacao_couvert', EmpresaAntigo.tributacao_couvert, EmpresaNovo.tributacao_couvert); if (EmpresaAntigo.tributacao_txservico <> EmpresaNovo.tributacao_txservico) then Auditoria.AdicionaCampoAlterado('tributacao_txservico', EmpresaAntigo.tributacao_txservico, EmpresaNovo.tributacao_txservico); if (EmpresaAntigo.diretorio_boliche <> EmpresaNovo.diretorio_boliche) then Auditoria.AdicionaCampoAlterado('diretorio_boliche', EmpresaAntigo.diretorio_boliche, EmpresaNovo.diretorio_boliche); if (EmpresaAntigo.diretorio_dispensadora <> EmpresaNovo.diretorio_dispensadora) then Auditoria.AdicionaCampoAlterado('diretorio_dispensadora', EmpresaAntigo.diretorio_dispensadora, EmpresaNovo.diretorio_dispensadora); if (EmpresaAntigo.estado <> EmpresaNovo.estado) then Auditoria.AdicionaCampoAlterado('estado', EmpresaAntigo.estado, EmpresaNovo.estado); if (EmpresaAntigo.cep <> EmpresaNovo.cep) then Auditoria.AdicionaCampoAlterado('cep', IntToStr(EmpresaAntigo.cep), IntToStr(EmpresaNovo.cep)); if (EmpresaAntigo.rua <> EmpresaNovo.rua) then Auditoria.AdicionaCampoAlterado('rua', EmpresaAntigo.rua, EmpresaNovo.rua); if (EmpresaAntigo.numero <> EmpresaNovo.numero) then Auditoria.AdicionaCampoAlterado('numero', EmpresaAntigo.numero, EmpresaNovo.numero); if (EmpresaAntigo.bairro <> EmpresaNovo.bairro) then Auditoria.AdicionaCampoAlterado('bairro', EmpresaAntigo.bairro, EmpresaNovo.bairro); if (EmpresaAntigo.complemento <> EmpresaNovo.complemento) then Auditoria.AdicionaCampoAlterado('complemento', EmpresaAntigo.complemento, EmpresaNovo.complemento); if (EmpresaAntigo.cod_municipio <> EmpresaNovo.cod_municipio) then Auditoria.AdicionaCampoAlterado('cod_municipio', IntToStr(EmpresaAntigo.cod_municipio), IntToStr(EmpresaNovo.cod_municipio)); if (EmpresaAntigo.taxa_entrega <> EmpresaNovo.taxa_entrega) then Auditoria.AdicionaCampoAlterado('taxa_entrega', FloatToStr(EmpresaAntigo.taxa_entrega), FloatToStr(EmpresaNovo.taxa_entrega)); end; procedure TRepositorioEmpresa.SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); var Empresa :TEmpresa; begin Empresa := (Objeto as TEmpresa); Auditoria.AdicionaCampoExcluido('codigo' , IntToStr(Empresa.codigo)); Auditoria.AdicionaCampoExcluido('razao_social' , Empresa.razao_social); Auditoria.AdicionaCampoExcluido('nome_fantasia' , Empresa.nome_fantasia); Auditoria.AdicionaCampoExcluido('cnpj' , Empresa.cnpj); Auditoria.AdicionaCampoExcluido('ie' , Empresa.ie); Auditoria.AdicionaCampoExcluido('telefone' , Empresa.telefone); Auditoria.AdicionaCampoExcluido('site' , Empresa.site); Auditoria.AdicionaCampoExcluido('quantidade_mesas' , IntToStr(Empresa.quantidade_mesas)); Auditoria.AdicionaCampoExcluido('couvert' , IfThen(Empresa.couvert, 'S', 'N')); Auditoria.AdicionaCampoExcluido('valor_couvert' , FloatToStr(Empresa.valor_couvert)); Auditoria.AdicionaCampoExcluido('cidade' , Empresa.cidade); Auditoria.AdicionaCampoExcluido('taxa_servico' , FloatToStr(Empresa.taxa_servico)); Auditoria.AdicionaCampoExcluido('aliquota_couvert' , FloatToStr(Empresa.aliquota_couvert)); Auditoria.AdicionaCampoExcluido('aliquota_txservico' , FloatToStr(Empresa.aliquota_txservico)); Auditoria.AdicionaCampoExcluido('tributacao_couvert' , Empresa.tributacao_couvert); Auditoria.AdicionaCampoExcluido('tributacao_txservico' , Empresa.tributacao_txservico); Auditoria.AdicionaCampoExcluido('diretorio_boliche' , Empresa.diretorio_boliche); Auditoria.AdicionaCampoExcluido('diretorio_dispensadora', Empresa.diretorio_dispensadora); Auditoria.AdicionaCampoExcluido('estado' , Empresa.estado); Auditoria.AdicionaCampoExcluido('cep' , IntToStr(Empresa.cep)); Auditoria.AdicionaCampoExcluido('rua' , Empresa.rua); Auditoria.AdicionaCampoExcluido('numero' , Empresa.numero); Auditoria.AdicionaCampoExcluido('bairro' , Empresa.bairro); Auditoria.AdicionaCampoExcluido('complemento' , Empresa.complemento); Auditoria.AdicionaCampoExcluido('cod_municipio' , IntToStr(Empresa.cod_municipio)); Auditoria.AdicionaCampoExcluido('taxa_entrega' , FloatToStr(Empresa.taxa_entrega)); end; procedure TRepositorioEmpresa.SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); var Empresa :TEmpresa; begin Empresa := (Objeto as TEmpresa); Auditoria.AdicionaCampoIncluido('codigo' , IntToStr(Empresa.codigo)); Auditoria.AdicionaCampoIncluido('razao_social' , Empresa.razao_social); Auditoria.AdicionaCampoIncluido('nome_fantasia' , Empresa.nome_fantasia); Auditoria.AdicionaCampoIncluido('cnpj' , Empresa.cnpj); Auditoria.AdicionaCampoIncluido('ie' , Empresa.ie); Auditoria.AdicionaCampoIncluido('telefone' , Empresa.telefone); Auditoria.AdicionaCampoIncluido('site' , Empresa.site); Auditoria.AdicionaCampoIncluido('quantidade_mesas' , IntToStr(Empresa.quantidade_mesas)); Auditoria.AdicionaCampoIncluido('couvert' , IfThen(Empresa.couvert, 'S', 'N')); Auditoria.AdicionaCampoIncluido('valor_couvert' , FloatToStr(Empresa.valor_couvert)); Auditoria.AdicionaCampoIncluido('cidade' , Empresa.cidade); Auditoria.AdicionaCampoIncluido('taxa_servico' , FloatToStr(Empresa.taxa_servico)); Auditoria.AdicionaCampoIncluido('aliquota_couvert' , FloatToStr(Empresa.aliquota_couvert)); Auditoria.AdicionaCampoIncluido('aliquota_txservico' , FloatToStr(Empresa.aliquota_txservico)); Auditoria.AdicionaCampoIncluido('tributacao_couvert' , Empresa.tributacao_couvert); Auditoria.AdicionaCampoIncluido('tributacao_txservico' , Empresa.tributacao_txservico); Auditoria.AdicionaCampoIncluido('diretorio_boliche' , Empresa.diretorio_boliche); Auditoria.AdicionaCampoIncluido('diretorio_dispensadora', Empresa.diretorio_dispensadora); Auditoria.AdicionaCampoIncluido('estado' , Empresa.estado); Auditoria.AdicionaCampoIncluido('cep' , IntToStr(Empresa.cep)); Auditoria.AdicionaCampoIncluido('rua' , Empresa.rua); Auditoria.AdicionaCampoIncluido('numero' , Empresa.numero); Auditoria.AdicionaCampoIncluido('bairro' , Empresa.bairro); Auditoria.AdicionaCampoIncluido('complemento' , Empresa.complemento); Auditoria.AdicionaCampoIncluido('cod_municipio' , IntToStr(Empresa.cod_municipio)); Auditoria.AdicionaCampoIncluido('taxa_entrega' , FloatToStr(Empresa.taxa_entrega)); end; procedure TRepositorioEmpresa.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TEmpresa(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioEmpresa.SetParametros(Objeto: TObject); var Empresa :TEmpresa; begin Empresa := (Objeto as TEmpresa); self.FQuery.ParamByName('codigo').AsInteger := Empresa.codigo; self.FQuery.ParamByName('razao_social').AsString := Empresa.razao_social; self.FQuery.ParamByName('nome_fantasia').AsString := Empresa.nome_fantasia; self.FQuery.ParamByName('cnpj').AsString := Empresa.cnpj; self.FQuery.ParamByName('ie').AsString := Empresa.ie; self.FQuery.ParamByName('telefone').AsString := Empresa.telefone; self.FQuery.ParamByName('site').AsString := Empresa.site; self.FQuery.ParamByName('quantidade_mesas').AsInteger := Empresa.quantidade_mesas; self.FQuery.ParamByName('couvert').AsString := IfThen(Empresa.couvert, 'S', 'N'); self.FQuery.ParamByName('valor_couvert').AsFloat := Empresa.valor_couvert; self.FQuery.ParamByName('cidade').AsString := Empresa.cidade; self.FQuery.ParamByName('taxa_servico').AsFloat := Empresa.taxa_servico; self.FQuery.ParamByName('aliquota_couvert').AsFloat := Empresa.aliquota_couvert; self.FQuery.ParamByName('aliquota_txservico').AsFloat := Empresa.aliquota_txservico; self.FQuery.ParamByName('tributacao_couvert').AsString := Empresa.tributacao_couvert; self.FQuery.ParamByName('tributacao_txservico').AsString := Empresa.tributacao_txservico; self.FQuery.ParamByName('diretorio_boliche').AsString := Empresa.diretorio_boliche; self.FQuery.ParamByName('diretorio_dispensadora').AsString := Empresa.diretorio_dispensadora; self.FQuery.ParamByName('estado').AsString := Empresa.estado; self.FQuery.ParamByName('cep').AsInteger := Empresa.cep; self.FQuery.ParamByName('rua').AsString := Empresa.rua; self.FQuery.ParamByName('numero').AsString := Empresa.numero; self.FQuery.ParamByName('bairro').AsString := Empresa.bairro; self.FQuery.ParamByName('complemento').AsString := Empresa.complemento; self.FQuery.ParamByName('cod_municipio').AsInteger := Empresa.cod_municipio; self.FQuery.ParamByName('taxa_entrega').AsFloat := Empresa.taxa_entrega; end; function TRepositorioEmpresa.SQLGet: String; begin result := 'select * from EMPRESA where codigo = :ncod'; end; function TRepositorioEmpresa.SQLGetAll: String; begin result := 'select * from EMPRESA'; end; function TRepositorioEmpresa.SQLGetExiste(campo: String): String; begin result := 'select '+ campo +' from EMPRESA where '+ campo +' = :ncampo'; end; function TRepositorioEmpresa.SQLRemover: String; begin result := ' delete from EMPRESA where codigo = :codigo '; end; function TRepositorioEmpresa.SQLSalvar: String; begin result := 'update or insert into EMPRESA (CODIGO ,RAZAO_SOCIAL ,NOME_FANTASIA ,CNPJ ,IE ,TELEFONE ,SITE ,QUANTIDADE_MESAS , '+ ' COUVERT ,VALOR_COUVERT ,CIDADE ,TAXA_SERVICO ,ALIQUOTA_COUVERT ,ALIQUOTA_TXSERVICO , '+ ' TRIBUTACAO_COUVERT ,TRIBUTACAO_TXSERVICO ,DIRETORIO_BOLICHE ,DIRETORIO_DISPENSADORA , '+ ' ESTADO ,CEP ,RUA ,NUMERO ,BAIRRO ,COMPLEMENTO ,COD_MUNICIPIO) '+ ' values ( :CODIGO, :RAZAO_SOCIAL, :NOME_FANTASIA, :CNPJ, :IE, :TELEFONE, :SITE, :QUANTIDADE_MESAS, '+ ' :COUVERT, :VALOR_COUVERT, :CIDADE, :TAXA_SERVICO, :ALIQUOTA_COUVERT, :ALIQUOTA_TXSERVICO,'+ ' :TRIBUTACAO_COUVERT, :TRIBUTACAO_TXSERVICO, :DIRETORIO_BOLICHE, :DIRETORIO_DISPENSADORA, '+ ' :ESTADO, :CEP, :RUA, :NUMERO, :BAIRRO, :COMPLEMENTO, :COD_MUNICIPIO) '; end; end.
program shadowborder; {$IFNDEF HASAMIGA} {$FATAL This source is compatible with Amiga, AROS and MorphOS only !} {$ENDIF} { Project : shadowborder Topic : program to show the use of an Intuition Border. Source : RKRM } {* ** The following example draws a double border using two pens to create a ** shadow effect. The border is drawn in two positions to show the ** flexibility in positioning borders, note that it could also be attached ** to a menu, gadget or requester. *} {$MODE OBJFPC}{$H+}{$HINTS ON} {$UNITPATH ../../../Base/CHelpers} {$UNITPATH ../../../Base/Trinity} {$DEFINE INTUI_V36_NAMES_ONLY} Uses Exec, AmigaDOS, AGraphics, Intuition, Utility, {$IFDEF AMIGA} SystemVarTags, {$ENDIF} CHelpers, Trinity; Type PUWORD = ^UWORD; var {$IFDEF AMIGA} IntuitionBase : PLibrary absolute _Intuitionbase; {$ENDIF} {$IFDEF AROS} IntuitionBase : PLibrary absolute Intuition.Intuitionbase; {$ENDIF} {$IFDEF MORPHOS} IntuitionBase : PLibrary absolute Intuition.Intuitionbase; {$ENDIF} const MYBORDER_LEFT = (0); MYBORDER_TOP = (0); var //* This is the border data. */ myBorderData : array [0..9] of SmallInt = ( 0,0, 50,0, 50,30, 0,30, 0,0 ); {* ** main routine. Open required library and window and draw the images. ** This routine opens a very simple window with no IDCMP. See the ** chapters on "Windows" and "Input and Output Methods" for more info. ** Free all resources when done. *} procedure Main(argc: integer; argv: PPChar); var screen : PScreen; drawinfo : PDrawInfo; win : PWindow; shineBorder : TBorder; shadowBorder : TBorder; mySHADOWPEN : ULONG = 1; //* set default values for pens */ mySHINEPEN : ULONG = 2; //* in case can't get info... */ begin {$IFDEF MORPHOS} IntuitionBase := OpenLibrary('intuition.library', 37); {$ENDIF} if assigned(IntuitionBase) then begin if SetAndTest(screen, LockPubScreen(nil)) then begin if SetAndTest(drawinfo, GetScreenDrawInfo(screen)) then begin {* Get a copy of the correct pens for the screen. ** This is very important in case the user or the ** application has the pens set in a unusual way. *} mySHADOWPEN := PUWORD(drawinfo^.dri_Pens)[SHADOWPEN]; mySHINEPEN := PUWORD(drawinfo^.dri_Pens)[SHINEPEN]; FreeScreenDrawInfo(screen, drawinfo); end; UnlockPubScreen(nil, screen); end; {* open a simple window on the workbench screen for displaying ** a border. An application would probably never use such a ** window, but it is useful for demonstrating graphics... *} if SetAndTest(win, OpenWindowTags(nil, [ TAG_(WA_PubScreen) , TAG_(screen), TAG_(WA_RMBTrap) , TAG_(TRUE), TAG_END ])) then begin //* set information specific to the shadow component of the border */ shadowBorder.LeftEdge := MYBORDER_LEFT + 1; shadowBorder.TopEdge := MYBORDER_TOP + 1; shadowBorder.FrontPen := mySHADOWPEN; shadowBorder.NextBorder := @shineBorder; //* set information specific to the shine component of the border */ shineBorder.LeftEdge := MYBORDER_LEFT; shineBorder.TopEdge := MYBORDER_TOP; shineBorder.FrontPen := mySHINEPEN; shineBorder.NextBorder := nil; //* the following attributes are the same for both borders. */ shineBorder.BackPen := 0; shineBorder.DrawMode := JAM1; shineBorder.Count := 5; shineBorder.XY := @myBorderData; shadowBorder.BackPen := shineBorder.BackPen; shadowBorder.DrawMode := shineBorder.DrawMode; shadowBorder.Count := shineBorder.Count; shadowBorder.XY := shineBorder.XY; //* Draw the border at 10,10 */ DrawBorder(win^.RPort, @shadowBorder, 10, 10); //* Draw the border again at 100,10 */ DrawBorder(win^.RPort, @shadowBorder, 100, 10); {* Wait a bit, then quit. ** In a real application, this would be an event loop, like the ** one described in the Intuition Input and Output Methods chapter. *} DOSDelay(200); CloseWindow(win); end; {$IFDEF MORPHOS} CloseLibrary(IntuitionBase); {$ENDIF} end; end; begin Main(ArgC, ArgV); end.
unit ccCodeVariables; interface uses Windows, Classes, SysUtils, Math, StrUtils, Dialogs, ccCodeMain; type TVar = class(TObject) Name:String; T:String; Value:String; Loc: Pointer; end; var VarList: TStringList; GlobalConst:TVar; function GetVar(S:String; Data:TsFunctionData):TVar; procedure AddVar(A:TVar; List:TStringList); procedure MakeVar(Name,T:String; Data:TsFunctionData); procedure SetVar(Name,V:String; Data:TsFunctionData); procedure FreeVar(S:String; Data:TsFunctionData); function GetVarValue(S:String; Data:TsFunctionData):String; function ToVars(S:String):TStringList; procedure DefaultVar(Vr:TVar); procedure Constant(Name, Data:String); implementation uses ccCodeStrings, ccCodeNumbers, ccCodeBools, ccCodeFuncs; function ToVars(S:String):TStringList; var i:Integer;Ss:String; begin Result := TStringList.Create; for i := 1 to Length(S) do begin if S[i]=',' then begin Result.Add(Trim(Ss)); Ss := ''; end else Ss := Ss+S[i]; end; end; procedure DefaultVar(Vr:TVar); begin if Vr.T = 'int' then Vr.Value := '0' else if Vr.T = 'string' then Vr.Value := '' else if Vr.T = 'boolean' then Vr.Value := '0' end; procedure SetVar(Name,V:String; Data:TsFunctionData); var Vr:TVar; begin Vr := GetVar(Name, Data); if Vr.T = 'int' then Vr.Value := ParseInt(V, Data) else if Vr.T = 'string' then Vr.Value := ParseStr(V, Data) else if Vr.T = 'boolean' then Vr.Value := ParseBool(V, Data); Debug('Var: '+Name +' is now "'+Vr.Value+'"'); end; procedure MakeVar(Name,T:String; Data:TsFunctionData); var A:TVar; begin A := TVar.Create; A.Name := Name; A.T := T; DefaultVar(A); AddVar(A, Data.Vars); Debug('Made '''+Name+''' as '''+T+''''); end; function GetVar(S:String; Data:TsFunctionData):TVar; var i:Integer; begin Result := nil; I := Data.Vars.IndexOf(S); if i <> -1 then begin Result := TVar(Data.Vars.Objects[i]); Exit; end; I := Data.Func.Script.Vars.IndexOf(S); if i <> -1 then begin Result := TVar(Data.Func.Script.Vars.Objects[i]); Exit; end; I := VarList.IndexOf(S); if i <> -1 then begin Result := TVar(VarList.Objects[i]); Exit; end; end; function GetVarValue(S:String; Data:TsFunctionData):String; begin Result := GetVar(S, Data).Value; // Result := '1'; end; procedure AddVar(A:TVar; List:TStringList); begin List.AddObject(A.Name, A); end; procedure FreeVar(S:String; Data:TsFunctionData); var I:Integer; begin I := VarList.IndexOf(S); TVar(i).Free; VarList.Delete(i); Debug('Cleaned '+S); end; procedure Constant(Name, Data:String); var GlobalConst:TVar; begin GlobalConst := TVar.Create; GlobalConst.Name := Name; GlobalConst.Value := Data; AddVar(GlobalConst, VarList); end; initialization DecimalSeparator := '.'; VarList := TStringList.Create; Constant('true', '1'); Constant('false', '0'); end.
unit fEnemy; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GR32_Image, GR32, BCData; type TfrmEnemyEditor = class(TForm) cmdOK: TButton; cmdCancel: TButton; imgLevelTanks: TImage32; grpEnemy1: TGroupBox; imgEnemy1: TImage32; lblEnemyType1: TLabel; lblShieldStrength1: TLabel; chkGivePowerup1: TCheckBox; lblAmount1: TLabel; grpEnemy2: TGroupBox; lblEnemyType2: TLabel; lblShieldStrength2: TLabel; lblAmount2: TLabel; imgEnemy2: TImage32; chkGivePowerup2: TCheckBox; grpEnemy3: TGroupBox; lblEnemyType3: TLabel; lblShieldStrength3: TLabel; lblAmount3: TLabel; imgEnemy3: TImage32; chkGivePowerup3: TCheckBox; grpEnemy4: TGroupBox; lblEnemyType4: TLabel; lblShieldStrength4: TLabel; lblAmount4: TLabel; imgEnemy4: TImage32; chkGivePowerup4: TCheckBox; lblLevelTanks: TLabel; txtEnemy1Type: TEdit; txtAmount1: TEdit; txtShieldStrength1: TEdit; txtEnemyType2: TEdit; txtAmount2: TEdit; txtShieldStrength2: TEdit; txtEnemyType3: TEdit; txtShieldStrength3: TEdit; txtAmount3: TEdit; txtEnemyType4: TEdit; txtShieldStrength4: TEdit; txtAmount4: TEdit; procedure FormShow(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure txtEnemy1TypeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtEnemyType2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtEnemyType3KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtEnemyType4KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtAmount1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtAmount2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtAmount3KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure txtAmount4KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure cmdCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private _BattleCityROM : TBattleCityROM; procedure DisplayEnemy; procedure SaveEnemy; procedure LoadEnemy; procedure DrawAllTanks; procedure DisplayTankGFX(pIndex: Integer); procedure DrawEnemyList; { Private declarations } public { Public declarations } constructor Create(AOwner: TComponent; ROMData: TBattleCityROM); end; var frmEnemyEditor: TfrmEnemyEditor; TanksGFX : TBitmap32; // TankList : Array [0..19] of Byte; implementation {$R *.dfm} uses fBattleCity, uGlobals; procedure TfrmEnemyEditor.DisplayEnemy(); begin // Display the first enemy { txtEnemy1Type.Text := IntToStr(EnemyTypes[0].EnemyType); txtAmount1.Text := IntToStr(EnemyTypes[0].Amount); txtShieldStrength1.Text := IntToStr(EnemyTypes[0].ShieldStrength); if EnemyTypes[0].Powerups > 0 then chkGivePowerup1.Checked := true else chkGivePowerup1.Checked := false; // Display the second enemy txtEnemyType2.Text := IntToStr(EnemyTypes[1].EnemyType); txtAmount2.Text := IntToStr(EnemyTypes[1].Amount); txtShieldStrength2.Text := IntToStr(EnemyTypes[1].ShieldStrength); if EnemyTypes[1].Powerups > 0 then chkGivePowerup2.Checked := true else chkGivePowerup2.Checked := false; // Display the third enemy txtEnemyType3.Text := IntToStr(EnemyTypes[2].EnemyType); txtAmount3.Text := IntToStr(EnemyTypes[2].Amount); txtShieldStrength3.Text := IntToStr(EnemyTypes[2].ShieldStrength); if EnemyTypes[2].Powerups > 0 then chkGivePowerup3.Checked := true else chkGivePowerup3.Checked := false; // Display the fourth enemy txtEnemyType4.Text := IntToStr(EnemyTypes[3].EnemyType); txtAmount4.Text := IntToStr(EnemyTypes[3].Amount); txtShieldStrength4.Text := IntToStr(EnemyTypes[3].ShieldStrength); if EnemyTypes[3].Powerups > 0 then chkGivePowerup4.Checked := true else chkGivePowerup4.Checked := false;} end; procedure TfrmEnemyEditor.LoadEnemy(); var EnemyByte : Byte; begin // Load the first enemy { EnemyByte :=BattleCityROM.ROM[EnemyLoc[frmBattleCity.CurrentLevel]]; EnemyTypes[0].EnemyType := EnemyByte Shr 5; EnemyTypes[0].Unused1 := (Enemybyte Shr 4) and 1; EnemyTypes[0].Unused2 := (Enemybyte Shr 3) and 1; EnemyTypes[0].Powerups := (EnemyByte Shr 2) and 1; EnemyTypes[0].ShieldStrength := EnemyByte and 3; EnemyTypes[0].Amount :=BattleCityROM.ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]]; // Load the second enemy EnemyByte :=BattleCityROM.ROM[EnemyLoc[frmBattleCity.CurrentLevel]+1]; EnemyTypes[1].EnemyType := EnemyByte Shr 5; EnemyTypes[1].Unused1 := (Enemybyte Shr 4) and 1; EnemyTypes[1].Unused2 := (Enemybyte Shr 3) and 1; EnemyTypes[1].Powerups := (EnemyByte Shr 2) and 1; EnemyTypes[1].ShieldStrength := EnemyByte and 3; EnemyTypes[1].Amount :=BattleCityROM.ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]+1]; // Load the third enemy EnemyByte :=BattleCityROM.ROM[EnemyLoc[frmBattleCity.CurrentLevel]+2]; EnemyTypes[2].EnemyType := EnemyByte Shr 5; EnemyTypes[2].Unused1 := (Enemybyte Shr 4) and 1; EnemyTypes[2].Unused2 := (Enemybyte Shr 3) and 1; EnemyTypes[2].Powerups := (EnemyByte Shr 2) and 1; EnemyTypes[2].ShieldStrength := EnemyByte and 3; EnemyTypes[2].Amount :=BattleCityROM.ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]+2]; // Load the fourth enemy EnemyByte :=BattleCityROM.ROM[EnemyLoc[frmBattleCity.CurrentLevel]+3]; EnemyTypes[3].EnemyType := EnemyByte Shr 5; EnemyTypes[3].Unused1 := (Enemybyte Shr 4) and 1; EnemyTypes[3].Unused2 := (Enemybyte Shr 3) and 1; EnemyTypes[3].Powerups := (EnemyByte Shr 2) and 1; EnemyTypes[3].ShieldStrength := EnemyByte and 3; EnemyTypes[3].Amount :=BattleCityROM.ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]+3];} end; procedure TfrmEnemyEditor.SaveEnemy(); var EnemyByte : Byte; begin // Display the first enemy { EnemyTypes[0].EnemyType := StrToInt(txtEnemy1Type.Text); EnemyTypes[0].Amount := StrToInt(txtAmount1.Text); EnemyTypes[0].ShieldStrength := StrToInt(txtShieldStrength1.Text); if chkGivePowerup1.Checked = true then EnemyTypes[0].Powerups := 1 else EnemyTypes[0].Powerups := 0; // Display the first enemy EnemyTypes[1].EnemyType := StrToInt(txtEnemyType2.Text); EnemyTypes[1].Amount := StrToInt(txtAmount2.Text); EnemyTypes[1].ShieldStrength := StrToInt(txtShieldStrength2.Text); if chkGivePowerup2.Checked = true then EnemyTypes[1].Powerups := 1 else EnemyTypes[1].Powerups := 0; // Display the first enemy EnemyTypes[2].EnemyType := StrToInt(txtEnemyType3.Text); EnemyTypes[2].Amount := StrToInt(txtAmount3.Text); EnemyTypes[2].ShieldStrength := StrToInt(txtShieldStrength3.Text); if chkGivePowerup3.Checked = true then EnemyTypes[2].Powerups := 1 else EnemyTypes[2].Powerups := 0; // Display the first enemy EnemyTypes[3].EnemyType := StrToInt(txtEnemyType4.Text); EnemyTypes[3].Amount := StrToInt(txtAmount4.Text); EnemyTypes[3].ShieldStrength := StrToInt(txtShieldStrength4.Text); if chkGivePowerup4.Checked = true then EnemyTypes[3].Powerups := 1 else EnemyTypes[3].Powerups := 0; // Save the first enemy EnemyByte := EnemyTypes[0].EnemyType shl 5; EnemyByte := EnemyByte + EnemyTypes[0].Unused1 shl 4; EnemyByte := EnemyByte + EnemyTypes[0].Unused2 shl 3; EnemyByte := EnemyByte + EnemyTypes[0].Powerups shl 2; EnemyByte := EnemyByte + EnemyTypes[0].ShieldStrength; BattleCityROM.ROM[EnemyLoc[frmBattleCity.CurrentLevel]] := EnemyByte; BattleCityROM.ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]] := EnemyTypes[0].Amount; // Save the second enemy EnemyByte := EnemyTypes[1].EnemyType shl 5; EnemyByte := EnemyByte + EnemyTypes[1].Unused1 shl 4; EnemyByte := EnemyByte + EnemyTypes[1].Unused2 shl 3; EnemyByte := EnemyByte + EnemyTypes[1].Powerups shl 2; EnemyByte := EnemyByte + EnemyTypes[1].ShieldStrength; BattleCityROM.ROM[EnemyLoc[frmBattleCity.CurrentLevel]+1] := EnemyByte; BattleCityROM.ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]+1] := EnemyTypes[1].Amount; // Save the third enemy EnemyByte := EnemyTypes[2].EnemyType shl 5; EnemyByte := EnemyByte + EnemyTypes[2].Unused1 shl 4; EnemyByte := EnemyByte + EnemyTypes[2].Unused2 shl 3; EnemyByte := EnemyByte + EnemyTypes[2].Powerups shl 2; EnemyByte := EnemyByte + EnemyTypes[2].ShieldStrength; BattleCityROM.ROM[EnemyLoc[frmBattleCity.CurrentLevel]+2] := EnemyByte; BattleCityROM.ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]+2] := EnemyTypes[2].Amount; // Save the fourth enemy EnemyByte := EnemyTypes[3].EnemyType shl 5; EnemyByte := EnemyByte + EnemyTypes[3].Unused1 shl 4; EnemyByte := EnemyByte + EnemyTypes[3].Unused2 shl 3; EnemyByte := EnemyByte + EnemyTypes[3].Powerups shl 2; EnemyByte := EnemyByte + EnemyTypes[3].ShieldStrength; BattleCityROM.ROM[EnemyLoc[frmBattleCity.CurrentLevel]+3] := EnemyByte; BattleCityROM.ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]+3] := EnemyTypes[3].Amount;} { EnemyTypes[0].EnemyType := EnemyByte Shr 5; EnemyTypes[0].Unused1 := (Enemybyte Shr 4) and 1; EnemyTypes[0].Unused1 := (Enemybyte Shr 3) and 1; EnemyTypes[0].Powerups := (EnemyByte Shr 2) and 1; EnemyTypes[0].ShieldStrength := EnemyByte and 3; EnemyTypes[0].Amount :=ROM[EnemyNumbersLoc[frmBattleCity.CurrentLevel]];} end; procedure TfrmEnemyEditor.DrawAllTanks(); var i : Integer; begin { if TanksGFX = nil then TanksGFX := TBitmap32.Create; try TanksGFX.Width := 128; TanksGFX.Height := 16; // Draw tank type 1 for i := 0 to 7 do begin DrawNESTile(SpritePatternTable + ((i*$20)*16), TanksGFX,(i*16) + 0,0,2); DrawNESTile(SpritePatternTable + ((i*$20)*16) + 16, TanksGFX,(i*16) + 0,8,2); DrawNESTile(SpritePatternTable + ((i*$20)*16) + 32, TanksGFX,(i*16) + 8,0,2); DrawNESTile(SpritePatternTable + ((i*$20)*16) + 48, TanksGFX,(i*16) + 8,8,2); end; // TanksGFX.SaveToFile('C:\test.bmp'); except ShowMessage('An unknown error occurred'); end;} end; procedure TfrmEnemyEditor.DisplayTankGFX(pIndex : Integer); var TankBitmap : TBitmap32; begin TankBitmap := TBitmap32.Create; try TankBitmap.Width := 16; TankBitmap.Height := 16; if pIndex = 0 then begin TankBitmap.Draw(bounds(0,0,16,16),bounds(StrToInt(txtEnemy1Type.Text)*16,0,16,16),TanksGFX); imgEnemy1.Bitmap := TankBitmap; end else if pIndex = 1 then begin TankBitmap.Draw(bounds(0,0,16,16),bounds(StrToInt(txtEnemyType2.Text)*16,0,16,16),TanksGFX); imgEnemy2.Bitmap := TankBitmap; end else if pIndex = 2 then begin TankBitmap.Draw(bounds(0,0,16,16),bounds(StrToInt(txtEnemyType3.Text)*16,0,16,16),TanksGFX); imgEnemy3.Bitmap := TankBitmap; end else if pIndex = 3 then begin TankBitmap.Draw(bounds(0,0,16,16),bounds(StrToInt(txtEnemyType4.Text) *16,0,16,16),TanksGFX); imgEnemy4.Bitmap := TankBitmap; end; finally FreeAndNil(TankBitmap); end; end; procedure TfrmEnemyEditor.DrawEnemyList(); var Position : Integer; TankList : TBitmap32; TankListArr : Array Of Byte; NumberOfTanks, EndTank, i : Integer; Amount1, Amount2, Amount3, Amount4 : Integer; begin Position := 0; Amount1 := StrToInt(txtAmount1.Text); Amount2 := StrToInt(txtAmount2.Text); Amount3 := StrToInt(txtAmount3.Text); Amount4 := StrToInt(txtAmount4.Text); NumberOfTanks := Amount1 + Amount2 + Amount3 + Amount4; SetLength(TankListArr,NumberOfTanks); for i := 0 to Amount1 -1 do TankListArr[i] := StrToInt(txtEnemy1Type.Text); for i := Amount1 to Amount1+Amount2 - 1 do TankListArr[i] := StrToInt(txtEnemyType2.Text); for i := Amount1+Amount2 to Amount1 + Amount2 + Amount3 - 1 do TankListArr[i] := StrToInt(txtEnemyType3.Text); for i := Amount1+Amount2 + Amount3 to Amount1 + Amount2 + Amount3 + Amount4 - 1 do TankListArr[i] := StrToInt(txtEnemyType4.Text); TankList := TBitmap32.Create; try TankList.Width := 32; TankList.Height := 160; if NumberOfTanks < 20 then EndTank := NumberOfTanks else EndTank := 20; while (Position < EndTank) do begin TankList.Draw(bounds((Position mod 2)*16,(Position div 2)*16,16,16),bounds(TankListArr[Position]*16,0,16,16),TanksGFX); // TanksGFX Position div 2 inc(Position); end; imgLevelTanks.Bitmap := TankList; finally SetLength(TankListArr,0); FreeAndNil(TankList); end; end; procedure TfrmEnemyEditor.FormShow(Sender: TObject); begin LoadEnemy(); DrawAllTanks(); DisplayEnemy(); DisplayTankGFX(0); DisplayTankGFX(1); DisplayTankGFX(2); DisplayTankGFX(3); DrawEnemyList(); end; procedure TfrmEnemyEditor.cmdOKClick(Sender: TObject); begin SaveEnemy(); FreeAndNil(TanksGFX); end; constructor TfrmEnemyEditor.Create(AOwner: TComponent; ROMData: TBattleCityROM); begin inherited Create(AOwner); _BattleCityROM := ROMData; end; procedure TfrmEnemyEditor.txtEnemy1TypeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if StrToInt(txtEnemy1Type.Text) > 7 then txtEnemy1Type.Text := '7'; if StrToInt(txtEnemy1Type.Text) < 0 then txtEnemy1Type.Text := '0'; DisplayTankGFX(0); DrawEnemyList(); end; procedure TfrmEnemyEditor.txtEnemyType2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if StrToInt(txtEnemyType2.Text) > 7 then txtEnemyType2.Text := '7'; if StrToInt(txtEnemyType2.Text) < 0 then txtEnemyType2.Text := '0'; DisplayTankGFX(1); DrawEnemyList(); end; procedure TfrmEnemyEditor.txtEnemyType3KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if StrToInt(txtEnemyType3.Text) > 7 then txtEnemyType3.Text := '7'; if StrToInt(txtEnemyType3.Text) < 0 then txtEnemyType3.Text := '0'; DisplayTankGFX(2); DrawEnemyList(); end; procedure TfrmEnemyEditor.txtEnemyType4KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if StrToInt(txtEnemyType4.Text) > 7 then txtEnemyType4.Text := '7'; if StrToInt(txtEnemyType4.Text) < 0 then txtEnemyType4.Text := '0'; DisplayTankGFX(3); DrawEnemyList(); end; procedure TfrmEnemyEditor.txtAmount1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if StrToInt(txtAmount1.Text) > 20 then txtAmount1.Text := '20'; if StrToInt(txtAmount1.Text) < 0 then txtAmount1.Text := '0'; DrawEnemyList(); end; procedure TfrmEnemyEditor.txtAmount2KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if StrToInt(txtAmount2.Text) > 20 then txtAmount2.Text := '20'; if StrToInt(txtAmount2.Text) < 0 then txtAmount2.Text := '0'; DrawEnemyList(); end; procedure TfrmEnemyEditor.txtAmount3KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if StrToInt(txtAmount3.Text) > 20 then txtAmount3.Text := '20'; if StrToInt(txtAmount3.Text) < 0 then txtAmount3.Text := '0'; DrawEnemyList(); end; procedure TfrmEnemyEditor.txtAmount4KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if StrToInt(txtAmount4.Text) > 20 then txtAmount4.Text := '20'; if StrToInt(txtAmount4.Text) < 0 then txtAmount4.Text := '0'; DrawEnemyList(); end; procedure TfrmEnemyEditor.cmdCancelClick(Sender: TObject); begin FreeAndNil(TanksGFX); end; procedure TfrmEnemyEditor.FormClose(Sender: TObject; var Action: TCloseAction); begin FreeAndNil(TanksGFX); end; end.
{$MODESWITCH RESULT+} {$GOTO ON} (************************************************************************* Copyright (c) 1992-2007 The University of Tennessee. All rights reserved. Contributors: * Sergey Bochkanov (ALGLIB project). Translation from FORTRAN to pseudocode. See subroutines comments for additional copyrights. >>> SOURCE LICENSE >>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation (www.fsf.org); either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy of the GNU General Public License is available at http://www.fsf.org/licensing/licenses >>> END OF LICENSE >>> *************************************************************************) unit trfac; interface uses Math, Sysutils, Ap, reflections, creflections, hqrnd, matgen, ablasf, ablas; procedure RMatrixLU(var A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); procedure CMatrixLU(var A : TComplex2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); function HPDMatrixCholesky(var A : TComplex2DArray; N : AlglibInteger; IsUpper : Boolean):Boolean; function SPDMatrixCholesky(var A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean):Boolean; procedure RMatrixLUP(var A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); procedure CMatrixLUP(var A : TComplex2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); procedure RMatrixPLU(var A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); procedure CMatrixPLU(var A : TComplex2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); implementation procedure CMatrixLUPRec(var A : TComplex2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TComplex1DArray);forward; procedure RMatrixLUPRec(var A : TReal2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TReal1DArray);forward; procedure CMatrixPLURec(var A : TComplex2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TComplex1DArray);forward; procedure RMatrixPLURec(var A : TReal2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TReal1DArray);forward; procedure CMatrixLUP2(var A : TComplex2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TComplex1DArray);forward; procedure RMatrixLUP2(var A : TReal2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TReal1DArray);forward; procedure CMatrixPLU2(var A : TComplex2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TComplex1DArray);forward; procedure RMatrixPLU2(var A : TReal2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TReal1DArray);forward; function HPDMatrixCholeskyRec(var A : TComplex2DArray; Offs : AlglibInteger; N : AlglibInteger; IsUpper : Boolean; var Tmp : TComplex1DArray):Boolean;forward; function SPDMatrixCholeskyRec(var A : TReal2DArray; Offs : AlglibInteger; N : AlglibInteger; IsUpper : Boolean; var Tmp : TReal1DArray):Boolean;forward; function HPDMatrixCholesky2(var AAA : TComplex2DArray; Offs : AlglibInteger; N : AlglibInteger; IsUpper : Boolean; var Tmp : TComplex1DArray):Boolean;forward; function SPDMatrixCholesky2(var AAA : TReal2DArray; Offs : AlglibInteger; N : AlglibInteger; IsUpper : Boolean; var Tmp : TReal1DArray):Boolean;forward; (************************************************************************* LU decomposition of a general real matrix with row pivoting A is represented as A = P*L*U, where: * L is lower unitriangular matrix * U is upper triangular matrix * P = P0*P1*...*PK, K=min(M,N)-1, Pi - permutation matrix for I and Pivots[I] This is cache-oblivous implementation of LU decomposition. It is optimized for square matrices. As for rectangular matrices: * best case - M>>N * worst case - N>>M, small M, large N, matrix does not fit in CPU cache INPUT PARAMETERS: A - array[0..M-1, 0..N-1]. M - number of rows in matrix A. N - number of columns in matrix A. OUTPUT PARAMETERS: A - matrices L and U in compact form: * L is stored under main diagonal * U is stored on and above main diagonal Pivots - permutation matrix in compact form. array[0..Min(M-1,N-1)]. -- ALGLIB routine -- 10.01.2010 Bochkanov Sergey *************************************************************************) procedure RMatrixLU(var A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); begin Assert(M>0, 'RMatrixLU: incorrect M!'); Assert(N>0, 'RMatrixLU: incorrect N!'); RMatrixPLU(A, M, N, Pivots); end; (************************************************************************* LU decomposition of a general complex matrix with row pivoting A is represented as A = P*L*U, where: * L is lower unitriangular matrix * U is upper triangular matrix * P = P0*P1*...*PK, K=min(M,N)-1, Pi - permutation matrix for I and Pivots[I] This is cache-oblivous implementation of LU decomposition. It is optimized for square matrices. As for rectangular matrices: * best case - M>>N * worst case - N>>M, small M, large N, matrix does not fit in CPU cache INPUT PARAMETERS: A - array[0..M-1, 0..N-1]. M - number of rows in matrix A. N - number of columns in matrix A. OUTPUT PARAMETERS: A - matrices L and U in compact form: * L is stored under main diagonal * U is stored on and above main diagonal Pivots - permutation matrix in compact form. array[0..Min(M-1,N-1)]. -- ALGLIB routine -- 10.01.2010 Bochkanov Sergey *************************************************************************) procedure CMatrixLU(var A : TComplex2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); begin Assert(M>0, 'CMatrixLU: incorrect M!'); Assert(N>0, 'CMatrixLU: incorrect N!'); CMatrixPLU(A, M, N, Pivots); end; (************************************************************************* Cache-oblivious Cholesky decomposition The algorithm computes Cholesky decomposition of a Hermitian positive- definite matrix. The result of an algorithm is a representation of A as A=U'*U or A=L*L' (here X' detones conj(X^T)). INPUT PARAMETERS: A - upper or lower triangle of a factorized matrix. array with elements [0..N-1, 0..N-1]. N - size of matrix A. IsUpper - if IsUpper=True, then A contains an upper triangle of a symmetric matrix, otherwise A contains a lower one. OUTPUT PARAMETERS: A - the result of factorization. If IsUpper=True, then the upper triangle contains matrix U, so that A = U'*U, and the elements below the main diagonal are not modified. Similarly, if IsUpper = False. RESULT: If the matrix is positive-definite, the function returns True. Otherwise, the function returns False. Contents of A is not determined in such case. -- ALGLIB routine -- 15.12.2009 Bochkanov Sergey *************************************************************************) function HPDMatrixCholesky(var A : TComplex2DArray; N : AlglibInteger; IsUpper : Boolean):Boolean; var Tmp : TComplex1DArray; begin if N<1 then begin Result := False; Exit; end; SetLength(Tmp, 2*N); Result := HPDMatrixCholeskyRec(A, 0, N, IsUpper, Tmp); end; (************************************************************************* Cache-oblivious Cholesky decomposition The algorithm computes Cholesky decomposition of a symmetric positive- definite matrix. The result of an algorithm is a representation of A as A=U^T*U or A=L*L^T INPUT PARAMETERS: A - upper or lower triangle of a factorized matrix. array with elements [0..N-1, 0..N-1]. N - size of matrix A. IsUpper - if IsUpper=True, then A contains an upper triangle of a symmetric matrix, otherwise A contains a lower one. OUTPUT PARAMETERS: A - the result of factorization. If IsUpper=True, then the upper triangle contains matrix U, so that A = U^T*U, and the elements below the main diagonal are not modified. Similarly, if IsUpper = False. RESULT: If the matrix is positive-definite, the function returns True. Otherwise, the function returns False. Contents of A is not determined in such case. -- ALGLIB routine -- 15.12.2009 Bochkanov Sergey *************************************************************************) function SPDMatrixCholesky(var A : TReal2DArray; N : AlglibInteger; IsUpper : Boolean):Boolean; var Tmp : TReal1DArray; begin if N<1 then begin Result := False; Exit; end; SetLength(Tmp, 2*N); Result := SPDMatrixCholeskyRec(A, 0, N, IsUpper, Tmp); end; procedure RMatrixLUP(var A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); var Tmp : TReal1DArray; I : AlglibInteger; J : AlglibInteger; MX : Double; V : Double; begin // // Internal LU decomposition subroutine. // Never call it directly. // Assert(M>0, 'RMatrixLUP: incorrect M!'); Assert(N>0, 'RMatrixLUP: incorrect N!'); // // Scale matrix to avoid overflows, // decompose it, then scale back. // MX := 0; I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin MX := Max(MX, AbsReal(A[I,J])); Inc(J); end; Inc(I); end; if AP_FP_Neq(MX,0) then begin V := 1/MX; I:=0; while I<=M-1 do begin APVMul(@A[I][0], 0, N-1, V); Inc(I); end; end; SetLength(Pivots, Min(M, N)); SetLength(Tmp, 2*Max(M, N)); RMatrixLUPRec(A, 0, M, N, Pivots, Tmp); if AP_FP_Neq(MX,0) then begin V := MX; I:=0; while I<=M-1 do begin APVMul(@A[I][0], 0, Min(I, N-1), V); Inc(I); end; end; end; procedure CMatrixLUP(var A : TComplex2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); var Tmp : TComplex1DArray; I : AlglibInteger; J : AlglibInteger; MX : Double; V : Double; i_ : AlglibInteger; begin // // Internal LU decomposition subroutine. // Never call it directly. // Assert(M>0, 'CMatrixLUP: incorrect M!'); Assert(N>0, 'CMatrixLUP: incorrect N!'); // // Scale matrix to avoid overflows, // decompose it, then scale back. // MX := 0; I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin MX := Max(MX, AbsComplex(A[I,J])); Inc(J); end; Inc(I); end; if AP_FP_Neq(MX,0) then begin V := 1/MX; I:=0; while I<=M-1 do begin for i_ := 0 to N-1 do begin A[I,i_] := C_MulR(A[I,i_],V); end; Inc(I); end; end; SetLength(Pivots, Min(M, N)); SetLength(Tmp, 2*Max(M, N)); CMatrixLUPRec(A, 0, M, N, Pivots, Tmp); if AP_FP_Neq(MX,0) then begin V := MX; I:=0; while I<=M-1 do begin for i_ := 0 to Min(I, N-1) do begin A[I,i_] := C_MulR(A[I,i_],V); end; Inc(I); end; end; end; procedure RMatrixPLU(var A : TReal2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); var Tmp : TReal1DArray; I : AlglibInteger; J : AlglibInteger; MX : Double; V : Double; begin // // Internal LU decomposition subroutine. // Never call it directly. // Assert(M>0, 'RMatrixPLU: incorrect M!'); Assert(N>0, 'RMatrixPLU: incorrect N!'); SetLength(Tmp, 2*Max(M, N)); SetLength(Pivots, Min(M, N)); // // Scale matrix to avoid overflows, // decompose it, then scale back. // MX := 0; I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin MX := Max(MX, AbsReal(A[I,J])); Inc(J); end; Inc(I); end; if AP_FP_Neq(MX,0) then begin V := 1/MX; I:=0; while I<=M-1 do begin APVMul(@A[I][0], 0, N-1, V); Inc(I); end; end; RMatrixPLURec(A, 0, M, N, Pivots, Tmp); if AP_FP_Neq(MX,0) then begin V := MX; I:=0; while I<=Min(M, N)-1 do begin APVMul(@A[I][0], I, N-1, V); Inc(I); end; end; end; procedure CMatrixPLU(var A : TComplex2DArray; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray); var Tmp : TComplex1DArray; I : AlglibInteger; J : AlglibInteger; MX : Double; V : Complex; i_ : AlglibInteger; begin // // Internal LU decomposition subroutine. // Never call it directly. // Assert(M>0, 'CMatrixPLU: incorrect M!'); Assert(N>0, 'CMatrixPLU: incorrect N!'); SetLength(Tmp, 2*Max(M, N)); SetLength(Pivots, Min(M, N)); // // Scale matrix to avoid overflows, // decompose it, then scale back. // MX := 0; I:=0; while I<=M-1 do begin J:=0; while J<=N-1 do begin MX := Max(MX, AbsComplex(A[I,J])); Inc(J); end; Inc(I); end; if AP_FP_Neq(MX,0) then begin V := C_Complex(1/MX); I:=0; while I<=M-1 do begin for i_ := 0 to N-1 do begin A[I,i_] := C_Mul(V, A[I,i_]); end; Inc(I); end; end; CMatrixPLURec(A, 0, M, N, Pivots, Tmp); if AP_FP_Neq(MX,0) then begin V := C_Complex(MX); I:=0; while I<=Min(M, N)-1 do begin for i_ := I to N-1 do begin A[I,i_] := C_Mul(V, A[I,i_]); end; Inc(I); end; end; end; (************************************************************************* Recurrent complex LU subroutine. Never call it directly. -- ALGLIB routine -- 04.01.2010 Bochkanov Sergey *************************************************************************) procedure CMatrixLUPRec(var A : TComplex2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TComplex1DArray); var I : AlglibInteger; M1 : AlglibInteger; M2 : AlglibInteger; i_ : AlglibInteger; i1_ : AlglibInteger; begin // // Kernel case // if Min(M, N)<=ABLASComplexBlockSize(A) then begin CMatrixLUP2(A, Offs, M, N, Pivots, Tmp); Exit; end; // // Preliminary step, make N>=M // // ( A1 ) // A = ( ), where A1 is square // ( A2 ) // // Factorize A1, update A2 // if M>N then begin CMatrixLUPRec(A, Offs, N, N, Pivots, Tmp); I:=0; while I<=N-1 do begin i1_ := (Offs+N) - (0); for i_ := 0 to M-N-1 do begin Tmp[i_] := A[i_+i1_,Offs+I]; end; for i_ := Offs+N to Offs+M-1 do begin A[i_,Offs+I] := A[i_,Pivots[Offs+I]]; end; i1_ := (0) - (Offs+N); for i_ := Offs+N to Offs+M-1 do begin A[i_,Pivots[Offs+I]] := Tmp[i_+i1_]; end; Inc(I); end; CMatrixRightTRSM(M-N, N, A, Offs, Offs, True, True, 0, A, Offs+N, Offs); Exit; end; // // Non-kernel case // ABLASComplexSplitLength(A, M, M1, M2); CMatrixLUPRec(A, Offs, M1, N, Pivots, Tmp); if M2>0 then begin I:=0; while I<=M1-1 do begin if Offs+I<>Pivots[Offs+I] then begin i1_ := (Offs+M1) - (0); for i_ := 0 to M2-1 do begin Tmp[i_] := A[i_+i1_,Offs+I]; end; for i_ := Offs+M1 to Offs+M-1 do begin A[i_,Offs+I] := A[i_,Pivots[Offs+I]]; end; i1_ := (0) - (Offs+M1); for i_ := Offs+M1 to Offs+M-1 do begin A[i_,Pivots[Offs+I]] := Tmp[i_+i1_]; end; end; Inc(I); end; CMatrixRightTRSM(M2, M1, A, Offs, Offs, True, True, 0, A, Offs+M1, Offs); CMatrixGEMM(M-M1, N-M1, M1, C_Complex(-Double(1.0)), A, Offs+M1, Offs, 0, A, Offs, Offs+M1, 0, C_Complex(+Double(1.0)), A, Offs+M1, Offs+M1); CMatrixLUPRec(A, Offs+M1, M-M1, N-M1, Pivots, Tmp); I:=0; while I<=M2-1 do begin if Offs+M1+I<>Pivots[Offs+M1+I] then begin i1_ := (Offs) - (0); for i_ := 0 to M1-1 do begin Tmp[i_] := A[i_+i1_,Offs+M1+I]; end; for i_ := Offs to Offs+M1-1 do begin A[i_,Offs+M1+I] := A[i_,Pivots[Offs+M1+I]]; end; i1_ := (0) - (Offs); for i_ := Offs to Offs+M1-1 do begin A[i_,Pivots[Offs+M1+I]] := Tmp[i_+i1_]; end; end; Inc(I); end; end; end; (************************************************************************* Recurrent real LU subroutine. Never call it directly. -- ALGLIB routine -- 04.01.2010 Bochkanov Sergey *************************************************************************) procedure RMatrixLUPRec(var A : TReal2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TReal1DArray); var I : AlglibInteger; M1 : AlglibInteger; M2 : AlglibInteger; i_ : AlglibInteger; i1_ : AlglibInteger; begin // // Kernel case // if Min(M, N)<=ABLASBlockSize(A) then begin RMatrixLUP2(A, Offs, M, N, Pivots, Tmp); Exit; end; // // Preliminary step, make N>=M // // ( A1 ) // A = ( ), where A1 is square // ( A2 ) // // Factorize A1, update A2 // if M>N then begin RMatrixLUPRec(A, Offs, N, N, Pivots, Tmp); I:=0; while I<=N-1 do begin if Offs+I<>Pivots[Offs+I] then begin i1_ := (Offs+N) - (0); for i_ := 0 to M-N-1 do begin Tmp[i_] := A[i_+i1_,Offs+I]; end; for i_ := Offs+N to Offs+M-1 do begin A[i_,Offs+I] := A[i_,Pivots[Offs+I]]; end; i1_ := (0) - (Offs+N); for i_ := Offs+N to Offs+M-1 do begin A[i_,Pivots[Offs+I]] := Tmp[i_+i1_]; end; end; Inc(I); end; RMatrixRightTRSM(M-N, N, A, Offs, Offs, True, True, 0, A, Offs+N, Offs); Exit; end; // // Non-kernel case // ABLASSplitLength(A, M, M1, M2); RMatrixLUPRec(A, Offs, M1, N, Pivots, Tmp); if M2>0 then begin I:=0; while I<=M1-1 do begin if Offs+I<>Pivots[Offs+I] then begin i1_ := (Offs+M1) - (0); for i_ := 0 to M2-1 do begin Tmp[i_] := A[i_+i1_,Offs+I]; end; for i_ := Offs+M1 to Offs+M-1 do begin A[i_,Offs+I] := A[i_,Pivots[Offs+I]]; end; i1_ := (0) - (Offs+M1); for i_ := Offs+M1 to Offs+M-1 do begin A[i_,Pivots[Offs+I]] := Tmp[i_+i1_]; end; end; Inc(I); end; RMatrixRightTRSM(M2, M1, A, Offs, Offs, True, True, 0, A, Offs+M1, Offs); RMatrixGEMM(M-M1, N-M1, M1, -Double(1.0), A, Offs+M1, Offs, 0, A, Offs, Offs+M1, 0, +Double(1.0), A, Offs+M1, Offs+M1); RMatrixLUPRec(A, Offs+M1, M-M1, N-M1, Pivots, Tmp); I:=0; while I<=M2-1 do begin if Offs+M1+I<>Pivots[Offs+M1+I] then begin i1_ := (Offs) - (0); for i_ := 0 to M1-1 do begin Tmp[i_] := A[i_+i1_,Offs+M1+I]; end; for i_ := Offs to Offs+M1-1 do begin A[i_,Offs+M1+I] := A[i_,Pivots[Offs+M1+I]]; end; i1_ := (0) - (Offs); for i_ := Offs to Offs+M1-1 do begin A[i_,Pivots[Offs+M1+I]] := Tmp[i_+i1_]; end; end; Inc(I); end; end; end; (************************************************************************* Recurrent complex LU subroutine. Never call it directly. -- ALGLIB routine -- 04.01.2010 Bochkanov Sergey *************************************************************************) procedure CMatrixPLURec(var A : TComplex2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TComplex1DArray); var I : AlglibInteger; N1 : AlglibInteger; N2 : AlglibInteger; i_ : AlglibInteger; i1_ : AlglibInteger; begin // // Kernel case // if Min(M, N)<=ABLASComplexBlockSize(A) then begin CMatrixPLU2(A, Offs, M, N, Pivots, Tmp); Exit; end; // // Preliminary step, make M>=N. // // A = (A1 A2), where A1 is square // Factorize A1, update A2 // if N>M then begin CMatrixPLURec(A, Offs, M, M, Pivots, Tmp); I:=0; while I<=M-1 do begin i1_ := (Offs+M) - (0); for i_ := 0 to N-M-1 do begin Tmp[i_] := A[Offs+I,i_+i1_]; end; for i_ := Offs+M to Offs+N-1 do begin A[Offs+I,i_] := A[Pivots[Offs+I],i_]; end; i1_ := (0) - (Offs+M); for i_ := Offs+M to Offs+N-1 do begin A[Pivots[Offs+I],i_] := Tmp[i_+i1_]; end; Inc(I); end; CMatrixLeftTRSM(M, N-M, A, Offs, Offs, False, True, 0, A, Offs, Offs+M); Exit; end; // // Non-kernel case // ABLASComplexSplitLength(A, N, N1, N2); CMatrixPLURec(A, Offs, M, N1, Pivots, Tmp); if N2>0 then begin I:=0; while I<=N1-1 do begin if Offs+I<>Pivots[Offs+I] then begin i1_ := (Offs+N1) - (0); for i_ := 0 to N2-1 do begin Tmp[i_] := A[Offs+I,i_+i1_]; end; for i_ := Offs+N1 to Offs+N-1 do begin A[Offs+I,i_] := A[Pivots[Offs+I],i_]; end; i1_ := (0) - (Offs+N1); for i_ := Offs+N1 to Offs+N-1 do begin A[Pivots[Offs+I],i_] := Tmp[i_+i1_]; end; end; Inc(I); end; CMatrixLeftTRSM(N1, N2, A, Offs, Offs, False, True, 0, A, Offs, Offs+N1); CMatrixGEMM(M-N1, N-N1, N1, C_Complex(-Double(1.0)), A, Offs+N1, Offs, 0, A, Offs, Offs+N1, 0, C_Complex(+Double(1.0)), A, Offs+N1, Offs+N1); CMatrixPLURec(A, Offs+N1, M-N1, N-N1, Pivots, Tmp); I:=0; while I<=N2-1 do begin if Offs+N1+I<>Pivots[Offs+N1+I] then begin i1_ := (Offs) - (0); for i_ := 0 to N1-1 do begin Tmp[i_] := A[Offs+N1+I,i_+i1_]; end; for i_ := Offs to Offs+N1-1 do begin A[Offs+N1+I,i_] := A[Pivots[Offs+N1+I],i_]; end; i1_ := (0) - (Offs); for i_ := Offs to Offs+N1-1 do begin A[Pivots[Offs+N1+I],i_] := Tmp[i_+i1_]; end; end; Inc(I); end; end; end; (************************************************************************* Recurrent real LU subroutine. Never call it directly. -- ALGLIB routine -- 04.01.2010 Bochkanov Sergey *************************************************************************) procedure RMatrixPLURec(var A : TReal2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TReal1DArray); var I : AlglibInteger; N1 : AlglibInteger; N2 : AlglibInteger; begin // // Kernel case // if Min(M, N)<=ABLASBlockSize(A) then begin RMatrixPLU2(A, Offs, M, N, Pivots, Tmp); Exit; end; // // Preliminary step, make M>=N. // // A = (A1 A2), where A1 is square // Factorize A1, update A2 // if N>M then begin RMatrixPLURec(A, Offs, M, M, Pivots, Tmp); I:=0; while I<=M-1 do begin APVMove(@Tmp[0], 0, N-M-1, @A[Offs+I][0], Offs+M, Offs+N-1); APVMove(@A[Offs+I][0], Offs+M, Offs+N-1, @A[Pivots[Offs+I]][0], Offs+M, Offs+N-1); APVMove(@A[Pivots[Offs+I]][0], Offs+M, Offs+N-1, @Tmp[0], 0, N-M-1); Inc(I); end; RMatrixLeftTRSM(M, N-M, A, Offs, Offs, False, True, 0, A, Offs, Offs+M); Exit; end; // // Non-kernel case // ABLASSplitLength(A, N, N1, N2); RMatrixPLURec(A, Offs, M, N1, Pivots, Tmp); if N2>0 then begin I:=0; while I<=N1-1 do begin if Offs+I<>Pivots[Offs+I] then begin APVMove(@Tmp[0], 0, N2-1, @A[Offs+I][0], Offs+N1, Offs+N-1); APVMove(@A[Offs+I][0], Offs+N1, Offs+N-1, @A[Pivots[Offs+I]][0], Offs+N1, Offs+N-1); APVMove(@A[Pivots[Offs+I]][0], Offs+N1, Offs+N-1, @Tmp[0], 0, N2-1); end; Inc(I); end; RMatrixLeftTRSM(N1, N2, A, Offs, Offs, False, True, 0, A, Offs, Offs+N1); RMatrixGEMM(M-N1, N-N1, N1, -Double(1.0), A, Offs+N1, Offs, 0, A, Offs, Offs+N1, 0, +Double(1.0), A, Offs+N1, Offs+N1); RMatrixPLURec(A, Offs+N1, M-N1, N-N1, Pivots, Tmp); I:=0; while I<=N2-1 do begin if Offs+N1+I<>Pivots[Offs+N1+I] then begin APVMove(@Tmp[0], 0, N1-1, @A[Offs+N1+I][0], Offs, Offs+N1-1); APVMove(@A[Offs+N1+I][0], Offs, Offs+N1-1, @A[Pivots[Offs+N1+I]][0], Offs, Offs+N1-1); APVMove(@A[Pivots[Offs+N1+I]][0], Offs, Offs+N1-1, @Tmp[0], 0, N1-1); end; Inc(I); end; end; end; (************************************************************************* Complex LUP kernel -- ALGLIB routine -- 10.01.2010 Bochkanov Sergey *************************************************************************) procedure CMatrixLUP2(var A : TComplex2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TComplex1DArray); var I : AlglibInteger; J : AlglibInteger; JP : AlglibInteger; S : Complex; i_ : AlglibInteger; i1_ : AlglibInteger; begin // // Quick return if possible // if (M=0) or (N=0) then begin Exit; end; // // main cycle // J:=0; while J<=Min(M-1, N-1) do begin // // Find pivot, swap columns // JP := J; I:=J+1; while I<=N-1 do begin if AP_FP_Greater(AbsComplex(A[Offs+J,Offs+I]),AbsComplex(A[Offs+J,Offs+JP])) then begin JP := I; end; Inc(I); end; Pivots[Offs+J] := Offs+JP; if JP<>J then begin i1_ := (Offs) - (0); for i_ := 0 to M-1 do begin Tmp[i_] := A[i_+i1_,Offs+J]; end; for i_ := Offs to Offs+M-1 do begin A[i_,Offs+J] := A[i_,Offs+JP]; end; i1_ := (0) - (Offs); for i_ := Offs to Offs+M-1 do begin A[i_,Offs+JP] := Tmp[i_+i1_]; end; end; // // LU decomposition of 1x(N-J) matrix // if C_NotEqualR(A[Offs+J,Offs+J],0) and (J+1<=N-1) then begin S := C_RDiv(1,A[Offs+J,Offs+J]); for i_ := Offs+J+1 to Offs+N-1 do begin A[Offs+J,i_] := C_Mul(S, A[Offs+J,i_]); end; end; // // Update trailing (M-J-1)x(N-J-1) matrix // if J<Min(M-1, N-1) then begin i1_ := (Offs+J+1) - (0); for i_ := 0 to M-J-2 do begin Tmp[i_] := A[i_+i1_,Offs+J]; end; i1_ := (Offs+J+1) - (M); for i_ := M to M+N-J-2 do begin Tmp[i_] := C_Opposite(A[Offs+J,i_+i1_]); end; CMatrixRank1(M-J-1, N-J-1, A, Offs+J+1, Offs+J+1, Tmp, 0, Tmp, M); end; Inc(J); end; end; (************************************************************************* Real LUP kernel -- ALGLIB routine -- 10.01.2010 Bochkanov Sergey *************************************************************************) procedure RMatrixLUP2(var A : TReal2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TReal1DArray); var I : AlglibInteger; J : AlglibInteger; JP : AlglibInteger; S : Double; i_ : AlglibInteger; i1_ : AlglibInteger; begin // // Quick return if possible // if (M=0) or (N=0) then begin Exit; end; // // main cycle // J:=0; while J<=Min(M-1, N-1) do begin // // Find pivot, swap columns // JP := J; I:=J+1; while I<=N-1 do begin if AP_FP_Greater(AbsReal(A[Offs+J,Offs+I]),AbsReal(A[Offs+J,Offs+JP])) then begin JP := I; end; Inc(I); end; Pivots[Offs+J] := Offs+JP; if JP<>J then begin i1_ := (Offs) - (0); for i_ := 0 to M-1 do begin Tmp[i_] := A[i_+i1_,Offs+J]; end; for i_ := Offs to Offs+M-1 do begin A[i_,Offs+J] := A[i_,Offs+JP]; end; i1_ := (0) - (Offs); for i_ := Offs to Offs+M-1 do begin A[i_,Offs+JP] := Tmp[i_+i1_]; end; end; // // LU decomposition of 1x(N-J) matrix // if AP_FP_Neq(A[Offs+J,Offs+J],0) and (J+1<=N-1) then begin S := 1/A[Offs+J,Offs+J]; APVMul(@A[Offs+J][0], Offs+J+1, Offs+N-1, S); end; // // Update trailing (M-J-1)x(N-J-1) matrix // if J<Min(M-1, N-1) then begin i1_ := (Offs+J+1) - (0); for i_ := 0 to M-J-2 do begin Tmp[i_] := A[i_+i1_,Offs+J]; end; APVMoveNeg(@Tmp[0], M, M+N-J-2, @A[Offs+J][0], Offs+J+1, Offs+N-1); RMatrixRank1(M-J-1, N-J-1, A, Offs+J+1, Offs+J+1, Tmp, 0, Tmp, M); end; Inc(J); end; end; (************************************************************************* Complex PLU kernel -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1992 *************************************************************************) procedure CMatrixPLU2(var A : TComplex2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TComplex1DArray); var I : AlglibInteger; J : AlglibInteger; JP : AlglibInteger; S : Complex; i_ : AlglibInteger; i1_ : AlglibInteger; begin // // Quick return if possible // if (M=0) or (N=0) then begin Exit; end; J:=0; while J<=Min(M-1, N-1) do begin // // Find pivot and test for singularity. // JP := J; I:=J+1; while I<=M-1 do begin if AP_FP_Greater(AbsComplex(A[Offs+I,Offs+J]),AbsComplex(A[Offs+JP,Offs+J])) then begin JP := I; end; Inc(I); end; Pivots[Offs+J] := Offs+JP; if C_NotEqualR(A[Offs+JP,Offs+J],0) then begin // //Apply the interchange to rows // if JP<>J then begin I:=0; while I<=N-1 do begin S := A[Offs+J,Offs+I]; A[Offs+J,Offs+I] := A[Offs+JP,Offs+I]; A[Offs+JP,Offs+I] := S; Inc(I); end; end; // //Compute elements J+1:M of J-th column. // if J+1<=M-1 then begin S := C_RDiv(1,A[Offs+J,Offs+J]); for i_ := Offs+J+1 to Offs+M-1 do begin A[i_,Offs+J] := C_Mul(S, A[i_,Offs+J]); end; end; end; if J<Min(M, N)-1 then begin // //Update trailing submatrix. // i1_ := (Offs+J+1) - (0); for i_ := 0 to M-J-2 do begin Tmp[i_] := A[i_+i1_,Offs+J]; end; i1_ := (Offs+J+1) - (M); for i_ := M to M+N-J-2 do begin Tmp[i_] := C_Opposite(A[Offs+J,i_+i1_]); end; CMatrixRank1(M-J-1, N-J-1, A, Offs+J+1, Offs+J+1, Tmp, 0, Tmp, M); end; Inc(J); end; end; (************************************************************************* Real PLU kernel -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University June 30, 1992 *************************************************************************) procedure RMatrixPLU2(var A : TReal2DArray; Offs : AlglibInteger; M : AlglibInteger; N : AlglibInteger; var Pivots : TInteger1DArray; var Tmp : TReal1DArray); var I : AlglibInteger; J : AlglibInteger; JP : AlglibInteger; S : Double; i_ : AlglibInteger; i1_ : AlglibInteger; begin // // Quick return if possible // if (M=0) or (N=0) then begin Exit; end; J:=0; while J<=Min(M-1, N-1) do begin // // Find pivot and test for singularity. // JP := J; I:=J+1; while I<=M-1 do begin if AP_FP_Greater(AbsReal(A[Offs+I,Offs+J]),AbsReal(A[Offs+JP,Offs+J])) then begin JP := I; end; Inc(I); end; Pivots[Offs+J] := Offs+JP; if AP_FP_Neq(A[Offs+JP,Offs+J],0) then begin // //Apply the interchange to rows // if JP<>J then begin I:=0; while I<=N-1 do begin S := A[Offs+J,Offs+I]; A[Offs+J,Offs+I] := A[Offs+JP,Offs+I]; A[Offs+JP,Offs+I] := S; Inc(I); end; end; // //Compute elements J+1:M of J-th column. // if J+1<=M-1 then begin S := 1/A[Offs+J,Offs+J]; for i_ := Offs+J+1 to Offs+M-1 do begin A[i_,Offs+J] := S*A[i_,Offs+J]; end; end; end; if J<Min(M, N)-1 then begin // //Update trailing submatrix. // i1_ := (Offs+J+1) - (0); for i_ := 0 to M-J-2 do begin Tmp[i_] := A[i_+i1_,Offs+J]; end; APVMoveNeg(@Tmp[0], M, M+N-J-2, @A[Offs+J][0], Offs+J+1, Offs+N-1); RMatrixRank1(M-J-1, N-J-1, A, Offs+J+1, Offs+J+1, Tmp, 0, Tmp, M); end; Inc(J); end; end; (************************************************************************* Recursive computational subroutine for HPDMatrixCholesky -- ALGLIB routine -- 15.12.2009 Bochkanov Sergey *************************************************************************) function HPDMatrixCholeskyRec(var A : TComplex2DArray; Offs : AlglibInteger; N : AlglibInteger; IsUpper : Boolean; var Tmp : TComplex1DArray):Boolean; var N1 : AlglibInteger; N2 : AlglibInteger; begin // // check N // if N<1 then begin Result := False; Exit; end; // // special cases // if N=1 then begin if AP_FP_Greater(A[Offs,Offs].X,0) then begin A[Offs,Offs] := C_Complex(Sqrt(A[Offs,Offs].X)); Result := True; end else begin Result := False; end; Exit; end; if N<=ABLASComplexBlockSize(A) then begin Result := HPDMatrixCholesky2(A, Offs, N, IsUpper, Tmp); Exit; end; // // general case: split task in cache-oblivious manner // Result := True; ABLASComplexSplitLength(A, N, N1, N2); Result := HPDMatrixCholeskyRec(A, Offs, N1, IsUpper, Tmp); if not Result then begin Exit; end; if N2>0 then begin if IsUpper then begin CMatrixLeftTRSM(N1, N2, A, Offs, Offs, IsUpper, False, 2, A, Offs, Offs+N1); CMatrixSYRK(N2, N1, -Double(1.0), A, Offs, Offs+N1, 2, +Double(1.0), A, Offs+N1, Offs+N1, IsUpper); end else begin CMatrixRightTRSM(N2, N1, A, Offs, Offs, IsUpper, False, 2, A, Offs+N1, Offs); CMatrixSYRK(N2, N1, -Double(1.0), A, Offs+N1, Offs, 0, +Double(1.0), A, Offs+N1, Offs+N1, IsUpper); end; Result := HPDMatrixCholeskyRec(A, Offs+N1, N2, IsUpper, Tmp); if not Result then begin Exit; end; end; end; (************************************************************************* Recursive computational subroutine for SPDMatrixCholesky -- ALGLIB routine -- 15.12.2009 Bochkanov Sergey *************************************************************************) function SPDMatrixCholeskyRec(var A : TReal2DArray; Offs : AlglibInteger; N : AlglibInteger; IsUpper : Boolean; var Tmp : TReal1DArray):Boolean; var N1 : AlglibInteger; N2 : AlglibInteger; begin // // check N // if N<1 then begin Result := False; Exit; end; // // special cases // if N=1 then begin if AP_FP_Greater(A[Offs,Offs],0) then begin A[Offs,Offs] := Sqrt(A[Offs,Offs]); Result := True; end else begin Result := False; end; Exit; end; if N<=ABLASBlockSize(A) then begin Result := SPDMatrixCholesky2(A, Offs, N, IsUpper, Tmp); Exit; end; // // general case: split task in cache-oblivious manner // Result := True; ABLASSplitLength(A, N, N1, N2); Result := SPDMatrixCholeskyRec(A, Offs, N1, IsUpper, Tmp); if not Result then begin Exit; end; if N2>0 then begin if IsUpper then begin RMatrixLeftTRSM(N1, N2, A, Offs, Offs, IsUpper, False, 1, A, Offs, Offs+N1); RMatrixSYRK(N2, N1, -Double(1.0), A, Offs, Offs+N1, 1, +Double(1.0), A, Offs+N1, Offs+N1, IsUpper); end else begin RMatrixRightTRSM(N2, N1, A, Offs, Offs, IsUpper, False, 1, A, Offs+N1, Offs); RMatrixSYRK(N2, N1, -Double(1.0), A, Offs+N1, Offs, 0, +Double(1.0), A, Offs+N1, Offs+N1, IsUpper); end; Result := SPDMatrixCholeskyRec(A, Offs+N1, N2, IsUpper, Tmp); if not Result then begin Exit; end; end; end; (************************************************************************* Level-2 Hermitian Cholesky subroutine. -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 *************************************************************************) function HPDMatrixCholesky2(var AAA : TComplex2DArray; Offs : AlglibInteger; N : AlglibInteger; IsUpper : Boolean; var Tmp : TComplex1DArray):Boolean; var I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; J1 : AlglibInteger; J2 : AlglibInteger; AJJ : Double; V : Complex; R : Double; i_ : AlglibInteger; i1_ : AlglibInteger; begin Result := True; if N<0 then begin Result := False; Exit; end; // // Quick return if possible // if N=0 then begin Exit; end; if IsUpper then begin // // Compute the Cholesky factorization A = U'*U. // J:=0; while J<=N-1 do begin // // Compute U(J,J) and test for non-positive-definiteness. // V := C_Complex(0.0); for i_ := Offs to Offs+J-1 do begin V := C_Add(V,C_Mul(Conj(AAA[i_,Offs+J]),AAA[i_,Offs+J])); end; AJJ := C_Sub(AAA[Offs+J,Offs+J],V).X; if AP_FP_Less_Eq(AJJ,0) then begin AAA[Offs+J,Offs+J] := C_Complex(AJJ); Result := False; Exit; end; AJJ := SQRT(AJJ); AAA[Offs+J,Offs+J] := C_Complex(AJJ); // // Compute elements J+1:N-1 of row J. // if J<N-1 then begin if J>0 then begin i1_ := (Offs) - (0); for i_ := 0 to J-1 do begin Tmp[i_] := C_Opposite(Conj(AAA[i_+i1_,Offs+J])); end; CMatrixMV(N-J-1, J, AAA, Offs, Offs+J+1, 1, Tmp, 0, Tmp, N); i1_ := (N) - (Offs+J+1); for i_ := Offs+J+1 to Offs+N-1 do begin AAA[Offs+J,i_] := C_Add(AAA[Offs+J,i_], Tmp[i_+i1_]); end; end; R := 1/AJJ; for i_ := Offs+J+1 to Offs+N-1 do begin AAA[Offs+J,i_] := C_MulR(AAA[Offs+J,i_],R); end; end; Inc(J); end; end else begin // // Compute the Cholesky factorization A = L*L'. // J:=0; while J<=N-1 do begin // // Compute L(J+1,J+1) and test for non-positive-definiteness. // V := C_Complex(0.0); for i_ := Offs to Offs+J-1 do begin V := C_Add(V,C_Mul(Conj(AAA[Offs+J,i_]),AAA[Offs+J,i_])); end; AJJ := C_Sub(AAA[Offs+J,Offs+J],V).X; if AP_FP_Less_Eq(AJJ,0) then begin AAA[Offs+J,Offs+J] := C_Complex(AJJ); Result := False; Exit; end; AJJ := SQRT(AJJ); AAA[Offs+J,Offs+J] := C_Complex(AJJ); // // Compute elements J+1:N of column J. // if J<N-1 then begin if J>0 then begin i1_ := (Offs) - (0); for i_ := 0 to J-1 do begin Tmp[i_] := Conj(AAA[Offs+J,i_+i1_]); end; CMatrixMV(N-J-1, J, AAA, Offs+J+1, Offs, 0, Tmp, 0, Tmp, N); I:=0; while I<=N-J-2 do begin AAA[Offs+J+1+I,Offs+J] := C_DivR(C_Sub(AAA[Offs+J+1+I,Offs+J],Tmp[N+I]),AJJ); Inc(I); end; end else begin I:=0; while I<=N-J-2 do begin AAA[Offs+J+1+I,Offs+J] := C_DivR(AAA[Offs+J+1+I,Offs+J],AJJ); Inc(I); end; end; end; Inc(J); end; end; end; (************************************************************************* Level-2 Cholesky subroutine -- LAPACK routine (version 3.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University February 29, 1992 *************************************************************************) function SPDMatrixCholesky2(var AAA : TReal2DArray; Offs : AlglibInteger; N : AlglibInteger; IsUpper : Boolean; var Tmp : TReal1DArray):Boolean; var I : AlglibInteger; J : AlglibInteger; K : AlglibInteger; J1 : AlglibInteger; J2 : AlglibInteger; AJJ : Double; V : Double; R : Double; i_ : AlglibInteger; i1_ : AlglibInteger; begin Result := True; if N<0 then begin Result := False; Exit; end; // // Quick return if possible // if N=0 then begin Exit; end; if IsUpper then begin // // Compute the Cholesky factorization A = U'*U. // J:=0; while J<=N-1 do begin // // Compute U(J,J) and test for non-positive-definiteness. // V := 0.0; for i_ := Offs to Offs+J-1 do begin V := V + AAA[i_,Offs+J]*AAA[i_,Offs+J]; end; AJJ := AAA[Offs+J,Offs+J]-V; if AP_FP_Less_Eq(AJJ,0) then begin AAA[Offs+J,Offs+J] := AJJ; Result := False; Exit; end; AJJ := SQRT(AJJ); AAA[Offs+J,Offs+J] := AJJ; // // Compute elements J+1:N-1 of row J. // if J<N-1 then begin if J>0 then begin i1_ := (Offs) - (0); for i_ := 0 to J-1 do begin Tmp[i_] := -AAA[i_+i1_,Offs+J]; end; RMatrixMV(N-J-1, J, AAA, Offs, Offs+J+1, 1, Tmp, 0, Tmp, N); APVAdd(@AAA[Offs+J][0], Offs+J+1, Offs+N-1, @Tmp[0], N, 2*N-J-2); end; R := 1/AJJ; APVMul(@AAA[Offs+J][0], Offs+J+1, Offs+N-1, R); end; Inc(J); end; end else begin // // Compute the Cholesky factorization A = L*L'. // J:=0; while J<=N-1 do begin // // Compute L(J+1,J+1) and test for non-positive-definiteness. // V := APVDotProduct(@AAA[Offs+J][0], Offs, Offs+J-1, @AAA[Offs+J][0], Offs, Offs+J-1); AJJ := AAA[Offs+J,Offs+J]-V; if AP_FP_Less_Eq(AJJ,0) then begin AAA[Offs+J,Offs+J] := AJJ; Result := False; Exit; end; AJJ := SQRT(AJJ); AAA[Offs+J,Offs+J] := AJJ; // // Compute elements J+1:N of column J. // if J<N-1 then begin if J>0 then begin APVMove(@Tmp[0], 0, J-1, @AAA[Offs+J][0], Offs, Offs+J-1); RMatrixMV(N-J-1, J, AAA, Offs+J+1, Offs, 0, Tmp, 0, Tmp, N); I:=0; while I<=N-J-2 do begin AAA[Offs+J+1+I,Offs+J] := (AAA[Offs+J+1+I,Offs+J]-Tmp[N+I])/AJJ; Inc(I); end; end else begin I:=0; while I<=N-J-2 do begin AAA[Offs+J+1+I,Offs+J] := AAA[Offs+J+1+I,Offs+J]/AJJ; Inc(I); end; end; end; Inc(J); end; end; end; end.
unit pic; interface type TPrimaryIRQ = ( IRQ_SOFTINT = $00000001, IRQ_UARTINT0 = $00000002, IRQ_UARTINT1 = $00000004, IRQ_KBDINT = $00000008, IRQ_MOUSEINT = $00000010, IRQ_TIMERINT0 = $00000020, IRQ_TIMERINT1 = $00000040, IRQ_TIMERINT2 = $00000080, IRQ_RTCINT = $00000100, IRQ_LM_LLINT0 = $00000200, IRQ_LM_LLINT1 = $00000400, IRQ_CLCDINT = $00400000, IRQ_MMCIINT0 = $00800000, IRQ_MMCIINT1 = $01000000, IRQ_AACIINT = $02000000, IRQ_CPPLDINT = $04000000, IRQ_ETH_INT = $08000000, IRQ_TS_PENINT = $10000000); procedure EnableIRQ(AIrq: TPrimaryIRQ); implementation const PIC_BASE = $14000000; var PIC_IRQ_ENABLESET: longword absolute PIC_BASE+$08; procedure EnableIRQ(AIrq: TPrimaryIRQ); begin PIC_IRQ_ENABLESET := longword(AIrq); end; end.
unit Specifications; // 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 DUnitLite. // // The Initial Developer of the Original Code is Joe White. // Portions created by Joe White are Copyright (C) 2007 // Joe White. All Rights Reserved. // // Contributor(s): // // Alternatively, the contents of this file may be used under the terms // of the LGPL license (the "LGPL License"), in which case the // provisions of LGPL License are applicable instead of those // above. If you wish to allow use of your version of this file only // under the terms of the LGPL License and not to allow others to use // your version of this file under the MPL, indicate your decision by // deleting the provisions above and replace them with the notice and // other provisions required by the LGPL License. If you do not delete // the provisions above, a recipient may use your version of this file // under either the MPL or the LGPL License. interface uses InsulatedTests, Specifiers; type TSpecification = class(TInsulatedTest) strict protected type Given = Specifiers.Given; Should = Specifiers.Should; Specify = Specifiers.Specify; end; TRegisterableSpecification = class(TSpecification) public class procedure Register; end; implementation uses TestFramework; { TRegisterableSpecification } class procedure TRegisterableSpecification.Register; begin TestFramework.RegisterTest(Self.Suite); end; end.
unit svm_grabber; {$mode objfpc} {$inline on} interface uses SysUtils; const GrabberStackBlockSize = 1024 * 8; type TGrabberStack = object public items: array of pointer; size, i_pos: cardinal; procedure init; procedure push(p: pointer); procedure pop; procedure drop; procedure free; end; TGrabber = class public Stack: TGrabberStack; ChkCnt: byte; constructor Create; destructor Destroy; override; procedure Reg(value: pointer); procedure Run; procedure Term; end; implementation uses svm_mem; {***** stack *****} procedure TGrabberStack.init; begin SetLength(items, GrabberStackBlockSize); i_pos := 0; size := GrabberStackBlockSize; end; procedure TGrabberStack.push(p: pointer); inline; begin items[i_pos] := p; Inc(i_pos); if i_pos >= size then begin size := size + GrabberStackBlockSize; SetLength(items, size); end; end; procedure TGrabberStack.pop; inline; begin Dec(i_pos); if size - i_pos > GrabberStackBlockSize then begin size := size - GrabberStackBlockSize; SetLength(items, size); end; end; procedure TGrabberStack.drop; inline; begin SetLength(items, GrabberStackBlockSize); size := GrabberStackBlockSize; i_pos := 0; end; procedure TGrabberStack.free; inline; begin SetLength(items, 0); size := 0; i_pos := 0; end; {***** grabber *****} constructor TGrabber.Create; begin Stack.Init; ChkCnt := 0; end; destructor TGrabber.Destroy; begin Stack.Free; inherited; end; procedure TGrabber.Reg(value: pointer); begin Stack.push(value); end; procedure TGrabber.Run; var i: integer; c, l: cardinal; r: TSVMMem; p: pointer; begin if ChkCnt < 16 then begin i := stack.i_pos div 2; Inc(ChkCnt); end else begin i := 0; ChkCnt := 0; end; while i < stack.i_pos do begin r := TSVMMem(stack.items[i]); if r.m_refc < 1 then begin stack.items[i] := stack.items[stack.i_pos - 1]; stack.pop; if r.m_type in [svmtArr, svmtClass] then begin c := 0; l := Length(PMemArray(r.m_val)^); while c < l do begin p := PMemArray(r.m_val)^[c]; if p <> nil then Dec(TSVMMem(p).m_refc); Inc(c); end; end; FreeAndNil(r); dec(i); end; inc(i); end; end; procedure TGrabber.Term; var c: cardinal; r: TSVMMem; begin c := 0; while c < stack.i_pos do begin r := TSVMMem(stack.items[c]); FreeAndNil(r); Inc(c); end; end; end.
// see ISC_license.txt {$I genLL.inc} unit GramLexer; interface uses Sysutils, Runtime; const { token type } LEX_APOSTROPHE = 4; LEX_ASTERISK = 5; LEX_COLON = 6; LEX_DIGIT = 7; //LEX_ESC = 8; LEX_IDENT = 9; LEX_LEFT_CURLY_BRACKET = 10; LEX_LEFT_PARENTHESIS = 11; LEX_LETTER = 12; LEX_PLUS_SIGN = 14; LEX_QUESTION_MARK = 15; LEX_RIGHT_CURLY_BRACKET = 16; LEX_RIGHT_PARENTHESIS = 17; LEX_STRING_LITERAL = 18; LEX_TILDE = 19; LEX_VERTICAL_LINE = 20; LEX_WS = 21; //LEX_XDIGIT = 22; LEX_COMMENT = 23; LEX_SEMICOLON = 24; {$IFDEF EDU} LEX_EMPTY_LINE = 25; {$ENDIF} type TGramLexer = class(TLexer) protected procedure Tokens(); override; function GetTokenName(tokenType: integer): string; override; procedure mWS(); procedure mCOMMENT(); procedure mSTRING_LITERAL(); procedure mIDENT(); procedure mCOLON(); procedure mLEFT_CURLY_BRACKET(); procedure mRIGHT_CURLY_BRACKET(); procedure mLEFT_PARENTHESIS(); procedure mRIGHT_PARENTHESIS(); procedure mVERTICAL_LINE(); procedure mQUESTION_MARK(); procedure mPLUS_SIGN(); procedure mASTERISK(); procedure mTILDE(); procedure mSEMICOLON(); end; implementation uses Tokens; procedure TGramLexer.Tokens; var LA1: integer; begin LA1 := LA(1); if LA1 = LEX_EOF then begin ApproveTokenBuf(LEX_EOF, ceDefault); exit; end; case LA1 of 9 .. 10, 12 .. 13, ord(' '): mWS(); ord('/'): if LA(2) = ord('/') then mCOMMENT() else raise ENoViableAltException.Create(''); ord(''''): mSTRING_LITERAL(); ord('A') .. ord('Z'), ord('a') .. ord('z'): mIDENT(); ord(':'): mCOLON(); ord('|'): mVERTICAL_LINE(); ord('{'): mLEFT_CURLY_BRACKET(); ord('}'): mRIGHT_CURLY_BRACKET(); ord('?'): mQUESTION_MARK(); ord('+'): mPLUS_SIGN(); ord('*'): mASTERISK(); ord('~'): mTILDE(); ord('('): mLEFT_PARENTHESIS(); ord(')'): mRIGHT_PARENTHESIS(); ord(';'): mSEMICOLON(); else raise ENoViableAltException.Create(''); end; end; procedure TGramLexer.mWS(); var LA1: integer; cnt: integer; cntNewLine: integer; begin cnt := 0; cntNewLine := 0; repeat LA1 := LA(1); if (LA1 = 9) or (LA1 = 10) or (LA1 = 12) or (LA1 = 13) or (LA1 = ord(' ')) then begin if LA1 = 10 then inc(cntNewLine); Consume(); end else if cnt >= 1 then break else ErrorL(''); inc(cnt); until false; {$IFDEF EDU} if cntNewLine >= 2 then ApproveTokenBuf(LEX_EMPTY_LINE, ceDefault) else {$endif} ApproveTokenBuf(LEX_WS, ceHidden); end; procedure TGramLexer.mCOMMENT(); var LA1: integer; begin MatchLatin('//'); repeat LA1 := LA(1); if (LA1 <> -1) and (LA1 <> 10) and (LA1 <> 13) then Consume() else break; until false; ApproveTokenBuf(LEX_COMMENT, ceHidden); end; procedure TGramLexer.mSTRING_LITERAL(); var LA1: integer; begin Consume; // first ' repeat LA1 := LA(1); if (LA1 > 0) and (LA1 <> ord('''')) and (LA1 <> 10) and (LA1 <> 13) then Consume() else if (LA1 = ord('''')) and (LA(2) = ord('''')) then Consume(2) //two ' else break; until false; MatchOne(ord('''')); //last ' ApproveTokenBuf(LEX_STRING_LITERAL, ceDefault); end; procedure TGramLexer.mIDENT(); var LA1: integer; begin repeat LA1 := LA(1); if (LA1 >= ord('A')) and (LA1 <= ord('Z')) or (LA1 >= ord('a')) and (LA1 <= ord('z')) or (LA1 >= ord('0')) and (LA1 <= ord('9')) or (LA1 = ord('_')) then Consume() else break; until false; ApproveTokenBuf(LEX_IDENT, ceDefault); end; procedure TGramLexer.mCOLON(); begin Consume; //c ApproveTokenBuf(LEX_COLON, ceDefault); end; procedure TGramLexer.mLEFT_CURLY_BRACKET(); begin Consume; // { ApproveTokenBuf(LEX_LEFT_CURLY_BRACKET, ceDefault); end; procedure TGramLexer.mRIGHT_CURLY_BRACKET(); begin Consume; // } ApproveTokenBuf(LEX_RIGHT_CURLY_BRACKET, ceDefault); end; procedure TGramLexer.mLEFT_PARENTHESIS(); begin Consume; // ( ApproveTokenBuf(LEX_LEFT_PARENTHESIS, ceDefault); end; procedure TGramLexer.mRIGHT_PARENTHESIS(); begin Consume; // ) ApproveTokenBuf(LEX_RIGHT_PARENTHESIS, ceDefault); end; procedure TGramLexer.mVERTICAL_LINE; begin Consume; // | ApproveTokenBuf(LEX_VERTICAL_LINE, ceDefault); end; procedure TGramLexer.mQUESTION_MARK; begin Consume; // ? ApproveTokenBuf(LEX_QUESTION_MARK, ceDefault); end; procedure TGramLexer.mPLUS_SIGN; begin Consume; // + ApproveTokenBuf(LEX_PLUS_SIGN, ceDefault); end; function TGramLexer.GetTokenName(tokenType: integer): string; begin case tokenType of LEX_EOF: result := 'EOF'; LEX_APOSTROPHE : result := ''''; LEX_ASTERISK : result := '*'; LEX_COLON : result := ':'; LEX_DIGIT : result := '0..9'; LEX_IDENT : result := 'Ident'; LEX_LEFT_CURLY_BRACKET : result := '{'; LEX_LEFT_PARENTHESIS : result := '('; LEX_LETTER : result := 'Letter'; LEX_PLUS_SIGN : result := '+'; LEX_QUESTION_MARK : result := '?'; LEX_RIGHT_CURLY_BRACKET : result := '}'; LEX_RIGHT_PARENTHESIS : result := ')'; LEX_STRING_LITERAL : result := 'string'; LEX_TILDE : result := '~'; LEX_VERTICAL_LINE: result := '|'; LEX_WS: result := 'White space'; LEX_COMMENT: result := 'Comment'; LEX_SEMICOLON: result := ';'; {$IFDEF EDU} LEX_EMPTY_LINE: result := 'Empty line'; {$ENDIF} end; end; procedure TGramLexer.mASTERISK(); begin Consume; // * ApproveTokenBuf(LEX_ASTERISK, ceDefault); end; procedure TGramLexer.mTILDE(); begin Consume; // ~ ApproveTokenBuf(LEX_TILDE, ceDefault); end; procedure TGramLexer.mSEMICOLON(); begin Consume; // ; ApproveTokenBuf(LEX_SEMICOLON, ceDefault); end; end.
unit fmSeleccionarFS; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fmBase, ExtCtrls, frFS,dmFS, StdCtrls, Buttons, VirtualTrees; type TSelections = set of TFSType; TFSClass = class of TFS; TfSeleccionarFS = class(TfBase) fFS: TfFS; Panel1: TPanel; bSeleccionar: TBitBtn; BitBtn2: TBitBtn; procedure fFS1TreeFSChange(Sender: TBaseVirtualTree; Node: PVirtualNode); private FSelections: TSelections; function GetSelected: TBasicNodeData; public constructor Create(AOwner: TComponent); override; procedure SetFSClass(const FSClass: TFSClass); property Selections: TSelections read FSelections write FSelections; property Selected: TBasicNodeData read GetSelected; end; implementation {$R *.dfm} constructor TfSeleccionarFS.Create(AOwner: TComponent); begin inherited; Include(FSelections, fstFile); end; procedure TfSeleccionarFS.fFS1TreeFSChange(Sender: TBaseVirtualTree; Node: PVirtualNode); begin inherited; bSeleccionar.Enabled := ((fFS.IsFocusedDirectory) and (fstDirectory in FSelections)) or ((fFs.IsFocusedFile) and (fstFile in FSelections)); end; function TfSeleccionarFS.GetSelected: TBasicNodeData; begin result := fFS.GetNodeDataFocused; end; procedure TfSeleccionarFS.SetFSClass(const FSClass: TFSClass); begin fFS.FS := FSClass.Create(Self); end; end.
//********************************************************* //GLFONT.CPP -- glFont routines //Copyright (c) 1998 Brad Fish //********************************************************* unit FFonts; interface uses Windows, FOpenGL, OpenGl, FLogs, SysUtils, Math, Classes, FTerrain; type PGLFontChar = ^TGLFontChar; TGLFontChar = record dx, dy : Single; tx1, ty1 : Single; tx2, ty2 : Single; end; PGLFont = ^TGLFont; TGLFont = record tex : Integer; texWidth, texHeight : Integer; intStart, intEnd : Integer; character : PGLFontChar; end; PFont = ^TFont; TFont = record Path : string; GLID : GLuint; FontID : integer; end; var LoadedFonts : TList; GLFonts: array of TGLFont; FontSquares : TSquares; FontSquaresIndices : array of Integer; procedure glPrint(text : string; fontID : integer); procedure glFontCreate(var tex : GLuint; pFont : PGLFont; fileName : string); procedure glFontDestroy(pFont : PGLFont); procedure SetFontSquares(pFont : PGLFont; str : string); procedure SetStringSize(var x, y : integer; id : integer; str : string); function LoadFont(path: string) : integer; procedure InitFonts(); procedure glGenTextures(n: GLsizei; var textures: GLuint); stdcall; external opengl32; implementation uses FXMLLoader, FBase; procedure InitFonts(); begin LoadedFonts := TList.Create(); end; function LoadFont(path: string) : integer; var index, len : integer; t : PFont; begin if path <> '' then begin path := 'Fonts/' + path + '.glf'; index := 0; len := LoadedFonts.Count; while (index < len) and (PFont(LoadedFonts.Items[index])^.Path <> path) do Inc(index); if (index = len) then begin New(t); t^.Path := path; len := Length(GLFonts); SetLength(GLFonts, len + 1); t^.FontID := len; glFontCreate(t^.GLID, @GLFonts[len], t^.Path); Result := LoadedFonts.Add(t); end else begin Result := index; end; end else Result := 0; end; procedure glPrint(text : string; fontID : integer); var color : array[1..4] of GLFloat; pFont : PGLFont; begin pFont := @GLFonts[fontID]; glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, pFont^.tex); // Shadow GlGetFloatv(GL_CURRENT_COLOR, @color); SetFontSquares(pFont, text); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(2, GL_FLOAT, 0, FontSquares.vertex); glTexCoordPointer(2, GL_FLOAT, 0, FontSquares.texture); glColor3f(0, 0, 0); glPushMatrix(); glTranslatef(2, 2, 0); glDrawElements(GL_QUADS, Length(text)*4, GL_UNSIGNED_INT, FontSquaresIndices); glcolor3f(color[1], color[2], color[3]); glTranslatef(-1.5, -1.5, 0); glDrawElements(GL_QUADS, Length(text)*4, GL_UNSIGNED_INT, FontSquaresIndices); glTranslatef(-0.5, 0, 0); glDrawElements(GL_QUADS, Length(text)*4, GL_UNSIGNED_INT, FontSquaresIndices); glPopMatrix(); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); end; procedure glFontCreate(var tex : GLuint; pFont : PGLFont; fileName : string); var input : file; pTexBytes : PChar; num : integer; begin AssignFile(input, fileName); Reset(input, 1); BlockRead(input, pFont^, SizeOf(TGLFont)); glGenTextures(1, tex); pFont^.tex := tex; num := pFont^.intEnd - pFont^.intStart + 1; GetMem(pFont.character, SizeOf(TGLFontChar) * num); BlockRead(input, pFont^.character^, SizeOf(TGLFontChar) * num); num := pFont^.texWidth * pFont^.texHeight * 2; GetMem(pTexBytes, num); BlockRead(input, pTexBytes^, num); glBindTexture(GL_TEXTURE_2D, pFont^.tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexImage2D(GL_TEXTURE_2D, 0, 2, pFont^.texWidth, pFont^.texHeight, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, pTexBytes); CloseFile(input); num := pFont^.texWidth * pFont^.texHeight * 2; FreeMem(pTexBytes, num); end; procedure glFontDestroy(pFont : PGLFont); var num : Integer; begin num := pFont^.intEnd - pFont^.intStart + 1; FreeMem(pFont^.character, SizeOf(TGLFontChar) * num); pFont^.character := nil; end; procedure SetStringSize(var x, y : integer; id : integer; str : string); var i : integer; font : PGLFont; pCharacter : PGLFontChar; dx, dy : Double; begin dx := 0; dy := 0; font := @GLFonts[id]; for i := 0 to Length(str) - 1 do begin pCharacter := font^.character; Inc(pCharacter, Integer(str[i + 1]) - font^.intStart); dx := dx + pCharacter^.dx * font^.texWidth; dy := Max(dy, pCharacter^.dy * font^.texHeight); end; x := Round(dx); y := Round(dy); end; procedure SetFontSquares(pFont : PGLFont; str : string); var i : Integer; pCharacter : PGLFontChar; x, dx, dy : Single; begin SetLength(FontSquares.texture, Length(str) * 8); SetLength(FontSquares.vertex, Length(str) * 8); SetLength(FontSquaresIndices, Length(str) * 4); x := 0; for i := 0 to Length(str) - 1 do begin pCharacter := pFont^.character; Inc(pCharacter, Integer(str[i + 1]) - pFont^.intStart); dx := pCharacter^.dx * pFont^.texWidth; dy := pCharacter^.dy * pFont^.texHeight; FontSquares.texture[i*8 + 0] := pCharacter^.tx1; FontSquares.texture[i*8 + 1] := pCharacter^.ty1; FontSquares.texture[i*8 + 2] := pCharacter^.tx1; FontSquares.texture[i*8 + 3] := pCharacter^.ty2; FontSquares.texture[i*8 + 4] := pCharacter^.tx2; FontSquares.texture[i*8 + 5] := pCharacter^.ty2; FontSquares.texture[i*8 + 6] := pCharacter^.tx2; FontSquares.texture[i*8 + 7] := pCharacter^.ty1; FontSquares.vertex[i*8 + 0] := x; FontSquares.vertex[i*8 + 1] := 0; FontSquares.vertex[i*8 + 2] := x; FontSquares.vertex[i*8 + 3] := dy; FontSquares.vertex[i*8 + 4] := x + dx; FontSquares.vertex[i*8 + 5] := dy; FontSquares.vertex[i*8 + 6] := x + dx; FontSquares.vertex[i*8 + 7] := 0; FontSquaresIndices[i*4 + 0] := i*4 + 0; FontSquaresIndices[i*4 + 1] := i*4 + 1; FontSquaresIndices[i*4 + 2] := i*4 + 2; FontSquaresIndices[i*4 + 3] := i*4 + 3; x := x + dx; end; end; end.
unit uFuzzyStringMatch; interface type IFuzzyStringMatch = interface ['{03DF88E3-6C5D-4262-8F4B-5D8A92D15357}'] function StringSimilarityRatio(const Str1, Str2: String; IgnoreCase: Boolean): Double; end; TFuzzyStringMatch = class//(TInterfacedObject, IFuzzyStringMatch) private class function DamerauLevenshteinDistance(const Str1, Str2: String): Integer; public class function StringSimilarityRatio(const Str1, Str2: String; IgnoreCase: Boolean): Double; end; implementation uses System.SysUtils; { TFuzzyStringMatch } class function TFuzzyStringMatch.DamerauLevenshteinDistance(const Str1, Str2: String): Integer; function Min(const A, B, C: Integer): Integer; begin Result := A; if B < Result then Result := B; if C < Result then Result := C; end; var LenStr1, LenStr2: Integer; I, J, T, Cost, PrevCost: Integer; pStr1, pStr2, S1, S2: PChar; D: PIntegerArray; begin LenStr1 := Length(Str1); LenStr2 := Length(Str2); // save a bit memory by making the second index points to the shorter string if LenStr1 < LenStr2 then begin T := LenStr1; LenStr1 := LenStr2; LenStr2 := T; pStr1 := PChar(Str2); pStr2 := PChar(Str1); end else begin pStr1 := PChar(Str1); pStr2 := PChar(Str2); end; // bypass leading identical characters while (LenStr2 <> 0) and (pStr1^ = pStr2^) do begin Inc(pStr1); Inc(pStr2); Dec(LenStr1); Dec(LenStr2); end; // bypass trailing identical characters while (LenStr2 <> 0) and ((pStr1 + LenStr1 - 1)^ = (pStr2 + LenStr2 - 1)^) do begin Dec(LenStr1); Dec(LenStr2); end; // is the shorter string empty? so, the edit distance is length of the longer one if LenStr2 = 0 then begin Result := LenStr1; Exit; end; // calculate the edit distance GetMem(D, (LenStr2 + 1) * SizeOf(Integer)); for I := 0 to LenStr2 do D[I] := I; S1 := pStr1; for I := 1 to LenStr1 do begin PrevCost := I - 1; Cost := I; S2 := pStr2; for J := 1 to LenStr2 do begin if (S1^ = S2^) or ((I > 1) and (J > 1) and (S1^ = (S2 - 1)^) and (S2^ = (S1 - 1)^)) then Cost := PrevCost else Cost := 1 + Min(Cost, PrevCost, D[J]); PrevCost := D[J]; D[J] := Cost; Inc(S2); end; Inc(S1); end; Result := D[LenStr2]; FreeMem(D); end; class function TFuzzyStringMatch.StringSimilarityRatio(const Str1, Str2: String; IgnoreCase: Boolean): Double; var MaxLen: Integer; Distance: Integer; begin Result := 1.0; if Length(Str1) > Length(Str2) then MaxLen := Length(Str1) else MaxLen := Length(Str2); if MaxLen <> 0 then begin if IgnoreCase then Distance := DamerauLevenshteinDistance(LowerCase(Str1), LowerCase(Str2)) else Distance := DamerauLevenshteinDistance(Str1, Str2); Result := Result - (Distance / MaxLen); end; end; end.
(* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Any non-GPL usage of this software or parts of this software is strictly * forbidden. * * The "appropriate copyright message" mentioned in section 2c of the GPLv2 * must read: "Code from FAAD2 is copyright (c) Nero AG, www.nero.com" * * Commercial non-GPL licensing of this software is possible. * please contact robert@prog.olsztyn.pl * * http://prog.olsztyn.pl/paslibvlc/ * *) {$I ..\..\source\compiler.inc} unit MainFormUnit; interface uses LCLIntf, LCLType, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, PasLibVlcPlayerUnit; type { TMainForm } TMainForm = class(TForm) mrlEdit: TEdit; player: TPasLibVlcPlayer; playButton: TButton; procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure playerMediaPlayerTimeChanged(Sender: TObject; time: Int64); procedure playButtonClick(Sender: TObject); private needStop : Boolean; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.lfm} procedure TMainForm.FormCreate(Sender: TObject); begin {$IFDEF LCLGTK2} Caption := Caption + ' LCL GTK2'; {$ELSE} {$IFDEF LCLQT} Caption := Caption + ' LCL QT'; {$ELSE} Caption := Caption + ' LCL WIN'; {$ENDIF} {$ENDIF} Caption := Caption + ' x' + {$IFDEF CPUX32}'32'{$ELSE}'64'{$ENDIF}; needStop := TRUE; mrlEdit.Text := '..'+PathDelim+'..'+PathDelim+'_testFiles'+PathDelim+'test.ts'; player.Play(WideString(mrlEdit.Text)); end; procedure TMainForm.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin player.Stop(); end; procedure TMainForm.playButtonClick(Sender: TObject); begin player.Resume(); end; procedure TMainForm.playerMediaPlayerTimeChanged(Sender: TObject; time: Int64); begin if (needStop) and (time > 500) then begin needStop := FALSE; player.Pause(); end; end; end.
unit StatementSystemStek; interface uses Formulae; procedure initStek(); procedure push(var SS : TStatementSystem); // кладём function pop() : TStatementSystem; //вынимаем implementation type SSStek = record SSArray : array of TStatementSystem; position : integer; length : integer; end; var stek : SSStek; procedure initStek(); begin stek.position := -1; stek.length := 2; setlength(stek.SSArray, stek.length); end; procedure expansion(); begin inc(stek.position); if stek.position >= stek.length then begin stek.length := stek.length * 2; setlength(stek.SSArray, stek.length); end; end; procedure push(var SS : TStatementSystem); // кладём begin expansion(); stek.SSArray[stek.position] := SS; end; function pop() : TStatementSystem; //вынимаем begin result := stek.SSArray[stek.position]; stek.position := stek.position - 1; end; end.
/////////////////////////////////////////////////////////////////////////// // Project: CW // Program: codesndu.pas // Language: Object Pascal - Delphi ver 3.0 // Support: David Fahey // Date: 01Oct97 // Purpose: Sends a never ending sequence of random characters. // History: 10Oct97 Initial coding DAF // Notes: None /////////////////////////////////////////////////////////////////////////// unit codesndu; interface uses Classes; type TCodeSend = class(TThread) private { Private declarations } protected procedure DispLetter ; procedure Execute; override; end; implementation uses Windows, SysUtils, cwu ; const MaxSize = 20000000 ; procedure TCodeSend.DispLetter ; begin Form1.LetterSent.Caption := Letter ; end; { TCodeSend } procedure TCodeSend.Execute; var i,j: integer ; begin FreeOnTerminate := True ; for i := 1 to MaxSize do {do for ever} begin If Terminated then Break ; {generate random character} j := ord('A') + Trunc(Random(26)) ; {send character} SendChar(chr(j)) ; {display the letter for a short time} Letter := Chr(j) ; Synchronize(DispLetter) ; if Twice then begin Sleep(1000) ; {send character} SendChar(chr(j)) ; Sleep(1500) ; end else Sleep(2500) ; Letter := '' ; Synchronize(DispLetter) ; end ; end; end.
unit RESTRequest4D.Request.Client; interface uses RESTRequest4D.Request.Contract, Data.DB, REST.Client, REST.Response.Adapter, REST.Types, System.SysUtils, System.Classes, RESTRequest4D.Response.Contract, REST.Authenticator.Basic{$IF COMPILERVERSION >= 33.0}, System.Net.HttpClient{$ENDIF}, System.JSON, RESTRequest4D.Request.Adapter.Contract; type TRequestClient = class(TInterfacedObject, IRequest) private FParams: TStrings; FResponse: IResponse; FHeaders: TStrings; FHTTPBasicAuthenticator: THTTPBasicAuthenticator; FRESTRequest: TRESTRequest; FAdapters: TArray<IRequestAdapter>; FRESTResponse: TRESTResponse; FRESTClient: TRESTClient; FRetries: Integer; procedure ExecuteRequest; procedure DoJoinComponents; function PrepareUrlSegments(const AValue: string): string; function AcceptEncoding: string; overload; function AcceptEncoding(const AAcceptEncoding: string): IRequest; overload; function AcceptCharset: string; overload; function AcceptCharset(const AAcceptCharset: string): IRequest; overload; function Accept: string; overload; function Accept(const AAccept: string): IRequest; overload; function Adapters(const AAdapter: IRequestAdapter): IRequest; overload; function Adapters(const AAdapters: TArray<IRequestAdapter>): IRequest; overload; function Adapters: TArray<IRequestAdapter>; overload; function BaseURL(const ABaseURL: string): IRequest; overload; function BaseURL: string; overload; function Resource(const AResource: string): IRequest; overload; function Resource: string; overload; function ResourceSuffix(const AResourceSuffix: string): IRequest; overload; function ResourceSuffix: string; overload; function Timeout(const ATimeout: Integer): IRequest; overload; function Timeout: Integer; overload; function RaiseExceptionOn500: Boolean; overload; function RaiseExceptionOn500(const ARaiseException: Boolean): IRequest; overload; function FullRequestURL(const AIncludeParams: Boolean = True): string; function Token(const AToken: string): IRequest; function TokenBearer(const AToken: string): IRequest; function BasicAuthentication(const AUsername, APassword: string): IRequest; function Retry(const ARetries: Integer): IRequest; function Get: IResponse; function Post: IResponse; function Put: IResponse; function Delete: IResponse; function Patch: IResponse; function ClearBody: IRequest; function AddParam(const AName, AValue: string; const AKind: TRESTRequestParameterKind = {$IF COMPILERVERSION < 33}TRESTRequestParameterKind.pkGETorPOST{$ELSE}TRESTRequestParameterKind.pkQUERY{$ENDIF}): IRequest; function AddBody(const AContent: string; const AContentType: TRESTContentType = ctAPPLICATION_JSON): IRequest; overload; function AddBody(const AContent: TJSONObject; const AOwns: Boolean = True): IRequest; overload; function AddBody(const AContent: TJSONArray; const AOwns: Boolean = True): IRequest; overload; function AddBody(const AContent: TObject; const AOwns: Boolean = True): IRequest; overload; function AddBody(const AContent: TStream; const AOwns: Boolean = True): IRequest; overload; function FallbackCharsetEncoding(const AFallbackCharsetEncoding: string): IRequest; function AddUrlSegment(const AName, AValue: string): IRequest; function SynchronizedEvents(const AValue: Boolean): IRequest; function ClearHeaders: IRequest; function AddHeader(const AName, AValue: string; const AOptions: TRESTRequestParameterOptions = []): IRequest; function ClearParams: IRequest; function ContentType(const AContentType: string): IRequest; function UserAgent(const AName: string): IRequest; function AddCookies(const ACookies: TStrings): IRequest; function AddCookie(const ACookieName, ACookieValue: string): IRequest; function AddField(const AFieldName: string; const AValue: string): IRequest; overload; function AddFile(const AFieldName: string; const AFileName: string; const AContentType: TRESTContentType = TRESTContentType.ctNone): IRequest; overload; function AddFile(const AFieldName: string; const AValue: TStream; const AFileName: string = ''; const AContentType: TRESTContentType = TRESTContentType.ctNone): IRequest; overload; function Proxy(const AServer, APassword, AUsername: string; const APort: Integer): IRequest; function DeactivateProxy: IRequest; protected procedure DoAfterExecute(Sender: TCustomRESTRequest); virtual; procedure DoBeforeExecute(Sender: TCustomRESTRequest); virtual; procedure DoHTTPProtocolError(Sender: TCustomRESTRequest); virtual; public constructor Create; virtual; destructor Destroy; override; end; implementation uses System.Generics.Collections, RESTRequest4D.Response.Client; function TRequestClient.AddBody(const AContent: string; const AContentType: TRESTContentType): IRequest; begin Result := Self; if AContent.Trim.IsEmpty then Exit; {$IF COMPILERVERSION <= 29} FRESTRequest.AddBody(AContent, AContentType); {$ELSE} FRESTRequest.Body.Add(AContent, AContentType); {$ENDIF} end; function TRequestClient.AddBody(const AContent: TJSONObject; const AOwns: Boolean): IRequest; begin Result := Self; if not Assigned(AContent) then Exit; {$IF COMPILERVERSION <= 29} FRESTRequest.AddBody(AContent); {$ELSE} FRESTRequest.Body.Add(AContent); {$ENDIF} if AOwns then begin {$IFDEF MSWINDOWS} AContent.Free; {$ELSE} AContent.DisposeOf; {$ENDIF} end; end; function TRequestClient.AddBody(const AContent: TJSONArray; const AOwns: Boolean): IRequest; begin Result := Self; if not Assigned(AContent) then Exit; Self.AddBody(AContent.ToString); if AOwns then begin {$IFDEF MSWINDOWS} AContent.Free; {$ELSE} AContent.DisposeOf; {$ENDIF} end; end; function TRequestClient.AddBody(const AContent: TObject; const AOwns: Boolean): IRequest; begin Result := Self; if not Assigned(AContent) then Exit; {$IF COMPILERVERSION <= 29} FRESTRequest.AddBody(AContent); {$ELSE} FRESTRequest.Body.Add(AContent); {$ENDIF} if AOwns then begin {$IFDEF MSWINDOWS} AContent.Free; {$ELSE} AContent.DisposeOf; {$ENDIF} end; end; function TRequestClient.AddField(const AFieldName: string; const AValue: string): IRequest; begin Result := Self; FRESTRequest.Params.AddItem(AFieldName, AValue); end; function TRequestClient.AddFile(const AFieldName: string; const AFileName: string; const AContentType: TRESTContentType): IRequest; begin Result := Self; {$IF COMPILERVERSION >= 32.0} if not FileExists(AFileName) then Exit; FRESTRequest.AddFile(AFieldName, AFileName, AContentType); {$ELSE} raise Exception.Create('Method not implemented for your Delphi version. Try changing the engine or submitting a pull request.'); {$ENDIF} end; function TRequestClient.AddFile(const AFieldName: string; const AValue: TStream; const AFileName: string; const AContentType: TRESTContentType): IRequest; {$IF COMPILERVERSION >= 33.0} var lFileName: string; {$ENDIF} begin Result := Self; {$IF COMPILERVERSION >= 33.0} if not Assigned(AValue) then Exit; lFileName := Trim(AFileName); if (lFileName = EmptyStr) then lFileName := AFieldName; AValue.Position := 0; with FRESTRequest.Params.AddItem do begin name := AFieldName; SetStream(AValue); Value := lFileName; Kind := TRESTRequestParameterKind.pkFILE; ContentType := AContentType; end; {$ELSE} raise Exception.Create('Method not implemented for your Delphi version. Try changing the engine or submitting a pull request.'); {$ENDIF} end; function TRequestClient.AddHeader(const AName, AValue: string; const AOptions: TRESTRequestParameterOptions): IRequest; begin Result := Self; if AName.Trim.IsEmpty or AValue.Trim.IsEmpty then Exit; if FHeaders.IndexOf(AName) < 0 then FHeaders.Add(AName); FRESTRequest.Params.AddHeader(AName, AValue); FRESTRequest.Params.ParameterByName(AName).Options := AOptions; end; function TRequestClient.AddParam(const AName, AValue: string; const AKind: TRESTRequestParameterKind): IRequest; begin Result := Self; if AName.Trim.IsEmpty or AValue.Trim.IsEmpty then Exit; FParams.Add(AName); FRESTRequest.AddParameter(AName, AValue, AKind); end; function TRequestClient.AddUrlSegment(const AName, AValue: string): IRequest; begin Result := Self; if AName.Trim.IsEmpty or AValue.Trim.IsEmpty then Exit; if not FRESTRequest.Params.ContainsParameter(AName) then begin if (not ResourceSuffix.Trim.IsEmpty) and (not ResourceSuffix.EndsWith('/')) then ResourceSuffix(ResourceSuffix + '/'); ResourceSuffix(ResourceSuffix + '{' + AName + '}'); end; FRESTRequest.Params.AddUrlSegment(AName, AValue); end; function TRequestClient.BasicAuthentication(const AUsername, APassword: string): IRequest; begin Result := Self; if not Assigned(FHTTPBasicAuthenticator) then begin FHTTPBasicAuthenticator := THTTPBasicAuthenticator.Create(nil); FRESTClient.Authenticator := FHTTPBasicAuthenticator; end; FHTTPBasicAuthenticator.Username := AUsername; FHTTPBasicAuthenticator.Password := APassword; end; function TRequestClient.ClearBody: IRequest; begin Result := Self; FRESTRequest.ClearBody; end; function TRequestClient.ClearHeaders: IRequest; var I: Integer; begin Result := Self; for I := 0 to Pred(FHeaders.Count) do FRESTRequest.Params.Delete(FRESTRequest.Params.ParameterByName(FHeaders[I])); end; function TRequestClient.ClearParams: IRequest; var I: Integer; begin Result := Self; for I := 0 to Pred(FParams.Count) do FRESTRequest.Params.Delete(FRESTRequest.Params.ParameterByName(FParams[I])); end; function TRequestClient.ContentType(const AContentType: string): IRequest; begin Result := Self; Self.AddHeader('Content-Type', AContentType, [poDoNotEncode]); end; function TRequestClient.UserAgent(const AName: string): IRequest; begin Result := Self; if not AName.Trim.IsEmpty then FRESTRequest.Client.UserAgent := AName; end; constructor TRequestClient.Create; begin FRESTResponse := TRESTResponse.Create(nil); FRESTClient := TRESTClient.Create(nil); FRESTClient.SynchronizedEvents := False; {$IF COMPILERVERSION >= 33} FRESTClient.SecureProtocols := [THTTPSecureProtocol.SSL3, THTTPSecureProtocol.TLS1, THTTPSecureProtocol.TLS11, THTTPSecureProtocol.TLS12]; {$ENDIF} FRESTRequest := TRESTRequest.Create(nil); FRESTRequest.SynchronizedEvents := False; FParams := TStringList.Create; FHeaders := TStringList.Create; FResponse := TResponseClient.Create(FRESTResponse); FRESTRequest.OnAfterExecute := DoAfterExecute; FRESTRequest.OnHTTPProtocolError := DoHTTPProtocolError; DoJoinComponents; FRESTClient.RaiseExceptionOn500 := False; FRetries := 0; end; function TRequestClient.DeactivateProxy: IRequest; begin Result := Self; FRESTClient.ProxyPassword := EmptyStr; FRESTClient.ProxyServer := EmptyStr; FRESTClient.ProxyUsername := EmptyStr; FRESTClient.ProxyPort := 0; end; function TRequestClient.Delete: IResponse; begin Result := FResponse; DoBeforeExecute(FRESTRequest); FRESTRequest.Method := TRESTRequestMethod.rmDELETE; ExecuteRequest; end; destructor TRequestClient.Destroy; begin if Assigned(FHTTPBasicAuthenticator) then FreeAndNil(FHTTPBasicAuthenticator); FreeAndNil(FParams); FreeAndNil(FHeaders); FreeAndNil(FRESTRequest); FreeAndNil(FRESTClient); FreeAndNil(FRESTResponse); inherited; end; procedure TRequestClient.DoAfterExecute(Sender: TCustomRESTRequest); var LAdapter: IRequestAdapter; begin for LAdapter in FAdapters do LAdapter.Execute(FRESTResponse.Content); end; procedure TRequestClient.DoBeforeExecute(Sender: TCustomRESTRequest); begin // virtual method end; procedure TRequestClient.DoHTTPProtocolError(Sender: TCustomRESTRequest); begin // virtual method end; procedure TRequestClient.DoJoinComponents; begin FRESTRequest.Client := FRESTClient; FRESTRequest.Response := FRESTResponse; end; procedure TRequestClient.ExecuteRequest; var LAttempts: Integer; begin LAttempts := FRetries + 1; while LAttempts > 0 do begin try FRESTRequest.Execute; LAttempts := 0; except begin LAttempts := LAttempts - 1; if LAttempts = 0 then raise; end; end; end; end; function TRequestClient.Get: IResponse; begin Result := FResponse; DoBeforeExecute(FRESTRequest); FRESTRequest.Method := TRESTRequestMethod.rmGET; ExecuteRequest; end; function TRequestClient.Accept: string; begin Result := FRESTRequest.Accept; end; function TRequestClient.AcceptCharset: string; begin Result := FRESTRequest.AcceptCharset; end; function TRequestClient.AcceptEncoding: string; begin Result := FRESTRequest.AcceptEncoding; end; function TRequestClient.BaseURL: string; begin Result := FRESTClient.BaseURL; end; function TRequestClient.FallbackCharsetEncoding(const AFallbackCharsetEncoding: string): IRequest; begin Result := Self; FRESTClient.FallbackCharsetEncoding := AFallbackCharsetEncoding; end; function TRequestClient.FullRequestURL(const AIncludeParams: Boolean): string; begin Result := FRESTRequest.GetFullRequestURL(AIncludeParams); end; function TRequestClient.Resource: string; begin Result := FRESTRequest.Resource; end; function TRequestClient.ResourceSuffix: string; begin Result := FRESTRequest.ResourceSuffix; end; function TRequestClient.Retry(const ARetries: Integer): IRequest; begin Result := Self; FRetries := ARetries; end; function TRequestClient.SynchronizedEvents(const AValue: Boolean): IRequest; begin FRESTClient.SynchronizedEvents := AValue; FRESTRequest.SynchronizedEvents := AValue; end; function TRequestClient.Timeout: Integer; begin {$IF COMPILERVERSION <= 33} Result := FRESTRequest.Timeout; {$ELSE} Result := FRESTRequest.ConnectTimeout; {$ENDIF} end; function TRequestClient.Patch: IResponse; begin Result := FResponse; DoBeforeExecute(FRESTRequest); FRESTRequest.Method := TRESTRequestMethod.rmPATCH; ExecuteRequest; end; function TRequestClient.Post: IResponse; begin Result := FResponse; DoBeforeExecute(FRESTRequest); FRESTRequest.Method := TRESTRequestMethod.rmPOST; ExecuteRequest; end; function TRequestClient.PrepareUrlSegments(const AValue: string): string; var LSplitedPath: TArray<string>; LPart: string; LPreparedUrl: string; begin LSplitedPath := AValue.Split(['/', '?', '=', '&']); LPreparedUrl := AValue; for LPart in LSplitedPath do begin if LPart.StartsWith(':') then LPreparedUrl := StringReplace(LPreparedUrl, LPart, Format('{%s}', [LPart.TrimLeft([':'])]), []); end; Result := LPreparedUrl; end; function TRequestClient.Proxy(const AServer, APassword, AUsername: string; const APort: Integer): IRequest; begin Result := Self; FRESTClient.ProxyPassword := APassword; FRESTClient.ProxyServer := AServer; FRESTClient.ProxyUsername := AUsername; FRESTClient.ProxyPort := APort; end; function TRequestClient.Put: IResponse; begin Result := FResponse; DoBeforeExecute(FRESTRequest); FRESTRequest.Method := TRESTRequestMethod.rmPUT; ExecuteRequest; end; function TRequestClient.Accept(const AAccept: string): IRequest; const REQUEST_DEFAULT_ACCEPT = CONTENTTYPE_APPLICATION_JSON + ', ' + CONTENTTYPE_TEXT_PLAIN + '; q=0.9, ' + CONTENTTYPE_TEXT_HTML + ';q=0.8,'; begin Result := Self; FRESTRequest.Accept := REQUEST_DEFAULT_ACCEPT; if not AAccept.Trim.IsEmpty then FRESTRequest.Accept := AAccept; end; function TRequestClient.AcceptCharset(const AAcceptCharset: string): IRequest; const REQUEST_DEFAULT_ACCEPT_CHARSET = 'utf-8, *;q=0.8'; begin Result := Self; FRESTRequest.AcceptCharset := REQUEST_DEFAULT_ACCEPT_CHARSET; if not AAcceptCharset.Trim.IsEmpty then FRESTRequest.AcceptCharset := AAcceptCharset; end; function TRequestClient.AcceptEncoding(const AAcceptEncoding: string): IRequest; begin Result := Self; FRESTRequest.AcceptEncoding := AAcceptEncoding; end; function TRequestClient.BaseURL(const ABaseURL: string): IRequest; begin Result := Self; FRESTClient.BaseURL := PrepareUrlSegments(ABaseURL); end; function TRequestClient.RaiseExceptionOn500: Boolean; begin Result := FRESTClient.RaiseExceptionOn500; end; function TRequestClient.RaiseExceptionOn500(const ARaiseException: Boolean): IRequest; begin Result := Self; FRESTClient.RaiseExceptionOn500 := ARaiseException; end; function TRequestClient.Resource(const AResource: string): IRequest; begin Result := Self; FRESTRequest.Resource := PrepareUrlSegments(AResource); end; function TRequestClient.ResourceSuffix(const AResourceSuffix: string): IRequest; begin Result := Self; FRESTRequest.ResourceSuffix := PrepareUrlSegments(AResourceSuffix); end; function TRequestClient.Timeout(const ATimeout: Integer): IRequest; begin Result := Self; {$IF COMPILERVERSION <= 33} FRESTRequest.Timeout := ATimeout; {$ELSE} FRESTRequest.ConnectTimeout := ATimeout; FRESTRequest.ReadTimeout := ATimeout; {$ENDIF} end; function TRequestClient.Token(const AToken: string): IRequest; const AUTHORIZATION = 'Authorization'; begin Result := Self; if AToken.Trim.IsEmpty then Exit; if FHeaders.IndexOf(AUTHORIZATION) < 0 then FHeaders.Add(AUTHORIZATION); FRESTRequest.Params.AddHeader(AUTHORIZATION, AToken); FRESTRequest.Params.ParameterByName(AUTHORIZATION).Options := [poDoNotEncode]; end; function TRequestClient.TokenBearer(const AToken: string): IRequest; begin Result := Self; if AToken.Trim.IsEmpty then Exit; Self.Token('Bearer ' + AToken); end; function TRequestClient.Adapters(const AAdapter: IRequestAdapter): IRequest; begin Result := Adapters([AAdapter]); end; function TRequestClient.Adapters(const AAdapters: TArray<IRequestAdapter>): IRequest; begin FAdapters := AAdapters; Result := Self; end; function TRequestClient.Adapters: TArray<IRequestAdapter>; begin Result := FAdapters; end; function TRequestClient.AddBody(const AContent: TStream; const AOwns: Boolean): IRequest; begin Result := Self; if not Assigned(AContent) then Exit; {$IF COMPILERVERSION <= 29} FRESTRequest.AddBody(AContent, TRESTContentType.ctAPPLICATION_OCTET_STREAM); {$ELSE} FRESTRequest.Body.Add(AContent, TRESTContentType.ctAPPLICATION_OCTET_STREAM); {$ENDIF} if AOwns then begin {$IFDEF MSWINDOWS} AContent.Free; {$ELSE} AContent.DisposeOf; {$ENDIF} end; end; function TRequestClient.AddCookies(const ACookies: TStrings): IRequest; var I: Integer; begin Result := Self; for I := 0 to Pred(ACookies.Count) do FRESTRequest.AddParameter(ACookies.Names[I], ACookies.Values[ACookies.Names[I]], TRESTRequestParameterKind.pkCOOKIE); end; function TRequestClient.AddCookie(const ACookieName, ACookieValue: string): IRequest; begin Result := Self; FRESTRequest.AddParameter(ACookieName, ACookieValue, TRESTRequestParameterKind.pkCOOKIE); end; end.
//******************************************************* // // Delphi DataSnap Framework // // Copyright(c) 1995-2012 Embarcadero Technologies, Inc. // //******************************************************* unit DBXFPCCommon; {$IFDEF FPC} {$mode Delphi} {$ENDIF} interface uses DBXValue, DSRestTypes, Classes, DBXFPCJSON, Contnrs; type TDBXUInt8Value = class(TDBXValue) private FValueNull: boolean; FDBXUInt8Value: UInt8; protected function GetAsUInt8: UInt8; override; procedure SetAsUInt8(const Value: UInt8); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXUInt16Value = class(TDBXValue) private FValueNull: boolean; FDBXUInt16Value: UInt16; protected function GetAsUInt16: UInt16; override; procedure SetAsUInt16(const Value: UInt16); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXInt8Value = class(TDBXValue) private ValueNull: boolean; DBXInt8Value: Int8; protected function GetAsInt8: Int8; override; procedure SetAsInt8(const Value: Int8); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; { TDBXInt16Value } TDBXInt16Value = class(TDBXValue) private DBXInt16Value: Int16; ValueNull: boolean; protected function GetAsInt16: Int16; override; procedure SetAsInt16(const Value: Int16); override; public function isNull: boolean; procedure SetNull;override; constructor Create; override; end; TDBXInt32Value = class(TDBXValue) private DBXInt32Value: Int32; ValueNull: boolean; protected function GetAsInt32: Int32; override; procedure SetAsInt32(const Value: Int32); override; public function isNull: boolean; procedure SetNull(const Value: boolean);reintroduce; constructor Create; override; end; TDBXInt64Value = class(TDBXValue) private DBXInt64Value: int64; ValueNull: boolean; protected function GetAsInt64: int64; override; procedure SetAsInt64(const Value: int64); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXDoubleValue = class(TDBXValue) private DBXDoubleValue: double; ValueNull: boolean; protected function GetAsDouble: double; override; procedure SetAsDouble(const Value: double); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXSingleValue = class(TDBXValue) private DBXSingleValue: single; ValueNull: boolean; protected function GetAsSingle: single; override; procedure SetAsSingle(const Value: single); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXBcdValue = class(TDBXValue) private ValueNull: boolean; DBXBcdValue: double; protected function GetAsBcd: double; override; procedure SetAsBcd(const Value: double); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXBooleanValue = class(TDBXValue) private DBXBooleanValue: boolean; ValueNull: boolean; protected function GetAsBoolean: boolean; override; procedure SetAsBoolean(const Value: boolean); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXAnsiStringValue = class(TDBXValue) private DBXAnsiStringValue: AnsiString; ValueNull: boolean; protected function GetAsAnsiString: AnsiString; override; procedure SetAsAnsiString(const Value: AnsiString); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXAnsiCharsValue = class(TDBXValue) private DBXAnsiCharsValue: string; ValueNull: boolean; protected function GetAsString: string; override; procedure SetAsString(const Value: string); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXDateValue = class(TDBXValue) private DBXDateValue: longint; ValueNull: boolean; protected function GetAsTDBXDate: longint; override; procedure SetAsTDBXDate(const Value: longint); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXStreamValue = class(TDBXValue) private ValueNull: boolean; FStreamValue:TStream; protected function GetAsStream: TStream; override; procedure SetAsStream(const Value: TStream); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXStringValue = class(TDBXValue) private ValueNull: boolean; DBXStringValue: string; protected function GetAsString: string; override; procedure SetAsString(const Value: string); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXWideStringValue = class(TDBXValue) private DBXWideStringValue: wideString; ValueNull: boolean; protected function GetAsString: string; override; procedure SetAsString(const Value: string); override; function GetAsWideString: wideString; override; procedure SetAsWideString(const Value: wideString); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXTimeValue = class(TDBXValue) private DBXTimeValue: longint; ValueNull: boolean; protected function GetAsTDBXTime: longint; override; procedure SetAsTDBXTime(const Value: longint); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; TDBXTimeStampValue = class(TDBXValue) private ValueNull: boolean; DBXTimeStampValue: TDateTime; protected function GetAsDateTime: TDateTime; override; procedure SetAsDateTime(const Value: TDateTime); override; function GetAsTimeStamp: TDateTime; override; procedure SetAsTimeStamp(const Value: TDateTime); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; end; { TDBXParameter } TDBXParameter = class(TDBXValueType) private Value: TDBXWritableValue; public function GetValue: TDBXWritableValue; procedure setDataType(dataType: TDBXDataTypes); override; function getDataType: integer; override; function ToJSON: TJSONArray; constructor Create; destructor Destroy; override; end; TDBXParameterList = class private FObjectList: TObjectList; protected function GetItems(Index: cardinal): TDBXParameter; procedure SetItems(Index: cardinal; const Value: TDBXParameter); public constructor Create; overload; constructor Create(FreeObjects: boolean); overload; procedure Clear; destructor Destroy; override; procedure Add(AObject: TDBXParameter); overload; function Add: TDBXParameter; overload; procedure Delete(Index: cardinal); function Count: cardinal; property Items[Index: cardinal]: TDBXParameter read GetItems write SetItems; default; end; // JSONSerializable = interface // ['{7057563B-46DB-4485-A8FE-EE0473B4F3DD}'] // function asJSONObject: TJSONObject; // end; // // TableType = interface // ['{6C03419D-B362-4977-9225-392375A608B9}'] // end; { TParams } TDSParams = class private FParams: TDBXParameterList; public function asJSONObject: TJSONObject; constructor Create; destructor Destroy; override; function AddParameter(parameter: TDBXParameter): TDSParams; function FindParamByName(Value: string): TDBXParameter; function GetParamByName(Value: string): TDBXParameter; function Size: integer; function getParameter(Index: integer): TDBXParameter; class procedure LoadParametersValues(params: TDSParams; Value: TJSONObject); overload; class function LoadParametersValues(params: TDSParams; Value: TJSONObject; Offset: integer): boolean; overload; class function CreateFrom(Value: TJSONObject): TDSParams; class function CreateParametersFromMetadata(paramsMetadata: TJSONArray) : TDSParams; end; { TDBXReader } TDBXReader = class private FInternalDataStore: TJSONObject; FColumns: TDSParams; protected currentPosition: longint; function GetColumns: TDSParams; procedure SetParameters(const Value: TDSParams); public property Columns: TDSParams read GetColumns write SetParameters; procedure Reset; function asJSONObject: TJSONObject; function GetValue(position: integer): TDBXWritableValue; overload; function GetValue(Name: string): TDBXWritableValue; overload; function Next: boolean; constructor Create(params: TDSParams; Value: TJSONObject); destructor Destroy; override; class function CreateFrom(Value: TJSONObject): TDBXReader; end; { TDBXReaderValue } TDBXReaderValue = class(TDBXValue) private ValueNull: boolean; function getAsDBXReader: TDBXReader; procedure setAsDBXReader(const Value: TDBXReader); protected function GetAsTable: TObject; override; procedure SetAsTable(const Value: TObject); override; public function isNull: boolean; procedure SetNull; override; constructor Create; override; property AsDBXReader:TDBXReader read getAsDBXReader write setAsDBXReader; end; implementation uses SysUtils, DBXJsonTools,FPCStrings; { TDBXReaderValue } function TDBXReaderValue.getAsDBXReader: TDBXReader; begin result:= GetAsTable as TDBXReader ; end; function TDBXReaderValue.GetAsTable: TObject; begin Result := FobjectValue; end; procedure TDBXReaderValue.SetAsTable(const Value: TObject); begin ValueNull := False; FobjectValue:=Value; end; function TDBXReaderValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXReaderValue.setAsDBXReader(const Value: TDBXReader); begin SetAsTable(Value); end; procedure TDBXReaderValue.setNull; begin ValueNull := True; Clear; end; constructor TDBXReaderValue.Create; begin inherited; SetDBXType(TableType); ValueNull := False; end; { TDBXParameter } function TDBXParameter.GetValue: TDBXWritableValue; begin Result := Value; end; procedure TDBXParameter.setDataType(dataType: TDBXDataTypes); begin Value.DBXType := dataType; end; function TDBXParameter.getDataType: integer; begin Result := Ord(GetValue.DBXType); end; function TDBXParameter.ToJSON: TJSONArray; begin Result := TJSONArray.Create; Result.Add(Name); Result.Add(getDataType); Result.Add(Ordinal); Result.Add(SubType); Result.Add(Scale); Result.Add(Size); Result.Add(Precision); Result.Add(ChildPosition); Result.Add(Nullable); Result.Add(Hidden); Result.Add(ParameterDirection); Result.Add(ValueParameter); Result.Add(Literal); end; constructor TDBXParameter.Create; begin inherited; Value := TDBXWritableValue.Create; Value.Clear; end; destructor TDBXParameter.Destroy; begin Value.Free; inherited Destroy; end; { TDBXInt8Value } constructor TDBXInt8Value.Create; begin inherited; SetDBXType(Int8Type); ValueNull := False; end; function TDBXInt8Value.getAsInt8: Int8; begin try Result := DBXInt8Value; except on e: Exception do raise DBXException.Create(e.Message); end; end; function TDBXInt8Value.isNull: boolean; begin Result := ValueNull; end; procedure TDBXInt8Value.SetAsInt8(const Value: Int8); begin try DBXInt8Value := Value; ValueNull := False; except on e: Exception do raise DBXException.Create(e.Message); end; end; procedure TDBXInt8Value.setNull; begin SetAsInt8(0); ValueNull := True; end; { TDBXInt16Value } constructor TDBXInt16Value.Create; begin SetDBXType(Int16Type); end; function TDBXInt16Value.getAsInt16: Int16; begin Result := DBXInt16Value; end; function TDBXInt16Value.isNull: boolean; begin Result := ValueNull; end; procedure TDBXInt16Value.SetAsInt16(const Value: Int16); begin ValueNull := False; DBXInt16Value := Value; end; procedure TDBXInt16Value.setNull; begin SetAsInt16(0); ValueNull := True; end; { TDBXInt32Value } constructor TDBXInt32Value.Create; begin inherited; SetDBXType(Int32Type); ValueNull := False; end; function TDBXInt32Value.getAsInt32: Int32; begin Result := DBXInt32Value; end; function TDBXInt32Value.isNull: boolean; begin Result := ValueNull; end; procedure TDBXInt32Value.SetAsInt32(const Value: Int32); begin ValueNull := False; DBXInt32Value := Value; end; procedure TDBXInt32Value.setNull; begin SetAsInt32(0); ValueNull := True; end; { TDBXInt64Value } constructor TDBXInt64Value.Create; begin inherited; SetDBXType(Int64Type); ValueNull := False; end; function TDBXInt64Value.getAsInt64: int64; begin Result := DBXInt64Value; end; function TDBXInt64Value.isNull: boolean; begin Result := ValueNull; end; procedure TDBXInt64Value.SetAsInt64(const Value: int64); begin ValueNull := False; DBXInt64Value := Value; end; procedure TDBXInt64Value.setNull; begin SetAsInt64(0); ValueNull := True; end; { TDBXDoubleValue } constructor TDBXDoubleValue.Create; begin inherited; SetDBXType(DoubleType); ValueNull := False; end; function TDBXDoubleValue.getAsDouble: double; begin Result := DBXDoubleValue; end; function TDBXDoubleValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXDoubleValue.SetAsDouble(const Value: double); begin ValueNull := False; DBXDoubleValue := Value; end; procedure TDBXDoubleValue.setNull; begin SetAsDouble(0); ValueNull := True; end; { TDBXSingleValue } constructor TDBXSingleValue.Create; begin inherited; SetDBXType(SingleType); ValueNull := False; end; function TDBXSingleValue.getAsSingle: single; begin Result := DBXSingleValue; end; function TDBXSingleValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXSingleValue.SetAsSingle(const Value: single); begin ValueNull := False; DBXSingleValue := Value; end; procedure TDBXSingleValue.setNull; begin SetAsSingle(0); ValueNull := True; end; { TDBXBcdValue } constructor TDBXBcdValue.Create; begin inherited; SetDBXType(BcdType); ValueNull := False; end; function TDBXBcdValue.getAsBcd: double; begin Result := DBXBcdValue; end; function TDBXBcdValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXBcdValue.SetAsBcd(const Value: double); begin ValueNull := False; DBXBcdValue := Value; end; procedure TDBXBcdValue.setNull; begin ValueNull := True; SetAsBcd(0); end; { TDBXBooleanValue } constructor TDBXBooleanValue.Create; begin inherited; SetDBXType(BooleanType); ValueNull := False; end; function TDBXBooleanValue.GetAsBoolean: boolean; begin Result := DBXBooleanValue; end; function TDBXBooleanValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXBooleanValue.SetAsBoolean(const Value: boolean); begin ValueNull := False; DBXBooleanValue := Value; end; procedure TDBXBooleanValue.setNull; begin SetAsBoolean(False); ValueNull := True; end; { TDBXAnsiStringValue } constructor TDBXAnsiStringValue.Create; begin inherited; SetDBXType(AnsiStringType); ValueNull := False; end; function TDBXAnsiStringValue.GetAsAnsiString: AnsiString; begin Result := DBXAnsiStringValue; end; function TDBXAnsiStringValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXAnsiStringValue.SetAsAnsiString(const Value: AnsiString); begin ValueNull := False; DBXAnsiStringValue := Value; end; procedure TDBXAnsiStringValue.setNull; begin SetAsAnsiString(''); ValueNull := True; end; { TDBXAnsiCharsValue } constructor TDBXAnsiCharsValue.Create; begin inherited; SetDBXType(WideStringType); ValueNull := False; end; function TDBXAnsiCharsValue.GetAsString: string; begin Result := DBXAnsiCharsValue; end; function TDBXAnsiCharsValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXAnsiCharsValue.SetAsString(const Value: string); begin ValueNull := False; DBXAnsiCharsValue := Value; end; procedure TDBXAnsiCharsValue.setNull; begin SetAsString(''); ValueNull := True; end; { TDBXDateValue } constructor TDBXDateValue.Create; begin inherited; SetDBXType(DateType); ValueNull := False; end; function TDBXDateValue.GetAsTDBXDate: longint; begin Result := DBXDateValue; end; function TDBXDateValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXDateValue.SetAsTDBXDate(const Value: longint); begin ValueNull := False; DBXDateValue := Value; end; procedure TDBXDateValue.setNull; begin SetAsTDBXDate(0); ValueNull := True; end; { TDBXStreamValue } constructor TDBXStreamValue.Create; begin inherited; SetDBXType(BinaryBlobType); ValueNull := False; end; function TDBXStreamValue.GetAsStream: TStream; begin Result := FStreamValue; end; function TDBXStreamValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXStreamValue.SetAsStream(const Value: TStream); begin ValueNull := False; FStreamValue := Value; end; procedure TDBXStreamValue.setNull; begin ValueNull := True; Clear; end; { TDBXStringValue } constructor TDBXStringValue.Create; begin inherited; SetDBXType(WideStringType); ValueNull := False; end; function TDBXStringValue.GetAsString: string; begin Result := DBXStringValue; end; function TDBXStringValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXStringValue.SetAsString(const Value: string); begin ValueNull := False; DBXStringValue := Value; end; procedure TDBXStringValue.setNull; begin DBXStringValue := ''; ValueNull := True; end; { TDBXWideStringValue } constructor TDBXWideStringValue.Create; begin inherited; SetDBXType(WideStringType); ValueNull := False; end; function TDBXWideStringValue.GetAsString: string; begin Result := GetAsWideString; end; function TDBXWideStringValue.GetAsWideString: wideString; begin Result := DBXWideStringValue; end; function TDBXWideStringValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXWideStringValue.SetAsString(const Value: string); begin SetAsWideString(Value); end; procedure TDBXWideStringValue.SetAsWideString(const Value: wideString); begin ValueNull := False; DBXWideStringValue := Value; end; procedure TDBXWideStringValue.setNull; begin DBXWideStringValue := ''; ValueNull := True; end; { TDBXTimeValue } constructor TDBXTimeValue.Create; begin inherited; SetDBXType(TimeType); ValueNull := False; end; function TDBXTimeValue.getAsTDBXTime: longint; begin Result := DBXTimeValue; end; function TDBXTimeValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXTimeValue.setAsTDBXTime(const Value: longint); begin ValueNull := False; DBXTimeValue := Value; end; procedure TDBXTimeValue.setNull; begin DBXTimeValue := 0; ValueNull := True; end; { TDBXTimeStampValue } constructor TDBXTimeStampValue.Create; begin inherited; SetDBXType(TimeStampType); ValueNull := False; end; function TDBXTimeStampValue.getAsDateTime: TDateTime; begin Result:= GetAsTimeStamp; end; function TDBXTimeStampValue.getAsTimeStamp: TDateTime; begin Result := DBXTimeStampValue; end; function TDBXTimeStampValue.isNull: boolean; begin Result := ValueNull; end; procedure TDBXTimeStampValue.setAsDateTime(const Value: TDateTime); begin SetAsTimeStamp(Value); end; procedure TDBXTimeStampValue.setAsTimeStamp(const Value: TDateTime); begin ValueNull := False; DBXTimeStampValue := Value; end; procedure TDBXTimeStampValue.setNull; begin ValueNull := True; DBXTimeStampValue := 0; end; { TDBXReader } function TDBXReader.asJSONObject: TJSONObject; var lastPosition: longint; begin try lastPosition := currentPosition; try Reset; Result := TDBXJsonTools.DBXReaderToJSONObject(Self); finally currentPosition := lastPosition; end; except on e: Exception do raise DBXException.Create(e.Message); end; end; constructor TDBXReader.Create(params: TDSParams; Value: TJSONObject); begin currentPosition := -1; FInternalDataStore := Value; SetParameters(params); end; destructor TDBXReader.Destroy; begin FColumns.Free; FInternalDataStore.Free; inherited Destroy; end; class function TDBXReader.CreateFrom(Value: TJSONObject): TDBXReader; begin try Result := TDBXReader.Create(TDSParams.CreateParametersFromMetadata (Value.GetJSONArray('table')), Value); except on e: Exception do raise DBXException.Create(e.Message); end; end; function TDBXReader.GetColumns: TDSParams; begin Result := FColumns; end; function TDBXReader.GetValue(Name: string): TDBXWritableValue; begin Result := FColumns.GetParamByName(Name).GetValue; end; function TDBXReader.Next: boolean; begin Inc(currentPosition); try Result := TDSParams.LoadParametersValues(Columns, FInternalDataStore, currentPosition); except Result := False; end; end; function TDBXReader.GetValue(position: integer): TDBXWritableValue; begin Result := FColumns.getParameter(position).GetValue; end; procedure TDBXReader.SetParameters(const Value: TDSParams); begin FColumns := Value; end; procedure TDBXReader.Reset; begin currentPosition := -1; end; { TParams } function TDSParams.asJSONObject: TJSONObject; begin try Result := TDBXJsonTools.DBXParametersToJSONObject(Self); except on e: Exception do raise DBXException.Create(e.Message); end; end; constructor TDSParams.Create; begin inherited; FParams := TDBXParameterList.Create(True); end; destructor TDSParams.Destroy; begin FParams.Free; inherited Destroy; end; function TDSParams.AddParameter(parameter: TDBXParameter): TDSParams; begin try if FindParamByName(parameter.Name) = nil then FParams.Add(parameter) else raise DBXException.Create('Parameter name must be unique'); Result := Self; except on e: Exception do raise DBXException.Create(e.Message); end; end; function TDSParams.FindParamByName(Value: string): TDBXParameter; var i: integer; p: TDBXParameter; begin for i := 0 to FParams.Count - 1 do begin p := FParams.Items[i]; if p.Name = Value then begin Exit(p); end; end; Result := nil; end; function TDSParams.GetParamByName(Value: string): TDBXParameter; var p: TDBXParameter; begin p := FindParamByName(Value); if p <> nil then Result := p else raise DBXException.Create('Parameter not found [ ' + Value + ' ]'); end; function TDSParams.Size: integer; begin Result := FParams.Count; end; function TDSParams.getParameter(Index: integer): TDBXParameter; begin Result := FParams.GetItems(Index); end; class procedure TDSParams.LoadParametersValues(params: TDSParams; Value: TJSONObject); begin try LoadParametersValues(params, Value, 0); except on e: Exception do raise DBXException.Create(e.Message); end; end; class function TDSParams.LoadParametersValues(params: TDSParams; Value: TJSONObject; Offset: integer): boolean; var parValue: TJSONArray; par: TDBXParameter; val: TDBXValue; i: integer; begin try if params.Size <= 0 then Exit(False); for i := 0 to params.Size - 1 do begin par := params.getParameter(i); try parValue := Value.GetJSONArray(par.Name); except raise DBXException.Create('Num ' + IntToStr(i) + ' par name = ' + par.Name); end; if parValue.Size < Offset + 1 then Exit(False); val := par.GetValue; TDBXJsonTools.jsonToDBX(parValue.Get(Offset), val, ''); end; Result := True; except on e: Exception do raise DBXException.Create(e.Message); end; end; class function TDSParams.CreateFrom(Value: TJSONObject): TDSParams; var params: TDSParams; begin params := CreateParametersFromMetadata(Value.GetJSONArray('table')); LoadParametersValues(params, Value); Result := params; end; class function TDSParams.CreateParametersFromMetadata(paramsMetadata : TJSONArray): TDSParams; var o: TDSParams; paramMetadata: TJSONArray; { todo } // parameter: TDBXValueType; parameter: TDBXParameter; i: integer; begin try o := TDSParams.Create; for i := 0 to paramsMetadata.Size - 1 do begin paramMetadata := paramsMetadata.GetJSONArray(i); parameter := TDBXParameter.Create; TDBXJsonTools.JSONToValueType(paramMetadata, TDBXValueType(parameter)); o.AddParameter(parameter); end; Result := o; except on e: Exception do raise DBXException.Create(e.Message); end; end; { TDBXParameterList } function TDBXParameterList.Add: TDBXParameter; begin Result := TDBXParameter.Create; Add(Result); end; procedure TDBXParameterList.Add(AObject: TDBXParameter); begin FObjectList.Add(AObject); end; procedure TDBXParameterList.Clear; begin FObjectList.Clear; end; function TDBXParameterList.Count: cardinal; begin Result := FObjectList.Count; end; constructor TDBXParameterList.Create(FreeObjects: boolean); begin inherited Create; FObjectList := TObjectList.Create(FreeObjects); end; constructor TDBXParameterList.Create; begin inherited; FObjectList := TObjectList.Create(True); end; procedure TDBXParameterList.Delete(Index: cardinal); begin FObjectList.Delete(Index); end; destructor TDBXParameterList.Destroy; begin FObjectList.Free; inherited; end; function TDBXParameterList.GetItems(Index: cardinal): TDBXParameter; begin Result := TDBXParameter(FObjectList[Index]); end; procedure TDBXParameterList.SetItems(Index: cardinal; const Value: TDBXParameter); begin FObjectList[Index] := Value; end; { TDBXUInt8Value } constructor TDBXUInt8Value.Create; begin inherited; SetDBXType(UInt8Type); FValueNull := False; end; function TDBXUInt8Value.getAsUInt8: UInt8; begin try Result := FDBXUInt8Value; except on e: Exception do raise DBXException.Create(e.Message); end; end; function TDBXUInt8Value.isNull: boolean; begin result:= FValueNull; end; procedure TDBXUInt8Value.SetAsUInt8(const Value: UInt8); begin try FDBXUInt8Value := Value; FValueNull := False; except on e: Exception do raise DBXException.Create(e.Message); end; end; procedure TDBXUInt8Value.setNull; begin inherited; SetAsUInt8(0); FValueNull:= true; end; { TDBXUInt16Value } constructor TDBXUInt16Value.Create; begin inherited; SetDBXType(UInt16Type); end; function TDBXUInt16Value.getAsUInt16: UInt16; begin result:= FDBXUInt16Value; end; function TDBXUInt16Value.isNull: boolean; begin result:= FValueNull; end; procedure TDBXUInt16Value.SetAsUInt16(const Value: UInt16); begin try FDBXUInt16Value := Value; FValueNull := False; except on e: Exception do raise DBXException.Create(e.Message); end; end; procedure TDBXUInt16Value.setNull; begin SetAsUInt16(0); FValueNull:= true; end; end.
unit Unit2; interface uses System.Colors, System.Types, SmartCL.System, SmartCL.Controls, SmartCL.Controls.Image, SmartCL.Layout; type TXControl = class(TW3Panel) private FLayout: TLayout; FImage: TW3Image; FTotalLabel: TW3Label; FQtyLabel: TW3Label; FFaceLabel: TW3Label; FDenomLabel: TW3Label; FImageUrl: String; FDenomination: String; FFaceValue: Float; FQty: Integer; FTotal: Float; protected procedure SetQty(const aValue: Integer); virtual; Function GetTotal: Float; virtual; procedure SetFaceValue(const aValue: Float); virtual; procedure SetDenomination(const aValue: String); virtual; procedure SetImageUrl(const aValue: String); virtual; procedure InitializeObject; override; procedure FinalizeObject; override; procedure Resize; override; public property ImageUrl: String read FImageUrl write SetImageUrl; property Denomination: String read FDenomination write SetDenomination; property FaceValue: Float read FFaceValue write SetFaceValue; property Qty: Integer read FQty write SetQty; property Total: Float read GetTotal; end; implementation Function TXControl.GetTotal: Float; begin result := FQty * FFaceValue; end; procedure TXControl.SetQty(const aValue: Integer); begin if aValue <> FQty then begin BeginUpdate; FQty := aValue; FTotal := FQty * FFaceValue; FQtyLabel.Caption := IntToStr(FQty); FTotalLabel.Caption := '$' + format('%0.2f', [FTotal]); EndUpdate; end; end; procedure TXControl.SetFaceValue(const aValue: Float); begin if aValue <> FFaceValue then begin BeginUpdate; FFaceValue := aValue; FFaceLabel.Caption := '$' + format('%0.2f', [FFaceValue]); EndUpdate; end; end; procedure TXControl.SetDenomination(const aValue: String); begin if aValue <> FImageUrl then begin BeginUpdate; FDenomination := aValue; FDenomLabel.Caption := FDenomination; EndUpdate; end; end; procedure TXControl.SetImageUrl(const aValue: String); begin if aValue <> FImageUrl then begin BeginUpdate; FImageUrl := aValue; FImage.LoadFromURL(FImageUrl); EndUpdate; end; end; procedure TXControl.InitializeObject; begin inherited; FImage := TW3Image.Create(Self); FImage.LoadFromURL(FImageUrl); FLayout := Layout.Left(Layout.Stretch, [FImage]); { FDenomLabel:= TW3Label.Create(Self); FDenomLabel.AlignText:= taLeft; FDenomLabel.Caption:= FDenomination; FDenomLabel.Width:= 100; FFaceLabel:= TW3Label.Create(Self); FFaceLabel.AlignText:= taCenter; FFaceLabel.Caption:= '$' + format('%0.2f', [FFaceValue]); FFaceLabel.Width:= 100; FQtyLabel:= TW3Label.Create(Self); FQtyLabel.AlignText:= taCenter; FQtyLabel.Caption:= IntToStr(FQty); FQtyLabel.Width:= 100; FTotalLabel:= TW3Label.Create(Self); FTotalLabel.AlignText:= taRight; FTotalLabel.Caption:= IntToStr(FQty); FTotalLabel.Width:= 100; } // FLayout:= Layout.Left(Layout.Stretch, [FImage, FDenomLabel, FFaceLabel, FQtyLabel, FTotalLabel]); end; procedure TXControl.FinalizeObject; begin FImage.Free; FImage := nil; // FDenomLabel.Free; // FDenomLabel:= nil; // FFaceLabel.Free; // FFaceLabel:= nil; // FQtyLabel.Free; // FQtyLabel:= nil; // FTotalLabel.Free; // FTotalLabel:= nil; inherited; end; procedure TXControl.Resize; begin inherited; FLayout.Resize(Self); end; end.
unit RepositorioManutencaoSistema; interface uses DB, Repositorio, Auditoria; type TRepositorioManutencaoSistema = class(TRepositorio) protected function Get (Dataset :TDataSet) :TObject; overload; override; function GetNomeDaTabela :String; override; function GetIdentificador(Objeto :TObject) :Variant; override; function GetRepositorio :TRepositorio; override; protected function SQLGet :String; override; function SQLSalvar :String; override; function SQLGetAll :String; override; function SQLRemover :String; override; function SQLGetExiste(campo: String): String; override; protected function IsInsercao(Objeto :TObject) :Boolean; override; protected procedure SetParametros (Objeto :TObject ); override; procedure SetIdentificador(Objeto :TObject; Identificador :Variant); override; //============================================================================== // Auditoria //============================================================================== protected procedure SetCamposIncluidos(Auditoria :TAuditoria; Objeto :TObject); override; procedure SetCamposAlterados(Auditoria :TAuditoria; AntigoObjeto, Objeto :TObject); override; procedure SetCamposExcluidos(Auditoria :TAuditoria; Objeto :TObject); override; end; implementation uses ManutencaoSistema, SysUtils; { TRepositorioManutencaoSistema } function TRepositorioManutencaoSistema.Get(Dataset: TDataSet): TObject; var Manutencao :TManutencaoSistema; begin Manutencao := TManutencaoSistema.Create; Manutencao.Codigo := self.FQuery.FieldByName('codigo').AsInteger; Manutencao.CodigoUsuarioResponsavel := self.FQuery.FieldByName('cod_usuario_responsavel').AsInteger; Manutencao.HorarioInicio := self.FQuery.FieldByName('horario_inicio').AsDateTime; Manutencao.HorarioTermino := self.FQuery.FieldByName('horario_termino').AsDateTime; Manutencao.TerminalResponsavel := self.FQuery.FieldByName('terminal_responsavel').AsString; result := Manutencao; end; function TRepositorioManutencaoSistema.GetIdentificador( Objeto: TObject): Variant; begin result := TManutencaoSistema(Objeto).Codigo; end; function TRepositorioManutencaoSistema.GetNomeDaTabela: String; begin result := 'MANUTENCAO_SISTEMA'; end; function TRepositorioManutencaoSistema.GetRepositorio: TRepositorio; begin result := TRepositorioManutencaoSistema.Create; end; function TRepositorioManutencaoSistema.IsInsercao( Objeto: TObject): Boolean; begin result := (TManutencaoSistema(Objeto).Codigo <= 0); end; procedure TRepositorioManutencaoSistema.SetCamposAlterados( Auditoria: TAuditoria; AntigoObjeto, Objeto: TObject); begin { Não há alteração pra esses dados. Apenas inclusão e remoção } end; procedure TRepositorioManutencaoSistema.SetCamposExcluidos( Auditoria: TAuditoria; Objeto: TObject); var Manutencao :TManutencaoSistema; begin Manutencao := (Objeto as TManutencaoSistema); Auditoria.AdicionaCampoExcluido('codigo', IntToStr(Manutencao.Codigo)); Auditoria.AdicionaCampoExcluido('cod_usuario_responsavel', IntToStr(Manutencao.CodigoUsuarioResponsavel)); Auditoria.AdicionaCampoExcluido('horario_inicio', FormatDateTime('hh:mm:ss', Manutencao.HorarioInicio)); Auditoria.AdicionaCampoExcluido('horario_termino', FormatDateTime('hh:mm:ss', Manutencao.HorarioTermino)); Auditoria.AdicionaCampoExcluido('terminal_responsavel', Manutencao.TerminalResponsavel); end; procedure TRepositorioManutencaoSistema.SetCamposIncluidos( Auditoria: TAuditoria; Objeto: TObject); var Manutencao :TManutencaoSistema; begin Manutencao := (Objeto as TManutencaoSistema); Auditoria.AdicionaCampoIncluido('codigo', IntToStr(Manutencao.Codigo)); Auditoria.AdicionaCampoIncluido('cod_usuario_responsavel', IntToStr(Manutencao.CodigoUsuarioResponsavel)); Auditoria.AdicionaCampoIncluido('horario_inicio', FormatDateTime('hh:mm:ss', Manutencao.HorarioInicio)); Auditoria.AdicionaCampoIncluido('horario_termino', FormatDateTime('hh:mm:ss', Manutencao.HorarioTermino)); Auditoria.AdicionaCampoIncluido('terminal_responsavel', Manutencao.TerminalResponsavel); end; procedure TRepositorioManutencaoSistema.SetIdentificador(Objeto: TObject; Identificador: Variant); begin TManutencaoSistema(Objeto).Codigo := Integer(Identificador); end; procedure TRepositorioManutencaoSistema.SetParametros(Objeto: TObject); var Manutencao :TManutencaoSistema; begin Manutencao := (Objeto as TManutencaoSistema); if (Manutencao.Codigo > 0) then inherited SetParametro('codigo', Manutencao.Codigo) else inherited LimpaParametro('codigo'); inherited SetParametro('COD_USUARIO_RESPONSAVEL', Manutencao.CodigoUsuarioResponsavel); inherited SetParametro('HORARIO_INICIO', Manutencao.HorarioInicio); inherited SetParametro('HORARIO_TERMINO', Manutencao.HorarioTermino); inherited SetParametro('terminal_responsavel', Manutencao.TerminalResponsavel); end; function TRepositorioManutencaoSistema.SQLGet: String; begin result := 'select first 1 * from manutencao_sistema where (codigo >= 0) and (:migue = 0)'; end; function TRepositorioManutencaoSistema.SQLGetAll: String; begin result := 'select * from manutencao_sistema '; end; function TRepositorioManutencaoSistema.SQLGetExiste(campo: String): String; begin result := 'select '+ campo +' from '+ self.GetNomeDaTabela+' where '+ campo +' = :ncampo'; end; function TRepositorioManutencaoSistema.SQLRemover: String; begin result := 'delete from manutencao_sistema where (codigo >= 0) and (:migue >= 0)'; end; function TRepositorioManutencaoSistema.SQLSalvar: String; begin result := ' update or insert into manutencao_sistema '+ ' ( codigo, cod_usuario_responsavel, horario_inicio, horario_termino, terminal_responsavel )'+ ' values '+ ' ( :codigo, :cod_usuario_responsavel, :horario_inicio, :horario_termino, :terminal_responsavel ) '; end; end.
unit uGenericDAO; interface uses RTTI, TypInfo, SysUtils, uAtribEntity, System.Generics.Collections, System.StrUtils, uTiposPrimitivos, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB, FireDAC.Phys.FBDef, FireDAC.VCLUI.Wait, Data.DB, FireDAC.Comp.Client, Vcl.StdCtrls, FireDAC.Phys.IBBase, FireDAC.Dapt, uBancoDados, Vcl.Grids; type TGenericDAO = class(TObject) private FClass: TObject; function GetNomeTabela: string; function Clausula(var adicionou_where: Boolean): string; function strIgualdade(str_valor: string; tipo_variavel: string): string; function GerarSelect: string; function AlimentarObjeto(qry: TFDQuery; var grid: TStringGrid): TObjectList<TObject>; protected property Classe: TObject read FClass write FClass; public constructor Create; virtual; abstract; function Select(var grid: TStringGrid): TObjectList<TObject>; function Insert: string; function Update: string; end; implementation uses System.Classes; const cIgualdade = ' = '; cIsNull = ' is null '; function TGenericDAO.GerarSelect: string; var contexto: TRttiContext; type_obj: TRttiType; prop: TRttiProperty; atributo: TCustomAttribute; script_select: TStringList; script_ligacoes: TStringList; str_valor: string; str_condicaoWhere: string; str_campos: string; adicionou_where: Boolean; apelido_tabelas: TDictionary<string, string>; apelido_tab_estrangeira: string; tabela_estrangeira: string; tabela_principal: string; apelido_tab_principal: string; str: string; tipo_valor: string; coluna: string; i: Integer; value_str: TString; value_int: TInteger; value_double: TDouble; value_date: TDate; filtrar_campo: Boolean; begin script_ligacoes := TStringList.Create; str_valor := EmptyStr; str_condicaoWhere := EmptyStr; str_campos := EmptyStr; adicionou_where := False; str := EmptyStr; tabela_principal := GetNomeTabela; apelido_tab_principal := Copy(tabela_principal, 1, 3); apelido_tabelas := TDictionary<string, string>.Create; apelido_tabelas.Add(tabela_principal, apelido_tab_principal); contexto := TRttiContext.Create; type_obj := contexto.GetType(FClass.ClassInfo); //Buscando as propertys do objeto for prop in type_obj.GetProperties do begin filtrar_campo := True; //Verificando se existe valor if not prop.GetValue(FClass).IsEmpty then begin str_valor := EmptyStr; try case prop.GetValue(FClass).Kind of //Tive que fazer isso porque o RTTI percorre também as propertys da classe pai tkClass: Continue; tkRecord: begin if prop.GetValue(Fclass).IsType(TypeInfo(TString)) then begin tipo_valor := 'TString'; value_str := prop.GetValue(FClass).AsType<TString>; if value_str.HasValue then str_valor := QuotedStr(value_str) else if value_str.Value_Null then str_valor := ' is null ' else filtrar_campo := False; end else if prop.GetValue(Fclass).IsType(TypeInfo(TInteger)) then begin tipo_valor := 'TInteger'; value_int := prop.GetValue(FClass).AsType<TInteger>; if value_int.HasValue then str_valor := IntToStr(value_int) else if value_int.Value_Null then str_valor := ' is null ' else filtrar_campo := False; end else if prop.GetValue(Fclass).IsType(TypeInfo(TDouble)) then begin tipo_valor := 'TDouble'; value_double := prop.GetValue(FClass).AsType<TDouble>; if value_double.HasValue then str_valor := FloatToStr(value_double) else if value_double.Value_Null then str_valor := ' is null ' else filtrar_campo := False; end else if prop.GetValue(Fclass).IsType(TypeInfo(TDate)) then begin tipo_valor := 'TDate'; value_date := prop.GetValue(FClass).AsType<TDate>; if value_date.HasValue then str_valor := DateTimeToStr(value_date) else if value_date.Value_Null then str_valor := ' is null ' else filtrar_campo := False; end end; end; except on e: Exception do raise Exception.Create('O valor informado (' + str_valor + ') na propriedade "' + prop.Name + '" no objeto ' + FClass.ClassName + ' não é compátivel com o tipo definido na classe (' + tipo_valor + ')!'); end; end; apelido_tab_estrangeira := EmptyStr; coluna := EmptyStr; for atributo in prop.GetAttributes do begin if atributo is DadosColuna then begin if coluna = EmptyStr then coluna := DadosColuna(atributo).Nome_Coluna; Continue; end else if atributo is ChaveEstrangeira then begin apelido_tab_estrangeira := ChaveEstrangeira(atributo).Apelido_Tabela_Estrangeira; if apelido_tab_estrangeira = EmptyStr then Continue; //Verificando se o campo em questão faz referência a uma coluna de outra tabela if ChaveEstrangeira(atributo).Coluna_Estrangeira <> EmptyStr then begin tabela_estrangeira := ChaveEstrangeira(atributo).Tabela_Estrangeira; //Verificando se já foi adicionado essa tabela estrangeira no inner if apelido_tabelas.ContainsKey(apelido_tab_estrangeira) then begin //Lembra que quando não existe a ligação com a tabela ainda, adicionamos uma linha em branco? Pois é, agora vamos adicionar o "AND" nela. i := script_ligacoes.IndexOf(apelido_tab_estrangeira) + 2; //Porém, pode ser um inner com 3 colunas ou mais. Por isso vamos procurar a próxima linha em branco antes de adicionar while script_ligacoes[i] <> EmptyStr do Inc(i); //Lembra que quando não existe a ligação com a tabela ainda, adicionamos uma linha em branco? Pois é, agora vamos adicionar o "AND" nela. script_ligacoes.Insert(i, 'and ' + apelido_tab_principal + '.' + ChaveEstrangeira(atributo).Coluna_Estrangeira + ' = ' + apelido_tab_estrangeira + '.' + ChaveEstrangeira(atributo).Coluna_Estrangeira); end else begin apelido_tabelas.Add(apelido_tab_estrangeira, str); //Montando a ligação, pois se entrou aqui, significa que ainda não existia o inner com essa tabela... script_ligacoes.Add(IfThen(ChaveEstrangeira(atributo).Tipo_Ligacao = Inner, 'inner ', 'left ') + ' join ' + tabela_estrangeira + ' ' + apelido_tab_estrangeira); script_ligacoes.Add('on ' + apelido_tab_principal + '.' + ChaveEstrangeira(atributo).Coluna_Estrangeira + ' = ' + apelido_tab_estrangeira + '.' + ChaveEstrangeira(atributo).Coluna_Estrangeira); //Adicionando essa linha vazia, pois a mesma irá servir para quando for necessário adicionar mais um filtro no inner dessa tabela... script_ligacoes.Add(EmptyStr); end; coluna := ChaveEstrangeira(atributo).Coluna_Estrangeira; end; end; end; //For atributo str_campos := str_campos + ' ' + IfThen(apelido_tab_estrangeira <> EmptyStr, apelido_tab_estrangeira, apelido_tab_principal) + '.' + coluna + ', ' + sLineBreak; //Essa variável é marcada com True se existir algum valor na propriedade percorrida. if filtrar_campo then str_condicaoWhere := str_condicaoWhere + Clausula(adicionou_where) + IfThen(apelido_tab_estrangeira = EmptyStr, apelido_tab_principal, apelido_tab_estrangeira) + '.' + coluna + strIgualdade(str_valor, tipo_valor) + str_valor + sLineBreak; end; str_campos := Trim(str_campos); str_campos := Copy(str_campos, 0, Length(str_campos) - 1); str_condicaoWhere := Trim(str_condicaoWhere); script_select := TStringList.Create; script_select.Add('select'); script_select.Add(' ' + str_campos); script_select.Add('from '); script_select.Add(' ' + tabela_principal + ' ' + apelido_tab_principal); script_select.Add(EmptyStr); if script_ligacoes.GetText <> EmptyStr then script_select.Add(script_ligacoes.GetText); script_select.Add(str_condicaoWhere); Result := script_select.GetText; script_select.Free; end; function TGenericDAO.GetNomeTabela: string; var Contexto: TRttiContext; TypObj: TRttiType; Atributo: TCustomAttribute; begin Contexto := TRttiContext.Create; TypObj := Contexto.GetType(FClass.ClassInfo); for Atributo in TypObj.GetAttributes do begin if Atributo is NomeTabela then Exit(NomeTabela(Atributo).Nome_Tabela); end; end; function TGenericDAO.Insert: string; var Contexto: TRttiContext; TypObj: TRttiType; Prop: TRttiProperty; comando_insert, campos, valores: String; tipo_valor: string; Atributo: TCustomAttribute; valor: string; value_str: TString; value_int: TInteger; value_double: TDouble; value_date: TDate; begin comando_insert := EmptyStr; campos := EmptyStr; valores := EmptyStr; comando_insert := 'insert into ' + GetNomeTabela; Contexto := TRttiContext.Create; TypObj := Contexto.GetType(FClass.ClassInfo); for Prop in TypObj.GetProperties do begin try case Prop.GetValue(FClass).Kind of tkClass: Break; tkRecord: begin if Prop.GetValue(Fclass).IsType(TypeInfo(TString)) then begin tipo_valor := 'TString'; value_str := Prop.GetValue(FClass).AsType<TString>; if value_str.HasValue then valor := QuotedStr(value_str) + ', ' else valor := 'null, '; end else if Prop.GetValue(Fclass).IsType(TypeInfo(TInteger)) then begin tipo_valor := 'TInteger'; value_int := Prop.GetValue(FClass).AsType<TInteger>; if value_int.HasValue then valor := IntToStr(value_int) + ', ' else valor := 'null, '; end else if Prop.GetValue(Fclass).IsType(TypeInfo(TDouble)) then begin tipo_valor := 'TDouble'; value_double := Prop.GetValue(FClass).AsType<TDouble>; if value_double.HasValue then valor := FloatToStr(value_double) + ', ' else valor := 'null, '; end else if Prop.GetValue(Fclass).IsType(TypeInfo(TDate)) then begin tipo_valor := 'TDate'; value_date := Prop.GetValue(FClass).AsType<TDate>; if value_date.HasValue then valor := DateTimeToStr(value_date) + ', ' else valor := 'null, '; end end; end; except on e: Exception do raise Exception.Create('O valor informado (' + valor + ') na propriedade "' + Prop.Name + '" no objeto ' + FClass.ClassName + ' não é compátivel com o tipo definido na classe (' + tipo_valor + ')!'); end; for Atributo in Prop.GetAttributes do begin if Atributo is DadosColuna then begin if DadosColuna(Atributo).Somente_Leitura then Break; campos := campos + DadosColuna(Atributo).Nome_Coluna + ', '; valores := valores + valor; Break; end; if Atributo is ChaveEstrangeira then Continue; end; end; campos := Copy(campos, 1, Length(campos) - 2); valores := Copy(valores, 1, Length(valores) - 2); comando_insert := comando_insert + ' ( ' + sLineBreak + campos + sLineBreak + ' ) values ( ' + sLineBreak + valores + sLineBreak + ' )'; try //Executar SQL Result := comando_insert; except on e: Exception do begin raise E.Create('Erro: ' + e.Message); end; end; end; function TGenericDAO.AlimentarObjeto(qry: TFDQuery; var grid: TStringGrid): TObjectList<TObject>; var contexto: TRttiContext; type_obj: TRttiType; type_class: TRttiType; prop: TRttiProperty; prop_class: TRttiProperty; atributo: TCustomAttribute; i: Integer; j: Integer; linha: Integer; continuar_loop: Boolean; begin if qry.IsEmpty then Exit(nil); linha := 0; if Assigned(grid)then linha := grid.FixedRows; contexto := TRttiContext.Create; type_obj := contexto.GetType(FClass.ClassInfo); Result := TObjectList<TObject>.Create; qry.First; while not qry.EoF do begin FClass := FClass.NewInstance; for i := 0 to qry.FieldCount - 1 do begin //Loop de coluna por coluna para localizar o campo no objeto for prop in type_obj.GetProperties do begin continuar_loop := True; for atributo in prop.GetAttributes do begin if atributo is DadosColuna then begin if DadosColuna(atributo).Nome_Coluna = qry.Fields[i].FieldName then begin if prop.GetValue(Fclass).IsType(TypeInfo(TString)) then prop.SetValue(FClass, TValue.From(TString(qry.Fields[i].AsString))) else if prop.GetValue(Fclass).IsType(TypeInfo(TInteger)) then prop.SetValue(FClass, TValue.From(TInteger(qry.Fields[i].AsInteger))) else if prop.GetValue(Fclass).IsType(TypeInfo(TDouble)) then prop.SetValue(FClass, TValue.From(TDouble(qry.Fields[i].AsFloat))) else if prop.GetValue(Fclass).IsType(TypeInfo(TDate)) then prop.SetValue(FClass, TValue.From(qry.Fields[i].AsDateTime)); if Assigned(grid) then begin j := 0; while grid.Objects[j, 0] <> nil do begin type_class := TRttiContext.Create.GetType(grid.Objects[j, 0].ClassInfo); prop_class := type_class.GetProperty('Nome'); if not Assigned(prop_class) then Break; if prop_class.GetValue(grid.Objects[j, 0]).AsString = qry.Fields[i].FieldName then grid.Cells[j, linha] := qry.Fields[i].AsString; Inc(j); end; end; continuar_loop := False; Break; end; end; end; if not continuar_loop then Break; end; end; Result.Add(FClass); Inc(linha); qry.Next; end; if Assigned(grid) then grid.RowCount := Result.Count + grid.FixedRows; end; function TGenericDAO.Clausula(var adicionou_where: Boolean): string; begin if adicionou_where then Result := ' and ' else begin adicionou_where := True; Result := ' where '; end; end; function TGenericDAO.strIgualdade(str_valor: string; tipo_variavel: string): string; begin Result := IfThen(str_valor <> ' is null ', IfThen(tipo_variavel = 'TString', ' like ', ' = ')); end; function TGenericDAO.Select(var grid: TStringGrid): TObjectList<TObject>; var qry: TFDQuery; begin try //Executando o SQL qry := TFDQuery.Create(nil); qry.Connection := TBD.Conexao; qry.Open(GerarSelect); Result := AlimentarObjeto(qry, grid); except on e: Exception do begin raise E.Create('Erro: ' + e.Message); end; end; end; function TGenericDAO.Update: string; var Contexto: TRttiContext; TypObj: TRttiType; Prop: TRttiProperty; comando_update: String; tipo_valor: string; Atributo: TCustomAttribute; colunas: string; comando_where: string; adicionou_where: Boolean; valor: string; value_str: TString; value_int: TInteger; value_double: TDouble; value_date: TDate; function Clausula: string; begin if adicionou_where then Result := 'and ' else begin adicionou_where := True; Result := 'where '; end; end; begin comando_update := EmptyStr; comando_where := EmptyStr; tipo_valor := EmptyStr; colunas := EmptyStr; valor := EmptyStr; adicionou_where := False; Contexto := TRttiContext.Create; TypObj := Contexto.GetType(FClass.ClassInfo); for Prop in TypObj.GetProperties do begin try case Prop.GetValue(FClass).Kind of tkClass: Break; tkRecord: begin if Prop.GetValue(Fclass).IsType(TypeInfo(TString)) then begin tipo_valor := 'TString'; value_str := Prop.GetValue(FClass).AsType<TString>; if value_str.HasValue then valor := QuotedStr(value_str) + ', ' else if value_str.Value_Null then valor := 'null, ' else valor := EmptyStr; end else if Prop.GetValue(Fclass).IsType(TypeInfo(TInteger)) then begin tipo_valor := 'TInteger'; value_int := Prop.GetValue(FClass).AsType<TInteger>; if value_int.HasValue then valor := IntToStr(value_int) + ', ' else if value_int.Value_Null then valor := 'null, ' else valor := EmptyStr; end else if Prop.GetValue(Fclass).IsType(TypeInfo(TDouble)) then begin tipo_valor := 'TDouble'; value_double := Prop.GetValue(FClass).AsType<TDouble>; if value_double.HasValue then valor := FloatToStr(value_double) + ', ' else if value_double.Value_Null then valor := 'null, ' else valor := EmptyStr; end else if Prop.GetValue(Fclass).IsType(TypeInfo(TDate)) then begin tipo_valor := 'TDate'; value_date := Prop.GetValue(FClass).AsType<TDate>; if value_date.HasValue then valor := DateToStr(value_date) + ', ' else if value_date.Value_Null then valor := 'null, ' else valor := EmptyStr; end end; end; except on e: Exception do raise Exception.Create('O valor informado (' + valor + ') na propriedade "' + Prop.Name + '" no objeto ' + FClass.ClassName + ' não é compátivel com o tipo definido na classe (' + tipo_valor + ')!'); end; if valor = EmptyStr then Continue; for Atributo in Prop.GetAttributes do begin if Atributo is DadosColuna then begin if DadosColuna(Atributo).Somente_Leitura then Break; if DadosColuna(Atributo).Chave_Primaria then begin valor := Copy(valor, 1, Length(valor) - 2); comando_where := comando_where + Clausula + DadosColuna(Atributo).Nome_Coluna + ' = ' + valor + sLineBreak; end else colunas := colunas + ' ' + DadosColuna(Atributo).Nome_Coluna + ' = ' + valor + sLineBreak; end; Break; end; end; colunas := Trim(colunas); colunas := Copy(colunas, 1, Length(colunas) - 1); if comando_where = EmptyStr then begin raise Exception.Create('Não pode ser montado um update sem informar a clausula WHERE'); end; comando_update := 'update ' + GetNomeTabela + ' set ' + sLineBreak + ' ' + colunas + sLineBreak + comando_where; try //Executar SQL Result := comando_update; except on e: Exception do begin raise E.Create('Erro: ' + e.Message); end; end; end; end.
%include 'umb$disk2:[math.cs210]gbfpbf.pas' (*************************************************************************) FUNCTION IsReal(C: character): boolean; {Returns true if the number is a int or contains a period} BEGIN {IsReal} IsReal := IsDigit(C) OR (C = PERIOD); END; {IsReal} (*************************************************************************) FUNCTION IsOperator(C: character): boolean; {Checks to see if character is an operator} BEGIN {IsOperator} IsOperator := C in [ENDFILE,STAR..SLASH, CARET,RPAREN,LPAREN,PLUS,RBRACE,LBRACE] END; {IsOperator} (***********************************************************************) FUNCTION IsVar(C:character): boolean; {Checks to see if token is a legal pascal variable} BEGIN {IsVar} IsVar := IsAlphanum(C) OR C = UNDERLINE; END; {IsVar} (***********************************************************************) FUNCTION IsComment(C: Character): boolean; {Checks for LBRACE OR LPAREN+STAR} VAR C1: Character; BEGIN {IsComment} IsComment := (C = LBRACE) OR (C = LPAREN AND Getpbcf(C1,STDIN) = STAR); PutBackf(C1,STDIN); END; {IsComment (***********************************************************************) FUNCTION EndComment(C: Character): Boolean; {Checks for RBRACE or STAR+RPAREN} VAR C1: Character; BEGIN {EndComment} EndComment := (C = RBRACE) OR (C = STAR AND Getpbcf(C1,STDIN) = RPAREN); PutBackf(C1,STDIN); END; {EndComment (*************************************************************************) FUNCTION GetTok(var Token: string): character; {This function returns as it's value the first character of the Token string and return the complete string as Token} VAR Counter: integer; C: character; TokenCollected: boolean; BEGIN {GetTok} Counter := 1; TokenCollected := False; Token[Counter] := Getpbcf(C,STDIN); REPEAT IF NOT IsReal(Token[Counter]) THEN IF NOT IsOperator(Token[Counter]) AND NOT IsVar(Token[Counter]) THEN Token[Counter] := Getpbcf(C,STDIN) ELSE IF IsVar(Token[Counter]) THEN BEGIN WHILE IsVar(Getpbcf(C,STDIN)) DO BEGIN Counter := Counter + 1; Token[Counter] := C; END; TokenCollected := True; PutBackf(C,STDIN); END ELSE IF IsComment(Token[Counter]) THEN BEGIN WHILE NOT EndComment(Getpbcf(C,STDIN) DO BEGIN Counter := Counter + 1; Token[Counter] := C; END; TokenCollected := True; END ELSE TokenCollected := True ELSE BEGIN {SECOND IF-THEN-ELSE} WHILE IsReal(Getpbcf(C,STDIN)) DO BEGIN {WHILE} Counter := Counter + 1; Token[Counter] := C; END; {WHILE} TokenCollected := True; Putbackf(C,STDIN); END; {else} UNTIL TokenCollected; Token[Counter + 1] := ENDSTR; GetTok := Token[1]; END; {GetTok} 
unit NLDStringGridEdit; interface uses DesignEditors, NLDStringGrid, ColnEdit; type TNLDStringGridEditor = class(TComponentEditor) private function StringGrid: TNLDStringGrid; public procedure ExecuteVerb(Index: Integer); override; function GetVerb(Index: Integer): String; override; function GetVerbCount: Integer; override; end; implementation { TNLDStringGridEditor } const SEditorVerb0 = 'Columns Editor...'; SColumnsPropName = 'Columns'; procedure TNLDStringGridEditor.ExecuteVerb(Index: Integer); begin case Index of 0: ShowCollectionEditor(Designer, Component, StringGrid.Columns, SColumnsPropName); end; end; function TNLDStringGridEditor.GetVerb(Index: Integer): String; begin case Index of 0: Result := SEditorVerb0; else Result := ''; end; end; function TNLDStringGridEditor.GetVerbCount: Integer; begin Result := 1; end; function TNLDStringGridEditor.StringGrid: TNLDStringGrid; begin Result := TNLDStringGrid(Component); end; end.
unit uEscolheData; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, JvExControls, JvXPCore, JvXPButtons, StdCtrls, Mask, JvExMask, JvToolEdit; type TfrmEscolheData = class(TForm) lbTexto: TLabel; btconfirmar: TJvXPButton; btCancelar: TJvXPButton; edData: TJvDateEdit; procedure btconfirmarClick(Sender: TObject); private { Private declarations } public class function EntraData(var Data : TDateTime; Texto : String = '') : Boolean; { Public declarations } end; var frmEscolheData: TfrmEscolheData; implementation {$R *.dfm} { TForm1 } procedure TfrmEscolheData.btconfirmarClick(Sender: TObject); begin if edData.Date = 0 then begin MessageBox(handle, 'Informe uma data', 'Atenção!', MB_ICONERROR); edData.SetFocus; end else ModalResult := mrOk; end; class function TfrmEscolheData.EntraData(var Data: TDateTime; Texto: String): Boolean; var frmEscolheData: TfrmEscolheData; begin frmEscolheData := TfrmEscolheData.Create(Application); try if Texto <> '' then frmEscolheData.lbTexto.Caption := Texto; frmEscolheData.edData.Date := Data; frmEscolheData.Caption := Application.Title; Result := frmEscolheData.ShowModal = mrOk; if Result then Data := frmEscolheData.edData.Date; finally FreeAndNil(frmEscolheData); end; end; end.
unit UBuildQuery; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IBConnection, sqldb, DB, FileUtil, Forms, Controls, Graphics, Dialogs, DBCtrls, DBGrids, StdCtrls, Menus, ExtCtrls, Grids, types, UMetadata, UDBConnection,URecords; type { TQueryBuilder } TQueryBuilder = class function FindRealValues(FieldId: integer; Table: TTableInformation): TStringDynArray; function Build(Tableinf: TTableInformation; FOutPutFileds: array of TOutputField; Conditions: array of TCondition; OrderBy: array of string;AdditionalConditions:string): string; procedure FillOutputs(Table: TTableInformation); function DeleteQuery(FieldId: string; Table: TTableInformation): string; function InsertQuery(Table: TTableInformation; Values: array of string): string; function UpdateQuery(Table: TTableInformation; Values: array of string; UpdateID: string): string; function TakeValue(Table: TTableInformation): string; function ReferenceTable(FField: TFieldInformation): TTableInformation; function GetRecordIdFromTimeTable(TableName: string): integer; procedure DeleteField(FId: string; Table: TTableInformation); function SelectAll(Table: TTableInformation): string; public OutPutFileds: array of TOutputField; InnerJoins: array of string; OutPuts: array of string; FieldNames: array of string; IdValues: array of string; end; var QueryBuilder: TQueryBuilder; implementation uses UNotification; procedure TQueryBuilder.FillOutputs(Table: TTableInformation); var i, j: integer; RefTable: TTableInformation; procedure Fill(Table: TTableInformation; Field: TFieldInformation); begin SetLength(OutPutFileds, Length(OutPutFileds) + 1); with OutPutFileds[High(OutPutFileds)] do begin Show := True; TableName := Table.Name; FieldName := Field.Name; FieldCaption := Field.Caption; ColWidth := Field.ColumWidth; end; end; begin SetLength(OutPutFileds, 0); SetLength(InnerJoins, 0); for i := 0 to High(Table.Information) do begin if Table.Information[i].Reference.TableName = '' then begin Fill(Table, Table.Information[i]); end else begin RefTable := ReferenceTable(Table.Information[i]); for j := 0 to High(RefTable.Information) do begin if RefTable.Information[j].Name = 'id' then Continue; Fill(RefTable, RefTable.Information[j]); end; SetLength(InnerJoins, Length(InnerJoins) + 1); InnerJoins[High(InnerJoins)] := ' inner join ' + Table.Information[i].Reference.TableName + ' on ' + Table.Name + '.' + Table.Information[i].Name + ' = ' + Table.Information[i].Reference.TableName + '.' + Table.Information[i].Reference.FieldName; end; end; end; function TQueryBuilder.Build(Tableinf: TTableInformation; FOutPutFileds: array of TOutputField; Conditions: array of TCondition; OrderBy: array of string;AdditionalConditions:string): string; var QueryText: string; i, k: integer; RefTable: TTableInformation; begin SetLength(OutPuts, 0); SetLength(FieldNames, 0); QueryText := 'select '; for i := 0 to High(FOutPutFileds) do begin if FOutPutFileds[i].Show then QueryText += FOutPutFileds[i].TableName + '.' + FOutPutFileds[i].FieldName + ','; end; Delete(QueryText, Length(QueryText), 1); QueryText += ' from ' + TableInf.Name; for i := 0 to High(InnerJoins) do QueryText += InnerJoins[i]; if (Length(Conditions) > 0) or (AdditionalConditions <> '') then QueryText += ' where '; if (Length(Conditions) > 0) then begin for i := 0 to High(Conditions) do begin QueryText += Conditions[i].FieldName + Conditions[i].ConditionSign + ' :param' + IntToStr(i) + ' and '; end; Delete(QueryText, Length(QueryText) - 4, 4); if AdditionalConditions <> '' then QueryText += ' or ' end; QueryText+=AdditionalConditions; Result := QueryText; if Length(OrderBy) > 0 then begin Result +=' order by '; for i:=0 to High(OrderBy) do Result += OrderBy[i] + ','; Delete(Result,Length(Result),1); end; end; function TQueryBuilder.ReferenceTable(FField: TFieldInformation): TTableInformation; var i: integer; begin for i := 0 to High(Metadata.Tables) do if (Metadata.Tables[i].Name = FField.Reference.TableName) then exit(Metadata.Tables[i]); end; function TQueryBuilder.SelectAll(Table: TTableInformation): string; var i:integer; begin Result:='select '; for i:=0 to High(Table.Information) do Result+= Table.Name + '.' + Table.Information[i].Name+','; Delete(Result,Length(Result),1); Result+=' from ' + Table.Name; end; function TQueryBuilder.DeleteQuery(FieldId: string; Table: TTableInformation): string; var Qtext: string; begin Qtext := 'delete from ' + Table.Name + ' where ' + Table.Name + '.' + 'id = ' + FieldId; Result := Qtext; end; function TQueryBuilder.TakeValue(Table: TTableInformation): string; var QueryText: string; i: integer; begin QueryText := 'select '; for i := 0 to High(Table.Information) do begin if Table.Information[i].Name = 'id' then Continue; QueryText += Table.Name + '.' + Table.Information[i].Name + ', '; end; Delete(QueryText, Length(QueryText) - 1, 1); QueryText += ' FROM ' + Table.Name; Result := QueryText; end; function TQueryBuilder.InsertQuery(Table: TTableInformation; Values: array of string): string; var QueryText: string; i: integer; begin QueryText := 'insert into ' + Table.Name + ' values (0, '; for i := 0 to High(Values) do begin QueryText += ':param' + IntToStr(i) + ', '; end; Delete(QueryText, Length(QueryText) - 1, 1); QueryText += ')'; Result := QueryText; end; function TQueryBuilder.UpdateQuery(Table: TTableInformation; Values: array of string; UpdateID: string): string; var QueryText: string; i: integer; begin QueryText := 'update ' + Table.Name + ' set '; for i := 0 to High(Values) do begin QueryText += Table.Name + '.' + Table.Information[i + 1].Name + ' = ' + ':param' + IntToStr(i) + ', '; end; Delete(QueryText, Length(QueryText) - 1, 1); QueryText += ' where ' + Table.Name + '.id = ' + UpdateID; Result := QueryText; end; function TQueryBuilder.FindRealValues(FieldId: integer; Table: TTableInformation): TStringDynArray; var q: TSQLQuery; i: integer; begin SetLength(Result, 0); q := TSQlquery.Create(nil); q.DataBase := DataBase.IBConnection; q.SQL.Text := QueryBuilder.TakeValue(Table) + ' where ' + Table.Name + '.id = ' + IntToStr(FieldId); q.Open; for i := 1 to High(Table.Information) do begin SetLength(Result, Length(Result) + 1); Result[High(Result)] := q.FieldByName(Table.Information[i].Name).AsString; end; end; function TQueryBuilder.GetRecordIdFromTimeTable(TableName: string): integer; var i: integer; begin for i := 0 to High(Metadata.Tables[High(Metadata.Tables)].Information) do begin if Metadata.Tables[High(Metadata.Tables)].Information[i].Reference.TableName = TableName then exit(i); end; Result := -1; end; procedure TQueryBuilder.DeleteField(FId: string; Table: TTableInformation); var SQLQuery: TSQLQuery; begin case QuestionDlg('Предупреждение', 'Вы уверены что хотите удалить запись? Вся информация о ней ' + 'будет стёрта и с других таблиц', mtConfirmation, [mrYes, 'Да', mrNo, 'Нет'], '') of mrYes: begin SQLQuery := TSQLQuery.Create(nil); SQLQuery.DataBase := DataBase.IBConnection; SQLQuery.SQL.Text := DeleteQuery(FId, Table); SQLQuery.ExecSQL; DataBase.SQLTransaction.Commit; FNotification.SendMessage(); SQLQuery.Free; end; mrNo: Exit; end; end; initialization QueryBuilder := TQueryBuilder.Create; end.
unit UnitMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ImgList, ExtCtrls, StdCtrls, ShellCtrls, Contnrs, jpeg, GDIPAPI, GDIPOBJ, GDIPUTIL, Buttons, LXImage, ActnList, ToolWin, ShellAPI, Menus; const WM_UPDATE_SELECTION = WM_USER + 200; WM_UPDATE_IMAGE = WM_USER + 201; INFO_QUERY_CAPTION = '提示'; INFO_ERROR_CAPTION = '错误'; INI_FILE = '.\feipaibuke.ini'; ERROR_FILE = '.\error.bmp'; type TDisplayMode = (dmMatch, dmActual, dmCustom); TFormMain = class(TForm) pnlLeft: TPanel; statBar: TStatusBar; spl1: TSplitter; pnlMain: TPanel; pnlImage: TPanel; spl2: TSplitter; pnlContain: TPanel; tvMain: TShellTreeView; spl3: TSplitter; pnlLeftBottom: TPanel; pnlToolbar: TPanel; lvImages: TListView; ilImages: TImageList; lstSelection: TListBox; pnlContentBtm: TPanel; actlstMain: TActionList; actSelectAll: TAction; actSelectNone: TAction; actShowMatch: TAction; actShowActual: TAction; actCopySelection: TAction; actRemoveSelection: TAction; bvl1: TBevel; ilActions: TImageList; actPrevImage: TAction; actNextImage: TAction; tlbSelection: TToolBar; btnSelectAll: TToolButton; btnSelectNone: TToolButton; btnRemoveSelection: TToolButton; btnCopySelection: TToolButton; btn1: TToolButton; tlbImage: TToolBar; btnPrevImage: TToolButton; btnNextImage: TToolButton; btnShowActual: TToolButton; btnShowMatch: TToolButton; btn2: TToolButton; actSlide: TAction; btn3: TToolButton; btnSlide: TToolButton; actSetting: TAction; btnSetting: TToolButton; btn5: TToolButton; pnlDisplay: TPanel; actDeleteFile: TAction; btnDeleteFile: TToolButton; btn4: TToolButton; actContextMenu: TAction; actShowInfo: TAction; pmImage: TPopupMenu; N1: TMenuItem; N2: TMenuItem; actRotateClockWise: TAction; actRotateAntiClockWise: TAction; btnRotateClockWise: TToolButton; btnRotateAntiClockWise: TToolButton; btn6: TToolButton; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; N6: TMenuItem; procedure tvMainChange(Sender: TObject; Node: TTreeNode); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lvImagesData(Sender: TObject; Item: TListItem); procedure lvImagesCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); procedure lvImagesChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure lvImagesDblClick(Sender: TObject); procedure lvImagesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure actShowMatchExecute(Sender: TObject); procedure actShowActualExecute(Sender: TObject); procedure lvImagesKeyPress(Sender: TObject; var Key: Char); procedure actSelectAllExecute(Sender: TObject); procedure actSelectNoneExecute(Sender: TObject); procedure actCopySelectionExecute(Sender: TObject); procedure tvMainChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure actRemoveSelectionExecute(Sender: TObject); procedure lstSelectionKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure pnlContentBtmResize(Sender: TObject); procedure actPrevImageExecute(Sender: TObject); procedure actNextImageExecute(Sender: TObject); procedure actSlideExecute(Sender: TObject); procedure pnlToolbarResize(Sender: TObject); procedure lstSelectionDblClick(Sender: TObject); procedure actlstMainUpdate(Action: TBasicAction; var Handled: Boolean); procedure actSettingExecute(Sender: TObject); procedure pnlDisplayResize(Sender: TObject); procedure actDeleteFileExecute(Sender: TObject); procedure actContextMenuExecute(Sender: TObject); procedure actShowInfoExecute(Sender: TObject); procedure actRotateClockWiseExecute(Sender: TObject); procedure actRotateAntiClockWiseExecute(Sender: TObject); private { Private declarations } FCheckedBitmap: TBitmap; FUncheckedBitMap: TBitmap; FCheckedIcon: TIcon; FUncheckedIcon: TIcon; FFiles: TObjectList; FCurrentFileName: string; FCurrentIndex: Integer; FCurrentGPImage: TGPImage; FCurImgWidth, FCurImgHeight: Integer; FDisplayMode: TDisplayMode; FImgContent: TLXImage; FZoomFactor: Extended; FSrcRect: TRect; // 以源内容为参考系的绘制源区域 FDestRect: TRect; // 以FImgContent区域为参考系的绘制目标区域 FImageMouseDownPos: TPoint; FImageMouseDown: Boolean; FCurSelectionChanged: Boolean; FExifTool: string; FGmTool: string; procedure OnFindFile(const FileName: string; const Info: TSearchRec; var Abort: Boolean); procedure UpdateSelectionText(var Msg: TMessage); message WM_UPDATE_SELECTION; procedure UpdateImage(var Msg: TMessage); message WM_UPDATE_IMAGE; procedure UpdateSelectionSummary; procedure UpdateShowingImageInfo; procedure ShowMatchedImage(const FileName: string; ForceReload: Boolean = True); procedure ShowActualImage(const FileName: string; ForceReload: Boolean = True); procedure ClearImage(); procedure ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ImageDblClick(Sender: TObject); function QueryDlg(const Msg: string; const Cap: string = INFO_QUERY_CAPTION ): Boolean; procedure InfoDlg(const Msg: string; const Cap: string = INFO_QUERY_CAPTION); procedure ErrDlg(const Msg: string; const Cap: string = INFO_ERROR_CAPTION); function YesNoDlg(const Msg: string; const Cap: string = INFO_QUERY_CAPTION): Boolean; procedure RefreshCurrentThumbnail(); public { Public declarations } end; TFileItem = class(TObject) private FCaption: string; FFileName: string; FChecked: Boolean; FBitmap: TBitmap; FThumbValid: Boolean; FImageIndex: Integer; public constructor Create; destructor Destroy; override; property FileName: string read FFileName write FFileName; property Caption: string read FCaption write FCaption; property Checked: Boolean read FChecked write FChecked; property Bitmap: TBitmap read FBitmap; property ImageIndex: Integer read FImageIndex write FImageIndex; property ThumbValid: Boolean read FThumbValid write FThumbValid; end; var FormMain: TFormMain; implementation uses UnitSlide, UnitOptions, UnitDisplay, UnitSetting, CnShellUtils, UnitInfo; {$R *.dfm} const THUMB_MAX = 120; ICON_SIZE = 16; ListViewIconW: Word = 120; {Width of thumbnail in ICON view mode} ListViewIconH: Word = 120; {Height of thumbnail size} CheckWidth: Word = 16; {Width of check mark box} CheckHeight: Word = 16; {Height of checkmark} CheckBiasTop: Word = 20; {This aligns the checkbox to be in centered} CheckBiasLeft: Word = 20; {In the row of the list item display} SCnMsgDlgOK = '确定'; SCnMsgDlgCancel = '取消'; type TFindCallBack = procedure(const FileName: string; const Info: TSearchRec; var Abort: Boolean) of object; {* 查找指定目录下文件的回调函数} TDirCallBack = procedure(const SubDir: string) of object; {* 查找指定目录时进入子目录回调函数} var FindAbort: Boolean; // 运行一个文件并等待其结束 function WinExecAndWait32(FileName: string; Visibility: Integer; ProcessMsg: Boolean): Integer; var zAppName: array[0..512] of Char; zCurDir: array[0..255] of Char; WorkDir: string; StartupInfo: TStartupInfo; ProcessInfo: TProcessInformation; begin StrPCopy(zAppName, FileName); GetDir(0, WorkDir); StrPCopy(zCurDir, WorkDir); FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.dwFlags := STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := Visibility; if not CreateProcess(nil, zAppName, { pointer to command line string } nil, { pointer to process security attributes } nil, { pointer to thread security attributes } False, { handle inheritance flag } CREATE_NEW_CONSOLE or { creation flags } NORMAL_PRIORITY_CLASS, nil, { pointer to new environment block } nil, { pointer to current directory name } StartupInfo, { pointer to STARTUPINFO } ProcessInfo) then Result := -1 { pointer to PROCESS_INF } else begin if ProcessMsg then begin repeat Application.ProcessMessages; GetExitCodeProcess(ProcessInfo.hProcess, Cardinal(Result)); until (Result <> STILL_ACTIVE) or Application.Terminated; end else begin WaitforSingleObject(ProcessInfo.hProcess, INFINITE); GetExitCodeProcess(ProcessInfo.hProcess, Cardinal(Result)); end; end; end; // 用管道方式在 Dir 目录执行 CmdLine,Output 返回输出信息, // dwExitCode 返回退出码。如果成功返回 True function InternalWinExecWithPipe(const CmdLine, Dir: string; slOutput: TStrings; var dwExitCode: Cardinal): Boolean; var HOutRead, HOutWrite: THandle; StartInfo: TStartupInfo; ProceInfo: TProcessInformation; sa: TSecurityAttributes; InStream: THandleStream; strTemp: string; PDir: PChar; procedure ReadLinesFromPipe(IsEnd: Boolean); var s: string; ls: TStringList; i: Integer; begin if InStream.Position < InStream.Size then begin SetLength(s, InStream.Size - InStream.Position); InStream.Read(PChar(s)^, InStream.Size - InStream.Position); strTemp := strTemp + s; ls := TStringList.Create; try ls.Text := strTemp; for i := 0 to ls.Count - 2 do slOutput.Add(ls[i]); strTemp := ls[ls.Count - 1]; finally ls.Free; end; end; if IsEnd and (strTemp <> '') then begin slOutput.Add(strTemp); strTemp := ''; end; end; begin dwExitCode := 0; Result := False; try FillChar(sa, sizeof(sa), 0); sa.nLength := sizeof(sa); sa.bInheritHandle := True; sa.lpSecurityDescriptor := nil; InStream := nil; strTemp := ''; HOutRead := INVALID_HANDLE_VALUE; HOutWrite := INVALID_HANDLE_VALUE; try Win32Check(CreatePipe(HOutRead, HOutWrite, @sa, 0)); FillChar(StartInfo, SizeOf(StartInfo), 0); StartInfo.cb := SizeOf(StartInfo); StartInfo.wShowWindow := SW_HIDE; StartInfo.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW; StartInfo.hStdError := HOutWrite; StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); StartInfo.hStdOutput := HOutWrite; InStream := THandleStream.Create(HOutRead); if Dir <> '' then PDir := PChar(Dir) else PDir := nil; Win32Check(CreateProcess(nil, //lpApplicationName: PChar PChar(CmdLine), //lpCommandLine: PChar nil, //lpProcessAttributes: PSecurityAttributes nil, //lpThreadAttributes: PSecurityAttributes True, //bInheritHandles: BOOL NORMAL_PRIORITY_CLASS, //CREATE_NEW_CONSOLE, nil, PDir, StartInfo, ProceInfo)); while WaitForSingleObject(ProceInfo.hProcess, 100) = WAIT_TIMEOUT do begin ReadLinesFromPipe(False); Application.ProcessMessages; //if Application.Terminated then break; end; ReadLinesFromPipe(True); GetExitCodeProcess(ProceInfo.hProcess, dwExitCode); CloseHandle(ProceInfo.hProcess); CloseHandle(ProceInfo.hThread); Result := True; finally if InStream <> nil then InStream.Free; if HOutRead <> INVALID_HANDLE_VALUE then CloseHandle(HOutRead); if HOutWrite <> INVALID_HANDLE_VALUE then CloseHandle(HOutWrite); end; except ; end; end; function WinExecWithPipe(const CmdLine, Dir: string; var Output: string; var dwExitCode: Cardinal): Boolean; var slOutput: TStringList; begin slOutput := TStringList.Create; try Result := InternalWinExecWithPipe(CmdLine, Dir, slOutput, dwExitCode); Output := slOutput.Text; finally slOutput.Free; end; end; function DeleteFileWithUndo(FileName : string ): Boolean; var Fos : TSHFileOpStruct; begin FillChar( Fos, SizeOf( Fos ), 0 ); with Fos do begin wFunc := FO_DELETE; pFrom := PChar( FileName ); fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION or FOF_SILENT; end; Result := ( 0 = ShFileOperation( Fos ) ); end; procedure ExploreDir(APath: string; ShowDir: Boolean); var strExecute: AnsiString; begin if not ShowDir then strExecute := AnsiString(Format('EXPLORER.EXE "%s"', [APath])) else strExecute := AnsiString(Format('EXPLORER.EXE /e, "%s"', [APath])); WinExec(PAnsiChar(strExecute), SW_SHOWNORMAL); end; function GetAveCharSize(Canvas: TCanvas): TPoint; var I: Integer; Buffer: array[0..51] of Char; begin for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A')); for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a')); GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(Result)); Result.X := Result.X div 52; end; // 输入对话框 function CnInputQuery(const ACaption, APrompt: string; var Value: string): Boolean; var Form: TForm; Prompt: TLabel; Edit: TEdit; ComboBox: TComboBox; DialogUnits: TPoint; ButtonTop, ButtonWidth, ButtonHeight: Integer; {$IFDEF CREATE_PARAMS_BUG} OldLong: Longint; AHandle: THandle; NeedChange: Boolean; {$ENDIF} begin Result := False; ComboBox := nil; {$IFDEF CREATE_PARAMS_BUG} NeedChange := False; OldLong := 0; AHandle := Application.ActiveFormHandle; {$ENDIF} Form := TForm.Create(Application); with Form do try Scaled := False; Font.Handle := GetStockObject(DEFAULT_GUI_FONT); Canvas.Font := Font; DialogUnits := GetAveCharSize(Canvas); BorderStyle := bsDialog; Caption := ACaption; ClientWidth := MulDiv(180, DialogUnits.X, 4); ClientHeight := MulDiv(63, DialogUnits.Y, 8); Position := poScreenCenter; Prompt := TLabel.Create(Form); with Prompt do begin Parent := Form; AutoSize := True; Left := MulDiv(8, DialogUnits.X, 4); Top := MulDiv(8, DialogUnits.Y, 8); Caption := APrompt; end; Edit := TEdit.Create(Form); with Edit do begin Parent := Form; Left := Prompt.Left; Top := MulDiv(19, DialogUnits.Y, 8); Width := MulDiv(164, DialogUnits.X, 4); MaxLength := 255; Text := Value; SelectAll; end; ButtonTop := MulDiv(41, DialogUnits.Y, 8); ButtonWidth := MulDiv(50, DialogUnits.X, 4); ButtonHeight := MulDiv(14, DialogUnits.Y, 8); with TButton.Create(Form) do begin Parent := Form; Caption := SCnMsgDlgOK; ModalResult := mrOk; Default := True; SetBounds(MulDiv(38, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight); end; with TButton.Create(Form) do begin Parent := Form; Caption := SCnMsgDlgCancel; ModalResult := mrCancel; Cancel := True; SetBounds(MulDiv(92, DialogUnits.X, 4), ButtonTop, ButtonWidth, ButtonHeight); end; {$IFDEF CREATE_PARAMS_BUG} if AHandle <> 0 then begin OldLong := GetWindowLong(AHandle, GWL_EXSTYLE); NeedChange := OldLong and WS_EX_TOOLWINDOW = WS_EX_TOOLWINDOW; if NeedChange then SetWindowLong(AHandle, GWL_EXSTYLE, OldLong and not WS_EX_TOOLWINDOW); end; {$ENDIF} if ShowModal = mrOk then begin if Assigned(ComboBox) then begin Value := ComboBox.Text; end else Value := Edit.Text; Result := True; end; finally {$IFDEF CREATE_PARAMS_BUG} if NeedChange and (OldLong <> 0) then SetWindowLong(AHandle, GWL_EXSTYLE, OldLong); {$ENDIF} Form.Free; end; end; // 输入对话框 function CnInputBox(const ACaption, APrompt, ADefault: string; var Res: string): Boolean; begin Res := ADefault; Result := CnInputQuery(ACaption, APrompt, Res); end; procedure LoadThumb(const FileName: string; Bmp: TBitmap); var E: Extended; H, W: Integer; G: TGPGraphics; Img, Thumb, Err: TGPImage; begin if not Bmp.HandleAllocated then Exit; G := nil; Img := nil; Thumb := nil; try try G := TGPGraphics.Create(Bmp.Canvas.Handle); Img := TGPImage.Create(FileName); W := Img.GetWidth; H := Img.GetHeight; if W > H then begin W := THUMB_MAX; E := Img.GetWidth / W; E := Img.GetHeight / E; H := Round(E); end else begin H := THUMB_MAX; E := Img.GetHeight /H; E := Img.GetWidth /E; W := Round(E); end; Thumb := Img.GetThumbnailImage(W, H, nil, nil); G.Clear(MakeColor($FF, $FF, $FF)); G.DrawImage(Thumb, (Bmp.Width - W) div 2, (Bmp.Height - H) div 2, Thumb.GetWidth, Thumb.GetHeight); except G.Clear(MakeColor($FF, $FF, $FF)); Err := nil; try try Err := TGPImage.Create(ERROR_FILE); G.DrawImage(Err, (Bmp.Width - Err.GetWidth) div 2, (Bmp.Height - Err.GetHeight) div 2); except ; end; finally Err.Free; end; end; finally Img.Free; Thumb.Free; G.Free; end; end; // 查找指定目录下文件 function FindFile(const Path: string; const FileName: string = '*.*'; Proc: TFindCallBack = nil; DirProc: TDirCallBack = nil; bSub: Boolean = True; bMsg: Boolean = True): Boolean; procedure DoFindFile(const Path, SubPath: string; const FileName: string; Proc: TFindCallBack; DirProc: TDirCallBack; bSub: Boolean; bMsg: Boolean); var APath: string; Info: TSearchRec; Succ: Integer; begin FindAbort := False; APath := IncludeTrailingPathDelimiter(IncludeTrailingPathDelimiter(Path) + SubPath); Succ := FindFirst(APath + FileName, faAnyFile - faVolumeID, Info); try while Succ = 0 do begin if (Info.Name <> '.') and (Info.Name <> '..') then begin if (Info.Attr and faDirectory) <> faDirectory then begin if Assigned(Proc) then Proc(APath + Info.FindData.cFileName, Info, FindAbort); end end; if bMsg then Application.ProcessMessages; if FindAbort then Exit; Succ := FindNext(Info); end; finally FindClose(Info); end; if bSub then begin Succ := FindFirst(APath + '*.*', faAnyFile - faVolumeID, Info); try while Succ = 0 do begin if (Info.Name <> '.') and (Info.Name <> '..') and (Info.Attr and faDirectory = faDirectory) then begin if Assigned(DirProc) then DirProc(IncludeTrailingPathDelimiter(SubPath) + Info.Name); DoFindFile(Path, IncludeTrailingPathDelimiter(SubPath) + Info.Name, FileName, Proc, DirProc, bSub, bMsg); if FindAbort then Exit; end; Succ := FindNext(Info); end; finally FindClose(Info); end; end; end; begin DoFindFile(Path, '', FileName, Proc, DirProc, bSub, bMsg); Result := not FindAbort; end; procedure TFormMain.tvMainChange(Sender: TObject; Node: TTreeNode); var Res: Boolean; begin // Get All Files List if FFiles = nil then Exit; FFiles.Clear; ilImages.Clear; lstSelection.Clear; FCurrentFileName := ''; ClearImage; Screen.Cursor := crHourGlass; try Res := FindFile(tvMain.Path, '*.JPG', OnFindFile, nil, False, False); finally Screen.Cursor := crDefault; end; if Res then begin lvImages.Items.Count := FFiles.Count; lvImages.Invalidate; end; FCurSelectionChanged := False; end; procedure TFormMain.OnFindFile(const FileName: string; const Info: TSearchRec; var Abort: Boolean); var F: TFileItem; begin F := TFileItem.Create; F.FileName := FileName; F.Caption := ChangeFileExt(ExtractFileName(FileName), ''); FFiles.Add(F); ilImages.Add(F.Bitmap, nil); end; procedure TFormMain.FormCreate(Sender: TObject); var P: string; begin FFiles := TObjectList.Create(True); FCheckedIcon := TIcon.Create; FCheckedIcon.Height := ICON_SIZE; FCheckedIcon.Width := ICON_SIZE; FCheckedIcon.LoadFromFile('checked.ico'); //FCheckedIcon.Handle := LoadIcon(HInstance, 'CHECKED'); FUnCheckedIcon := TIcon.Create; FUnCheckedIcon.LoadFromFile('unchecked.ico'); FUncheckedIcon.Height := ICON_SIZE; FUncheckedIcon.Width := ICON_SIZE; //FUncheckedIcon.Handle := LoadIcon(HInstance, 'UNCHECKED'); FImgContent := TLXImage.Create(Self); FImgContent.Parent := pnlDisplay; FImgContent.AutoSize := True; FImgContent.Align := alClient; FImgContent.OnMouseDown := ImageMouseDown; FImgContent.OnMouseMove := ImageMouseMove; FImgContent.OnMouseUp := ImageMouseUp; FImgContent.OnDblClick := ImageDblClick; FImgContent.PopupMenu := pmImage; IniOptions.LoadFromFile(INI_FILE); if DirectoryExists(IniOptions.ConfigRootDir) then begin tvMain.Path := IniOptions.ConfigRootDir; tvMain.Selected.Expand(False); // TODO: Expand? end; Application.Title := Caption; Left := 0; Top := 0; Width := Screen.DesktopWidth; Height := Screen.DesktopHeight - 30; lvImages.DoubleBuffered := True; P := ExtractFilePath(Application.ExeName); P := IncludeTrailingPathDelimiter(P) + '\exiftool.exe'; if FileExists(P) then begin FExifTool := P; end else begin P := ExtractFilePath(Application.ExeName); P := IncludeTrailingPathDelimiter(P) + '..\GaiPic\exiftool.exe'; if FileExists(P) then begin FExifTool := P; end; end; P := ExtractFilePath(Application.ExeName); P := IncludeTrailingPathDelimiter(P) + '\gm.exe'; if FileExists(P) then begin FGmTool := P; end else begin P := ExtractFilePath(Application.ExeName); P := IncludeTrailingPathDelimiter(P) + '..\GaiPic\gm.exe'; if FileExists(P) then begin FGmTool := P; end; end; end; procedure TFormMain.FormDestroy(Sender: TObject); begin FUncheckedIcon.Free; FCheckedIcon.Free; FUncheckedBitMap.Free; FCheckedBitmap.Free; FFiles.Free; end; procedure TFormMain.lvImagesData(Sender: TObject; Item: TListItem); var F: TFileItem; Idx: Integer; begin if Item <> nil then begin Idx := Item.Index; if (Idx >= 0) and (Idx < FFiles.Count) then begin F := TFileItem(FFiles.Items[Idx]); if F <> nil then begin Item.Caption := F.Caption; Item.Checked := F.Checked; if not F.ThumbValid then begin LoadThumb(F.FileName, F.Bitmap); F.ThumbValid := True; F.ImageIndex := ilImages.Add(F.Bitmap, nil); end; Item.ImageIndex := F.ImageIndex; end; end; end; end; { TFileItem } constructor TFileItem.Create; begin FImageIndex := -1; FBitmap := TBitmap.Create; FBitmap.Width := THUMB_MAX; FBitmap.Height := THUMB_MAX; end; destructor TFileItem.Destroy; begin FBitmap.Free; inherited; end; procedure TFormMain.lvImagesCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; var DefaultDraw: Boolean); var P: TPoint; OldColor: TColor; begin OldColor := Sender.Canvas.Pen.Color; P := Item.GetPosition; if Item.Checked then Sender.Canvas.Draw(P.X - 12, P.Y + 2, FCheckedIcon) else Sender.Canvas.Draw(P.X - 12, P.Y + 2, FUncheckedIcon); Sender.Canvas.Brush.Color := (Sender as TListView).Color; Sender.Canvas.Pen.Color := OldColor; end; procedure TFormMain.UpdateSelectionText(var Msg: TMessage); var I: Integer; F: TFileItem; begin lstSelection.Clear; lstSelection.Items.BeginUpdate; try for I := 0 to FFiles.Count - 1 do begin F := TFileItem(FFiles.Items[I]); if (F <> nil) and F.Checked then lstSelection.Items.Add(F.Caption); end; finally lstSelection.Items.EndUpdate; end; FCurSelectionChanged := True; UpdateSelectionSummary; end; procedure TFormMain.lvImagesChange(Sender: TObject; Item: TListItem; Change: TItemChange); var Idx: Integer; F: TFileItem; begin if Change = ctState then begin if (Item <> nil) and Item.Selected then begin Idx := Item.Index; if (Idx >= 0) and (Idx < FFiles.Count) then begin F := TFileItem(FFiles.Items[Idx]); if FCurrentFileName <> F.FileName then begin ShowMatchedImage(F.FileName); FCurrentIndex := Idx; UpdateShowingImageInfo; end; end; end; end; end; procedure TFormMain.lvImagesDblClick(Sender: TObject); var P: TPoint; Item: TListItem; Idx: Integer; F: TFileItem; begin P := Mouse.CursorPos; P := (Sender as TListView).ScreenToClient(P); Item := (Sender as TListView).GetItemAt(P.X, P.Y); if Item = nil then Exit; Idx := Item.Index; if (Idx < 0) or (Idx >= FFiles.Count) then Exit; F := TFileItem(FFiles.Items[Idx]); F.Checked := not F.Checked; (Sender as TListView).Invalidate; PostMessage(Handle, WM_UPDATE_SELECTION, 0, 0); end; procedure TFormMain.ShowMatchedImage(const FileName: string; ForceReload: Boolean); var W, H: Integer; EW, EH: Extended; G: TGPGraphics; begin if FileName = '' then Exit; if not FileExists(FileName) then Exit; try // Show this image as Matched. // 只有文件名相同并且ForceReload是False时才不重新来 // 如果文件名不同或ForceReload是True,就释放掉重来 if ForceReload or (FCurrentFileName <> FileName) then begin if FCurrentGPImage <> nil then FreeAndNil(FCurrentGPImage); FCurrentGPImage := TGPImage.Create(FileName); end; if FCurrentGPImage = nil then FCurrentGPImage := TGPImage.Create(FileName); W := FCurrentGPImage.GetWidth; H := FCurrentGPImage.GetHeight; // Matched 状态,源区是整张图 FSrcRect.Left := 0; FSrcRect.Top := 0; FSrcRect.Right := W; FSrcRect.Bottom := H; if (FCurImgWidth > 0) and (FCurImgHeight > 0) then begin G := TGPGraphics.Create(FImgContent.Canvas.Handle); G.Clear(MakeColor($FF, $FF, $FF)); if (W <= FCurImgWidth) and (H <= FCurImgHeight) then begin // 直接原始大小居中显示 FZoomFactor := 1.0; FDestRect.Left := (FCurImgWidth - W) div 2; FDestRect.Top := (FCurImgHeight - H) div 2; FDestRect.Right := FDestRect.Left + W; FDestRect.Bottom := FDestRect.Top + H; G.DrawImage(FCurrentGPImage, FDestRect.Left, FDestRect.Top, W, H); end else begin // 缩放至合适大小 EW := FCurImgWidth / W; // 横向缩比例 EH := FCurImgHeight / H; // 纵向缩比例 if EW >= EH then // 横的缩得多,按横的来 begin FZoomFactor := EH; W := Round(W * FZoomFactor); H := Round(H * FZoomFactor); end else begin FZoomFactor := EW; W := Round(W * FZoomFactor); H := Round(H * FZoomFactor); end; // 再用缩放的显示 FDestRect.Left := (FCurImgWidth - W) div 2; FDestRect.Top := (FCurImgHeight - H) div 2; FDestRect.Right := FDestRect.Left + W; FDestRect.Bottom := FDestRect.Top + H; G.DrawImage(FCurrentGPImage, FDestRect.Left, FDestRect.Top, W, H); // TODO: 画个黑框? // R.Left := (FCurImgWidth - W) div 2; // R.Top := (FCurImgHeight - H) div 2; // R.Right := R.Left + W; // R.Bottom := R.Top + H; // imgContent.Canvas.Pen.Color := clBlack; // imgContent.Canvas.FrameRect(R); end; G.Free; end; FImgContent.Invalidate; FDisplayMode := dmMatch; except ; end; FCurrentFileName := FileName; end; procedure TFormMain.UpdateImage(var Msg: TMessage); begin if FDisplayMode = dmMatch then ShowMatchedImage(FCurrentFileName, False) else if FDisplayMode = dmActual then ShowActualImage(FCurrentFileName, False); end; procedure TFormMain.ShowActualImage(const FileName: string; ForceReload: Boolean); var W, H: Integer; G: TGPGraphics; begin if FileName = '' then Exit; if not FileExists(FileName) then Exit; try // Show this image as Actual. // 只有文件名相同并且ForceReload是False时才不重新来 // 如果文件名不同或ForceReload是True,就释放掉重来 if ForceReload or (FCurrentFileName <> FileName) then begin if FCurrentGPImage <> nil then FreeAndNil(FCurrentGPImage); FCurrentGPImage := TGPImage.Create(FileName); end; if FCurrentGPImage = nil then FCurrentGPImage := TGPImage.Create(FileName); W := FCurrentGPImage.GetWidth; H := FCurrentGPImage.GetHeight; if (FCurImgWidth > 0) and (FCurImgHeight > 0) then begin G := TGPGraphics.Create(FImgContent.Canvas.Handle); G.Clear(MakeColor($FF, $FF, $FF)); FDestRect.Left := (FCurImgWidth - W) div 2; FDestRect.Top := (FCurImgHeight - H) div 2; FDestRect.Right := FDestRect.Left + W; FDestRect.Bottom := FDestRect.Top + H; if FDestRect.Left > 0 then FSrcRect.Left := 0 else FSrcRect.Left := - FDestRect.Left; if FDestRect.Top > 0 then FSrcRect.Top := 0 else FSrcRect.Top := - FDestRect.Top; FSrcRect.Right := FSrcRect.Left + W; FSrcRect.Bottom := FSrcRect.Top + H; // To prevent exceed Image Size? G.DrawImage(FCurrentGPImage, FDestRect.Left, FDestRect.Top, W, H); G.Free; end; FImgContent.Invalidate; FDisplayMode := dmActual; FZoomFactor := 1.0; except ; end; FCurrentFileName := FileName; end; procedure TFormMain.ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin FImageMouseDown := True; FImageMouseDownPos.X := X; FImageMouseDownPos.Y := Y; end; end; procedure TFormMain.ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var DeltaX, DeltaY: Integer; G: TGPGraphics; R: TRect; begin if FImageMouseDown and (FCurrentGPImage <> nil) then begin DeltaX := X - FImageMouseDownPos.X; DeltaY := Y - FImageMouseDownPos.Y; G := TGPGraphics.Create(FImgContent.Canvas.Handle); G.Clear(MakeColor($FF, $FF, $FF)); R := FDestRect; OffsetRect(R, DeltaX, DeltaY); G.DrawImage(FCurrentGPImage, R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top); FImgContent.Invalidate; FDisplayMode := dmCustom; end; end; procedure TFormMain.ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P: TPoint; DeltaX, DeltaY: Integer; begin if Button = mbLeft then begin FImageMouseDown := False; DeltaX := X - FImageMouseDownPos.X; DeltaY := Y - FImageMouseDownPos.Y; OffsetRect(FDestRect, DeltaX, DeltaY); end; // else if Button = mbRight then // begin // if FCurrentFileName <> '' then // begin // P.X := X; // P.Y := Y; // DisplayContextMenu(Handle, FCurrentFileName, FImgContent.ClientToScreen(P)); // end; // end; end; procedure TFormMain.ImageDblClick(Sender: TObject); begin if FDisplayMode <> dmMatch then ShowMatchedImage(FCurrentFileName, False) else ShowActualImage(FCurrentFileName, False); end; procedure TFormMain.lvImagesMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P: TPoint; Item: TListItem; Idx: Integer; F: TFileItem; R: TRect; begin if Button = mbLeft then begin P := Mouse.CursorPos; P := (Sender as TListView).ScreenToClient(P); Item := (Sender as TListView).GetItemAt(P.X, P.Y); if Item = nil then Item := (Sender as TListView).GetItemAt(P.X + 20, P.Y); if Item = nil then Exit; Idx := Item.Index; if (Idx < 0) or (Idx >= FFiles.Count) then Exit; F := TFileItem(FFiles.Items[Idx]); R := Item.DisplayRect(drBounds); if (X - R.Left < 20) and (Y - R.Top < 20) then begin F.Checked := not F.Checked; (Sender as TListView).Invalidate; PostMessage(Handle, WM_UPDATE_SELECTION, 0, 0); end; end; end; procedure TFormMain.actShowMatchExecute(Sender: TObject); begin // 适合窗口尺寸。双边都小于窗口尺寸则以实际大小显示并居中 // 有一大于窗口尺寸则缩放并居中。 ShowMatchedImage(FCurrentFileName, False); end; procedure TFormMain.actShowActualExecute(Sender: TObject); begin // 实际大小。双边都小于窗口尺寸则以实际大小显示并居中 // 有一大于窗口尺寸则实际显示并居中。 ShowActualImage(FCurrentFileName, False); end; procedure TFormMain.lvImagesKeyPress(Sender: TObject; var Key: Char); var Item: TListItem; Idx: Integer; F: TFileItem; begin if Key = ' ' then begin if (Sender as TListView).Selected <> nil then begin Item := (Sender as TListView).Selected; Idx := Item.Index; if (Idx < 0) or (Idx >= FFiles.Count) then Exit; F := TFileItem(FFiles.Items[Idx]); F.Checked := not F.Checked; (Sender as TListView).Invalidate; PostMessage(Handle, WM_UPDATE_SELECTION, 0, 0); end; end; end; procedure TFormMain.UpdateSelectionSummary; begin if lstSelection.Items.Count = 0 then statBar.Panels[0].Text := '' else statBar.Panels[0].Text := Format('已选择 %d 张照片。', [lstSelection.Items.Count]); end; procedure TFormMain.UpdateShowingImageInfo; begin if FCurrentFileName <> '' then statBar.Panels[1].Text := Format('当前照片:%s', [FCurrentFileName]) else statBar.Panels[1].Text := ''; end; function TFormMain.QueryDlg(const Msg, Cap: string): Boolean; begin Result := False; if Application.MessageBox(PChar(Msg), PChar(Cap), MB_OKCANCEL + MB_ICONQUESTION) = IDOK then begin Result := True; end; end; procedure TFormMain.actSelectAllExecute(Sender: TObject); var I: Integer; F: TFileItem; begin if QueryDlg('要全部选择当前文件夹下的所有照片?') then begin for I := 0 to FFiles.Count - 1 do begin F := TFileItem(FFiles[I]); F.Checked := True; lvImages.Invalidate; PostMessage(Handle, WM_UPDATE_SELECTION, 0, 0); end; end; end; procedure TFormMain.actSelectNoneExecute(Sender: TObject); var I: Integer; F: TFileItem; begin if QueryDlg('要忘掉所有选择?') then begin for I := 0 to FFiles.Count - 1 do begin F := TFileItem(FFiles[I]); F.Checked := False; lvImages.Invalidate; PostMessage(Handle, WM_UPDATE_SELECTION, 0, 0); end; end; end; procedure TFormMain.actCopySelectionExecute(Sender: TObject); var DirName, FullDir, Dst: string; I, C: Integer; F: TFileItem; begin if lstSelection.Count = 0 then begin ErrDlg('没有选择的照片。'); Exit; end; if CnInputBox(INFO_QUERY_CAPTION, '将建立子目录于当前目录:' + tvMain.Path, '选片', DirName) then begin if DirName <> '' then begin Screen.Cursor := crHourGlass; try FullDir := IncludeTrailingPathDelimiter(tvMain.Path) + DirName; if DirectoryExists(FullDir) then begin if not QueryDlg(Format('目录 %s 已存在,是否确定要将选片结果覆盖存储至此目录下?', [DirName])) then Exit; end; ForceDirectories(FullDir); C := 0; for I := 0 to FFiles.Count - 1 do begin F := TFileItem(FFiles.Items[I]); if F.Checked then begin Dst := IncludeTrailingPathDelimiter(FullDir) + ExtractFileName(F.FileName); if CopyFile(PChar(F.FileName), PChar(Dst), False) then Inc(C); end; end; finally Screen.Cursor := crDefault; end; FCurSelectionChanged := False; if YesNoDlg(Format('已成功选片 %d 张。是否要打开子目录 %s 来查看选片结果?', [C, DirName])) then ExploreDir(FullDir, False); end; end; end; procedure TFormMain.InfoDlg(const Msg, Cap: string); begin Application.MessageBox(PChar(Msg), PChar(Cap), MB_OK + MB_ICONINFORMATION); end; procedure TFormMain.ErrDlg(const Msg, Cap: string); begin Application.MessageBox(PChar(Msg), PChar(Cap), MB_OK + MB_ICONERROR); end; procedure TFormMain.tvMainChanging(Sender: TObject; Node: TTreeNode; var AllowChange: Boolean); begin if FCurSelectionChanged and (lstSelection.Count > 0) then AllowChange := QueryDlg('当前目录下的选片结果未保存,是否放弃?'); end; procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if FCurSelectionChanged and (lstSelection.Count > 0) then CanClose := QueryDlg('当前目录下的选片结果未保存,是否放弃?') else CanClose := True; end; procedure TFormMain.actRemoveSelectionExecute(Sender: TObject); var I, J: Integer; S: string; F: TFileItem; begin for I := 0 to lstSelection.Items.Count - 1 do begin if lstSelection.Selected[I] then begin S := Trim(lstSelection.Items[I]); for J := 0 to FFiles.Count - 1 do begin F := TFileItem(FFiles.Items[J]); if F.Checked and (F.Caption = S) then begin F.Checked := False; lvImages.Invalidate; PostMessage(Handle, WM_UPDATE_SELECTION, 0, 0); Exit; end; end; end; end; end; procedure TFormMain.lstSelectionKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_DELETE then begin actRemoveSelection.Execute; end; end; procedure TFormMain.pnlContentBtmResize(Sender: TObject); begin tlbImage.Left := (pnlContentBtm.Width - tlbImage.Width) div 2; end; procedure TFormMain.actPrevImageExecute(Sender: TObject); var Idx: Integer; begin if lvImages.Selected <> nil then Idx := lvImages.Selected.Index else Idx := FCurrentIndex; if Idx > 0 then begin Dec(Idx); lvImages.Selected := lvImages.Items[Idx]; lvImages.Selected.MakeVisible(False); end; end; procedure TFormMain.actNextImageExecute(Sender: TObject); var Idx: Integer; begin if lvImages.Selected <> nil then Idx := lvImages.Selected.Index else Idx := FCurrentIndex; if Idx < lvImages.Items.Count - 1 then begin Inc(Idx); lvImages.Selected := lvImages.Items[Idx]; lvImages.Selected.MakeVisible(False); end; end; procedure TFormMain.actSlideExecute(Sender: TObject); var Idx: Integer; begin if (FFiles = nil) or (FFiles.Count = 0) then Exit; Idx := 0; if lvImages.Selected <> nil then Idx := lvImages.Selected.Index; with TFormSlide.Create(nil) do begin Files := FFiles; CurIdx := Idx; ShowModal; Idx := CurIdx; Free; if (Idx >= 0) and (Idx < lvImages.Items.Count) then begin lvImages.Selected := lvImages.Items[Idx]; lvImages.Selected.MakeVisible(False); end; end; end; procedure TFormMain.pnlToolbarResize(Sender: TObject); begin tlbSelection.Left := (pnlToolbar.Width - tlbSelection.Width) div 2; end; function TFormMain.YesNoDlg(const Msg, Cap: string): Boolean; begin Result := False; if Application.MessageBox(PChar(Msg), PChar(Cap), MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2) = IDYES then begin Result := True; end; end; procedure TFormMain.lstSelectionDblClick(Sender: TObject); var J: Integer; F: TFileItem; S: string; begin if lstSelection.ItemIndex >= 0 then begin S := Trim(lstSelection.Items[lstSelection.ItemIndex]); for J := 0 to FFiles.Count - 1 do begin F := TFileItem(FFiles.Items[J]); if F.Checked and (F.Caption = S) then begin with TFormDisplay.Create(nil) do begin FileName := F.FileName; ShowModal; Free; end; end; end; end; end; procedure TFormMain.actlstMainUpdate(Action: TBasicAction; var Handled: Boolean); begin if Action = actSelectAll then begin (Action as TAction).Enabled := FFiles.Count > 0; Handled := True; end else if Action = actSelectNone then begin (Action as TAction).Enabled := lstSelection.Items.Count > 0; Handled := True; end else if Action = actRemoveSelection then begin (Action as TAction).Enabled := lstSelection.ItemIndex >= 0; Handled := True; end else if Action = actCopySelection then begin (Action as TAction).Enabled := FCurSelectionChanged and (lstSelection.Items.Count > 0); Handled := True; end else if Action = actPrevImage then begin (Action as TAction).Enabled := FCurrentIndex > 0; Handled := True; end else if Action = actNextImage then begin (Action as TAction).Enabled := FCurrentIndex < FFiles.Count - 1; Handled := True; end else if Action = actShowMatch then begin (Action as TAction).Enabled := (FDisplayMode <> dmMatch) and (FCurrentFileName <> ''); Handled := True; end else if Action = actShowActual then begin (Action as TAction).Enabled := (FDisplayMode <> dmActual) and (FCurrentFileName <> ''); Handled := True; end else if Action = actSlide then begin (Action as TAction).Enabled := FFiles.Count > 0; Handled := True; end else if Action = actDeleteFile then begin (Action as TAction).Enabled := FCurrentFileName <> ''; Handled := True; end else if Action = actShowInfo then begin (Action as TAction).Enabled := FCurrentFileName <> ''; Handled := True; end else if Action = actContextMenu then begin (Action as TAction).Enabled := FCurrentFileName <> ''; Handled := True; end else if Action = actRotateClockWise then begin (Action as TAction).Enabled := FCurrentFileName <> ''; Handled := True; end else if Action = actRotateAntiClockWise then begin (Action as TAction).Enabled := FCurrentFileName <> ''; Handled := True; end end; procedure TFormMain.actSettingExecute(Sender: TObject); begin // Do settings with TFormSetting.Create(nil) do begin edtRoot.Text := IniOptions.ConfigRootDir; seInterval.Value := IniOptions.ConfigSlideDelay; if ShowModal = mrOK then begin IniOptions.ConfigSlideDelay := seInterval.Value; IniOptions.ConfigRootDir := edtRoot.Text; IniOptions.SaveToFile(INI_FILE); end; Free; end; end; procedure TFormMain.pnlDisplayResize(Sender: TObject); begin FCurImgWidth := pnlDisplay.Width; FCurImgHeight := pnlDisplay.Height; PostMessage(Handle, WM_UPDATE_IMAGE, 0, 0); end; procedure TFormMain.ClearImage; var G: TGPGraphics; begin G := TGPGraphics.Create(FImgContent.Canvas.Handle); G.Clear(MakeColor($FF, $FF, $FF)); G.Free; FImgContent.Invalidate; end; procedure TFormMain.actDeleteFileExecute(Sender: TObject); var I: Integer; F: TFileItem; Deleted, Res: Boolean; begin if FCurrentFileName <> '' then begin if QueryDlg('确实要删除文件:' + FCurrentFileName + '?删除后不可恢复。') then begin if FCurrentGPImage <> nil then FreeAndNil(FCurrentGPImage); Res := DeleteFile(FCurrentFileName); if not Res then begin ErrDlg('文件删除失败!错误码:' + IntToStr(GetLastError)); Exit; end; Deleted := False; for I := 0 to FFiles.Count - 1 do begin F := TFileItem(FFiles.Items[I]); if F.FileName = FCurrentFileName then begin FFiles.Remove(F); Deleted := True; Break; end; end; if Deleted then begin PostMessage(Handle, WM_UPDATE_SELECTION, 0, 0); lvImages.Items.Count := FFiles.Count; lvImages.Invalidate; if FFiles.Count = 0 then begin ClearImage; FCurrentFileName := ''; UpdateShowingImageInfo; Exit; end; if FCurrentIndex >= FFiles.Count then FCurrentIndex := FFiles.Count - 1; FCurrentFileName := TFileItem(FFiles.Items[FCurrentIndex]).FileName; ShowMatchedImage(FCurrentFileName); end; end; end; end; procedure TFormMain.actContextMenuExecute(Sender: TObject); begin if FCurrentFileName <> '' then begin DisplayContextMenu(Handle, FCurrentFileName, Mouse.CursorPos); end; end; procedure TFormMain.actShowInfoExecute(Sender: TObject); var S: string; ExitCode: DWORD; begin Screen.Cursor := crHourGlass; if WinExecWithPipe(FExifTool + ' ' + FCurrentFileName, '', S, ExitCode) then begin with TFormInfo.Create(nil) do begin Caption := FCurrentFileName; lstInfo.Items.Clear; lstInfo.Items.Text := S; TranslateStrings; Screen.Cursor := crDefault; ShowModal; Free; end; end; Screen.Cursor := crDefault; end; procedure TFormMain.actRotateClockWiseExecute(Sender: TObject); var Cmd: string; Res: Integer; begin if FCurrentGPImage <> nil then FreeAndNil(FCurrentGPImage); Cmd := FGmTool + ' convert -rotate 90 -compress Lossless "' + FCurrentFileName + '" "' + FCurrentFileName + '"'; Screen.Cursor := crHourGlass; try Res := WinExecAndWait32(Cmd, SW_HIDE, True); finally Screen.Cursor := crDefault; end; if Res <> 0 then begin ErrDlg('错误码:' + IntToStr(Res) + ' 旋转失败:' + Cmd); Exit; end; // 刷新缩略图 RefreshCurrentThumbnail(); ShowMatchedImage(FCurrentFileName, True); end; procedure TFormMain.actRotateAntiClockWiseExecute(Sender: TObject); var Cmd: string; Res: Integer; begin if FCurrentGPImage <> nil then FreeAndNil(FCurrentGPImage); Cmd := FGmTool + ' convert -rotate -90 -compress Lossless "' + FCurrentFileName + '" "' + FCurrentFileName + '"'; Screen.Cursor := crHourGlass; try Res := WinExecAndWait32(Cmd, SW_HIDE, True); finally Screen.Cursor := crDefault; end; if Res <> 0 then begin ErrDlg('错误码:' + IntToStr(Res) + ' 旋转失败:' + Cmd); Exit; end; // 刷新缩略图 RefreshCurrentThumbnail(); ShowMatchedImage(FCurrentFileName, True); end; procedure TFormMain.RefreshCurrentThumbnail; var Idx: Integer; F: TFileItem; begin if lvImages.Selected = nil then Exit; Idx := lvImages.Selected.Index; if (Idx < 0) or (Idx >= FFiles.Count) then Exit; F := TFileItem(FFiles.Items[Idx]); if F.FileName <> FCurrentFileName then Exit; F.ThumbValid := False; lvImages.Invalidate; end; end.
{******************************************************************************} { CnPack For Delphi/C++Builder } { 中国人自己的开放源码第三方开发包 } { (C)Copyright 2001-2023 CnPack 开发组 } { ------------------------------------ } { } { 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 } { 改和重新发布这一程序。 } { } { 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 } { 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 } { } { 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 } { 还没有,可访问我们的网站: } { } { 网站地址:http://www.cnpack.org } { 电子邮件:master@cnpack.org } { } {******************************************************************************} unit CnNative; {* |<PRE> ================================================================================ * 软件名称:CnPack 组件包 * 单元名称:32 位和 64 位的一些统一声明以及一堆基础实现 * 单元作者:刘啸 (liuxiao@cnpack.org) * 备 注:Delphi XE 2 支持 32 和 64 以来,开放出的 NativeInt 和 NativeUInt 随 * 当前是 32 位还是 64 而动态变化,影响到的是 Pointer、Reference等东西。 * 考虑到兼容性,固定长度的 32 位 Cardinal/Integer 等和 Pointer 这些就 * 不能再通用了,即使 32 位下也被编译器禁止。因此本单元声明了几个类型, * 供同时在低版本和高版本的 Delphi 中使用。 * 后来加入 UInt64 的包装,注意 D567 下不直接支持 UInt64 的运算,需要用 * 辅助函数实现,目前实现了 div 与 mod * 另外地址运算 Integer(APtr) 在 64 位下尤其是 MacOS 上容易出现截断,需要用 NativeInt * 开发平台:PWin2000 + Delphi 5.0 * 兼容测试:PWin9X/2000/XP + Delphi 5/6/7 XE 2 * 本 地 化:该单元中的字符串均符合本地化处理方式 * 修改记录:2022.11.11 V2.3 * 补上几个无符号数的字节顺序调换函数 * 2022.07.23 V2.2 * 增加几个内存位运算函数与二进制转换字符串函数,并改名为 CnNative * 2022.06.08 V2.1 * 增加四个时间固定的交换函数以及内存倒排函数 * 2022.03.14 V2.0 * 增加几个十六进制转换函数 * 2022.02.17 V1.9 * 增加 FPC 的编译支持 * 2022.02.09 V1.8 * 加入运行期的大小端判断函数 * 2021.09.05 V1.7 * 加入 Int64/UInt64 的整数次幂与根的运算函数 * 2020.10.28 V1.6 * 加入 UInt64 溢出相关的判断与运算函数 * 2020.09.06 V1.5 * 加入求 UInt64 整数平方根的函数 * 2020.07.01 V1.5 * 加入判断 32 位与 64 位有无符号数相加是否溢出的函数 * 2020.06.20 V1.4 * 加入 32 位与 64 位获取最高与最低的 1 位位置的函数 * 2020.01.01 V1.3 * 加入 32 位无符号整型的 mul 运算,在不支持 UInt64 的系统上以 Int64 代替以避免溢出 * 2018.06.05 V1.2 * 加入 64 位整型的 div/mod 运算,在不支持 UInt64 的系统上以 Int64 代替 * 2016.09.27 V1.1 * 加入 64 位整型的一些定义 * 2011.07.06 V1.0 * 创建单元,实现功能 ================================================================================ |</PRE>} interface {$I CnPack.inc} uses Classes, SysUtils, SysConst, Math {$IFDEF COMPILER5}, Windows {$ENDIF}; // D5 下需要引用 Windows 中的 PByte type {$IFDEF COMPILER5} PCardinal = ^Cardinal; {* D5 下 System 单元中未定义,定义上} PByte = Windows.PByte; {* D5 下 PByte 定义在 Windows 中,其他版本定义在 System 中, 这里统一一下供外界使用 PByte 时无需 uses Windows,以有利于跨平台} {$ENDIF} {$IFDEF SUPPORT_32_AND_64} TCnNativeInt = NativeInt; TCnNativeUInt = NativeUInt; TCnNativePointer = NativeInt; TCnNativeIntPtr = PNativeInt; TCnNativeUIntPtr = PNativeUInt; {$ELSE} TCnNativeInt = Integer; TCnNativeUInt = Cardinal; TCnNativePointer = Integer; TCnNativeIntPtr = PInteger; TCnNativeUIntPtr = PCardinal; {$ENDIF} {$IFDEF CPU64BITS} TCnUInt64 = NativeUInt; TCnInt64 = NativeInt; {$ELSE} {$IFDEF SUPPORT_UINT64} TCnUInt64 = UInt64; {$ELSE} TCnUInt64 = packed record // 只能用这样的结构代替 case Boolean of True: (Value: Int64); False: (Lo32, Hi32: Cardinal); end; {$ENDIF} TCnInt64 = Int64; {$ENDIF} // TUInt64 用于 cnvcl 库中不支持 UInt64 的运算如 div mod 等 {$IFDEF SUPPORT_UINT64} TUInt64 = UInt64; {$IFNDEF SUPPORT_PUINT64} PUInt64 = ^UInt64; {$ENDIF} {$ELSE} TUInt64 = Int64; PUInt64 = ^TUInt64; {$ENDIF} {$IFNDEF SUPPORT_INT64ARRAY} // 如果系统没有定义 Int64Array Int64Array = array[0..$0FFFFFFE] of Int64; PInt64Array = ^Int64Array; {$ENDIF} TUInt64Array = array of TUInt64; // 这个动态数组声明似乎容易和静态数组声明有冲突 ExtendedArray = array[0..65537] of Extended; PExtendedArray = ^ExtendedArray; PCnWord16Array = ^TCnWord16Array; TCnWord16Array = array [0..0] of Word; {$IFDEF POSIX64} TCnLongWord32 = Cardinal; // Linux64/MacOS64 (or POSIX64?) LongWord is 64 Bits {$ELSE} TCnLongWord32 = LongWord; {$ENDIF} PCnLongWord32 = ^TCnLongWord32; TCnLongWord32Array = array [0..MaxInt div SizeOf(Integer) - 1] of TCnLongWord32; PCnLongWord32Array = ^TCnLongWord32Array; {$IFNDEF TBYTES_DEFINED} TBytes = array of Byte; {* 无符号字节数组,未定义时定义上} {$ENDIF} TShortInts = array of ShortInt; {* 有符号字节数组} PCnByte = ^Byte; PCnWord = ^Word; TCnBitOperation = (boAnd, boOr, boXor, boNot); {* 位操作类型} type TCnMemSortCompareProc = function (P1, P2: Pointer; ElementByteSize: Integer): Integer; {* 内存固定块尺寸的数组排序比较函数原型} const CN_MAX_SQRT_INT64: Cardinal = 3037000499; CN_MAX_UINT16: Word = $FFFF; CN_MAX_UINT32: Cardinal = $FFFFFFFF; CN_MAX_TUINT64: TUInt64 = $FFFFFFFFFFFFFFFF; CN_MAX_SIGNED_INT64_IN_TUINT64: TUInt64 = $7FFFFFFFFFFFFFFF; {* 对于 D567 等不支持 UInt64 的编译器,虽然可以用 Int64 代替 UInt64 进行加减、存储 但乘除运算则无法直接完成,这里封装了两个调用 System 库中的 _lludiv 与 _llumod 函数,实现以 Int64 表示的 UInt64 数据的 div 与 mod 功能。 } function UInt64Mod(A, B: TUInt64): TUInt64; {* 两个 UInt64 求余} function UInt64Div(A, B: TUInt64): TUInt64; {* 两个 UInt64 整除} function UInt64Mul(A, B: Cardinal): TUInt64; {* 无符号 32 位整数不溢出的相乘,在不支持 UInt64 的平台上,结果以 UInt64 的形式放在 Int64 里, 如果结果直接使用 Int64 计算则有可能溢出} procedure UInt64AddUInt64(A, B: TUInt64; var ResLo, ResHi: TUInt64); {* 两个无符号 64 位整数相加,处理溢出的情况,结果放 ResLo 与 ResHi 中 注:内部实现按算法来看较为复杂,实际上如果溢出,ResHi 必然是 1,直接判断溢出并将其设 1 即可} procedure UInt64MulUInt64(A, B: TUInt64; var ResLo, ResHi: TUInt64); {* 两个无符号 64 位整数相乘,结果放 ResLo 与 ResHi 中,64 位下用汇编实现,提速约一倍以上} function UInt64ToHex(N: TUInt64): string; {* 将 UInt64 转换为十六进制字符串} function UInt64ToStr(N: TUInt64): string; {* 将 UInt64 转换为字符串} function StrToUInt64(const S: string): TUInt64; {* 将字符串转换为 UInt64} function UInt64Compare(A, B: TUInt64): Integer; {* 比较两个 UInt64 值,分别根据 > = < 返回 1、0、-1} function UInt64Sqrt(N: TUInt64): TUInt64; {* 求 UInt64 的平方根的整数部分} function UInt32IsNegative(N: Cardinal): Boolean; {* 该 Cardinal 被当成 Integer 时是否小于 0} function UInt64IsNegative(N: TUInt64): Boolean; {* 该 UInt64 被当成 Int64 时是否小于 0} procedure UInt64SetBit(var B: TUInt64; Index: Integer); {* 给 UInt64 的某一位置 1,位 Index 从 0 开始} procedure UInt64ClearBit(var B: TUInt64; Index: Integer); {* 给 UInt64 的某一位置 0,位 Index 从 0 开始} function GetUInt64BitSet(B: TUInt64; Index: Integer): Boolean; {* 返回 UInt64 的某一位是否是 1,位 Index 从 0 开始} function GetUInt64HighBits(B: TUInt64): Integer; {* 返回 UInt64 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1} function GetUInt32HighBits(B: Cardinal): Integer; {* 返回 Cardinal 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1} function GetUInt64LowBits(B: TUInt64): Integer; {* 返回 Int64 的是 1 的最低二进制位是第几位,最低位是 0,基本等同于末尾几个 0。如果没有 1,返回 -1} function GetUInt32LowBits(B: Cardinal): Integer; {* 返回 Cardinal 的是 1 的最低二进制位是第几位,最低位是 0,基本等同于末尾几个 0。如果没有 1,返回 -1} function Int64Mod(M, N: Int64): Int64; {* 封装的 Int64 Mod,M 碰到负值时取反求模再模减,但 N 仍要求正数否则结果不靠谱} function IsUInt32PowerOf2(N: Cardinal): Boolean; {* 判断一 32 位无符号整数是否 2 的整数次幂} function IsUInt64PowerOf2(N: TUInt64): Boolean; {* 判断一 64 位无符号整数是否 2 的整数次幂} function GetUInt32PowerOf2GreaterEqual(N: Cardinal): Cardinal; {* 得到一比指定 32 位无符号整数数大或等的 2 的整数次幂,如溢出则返回 0} function GetUInt64PowerOf2GreaterEqual(N: TUInt64): TUInt64; {* 得到一比指定 64 位无符号整数数大或等的 2 的整数次幂,如溢出则返回 0} function IsInt32AddOverflow(A, B: Integer): Boolean; {* 判断两个 32 位有符号数相加是否溢出 32 位有符号上限} function IsUInt32AddOverflow(A, B: Cardinal): Boolean; {* 判断两个 32 位无符号数相加是否溢出 32 位无符号上限} function IsInt64AddOverflow(A, B: Int64): Boolean; {* 判断两个 64 位有符号数相加是否溢出 64 位有符号上限} function IsUInt64AddOverflow(A, B: TUInt64): Boolean; {* 判断两个 64 位无符号数相加是否溢出 64 位无符号上限} procedure UInt64Add(var R: TUInt64; A, B: TUInt64; out Carry: Integer); {* 两个 64 位无符号数相加,A + B => R,如果有溢出,则溢出的 1 搁进位标记里,否则清零} procedure UInt64Sub(var R: TUInt64; A, B: TUInt64; out Carry: Integer); {* 两个 64 位无符号数相减,A - B => R,如果不够减有借位,则借的 1 搁借位标记里,否则清零} function IsInt32MulOverflow(A, B: Integer): Boolean; {* 判断两个 32 位有符号数相乘是否溢出 32 位有符号上限} function IsUInt32MulOverflow(A, B: Cardinal): Boolean; {* 判断两个 32 位无符号数相乘是否溢出 32 位无符号上限} function IsUInt32MulOverflowInt64(A, B: Cardinal; out R: TUInt64): Boolean; {* 判断两个 32 位无符号数相乘是否溢出 64 位有符号数,如未溢出也即返回 False 时,R 中直接返回结果 如溢出也即返回 True,外界需要重新调用 UInt64Mul 才能实施相乘} function IsInt64MulOverflow(A, B: Int64): Boolean; {* 判断两个 64 位有符号数相乘是否溢出 64 位有符号上限} function PointerToInteger(P: Pointer): Integer; {* 指针类型转换成整型,支持 32/64 位,注意 64 位下可能会丢超出 32 位的内容} function IntegerToPointer(I: Integer): Pointer; {* 整型转换成指针类型,支持 32/64 位} function Int64NonNegativeAddMod(A, B, N: Int64): Int64; {* 求 Int64 范围内俩加数的和求余,处理溢出的情况,要求 N 大于 0} function UInt64NonNegativeAddMod(A, B, N: TUInt64): TUInt64; {* 求 UInt64 范围内俩加数的和求余,处理溢出的情况,要求 N 大于 0} function Int64NonNegativeMulMod(A, B, N: Int64): Int64; {* Int64 范围内的相乘求余,不能直接计算,容易溢出。要求 N 大于 0} function UInt64NonNegativeMulMod(A, B, N: TUInt64): TUInt64; {* UInt64 范围内的相乘求余,不能直接计算,容易溢出。} function Int64NonNegativeMod(N: Int64; P: Int64): Int64; {* 封装的 Int64 非负求余函数,也就是余数为负时,加个除数变正,调用者需保证 P 大于 0} function Int64NonNegativPower(N: Int64; Exp: Integer): Int64; {* Int64 的非负整数指数幂,不考虑溢出的情况} function Int64NonNegativeRoot(N: Int64; Exp: Integer): Int64; {* 求 Int64 的非负整数次方根的整数部分,不考虑溢出的情况} function UInt64NonNegativPower(N: TUInt64; Exp: Integer): TUInt64; {* UInt64 的非负整数指数幂,不考虑溢出的情况} function UInt64NonNegativeRoot(N: TUInt64; Exp: Integer): TUInt64; {* 求 UInt64 的非负整数次方根的整数部分,不考虑溢出的情况} function CurrentByteOrderIsBigEndian: Boolean; {* 返回当前运行期环境是否是大端,也就是是否将整数中的高序字节存储在较低的起始地址,符合从左到右的阅读习惯,如部分指定的 ARM 和 MIPS} function CurrentByteOrderIsLittleEndian: Boolean; {* 返回当前运行期环境是否是小端,也就是是否将整数中的高序字节存储在较高的起始地址,如 x86 与部分默认 arm} function Int64ToBigEndian(Value: Int64): Int64; {* 确保 Int64 值为大端,在小端环境中会进行转换} function Int32ToBigEndian(Value: Integer): Integer; {* 确保 Int32 值为大端,在小端环境中会进行转换} function Int16ToBigEndian(Value: SmallInt): SmallInt; {* 确保 Int16 值为大端,在小端环境中会进行转换} function Int64ToLittleEndian(Value: Int64): Int64; {* 确保 Int64 值为小端,在大端环境中会进行转换} function Int32ToLittleEndian(Value: Integer): Integer; {* 确保 Int32 值为小端,在大端环境中会进行转换} function Int16ToLittleEndian(Value: SmallInt): SmallInt; {* 确保 Int16 值为小端,在大端环境中会进行转换} function UInt64ToBigEndian(Value: TUInt64): TUInt64; {* 确保 UInt64 值为大端,在小端环境中会进行转换} function UInt32ToBigEndian(Value: Cardinal): Cardinal; {* 确保 UInt32 值为大端,在小端环境中会进行转换} function UInt16ToBigEndian(Value: Word): Word; {* 确保 UInt16 值为大端,在小端环境中会进行转换} function UInt64ToLittleEndian(Value: TUInt64): TUInt64; {* 确保 UInt64 值为小端,在大端环境中会进行转换} function UInt32ToLittleEndian(Value: Cardinal): Cardinal; {* 确保 UInt32 值为小端,在大端环境中会进行转换} function UInt16ToLittleEndian(Value: Word): Word; {* 确保 UInt16 值为小端,在大端环境中会进行转换} function Int64HostToNetwork(Value: Int64): Int64; {* 将 Int64 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换} function Int32HostToNetwork(Value: Integer): Integer; {* 将 Int32 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换} function Int16HostToNetwork(Value: SmallInt): SmallInt; {* 将 Int16 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换} function Int64NetworkToHost(Value: Int64): Int64; {* 将 Int64 值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换} function Int32NetworkToHost(Value: Integer): Integer; {* 将 Int32值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换} function Int16NetworkToHost(Value: SmallInt): SmallInt; {* 将 Int16 值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换} function UInt64HostToNetwork(Value: TUInt64): TUInt64; {* 将 UInt64 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换} function UInt32HostToNetwork(Value: Cardinal): Cardinal; {* 将 UInt32 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换} function UInt16HostToNetwork(Value: Word): Word; {* 将 UInt16 值从主机字节顺序转换为网络字节顺序,在小端环境中会进行转换} function UInt64NetworkToHost(Value: TUInt64): TUInt64; {* 将 UInt64 值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换} function UInt32NetworkToHost(Value: Cardinal): Cardinal; {* 将 UInt32值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换} function UInt16NetworkToHost(Value: Word): Word; {* 将 UInt16 值从网络字节顺序转换为主机字节顺序,在小端环境中会进行转换} procedure ReverseMemory(AMem: Pointer; MemByteLen: Integer); {* 按字节顺序倒置一块内存块,字节内部不变} function ReverseBitsInInt8(V: Byte): Byte; {* 倒置一字节内容} function ReverseBitsInInt16(V: Word): Word; {* 倒置二字节内容} function ReverseBitsInInt32(V: Cardinal): Cardinal; {* 倒置四字节内容} function ReverseBitsInInt64(V: Int64): Int64; {* 倒置八字节内容} procedure ReverseMemoryWithBits(AMem: Pointer; MemByteLen: Integer); {* 按字节顺序倒置一块内存块,并且每个字节也倒过来} procedure MemoryAnd(AMem, BMem: Pointer; MemByteLen: Integer; ResMem: Pointer); {* 两块长度相同的内存 AMem 和 BMem 按位与,结果放 ResMem 中,三者可相同} procedure MemoryOr(AMem, BMem: Pointer; MemByteLen: Integer; ResMem: Pointer); {* 两块长度相同的内存 AMem 和 BMem 按位或,结果放 ResMem 中,三者可相同} procedure MemoryXor(AMem, BMem: Pointer; MemByteLen: Integer; ResMem: Pointer); {* 两块长度相同的内存 AMem 和 BMem 按位异或,结果放 ResMem 中,三者可相同} procedure MemoryNot(AMem: Pointer; MemByteLen: Integer; ResMem: Pointer); {* 一块内存 AMem 取反,结果放 ResMem 中,两者可相同} procedure MemoryShiftLeft(AMem, BMem: Pointer; MemByteLen: Integer; BitCount: Integer); {* AMem 整块内存左移 BitCount 位至 BMem,往内存地址低位移,空位补 0,两者可相等} procedure MemoryShiftRight(AMem, BMem: Pointer; MemByteLen: Integer; BitCount: Integer); {* AMem 整块内存右移 BitCount 位至 BMem,往内存地址高位移,空位补 0,两者可相等} function MemoryIsBitSet(AMem: Pointer; N: Integer): Boolean; {* 返回内存块某 Bit 位是否置 1,内存地址低位是 0,字节内还是右边为 0} procedure MemorySetBit(AMem: Pointer; N: Integer); {* 给内存块某 Bit 位置 1,内存地址低位是 0,字节内还是右边为 0} procedure MemoryClearBit(AMem: Pointer; N: Integer); {* 给内存块某 Bit 位置 0,内存地址低位是 0,字节内还是右边为 0} function MemoryToBinStr(AMem: Pointer; MemByteLen: Integer; Sep: Boolean = False): string; {* 将一块内存内容从低到高字节顺序输出为二进制字符串,Sep 表示是否空格分隔} procedure MemorySwap(AMem, BMem: Pointer; MemByteLen: Integer); {* 交换两块相同长度的内存块的内容,如两者是相同的内存块则什么都不做} function MemoryCompare(AMem, BMem: Pointer; MemByteLen: Integer): Integer; {* 以无符号数的方式比较两块内存,返回 1、0、-1,如两者是相同的内存块则直接返回 0} procedure MemoryQuickSort(Mem: Pointer; ElementByteSize: Integer; ElementCount: Integer; CompareProc: TCnMemSortCompareProc = nil); {* 针对固定大小的元素的数组进行排序} function UInt8ToBinStr(V: Byte): string; {* 将一无符号字节转换为二进制字符串} function UInt16ToBinStr(V: Word): string; {* 将一无符号字转换为二进制字符串} function UInt32ToBinStr(V: Cardinal): string; {* 将一四字节无符号整数转换为二进制字符串} function UInt32ToStr(V: Cardinal): string; {* 将一四字节无符号整数转换为字符串} function UInt64ToBinStr(V: TUInt64): string; {* 将一无符号 64 字节整数转换为二进制字符串} function HexToInt(const Hex: string): Integer; overload; {* 将一十六进制字符串转换为整型,适合较短尤其是 2 字符的字符串} function HexToInt(Hex: PChar; CharLen: Integer): Integer; overload; {* 将一十六进制字符串指针所指的内容转换为整型,适合较短尤其是 2 字符的字符串} function IsHexString(const Hex: string): Boolean; {* 判断一字符串是否合法的十六进制字符串,不区分大小写} function DataToHex(InData: Pointer; ByteLength: Integer; UseUpperCase: Boolean = True): string; {* 内存块转换为十六进制字符串,内存低位的内容出现在字符串左方,相当于网络字节顺序, UseUpperCase 控制输出内容的大小写} function HexToData(const Hex: string; OutData: Pointer = nil): Integer; {* 十六进制字符串转换为内存块,字符串左方的内容出现在内存低位,相当于网络字节顺序, 十六进制字符串长度为奇或转换失败时抛出异常。返回转换成功的字节数 注意 OutData 应该指向足够容纳转换内容的区域,长度至少为 Length(Hex) div 2 如果传 nil,则只返回所需的字节长度,不进行正式转换} function StringToHex(const Data: string; UseUpperCase: Boolean = True): string; {* 字符串转换为十六进制字符串,UseUpperCase 控制输出内容的大小写} function HexToString(const Hex: string): string; {* 十六进制字符串转换为字符串,十六进制字符串长度为奇或转换失败时抛出异常} function HexToAnsiStr(const Hex: AnsiString): AnsiString; {* 十六进制字符串转换为字符串,十六进制字符串长度为奇或转换失败时抛出异常} function BytesToHex(Data: TBytes; UseUpperCase: Boolean = True): string; {* 字节数组转换为十六进制字符串,下标低位的内容出现在字符串左方,相当于网络字节顺序, UseUpperCase 控制输出内容的大小写} function HexToBytes(const Hex: string): TBytes; {* 十六进制字符串转换为字节数组,字符串左边的内容出现在下标低位,相当于网络字节顺序, 字符串长度为奇或转换失败时抛出异常} procedure ReverseBytes(Data: TBytes); {* 按字节顺序倒置一字节数组} function StreamToBytes(Stream: TStream): TBytes; {* 从流从头读入全部内容至字节数组,返回创建的字节数组} function BytesToStream(Data: TBytes; OutStream: TStream): Integer; {* 字节数组写入整个流,返回写入字节数} procedure MoveMost(const Source; var Dest; ByteLen, MostLen: Integer); {* 从 Source 移动 ByteLen 且不超过 MostLen 个字节到 Dest 中, 如 ByteLen 小于 MostLen,则 Dest 填充 0,要求 Dest 容纳至少 MostLen} procedure ConstantTimeConditionalSwap8(CanSwap: Boolean; var A, B: Byte); {* 针对两个字节变量的执行时间固定的条件交换,CanSwap 为 True 时才实施 A B 交换} procedure ConstantTimeConditionalSwap16(CanSwap: Boolean; var A, B: Word); {* 针对两个双字节变量的执行时间固定的条件交换,CanSwap 为 True 时才实施 A B 交换} procedure ConstantTimeConditionalSwap32(CanSwap: Boolean; var A, B: Cardinal); {* 针对两个四字节变量的执行时间固定的条件交换,CanSwap 为 True 时才实施 A B 交换} procedure ConstantTimeConditionalSwap64(CanSwap: Boolean; var A, B: TUInt64); {* 针对两个八字节变量的执行时间固定的条件交换,CanSwap 为 True 时才实施 A B 交换} {$IFDEF MSWINDOWS} // 这四个函数因为用了 Intel 汇编,因而只支持 32 位和 64 位的 Intel CPU,照理应该用条件:CPUX86 或 CPUX64 procedure Int64DivInt32Mod(A: Int64; B: Integer; var DivRes, ModRes: Integer); {* 64 位有符号数除以 32 位有符号数,商放 DivRes,余数放 ModRes 调用者须自行保证商在 32 位范围内,否则会抛溢出异常} procedure UInt64DivUInt32Mod(A: TUInt64; B: Cardinal; var DivRes, ModRes: Cardinal); {* 64 位无符号数除以 32 位无符号数,商放 DivRes,余数放 ModRes 调用者须自行保证商在 32 位范围内,否则会抛溢出异常} procedure Int128DivInt64Mod(ALo, AHi: Int64; B: Int64; var DivRes, ModRes: Int64); {* 128 位有符号数除以 64 位有符号数,商放 DivRes,余数放 ModRes 调用者须自行保证商在 64 位范围内,否则会抛溢出异常} procedure UInt128DivUInt64Mod(ALo, AHi: TUInt64; B: TUInt64; var DivRes, ModRes: TUInt64); {* 128 位无符号数除以 64 位无符号数,商放 DivRes,余数放 ModRes 调用者须自行保证商在 64 位范围内,否则会抛溢出异常} {$ENDIF} function IsUInt128BitSet(Lo, Hi: TUInt64; N: Integer): Boolean; {* 针对两个 Int64 拼成的 128 位数字,返回第 N 位是否为 1,N 从 0 到 127} procedure SetUInt128Bit(var Lo, Hi: TUInt64; N: Integer); {* 针对两个 Int64 拼成的 128 位数字,设置第 N 位为 1,N 从 0 到 127} procedure ClearUInt128Bit(var Lo, Hi: TUInt64; N: Integer); {* 针对两个 Int64 拼成的 128 位数字,清掉第 N 位,N 从 0 到 127} function UnsignedAddWithLimitRadix(A, B, C: Cardinal; var R: Cardinal; L, H: Cardinal): Cardinal; {* 计算非正常进制的无符号加法,A + B + C,结果放 R 中,返回进位值 结果确保在 L 和 H 的闭区间内,用户须确保 H 大于 L,不考虑溢出的情形 该函数多用于字符分区间计算与映射,其中 C 一般是进位} implementation uses CnFloat; var FByteOrderIsBigEndian: Boolean = False; function CurrentByteOrderIsBigEndian: Boolean; type TByteOrder = packed record case Boolean of False: (C: array[0..1] of Byte); True: (W: Word); end; var T: TByteOrder; begin T.W := $00CC; Result := T.C[1] = $CC; end; function CurrentByteOrderIsLittleEndian: Boolean; begin Result := not CurrentByteOrderIsBigEndian; end; function SwapInt64(Value: Int64): Int64; var Lo, Hi: Cardinal; Rec: Int64Rec; begin Lo := Int64Rec(Value).Lo; Hi := Int64Rec(Value).Hi; Lo := ((Lo and $000000FF) shl 24) or ((Lo and $0000FF00) shl 8) or ((Lo and $00FF0000) shr 8) or ((Lo and $FF000000) shr 24); Hi := ((Hi and $000000FF) shl 24) or ((Hi and $0000FF00) shl 8) or ((Hi and $00FF0000) shr 8) or ((Hi and $FF000000) shr 24); Rec.Lo := Hi; Rec.Hi := Lo; Result := Int64(Rec); end; function SwapUInt64(Value: TUInt64): TUInt64; var Lo, Hi: Cardinal; Rec: Int64Rec; begin Lo := Int64Rec(Value).Lo; Hi := Int64Rec(Value).Hi; Lo := ((Lo and $000000FF) shl 24) or ((Lo and $0000FF00) shl 8) or ((Lo and $00FF0000) shr 8) or ((Lo and $FF000000) shr 24); Hi := ((Hi and $000000FF) shl 24) or ((Hi and $0000FF00) shl 8) or ((Hi and $00FF0000) shr 8) or ((Hi and $FF000000) shr 24); Rec.Lo := Hi; Rec.Hi := Lo; Result := TUInt64(Rec); end; function Int64ToBigEndian(Value: Int64): Int64; begin if FByteOrderIsBigEndian then Result := Value else Result := SwapInt64(Value); end; function Int32ToBigEndian(Value: Integer): Integer; begin if FByteOrderIsBigEndian then Result := Value else Result := Integer((Value and $000000FF) shl 24) or Integer((Value and $0000FF00) shl 8) or Integer((Value and $00FF0000) shr 8) or Integer((Value and $FF000000) shr 24); end; function Int16ToBigEndian(Value: SmallInt): SmallInt; begin if FByteOrderIsBigEndian then Result := Value else Result := SmallInt((Value and $00FF) shl 8) or SmallInt((Value and $FF00) shr 8); end; function Int64ToLittleEndian(Value: Int64): Int64; begin if not FByteOrderIsBigEndian then Result := Value else Result := SwapInt64(Value); end; function Int32ToLittleEndian(Value: Integer): Integer; begin if not FByteOrderIsBigEndian then Result := Value else Result := Integer((Value and $000000FF) shl 24) or Integer((Value and $0000FF00) shl 8) or Integer((Value and $00FF0000) shr 8) or Integer((Value and $FF000000) shr 24); end; function Int16ToLittleEndian(Value: SmallInt): SmallInt; begin if not FByteOrderIsBigEndian then Result := Value else Result := SmallInt((Value and $00FF) shl 8) or SmallInt((Value and $FF00) shr 8); end; function UInt64ToBigEndian(Value: TUInt64): TUInt64; begin if FByteOrderIsBigEndian then Result := Value else Result := SwapUInt64(Value); end; function UInt32ToBigEndian(Value: Cardinal): Cardinal; begin if FByteOrderIsBigEndian then Result := Value else Result := Cardinal((Value and $000000FF) shl 24) or Cardinal((Value and $0000FF00) shl 8) or Cardinal((Value and $00FF0000) shr 8) or Cardinal((Value and $FF000000) shr 24); end; function UInt16ToBigEndian(Value: Word): Word; begin if FByteOrderIsBigEndian then Result := Value else Result := Word((Value and $00FF) shl 8) or Word((Value and $FF00) shr 8); end; function UInt64ToLittleEndian(Value: TUInt64): TUInt64; begin if not FByteOrderIsBigEndian then Result := Value else Result := SwapUInt64(Value); end; function UInt32ToLittleEndian(Value: Cardinal): Cardinal; begin if not FByteOrderIsBigEndian then Result := Value else Result := Cardinal((Value and $000000FF) shl 24) or Cardinal((Value and $0000FF00) shl 8) or Cardinal((Value and $00FF0000) shr 8) or Cardinal((Value and $FF000000) shr 24); end; function UInt16ToLittleEndian(Value: Word): Word; begin if not FByteOrderIsBigEndian then Result := Value else Result := Word((Value and $00FF) shl 8) or Word((Value and $FF00) shr 8); end; function Int64HostToNetwork(Value: Int64): Int64; begin if not FByteOrderIsBigEndian then Result := SwapInt64(Value) else Result := Value; end; function Int32HostToNetwork(Value: Integer): Integer; begin if not FByteOrderIsBigEndian then Result := Integer((Value and $000000FF) shl 24) or Integer((Value and $0000FF00) shl 8) or Integer((Value and $00FF0000) shr 8) or Integer((Value and $FF000000) shr 24) else Result := Value; end; function Int16HostToNetwork(Value: SmallInt): SmallInt; begin if not FByteOrderIsBigEndian then Result := SmallInt((Value and $00FF) shl 8) or SmallInt((Value and $FF00) shr 8) else Result := Value; end; function Int64NetworkToHost(Value: Int64): Int64; begin if not FByteOrderIsBigEndian then REsult := SwapInt64(Value) else Result := Value; end; function Int32NetworkToHost(Value: Integer): Integer; begin if not FByteOrderIsBigEndian then Result := Integer((Value and $000000FF) shl 24) or Integer((Value and $0000FF00) shl 8) or Integer((Value and $00FF0000) shr 8) or Integer((Value and $FF000000) shr 24) else Result := Value; end; function Int16NetworkToHost(Value: SmallInt): SmallInt; begin if not FByteOrderIsBigEndian then Result := SmallInt((Value and $00FF) shl 8) or SmallInt((Value and $FF00) shr 8) else Result := Value; end; function UInt64HostToNetwork(Value: TUInt64): TUInt64; begin if CurrentByteOrderIsBigEndian then Result := Value else Result := SwapUInt64(Value); end; function UInt32HostToNetwork(Value: Cardinal): Cardinal; begin if not FByteOrderIsBigEndian then Result := Cardinal((Value and $000000FF) shl 24) or Cardinal((Value and $0000FF00) shl 8) or Cardinal((Value and $00FF0000) shr 8) or Cardinal((Value and $FF000000) shr 24) else Result := Value; end; function UInt16HostToNetwork(Value: Word): Word; begin if not FByteOrderIsBigEndian then Result := ((Value and $00FF) shl 8) or ((Value and $FF00) shr 8) else Result := Value; end; function UInt64NetworkToHost(Value: TUInt64): TUInt64; begin if CurrentByteOrderIsBigEndian then Result := Value else Result := SwapUInt64(Value); end; function UInt32NetworkToHost(Value: Cardinal): Cardinal; begin if not FByteOrderIsBigEndian then Result := Cardinal((Value and $000000FF) shl 24) or Cardinal((Value and $0000FF00) shl 8) or Cardinal((Value and $00FF0000) shr 8) or Cardinal((Value and $FF000000) shr 24) else Result := Value; end; function UInt16NetworkToHost(Value: Word): Word; begin if not FByteOrderIsBigEndian then Result := ((Value and $00FF) shl 8) or ((Value and $FF00) shr 8) else Result := Value; end; function ReverseBitsInInt8(V: Byte): Byte; begin // 0 和 1 交换、2 和 3 交换、4 和 5 交换、6 和 7 交换 V := ((V and $AA) shr 1) or ((V and $55) shl 1); // 01 和 23 交换、45 和 67 交换 V := ((V and $CC) shr 2) or ((V and $33) shl 2); // 0123 和 4567 交换 V := (V shr 4) or (V shl 4); Result := V; end; function ReverseBitsInInt16(V: Word): Word; begin Result := (ReverseBitsInInt8(V and $00FF) shl 8) or ReverseBitsInInt8((V and $FF00) shr 8); end; function ReverseBitsInInt32(V: Cardinal): Cardinal; begin Result := (ReverseBitsInInt16(V and $0000FFFF) shl 16) or ReverseBitsInInt16((V and $FFFF0000) shr 16); end; function ReverseBitsInInt64(V: Int64): Int64; begin Result := (Int64(ReverseBitsInInt32(V and $00000000FFFFFFFF)) shl 32) or ReverseBitsInInt32((V and $FFFFFFFF00000000) shr 32); end; procedure ReverseMemory(AMem: Pointer; MemByteLen: Integer); var I, L: Integer; P: PByteArray; T: Byte; begin if (AMem = nil) or (MemByteLen < 2) then Exit; L := MemByteLen div 2; P := PByteArray(AMem); for I := 0 to L - 1 do begin // 交换第 I 和第 MemLen - I - 1 T := P^[I]; P^[I] := P^[MemByteLen - I - 1]; P^[MemByteLen - I - 1] := T; end; end; procedure ReverseMemoryWithBits(AMem: Pointer; MemByteLen: Integer); var I: Integer; P: PByteArray; begin if (AMem = nil) or (MemByteLen <= 0) then Exit; ReverseMemory(AMem, MemByteLen); P := PByteArray(AMem); for I := 0 to MemByteLen - 1 do P^[I] := ReverseBitsInInt8(P^[I]); end; // N 字节长度的内存块的位操作 procedure MemoryBitOperation(AMem, BMem, RMem: Pointer; N: Integer; Op: TCnBitOperation); var A, B, R: PCnLongWord32Array; BA, BB, BR: PByteArray; begin if N <= 0 then Exit; if (AMem = nil) or ((BMem = nil) and (Op <> boNot)) or (RMem = nil) then Exit; A := PCnLongWord32Array(AMem); B := PCnLongWord32Array(BMem); R := PCnLongWord32Array(RMem); while (N and (not 3)) <> 0 do begin case Op of boAnd: R^[0] := A^[0] and B^[0]; boOr: R^[0] := A^[0] or B^[0]; boXor: R^[0] := A^[0] xor B^[0]; boNot: // 求反时忽略 B R^[0] := not A^[0]; end; A := PCnLongWord32Array(TCnNativeInt(A) + SizeOf(Cardinal)); B := PCnLongWord32Array(TCnNativeInt(B) + SizeOf(Cardinal)); R := PCnLongWord32Array(TCnNativeInt(R) + SizeOf(Cardinal)); Dec(N, SizeOf(Cardinal)); end; if N > 0 then begin BA := PByteArray(A); BB := PByteArray(B); BR := PByteArray(R); while N <> 0 do begin case Op of boAnd: BR^[0] := BA^[0] and BB^[0]; boOr: BR^[0] := BA^[0] or BB^[0]; boXor: BR^[0] := BA^[0] xor BB^[0]; boNot: BR^[0] := not BA^[0]; end; BA := PByteArray(TCnNativeInt(BA) + SizeOf(Byte)); BB := PByteArray(TCnNativeInt(BB) + SizeOf(Byte)); BR := PByteArray(TCnNativeInt(BR) + SizeOf(Byte)); Dec(N); end; end; end; procedure MemoryAnd(AMem, BMem: Pointer; MemByteLen: Integer; ResMem: Pointer); begin MemoryBitOperation(AMem, BMem, ResMem, MemByteLen, boAnd); end; procedure MemoryOr(AMem, BMem: Pointer; MemByteLen: Integer; ResMem: Pointer); begin MemoryBitOperation(AMem, BMem, ResMem, MemByteLen, boOr); end; procedure MemoryXor(AMem, BMem: Pointer; MemByteLen: Integer; ResMem: Pointer); begin MemoryBitOperation(AMem, BMem, ResMem, MemByteLen, boXor); end; procedure MemoryNot(AMem: Pointer; MemByteLen: Integer; ResMem: Pointer); begin MemoryBitOperation(AMem, nil, ResMem, MemByteLen, boNot); end; procedure MemoryShiftLeft(AMem, BMem: Pointer; MemByteLen: Integer; BitCount: Integer); var I, L, N, LB, RB: Integer; PF, PT: PByteArray; begin if (AMem = nil) or (MemByteLen <= 0) or (BitCount = 0) then Exit; if BitCount < 0 then begin MemoryShiftRight(AMem, BMem, MemByteLen, -BitCount); Exit; end; if BMem = nil then BMem := AMem; if (MemByteLen * 8) <= BitCount then // 移太多不够,全 0 begin FillChar(BMem^, MemByteLen, 0); Exit; end; N := BitCount div 8; // 移位超过的整字节数 RB := BitCount mod 8; // 去除整字节后剩下的位数 LB := 8 - RB; // 上面剩下的位数在一字节内再剩下的位数 PF := PByteArray(AMem); PT := PByteArray(BMem); if RB = 0 then // 整块,好办,要移位的字节数是 MemLen - NW begin Move(PF^[N], PT^[0], MemByteLen - N); FillChar(PT^[MemByteLen - N], N, 0); end else begin // 起点是 PF^[N] 和 PT^[0],长度 MemLen - N 个字节,但相邻字节间有交叉 L := MemByteLen - N; PF := PByteArray(TCnNativeInt(PF) + N); for I := 1 to L do // 从低位往低移动,先处理低的 begin PT^[0] := Byte(PF^[0] shl RB); if I < L then // 最高一个字节 PF^[1] 会超界 PT^[0] := (PF^[1] shr LB) or PT^[0]; PF := PByteArray(TCnNativeInt(PF) + 1); PT := PByteArray(TCnNativeInt(PT) + 1); end; // 剩下的要填 0 if N > 0 then FillChar(PT^[0], N, 0); end; end; procedure MemoryShiftRight(AMem, BMem: Pointer; MemByteLen: Integer; BitCount: Integer); var I, L, N, LB, RB: Integer; PF, PT: PByteArray; begin if (AMem = nil) or (MemByteLen <= 0) or (BitCount = 0) then Exit; if BitCount < 0 then begin MemoryShiftLeft(AMem, BMem, MemByteLen, -BitCount); Exit; end; if BMem = nil then BMem := AMem; if (MemByteLen * 8) <= BitCount then // 移太多不够,全 0 begin FillChar(BMem^, MemByteLen, 0); Exit; end; N := BitCount div 8; // 移位超过的整字节数 RB := BitCount mod 8; // 去除整字节后剩下的位数 LB := 8 - RB; // 上面剩下的位数在一字节内再剩下的位数 if RB = 0 then // 整块,好办,要移位的字节数是 MemLen - N begin PF := PByteArray(AMem); PT := PByteArray(BMem); Move(PF^[0], PT^[N], MemByteLen - N); FillChar(PT^[0], N, 0); end else begin // 起点是 PF^[0] 和 PT^[N],长度 MemLen - N 个字节,但得从高处开始,且相邻字节间有交叉 L := MemByteLen - N; PF := PByteArray(TCnNativeInt(AMem) + L - 1); PT := PByteArray(TCnNativeInt(BMem) + MemByteLen - 1); for I := L downto 1 do // 从高位往高位移动,先处理后面的 begin PT^[0] := Byte(PF^[0] shr RB); if I > 1 then // 最低一个字节 PF^[-1] 会超界 begin PF := PByteArray(TCnNativeInt(PF) - 1); PT^[0] := (PF^[0] shl LB) or PT^[0]; end else PF := PByteArray(TCnNativeInt(PF) - 1); PT := PByteArray(TCnNativeInt(PT) - 1); end; // 剩下的最前面的要填 0 if N > 0 then FillChar(BMem^, N, 0); end; end; function MemoryIsBitSet(AMem: Pointer; N: Integer): Boolean; var P: PByte; A, B: Integer; V: Byte; begin if (AMem = nil) or (N < 0) then raise Exception.Create(SRangeError); A := N div 8; B := N mod 8; P := PByte(TCnNativeInt(AMem) + A); V := Byte(1 shl B); Result := (P^ and V) <> 0; end; procedure MemorySetBit(AMem: Pointer; N: Integer); var P: PByte; A, B: Integer; V: Byte; begin if (AMem = nil) or (N < 0) then raise Exception.Create(SRangeError); A := N div 8; B := N mod 8; P := PByte(TCnNativeInt(AMem) + A); V := Byte(1 shl B); P^ := P^ or V; end; procedure MemoryClearBit(AMem: Pointer; N: Integer); var P: PByte; A, B: Integer; V: Byte; begin if (AMem = nil) or (N < 0) then raise Exception.Create(SRangeError); A := N div 8; B := N mod 8; P := PByte(TCnNativeInt(AMem) + A); V := not Byte(1 shl B); P^ := P^ and V; end; function MemoryToBinStr(AMem: Pointer; MemByteLen: Integer; Sep: Boolean): string; var J, L: Integer; P: PByteArray; B: PChar; procedure FillAByteToBuf(V: Byte; Buf: PChar); const M = $80; var I: Integer; begin for I := 0 to 7 do begin if (V and M) <> 0 then Buf[I] := '1' else Buf[I] := '0'; V := V shl 1; end; end; begin Result := ''; if (AMem = nil) or (MemByteLen <= 0) then Exit; L := MemByteLen * 8; if Sep then L := L + MemByteLen - 1; // 中间用空格分隔 SetLength(Result, L); B := PChar(@Result[1]); P := PByteArray(AMem); for J := 0 to MemByteLen - 1 do begin FillAByteToBuf(P^[J], B); if Sep then begin B[8] := ' '; Inc(B, 9); end else Inc(B, 8); end; end; procedure MemorySwap(AMem, BMem: Pointer; MemByteLen: Integer); var A, B: PCnLongWord32Array; BA, BB: PByteArray; TC: Cardinal; TB: Byte; begin if (AMem = nil) or (BMem = nil) or (MemByteLen <= 0) then Exit; A := PCnLongWord32Array(AMem); B := PCnLongWord32Array(BMem); if A = B then Exit; while (MemByteLen and (not 3)) <> 0 do begin TC := A^[0]; A^[0] := B^[0]; B^[0] := TC; A := PCnLongWord32Array(TCnNativeInt(A) + SizeOf(Cardinal)); B := PCnLongWord32Array(TCnNativeInt(B) + SizeOf(Cardinal)); Dec(MemByteLen, SizeOf(Cardinal)); end; if MemByteLen > 0 then begin BA := PByteArray(A); BB := PByteArray(B); while MemByteLen <> 0 do begin TB := BA^[0]; BA^[0] := BB^[0]; BB^[0] :=TB; BA := PByteArray(TCnNativeInt(BA) + SizeOf(Byte)); BB := PByteArray(TCnNativeInt(BB) + SizeOf(Byte)); Dec(MemByteLen); end; end; end; function MemoryCompare(AMem, BMem: Pointer; MemByteLen: Integer): Integer; var A, B: PCnLongWord32Array; BA, BB: PByteArray; begin Result := 0; if ((AMem = nil) and (BMem = nil)) or (AMem = BMem) then // 同一块 Exit; if MemByteLen <= 0 then Exit; if AMem = nil then begin Result := -1; Exit; end; if BMem = nil then begin Result := 1; Exit; end; A := PCnLongWord32Array(AMem); B := PCnLongWord32Array(BMem); while (MemByteLen and (not 3)) <> 0 do begin if A^[0] > B^[0] then begin Result := 1; Exit; end else if A^[0] < B^[0] then begin Result := -1; Exit; end; A := PCnLongWord32Array(TCnNativeInt(A) + SizeOf(Cardinal)); B := PCnLongWord32Array(TCnNativeInt(B) + SizeOf(Cardinal)); Dec(MemByteLen, SizeOf(Cardinal)); end; if MemByteLen > 0 then begin BA := PByteArray(A); BB := PByteArray(B); while MemByteLen <> 0 do begin if BA^[0] > BB^[0] then begin Result := 1; Exit; end else if BA^[0] < BB^[0] then begin Result := -1; Exit; end; BA := PByteArray(TCnNativeInt(BA) + SizeOf(Byte)); BB := PByteArray(TCnNativeInt(BB) + SizeOf(Byte)); Dec(MemByteLen); end; end; end; function UInt8ToBinStr(V: Byte): string; const M = $80; var I: Integer; begin SetLength(Result, 8 * SizeOf(V)); for I := 1 to 8 * SizeOf(V) do begin if (V and M) <> 0 then Result[I] := '1' else Result[I] := '0'; V := V shl 1; end; end; function UInt16ToBinStr(V: Word): string; const M = $8000; var I: Integer; begin SetLength(Result, 8 * SizeOf(V)); for I := 1 to 8 * SizeOf(V) do begin if (V and M) <> 0 then Result[I] := '1' else Result[I] := '0'; V := V shl 1; end; end; function UInt32ToBinStr(V: Cardinal): string; const M = $80000000; var I: Integer; begin SetLength(Result, 8 * SizeOf(V)); for I := 1 to 8 * SizeOf(V) do begin if (V and M) <> 0 then Result[I] := '1' else Result[I] := '0'; V := V shl 1; end; end; function UInt32ToStr(V: Cardinal): string; begin Result := Format('%u', [V]); end; function UInt64ToBinStr(V: TUInt64): string; const M = $8000000000000000; var I: Integer; begin SetLength(Result, 8 * SizeOf(V)); for I := 1 to 8 * SizeOf(V) do begin if (V and M) <> 0 then Result[I] := '1' else Result[I] := '0'; V := V shl 1; end; end; const HiDigits: array[0..15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); const LoDigits: array[0..15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); function HexToInt(Hex: PChar; CharLen: Integer): Integer; var I, Res: Integer; C: Char; begin Res := 0; for I := 0 to CharLen - 1 do begin C := Hex[I]; if (C >= '0') and (C <= '9') then Res := Res * 16 + Ord(C) - Ord('0') else if (C >= 'A') and (C <= 'F') then Res := Res * 16 + Ord(C) - Ord('A') + 10 else if (C >= 'a') and (C <= 'f') then Res := Res * 16 + Ord(C) - Ord('a') + 10 else raise Exception.CreateFmt('Error: not a Hex PChar: %c', [C]); end; Result := Res; end; function HexToInt(const Hex: string): Integer; begin Result := HexToInt(PChar(Hex), Length(Hex)); end; {$WARNINGS OFF} function IsHexString(const Hex: string): Boolean; var I, L: Integer; begin Result := False; L := Length(Hex); if (L <= 0) or ((L and 1) <> 0) then // 空或非偶长度都不是 Exit; for I := 1 to L do begin // 注意此处 Unicode 下虽然有 Warning,但并不是将 Hex[I] 这个 WideChar 直接截断至 AnsiChar // 后再进行判断(那样会导致“晦晦”这种 $66$66$66$66 的字符串出现误判),而是 // 直接通过 WideChar 的值(在 ax 中因而是双字节的)加减来判断,不会出现误判 if not (Hex[I] in ['0'..'9', 'A'..'F', 'a'..'f']) then Exit; end; Result := True; end; {$WARNINGS ON} function DataToHex(InData: Pointer; ByteLength: Integer; UseUpperCase: Boolean = True): string; var I: Integer; B: Byte; begin Result := ''; if ByteLength <= 0 then Exit; SetLength(Result, ByteLength * 2); if UseUpperCase then begin for I := 0 to ByteLength - 1 do begin B := PByte(TCnNativeInt(InData) + I * SizeOf(Byte))^; Result[I * 2 + 1] := HiDigits[(B shr 4) and $0F]; Result[I * 2 + 2] := HiDigits[B and $0F]; end; end else begin for I := 0 to ByteLength - 1 do begin B := PByte(TCnNativeInt(InData) + I * SizeOf(Byte))^; Result[I * 2 + 1] := LoDigits[(B shr 4) and $0F]; Result[I * 2 + 2] := LoDigits[B and $0F]; end; end; end; function HexToData(const Hex: string; OutData: Pointer): Integer; var I, L: Integer; H: PChar; begin L := Length(Hex); if (L mod 2) <> 0 then raise Exception.CreateFmt('Error Length %d: not a Hex String', [L]); if OutData = nil then begin Result := L div 2; Exit; end; Result := 0; H := PChar(Hex); for I := 1 to L div 2 do begin PByte(TCnNativeInt(OutData) + I - 1)^ := Byte(HexToInt(@H[(I - 1) * 2], 2)); Inc(Result); end; end; function StringToHex(const Data: string; UseUpperCase: Boolean): string; var I, L: Integer; B: Byte; Buffer: PChar; begin Result := ''; L := Length(Data); if L = 0 then Exit; SetLength(Result, L * 2); Buffer := @Data[1]; if UseUpperCase then begin for I := 0 to L - 1 do begin B := PByte(TCnNativeInt(Buffer) + I * SizeOf(Char))^; Result[I * 2 + 1] := HiDigits[(B shr 4) and $0F]; Result[I * 2 + 2] := HiDigits[B and $0F]; end; end else begin for I := 0 to L - 1 do begin B := PByte(TCnNativeInt(Buffer) + I * SizeOf(Char))^; Result[I * 2 + 1] := LoDigits[(B shr 4) and $0F]; Result[I * 2 + 2] := LoDigits[B and $0F]; end; end; end; function HexToString(const Hex: string): string; var I, L: Integer; H: PChar; begin L := Length(Hex); if (L mod 2) <> 0 then raise Exception.CreateFmt('Error Length %d: not a Hex String', [L]); SetLength(Result, L div 2); H := PChar(Hex); for I := 1 to L div 2 do Result[I] := Chr(HexToInt(@H[(I - 1) * 2], 2)); end; function HexToAnsiStr(const Hex: AnsiString): AnsiString; var I, L: Integer; S: string; begin L := Length(Hex); if (L mod 2) <> 0 then raise Exception.CreateFmt('Error Length %d: not a Hex AnsiString', [L]); SetLength(Result, L div 2); for I := 1 to L div 2 do begin S := string(Copy(Hex, I * 2 - 1, 2)); Result[I] := AnsiChar(Chr(HexToInt(S))); end; end; function BytesToHex(Data: TBytes; UseUpperCase: Boolean): string; var I, L: Integer; B: Byte; Buffer: PAnsiChar; begin Result := ''; L := Length(Data); if L = 0 then Exit; SetLength(Result, L * 2); Buffer := @Data[0]; if UseUpperCase then begin for I := 0 to L - 1 do begin B := PByte(TCnNativeInt(Buffer) + I)^; Result[I * 2 + 1] := HiDigits[(B shr 4) and $0F]; Result[I * 2 + 2] := HiDigits[B and $0F]; end; end else begin for I := 0 to L - 1 do begin B := PByte(TCnNativeInt(Buffer) + I)^; Result[I * 2 + 1] := LoDigits[(B shr 4) and $0F]; Result[I * 2 + 2] := LoDigits[B and $0F]; end; end; end; function HexToBytes(const Hex: string): TBytes; var I, L: Integer; H: PChar; begin L := Length(Hex); if (L mod 2) <> 0 then raise Exception.CreateFmt('Error Length %d: not a Hex String', [L]); SetLength(Result, L div 2); H := PChar(Hex); for I := 1 to L div 2 do Result[I - 1] := Byte(HexToInt(@H[(I - 1) * 2], 2)); end; procedure ReverseBytes(Data: TBytes); var I, L, M: Integer; T: Byte; begin if (Data = nil) or (Length(Data) <= 1) then Exit; L := Length(Data); M := L div 2; for I := 0 to M - 1 do begin // 交换 I 和 L - I - 1 T := Data[I]; Data[I] := Data[L - I - 1]; Data[L - I - 1] := T; end; end; function StreamToBytes(Stream: TStream): TBytes; begin Result := nil; if (Stream <> nil) and (Stream.Size > 0) then begin SetLength(Result, Stream.Size); Stream.Position := 0; Stream.Read(Result[0], Stream.Size); end; end; function BytesToStream(Data: TBytes; OutStream: TStream): Integer; begin Result := 0; if (Data <> nil) and (Length(Data) > 0) and (OutStream <> nil) then begin OutStream.Size := 0; Result := OutStream.Write(Data[0], Length(Data)); end; end; procedure MoveMost(const Source; var Dest; ByteLen, MostLen: Integer); begin if MostLen <= 0 then Exit; if ByteLen > MostLen then ByteLen := MostLen else if ByteLen < MostLen then FillChar(Dest, MostLen, 0); Move(Source, Dest, ByteLen); end; procedure ConstantTimeConditionalSwap8(CanSwap: Boolean; var A, B: Byte); var T, V: Byte; begin if CanSwap then T := $FF else T := 0; V := (A xor B) and T; A := A xor V; B := B xor V; end; procedure ConstantTimeConditionalSwap16(CanSwap: Boolean; var A, B: Word); var T, V: Word; begin if CanSwap then T := $FFFF else T := 0; V := (A xor B) and T; A := A xor V; B := B xor V; end; procedure ConstantTimeConditionalSwap32(CanSwap: Boolean; var A, B: Cardinal); var T, V: Cardinal; begin if CanSwap then T := $FFFFFFFF else T := 0; V := (A xor B) and T; A := A xor V; B := B xor V; end; procedure ConstantTimeConditionalSwap64(CanSwap: Boolean; var A, B: TUInt64); var T, V: TUInt64; begin if CanSwap then begin {$IFDEF SUPPORT_UINT64} T := $FFFFFFFFFFFFFFFF; {$ELSE} T := not 0; {$ENDIF} end else T := 0; V := (A xor B) and T; A := A xor V; B := B xor V; end; {$IFDEF MSWINDOWS} {$IFDEF CPUX64} // 64 位汇编用 IDIV 和 IDIV 指令实现,其中 A 在 RCX 里,B 在 EDX/RDX 里,DivRes 地址在 R8 里,ModRes 地址在 R9 里 procedure Int64DivInt32Mod(A: Int64; B: Integer; var DivRes, ModRes: Integer); assembler; asm PUSH RCX // RCX 是 A MOV RCX, RDX // 除数 B 放入 RCX POP RAX // 被除数 A 放入 RAX XOR RDX, RDX // 被除数高 64 位清零 IDIV RCX MOV [R8], EAX // 商放入 R8 所指的 DivRes MOV [R9], EDX // 余数放入 R9 所指的 ModRes end; procedure UInt64DivUInt32Mod(A: TUInt64; B: Cardinal; var DivRes, ModRes: Cardinal); assembler; asm PUSH RCX // RCX 是 A MOV RCX, RDX // 除数 B 放入 RCX POP RAX // 被除数 A 放入 RAX XOR RDX, RDX // 被除数高 64 位清零 DIV RCX MOV [R8], EAX // 商放入 R8 所指的 DivRes MOV [R9], EDX // 余数放入 R9 所指的 ModRes end; // 64 位汇编用 IDIV 和 IDIV 指令实现,ALo 在 RCX,AHi 在 RDX,B 在 R8,DivRes 的地址在 R9, procedure Int128DivInt64Mod(ALo, AHi: Int64; B: Int64; var DivRes, ModRes: Int64); assembler; asm MOV RAX, RCX // ALo 放入 RAX,AHi 已经在 RDX 了 MOV RCX, R8 // B 放入 RCX IDIV RCX MOV [R9], RAX // 商放入 R9 所指的 DivRes MOV RAX, [RBP + $30] // ModRes 地址放入 RAX MOV [RAX], RDX // 余数放入 RAX 所指的 ModRes end; procedure UInt128DivUInt64Mod(ALo, AHi: UInt64; B: UInt64; var DivRes, ModRes: UInt64); assembler; asm MOV RAX, RCX // ALo 放入 RAX,AHi 已经在 RDX 了 MOV RCX, R8 // B 放入 RCX DIV RCX MOV [R9], RAX // 商放入 R9 所指的 DivRes MOV RAX, [RBP + $30] // ModRes 地址放入 RAX MOV [RAX], RDX // 余数放入 RAX 所指的 ModRes end; {$ELSE} // 32 位汇编用 IDIV 和 IDIV 指令实现,其中 A 在堆栈上,B 在 EAX,DivRes 地址在 EDX,ModRes 地址在 ECX procedure Int64DivInt32Mod(A: Int64; B: Integer; var DivRes, ModRes: Integer); assembler; asm PUSH ECX // ECX 是 ModRes 地址,先保存 MOV ECX, B // B 在 EAX 中,搬移到 ECX 中 PUSH EDX // DivRes 的地址在 EDX 中,也保存 MOV EAX, [EBP + $8] // A Lo MOV EDX, [EBP + $C] // A Hi IDIV ECX POP ECX // 弹出 ECX,拿到 DivRes 地址 MOV [ECX], EAX POP ECX // 弹出 ECX,拿到 ModRes 地址 MOV [ECX], EDX end; procedure UInt64DivUInt32Mod(A: TUInt64; B: Cardinal; var DivRes, ModRes: Cardinal); assembler; asm PUSH ECX // ECX 是 ModRes 地址,先保存 MOV ECX, B // B 在 EAX 中,搬移到 ECX 中 PUSH EDX // DivRes 的地址在 EDX 中,也保存 MOV EAX, [EBP + $8] // A Lo MOV EDX, [EBP + $C] // A Hi DIV ECX POP ECX // 弹出 ECX,拿到 DivRes 地址 MOV [ECX], EAX POP ECX // 弹出 ECX,拿到 ModRes 地址 MOV [ECX], EDX end; // 32 位下的实现 procedure Int128DivInt64Mod(ALo, AHi: Int64; B: Int64; var DivRes, ModRes: Int64); var C: Integer; begin if B = 0 then raise EDivByZero.Create(SDivByZero); if (AHi = 0) or (AHi = $FFFFFFFFFFFFFFFF) then // 高 64 位为 0 的正值或负值 begin DivRes := ALo div B; ModRes := ALo mod B; end else begin if B < 0 then // 除数是负数 begin Int128DivInt64Mod(ALo, AHi, -B, DivRes, ModRes); DivRes := -DivRes; Exit; end; if AHi < 0 then // 被除数是负数 begin // AHi, ALo 求反加 1,以得到正值 AHi := not AHi; ALo := not ALo; {$IFDEF SUPPORT_UINT64} UInt64Add(UInt64(ALo), UInt64(ALo), 1, C); {$ELSE} UInt64Add(ALo, ALo, 1, C); {$ENDIF} if C > 0 then AHi := AHi + C; // 被除数转正了 Int128DivInt64Mod(ALo, AHi, B, DivRes, ModRes); // 结果再调整 if ModRes = 0 then DivRes := -DivRes else begin DivRes := -DivRes - 1; ModRes := B - ModRes; end; Exit; end; // 全正后,按无符号来除 {$IFDEF SUPPORT_UINT64} UInt128DivUInt64Mod(TUInt64(ALo), TUInt64(AHi), TUInt64(B), TUInt64(DivRes), TUInt64(ModRes)); {$ELSE} UInt128DivUInt64Mod(ALo, AHi, B, DivRes, ModRes); {$ENDIF} end; end; procedure UInt128DivUInt64Mod(ALo, AHi: TUInt64; B: TUInt64; var DivRes, ModRes: TUInt64); var I, Cnt: Integer; Q, R: TUInt64; begin if B = 0 then raise EDivByZero.Create(SDivByZero); if AHi = 0 then begin DivRes := UInt64Div(ALo, B); ModRes := UInt64Mod(ALo, B); end else begin // 有高位有低位咋办?先判断是否会溢出,如果 AHi >= B,则表示商要超 64 位,溢出 if UInt64Compare(AHi, B) >= 0 then raise Exception.Create(SIntOverflow); Q := 0; R := 0; Cnt := GetUInt64LowBits(AHi) + 64; for I := Cnt downto 0 do begin R := R shl 1; if IsUInt128BitSet(ALo, AHi, I) then // 被除数的第 I 位是否是 0 R := R or 1 else R := R and TUInt64(not 1); if UInt64Compare(R, B) >= 0 then begin R := R - B; Q := Q or (TUInt64(1) shl I); end; end; DivRes := Q; ModRes := R; end; end; {$ENDIF} {$ENDIF} {$IFDEF SUPPORT_UINT64} // 只要支持 64 位无符号整数,无论 32/64 位 Intel 还是 ARM,无论 Delphi 还是 FPC,无论什么操作系统都能如此 function UInt64Mod(A, B: TUInt64): TUInt64; begin Result := A mod B; end; function UInt64Div(A, B: TUInt64): TUInt64; begin Result := A div B; end; {$ELSE} { 不支持 UInt64 的低版本 Delphi 下用 Int64 求 A mod/div B 调用的入栈顺序是 A 的高位,A 的低位,B 的高位,B 的低位。挨个 push 完毕并进入函数后, ESP 是返回地址,ESP+4 是 B 的低位,ESP + 8 是 B 的高位,ESP + C 是 A 的低位,ESP + 10 是 A 的高位 进入后 push esp 让 ESP 减了 4,然后 mov ebp esp,之后用 EBP 来寻址,全要多加 4 而 System.@_llumod 要求在刚进入时,EAX <- A 的低位,EDX <- A 的高位,(System 源码注释中 EAX/EDX 写反了) [ESP + 8](也就是 EBP + C)<- B 的高位,[ESP + 4] (也就是 EBP + 8)<- B 的低位 所以 CALL 前加了四句搬移代码。UInt64 Div 的也类似 } function UInt64Mod(A, B: TUInt64): TUInt64; asm // PUSH ESP 让 ESP 减了 4,要补上 MOV EAX, [EBP + $10] // A Lo MOV EDX, [EBP + $14] // A Hi PUSH DWORD PTR[EBP + $C] // B Hi PUSH DWORD PTR[EBP + $8] // B Lo CALL System.@_llumod; end; function UInt64Div(A, B: TUInt64): TUInt64; asm // PUSH ESP 让 ESP 减了 4,要补上 MOV EAX, [EBP + $10] // A Lo MOV EDX, [EBP + $14] // A Hi PUSH DWORD PTR[EBP + $C] // B Hi PUSH DWORD PTR[EBP + $8] // B Lo CALL System.@_lludiv; end; {$ENDIF} {$IFDEF SUPPORT_UINT64} // 只要支持 64 位无符号整数,无论 32/64 位 Intel 还是 ARM,无论 Delphi 还是 FPC,无论什么操作系统都能如此 function UInt64Mul(A, B: Cardinal): TUInt64; begin Result := TUInt64(A) * B; end; {$ELSE} // 只有低版本 Delphi 会进这里,Win32 x86 { 无符号 32 位整数相乘,如果结果直接使用 Int64 会溢出,模拟 64 位无符号运算 调用寄存器约定是 A -> EAX,B -> EDX,不使用堆栈 而 System.@_llmul 要求在刚进入时,EAX <- A 的低位,EDX <- A 的高位 0, [ESP + 8](也就是 EBP + C)<- B 的高位 0,[ESP + 4] (也就是 EBP + 8)<- B 的低位 } function UInt64Mul(A, B: Cardinal): TUInt64; asm PUSH 0 // PUSH B 高位 0 PUSH EDX // PUSH B 低位 // EAX A 低位,已经是了 XOR EDX, EDX // EDX A 高位 0 CALL System.@_llmul; // 返回 EAX 低 32 位、EDX 高 32 位 end; {$ENDIF} // 两个无符号 64 位整数相加,处理溢出的情况,结果放 ResLo 与 ResHi 中 procedure UInt64AddUInt64(A, B: TUInt64; var ResLo, ResHi: TUInt64); var X, Y, Z, T, R0L, R0H, R1L, R1H: Cardinal; R0, R1, R01, R12: TUInt64; begin // 基本思想:2^32 是系数 M,拆成 (xM+y) + (zM+t) = (x+z) M + (y+t) // y+t 是 R0 占 0、1,x+z 是 R1 占 1、2,把 R0, R1 再拆开相加成 R01, R12 if IsUInt64AddOverflow(A, B) then begin X := Int64Rec(A).Hi; Y := Int64Rec(A).Lo; Z := Int64Rec(B).Hi; T := Int64Rec(B).Lo; R0 := TUInt64(Y) + TUInt64(T); R1 := TUInt64(X) + TUInt64(Z); R0L := Int64Rec(R0).Lo; R0H := Int64Rec(R0).Hi; R1L := Int64Rec(R1).Lo; R1H := Int64Rec(R1).Hi; R01 := TUInt64(R0H) + TUInt64(R1L); R12 := TUInt64(R1H) + TUInt64(Int64Rec(R01).Hi); Int64Rec(ResLo).Lo := R0L; Int64Rec(ResLo).Hi := Int64Rec(R01).Lo; Int64Rec(ResHi).Lo := Int64Rec(R12).Lo; Int64Rec(ResHi).Hi := Int64Rec(R12).Hi; end else begin ResLo := A + B; ResHi := 0; end; end; {$IFDEF WIN64} // 注意 Linux 64 下不支持 ASM,只能 WIN64 // 64 位下两个无符号 64 位整数相乘,结果放 ResLo 与 ResHi 中,直接用汇编实现,比下面快了一倍以上 procedure UInt64MulUInt64(A, B: UInt64; var ResLo, ResHi: UInt64); assembler; asm PUSH RAX MOV RAX, RCX MUL RDX // 得用无符号,不能用有符号的 IMUL MOV [R8], RAX MOV [R9], RDX POP RAX end; {$ELSE} // 两个无符号 64 位整数相乘,结果放 ResLo 与 ResHi 中 procedure UInt64MulUInt64(A, B: TUInt64; var ResLo, ResHi: TUInt64); var X, Y, Z, T: Cardinal; YT, XT, ZY, ZX: TUInt64; P, R1Lo, R1Hi, R2Lo, R2Hi: TUInt64; begin // 基本思想:2^32 是系数 M,拆成 (xM+y)*(zM+t) = xzM^2 + (xt+yz)M + yt // 各项系数都是 UInt64,xz 占 2、3、4,xt+yz 占 1、2、3,yt 占 0、1,然后累加 X := Int64Rec(A).Hi; Y := Int64Rec(A).Lo; Z := Int64Rec(B).Hi; T := Int64Rec(B).Lo; YT := UInt64Mul(Y, T); XT := UInt64Mul(X, T); ZY := UInt64Mul(Y, Z); ZX := UInt64Mul(X, Z); Int64Rec(ResLo).Lo := Int64Rec(YT).Lo; P := Int64Rec(YT).Hi; UInt64AddUInt64(P, XT, R1Lo, R1Hi); UInt64AddUInt64(ZY, R1Lo, R2Lo, R2Hi); Int64Rec(ResLo).Hi := Int64Rec(R2Lo).Lo; P := TUInt64(Int64Rec(R2Lo).Hi) + TUInt64(Int64Rec(ZX).Lo); Int64Rec(ResHi).Lo := Int64Rec(P).Lo; Int64Rec(ResHi).Hi := Int64Rec(R1Hi).Lo + Int64Rec(R2Hi).Lo + Int64Rec(ZX).Hi + Int64Rec(P).Hi; end; {$ENDIF} {$HINTS OFF} function _ValUInt64(const S: string; var Code: Integer): TUInt64; const FirstIndex = 1; var I: Integer; Dig: Integer; Sign: Boolean; Empty: Boolean; begin I := FirstIndex; Dig := 0; // To avoid warning Result := 0; if S = '' then begin Code := 1; Exit; end; while S[I] = Char(' ') do Inc(I); Sign := False; if S[I] = Char('-') then begin Sign := True; Inc(I); end else if S[I] = Char('+') then Inc(I); Empty := True; if (S[I] = Char('$')) or (UpCase(S[I]) = Char('X')) or ((S[I] = Char('0')) and (I < Length(S)) and (UpCase(S[I+1]) = Char('X'))) then begin if S[I] = Char('0') then Inc(I); Inc(I); while True do begin case Char(S[I]) of Char('0').. Char('9'): Dig := Ord(S[I]) - Ord('0'); Char('A').. Char('F'): Dig := Ord(S[I]) - (Ord('A') - 10); Char('a').. Char('f'): Dig := Ord(S[I]) - (Ord('a') - 10); else Break; end; if Result > (CN_MAX_TUINT64 shr 4) then Break; if Sign and (Dig <> 0) then Break; Result := Result shl 4 + TUInt64(Dig); Inc(I); Empty := False; end; end else begin while True do begin case Char(S[I]) of Char('0').. Char('9'): Dig := Ord(S[I]) - Ord('0'); else Break; end; if Result > UInt64Div(CN_MAX_TUINT64, 10) then Break; if Sign and (Dig <> 0) then Break; Result := Result * 10 + TUInt64(Dig); Inc(I); Empty := False; end; end; if (S[I] <> Char(#0)) or Empty then Code := I + 1 - FirstIndex else Code := 0; end; {$HINTS ON} function UInt64ToHex(N: TUInt64): string; const Digits: array[0..15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); function HC(B: Byte): string; begin Result := string(Digits[(B shr 4) and $0F] + Digits[B and $0F]); end; begin Result := HC(Byte((N and $FF00000000000000) shr 56)) + HC(Byte((N and $00FF000000000000) shr 48)) + HC(Byte((N and $0000FF0000000000) shr 40)) + HC(Byte((N and $000000FF00000000) shr 32)) + HC(Byte((N and $00000000FF000000) shr 24)) + HC(Byte((N and $0000000000FF0000) shr 16)) + HC(Byte((N and $000000000000FF00) shr 8)) + HC(Byte((N and $00000000000000FF))); end; function UInt64ToStr(N: TUInt64): string; begin Result := Format('%u', [N]); end; function StrToUInt64(const S: string): TUInt64; {$IFNDEF DELPHIXE6_UP} var E: Integer; {$ENDIF} begin {$IFDEF DELPHIXE6_UP} Result := SysUtils.StrToUInt64(S); // StrToUInt64 only exists under XE6 or above {$ELSE} Result := _ValUInt64(S, E); if E <> 0 then raise EConvertError.CreateResFmt(@SInvalidInteger, [S]); {$ENDIF} end; function UInt64Compare(A, B: TUInt64): Integer; {$IFNDEF SUPPORT_UINT64} var HiA, HiB, LoA, LoB: LongWord; {$ENDIF} begin {$IFDEF SUPPORT_UINT64} if A > B then Result := 1 else if A < B then Result := -1 else Result := 0; {$ELSE} HiA := (A and $FFFFFFFF00000000) shr 32; HiB := (B and $FFFFFFFF00000000) shr 32; if HiA > HiB then Result := 1 else if HiA < HiB then Result := -1 else begin LoA := LongWord(A and $00000000FFFFFFFF); LoB := LongWord(B and $00000000FFFFFFFF); if LoA > LoB then Result := 1 else if LoA < LoB then Result := -1 else Result := 0; end; {$ENDIF} end; function UInt64Sqrt(N: TUInt64): TUInt64; var Rem, Root: TUInt64; I: Integer; begin Result := 0; if N = 0 then Exit; if UInt64Compare(N, 4) < 0 then begin Result := 1; Exit; end; Rem := 0; Root := 0; for I := 0 to 31 do begin Root := Root shl 1; Inc(Root); Rem := Rem shl 2; Rem := Rem or (N shr 62); N := N shl 2; if UInt64Compare(Root, Rem) <= 0 then begin Rem := Rem - Root; Inc(Root); end else Dec(Root); end; Result := Root shr 1; end; function UInt32IsNegative(N: Cardinal): Boolean; begin Result := (N and (1 shl 31)) <> 0; end; function UInt64IsNegative(N: TUInt64): Boolean; begin {$IFDEF SUPPORT_UINT64} Result := (N and (UInt64(1) shl 63)) <> 0; {$ELSE} Result := N < 0; {$ENDIF} end; // 给 UInt64 的某一位置 1,位 Index 从 0 开始 procedure UInt64SetBit(var B: TUInt64; Index: Integer); begin B := B or (TUInt64(1) shl Index); end; // 给 UInt64 的某一位置 0,位 Index 从 0 开始 procedure UInt64ClearBit(var B: TUInt64; Index: Integer); begin B := B and not (TUInt64(1) shl Index); end; // 返回 UInt64 的第几位是否是 1,0 开始 function GetUInt64BitSet(B: TUInt64; Index: Integer): Boolean; begin B := B and (TUInt64(1) shl Index); Result := B <> 0; end; // 返回 Int64 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1 function GetUInt64HighBits(B: TUInt64): Integer; begin if B = 0 then begin Result := -1; Exit; end; Result := 1; if B shr 32 = 0 then begin Inc(Result, 32); B := B shl 32; end; if B shr 48 = 0 then begin Inc(Result, 16); B := B shl 16; end; if B shr 56 = 0 then begin Inc(Result, 8); B := B shl 8; end; if B shr 60 = 0 then begin Inc(Result, 4); B := B shl 4; end; if B shr 62 = 0 then begin Inc(Result, 2); B := B shl 2; end; Result := Result - Integer(B shr 63); // 得到前导 0 的数量 Result := 63 - Result; end; // 返回 Cardinal 的是 1 的最高二进制位是第几位,最低位是 0,如果没有 1,返回 -1 function GetUInt32HighBits(B: Cardinal): Integer; begin if B = 0 then begin Result := -1; Exit; end; Result := 1; if B shr 16 = 0 then begin Inc(Result, 16); B := B shl 16; end; if B shr 24 = 0 then begin Inc(Result, 8); B := B shl 8; end; if B shr 28 = 0 then begin Inc(Result, 4); B := B shl 4; end; if B shr 30 = 0 then begin Inc(Result, 2); B := B shl 2; end; Result := Result - Integer(B shr 31); // 得到前导 0 的数量 Result := 31 - Result; end; // 返回 Int64 的是 1 的最低二进制位是第几位,最低位是 0,如果没有 1,返回 -1 function GetUInt64LowBits(B: TUInt64): Integer; var Y: TUInt64; N: Integer; begin Result := -1; if B = 0 then Exit; N := 63; Y := B shl 32; if Y <> 0 then begin Dec(N, 32); B := Y; end; Y := B shl 16; if Y <> 0 then begin Dec(N, 16); B := Y; end; Y := B shl 8; if Y <> 0 then begin Dec(N, 8); B := Y; end; Y := B shl 4; if Y <> 0 then begin Dec(N, 4); B := Y; end; Y := B shl 2; if Y <> 0 then begin Dec(N, 2); B := Y; end; B := B shl 1; Result := N - Integer(B shr 63); end; // 返回 Cardinal 的是 1 的最低二进制位是第几位,最低位是 0,如果没有 1,返回 -1 function GetUInt32LowBits(B: Cardinal): Integer; var Y, N: Integer; begin Result := -1; if B = 0 then Exit; N := 31; Y := B shl 16; if Y <> 0 then begin Dec(N, 16); B := Y; end; Y := B shl 8; if Y <> 0 then begin Dec(N, 8); B := Y; end; Y := B shl 4; if Y <> 0 then begin Dec(N, 4); B := Y; end; Y := B shl 2; if Y <> 0 then begin Dec(N, 2); B := Y; end; B := B shl 1; Result := N - Integer(B shr 31); end; // 封装的 Int64 Mod,碰到负值时取反求模再模减 function Int64Mod(M, N: Int64): Int64; begin if M > 0 then Result := M mod N else Result := N - ((-M) mod N); end; // 判断一 32 位无符号整数是否 2 的整数次幂 function IsUInt32PowerOf2(N: Cardinal): Boolean; begin Result := (N and (N - 1)) = 0; end; // 判断一 64 位无符号整数是否 2 的整数次幂 function IsUInt64PowerOf2(N: TUInt64): Boolean; begin Result := (N and (N - 1)) = 0; end; // 得到一比指定 32 位无符号整数数大或等的 2 的整数次幂,如溢出则返回 0 function GetUInt32PowerOf2GreaterEqual(N: Cardinal): Cardinal; begin Result := N - 1; Result := Result or (Result shr 1); Result := Result or (Result shr 2); Result := Result or (Result shr 4); Result := Result or (Result shr 8); Result := Result or (Result shr 16); Inc(Result); end; // 得到一比指定 64 位无符号整数数大的 2 的整数次幂,如溢出则返回 0 function GetUInt64PowerOf2GreaterEqual(N: TUInt64): TUInt64; begin Result := N - 1; Result := Result or (Result shr 1); Result := Result or (Result shr 2); Result := Result or (Result shr 4); Result := Result or (Result shr 8); Result := Result or (Result shr 16); Result := Result or (Result shr 32); Inc(Result); end; // 判断两个 32 位有符号数相加是否溢出 32 位有符号上限 function IsInt32AddOverflow(A, B: Integer): Boolean; var C: Integer; begin C := A + B; Result := ((A > 0) and (B > 0) and (C < 0)) or // 同符号且结果换号了说明出现了溢出 ((A < 0) and (B < 0) and (C > 0)); end; // 判断两个 32 位无符号数相加是否溢出 32 位无符号上限 function IsUInt32AddOverflow(A, B: Cardinal): Boolean; begin Result := (A + B) < A; // 无符号相加,结果只要小于任一个数就说明溢出了 end; // 判断两个 64 位有符号数相加是否溢出 64 位有符号上限 function IsInt64AddOverflow(A, B: Int64): Boolean; var C: Int64; begin C := A + B; Result := ((A > 0) and (B > 0) and (C < 0)) or // 同符号且结果换号了说明出现了溢出 ((A < 0) and (B < 0) and (C > 0)); end; // 判断两个 64 位无符号数相加是否溢出 64 位无符号上限 function IsUInt64AddOverflow(A, B: TUInt64): Boolean; begin Result := UInt64Compare(A + B, A) < 0; // 无符号相加,结果只要小于任一个数就说明溢出了 end; // 两个 64 位无符号数相加,A + B => R,如果有溢出,则溢出的 1 搁进位标记里,否则清零 procedure UInt64Add(var R: TUInt64; A, B: TUInt64; out Carry: Integer); begin R := A + B; if UInt64Compare(R, A) < 0 then // 无符号相加,结果只要小于任一个数就说明溢出了 Carry := 1 else Carry := 0; end; // 两个 64 位无符号数相减,A - B => R,如果不够减有借位,则借的 1 搁借位标记里,否则清零 procedure UInt64Sub(var R: TUInt64; A, B: TUInt64; out Carry: Integer); begin R := A - B; if UInt64Compare(R, A) > 0 then // 无符号相减,结果只要大于被减数就说明借位了 Carry := 1 else Carry := 0; end; // 判断两个 32 位有符号数相乘是否溢出 32 位有符号上限 function IsInt32MulOverflow(A, B: Integer): Boolean; var T: Integer; begin T := A * B; Result := (B <> 0) and ((T div B) <> A); end; // 判断两个 32 位无符号数相乘是否溢出 32 位无符号上限 function IsUInt32MulOverflow(A, B: Cardinal): Boolean; var T: TUInt64; begin T := TUInt64(A) * TUInt64(B); Result := (T = Cardinal(T)); end; // 判断两个 32 位无符号数相乘是否溢出 64 位有符号数,如未溢出也即返回 False 时,R 中直接返回结果 function IsUInt32MulOverflowInt64(A, B: Cardinal; out R: TUInt64): Boolean; var T: Int64; begin T := Int64(A) * Int64(B); Result := T < 0; // 如果出现 Int64 负值则说明溢出 if not Result then R := TUInt64(T); end; // 判断两个 64 位有符号数相乘是否溢出 64 位有符号上限 function IsInt64MulOverflow(A, B: Int64): Boolean; var T: Int64; begin T := A * B; Result := (B <> 0) and ((T div B) <> A); end; // 指针类型转换成整型,支持 32/64 位 function PointerToInteger(P: Pointer): Integer; begin {$IFDEF CPU64BITS} // 先这么写,利用 Pointer 的低 32 位存 Integer Result := Integer(P); {$ELSE} Result := Integer(P); {$ENDIF} end; // 整型转换成指针类型,支持 32/64 位 function IntegerToPointer(I: Integer): Pointer; begin {$IFDEF CPU64BITS} // 先这么写,利用 Pointer 的低 32 位存 Integer Result := Pointer(I); {$ELSE} Result := Pointer(I); {$ENDIF} end; // 求 Int64 范围内俩加数的和求余,处理溢出的情况,要求 N 大于 0 function Int64NonNegativeAddMod(A, B, N: Int64): Int64; begin if IsInt64AddOverflow(A, B) then // 如果加起来溢出 Int64 begin if A > 0 then begin // A 和 B 都大于 0,采用 UInt64 相加取模(和未溢出 UInt64 上限),注意 N 未溢出 Int64 因此取模结果小于 Int64 上限,不会变成负值 Result := UInt64NonNegativeAddMod(A, B, N); end else begin // A 和 B 都小于 0,取反后采用 UInt64 相加取模(反后的和未溢出 UInt64 上限),模再被除数减一下 {$IFDEF SUPPORT_UINT64} Result := UInt64(N) - UInt64NonNegativeAddMod(-A, -B, N); {$ELSE} Result := N - UInt64NonNegativeAddMod(-A, -B, N); {$ENDIF} end; end else // 不溢出,直接加起来求余 Result := Int64NonNegativeMod(A + B, N); end; // 求 UInt64 范围内俩加数的和求余,处理溢出的情况,要求 N 大于 0 function UInt64NonNegativeAddMod(A, B, N: TUInt64): TUInt64; var C, D: TUInt64; begin if IsUInt64AddOverflow(A, B) then // 如果加起来溢出 begin C := UInt64Mod(A, N); // 就各自求模 D := UInt64Mod(B, N); if IsUInt64AddOverflow(C, D) then begin // 如果还是溢出,说明模比两个加数都大,各自求模没用。 // 至少有一个加数大于等于 2^63,N 至少是 2^63 + 1 // 和 = 溢出结果 + 2^64 // 和 mod N = 溢出结果 mod N + (2^64 - 1) mod N) + 1 // 这里 N 至少是 2^63 + 1,溢出结果最多是 2^64 - 2,所以前两项相加不会溢出,可以直接相加后减一再求模 Result := UInt64Mod(UInt64Mod(A + B, N) + UInt64Mod(CN_MAX_TUINT64, N) + 1, N); end else Result := UInt64Mod(C + D, N); end else begin Result := UInt64Mod(A + B, N); end; end; function Int64NonNegativeMulMod(A, B, N: Int64): Int64; var Neg: Boolean; begin if N <= 0 then raise EDivByZero.Create(SDivByZero); // 范围小就直接算 if not IsInt64MulOverflow(A, B) then begin Result := A * B mod N; if Result < 0 then Result := Result + N; Exit; end; // 调整符号到正 Result := 0; if (A = 0) or (B = 0) then Exit; Neg := False; if (A < 0) and (B > 0) then begin A := -A; Neg := True; end else if (A > 0) and (B < 0) then begin B := -B; Neg := True; end else if (A < 0) and (B < 0) then begin A := -A; B := -B; end; // 移位循环算 while B <> 0 do begin if (B and 1) <> 0 then Result := ((Result mod N) + (A mod N)) mod N; A := A shl 1; if A >= N then A := A mod N; B := B shr 1; end; if Neg then Result := N - Result; end; function UInt64NonNegativeMulMod(A, B, N: TUInt64): TUInt64; begin Result := 0; if (UInt64Compare(A, CN_MAX_UINT32) <= 0) and (UInt64Compare(B, CN_MAX_UINT32) <= 0) then begin Result := UInt64Mod(A * B, N); // 足够小的话直接乘后求模 end else begin while B <> 0 do begin if (B and 1) <> 0 then Result := UInt64NonNegativeAddMod(Result, A, N); A := UInt64NonNegativeAddMod(A, A, N); // 不能用传统算法里的 A := A shl 1,大于 N 后再 mod N,因为会溢出 B := B shr 1; end; end; end; // 封装的非负求余函数,也就是余数为负时,加个除数变正,调用者需保证 P 大于 0 function Int64NonNegativeMod(N: Int64; P: Int64): Int64; begin if P <= 0 then raise EDivByZero.Create(SDivByZero); Result := N mod P; if Result < 0 then Inc(Result, P); end; // Int64 的非负整数指数幂 function Int64NonNegativPower(N: Int64; Exp: Integer): Int64; var T: Int64; begin if Exp < 0 then raise ERangeError.Create(SRangeError) else if Exp = 0 then begin if N <> 0 then Result := 1 else raise EDivByZero.Create(SDivByZero); end else if Exp = 1 then Result := N else begin Result := 1; T := N; while Exp > 0 do begin if (Exp and 1) <> 0 then Result := Result * T; Exp := Exp shr 1; T := T * T; end; end; end; function Int64NonNegativeRoot(N: Int64; Exp: Integer): Int64; var I: Integer; X: Int64; X0, X1: Extended; begin if (Exp < 0) or (N < 0) then raise ERangeError.Create(SRangeError) else if Exp = 0 then raise EDivByZero.Create(SDivByZero) else if (N = 0) or (N = 1) then Result := N else if Exp = 2 then Result := UInt64Sqrt(N) else begin // 牛顿迭代法求根 I := GetUInt64HighBits(N) + 1; // 得到大约 Log2 N 的值 I := (I div Exp) + 1; X := 1 shl I; // 得到一个较大的 X0 值作为起始值 X0 := X; X1 := X0 - (Power(X0, Exp) - N) / (Exp * Power(X0, Exp - 1)); while True do begin if (Trunc(X0) = Trunc(X1)) and (Abs(X0 - X1) < 0.001) then begin Result := Trunc(X1); // Trunc 只支持 Int64,超界了会出错 Exit; end; X0 := X1; X1 := X0 - (Power(X0, Exp) - N) / (Exp * Power(X0, Exp - 1)); end; end; end; function UInt64NonNegativPower(N: TUInt64; Exp: Integer): TUInt64; var T, RL, RH: TUInt64; begin if Exp < 0 then raise ERangeError.Create(SRangeError) else if Exp = 0 then begin if N <> 0 then Result := 1 else raise EDivByZero.Create(SDivByZero); end else if Exp = 1 then Result := N else begin Result := 1; T := N; while Exp > 0 do begin if (Exp and 1) <> 0 then begin UInt64MulUInt64(Result, T, RL, RH); Result := RL; end; Exp := Exp shr 1; UInt64MulUInt64(T, T, RL, RH); T := RL; end; end; end; function UInt64NonNegativeRoot(N: TUInt64; Exp: Integer): TUInt64; var I: Integer; X: TUInt64; XN, X0, X1: Extended; begin if Exp < 0 then raise ERangeError.Create(SRangeError) else if Exp = 0 then raise EDivByZero.Create(SDivByZero) else if (N = 0) or (N = 1) then Result := N else if Exp = 2 then Result := UInt64Sqrt(N) else begin // 牛顿迭代法求根 I := GetUInt64HighBits(N) + 1; // 得到大约 Log2 N 的值 I := (I div Exp) + 1; X := 1 shl I; // 得到一个较大的 X0 值作为起始值 X0 := UInt64ToExtended(X); XN := UInt64ToExtended(N); X1 := X0 - (Power(X0, Exp) - XN) / (Exp * Power(X0, Exp - 1)); while True do begin if (ExtendedToUInt64(X0) = ExtendedToUInt64(X1)) and (Abs(X0 - X1) < 0.001) then begin Result := ExtendedToUInt64(X1); Exit; end; X0 := X1; X1 := X0 - (Power(X0, Exp) - XN) / (Exp * Power(X0, Exp - 1)); end; end; end; function IsUInt128BitSet(Lo, Hi: TUInt64; N: Integer): Boolean; begin if N < 64 then Result := (Lo and (TUInt64(1) shl N)) <> 0 else begin Dec(N, 64); Result := (Hi and (TUInt64(1) shl N)) <> 0; end; end; procedure SetUInt128Bit(var Lo, Hi: TUInt64; N: Integer); begin if N < 64 then Lo := Lo or (TUInt64(1) shl N) else begin Dec(N, 64); Hi := Hi or (TUInt64(1) shl N); end; end; procedure ClearUInt128Bit(var Lo, Hi: TUInt64; N: Integer); begin if N < 64 then Lo := Lo and not (TUInt64(1) shl N) else begin Dec(N, 64); Hi := Hi and not (TUInt64(1) shl N); end; end; function UnsignedAddWithLimitRadix(A, B, C: Cardinal; var R: Cardinal; L, H: Cardinal): Cardinal; begin R := A + B + C; if R > H then // 有进位 begin A := H - L + 1; // 得到进制 B := R - L; // 得到超出 L 的值 Result := B div A; // 超过进制的第几倍就进几 R := L + (B mod A); // 去掉进制后的余数,加上下限 end else Result := 0; end; procedure InternalQuickSort(Mem: Pointer; L, R: Integer; ElementByteSize: Integer; CompareProc: TCnMemSortCompareProc); var I, J, P: Integer; begin repeat I := L; J := R; P := (L + R) shr 1; repeat while CompareProc(Pointer(TCnNativeInt(Mem) + I * ElementByteSize), Pointer(TCnNativeInt(Mem) + P * ElementByteSize), ElementByteSize) < 0 do Inc(I); while CompareProc(Pointer(TCnNativeInt(Mem) + J * ElementByteSize), Pointer(TCnNativeInt(Mem) + P * ElementByteSize), ElementByteSize) > 0 do Dec(J); if I <= J then begin MemorySwap(Pointer(TCnNativeInt(Mem) + I * ElementByteSize), Pointer(TCnNativeInt(Mem) + J * ElementByteSize), ElementByteSize); if P = I then P := J else if P = J then P := I; Inc(I); Dec(J); end; until I > J; if L < J then InternalQuickSort(Mem, L, J, ElementByteSize, CompareProc); L := I; until I >= R; end; function DefaultCompareProc(P1, P2: Pointer; ElementByteSize: Integer): Integer; begin Result := MemoryCompare(P1, P2, ElementByteSize); end; procedure MemoryQuickSort(Mem: Pointer; ElementByteSize: Integer; ElementCount: Integer; CompareProc: TCnMemSortCompareProc); begin if (Mem <> nil) and (ElementCount > 0) and (ElementCount > 0) then begin if Assigned(CompareProc) then InternalQuickSort(Mem, 0, ElementCount - 1, ElementByteSize, CompareProc) else InternalQuickSort(Mem, 0, ElementCount - 1, ElementByteSize, DefaultCompareProc); end; end; initialization FByteOrderIsBigEndian := CurrentByteOrderIsBigEndian; end.
unit CubanRadars; interface uses Description, Graphics; function Find( Radar : TRadar ) : TRadarDesc; stdcall; function TrustStr ( Trust : TRadarTrust ) : string; stdcall; function BrandStr ( Brand : TRadarBrand ) : string; stdcall; function Manufacturer( Brand : TRadarBrand ) : string; stdcall; implementation const theRadars : array[rdNone..rdGranPiedra] of TRadarDesc = ( ( Name : 'Ninguno'; Owner : 'Nadie'; Brand : rbUnknown; Trust : rtLow; Location : ( Longitude : 00.0000; Latitude : 00.0000; Altitude : 0 ); Range : 0 ), ( Name : 'La Bajada'; Owner : 'La Bajada, Pinar del Rio'; Brand : rbRC32B; Trust : rtLow; Location : ( Longitude : 84.4784; // 84.2842 Latitude : 21.9212; // 21.5516 Altitude : 15 ); Range : 500 ), ( Name : 'Punta del Este'; Owner : 'Punta del Este, Isla de la Juventud'; Brand : rbRC32B; Trust : rtLow; Location : ( Longitude : 82.5583; // 82.3361 Latitude : 21.5669; // 21.3290 Altitude : 20 ); Range : 500 ), ( Name : 'Casablanca'; Owner : 'Instituto de Meteorología'; Brand : rbMRL5M; Trust : rtMean; Location : ( Longitude : 82.3500; // 82.2100 Latitude : 23.1495; // 23.0858 Altitude : 50 ); Range : 300 ), ( Name : 'Pico San Juan'; Owner : 'Pico San Juan, Cienfuegos'; Brand : rbMRL5M; Trust : rtHigh; Location : ( Longitude : 80.1475; // 80.0851 - 238 Latitude : 21.9892; // 21.5921 + 67 Altitude : 1140 ); Range : 500 ), ( Name : 'Camagüey'; Owner : 'Loma La Mula, Camagüey'; Brand : rbMRL5M; Trust : rtHigh; Location : ( Longitude : 77.8451; // 77.5042 Latitude : 21.3836; // 21.2301 Altitude : 160 ); Range : 450 ), ( Name : 'Pilón'; Owner : 'Pilón, Granma'; Brand : rbMRL5M; Trust : rtLow; Location : ( Longitude : 77.5000; // 77.3000 Latitude : 19.9167; // 19.5500 Altitude : 500 ); Range : 300 ), ( Name : 'La Gran Piedra'; Owner : 'La Gran Piedra, Sierra Maestra'; Brand : rbRC32B; Trust : rtLow; Location : ( Longitude : 75.6389; // 75.3820 Latitude : 20.0136; // 20.0049 Altitude : 1214 ); Range : 500 ) ); { Public procedures & functions } function Find( Radar : TRadar ) : TRadarDesc; begin Result := theRadars[Radar]; end; function TrustStr( Trust : TRadarTrust ) : string; const TrustStrs : array[TRadarTrust] of string = ('Mala', 'Media', 'Buena' ); begin Result := TrustStrs[Trust]; end; function BrandStr( Brand : TRadarBrand ) : string; const BrandStrs : array[TRadarBrand] of string = ( 'Desconocido', 'MRL-5', 'RC-32B', 'MRL-5M' ); begin Result := BrandStrs[Brand]; end; function Manufacturer( Brand : TRadarBrand ) : string; begin case Brand of rbRC32B : Result := 'Japonesa'; rbMRL5, rbMRL5M : Result := 'Sovietica'; else Result := 'Desconocida'; end; end; end.
unit unConexao; interface uses Data.DB, FireDAC.Comp.Client, FireDAC.Phys.MySQL, FireDAC.Phys.MySQLDef, FireDAC.Comp.UI, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait; type iModelConexao = interface ['{23B13564-CFE2-4B96-9265-AA370634418D}'] function Connection : TObject; end; type TModelConexaoFiredac = class (TInterfacedObject, iModelConexao) private FConexao : TFDConnection; public constructor Create; destructor Destroy; override; class function New : iModelConexao; function Connection : TObject; end; implementation { TModelConexaoFiredac } function TModelConexaoFiredac.Connection: TObject; begin Result := FConexao; end; constructor TModelConexaoFiredac.Create; begin FConexao := TFDConnection.Create(nil); FConexao.Params.DriverID := 'MySQL'; FConexao.Params.Database := 'wkbase'; FConexao.Params.Add('port=3306'); FConexao.Params.UserName:='root'; FConexao.Params.Password:=''; FConexao.Connected := True; end; destructor TModelConexaoFiredac.Destroy; begin FConexao.DisposeOf; //FreeAndNil(FConexao); inherited; end; class function TModelConexaoFiredac.New: iModelConexao; begin Result := Self.Create end; end.
unit uTCPFunctions; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics; function FormatSize(Size: Int64): String; function FormatSpeed(Speed: LongInt): String; function SecToHourAndMin(const ASec: LongInt): String; implementation function FormatSize(Size: Int64): String; const KB = 1024; MB = 1024 * KB; GB = 1024 * MB; begin if Size < KB then Result := FormatFloat('#,##0 Bytes', Size) else if Size < MB then Result := FormatFloat('#,##0.0 KB', Size / KB) else if Size < GB then Result := FormatFloat('#,##0.0 MB', Size / MB) else Result := FormatFloat('#,##0.0 GB', Size / GB); end; function FormatSpeed(Speed: LongInt): String; const KB = 1024; MB = 1024 * KB; GB = 1024 * MB; begin if Speed < KB then Result := FormatFloat('#,##0 bits/s', Speed) else if Speed < MB then Result := FormatFloat('#,##0.0 kB/s', Speed / KB) else if Speed < GB then Result := FormatFloat('#,##0.0 MB/s', Speed / MB) else Result := FormatFloat('#,##0.0 GB/s', Speed / GB); end; function SecToHourAndMin(const ASec: LongInt): String; var Hour, Min, Sec: LongInt; begin Hour := Trunc(ASec/3600); Min := Trunc((ASec - Hour*3600)/60); Sec := ASec - Hour*3600 - 60*Min; Result := IntToStr(Hour) + 'h: ' + IntToStr(Min) + 'm: ' + IntToStr(Sec) + 's'; end; end.
unit Helper.ManageIniFile; interface uses System.SysUtils, System.IOUtils, System.IniFiles; type TManageIniFile = class public class function ClearIni(const AFilePath, AFileName: String): Boolean; class function ReadIni(const AFilePath, AFileName, ASection, AIdent, AValue: string): String; class function ReadIniInt(const AFilePath, AFileName, ASection, AIdent, AValue: string): Integer; class function ReadIniBool(const AFilePath, AFileName, ASection, AIdent, AValue: string): Boolean; class function WriteIni(const AFilePath, AFileName, ASection, AIdent, AValue: string): Boolean; private end; implementation { TIniFile } class function TManageIniFile.ClearIni(const AFilePath, AFileName: String): Boolean; begin Result := False; if (FileExists(System.IOUtils.TPath.Combine(AFilePath, AFileName))) then begin try DeleteFile(System.IOUtils.TPath.Combine(AFilePath, AFileName)); Result := True; except end; end; end; class function TManageIniFile.ReadIni(const AFilePath, AFileName, ASection, AIdent, AValue: string): String; var vIniFile: TIniFile; begin Result := AValue; if (FileExists(System.IOUtils.TPath.Combine(AFilePath, AFileName))) then begin try vIniFile := TIniFile.Create(System.IOUtils.TPath.Combine(AFilePath, AFileName)); Result := vIniFile.ReadString(ASection, AIdent, AValue); finally FreeAndNil(vIniFile); end; end; end; class function TManageIniFile.ReadIniInt(const AFilePath, AFileName, ASection, AIdent, AValue: string): Integer; begin TryStrToInt(ReadIni(AFilePath, AFileName, ASection, AIdent, AValue), Result); end; class function TManageIniFile.ReadIniBool(const AFilePath, AFileName, ASection, AIdent, AValue: string): Boolean; begin TryStrToBool(ReadIni(AFilePath, AFileName, ASection, AIdent, AValue), Result); end; class function TManageIniFile.WriteIni(const AFilePath, AFileName, ASection, AIdent, AValue: string): Boolean; var vIniFile: TIniFile; begin Result := False; try vIniFile := TIniFile.Create(System.IOUtils.TPath.Combine(AFilePath, AFileName)); vIniFile.WriteString(ASection, AIdent, AValue); Result := True; finally FreeAndNil(vIniFile); end; end; end.
unit AbstractList; interface uses System.Generics.Collections; type TAbstractList<T: class> = class abstract(TInterfacedObject) private FList: TObjectList<T>; FValidadeMaxList: Boolean; protected procedure Initialize(const AValidateMaxList: Boolean); public constructor Create; destructor Destroy; override; function validate(const AValue: T): Boolean; virtual; abstract; procedure validateMaxDrones; procedure SaveValue(const AValue: T); function GetList: TObjectList<T>; function GetListQuantity: Integer; end; implementation uses System.SysUtils; { TAbstractList } constructor TAbstractList<T>.Create; begin raise Exception.Create('Use the method CreateProtected'); end; procedure TAbstractList<T>.Initialize(const AValidateMaxList: Boolean); begin FList := TObjectList<T>.Create; FValidadeMaxList := AValidateMaxList; end; destructor TAbstractList<T>.Destroy; begin FList.Clear; FList.Free; inherited; end; function TAbstractList<T>.GetList: TObjectList<T>; begin Result := FList; end; function TAbstractList<T>.GetListQuantity: Integer; begin Result := FList.Count; end; procedure TAbstractList<T>.SaveValue(const AValue: T); begin if FValidadeMaxList then validateMaxDrones; if validate(AValue) then FList.Add(AValue) else raise Exception.Create('Invalid data. Check out'); end; procedure TAbstractList<T>.validateMaxDrones; const MAX_DRONES = 100; begin if GetListQuantity > MAX_DRONES then raise Exception.Create('Adding more drones is not allowed'); end; end.
unit LossMovementItemTest; interface uses dbTest, ObjectTest; type TLossMovementItemTest = class(TdbTest) protected //procedure SetUp; override; published // загрузка процедура из определенной директории procedure ProcedureLoad; override; procedure Test; override; end; TLossMovementItem = class(TMovementItemTest) private function InsertDefault: integer; override; protected procedure SetDataSetParam; override; public function InsertUpdateMovementItemLoss (Id, MovementId, GoodsId: Integer; Amount: double): integer; constructor Create; override; end; implementation uses UtilConst, Db, SysUtils, dbMovementTest, UnitsTest, Storage, Authentication, TestFramework, CommonData, dbObjectTest, Variants, LossTest, IncomeMovementItemTest; { TLossMovementItemTest } procedure TLossMovementItemTest.Test; var MovementItemLoss: TLossMovementItem; Id: Integer; begin exit; MovementItemLoss := TLossMovementItem.Create; Id := MovementItemLoss.InsertDefault; // создание документа try // редактирование finally // удаление MovementItemLoss.Delete(Id); end; end; procedure TLossMovementItemTest.ProcedureLoad; begin ScriptDirectory := LocalProcedurePath + 'Movement\Loss\'; inherited; ScriptDirectory := LocalProcedurePath + 'MovementItem\Loss\'; inherited; ScriptDirectory := LocalProcedurePath + 'MovementItemContainer\Loss\'; inherited; end; { TLossMovementItem } constructor TLossMovementItem.Create; begin inherited; spInsertUpdate := 'gpInsertUpdate_MovementItem_Loss'; spSelect := 'gpSelect_MovementItem_Loss'; // spGet := 'gpGet_MovementItem_Loss'; end; procedure TLossMovementItem.SetDataSetParam; begin inherited; FParams.AddParam('inMovementId', ftInteger, ptInput, TLoss.Create.GetDefault); FParams.AddParam('inShowAll', ftBoolean, ptInput, true); FParams.AddParam('inIsErased', ftBoolean, ptInput, False); end; function TLossMovementItem.InsertDefault: integer; var Id, MovementId, GoodsId, PartionGoodsId: Integer; Amount, Price: double; begin Id:=0; MovementId := TLoss.Create.GetDefault; With TIncomeMovementItem.Create.GetDataSet DO Begin GoodsId := FieldByName('GoodsId').asInteger; Amount := FieldBYName('Amount').asFloat; End; result := InsertUpdateMovementItemLoss(Id, MovementId, GoodsId, Amount); end; function TLossMovementItem.InsertUpdateMovementItemLoss (Id, MovementId, GoodsId: Integer; Amount: double): integer; begin FParams.Clear; FParams.AddParam('ioId', ftInteger, ptInputOutput, Id); FParams.AddParam('inMovementId', ftInteger, ptInput, MovementId); FParams.AddParam('inGoodsId', ftInteger, ptInput, GoodsId); FParams.AddParam('inAmount', ftFloat, ptInput, Amount); result := InsertUpdate(FParams); end; initialization TestFramework.RegisterTest('Строки Документов', TLossMovementItemTest.Suite); end.
unit TestGUnzip; interface uses Classes, System.ZLib, TestFramework; type TTestGUnzip = class(TTestCase) private FMemoryStream: TMemoryStream; FDataStream: TStringStream; FGZip: TZDecompressionStream; function CompressFile: string; procedure CorruptGzip(const AFile: string); public procedure SetUp; override; procedure TearDown; override; published procedure TestNormal; procedure TestCorrupted; procedure TestCharges; procedure TestCorruptedCharges; end; implementation uses SysUtils, Windows; { TTestGUnzip } procedure TTestGUnzip.CorruptGzip(const AFile: string); var i: byte; LFile: TFileStream; begin LFile := TFileStream.Create(AFile, fmOpenReadWrite); try LFile.Seek(-256, soFromEnd); for i := 0 to 255 do LFile.Write(i, SizeOf(Byte)); finally FreeAndNil(LFile); end; end; procedure TTestGUnzip.SetUp; begin inherited; FMemoryStream := TMemoryStream.Create; FDataStream := TStringStream.Create;; FGZip := nil; end; procedure TTestGUnzip.TearDown; begin FreeAndNil(FMemoryStream); FreeAndNil(FDataStream); FreeAndNil(FGZip); inherited; end; procedure TTestGUnzip.TestCharges; var LFileStream: TFileStream; LFile: string; begin LFile := CompressFile; LFileStream := TFileStream.Create(LFile, fmOpenRead); try FGZip := TZDecompressionStream.Create(LFileStream, 15 + 16); FDataStream.CopyFrom(FGZip, 0); CheckEquals(57060, FDataStream.Size); finally FreeAndNil(LFileStream); end; end; procedure TTestGUnzip.TestCorrupted; begin // this is a // $ echo -n Hello, world | gzip -f | xxd -ps -c 40 FMemoryStream.Size := 32; CheckEquals(32, HexToBin('1f8b0800ad5d9f5c0003f348cdc9c9d75128cf2fca490100c2a99aefedEFFF00', FMemoryStream.Memory, FMemoryStream.Size)); StartExpectingException(EZDecompressionError); FGZip := TZDecompressionStream.Create(FMemoryStream, 15 + 16); FDataStream.CopyFrom(FGZip, 0); end; procedure TTestGUnzip.TestCorruptedCharges; var LFileStream: TFileStream; LFile: string; begin LFile := CompressFile; CorruptGZip(LFile); LFileStream := TFileStream.Create(LFile, fmOpenRead); try FGZip := TZDecompressionStream.Create(LFileStream, 15 + 16); StartExpectingException(EZDecompressionError); FDataStream.CopyFrom(FGZip, 0); finally FreeAndNil(LFileStream); end; end; function TTestGUnzip.CompressFile: string; var LResStream: TResourceStream; LCompressStream: TFileStream; begin LResStream := TResourceStream.Create(HInstance, 'CHARGES', RT_RCDATA); try Result := ExpandFileName('Charges.gz'); DeleteFile(PChar(Result)); LCompressStream := TFileStream.Create(Result, fmOpenWrite or fmCreate); try with TZCompressionStream.Create(LCompressStream, TZCompressionLevel.zcMax, 15 or 16) do try CopyFrom(LResStream, 0); finally Free; end; finally FreeAndNil(LCompressStream); end; finally FreeAndNil(LResStream); end; end; procedure TTestGUnzip.TestNormal; begin // this is a // $ echo -n Hello, world | gzip -f | xxd -ps -c 40 FMemoryStream.Size := 32; CheckEquals(32, HexToBin('1f8b0800ad5d9f5c0003f348cdc9c9d75128cf2fca490100c2a99ae70c000000', FMemoryStream.Memory, FMemoryStream.Size)); FGZip := TZDecompressionStream.Create(FMemoryStream, 15 + 16); FDataStream.CopyFrom(FGZip, 0); CheckEquals('Hello, world', FDataStream.DataString); end; initialization RegisterTest(TTestGUnzip.Suite); end.
unit Menus.Controller.Forms.Default; interface type TControllerFormsDefault = class class procedure CreateForm(ClassName : String); end; implementation uses FMX.Types, System.Classes, FMX.Forms, System.SysUtils; { TControllerFormsDefault } class procedure TControllerFormsDefault.CreateForm(ClassName: String); var objFMX : TFMXObjectClass; newForm: TCustomForm; begin objFMX := TFmxObjectClass( GetClass(ClassName)); try newForm := (objFMX.Create(nil) as TCustomForm); try newForm.Position := TFormPosition.ScreenCenter; newForm.ShowModal; finally newForm.free; end; except raise Exception.Create('Objeto não existe'); end; end; end.
unit uAdvancedPropertyEditor; {$mode objfpc}{$H+} interface uses Classes, SysUtils, VirtualTrees, Menus, uPropertyEditorNew, uVtBaseEditor; type { TAdvancedPropertyEditor } TAdvancedPropertyEditor = class(TPropertyEditor) protected procedure ConstructPopupMenu; virtual; procedure AddNewItem(Sender: TObject); virtual; abstract; procedure CloneItem(Sender: TObject); virtual; abstract; procedure DeleteItem(Sender: TObject); virtual; abstract; procedure CollapseAll(Sender: TObject); virtual; procedure ExpandAll(Sender: TObject); virtual; public procedure AfterConstruction; override; end; implementation uses {%H-}uMenuHelper; { TAdvancedPropertyEditor } procedure TAdvancedPropertyEditor.ConstructPopupMenu; var Menu: TPopupMenu; begin Menu := TPopupMenu.Create(Self); Menu.Parent := Self; PopupMenu := Menu; Menu.AddMenuItem('Добавить...', @AddNewItem); Menu.AddMenuItem('Клонировать...', @CloneItem); Menu.AddMenuItem('-'); Menu.AddMenuItem('Удалить...', @DeleteItem); Menu.AddMenuItem('-'); Menu.AddMenuItem('Развернуть все', @ExpandAll); Menu.AddMenuItem('Свернуть все все', @CollapseAll); end; procedure TAdvancedPropertyEditor.CollapseAll(Sender: TObject); begin FullCollapse(); end; procedure TAdvancedPropertyEditor.ExpandAll(Sender: TObject); begin FullExpand(); end; procedure TAdvancedPropertyEditor.AfterConstruction; begin inherited AfterConstruction; ConstructPopupMenu; end; end.
unit UFileWatchThread; interface uses classes, dirnotify, ExtCtrls; type // 文件变化监听 TFileWatchThread = class( TThread ) private ControlPath : string; LocalPath, NetworkPath : string; private LocalDirNotify : TDirNotify; // 目录监听器 Timer : TTimer; public constructor Create; procedure SetPath( _ControlPath, _LocalPath, _NetworkPath : string ); procedure SetLocalPath( _LocalPath : string ); procedure SetNetworkPath( _NetworkPath : string ); destructor Destroy; override; protected procedure Execute; override; private procedure LocalFolderChange(Sender: TObject); procedure NetworkFolderChange; private procedure OnTime( Sender: TObject ); end; // 文件监听对象 TMyFileWatch = class public IsStop : Boolean; FileWatchThread : TFileWatchThread; public constructor Create; procedure Stop; public procedure SetPath( ControlPath, LocalPath, NetworkPath : string ); procedure SetLocalPath( LocalPath : string ); procedure SetNetworkPath( NetworkPath : string ); end; var MyFileWatch : TMyFileWatch; implementation uses UMyUtils, SysUtils, UMyFaceThread; { TFileWatchThread } constructor TFileWatchThread.Create; begin inherited Create( True ); LocalPath := ''; NetworkPath := ''; LocalDirNotify := TDirNotify.Create( nil ); LocalDirNotify.OnChange := LocalFolderChange; Timer := TTimer.Create( nil ); Timer.Enabled := False; Timer.Interval := 1000; Timer.OnTimer := OnTime; end; destructor TFileWatchThread.Destroy; begin Terminate; Resume; WaitFor; LocalDirNotify.Free; Timer.Free; inherited; end; procedure TFileWatchThread.Execute; var i: Integer; begin while not Terminated do begin for i := 1 to 200 do // 20 秒刷新一次 begin if Terminated then Break; Sleep(100); end; if NetworkPath <> '' then // 刷新 NetworkFolderChange; end; end; procedure TFileWatchThread.LocalFolderChange(Sender: TObject); begin Timer.Enabled := False; Timer.Enabled := True; end; procedure TFileWatchThread.NetworkFolderChange; begin MyFaceJobHandler.FileChange( ControlPath, NetworkPath, False ); end; procedure TFileWatchThread.OnTime(Sender: TObject); begin MyFaceJobHandler.FileChange( ControlPath, LocalPath, True ); end; procedure TFileWatchThread.SetLocalPath(_LocalPath: string); begin LocalPath := _LocalPath; TThread.CreateAnonymousThread( procedure begin if ( LocalPath <> '' ) and MyFilePath.getIsFixedDriver( ExtractFileDrive( LocalPath ) ) then begin LocalDirNotify.Path := LocalPath; LocalDirNotify.Enabled := True; end else LocalDirNotify.Enabled := False; end).Start; end; procedure TFileWatchThread.SetNetworkPath(_NetworkPath: string); begin NetworkPath := _NetworkPath; end; procedure TFileWatchThread.SetPath(_ControlPath, _LocalPath, _NetworkPath: string); begin ControlPath := _ControlPath; SetLocalPath( _LocalPath ); SetNetworkPath( _NetworkPath ); end; { TMyFileWatch } constructor TMyFileWatch.Create; begin FileWatchThread := TFileWatchThread.Create; FileWatchThread.Resume; IsStop := False; end; procedure TMyFileWatch.SetLocalPath(LocalPath: string); begin if IsStop then Exit; FileWatchThread.SetLocalPath( LocalPath ); end; procedure TMyFileWatch.SetNetworkPath(NetworkPath: string); begin if IsStop then Exit; FileWatchThread.SetNetworkPath( NetworkPath ); end; procedure TMyFileWatch.SetPath(ControlPath, LocalPath, NetworkPath : string); begin if IsStop then Exit; FileWatchThread.SetPath( ControlPath, LocalPath, NetworkPath ); end; procedure TMyFileWatch.Stop; begin IsStop := True; FileWatchThread.Free; end; end.
unit UVersion; { ClickForms Application } { Bradford Technologies, Inc. } { All Rights Reserved } { Source Code Copyrighted © 1998-2011 by Bradford Technologies, Inc.} interface uses Windows, Classes; type // abstract version class TVersion = class(TComponent) protected FMajor: Word; FMinor: Word; FBuild: Word; protected function GetMajor: Word; virtual; procedure SetMajor(const Value: Word); virtual; function GetMinor: Word; virtual; procedure SetMinor(const Value: Word); virtual; function GetBuild: Word; virtual; procedure SetBuild(const Value: Word); virtual; function GetValue: LongWord; virtual; procedure SetValue(const Value: LongWord); virtual; public procedure AssignTo(Dest: TPersistent); override; function AsString: String; virtual; procedure Refresh; virtual; published property Major: Word read GetMajor write SetMajor; property Minor: Word read GetMinor write SetMinor; property Build: Word read GetBuild write SetBuild; property Value: LongWord read GetValue write SetValue; end; TVersionClass = class of TVersion; // document schema version stored in docData TDocumentSchemaVersion = class(TVersion) private FDocument: TComponent; protected procedure Initialize; procedure LoadData; procedure SaveData; procedure SetDocument(const Value: TComponent); public constructor Create(AOwner: TComponent); override; procedure Refresh; override; published property Document: TComponent read FDocument write SetDocument; end; // software version of an installed product TProductID = TGUID; TProductVersion = class(TVersion) private FInstalled: Boolean; FProductID: TProductID; private procedure SetProductID(const ProductID: TProductID); public procedure AssignTo(Dest: TPersistent); override; procedure Refresh; override; published property Installed: Boolean read FInstalled write FInstalled; property ProductID: TProductID read FProductID write SetProductID; end; // windows version TWindowsProduct = (wpUnknown, wpWin95, wpWin98, wpWin98SE, wpWinNT, wpWinME, wpWin2000, wpWinXP, wpWinVista, wpWin7, wpWinFuture); TWindowsVersion = class(TVersion) private FVersionInfo: TOSVersionInfo; protected function GetProduct: TWindowsProduct; public constructor Create(AOwner: TComponent); override; procedure AssignTo(Dest: TPersistent); override; procedure Refresh; override; published property Product: TWindowsProduct read GetProduct; end; implementation uses IdHTTP, Registry, SysUtils, UContainer, UPaths, UWebUtils; const // imported from Visual C++ GUID_NULL: TGUID = '{00000000-0000-0000-0000-000000000000}'; // --- TVersion --------------------------------------------------------------- function TVersion.GetMajor: Word; begin Result := FMajor; end; procedure TVersion.SetMajor(const Value: Word); begin FMajor := Value; end; function TVersion.GetMinor: Word; begin Result := FMinor; end; procedure TVersion.SetMinor(const Value: Word); begin FMinor := Value; end; function TVersion.GetBuild: Word; begin Result := FBuild; end; procedure TVersion.SetBuild(const Value: Word); begin FBuild := Value; end; function TVersion.GetValue: LongWord; begin Result := FBuild or (FMinor shl 16) or (FMajor shl 24); end; procedure TVersion.SetValue(const Value: LongWord); begin FMajor := Value and $ff000000 shr 24; FMinor := Value and $00ff0000 shr 16; FBuild := Value and $0000ffff; end; procedure TVersion.AssignTo(Dest: TPersistent); var Version: TVersion; begin if (Dest is TVersion) then begin Version := Dest as TVersion; Version.FMajor := FMajor; Version.FMinor := FMinor; Version.FBuild := FBuild; end; end; function TVersion.AsString: String; begin Result := Format('%d.%d.%d', [Major, Minor, Build]); end; procedure TVersion.Refresh; begin inherited; FMajor := 0; FMinor := 0; FBuild := 0; end; // --- TDocumentVersion ------------------------------------------------------- const CSchemaVersionKind = 'SchemaVersion'; type // a generic version record TVersionRecord = record Major: Integer; Minor: Integer; Build: Integer; end; procedure TDocumentSchemaVersion.Initialize; begin FMajor := 7; FMinor := 0; FBuild := 0; end; procedure TDocumentSchemaVersion.LoadData; var Stream: TMemoryStream; Version: TVersionRecord; begin if Assigned(FDocument) then begin Stream := (FDocument as TContainer).docData.FindData(CSchemaVersionKind); if Assigned(Stream) and (Stream.Size = SizeOf(Version)) then begin Stream.Read(Version, SizeOf(Version)); FMajor := Version.Major; FMinor := Version.Minor; FBuild := Version.Build; end else begin Initialize; SaveData; end; end; end; procedure TDocumentSchemaVersion.SaveData; var DataChanged: Boolean; Stream: TMemoryStream; Version: TVersionRecord; begin if Assigned(FDocument) then begin DataChanged := (FDocument as TContainer).docDataChged; Stream := TMemoryStream.Create; try Version.Major := FMajor; Version.Minor := FMinor; Version.Build := FBuild; Stream.Write(Version, SizeOf(Version)); (FDocument as TContainer).docData.UpdateData(CSchemaVersionKind, Stream); (FDocument as TContainer).docDataChged := DataChanged; // don't change the flag finally FreeAndNil(Stream); end; end; end; procedure TDocumentSchemaVersion.SetDocument(const Value: TComponent); begin if (Value <> FDocument) and (Value is TContainer) then begin FDocument := Value; LoadData; end; end; constructor TDocumentSchemaVersion.Create(AOwner: TComponent); begin inherited; Initialize; end; procedure TDocumentSchemaVersion.Refresh; begin inherited; LoadData; end; // --- TProductVersion -------------------------------------------------------- procedure TProductVersion.SetProductID(const ProductID: TProductID); begin FProductID := ProductID; Refresh; end; procedure TProductVersion.AssignTo(Dest: TPersistent); begin inherited; if (Dest is TProductVersion) then (Dest as TProductVersion).FProductID := FProductID; end; procedure TProductVersion.Refresh; const CRegValueVersion = 'Version'; // do not localize var Key: String; Registry: TRegistry; begin inherited; FInstalled := False; Key := TRegPaths.Uninstall + GuidToString(FProductID); Registry := TRegistry.Create(KEY_READ); try Registry.RootKey := HKEY_LOCAL_MACHINE; if Registry.KeyExists(Key) then begin Registry.OpenKeyReadOnly(Key); if Registry.ValueExists(CRegValueVersion) then begin Value := Registry.ReadInteger(CRegValueVersion); FInstalled := True; end; Registry.CloseKey; end; finally FreeAndNil(Registry); end; end; // --- TWindowsVersion -------------------------------------------------------- function TWindowsVersion.GetProduct: TWindowsProduct; begin case FVersionInfo.dwPlatformId of VER_PLATFORM_WIN32_NT: begin if FVersionInfo.dwMajorVersion <= 4 then Result := wpWinNT else if (FVersionInfo.dwMajorVersion = 5) and (FVersionInfo.dwMinorVersion = 0) then Result := wpWin2000 else if (FVersionInfo.dwMajorVersion = 5) and (FVersionInfo.dwMinorVersion = 1) then Result := wpWinXP else if (FVersionInfo.dwMajorVersion = 6) and (FVersionInfo.dwMinorVersion = 0) then Result := wpWinVista else if (FVersionInfo.dwMajorVersion = 6) and (FVersionInfo.dwMinorVersion = 1) then Result := wpWin7 else if (FVersionInfo.dwMajorVersion = 6) and (FVersionInfo.dwMinorVersion > 1) then Result := wpWinFuture else if (FVersionInfo.dwMajorVersion > 6) then Result := wpWinFuture else Result := wpUnknown; end; VER_PLATFORM_WIN32_WINDOWS: begin if (FVersionInfo.dwMajorVersion = 4) and (FVersionInfo.dwMinorVersion = 0) then Result := wpWin95 else if (FVersionInfo.dwMajorVersion = 4) and (FVersionInfo.dwMinorVersion = 10) then begin if FVersionInfo.szCSDVersion[1] = 'A' then Result := wpWin98SE else Result := wpWin98; end else if (FVersionInfo.dwMajorVersion = 4) and (FVersionInfo.dwMinorVersion = 90) then Result := wpWinME else Result := wpUnknown; end; else Result := wpUnknown; end; end; constructor TWindowsVersion.Create(AOwner: TComponent); begin inherited; Refresh; end; procedure TWindowsVersion.AssignTo(Dest: TPersistent); begin inherited; if (Dest is TWindowsVersion) then (Dest as TWindowsVersion).FVersionInfo := FVersionInfo; end; procedure TWindowsVersion.Refresh; begin inherited; FVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo); GetVersionEx(FVersionInfo); FMajor := FVersionInfo.dwMajorVersion; FMinor := FVersionInfo.dwMinorVersion; FBuild := FVersionInfo.dwBuildNumber; end; end.
unit tg; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpJSON, jsonparser, SyncObjs, regexpr, fgl, gqueue, fphttpclient, Math, LazLogger, flqueue, tgtypes; //The API will not allow more than ~30 messages to different users per second //Also note that your bot will not be able to send more than 20 messages per minute to the same group. //If you're sending bulk notifications to multiple users, the API will not allow more than 30 messages per second or so. //error_code type { TTGQueueRequestsThread } TTGQueneProcessorThread = class(TThread) private fToken: string; fQueue: TFLQueue; protected procedure Execute; override; public constructor Create(const aToken: string; aPower : NativeInt = 10); destructor Destroy; override; procedure AddUpdateObj(UpdateObj: TTelegramUpdateObj); end; { TTGLongPollThread } TTGLongPollThread = class(TThread) private fToken: string; fQueneProcessor: TTGQueneProcessorThread; protected function StreamToJSONObject(Stream: TMemoryStream): TJSONObject; function GetUpdates(HTTPClient: TFPHTTPClient; aOffset: Integer): Integer; procedure Execute; override; public constructor Create(const aToken: string); destructor Destroy; override; end; const TELEGRAM_REQUEST_GETUPDATES = 'getUpdates'; implementation { TTGQueneProcessorThread } procedure TTGQueneProcessorThread.Execute; var lUpdateObj: TTelegramUpdateObj; lMessageEntityObj: TTelegramMessageEntityObj; lHTTPClient: TFPHTTPClient; lCommand: string; begin { lHTTPClient := TFPHTTPClient.Create(nil); try while not Terminated do while fQueue.length <> 0 do begin lUpdateObj := fQueue.pop as TTelegramUpdateObj; if Assigned(lUpdateObj.Message) then for lMessageEntityObj in lUpdateObj.Message.Entities do if (lMessageEntityObj.TypeEntity = 'bot_command') and (lMessageEntityObj.Offset = 0) then begin lCommand := Copy(lUpdateObj.Message.Text, lMessageEntityObj.Offset, lMessageEntityObj.Length); if lCommand = '/help' or lCommand = '/start' then begin lHTTPClient.Get('https://api.telegram.org/bot' + fToken + '/sendMessage?chat_id=' + IntToStr(lUpdateObj.Message.ChatId) + '&parse_mode=Markdown&text=' + EncodeURLElement( '*Привет!' + #$F0#$9F#$98#$81 + 'Я умеею показывать расписание.*') ); end; end; end; finally lHTTPClient.Free; end; } end; constructor TTGQueneProcessorThread.Create(const aToken: string; aPower : NativeInt); begin FreeOnTerminate := False; inherited Create(False); fToken := aToken; fQueue := TFLQueue.Create(10); end; destructor TTGQueneProcessorThread.Destroy; begin fQueue.Free; inherited Destroy; end; procedure TTGQueneProcessorThread.AddUpdateObj(UpdateObj: TTelegramUpdateObj); begin fQueue.push(UpdateObj); end; { TTGLongPollThread } function TTGLongPollThread.StreamToJSONObject(Stream: TMemoryStream): TJSONObject; var lParser: TJSONParser; lJSON: TJSONObject; begin Result := nil; if Stream.Size > 0 then begin Stream.Position := 0; lParser := TJSONParser.Create(Stream); try try lJSON := lParser.Parse as TJSONObject; if lJSON.Booleans['ok'] then Result := lJSON; except end; finally lParser.Free; end; end; end; function TTGLongPollThread.GetUpdates(HTTPClient: TFPHTTPClient; aOffset: Integer): Integer; var lData: TMemoryStream; lJSON: TJSONObject; lJSONArray: TJSONArray; lJSONEnum: TJSONEnum; lUpdateObj: TTelegramUpdateObj; begin Result := 0; lData := TMemoryStream.Create; try if aOffset > 0 then HTTPClient.Get('https://api.telegram.org/bot' + fToken + '/getUpdates?offset=' + IntToStr(aOffset) + '&timeout=30', lData) else HTTPClient.Get('https://api.telegram.org/bot' + fToken + '/getUpdates?timeout=30', lData); lJSON := StreamToJSONObject(lData); if Assigned(lJSON) then try lJSONArray := lJSON.Find('result', jtArray) as TJSONArray; if Assigned(lJSONArray) then for lJSONEnum in lJSONArray do begin lUpdateObj := TTelegramUpdateObj.CreateFromJSONObject(lJSONEnum.Value as TJSONObject) as TTelegramUpdateObj; fQueneProcessor.AddUpdateObj(lUpdateObj); Result := Max(Result, lUpdateObj.UpdateId); end; except end; lData.Clear; finally lData.Free; end; end; procedure TTGLongPollThread.Execute; var lOffset: Integer; lHTTPClient: TFPHTTPClient; begin lHTTPClient := TFPHTTPClient.Create(nil); try while not Terminated do begin lOffset := GetUpdates(lHTTPClient, lOffset); // next! if lOffset > 0 then lOffset := lOffset + 1; end; finally lHTTPClient.Free; end; end; constructor TTGLongPollThread.Create(const aToken: string); begin FreeOnTerminate := False; inherited Create(False); fToken := aToken; fQueneProcessor := TTGQueneProcessorThread.Create(fToken, 10); end; destructor TTGLongPollThread.Destroy; begin fQueneProcessor.Terminate; fQueneProcessor.WaitFor; fQueneProcessor.Free; inherited Destroy; end; end.