text
stringlengths
14
6.51M
{ "anchors": { "anchorOrder": [ ] }, "backgroundName": "blueprint_grey_tiled.jpg", "blocks": [ { "focused": false, "height": 115, "internalState": { "chanNumber": 15, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 3019, "posY": 724, "uid": "15438709614538", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 14, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 2899, "posY": 724, "uid": "15438709137626", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 13, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 2779, "posY": 724, "uid": "15438709119308", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 12, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 2659, "posY": 724, "uid": "15438709035966", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 10, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 2539, "posY": 724, "uid": "15438709012954", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 9, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 2419, "posY": 724, "uid": "15438708992629", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 8, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 2299, "posY": 724, "uid": "15438708975101", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 7, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 2179, "posY": 724, "uid": "15438708967370", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 6, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 2059, "posY": 724, "uid": "15438708936805", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 5, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 1939, "posY": 724, "uid": "15438708912264", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 1, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 1533, "posY": 721, "uid": "15438698806249", "width": 70 }, { "focused": false, "height": 30, "internalState": { "bold": true, "centered": true, "color": "#000000", "fontFamily": "Quicksand", "fontSize": 30, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0, "shadow": true, "shadowColor": "#d5d5d5", "text": "No Project is loaded", "underline": true }, "name": "Styled Text", "nodeMergeModes": { }, "posX": 137, "posY": 148, "uid": "15349282247567", "width": 317 }, { "focused": false, "height": 30, "internalState": { "bold": false, "centered": true, "color": "#000000", "fontFamily": "Quicksand", "fontSize": 30, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0, "shadow": false, "shadowColor": "#dfdfdf", "text": "Create a new one \nor load an existing one to start!", "underline": false }, "name": "Styled Text", "nodeMergeModes": { }, "posX": 49, "posY": 264, "uid": "15349278949690", "width": 484 }, { "focused": false, "height": 30, "internalState": { "bold": true, "centered": false, "color": "#19ff00", "fontFamily": "Quicksand", "fontSize": 36, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0, "shadow": true, "shadowColor": "#555555", "text": "New Forum:", "underline": true }, "name": "Styled Text", "nodeMergeModes": { }, "posX": 177, "posY": 406, "uid": "15153380303386", "width": 233 }, { "focused": false, "height": 30, "internalState": { "bold": true, "centered": false, "color": "#00ff00", "fontFamily": "Quicksand", "fontSize": 20, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0, "shadow": true, "shadowColor": "#555555", "text": "www.alienstagecraft.com/forum/", "underline": false }, "name": "Styled Text", "nodeMergeModes": { }, "posX": 116, "posY": 474, "uid": "15153381725027", "width": 347 }, { "focused": false, "height": 120, "internalState": { "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Info", "nodeMergeModes": { }, "posX": 547, "posY": 70, "uid": "15437994347464", "width": 490 }, { "focused": false, "height": 30, "internalState": { "additionalValueString": "DMX Value 255", "currentValue": 1, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Value Inspector", "nodeMergeModes": { "0": true }, "posX": 1237, "posY": 926, "uid": "15438005643037", "width": 140 }, { "focused": false, "height": 297, "internalState": { "agcEnabled": false, "bandwidth": 0.2, "currentBand": 0.31245791245791243, "frequencyMode": false, "group": "", "guiItemHidden": false, "inputName": "Microphone Array (Realtek Audio) Left", "label": "", "manualGain": 8, "sceneGroup": 0, "showSpectrogram": false, "upperBound": 1 }, "name": "Audio Level", "nodeMergeModes": { }, "posX": 527, "posY": 886, "uid": "15438007987350", "width": 594 }, { "focused": false, "height": 222, "internalState": { "group": "", "guiItemHidden": false, "label": "", "labelText": "", "sceneGroup": 0, "toggleMode": false, "value": 0 }, "name": "Button", "nodeMergeModes": { }, "posX": 1091, "posY": 1, "uid": "15438009184623", "width": 200 }, { "focused": false, "height": 92, "internalState": { "customKeyName": "", "customLabel": "", "group": "", "guiItemHidden": false, "keyName": "go_0", "label": "", "runInBackground": false, "sceneGroup": 0 }, "name": "Eos Key", "nodeMergeModes": { "0": true }, "posX": 1885, "posY": 962, "uid": "15438494271756", "width": 70 }, { "focused": false, "height": 200, "internalState": { "group": "", "guiItemHidden": false, "label": "", "ratio": 0, "sceneGroup": 0 }, "name": "Crossfade", "nodeMergeModes": { "1": true, "2": true, "3": true }, "posX": 1458, "posY": 515, "uid": "15438497843323", "width": 75 }, { "focused": false, "height": 150, "internalState": { "code": "v = (x<1.0) ? 0 : 1", "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Script", "nodeMergeModes": { "1": true, "2": true, "3": true }, "posX": 1566, "posY": 933, "uid": "15438497925639", "width": 174 }, { "focused": false, "height": 220, "internalState": { "factor": 1, "group": "", "guiItemHidden": false, "inputName": "Microphone Array (Realtek Audio) Left", "label": "", "minBpm": 0, "sceneGroup": 0 }, "name": "Beat Detection", "nodeMergeModes": { }, "posX": 515, "posY": 478, "uid": "15438503151930", "width": 600 }, { "focused": false, "height": 90, "internalState": { "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0, "stepTime": 0.22000000671386738 }, "name": "Tick Generator", "nodeMergeModes": { "1": true }, "posX": 1188, "posY": 581, "uid": "15438503535673", "width": 130 }, { "focused": false, "height": 200, "internalState": { "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0, "subNumber": 1, "value": 0 }, "name": "Eos Sub", "nodeMergeModes": { "0": true }, "posX": 1838, "posY": 452, "uid": "15438504612745", "width": 70 }, { "focused": false, "height": 120, "internalState": { "alwaysStartAtBegin": false, "filePath": "file:///C:/Users/hhinrich/Music/01 - Superliminal.wav", "group": "", "guiItemHidden": false, "label": "", "loop": false, "sceneGroup": 0, "toggleMode": true }, "name": "Audio Playback", "nodeMergeModes": { "0": true, "1": true, "2": true }, "posX": 1320, "posY": 16, "uid": "15438005744316", "width": 480 }, { "focused": false, "height": 30, "internalState": { "additionalValueString": "DMX Value 0", "currentValue": 0, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Value Inspector", "nodeMergeModes": { "0": true }, "posX": 1579, "posY": 435, "uid": "15438507297767", "width": 140 }, { "focused": false, "height": 30, "internalState": { "additionalValueString": "DMX Value 0", "currentValue": 0, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Value Inspector", "nodeMergeModes": { "0": true }, "posX": 1899, "posY": 75, "uid": "15438507295031", "width": 140 }, { "focused": false, "height": 90, "internalState": { "agcEnabled": true, "group": "", "guiItemHidden": false, "inputName": "Microphone Array (Realtek Audio) Left", "label": "", "sceneGroup": 0 }, "name": "Audio Volume", "nodeMergeModes": { }, "posX": 1154, "posY": 754, "uid": "15438698191514", "width": 150 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 2, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 1627, "posY": 721, "uid": "15438698815798", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 3, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 1718, "posY": 722, "uid": "15438698823008", "width": 70 }, { "focused": false, "height": 115, "internalState": { "chanNumber": 4, "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0 }, "name": "Eos Channel", "nodeMergeModes": { "0": true }, "posX": 1829, "posY": 724, "uid": "15438698826989", "width": 70 }, { "focused": false, "height": 60, "internalState": { "group": "", "guiItemHidden": false, "label": "", "pattern": 0, "sceneGroup": 0 }, "name": "1D Pattern", "nodeMergeModes": { "1": true }, "posX": 1401, "posY": 755, "uid": "15438699294523", "width": 90 }, { "focused": false, "height": 60, "internalState": { "group": "", "guiItemHidden": false, "label": "", "sceneGroup": 0, "value": 0 }, "name": "Switch", "nodeMergeModes": { }, "posX": 1204, "posY": 430, "uid": "15438702322796", "width": 90 } ], "connections": [ "15438709137626|1->15438709614538|0", "15438709119308|1->15438709137626|0", "15438709035966|1->15438709119308|0", "15438709012954|1->15438709035966|0", "15438708992629|1->15438709012954|0", "15438708975101|1->15438708992629|0", "15438708967370|1->15438708975101|0", "15438708936805|1->15438708967370|0", "15438708912264|1->15438708936805|0", "15438698806249|1->15438698815798|0", "15438007987350|0->15438005643037|0", "15438007987350|0->15438497925639|1", "15438009184623|0->15438005744316|2", "15438497843323|0->15438507297767|0", "15438497843323|0->15438504612745|0", "15438497925639|0->15438494271756|0", "15438503151930|0->15438503535673|1", "15438503535673|0->15438497843323|2", "15438005744316|5->15438507295031|0", "15438698191514|0->15438699294523|1", "15438698815798|1->15438698823008|0", "15438698823008|1->15438698826989|0", "15438698826989|1->15438708912264|0", "15438699294523|0->15438698806249|0", "15438702322796|0->15438497843323|3" ], "displayedGroup": "", "fileName": "OSC Demo", "midiMapping": { "controlToFeedback": "AAAAAA==", "feedbackEnabled": true, "midiToControl": "AAAAAA==" }, "planeX": -445, "planeY": -293, "version": 0.1 }
unit VariantUtils; interface uses Variants, SysUtils; function VarToStringDef(Value: Variant; default: String = ''): string; function VarToInt(Value: Variant): int64; function VarToIntDef(Value: Variant; default: int64 = 0): int64; function VarToIntf(Value: Variant): IUnknown; function VarToBool(Value: Variant): Boolean; function VarToBoolDef(Value: Variant; default: Boolean = False): Boolean; function VarToFloat(Value: Variant): Extended; function VarToFloatDef(Value: Variant; default: Extended = 0): Extended; function VarToDateTimeDef(Value: Variant; default: TDateTime = 0): TDateTime; function VarIntToSQL(Value: Variant): string; function VarStrToSQL(Value: Variant): string; function GetVariantTypeName(Value: Variant): string; implementation function VarToStringDef(Value: Variant; default: String = ''): string; begin if VarIsNull(Value) then result := Default else result := Value; end; function VarToInt(Value: Variant): int64; begin if VarType(Value) in [varSmallint, varInteger, varBoolean, varShortInt, varByte, varWord, varLongWord, varInt64] then result := Value else raise Exception.Create(format('Unable to convert value from variant type %s to Int', [GetVariantTypeName(Value)])); end; function VarToIntDef(Value: Variant; default: int64 = 0): int64; begin if VarType(Value) in [varSmallint, varInteger, varBoolean, varShortInt, varByte, varWord, varLongWord, varInt64] then result := Value else if (VarType(Value) = varString) or (VarType(Value) = varOleStr) or (VarType(Value) = varUString) then result := StrToIntDef(Value, Default) else result := Default; end; function VarToIntf(Value: Variant): IUnknown; var i: nativeint; begin i := VarToIntDef(Value, 0); result := IUnknown(i); end; function VarToBool(Value: Variant): Boolean; begin if VarType(Value) = varBoolean then result := Value else raise Exception.Create(format('Unable to convert value from variant type %s to Int', [GetVariantTypeName(Value)])); end; function VarToBoolDef(Value: Variant; default: Boolean = False): Boolean; begin if VarType(Value) = varBoolean then result := Value else result := VarToIntDef(Value, integer(Default)) <> 0; end; function VarToFloat(Value: Variant): Extended; begin if VarType(Value) in [varSmallint, varInteger, varBoolean, varShortInt, varByte, varWord, varLongWord, varInt64, varSingle, varDouble, varCurrency, varDate] then result := Value else raise Exception.Create(format('Unable to convert value from variant type %s to Int', [GetVariantTypeName(Value)])); end; function VarToFloatDef(Value: Variant; default: Extended = 0): Extended; begin if VarType(Value) in [varSmallint, varInteger, varBoolean, varShortInt, varByte, varWord, varLongWord, varInt64, varSingle, varDouble, varCurrency, varDate] then result := Value else if (VarType(Value) = varString) or (VarType(Value) = varOleStr) then result := StrToFloatDef(Value, Default) else result := Default; end; function GetVariantTypeName(Value: Variant): string; begin case VarType(Value) of varEmpty: result := 'varEmpty'; varNull: result := 'varNull'; varSmallint: result := 'varSmallint'; varInteger: result := 'varInteger'; varSingle: result := 'varSingle'; varDouble: result := 'varDouble'; varCurrency: result := 'varCurrency'; varDate: result := 'varDate'; varOleStr: result := 'varOleStr'; varDispatch: result := 'varDispatch'; varError: result := 'varError'; varBoolean: result := 'varBoolean'; varVariant: result := 'varVariant'; varUnknown: result := 'varUnknown'; varShortInt: result := 'varShortInt'; varByte: result := 'varByte'; varWord: result := 'varWord'; varLongWord: result := 'varLongWord'; varInt64: result := 'varInt64'; varStrArg: result := 'varStrArg'; varString: result := 'varString'; varAny: result := 'varAny'; varTypeMask: result := 'varTypeMask'; varArray: result := 'varArray'; varByRef: result := 'varByRef'; else result := 'Undefined'; end; end; function VarToDateTimeDef(Value: Variant; default: TDateTime = 0): TDateTime; begin if VarIsNull(Value) then result := Default else result := VarToDateTime(Value); end; function VarIntToSQL(Value: Variant): string; begin if Value = Unassigned then Value := null; if VarIsNull(Value) then result := 'NULL' else result := IntToStr(VarToInt(Value)); end; function VarStrToSQL(Value: Variant): string; begin if VarIsNull(Value) then result := 'NULL' else result := QuotedStr(VarToStr(Value)); end; end.
unit CompressIntf; interface uses Windows, FIFOIntf; type ICompressor = interface['{55624380-6518-11d3-B638-00400566F3E8}'] function SetOutputFIFO(const aFIFO : IFIFO) : hResult; stdcall; function GetOutputFIFO(out aFIFO : IFIFO) : hResult; stdcall; function Reset : hResult; stdcall; function GetInputType(out SamplingRate, BitsPerSample, Channels : integer) : hResult; stdcall; function Convert(const Data; Size : integer) : hResult; stdcall; end; IDecompressor = interface['{55624381-6518-11d3-B638-00400566F3E8}'] function SetInputFIFO(const aFIFO : IFIFO) : hResult; stdcall; function GetInputFIFO(out aFIFO : IFIFO) : hResult; stdcall; function Reset : hResult; stdcall; function GetOutputType(out SamplingRate, BitsPerSample, Channels : integer) : hResult; stdcall; function GetAvailData(out Actual : integer) : hResult; stdcall; function Convert(out Data; Size : integer; out Actual : integer) : hResult; stdcall; end; implementation end.
unit Entidade.Fornecedor; interface uses SimpleAttributes; type TFORNECEDOR= class private FBAIRRO: string; FEMAIL: string; FUSUARIO_CADASTRO: string; FUF: string; FDATA_CADASTRO: TDateTime; FCEP: string; FCPFCNPJ: string; FID: Integer; FNUMERO: string; FNOMERAZAO: string; FTIPO: string; FCIDADE: string; FTELEFONE: string; FRUA: string; FCELULAR: string; procedure SetBAIRRO(const Value: string); procedure SetCELULAR(const Value: string); procedure SetCEP(const Value: string); procedure SetCIDADE(const Value: string); procedure SetCPFCNPJ(const Value: string); procedure SetDATA_CADASTRO(const Value: TDateTime); procedure SetEMAIL(const Value: string); procedure SetID(const Value: Integer); procedure SetNOMERAZAO(const Value: string); procedure SetNUMERO(const Value: string); procedure SetRUA(const Value: string); procedure SetTELEFONE(const Value: string); procedure SetTIPO(const Value: string); procedure SetUF(const Value: string); procedure SetUSUARIO_CADASTRO(const Value: string); published [PK,AutoInc] property ID: Integer read FID write SetID; property NOMERAZAO:string read FNOMERAZAO write SetNOMERAZAO; property CPFCNPJ:string read FCPFCNPJ write SetCPFCNPJ; property EMAIL:string read FEMAIL write SetEMAIL; property TELEFONE:string read FTELEFONE write SetTELEFONE; property CELULAR:string read FCELULAR write SetCELULAR; property RUA:string read FRUA write SetRUA; property NUMERO:string read FNUMERO write SetNUMERO; property BAIRRO:string read FBAIRRO write SetBAIRRO; property CIDADE:string read FCIDADE write SetCIDADE; property UF:string read FUF write SetUF; property CEP:string read FCEP write SetCEP; property USUARIO_CADASTRO:string read FUSUARIO_CADASTRO write SetUSUARIO_CADASTRO; property DATA_CADASTRO:TDateTime read FDATA_CADASTRO write SetDATA_CADASTRO; property TIPO:string read FTIPO write SetTIPO; end; implementation { TFORNECEDOR } procedure TFORNECEDOR.SetBAIRRO(const Value: string); begin FBAIRRO := Value; end; procedure TFORNECEDOR.SetCELULAR(const Value: string); begin FCELULAR := Value; end; procedure TFORNECEDOR.SetCEP(const Value: string); begin FCEP := Value; end; procedure TFORNECEDOR.SetCIDADE(const Value: string); begin FCIDADE := Value; end; procedure TFORNECEDOR.SetCPFCNPJ(const Value: string); begin FCPFCNPJ := Value; end; procedure TFORNECEDOR.SetDATA_CADASTRO(const Value: TDateTime); begin FDATA_CADASTRO := Value; end; procedure TFORNECEDOR.SetEMAIL(const Value: string); begin FEMAIL := Value; end; procedure TFORNECEDOR.SetID(const Value: Integer); begin FID := Value; end; procedure TFORNECEDOR.SetNOMERAZAO(const Value: string); begin FNOMERAZAO := Value; end; procedure TFORNECEDOR.SetNUMERO(const Value: string); begin FNUMERO := Value; end; procedure TFORNECEDOR.SetRUA(const Value: string); begin FRUA := Value; end; procedure TFORNECEDOR.SetTELEFONE(const Value: string); begin FTELEFONE := Value; end; procedure TFORNECEDOR.SetTIPO(const Value: string); begin FTIPO := Value; end; procedure TFORNECEDOR.SetUF(const Value: string); begin FUF := Value; end; procedure TFORNECEDOR.SetUSUARIO_CADASTRO(const Value: string); begin FUSUARIO_CADASTRO := Value; end; end.
unit UDemo; interface uses SysUtils, Types, UITypes, Classes, Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSBaseControl, FMX.TMSGridOptions, FMX.TMSGridData, FMX.TMSGrid, FMX.GridExcelIO, FMX.TMSBitmapContainer, FMX.TMSGridCell, FMX.TMSXUtil, UIConsts, FMX.TMSCustomGrid, FMX.StdCtrls; type TForm719 = class(TForm) TMSFMXGrid1: TTMSFMXGrid; Panel1: TPanel; Button1: TButton; TMSFMXBitmapContainer1: TTMSFMXBitmapContainer; TMSFMXGridExcelIO1: TTMSFMXGridExcelIO; Button2: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure TMSFMXGrid1GetCellLayout(Sender: TObject; ACol, ARow: Integer; ALayout: TTMSFMXGridCellLayout; ACellState: TCellState); private { Private declarations } public { Public declarations } procedure InitGrid; end; var Form719: TForm719; implementation {$IFDEF WIN32} uses ShellAPI,Windows; {$ENDIF} {$R *.fmx} { TForm719 } procedure TForm719.Button1Click(Sender: TObject); begin TMSFMXGridExcelIO1.XLSExport('..\..\gridexport.xls'); XOpenFile('open', '..\..\gridexport.xls', '', ''); end; procedure TForm719.Button2Click(Sender: TObject); begin TMSFMXGridExcelIO1.XLSImport('..\..\cars.xls'); end; procedure TForm719.FormCreate(Sender: TObject); begin TMSFMXGridExcelIO1.Options.ImportCellProperties := true; TMSFMXGridExcelIO1.Options.ExportCellProperties := true; TMSFMXGridExcelIO1.Options.ExportOverwrite := omAlways; TMSFMXGridExcelIO1.Options.ExportImages := true; InitGrid; end; procedure TForm719.InitGrid; begin TMSFMXGrid1.ColumnCount := 6; TMSFMXGrid1.RandomFill; TMSFMXGrid1.AutoNumberCol(0); TMSFMXGrid1.Colors[2,2] := claRed; TMSFMXGrid1.Colors[3,3] := claLime; TMSFMXGrid1.Colors[4,4] := claYellow; TMSFMXGrid1.HorzAlignments[2,3] := TTextAlign.taCenter; TMSFMXGrid1.HorzAlignments[3,4] := TTextAlign.taTrailing; TMSFMXGrid1.FontStyles[1,1] := [TFontStyle.fsBold]; TMSFMXGrid1.FontStyles[1,2] := [TFontStyle.fsItalic]; TMSFMXGrid1.MergeCells(1,4,2,2); TMSFMXGrid1.AddBitmap(1,7,'1'); TMSFMXGrid1.AddBitmap(1,8,'2'); TMSFMXGrid1.AddBitmap(1,9,'3'); end; procedure TForm719.TMSFMXGrid1GetCellLayout(Sender: TObject; ACol, ARow: Integer; ALayout: TTMSFMXGridCellLayout; ACellState: TCellState); begin if (ACol = 5) then begin ALayout.FontFill.Color := claRed; ALayout.TextAlign := TTextAlign.taTrailing; end; end; end.
program pcibil; {============================================================================== Kodlayan: Fatih KILIÇ Telif Bilgisi: haklar.txt dosyasına bakınız Program Adı: pcibil.lpr Program İşlevi: pci aygıtları hakkında bilgi verir Güncelleme Tarihi: 15/05/2013 ==============================================================================} {$mode objfpc} uses process, forms, buttons; const sAppName: string = 'PCI Aygıt Bilgileri'; type TPciClass = record ClassCode: LongWord; ClassName: string; end; var PciClassList: array[0..139] of TPciClass = ( (ClassCode: $000000; ClassName: 'Old No-VGA combatible device'), (ClassCode: $000100; ClassName: 'Old VGA combatible device'), (ClassCode: $010000; ClassName: 'SCSI bus controller'), (ClassCode: $01018a; ClassName: 'IDE controller'), (ClassCode: $010185; ClassName: 'IDE Mass Storage'), (ClassCode: $010200; ClassName: 'Floppy disk controller'), (ClassCode: $010300; ClassName: 'IPI bus controller'), (ClassCode: $010400; ClassName: 'RAID controller'), (ClassCode: $010520; ClassName: 'ATA controller with single DMA'), (ClassCode: $010530; ClassName: 'ATA controller with chained DMA'), (ClassCode: $010600; ClassName: 'Serial ATA Direct Port Access (DPA)'), (ClassCode: $010601; ClassName: 'SATA Mass Storage'), (ClassCode: $018000; ClassName: 'Other mass storage controller'), (ClassCode: $020000; ClassName: 'Ethernet controller'), (ClassCode: $020100; ClassName: 'Token Ring controller'), (ClassCode: $020200; ClassName: 'FDDI controller'), (ClassCode: $020300; ClassName: 'ATM controller'), (ClassCode: $020400; ClassName: 'ISDN controller'), (ClassCode: $020500; ClassName: 'WorldFip controller'), (ClassCode: $020600; ClassName: 'PICMG 2.14 Multi Computing'), (ClassCode: $028000; ClassName: 'Other network controller'), (ClassCode: $030000; ClassName: 'VGA-compatible controller'), (ClassCode: $030001; ClassName: '8514-compatible controller'), (ClassCode: $030100; ClassName: 'XGA controller'), (ClassCode: $030200; ClassName: '3D controller'), (ClassCode: $038000; ClassName: 'Other display controller'), (ClassCode: $040000; ClassName: 'Video device'), (ClassCode: $040100; ClassName: 'Audio device'), (ClassCode: $040200; ClassName: 'Computer telephony device'), (ClassCode: $040300; ClassName: 'Multimedia'), (ClassCode: $048000; ClassName: 'Other multimedia device'), (ClassCode: $050000; ClassName: 'RAM'), (ClassCode: $050100; ClassName: 'Flash'), (ClassCode: $058000; ClassName: 'Other memory controller'), (ClassCode: $060000; ClassName: 'Host bridge'), (ClassCode: $060100; ClassName: 'ISA bridge'), (ClassCode: $060200; ClassName: 'EISA bridge'), (ClassCode: $060300; ClassName: 'MCA bridge'), (ClassCode: $060400; ClassName: 'PCI-to-PCI bridge'), (ClassCode: $060401; ClassName: 'Subtractive Decode PCI-to-PCI bridge'), (ClassCode: $060500; ClassName: 'PCMCIA bridge'), (ClassCode: $060600; ClassName: 'NuBus bridge'), (ClassCode: $060700; ClassName: 'CardBus bridge'), (ClassCode: $060800; ClassName: 'RACEway bridge'), (ClassCode: $060940; ClassName: 'Semi-transparent PCI-to-PCI bridge (pri)'), (ClassCode: $060980; ClassName: 'Semi-transparent PCI-to-PCI bridge (sec)'), (ClassCode: $060a00; ClassName: 'InfiniBand-to-PCI host bridge'), (ClassCode: $068000; ClassName: 'Other bridge device'), (ClassCode: $070000; ClassName: 'Generic XT-compatible serial controller'), (ClassCode: $070001; ClassName: '16450-compatible serial controller'), (ClassCode: $070002; ClassName: '16550-compatible serial controller'), (ClassCode: $070003; ClassName: '16650-compatible serial controller'), (ClassCode: $070004; ClassName: '16750-compatible serial controller'), (ClassCode: $070005; ClassName: '16850-compatible serial controller'), (ClassCode: $070006; ClassName: '16950-compatible serial controller'), (ClassCode: $070100; ClassName: 'Parallel port'), (ClassCode: $070101; ClassName: 'Bidirectional parallel port'), (ClassCode: $070102; ClassName: 'ECP 1.X compliant parallel port'), (ClassCode: $070103; ClassName: 'IEEE1284 controller'), (ClassCode: $0701fe; ClassName: 'IEEE1284 target device (not a controller)'), (ClassCode: $070200; ClassName: 'Multiport serial controller'), (ClassCode: $070300; ClassName: 'Generic modem'), (ClassCode: $070301; ClassName: 'Hayes compatible modem (16450)'), (ClassCode: $070302; ClassName: 'GPIB (IEEE 488.1/2) controller'), (ClassCode: $070303; ClassName: 'Smart Card'), (ClassCode: $070304; ClassName: 'Hayes compatible modem (16550)'), (ClassCode: $070400; ClassName: 'Hayes compatible modem (16650)'), (ClassCode: $070500; ClassName: 'Hayes compatible modem (16750)'), (ClassCode: $078000; ClassName: 'Other communications device'), (ClassCode: $080000; ClassName: 'Generic 8259 PIC'), (ClassCode: $080001; ClassName: 'ISA PIC'), (ClassCode: $080002; ClassName: 'EISA PIC'), (ClassCode: $080010; ClassName: 'I/O APIC interrupt controller'), (ClassCode: $080020; ClassName: 'I/O(x) APIC interrupt controller'), (ClassCode: $080100; ClassName: 'Generic 8237 DMA controller'), (ClassCode: $080101; ClassName: 'ISA DMA controller'), (ClassCode: $080102; ClassName: 'EISA DMA controller'), (ClassCode: $080200; ClassName: 'Generic 8254 system timer'), (ClassCode: $080201; ClassName: 'ISA system timer'), (ClassCode: $080202; ClassName: 'EISA system timers'), (ClassCode: $080300; ClassName: 'Generic RTC controller'), (ClassCode: $080301; ClassName: 'ISA RTC controller'), (ClassCode: $080400; ClassName: 'Generic PCI Hot-Plug controller'), (ClassCode: $080501; ClassName: 'Base Peripheral'), (ClassCode: $088000; ClassName: 'Other system peripheral'), (ClassCode: $090000; ClassName: 'Keyboard controller'), (ClassCode: $090100; ClassName: 'Digitizer (pen)'), (ClassCode: $090200; ClassName: 'Mouse controller'), (ClassCode: $090300; ClassName: 'Scanner controller'), (ClassCode: $090400; ClassName: 'Gameport controller (generic)'), (ClassCode: $090410; ClassName: 'Gameport controller (legacy)'), (ClassCode: $098000; ClassName: 'Other input controller'), (ClassCode: $0a0000; ClassName: 'Generic docking station'), (ClassCode: $0a8000; ClassName: 'Other type of docking station'), (ClassCode: $0b0000; ClassName: '386'), (ClassCode: $0b0100; ClassName: '486'), (ClassCode: $0b0200; ClassName: 'Pentium'), (ClassCode: $0b1000; ClassName: 'Alpha'), (ClassCode: $0b2000; ClassName: 'PowerPC'), (ClassCode: $0b3000; ClassName: 'MIPS'), (ClassCode: $0b4000; ClassName: 'Co-processor'), (ClassCode: $0c0000; ClassName: 'IEEE 1394 (FireWire)'), (ClassCode: $0c0010; ClassName: 'IEEE 1394 (FireWire) OHCI'), (ClassCode: $0c0100; ClassName: 'ACCESS.bus'), (ClassCode: $0c0200; ClassName: 'SSA'), (ClassCode: $0c0300; ClassName: 'USB Controller (UHCI)'), (ClassCode: $0c0310; ClassName: 'USB Controller (OHCI)'), (ClassCode: $0c0320; ClassName: 'USB Controller (EHCI)'), (ClassCode: $0c0380; ClassName: 'USB Controller'), (ClassCode: $0c03fe; ClassName: 'USB Device'), (ClassCode: $0c0400; ClassName: 'Fibre Channel'), (ClassCode: $0c0500; ClassName: 'SMBus'), (ClassCode: $0c0600; ClassName: 'InfiniBand'), (ClassCode: $0c0700; ClassName: 'IPMI SMIC Interface'), (ClassCode: $0c0701; ClassName: 'IPMI Kybd Controller Style Interface'), (ClassCode: $0c0702; ClassName: 'IPMI Block Transfer Interfac'), (ClassCode: $0c0800; ClassName: 'SERCOS Interface Standard (IEC 61491)'), (ClassCode: $0c0900; ClassName: 'CANbus'), (ClassCode: $0d0000; ClassName: 'iRDA compatible controller'), (ClassCode: $0d0100; ClassName: 'Consumer IR controller'), (ClassCode: $0d1000; ClassName: 'RF controller'), (ClassCode: $0d1100; ClassName: 'Bluetooth'), (ClassCode: $0d1200; ClassName: 'Broadband'), (ClassCode: $0d2000; ClassName: 'Ethernet (802.11a - 5 GHz)'), (ClassCode: $0d2100; ClassName: 'Ethernet (802.11b - 2.4 GHz)'), (ClassCode: $0d8000; ClassName: 'Other type of wireless controller'), (ClassCode: $0e0000; ClassName: 'Intelligent I/O (I2O) Architecture Spec 1.0'), (ClassCode: $0e0000; ClassName: 'Message FIFO at offset $40'), (ClassCode: $0f0100; ClassName: 'Satellite TV'), (ClassCode: $0f0200; ClassName: 'Satellite Audio'), (ClassCode: $0f0300; ClassName: 'Satellite Voice'), (ClassCode: $0f0400; ClassName: 'Satellite Data'), (ClassCode: $100000; ClassName: 'Network and computing en/decryption'), (ClassCode: $101000; ClassName: 'Entertainment en/decryption'), (ClassCode: $108000; ClassName: 'Other en/decryption'), (ClassCode: $110000; ClassName: 'DPIO modules'), (ClassCode: $110100; ClassName: 'Performance counters'), (ClassCode: $111000; ClassName: 'Communications synchronization plus time and frequency test/measurement'), (ClassCode: $112000; ClassName: 'Management card'), (ClassCode: $118000; ClassName: 'Other data acquisition/signal processing controllers')); type TVendors = record VendID: Word; VendName: string; end; var VendorList: array[0..12] of TVendors = ( (VendID: $1000; VendName: 'LSI Logic / Symbios Logic'), (VendID: $1022; VendName: 'Advanced Micro Devices'), (VendID: $104c; VendName: 'Texas Instruments'), (VendID: $106b; VendName: 'Apple Inc'), (VendID: $109e; VendName: 'Brooktree Corporation'), (VendID: $10de; VendName: 'nVidia Corporation'), (VendID: $10ec; VendName: 'Realtek Semiconductor Co.Ltd'), (VendID: $1217; VendName: 'O2 Micro, Inc'), (VendID: $1274; VendName: 'Ensoniq'), (VendID: $15ad; VendName: 'VMware'), (VendID: $168c; VendName: 'Atheros Communications Inc'), (VendID: $8086; VendName: 'Intel Corporation'), (VendID: $80ee; VendName: 'InnoTek Systemberatung GmbH')); type TPciDevice = record VendID: Word; DevID: Word; DevName: string; end; var PciDeviceList: array[0..65] of TPciDevice = ( (VendID: $1000; DevID: $0030; DevName: '53c1030 PCI-X Fusion-MPT Dual Ultra320 SCSI'), (VendID: $1022; DevID: $1100; DevName: 'K8 [Athlon64/Opteron] HyperTransport Technology Configuration'), (VendID: $1022; DevID: $1101; DevName: 'K8 [Athlon64/Opteron] Address Map'), (VendID: $1022; DevID: $1102; DevName: 'K8 [Athlon64/Opteron] DRAM Controller'), (VendID: $1022; DevID: $1103; DevName: 'K8 [Athlon64/Opteron] Miscellaneous Control'), (VendID: $1022; DevID: $2000; DevName: 'Am79C970/1/2/3/5/6 PCnet LANCE PCI Ethernet Controller'), (VendID: $104c; DevID: $8024; DevName: 'TSB43AB23 IEEE-1394a-2000 Controller (PHY/Link)'), (VendID: $106b; DevID: $003f; DevName: 'KeyLargo/Intrepid USB'), (VendID: $109e; DevID: $036e; DevName: 'Bt878 Video Capture'), (VendID: $109e; DevID: $0878; DevName: 'Bt878 Audio Capture'), (VendID: $10de; DevID: $01d3; DevName: 'G72 [GeForce 7300 SE/7200 GS]'), (VendID: $10de; DevID: $0441; DevName: 'MCP65 LPC Bridge'), (VendID: $10de; DevID: $0444; DevName: 'MCP65 Memory Controller'), (VendID: $10de; DevID: $0445; DevName: 'MCP65 Memory Controller'), (VendID: $10de; DevID: $0446; DevName: 'MCP65 SMBus'), (VendID: $10de; DevID: $0448; DevName: 'MCP65 IDE'), (VendID: $10de; DevID: $0449; DevName: 'MCP65 PCI bridge'), (VendID: $10de; DevID: $044a; DevName: 'MCP65 High Definition Audio'), (VendID: $10de; DevID: $0450; DevName: 'MCP65 Ethernet'), (VendID: $10de; DevID: $0454; DevName: 'MCP65 USB Controller'), (VendID: $10de; DevID: $0455; DevName: 'MCP65 USB Controller'), (VendID: $10de; DevID: $0458; DevName: 'MCP65 PCI Express bridge'), (VendID: $10de; DevID: $045d; DevName: 'MCP65 SATA Controller'), (VendID: $10ec; DevID: $8139; DevName: 'RTL-8139/8139C/8139C+'), (VendID: $10ec; DevID: $8168; DevName: 'RTL8111/8168B PCI Express Gigabit Ethernet controller'), (VendID: $1217; DevID: $00f7; DevName: '1394 Open Host Controller Interface'), (VendID: $1217; DevID: $7120; DevName: 'Integrated MMC/SD Controller'), (VendID: $1217; DevID: $7130; DevName: 'Integrated MS/xD Controller'), (VendID: $1217; DevID: $7136; DevName: 'OZ711SP1 Memory CardBus Controller'), (VendID: $1274; DevID: $1371; DevName: 'ES1371 [AudioPCI-97]'), (VendID: $15ad; DevID: $0405; DevName: 'SVGA II Adapter'), (VendID: $15ad; DevID: $0740; DevName: 'Virtual Machine Communication Interface'), (VendID: $15ad; DevID: $0770; DevName: 'USB2 EHCI Controller'), (VendID: $15ad; DevID: $0790; DevName: 'PCI bridge'), (VendID: $15ad; DevID: $07a0; DevName: 'PCI Express Root Port'), (VendID: $168c; DevID: $011c; DevName: 'AR5001 Wireless Network Adapter'), (VendID: $8086; DevID: $100f; DevName: '82545EM Gigabit Ethernet Controller (Copper)'), (VendID: $8086; DevID: $1237; DevName: '82441FX PCI & Memory Controller (PMC)'), (VendID: $8086; DevID: $2415; DevName: '82801AA AC97 Audio Controller'), (VendID: $8086; DevID: $2448; DevName: '82801 Mobile PCI Bridge'), (VendID: $8086; DevID: $265c; DevName: '82801FB/FBM/FR/FW/FRW (ICH6 Family) USB2 EHCI Controller'), (VendID: $8086; DevID: $2815; DevName: '82801HEM (ICH8M) LPC Interface Controller'), (VendID: $8086; DevID: $2829; DevName: '82801HBM/HEM (ICH8M/ICH8M-E) SATA AHCI Controller'), (VendID: $8086; DevID: $2830; DevName: '82801H (ICH8 Family) USB UHCI Controller #1'), (VendID: $8086; DevID: $2831; DevName: '82801H (ICH8 Family) USB UHCI Controller #2'), (VendID: $8086; DevID: $2832; DevName: '82801H (ICH8 Family) USB UHCI Controller #3'), (VendID: $8086; DevID: $2834; DevName: '82801H (ICH8 Family) USB UHCI Controller #4'), (VendID: $8086; DevID: $2835; DevName: '82801H (ICH8 Family) USB UHCI Controller #5'), (VendID: $8086; DevID: $2836; DevName: '82801H (ICH8 Family) USB2 EHCI Controller #1'), (VendID: $8086; DevID: $283a; DevName: '82801H (ICH8 Family) USB2 EHCI Controller #2'), (VendID: $8086; DevID: $283e; DevName: '82801H (ICH8 Family) SMBus Controller'), (VendID: $8086; DevID: $283f; DevName: '82801H (ICH8 Family) PCI Express Port 1'), (VendID: $8086; DevID: $2843; DevName: '82801H (ICH8 Family) PCI Express Port 3'), (VendID: $8086; DevID: $284b; DevName: '82801H (ICH8 Family) HD Audio Controller'), (VendID: $8086; DevID: $2850; DevName: '82801HBM/HEM (ICH8M/ICH8M-E) IDE Controller'), (VendID: $8086; DevID: $2a00; DevName: 'Mobile PM965/GM965/GL960 Memory Controller Hub'), (VendID: $8086; DevID: $2a03; DevName: 'Mobile GM965/GL960 Integrated Graphics Controller'), (VendID: $8086; DevID: $7000; DevName: '82371SB PIIX3 PCI-to-ISA Bridge (Triton II)'), (VendID: $8086; DevID: $7110; DevName: '82371AB/EB/MB PIIX4 ISA'), (VendID: $8086; DevID: $7111; DevName: '82371AB/EB/MB PIIX4/4E/4M IDE Controller'), (VendID: $8086; DevID: $7112; DevName: '82371AB/EB/MB PIIX4 USB'), (VendID: $8086; DevID: $7113; DevName: '82371AB/EB/MB PIIX4/4E/4M Power Management Controller'), (VendID: $8086; DevID: $7190; DevName: '440BX/ZX/DX - 82443BX/ZX/DX Host bridge'), (VendID: $8086; DevID: $7191; DevName: '440BX/ZX/DX - 82443BX/ZX/DX AGP bridge'), (VendID: $80ee; DevID: $cafe; DevName: 'VirtualBox Guest Service'), (VendID: $80ee; DevID: $beef; DevName: 'VirtualBox Graphics Adapter')); var Application: TApplication; frmMain: TForm; btnNextBtn, btnPrevBtn: TButton; TotalPciDevNums: Word; CurrentPciDev: Word; PciDevInfo: TPciDevInfo; Event: TEv; Val32: LongWord; Val8: Byte; i, k: SmallInt; BaseAddr: LongWord; DevType: string; VendorName: string; PciDevName: string; function GetPciDevType(ClassCode: LongWord): string; var i: Byte; begin for i := 0 to 139 do begin if(PciClassList[i].ClassCode = ClassCode) then begin GetPciDevType := PciClassList[i].ClassName; Exit; end; end; GetPciDevType := 'Bilinmeyen Aygıt Tipi'; end; function GetPciVendor(VendorID: Word): string; var i: Byte; begin for i := 0 to 12 do begin if(VendorList[i].VendID = VendorID) then begin GetPciVendor := VendorList[i].VendName; Exit; end; end; GetPciVendor := 'Bilinmeyen Satıcı'; end; function GetPciDevName(VendID, DevID: Word): string; var i: Byte; begin for i := 0 to 65 do begin if(PciDeviceList[i].VendID = VendID) and (PciDeviceList[i].DevID = DevID) then begin GetPciDevName := PciDeviceList[i].DevName; Exit; end; end; GetPciDevName := 'Bilinmeyen Aygıt'; end; begin frmMain.Create(-1, 50, 10, 475, 450, bsDialog, sAppName); if(frmMain.Handle < 0) then Application.Terminate; btnNextBtn.Create(frmMain.Handle, 392, 2, 65, 20, 'Sonraki'); btnNextBtn.Show; btnPrevBtn.Create(frmMain.Handle, 392, 24, 65, 20, 'Önceki'); btnPrevBtn.Show; frmMain.Show; CurrentPciDev := 0; TotalPciDevNums := GetPciDevNums; if(TotalPciDevNums > 0) then GetPciDevInfo(CurrentPciDev, @PciDevInfo); repeat Application.WaitEvent(Event); if(Event.Event = ONMOUSE_CLICK) then begin if(Event.Handle = btnNextBtn.Handle) then begin if(CurrentPciDev + 1 < TotalPciDevNums) then Inc(CurrentPciDev); end else if(Event.Handle = btnPrevBtn.Handle) then begin if(CurrentPciDev - 1 >= 0) then Dec(CurrentPciDev); end; GetPciDevInfo(CurrentPciDev, @PciDevInfo); frmMain.Draw; end else if(Event.Event = ONDRAW) then begin frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 0*16, 'Aygıt No:'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(10*8, 0*16, True, 2, CurrentPciDev + 1); frmMain.Canvas.WriteChar(14*8, 0*16, ':'); frmMain.Canvas.WriteHex(15*8, 0*16, True, 2, TotalPciDevNums); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 2*16, 'Bus :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(6*8, 2*16, True, 2, PciDevInfo.Bus); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(18*8, 2*16, 'Dev :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(24*8, 2*16, True, 2, PciDevInfo.Dev); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(35*8, 2*16, 'Func :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(42*8, 2*16, True, 2, PciDevInfo.Func); Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, 4); PciDevInfo.Command := (Val32 and $ffff); PciDevInfo.Status := ((Val32 shr 16) and $ffff); Val8 := PciReadByte(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, 8); PciDevInfo.RevId := Val8; frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 3*16, 'Command :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(10*8, 3*16, True, 4, PciDevInfo.Command); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(18*8, 3*16, 'Status :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(27*8, 3*16, True, 4, PciDevInfo.Status); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(35*8, 3*16, 'Rev-ID :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(44*8, 3*16, True, 2, PciDevInfo.RevId); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 5*16, 'Device Class :'); DevType := GetPciDevType(PciDevInfo.ClassCode); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.TextOut(15*8, 5*16, DevType); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 6*16, 'Vendor :'); frmMain.Canvas.Pen.Color := COLOR_RED; frmMain.Canvas.WriteHex(9*8, 6*16, True, 4, PciDevInfo.VendId); frmMain.Canvas.WriteChar(16*8, 6*16, '-'); VendorName := GetPciVendor(PciDevInfo.VendId); frmMain.Canvas.TextOut(18*8, 6*16, VendorName); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 7*16, 'Device :'); frmMain.Canvas.Pen.Color := COLOR_RED; frmMain.Canvas.WriteHex(9*8, 7*16, True, 4, PciDevInfo.DevId); frmMain.Canvas.WriteChar(16*8, 7*16, '-'); PciDevName := GetPciDevName(PciDevInfo.VendId, PciDevInfo.DevId); frmMain.Canvas.TextOut(18*8, 7*16, PciDevName); Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $c); PciDevInfo.CacheLineSize := (Val32 and $ff); PciDevInfo.LatencyTimer := ((Val32 shr 8) and $ff); PciDevInfo.HeaderType := ((Val32 shr 16) and $ff); PciDevInfo.Bist := ((Val32 shr 24) and $ff); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 9*16, 'Cache Line Size :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(18*8, 9*16, True, 2, PciDevInfo.CacheLineSize); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(28*8, 9*16, 'Latency Timer :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(44*8, 9*16, True, 2, PciDevInfo.LatencyTimer); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 10*16, 'Header Type :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(14*8, 10*16, True, 2, PciDevInfo.HeaderType); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(28*8, 10*16, 'BIST :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(35*8, 10*16, True, 2, PciDevInfo.Bist); Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $2c); PciDevInfo.SubsysVendId := (Val32 and $ffff); PciDevInfo.SubsysId := ((Val32 shr 16) and $ffff); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 11*16, 'Subsystem VID :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(16*8, 11*16, True, 4, PciDevInfo.SubsysVendId); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(28*8, 11*16, 'Subsystem ID :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(43*8, 11*16, True, 4, PciDevInfo.SubsysId); Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $3c); PciDevInfo.IntLine := (Val32 and $ff); PciDevInfo.IntPin := ((Val32 shr 8) and $ff); PciDevInfo.MinGnt := ((Val32 shr 16) and $ff); PciDevInfo.MaxLat := ((Val32 shr 24) and $ff); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 13*16, 'Int Line :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(11*8, 13*16, True, 2, PciDevInfo.IntLine); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(28*8, 13*16, 'Int Pin :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(38*8, 13*16, True, 2, PciDevInfo.IntPin); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 14*16, 'Min Gnt :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(10*8, 14*16, True, 2, PciDevInfo.MinGnt); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(28*8, 14*16, 'Max Lat :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(38*8, 14*16, True, 2, PciDevInfo.MaxLat); Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $28); PciDevInfo.CardbusCisp := Val32; Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $30); PciDevInfo.ExpRomBaseAddr := Val32; frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 16*16, 'CardBus CIS Pointer :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(22*8, 16*16, True, 8, PciDevInfo.CardbusCisp); frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 17*16, 'EXP-ROM Base Addr :'); frmMain.Canvas.Pen.Color := COLOR_BLUE; frmMain.Canvas.WriteHex(20*8, 17*16, True, 8, PciDevInfo.ExpRomBaseAddr); Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $10); PciDevInfo.BaseAddr[0] := Val32; Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $14); PciDevInfo.BaseAddr[1] := Val32; Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $18); PciDevInfo.BaseAddr[2] := Val32; Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $1c); PciDevInfo.BaseAddr[3] := Val32; Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $20); PciDevInfo.BaseAddr[4] := Val32; Val32 := PciReadDWord(PciDevInfo.Bus, PciDevInfo.Dev, PciDevInfo.Func, $24); PciDevInfo.BaseAddr[5] := Val32; frmMain.Canvas.Pen.Color := COLOR_BLACK; frmMain.Canvas.TextOut(0, 19*16, 'Kaynaklar :'); k := 20; for i := 0 to 5 do begin frmMain.Canvas.Pen.Color := COLOR_BLUE; if((PciDevInfo.BaseAddr[i] and 1) = 1) then begin BaseAddr := (PciDevInfo.BaseAddr[i] and (not 3)); if(BaseAddr > 0) then begin frmMain.Canvas.WriteHex(5*8, k*16, True, 8, BaseAddr); frmMain.Canvas.TextOut(16*8, k*16, '- IO'); Inc(k); end; end else begin BaseAddr := (PciDevInfo.BaseAddr[i] and (not 15)); if(BaseAddr > 0) then begin frmMain.Canvas.WriteHex(5*8, k*16, True, 8, BaseAddr); frmMain.Canvas.TextOut(16*8, k*16, '- MEM'); Inc(k); end; end; end; end; until (1 = 2); end.
{--------------------------------------------------------------} { Unit Declaration } unit pastemyst; {--------------------------------------------------------------} { switches } {$mode delphi} {==============================================================} { Public Interface } interface {--------------------------------------------------------------} { Fetches a paste with given id } function get_paste(_id: string): string; {--------------------------------------------------------------} { Fetches a private paste with given id } function get_private_paste(_id: string; _token: string): string; {--------------------------------------------------------------} { Creating a new public paste } function create_paste(params: string): string; {--------------------------------------------------------------} { Creating a new private paste } function create_private_paste(params: string; _token: string): string; {--------------------------------------------------------------} { Editing an existing paste } function edit_paste(_id: string; params: string; _token: string): string; {--------------------------------------------------------------} { Delete an existing paste } function delete_paste(_id: string; _token: string): string; {--------------------------------------------------------------} { Get info about a user } function get_user(user_name: string): string; {--------------------------------------------------------------} { Checks whether user exists } function user_exists(user_name: string): integer; {--------------------------------------------------------------} { Get programming language by it's name } function get_language_by_name(_name: string): string; {--------------------------------------------------------------} { Get programming language by it's extension } function get_language_by_extension(extension: string): string; {==============================================================} { Private Implementation } implementation {--------------------------------------------------------------} { Units } uses fphttpclient, opensslsockets, SysUtils, classes; {--------------------------------------------------------------} { Constant Declarations } const url = 'https://paste.myst.rs/api/v2/'; {--------------------------------------------------------------} { Variable Declarations } Var Client : TFPHttpClient; Response : TStringStream; {--------------------------------------------------------------} { Fetches a paste with given id } function get_paste(_id: string): string; begin Client := TFPHttpClient.Create(Nil); try get_paste := Client.Get(url + 'paste/' + _id); finally Client.Free; end; end; {--------------------------------------------------------------} { Fetches a private paste with given id } function get_private_paste(_id: string; _token: string): string; begin Client := TFPHttpClient.Create(Nil); Client.AddHeader('Authorization', _token); try get_private_paste := Client.Get(url + 'paste/' + _id); finally Client.Free; end; end; {--------------------------------------------------------------} { Creating a new public paste } function create_paste(params: string): string; begin Client := TFPHttpClient.Create(Nil); Client.AddHeader('Content-Type','application/json; charset=UTF-8'); Client.RequestBody := TRawByteStringStream.Create(params); Response := TStringStream.Create(''); try Client.Post(url + 'paste', Response); create_paste := Response.DataString; finally Client.RequestBody.Free; Client.Free; Response.Free; end; end; {--------------------------------------------------------------} { Creating a new private paste } function create_private_paste(params: string; _token: string): string; begin Client := TFPHttpClient.Create(Nil); Client.AddHeader('Content-Type', 'application/json; charset=UTF-8'); Client.AddHeader('Authorization', _token); Client.RequestBody := TRawByteStringStream.Create(params); Response := TStringStream.Create(''); try Client.Post(url + 'paste', Response); create_paste := Response.DataString; finally Client.RequestBody.Free; Client.Free; Response.Free; end; end; {--------------------------------------------------------------} { Editing an existing paste } function edit_paste(_id: string; params: string; _token: string): string; begin Client := TFPHttpClient.Create(Nil); Client.AddHeader('Content-Type', 'application/json; charset=UTF-8'); Client.AddHeader('Authorization', _token); Client.RequestBody := TRawByteStringStream.Create(params); Response := TStringStream.Create(''); try Client.HTTPMethod('PATCH', url + 'paste/' + _id, Response, []); create_paste := Response.DataString; finally Client.RequestBody.Free; Client.Free; Response.Free; end; end; {--------------------------------------------------------------} { Delete an existing paste } function delete_paste(_id: string; _token: string): string; begin Client := TFPHttpClient.Create(Nil); Client.AddHeader('Authorization', _token); try delete_paste := Client.Delete(url + 'paste/' + _id); finally Client.Free; end; end; {--------------------------------------------------------------} { Get info about a user } function get_user(user_name: string): string; begin Client := TFPHttpClient.Create(Nil); try get_user := Client.Get(url + 'user/' + user_name); finally Client.Free; end; end; {--------------------------------------------------------------} { Checks whether user exists } function user_exists(user_name: string): integer; begin Client := TFPHttpClient.Create(Nil); try Client.Get(url + 'user/' + user_name + '/exists'); user_exists := Client.ResponseStatusCode // make it return a boolean later finally Client.Free; end; end; {--------------------------------------------------------------} { Get programming language by it's name } function get_language_by_name(_name: string): string; begin Client := TFPHttpClient.Create(Nil); try get_language_by_name := Client.Get(url + 'data/language?name=' + _name); finally Client.Free; end; end; {--------------------------------------------------------------} { Get programming language by it's extension } function get_language_by_extension(extension: string): string; begin Client := TFPHttpClient.Create(Nil); try get_language_by_extension := Client.Get(url + 'data/languageExt?extension=' + extension) finally Client.Free; end; end; {--------------------------------------------------------------} end.
unit fSpriteChange; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GR32_Image, gr32,DanHexEdit, Spin, gr32_layers, cMegaROM, cConfiguration; type TfrmSpriteChange = class(TForm) lbl80: TLabel; lbl90: TLabel; lblA0: TLabel; lblBO: TLabel; lblC0: TLabel; imgSprPal3: TImage32; imgSprPal4: TImage32; cmdOK: TButton; cmdCancel: TButton; lblSpritePalette3: TLabel; lblSpritePalette4: TLabel; img80: TImage32; img90: TImage32; imgA0: TImage32; imgB0: TImage32; imgC0: TImage32; cb80: TComboBox; cb90: TComboBox; cbA0: TComboBox; cbB0: TComboBox; cbC0: TComboBox; lblSpriteChangeSet: TLabel; txtSpriteChangeSet: TSpinEdit; imgNESColours: TImage32; lbl000F: TLabel; lbl101F: TLabel; lbl202F: TLabel; lbl303F: TLabel; lblCurrentPalette: TLabel; lblRoom: TLabel; cbRoom: TComboBox; procedure FormShow(Sender: TObject); procedure cb80Change(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure txtSpriteChangeSetChange(Sender: TObject); procedure imgSprPal3MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure imgNESColoursMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure imgSprPal4MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); procedure imgNESColoursMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; _TileX, _TileY : Integer; _CurColour : Byte; _CurrentSet : Byte; // _IgnoreChanges : Boolean; _SprPal3 : Array [0..2] of Byte; _SprPal4 : Array [0..2] of Byte; _SpriteSettings : Array [0..4] of Integer; procedure DrawNESColours; procedure DrawSpriteChange; procedure DrawPalettes; procedure SaveData; procedure LoadData; { Private declarations } public property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmSpriteChange: TfrmSpriteChange; implementation {$R *.dfm} uses uglobal; procedure TfrmSpriteChange.FormShow(Sender: TObject); var i : Integer; begin _TileX := 0; _TileY := 0; _CurColour := 0; cb80.Items.Clear; cb80.Items.BeginUpdate; for i := 0 to $FF do cb80.Items.Add(IntToHex((i * $100) + $10,4)); for i := 0 to $2F do cbRoom.Items.Add(IntToHex(i,2)); cb80.ItemIndex := 0; cb80.Items.EndUpdate; // _IgnoreChanges := True; cb90.Items := cb80.Items; cbA0.Items := cb80.Items; cbB0.Items := cb80.Items; cbC0.Items := cb80.Items; _CurrentSet := _ROMData.GetSpriteSet(cbRoom.ItemIndex) div $B; // if MegamanROM.GetSpriteSet mod $B >0 then showmessage('eh'); loaddata; cb80.ItemIndex := cb80.Items.IndexOf(IntTohex(_SpriteSettings[0],4)); cb90.ItemIndex := cb90.Items.IndexOf(IntTohex(_SpriteSettings[1],4)); cbA0.ItemIndex := cbA0.Items.IndexOf(IntTohex(_SpriteSettings[2],4)); cbB0.ItemIndex := cbB0.Items.IndexOf(IntTohex(_SpriteSettings[3],4)); cbC0.ItemIndex := cbC0.Items.IndexOf(IntTohex(_SpriteSettings[4],4)); txtSpriteChangeSet.Value := _CurrentSet; DrawSpriteChange; DrawPalettes; DrawNESColours; // _IgnoreChanges := False; end; procedure TfrmSpriteChange.DrawSpriteChange; var SprChange : TBitmap32; begin SprChange := TBitmap32.Create; SprChange.Width := 128; SprChange.Height := 8; try if cb80.Text <> '' then begin _ROMData.DrawSpriteChangeTiles(StrToInt('$' + cb80.Text),SprChange); img80.Bitmap := SprChange; end; if cb90.Text <> '' then begin _ROMData.DrawSpriteChangeTiles(StrToInt('$' + cb90.Text),SprChange); img90.Bitmap := SprChange; end; if cbA0.Text <> '' then begin _ROMData.DrawSpriteChangeTiles(StrToInt('$' + cbA0.Text),SprChange); imgA0.Bitmap := SprChange; end; if cbB0.Text <> '' then begin _ROMData.DrawSpriteChangeTiles(StrToInt('$' + cbB0.Text),SprChange); imgB0.Bitmap := SprChange; end; if cbC0.Text <> '' then begin _ROMData.DrawSpriteChangeTiles(StrToInt('$' + cbC0.Text),SprChange); imgC0.Bitmap := SprChange; end; finally FreeAndNil(SprChange); end; end; procedure TfrmSpriteChange.cb80Change(Sender: TObject); begin DrawSpriteChange; end; procedure TfrmSpriteChange.cmdOKClick(Sender: TObject); begin SaveData; end; procedure TfrmSpriteChange.txtSpriteChangeSetChange(Sender: TObject); begin // if _IgnoreChanges = false then SaveData; _CurrentSet := txtSpriteChangeSet.Value; LoadData; cb80.ItemIndex := cb80.Items.IndexOf(IntTohex(_SpriteSettings[0],4)); cb90.ItemIndex := cb90.Items.IndexOf(IntTohex(_SpriteSettings[1],4)); cbA0.ItemIndex := cbA0.Items.IndexOf(IntTohex(_SpriteSettings[2],4)); cbB0.ItemIndex := cbB0.Items.IndexOf(IntTohex(_SpriteSettings[3],4)); cbC0.ItemIndex := cbC0.Items.IndexOf(IntTohex(_SpriteSettings[4],4)); DrawSpriteChange; DrawPalettes; end; procedure TfrmSpriteChange.DrawPalettes; var PalBit : TBitmap32; begin PalBit := TBitmap32.Create; try PalBit.Width := 75; PalBit.Height := 25; PalBit.FillRect(0,0,25,25, _ROMData.NESPal[_SprPal3[0]]); PalBit.FillRect(25,0,50,25, _ROMData.NESPal[_SprPal3[1]]); PalBit.FillRect(50,0,75,25, _ROMData.NESPal[_SprPal3[2]]); imgSprPal3.Hint := '$' + IntToHex(_SprPal3[0],2) + ' $' + IntToHex(_SprPal3[1],2) + ' $' + IntToHex(_SprPal3[2],2); imgSprPal3.Bitmap := PalBit; PalBit.FillRect(0,0,25,25, _ROMData.NESPal[_SprPal4[0]]); PalBit.FillRect(25,0,50,25, _ROMData.NESPal[_SprPal4[1]]); PalBit.FillRect(50,0,75,25, _ROMData.NESPal[_SprPal4[2]]); imgSprPal4.Hint := '$' + IntToHex(_SprPal4[0],2) + ' $' + IntToHex(_SprPal4[1],2) + ' $' + IntToHex(_SprPal4[2],2); imgSprPal4.Bitmap := PalBit; finally FreeAndNil(PalBit); end; end; procedure TfrmSpriteChange.LoadData; var i : Integer; begin for i := 0 to 4 do _SpriteSettings[i] := _ROMData.GetSpriteChangeOffset(_CurrentSet * $B,i); for i := 0 to 2 do _SprPal3[i] := _ROMData.GetSpriteChangePal(_CurrentSet * $B,i); for i := 0 to 2 do _SprPal4[i] := _ROMData.GetSpriteChangePal(_CurrentSet * $B,i+3); end; procedure TfrmSpriteChange.SaveData; var i : Integer; begin _ROMData.SetSpriteSet(_CurrentSet * $B,(cbRoom.ItemIndex)); _ROMData.SetSpriteChangeOffset(_CurrentSet * $B,0,StrToInt('$' + cb80.Text)); _ROMData.SetSpriteChangeOffset(_CurrentSet * $B,1,StrToInt('$' + cb90.Text)); _ROMData.SetSpriteChangeOffset(_CurrentSet * $B,2,StrToInt('$' + cbA0.Text)); _ROMData.SetSpriteChangeOffset(_CurrentSet * $B,3,StrToInt('$' + cbB0.Text)); _ROMData.SetSpriteChangeOffset(_CurrentSet * $B,4,StrToInt('$' + cbC0.Text)); for i := 0 to 2 do _ROMData.SetSpriteChangePal(_CurrentSet * $B,i,_SprPal3[i]); for i := 0 to 2 do _ROMData.SetSpriteChangePal(_CurrentSet * $B,i+3,_SprPal4[i]); end; procedure TfrmSpriteChange.DrawNESColours; var TempBitmap : TBitmap32; begin TempBitmap := TBitmap32.Create; try _ROMData.DrawNESColours(TempBitmap); if _TileX = 0 then TempBitmap.FrameRectS(_TileX,_TileY,_TileX+18,_TileY+19,clRed32) else TempBitmap.FrameRectS(_TileX-1,_TileY,_TileX+18,_TileY+19,clRed32); imgNESColours.Bitmap := TempBitmap; finally FreeAndNil(TempBitmap); end; end; procedure TfrmSpriteChange.imgSprPal3MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin _SprPal3[x div 25] := _CurColour; DrawPalettes; end; procedure TfrmSpriteChange.imgNESColoursMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin _CurColour := ((X div 18) + (Y div 18) * 16); _TileX := (X div 18) * 18; _TileY := (y div 18) * 18; DrawNESColours(); end; procedure TfrmSpriteChange.imgSprPal4MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin _SprPal4[x div 25] := _CurColour; DrawPalettes; end; procedure TfrmSpriteChange.imgNESColoursMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer; Layer: TCustomLayer); begin lblCurrentPalette.Caption := 'Palette Colour Under Mouse: $' + IntToHex(((X div 18) + (Y div 18) * 16),2); end; end.
unit UCloudAdapterDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSBaseControl, FMX.TMSPlannerBase, FMX.TMSPlannerData, FMX.TMSPlanner, FMX.TMSCloudCustomLive, FMX.TMSCloudLiveFMX, FMX.TMSCloudCustomLiveCalendar, FMX.TMSCloudLiveCalendar, FMX.TMSCloudBase, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomGoogle, FMX.TMSCloudGoogleFMX, FMX.TMSCloudCustomGCalendar, FMX.TMSCloudGCalendar, FMX.TMSBaseGroup, FMX.TMSRadioGroup, FMX.TMSPlannerLiveAdapter, FMX.TMSPlannerGoogleAdapter, FMX.ListBox; type TForm1 = class(TForm) TMSFMXPlanner1: TTMSFMXPlanner; TMSFMXPlannerGoogleAdapter1: TTMSFMXPlannerGoogleAdapter; TMSFMXPlannerLiveAdapter1: TTMSFMXPlannerLiveAdapter; TMSFMXRadioGroup1: TTMSFMXRadioGroup; btnConnect: TButton; TMSFMXCloudGCalendar1: TTMSFMXCloudGCalendar; TMSFMXCloudLiveCalendar1: TTMSFMXCloudLiveCalendar; comboCal: TComboBox; btnGetCal: TButton; Label1: TLabel; procedure TMSFMXRadioGroup1RadioButtonChange(Sender: TObject; Index: Integer); procedure btnConnectClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure TMSFMXCloudGCalendar1ReceivedAccessToken(Sender: TObject); procedure TMSFMXCloudLiveCalendar1ReceivedAccessToken(Sender: TObject); procedure btnGetCalClick(Sender: TObject); procedure TMSFMXPlanner1AfterNavigateToDateTime(Sender: TObject; ADirection: TTMSFMXPlannerNavigationDirection; ACurrentDateTime, ANewDateTime: TDateTime); procedure TMSFMXPlanner1BeforeNavigateToDateTime(Sender: TObject; ADirection: TTMSFMXPlannerNavigationDirection; ACurrentDateTime: TDateTime; var ANewDateTime: TDateTime; var AAllow: Boolean); private { Private declarations } public { Public declarations } procedure InitGCalendars; procedure InitLiveCalendars; procedure Connect; procedure Disconnect; end; var Form1: TForm1; implementation {$R *.fmx} {$I APPIDS.INC} procedure TForm1.btnConnectClick(Sender: TObject); begin if btnConnect.Tag = 1 then Disconnect else Connect; end; procedure TForm1.btnGetCalClick(Sender: TObject); var idx: integer; begin idx := comboCal.ItemIndex; if idx < 0 then Exit; TMSFMXPlanner1.Enabled := true; case TMSFMXRadioGroup1.ItemIndex of 0: begin TMSFMXPlanner1.Adapter := TMSFMXPlannerGoogleAdapter1; TMSFMXPlannerGoogleAdapter1.CalendarID := TMSFMXCloudGCalendar1.Calendars[idx].ID; TMSFMXPlannerGoogleAdapter1.Active := true; end; 1: begin TMSFMXPlanner1.Adapter := TMSFMXPlannerLiveAdapter1; TMSFMXPlannerLiveAdapter1.CalendarID := TMSFMXCloudLiveCalendar1.Calendars[idx].ID; TMSFMXPlannerLiveAdapter1.Active := true; end; end; end; procedure TForm1.Connect; var res: boolean; begin case TMSFMXRadioGroup1.ItemIndex of 0: begin res := TMSFMXCloudGCalendar1.TestTokens; if not res then begin TMSFMXCloudGCalendar1.RefreshAccess; res := TMSFMXCloudGCalendar1.TestTokens; end; if res then begin InitGCalendars end else TMSFMXCloudGCalendar1.DoAuth; end; 1: begin res := TMSFMXCloudLiveCalendar1.TestTokens; if not res then begin TMSFMXCloudLiveCalendar1.RefreshAccess; res := TMSFMXCloudLiveCalendar1.TestTokens; end; if res then InitLiveCalendars else TMSFMXCloudLiveCalendar1.DoAuth; end; end; end; procedure TForm1.Disconnect; begin btnConnect.Text := 'Connect'; btnConnect.Tag := 0; btnGetCal.Enabled := false; comboCal.ItemIndex := -1; comboCal.Items.Clear; TMSFMXPlannerGoogleAdapter1.Active := false; TMSFMXPlannerLiveAdapter1.Active := false; TMSFMXPlanner1.Enabled := false; end; procedure TForm1.FormCreate(Sender: TObject); begin // initialize cloud calendar access components TMSFMXCloudGCalendar1.App.Key := GAppkey; TMSFMXCloudGCalendar1.App.Secret := GAppSecret; TMSFMXCloudGCalendar1.PersistTokens.Location := plIniFile; TMSFMXCloudGCalendar1.PersistTokens.Key := '.\TOKENS.INI'; TMSFMXCloudGCalendar1.PersistTokens.Section := 'GOOGLE'; TMSFMXCloudLiveCalendar1.App.Key := LiveAppkey; TMSFMXCloudLiveCalendar1.App.Secret := LiveAppSecret; TMSFMXCloudLiveCalendar1.PersistTokens.Location := plIniFile; TMSFMXCloudLiveCalendar1.PersistTokens.Key := '.\TOKENS.INI'; TMSFMXCloudLiveCalendar1.PersistTokens.Section := 'MSLIVE'; TMSFMXCloudGCalendar1.LoadTokens; TMSFMXCloudLiveCalendar1.LoadTokens; TMSFMXPlanner1.ModeSettings.StartTime := Int(Now); end; procedure TForm1.InitGCalendars; var i: integer; begin // get Google calendars TMSFMXCloudGCalendar1.GetCalendars; comboCal.Items.Clear; for i := 0 to TMSFMXCloudGCalendar1.Calendars.Count - 1 do comboCal.Items.Add(TMSFMXCloudGCalendar1.Calendars[i].Summary); btnGetCal.Enabled := comboCal.Items.Count > 0; btnConnect.Text := 'Disconnect'; btnConnect.Tag := 1; if comboCal.Items.Count > 0 then begin comboCal.ItemIndex := 0; end; end; procedure TForm1.InitLiveCalendars; var i: integer; begin // get Live calendars TMSFMXCloudLiveCalendar1.GetCalendars; comboCal.Items.Clear; for i := 0 to TMSFMXCloudLiveCalendar1.Calendars.Count - 1 do comboCal.Items.Add(TMSFMXCloudLiveCalendar1.Calendars[i].Summary); btnGetCal.Enabled := comboCal.Items.Count > 0; btnConnect.Text := 'Disconnect'; btnConnect.Tag := 1; if comboCal.Items.Count > 0 then comboCal.ItemIndex := 0; end; procedure TForm1.TMSFMXCloudGCalendar1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudGCalendar1.SaveTokens; InitGCalendars; end; procedure TForm1.TMSFMXCloudLiveCalendar1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudLiveCalendar1.SaveTokens; InitLiveCalendars; end; procedure TForm1.TMSFMXPlanner1AfterNavigateToDateTime(Sender: TObject; ADirection: TTMSFMXPlannerNavigationDirection; ACurrentDateTime, ANewDateTime: TDateTime); begin case TMSFMXRadioGroup1.ItemIndex of 0: TMSFMXPlannerGoogleAdapter1.Update; 1: TMSFMXPlannerLiveAdapter1.Update; end; end; procedure TForm1.TMSFMXPlanner1BeforeNavigateToDateTime(Sender: TObject; ADirection: TTMSFMXPlannerNavigationDirection; ACurrentDateTime: TDateTime; var ANewDateTime: TDateTime; var AAllow: Boolean); begin case ADirection of pndPrevious: ANewDateTime := ACurrentDateTime - 7; pndNext: ANewDateTime := ACurrentDateTime + 7; end; end; procedure TForm1.TMSFMXRadioGroup1RadioButtonChange(Sender: TObject; Index: Integer); begin case Index of 0: TMSFMXPlanner1.Adapter := TMSFMXPlannerGoogleAdapter1; 1: TMSFMXPlanner1.Adapter := TMSFMXPlannerLiveAdapter1; end; end; end.
program ManageFlexArrays; {$MODE DELPHI} uses SysUtils, Quick.Commons, Quick.Console, Quick.Arrays; type TUser = class private fName : string; public property Name : string read fName write fName; end; var flexarray : TFlexArray; user : TUser; begin try flexarray.Add(10); flexarray.Add('Hello'); user := TUser.Create; try user.Name := 'Joe'; flexarray.Add(user); cout('Integer Item = %d',[flexarray[0].AsInteger],etInfo); cout('String Item = %s',[flexarray[1].AsString],etInfo); cout('Record Item = %s',[TUser(flexarray[2].AsObject).Name],etInfo); finally user.Free; end; cout('Press <Enter> to Exit',ccYellow); ConsoleWaitForEnterKey; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
unit DAO.TipoCadastro; interface uses DAO.Base, Model.TipoCadastro, Generics.Collections, System.Classes; type TTipoCadastroDAO = class(TDAO) public function Insert(aTipo: Model.TipoCadastro.TTipoCadastro): Boolean; function Update(aTipo: Model.TipoCadastro.TTipoCadastro): Boolean; function Delete(sFiltro: String): Boolean; function FindTipo(sFiltro: String): TObjectList<Model.TipoCadastro.TTipoCadastro>; end; const TABLENAME = 'CAD_TIPO_CADASTRO'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TTipoCadastroDAO.Insert(aTipo: TTipoCadastro): Boolean; var sSQL : System.string; begin Result := False; aTipo.Codigo := GetKeyValue(TABLENAME,'COD_TIPO'); sSQL := 'INSERT INTO ' + TABLENAME + ' '+ '(COD_TIPO, DES_TIPO, DOM_PESSOA, DOM_RH, DOM_JORNAL, DOM_EXPRESSAS, DES_LOG) ' + 'VALUES ' + '(:CODIGO, :DESCRICAO, :PESSOA, :RH, :JORNAL, :EXPRESSA, :LOG);'; Connection.ExecSQL(sSQL,[aTipo.Codigo, aTipo.Descricao, aTipo.Pessoa, aTipo.RH, aTipo.Jornal, aTipo.Expressas, aTipo.Log], [ftInteger, ftString, ftInteger, ftBoolean, ftBoolean, ftBoolean, ftString]); Result := True; end; function TTipoCadastroDAO.Update(aTipo: TTipoCadastro): Boolean; var sSQL: System.string; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' ' + 'SET ' + 'DES_TIPO = :DESCRICAO, DOM_PESSOA = :PESSOA, DOM_RH = :RH, DOM_JORNAL = :JORNAL, DOM_EXPRESSAS = :EXPRESSA, ' + 'DES_LOG = :LOG ' + 'WHERE COD_TIPO = :CODIGO;'; Connection.ExecSQL(sSQL,[aTipo.Descricao, aTipo.Pessoa, aTipo.RH, aTipo.Jornal, aTipo.Expressas, aTipo.Log, aTipo.Codigo], [ftString, ftInteger, ftBoolean, ftBoolean, ftBoolean, ftString, ftInteger]); Result := True; end; function TTipoCadastroDAO.Delete(sFiltro: string): Boolean; var sSQL : String; begin Result := False; sSQL := 'DELETE FROM ' + TABLENAME + ' '; if not sFiltro.IsEmpty then begin sSQl := sSQL + sFiltro; end else begin Exit; end; Connection.ExecSQL(sSQL); Result := True; end; function TTipoCadastroDAO.FindTipo(sFiltro: string): TObjectList<Model.TipoCadastro.TTipoCadastro>; var FDQuery: TFDQuery; tipos: TObjectList<Model.TipoCadastro.TTipoCadastro>; begin FDQuery := TFDQuery.Create(nil); try FDQuery.Connection := Connection; FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME); if not sFiltro.IsEmpty then begin FDQuery.SQL.Add(sFiltro); end; FDQuery.Open(); tipos := TObjectList<Model.TipoCadastro.TTipoCadastro>.Create(); while not FDQuery.Eof do begin tipos.Add(TTipoCadastro.Create(FDQuery.FieldByName('COD_TIPO').AsInteger, FDQuery.FieldByName('DES_TIPO').AsString, FDQuery.FieldByName('DOM_PESSOA').AsInteger, FDQuery.FieldByName('DOM_RH').AsBoolean, FDQuery.FieldByName('DOM_JORNAL').AsBoolean, FDQuery.FieldByName('DOM_EXPRESSAS').AsBoolean, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; Result := tipos; finally FDQuery.Free; end; end; end.
unit msmSomeModelElementsList; // Модуль: "w:\common\components\gui\Garant\msm\msmSomeModelElementsList.pas" // Стереотип: "SimpleClass" // Элемент модели: "TmsmSomeModelElementsList" MUID: (57E54DCD0141) {$Include w:\common\components\msm.inc} interface uses l3IntfUses , l3CProtoObject , msmElementViews {$If NOT Defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} // NOT Defined(NoScripts) , msmModelElements , l3Interfaces , msmEvents , ImsmEventsSubscriberList ; type _msmEventsPublisher_Parent_ = Tl3CProtoObject; {$Include w:\common\components\gui\Garant\msm\msmEventsPublisher.imp.pas} TmsmSomeModelElementsList = class(_msmEventsPublisher_, ImsmModelElementStringList, ImsmEventsPublisher) private f_List: ItfwValueList; protected function As_ImsmEventsPublisher: ImsmEventsPublisher; {* Метод приведения нашего интерфейса к ImsmEventsPublisher } function Get_Item(anIndex: Integer): ImsmModelElement; function Get_Count: Integer; function Get_Owner: ImsmModelElement; function Get_Strings(anIndex: Integer): Il3CString; function Get_StringsToFind(anIndex: Integer): Il3CString; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create(const aList: ItfwValueList); reintroduce; class function Make(const aList: ItfwValueList): ImsmModelElementStringList; reintroduce; function IndexOfElementView(const anElement: ImsmModelElement): Integer; procedure Add(anItem: TtfwWord); end;//TmsmSomeModelElementsList implementation uses l3ImplUses , msmModelElement , SysUtils //#UC START# *57E54DCD0141impl_uses* //#UC END# *57E54DCD0141impl_uses* ; {$Include w:\common\components\gui\Garant\msm\msmEventsPublisher.imp.pas} constructor TmsmSomeModelElementsList.Create(const aList: ItfwValueList); //#UC START# *57E54E69027B_57E54DCD0141_var* //#UC END# *57E54E69027B_57E54DCD0141_var* begin //#UC START# *57E54E69027B_57E54DCD0141_impl* Assert(aList <> nil); f_List := aList; inherited Create; //#UC END# *57E54E69027B_57E54DCD0141_impl* end;//TmsmSomeModelElementsList.Create class function TmsmSomeModelElementsList.Make(const aList: ItfwValueList): ImsmModelElementStringList; var l_Inst : TmsmSomeModelElementsList; begin l_Inst := Create(aList); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TmsmSomeModelElementsList.Make function TmsmSomeModelElementsList.As_ImsmEventsPublisher: ImsmEventsPublisher; {* Метод приведения нашего интерфейса к ImsmEventsPublisher } begin Result := Self; end;//TmsmSomeModelElementsList.As_ImsmEventsPublisher function TmsmSomeModelElementsList.Get_Item(anIndex: Integer): ImsmModelElement; //#UC START# *57AAD86403AD_57E54DCD0141get_var* //#UC END# *57AAD86403AD_57E54DCD0141get_var* begin //#UC START# *57AAD86403AD_57E54DCD0141get_impl* if (f_List = nil) then Result := nil else Result := TmsmModelElement.MakeFromValue(f_List[anIndex]); //#UC END# *57AAD86403AD_57E54DCD0141get_impl* end;//TmsmSomeModelElementsList.Get_Item function TmsmSomeModelElementsList.Get_Count: Integer; //#UC START# *57AAD89C0277_57E54DCD0141get_var* //#UC END# *57AAD89C0277_57E54DCD0141get_var* begin //#UC START# *57AAD89C0277_57E54DCD0141get_impl* if (f_List = nil) then Result := 0 else Result := f_List.Count; //#UC END# *57AAD89C0277_57E54DCD0141get_impl* end;//TmsmSomeModelElementsList.Get_Count function TmsmSomeModelElementsList.Get_Owner: ImsmModelElement; //#UC START# *57AE2E140297_57E54DCD0141get_var* //#UC END# *57AE2E140297_57E54DCD0141get_var* begin //#UC START# *57AE2E140297_57E54DCD0141get_impl* Result := nil; //#UC END# *57AE2E140297_57E54DCD0141get_impl* end;//TmsmSomeModelElementsList.Get_Owner function TmsmSomeModelElementsList.Get_Strings(anIndex: Integer): Il3CString; //#UC START# *57AEBED1018D_57E54DCD0141get_var* var l_E : ImsmModelElement; //#UC END# *57AEBED1018D_57E54DCD0141get_var* begin //#UC START# *57AEBED1018D_57E54DCD0141get_impl* l_E := Get_Item(anIndex); if (l_E = nil) then Result := TtfwCStringFactory.C('(unexisting)') else Result := l_E.StringProp['DefaultText']; //#UC END# *57AEBED1018D_57E54DCD0141get_impl* end;//TmsmSomeModelElementsList.Get_Strings function TmsmSomeModelElementsList.Get_StringsToFind(anIndex: Integer): Il3CString; //#UC START# *57B6C7D40215_57E54DCD0141get_var* var l_E : ImsmModelElement; //#UC END# *57B6C7D40215_57E54DCD0141get_var* begin //#UC START# *57B6C7D40215_57E54DCD0141get_impl* l_E := Get_Item(anIndex); if (l_E = nil) then Result := TtfwCStringFactory.C('(unexisting)') else Result := l_E.StringProp['DefaultSearchText']; //#UC END# *57B6C7D40215_57E54DCD0141get_impl* end;//TmsmSomeModelElementsList.Get_StringsToFind function TmsmSomeModelElementsList.IndexOfElementView(const anElement: ImsmModelElement): Integer; //#UC START# *57D1327900BC_57E54DCD0141_var* var l_Index : Integer; l_E : ImsmModelElement; //#UC END# *57D1327900BC_57E54DCD0141_var* begin //#UC START# *57D1327900BC_57E54DCD0141_impl* Result := -1; if (anElement <> nil) then begin for l_Index := 0 to Pred(Get_Count) do begin l_E := Get_Item(l_Index); if l_E.IsSameElement(anElement) then begin Result := l_Index; Exit; end;//l_E.IsSameElement(anElement) end;//for l_Index for l_Index := 0 to Pred(Get_Count) do begin l_E := Get_Item(l_Index); if l_E.IsSameElementView(anElement) then begin Result := l_Index; Exit; end;//l_E.IsSameElementView(anElement) end;//for l_Index end;//anElement <> nil //#UC END# *57D1327900BC_57E54DCD0141_impl* end;//TmsmSomeModelElementsList.IndexOfElementView procedure TmsmSomeModelElementsList.Add(anItem: TtfwWord); //#UC START# *58094B920194_57E54DCD0141_var* //#UC END# *58094B920194_57E54DCD0141_var* begin //#UC START# *58094B920194_57E54DCD0141_impl* Assert(false); //#UC END# *58094B920194_57E54DCD0141_impl* end;//TmsmSomeModelElementsList.Add procedure TmsmSomeModelElementsList.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_57E54DCD0141_var* //#UC END# *479731C50290_57E54DCD0141_var* begin //#UC START# *479731C50290_57E54DCD0141_impl* f_List := nil; inherited; //#UC END# *479731C50290_57E54DCD0141_impl* end;//TmsmSomeModelElementsList.Cleanup procedure TmsmSomeModelElementsList.ClearFields; begin f_List := nil; inherited; end;//TmsmSomeModelElementsList.ClearFields end.
// *************************************************************************** // // FMXComponents: Firemonkey Opensource Components Set // // Copyright 2017 谢顿 (zhaoyipeng@hotmail.com) // // https://github.com/zhaoyipeng/FMXComponents // // *************************************************************************** // // 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 FMX.RegComponents; interface uses System.Classes // 可根据需要注释调不需要的控件单元和注册 , FMX.CircleScoreIndicator , FMX.ImageSlider , FMX.RatingBar , FMX.ScrollableList , FMX.SimpleBBCodeText , FMX.GesturePassword , FMX.CalendarControl , FMX.Seg7Shape , FMX.Toast , FMX.QRCode , FMX.LoadingIndicator , FMX.Callout , FMX.RotatingText ; procedure Register; implementation const FMX_COMPONENTS_PALETTE = 'FMXComponents'; procedure Register; begin RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXCircleScoreIndicator]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXImageSlider]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXRatingBar]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXScrollableList]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXSimpleBBCodeText]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXGesturePassword]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXCalendarControl]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXSeg7Shape]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXToast]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXQRCode]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXLoadingIndicator]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXCallout]); RegisterComponents(FMX_COMPONENTS_PALETTE, [TFMXRotatingText]); end; end.
unit GX_AboutExperimental; {$I GX_CondDefine.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, GX_About, ExtCtrls, StdCtrls; type TfmAboutExperimental = class(TfmAbout) l_CreatedBy: TLabel; l_DummzeuchDe: TLabel; l_Formatter: TLabel; protected class function DoAddToAboutDialog: integer; override; public constructor Create(_Owner: TComponent); override; end; implementation {$R *.dfm} uses ToolsAPI, GX_GenericUtils; { TfmAboutExperimental } constructor TfmAboutExperimental.Create(_Owner: TComponent); begin inherited; SetFontUnderline(l_DummzeuchDe); SetFontColor(l_DummzeuchDe, clBlue); SetFontUnderline(l_Formatter); SetFontColor(l_Formatter, clBlue); end; class function TfmAboutExperimental.DoAddToAboutDialog: integer; {$IFDEF GX_VER170_up} // Only Delphi 2005 and up support the about box services var AboutBoxServices: IOTAAboutBoxServices; begin Result := -1; if Supports(BorlandIDEServices, IOTAAboutBoxServices, AboutBoxServices) then begin Result := AboutBoxServices.AddPluginInfo( 'GExperts Experimental', 'GExperts is a free set of tools built to increase the productivity of Delphi and C++Builder' + ' programmers by adding several features to the IDE.' + ' GExperts is developed as Open Source software and we encourage user contributions to the project.'#13#10 + '(c) Erik Berry and the GExperts Team'#13#10 + 'http://blog.dummzeuch.de', GetAboutIcon, False, '', // leave this empty! GetVersionStr + ' experimental'); end; end; {$ELSE not GX_VER170_up} begin Result := -1; end; {$ENDIF not GX_VER170_up} initialization TfmAboutExperimental.SetCustomBuildEmails('gexperts@dummzeuch.de', 'gexperts@dummzeuch.de'); gblAboutFormClass := TfmAboutExperimental; end.
unit LogSpecificMessageUnit; interface uses SysUtils, BaseExampleUnit; type TLogSpecificMessage = class(TBaseExample) public function Execute(Message, RouteId: String): boolean; end; implementation function TLogSpecificMessage.Execute(Message, RouteId: String): boolean; var ErrorString: String; begin Result := Route4MeManager.ActivityFeed.LogSpecificMessage(RouteId, Message, ErrorString); WriteLn(''); if (Result) then WriteLn('LogSpecificMessage executed successfully') else WriteLn(Format('LogSpecificMessage error: "%s"', [ErrorString])); end; end.
unit UFrmPadraoCadastro; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.ImgList, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Vcl.ExtCtrls, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnList, Vcl.ActnMan, Vcl.Buttons, Vcl.ToolWin, System.Win.ComObj, UDaoPermissaoTelaClient, UPermissaoTela, Datasnap.DBClient, UDaoPadrao, UUtil, UConstante; type TControleBotoes = (cbNovo, cbAltera, cbExcluir, cbCancelar, cbSavar, cbNavegar); TOperacao = (opIncluir, opEditar, opNavegar); TFrmPadraoCadastro = class(TForm) sbPadrao: TStatusBar; pnl1: TPanel; pgcPadrao: TPageControl; tsPesquisa: TTabSheet; tsFormulario: TTabSheet; Panel1: TPanel; Panel2: TPanel; dgPadrao: TDBGrid; lbl1: TLabel; edtLocalizar: TEdit; ilPadrao: TImageList; dsPesq: TDataSource; alPadrao: TActionList; actNovo: TAction; actAlterar: TAction; actExcluir: TAction; actCancelar: TAction; actSalvar: TAction; actNavegar: TAction; actLocaliza: TAction; tlbPadrao: TToolBar; btnNovo: TToolButton; btnAlterar: TToolButton; btnExcluir: TToolButton; btnCancelar: TToolButton; btnSalvar: TToolButton; btn1: TToolButton; btnNavegar: TToolButton; ToolButton1: TToolButton; btnExcel: TToolButton; actExcel: TAction; actAtualiza: TAction; btnAtualiza: TToolButton; ilPadrao16: TImageList; cdsMaster: TClientDataSet; dsLigaMaster: TDataSource; procedure FormShow(Sender: TObject); procedure actNovoExecute(Sender: TObject); procedure actAlterarExecute(Sender: TObject); procedure actExcluirExecute(Sender: TObject); procedure actCancelarExecute(Sender: TObject); procedure actSalvarExecute(Sender: TObject); procedure actNavegarExecute(Sender: TObject); procedure actLocalizaExecute(Sender: TObject); procedure actExcelExecute(Sender: TObject); procedure actAtualizaExecute(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); procedure dgPadraoTitleClick(Column: TColumn); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } FCampoPesq: string; FOperacao: TOperacao; FVarMaster: OleVariant; FDataSetLista: OleVariant; FPost: string; FPut: string; FGet: string; FDelete: string; FPadrao: TDaoPadrao; procedure Movimentacao(ABotao: TControleBotoes); procedure SetCampoPesq(const Value: string); procedure SetOperacao(const Value: TOperacao); procedure SetDataSetLista(const Value: OleVariant); procedure SetDelete(const Value: string); procedure SetGet(const Value: string); procedure SetPost(const Value: string); procedure SetPut(const Value: string); procedure SetPadrao(const Value: TDaoPadrao); public { Public declarations } procedure AtualizaDataSet; virtual; procedure OpenDataSet; virtual; procedure ConfiguraGrid; virtual; procedure Novo; virtual; procedure Alterar; virtual; procedure Excluir; virtual; procedure Cancelar; virtual; procedure Salvar; virtual; procedure SetObjeto; virtual; abstract; procedure Permissao; procedure Limpar; property CampoPesq: string read FCampoPesq write SetCampoPesq; property Operacao: TOperacao read FOperacao write SetOperacao; property VarMaster: OleVariant read FVarMaster write FVarMaster; property DataSetLista: OleVariant read FDataSetLista write SetDataSetLista; property Get: string read FGet write SetGet; property Put: string read FPut write SetPut; property Post: string read FPost write SetPost; property Delete: string read FDelete write SetDelete; property Padrao: TDaoPadrao read FPadrao write SetPadrao; property SetMovimentacao: TControleBotoes write Movimentacao; end; var FrmPadraoCadastro: TFrmPadraoCadastro; implementation {$R *.dfm} uses UDmConexao; procedure TFrmPadraoCadastro.actAlterarExecute(Sender: TObject); begin if actAlterar.Enabled then begin Self.Alterar; end; end; procedure TFrmPadraoCadastro.actAtualizaExecute(Sender: TObject); begin Self.FormShow(Self); end; procedure TFrmPadraoCadastro.actCancelarExecute(Sender: TObject); begin Self.Movimentacao(cbCancelar); Self.FOperacao := opNavegar; Self.Cancelar; end; procedure TFrmPadraoCadastro.actExcelExecute(Sender: TObject); begin Excel(dsPesq); end; procedure TFrmPadraoCadastro.actExcluirExecute(Sender: TObject); begin Self.FOperacao := opNavegar; Self.Excluir; Self.OpenDataSet; Self.ConfiguraGrid; Self.Movimentacao(cbExcluir); Self.Permissao; end; procedure TFrmPadraoCadastro.actLocalizaExecute(Sender: TObject); begin try if Length(Trim(TEdit(Sender).Text)) >= 2 then dsPesq.DataSet.Locate(Self.FCampoPesq, TEdit(Sender).Text, [loPartialKey, loCaseInsensitive]); except ShowMessage(Format(_msg00002, [TEdit(Sender).Text, Self.FCampoPesq])); end; end; procedure TFrmPadraoCadastro.actNavegarExecute(Sender: TObject); begin Self.Movimentacao(cbNavegar); end; procedure TFrmPadraoCadastro.actNovoExecute(Sender: TObject); begin Self.Novo; end; procedure TFrmPadraoCadastro.actSalvarExecute(Sender: TObject); begin Self.Salvar; Self.OpenDataSet; Self.ConfiguraGrid; Self.Movimentacao(cbSavar); Self.Permissao; Self.FOperacao := opNavegar; Self.edtLocalizar.SetFocus; end; procedure TFrmPadraoCadastro.Alterar; begin Self.Movimentacao(cbAltera); Self.FOperacao := opEditar; dsPesq.DataSet.Edit; end; procedure TFrmPadraoCadastro.AtualizaDataSet; begin if Length(Trim(Self.FGet)) > 0 then begin Self.FDataSetLista := Self.FPadrao.Consultar(Self.FGet); end; Self.VarMaster := Self.FDataSetLista[0]; try cdsMaster.Close; cdsMaster.Data := Self.FVarMaster; except cdsMaster.IndexName := _msg00022; cdsMaster.Open; end; end; procedure TFrmPadraoCadastro.Cancelar; begin dsPesq.DataSet.Cancel; Self.Limpar; ShowMessage(_msg00007); end; procedure TFrmPadraoCadastro.ConfiguraGrid; var I: Integer; begin for I := 0 to dgPadrao.Columns.Count -1 do begin case dgPadrao.Columns[I].Field.DataType of ftString, ftWideString: dgPadrao.Columns[I].Width := 200; ftInteger: begin dgPadrao.Columns[I].Width := 50; end; ftBoolean: dgPadrao.Columns[I].Width := 30; ftFloat, ftCurrency, ftBCD, ftDate, ftTime, ftDateTime, ftTimeStamp: dgPadrao.Columns[I].Width := 110; ftBlob, ftMemo: dgPadrao.Columns[I].Width := 400; end; end; for I := 0 to dsPesq.DataSet.FieldCount -1 do begin case dsPesq.DataSet.Fields[I].DataType of ftInteger: TIntegerField(dsPesq.DataSet.Fields[I]).DisplayFormat := _msg00010; ftFloat, ftCurrency, ftBCD, ftFMTBcd: TIntegerField(dsPesq.DataSet.Fields[I]).DisplayFormat := _msg00011; end; end; end; procedure TFrmPadraoCadastro.dgPadraoTitleClick(Column: TColumn); begin Self.FCampoPesq := Column.FieldName; lbl1.Caption := Format(_msg00003, [Self.FCampoPesq]); OrdenaGrid(cdsMaster, dgPadrao, Column); end; procedure TFrmPadraoCadastro.Excluir; begin Self.SetObjeto; end; procedure TFrmPadraoCadastro.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(cdsMaster) then begin FreeAndNil(cdsMaster); end; end; procedure TFrmPadraoCadastro.FormCreate(Sender: TObject); begin Self.FPadrao := DmConexao.Factory.ClassDaoPadrao; end; procedure TFrmPadraoCadastro.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // KeyPreview := True; if ((Shift = [ssCtrl]) and (Key = 13)) then actSalvarExecute(Self); case key of VK_F2: actNovoExecute(Self); VK_F3: actAlterarExecute(Self); VK_F4: actExcluirExecute(Self); VK_F5: actSalvarExecute(Self); VK_F6: actCancelarExecute(Self); VK_F7: actNavegarExecute(Self); VK_F8: actExcelExecute(Self); VK_F9: actAtualizaExecute(Self); end; end; procedure TFrmPadraoCadastro.FormKeyPress(Sender: TObject; var Key: Char); begin If key = #13 then Begin Key:= #0; Perform(Wm_NextDlgCtl,0,0); end; end; procedure TFrmPadraoCadastro.FormShow(Sender: TObject); begin Self.OpenDataSet; Self.ConfiguraGrid; Self.Width := TamanhoGrid(dgPadrao); Self.Height:= 550; Self.Movimentacao(cbSavar); Self.Permissao; Self.FCampoPesq := dgPadrao.SelectedField.FieldName; lbl1.Caption := Format(_msg00003, [Self.FCampoPesq]); Self.edtLocalizar.SetFocus; end; procedure TFrmPadraoCadastro.Limpar; var I: Word; begin for I := 0 to ComponentCount -1 do begin if Components[I] is TEdit then (Components[I] as TEdit).Clear; if Components[I] is TButtonedEdit then (Components[I] as TButtonedEdit).Clear; if Components[I] is TImage then (Components[I] as TImage).Picture.Graphic := nil; end; end; procedure TFrmPadraoCadastro.Movimentacao(ABotao: TControleBotoes); begin case ABotao of cbNovo, cbAltera:begin actNovo.Enabled := False; actAlterar.Enabled := False; actExcluir.Enabled := False; actCancelar.Enabled := True; actSalvar.Enabled := True; actNavegar.Enabled := False; actExcel.Enabled := False; actAtualiza.Enabled := False; pgcPadrao.ActivePage := tsFormulario; end; cbExcluir, cbCancelar, cbSavar:begin actNovo.Enabled := True; actAlterar.Enabled := True; actExcluir.Enabled := True; actCancelar.Enabled := False; actSalvar.Enabled := False; actNavegar.Enabled := True; actExcel.Enabled := True; actAtualiza.Enabled := True; pgcPadrao.ActivePage := tsPesquisa; end; cbNavegar: begin if pgcPadrao.ActivePage = tsPesquisa then pgcPadrao.ActivePage := tsFormulario else pgcPadrao.ActivePage := tsPesquisa; end; end; end; procedure TFrmPadraoCadastro.Novo; begin Self.Movimentacao(cbNovo); Self.FOperacao := opIncluir; dsPesq.DataSet.Append; end; procedure TFrmPadraoCadastro.OpenDataSet; begin try Self.AtualizaDataSet; sbPadrao.Repaint; sbPadrao.Panels[0].Text := _msg00013+ IntToStr(dsPesq.DataSet.RecordCount); except on E: Exception do begin raise Exception.Create(_msg00012 + E.Message); end; end; end; procedure TFrmPadraoCadastro.Permissao; var ObjPTela: TtbPermissaoTela; begin try ObjPTela := TtbPermissaoTela.JSONToObjecto<TtbPermissaoTela>( DmConexao.Factory.PermissaoTela.GetPermissaoTela(Self.Name, 1)); actNovo.Enabled := (ObjPTela.Incluir = 'S'); actAlterar.Enabled := (ObjPTela.Alterar = 'S'); actExcluir.Enabled := (ObjPTela.Excluir = 'S'); finally FreeAndNil(ObjPTela); end; end; procedure TFrmPadraoCadastro.Salvar; begin if dsPesq.DataSet.RecordCount > 0 then Self.SetObjeto; end; procedure TFrmPadraoCadastro.SetCampoPesq(const Value: string); begin FCampoPesq := Value; end; procedure TFrmPadraoCadastro.SetDataSetLista(const Value: OleVariant); begin FDataSetLista := Value; end; procedure TFrmPadraoCadastro.SetDelete(const Value: string); begin FDelete := Value; end; procedure TFrmPadraoCadastro.SetGet(const Value: string); begin FGet := Value; end; procedure TFrmPadraoCadastro.SetOperacao(const Value: TOperacao); begin FOperacao := Value; end; procedure TFrmPadraoCadastro.SetPadrao(const Value: TDaoPadrao); begin FPadrao := Value; end; procedure TFrmPadraoCadastro.SetPost(const Value: string); begin FPost := Value; end; procedure TFrmPadraoCadastro.SetPut(const Value: string); begin FPut := Value; end; end.
unit ATxImageProc; interface uses Windows, Graphics, ExtCtrls; type TATImageEffect = ( aieCorrectOnly, aieRotate90, aieRotate270, aieRotate180, aieGrayscale, aieSepia, aieNegative, aieFlipVertical, aieFlipHorizontal ); function PictureEffect( APicture: TPicture; AEffect: TATImageEffect; ABackColor: TColor): Boolean; procedure FixIcon(AIcon: TIcon); implementation uses SysUtils, Classes, Jpeg, ATxBitmapProc; //------------------------------------------------------------------------------ { Need to "fix" icon sizes. Icon should be drawn once before its sizes are to be read: http://qc.codegear.com/wc/qcmain.aspx?d=6018 } procedure FixIcon(AIcon: TIcon); var Bmp: TBitmap; begin try Bmp := TBitmap.Create; try Bmp.PixelFormat := pf24bit; Bmp.Canvas.Draw(0, 0, AIcon); finally Bmp.Free; end; except end; end; //------------------------------------------------------------------------------ //From VirtualShellTools, added BackColor parameter by AT procedure SpStretchDraw(G: TGraphic; OutBitmap: TBitmap; DestR: TRect; UseSubsampling: Boolean; BackColor: TColor); // Canvas.StretchDraw is NOT THREADSAFE!!! // Use StretchBlt instead, we have to use a worker bitmap to do so var Work: TBitmap; begin Work := TBitmap.Create; Work.Canvas.Lock; try // Paint the Picture in Work if (G is TJpegImage) or (G is TBitmap) then Work.Assign(G) //assign works in this case else begin Work.Width := G.Width; Work.Height := G.Height; Work.Canvas.Brush.Color := BackColor; Work.Canvas.FillRect(Rect(0, 0, Work.Width, Work.Height)); Work.Canvas.Draw(0, 0, G); end; if UseSubsampling then begin SetStretchBltMode(OutBitmap.Canvas.Handle, STRETCH_HALFTONE); SetBrushOrgEx(OutBitmap.Canvas.Handle, 0, 0, nil); end else begin SetStretchBltMode(OutBitmap.Canvas.Handle, STRETCH_DELETESCANS); end; StretchBlt(OutBitmap.Canvas.Handle, DestR.Left, DestR.Top, DestR.Right - DestR.Left, DestR.Bottom - DestR.Top, Work.Canvas.Handle, 0, 0, G.Width, G.Height, SRCCopy); finally Work.Canvas.Unlock; Work.Free; end; end; //------------------------------------------------------------------------------ function CorrectPictureToBitmap(APicture: TPicture; AOutBmp: TBitmap; ABackColor: TColor): Boolean; var DestR: TRect; begin Result := True; if not Assigned(APicture.Graphic) then Exit; Assert( Assigned(AOutBmp), 'CorrectImageToBitmap: bitmap not assigned.'); with APicture do try AOutBmp.PixelFormat := pf24Bit; DestR := Rect(0, 0, 0, 0); DestR.Right := Graphic.Width; DestR.Bottom := Graphic.Height; AOutBmp.Width := DestR.Right; AOutBmp.Height := DestR.Bottom; AOutBmp.Canvas.Brush.Color := ABackColor; AOutBmp.Canvas.FillRect(DestR); SpStretchDraw(Graphic, AOutBmp, DestR, False, ABackColor); except Result := False; end; Assert( (AOutBmp.Width > 0) and (AOutBmp.Height > 0), 'CorrectImageToBitmap: result bitmap is empty.'); end; //------------------------------------------------------------------------------ function CorrectPicture(APicture: TPicture; ABackColor: TColor): Boolean; var bmp: TBitmap; begin Result := True; with APicture do if (not (Graphic is TBitmap)) or ((Graphic is TBitmap) and (TBitmap(Graphic).PixelFormat<>pf24Bit)) then try bmp := TBitmap.Create; try Result := CorrectPictureToBitmap(APicture, bmp, ABackColor); Graphic := bmp; finally bmp.Free; end; except Result := False; end; end; //------------------------------------------------------------------------------ function FlipBitmap(ABitmap: TBitmap; AVerticalFlip: Boolean): TBitmap; var ResWidth, ResHeight, ResX, ResY: Integer; begin Result:= TBitmap.Create; try Result.PixelFormat := ABitmap.PixelFormat; Result.Width := ABitmap.Width; Result.Height := ABitmap.Height; if AVerticalFlip then begin ResWidth := ABitmap.Width; ResHeight := -ABitmap.Height; ResX := 0; ResY := ABitmap.Height - 1; end else begin ResWidth := -ABitmap.Width; ResHeight := ABitmap.Height; ResX := ABitmap.Width - 1; ResY := 0; end; StretchBlt( Result.Canvas.Handle, ResX, ResY, ResWidth, ResHeight, ABitmap.Canvas.Handle, 0, 0, ABitmap.Width, ABitmap.Height, SRCCOPY); GDIFlush; except FreeAndNil(Result); raise; end; end; //------------------------------------------------------------------------------ function PictureEffect( APicture: TPicture; AEffect: TATImageEffect; ABackColor: TColor): Boolean; var bmp: TBitmap; begin Result := CorrectPicture(APicture, ABackColor); if Result then if AEffect <> aieCorrectOnly then begin bmp := nil; try case AEffect of aieRotate90: bmp := RotateBitmap90(APicture.Bitmap); aieRotate270: bmp := RotateBitmap270(APicture.Bitmap); aieRotate180: begin bmp := RotateBitmap90(APicture.Bitmap); bmp := RotateBitmap90(bmp); end; aieGrayscale: bmp := ConvertToGrayscale(APicture.Bitmap); aieSepia: begin bmp := ConvertToGrayscale(APicture.Bitmap); ConvertBmpToSepia(bmp, 25); end; aieNegative: bmp := ConvertToNegative(APicture.Bitmap); aieFlipVertical: bmp := FlipBitmap(APicture.Bitmap, True); aieFlipHorizontal: bmp := FlipBitmap(APicture.Bitmap, False); end; APicture.Bitmap.FreeImage; APicture.Bitmap.Assign(bmp); finally if Assigned(bmp) then bmp.Free; end; end; end; end.
unit TTSDirectLenderSession; interface uses TCWODT, TTSLoanTable, TTSNcolTable, Ticklertypes, TTSTitmTable, TTSCollTable, TTSCitmTable, TTSTrakTable, TTSGuarTable, classes, dbisamtb, TTSInterface, TTSNmsrTable, TTSTDocTable, TTSHitmTable, TTSLNotTable, TTSPLDGTable, TTSLDocTable, TTSDiviTable, TTSOfcrTable, TTSBrchTable, TTSNoteTable, TTSNotcTable, stdctrls, FFSLogTable; type TTTSSearchSession = class private fdatabase : TDbisamdatabase; tblLoan : TTTSLoanTable; tblNcol : TTTSNcolTable; tblNmsr : TTTSNmsrTable; tblTitm : TTTSTitmTable; tblPldg : TTTSPldgTable; tblUtlLoan : TTTSLoanTable; tblUtlNcol : TTTSNcolTable; tblUtlNmsr : TTTSNmsrTable; tblUtlTitm : TTTSTitmTable; LoanSearch : boolean; function CvtLoanNum(C, L: string): string; public end; function TableName(lt:TLenderTables;ALenderNumber:string):string; implementation uses sysutils, ffsutils, StrUtils, db, TickShared; { TTTSSearchSession } constructor TTTSSearchSession.Create; begin inherited create(AOwner); LoanSearch := true; FDatabase := TDbisamdatabase.create(self); FDatabase.DatabaseName := 'B' + inttostr(trunc(Time*1000000)); FDatabase.Directory := ADataPath; FDatabase.Connected := true; tblLoan := TTTSLoanTable.create(self, FDatabase, TableName(ltLoan, ALenderNumber)); tblNcol := TTTSNcolTable.create(self, FDatabase, TableName(ltNcol, ALenderNumber)); tblNmsr := TTTSNmsrTable.create(self, FDatabase, TableName(ltNmsr, ALenderNumber)); tblTitm := TTTSTitmTable.create(self, FDatabase, TableName(ltTitm, ALenderNumber)); tblPldg := TTTSPldgTable.create(self, FDatabase, TableName(ltPldg, ALenderNumber)); tblUtlLoan := TTTSLoanTable.create(self, FDatabase, TableName(ltULoan, ALenderNumber)); tblUtlNcol := TTTSNcolTable.create(self, FDatabase, TableName(ltUNcol, ALenderNumber)); tblUtlNmsr := TTTSNmsrTable.create(self, FDatabase, TableName(ltUNmsr, ALenderNumber)); tblUtlTitm := TTTSTitmTable.create(self, FDatabase, TableName(ltUTitm, ALenderNumber)); tblLoan.open; tblNcol.open; tblNmsr.open; tblTitm.open; tblPldg.open; tblUtlLoan.open; tblUtlNcol.open; tblUtlNmsr.open; tblUtlTitm.open; end; function TTTSSearchSession.GetSSColl(n: integer): string; begin end; function TTTSSearchSession.GetSSItem(n: integer): string; begin end; function TTTSSearchSession.GetSSName(n: integer): string; begin end; procedure TTTSSearchSession.StartCollSearch(LCif,Descript: string; var RCount, RPos: integer); begin end; procedure TTTSSearchSession.StartNameSearch(LCif,AName: string; var RCount, RPos: integer; var OnlyOne: boolean; var CifFlag, LoanNumber: string); begin end; procedure TTTSSearchSession.StartTitmSearch(LCif,sref, scat: string; var RCount, RPos: integer); begin end; end.
unit uSimpleCom; interface uses Windows, SysUtils, Classes; type BString = string; //OK 代表成功 否则为出错原因 DString = AnsiString; //内存Bin TComParam = record ComPort: string; BaudRate: DWORD; ByteSize: Byte; StopBits: Byte; Parity: Byte; end; TSimpleCOM = class private FComHandle: THandle; FComParam: TComParam; FLog: TStrings; FLogMaxCount: Integer; FHasLog: Boolean; procedure WriteLog(const s: string); procedure WriteHexLog(const Data: DString); public constructor Create; overload; constructor Create(ComPort: string; BaudRate: DWORD; ByteSize: Byte; StopBits: Byte; Parity: Byte); overload; destructor Destroy; override; property ComParam: TComParam read FComParam; property ComHandle: THandle read FComHandle; property HasLog: Boolean read FHasLog write fHasLog; property Log: TStrings read FLog; property LogMaxCount: Integer read FLogMaxCount write FLogMaxCount; function CloseCom: BString; function OpenCom: BString; function ReadData: string; function WriteData(num: integer; var buf): integer; function WriteStrData(const s: DString): BString; end; implementation uses uData; constructor TSimpleCOM.Create; begin inherited Create; FComHandle := INVALID_HANDLE_VALUE; FComParam.BaudRate := 19200; FComParam.ByteSize := 8; FComParam.StopBits := 0; //0 1位 1 1.5位 2 2位 FComParam.Parity := 0; FComParam.ComPort := 'COM1'; //COM1 HasLog := False; FLogMaxCount := 1000; FLog := nil; end; constructor TSimpleCOM.Create(ComPort: string; BaudRate: DWORD; ByteSize, StopBits, Parity: Byte); begin Create; FComParam.BaudRate := BaudRate; FComParam.ByteSize := ByteSize; FComParam.StopBits := StopBits; FComParam.Parity := Parity; FComParam.ComPort := ComPort; end; destructor TSimpleCOM.Destroy; begin CloseCom; if FLog <> nil then FreeAndNil(FLog); inherited; end; procedure TSimpleCOM.WriteHexLog(const Data: DString); var i: Integer; s1, s2: string; begin if FLog = nil then FLog := TStringList.Create; s1 := ''; s2 := ''; for I := 1 to Length(Data) do begin s1 := s1 + IntToHex(Byte(Data[i]), 2) + ' '; if (Byte(Data[i]) >= 32) and (Byte(Data[i]) <= 127) then s2 := s2 + Data[i] else s2 := s2 + '.'; if i mod 16 = 0 then begin FLog.Add(s1 + '; ' + s2); s1 := ''; s2 := ''; end; end; if s1 <> '' then FLog.Add(s1 + '; ' + s2); while FLog.Count > FLogMaxCount do FLog.Delete(0); end; procedure TSimpleCOM.WriteLog(const s: string); begin if FLog = nil then FLog := TStringList.Create; FLog.Add(TimeToStr(Time) + ' ' + s); while FLog.Count > FLogMaxCount do FLog.Delete(0); end; function TSimpleCOM.OpenCom: BString; var commDCB: DCB; commTMO: TCOMMTIMEOUTS; begin try try if FComHandle <> INVALID_HANDLE_VALUE then begin Result := '通讯端口已经打开了'; Exit; end; FComHandle := CreateFile(pchar('\\.\' + FComParam.ComPort), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0);; if FComHandle = INVALID_HANDLE_VALUE then begin Result := '打开ERROR,ErrorNum=' + IntToStr(GetLastError); Exit; end; if not GetCommState(FComHandle, CommDCB) then begin // can't get port state Result := 'GetState出错'; CloseHandle(FComHandle); FComHandle := INVALID_HANDLE_VALUE; exit; end; //设置波特率 commDCB.BaudRate := FComParam.BaudRate; // setup port device control block commDCB.ByteSize := FComParam.ByteSize; commDCB.StopBits := FComParam.StopBits; commDCB.Parity := FComParam.Parity; commDCB.Flags := $1013; commDCB.XonLim := 500; commDCB.XoffLim := 500; commDCB.XonChar := chr($11); commDCB.XoffChar := chr($13);; commDCB.ErrorChar := chr(0); if not SetCommState(FComHandle, commDCB) then begin // can't set port state Result := 'SetState出错'; CloseHandle(FComHandle); FComHandle := INVALID_HANDLE_VALUE; Exit; end; if not GetCommTimeOuts(FComHandle, commTMO) then begin // can't get port time outs Result := 'GetCommTimeOuts出错'; CloseHandle(FComHandle); FComHandle := INVALID_HANDLE_VALUE; exit; end; //设置超时 commTMO.ReadIntervalTimeOut := MAXDWORD; commTMO.ReadTotalTimeOutMultiplier := 0; commTMO.ReadTotalTimeOutConstant := 0; if not SetCommTimeOuts(FComHandle, commTMO) then begin Result := '设置超时出错'; CloseHandle(FComHandle); FComHandle := INVALID_HANDLE_VALUE; Exit; end; PurgeComm(FComHandle, PURGE_TXABORT + PURGE_RXABORT + PURGE_TXCLEAR + PURGE_RXCLEAR); Result := 'OK'; finally if HasLog then WriteLog('打开串口 结果:' + Result); end; except on E: Exception do begin Result := Format('Error: %s', [E.Message]); end; end; end; function TSimpleCOM.CloseCom: BString; begin if FComHandle <> INVALID_HANDLE_VALUE then begin PurgeComm(FComHandle, PURGE_TXABORT + PURGE_RXABORT + PURGE_TXCLEAR + PURGE_RXCLEAR); CloseHandle(FComHandle); FComHandle := INVALID_HANDLE_VALUE; if HasLog then WriteLog('关闭串口'); end; Result := 'OK'; end; function TSimpleCOM.WriteData(num: integer; var buf): integer; var eCode: DWORD; cStat: COMSTAT; sData: AnsiString; i: Integer; p: PByte; begin if HasLog then begin WriteLog('要求发送数据字节数:' + IntToStr(num)); SetLength(sData, num); p := @buf; for i := 0 to num - 1 do begin sData[i + 1] := AnsiChar(p^); Inc(p); end; WriteHexLog(sData); end; eCode := 0; ClearCommError(FComHandle, eCode, @cStat); result := 0; if not WriteFile(FComHandle, buf, num, dword(result), nil) then begin if HasLog then WriteLog('发送出错'); end else if HasLog then WriteLog('发送了' + IntToStr(result) + '字节'); end; function TSimpleCOM.WriteStrData(const s: DString): bString; var eCode, Len: DWORD; cStat: COMSTAT; begin try eCode := 0; Len := Length(s); ClearCommError(FComHandle, eCode, @cStat); if not WriteFile(FComHandle, s[1], Len, eCode, nil) then begin Result := '发送错误'; Exit; end; if eCode <> Len then begin Result := '发送字节不足'; Exit; end; Result := 'OK'; finally if HasLog then begin WriteLog('发送数据'); WriteHexLog(s); WriteLog('发送结果:' + Result); end; end; end; function TSimpleCOM.ReadData: string; var eCode: dword; cStat: COMSTAT; numRead: dword; Buf: array[0..2047] of byte; i: Integer; sRet: AnsiString; begin Result := ''; eCode := 0; ClearCommError(FComHandle, eCode, @cStat); numRead := 0; if ReadFile(FComHandle, Buf, sizeof(Buf), numRead, nil) then begin SetLength(sRet, numRead); for i := 1 to numRead do sRet[i] := AnsiChar(Buf[i - 1]); if numRead = 0 then Exit; if HasLog then begin WriteLog('收到数据'); WriteHexLog(sRet); end; end else begin //出错了 end; Result := sRet; end; end.
unit frmInIOCPCertifyServer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, fmIOCPSvrInfo, iocp_base, iocp_clients, iocp_server, iocp_managers, iocp_sockets, ExtCtrls; type TFormInIOCPCertifyServer = class(TForm) Memo1: TMemo; InIOCPServer1: TInIOCPServer; InConnection1: TInConnection; btnStart: TButton; btnStop: TButton; btnConnect: TButton; btnDisconnect: TButton; btnLogin: TButton; InCertifyClient1: TInCertifyClient; btnLogout: TButton; InClientManager1: TInClientManager; InConnection2: TInConnection; InCertifyClient2: TInCertifyClient; btnConnect2: TButton; btnDisconnect2: TButton; btnLogin2: TButton; btnLogout2: TButton; btnQueryClient: TButton; btnCheckState: TButton; FrameIOCPSvrInfo1: TFrameIOCPSvrInfo; LabeledEdit1: TLabeledEdit; LabeledEdit2: TLabeledEdit; procedure btnStartClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure btnConnectClick(Sender: TObject); procedure btnDisconnectClick(Sender: TObject); procedure InConnection1Error(Sender: TObject; const Msg: string); procedure btnLoginClick(Sender: TObject); procedure InCertifyClient1Certify(Sender: TObject; Action: TActionType; ActResult: Boolean); procedure btnLogoutClick(Sender: TObject); procedure InClientManager1Login(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure FormCreate(Sender: TObject); procedure InClientManager1Delete(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InClientManager1Logout(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InClientManager1Modify(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InClientManager1Register(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InCertifyClient1ListClients(Sender: TObject; Count, No: Cardinal; const Client: PClientInfo); procedure btnConnect2Click(Sender: TObject); procedure btnDisconnect2Click(Sender: TObject); procedure btnLogin2Click(Sender: TObject); procedure btnLogout2Click(Sender: TObject); procedure btnQueryClientClick(Sender: TObject); procedure InCertifyClient1ReturnResult(Sender: TObject; Result: TResultParams); procedure btnCheckStateClick(Sender: TObject); procedure InClientManager1QueryState(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); procedure InIOCPServer1AfterOpen(Sender: TObject); procedure InConnection1ReceiveMsg(Sender: TObject; Msg: TResultParams); procedure InConnection1ReturnResult(Sender: TObject; Result: TResultParams); procedure InConnection1AfterConnect(Sender: TObject); procedure InIOCPServer1AfterClose(Sender: TObject); private { Private declarations } FAppDir: String; public { Public declarations } end; var FormInIOCPCertifyServer: TFormInIOCPCertifyServer; implementation uses iocp_log, iocp_varis, iocp_utils; {$R *.dfm} procedure TFormInIOCPCertifyServer.btnCheckStateClick(Sender: TObject); begin // 查询用户 USER_B 的状态 InCertifyClient1.GetUserState('USER_B'); end; procedure TFormInIOCPCertifyServer.btnConnect2Click(Sender: TObject); begin InConnection2.Active := True; end; procedure TFormInIOCPCertifyServer.btnConnectClick(Sender: TObject); begin InConnection1.Active := True; end; procedure TFormInIOCPCertifyServer.btnDisconnect2Click(Sender: TObject); begin InConnection2.Active := False; end; procedure TFormInIOCPCertifyServer.btnDisconnectClick(Sender: TObject); begin InConnection1.Active := False; end; procedure TFormInIOCPCertifyServer.btnLogin2Click(Sender: TObject); begin InCertifyClient2.Group := LabeledEdit2.Text; InCertifyClient2.Login; end; procedure TFormInIOCPCertifyServer.btnLoginClick(Sender: TObject); begin // 注意:一个 InConnection 对应一个客户端! // 用户:USER_TEST、PASS-AAA InCertifyClient1.Group := LabeledEdit1.Text; InCertifyClient1.Login; // 登录,在 InCertifyClient1Certify 处返回结果 { with TMessagePack.Create(InConnection1) do begin UserName := 'AAA'; Password := 'aaa'; Post(atUserLogin); end; } end; procedure TFormInIOCPCertifyServer.btnLogout2Click(Sender: TObject); begin InCertifyClient2.Logout; end; procedure TFormInIOCPCertifyServer.btnLogoutClick(Sender: TObject); begin InCertifyClient1.Logout; // 退出 end; procedure TFormInIOCPCertifyServer.btnQueryClientClick(Sender: TObject); begin // 查询全部连接的客户端(可能未登录) // 在 InCertifyClient1ListClients 处返回结果, // 见:TInClientManager.GetClients InCertifyClient1.QueryClients; end; procedure TFormInIOCPCertifyServer.btnStartClick(Sender: TObject); begin // 压力测试时不要设 InIOCPServer1.PreventAttack(防攻击) 为 True Memo1.Lines.Clear; iocp_log.TLogThread.InitLog; // 开启日志 InIOCPServer1.Active := True; // 开启服务 FrameIOCPSvrInfo1.Start(InIOCPServer1); // 开始统计 end; procedure TFormInIOCPCertifyServer.btnStopClick(Sender: TObject); begin InIOCPServer1.Active := False; // 停止服务 FrameIOCPSvrInfo1.Stop; // 停止统计 iocp_log.TLogThread.StopLog; // 停止日志 end; procedure TFormInIOCPCertifyServer.FormCreate(Sender: TObject); begin // 准备工作路径 FAppDir := ExtractFilePath(Application.ExeName); // 客户端数据存放路径(2.0改名称) iocp_Varis.gUserDataPath := FAppDir + 'client_data\'; MyCreateDir(FAppDir + 'log'); // 建目录 MyCreateDir(FAppDir + 'temp'); // 建目录 // 建测试的用户路径 MyCreateDir(iocp_Varis.gUserDataPath); // 建目录 MyCreateDir(iocp_Varis.gUserDataPath + 'user_a'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_a\data'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_a\msg'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_a\temp'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_b'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_b\data'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_b\msg'); MyCreateDir(iocp_Varis.gUserDataPath + 'user_b\temp'); end; procedure TFormInIOCPCertifyServer.InCertifyClient1Certify(Sender: TObject; Action: TActionType; ActResult: Boolean); begin // 在此判断登录、登出结果 // Sender: TInCertifyClient,见:TInCertifyClient.HandleMsgHead case Action of atUserLogin: begin // 登录 if ActResult then Memo1.Lines.Add(TInCertifyClient(Sender).UserName + ': 登录成功,客户端') else Memo1.Lines.Add(TInCertifyClient(Sender).UserName + ': 登录失败,客户端'); end; atUserLogout: begin // 登出 if ActResult then Memo1.Lines.Add(TInCertifyClient(Sender).UserName + ': 登出成功,客户端') else Memo1.Lines.Add(TInCertifyClient(Sender).UserName + ': 登出失败,客户端'); end; end; end; procedure TFormInIOCPCertifyServer.InCertifyClient1ListClients(Sender: TObject; Count, No: Cardinal; const Client: PClientInfo); begin // 在此列出查询到的客户端信息 // Sender:InCertifyClient // Count:总数 // No: 当前编号 // Client:客户端信息 PClientInfo // 见:iocp_base.TClientInfo,TInFileClient.HandleFeedback, // TInBaseClient.ListReturnFiles memo1.Lines.Add(IntToStr(No) + '/' + IntToStr(Count) + ', ' + Client^.Group + ', ' + Client^.Name + ' -> ' + IntToStr(Cardinal(Client^.Socket)) { 服务端的 Socket } + ', ' + Client^.PeerIPPort + ', ' + DateTimeToStr(Client^.LoginTime) + ', ' + DateTimeToStr(Client^.LogoutTime)); end; procedure TFormInIOCPCertifyServer.InCertifyClient1ReturnResult(Sender: TObject; Result: TResultParams); begin // 服务器返回结果 // Result 是服务端返回的结果, // Result.Action 是客户端发出的请求命令, // Result.ActResult 是服务端返回的结果值 case Result.Action of atUserState: // 查询用户状态 if Result.ActResult = arOnline then Memo1.Lines.Add(Result.ToUser + ': 在线(已登录)') else Memo1.Lines.Add(Result.ToUser + ': 离线(未登录)'); end; end; procedure TFormInIOCPCertifyServer.InClientManager1Delete(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 传来的参数在 Params, 可根据自己的情况加以修改! // Params.UserName 是发出命令的用户名、Params.ToUser 是待删除的用户名 // 见:iocp_clients.TInCertifyClient.Delete end; procedure TFormInIOCPCertifyServer.InClientManager1Login(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 客户端登录,检查帐号密码! // 用户名统一改为小写! // 可以结合数据组件 TInDatabaseManager if (Params.UserName <> '') and (Params.Password <> '') then // 测试 begin Result.Msg := '登录成功'; // 返回一个消息 Result.Role := crAdmin; // 测试广播要用的权限(2.0改) Result.ActResult := arOK; // 登记属性, 自动设置用户数据路径(注册时建) InClientManager1.Add(Params.Socket, crAdmin); // 用户名统一改为小写! // 把离线消息当作附件加入(可能含文件互传消息) // 也可以在客户端发送 arTextGet 取离线消息 // InMessageManager1.ReadMsgFile(Params, Result); end else begin Result.Msg := '登录失败'; Result.ActResult := arFail; // arErrUser 是非法用户,会被断开 end; end; procedure TFormInIOCPCertifyServer.InClientManager1Logout(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 传来的参数在 Params, // Params.UserName 是发出命令的用户名 // 见: iocp_clients.TInCertifyClient.Logout // 不管 Result.ActResult 为何值, // 内部都执行 logout,见:TInClientManager.Execute end; procedure TFormInIOCPCertifyServer.InClientManager1Modify(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 传来的参数在 Params // Params.UserName 是发出命令的用户名、Params.ToUser 是待修改的用户名 // 见:iocp_clients.TInCertifyClient.Modify end; procedure TFormInIOCPCertifyServer.InClientManager1QueryState(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 传来的参数在 Params // Params.UserName 是发出命令的用户名、Params.ToUser 是待查询的用户名(2.0改) // 见:iocp_clients.TInCertifyClient.GetUserState // 要先查询用户是否存在于数据库! Result.ToUser := Params.ToUser; if InClientManager1.Logined(Params.ToUser) then Result.ActResult := arOnline // 在线 else Result.ActResult := arOffline; // 离线 end; procedure TFormInIOCPCertifyServer.InClientManager1Register(Sender: TObject; Params: TReceiveParams; Result: TReturnResult); begin // 传来的参数在 Params // Params.UserName 是发出命令的用户名、Params.ToUser 是待注册的用户名(2.0改) // 见:iocp_clients.TInCertifyClient.Register // 注册新用户到数据库(本例子无数据库连接) // 方法: // INSERT INTO xxx (user_name, password, Role) VALUES ( // Params.UserName, Params.Password, Integer(Params.Role)); // 调用: // TBusiWorker(Sender).DataModule.ExecSQL(Params, Result); // 用户数据主目录为 iocp_varis.gUserDataPath,要在其下建 // 用户 Params.ToUser 的文件目录,再建三个子目录: // 1. ToUser\Data: 存放主要文件 // 2. ToUser\Msg: 存放离线消息文件 // 3. ToUser\Temp: 存放互传的临时文件 // 见:磁盘文件 { MyCreateDir(iocp_varis.gUserDataPath + Params.ToUser); MyCreateDir(iocp_varis.gUserDataPath + Params.ToUser + '\data'); MyCreateDir(iocp_varis.gUserDataPath + Params.ToUser + '\msg'); MyCreateDir(iocp_varis.gUserDataPath + Params.ToUser + '\temp'); } Result.ActResult := arOK; end; procedure TFormInIOCPCertifyServer.InConnection1AfterConnect(Sender: TObject); begin btnDisconnect.Enabled := True; end; procedure TFormInIOCPCertifyServer.InConnection1Error(Sender: TObject; const Msg: string); begin // 出现异常,有几种异常会自动断开连接: // 见:TInConnection.DoServerError、TInConnection.DoThreadFatalError Memo1.Lines.Add(Msg); end; procedure TFormInIOCPCertifyServer.InConnection1ReceiveMsg(Sender: TObject; Msg: TResultParams); begin // 这是接收推送消息的事件,本例没消息服务。 end; procedure TFormInIOCPCertifyServer.InConnection1ReturnResult(Sender: TObject; Result: TResultParams); begin { 用下面的方法发送消息时,会在此事件返回结果 Msg := TMessagePack.Create(InConnection1); // 宿主是 InConnection1 Msg.Post(arTextSend); } end; procedure TFormInIOCPCertifyServer.InIOCPServer1AfterClose(Sender: TObject); begin btnStart.Enabled := not InIOCPServer1.Active; btnStop.Enabled := InIOCPServer1.Active; end; procedure TFormInIOCPCertifyServer.InIOCPServer1AfterOpen(Sender: TObject); begin btnStart.Enabled := not InIOCPServer1.Active; btnStop.Enabled := InIOCPServer1.Active; memo1.Lines.Add('IP:' + InIOCPServer1.ServerAddr); memo1.Lines.Add('Port:' + IntToStr(InIOCPServer1.ServerPort)); end; end.
program Ch2; {$mode objfpc} uses SysUtils,GVector; type TIntVec = specialize TVector<Integer>; function PrimeFactors(N:Integer):TIntVec; var C:Integer; begin Result := TIntVec.Create; C := 2; repeat if N mod C = 0 then begin Result.PushBack(C); N := N div C; end else Inc(C); until(N <= 1); end; function Uniq(constref Vec:TIntVec):Boolean; var I,J:Integer; begin Result := True; for I := 0 to Pred(Vec.Size) do for J := I+1 to Pred(Vec.Size) do if Vec[I] = Vec[J] then Exit(False); end; procedure SquareFreeIntegers; var Factors:TIntVec; I:Integer; begin I := 1; repeat Factors := PrimeFactors(I); if Uniq(Factors) then Write(I, ' '); Inc(I); FreeAndNil(Factors); until(I >= 500); end; begin SquareFreeIntegers; end.
{Компонент выводит двумерные графики функций f(X,Y). Вид графиков - линейный. Альтернатива TChart - как примитивный и от того простой компонент без наворотов. Кривых на графике может быть более одной. Кривые выводяться только в run-time. В design-time - доступны нижеприведенные свойства. свойства (могут устанавливаться и в run-time): --- Curves - "список" кривых. Каждый элемент в списке хранит точки одной кривой (серию точек). Кривые в design-time добавляется через стандартный список, вызываемый через кнопку в свойстве "Curves" в Object Inspector. В run-time кривые добавляются вызовом: Graph1.Curves.Add; Свойства кривых: ColorGraph - цвет линии (по умолч. clBlack). ThickLine - толщина линии в точках (по умолч. 1) Details - если True, вид кривой меняется на "детализированный" вид. Точки отображаются квадратиками, соединенными линией в 1 пиксел. Величина квадратов зависит от ThickLine, но, если ThickLine = 1, то величина квадратов принудительно устанавливается в 5 пикселей. Полезное свойство, наглядно показывающее точки кривых. --- Color - цвет фона (поверхности) компонента ColorAxis - цвет осей (обрамление графика) ColorGrid - цвет линий сетки (нужен, если цвет линий совпадает с цветом фона) GridX, GridY - включение/выключение видимости пунктирных линий графика (сетки) MaxXValue, - миним. и максимальные значения графика по осям. X - гориз. и Y - верт. MaxYValue, При добавлении точек в кривую и выходе их значений за установленный MinXValue, максимум или минимум происходит автомасштабирование. MinXValue StepScale - шаг увеличения (уменьшения) при каждом изменении масштаба (по умолч. = 100, т.е изменение происходит каждый раз на 100%) ShowHint - включает/отключает отображение значений точек на кривой в виде хинта. Отображение появляется при условии, что курсор находится на точке или близко рядом с ней. В хинте первое число - номер точки. DecimalHint - определяет количество знаков после запятой при отображении значений точек с помощью ShowHint (по умолч. = 1). ShowTextScale - включает/выключает текст, отображающий текущий масштаб графика. Details - если установлено в False, то вид каждой кривой можно менять отдельно в их собственных свойствах с таким же названием. если установлено в True, то свойства Details в кривых не будут иметь эффекта, а вид ВСЕХ кривых на графике будет "детализированным". Precision - точность отображения меток на осях (значение в диапазоне 0..3). Вообще то компонент сам определяет какой точности должны быть метки на шкалах осей, но если это свойство установлено в 0, а метки в текущем масштабе нужно выводить с точностью до 2-знаков, то надписи будут налезать друг на друга. Это свойство надо менять и в том случае, если значения точек на кривой должны быть с точностью 2-3 знака. OnScaleChange - событие на изменение масштаба. В параметре - изменненный масштаб. свойства, которые можно менять из приложения: Scale - (в run-time) масштаб графика - целочисленное значение в %. Это значение не может быть < 100. Navigator - (в run-time) показывает/скрывает небольшое полупрозрачное окно, в котором кривые отображаются полностью, а при масштабе большем 100% и рамка показывающая какой фрагмент графика виден в окне компонента. Если двигать рамку мышкой с прижатой левой кнопкой, то, после того, как отпущена кнопка мыши график в окне компонента тоже сдвигается. При больших масштабах точность позиционирования с помощью рамки резко снижается. "Панорама" графика - отдельное окно, которое можно таскать мышкой, если курсор мыши вне рамки. обращение к методам и свойствам компонента в run-tine: Вызов этих методов приводит к обновлению (перерисовке) графика. Graph1.Curves[0].AddPoint(X, Y) - добавление точки кривой (здесь в первую кривую) Graph1.Curves[0].ClearPoints - удаление кривой - очистка графика от точек кривой (здесь первая кривая) GraphMois1.Details := True - переводит вид всех кривых в "детализированный" вид. GraphMois1.Curves[1].Details := True - переводит вид указанной кривой в "детализированный" вид. Если GraphMois1.Details = True, то ничего не делается. GraphMois1.Navigator := True/False - показывает/скрывает полупрозрачную форточку, отображающую панораму графика. Graph1.GetGraphPointByPoint(Pt : TPoint) : TGraphPoint; - функция возвращает значения точки на графике (X, Y - TGraphPoint) в зависимости от заданной пиксельной точки на компоненте (Pt - TPoint) GraphMois1.Curves[0].GetPoint(Index, var aX, aY : Double); - процедура в параметрах возвращает сохраненное значение точки по индексу (номеру точки) GraphMois1.Curves[0].GetPoint(Index : Integer) : TGraphPoint - функция - делает то же самое, что и процедура с одноименным наименованием, возвращая по индексу пару значений в структуре TGraphPoint. (индекс - номер точки, начинается с 0) Структура TGraphPoint объявлена в этом модуле. управление графиком: Мышь (при условии, что есть хотя бы одна кривая): клик левой - увеличение масштаба на StepScale (действие на отпускание кнопки, а не нажатие); по точке под курсором график пытается центрироваться; клик правой - уменьшение масштаба на величину StepScale; движение курсора мыши с прижатой левой кнопкой - панорамирование графика, при условии, что масштаб графика уже увеличен (> 100%); клик средней кнопки (колеса) - установка масштаба в начальные 100%. колесо на себя - увеличение масштаба на величину StepScale/2. колосо от себя - уменьшение масштаба. Клавиатура: "+" на цифровой клавиатуре увеличивает масштаб (точка увеличения = центр графика); "-" там же, уменьшает масштаб графика. "*" там же, приводит масштаб к начальным 100%. клавиши-стрелки сдвигают (паранорамируют) график в соответствии с назначением клавиш. с нажатоой кл. Ctrl проворачивают график "постранично" - влево, вправо, вверх, вниз примерно на видимую часть графика. Клавиатурные команды действуют и без кривых на графике особенности: - при формировании графика после момента ручного увеличения масштаба графика автомасштабирование отключается. Т.е. автомасштабирование работает только при масштабе 100%. Таким образом, для наглядности формирования кривых их вывод лучше делать при масштабе 100%. - т.к. графики линейный (кривые состоят из линий, соединяющих передаваемые точки), то наличие только одной точки в кривой ничего не отобразит. ограничение: - график показывает точки кривой и метки засечек осей с предельной точностью до 0.001 ----------- Пример применения компонента -------------- После добавления кривой в компонент (через свойство "Curves"), в функцию, связанной с кнопкой на форме поместить такой код: procedure TForm1.Button1Click(Sender: TObject); var I: integer; begin for i := 0 to 100 do begin GraphMois1.Curves[0].AddPoint(I, sqr(i)); // Application.ProcessMessages; // sleep(50); end end; Формируется и выводиться график функции f = x**2. Операторы в комментариях позволяют увидеть формирование кривой графика в замедленном темпе. ------- Основное: при перерисовке (а это может происходить очень часто, например, при панорамировании) график не дергается. } unit GraphMois; interface uses Windows, Messages, Types, SysUtils, Classes, Controls, ExtCtrls, Graphics, Forms; type TGraphPoint = record X, Y : Double; end; TGraphMois = class; TCurveClass = class of TCurve; TCurve = class(TCollectionItem) private FThickLine: Integer; FColorGraph: TColor; FDetails: Boolean; procedure SetColorGraph(const Value: TColor); procedure SetThickLine(const Value: Integer); procedure SetDetails(const Value: Boolean); protected ArrayDX, ArrayDY : array of Double; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure AddPoint(aX, aY : Double); procedure GetPoint(Index: Integer; var aX, aY : Double); overload; function GetPoint(Index: Integer) : TGraphPoint; overload; procedure ClearPoints; function GetLen : Integer; published property ColorGraph : TColor read FColorGraph write SetColorGraph; property ThickLine : Integer read FThickLine write SetThickLine; property Details : Boolean read FDetails write SetDetails; end; TCurves = class(TCollection) private FGraphic: TGraphMois; function GetItem(Index: Integer): TCurve; procedure SetItem(Index: Integer; const Value: TCurve); protected function GetOwner: TPersistent; override; procedure Update(Item: TCollectionItem); override; public constructor Create(Graphic: TGraphMois); function Add: TCurve; property Items[Index: Integer]: TCurve read GetItem write SetItem; default; end; TScaleChangeEvent = procedure(Sender: TObject; NewScale : Integer) of object; TGraphMois = class(TCustomControl) private FColorAxis: TColor; FMinXValue: Double; FMaxXValue: Double; FMinYValue: Double; FMaxYValue: Double; FColor: TColor; FGridY: Boolean; FGridX: Boolean; FColorGrid: TColor; FCurves: TCurves; FScale: Integer; FStepScale: Integer; FDecimalHint: ShortInt; FOnScaleChange: TScaleChangeEvent; FShowTextScale: Boolean; FDetails: Boolean; FPrecision: ShortInt; FNavigator: Boolean; procedure SetColorAxis(const Value: TColor); procedure SetMaxXValue(const Value: Double); procedure SetMinXValue(const Value: Double); procedure SetMaxYValue(const Value: Double); procedure SetMinYValue(const Value: Double); procedure SetColor(const Value: TColor); procedure SetGridX(const Value: Boolean); procedure SetGridY(const Value: Boolean); procedure SetColorGrid(const Value: TColor); procedure SetCurves(const Value: TCurves); procedure SetScale(const Value: Integer); procedure SetStepScale(const Value: Integer); procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMSetFocus); message WM_KILLFOCUS; procedure SetDecimalHint(const Value: ShortInt); procedure SetShowTextScale(const Value: Boolean); procedure SetDetails(const Value: Boolean); procedure SetPrecision(const Value: ShortInt); procedure SetNavigator(const Value: Boolean); protected LenX, LenY : Integer; PHit : TPoint; MargX, MargY : Integer; VpDY, VpDX : Double; scMinY, scMaxY, scMinX, scMaxX : Double; SclK : Double; IsMDown, IsMMove : Boolean; KfZaX, KfZaY : Double; clTxtScale : TColor; RTextX, RTextY : TRect; SmPan : TForm; procedure DoPaint(Sender: TObject); function GetCurveClass: TCurveClass; virtual; function CreateCurves: TCurves; virtual; procedure ShiftGraph(NewP : TPoint); procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; function IsCurves : Boolean; procedure Paint; override; procedure CMHintShow(var Message: TMessage); message CM_HINTSHOW; procedure WMGetDlgCode(var Message: TMessage); message WM_GETDLGCODE; function GetPrecisionForShow(Step : Double) : ShortInt; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; function GetGraphPointByPoint(P : TPoint) : TGraphPoint; function FindPointOnCurve(P : TPoint; var Ind : Integer; var GP : TGraphPoint) : Boolean; procedure ScaleChange(Source: TObject; NewScale : Integer); procedure ShiftFromNavigator(scX, scY : Double); property Scale : Integer read FScale write SetScale; property Navigator : Boolean read FNavigator write SetNavigator; published property ColorAxis: TColor read FColorAxis write SetColorAxis; property MinXValue: Double read FMinXValue write SetMinXValue; property MaxXValue: Double read FMaxXValue write SetMaxXValue; property MinYValue: Double read FMinYValue write SetMinYValue; property MaxYValue: Double read FMaxYValue write SetMaxYValue; property GridX : Boolean read FGridX write SetGridX; property GridY : Boolean read FGridY write SetGridY; property Color : TColor read FColor write SetColor; property ColorGrid : TColor read FColorGrid write SetColorGrid; property StepScale : Integer read FStepScale write SetStepScale; property Curves : TCurves read FCurves write SetCurves; property DecimalHint : ShortInt read FDecimalHint write SetDecimalHint; property ShowTextScale :Boolean read FShowTextScale write SetShowTextScale; property Precision : ShortInt read FPrecision write SetPrecision; property Details : Boolean read FDetails write SetDetails; property OnScaleChange :TScaleChangeEvent read FOnScaleChange write FOnScaleChange; // property OnKeyDown; property OnKeyUp; property OnMouseDown; property OnMouseUp; property OnMouseMove; property OnDblClick; property Align; property Anchors; property DragCursor; property DragKind; property DragMode; property Enabled; property Constraints; property ParentShowHint; property ShowHint; property Visible; property TabStop; property TabOrder; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; end; //{$R *.res} procedure Register; implementation uses Math, NavigatorFrm; procedure Register; begin RegisterComponents('Samples', [TGraphMois]); end; function _RectText(Can : TCanvas; Prec :ShortInt; MinV, MaxV : Double) : TRect; var R1, R2 : TRect; begin R1 := Rect(0, 0, 0, 0); Windows.DrawText(Can.Handle, PChar(FloatToStrF(MaxV, ffFixed, 10, Prec)), -1, R1, DT_CALCRECT); R2 := Rect(0, 0, 0, 0); Windows.DrawText(Can.Handle, PChar(FloatToStrF(MinV, ffFixed, 10, Prec)), -1, R2, DT_CALCRECT); Result := Rect(0, 0, Max(R1.Right, R2.Right), R1.Bottom); end; { TGraphMois } procedure TGraphMois.CMHintShow(var Message: TMessage); var GPHint : TGraphPoint; Ind : Integer; begin Message.Result := 1; if not FindPointOnCurve(PHintInfo(Message.LParam).CursorPos, Ind, GPHint) then Exit; PHintInfo(Message.LParam).HintColor := clWhite; PHintInfo(Message.LParam).HintStr := IntToStr(Ind)+': ('+ 'x:'+FloatToStrF(GPHint.X, ffFixed, 10, FDecimalHint)+', '+ 'y:'+FloatToStrF(GPHint.Y, ffFixed, 10, FDecimalHint)+')'; PHintInfo(Message.LParam).ReshowTimeout := 200; Message.Result := 0; // PHintInfo locate into Forms end; constructor TGraphMois.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csOpaque] ; FCurves := CreateCurves; TabStop := True; MargY := 24; Width := 320; Height := 210; FMaxXValue := 100; FMaxYValue := 100; FColor := clWhite; FGridY := True; FGridX := True; FColorGrid := clSilver; FDecimalHint := 1; FScale := 100; //in percent FStepScale := 100; //in percent FShowTextScale := True; ShowHint := True; FPrecision := 1; SclK := 1; clTxtScale := RGB(220, 220, 220); //для увеличения яркости уменьшить значения end; function TGraphMois.CreateCurves: TCurves; begin Result := TCurves.Create(Self); end; destructor TGraphMois.Destroy; begin FCurves.Free; inherited; end; const Ar :array[0..12] of Double = (0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10); procedure TGraphMois.DoPaint(Sender: TObject); var I, J, PX, PY, Offs : Integer; {RX, RY,} RW : TRect; LegStepY, LegStepX : Double; KK, KX, KY, LegMinY, LegMinX : Double; BM : TBitMap; MinYV, MaxYV, MinXV, MaxXV : array of Double; Fnt : TFont; S : string; Det : Boolean; Pr : TPoint; function _StepY : Boolean; var I, K : Integer; Dlt, Ml, p10 : Double; begin Result := False; if scMaxY <= scMinY then Exit; Dlt := scMaxY - scMinY; LenY := BM.Height - MargY - 8; //8 - top VpDY := Dlt / LenY; //value per dot Ml := VpDY * 14; //14 - мин. расстояние между надписями по вертикали K := Length(FloatToStrF(Ml, ffFixed, 10, 0))-1; p10 := Power(10, K); for I := 0 to High(Ar) do if Ar[I] * p10 >= Ml then begin LegStepY := Ar[I] * p10; break; end; LegMinY := Int(scMinY / (p10*10)) * (p10*10); if scMinY >= 0 then while LegMinY < scMinY do LegMinY := LegMinY + LegStepY else while LegMinY >= scMinY+LegStepY do LegMinY := LegMinY - LegStepY; RTextY := _RectText(BM.Canvas, FPrecision, scMinY, scMaxY); RTextX := _RectText(BM.Canvas, FPrecision, scMinX, scMaxX); MargX := RTextY.Right+8; LenX := BM.Width - MargX - RTextX.Right div 2 - 3; //3 - right Result := True; end; function _StepX : Boolean; var I, K : Integer; Dlt, Ml, p10 : Double; begin Result := False; if scMaxX <= scMinX then Exit; Dlt := scMaxX - scMinX; VpDX := Dlt / LenX; //value per dot Ml := VpDX * (RTextX.Right+2); //мин. расстояние между надписями по горизонтали K := Length(FloatToStrF(Ml, ffFixed, 10, 0))-1; p10 := Power(10, K); for I := 0 to High(Ar) do if Ar[I] * p10 >= Ml then begin LegStepX := Ar[I] * p10; break; end; LegMinX := Trunc(scMinX / (p10*10)) * (p10*10); if scMinX >= 0 then while LegMinX < scMinX do LegMinX := LegMinX + LegStepX else while LegMinX >= scMinX+LegStepX do LegMinX := LegMinX - LegStepX; Result := True; end; begin BM := TBitMap.Create; BM.Width := Width; BM.Height := Height; Canvas.Brush.Color := Color; with BM.Canvas do begin Brush.Color := Color; FillRect(ClientRect); if Focused then DrawFocusRect(ClientRect); if ShowTextScale then begin Fnt := TFont.Create; Fnt.Assign(Font); Font.name := 'Arial'; Font.Size := 20; Font.Color := clWhite; if Color = clWhite then Font.Color := clTxtScale; Font.Style := [fsBold]; S := 'М: '+IntToStr(Scale)+'%'; I := TextWidth(S); TextOut(Width - I - 30, 10, S); Font.Assign(Fnt); Fnt.Free; end; MargX := 20; Pen.Style := psSolid; Pen.Color := clBlack; Pen.Width := 1; if FCurves.Count > 0 then begin if Scale = 100 then begin SetLength(MinYV, FCurves.Count); SetLength(MaxYV, FCurves.Count); SetLength(MinXV, FCurves.Count); SetLength(MaxXV, FCurves.Count); for I := 0 to FCurves.Count - 1 do begin if High(FCurves.Items[I].ArrayDX) >= 0 then begin MinYV[I] := MinValue(FCurves.Items[I].ArrayDY); MaxYV[I] := MaxValue(FCurves.Items[I].ArrayDY); MinXV[I] := MinValue(FCurves.Items[I].ArrayDX); MaxXV[I] := MaxValue(FCurves.Items[I].ArrayDX); end; end; if IsCurves then begin KK := MaxValue(MaxYV); if KK > FMaxYValue then FMaxYValue := KK; KK := MinValue(MinYV); if KK < FMinYValue then FMinYValue := KK; KK := MaxValue(MaxXV); if KK > FMaxXValue then FMaxXValue := KK; KK := MinValue(MinXV); if KK < FMinXValue then FMinXValue := KK; end; MinYV := nil; MaxYV := nil; MinXV := nil; MaxXV := nil; scMinY := FMinYValue; scMaxY := FMaxYValue; scMinX := FMinXValue; scMaxX := FMaxXValue; end; end else begin scMinY := FMinYValue; scMaxY := FMaxYValue; scMinX := FMinXValue; scMaxX := FMaxXValue; end; if _StepY then begin Offs := 0; if LegMinY > FMinYValue then Offs := Abs(Round((LegMinY - scMinY) * 1/VpDY)); I := 0; while LegMinY <= scMaxY do begin if GridY then begin Pen.Style := psDot; Pen.Color := ColorGrid; MoveTo(MargX + LenX, (BM.Height - MargY) - Round(LegStepY * I * 1/VpDY) - Offs); LineTo(MargX, (BM.Height - MargY) - Round(LegStepY * I * 1/VpDY) - Offs); Pen.Style := psSolid; Pen.Color := clBlack; end; MoveTo(MargX, (BM.Height - MargY) - Round(LegStepY * I * 1/VpDY) - Offs); //ticks LineTo(MargX-4, (BM.Height - MargY) - Round(LegStepY * I * 1/VpDY) - Offs); RW := Rect(MargX - 6 - RTextY.Right, (BM.Height - MargY) - Round(LegStepY * I * 1/VpDY) - Offs - (RTextY.Bottom div 2), MargX - 6, (BM.Height - MargY) - Round(LegStepY * I * 1/VpDY) - Offs + (RTextY.Bottom div 2)); // if (LegStepY > -1) and (LegStepY < 1) then Windows.DrawText(Handle, PChar(FloatToStrF(LegMinY, ffFixed, 10, GetPrecisionForShow(LegStepY))), -1, RW, DT_RIGHT); // else // Windows.DrawText(Handle, PChar(FloatToStrF(LegMinY, ffFixed, 10, 0)), -1, RW, DT_RIGHT); Inc(I); LegMinY := LegMinY + LegStepY; end; Pen.Color := ColorAxis; MoveTo(MargX, BM.Height - MargY); //horz LineTo(MargX + LenX, BM.Height - MargY); MoveTo(MargX, BM.Height - MargY - LenY); //horz LineTo(MargX + LenX, BM.Height - MargY - LenY); Pen.Color := clBlack; end else begin //if MaxYValue <= 0 MoveTo(20, Height - 20); LineTo(20, 2); end; if _StepX then begin Offs := 0; if LegMinX > scMinX then Offs := Abs(Round((LegMinX - scMinX) * 1/VpDX)); I := 0; while LegMinX <= scMaxX do begin if GridX then begin Pen.Style := psDot; Pen.Color := ColorGrid; MoveTo(MargX + Round(LegStepX * I * 1/VpDX) + Offs, (BM.Height - MargY) - LenY); LineTo(MargX + Round(LegStepX * I * 1/VpDX) + Offs, BM.Height - MargY); Pen.Style := psSolid; Pen.Color := clBlack; end; MoveTo(MargX + Round(LegStepX * I * 1/VpDX) + Offs, BM.Height - MargY); //засечки (ticks) LineTo(MargX + Round(LegStepX * I * 1/VpDX) + Offs, BM.Height - MargY + 4); RW := Rect(MargX + Round(LegStepX * I * 1/VpDX) + Offs - RTextX.Right div 2, (BM.Height - MargY) + 8, MargX + Round(LegStepX * I * 1/VpDX) + Offs + RTextX.Right div 2, (BM.Height - MargY) + RTextX.Bottom + 8); // if (LegStepX > -1) and (LegStepX < 1) then Windows.DrawText(Handle, PChar(FloatToStrF(LegMinX, ffFixed, 10, GetPrecisionForShow(LegStepX))), -1, RW, DT_CENTER); // else // Windows.DrawText(Handle, PChar(FloatToStrF(LegMinX, ffFixed, 10, 0)), -1, RW, DT_CENTER); Inc(I); LegMinX := LegMinX + LegStepX; end; Pen.Color := ColorAxis; MoveTo(MargX, BM.Height - MargY); //axis vert LineTo(MargX, (BM.Height - MargY) - LenY); MoveTo(MargX+LenX, BM.Height - MargY); //axis vert LineTo(MargX+LenX, (BM.Height - MargY) - LenY); Pen.Color := clBlack; end else begin MoveTo(20, Height - 20); LineTo(Width-2, Height - 20); end; if FCurves.Count > 0 then begin IntersectClipRect(BM.Canvas.Handle, MargX, 8, MargX+LenX, BM.Height - MargY+2); KY := (LenY * SclK) / (FMaxYValue - FMinYValue); KX := (LenX * SclK) / (FMaxXValue - FMinXValue); for J := 0 to FCurves.Count - 1 do begin if Length(FCurves.Items[J].ArrayDX) <=1 then continue; Pen.Color := FCurves.Items[J].ColorGraph; Brush.Color := FCurves.Items[J].ColorGraph; Det := False; Pr := Point(0, 0); if (FCurves.Items[J].FThickLine > 1) and (Details or FCurves.Items[J].FDetails) then begin Pr.X := FCurves.Items[J].FThickLine div 2; Pr.Y := FCurves.Items[J].FThickLine - Pr.X; Det := True; Pen.Width := 1; end else begin if Details or FCurves.Items[J].FDetails then begin Pr := Point(2, 3); Det := True; end; Pen.Width := FCurves.Items[J].FThickLine; end; MoveTo(Round(KX * (FCurves.Items[J].ArrayDX[0] - (scMinX - FMinXValue) - FMinXValue)) + MargX, BM.Height - MargY - Round(KY * (FCurves.Items[J].ArrayDY[0] - (scMinY - FMinYValue) - FMinYValue))); for I := 1 to High(FCurves.Items[J].ArrayDX) do begin PY := Round(KY * (FCurves.Items[J].ArrayDY[I] - (scMinY - FMinYValue) - FMinYValue)); PX := Round(KX * (FCurves.Items[J].ArrayDX[I] - (scMinX - FMinXValue) - FMinXValue)); if Det then Rectangle(PX+MargX-Pr.X, BM.Height - PY - MargY-Pr.X, PX+MargX+Pr.Y, BM.Height - PY - MargY+Pr.Y); LineTo(PX +MargX, BM.Height - PY - MargY); end; end; end; Brush.Color := Color; end; Canvas.CopyRect(ClientRect, BM.Canvas, ClientRect); if SmPan <> nil then TNavigator(SmPan).UpdateWin(Curves, FMaxXValue, FMinXValue, FMaxYValue, FMinYValue, ScMaxX, ScMinX, ScMaxY, ScMinY, Scale > 100); BM.Free; end; { FindPointOnCurve } //Если Р (пиксельные координаты на компоненте) указывают точку на кривой //или находятся рядом с какой-то степенью приближения //(приближение управляется параметром Epsilon в фунции SameValue), //то в GP возвращается значение этой точки, а сама функция возвращает True; //Эта функция применяется в реализации отображения хинта (см. сообщение CMHintShow). //Реализовано так, что при движении мышки значения на кривой отображаются с помощью //хинта только тогда, когда курсор находится на кривой около точки. //Про Epsilon. Расширяет/уменьшает интервал значений, в котором ищется точка. //Например. Координата Х точки кривой имеет значение "28". //Указатель мыши находится на том месте графика, которое соответствует //значению Х точки на графике "26". Значение интервала поиска (Epsilon) "3". //Отсюда, диапазон поиска = 26±3 (23...29). Точка с координатой Х="28" будет найдена. //В функции делители (Width div 2) подобраны экспериментально. Чем больше делитель, //тем чувствительнее метод нахождения нужной точки (меньший интервал поиска), //но ловля точки мышкой затрудняется. //И наоборот, при меньшей чувствительность (большем интервале поиска) из близко //лежащих точек одна может никогда не показываться, //но хинт появляется при большем расстоянии курсора от точки. function TGraphMois.FindPointOnCurve(P : TPoint; var Ind : Integer; var GP : TGraphPoint) : Boolean; var G : TGraphPoint; I, J : Integer; EpX, EpY : Double; begin Result := False; Ind := 0; G := GetGraphPointByPoint(P); EpX := (scMaxX - scMinX) / (Width div 2); EpY := (scMaxY - scMinY) / (Height div 6); for J := 0 to FCurves.Count - 1 do begin if Length(FCurves.Items[J].ArrayDX) <=1 then continue; for I := 0 to High(FCurves.Items[J].ArrayDX) do If SameValue(FCurves.Items[J].ArrayDX[I], G.X, EpX) then If SameValue(FCurves.Items[J].ArrayDY[I], G.Y, EpY) then begin GP.X := FCurves.Items[J].ArrayDX[I]; GP.Y := FCurves.Items[J].ArrayDY[I]; Ind := I; Result := True; break; end; end; end; function TGraphMois.GetCurveClass: TCurveClass; begin Result := TCurve; end; function TGraphMois.GetGraphPointByPoint(P: TPoint): TGraphPoint; var DpVX, DpVY : Double; RX, RY : TRect; begin LenY := Height - MargY - 8; //8 - top DpVY := (LenY * SclK) / (FMaxYValue - FMinYValue); //dots per value // RY := _RectText(Canvas, FPrecision, scMinY, scMaxY); // RX := _RectText(Canvas, FPrecision, scMinX, scMaxX); RX := RTextX; RY := RTextY; MargX := RY.Right+8; LenX := Width - MargX - RX.Right div 2 - 3; //3 - right DpVX := (LenX * SclK) / (FMaxXValue - FMinXValue); if P.X = -1 then P := Point(LenX div 2 + MargX, Height - MargY - LenY div 2); Result.X := ((P.X - MargX) + (scMinX - FMinXValue) * DpVX) / DpVX + FMinXValue; Result.Y := ((Height - MargY - P.Y) + (scMinY - FMinYValue) * DpVY) / DpVY + FMinYValue; end; function TGraphMois.GetPrecisionForShow(Step: Double): ShortInt; begin Result := 0; if (Step > -0.01) and (Step < 0.01) then begin Result := 3; Exit; end; if (Step > -0.1) and (Step < 0.1) then begin Result := 2; Exit; end; if (Step > -1) and (Step < 1) then begin Result := 1; Exit; end; end; function TGraphMois.IsCurves: Boolean; var I : Integer; begin Result := False; for I := 0 to Curves.Count-1 do if Length(Curves[I].ArrayDX) > 1 then begin Result := True; Exit; end; end; procedure TGraphMois.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; case Key of VK_ADD : begin PHit := Point(-1, 0); Scale := Scale + StepScale; end; VK_SUBTRACT : if Scale > 100 then begin PHit := Point(-1, 0); Scale := Scale - StepScale; end; VK_MULTIPLY : Scale := 100; VK_LEFT : if Scale > 100 then begin PHit := Point((Width-MargX) div 2 + MargX, (Height-MargY) div 2); if ssCtrl in Shift then ShiftGraph(Point(PHit.X - (Width-MargX-10), PHit.Y)) else ShiftGraph(Point(PHit.X - 10, PHit.Y)); end; VK_RIGHT : if Scale > 100 then begin PHit := Point((Width-MargX) div 2 + MargX, (Height-MargY) div 2); if ssCtrl in Shift then ShiftGraph(Point(PHit.X + (Width-MargX-10), PHit.Y)) else ShiftGraph(Point(PHit.X + 10, PHit.Y)); end; VK_UP : if Scale > 100 then begin PHit := Point((Width-MargX) div 2 + MargX, (Height-MargY) div 2); if ssCtrl in Shift then ShiftGraph(Point(PHit.X, PHit.Y - (Height-MargY-8))) else ShiftGraph(Point(PHit.X, PHit.Y - 10)); end; VK_DOWN : if Scale > 100 then begin PHit := Point((Width-MargX) div 2 + MargX, (Height-MargY) div 2); if ssCtrl in Shift then ShiftGraph(Point(PHit.X, PHit.Y + (Height-MargY-8))) else ShiftGraph(Point(PHit.X, PHit.Y + 10)); end; end; end; procedure TGraphMois.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if (csDesigning in ComponentState) or not IsCurves then Exit; PHit := Point(X, Y); if Button = mbLeft then isMDown := True; //странная такая фигня: на сколько допускаем вылезание графика за пределы значений по всем //сторонам при масштабировании и панорамировании - здесь 1% от диапазона значений по осям // KfZaX := (FMaxXValue - FMinXValue) * 0.01; // KfZaY := (FMaxYValue - FMinYValue) * 0.01; //не применяется, т.к. если применять, но надо корректировать и другие параметры end; procedure TGraphMois.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited MouseMove(Shift, X, Y); if csDesigning in ComponentState then Exit; if Shift = [] then Exit; if isMDown and (Scale > 100) and ((X <> PHit.X) or (Y <> PHit.Y)) then begin IsMMove := True; ShiftGraph(Point(X, Y)); end; end; procedure TGraphMois.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseUp(Button, Shift, X, Y); if not Focused and CanFocus then begin SetFocus; Exit; end; if (csDesigning in ComponentState) or not IsCurves then Exit; if IsMMove then begin IsMMove := False; IsMDown := False; Exit; end; IsMDown := False; PHit := Point(X, Y); if Button = mbLeft then Scale := Scale + StepScale else if Button = mbRight then Scale := Scale - StepScale; if Button = mbMiddle then Scale := 100; end; procedure TGraphMois.Paint; begin inherited; DoPaint(nil); end; procedure TGraphMois.ScaleChange(Source: TObject; NewScale: Integer); begin if Assigned(FOnScaleChange) then FOnScaleChange(Self, NewScale); end; procedure TGraphMois.SetColor(const Value: TColor); begin FColor := Value; Invalidate; end; procedure TGraphMois.SetColorAxis(const Value: TColor); begin if FColorAxis = Value then Exit; FColorAxis := Value; Invalidate; end; procedure TGraphMois.SetColorGrid(const Value: TColor); begin if FColorGrid = Value then Exit; FColorGrid := Value; Invalidate; end; procedure TGraphMois.SetCurves(const Value: TCurves); begin FCurves.Assign(Value); end; procedure TGraphMois.SetDecimalHint(const Value: ShortInt); begin if (Value < 0) or (Value > 6) then Exit; FDecimalHint := Value; end; procedure TGraphMois.SetDetails(const Value: Boolean); begin if FDetails = Value then Exit; FDetails := Value; Invalidate; end; procedure TGraphMois.SetGridX(const Value: Boolean); begin if FGridX = Value then Exit; FGridX := Value; Invalidate; end; procedure TGraphMois.SetGridY(const Value: Boolean); begin if FGridY = Value then Exit; FGridY := Value; Invalidate; end; procedure TGraphMois.SetMaxXValue(const Value: Double); begin if FMaxXValue = Value then Exit; FMaxXValue := Value; if Value <= 0 then begin FMaxXValue := 0.0; end; Invalidate end; procedure TGraphMois.SetMaxYValue(const Value: Double); begin if FMaxYValue = Value then Exit; FMaxYValue := Value; if Value < 0 then begin FMaxYValue := 0; end; Invalidate; end; procedure TGraphMois.SetMinXValue(const Value: Double); begin if FMinXValue = Value then Exit; FMinXValue := Value; Invalidate; end; procedure TGraphMois.SetMinYValue(const Value: Double); begin if FMinYValue = Value then Exit; FMinYValue := Value; Invalidate; end; procedure TGraphMois.SetNavigator(const Value: Boolean); begin if FNavigator = Value then Exit; FNavigator := Value; if SmPan = nil then begin SmPan := TNavigator.Create(Self); SmPan.Visible := FALSE; SmPan.ClientWidth := Width div 4; SmPan.ClientHeight := Height div 4; SmPan.Left := ClientToScreen(BoundsRect.TopLeft).X - BoundsRect.Left + Width-SmPan.Width; SmPan.Top := ClientToScreen(BoundsRect.BottomRight).Y - BoundsRect.Top - SmPan.Height; end; if FNavigator then begin TNavigator(SmPan).UpdateWin(Curves, FMaxXValue, FMinXValue, FMaxYValue, FMinYValue, ScMaxX, ScMinX, ScMaxY, ScMinY, Scale > 100); ShowWindow(SmPan.Handle, SW_SHOWNA) end else ShowWindow(SmPan.Handle, SW_HIDE); end; procedure TGraphMois.SetPrecision(const Value: ShortInt); begin if FPrecision = Value then Exit; FPrecision := Value; if (Value < 0) or (Value > 3) then FPrecision := 1; Invalidate; end; procedure TGraphMois.SetScale(const Value: Integer); var KK : Double; GP : TGraphPoint; begin if FScale = Value then Exit; GP := GetGraphPointByPoint(PHit); FScale := Value; if FScale < 100 then FScale := 100; SclK := FScale / 100; KK := (FMaxXValue - FMinXValue) / SclK; //ширина scMinX := GP.X - KK / 2; scMaxX := GP.X + KK / 2; KK := scMaxX - scMinX; if scMinX < FMinXValue{-KfZaX} then begin //корректировка, чтобы график не вылезал scMinX := FMinXValue{-KfZaX}; scMaxX := scMinX + KK; end; if scMaxX > FMaxXValue{+KfZaX} then begin scMaxX := FMaxXValue{+KfZaX}; scMinX := scMaxX - KK; end; KK := (FMaxYValue - FMinYValue) / SclK; //высота scMinY := GP.Y - KK / 2; scMaxY := GP.Y + KK / 2; KK := scMaxY - scMinY; if scMinY < FMinYValue{-KfZaY} then begin scMinY := FMinYValue{-KfZaY}; scMaxY := scMinY + KK; end; if scMaxY > FMaxYValue{+KfZaY} then begin scMaxY := FMaxYValue{+KfZaY}; scMinY := scMaxY - KK; end; ScaleChange(Self, Scale); Invalidate; end; procedure TGraphMois.SetShowTextScale(const Value: Boolean); begin if FShowTextScale = Value then Exit; FShowTextScale := Value; Invalidate; end; procedure TGraphMois.SetStepScale(const Value: Integer); begin if FStepScale = Value then Exit; FStepScale := Value; if FStepScale <= 0 then FStepScale := 100; if FScale > 100 then Invalidate; end; procedure TGraphMois.ShiftFromNavigator(scX, scY: Double); var IntX, IntY : Double; begin IntX := scMaxX - scMinX; IntY := scMaxY - scMinY; scMinX := scX; scMaxX := scMinX + IntX; scMaxY := scY; scMinY := scMaxY - IntY; Invalidate; end; procedure TGraphMois.ShiftGraph(NewP: TPoint); var KK : Double; GP, GP2 : TGraphPoint; begin GP := GetGraphPointByPoint(PHit); GP2 := GetGraphPointByPoint(NewP); KK := scMaxX - scMinX; scMinX := scMinX + (GP.X - GP2.X); scMaxX := scMaxX + (GP.X - GP2.X); if scMinX < FMinXValue{-KfZaX} then begin scMinX := FMinXValue{-KfZaX}; scMaxX := scMinX + KK; end; if scMaxX > FMaxXValue{+KfZaX} then begin scMaxX := FMaxXValue{+KfZaX}; scMinX := scMaxX - KK; end; KK := scMaxY - scMinY; scMinY := scMinY + (GP.Y - GP2.Y); scMaxY := scMaxY + (GP.Y - GP2.Y); if scMinY < FMinYValue{-KfZaY} then begin scMinY := FMinYValue{-KfZaY}; scMaxY := scMinY + KK; end; if scMaxY > FMaxYValue{+KfZaY} then begin scMaxY := FMaxYValue{+KfZaY}; scMinY := scMaxY - KK; end; PHit := NewP; Invalidate; end; procedure TGraphMois.WMGetDlgCode(var Message: TMessage); begin Message.Result := DLGC_WANTARROWS; end; procedure TGraphMois.WMKillFocus(var Message: TWMSetFocus); begin inherited; Invalidate; end; procedure TGraphMois.WMMouseWheel(var Message: TWMMouseWheel); var D : Integer; begin if not IsCurves then Exit; D := Message.WheelDelta; PHit := ScreenToClient(Point(Message.XPos, Message.YPos)); IsMDown := False; if D < 0 then Scale := Scale + StepScale div 2 else Scale := Scale - StepScale div 2; end; procedure TGraphMois.WMSetFocus(var Message: TWMSetFocus); begin inherited; Invalidate; end; { TCurves } function TCurves.Add: TCurve; begin Result := TCurve(inherited Add); end; constructor TCurves.Create(Graphic: TGraphMois); begin if Graphic <> nil then inherited Create(Graphic.GetCurveClass) else inherited Create(TCurve); FGraphic := Graphic; end; function TCurves.GetItem(Index: Integer): TCurve; begin Result := TCurve(inherited GetItem(Index)); end; function TCurves.GetOwner: TPersistent; begin Result := FGraphic; end; procedure TCurves.SetItem(Index: Integer; const Value: TCurve); begin inherited SetItem(Index, Value); end; procedure TCurves.Update(Item: TCollectionItem); begin inherited; FGraphic.Invalidate; end; { TCurve } procedure TCurve.AddPoint(aX, aY: Double); begin SetLength(ArrayDX, Length(ArrayDX)+1); SetLength(ArrayDY, Length(ArrayDY)+1); ArrayDX[High(ArrayDX)] := aX; ArrayDY[High(ArrayDY)] := aY; TGraphMois(Collection.Owner).Invalidate; end; procedure TCurve.Assign(Source: TPersistent); begin if Source is TCurve then begin ColorGraph := TCurve(Source).ColorGraph; ThickLine := TCurve(Source).ThickLine; Details := TCurve(Source).Details; end else inherited Assign(Source); end; procedure TCurve.ClearPoints; begin ArrayDX := nil; ArrayDY := nil; TGraphMois(Collection.Owner).Invalidate; end; constructor TCurve.Create(Collection: TCollection); begin FThickLine := 1; FColorGraph := clBlack; inherited Create(Collection); end; destructor TCurve.Destroy; begin ArrayDX := nil; ArrayDY := nil; inherited; end; procedure TCurve.GetPoint(Index: Integer; var aX, aY: Double); begin aX := 0; aY := 0; if (Index > High(ArrayDX)) or (Index < 0) then Exit; aX := ArrayDX[Index]; aY := ArrayDY[Index]; end; function TCurve.GetLen: Integer; begin Result := High(ArrayDX); end; function TCurve.GetPoint(Index: Integer): TGraphPoint; begin Result.X := 0; Result.Y := 0; if (Index > High(ArrayDX)) or (Index < 0) then Exit; Result.X := ArrayDX[Index]; Result.Y := ArrayDY[Index]; end; procedure TCurve.SetColorGraph(const Value: TColor); begin if FColorGraph = Value then Exit; FColorGraph := Value; Changed(False); end; procedure TCurve.SetDetails(const Value: Boolean); begin if FDetails = Value then Exit; FDetails := Value; Changed(False); end; procedure TCurve.SetThickLine(const Value: Integer); begin if FThickLine = Value then Exit; FThickLine := Value; Changed(False); end; end.
unit ZMDrv19; (* ZMDrv19.pas - drive details Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TZipMaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip modified 2010-03-18 ---------------------------------------------------------------------------*) interface uses Classes, Windows; type //1 Provides details of drive TZMWorkDrive = class(TObject) private fDiskName: string; fDiskReadOnly: Boolean; fDiskSerial: cardinal; FDriveIsFloppy: Boolean; fDriveLetter: Char; fDriveStr: string; fDriveType: Integer; fLastDrive: string; fVolumeFreeClusters: DWORD; fVolumeSecSize: Cardinal; fVolumeSectorsPerCluster: DWORD; fVolumeSize: Int64; fVolumeSpace: Int64; fVolumeTotalClusters: DWORD; function GetDriveIsFixed: Boolean; procedure SetDrive(const path: string); procedure SetDriveStr(const Value: string); procedure SetExSizes(fields: Integer); public constructor Create; procedure AfterConstruction; override; procedure AssignFrom(const src: TZMWorkDrive); procedure Clear; function HasMedia(UnformOk: boolean): Boolean; function RenameDisk(const NewName: string): Boolean; procedure VolumeRefresh; property DiskName: string read fDiskName; property DiskReadOnly: Boolean read fDiskReadOnly; property DiskSerial: cardinal read fDiskSerial; property DriveIsFixed: Boolean read GetDriveIsFixed; property DriveIsFloppy: Boolean read FDriveIsFloppy; property DriveLetter: Char read fDriveLetter; property DriveStr: string read fDriveStr write SetDriveStr; property DriveType: Integer read fDriveType; property VolumeFreeClusters: DWORD read fVolumeFreeClusters; property VolumeSecSize: Cardinal read fVolumeSecSize; property VolumeSectorsPerCluster: DWORD read fVolumeSectorsPerCluster; property VolumeSize: Int64 read fVolumeSize; property VolumeSpace: Int64 read fVolumeSpace; property VolumeTotalClusters: DWORD read fVolumeTotalClusters; end; implementation uses SysUtils, ZMXcpt19, ZMMsg19; Const MAX_REMOVABLE = 10 * 1024 * 1024; constructor TZMWorkDrive.Create; begin inherited; end; procedure TZMWorkDrive.AfterConstruction; begin inherited; Clear; end; procedure TZMWorkDrive.AssignFrom(const src: TZMWorkDrive); begin if (self <> src) then begin fDiskName := src.DiskName; fDiskReadOnly := src.DiskReadOnly; fDiskSerial := src.DiskSerial; fDriveIsFloppy := src.DriveIsFloppy; fDriveLetter := src.DriveLetter; fDriveStr := src.DriveStr; fDriveType := src.DriveType; fVolumeFreeClusters := src.VolumeFreeClusters; fVolumeSecSize := src.VolumeSecSize; fVolumeSectorsPerCluster := src.VolumeSectorsPerCluster; fVolumeSize := src.VolumeSize; fVolumeSpace := src.VolumeSpace; fVolumeTotalClusters := src.VolumeTotalClusters; end; end; procedure TZMWorkDrive.Clear; begin fDiskName := ''; fLastDrive := ''; fDiskReadOnly := false; fDiskSerial := 0; fDriveIsFloppy := False; fDriveLetter := #0; fDriveStr := ''; fDriveType := 0; fVolumeSecSize := 512; fVolumeSectorsPerCluster := 4; fVolumeSize := 0; fVolumeSpace := 0; fVolumeTotalClusters := 0; end; function TZMWorkDrive.GetDriveIsFixed: Boolean; begin Result := not DriveIsFloppy; end; function TZMWorkDrive.HasMedia(UnformOk: boolean): Boolean; //const // _FILE_READ_ONLY_VOLUME = $00080000; var Bits: set of 0..25; err: cardinal; NamLen: Cardinal; Num: Integer; OldErrMode: DWord; SysFlags: DWord; SysLen: DWord; VolNameAry: array[0..255] of Char; begin NamLen := 255; SysLen := 255; fVolumeSize := 0; fVolumeSpace := 0; fDiskName := ''; fDiskSerial := 0; VolNameAry[0] := #0; Result := False; if DriveLetter <> #0 then // Only for local drives begin if (DriveLetter < 'A') or (DriveLetter > 'Z') then raise EZipMaster.CreateResStr( DS_NotaDrive, DriveStr); Integer(Bits) := GetLogicalDrives(); Num := Ord(DriveLetter) - Ord('A'); if not (Num in Bits) then raise EZipMaster.CreateResStr( DS_DriveNoMount, DriveStr); end; OldErrMode := SetErrorMode(SEM_FAILCRITICALERRORS); // Turn off critical errors: // Since v1.52c no exception will be raised here; moved to List() itself. // 1.72 only get Volume label for removable drives if (not GetVolumeInformation(Pchar(DriveStr), VolNameAry, NamLen, @fDiskSerial, SysLen, SysFlags, Nil, 0)) then begin // W'll get this if there is a disk but it is not or wrong formatted // so this disk can only be used when we also want formatting. err := GetLastError(); if (err = 31) and (UnformOk) then Result := True; end//; else begin fDiskName := VolNameAry; fDiskReadOnly := false; { get free disk space and size. } SetExSizes(7); // RCV150199 end; SetErrorMode(OldErrMode); // Restore critical errors: // -1 is not very likely to happen since GetVolumeInformation catches errors. // But on W95(+OSR1) and a UNC filename w'll get also -1, this would prevent // opening the file. !!!Potential error while using spanning with a UNC filename!!! if (DriveLetter = #0) or ((DriveLetter <> #0) and (VolumeSize <> -1)) then Result := True; end; function TZMWorkDrive.RenameDisk(const NewName: string): Boolean; begin Result := false; if DriveIsFloppy and HasMedia(false) and not DiskReadOnly and SetVolumeLabel(PChar(DriveStr), PChar(NewName)) then begin HasMedia(false); // get new name Result := True; end; end; procedure TZMWorkDrive.SetDrive(const path: string); var s: string; begin s := Uppercase(ExtractFileDrive(ExpandUNCFileName(path)) + '\'); if s <> fLastDrive then begin Clear; if (length(s) = 3) and (s[2] = ':') then begin // a local drive fDriveLetter := s[1]; fDriveType := GetDriveType(Pchar(s)); if DriveType = DRIVE_REMOVABLE then begin if (DriveLetter = 'A') or (DriveLetter = 'B') then fDriveIsFloppy := True; end; end else Clear; fLastDrive := s; fDriveStr := s; end; end; procedure TZMWorkDrive.SetDriveStr(const Value: string); begin if Value <> fDriveStr then SetDrive(Value); end; procedure TZMWorkDrive.SetExSizes(fields: Integer); var BytesPSector: DWORD; LDiskFree: Int64; LSizeOfDisk: Int64; SSize: cardinal; begin LDiskFree := -1; LSizeOfDisk := -1; SSize := 0; if GetDiskFreeSpace(Pchar(DriveStr), fVolumeSectorsPerCluster, BytesPSector, fVolumeFreeClusters, fVolumeTotalClusters) then begin SSize := BytesPSector; end; if not GetDiskFreeSpaceEx(Pchar(DriveStr), LDiskFree, LSizeOfDisk, Nil) then begin LDiskFree := -1; LSizeOfDisk := -1; if SSize <> 0 then begin LDiskFree := Int64(BytesPSector) * VolumeSectorsPerCluster * VolumeFreeClusters; LSizeOfDisk := Int64(BytesPSector) * VolumeSectorsPerCluster * VolumeTotalClusters; end; end; if (fields and 1) <> 0 then fVolumeSpace := LDiskFree; if (fields and 2) <> 0 then fVolumeSize := LSizeOfDisk; if (fields and 4) <> 0 then fVolumeSecSize := SSize; end; procedure TZMWorkDrive.VolumeRefresh; begin SetExSizes(7); end; end.
{ Version 1.0 - Author jasc2v8 at yahoo dot com This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org> } unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Dialogs, StdCtrls, ExtCtrls, //cipher_blowfish; cipher_xor; type { TForm1 } TForm1 = class(TForm) ButtonCrypt: TButton; ButtonClear: TButton; EditResult: TLabeledEdit; EditPassword: TLabeledEdit; EditKey: TLabeledEdit; procedure ButtonClearClick(Sender: TObject); procedure ButtonCryptClick(Sender: TObject); procedure FormCreate(Sender: TObject); private public end; const DS=DirectorySeparator; LE=LineEnding; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.ButtonCryptClick(Sender: TObject); begin if (EditPassword.Text='') or (EditKey.Text='') then begin EditResult.Text:='Enter password and key then press ENcode'; Exit; end; if ButtonCrypt.Caption='ENcode' then begin EditResult.Text:=EnCrypt(EditPassword.Text, EditKey.Text); ButtonCrypt.Caption:='DEcode'; end else begin EditResult.Text:=DeCrypt(EditResult.Text, EditKey.Text); ButtonCrypt.Caption:='ENcode'; end; end; procedure TForm1.ButtonClearClick(Sender: TObject); begin EditPassword.Clear; EditKey.Clear; EditResult.Clear; end; procedure TForm1.FormCreate(Sender: TObject); begin end; end.
unit umMainData; interface uses Generics.Collections, umTileData, ZConnection, ZDataset; type TAddTileProc<D> = procedure (aTileData : D) of object; TTilesDataList<D : TTileDataModel, constructor> = class private fTilesList : TObjectList<D>; ZConnectionDb: TZConnection; ZQueryTiles: TZQuery; fOnAddTile : TAddTileProc<D>; procedure setOnAddTile(aOnAddTile : TAddTileProc<D>); public constructor Create; destructor Destroy; override; procedure ConnectDb; procedure DisconnectDB; procedure DBLoadTiles; procedure DBInsertTile(aTileData : D); procedure DBDelTile(aTileData : D); property TilesList : TObjectList<D> read fTilesList; property OnAddTile : TAddTileProc<D> write setOnAddTile; end; implementation uses SysUtils, Forms, Windows, uvLogin, ZDbcIntfs; constructor TTilesDataList<D>.Create; begin inherited Create; fTilesList := TObjectList<D>.Create(true); end; destructor TTilesDataList<D>.Destroy; begin fTilesList.Free; inherited Destroy; end; procedure TTilesDataList<D>.ConnectDb; begin ZConnectionDb := TZConnection.Create(nil); fmLogin := TfmLogin.Create(nil); if fmLogin.ShowModal = id_ok then begin ZConnectionDb.HostName := fmLogin.edHostName.Text; ZConnectionDb.Database := fmLogin.edDatabase.Text; ZConnectionDb.User := fmLogin.edUser.Text; ZConnectionDb.Password := fmLogin.edPassword.Text; end else begin ZConnectionDb.HostName := '127.0.0.1'; ZConnectionDb.Database := 'tilesdb'; ZConnectionDb.User := 'root'; ZConnectionDb.Password := 'mysql'; end; fmLogin.Free; ZConnectionDb.Protocol := 'mysql-5'; ZConnectionDb.LibraryLocation := ExtractFilePath(Application.ExeName) + 'libmariadb.dll'; ZConnectionDb.TransactIsolationLevel := tiReadCommitted; ZConnectionDb.Connect; ZQueryTiles := TZQuery.Create(nil); ZQueryTiles.Connection := ZConnectionDb; end; procedure TTilesDataList<D>.DisconnectDB; begin try ZQueryTiles.Close; ZConnectionDb.Disconnect; except end; end; procedure TTilesDataList<D>.DBLoadTiles; var i, MaxNum : integer; curTileData : D; begin fTilesList.Clear; try try ZQueryTiles.Close; ZQueryTiles.sql.Clear; ZQueryTiles.sql.Append('select * from tile'); ZQueryTiles.open; MaxNum := ZQueryTiles.RecordCount; if MaxNum > 0 then begin ZQueryTiles.First; repeat curTileData := D.Create; curTileData.LoadFrom(ZQueryTiles); // fTilesList.Add(curTileData); if assigned(fOnAddTile) then fOnAddTile(curTileData); ZQueryTiles.Next; dec(MaxNum); until MaxNum = 0; end; except Application.MessageBox('Ошибка чтения из базы данных.', 'Внимание', mb_ok) ; //exit; end; finally ZQueryTiles.Close; end; end; procedure TTilesDataList<D>.DBInsertTile(aTileData : D); begin ZQueryTiles.Close; ZQueryTiles.sql.Clear; aTileData.PreapareInsertQry(ZQueryTiles); ZConnectionDb.StartTransaction; try ZQueryTiles.ExecSQL; ZConnectionDb.Commit; except ZConnectionDb.Rollback; raise; end; end; procedure TTilesDataList<D>.DBDelTile(aTileData : D); begin ZQueryTiles.Close; ZQueryTiles.sql.Clear; ZQueryTiles.sql.Append('delete from tile where id = :id'); ZQueryTiles.Params[0].AsInteger := aTileData.id; ZConnectionDb.StartTransaction; try ZQueryTiles.ExecSQL; ZConnectionDb.Commit; except ZConnectionDb.Rollback; raise; end; end; procedure TTilesDataList<D>.setOnAddTile(aOnAddTile : TAddTileProc<D>); begin fOnAddTile := aOnAddTile; end; end.
unit Unit2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, IniFiles; type TSelectWnd = class(TForm) ListBox: TListBox; OkBtn: TButton; ResolutionsCB: TComboBox; ResolutionsLbl: TLabel; CancelBtn: TButton; AutoCB: TCheckBox; procedure FormShow(Sender: TObject); procedure OkBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure AutoCBMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } public { Public declarations } end; var SelectWnd: TSelectWnd; implementation {$R *.dfm} procedure TSelectWnd.FormShow(Sender: TObject); var Window: HWND; Buff: array [0..127] of Char; Ini: TIniFile; begin Ini:=TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Setup.ini'); ResolutionsCB.Text:=Ini.ReadString('Main', 'Resolution', '1280x720'); Ini.Free; ListBox.Clear; Window:=GetWindow(Handle, GW_HWNDFIRST); while Window <> 0 do begin // Не показываем: if (Window <> Application.Handle) // Собственное окно and IsWindowVisible(Window) // Невидимые окна and (GetWindow(Window, GW_OWNER) = 0) // Дочерние окна and (GetWindowText(Window, Buff, SizeOf(Buff)) <> 0) then begin GetWindowText(Window, Buff, SizeOf(Buff)); ListBox.Items.Add(StrPas(Buff)); end; Window:=GetWindow(Window, GW_HWNDNEXT); end; ListBox.ItemIndex:=0; end; procedure TSelectWnd.OkBtnClick(Sender: TObject); var Wnd: HWND; WndWidth, WndHeight: integer; WndRect: TRect; MultiplyValue: integer; Ini: TIniFile; begin if ResolutionsCB.Text <> '1280x720' then begin Ini:=TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Setup.ini'); Ini.WriteString('Main', 'Resolution', ResolutionsCB.Text); Ini.Free; end; if ListBox.ItemIndex <> -1 then begin WND:=FindWindow(nil, PChar(ListBox.Items[ListBox.ItemIndex])); if WND <> 0 then begin if AutoCB.Checked = false then begin if ResolutionsCB.Text[1] = 'x' then begin //Multiply value MultiplyValue:=StrToIntDef(Copy(ResolutionsCB.Text, 1, Length(ResolutionsCB.Text)), 1); Windows.GetClientRect(Wnd, WndRect); WndWidth:=WndRect.Right * MultiplyValue; WndHeight:=WndRect.Bottom * MultiplyValue; end else begin //Statis resolutions WndWidth:=StrToIntDef(Copy(ResolutionsCB.Text, 1, Pos('x', ResolutionsCB.Text) - 1), 640); WndHeight:=StrToIntDef(Copy(ResolutionsCB.Text, Pos('x', ResolutionsCB.Text) + 1, Length(ResolutionsCB.Text)), 480); end; end else begin Windows.GetClientRect(Wnd, WndRect); WndWidth:=WndRect.Right; WndHeight:=WndRect.Bottom; end; //MessageBox(Handle, PChar(IntToStr(WndWidth) + ' ' + IntToStr(WndHeight) + ' ' + IntToStr(MultiplyValue)), '', 0); SetWindowLong(Wnd, GWL_STYLE, GetWindowLong(Wnd, GWL_STYLE) and not WS_BORDER and not WS_SIZEBOX and not WS_DLGFRAME); SetWindowPos(Wnd, HWND_TOP, Screen.Width div 2 - WndWidth div 2, Screen.Height div 2 - WndHeight div 2, WndWidth, WndHeight, SWP_FRAMECHANGED); SetForegroundWindow(Wnd); end; Close; end; end; procedure TSelectWnd.FormCreate(Sender: TObject); begin if FileExists(ExtractFilePath(ParamStr(0)) + 'Resolutions.txt') then ResolutionsCB.Items.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'Resolutions.txt'); end; procedure TSelectWnd.CancelBtnClick(Sender: TObject); begin Close; end; procedure TSelectWnd.AutoCBMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ResolutionsCB.Enabled:=AutoCB.Checked; end; end.
unit CrimeProtocol; interface // Error codes const CRIME_NOERROR = 0; CRIME_ERROR_Unknown = 1; CRIME_ERROR_GetCriminals = 2; CRIME_ERROR_GetCityList = 3; CRIME_ERROR_WrongLeaderName = 4; CRIME_ERROR_WrongTeamName = 5; CRIME_ERROR_WrongCriminalName = 6; CRIME_ERROR_MaxReached = 7; type TTargetType = (ttpCoordinates, ttpRoad, ttpCriminal, ttpTeam, ttpPlayer, ttpLeader, ttpCity, ttpFacility, ttpCompany, ttpFacilitiesFromPlayer, ttpFacilitiesFromPlayerInRadius, ttpFacilitiesFromCompany, ttpFacilitiesFromCompanyInRadius, ttpFacilitiesInRadius); TCriminalState = (tcsNoState, tcsOnTheMarket, tcsOnTheMarketHidden, tcsInTeamStandBy, tcsInTeamTraining, tcsInTeamInMission, tcsInTeamInMissionDead, tcsInJail, tcsHiddenByPolice, tcsInTeamDead, tcsInTeamInJail); implementation end.
{$I ACBr.inc} unit pciotViagens; interface uses SysUtils, Classes, pcnAuxiliar, pcnConversao, pcnLeitor, pcnGerador, pciotCIOT; type TGeradorOpcoes = class; TViagensR = class(TPersistent) private FLeitor: TLeitor; FSucesso: Boolean; FMensagem: String; FQTPagamentos: integer; FDocumentos: TStrings; FPagamentos: TStrings; FQTDocumentos: integer; public constructor Create; destructor Destroy; override; function LerXml: boolean; property Sucesso: Boolean read FSucesso write FSucesso; property Mensagem: String read FMensagem write FMensagem; property QTDocumentos: integer read FQTDocumentos write FQTDocumentos; property Documentos: TStrings read FDocumentos write FDocumentos; property QTPagamentos: integer read FQTPagamentos write FQTPagamentos; property Pagamentos: TStrings read FPagamentos write FPagamentos; published property Leitor: TLeitor read FLeitor write FLeitor; end; TViagensW = class(TPersistent) private FGerador: TGerador; FOperacaoTransporte: TOperacaoTransporte; FOpcoes: TGeradorOpcoes; public constructor Create(AOwner: TOperacaoTransporte); destructor Destroy; override; function GerarXML: boolean; published property Gerador: TGerador read FGerador write FGerador; property OperacaoTransporte: TOperacaoTransporte read FOperacaoTransporte write FOperacaoTransporte; property Opcoes: TGeradorOpcoes read FOpcoes write FOpcoes; end; TGeradorOpcoes = class(TPersistent) private FAjustarTagNro: boolean; FNormatizarMunicipios: boolean; FGerarTagAssinatura: TpcnTagAssinatura; FPathArquivoMunicipios: string; FValidarInscricoes: boolean; FValidarListaServicos: boolean; published property AjustarTagNro: boolean read FAjustarTagNro write FAjustarTagNro; property NormatizarMunicipios: boolean read FNormatizarMunicipios write FNormatizarMunicipios; property GerarTagAssinatura: TpcnTagAssinatura read FGerarTagAssinatura write FGerarTagAssinatura; property PathArquivoMunicipios: string read FPathArquivoMunicipios write FPathArquivoMunicipios; property ValidarInscricoes: boolean read FValidarInscricoes write FValidarInscricoes; property ValidarListaServicos: boolean read FValidarListaServicos write FValidarListaServicos; end; implementation { TViagensW } uses ACBrCIOT; constructor TViagensW.Create(AOwner: TOperacaoTransporte); begin FOperacaoTransporte := AOwner; FGerador := TGerador.Create; FGerador.FIgnorarTagNivel := '|?xml version|CTe xmlns|infCTe versao|obsCont|obsFisco|'; FOpcoes := TGeradorOpcoes.Create; FOpcoes.FAjustarTagNro := True; FOpcoes.FNormatizarMunicipios := False; FOpcoes.FGerarTagAssinatura := taSomenteSeAssinada; FOpcoes.FValidarInscricoes := False; FOpcoes.FValidarListaServicos := False; end; destructor TViagensW.Destroy; begin FGerador.Free; FOpcoes.Free; inherited Destroy; end; function TViagensW.GerarXML: boolean; var chave: AnsiString; Gerar: boolean; xProtCTe : String; I, J: integer; begin Gerador.Opcoes.IdentarXML := True; Gerador.Opcoes.TagVaziaNoFormatoResumido := False; Gerador.ArquivoFormatoXML := ''; Gerador.wGrupo('AdicionarViagemRequest ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'HP01'); Gerador.wCampo(tcStr, 'HP02', 'NaoAdicionarParcialmente', 001, 001, 1, LowerCase(BoolToStr(false, false)), '');//NaoAdicionarParcialmente //E HP01 B 0-1 - - Indica se deseja ou não adicionar viagens / pagamentos de forma parcial. true: Caso um pagamento da requisição seja encontrado na base, nada é adicionado. False: A adição dos dados é incremental, se algum dos //pagamentos da requisição não estiver presente na base ele é gravado, o pagamento que já estiver gravado não. Se a viagem já estiver gravada //nenhum dos pagamentos informados na requisição é adicionado, para adicionar apenas pagamentos consultar o método AdicionarPagamento. Gerador.wCampo(tcStr, 'HP03', 'CodigoIdentificacaoOperacao', 001, 001, 1, FOperacaoTransporte.NumeroCIOT, ''); Gerador.wCampo(tcStr, 'HP04', 'Integrador', 001, 001, 1, TACBrCIOT( FOperacaoTransporte.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'HP06', 'Versao', 001, 001, 1, 2, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('Viagens ' + NAME_SPACE_EFRETE_PEFADICIONAR_OBJECTS, 'HP07'); for I := 0 to FOperacaoTransporte.Viagens.Count -1 do begin with FOperacaoTransporte.Viagens.Items[I] do begin Gerador.wCampo(tcInt, 'HP08', 'CodigoMunicipioDestino', 001, 007, 1, CodigoMunicipioDestino); Gerador.wCampo(tcInt, 'HP09', 'CodigoMunicipioOrigem', 001, 007, 1, CodigoMunicipioOrigem); Gerador.wCampo(tcStr, 'HP10', 'DocumentoViagem', 001, 001, 1, DocumentoViagem, 'Exemplo: CT-e / Serie, CTRC / Serie, Ordem de Serviço.'); Gerador.wGrupo('NotasFiscais', 'HP11'); for J := 0 to NotasFiscais.Count -1 do begin with NotasFiscais.Items[J] do begin Gerador.wGrupo('NotaFiscal'); Gerador.wCampo(tcInt, 'HP12', 'CodigoNCMNaturezaCarga', 001, 004, 1, CodigoNCMNaturezaCarga); Gerador.wCampo(tcDat, 'HP13', 'Data', 001, 004, 1, Data); Gerador.wCampo(tcStr, 'HP14', 'DescricaoDaMercadoria', 001, 060, 1, DescricaoDaMercadoria, 'Descrição adicional ao código NCM.'); Gerador.wCampo(tcStr, 'HP15', 'Numero', 001, 010, 1, Numero); Gerador.wCampo(tcDe3, 'HP16', 'QuantidadeDaMercadoriaNoEmbarque', 001, 010, 1, QuantidadeDaMercadoriaNoEmbarque); Gerador.wCampo(tcStr, 'HP17', 'Serie', 001, 001, 1, Serie); Gerador.wCampo(tcStr, 'HP18', 'TipoDeCalculo', 001, 001, 1, TpVgTipoCalculoToStr(TipoDeCalculo)); Gerador.wGrupo('ToleranciaDePerdaDeMercadoria', 'HP19'); Gerador.wCampo(tcStr, 'HP20', 'Tipo', 001, 001, 1, TpProporcaoToStr(ToleranciaDePerdaDeMercadoria.Tipo)); Gerador.wCampo(tcDe2, 'HP21', 'Valor', 001, 001, 1, ToleranciaDePerdaDeMercadoria.Valor); Gerador.wGrupo('/ToleranciaDePerdaDeMercadoria'); // if DiferencaDeFrete.Tipo <> SemDiferenca then // begin // Gerador.wGrupo('DiferencaDeFrete', 'AP147'); // Gerador.wCampo(tcStr, 'AP148', 'Tipo', 001, 001, 1, TpDifFreteToStr(DiferencaDeFrete.Tipo)); // Gerador.wCampo(tcStr, 'AP149', 'Base', 001, 001, 1, TpDiferencaFreteBCToStr(DiferencaDeFrete.Base)); // Gerador.wGrupo('Tolerancia', 'AP150'); // Gerador.wCampo(tcStr, 'AP151', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.Tolerancia.Tipo)); // Gerador.wCampo(tcDe2, 'AP152', 'Valor', 001, 001, 1, DiferencaDeFrete.Tolerancia.Valor); // Gerador.wGrupo('/Tolerancia'); // Gerador.wGrupo('MargemGanho', 'AP153'); // Gerador.wCampo(tcStr, 'AP154', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.MargemGanho.Tipo)); // Gerador.wCampo(tcDe2, 'AP155', 'Valor', 001, 001, 1, DiferencaDeFrete.MargemGanho.Valor); // Gerador.wGrupo('/MargemGanho'); // Gerador.wGrupo('MargemPerda', 'AP156'); // Gerador.wCampo(tcStr, 'AP157', 'Tipo', 001, 001, 1, TpProporcaoToStr(DiferencaDeFrete.MargemPerda.Tipo)); // Gerador.wCampo(tcDe2, 'AP158', 'Valor', 001, 001, 1, DiferencaDeFrete.MargemPerda.Valor); // Gerador.wGrupo('/MargemPerda'); // Gerador.wGrupo('/DiferencaDeFrete'); // end; Gerador.wCampo(tcStr, 'HP22', 'UnidadeDeMedidaDaMercadoria', 001, 001, 1, TpUnMedMercToStr(UnidadeDeMedidaDaMercadoria)); Gerador.wCampo(tcDe2, 'HP23', 'ValorDaMercadoriaPorUnidade', 001, 001, 1, ValorDaMercadoriaPorUnidade); Gerador.wCampo(tcDe2, 'HP24', 'ValorDoFretePorUnidadeDeMercadoria', 001, 001, 1, ValorDoFretePorUnidadeDeMercadoria); Gerador.wCampo(tcDe2, 'HP25', 'ValorTotal', 001, 001, 1, ValorTotal); Gerador.wGrupo('/NotaFiscal'); end; end; Gerador.wGrupo('/NotasFiscais'); Gerador.wGrupo('Valores ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'HP26'); with Valores do begin Gerador.wCampo(tcDe2, 'HP27', 'Combustivel', 001, 001, 1, Combustivel); Gerador.wCampo(tcStr, 'HP28', 'JustificativaOutrosCreditos', 001, 001, 1, JustificativaOutrosCreditos); Gerador.wCampo(tcStr, 'HP29', 'JustificativaOutrosDebitos', 001, 001, 1, JustificativaOutrosDebitos); Gerador.wCampo(tcDe2, 'HP30', 'OutrosCreditos', 001, 001, 1, OutrosCreditos); Gerador.wCampo(tcDe2, 'HP31', 'OutrosDebitos', 001, 001, 1, OutrosDebitos); Gerador.wCampo(tcDe2, 'HP32', 'Pedagio', 001, 001, 1, Pedagio); Gerador.wCampo(tcDe2, 'HP33', 'Seguro', 001, 001, 1, Seguro); Gerador.wCampo(tcDe2, 'HP34', 'TotalDeAdiantamento', 001, 001, 1, TotalDeAdiantamento); Gerador.wCampo(tcDe2, 'HP35', 'TotalDeQuitacao', 001, 001, 1, TotalDeQuitacao); Gerador.wCampo(tcDe2, 'HP36', 'TotalOperacao', 001, 001, 1, TotalOperacao); Gerador.wCampo(tcDe2, 'HP37', 'TotalViagem', 001, 001, 1, TotalViagem); end; Gerador.wGrupo('/Valores'); for I := 0 to Pagamentos.Count -1 do begin with Pagamentos.Items[I] do begin Gerador.wGrupo('Pagamentos ' + NAME_SPACE_EFRETE_PEFADICIONAR_OBJECTS, 'HP38'); //Pagamentos registrados. - Pode existir mais de 1 pagamento com uma mesma categoria (exceto para Quitacao). - A soma dos pagamentos c/ categoria Adiantamento, deverá ter o mesmo valor apontado na tag TotalAdiantamento da tag Viagem/Valores, e neste caso, a tag Documento do pagamento deverá conter o mesmo valor da tag DocumentoViagem da tag Viagem . - Se a viagem possuir a tag TotalQuitacao maior que zero, deverá ter um pagamento correspondente, com Categoria Quitacao e com o Documento o mesmo valor apontado na tag DocumentoViagem . Gerador.wCampo(tcStr, 'HP39', 'Categoria', 001, 001, 1, TpCatPagToStr(Categoria), 'Categoria relacionada ao pagamento realizado. Restrita aos membros da ENUM: -Adiantamento, -Estadia, Quitacao, -SemCategoria ', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcDat, 'HP40', 'DataDeLiberacao', 001, 001, 1, DataDeLiberacao); Gerador.wCampo(tcStr, 'HP41', 'Documento', 001, 020, 1, Documento, 'Documento relacionado a viagem.'); Gerador.wCampo(tcStr, 'HP42', 'IdPagamentoCliente', 001, 020, 1, IdPagamentoCliente, 'Identificador do pagamento no sistema do Cliente. '); Gerador.wCampo(tcStr, 'HP43', 'InformacaoAdicional', 001, 000, 0, InformacaoAdicional, ''); Gerador.wGrupo('InformacoesBancarias ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE, 'HP44'); with InformacoesBancarias do begin Gerador.wCampo(tcStr, 'HP45', 'Agencia', 001, 001, 1, Agencia); Gerador.wCampo(tcStr, 'HP46', 'Conta', 001, 001, 1, Conta); Gerador.wCampo(tcStr, 'HP47', 'InstituicaoBancaria', 001, 001, 1, InstituicaoBancaria); end; Gerador.wGrupo('/InformacoesBancarias'); Gerador.wCampo(tcStr, 'HP48', 'TipoPagamento', 001, 020, 1, TpPagamentoToStr(TipoPagamento), 'Tipo de pagamento que será usado pelo contratante. Restrito aos itens da enum: -TransferenciaBancaria -eFRETE', ' ' + NAME_SPACE_EFRETE_OPERACAOTRANSPORTE_EFRETE); Gerador.wCampo(tcDe2, 'HP49', 'Valor', 001, 020, 1, Valor, 'Valor do pagamento.'); Gerador.wGrupo('/Pagamentos'); end; end; end; end; Gerador.wGrupo('/Viagens'); Gerador.wGrupo('/AdicionarViagemRequest'); Result := (Gerador.ListaDeAlertas.Count = 0); end; { TViagensR } constructor TViagensR.Create; begin FLeitor := TLeitor.Create; FDocumentos := TStringList.Create; FPagamentos := TStringList.Create; end; destructor TViagensR.Destroy; begin FLeitor.Free; FDocumentos.Free; FPagamentos.Free; inherited Destroy; end; function TViagensR.LerXml: boolean; var ok: boolean; begin if Leitor.rExtrai(1, 'AdicionarViagemResult') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); FQTPagamentos := Leitor.rCampo(tcInt, 'QuantidadePagamentos'); FPagamentos.Text := Leitor.rCampo(tcStr, 'DocumentoPagamento'); FQTDocumentos := Leitor.rCampo(tcInt, 'QuantidadeViagem'); FDocumentos.Text := Leitor.rCampo(tcStr, 'DocumentoViagem'); end; Result := true; end; end.
unit evPersistentDataObject; // Модуль: "w:\common\components\gui\Garant\Everest\evPersistentDataObject.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevPersistentDataObject" MUID: (48F4732803C8) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3Memory , l3Interfaces , evdInterfaces , nevTools , nevBase , l3Core , l3IID , evDataObject ; type RevDataObject = class of TevDataObject; TevPersistentDataObject = class(Tl3MemoryStream, Il3DataObjectInfo, IevdDataObject, InevDataObjectPrim2) private f_TagStorageR: InevTagReader; f_TagStorageW: InevTagWriter; f_Formats: Tl3ClipboardFormats; f_SameFormat: Boolean; f_Format: Tl3ClipboardFormat; protected function DataObjectClass: RevDataObject; virtual; function Sharp: Boolean; virtual; function GetIsQuestionNeedBeforeFlush: Boolean; virtual; function DoStore(aFormat: TnevFormat; const aPool: IStream; const aFilters: InevTagGenerator; aFlags: TevdStoreFlags): Boolean; virtual; function pm_GetIsQuestionNeedBeforeFlush: Boolean; procedure Store(const aView: InevView; const G: InevTagGenerator; aFlags: TevdStoreFlags = evDefaultStoreFlags); overload; {* сохраняет выделение в G. } function Store(aFormat: TevdClipboardFormat; const aPool: IStream; const aFilters: TevdTagGenerator; aFlags: TevdStoreFlags = [evd_sfStoreParaEnd]): Boolean; overload; {* сохраняет выделение в формате aFormat в Pool, который должен реализовывать IStream. } function pm_GetBorders: TevPair; procedure Cleanup; override; {* Функция очистки полей объекта. } function COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; override; {* метод для реализации QueryInterface (Для перекрытия в потомках) } public constructor Create(const aBlock: IevdDataObject; anInternal: Boolean; aFormat: Tl3ClipboardFormat; const aTagStorageR: InevTagReader; const aTagStorageW: InevTagWriter; const aFormats: Tl3ClipboardFormats; const aFilters: InevTagGenerator); reintroduce; overload; constructor Create(aData: THandle; aFormat: Tl3ClipboardFormat; const aTagStorageR: InevTagReader; const aTagStorageW: InevTagWriter; const aFormats: Tl3ClipboardFormats); reintroduce; overload; class function Make(const aBlock: IevdDataObject; anInternal: Boolean; aFormat: Tl3ClipboardFormat; const aTagStorageR: InevTagReader; const aTagStorageW: InevTagWriter; const aFormats: Tl3ClipboardFormats; const aFilters: InevTagGenerator): InevDataObjectPrim2; reintroduce; overload; class function Make(aData: THandle; aFormat: Tl3ClipboardFormat; const aTagStorageR: InevTagReader; const aTagStorageW: InevTagWriter; const aFormats: Tl3ClipboardFormats): InevDataObjectPrim2; reintroduce; overload; protected property Format: Tl3ClipboardFormat read f_Format; end;//TevPersistentDataObject implementation uses l3ImplUses , k2InternalInterfaces , SysUtils , l3Base , l3Stream , Classes //#UC START# *48F4732803C8impl_uses* //#UC END# *48F4732803C8impl_uses* ; constructor TevPersistentDataObject.Create(const aBlock: IevdDataObject; anInternal: Boolean; aFormat: Tl3ClipboardFormat; const aTagStorageR: InevTagReader; const aTagStorageW: InevTagWriter; const aFormats: Tl3ClipboardFormats; const aFilters: InevTagGenerator); //#UC START# *48F475A20016_48F4732803C8_var* //#UC END# *48F475A20016_48F4732803C8_var* begin //#UC START# *48F475A20016_48F4732803C8_impl* inherited Make(Sharp); f_Format := aFormat; f_Formats := aFormats; f_TagStorageR := aTagStorageR; f_TagStorageW := aTagStorageW; if (aBlock <> nil) then if anInternal then aBlock.Store(f_Format, Self, aFilters, evDefaultStoreFlags + [evd_sfInternal]) else aBlock.Store(f_Format, Self, aFilters, evDefaultStoreFlags - [evd_sfInternal]); //#UC END# *48F475A20016_48F4732803C8_impl* end;//TevPersistentDataObject.Create constructor TevPersistentDataObject.Create(aData: THandle; aFormat: Tl3ClipboardFormat; const aTagStorageR: InevTagReader; const aTagStorageW: InevTagWriter; const aFormats: Tl3ClipboardFormats); //#UC START# *48F4764A01A0_48F4732803C8_var* //#UC END# *48F4764A01A0_48F4732803C8_var* begin //#UC START# *48F4764A01A0_48F4732803C8_impl* inherited Make(Sharp); f_Format := aFormat; f_Formats := aFormats; f_TagStorageR := aTagStorageR; f_TagStorageW := aTagStorageW; MemoryPool.AsHandle := aData; //#UC END# *48F4764A01A0_48F4732803C8_impl* end;//TevPersistentDataObject.Create class function TevPersistentDataObject.Make(const aBlock: IevdDataObject; anInternal: Boolean; aFormat: Tl3ClipboardFormat; const aTagStorageR: InevTagReader; const aTagStorageW: InevTagWriter; const aFormats: Tl3ClipboardFormats; const aFilters: InevTagGenerator): InevDataObjectPrim2; var l_Inst : TevPersistentDataObject; begin l_Inst := Create(aBlock, anInternal, aFormat, aTagStorageR, aTagStorageW, aFormats, aFilters); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TevPersistentDataObject.Make class function TevPersistentDataObject.Make(aData: THandle; aFormat: Tl3ClipboardFormat; const aTagStorageR: InevTagReader; const aTagStorageW: InevTagWriter; const aFormats: Tl3ClipboardFormats): InevDataObjectPrim2; var l_Inst : TevPersistentDataObject; begin l_Inst := Create(aData, aFormat, aTagStorageR, aTagStorageW, aFormats); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TevPersistentDataObject.Make function TevPersistentDataObject.DataObjectClass: RevDataObject; //#UC START# *48F4795901B5_48F4732803C8_var* //#UC END# *48F4795901B5_48F4732803C8_var* begin //#UC START# *48F4795901B5_48F4732803C8_impl* Result := TevDataObject; //#UC END# *48F4795901B5_48F4732803C8_impl* end;//TevPersistentDataObject.DataObjectClass function TevPersistentDataObject.Sharp: Boolean; //#UC START# *48F479680376_48F4732803C8_var* //#UC END# *48F479680376_48F4732803C8_var* begin //#UC START# *48F479680376_48F4732803C8_impl* Result := false; //#UC END# *48F479680376_48F4732803C8_impl* end;//TevPersistentDataObject.Sharp function TevPersistentDataObject.GetIsQuestionNeedBeforeFlush: Boolean; //#UC START# *48F4818300A5_48F4732803C8_var* //#UC END# *48F4818300A5_48F4732803C8_var* begin //#UC START# *48F4818300A5_48F4732803C8_impl* Result := (Size >= 512 * 1024); //#UC END# *48F4818300A5_48F4732803C8_impl* end;//TevPersistentDataObject.GetIsQuestionNeedBeforeFlush function TevPersistentDataObject.DoStore(aFormat: TnevFormat; const aPool: IStream; const aFilters: InevTagGenerator; aFlags: TevdStoreFlags): Boolean; //#UC START# *48F481B6035B_48F4732803C8_var* //#UC END# *48F481B6035B_48F4732803C8_var* begin //#UC START# *48F481B6035B_48F4732803C8_impl* f_SameFormat := (aFormat = f_Format); Result := (f_TagStorageR.ReadTag(aFormat, aPool, aFilters, Self, aFlags) > 0); //#UC END# *48F481B6035B_48F4732803C8_impl* end;//TevPersistentDataObject.DoStore function TevPersistentDataObject.pm_GetIsQuestionNeedBeforeFlush: Boolean; //#UC START# *4680FC190114_48F4732803C8get_var* //#UC END# *4680FC190114_48F4732803C8get_var* begin //#UC START# *4680FC190114_48F4732803C8get_impl* Result := GetIsQuestionNeedBeforeFlush; //#UC END# *4680FC190114_48F4732803C8get_impl* end;//TevPersistentDataObject.pm_GetIsQuestionNeedBeforeFlush procedure TevPersistentDataObject.Store(const aView: InevView; const G: InevTagGenerator; aFlags: TevdStoreFlags = evDefaultStoreFlags); {* сохраняет выделение в G. } //#UC START# *47C68BFD011C_48F4732803C8_var* var l_FilerSource : Ik2FilerSource; //#UC END# *47C68BFD011C_48F4732803C8_var* begin //#UC START# *47C68BFD011C_48F4732803C8_impl* Position := 0; if f_SameFormat AND Supports(G, Ik2FilerSource, l_FilerSource) then try with l_FilerSource.Filer do begin Seek(0, soBeginning); l3CopyStream(Self, Stream); end;//with l_FilerSource.Filer finally l_FilerSource := nil; end//try..finally else if (f_TagStorageW <> nil) then f_TagStorageW.WriteTag(aView, f_Format, Self, G, [ev_lfInternal]) //#UC END# *47C68BFD011C_48F4732803C8_impl* end;//TevPersistentDataObject.Store function TevPersistentDataObject.Store(aFormat: TevdClipboardFormat; const aPool: IStream; const aFilters: TevdTagGenerator; aFlags: TevdStoreFlags = [evd_sfStoreParaEnd]): Boolean; {* сохраняет выделение в формате aFormat в Pool, который должен реализовывать IStream. } //#UC START# *47C68C6701AF_48F4732803C8_var* //#UC END# *47C68C6701AF_48F4732803C8_var* begin //#UC START# *47C68C6701AF_48F4732803C8_impl* Result := DoStore(aFormat, aPool, aFilters, aFlags); //#UC END# *47C68C6701AF_48F4732803C8_impl* end;//TevPersistentDataObject.Store function TevPersistentDataObject.pm_GetBorders: TevPair; //#UC START# *47C6962E028E_48F4732803C8get_var* //#UC END# *47C6962E028E_48F4732803C8get_var* begin //#UC START# *47C6962E028E_48F4732803C8get_impl* Result.rStart := 0; Result.rFinish := Pred(High(Integer)); //#UC END# *47C6962E028E_48F4732803C8get_impl* end;//TevPersistentDataObject.pm_GetBorders procedure TevPersistentDataObject.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48F4732803C8_var* //#UC END# *479731C50290_48F4732803C8_var* begin //#UC START# *479731C50290_48F4732803C8_impl* f_TagStorageR := nil; f_TagStorageW := nil; f_Formats := nil; inherited; //#UC END# *479731C50290_48F4732803C8_impl* end;//TevPersistentDataObject.Cleanup function TevPersistentDataObject.COMQueryInterface(const IID: Tl3GUID; out Obj): Tl3HResult; {* метод для реализации QueryInterface (Для перекрытия в потомках) } //#UC START# *48F475350256_48F4732803C8_var* var l_DataObject : TevDataObject; //#UC END# *48F475350256_48F4732803C8_var* begin //#UC START# *48F475350256_48F4732803C8_impl* Result.SetOk; if IID.EQ(IDataObject) then begin l_DataObject := DataObjectClass.Create(Self, f_Formats, nil); try IDataObject(Obj) := l_DataObject; finally l3Free(l_DataObject); end;//try..finally end else if IID.EQ(InevTagReader) then InevTagReader(Obj) := f_TagStorageR else if IID.EQ(InevTagWriter) then InevTagWriter(Obj) := f_TagStorageW else Result := inherited COMQueryInterface(IID, Obj); //#UC END# *48F475350256_48F4732803C8_impl* end;//TevPersistentDataObject.COMQueryInterface end.
{9. Realizar un programa que lea un carácter, que puede ser “+” (suma) o “-” (resta); si se ingresa otro carácter, debe informar un error y finalizar. Una vez leído el carácter de suma o resta, deberá leerse una secuencia de números enteros que finaliza con 0. El programa deberá aplicar la operación leída con la secuencia de números, e imprimir el resultado final. Por ejemplo: ○ Si se leé el carácter “-” y la secuencia 4 3 5 -6 0 , deberá imprimir: 2 (4 – 3 – 5 - (-6) ) ○ Si se leé el carácter “+” y la secuencia -10 5 6 -1 0, deberá imprimir 0 ( -10 + 5 + 6 + (-1) )} program ejercicio9; var car: Char; numRamd, resultado: Integer; begin resultado:=0; write('Ingrese un caracter: '); readln(car); if ((car = '+') or (car = '-')) then begin write('ingrese un numero: '); readln(numRamd); while numRamd <> 0 do begin if car = '+' then begin resultado:= resultado + numRamd; end else if car = '-' then begin resultado:= resultado - numRamd; end; write('ingrese un numero: '); readln(numRamd); end; write('El resultado de la operacion es: ', resultado); end else writeln('El caracter que ingresos no es valido: '); readln(); end.
unit FavoritesCollection; interface uses Classes, RegFavorites; type TFavoritesCollectionItem = class (TCollectionItem) private FRegFavorite : TRegFavoritesFile; procedure SetRegFavorite(const Value: TRegFavoritesFile); public procedure Assign (aSource : TPersistent); override; published property RegFavorite : TRegFavoritesFile read FRegFavorite write SetRegFavorite; end; _COLLECTION_ITEM_ = TFavoritesCollectionItem; {$INCLUDE TemplateCollectionInterface} TFavoritesCollection = _COLLECTION_; implementation uses SysUtils; {$INCLUDE TemplateCollectionImplementation} procedure TFavoritesCollectionItem.Assign (aSource : TPersistent); begin if aSource is TFavoritesCollectionItem then begin RegFavorite.assign((aSource as TFavoritesCollectionItem).regfavorite); end else inherited; end; procedure TFavoritesCollectionItem.SetRegFavorite(const Value: TRegFavoritesFile); begin FRegFavorite := Value; end; end.
PROGRAM Prime(INPUT, OUTPUT); CONST Min = 2; Max = 100; VAR Sieve: SET OF Min .. Max; NextNumber, TotalNumber: INTEGER; BEGIN {Prime} Sieve := [Min .. Max]; NextNumber := Min; TotalNumber := Min; WRITE('Простые числа в диапазоне до ', Max, ' будут '); WHILE NextNumber <= Max DO BEGIN WHILE TotalNumber <= Max DO BEGIN Sieve := Sieve - [TotalNumber]; TotalNumber := TotalNumber + NextNumber END; WRITE(NextNumber, ' '); WHILE NOT(NextNumber IN Sieve) AND (NextNumber <= Max) DO NextNumber := NextNumber + 1; TotalNumber := NextNumber END; WRITELN END. {Prime}
{--------------------------------------------------------------------------- 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/NPL/NPL-1_1Final.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. The Original Code is: mwSimplePasParTypes, released November 14, 1999. The Initial Developer of the Original Code is Martin Waldenburg unit CastaliaPasLexTypes; ----------------------------------------------------------------------------} unit SimpleParser.Types; interface uses SysUtils, TypInfo; type TmwParseError = ( InvalidAdditiveOperator, InvalidAccessSpecifier, InvalidCharString, InvalidClassMethodHeading, InvalidConstantDeclaration, InvalidConstSection, InvalidDeclarationSection, InvalidDirective16Bit, InvalidDirectiveBinding, InvalidDirectiveCalling, InvalidExportedHeading, InvalidForStatement, InvalidInitializationSection, InvalidInterfaceDeclaration, InvalidInterfaceType, InvalidLabelId, InvalidLabeledStatement, InvalidMethodHeading, InvalidMultiplicativeOperator, InvalidNumber, InvalidOrdinalIdentifier, InvalidParameter, InvalidParseFile, InvalidProceduralDirective, InvalidProceduralType, InvalidProcedureDeclarationSection, InvalidProcedureMethodDeclaration, InvalidRealIdentifier, InvalidRelativeOperator, InvalidStorageSpecifier, InvalidStringIdentifier, InvalidStructuredType, InvalidTryStatement, InvalidTypeKind, InvalidVariantIdentifier, InvalidVarSection, vchInvalidClass, vchInvalidMethod, vchInvalidProcedure, vchInvalidCircuit, vchInvalidIncludeFile ); TmwPasCodeInfo = ( ciNone, ciAccessSpecifier, ciAdditiveOperator, ciArrayConstant, ciArrayType, ciAsmStatement, ciBlock, ciCaseLabel, ciCaseSelector, ciCaseStatement, ciCharString, ciClassClass, ciClassField, ciClassForward, ciClassFunctionHeading, ciClassHeritage, ciClassMemberList, ciClassMethodDirective, ciClassMethodHeading, ciClassMethodOrProperty, ciClassMethodResolution, ciClassProcedureHeading, ciClassProperty, ciClassReferenceType, ciClassType, ciClassTypeEnd, ciClassVisibility, ciCompoundStatement, ciConstantColon, ciConstantDeclaration, ciConstantEqual, ciConstantExpression, ciConstantName, ciConstantValue, ciConstantValueTyped, ciConstParameter, ciConstructorHeading, ciConstructorName, ciConstSection, ciContainsClause, ciContainsExpression, ciContainsIdentifier, ciContainsStatement, ciDeclarationSection, ciDesignator, ciDestructorHeading, ciDestructorName, ciDirective16Bit, ciDirectiveBinding, ciDirectiveCalling, ciDirectiveDeprecated, ciDirectiveLibrary, ciDirectiveLocal, ciDirectivePlatform, ciDirectiveVarargs, ciDispIDSpecifier, ciDispInterfaceForward, ciEmptyStatement, ciEnumeratedType, ciEnumeratedTypeItem, ciExceptBlock, ciExceptionBlockElseBranch, ciExceptionClassTypeIdentifier, ciExceptionHandler, ciExceptionHandlerList, ciExceptionIdentifier, ciExceptionVariable, ciExpliciteType, ciExportedHeading, ciExportsClause, ciExportsElement, ciExpression, ciExpressionList, ciExternalDirective, ciExternalDirectiveThree, ciExternalDirectiveTwo, ciFactor, ciFieldDeclaration, ciFieldList, ciFileType, ciFormalParameterList, ciFormalParameterSection, ciForStatement, ciForwardDeclaration, ciFunctionHeading, ciFunctionMethodDeclaration, ciFunctionMethodName, ciFunctionProcedureBlock, ciFunctionProcedureName, ciHandlePtCompDirect, ciHandlePtDefineDirect, ciHandlePtElseDirect, ciHandlePtIfDefDirect, ciHandlePtEndIfDirect, ciHandlePtIfNDefDirect, ciHandlePtIfOptDirect, ciHandlePtIncludeDirect, ciHandlePtResourceDirect, ciHandlePtUndefDirect, ciIdentifier, ciIdentifierList, ciIfStatement, ciImplementationSection, ciIncludeFile, ciIndexSpecifier, ciInheritedStatement, ciInitializationSection, ciInlineStatement, ciInterfaceDeclaration, ciInterfaceForward, ciInterfaceGUID, ciInterfaceHeritage, ciInterfaceMemberList, ciInterfaceSection, ciInterfaceType, ciLabelDeclarationSection, ciLabeledStatement, ciLabelId, ciLibraryFile, ciMainUsedUnitExpression, ciMainUsedUnitName, ciMainUsedUnitStatement, ciMainUsesClause, ciMultiplicativeOperator, ciNewFormalParameterType, ciNumber, ciNextToken, ciObjectConstructorHeading, ciObjectDestructorHeading, ciObjectField, ciObjectForward, ciObjectFunctionHeading, ciObjectHeritage, ciObjectMemberList, ciObjectMethodDirective, ciObjectMethodHeading, ciObjectNameOfMethod, ciObjectProcedureHeading, ciObjectProperty, ciObjectPropertySpecifiers, ciObjectType, ciObjectTypeEnd, ciObjectVisibility, ciOldFormalParameterType, ciOrdinalIdentifier, ciOrdinalType, ciOutParameter, ciPackageFile, ciParameterFormal, ciParameterName, ciParameterNameList, ciParseFile, ciPointerType, ciProceduralDirective, ciProceduralType, ciProcedureDeclarationSection, ciProcedureHeading, ciProcedureMethodDeclaration, ciProcedureMethodName, ciProgramBlock, ciProgramFile, ciPropertyDefault, ciPropertyInterface, ciPropertyName, ciPropertyParameterConst, ciPropertyParameterList, ciPropertySpecifiers, ciQualifiedIdentifier, ciQualifiedIdentifierList, ciRaiseStatement, ciReadAccessIdentifier, ciRealIdentifier, ciRealType, ciRecordConstant, ciRecordFieldConstant, ciRecordType, ciRecordVariant, ciRelativeOperator, ciRepeatStatement, ciRequiresClause, ciRequiresIdentifier, ciResolutionInterfaceName, ciResourceDeclaration, ciReturnType, ciSEMICOLON, ciSetConstructor, ciSetElement, ciSetType, ciSimpleExpression, ciSimpleStatement, ciSimpleType, ciSkipAnsiComment, ciSkipBorComment, ciSkipSlashesComment, ciSkipSpace, ciSkipCRLFco, ciSkipCRLF, ciStatement, ciStatementList, ciStorageExpression, ciStorageIdentifier, ciStorageDefault, ciStorageNoDefault, ciStorageSpecifier, ciStorageStored, ciStringIdentifier, ciStringStatement, ciStringType, ciStructuredType, ciSubrangeType, ciTagField, ciTagFieldName, ciTagFieldTypeName, ciTerm, ciTryStatement, ciTypedConstant, ciTypeDeclaration, ciTypeId, ciTypeKind, ciTypeName, ciTypeSection, ciUnitFile, ciUnitId, ciUsedUnitName, ciUsedUnitsList, ciUsesClause, ciVarAbsolute, ciVarEqual, ciVarDeclaration, ciVariable, ciVariableList, ciVariableReference, ciVariableTwo, ciVariantIdentifier, ciVariantSection, ciVarParameter, ciVarSection, ciVisibilityAutomated, ciVisibilityPrivate, ciVisibilityProtected, ciVisibilityPublic, ciVisibilityPublished, ciVisibilityUnknown, ciWhileStatement, ciWithStatement, ciWriteAccessIdentifier ); function ParserErrorName(Value: TmwParseError): string; implementation function ParserErrorName(Value: TmwParseError): string; begin result := GetEnumName(TypeInfo(TmwParseError), Integer(Value)); end; end.
unit BasicCurriculum; interface uses Kernel, BackupInterfaces, Languages; type TOpenItem = class( TCurriculumItem ) public constructor Create( anId : string; aKind : integer; aDesc : TMultiString; anImportance : integer; aPrestige : TPrestige ); private fDesc_MLS : TMultiString; fImportance : integer; fPrestige : TPrestige; protected function GetDesc( langId : TLanguageId ) : string; override; function GetImportance : integer; override; function GetPrestige : TPrestige; override; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; TOwnershipItem = class( TCurriculumItem ) protected function GetDesc( langId : TLanguageId ) : string; override; function GetImportance : integer; override; function GetPrestige : TPrestige; override; public class function IsGlobal : boolean; override; end; TResearchItem = class( TCurriculumItem ) protected function GetDesc( langId : TLanguageId ) : string; override; function GetImportance : integer; override; function GetPrestige : TPrestige; override; public class function IsGlobal : boolean; override; end; TCustomItem = class( TCurriculumItem ) public constructor Create(anId : string; aKind : integer; aPrestige : TPrestige; aMsg : string); private fMessage : string; fPrestige : TPrestige; protected function GetDesc(langId : TLanguageId) : string; override; function GetImportance : integer; override; function GetPrestige : TPrestige; override; procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; const currKind_Research = 2; procedure RegisterBackup; implementation uses SysUtils, SimHints, MathUtils; // TOpenItem constructor TOpenItem.Create( anId : string; aKind : integer; aDesc : TMultiString; anImportance : integer; aPrestige : TPrestige ); begin inherited Create( anId, aKind ); fDesc_MLS := aDesc; fImportance := anImportance; fPrestige := aPrestige; end; function TOpenItem.GetDesc( langId : TLanguageId ) : string; begin result := fDesc_MLS.Values[langId]; end; function TOpenItem.GetImportance : integer; begin result := fImportance; end; function TOpenItem.GetPrestige : TPrestige; begin result := fPrestige; end; procedure TOpenItem.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject( 'Desc_MLS', fDesc_MLS, nil ); if fDesc_MLS = nil then fDesc_MLS := TMultiString.Create; fImportance := Reader.ReadInteger( 'Importance', 0 ); fPrestige := Reader.ReadSingle( 'Prestige', 0 ); end; procedure TOpenItem.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteLooseObject( 'Desc_MLS', fDesc_MLS ); Writer.WriteInteger( 'Importance', fImportance ); Writer.WriteSingle( 'Prestige', fPrestige ); end; // TOwnershipItem function TOwnershipItem.GetDesc( langId : TLanguageId ) : string; var FacCount : integer; i : integer; begin FacCount := 0; try Tycoon.Companies.Lock; try for i := 0 to pred(Tycoon.Companies.Count) do inc( FacCount, TCompany(Tycoon.Companies[i]).Facilities.Count ); finally Tycoon.Companies.Unlock; end; result := SimHints.GetHintText(mtidOwnershipReport.Values[langId], [Tycoon.Companies.Count, FacCount, Tycoon.Area, FormatMoney(Tycoon.AreaTax)]); except result := ''; end; end; function TOwnershipItem.GetImportance : integer; begin result := 0; end; function TOwnershipItem.GetPrestige : TPrestige; begin result := Tycoon.FacPrestige; end; class function TOwnershipItem.IsGlobal : boolean; begin result := false; end; // TResearchItem function TResearchItem.GetDesc( langId : TLanguageId ) : string; begin try result := SimHints.GetHintText( mtidResearchReport.Values[langId], [Tycoon.ResearchCount] ); except result := ''; end; end; function TResearchItem.GetImportance : integer; begin result := 0; end; function TResearchItem.GetPrestige : TPrestige; begin result := Tycoon.ResearchPrest; end; class function TResearchItem.IsGlobal : boolean; begin result := false; end; // TCustomItem constructor TCustomItem.Create(anId : string; aKind : integer; aPrestige : TPrestige; aMsg : string); begin inherited Create(anId, aKind); fPrestige := aPrestige; fMessage := aMsg; end; function TCustomItem.GetDesc( langId : TLanguageId ) : string; begin result := Format(fMessage, [round(fPrestige)]); end; function TCustomItem.GetImportance : integer; begin result := inherited GetImportance; end; function TCustomItem.GetPrestige : TPrestige; begin result := fPrestige; end; procedure TCustomItem.LoadFromBackup( Reader : IBackupReader ); begin inherited; fPrestige := Reader.ReadSingle('Prestige', 0); fMessage := Reader.ReadString('Msg', ''); end; procedure TCustomItem.StoreToBackup ( Writer : IBackupWriter ); begin inherited; Writer.WriteSingle('Prestige', fPrestige); Writer.WriteString('Msg', fMessage); end; // RegisterBackup procedure RegisterBackup; begin RegisterClass( TOpenItem ); RegisterClass( TOwnershipItem ); RegisterClass( TResearchItem ); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 2/23/2005 6:34:28 PM JPMugaas New property for displaying permissions ina GUI column. Note that this should not be used like a CHMOD because permissions are different on different platforms - you have been warned. Rev 1.4 10/26/2004 9:46:34 PM JPMugaas Updated refs. Rev 1.3 4/19/2004 5:06:10 PM JPMugaas Class rework Kudzu wanted. Rev 1.2 2004.02.03 5:45:40 PM czhower Name changes Rev 1.1 10/19/2003 2:27:20 PM DSiders Added localization comments. Rev 1.0 4/7/2003 04:11:38 PM JPMugaas I mistakenly omitted the OS-9 parser when restructuring. Restored. } unit IdFTPListParseMicrowareOS9; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase,IdFTPListTypes; type TIdMicrowareOS9FTPListItem = class(TIdOwnerFTPListItem) protected FOS9OwnerPermissions : String; FOS9PublicPermissions : String; FOS9MiscPermissions : String; FOS9Sector: LongWord; public property OS9OwnerPermissions : String read FOS9OwnerPermissions write FOS9OwnerPermissions; property OS9PublicPermissions : String read FOS9PublicPermissions write FOS9PublicPermissions; property OS9MiscPermissions : String read FOS9MiscPermissions write FOS9MiscPermissions; property OS9Sector : LongWord read FOS9Sector write FOS9Sector; end; TIdFTPLPMicrowareOS9 = class(TIdFTPListBaseHeader) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsHeader(const AData: String): Boolean; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseMicrowareOS9"'*) implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings, SysUtils; const MICROWARE_OS9 = 'MicroWare OS-9'; {do not localize} { TIdFTPLPMicrowareOS9 } class function TIdFTPLPMicrowareOS9.GetIdent: String; begin Result := MICROWARE_OS9; end; class function TIdFTPLPMicrowareOS9.IsHeader(const AData: String): Boolean; var LWrds : TStrings; begin {The banner is usually something like this: Directory of . 11:44:44 Owner Last modified Attributes Sector Bytecount Name ––––––– ––––––––––––– –––––––––– –––––– ––––––––– –––– } LWrds := TStringList.Create; try Result := False; SplitColumns(AData, LWrds); if LWrds.Count > 2 then begin Result := (LWrds[0] = 'Directory') and (LWrds[1] = 'of') and {do not localize} (PatternsInStr(':', LWrds[LWrds.Count - 1]) = 2); if not Result then begin Result := (LWrds.Count = 7) and (LWrds[0] = 'Owner') and {do not localize} (LWrds[1] = 'Last') and {do not localize} (LWrds[2] = 'modified') and {do not localize} (LWrds[3] = 'Attributes') and {do not localize} (LWrds[4] = 'Sector') and {do not localize} (LWrds[5] = 'Bytecount') and {do not localize} (LWrds[6] = 'Name'); {do not localize} end; end; finally FreeAndNil(LWrds); end; end; class function TIdFTPLPMicrowareOS9.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdMicrowareOS9FTPListItem.Create(AOwner); end; class function TIdFTPLPMicrowareOS9.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuf : String; LPerms : String; LI : TIdMicrowareOS9FTPListItem; begin LI := AItem as TIdMicrowareOS9FTPListItem; LBuf := TrimLeft(LI.Data); //Owner LI.OwnerName := Fetch(LBuf); LBuf := TrimLeft(LBuf); //Modified date LI.ModifiedDate := DateYYMMDD(Fetch(LBuf)); LBuf := TrimLeft(LBuf); //not sure what this number is Fetch(LBuf); LBuf := TrimLeft(LBuf); //permissions LPerms := Fetch(LBuf); LBuf := TrimLeft(LBuf); if TextStartsWith(LPerms, 'd') then begin LI.ItemType := ditDirectory; end else begin LI.ItemType := ditFile; end; LI.PermissionDisplay := LPerms; LI.OS9MiscPermissions := Copy(LPerms, 1, 2); LI.OS9PublicPermissions := Copy(LPerms, 3, 3); LI.OS9OwnerPermissions := Copy(LPerms, 5, 3); //sector LI.OS9Sector := IndyStrToInt64('$'+Fetch(LBuf), 0); LBuf := TrimLeft(LBuf); //size not sure if in decimal or hexidecimal LI.Size := IndyStrToInt64(Fetch(LBuf), 0); //name LI.FileName := LBuf; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPMicrowareOS9); finalization UnRegisterFTPListParser(TIdFTPLPMicrowareOS9); end.
{ *************************************************************************** Copyright (c) 2016-2019 Kike Pérez Unit : Quick.MemoryCache.Compressor.LZO Description : Compress Cache data Author : Kike Pérez Version : 1.0 Created : 15/07/2019 Modified : 22/09/2019 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.MemoryCache.Compressor.LZO; {$i QuickLib.inc} interface uses Quick.MemoryCache.Types, Quick.Compression.LZO; type TCacheCompressorLZO = class(TInterfacedObject,ICacheCompressor) public function Compress(const aValue : string) : string; function Decompress(const aValue : string) : string; end; implementation { TCacheCompresorLZO } function TCacheCompressorLZO.Compress(const aValue: string): string; var lzo : TLZOCompressor; begin lzo := TLZOCompressor.Create; try Result := lzo.Compress(aValue); finally lzo.Free; end; end; function TCacheCompressorLZO.Decompress(const aValue: string): string; var lzo : TLZOCompressor; begin lzo := TLZOCompressor.Create; try Result := lzo.Decompress(aValue); finally lzo.Free; end; end; end.
unit CantoolsMemorySnap; (************************************************************** Cantools Memory Snap utility Instructions on Appendix A, Mastering Delphi 7 Released under LGPL license, distribute but keep this copyright notice. Please forward bug fixes and modifications to the author Copyright 1998-2003 Marco Cantý, www.marcocantu.com **************************************************************) // important notice: include this unit as first unit of your project interface var GetMemCount: Integer = 0; FreeMemCount: Integer = 0; ReallocMemCount: Integer = 0; duringSnap: boolean; // MarcoG function ObjectCheck(aClass: TClass; P: Pointer): string; // function PointerInfo(Format: integer): string; // save to a file the list of active memory blocks, // with a short description of each procedure SnapToFile(Filename: string); // checks whether a pointer falls within the range of // active memory blocks on the heap: // - this test can be applied to strings, objects, generic buffers // - cannot be applied to class references, functions/method pointers // constants and other globals function IsPointerWithinHeap(Address: Pointer): Boolean; // checks if a pointer refers to the beginning of a memory block // (object, buffer, etc). Don't use it for strings! function IsPointerToBlock(Address: Pointer): Boolean; // tries to extract the pointer to the class which is at the // beginning of an object memory block, and checks whether this // is actually a class (empirically) function IsPointerToObject(Address: Pointer): Boolean; implementation uses Windows, SysUtils, TypInfo; var OldMemMgr: TMemoryManager; ObjList: array[1..120000] of Pointer; FreeInList: Integer = 1; procedure AddToList(P: Pointer); begin { Se stai snappando non considerare tutti quegli oggetti } if duringSnap then exit; if FreeInList > High(ObjList) then begin MessageBox(0, 'List full ', 'MemMan', mb_ok); Exit; end; ObjList[FreeInList] := P; Inc(FreeInList); end; procedure RemoveFromList(P: Pointer); var I: Integer; begin for I := 1 to FreeInList - 1 do if ObjList[I] = P then begin // remove element shifting down the others Dec(FreeInList); Move(ObjList[I + 1], ObjList[I], (FreeInList - I) * sizeof(pointer)); Exit; end; end; function ObjectCheck(aClass: TClass; P: Pointer): string; //var // vmtPointer: PChar; begin if IsPointerToObject(P) then result := '' else Result := 'Invalid Pointer '; { begin vmtpointer := pchar(P^); if Pointer(vmtpointer) = aClass then Result := '' end;} end; type TDumpMemory = procedure(var OutFile: TextFile) of object; function IsPointerWithinHeap(Address: Pointer): Boolean; begin Result := True; if Assigned(Address) and (FindHInstance(Address) > 0) and (Cardinal(Address) >= Cardinal(ObjList[1])) and (Cardinal(Address) <= Cardinal(ObjList[FreeInList - 1])) then Result := True; end; function IsPointerToBlock(Address: Pointer): Boolean; var I: Integer; begin Result := False; if IsPointerWithinHeap(Address) then begin for I := 1 to FreeInList - 1 do if Address = ObjList[I] then begin Result := true; Exit; end; end; end; function IsPointerToObject(Address: Pointer): Boolean; var classPointer, vmtPointer: PChar; instsize: Integer; begin Result := False; if IsPointerWithinHeap(Address) then begin vmtpointer := pchar(Address^); classpointer := vmtpointer + vmtSelfPtr; if Assigned(vmtpointer) and (FindHInstance(vmtpointer) > 0) then begin instsize := (Pinteger(vmtpointer + vmtInstanceSize))^; // check self pointer and "reasonable" instance size if (pointer(pointer(classpointer)^) = pointer(vmtpointer)) and (instsize > 0) and (instsize < 10000) then Result := True; end; end; end; function IsPointerToString(Address: Pointer): Boolean; begin Result := False; end; function PointerInfo(Format: integer): string; begin end; procedure SnapToFile(Filename: string); var dumper: TMethod; OutFile: TextFile; I, CurrFree: Integer; strlen, strref: cardinal; // HeapStatus: THeapStatus; Item: TObject; // ptd: PTypeData; // ppi: PPropInfo; vmtpointer, pch: pchar; begin duringSnap := true; AssignFile(OutFile, Filename); try Rewrite(OutFile); CurrFree := FreeInList; // local heap status { HeapStatus := GetHeapStatus; with HeapStatus do begin write (OutFile, 'Available address space: '); write (OutFile, TotalAddrSpace div 1024); writeln (OutFile, ' Kbytes'); write (OutFile, 'Uncommitted portion: '); write (OutFile, TotalUncommitted div 1024); writeln (OutFile, ' Kbytes'); write (OutFile, 'Committed portion: '); write (OutFile, TotalCommitted div 1024); writeln (OutFile, ' Kbytes'); write (OutFile, 'Free portion: '); write (OutFile, TotalFree div 1024); writeln (OutFile, ' Kbytes'); write (OutFile, 'Allocated portion: '); write (OutFile, TotalAllocated div 1024); writeln (OutFile, ' Kbytes'); write (OutFile, 'Address space load: '); write (OutFile, TotalAllocated div (TotalAddrSpace div 100)); writeln (OutFile, '%'); write (OutFile, 'Total small free blocks: '); write (OutFile, FreeSmall div 1024); writeln (OutFile, ' Kbytes'); write (OutFile, 'Total big free blocks: '); write (OutFile, FreeBig div 1024); writeln (OutFile, ' Kbytes'); write (OutFile, 'Other unused blocks: '); write (OutFile, Unused div 1024); writeln (OutFile, ' Kbytes'); write (OutFile, 'Total overhead: '); write (OutFile, Overhead div 1024); writeln (OutFile, ' Kbytes'); end; } // custom memory manager information writeln(OutFile); // free line write(OutFile, 'Memory objects: '); writeln(OutFile, CurrFree - 1); // for each memory block for I := 1 to CurrFree - 1 do begin write(OutFile, I); write(OutFile, ') '); write(OutFile, IntToHex( Cardinal(ObjList[I]), 8)); write(OutFile, ': '); try // strings pch := ObjList[I]; strlen := pinteger(pch + 4)^; strref := pinteger(pch)^; pch := pch + 8; // if this a string? if ((strref > 0) and (strref < 100)) and ((strlen < 1000000) or (strlen = sysutils.strlen(pch))) then begin write(outFile, ' string: ['); write(OutFile, strlen); write(OutFile, '-'); write(OutFile, strref); write(OutFile, ']: '); while pch^ <> #0 do begin write(OutFile, pch^); inc(pch); end; end else begin // is it an object? Item := TObject(ObjList[I]); vmtpointer := pchar((ObjList[I])^); if Assigned(vmtpointer) and (FindHInstance(vmtpointer) > 0) then begin if IsPointerToObject(Item) then begin // it is an object write(outFile, ' object: ['); write(OutFile, Item.ClassName); write(outFile, ' - '); write(OutFile, Item.InstanceSize); write(OutFile, '] '); if (Item.ClassName = 'tArthaEntry') then begin writeln(OutFile); dumper.Data := Item; dumper.Code := Item.MethodAddress('DumpMemory'); TDumpMemory(dumper)(outFile); end; (*if (Item.ClassInfo <> nil) and (FindHInstance (Item.ClassInfo) > 0) then begin ptd := GetTypeData (PTypeInfo (Item.ClassInfo)); if ptd <> nil then begin // name, if a component if (Item.ClassName <> 'TFont') and isPublishedProp (Item, 'Name') then begin write (OutFile, GetStrProp (Item, 'Name')); {ppi := GetPropInfo (PTypeInfo (Item.ClassInfo), 'Name'); if ppi <> nil then write (OutFile, GetStrProp (Item, ppi));} end; end; end;*) end // an object else if IsPointerWithinHeap(vmtpointer) then begin write(outFile, ' buffer with heap pointer ['); write(outFile, IntToHex(Cardinal(vmtpointer), 8)); write(outFile, ']'); end else begin // still a valid pointer, but not to heap write(outFile, ' buffer with pointer ['); write(outFile, IntToHex(Cardinal(vmtpointer), 8)); write(outFile, ']'); end; end else begin // buffer with undefined data write(outFile, ' buffer: ['); write(outFile, IntToHex(Cardinal(pinteger(ObjList[I])^), 8)); {pch := ObjList [I]; for j := 0 to 3 do begin write (OutFile, Byte((pch+j)^)); write (OutFile, ' '); end;} write(OutFile, ']'); end; end; // string else object except on Exception do write(OutFile, 'memman error'); end; writeln(OutFile); end; // for finally CloseFile(OutFile); duringSnap := false; end; end; function NewGetMem(Size: Integer): Pointer; begin Inc(GetMemCount); Result := OldMemMgr.GetMem(Size); AddToList(Result); end; function NewFreeMem(P: Pointer): Integer; begin Inc(FreeMemCount); Result := OldMemMgr.FreeMem(P); RemoveFromList(P); end; function NewReallocMem(P: Pointer; Size: Integer): Pointer; begin Inc(ReallocMemCount); Result := OldMemMgr.ReallocMem(P, Size); // remove older object RemoveFromList(P); // add new one AddToList(Result); end; const NewMemMgr: TMemoryManager = ( GetMem: NewGetMem; FreeMem: NewFreeMem; ReallocMem: NewReallocMem); initialization GetMemoryManager(OldMemMgr); SetMemoryManager(NewMemMgr); finalization SetMemoryManager(OldMemMgr); { if (GetMemCount - FreeMemCount) <> 0 then MessageBox (0, pChar ('Objects left: ' + IntToStr (GetMemCount - FreeMemCount)), 'MemManager', mb_ok);} end.
//**************************************************************** // // Admin // // Copyright (c) 2006 Failproof Manufacturing Systems. // //**************************************************************** // // 02/17/2006 David Verespey Initial creation unit HolidayOvertime; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ADODB, DB, StdCtrls, ComCtrls, Grids, DBGrids, ExtCtrls, AdvCombo, ColCombo, NUMMIColumnComboBox ; type THolidayOvertimeForm = class(TForm) DBGrid1: TDBGrid; Panel1: TPanel; ClearButton: TButton; InsertButton: TButton; UpdateButton: TButton; DeleteButton: TButton; Panel2: TPanel; LineNameComboBox: TComboBox; SpecialDate: TDateTimePicker; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; DescriptionnEdit: TEdit; SearchButton: TButton; CloseButton: TButton; EventType_NUMMIColumnComboBox: TNUMMIColumnComboBox; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ClearButtonClick(Sender: TObject); procedure DataSource1DataChange(Sender: TObject; Field: TField); procedure FormDestroy(Sender: TObject); procedure SearchButtonClick(Sender: TObject); procedure InsertButtonClick(Sender: TObject); procedure UpdateButtonClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure LineNameComboBoxChange(Sender: TObject); procedure SpecialDateChange(Sender: TObject); procedure CloseButtonClick(Sender: TObject); private { Private declarations } fChanged:Boolean; procedure Clear; public { Public declarations } procedure Execute; end; var HolidayOvertimeForm: THolidayOvertimeForm; implementation uses DataModule; {$R *.dfm} procedure Execute; begin end; // // Buttons // procedure THolidayOvertimeForm.Clear; begin LineNameComboBox.Text:=''; LineNameComboBox.ItemIndex:=0; ProductionDateStatusComboBox.Text:=''; ProductionDateStatusComboBox.ItemIndex:=0; DescriptionnEdit.Text:=''; SpecialDate.DateTime:=now; end; procedure THolidayOvertimeForm.ClearButtonClick(Sender: TObject); begin Clear; InsertButton.Enabled:=TRUE; UpdateButton.Enabled:=FALSE; DeleteButton.Enabled:=FALSE; SearchButton.Enabled:=TRUE; end; procedure THolidayOvertimeForm.SearchButtonClick(Sender: TObject); var bm:TBookMark; found:boolean; begin try found:=TRUE; bm:=SpecialDatesDataSet.GetBookmark; SpecialDatesDataSet.DisableControls; SpecialDatesDataSet.First; while not SpecialDatesDataSet.Eof do begin if formatdatetime('yyyymmdd',SpecialDate.DateTime) = formatdateTime('yyyymmdd',SpecialDatesDataSet.FieldByName('Date').AsDateTime) then begin found:=TRUE; break; end; SpecialDatesDataSet.Next; end; if not found then begin SpecialDatesDataSet.GotoBookmark(bm); ShowMessage('Date not found'); end; fChanged:=FALSE; finally SpecialDatesDataSet.EnableControls; end; end; procedure THolidayOvertimeForm.InsertButtonClick(Sender: TObject); begin // INSERT if fChanged then begin if LineNameComboBox.Text = '' then begin ShowMessage('Must select a Line'); LineNameComboBox.SetFocus; exit; end; if ProductionDateStatusComboBox.Text = '' then begin ShowMessage('Must select a Date Status'); ProductionDateStatusComboBox.SetFocus; exit; end; if formatdatetime('yyyymmdd',SpecialDate.DateTime) < formatdatetime('yyyymmdd',now) then begin ShowMessage('Date cannot have already passed'); SpecialDate.SetFocus; exit; end; try SpecialDatesCommand.CommandType:=cmdStoredProc; SpecialDatesCommand.CommandText:='AD_InsertSpecialDate'; SpecialDatesCommand.Parameters.Clear; SpecialDatesCommand.Parameters.AddParameter.Name:='@LineName'; SpecialDatesCommand.Parameters.ParamValues['@LineName']:=LineNameComboBox.Text; SpecialDatesCommand.Parameters.AddParameter.Name:='@ProductionStatus'; SpecialDatesCommand.Parameters.ParamValues['@ProductionStatus']:=ProductionDateStatusComboBox.Text; SpecialDatesCommand.Parameters.AddParameter.Name:='@SpecialDateName'; SpecialDatesCommand.Parameters.ParamValues['@SpecialDateName']:=DescriptionnEdit.Text; SpecialDatesCommand.Parameters.AddParameter.Name:='@SpecialDate'; SpecialDatesCommand.Parameters.ParamValues['@SpecialDate']:=SpecialDate.DateTime; SpecialDatesCommand.Execute; Refresh; except on e:exception do begin ShowMessage('Unable to insert record, '+e.Message); Refresh; end; end; end else begin ShowMessage('Nothing to Insert'); end; end; procedure THolidayOvertimeForm.UpdateButtonClick(Sender: TObject); begin // UPDATE if fChanged then begin if LineNameComboBox.Text = '' then begin ShowMessage('Must select a Line'); LineNameComboBox.SetFocus; exit; end; if ProductionDateStatusComboBox.Text = '' then begin ShowMessage('Must select a Date Status'); ProductionDateStatusComboBox.SetFocus; exit; end; if formatdatetime('yyyymmdd',SpecialDate.DateTime) < formatdatetime('yyyymmdd',now) then begin ShowMessage('Date cannot have already passed'); SpecialDate.SetFocus; exit; end; try SpecialDatesCommand.CommandType:=cmdStoredProc; SpecialDatesCommand.CommandText:='AD_UpdateSpecialDate'; SpecialDatesCommand.Parameters.Clear; SpecialDatesCommand.Parameters.AddParameter.Name:='@SpecialDateID'; SpecialDatesCommand.Parameters.ParamValues['@SpecialDateID']:=SpecialDatesDataSet.FieldByName('SpecialDateID').AsInteger; SpecialDatesCommand.Parameters.AddParameter.Name:='@LineName'; SpecialDatesCommand.Parameters.ParamValues['@LineName']:=LineNameComboBox.Text; SpecialDatesCommand.Parameters.AddParameter.Name:='@ProductionStatus'; SpecialDatesCommand.Parameters.ParamValues['@ProductionStatus']:=ProductionDateStatusComboBox.Text; SpecialDatesCommand.Parameters.AddParameter.Name:='@SpecialDateName'; SpecialDatesCommand.Parameters.ParamValues['@SpecialDateName']:=DescriptionnEdit.Text; SpecialDatesCommand.Parameters.AddParameter.Name:='@SpecialDate'; SpecialDatesCommand.Parameters.ParamValues['@SpecialDate']:=SpecialDate.DateTime; SpecialDatesCommand.Execute; Refresh; except on e:exception do begin ShowMessage('Unable to update record, '+e.Message); Refresh; end; end; end else begin ShowMessage('Nothing to Update'); end; end; procedure THolidayOvertimeForm.DeleteButtonClick(Sender: TObject); begin // DELETE try if MessageDlg('Delete the record['+SpecialDatesDataSet.FieldByName('Description').AsString+':'+FormatDateTime('mm/dd/yyyy',SpecialDatesDataSet.FieldByName('Date').AsDateTime)+'] for Line('+LineNameComboBox.Text+')?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin SpecialDatesCommand.CommandType:=cmdStoredProc; SpecialDatesCommand.CommandText:='AD_DeleteSpecialDate'; SpecialDatesCommand.Parameters.Clear; SpecialDatesCommand.Parameters.AddParameter.Name:='@SpecialDateID'; SpecialDatesCommand.Parameters.ParamValues['@SpecialDateID']:=SpecialDatesDataSet.FieldByName('SpecialDateID').AsInteger; SpecialDatesCommand.Execute; Refresh; end; except on e:exception do begin ShowMessage('Unable to delete record, '+e.Message); end; end; end; procedure THolidayOvertimeForm.FormCreate(Sender: TObject); begin // load combos try With Data_Module do Begin Inv_DataSet.Filter:=''; Inv_DataSet.Filtered:=FALSE; SelectSingleFieldALC('LINE', 'LineName', LineNameComboBox); GetOvertimeHolidayInfo; JustifyColumns(Event_DBGrid); End; except on e:exception do begin ShowMessage('Unable to get Holiday/Overtime Data, '+e.Message); Close; end; end; end; procedure THolidayOvertimeForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action:=caFree; end; procedure THolidayOvertimeForm.FormDestroy(Sender: TObject); begin HolidayOvertimeForm:=nil; end; procedure THolidayOvertimeForm.LineNameComboBoxChange(Sender: TObject); begin fChanged:=TRUE; end; procedure THolidayOvertimeForm.SpecialDateChange(Sender: TObject); begin LineNameComboBoxChange(self); end; procedure THolidayOvertimeForm.CloseButtonClick(Sender: TObject); begin Close; end; end.
unit RemoveUserUnit; interface uses SysUtils, BaseExampleUnit, UserParametersUnit; type TRemoveUser = class(TBaseExample) public procedure Execute(MemberId: integer); end; implementation procedure TRemoveUser.Execute(MemberId: integer); var ErrorString: String; begin Route4MeManager.User.Remove(MemberId, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn('User removed successfully'); WriteLn(''); end else WriteLn(Format('RemoveUser error: "%s"', [ErrorString])); end; end.
unit vulkan.util; (* * Vulkan Samples * * Copyright (C) 2015-2016 Valve Corporation * Copyright (C) 2015-2016 LunarG, Inc. * Copyright (C) 2015-2016 Google, Inc. * * 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. *) interface //#################################################################### ■ uses vulkan_core, LUX.Code.C, LUX.D1, LUX.D2, LUX.D2x2, LUX.D3, LUX.D3x3, LUX.D4x4; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% T_layer_properties (* * A layer can expose extensions, keep track of those * extensions here. *) T_layer_properties = record properties :VkLayerProperties; instance_extensions :TArray<VkExtensionProperties>; device_extensions :TArray<VkExtensionProperties>; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% T_sample_info (* * Structure for tracking information used / created / modified * by utility functions. *) P_sample_info = ^T_sample_info; T_sample_info = record private const APP_NAME_STR_LEN = 80; public save_images :T_bool; framebuffers :TArray<VkFramebuffer>; vertex_buffer :record buf :VkBuffer; mem :VkDeviceMemory; buffer_info :VkDescriptorBufferInfo; end; vi_binding :VkVertexInputBindingDescription; vi_attribs :array [ 0..2-1 ] of VkVertexInputAttributeDescription; pipeline_layout :VkPipelineLayout; desc_layout :TArray<VkDescriptorSetLayout>; pipelineCache :VkPipelineCache; render_pass :VkRenderPass; desc_pool :VkDescriptorPool; desc_set :TArray<VkDescriptorSet>; viewport :VkViewport; scissor :VkRect2D; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 (* Number of samples needs to be the same at image creation, *) (* renderpass creation and pipeline creation. *) NUM_SAMPLES = VK_SAMPLE_COUNT_1_BIT; (* Number of descriptor sets needs to be the same at alloc, *) (* pipeline layout creation, and descriptor set layout creation *) NUM_DESCRIPTOR_SETS = 1; (* Amount of time, in nanoseconds, to wait for a command buffer to complete *) FENCE_TIMEOUT = 100000000; (* Number of viewports and number of scissors have to be the same *) (* at pipeline creation and in any call to set them dynamically *) (* They also have to be the same as each other *) NUM_VIEWPORTS = 1; NUM_SCISSORS = NUM_VIEWPORTS; //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 end. //######################################################################### ■
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.9 10/26/2004 10:10:58 PM JPMugaas { Updated refs. } { { Rev 1.8 3/6/2004 2:53:30 PM JPMugaas { Cleaned up an if as per Bug #79. } { { Rev 1.7 2004.02.03 5:43:42 PM czhower { Name changes } { { Rev 1.6 2004.01.27 1:39:26 AM czhower { CharIsInSet bug fix } { { Rev 1.5 1/22/2004 3:50:04 PM SPerry { fixed set problems (with CharIsInSet) } { { Rev 1.4 1/22/2004 7:10:06 AM JPMugaas { Tried to fix AnsiSameText depreciation. } { { Rev 1.3 10/5/2003 11:43:50 PM GGrieve { Use IsLeadChar } { { Rev 1.2 10/4/2003 9:15:14 PM GGrieve { DotNet changes } { { Rev 1.1 2/25/2003 12:56:20 PM JPMugaas { Updated with Hadi's fix for a bug . If complete boolean expression i on, you { may get an Index out of range error. } { { Rev 1.0 11/13/2002 07:53:52 AM JPMugaas } unit IdHeaderList; { 2002-Jan-27 Don Siders - Modified FoldLine to include Comma in break character set. 2000-May-31 J. Peter Mugaas - started this class to facilitate some work on Indy so we don't have to convert '=' to ":" and vice-versa just to use the Values property. } { NOTE: This is a modification of Borland's TStrings definition in a TStringList descendant. I had to conceal the original Values to do this since most of low level property setting routines aren't virtual and are private. } interface uses IdSys, IdObjs; type TIdHeaderList = class(TIdStringList) protected FNameValueSeparator : String; FCaseSensitive : Boolean; FUnfoldLines : Boolean; FFoldLines : Boolean; FFoldLinesLength : Integer; // {This deletes lines which were folded} Procedure DeleteFoldedLines(Index : Integer); {This folds one line into several lines} function FoldLine(AString : string) : TIdStringList; {Folds lines and inserts them into a position, Index} procedure FoldAndInsert(AString : String; Index : Integer); {Name property get method} function GetName(Index: Integer): string; {Value property get method} function GetValue(const AName: string): string; {Value property set method} procedure SetValue(const Name, Value: string); {Gets a value from a string} function GetValueFromLine(ALine : Integer) : String; Function GetNameFromLine(ALine : Integer) : String; public procedure AddStdValues(ASrc: TIdStrings); procedure ConvertToStdValues(ADest: TIdStrings); constructor Create; { This method given a name specified by AName extracts all of the values for that name - and puts them in a new string list (just the values) one per line in the ADest TIdStrings.} procedure Extract(const AName: string; ADest: TIdStrings); { This property works almost exactly as Borland's IndexOfName except it uses our deliniator defined in NameValueSeparator } function IndexOfName(const AName: string): Integer; reintroduce; { This property works almost exactly as Borland's Values except it uses our deliniator defined in NameValueSeparator } property Names[Index: Integer]: string read GetName; { This property works almost exactly as Borland's Values except it uses our deliniator defined in NameValueSeparator } property Values[const Name: string]: string read GetValue write SetValue; { This is the separator we need to separate the name from the value } property NameValueSeparator : String read FNameValueSeparator write FNameValueSeparator; { Should the names be tested in a case-senstive manner. } property CaseSensitive : Boolean read FCaseSensitive write FCaseSensitive; { Should we unfold lines so that continuation header data is returned as well} property UnfoldLines : Boolean read FUnfoldLines write FUnfoldLines; { Should we fold lines we the Values(x) property is set with an assignment } property FoldLines : Boolean read FFoldLines write FFoldLines; { The Wrap position for our folded lines } property FoldLength : Integer read FFoldLinesLength write FFoldLinesLength; end; implementation uses IdGlobal, IdGlobalProtocols; { TIdHeaderList } procedure TIdHeaderList.AddStdValues(ASrc: TIdStrings); var i: integer; begin for i := 0 to ASrc.Count - 1 do begin Add( Sys.ReplaceOnlyFirst (ASrc[i], '=', NameValueSeparator)); {Do not Localize} end; end; procedure TIdHeaderList.ConvertToStdValues(ADest: TIdStrings); var i: integer; begin for i := 0 to Count - 1 do begin ADest.Add(Sys.ReplaceOnlyFirst(Strings[i], NameValueSeparator, '=')); {Do not Localize} end; end; constructor TIdHeaderList.Create; begin inherited Create; FNameValueSeparator := ': '; {Do not Localize} FCaseSensitive := False; FUnfoldLines := True; FFoldLines := True; { 78 was specified by a message draft available at http://www.imc.org/draft-ietf-drums-msg-fmt } FFoldLinesLength := 78; end; procedure TIdHeaderList.DeleteFoldedLines(Index: Integer); begin Inc(Index); {skip the current line} if Index < Count then begin while ( Index < Count ) and CharIsInSet(Get(Index),1,' '+#9) do {Do not Localize} begin Delete( Index ); end; //while end; end; procedure TIdHeaderList.Extract(const AName: string; ADest: TIdStrings); var idx : Integer; begin if not Assigned(ADest) then Exit; for idx := 0 to Count - 1 do begin if TextIsSame(AName, GetNameFromLine(idx)) then begin ADest.Add(GetValueFromLine(idx)); end; end; end; procedure TIdHeaderList.FoldAndInsert(AString : String; Index: Integer); var strs : TIdStringList; idx : Integer; begin strs := FoldLine( AString ); try idx := strs.Count - 1; Put(Index, strs [ idx ] ); {We decrement by one because we put the last string into the HeaderList} Dec( idx ); while ( idx > -1 ) do begin Insert(Index, strs [ idx ] ); Dec( idx ); end; finally Sys.FreeAndNil( strs ); end; //finally end; function TIdHeaderList.FoldLine(AString : string): TIdStringList; var s : String; begin Result := TIdStringList.Create; try {we specify a space so that starts a folded line} s := WrapText(AString, EOL+' ', LWS+',', FFoldLinesLength); {Do not Localize} while s <> '' do {Do not Localize} begin Result.Add( Sys.TrimRight( Fetch( s, EOL ) ) ); end; // while s <> '' do {Do not Localize} finally end; //try..finally end; function TIdHeaderList.GetName(Index: Integer): string; var P: Integer; begin Result := Get( Index ); P := IndyPos( FNameValueSeparator , Result ); if P <> 0 then begin SetLength( Result, P - 1 ); end // if P <> 0 then else begin SetLength( Result, 0 ); end; // else if P <> 0 then Result := Result; end; function TIdHeaderList.GetNameFromLine(ALine: Integer): String; var p : Integer; begin Result := Get( ALine ); if not FCaseSensitive then begin Result := Sys.UpperCase( Result ); end; // if not FCaseSensitive then {We trim right to remove space to accomodate header errors such as Message-ID:<asdf@fdfs } P := IndyPos( Sys.TrimRight( FNameValueSeparator ), Result ); Result := Copy( Result, 1, P - 1 ); end; function TIdHeaderList.GetValue(const AName: string): string; begin Result := GetValueFromLine(IndexOfName(AName)); end; function TIdHeaderList.GetValueFromLine(ALine: Integer): String; var LFoldedLine: string; LName: string; begin if (ALine >= 0) and (ALine < Count) then begin LName := GetNameFromLine(ALine); Result := Copy(Get(ALine), Length(LName) + 2, MaxInt); if FUnfoldLines then begin while True do begin Inc(ALine); if ALine = Count then begin Break; end; LFoldedLine := Get(ALine); // s[1] is safe since header lines cannot be empty as that causes then end of the header block if not (CharIsInSet(LFoldedLine, 1, LWS)) then begin Break; end; Result := Sys.Trim(Result) + ' ' + Sys.Trim(LFoldedLine); {Do not Localize} end; end; end else begin Result := ''; {Do not Localize} end; // User may be fetching an folded line diretly. Result := Sys.Trim(Result); end; function TIdHeaderList.IndexOfName(const AName: string): Integer; var i: Integer; begin Result := -1; for i := 0 to Count - 1 do begin if TextIsSame(GetNameFromLine(i), AName) then begin Result := i; Break; end; end; end; procedure TIdHeaderList.SetValue(const Name, Value: string); var I: Integer; begin I := IndexOfName(Name); if Value <> '' then {Do not Localize} begin if I < 0 then begin I := Add( '' ); {Do not Localize} end; //if I < 0 then if FFoldLines then begin DeleteFoldedLines( I ); FoldAndInsert( Name + FNameValueSeparator + Value, I ); end else begin Put( I, Name + FNameValueSeparator + Value ); end; //else..FFoldLines end //if Value <> '' then {Do not Localize} else begin if I >= 0 then begin if FFoldLines then begin DeleteFoldedLines( I ); end; Delete( I ); end; //if I >= 0 then end; //else .. if Value <> '' then {Do not Localize} end; end.
unit mivLauncher_Unit; interface uses MobileInternetVersionMenuForm_Unit, SysUtils; type ELauncherError = class(Exception); TmivLauncher = class(TObject) private f_LauncherMenuForm: TMobileInternetVersionMenuForm; function MakeCommandString: String; function NeedShowMenu: Boolean; procedure ShowMenu; procedure ProcessUserCommand(ACommand: TmivUserCommand); procedure ExecuteShell(const ACommandLine: String); procedure RunProcess(const AApplication: string; const ACommandLine: string; const ACurrentDirectory: string); procedure ErrorMessageBox(const AText: string); public class procedure Run; destructor Destroy; override; end; implementation uses Controls, Forms, Dialogs, Windows, ShellApi, l3Base, LocaleMessages; const C_APPLICATION_FILENAME = 'garant.run'; C_OPEN_BY_NUMBER = '-OpenByNumber %s'; C_SILENT_RUN_AND_EXIT = '-SilentRunAndExit'; // Топик для "Начать работу с Интернет-версией" C_INTERNET_VERSION_TOPIC = '890941.100011'; // Топик для "Сгенерировать реквизиты для доступа" C_REQUISITES_TOPIC = '890941.100012'; // Топик для перехода на конструкторы договоров C_CONTRACT_CONSTRUCTOR_TOPIC = '890941.100013'; // Заголовок формы меню C_MENU_FORM_CAPTION = 'Мобильная интернет-версия системы ГАРАНТ'; { TmivLauncher } destructor TmivLauncher.Destroy; begin FreeAndNil(f_LauncherMenuForm); inherited; end; procedure TmivLauncher.ErrorMessageBox(const AText: string); begin MessageBox(Application.Handle, PChar(AText), PChar(Application.Title), MB_OK or MB_ICONERROR); end;//TmivLauncher.ErrorMessageBox procedure TmivLauncher.ExecuteShell(const ACommandLine: String); begin try RunProcess(C_APPLICATION_FILENAME, ACommandLine, GetCurrentDir) except on E: ELauncherError do begin ErrorMessageBox(Format(GetCurrentLocaleMessage(c_CommonUnexpectedException), [E.Message])); f_LauncherMenuForm.ModalResult := mrOK; end; end;//try..except end;//TmivLauncher.ExecuteShell function TmivLauncher.MakeCommandString: String; function lp_QuoteString(const AString: string): string; begin Result := Format('"%s"', [AString]); end;//lp_QuoteStringIfNeeded function lp_AddParamStrToCommandString(const ACommandString: String; const AParamStr: String): String; begin Result := Format('%s %s', [ACommandString, lp_QuoteString(AParamStr)]); end;//lp_AddParamStrToCommandString var l_Index: Integer; begin Result := EmptyStr; for l_Index := 1 to ParamCount do Result := lp_AddParamStrToCommandString(Result, ParamStr(l_Index)); end;//TmivLauncher.MakeCommandString function TmivLauncher.NeedShowMenu: Boolean; begin Result := ParamCount = 0; end;//TmivLauncher.NeedShowMenu procedure TmivLauncher.ProcessUserCommand(ACommand: TmivUserCommand); function lp_MakeOpenByNumberString(const ATopicStr: String): String; begin Result := Format(C_OPEN_BY_NUMBER, [ATopicStr]) + ' ' + C_SILENT_RUN_AND_EXIT; end;//lp_MakeOpenByNumberString var l_CommandStr: String; l_NeedRun: Boolean; begin l_NeedRun := True; case ACommand of mucStartWorkingWithInternetVersion: l_CommandStr := lp_MakeOpenByNumberString(C_INTERNET_VERSION_TOPIC); mucObtainRequisites: l_CommandStr := lp_MakeOpenByNumberString(C_REQUISITES_TOPIC); mucWorkLocal: l_CommandStr := ''; mucRunContractConstructor: l_CommandStr := lp_MakeOpenByNumberString(C_CONTRACT_CONSTRUCTOR_TOPIC); mucCancel: l_NeedRun := False; end;//case ACommand if l_NeedRun then ExecuteShell(l_CommandStr); end;//TmivLauncher.ProcessUserCommand class procedure TmivLauncher.Run; var l_Launcher: TmivLauncher; begin SetCurrentLocale('ru'); l_Launcher := TmivLauncher.Create; with l_Launcher do try if NeedShowMenu then ShowMenu else ExecuteShell(MakeCommandString); finally FreeAndNil(l_Launcher); Application.Terminate; end;//try..finally end;//TmivLauncher.Run procedure TmivLauncher.RunProcess(const AApplication: String; const ACommandLine: String; const ACurrentDirectory: string); function lp_GetCreationFlags: DWORD; begin Result := DWORD(CREATE_DEFAULT_ERROR_MODE or DETACHED_PROCESS or NORMAL_PRIORITY_CLASS); end;//lp_GetCreationFlags function lp_QuoteStringIfNeed(const AString: string): string; begin if ((Pos(' ', AString) <> 0) or (Pos('''', AString) <> 0)) then Result := Format('"%s"', [AString]) else Result := AString; end;//lp_QuoteStringIfNeeded var l_ShellExecuteInfo: TShellExecuteInfo; l_ProcessInformation: TProcessInformation; l_StartupInfo: TStartupInfo; l_Application: String; l_CommandLine: String; l_RunSuccess: BOOL; l_StructSize: Integer; begin l_Application := Format('%s\%s', [ACurrentDirectory, AApplication]); if (FileExists(l_Application)) then begin l_CommandLine := lp_QuoteStringIfNeed(l_Application); if (ACommandLine <> '') then l_CommandLine := Format('%s %s', [l_CommandLine, ACommandLine]); l3FillChar(l_ProcessInformation, SizeOf(l_ProcessInformation), 0); l3FillChar(l_StartupInfo, SizeOf(l_StartupInfo), 0); with l_StartupInfo do begin cb := DWORD(SizeOf(l_StartupInfo)); dwFlags := STARTF_USESTDHANDLES; end;//with l_StartupInfo l_RunSuccess := CreateProcess(nil, PChar(l_CommandLine), nil, nil, False, lp_GetCreationFlags, nil, PChar(ACurrentDirectory), l_StartupInfo, l_ProcessInformation); if l_RunSuccess then begin with l_ProcessInformation do begin CloseHandle(hThread); Application.Terminate; end;//with l_ProcessInformation end else//if l_RunSuccess begin l_StructSize := SizeOf(l_ShellExecuteInfo); l3FillChar(l_ShellExecuteInfo, l_StructSize, 0); with l_ShellExecuteInfo do begin cbSize := DWORD(l_StructSize); fMask := SEE_MASK_CLASSNAME or SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI or SEE_MASK_NOCLOSEPROCESS; lpVerb := 'runas'; lpFile := PChar(AApplication); lpParameters := PChar(ACommandLine); nShow := SW_SHOWDEFAULT; lpClass := 'exefile'; end;//with l_ShellExecuteInfo l_RunSuccess := ShellExecuteEx(@l_ShellExecuteInfo); if l_RunSuccess then Application.Terminate else raise ELauncherError.Create(Format(GetCurrentLocaleMessage(c_CommonUnableStartProcess), [l_Application])); end;//if l_RunSuccess end else//if (FileExists(l_Application) raise ELauncherError.Create(Format(GetCurrentLocaleMessage(c_CommonFileNotFound), [l_Application])); end;//TmivLauncher.RunProcess procedure TmivLauncher.ShowMenu; begin f_LauncherMenuForm := TMobileInternetVersionMenuForm.Create(Application); with f_LauncherMenuForm do begin Caption := C_MENU_FORM_CAPTION; OnCommand := ProcessUserCommand; ShowModal; end; end;//TmivLauncher.ShowMenu end.
unit WpcCommonTypes; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TWpcTimeMeasurementUnits = (MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS); { TWPCImage } TWpcImage = class(TObject) public constructor Create(Path : String); private Path : String; public function GetPath() : String; function IsExists() : Boolean; end; implementation { TWPCImage } constructor TWpcImage.Create(Path: String); begin Self.Path := Path; end; function TWpcImage.GetPath() : String; begin Result := Self.Path; end; function TWpcImage.IsExists() : Boolean; begin Result := FileExists(Self.Path); end; end.
{ Author: Jarl K. Holta License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html) Runtime datatype representations } unit xpr.bool; {$I express.inc} interface {$I objh.inc} uses SysUtils, xpr.express, xpr.objbase; type TBoolObject = class(TEpObject) value: Boolean; constructor Create(AValue:Boolean); function Copy(gcGen:Byte=0): TEpObject; override; function DeepCopy: TEpObject; override; function AsBool: Boolean; override; function AsInt: epInt; override; function AsFloat: Double; override; function AsString: epString; override; procedure ASGN(other:TEpObject; var dest:TEpObject); override; procedure EQ(other:TEpObject; var dest:TEpObject); override; procedure NE(other:TEpObject; var dest:TEpObject); override; procedure LT(other:TEpObject; var dest:TEpObject); override; procedure GT(other:TEpObject; var dest:TEpObject); override; procedure LE(other:TEpObject; var dest:TEpObject); override; procedure GE(other:TEpObject; var dest:TEpObject); override; procedure LOGIC_AND(other:TEpObject; var dest:TEpObject); override; procedure LOGIC_OR(other:TEpObject; var dest:TEpObject); override; procedure LOGIC_NOT(var dest:TEpObject); override; end; procedure SetBoolDest(var dest:TEpObject; constref value:Boolean); inline; implementation uses xpr.utils, xpr.errors, xpr.mmgr, xpr.int, xpr.float; procedure SetBoolDest(var dest:TEpObject; constref value:Boolean); var GC:TGarbageCollector; begin Assert(dest <> nil, 'dest is nil'); if dest.ClassType = TBoolObject then TBoolObject(dest).value := value else begin GC := TGarbageCollector(dest.gc); GC.Release(dest); dest := GC.AllocBool(value); end; end; constructor TBoolObject.Create(AValue:Boolean); begin self.Value := AValue; end; function TBoolObject.Copy(gcGen:Byte=0): TEpObject; begin Result := TGarbageCollector(GC).AllocBool(self.value, gcGen); end; function TBoolObject.DeepCopy: TEpObject; begin Result := TGarbageCollector(GC).AllocBool(self.value); end; function TBoolObject.AsBool: Boolean; begin Result := self.Value; end; function TBoolObject.AsInt: epInt; begin Result := ord(self.Value); end; function TBoolObject.AsFloat: Double; begin Result := ord(self.Value); end; function TBoolObject.AsString: epString; begin Result := BoolToStr(self.Value, True); end; procedure TBoolObject.ASGN(other:TEpObject; var dest:TEpObject); begin if other.ClassType = TBoolObject then self.value := TBoolObject(other).value else inherited; end; procedure TBoolObject.EQ(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TBoolObject) then SetBoolDest(dest, self.value = TBoolObject(other).value) else SetBoolDest(dest, self.value = other.AsBool) end; procedure TBoolObject.NE(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TBoolObject) then SetBoolDest(dest, self.value <> TBoolObject(other).value) else SetBoolDest(dest, self.value <> other.AsBool) end; procedure TBoolObject.LT(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TBoolObject) then SetBoolDest(dest, Ord(self.value) < Ord(TBoolObject(other).value)) else if (other.ClassType = TIntObject) then SetBoolDest(dest, Ord(self.value) < TIntObject(other).value) else if (other.ClassType = TFloatObject) then SetBoolDest(dest, Ord(self.value) < TFloatObject(other).value) else SetBoolDest(dest, Ord(self.value) < other.AsInt) end; procedure TBoolObject.GT(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TBoolObject) then SetBoolDest(dest, Ord(self.value) > Ord(TBoolObject(other).value)) else if (other.ClassType = TIntObject) then SetBoolDest(dest, Ord(self.value) > TIntObject(other).value) else if (other.ClassType = TFloatObject) then SetBoolDest(dest, Ord(self.value) > TFloatObject(other).value) else SetBoolDest(dest, Ord(self.value) > other.AsInt) end; procedure TBoolObject.LE(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TBoolObject) then SetBoolDest(dest, Ord(self.value) <= Ord(TBoolObject(other).value)) else if (other.ClassType = TIntObject) then SetBoolDest(dest, Ord(self.value) <= TIntObject(other).value) else if (other.ClassType = TFloatObject) then SetBoolDest(dest, Ord(self.value) <= TFloatObject(other).value) else SetBoolDest(dest, Ord(self.value) <= other.AsInt) end; procedure TBoolObject.GE(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TBoolObject) then SetBoolDest(dest, Ord(self.value) >= Ord(TBoolObject(other).value)) else if (other.ClassType = TIntObject) then SetBoolDest(dest, Ord(self.value) >= TIntObject(other).value) else if (other.ClassType = TFloatObject) then SetBoolDest(dest, Ord(self.value) >= TFloatObject(other).value) else SetBoolDest(dest, Ord(self.value) >= other.AsInt) end; procedure TBoolObject.LOGIC_AND(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TBoolObject) then SetBoolDest(dest, self.value and TBoolObject(other).value) else SetBoolDest(dest, self.value and other.AsBool); end; procedure TBoolObject.LOGIC_OR(other:TEpObject; var dest:TEpObject); begin if (other.ClassType = TBoolObject) then SetBoolDest(dest, self.value or TBoolObject(other).value) else SetBoolDest(dest, self.value or other.AsBool); end; procedure TBoolObject.LOGIC_NOT(var dest:TEpObject); begin SetBoolDest(dest, not self.value); end; end.
unit MazeSave; interface uses MazeMain; const ProgDir = 'Maze\'; TypeFileAddr = 'MazeHistory.ini'; TextFileDir = 'Mazes\'; Procedure SaveMazeToFile(Const MazeToSave: TMaze; const MazeStat: TMazeStat); Procedure SaveMazeToTypeFile(Const MazeStat: TMazeStat; const FileAddr: String); Function GetRecordsAmount(const FileAddr: String): Integer; Function ReadFromTypeFile(const RecordToRead: Integer; const FileAddr: string): TMazeStat; Procedure ClearTypeFile(const FileAddr: String); Procedure DeleteRecord(const RecordToDel: Integer; const FileAddr: String); Implementation Uses SysUtils, shlobj, Windows; function GetAppDataPath: String; var path: array [0..MAX_PATH] of char; UserPath: String; begin SHGetFolderPath(0, CSIDL_APPDATA, 0, SHGFP_TYPE_CURRENT, @path); userPath:= Path; UserPath:= UserPath + '\' + ProgDir; if not DirectoryExists(UserPath) then CreateDir(UserPath); Result := UserPath; end; //Write maze to text file Procedure WriteMaze(Const MazeToWrite: TMaze; Const StartPos, EndPos: TPos; const FileHand: TextFile); Var PrintMazeY, PrintMazeX: Integer; begin // Displaying the maze visualization For PrintMazeX := 0 to 2 * Length(MazeToWrite[0]) + 1 do Write(FileHand, '#'); Writeln(FileHand); For PrintMazeY := 0 to Length(MazeToWrite) - 1 do Begin Write(FileHand, '#'); For PrintMazeX := 0 to Length(MazeToWrite[0]) - 1 do Begin { Determine what type the cell belongs to Display the corresponding symbol } If (PrintMazeY = StartPos.PosY) and (PrintMazeX = StartPos.PosX) then Write(FileHand, #149, ' ') else If MazeToWrite[PrintMazeY, PrintMazeX] = Wall then Write(FileHand, '##') else If (PrintMazeY = EndPos.PosY) and (PrintMazeX = EndPos.PosX) then Write(FileHand, ' o') else Write(FileHand, ' '); End; Writeln(FileHand, '#'); End; For PrintMazeX := 0 to 2 * Length(MazeToWrite[0]) + 1 do Write(FileHand, '#'); end; //Write maze to text file Procedure SaveMazeToFile(Const MazeToSave: TMaze; const MazeStat: TMazeStat); var F: TextFile; NewFileName, NewFileName2: string; begin //Path := GetAppDataPath+ '\' + TextFileDir; CreateDir(TextFileDir); //Generate file name DateTimeToString(NewFileName, 'ddmmyy/hhnnss', Now); NewFileName2 := MazeStat.FileName + '_'+ NewFileName; //Save AssignFile(F, TextFileDir + NewFileName2 + '.txt'); Rewrite(F); WriteMaze(MazeToSave, MazeStat.StartPoint, MazeStat.EndPoint, F); CloseFile(F); end; //Save to Typed File Procedure SaveMazeToTypeFile(Const MazeStat: TMazeStat; const FileAddr: String); var F: File of TMazeStat; Path: String; begin Path := GetAppDataPath + FileAddr; try AssignFile(F, Path); Reset(F) except Rewrite(F); end; {if FileExists(FileAddr) then Reset(F) else Rewrite(F); } Seek(F, FileSize(F)); Write(F, MazeStat); CloseFile(F); end; //Get FileSize Function GetRecordsAmount(const FileAddr: String): Integer; var F: File of TMazeStat; Path: String; begin Path := GetAppDataPath + FileAddr; if not FileExists(Path) then begin Result := 0; Exit; end; AssignFile(F, Path); Reset(F); Result := FileSize(F); CloseFile(F); end; //Get Record with number Function ReadFromTypeFile(const RecordToRead: Integer; const FileAddr: string): TMazeStat; var F: File of TMazeStat; Path: String; begin Path := GetAppDataPath + FileAddr; if not FileExists(Path) then Exit; AssignFile(F, Path); Reset(F); Seek(F, RecordToRead-1); Read(F, Result); CloseFile(F); end; //Delete all records in type file Procedure ClearTypeFile(const FileAddr: String); var F: File of TMazeStat; Path: String; begin Path := GetAppDataPath + FileAddr; AssignFile(F, Path); Rewrite(F); CloseFile(F); end; //Delete record with number procedure DeleteRecord(const RecordToDel: Integer; const FileAddr: String); var F: File of TMazeStat; I: Integer; Buff: TMazeStat; Path: String; begin Path := GetAppDataPath + FileAddr; if (RecordToDel > GetRecordsAmount(FileAddr)) or (not FileExists(Path)) then Exit; AssignFile(F, Path); Reset(F); Seek(F,RecordToDel-1); //Shift all records for i := RecordToDel-1 to FileSize(F)-2 do begin seek(f,i+1); read(f,Buff); seek(f,i); write(f,Buff); end; Seek(F, FileSize(F)-1); Truncate(F); CloseFile(F); end; end.
unit untTypes; interface type { TIntParam } TIntParam = record Name: string; Value: Integer; end; const CashRegisterName: array[0..$FC] of string = ( {0} 'продаж в 1 отдел в чеке', 'покупок в 1 отдел в чеке', 'возврата продаж в 1 отдел в чеке', 'возврата покупок в 1 отдел в чеке', 'продаж в 2 отдел в чеке', 'покупок в 2 отдел в чеке', 'возврата продаж в 2 отдел в чеке', 'возврата покупок в 2 отдел в чеке', 'продаж в 3 отдел в чеке', 'покупок в 3 отдел в чеке', {0A} 'возврата продаж в 3 отдел в чеке', 'возврата покупок в 3 отдел в чеке', 'продаж в 4 отдел в чеке', 'покупок в 4 отдел в чеке', 'возврата продаж в 4 отдел в чеке', 'возврата покупок в 4 отдел в чеке', {10} 'продаж в 5 отдел в чеке', 'покупок в 5 отдел в чеке', 'возврата продаж в 5 отдел в чеке', 'возврата покупок в 5 отдел в чеке', 'продаж в 6 отдел в чеке', 'покупок в 6 отдел в чеке', 'возврата продаж в 6 отдел в чеке', 'возврата покупок в 6 отдел в чеке', 'продаж в 7 отдел в чеке', 'покупок в 7 отдел в чеке', {1A} 'возврата продаж в 7 отдел в чеке', 'возврата покупок в 7 отдел в чеке', 'продаж в 8 отдел в чеке', 'покупок в 8 отдел в чеке', 'возврата продаж в 8 отдел в чеке', 'возврата покупок в 8 отдел в чеке', {20} 'продаж в 9 отдел в чеке', 'покупок в 9 отдел в чеке', 'возврата продаж в 9 отдел в чеке', 'возврата покупок в 9 отдел в чеке', 'продаж в 10 отдел в чеке', 'покупок в 10 отдел в чеке', 'возврата продаж в 10 отдел в чеке', 'возврата покупок в 10 отдел в чеке', 'продаж в 11 отдел в чеке', 'покупок в 11 отдел в чеке', {2A} 'возврата продаж в 11 отдел в чеке', 'возврата покупок в 11 отдел в чеке', 'продаж в 12 отдел в чеке', 'покупок в 12 отдел в чеке', 'возврата продаж в 12 отдел в чеке', 'возврата покупок в 12 отдел в чеке', {30} 'продаж в 13 отдел в чеке', 'покупок в 13 отдел в чеке', 'возврата продаж в 13 отдел в чеке', 'возврата покупок в 13 отдел в чеке', 'продаж в 14 отдел в чеке', 'покупок в 14 отдел в чеке', 'возврата продаж в 14 отдел в чеке', 'возврата покупок в 14 отдел в чеке', 'продаж в 15 отдел в чеке', 'покупок в 15 отдел в чеке', {3A} 'возврата продаж в 15 отдел в чеке', 'возврата покупок в 15 отдел в чеке', 'продаж в 16 отдел в чеке', 'покупок в 16 отдел в чеке', 'возврата продаж в 16 отдел в чеке', 'возврата покупок в 16 отдел в чеке', {40} 'скидок с продаж в чеке', 'скидок с покупок в чеке', 'скидок с возврата продаж в чеке', 'скидок с возврата покупок в чеке', 'надбавок на продажи в чеке', 'надбавок на покупок в чеке', 'надбавок на возврата продаж в чеке', 'надбавок на возврата покупок в чеке', 'оплат продаж наличными в чеке', 'оплат покупок наличными в чеке', {4A} 'оплат возврата продаж наличными в чеке', 'оплат возврата покупок наличными в чеке', 'оплат продаж видом оплаты 2 в чеке', 'оплат покупок видом оплаты 2 в чеке', 'оплат возврата продаж видом оплаты 2 в чеке', 'оплат возврата покупок видом оплаты 2 в чеке', {50} 'оплат продаж видом оплаты 3 в чеке', 'оплат покупок видом оплаты 3 в чеке', 'оплат возврата продаж видом оплаты 3 в чеке', 'оплат возврата покупок видом оплаты 3 в чеке', 'оплат продаж видом оплаты 4 в чеке', 'оплат покупок видом оплаты 4 в чеке', 'оплат возврата продаж видом оплаты 4 в чеке', 'оплат возврата покупок видом оплаты 4 в чеке', 'налогу А с продаж в чеке', 'налогу А с покупок в чеке', {5A} 'налогу А с возврата продаж в чеке', 'налогу А с возврата покупок в чеке', 'налогу Б с продаж в чеке', 'налогу Б с покупок в чеке', 'налогу Б с возврата продаж в чеке', 'налогу Б с возврата покупок в чеке', {60} 'налогу В с продаж в чеке', 'налогу В с покупок в чеке', 'налогу В с возврата продаж в чеке', 'налогу В с возврата покупок в чеке', 'налогу Г с продаж в чеке', 'налогу Г с покупок в чеке', 'налогу Г с возврата продаж в чеке', 'налогу Г с возврата покупок в чеке', 'налогу А с продаж в чеке', 'налогу А с покупок в чеке', {6A} 'налогу А с возврата продаж в чеке', 'налогу А с возврата покупок в чеке', 'налогу Б с продаж в чеке', 'налогу Б с покупок в чеке', 'налогу Б с возврата продаж в чеке', 'налогу Б с возврата покупок в чеке', {70} 'налогу В с продаж в чеке', 'налогу В с покупок в чеке', 'налогу В с возврата продаж в чеке', 'налогу В с возврата покупок в чеке', 'налогу Г с продаж в чеке', 'налогу Г с покупок в чеке', 'налогу Г с возврата продаж в чеке', 'налогу Г с возврата покупок в чеке', 'в кассе на момент закрытия чека', 'продаж в 1 отдел в смене', {7A} 'покупок в 1 отдел в смене', 'возврата продаж в 1 отдел в смене', 'возврата покупок в 1 отдел в смене', 'продаж в 2 отдел в смене', 'покупок в 2 отдел в смене', 'возврата продаж в 2 отдел в смене', {80} 'возврата покупок в 2 отдел в смене', 'продаж в 3 отдел в смене', 'покупок в 3 отдел в смене', 'возврата продаж в 3 отдел в смене', 'возврата покупок в 3 отдел в смене', 'продаж в 4 отдел в смене', 'покупок в 4 отдел в смене', 'возврата продаж в 4 отдел в смене', 'возврата покупок в 4 отдел в смене', 'продаж в 5 отдел в смене', {8A} 'покупок в 5 отдел в смене', 'возврата продаж в 5 отдел в смене', 'возврата покупок в 5 отдел в смене', 'продаж в 6 отдел в смене', 'покупок в 6 отдел в смене', 'возврата продаж в 6 отдел в смене', {90} 'возврата покупок в 6 отдел в смене', 'продаж в 7 отдел в смене', 'покупок в 7 отдел в смене', 'возврата продаж в 7 отдел в смене', 'возврата покупок в 7 отдел в смене', 'продаж в 8 отдел в смене', 'покупок в 8 отдел в смене', 'возврата продаж в 8 отдел в смене', 'возврата покупок в 8 отдел в смене', 'продаж в 9 отдел в смене', {9A} 'покупок в 9 отдел в смене', 'возврата продаж в 9 отдел в смене', 'возврата покупок в 9 отдел в смене', 'продаж в 10 отдел в смене', 'покупок в 10 отдел в смене', 'возврата продаж в 10 отдел в смене', {A0} 'возврата покупок в 10 отдел в смене', 'продаж в 11 отдел в смене', 'покупок в 11 отдел в смене', 'возврата продаж в 11 отдел в смене', 'возврата покупок в 11 отдел в смене', 'продаж в 12 отдел в смене', 'покупок в 12 отдел в смене', 'возврата продаж в 12 отдел в смене', 'возврата покупок в 12 отдел в смене', 'продаж в 13 отдел в чеке', {AA} 'покупок в 13 отдел в чеке', 'возврата продаж в 13 отдел в чеке', 'возврата покупок в 13 отдел в чеке', 'продаж в 14 отдел в смене', 'покупок в 14 отдел в смене', 'возврата продаж в 14 отдел в смене', {B0} 'возврата покупок в 14 отдел в смене', 'продаж в 15 отдел в смене', 'покупок в 15 отдел в смене', 'возврата продаж в 15 отдел в смене', 'возврата покупок в 15 отдел в смене', 'продаж в 16 отдел в смене', 'покупок в 16 отдел в смене', 'возврата продаж в 16 отдел в смене', 'возврата покупок в 16 отдел в смене', 'скидок с продаж в смене', {BA} 'скидок с покупок в смене', 'скидок с возврата продаж в смене', 'скидок с возврата покупок в смене', 'надбавок на продажи в смене', 'надбавок на покупок в смене', 'надбавок на возврата продаж в смене', {C0} 'надбавок на возврата покупок в смене', 'оплат продаж наличными в смене', 'оплат покупок наличными в смене', 'оплат возврата продаж наличными в смене', 'оплат возврата покупок наличными в смене', 'оплат продаж видом оплаты 2 в смене', 'оплат покупок видом оплаты 2 в смене', 'оплат возврата продаж видом оплаты 2 в смене', 'оплат возврата покупок видом оплаты 2 в смене', 'оплат продаж видом оплаты 3 в смене', {CA} 'оплат покупок видом оплаты 3 в смене', 'оплат возврата продаж видом оплаты 3 в смене', 'оплат возврата покупок видом оплаты 3 в смене', 'оплат продаж видом оплаты 4 в смене', 'оплат покупок видом оплаты 4 в смене', 'оплат возврата продаж видом оплаты 4 в смене', {D0} 'оплат возврата покупок видом оплаты 4 в смене', 'налогу А с продаж в смене', 'налогу А с покупок в смене', 'налогу А с возврата продаж в смене', 'налогу А с возврата покупок в смене', 'налогу Б с продаж в смене', 'налогу Б с покупок в смене', 'налогу Б с возврата продаж в смене', 'налогу Б с возврата покупок в смене', 'налогу В с продаж в смене', {DA} 'налогу В с покупок в смене', 'налогу В с возврата продаж в смене', 'налогу В с возврата покупок в смене', 'налогу Г с продаж в смене', 'налогу Г с покупок в смене', 'налогу Г с возврата продаж в смене', {E0} 'налогу Г с возврата покупок в смене', 'налогу А с продаж в смене', 'налогу А с покупок в смене', 'налогу А с возврата продаж в смене', 'налогу А с возврата покупок в смене', 'налогу Б с продаж в смене', 'налогу Б с покупок в смене', 'налогу Б с возврата продаж в смене', 'налогу Б с возврата покупок в смене', 'налогу В с продаж в смене', {EA} 'налогу В с покупок в смене', 'налогу В с возврата продаж в смене', 'налогу В с возврата покупок в смене', 'налогу Г с продаж в смене', 'налогу Г с покупок в смене', 'налогу Г с возврата продаж в смене', {F0} 'налогу Г с возврата покупок в смене', 'наличности в кассе', 'внесений за смену', 'выплат за смену', 'до фискализации', 'продаж в смене из ЭКЛЗ', 'покупок в смене из ЭКЛЗ', 'возвратов продаж в смене из ЭКЛЗ', 'возвратов покупок в смене из ЭКЛЗ', {F9} 'продаж в смене', 'покупок в смене', 'возвратов продаж в смене', 'возвратов покупок в смене'); const OperationRegisterName: array[0..$B9] of string = ( {0} 'продаж в 1 отдел в чеке', 'покупок в 1 отдел в чеке', 'возврата продаж в 1 отдел в чеке', 'возврата покупок в 1 отдел в чеке', 'продаж в 2 отдел в чеке', 'покупок в 2 отдел в чеке', 'возврата продаж в 2 отдел в чеке', 'возврата покупок в 2 отдел в чеке', 'продаж в 3 отдел в чеке', 'покупок в 3 отдел в чеке', {0A} 'возврата продаж в 3 отдел в чеке', 'возврата покупок в 3 отдел в чеке', 'продаж в 4 отдел в чеке', 'покупок в 4 отдел в чеке', 'возврата продаж в 4 отдел в чеке', 'возврата покупок в 4 отдел в чеке', {10} 'продаж в 5 отдел в чеке', 'покупок в 5 отдел в чеке', 'возврата продаж в 5 отдел в чеке', 'возврата покупок в 5 отдел в чеке', 'продаж в 6 отдел в чеке', 'покупок в 6 отдел в чеке', 'возврата продаж в 6 отдел в чеке', 'возврата покупок в 6 отдел в чеке', 'продаж в 7 отдел в чеке', 'покупок в 7 отдел в чеке', {1A} 'возврата продаж в 7 отдел в чеке', 'возврата покупок в 7 отдел в чеке', 'продаж в 8 отдел в чеке', 'покупок в 8 отдел в чеке', 'возврата продаж в 8 отдел в чеке', 'возврата покупок в 8 отдел в чеке', {20} 'продаж в 9 отдел в чеке', 'покупок в 9 отдел в чеке', 'возврата продаж в 9 отдел в чеке', 'возврата покупок в 9 отдел в чеке', 'продаж в 10 отдел в чеке', 'покупок в 10 отдел в чеке', 'возврата продаж в 10 отдел в чеке', 'возврата покупок в 10 отдел в чеке', 'продаж в 11 отдел в чеке', 'покупок в 11 отдел в чеке', {2A} 'возврата продаж в 11 отдел в чеке', 'возврата покупок в 11 отдел в чеке', 'продаж в 12 отдел в чеке', 'покупок в 12 отдел в чеке', 'возврата продаж в 12 отдел в чеке', 'возврата покупок в 12 отдел в чеке', {30} 'продаж в 13 отдел в чеке', 'покупок в 13 отдел в чеке', 'возврата продаж в 13 отдел в чеке', 'возврата покупок в 13 отдел в чеке', 'продаж в 14 отдел в чеке', 'покупок в 14 отдел в чеке', 'возврата продаж в 14 отдел в чеке', 'возврата покупок в 14 отдел в чеке', 'продаж в 15 отдел в чеке', 'покупок в 15 отдел в чеке', {3A} 'возврата продаж в 15 отдел в чеке', 'возврата покупок в 15 отдел в чеке', 'продаж в 16 отдел в чеке', 'покупок в 16 отдел в чеке', 'возврата продаж в 16 отдел в чеке', 'возврата покупок в 16 отдел в чеке', {40} 'скидок с продаж в чеке', 'скидок с покупок в чеке', 'скидок с возврата продаж в чеке', 'скидок с возврата покупок в чеке', 'надбавок на продажи в чеке', 'надбавок на покупок в чеке', 'надбавок на возврата продаж в чеке', 'надбавок на возврата покупок в чеке', 'продаж в 1 отдел в смене', 'покупок в 1 отдел в смене', {4A} 'возврата продаж в 1 отдел в смене', 'возврата покупок в 1 отдел в смене', 'продаж в 2 отдел в смене', 'покупок в 2 отдел в смене', 'возврата продаж в 2 отдел в смене', 'возврата покупок в 2 отдел в смене', {50} 'продаж в 3 отдел в смене', 'покупок в 3 отдел в смене', 'возврата продаж в 3 отдел в смене', 'возврата покупок в 3 отдел в смене', 'продаж в 4 отдел в смене', 'покупок в 4 отдел в смене', 'возврата продаж в 4 отдел в смене', 'возврата покупок в 4 отдел в смене', 'продаж в 5 отдел в смене', 'покупок в 5 отдел в смене', {5A} 'возврата продаж в 5 отдел в смене', 'возврата покупок в 5 отдел в смене', 'продаж в 6 отдел в смене', 'покупок в 6 отдел в смене', 'возврата продаж в 6 отдел в смене', 'возврата покупок в 6 отдел в смене', {60} 'продаж в 7 отдел в смене', 'покупок в 7 отдел в смене', 'возврата продаж в 7 отдел в смене', 'возврата покупок в 7 отдел в смене', 'продаж в 8 отдел в смене', 'покупок в 8 отдел в смене', 'возврата продаж в 8 отдел в смене', 'возврата покупок в 8 отдел в смене', 'продаж в 9 отдел в смене', 'покупок в 9 отдел в смене', {6A} 'возврата продаж в 9 отдел в смене', 'возврата покупок в 9 отдел в смене', 'продаж в 10 отдел в смене', 'покупок в 10 отдел в смене', 'возврата продаж в 10 отдел в смене', 'возврата покупок в 10 отдел в смене', {70} 'продаж в 11 отдел в смене', 'покупок в 11 отдел в смене', 'возврата продаж в 11 отдел в смене', 'возврата покупок в 11 отдел в смене', 'продаж в 12 отдел в смене', 'покупок в 12 отдел в смене', 'возврата продаж в 12 отдел в смене', 'возврата покупок в 12 отдел в смене', 'продаж в 13 отдел в чеке', 'покупок в 13 отдел в чеке', {7A} 'возврата продаж в 13 отдел в чеке', 'возврата покупок в 13 отдел в чеке', 'продаж в 14 отдел в смене', 'покупок в 14 отдел в смене', 'возврата продаж в 14 отдел в смене', 'возврата покупок в 14 отдел в смене', {80} 'продаж в 15 отдел в смене', 'покупок в 15 отдел в смене', 'возврата продаж в 15 отдел в смене', 'возврата покупок в 15 отдел в смене', 'продаж в 16 отдел в смене', 'покупок в 16 отдел в смене', 'возврата продаж в 16 отдел в смене', 'возврата покупок в 16 отдел в смене', 'скидок с продаж в смене', 'скидок с покупок в смене', {8A} 'скидок с возврата продаж в смене', 'скидок с возврата покупок в смене', 'надбавок на продажи в смене', 'надбавок на покупки в смене', 'надбавок на возвраты продаж в смене', 'надбавок на возвраты покупок в смене', {90} 'чеков продаж в смене', 'чеков покупок в смене', 'чеков возврата продаж в смене', 'чеков возврата покупок в смене', 'чека продаж', 'чека покупок', 'чека возврата продаж', 'чека возврата покупок', 'документа', 'внесений денежных сумм за смену', {9A} 'выплат денежных сумм за смену', 'внесения денежных сумм', 'выплаты денежных сумм', 'отмененных документов за смену', 'сменного отчета без гашения', 'сменного отчета с гашением до фискализации', {A0} 'общего гашения', 'полного фискального отчета', 'сокращенного фискального отчета', 'тестового прогона', 'снятия показаний операционных регистров', 'отчетов по секциям', 'аннулирований', 'запусков теста самодиагностики', 'активизаций ЭКЛЗ', 'итогам активизации ЭКЛЗ', ' номеру КПК из ЭКЛЗ', 'контрольной ленте из ЭКЛЗ', 'датам из ЭКЛЗ', 'сменам из ЭКЛЗ', 'итогам смен из ЭКЛЗ', 'датам в отделе из ЭКЛЗ', {B0} 'сменам в отделе из ЭКЛЗ', 'закрытий архивов ЭКЛЗ', 'налогам', {B3} 'продажам', 'покупкам', 'возвратам продаж', 'возвратам покупок', {B7} 'в день', 'всего', {B9} 'документа'); implementation end.
{$I ATViewerOptions.inc} unit ATxUtils; interface uses Windows, Graphics, Controls, Forms; function IsWindowsVista: Boolean; procedure SSetFont(AFont: TFont; S: string); function SFontToString(AFont: TFont): string; procedure FixFormFont(AFont: TFont); procedure FixImageList32Bit(ImageList: TImageList); procedure SetFormStyle(Form: TForm; Value: Boolean); function GetFormOnTop(Form: TForm): Boolean; procedure SetFormOnTop(Form: TForm; Value: Boolean); //function FGetAppDataPath: WideString; //%AppData% path procedure SSetEnv(const Name, Value: WideString); //Set env var function IsFilenameRemote(const fn: string): Boolean; //File on Network disk ( \\server\share\... ) function IsFilenameFixed(const fn: string): Boolean; //File on fixed disk (C: D:..) procedure SDecodeSearchW(var S: WideString); //Prepare string for search: replace \n \r \0.. function FFileWriteStringA(const AFileName: WideString; const S: AnsiString): Boolean; function FFileWriteStringW(const AFileName: WideString; const S: WideString): Boolean; function FNumberName(const FN: WideString): WideString; //Generate number name by mask 'File%d.ext' function FTempText: WideString; function FTempClip(const Ext: WideString): WideString; //Clipboard file name (in %Temp%) function FPasteToFile: WideString; //Pastes clipboard to FClipName function FSearchDir(const sname, sdir: string; var fn: string): boolean; const WM_XBUTTONDOWN = $020B; WM_XBUTTONUP = $020C; WM_XBUTTONDBLCLK = $020D; function FormatFileSize(const Size: Int64): string; function FormatFileTime(const ft: TFileTime): string; implementation uses SysUtils, Classes, Consts, CommCtrl, ATxFProc, ATxSProc, TntClasses, Clipbrd, TntClipbrd, {$ifdef PNG} PngImage, {$endif} ATViewerMsg, ATxMsgProc; //-------------------------------------------------------- function IsWindowsVista: Boolean; begin Result:= (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 6); end; //-------------------------------------------------------- { Windows XP icons in Delphi I want to display Windows XP compatible icons on tool bars in my Delphi application. How do I do that? http://discuss.joelonsoftware.com/default.asp?joel.3.8105.4 } procedure FixImageList32Bit(ImageList: TImageList); const Mask: array[Boolean] of Longint = (0, ILC_MASK); var TempList: TImageList; begin if (Win32Platform = VER_PLATFORM_WIN32_NT) and Assigned(ImageList) then begin TempList := TImageList.Create(nil); try TempList.Assign(ImageList); with ImageList do begin Handle := ImageList_Create(Width, Height, ILC_COLOR32 or Mask[Masked], 0, AllocBy); if not HandleAllocated then raise EInvalidOperation.Create(SInvalidImageList); end; Imagelist.AddImages(TempList); finally FreeAndNil(TempList); end; end; end; //-------------------------------------------------------- // Creating Windows Vista Ready Applications with Delphi // http://www.installationexcellence.com/articles/VistaWithDelphi/Index.html procedure FixFormFont(AFont: TFont); var LogFont: TLogFont; begin if SystemParametersInfo(SPI_GETICONTITLELOGFONT, SizeOf(LogFont), @LogFont, 0) then AFont.Handle := CreateFontIndirect(LogFont) else AFont.Handle := GetStockObject(DEFAULT_GUI_FONT); end; //-------------------------------------------------------- type TSHGetSpecialFolderPathA = function(hwndOwner: HWND; lpszPath: PAnsiChar; nFolder: Integer; fCreate: BOOL): BOOL; stdcall; TSHGetSpecialFolderPathW = function(hwndOwner: HWND; lpszPath: PWideChar; nFolder: Integer; fCreate: BOOL): BOOL; stdcall; (* function FGetAppDataPathA: string; const CSIDL_APPDATA = $001a; var Handle: THandle; Func: TSHGetSpecialFolderPathA; Buffer: array[0 .. MAX_PATH - 1] of AnsiChar; begin Result := ''; Handle := GetModuleHandle(kernel32); if Handle <> 0 then begin Func := GetProcAddress(Handle, 'SHGetSpecialFolderPathA'); if Assigned(Func) then begin if Func(0, Buffer, CSIDL_APPDATA, True) then Result := AnsiString(Buffer); end; end; if Result = '' then Result := SExpandVars('%AppData%'); end; function FGetAppDataPath: WideString; begin Result:= FGetAppDataPathA; end; *) //-------------------------------------------------------- function SExpandVars(const S: WideString): WideString; const BufSize = 4 * 1024; var BufferA: array[0 .. BufSize - 1] of AnsiChar; BufferW: array[0 .. BufSize - 1] of WideChar; begin if Win32Platform = VER_PLATFORM_WIN32_NT then begin FillChar(BufferW, SizeOf(BufferW), 0); ExpandEnvironmentStringsW(PWChar(S), BufferW, BufSize); Result := WideString(BufferW); end else begin FillChar(BufferA, SizeOf(BufferA), 0); ExpandEnvironmentStringsA(PAnsiChar(AnsiString(S)), BufferA, BufSize); Result := AnsiString(BufferA); end; end; procedure SSetEnv(const Name, Value: WideString); begin if Win32Platform = VER_PLATFORM_WIN32_NT then SetEnvironmentVariableW(PWChar(Name), PWChar(Value)) else SetEnvironmentVariableA(PAnsiChar(AnsiString(Name)), PAnsiChar(AnsiString(Value))); end; //-------------------------------------------------------- procedure SDecodeSearchW(var S: WideString); const DecodeRec: array[1..5] of TStringDecodeRecW = ((SFrom: '\r'; STo: #13), (SFrom: '\n'; STo: #10), (SFrom: '\t'; STo: #9), (SFrom: '\\'; STo: '\'), (SFrom: '\0'; STo: #0)); begin S := SDecodeW(S, DecodeRec); end; //-------------------------------------------------------- function IsFilenameRemote(const fn: string): Boolean; begin Result := Copy(fn, 1, 2) = '\\'; end; function IsFilenameFixed(const fn: string): Boolean; var Dir: string; begin Result := false; if Pos(':\', fn) = 2 then begin Dir:= Copy(fn, 1, 3); Result:= GetDriveType(PChar(Dir)) = DRIVE_FIXED; end; end; //-------------------------------------------------------- procedure SetFormStyle(Form: TForm; Value: Boolean); const cNormalStyles = WS_BORDER or WS_DLGFRAME or WS_CAPTION or WS_THICKFRAME; begin with Form do begin if Value then SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) or cNormalStyles) else SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) and not cNormalStyles); SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_NOZORDER or SWP_NOSIZE or SWP_NOMOVE or SWP_FRAMECHANGED); end; end; function GetFormOnTop(Form: TForm): Boolean; begin with Form do Result:= (GetWindowLong(Handle, GWL_EXSTYLE) and WS_EX_TOPMOST) <> 0; end; procedure SetFormOnTop(Form: TForm; Value: Boolean); const cTopMost: array[Boolean] of DWORD = (HWND_NOTOPMOST, HWND_TOPMOST); begin with Form do SetWindowPos(Handle, cTopMost[Value], 0, 0, 0, 0, SWP_NOSIZE or SWP_NOMOVE or SWP_NOOWNERZORDER); end; //-------------------------------------------------------- function FFileWriteStringA(const AFileName: WideString; const S: AnsiString): Boolean; begin if S = '' then begin Result := False; Exit end; try with TTntFileStream.Create(AFileName, fmCreate) do try WriteBuffer(S[1], Length(S)); Result := True; finally Free; end; except Result := False; end; end; function FFileWriteStringW(const AFileName: WideString; const S: WideString): Boolean; const Sig: WideChar = #$FEFF; begin if S = '' then begin Result := False; Exit end; try with TTntFileStream.Create(AFileName, fmCreate) do try if S[1] <> Sig then WriteBuffer(Sig, 2); WriteBuffer(S[1], Length(S) * 2); Result := True; finally Free; end; except Result := False; end; end; //FN must contain '%d' mask function FNumberName(const FN: WideString): WideString; var N: Integer; begin N := 0; repeat Inc(N); Result := SFormatWD(FN, [N]); until not IsFileExist(Result); end; function FTempText: WideString; begin Result := FTempPath + 'UV_conv.txt'; end; function FTempClip(const Ext: WideString): WideString; begin Result := FTempPath + 'Clipboard' + Ext; end; function FPasteToFile: WideString; var b: TBitmap; {$ifdef PNG} p: TPngObject; {$endif} //m: TMetafile; SA: AnsiString; SW: WideString; begin Result := ''; try if Clipboard.HasFormat(CF_BITMAP) then {$ifdef PNG} begin b := TBitmap.Create; p := TPngObject.Create; try b.Assign(Clipboard); p.Assign(b); Result := FTempClip('.png'); p.SaveToFile(Result); finally b.Free; p.Free; end; end {$else} begin b := TBitmap.Create; try b.Assign(Clipboard); Result := FTempClip('.bmp'); b.SaveToFile(Result); finally b.Free; end; end {$endif} (* else if Clipboard.HasFormat(CF_METAFILEPICT) then begin m := TMetafile.Create; try m.Assign(Clipboard); Result := FTempClip('.wmf'); m.SaveToFile(Result); finally m.Free; end; end *) else if Clipboard.HasFormat(CF_UNICODETEXT) then begin SW := TntClipboard.AsWideText; Result := FTempClip('.txt'); if not FFileWriteStringW(Result, SW) then raise Exception.Create(''); end else if Clipboard.HasFormat(CF_TEXT) then begin SA := AnsiString(Clipboard.AsText); Result := FTempClip('.txt'); if not FFileWriteStringA(Result, SA) then raise Exception.Create(''); end else MsgWarning(MsgString(127)); except MsgError(MsgString(156)); Result := ''; end; end; //---------------------------------------- // 'Name,Size,Color,Style,Charset' --> Font procedure SSetFont(AFont: TFont; S: string); function Item: string; var N: Integer; begin N := Pos(',', S); if N = 0 then N := MaxInt; Result := Copy(S, 1, N - 1); Delete(S, 1, N); end; begin Assert(Assigned(AFont), 'Font not assigned'); with AFont do begin Name := Item; Size := StrToIntDef(Item, Size); Color := StrToIntDef(Item, Color); Style := TFontStyles(byte(StrToIntDef(Item, byte(Style)))); Charset := TFontCharset(StrToIntDef(Item, Charset)); end; end; function SFontToString(AFont: TFont): string; begin Assert(Assigned(AFont), 'Font not assigned'); with AFont do Result := Format('%s,%d,%d,%d,%d', [Name, Size, Color, byte(Style), integer(CharSet)]); end; //------------------------------------------------- function FormatFileSize(const Size: Int64): string; const Kb = 1024; Mb = Kb*Kb; Gb = Kb*Kb*Kb; begin if Size >= Gb then Result:= Format(MsgString(304), [Size div Gb]) else if Size >= Mb then Result:= Format(MsgString(303), [Size div Mb]) else if Size >= Kb then Result:= Format(MsgString(302), [Size div Kb]) else Result:= Format(MsgString(301), [Size]); end; function FormatFileTime(const ft: TFileTime): string; var lt: TFileTime; st: TSystemTime; Date, Time: string; begin Result:= ''; if FileTimeToLocalFileTime(ft, lt) and FileTimeToSystemTime(lt, st) then begin Date:= Format('%2.2d%s%2.2d%s%d', [st.wDay, DateSeparator, st.wMonth, DateSeparator, st.wYear]); Time:= Format('%2.2d%s%2.2d%s%2.2d', [st.wHour, TimeSeparator, st.wMinute, TimeSeparator, st.wSecond]); Result:= Date + ' ' + Time; end; end; //---------------------------------------- function FSearchDir(const sname, sdir: string; var fn: string): boolean; var h: THandle; fd: TWin32FindData; begin if not IsDirExist(sdir) then begin Result:= false; Exit end; h:= FindFirstFile(PChar(sdir+'\'+sname), fd); Result:= h<>INVALID_HANDLE_VALUE; if Result then begin fn:= sdir+'\'+fd.cFileName; Windows.FindClose(h); Exit end; h:= FindFirstFile(PChar(sdir+'\*.*'), fd); if h=INVALID_HANDLE_VALUE then Exit; repeat if ((fd.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY)<>0) and (fd.cFileName[0]<>'.') then begin Result:= FSearchDir(sname, sdir+'\'+fd.cFileName, fn); if Result then Break; end; until not FindNextFile(h, fd); Windows.FindClose(h); end; //----------------------- initialization finalization FDelete(FTempClip('.txt')); FDelete(FTempText); end.
unit InstancePool; interface uses classes, SysUtils; type List = TList; TInstanceMemoryPool = class private FInstanceSize: Integer; FList: Pointer; FCapacity, FCount: integer; procedure SetCapacity(NewCapacity: Integer); public constructor Create(instanceSize: Integer); destructor Destroy; override; end; implementation { TInstanceMemoryPool } constructor TInstanceMemoryPool.Create(instanceSize: Integer); begin inherited Create(); FInstanceSize := instanceSize; end; destructor TInstanceMemoryPool.Destroy; begin SetCapacity(0); inherited; end; procedure TInstanceMemoryPool.SetCapacity(NewCapacity: Integer); begin if (NewCapacity < FCount) or (NewCapacity > MaxListSize) then raise Exception.Create('TInstanceMemoryPool.SetCapacity():'); if NewCapacity <> FCapacity then begin ReallocMem(FList, NewCapacity * SizeOf(Pointer)); FCapacity := NewCapacity; end; end; end.
unit uTestSqlite; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,SQLiteTable3, ExtCtrls, jpeg; type TForm1 = class(TForm) btnTest: TButton; memNotes: TMemo; Label1: TLabel; Label2: TLabel; ebName: TEdit; Label3: TLabel; ebNumber: TEdit; Label4: TLabel; ebID: TEdit; Image1: TImage; btnLoadImage: TButton; btnDisplayImage: TButton; procedure btnTestClick(Sender: TObject); procedure btnLoadImageClick(Sender: TObject); procedure btnDisplayImageClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnTestClick(Sender: TObject); var slDBpath: string; sldb: TSQLiteDatabase; sltb: TSQLIteTable; sSQL: string; Notes: String; begin slDBPath := ExtractFilepath(application.exename) + 'test.db'; sldb := TSQLiteDatabase.Create(slDBPath); try if sldb.TableExists('testTable') then begin sSQL := 'DROP TABLE testtable'; sldb.execsql(sSQL); end; sSQL := 'CREATE TABLE testtable ([ID] INTEGER PRIMARY KEY,[OtherID] INTEGER NULL,'; sSQL := sSQL + '[Name] VARCHAR (255),[Number] FLOAT, [notes] BLOB, [picture] BLOB COLLATE NOCASE);'; sldb.execsql(sSQL); sldb.execsql('CREATE INDEX TestTableName ON [testtable]([Name]);'); //begin a transaction sldb.BeginTransaction; sSQL := 'INSERT INTO testtable(Name,OtherID,Number,Notes) VALUES ("何かの名前",4,587.6594,"日本語でもokです");'; //do the insert sldb.ExecSQL(sSQL); sSQL := 'INSERT INTO testtable(Name,OtherID,Number,Notes) VALUES ("Another Name",12,4758.3265,"More notes");'; //do the insert sldb.ExecSQL(sSQL); //end the transaction sldb.Commit; //query the data sltb := slDb.GetTable('SELECT * FROM testtable'); try if sltb.Count > 0 then begin //display first row ebName.Text := sltb.FieldAsString(sltb.FieldIndex['Name']); ebID.Text := inttostr(sltb.FieldAsInteger(sltb.FieldIndex['ID'])); ebNumber.Text := floattostr( sltb.FieldAsDouble(sltb.FieldIndex['Number'])); Notes := sltb.FieldAsBlobText(sltb.FieldIndex['Notes']); memNotes.Text := notes; end; finally sltb.Free; end; finally sldb.Free; end; end; procedure TForm1.btnLoadImageClick(Sender: TObject); var slDBpath: string; sldb: TSQLiteDatabase; sltb: TSQLIteTable; iID: integer; fs: TFileStream; begin slDBPath := ExtractFilepath(application.exename) + 'test.db'; if not FileExists(slDBPath) then begin MessageDLg('Test.db does not exist. Click Test Sqlite 3 to create it.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try //get an ID //query the data sltb := slDb.GetTable('SELECT ID FROM testtable'); try if sltb.Count = 0 then begin MessageDLg('There are no rows in the database. Click Test Sqlite 3 to insert a row.',mtInformation,[mbOK],0); exit; end; iID := sltb.FieldAsInteger(sltb.FieldIndex['ID']); finally sltb.Free; end; //load an image fs := TFileStream.Create(ExtractFileDir(application.ExeName) + '\sunset.jpg',fmOpenRead); try //insert the image into the db sldb.UpdateBlob('UPDATE testtable set picture = ? WHERE ID = ' + inttostr(iID),fs); finally fs.Free; end; finally sldb.Free; end; end; procedure TForm1.btnDisplayImageClick(Sender: TObject); var slDBpath: string; sldb: TSQLiteDatabase; sltb: TSQLIteTable; iID: integer; ms: TMemoryStream; pic: TJPegImage; begin slDBPath := ExtractFilepath(application.exename) + 'test.db'; if not FileExists(slDBPath) then begin MessageDLg('Test.db does not exist. Click Test Sqlite 3 to create it, then Load image to load an image.',mtInformation,[mbOK],0); exit; end; sldb := TSQLiteDatabase.Create(slDBPath); try //get an ID //query the data sltb := slDb.GetTable('SELECT ID FROM testtable'); try if not sltb.Count = 0 then begin MessageDLg('No rows in the test database. Click Test Sqlite 3 to insert a row, then Load image to load an image.',mtInformation,[mbOK],0); exit; end; iID := sltb.FieldAsInteger(sltb.FieldIndex['ID']); finally sltb.Free; end; sltb := sldb.GetTable('SELECT picture FROM testtable where ID = ' + inttostr(iID)); try ms := sltb.FieldAsBlob(sltb.FieldIndex['picture']); //note that the memory stream is freed when the TSqliteTable is destroyed. if (ms = nil) then begin MessageDLg('No image in the test database. Click Load image to load an image.',mtInformation,[mbOK],0); exit; end; ms.Position := 0; pic := TJPEGImage.Create; pic.LoadFromStream(ms); self.Image1.Picture.Graphic := pic; pic.Free; finally sltb.Free; end; finally sldb.Free; end; end; end.
PROGRAM Ahorcado; USES CRT; CONST INI = 1; ERRORES = 10; TOPE = 40; TYPE TCadena = STRING [TOPE]; TAyuda = ARRAY [INI..ERRORES] OF char; PROCEDURE LeerCadena (VAR c: TCadena); VAR i: integer; BEGIN writeln ('Dame la cadena a ocultar'); readln (c); FOR i:= 1 TO length(c) DO c[i] := UPCASE (c[i]); END; {LeerCadena para poner todos los caracteres en mayusculas} PROCEDURE Ocultar (c: TCadena; VAR p: TCadena); VAR i: integer; BEGIN p := c; FOR i:= 1 TO length(p) DO IF c[i] = ' ' THEN p[i] := ' ' ELSE p[i] := '-'; END; {Ocultar la palabra a adivinar. Respeto los espacios en blanco que pueda haber} PROCEDURE Mostrar (a: TAyuda; cont: integer); VAR i: integer; BEGIN FOR i:= INI TO cont DO write (a[i], ' '); writeln; END; {Mostrar el array de letras erroneas} PROCEDURE Modificar (c: TCadena; l: char; VAR p: TCadena; VAR a: boolean); VAR i: integer; BEGIN a:= FALSE; FOR i:= INI TO length (c) DO IF (c[i] = l) THEN BEGIN a := TRUE; p[i] := l; END; END; {Modificar para introducir las letras acertadas en su lugar} PROCEDURE Jugar; VAR cadena, palabra: TCadena; pistas: TAyuda; letra: char; contador: integer; acierto, victoria: boolean; BEGIN LeerCadena (cadena); CLRSCR; Ocultar (cadena, palabra); contador:= PRED(INI); REPEAT writeln ('Dame una letra'); readln (letra); letra := UPCASE (letra); Modificar (cadena, letra, palabra, acierto); IF NOT acierto THEN BEGIN contador := SUCC (contador); pistas [contador] := letra; writeln ('Vuelve a intentarlo. Tienes ', contador, ' errores'); writeln ('Ya has probado con...'); Mostrar (pistas, contador); END; writeln (palabra); victoria := palabra = cadena; UNTIL (contador = ERRORES) OR (victoria); IF victoria THEN writeln ('Enhorabuena, has ganado') ELSE writeln ('Prueba otra vez. Lo siento, has perdido tras cometer ', contador, ' errores'); END; BEGIN {PP} Jugar; READKEY; END.
program TESTSET3 ( OUTPUT ) ; (********) (*$A+ *) (********) type CHAR32 = array [ 1 .. 32 ] of CHAR ; SYMB = ( SYMB_EOF , SYMB_UNKNOWN , EOLCHAR , SEPARATOR , COMMENT1 , COMMENT2 , COMMENT3 , COMMENT4 , COMMENT5 , STRINGCONST , HEXSTRINGCONST , BINSTRINGCONST , INTCONST , REALCONST , IDENT , SYLPARENT , SYRPARENT , SYLBRACK , SYRBRACK , SYCOMMA , SYSEMICOLON , SYARROW , SYPERIOD , SYDOTDOT , SYCOLON , SYPLUS , SYMINUS , SYMULT , SYSLASH , SYEQOP , SYNEOP , SYGTOP , SYLTOP , SYGEOP , SYLEOP , SYOROP , SYANDOP , SYASSIGN , SYAND , SYDIV , SYMOD , SYOR , SYXOR , SYIN , SYNOT , SYLABEL , SYCONST , SYTYPE , SYVAR , SYFUNC , SYPROG , SYPROC , SYSET , SYPACKED , SYARRAY , SYRECORD , SYFILE , SYFORWARD , SYBEGIN , SYIF , SYCASE , SYREPEAT , SYWHILE , SYFOR , SYWITH , SYGOTO , SYEND , SYELSE , SYUNTIL , SYOF , SYDO , SYTO , SYDOWNTO , SYTHEN , SYFRTRN , SYEXTRN , SYOTHERWISE , SYOTHER , SYBREAK , SYCONTINUE , SYRETURN , SYMODULE , SYLOCAL , SYSTATIC , NOTUSED ) ; SYMSET = set of SYMB ; var S : SYMSET ; const BLOCKBEGSYS : SYMSET = [ SYLABEL , SYCONST , SYTYPE , SYVAR , SYSTATIC , SYPROC , SYFUNC , SYLOCAL , SYBEGIN ] ; STATBEGSYS : SYMSET = [ SYBEGIN , SYGOTO , SYIF , SYWHILE , SYREPEAT , SYFOR , SYWITH , SYCASE , SYBREAK , SYCONTINUE , SYRETURN ] ; procedure DRUCKE_SYMSET ( T : CHAR32 ; S : SYMSET ) ; var X : SYMB ; begin (* DRUCKE_SYMSET *) WRITELN ( OUTPUT , 'symset at ' , T ) ; for X := SYMB_EOF to NOTUSED do if X in S then WRITE ( OUTPUT , X , ' ' ) ; WRITELN ( OUTPUT ) ; WRITELN ( OUTPUT ) ; end (* DRUCKE_SYMSET *) ; begin (* HAUPTPROGRAMM *) S := BLOCKBEGSYS + STATBEGSYS - [ SYCASE ] ; DRUCKE_SYMSET ( 'TEST FEHLER' , S ) ; end (* HAUPTPROGRAMM *) .
unit uFTPFirmware; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdTCPServer, IdFTPServer, StdCtrls, RzLstBox, Gauges, Buttons, RzButton, RzLabel, IdFTPList,IdGlobal,IdHashCRC,iniFiles,FileInfo, LMDCustomComponent, LMDIniCtrl, RzCmboBx, ExtCtrls, RzPanel, RzRadGrp; type TFirmwareDownInfo = Record Version: string; //Version FMM: string; //Flash Memory Map FSC: String; //Flash Start Command FWFN: String; //Flash Writer File Name FDFN: String; //Flash Data File Name CMDCODE: String; //FX##(##:00 이거나 CMDCODE) DEVICETYPE : string; end; TfmFTPFirmware = class(TForm) GroupBox1: TGroupBox; RzLabel41: TRzLabel; RzLabel1: TRzLabel; RzLabel2: TRzLabel; btnClose: TRzBitBtn; btnFirmwareUpdate: TRzBitBtn; ed_FirmwareFile: TEdit; btn_FileSearch: TBitBtn; btn_FirmwareCancel: TRzBitBtn; ed_pcip: TEdit; ed_pcPort: TEdit; GroupBox2: TGroupBox; ProgressBar1: TGauge; ListBox_DownLoadInfo: TRzListBox; IdFTPServer: TIdFTPServer; OpenDialog1: TOpenDialog; btn_FirmWareChange: TRzBitBtn; RzOpenDialog1: TOpenDialog; LMDIniCtrl2: TLMDIniCtrl; Group_811: TRzCheckGroup; procedure btnCloseClick(Sender: TObject); procedure btn_FirmWareChangeClick(Sender: TObject); procedure btn_FileSearchClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btn_FirmwareCancelClick(Sender: TObject); procedure btnFirmwareUpdateClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ed_pcPortChange(Sender: TObject); procedure cmb_EcuChange(Sender: TObject); procedure Group_811Change(Sender: TObject; Index: Integer; NewState: TCheckBoxState); private procedure IdFTPServer1UserLogin( ASender: TIdFTPServerThread; const AUsername, APassword: string; var AAuthenticated: Boolean ) ; procedure IdFTPServer1ListDirectory( ASender: TIdFTPServerThread; const APath: string; ADirectoryListing: TIdFTPListItems ) ; procedure IdFTPServer1RenameFile( ASender: TIdFTPServerThread; const ARenameFromFile, ARenameToFile: string ) ; procedure IdFTPServer1RetrieveFile( ASender: TIdFTPServerThread; const AFilename: string; var VStream: TStream ) ; procedure IdFTPServer1StoreFile( ASender: TIdFTPServerThread; const AFilename: string; AAppend: Boolean; var VStream: TStream ) ; procedure IdFTPServer1RemoveDirectory( ASender: TIdFTPServerThread; var VDirectory: string ) ; procedure IdFTPServer1MakeDirectory( ASender: TIdFTPServerThread; var VDirectory: string ) ; procedure IdFTPServer1GetFileSize( ASender: TIdFTPServerThread; const AFilename: string; var VFileSize: Int64 ) ; procedure IdFTPServer1DeleteFile( ASender: TIdFTPServerThread; const APathname: string ) ; procedure IdFTPServer1ChangeDirectory( ASender: TIdFTPServerThread; var VDirectory: string ) ; procedure IdFTPServer1CommandXCRC( ASender: TIdCommand ) ; procedure IdFTPServer1Connect( AThread: TIdPeerThread ) ; procedure IdFTPServer1DisConnect( AThread: TIdPeerThread ) ; procedure FTPSERVERStart(); public function TransLatePath( const APathname, homeDir: string ) : string; procedure GageMonitor(aEcuID,aPacketData:string); procedure LoadEcu; private L_stftpsendfilename : string; L_stftpsendfilesize : string; L_stlocalftproot : string; L_bClose : Boolean; L_bBroadCaset : Boolean; FTPSockList : TStringList; SockNo : integer; { Private declarations } Procedure LoadINI_firmwareInfo; procedure Write_ListBox_DownLoadInfo(aData: String); procedure FileLoad(aFileName:string); procedure DownLoadComplete; procedure Ecu_GroupCreate; function Get811ControlerNum(CheckGroup:TRZCheckGroup;var a811ControlerNum:string):integer; public { Public declarations } L_bFirmWareChange : Boolean; L_stSelectEcuID : string; L_bIsDownLoad : Boolean; procedure FirmwareProcess(aEcuID,aPacketData:string); procedure FirmwareProcess2(aEcuID,aPacketData:string); Procedure DownloadFMM(aEcuID :string); Procedure SendCancelRomUpDate(aEcuID:String); Procedure SendFPData(aEcuID: String; aNo:Integer;aMode:string); Procedure SendFPBineryData(aEcuID: String; aNo,aSize:Integer;aMode:string); Procedure SendFDData(aEcuID: String; aNo:Integer;aMode:string); Procedure SendFDBineryData(aEcuID: String; aNo,aSize:Integer;aMode:string); Procedure SendFSC(aEcuID :string); procedure ProcessKTT811FTPFirmWareDownloadComplete(aEcuID:string); end; var fmFTPFirmware: TfmFTPFirmware; aFI: TFirmwareDownInfo; IsFirmwareDownLoad: Boolean; ROM_FlashWrite: TStringList; ROM_FlashData : TStringList; ROM_BineryFlashWrite : PChar; ROM_BineryFlashData : PChar; implementation uses uMain, uSocket, uUtil, dllFunction, uCommon; {$R *.dfm} function SlashToBackSlash( const str: string ) : string; var a: dword; begin result := str; for a := 1 to length( result ) do if result[a] = '/' then result[a] := '\'; end; function GetSizeOfFile( const APathname: string ) : int64; begin result := FileSizeByName( APathname ) ; end; function CalculateCRC( const path: string ) : string; var f: tfilestream; value: dword; IdHashCRC32: TIdHashCRC32; begin IdHashCRC32 := nil; f := nil; try IdHashCRC32 := TIdHashCRC32.create; f := TFileStream.create( path, fmOpenRead or fmShareDenyWrite ) ; value := IdHashCRC32.HashValue( f ) ; result := inttohex( value, 8 ) ; finally f.free; IdHashCRC32.free; end; end; function GetNewDirectory( old, action: string ) : string; var a: integer; begin if action = '../' then begin if old = '/' then begin result := old; exit; end; a := length( old ) - 1; while ( old[a] <> '\' ) and ( old[a] <> '/' ) do dec( a ) ; result := copy( old, 1, a ) ; exit; end; if ( action[1] = '/' ) or ( action[1] = '\' ) then result := action else result := old + action; end; procedure TfmFTPFirmware.btnCloseClick(Sender: TObject); var i : integer; begin if L_bIsDownLoad then begin if Application.MessageBox('FirmWare Download중입니다. 종료 하시겠습니까?','주의',MB_OKCANCEL) = IDCANCEL then Exit; btn_FirmwareCancelClick(self); Delay(1000); end; if FTPSockList.Count > 0 then begin for i := FTPSockList.Count - 1 downto 0 do begin Try TIdPeerThread(FTPSockList.Objects[i]).Stop; Except continue; end; end; end; Try if IdFTPServer.Active then IdFTPServer.Active := False; Except End; L_bClose := True; Close; end; procedure TfmFTPFirmware.btn_FirmWareChangeClick(Sender: TObject); begin L_bFirmWareChange := True; L_bClose := True; Close; end; procedure TfmFTPFirmware.btn_FileSearchClick(Sender: TObject); var st: string; ini_fun : TiniFile; begin RzOpenDialog1.Title:= '펌웨어 설정 파일 찾기'; RzOpenDialog1.DefaultExt:= 'ini'; RzOpenDialog1.Filter := 'INI files (*.ini)|*.INI'; if RzOpenDialog1.Execute then begin st:= RzOpenDialog1.FileName; ed_FirmwareFile.Text:= st; ed_FirmwareFile.SelectAll; FileLoad(st); ini_fun := TiniFile.Create(ExtractFileDir(Application.ExeName) + '\ztcs.INI'); ini_fun.WriteString('FirmWare','FileName',ed_FirmwareFile.Text); ini_fun.Free; end; end; procedure TfmFTPFirmware.FormCreate(Sender: TObject); begin IdFTPServer := tIdFTPServer.create( nil ) ; IdFTPServer.DefaultPort := 21; IdFTPServer.AllowAnonymousLogin := False; IdFTPServer.EmulateSystem := ftpsUNIX; IdFTPServer.HelpReply.text := 'Help is not implemented'; IdFTPServer.OnChangeDirectory := IdFTPServer1ChangeDirectory; // IdFTPServer.OnChangeDirectory := IdFTPServer1ChangeDirectory; IdFTPServer.OnGetFileSize := IdFTPServer1GetFileSize; IdFTPServer.OnListDirectory := IdFTPServer1ListDirectory; IdFTPServer.OnUserLogin := IdFTPServer1UserLogin; IdFTPServer.OnRenameFile := IdFTPServer1RenameFile; IdFTPServer.OnDeleteFile := IdFTPServer1DeleteFile; IdFTPServer.OnRetrieveFile := IdFTPServer1RetrieveFile; IdFTPServer.OnStoreFile := IdFTPServer1StoreFile; IdFTPServer.OnMakeDirectory := IdFTPServer1MakeDirectory; IdFTPServer.OnRemoveDirectory := IdFTPServer1RemoveDirectory; IdFTPServer.Greeting.NumericCode := 220; IdFTPServer.OnDisconnect := IdFTPServer1DisConnect; IdFTPServer.OnConnect := IdFTPServer1Connect; with IdFTPServer.CommandHandlers.add do begin Command := 'XCRC'; OnCommand := IdFTPServer1CommandXCRC; end; ROM_FlashWrite:= TStringList.Create; ROM_FlashData := TStringList.Create; FTPSockList := TStringList.Create; FTPSockList.Clear; ROM_BineryFlashWrite := nil; ROM_BineryFlashData := nil; IsFirmwareDownLoad := False; L_bIsDownLoad := False; L_bClose := False; SockNo := 0; LoadEcu; end; procedure TfmFTPFirmware.FormClose(Sender: TObject; var Action: TCloseAction); begin fmMain.L_bFTPFirmWareSendShow := False; end; procedure TfmFTPFirmware.btn_FirmwareCancelClick(Sender: TObject); begin dmSocket.DirectSendPacket(L_stSelectEcuID,'R','fp00'); DownLoadComplete; end; procedure TfmFTPFirmware.btnFirmwareUpdateClick(Sender: TObject); var stData : string; stFileName : string; stDeviceID : string; nEcu : integer; st811ControlerNum : string; nIndex : integer; begin if Application.MessageBox('프로그램업데이트시 설정정보가 지워질수 있습니다. 계속 하시겠습니까?','주의',MB_OKCANCEL) = IDCANCEL then Exit; stFileName := ed_FirmwareFile.Text; if Not FileExists(stFileName) then begin showmessage('펌웨어 파일을 선택 하세요.'); Exit; end; if Not isDigit(ed_pcPort.Text) then begin showmessage('포트를 확인하세요.'); Exit; end; if Not dmSocket.SocketConnected then begin showmessage('통신연결이 안되었습니다.'); Exit; end; nEcu := Get811ControlerNum(Group_811,st811ControlerNum); if nEcu < 0 then begin showmessage('펌웨어 업데이트 할 컨트롤러를 선택하세요.'); Exit; end; L_bIsDownLoad := True; ListBox_DownLoadInfo.Clear; Write_ListBox_DownLoadInfo('FTP 펌웨어 업그레이드 시작'); Write_ListBox_DownLoadInfo('펌웨어 버젼:' + aFI.Version); btnFirmwareUpdate.Enabled := False; btn_FirmwareCancel.Enabled := True; btn_FileSearch.Enabled := False; btn_FirmWareChange.Enabled := False; btnClose.Enabled := False; if nEcu = 99 then begin stData := 'fp10'; //브로드캐스트 // if aFI.DEVICETYPE = 'MCU110' then stData := stData + 'mMCU110'; end else begin stData := 'fp01'; // 컨트롤러 다이렉트 전송 (* nIndex := DeviceList.IndexOf(FillZeroNumber(nEcu,2)); if nIndex < 0 then Exit; if (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType <> KTT811) and (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType <> KTT813) then begin showmessage('KTT811 시스템이 아닙니다..'); Exit; end; if (copy(TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceCode,1,7) = 'MCU-110') OR (copy(TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceCode,1,7) = 'ECU-110') then begin if aFI.DEVICETYPE <> 'MCU110' then begin showmessage('MCU-300 펌웨어 파일이 아닙니다.'); Exit; end; stData := stData + 'mMCU110'; end else begin if aFI.DEVICETYPE = 'MCU110' then begin showmessage('MCU-100 펌웨어 파일이 아닙니다.'); Exit; end; end; *) end; if nEcu = 99 then stData := 'fp10' //브로드캐스트 else stData := 'fp01'; //컨트롤러 다이렉트 전송 stData := stData + '0'; //모니터링 안함'0' stData := stData + '1'; //게이지 출력 '1' stData := stData + 'pc' + ' ' + Trim(ed_pcip.Text); stData := stData + ' ' + Trim(ed_pcPort.Text); stData := stData + ' zregFW' ;//+ ed_ftplocaluser.Text; stData := stData + ' zregpw' ; stData := stData + ' ' + L_stftpsendfilename; stData := stData + ' ' + L_stftpsendfilesize; if nEcu = 99 then stData := stData + ' ' + st811ControlerNum; IdFTPServer.DefaultPort := strtoint(ed_pcPort.Text); if IdFTPServer.Active = False then IdFTPServer.Active := true; L_bBroadCaset := False; if nEcu = 0 then begin L_stSelectEcuID := FillZeroNumber(0,2); L_bBroadCaset := True; end else L_stSelectEcuID := FillZeroNumber(nEcu,2); dmSocket.DirectSendPacket(L_stSelectEcuID,'R',stData); end; procedure TfmFTPFirmware.Write_ListBox_DownLoadInfo(aData: String); var st: string; begin st:= FormatDatetime('hh":"nn":"ss',Now) +' '+aData; ListBox_DownLoadInfo.Add(st); ListBox_DownLoadInfo.ItemIndex:= ListBox_DownLoadInfo.Items.Count - 1; ListBox_DownLoadInfo.Selected[ListBox_DownLoadInfo.Items.Count - 1] := True; end; procedure TfmFTPFirmware.FormShow(Sender: TObject); var i : integer; ini_fun : TiniFile; begin ed_pcip.Text := Get_Local_IPAddr; fmMain.L_bFTPFirmWareSendShow := True; ini_fun := TiniFile.Create(ExtractFileDir(Application.ExeName) + '\ztcs.INI'); ed_FirmwareFile.Text := ini_fun.ReadString('FirmWare','FileName',''); ini_fun.Free; if FileExists(ed_FirmwareFile.Text) then FileLoad(ed_FirmwareFile.Text); Ecu_GroupCreate; end; procedure TfmFTPFirmware.FirmwareProcess(aEcuID,aPacketData: string); var aRegCode: String; begin //FI:Flash Memory Map //FP:Flash Writer File Name //FD:Flash Data File Name //FX:Flash Start Command aRegCode:= Copy(aPacketData,G_nIDLength + 12,2); if aRegCode = 'FI' then begin L_bIsDownLoad:= True; Write_ListBox_DownLoadInfo('펌웨어 업그레이드정보 응답'); end else if aRegCode = 'FP' then begin Write_ListBox_DownLoadInfo('flash write program 응답'); end else if aRegCode = 'FD' then begin Write_ListBox_DownLoadInfo('flash Data program 응답'); end else if aRegCode = 'FX' then begin Write_ListBox_DownLoadInfo('flash exec data 요청 응답'); end else if aRegCode = 'FU' then begin end else begin end; end; procedure TfmFTPFirmware.FirmwareProcess2(aEcuID,aPacketData: string); var aRegCode: String; Addrstr: String; Addr: Integer; stSeq : string; begin // aDeviceID:= Copy(aPacketData,8,G_nIDLength + 2); aRegCode:= Copy(aPacketData,G_nIDLength + 12,2); if aRegCode = 'fu' then {버젼정보 확인} begin if (aFI.Version <> '' ) then begin ListBox_DownLoadInfo.Clear; Write_ListBox_DownLoadInfo('펌웨어 업그레이드정보 전송'); Write_ListBox_DownLoadInfo('펌웨어 버젼:' + aFI.Version); L_bIsDownLoad:= True; end; end else if aRegCode = 'fi' then {Flash Memory Map 전송} begin if aFI.FMM <> '' then begin DownloadFMM(aEcuID); end else begin ShowMessage('메모리맵 데이터가 없습니다.'); SendCancelRomUpDate(aEcuID); Exit; end; end else if aRegCode = 'fp' then { flash write program} begin Addrstr:= Copy(aPacketData,G_nIDLength + 16,7); Addr:= Strtoint(Addrstr); if Length(aPacketData) < (G_nIDLength + 27) then stSeq := '0000' else stSeq := copy(aPacketData,G_nIDLength + 24,4); if stSeq = '0000' then begin ProgressBar1.Progress:= Addr; ProgressBar1.MaxValue:= ROM_FlashWrite.Count; SendFPData(aEcuID,Addr,'M'); end else begin ProgressBar1.Progress:= Addr * strToint(stSeq); ProgressBar1.MaxValue:= Length(ROM_BineryFlashWrite); SendFPBineryData(aEcuID,Addr,strtoint(stSeq),'M'); end; end else if aRegCode = 'fd' then {flash data program} begin Addrstr:= Copy(aPacketData,G_nIDLength + 16,G_nIDLength); Addr:= Strtoint(Addrstr); if Length(aPacketData) < (G_nIDLength + 28) then stSeq := '0000' else stSeq := copy(aPacketData,(G_nIDLength + 24),4); if stSeq = '0000' then begin ProgressBar1.Progress:= Addr; ProgressBar1.MaxValue:= ROM_FlashData.Count; SendFDData(aEcuID,Addr,'M'); end else begin ProgressBar1.Progress:= Addr * strToint(stSeq); ProgressBar1.MaxValue:= Length(ROM_BineryFlashData); SendFDBineryData(aEcuID,Addr,strtoint(stSeq),'M'); end; end else if aRegCode = 'fx' then {Upgrade flash exec command request} begin SendFSC(aEcuID); end; end; procedure TfmFTPFirmware.DownloadFMM(aEcuID: string); var I: Integer; CMD: string; stTemp: string; aLength: Integer; //SYMFDST052S123455F00005F0000FF00005C0000F80000FF0000 begin CMD:= 'FI00'; stTemp := CMD + aFI.FMM ; if aFI.FMM = '' then begin ShowMessage('데이터 없음'); Exit; end; dmSocket.DirectSendPacket(aEcuID,'F', stTemp); Write_ListBox_DownLoadInfo('Flash Memory Map 전송'); end; procedure TfmFTPFirmware.SendCancelRomUpDate(aEcuID: String); var CMD: string; stTemp: string; i : integer; begin CMD:= 'FU00'; stTemp:= CMD +'0000000'+','+ '0000000'; dmSocket.DirectSendPacket(aEcuID,'F', stTemp); Write_ListBox_DownLoadInfo(' firmware upgrade 취소 전송'); end; procedure TfmFTPFirmware.SendFPData(aEcuID: String; aNo: Integer; aMode: string); var aData:String; st: String; begin if ROM_FlashWrite.Count < 1 then begin if MessageDlg('전송할 데이터가 없습니다.'+ '['+InttoStr(aNo)+']/'+ InttoStr(ROM_FlashWrite.Count) +#13+'취소 하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then SendCancelRomUpDate(aEcuID); Exit; end; if aNo = 0 then begin ShowMessage('flash write 요청번지가 0 입니다.'); Exit; end; if aNo <= ROM_FlashWrite.Count then begin aData:= ROM_FlashWrite[aNo-1]; if aMode = 'M' then st:= 'fP00'+FillZeroNumber(aNo,7)+aData else if aMode = 'S' then st:= 'FP00'+aData; dmSocket.DirectSendPacket(aEcuID,'F',st); Write_ListBox_DownLoadInfo('flash write 전송:'+InttoStr(aNo)); end else begin if MessageDlg('요청된 번지가 잘못되었거나 write 파일에 문제가 있습니다.'+ '['+InttoStr(aNo)+']/'+ InttoStr(ROM_FlashWrite.Count) +#13+'취소 하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then SendCancelRomUpDate(aEcuID); end; end; procedure TfmFTPFirmware.SendFPBineryData(aEcuID: String; aNo, aSize: Integer; aMode: string); var st: String; iFileLength: Integer; bSendData : Boolean; stSendData : string; begin if aNo = 0 then begin ShowMessage('flash write 요청번지가 0 입니다.'); Exit; end; if ROM_BineryFlashWrite = nil then begin st:= 'fP00' +FillZeroNumber(0,7); dmSocket.DirectSendPacket(aEcuID,'F',st); ShowMessage('전송 가능한 flash write 가 없습니다.'); Exit; end; bSendData := False; iFileLength := length(ROM_BineryFlashWrite); if iFileLength > 0 then begin //요청 데이터가 끝난 시점인지...체크 if iFileLength < ((aNo - 1) * aSize) then begin bSendData := False; end else begin //여기에서 데이터 셋팅 bSendData := True; if (aNo * aSize) < iFileLength then begin stSendData := copy(ROM_BineryFlashWrite,((aNo - 1) * aSize) + 1,aSize); end else begin stSendData := copy(ROM_BineryFlashWrite,((aNo - 1) * aSize) + 1,iFileLength -((aNo - 1) * aSize)); end; //RzFieldStatus1.Caption := inttostr(length(stSendData)) + ':' + stSendData; end; end; if Not bSendData then begin //보낼 데이터가 없음 if aMode = 'M' then st:= 'fP00' +FillZeroNumber(0,7) else if aMode = 'S' then st:= 'fP00'; dmSocket.DirectSendPacket(aEcuID,'F',st); Write_ListBox_DownLoadInfo('flash write 전송:'+InttoStr(aNo)); end else begin //데이터송신 if aMode = 'M' then st:= 'fP00' +FillZeroNumber(aNo,7)+ stSendData else if aMode = 'S' then st:= 'fP00' + stSendData; dmSocket.DirectSendPacket(aEcuID,'F',st); Write_ListBox_DownLoadInfo('flash write 전송:'+InttoStr(aNo)); end; end; procedure TfmFTPFirmware.SendFDData(aEcuID: String; aNo: Integer; aMode: string); var aData:String; st: String; begin if ROM_FlashData.Count < 1 then begin if MessageDlg('전송할 데이터가 없습니다.'+ '['+InttoStr(aNo)+']/'+ InttoStr(ROM_FlashWrite.Count) +#13+'취소 하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then SendCancelRomUpDate(aEcuID); Exit; end; if aNo = 0 then begin ShowMessage('flash data 요청번지가 0 입니다.'); Exit; end; if aNo <= ROM_FlashData.Count then begin aData:= ROM_FlashData[aNo-1]; if aMode = 'M' then st:= 'fD00'+FillZeroNumber(aNo,7)+aData else if aMode = 'S' then st:= 'FD00'+aData; dmsocket.DirectSendPacket(aEcuID,'F',st); Write_ListBox_DownLoadInfo('flash data 전송:'+InttoStr(aNo)); end else begin if MessageDlg('요청된 번지가 잘못되었거나 Data 파일에 문제가 있습니다.'+ '['+InttoStr(aNo)+']/'+ InttoStr(ROM_FlashData.Count) +#13+'취소 하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then SendCancelRomUpDate(aEcuID); end; end; procedure TfmFTPFirmware.SendFDBineryData(aEcuID: String; aNo, aSize: Integer; aMode: string); var st: String; iFileLength: Integer; bSendData : Boolean; stSendData : string; begin if aNo = 0 then begin ShowMessage('flash data 요청번지가 0 입니다.'); Exit; end; if ROM_BineryFlashData = nil then begin if aMode = 'M' then begin st:= 'fD00' +FillZeroNumber(0,7); dmsocket.DirectSendPacket(aEcuID,'F',st); end; ShowMessage('전송 가능한 flash data 가 없습니다.'); Exit; end; bSendData := False; iFileLength := length(ROM_BineryFlashData); if iFileLength > 0 then begin //요청 데이터가 끝난 시점인지...체크 if iFileLength < ((aNo - 1) * aSize) then begin bSendData := False; end else begin //여기에서 데이터 셋팅 bSendData := True; if (aNo * aSize) < iFileLength then begin stSendData := copy(ROM_BineryFlashData,((aNo - 1) * aSize) + 1,aSize); end else begin stSendData := copy(ROM_BineryFlashData,((aNo - 1) * aSize) + 1,iFileLength -((aNo - 1) * aSize)); end; end; end; if Not bSendData then begin //보낼 데이터가 없음 if aMode = 'M' then st:= 'fD00' + FillZeroNumber(0,7) else if aMode = 'S' then st:= 'fD00' ; dmsocket.DirectSendPacket(aEcuID,'F',st); Write_ListBox_DownLoadInfo('flash data 전송:'+InttoStr(aNo)); end else begin //데이터송신 if aMode = 'M' then st:= 'fD00' + FillZeroNumber(aNo,7) + stSendData else if aMode = 'S' then st:= 'fD00' + stSendData; dmsocket.DirectSendPacket(aEcuID,'F',st); Write_ListBox_DownLoadInfo('flash data 전송:'+InttoStr(aNo)); end; end; procedure TfmFTPFirmware.SendFSC(aEcuID: string); var CMD: string; st,stAdd: string; aLength: Integer; aTime: TDatetime; aData: String; i : integer; begin Delete(aFI.FSC,9,18); aFI.FSC:= aFI.FSC +#$20+'00/00/00 00:00:00'; CMD:= 'FX'+aFI.CMDCODE; aData:= CMD + aFI.FSC ; // aDeviceID:= Edit_CurrentID.Text + ComboBox_IDNO.Text; dmsocket.DirectSendPacket(aEcuID,'F', aData); Write_ListBox_DownLoadInfo('펌웨어 시작 시간 전송시작'); DownLoadComplete; end; procedure TfmFTPFirmware.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if Not L_bClose then CanClose := False; end; procedure TfmFTPFirmware.FileLoad(aFileName: string); var iFileLength: Integer; iBytesRead: Integer; iFileHandle: Integer; clFileInfo : TFileInfo; st : string; begin Try btnFirmwareUpdate.Enabled := True; clFileInfo := TFileInfo.Create(aFileName); L_stftpsendfilename := clFileInfo.FileName; L_stftpsendfilesize := inttostr(clFileInfo.FileSize); L_stlocalftproot := clFileInfo.Path; clFileInfo.Destroy; //if Not FTPUSE then //begin LMDIniCtrl2.IniFile:= aFileName; LoadINI_firmwareInfo; st:= aFI.Version + #13+ aFI.FMM + #13+ aFI.FSC + #13+ aFI.FWFN + #13+ aFI.FDFN; ROM_FlashWrite.Clear; ROM_FlashWrite.LoadFromFile(L_stlocalftproot + '\' + aFI.FWFN); ROM_FlashData.Clear; ROM_FlashData.LoadFromFile(L_stlocalftproot + '\' + aFI.FDFN); //여기서 첫번째 파일을 읽어 들이자 iFileHandle := FileOpen(L_stlocalftproot + '\' + aFI.FWFN, fmOpenRead); iFileLength := FileSeek(iFileHandle,0,2); FileSeek(iFileHandle,0,0); ROM_BineryFlashWrite := nil; ROM_BineryFlashWrite := PChar(AllocMem(iFileLength + 1)); iBytesRead := FileRead(iFileHandle, ROM_BineryFlashWrite^, iFileLength); FileClose(iFileHandle); //여기서 두번째 파일을 읽어 들이자 iFileHandle := FileOpen(L_stlocalftproot + '\' + aFI.FDFN, fmOpenRead); iFileLength := FileSeek(iFileHandle,0,2); FileSeek(iFileHandle,0,0); ROM_BineryFlashData := nil; ROM_BineryFlashData := PChar(AllocMem(iFileLength + 1)); iBytesRead := FileRead(iFileHandle, ROM_BineryFlashData^, iFileLength); FileClose(iFileHandle); Except btnFirmwareUpdate.Enabled := False; ed_FirmwareFile.Text := ''; End; end; procedure TfmFTPFirmware.DownLoadComplete; begin btnFirmwareUpdate.Enabled := True; btn_FirmwareCancel.Enabled := False; btn_FileSearch.Enabled := True; btnClose.Enabled := True; btn_FirmWareChange.Enabled := True; ProgressBar1.Progress := 0; L_bIsDownLoad:= False; Write_ListBox_DownLoadInfo('==== FirmWare Download Completed ====' ); end; procedure TfmFTPFirmware.ed_pcPortChange(Sender: TObject); begin IdFTPServer.Active := False; end; procedure TfmFTPFirmware.FTPSERVERStart; begin end; procedure TfmFTPFirmware.IdFTPServer1ChangeDirectory( ASender: TIdFTPServerThread; var VDirectory: string); begin VDirectory := GetNewDirectory( ASender.CurrentDir, VDirectory ) ; end; procedure TfmFTPFirmware.IdFTPServer1CommandXCRC(ASender: TIdCommand); var s: string; begin with TIdFTPServerThread( ASender.Thread ) do begin if Authenticated then begin try s := ProcessPath( CurrentDir, ASender.UnparsedParams ) ; s := TransLatePath( s, TIdFTPServerThread( ASender.Thread ) .HomeDir ) ; ASender.Reply.SetReply( 213, CalculateCRC( s ) ) ; except ASender.Reply.SetReply( 500, 'file error' ) ; end; end; end; end; procedure TfmFTPFirmware.IdFTPServer1Connect(AThread: TIdPeerThread); begin FTPSockList.AddObject(inttostr(SockNo),AThread); inc(SockNo); end; procedure TfmFTPFirmware.IdFTPServer1DeleteFile( ASender: TIdFTPServerThread; const APathname: string); begin DeleteFile( pchar( TransLatePath( ASender.CurrentDir + '/' + APathname, ASender.HomeDir ) ) ) ; end; procedure TfmFTPFirmware.IdFTPServer1DisConnect(AThread: TIdPeerThread); var i : integer; begin for i := 0 to FTPSockList.Count - 1 do begin if TIdPeerThread(FTPSockList.Objects[i]) = AThread then begin FTPSockList.Delete(i); end; end; AThread.Data := nil; AThread.Stop; Write_ListBox_DownLoadInfo('==== FTP STOP ====' ); if L_bBroadCaset then begin Write_ListBox_DownLoadInfo('==== CONTROLER SEND START ====' ); end; end; procedure TfmFTPFirmware.IdFTPServer1GetFileSize( ASender: TIdFTPServerThread; const AFilename: string; var VFileSize: Int64); begin VFileSize := GetSizeOfFile( TransLatePath( AFilename, ASender.HomeDir ) ) ; end; procedure TfmFTPFirmware.IdFTPServer1ListDirectory( ASender: TIdFTPServerThread; const APath: string; ADirectoryListing: TIdFTPListItems); procedure AddlistItem( aDirectoryListing: TIdFTPListItems; Filename: string; ItemType: TIdDirItemType; size: int64; date: tdatetime ) ; var listitem: TIdFTPListItem; begin listitem := aDirectoryListing.Add; listitem.ItemType := ItemType; listitem.FileName := Filename; listitem.OwnerName := 'anonymous'; listitem.GroupName := 'all'; listitem.OwnerPermissions := '---'; listitem.GroupPermissions := '---'; listitem.UserPermissions := '---'; listitem.Size := size; listitem.ModifiedDate := date; end; var f: tsearchrec; a: integer; begin ADirectoryListing.DirectoryName := apath; a := FindFirst( TransLatePath( apath, ASender.HomeDir ) + '*.*', faAnyFile, f ) ; while ( a = 0 ) do begin if ( f.Attr and faDirectory > 0 ) then AddlistItem( ADirectoryListing, f.Name, ditDirectory, f.size, FileDateToDateTime( f.Time ) ) else AddlistItem( ADirectoryListing, f.Name, ditFile, f.size, FileDateToDateTime( f.Time ) ) ; a := FindNext( f ) ; end; FindClose( f ) ; end; procedure TfmFTPFirmware.IdFTPServer1MakeDirectory( ASender: TIdFTPServerThread; var VDirectory: string); begin MkDir( TransLatePath( VDirectory, ASender.HomeDir ) ) ; end; procedure TfmFTPFirmware.IdFTPServer1RemoveDirectory( ASender: TIdFTPServerThread; var VDirectory: string); begin RmDir( TransLatePath( VDirectory, ASender.HomeDir ) ) ; end; procedure TfmFTPFirmware.IdFTPServer1RenameFile( ASender: TIdFTPServerThread; const ARenameFromFile, ARenameToFile: string); begin if not MoveFile( pchar( TransLatePath( ARenameFromFile, ASender.HomeDir ) ) , pchar( TransLatePath( ARenameToFile, ASender.HomeDir ) ) ) then RaiseLastWin32Error; end; procedure TfmFTPFirmware.IdFTPServer1RetrieveFile( ASender: TIdFTPServerThread; const AFilename: string; var VStream: TStream); begin Write_ListBox_DownLoadInfo('==== FTP SEND FILE Name : ' + AFilename); VStream := TFileStream.create( translatepath( AFilename, ASender.HomeDir ) , fmopenread or fmShareDenyWrite ) ; end; procedure TfmFTPFirmware.IdFTPServer1StoreFile(ASender: TIdFTPServerThread; const AFilename: string; AAppend: Boolean; var VStream: TStream); begin if FileExists( translatepath( AFilename, ASender.HomeDir ) ) and AAppend then begin VStream := TFileStream.create( translatepath( AFilename, ASender.HomeDir ) , fmOpenWrite or fmShareExclusive ) ; VStream.Seek( 0, soFromEnd ) ; end else VStream := TFileStream.create( translatepath( AFilename, ASender.HomeDir ) , fmCreate or fmShareExclusive ) ; end; procedure TfmFTPFirmware.IdFTPServer1UserLogin(ASender: TIdFTPServerThread; const AUsername, APassword: string; var AAuthenticated: Boolean); var st : string; begin AAuthenticated := ( AUsername = 'zregid' ) and ( APassword = 'zregpw' ) ; if not AAuthenticated then begin AAuthenticated := ( AUsername = 'zregFW' ) and ( APassword = 'zregpw' ) ; if not AAuthenticated then begin AAuthenticated := ( AUsername = 'zregBK' ) and ( APassword = 'zregpw' ) ; if not AAuthenticated then exit; end; end; Write_ListBox_DownLoadInfo('==== FTP USER LOGIN ==== '); Write_ListBox_DownLoadInfo('HOMEDIR:' + L_stlocalftproot); ASender.HomeDir := L_stlocalftproot; asender.currentdir := '/'; end; function TfmFTPFirmware.TransLatePath(const APathname, homeDir: string): string; var tmppath: string; begin result := SlashToBackSlash( homeDir ) ; tmppath := SlashToBackSlash( APathname ) ; if homedir = '/' then begin result := tmppath; exit; end; if length( APathname ) = 0 then exit; if result[length( result ) ] = '\' then result := copy( result, 1, length( result ) - 1 ) ; if tmppath[1] <> '\' then result := result + '\'; result := result + tmppath; end; procedure TfmFTPFirmware.GageMonitor(aEcuID,aPacketData: string); var stGauge : string; nPos : integer; stMax,stPrograss:string; stEcuID : string; FirmWareGauge : TGauge; FirmWareLabel : TLabel; nPosCount : integer; nStartPos : integer; nEndPos : integer; begin //if Not chk_Gauge.Checked then Exit; //048 K1000000000#UGc01 168550/495530 (34)76 stEcuID := copy(aPacketData,15,2); nPosCount := posCount(' ',aPacketData); nStartPos := PosIndex(' ',aPacketData,nPosCount - 1); nEndPos := PosIndex(' ',aPacketData,nPosCount); stGauge := copy(aPacketData,nStartPos + 1,nEndPos - nStartPos - 1); stPrograss := FindCharCopy(stGauge,0,'/'); stMax := FindCharCopy(stGauge,1,'/'); stMax := FindCharCopy(stMax,0,' '); ProgressBar1.MaxValue := strtoint(stMax); ProgressBar1.Progress := strtoint(stPrograss); Application.ProcessMessages; end; procedure TfmFTPFirmware.LoadINI_firmwareInfo; var st: string; begin //GetDir(0,aDir); with LMDIniCtrl2 do begin aFI.Version:= ReadString('DOWNLOAD','Version',''); aFI.FMM := ReadString('DOWNLOAD','FMM',''); st := ReadString('DOWNLOAD','FSC',''); aFI.FSC := FindCharCopy(st,0,','); aFI.CMDCODE:= FindCharCopy(st,1,','); if aFI.CMDCODE = '' then aFI.CMDCODE:= '00'; aFI.FWFN := ReadString('DOWNLOAD','FWFN',''); aFI.FDFN := ReadString('DOWNLOAD','FDFN',''); aFI.DEVICETYPE := ReadString('DOWNLOAD','DEVI',''); end; end; procedure TfmFTPFirmware.LoadEcu; var i : integer; stSelectEcuID : string; begin stSelectEcuID := ''; {if cmb_Ecu.Count > 0 then stSelectEcuID := cmb_Ecu.Text; cmb_Ecu.Clear; for i :=0 to deviceList.Count - 1 do begin if TCurrentDeviceState(DeviceList.Objects[i]).Connected then begin if TCurrentDeviceState(DeviceList.Objects[i]).DeviceType = KTT811 then begin cmb_Ecu.Add(deviceList.Strings[i]); if stSelectEcuID = deviceList.Strings[i] then begin cmb_Ecu.ItemIndex := cmb_Ecu.Count - 1; end; end; end; end; if cmb_Ecu.ItemIndex < 0 then cmb_Ecu.ItemIndex := 0; L_stSelectEcuID := cmb_Ecu.Text; } end; procedure TfmFTPFirmware.cmb_EcuChange(Sender: TObject); begin //L_stSelectEcuID := cmb_Ecu.Text; end; procedure TfmFTPFirmware.Ecu_GroupCreate; var i : integer; nIndex : integer; begin Group_811.Items.Clear; for I:= 0 to 63 do begin Group_811.Items.Add(FillZeroNumber(i,2)); nIndex := DeviceList.IndexOf(FillZeroNumber(i,2)); if nIndex > -1 then begin if TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT811 then begin if TCurrentDeviceState(DeviceList.Objects[nIndex]).Connected then begin Group_811.ItemChecked[i]:= True; end; end; end; end; Group_811.ItemChecked[0]:= True; end; function TfmFTPFirmware.Get811ControlerNum(CheckGroup: TRZCheckGroup; var a811ControlerNum: string): integer; var nTemp : array[0..8, 0..7] of Integer; i,j,k : Integer; stTemp: String; stHex:String; nDecimal: Integer; FirmWare812Gauge : TGauge; FirmWare812Label : TLabel; nSelectEcu : integer; nSelectCount : integer; begin nSelectCount := 0; stHex := '0'; for i:=1 to 99 do begin stHex := stHex + '0'; end; //체크 되어 있는 위치에 데이터를 넣는다. for k:= 0 to 63 do begin if CheckGroup.ItemChecked[k] = True then begin nSelectCount := nSelectCount + 1; nSelectEcu := k; stHex[k+1] := '1'; end; end; a811ControlerNum := stHex; if nSelectCount = 0 then Result := -1 else if nSelectCount = 1 then Result := nSelectEcu else Result := 0; end; procedure TfmFTPFirmware.ProcessKTT811FTPFirmWareDownloadComplete( aEcuID: string); begin DownLoadComplete; end; procedure TfmFTPFirmware.Group_811Change(Sender: TObject; Index: Integer; NewState: TCheckBoxState); var nIndex : integer; begin if NewState = cbUnchecked then Exit; nIndex := DeviceList.IndexOf(FillZeroNumber(Index,2)); if nIndex < 0 then begin Group_811.ItemChecked[Index]:= False; showmessage('등록되지 않은 컨트롤러입니다.'); Exit; end; if Not TCurrentDeviceState(DeviceList.Objects[nIndex]).Connected then begin Group_811.ItemChecked[Index]:= False; showmessage('해당 컨트롤러는 통신연결 상태가 아닙니다.'); Exit; end; if TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType <> KTT811 then begin Group_811.ItemChecked[Index]:= False; showmessage('KTT811 컨트롤러가 아닙니다.'); Exit; end; end; end.
unit Scroller; interface uses Classes,Windows,Graphics,Controls,Messages,Forms,Misc; type TBufferedScroller=class; TRenderBufferedScrollerEvent=procedure(BS:TBufferedScroller) of object; TGetRegionRectEvent=function( BS:TBufferedScroller; RegionNum:Integer; var dx,dy:Integer; var R:TRect ):Integer of object; TFPScrollBar=class; TBufferedScroller=class(TCustomControl) protected FBuffer:TBitmap; FHorzSB, FVertSB: TFPScrollBar; FVSize:TPoint; FDelta,FOldDelta:TPoint; FFixedField:TPoint; renderLockCnt: Integer; setvLockCnt: Integer; needRender: Boolean; needRepaint: Boolean; needSetVSize: Boolean; validBufferSize: Boolean; FUseScrollWindow: Boolean; FOnBeforeScroll,FOnAfterScroll,FOnMouseLeave:TNotifyEvent; FOnRender:TRenderBufferedScrollerEvent; FOnGetRegionRect:TGetRegionRectEvent; procedure paint; override; procedure renderer; virtual; procedure Resize; override; private function GetClientSize: TPoint; procedure SetDelta(Value: TPoint); procedure ScrollProc(SB: TObject); procedure resizeBuffer; procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMGetMinMaxInfo(var Msg: TWMGetMinMaxInfo); message WM_GETMINMAXINFO; procedure WMHScroll(var Msg: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL; procedure CMMouseLeave(var Msg:TMsg); message CM_MOUSELEAVE; procedure SetVSize(const Value: TPoint); procedure CalcAndSetPageSize(const CS,VS:TPoint); function GetPixelFormat: TPixelFormat; procedure SetPixelFormat(const Value: TPixelFormat); procedure ChangeSize; function GetBuffer: TBitmap; procedure Set_HorzSB(const Value: TFPScrollBar); procedure Set_VertSB(const Value: TFPScrollBar); public BufferChanged:Boolean; procedure lockRender; procedure lockSetV; procedure render(Repaint:Boolean); procedure unlockRender; procedure unlockSetV; constructor create(AOwner: TComponent); override; destructor destroy; override; // property Buffer:TBitmap read GetBuffer; property OldDelta:TPoint read FOldDelta; property Delta: TPoint read FDelta write SetDelta stored False; property VSize: TPoint read FVSize write SetVSize stored False; property FixedField:TPoint read FFixedField write FFixedField; property ClientSize: TPoint read GetClientSize; property HorzSB:TFPScrollBar read FHorzSB write Set_HorzSB; property VertSB:TFPScrollBar read FVertSB write Set_VertSB; published property OnBeforeScroll: TNotifyEvent read FOnBeforeScroll write FOnBeforeScroll; property OnAfterScroll: TNotifyEvent read FOnAfterScroll write FOnAfterScroll; property OnGetRegionRect: TGetRegionRectEvent read FOnGetRegionRect write FOnGetRegionRect; property OnRender: TRenderBufferedScrollerEvent read FOnRender write FOnRender; property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave; property PixelFormat:TPixelFormat read GetPixelFormat write SetPixelFormat; property UseScrollWindow:Boolean read FUseScrollWindow write FUseScrollWindow; // property BorderWidth; // property Align; property Anchors; property Constraints; property MouseCapture; property Visible; property ParentShowHint; property PopupMenu; property OnCanResize; property OnClick; property OnConstrainedResize; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnResize; property OnStartDock; property OnStartDrag; end; TUniViewer=class(TBufferedScroller) private procedure SetRealSize(const Value: TDblPoint); procedure SetScale(const Value: TDblPoint); function GetRealClientSize: TDblPoint; function GetRealDelta: TDblPoint; procedure SetRealSizeX(const Value: Double); procedure SetRealSizeY(const Value: Double); procedure SetScaleX(const Value: Double); procedure SetScaleY(const Value: Double); protected FScale:TDblPoint; FRealSize:TDblPoint; public property RealDelta:TDblPoint read GetRealDelta; property RealClientSize:TDblPoint read GetRealClientSize; property Scale:TDblPoint read FScale write SetScale; property RealSize:TDblPoint read FRealSize write SetRealSize; published property ScaleX:Double read FScale.X write SetScaleX; property ScaleY:Double read FScale.Y write SetScaleY; property RealSizeX:Double read FRealSize.X write SetRealSizeX; property RealSizeY:Double read FRealSize.Y write SetRealSizeY; property HorzSB; property VertSB; end; TFPScrollBar=class(TPersistent) private procedure SetDisableNoScroll(const Value: Boolean); procedure SetEnabled(const Value: Boolean); procedure SetPageSize(Value: Double); procedure SetPosition(Value: Double); procedure SetVisible(Value: Boolean); procedure CutOffPosition(var Pos:Double); protected FControl: TWinControl; FIncrement: Double; FKind: TScrollBarKind; FOnScroll: TNotifyEvent; FPageSize: Double; FPosition: Double; needRedraw: Boolean; FVisible, FDisableNoScroll, FEnabled: Boolean; redrawLockCnt: Integer; function GetSize: Integer; procedure ScrollMessage(var Msg: TWMScroll); procedure update(Immediate:Boolean); public constructor create(AControl: TWinControl; AKind: TScrollBarKind); procedure lockRedraw; procedure unlockRedraw; procedure Assign(Source:TPersistent);override; public property OnScroll: TNotifyEvent read FOnScroll write FOnScroll; property Position: Double read FPosition write SetPosition; property Size: Integer read GetSize; property PageSize: Double read FPageSize write SetPageSize; published property DisableNoScroll:Boolean read FDisableNoScroll write SetDisableNoScroll; property Enabled: Boolean read FEnabled write SetEnabled; property Visible: Boolean read FVisible write SetVisible; end; implementation const MaxInt16=32767; OneDivMaxInt16=1/MaxInt16; function TBufferedScroller.GetClientSize: TPoint; var R:TRect; begin Windows.GetClientRect(Handle,R); Result.X:=R.Right-R.Left+1; Result.Y:=R.Bottom-R.Top+1; end; procedure TBufferedScroller.SetDelta(Value: TPoint); var Flag:Boolean; begin lockRender; Flag:=False; if (FDelta.x<>Value.x) then begin if FVSize.x>0 then HorzSB.Position:=Value.x/FVSize.x else HorzSB.Position:=0; Value.x:=Round(HorzSB.Position*FVSize.x); if FDelta.x<>Value.x then begin FDelta.x:=Value.x; Flag:=True; end; end; if (FDelta.y<>Value.y) then begin if FVSize.y>0 then VertSB.Position:=Value.y/FVSize.y else VertSB.Position:=0; Value.y:=Round(VertSB.Position*FVSize.y); if FDelta.y<>Value.y then begin FDelta.y:=Value.y; Flag:=True; end; end; if Flag then render(True); unlockRender; end; procedure TBufferedScroller.WMGetMinMaxInfo(var Msg: TWMGetMinMaxInfo); var P:TPoint; begin with Msg.MinMaxInfo.ptMinTrackSize do begin x:=64; y:=64; end; P.x:=FVSize.x+FixedField.x; P.y:=FVSize.y+FixedField.y; Msg.MinMaxInfo.ptMaxTrackSize:=P; end; procedure TBufferedScroller.WMHScroll(var Msg: TWMHScroll); begin FHorzSB.ScrollMessage(Msg); end; procedure TBufferedScroller.WMVScroll(var Msg: TWMVScroll); begin FVertSB.ScrollMessage(Msg); end; constructor TBufferedScroller.create(AOwner: TComponent); var Style,ExStyle:Integer; begin inherited; FBuffer:=TBitmap.Create; FHorzSB:=TFPScrollBar.create(Self,sbHorizontal); FVertSB:=TFPScrollBar.create(Self,sbVertical); Parent:=Owner as TWinControl; Style:=GetWindowLong(Handle,GWL_STYLE); Style:=Style or WS_VSCROLL or WS_HSCROLL;// or WS_BORDER or WS_THICKFRAME; SetWindowLong(Handle,GWL_STYLE,Style); ExStyle:=GetWindowLong(Handle,GWL_EXSTYLE) or WS_EX_CLIENTEDGE; SetWindowLong(Handle,GWL_EXSTYLE,ExStyle); SetBounds(0,0,64,64); // HorzSB.OnScroll:=ScrollProc; VertSB.OnScroll:=ScrollProc; end; destructor TBufferedScroller.destroy; begin FBuffer.Free; inherited; end; procedure TBufferedScroller.CalcAndSetPageSize(const CS, VS: TPoint); var PGS:TDblPoint; begin if VS.x=0 then PGS.x:=1.0 else PGS.x:=(CS.x-FixedField.x)/VS.x; if VS.y=0 then PGS.y:=1.0 else PGS.y:=(CS.y-FixedField.y)/VS.y; HorzSB.PageSize:=PGS.x; VertSB.PageSize:=PGS.y; end; procedure TBufferedScroller.lockRender; begin Inc(renderLockCnt); end; procedure TBufferedScroller.renderer; begin if Assigned(FOnRender) then FOnRender(Self); end; procedure TBufferedScroller.unlockRender; begin Dec(renderLockCnt); if (renderLockCnt=0) and needRender then render(True); end; procedure TBufferedScroller.render(Repaint:Boolean); begin needRender:=true; needRepaint:=needRepaint or Repaint; if renderLockCnt>0 then exit; renderer; needRender:=False; if needRepaint then Self.Repaint else Self.Update; needRepaint:=False; end; procedure TBufferedScroller.ScrollProc(SB: TObject); var dx,dy,adx,ady:Integer; i,RegCnt:Integer; R,CR:TRect; begin if Assigned(FOnBeforeScroll) then FOnBeforeScroll(Self); if SB=HorzSB then FDelta.x:=round(HorzSB.Position*FVSize.x) else if SB=VertSB then FDelta.y:=round(VertSB.Position*FVSize.y); dx:=FOldDelta.x-FDelta.x; dy:=FOldDelta.y-FDelta.y; if (dx<>0)or(dy<>0) then begin if (renderLockCnt=0) then begin renderer; if FUseScrollWindow then begin CR:=GetClientRect; if Assigned(OnGetRegionRect) then begin R:=CR; adx:=dx; ady:=dy; RegCnt:=OnGetRegionRect(Self,0,adx,ady,CR); for i:=1 to RegCnt do begin R:=CR; adx:=dx; ady:=dy; OnGetRegionRect(Self,i,adx,ady,R); ScrollWindow(Handle,adx,ady,nil,@R); end; end else ScrollWindow(Handle,dx,dy,nil,nil); end else Invalidate; update; end; end; if Assigned(FOnAfterScroll) then FOnAfterScroll(Self); FOldDelta:=FDelta; end; procedure TBufferedScroller.paint; begin if renderLockCnt>0 then exit; if needRender then render(true); Canvas.draw(0,0,Buffer); end; procedure TBufferedScroller.resizeBuffer; var CS:TPoint; begin CS:=ClientSize; FBuffer.Width :=CS.x; FBuffer.Height:=CS.y; validBufferSize:=True; end; procedure TBufferedScroller.SetVSize(const Value: TPoint); begin FVSize := Value; if (setvLockCnt>0) then begin needSetVSize:=True; exit; end; needSetVSize:=False; CalcAndSetPageSize(ClientSize,Value); FDelta.x:=Round(HorzSB.Position*FVSize.x); FDelta.y:=Round(VertSB.Position*FVSize.y); FOldDelta:=FDelta; render(true); end; procedure TBufferedScroller.WMEraseBkgnd(var Msg: TWMEraseBkgnd); begin // do nothing end; { TFPScrollBar } procedure TFPScrollBar.Assign(Source: TPersistent); begin if Source is TFPScrollBar then begin lockRedraw; Position:=TFPScrollBar(Source).Position; PageSize:=TFPScrollBar(Source).PageSize; Visible:=TFPScrollBar(Source).Visible; unlockRedraw; end; inherited Assign(Source); end; constructor TFPScrollBar.create(AControl: TWinControl; AKind: TScrollBarKind); begin inherited create; FControl:=AControl; FKind:=AKind; FPosition:=0; FPageSize:=1; FIncrement:=0.001; FEnabled:=True; end; procedure TFPScrollBar.CutOffPosition(var Pos: Double); begin if Pos<0 then Pos:=0 else if Pos+FPageSize>1 then Pos:=1-FPageSize; end; function TFPScrollBar.GetSize: Integer; begin if Visible then begin if FKind=sbVertical then Result:=GetSystemMetrics(SM_CXVSCROLL) else Result:=GetSystemMetrics(SM_CYHSCROLL); end else Result:=0; end; procedure TFPScrollBar.lockRedraw; begin inc(redrawLockCnt); end; procedure TFPScrollBar.ScrollMessage(var Msg: TWMScroll); begin if not Visible or not Enabled then exit; with Msg do case ScrollCode of SB_LINEUP: SetPosition(FPosition - FIncrement); SB_LINEDOWN: SetPosition(FPosition + FIncrement); SB_PAGEUP: SetPosition(FPosition - FPageSize); SB_PAGEDOWN: SetPosition(FPosition + FPageSize); SB_TOP: SetPosition(0); SB_BOTTOM: SetPosition(1); SB_THUMBPOSITION: SetPosition(Pos*OneDivMaxInt16); SB_THUMBTRACK: SetPosition(Pos*OneDivMaxInt16); SB_ENDSCROLL:; end; end; procedure TFPScrollBar.SetDisableNoScroll(const Value: Boolean); begin FDisableNoScroll := Value; update(False); end; procedure TFPScrollBar.SetEnabled(const Value: Boolean); var Code:Cardinal; Arrows:Cardinal; begin if FEnabled<>Value then begin FEnabled:=Value; if FKind=sbHorizontal then Code:=SB_HORZ else Code:=SB_VERT; if Value then begin Arrows:=ESB_ENABLE_BOTH; if Visible then update(False); end else Arrows:=ESB_DISABLE_BOTH; EnableScrollBar(FControl.Handle,Code,Arrows); end; end; procedure TFPScrollBar.SetPageSize(Value: Double); begin if (FPageSize <> Value) then begin if Value < 0 then Value := 0 else if 1 < Value then Value := 1; FPageSize := Value; CutOffPosition(FPosition); update(False); end; end; procedure TFPScrollBar.SetPosition(Value: Double); begin CutOffPosition(Value); if (FPosition<>Value) then begin FPosition := Value; if Assigned(FOnScroll) then FOnScroll(Self); update(False); end; end; procedure TFPScrollBar.SetVisible(Value: Boolean); var Code:Cardinal; begin if FVisible<>Value then begin FVisible:=Value; if FKind=sbHorizontal then Code:=SB_HORZ else Code:=SB_VERT; ShowScrollBar(FControl.Handle,Code,Value); update(True); end; end; procedure TFPScrollBar.unlockRedraw; begin if redrawLockCnt=0 then exit; Dec(redrawLockCnt); if (redrawLockCnt=0) and needRedraw then update(False); end; procedure TFPScrollBar.update; var ScrollInfo:TScrollInfo; Code:Cardinal; begin if not Immediate and (not Visible or not Enabled) then exit; needRedraw:=True; if redrawLockCnt>0 then exit; if FKind=sbHorizontal then Code:=SB_HORZ else Code:=SB_VERT; ScrollInfo.cbSize:=SizeOf(ScrollInfo); ScrollInfo.fMask:=SIF_ALL; if DisableNoScroll then ScrollInfo.fMask:=ScrollInfo.fMask or SIF_DISABLENOSCROLL; CutOffPosition(FPosition); { if (FPageSize<1) then ScrollInfo.nMin:=0 else ScrollInfo.nMin:=MaxInt16; } ScrollInfo.nMin:=0; ScrollInfo.nMax:=MaxInt16; ScrollInfo.nPage:=round(FPageSize*MaxInt16); ScrollInfo.nPos:=round(FPosition*MaxInt16); ScrollInfo.nTrackPos:=ScrollInfo.nPos; SetScrollInfo(FControl.Handle, Code, ScrollInfo, True); needRedraw:=False; end; { TUniViewer } function TUniViewer.GetRealClientSize: TDblPoint; var CS:TPoint; begin CS:=ClientSize; Result.x:=(CS.x-FixedField.x)/FScale.x; Result.y:=(CS.y-FixedField.y)/FScale.y; end; function TUniViewer.GetRealDelta: TDblPoint; begin Result.x:=Delta.x/FScale.x; Result.y:=Delta.y/FScale.y; end; procedure TUniViewer.SetRealSize(const Value: TDblPoint); var NVS:TPoint; // New VSize begin FRealSize:=Value; try NVS.x:=Round(Value.x*FScale.x); NVS.y:=Round(Value.y*FScale.y); VSize:=NVS; except end; end; procedure TUniViewer.SetRealSizeX(const Value: Double); var P:TDblPoint; begin P.X:=Value; P.Y:=FRealSize.Y; SetRealSize(P); end; procedure TUniViewer.SetRealSizeY(const Value: Double); var P:TDblPoint; begin P.X:=FRealSize.X; P.Y:=Value; SetRealSize(P); end; procedure TUniViewer.SetScale(const Value: TDblPoint); var NVS:TPoint; // New VSize begin FScale:=Value; NVS.x:=Round(FRealSize.x*Value.x); NVS.y:=Round(FRealSize.y*Value.y); VSize:=NVS; end; procedure TUniViewer.SetScaleX(const Value: Double); var P:TDblPoint; begin P.X:=Value; P.Y:=FScale.Y; SetScale(P); end; procedure TUniViewer.SetScaleY(const Value: Double); var P:TDblPoint; begin P.X:=FScale.X; P.Y:=Value; SetScale(P); end; function TBufferedScroller.GetPixelFormat: TPixelFormat; begin Result:=Buffer.PixelFormat; end; procedure TBufferedScroller.SetPixelFormat(const Value: TPixelFormat); begin FBuffer.PixelFormat:=Value; end; procedure TBufferedScroller.Resize; begin ChangeSize; inherited; end; procedure TBufferedScroller.ChangeSize; var CS,D:TPoint; begin lockRender; CS:=GetClientSize; D:=Delta; if D.x+CS.x>FVSize.x then begin D.x:=FVSize.x-CS.x; if D.x<0 then D.x:=0; end; if D.y+CS.y>FVSize.y then begin D.y:=FVSize.y-CS.y; if D.y<0 then D.y:=0; end; CalcAndSetPageSize(CS,FVSize); Delta:=D; // validBufferSize:=False; if FBuffer<>nil then render(True); unlockRender; end; function TBufferedScroller.GetBuffer: TBitmap; begin if not validBufferSize then resizeBuffer; Result:=FBuffer; end; procedure TBufferedScroller.lockSetV; begin Inc(setvLockCnt); end; procedure TBufferedScroller.unlockSetV; begin Dec(setvLockCnt); if (setvLockCnt=0) and needSetVSize then SetVSize(FVSize); end; procedure TBufferedScroller.CMMouseLeave(var Msg: TMsg); begin if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); end; procedure TBufferedScroller.Set_HorzSB(const Value: TFPScrollBar); begin FHorzSB.Assign(Value); end; procedure TBufferedScroller.Set_VertSB(const Value: TFPScrollBar); begin FVertSB.Assign(Value); end; end.
unit RangeStrUtils; interface // const rngIncluded = 0; rngUnderflow = -1; rngOverflow = MaxInt; type TRange = record rLow, rHigh : integer; end; type PRanges = ^TRanges; TRanges = record Count : integer; Items : array[0..50] of TRange; end; type TRangeStr = class public constructor Create( const aRange : string ); protected fRangeStr : string; fRangeMin : integer; fRangeMax : integer; fRanges : TRanges; procedure SetRange( const aRange : string ); procedure ParseRangeStr; public property RangeStr : string read fRangeStr write SetRange; property RangeMin : integer read fRangeMin; property RangeMax : integer read fRangeMax; function Includes( Indx : integer ) : integer; procedure Add( FromIndx, ToIndx : integer ); function Next( Indx : integer ) : integer; function Prev( Indx : integer ) : integer; function Nearest( Indx : integer ) : integer; function NearestNext( Indx : integer ) : integer; function NearestPrev( Indx : integer ) : integer; end; implementation uses SysUtils, StrUtils; function GetNextToken( const aRange : string; var aPos : integer ) : string; var i : integer; begin i := Pos( ' ', aRange, aPos + 1 ); if i = 0 then i := length( aRange ) + 1; Result := copy( aRange, aPos, i - aPos ); aPos := i + 1; end; procedure GetTokenValues( const aRange : string; var Min, Max : integer ); var i : integer; begin i := System.Pos( '-', aRange ); if i = 0 // '18' then begin Min := StrToInt( aRange ); Max := Min; end else // '18-25' begin Min := StrToInt( LeftStr( aRange, i - 1 ) ); Max := StrToInt( copy( aRange, i + 1, MaxInt ) ); end; end; procedure Ranges2RangeStr( const Ranges : TRanges; var aRangeStr : string ); var i : integer; begin aRangeStr := ''; with Ranges do for i := 0 to Count - 1 do with Items[i] do if rLow = rHigh then aRangeStr := aRangeStr + IntToStr( rLow ) + ' ' else aRangeStr := aRangeStr + IntToStr( rLow ) + '-' + IntToStr( rHigh ) + ' '; SetLength( aRangeStr, length( aRangeStr ) - 1 ); end; procedure AddTokenToRange( Min, Max : integer; var Ranges : TRanges ); var i : integer; begin with Ranges do begin i := 0; while (i < Count) and (Items[i].rHigh + 1 < Min) do inc( i ); if i = Count then begin // This range is higher than all previous... with Items[Ranges.Count] do begin rLow := Min; rHigh := Max; end; inc( Count ); end else if Min > Items[i].rHigh + 1 then // There is no overlapping... with Items[i] do begin Move( Items[i], Items[i + 1], sizeof( Items[0] ) * ( Count - i + 1 ) ); rLow := Min; rHigh := Max; inc( Count ); end else with Items[i] do begin if rLow > Min // Left Overlapping? then rLow := Min; if rHigh < Max // Right Overlapping? then rHigh := Max; end; end; end; procedure PackRanges( var Ranges : TRanges ); var i : integer; OldLow : integer; begin i := 0; with Ranges do while i < Count - 1 do if Items[i].rHigh + 1 >= Items[i + 1].rLow then begin // overlapping... OldLow := Items[i].rLow; Move( Items[i + 1], Items[i], sizeof( Items[0] ) * ( Count - i + 1 ) ); Items[i].rLow := OldLow; dec( Count ); end else inc( i ); end; procedure RangeStr2Ranges( const aRangeStr : string; var Ranges : TRanges ); var i : integer; Token : string; Min, Max : integer; begin Ranges.Count := 0; i := 1; repeat Token := GetNextToken( aRangeStr, i ); if Token <> '' then begin try GetTokenValues( Token, Min, Max ); AddTokenToRange( Min, Max, Ranges ); except end; end; until Token = ''; PackRanges( Ranges ); end; procedure TRangeStr.ParseRangeStr; begin RangeStr2Ranges( fRangeStr, fRanges ); Ranges2RangeStr( fRanges, fRangeStr ); fRangeMin := fRanges.Items[0].rLow; fRangeMax := fRanges.Items[fRanges.Count - 1].rHigh; end; constructor TRangeStr.Create( const aRange : string ); begin RangeStr := aRange; inherited Create; end; procedure TRangeStr.SetRange( const aRange : string ); begin fRangeStr := ReplaceStr( ReplaceStr( Trim( PackSpaces( aRange ) ), ' -', '-' ), '- ', '-' ); ParseRangeStr; end; procedure TRangeStr.Add( FromIndx, ToIndx : integer ); begin RangeStr := RangeStr + ' ' + IntToStr( FromIndx ) + '-' + IntToStr( ToIndx ); end; function TRangeStr.Includes( Indx : integer ) : integer; var i : integer; begin i := Nearest( Indx ); if i = Indx then Result := rngIncluded else Result := i; end; function TRangeStr.Next( Indx : integer ) : integer; begin Result := NearestNext( Indx + 1 ); end; function TRangeStr.Prev( Indx : integer ) : integer; begin Result := NearestPrev( Indx - 1 ); end; function TRangeStr.NearestNext( Indx : integer ) : integer; var i : integer; begin if (Indx < RangeMin) // Fix needed or (Indx > RangeMax) // Wrap needed then Result := RangeMin else with fRanges do begin i := 0; while Items[i].rHigh < Indx do inc( i ); if ( Indx >= Items[i].rLow ) and ( Indx <= Items[i].rHigh ) then Result := Indx else Result := Items[i].rLow; end; end; function TRangeStr.NearestPrev( Indx : integer ) : integer; var i : integer; begin if (Indx < RangeMin) // Fix needed or (Indx > RangeMax) // Wrap needed then Result := RangeMax else with fRanges do begin i := Count - 1; while Items[i].rLow > Indx do dec( i ); if ( Indx >= Items[i].rLow ) and ( Indx <= Items[i].rHigh ) then Result := Indx else Result := Items[i].rHigh; end; end; function TRangeStr.Nearest( Indx : integer ) : integer; var NextIndx : integer; PrevIndx : integer; begin NextIndx := NearestNext( Indx ); if NextIndx = Indx then Result := NextIndx else begin // Too bad, Indx not in range... PrevIndx := NearestPrev( Indx ); if Indx - PrevIndx > NextIndx - Indx // Get nearest of both then Result := PrevIndx else Result := NextIndx; end; end; end.
{ Helper function that implements synchronous TLS handshake by means of Windows SChannel. The function is transport-agnostic so it could be applied to any socket implementation or even other transport. Inspired by [TLS-Sample](http://www.coastrd.com/c-schannel-smtp) Uses [JEDI API units](https://jedi-apilib.sourceforge.net) (c) Fr0sT-Brutal License MIT } unit SChannel.SyncHandshake; interface {$IFDEF MSWINDOWS} uses Windows, SysUtils, SChannel.JwaBaseTypes, SChannel.JwaWinError, SChannel.JwaWinCrypt, SChannel.JwaSspi, SChannel.JwaSChannel, SChannel.Utils; type // Synchronous communication method. // @param Buf - buffer with data // @param BufLen - size of data in buffer // @returns amount of data sent if >= 0 or error code if < 0. \ // Error code is used to log and create exception. FormatMessage is used to \ // generate a string from error code. \ // Must try to send all data in full, as no retries or repeated sends is done. // @raises exception on some non-network error TSendFn = function (Buf: Pointer; BufLen: Integer): Integer of object; // Synchronous communication method. // @param Buf - buffer to receive data // @param BufLen - size of free space in buffer // @returns amount of data received if >= 0 or error code if < 0. \ // Error code is used to log and create exception. FormatMessage is used to \ // generate a string from error code. \ // Could receive only some of the data available as incomplete packet is \ // read in loop // @raises exception on some non-network error TRecvFn = function (Buf: Pointer; BufLen: Integer): Integer of object; // Specific exception class raised by PerformClientHandshake on communication failures. // Just to distinguish SChannel-level errors from recv/send failures EHandshakeCommError = class(Exception) public ErrCode: DWORD; end; // Synchronously perform full handshake process including communication with server. procedure PerformClientHandshake(var SessionData: TSessionData; const ServerName: string; DebugLogFn: TDebugFn; SendFn: TSendFn; RecvFn: TRecvFn; out hContext: CtxtHandle; out ExtraData: TBytes); {$ENDIF MSWINDOWS} implementation {$IFDEF MSWINDOWS} // ~~ Utils ~~ function CommError(ErrCode: DWORD; const Msg: string): EHandshakeCommError; begin if ErrCode <> 0 then Result := EHandshakeCommError.CreateFmt(Msg, [ErrCode, SysErrorMessage(ErrCode)]) else Result := EHandshakeCommError.Create(Msg); Result.ErrCode := ErrCode; end; // Synchronously perform full handshake process including communication with server. // Communication is done via two callback functions. // @param SessionData - [IN/OUT] record with session data // @param ServerName - name of domain to connect to // @param DebugLogFn - logging callback, could be @nil // @param Data - any data with which `SendFn` and `RecvFn` will be called // @param SendFn - data send callback // @param RecvFn - data read callback // @param hContext - [OUT] receives current session context // @param ExtraData - [OUT] receives extra data sent by server to be decrypted // @raises ESSPIError on SChannel-related failure, // EHandshakeCommError on communication failure procedure PerformClientHandshake(var SessionData: TSessionData; const ServerName: string; DebugLogFn: TDebugFn; SendFn: TSendFn; RecvFn: TRecvFn; out hContext: CtxtHandle; out ExtraData: TBytes); var HandShakeData: THandShakeData; cbData: Integer; HandshakeBug: Boolean; procedure DoHandshakeStart; begin // Generate hello DoClientHandshake(SessionData, HandShakeData, DebugLogFn); Assert(HandShakeData.Stage = hssSendCliHello); // Send hello to server cbData := SendFn(HandShakeData.OutBuffers[0].pvBuffer, HandShakeData.OutBuffers[0].cbBuffer); if cbData <> Integer(HandShakeData.OutBuffers[0].cbBuffer) then if cbData < 0 then raise CommError(Abs(cbData), S_Msg_HShStageW1Fail) else raise CommError(0, S_Msg_HShStageW1Incomplete); Debug(DebugLogFn, Format(S_Msg_HShStageW1Success, [cbData])); g_pSSPI.FreeContextBuffer(HandShakeData.OutBuffers[0].pvBuffer); // Free output buffer. SetLength(HandShakeData.OutBuffers, 0); HandShakeData.Stage := hssReadSrvHello; end; begin HandShakeData := Default(THandShakeData); SessionData.ServerName := ServerName; hContext := Default(CtxtHandle); HandshakeBug := False; try try DoHandshakeStart; // Read hello from server SetLength(HandShakeData.IoBuffer, IO_BUFFER_SIZE); HandShakeData.cbIoBuffer := 0; // Read response until it is complete repeat if HandShakeData.Stage = hssReadSrvHello then begin cbData := RecvFn((PByte(HandShakeData.IoBuffer) + HandShakeData.cbIoBuffer), Length(HandShakeData.IoBuffer) - HandShakeData.cbIoBuffer); if cbData <= 0 then raise CommError(Abs(cbData), S_Msg_HShStageRFail); Debug(DebugLogFn, Format(S_Msg_HShStageRSuccess, [cbData])); Inc(HandShakeData.cbIoBuffer, cbData); end; // Decode hello try DoClientHandshake(SessionData, HandShakeData, DebugLogFn); except on E: ESSPIError do // Hide Windows handshake bug and restart the process for the first time if (HandShakeData.Stage = hssReadSrvHello) and IsWinHandshakeBug(E.SecStatus) and not HandshakeBug then begin Debug(DebugLogFn, Format(S_Msg_HandshakeBug, [E.Message])); HandshakeBug := True; DeleteContext(HandShakeData.hContext); HandShakeData.Stage := hssNotStarted; DoHandshakeStart; Continue; end else raise; end; // Send token if needed if HandShakeData.Stage in [hssReadSrvHelloContNeed, hssReadSrvHelloOK] then begin if (HandShakeData.OutBuffers[0].cbBuffer > 0) and (HandShakeData.OutBuffers[0].pvBuffer <> nil) then begin cbData := SendFn(HandShakeData.OutBuffers[0].pvBuffer, HandShakeData.OutBuffers[0].cbBuffer); if cbData <> Integer(HandShakeData.OutBuffers[0].cbBuffer) then if cbData < 0 then raise CommError(Abs(cbData), S_Msg_HShStageW2Fail) else raise CommError(0, S_Msg_HShStageW2Incomplete); Debug(DebugLogFn, Format(S_Msg_HShStageW2Success, [cbData])); g_pSSPI.FreeContextBuffer(HandShakeData.OutBuffers[0].pvBuffer); // Free output buffer SetLength(HandShakeData.OutBuffers, 0); end; if HandShakeData.Stage = hssReadSrvHelloContNeed then begin HandShakeData.Stage := hssReadSrvHello; Continue; end else if HandShakeData.Stage = hssReadSrvHelloOK then begin if HandShakeData.cbIoBuffer > 0 then Debug(DebugLogFn, Format(S_Msg_HShExtraData, [HandShakeData.cbIoBuffer])); Debug(DebugLogFn, S_Msg_Established); HandShakeData.Stage := hssDone; // useless // Return extra data if any received. 0-length will work as well ExtraData := Copy(HandShakeData.IoBuffer, 0, HandShakeData.cbIoBuffer); Break; end; end; until False; except begin // Delete the security context in the case of a fatal error. DeleteContext(HandShakeData.hContext); raise; end; end; finally begin if Length(HandShakeData.OutBuffers) > 0 then g_pSSPI.FreeContextBuffer(HandShakeData.OutBuffers[0].pvBuffer); // Free output buffer SetLength(HandShakeData.OutBuffers, 0); hContext := HandShakeData.hContext; end; end; end; {$ENDIF MSWINDOWS} end.
{ Subroutine SST_R_PAS_ROUTINE (STR_ROUT_H,V,ARGS_HERE,PROC_P) * * Create a complete routine descriptor. STR_ROUT_H is the string handle to the * whole call. V is the "variable" descriptor * for the routine name. This is either directly a routine name or a variable * with the routine data type. If TRUE, ARGS_HERE indicates that the next * tag read is for the FUNCTION_ARGUMENTS syntax. When FALSE, it indicates * that the routine has no arguments. PROC_P is returned pointing to the * newly created procedure descriptor. It will be completely filled in. } module sst_r_pas_ROUTINE; define sst_r_pas_routine; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_routine ( {create routine descriptor} in str_rout_h: syo_string_t; {string handle to whole call} in v: sst_var_t; {"variable" descriptor for routine name} in args_here: boolean; {TRUE if FUNCTION_ARGUMENTS syntax exists} out proc_p: sst_proc_p_t); {will point to new routine descriptor} var template_p: sst_proc_p_t; {points to template for this routine} arg_pp: sst_proc_arg_pp_t; {where to put pointer to next arg descriptor} arg_p: sst_proc_arg_p_t; {points to current call argument} argt_p: sst_proc_arg_p_t; {pointer to argument descriptor from template} tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} stat: sys_err_t; {completion status code} label done_args, next_arg, var_not_rout; begin if v.vtype <> sst_vtype_rout_k {variable does not refer to a routine ?} then goto var_not_rout; template_p := v.rout_proc_p; {get pointer to routine template} { * The variable descriptor references a legal routine, and TEMPLATE_P points * to the routine template descriptor. } sst_mem_alloc_scope (sizeof(proc_p^), proc_p); {alloc mem for routine descriptor} proc_p^ := template_p^; {init routine descriptor from template} proc_p^.n_args := 0; {init to no call arguments so far} proc_p^.first_arg_p := nil; if not args_here then goto done_args; {no call arguments to process ?} { * The FUNCTION_ARGUMENTS syntax exists. Now process the call arguments. } syo_level_down; {down into FUNCTION_ARGUMENTS syntax} arg_pp := addr(proc_p^.first_arg_p); {adr of where to put pointer to next arg} argt_p := template_p^.first_arg_p; {init pointer to template for argument} next_arg: {back here each new call argument} syo_get_tag_msg ( {get tag to this call argument} tag, str_h, 'sst_pas_read', 'args_syntax_err', nil, 0); if tag = syo_tag_end_k then begin {done with all the call arguments ?} syo_level_up; {back up from FUNCTION_ARGUMENTS syntax} goto done_args; end; if tag <> 1 {illegal TAG value ?} then syo_error_tag_unexp (tag, str_h); proc_p^.n_args := proc_p^.n_args + 1; {one more call argument} sst_mem_alloc_scope (sizeof(arg_p^), arg_p); {allocate mem for argument descriptor} arg_pp^ := arg_p; {link new arg descriptor to end of chain} arg_pp := addr(arg_p^.next_p); {save adr of where next arg pointer goes} arg_p^.next_p := nil; {init argument descriptor} arg_p^.sym_p := nil; arg_p^.name_p := nil; if argt_p <> nil then arg_p^.pass := argt_p^.pass else arg_p^.pass := sst_pass_none_k; arg_p^.univ := false; sst_r_pas_exp (str_h, false, arg_p^.exp_p); {create expression descriptor for arg} arg_p^.dtype_p := arg_p^.exp_p^.dtype_p; {argument data type comes from expression} arg_p^.rwflag_ext := arg_p^.exp_p^.rwflag; {get access permission for this argument} if argt_p <> nil {advance to next argument template} then argt_p := argt_p^.next_p; goto next_arg; {back to process next call argument} { * All done handling call arguments. These are all filled in if they exist * at all. * * Now verify that the call matches the procedure template. } done_args: {definately done processing call arguments} sst_routines_match (template_p^, proc_p^, stat); {check call against template} syo_error_abort (stat, str_rout_h, '', '', nil, 0); return; var_not_rout: {"variable" descriptor not indicate a routine} syo_error (str_rout_h, 'sst_pas_read', 'not_a_procedure', nil, 0); end;
unit xdg_output_unstable_v1_protocol; {$mode objfpc} {$H+} {$interfaces corba} interface uses Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol; type Pzxdg_output_manager_v1 = Pointer; Pzxdg_output_v1 = Pointer; Pzxdg_output_manager_v1_listener = ^Tzxdg_output_manager_v1_listener; Tzxdg_output_manager_v1_listener = record end; Pzxdg_output_v1_listener = ^Tzxdg_output_v1_listener; Tzxdg_output_v1_listener = record logical_position : procedure(data: Pointer; AZxdgOutputV1: Pzxdg_output_v1; AX: LongInt; AY: LongInt); cdecl; logical_size : procedure(data: Pointer; AZxdgOutputV1: Pzxdg_output_v1; AWidth: LongInt; AHeight: LongInt); cdecl; done : procedure(data: Pointer; AZxdgOutputV1: Pzxdg_output_v1); cdecl; name : procedure(data: Pointer; AZxdgOutputV1: Pzxdg_output_v1; AName: Pchar); cdecl; description : procedure(data: Pointer; AZxdgOutputV1: Pzxdg_output_v1; ADescription: Pchar); cdecl; end; TZxdgOutputManagerV1 = class; TZxdgOutputV1 = class; IZxdgOutputManagerV1Listener = interface ['IZxdgOutputManagerV1Listener'] end; IZxdgOutputV1Listener = interface ['IZxdgOutputV1Listener'] procedure zxdg_output_v1_logical_position(AZxdgOutputV1: TZxdgOutputV1; AX: LongInt; AY: LongInt); procedure zxdg_output_v1_logical_size(AZxdgOutputV1: TZxdgOutputV1; AWidth: LongInt; AHeight: LongInt); procedure zxdg_output_v1_done(AZxdgOutputV1: TZxdgOutputV1); procedure zxdg_output_v1_name(AZxdgOutputV1: TZxdgOutputV1; AName: String); procedure zxdg_output_v1_description(AZxdgOutputV1: TZxdgOutputV1; ADescription: String); end; TZxdgOutputManagerV1 = class(TWLProxyObject) private const _DESTROY = 0; const _GET_XDG_OUTPUT = 1; public destructor Destroy; override; function GetXdgOutput(AOutput: TWlOutput; AProxyClass: TWLProxyObjectClass = nil {TZxdgOutputV1}): TZxdgOutputV1; function AddListener(AIntf: IZxdgOutputManagerV1Listener): LongInt; end; TZxdgOutputV1 = class(TWLProxyObject) private const _DESTROY = 0; public destructor Destroy; override; function AddListener(AIntf: IZxdgOutputV1Listener): LongInt; end; var zxdg_output_manager_v1_interface: Twl_interface; zxdg_output_v1_interface: Twl_interface; implementation var vIntf_zxdg_output_manager_v1_Listener: Tzxdg_output_manager_v1_listener; vIntf_zxdg_output_v1_Listener: Tzxdg_output_v1_listener; destructor TZxdgOutputManagerV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgOutputManagerV1.GetXdgOutput(AOutput: TWlOutput; AProxyClass: TWLProxyObjectClass = nil {TZxdgOutputV1}): TZxdgOutputV1; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _GET_XDG_OUTPUT, @zxdg_output_v1_interface, nil, AOutput.Proxy); if AProxyClass = nil then AProxyClass := TZxdgOutputV1; Result := TZxdgOutputV1(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZxdgOutputV1) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZxdgOutputV1]); end; function TZxdgOutputManagerV1.AddListener(AIntf: IZxdgOutputManagerV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_output_manager_v1_Listener, @FUserDataRec); end; destructor TZxdgOutputV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZxdgOutputV1.AddListener(AIntf: IZxdgOutputV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zxdg_output_v1_Listener, @FUserDataRec); end; procedure zxdg_output_v1_logical_position_Intf(AData: PWLUserData; Azxdg_output_v1: Pzxdg_output_v1; AX: LongInt; AY: LongInt); cdecl; var AIntf: IZxdgOutputV1Listener; begin if AData = nil then Exit; AIntf := IZxdgOutputV1Listener(AData^.ListenerUserData); AIntf.zxdg_output_v1_logical_position(TZxdgOutputV1(AData^.PascalObject), AX, AY); end; procedure zxdg_output_v1_logical_size_Intf(AData: PWLUserData; Azxdg_output_v1: Pzxdg_output_v1; AWidth: LongInt; AHeight: LongInt); cdecl; var AIntf: IZxdgOutputV1Listener; begin if AData = nil then Exit; AIntf := IZxdgOutputV1Listener(AData^.ListenerUserData); AIntf.zxdg_output_v1_logical_size(TZxdgOutputV1(AData^.PascalObject), AWidth, AHeight); end; procedure zxdg_output_v1_done_Intf(AData: PWLUserData; Azxdg_output_v1: Pzxdg_output_v1); cdecl; var AIntf: IZxdgOutputV1Listener; begin if AData = nil then Exit; AIntf := IZxdgOutputV1Listener(AData^.ListenerUserData); AIntf.zxdg_output_v1_done(TZxdgOutputV1(AData^.PascalObject)); end; procedure zxdg_output_v1_name_Intf(AData: PWLUserData; Azxdg_output_v1: Pzxdg_output_v1; AName: Pchar); cdecl; var AIntf: IZxdgOutputV1Listener; begin if AData = nil then Exit; AIntf := IZxdgOutputV1Listener(AData^.ListenerUserData); AIntf.zxdg_output_v1_name(TZxdgOutputV1(AData^.PascalObject), AName); end; procedure zxdg_output_v1_description_Intf(AData: PWLUserData; Azxdg_output_v1: Pzxdg_output_v1; ADescription: Pchar); cdecl; var AIntf: IZxdgOutputV1Listener; begin if AData = nil then Exit; AIntf := IZxdgOutputV1Listener(AData^.ListenerUserData); AIntf.zxdg_output_v1_description(TZxdgOutputV1(AData^.PascalObject), ADescription); end; const pInterfaces: array[0..9] of Pwl_interface = ( (nil), (nil), (nil), (nil), (nil), (nil), (nil), (nil), (@zxdg_output_v1_interface), (@wl_output_interface) ); zxdg_output_manager_v1_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'get_xdg_output'; signature: 'no'; types: @pInterfaces[8]) ); zxdg_output_v1_requests: array[0..0] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]) ); zxdg_output_v1_events: array[0..4] of Twl_message = ( (name: 'logical_position'; signature: 'ii'; types: @pInterfaces[0]), (name: 'logical_size'; signature: 'ii'; types: @pInterfaces[0]), (name: 'done'; signature: ''; types: @pInterfaces[0]), (name: 'name'; signature: '2s'; types: @pInterfaces[0]), (name: 'description'; signature: '2s'; types: @pInterfaces[0]) ); initialization Pointer(vIntf_zxdg_output_v1_Listener.logical_position) := @zxdg_output_v1_logical_position_Intf; Pointer(vIntf_zxdg_output_v1_Listener.logical_size) := @zxdg_output_v1_logical_size_Intf; Pointer(vIntf_zxdg_output_v1_Listener.done) := @zxdg_output_v1_done_Intf; Pointer(vIntf_zxdg_output_v1_Listener.name) := @zxdg_output_v1_name_Intf; Pointer(vIntf_zxdg_output_v1_Listener.description) := @zxdg_output_v1_description_Intf; zxdg_output_manager_v1_interface.name := 'zxdg_output_manager_v1'; zxdg_output_manager_v1_interface.version := 2; zxdg_output_manager_v1_interface.method_count := 2; zxdg_output_manager_v1_interface.methods := @zxdg_output_manager_v1_requests; zxdg_output_manager_v1_interface.event_count := 0; zxdg_output_manager_v1_interface.events := nil; zxdg_output_v1_interface.name := 'zxdg_output_v1'; zxdg_output_v1_interface.version := 2; zxdg_output_v1_interface.method_count := 1; zxdg_output_v1_interface.methods := @zxdg_output_v1_requests; zxdg_output_v1_interface.event_count := 5; zxdg_output_v1_interface.events := @zxdg_output_v1_events; end.
unit BFixer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Path: TEdit; Label1: TLabel; Forums: TListBox; Label2: TLabel; Search: TButton; Fix: TButton; procedure SearchClick(Sender: TObject); procedure FixClick(Sender: TObject); private procedure FixForum( name: string ); end; var Form1: TForm1; implementation {$R *.DFM} const tidPrefix_Author = 'Author'; tidPrefix_Subject = 'Subject'; tidPrefix_Id = 'Id'; tidPrefix_UId = 'UId'; tidPrefix_TimeStamp = 'TimeStamp'; tidPrefix_Kind = 'Kind'; tidFileExt_Topic = '.topic'; tidFileExt_Post = '.post'; tidProperty_Modified = 'Modified'; tidProperty_PostCount = 'PostCount'; tidProperty_PollItemsCount = 'PollItemCount'; tidProperty_PollItemDesc = 'PollItemDesc'; tidProperty_PollItemVotes = 'PollItemVotes'; tidFileName_TopicIdx = 'topic.index'; procedure TForm1.SearchClick(Sender: TObject); var SearchRec : TSearchRec; found : integer; begin if Path.Text = '' then MessageDlg( 'You have to specify a path !', mtError, [mbOk], 0 ) else begin Forums.Items.Clear; found := FindFirst( Path.Text + '\*', faDirectory, SearchRec ); try while found = 0 do begin if ((SearchRec.Attr and faDirectory) = faDirectory) and (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then Forums.Items.Add( SearchRec.Name ); found := FindNext( SearchRec ); end; finally FindClose( SearchRec ); end; Fix.Enabled := true; end; end; procedure TForm1.FixClick(Sender: TObject); var i : integer; begin if Forums.SelCount = 0 then MessageDlg( 'You have to select some forums from the list !', mtError, [mbOk], 0 ) else for i := 0 to Forums.Items.Count - 1 do if Forums.Selected[i] then begin FixForum( Forums.Items[i] ); Forums.Items[i] := Forums.Items[i] + ' --> FIXED!'; end; end; procedure TForm1.FixForum( name: string ); var folder : string; SearchRec : TSearchRec; found : integer; Topics : TStringList; RepCount : integer; TopicIdx : TStringList; DateStamp : string; i : integer; TopicPath : string; begin folder := Path.Text + '\' + name; Topics := TStringList.Create; try found := FindFirst( folder + '\*' + tidFileExt_Topic, faAnyFile, SearchRec ); try while found = 0 do begin Topics.Add( SearchRec.Name ); found := FindNext( SearchRec ); end; finally FindClose( SearchRec ); end; if Topics.Count > 0 then for i := 0 to Topics.Count - 1 do begin TopicPath := folder + '\' + Topics[i]; RepCount := 0; found := FindFirst( TopicPath + '\*' + tidFileExt_Post, faAnyFile, SearchRec ); try while found = 0 do begin inc( RepCount ); found := FindNext( SearchRec ); end; finally FindClose( SearchRec ); end; TopicIdx := TStringList.Create; try TopicIdx.LoadFromFile( TopicPath + '\' + tidFileName_TopicIdx ); DateStamp := TopicIdx.Values[tidProperty_Modified]; finally TopicIdx.Free; end; if DateStamp <> '' then begin TopicIdx := TStringList.Create; try try TopicIdx.LoadFromFile( TopicPath + '\' + tidFileName_TopicIdx ); except end; TopicIdx.Values[tidProperty_Modified] := DateStamp; TopicIdx.Values[tidProperty_PostCount] := IntToStr( RepCount ); TopicIdx.SaveToFile( TopicPath + '\' + tidFileName_TopicIdx ); finally TopicIdx.Free; end; end; end; finally Topics.Free; end; end; end.
unit u_Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Menus, u_Usuario, u_Empresa, u_Cliente, u_Fornecedor, u_Produto, u_FormaPgto, u_Compra; type TfrmPrincipal = class(TForm) Panel1: TPanel; btnUsuario: TSpeedButton; btnEmpresa: TSpeedButton; btnCliente: TSpeedButton; btnFornecedor: TSpeedButton; btnProduto: TSpeedButton; btnFormaPgto: TSpeedButton; btnCompra: TSpeedButton; btnVenda: TSpeedButton; btnTrocarUsuario: TSpeedButton; btnFechar: TSpeedButton; StatusBar1: TStatusBar; Timer1: TTimer; MainMenu1: TMainMenu; Cadastro1: TMenuItem; menuUsuario: TMenuItem; menuEmpresa: TMenuItem; menuCliente: TMenuItem; menuFornecedores: TMenuItem; menuProdutos: TMenuItem; menuFormaPgto: TMenuItem; Movimentos1: TMenuItem; Compras1: TMenuItem; Vendas1: TMenuItem; Relatrios1: TMenuItem; ListaUsurios1: TMenuItem; ListaFornecedores1: TMenuItem; ListaClientes1: TMenuItem; ListaProdutos1: TMenuItem; ListaCompras1: TMenuItem; ListaVendas1: TMenuItem; Sobreosistema1: TMenuItem; procedure Timer1Timer(Sender: TObject); procedure btnFecharClick(Sender: TObject); procedure btnUsuarioClick(Sender: TObject); procedure AbreTelaUsuario(); procedure btnEmpresaClick(Sender: TObject); procedure AbreTelaEmpresa(); procedure menuUsuarioClick(Sender: TObject); procedure menuEmpresaClick(Sender: TObject); procedure btnClienteClick(Sender: TObject); procedure AbreTelaCliente(); procedure menuClienteClick(Sender: TObject); procedure btnFornecedorClick(Sender: TObject); procedure AbreTelaFornecedor(); procedure menuFornecedoresClick(Sender: TObject); procedure btnProdutoClick(Sender: TObject); procedure AbreTelaProduto(); procedure menuProdutosClick(Sender: TObject); procedure btnFormaPgtoClick(Sender: TObject); procedure AbreTelaFormaPgto(); procedure menuFormaPgtoClick(Sender: TObject); procedure btnCompraClick(Sender: TObject); Procedure AbreTelaCompra(); private { Private declarations } public { Public declarations } end; var frmPrincipal: TfrmPrincipal; implementation {$R *.dfm} procedure TfrmPrincipal.btnFecharClick(Sender: TObject); begin if messagedlg('Deseja realmente sair do sistema?',mtConfirmation,[mbOk,mbNo],0)=mrOk then begin Application.Terminate; end else begin abort; end; end; procedure TfrmPrincipal.btnEmpresaClick(Sender: TObject); begin AbreTelaEmpresa; end; procedure TfrmPrincipal.btnClienteClick(Sender: TObject); begin AbreTelaCliente; end; procedure TfrmPrincipal.btnCompraClick(Sender: TObject); begin AbreTelaCompra; end; procedure TfrmPrincipal.btnFormaPgtoClick(Sender: TObject); begin AbreTelaFormaPgto; end; procedure TfrmPrincipal.btnFornecedorClick(Sender: TObject); begin AbreTelaFornecedor; end; procedure TfrmPrincipal.btnProdutoClick(Sender: TObject); begin AbreTelaProduto; end; procedure TfrmPrincipal.AbreTelaCliente; begin frmCliente:=TfrmCliente.Create(self); frmCliente.ShowModal; try finally frmCliente.Free; frmCliente:=nil;//LIMPANDO A MEMORIA end; end; procedure TfrmPrincipal.AbreTelaCompra; begin frmCompra:=TfrmCOmpra.Create(self); frmCompra.ShowModal; try finally frmCompra.Free; frmCompra:=nil; end; end; procedure TfrmPrincipal.AbreTelaEmpresa; begin frmEmpresa:=TfrmEmpresa.Create(self); frmEmpresa.ShowModal; try finally frmEmpresa.Free; frmEmpresa:=nil;//LIMPANDO A MEMORIA end; end; procedure TfrmPrincipal.AbreTelaFormaPgto; begin frmFormaPgto:=TfrmFormaPgto.create(self); frmFormaPgto.ShowModal; try finally frmFormaPgto.Free; frmFormaPgto:=nil; end; end; procedure TfrmPrincipal.AbreTelaFornecedor; begin frmFornecedor:=TfrmFornecedor.Create(self); //O FORM ESTA CRIANDO E RECEBENDO ELE MESMO frmFornecedor.ShowModal; //NO SHOW MODAL SÓ PODE MEXER NA TELA QUE ESTA ABERTA try finally frmFornecedor.Free; frmFornecedor:=nil; end; end; procedure TfrmPrincipal.AbreTelaProduto; begin frmProduto:=TfrmProduto.create(self); frmProduto.ShowModal; try finally frmProduto.Free; frmProduto:=nil; end; end; procedure TfrmPrincipal.AbreTelaUsuario; begin frmUsuario:=TfrmUsuario.Create(self); frmUsuario.ShowModal; try finally frmUsuario.Free; frmUsuario:=nil; end; end; procedure TfrmPrincipal.btnUsuarioClick(Sender: TObject); begin AbreTelaUsuario; end; procedure TfrmPrincipal.menuClienteClick(Sender: TObject); begin AbreTelaCliente; end; procedure TfrmPrincipal.menuEmpresaClick(Sender: TObject); begin AbreTelaEmpresa; end; procedure TfrmPrincipal.menuFormaPgtoClick(Sender: TObject); begin AbreTelaFormaPgto; end; procedure TfrmPrincipal.menuFornecedoresClick(Sender: TObject); begin AbreTelaFornecedor; end; procedure TfrmPrincipal.menuProdutosClick(Sender: TObject); begin AbreTelaProduto; end; procedure TfrmPrincipal.Timer1Timer(Sender: TObject); begin //insere dados no status bar Statusbar1.Panels[0].Text:=DateTostr(now); Statusbar1.Panels[1].Text:=TimeTostr(now); Statusbar1.Panels[2].Text:=' SEJA BEM VINDO AO SISTEMA'; end; procedure TfrmPrincipal.menuUsuarioClick(Sender: TObject); begin AbreTelaUsuario; end; end.
unit jc.DateUtils; interface uses Windows, Messages, SysUtils, Classes, DateUtils; function DateToText(ADate: TDateTime): string; Function DateTimeToText(ADateTime: TDateTime): string; function TextToDate(ADate: string): TDateTime; implementation function DateToText(ADate: TDateTime): string; begin if ADate > 0 then Result := FormatDateTime('YYYY-MM-DD',ADate) else Result := '0000-00-00'; end; Function DateTimeToText(ADateTime: TDateTime): string; begin if ADateTime > 0 then Result := FormatDateTime('YYYY-MM-DDTHH:MM:SEG', ADateTime) else Result := '0000-00-00T00:00:00'; end; Function DateToTextBr(ADate: TDateTime): string; begin if ADate > 0 then Result := FormatDateTime('DD-MM-YYYY', ADate) else Result := '00-00-0000'; end; Function DateToDateTime(ADate: TDateTime): TDateTime; var Dia, Mes, Ano, Hor, Min, Seg, Mis: Word; begin if (ADate > 0) then begin DecodeDateTime(Now, Ano, Mes, Dia, Hor, Min, Seg, Mis); DecodeDate(ADate, Ano, Mes, Dia); Result := EncodeDateTime(Ano, Mes, Dia, Hor, Min, Seg, 0); end else Result := 0; end; function TextToDate(ADate: string): TDateTime; var Dia, Mes, Ano: Integer; begin if (ADate <> '') AND (ADate <> '0000-00-00') then begin Dia := StrToInt(Copy(ADate,9,2)); Mes := StrToInt(Copy(ADate,6,2)); Ano := StrToInt(Copy(ADate,1,4)); Result := EncodeDate(Ano,Mes,Dia); end else Result := 0; end; function TextToDateTime(ADateTime: string): TDateTime; var Dia, Mes, Ano, Hor, Min, Seg: Integer; begin if (ADateTime <> '') AND (ADateTime <> '0000-00-00T00:00:00') then begin Dia := StrToInt(Copy(ADateTime,9,2)); Mes := StrToInt(Copy(ADateTime,6,2)); Ano := StrToInt(Copy(ADateTime,1,4)); Hor := StrToInt(Copy(ADateTime,12,2)); Min := StrToInt(Copy(ADateTime,15,2)); Seg := StrToInt(Copy(ADateTime,18,2)); Result := EncodeDateTime(Ano,Mes,Dia, Hor, Min, Seg, 0); end else Result := 0; end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.ZeroMQ.Settings; { Persistable settings for ZeroMQ receiver. } interface uses System.Classes, Spring; type TZeroMQSettings = class(TPersistent) const DEFAULT_POLLING_INTERVAL = 100; private FOnChanged : Event<TNotifyEvent>; FEnabled : Boolean; FEndpoints : TStrings; FPollingInterval : Integer; protected {$REGION 'property access methods'} function GetPollingInterval: Integer; procedure SetPollingInterval(const Value: Integer); function GetEndpoints: TStrings; function GetEnabled: Boolean; procedure SetEnabled(const Value: Boolean); function GetOnChanged: IEvent<TNotifyEvent>; {$ENDREGION} procedure Changed; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure Assign(Source: TPersistent); override; property OnChanged: IEvent<TNotifyEvent> read GetOnChanged; published property Enabled: Boolean read GetEnabled write SetEnabled; property PollingInterval: Integer // in ms read GetPollingInterval write SetPollingInterval default DEFAULT_POLLING_INTERVAL; property Endpoints: TStrings read GetEndpoints; end; implementation {$REGION 'construction and destruction'} procedure TZeroMQSettings.AfterConstruction; begin inherited AfterConstruction; FEndpoints := TStringList.Create; FPollingInterval := DEFAULT_POLLING_INTERVAL; end; procedure TZeroMQSettings.BeforeDestruction; begin FEndpoints.Free; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'property access methods'} function TZeroMQSettings.GetOnChanged: IEvent<TNotifyEvent>; begin Result := FOnChanged; end; function TZeroMQSettings.GetEndpoints: TStrings; begin Result := FEndpoints; end; function TZeroMQSettings.GetPollingInterval: Integer; begin Result := FPollingInterval; end; procedure TZeroMQSettings.SetPollingInterval(const Value: Integer); begin if Value <> PollingInterval then begin FPollingInterval := Value; Changed; end; end; function TZeroMQSettings.GetEnabled: Boolean; begin Result := FEnabled; end; procedure TZeroMQSettings.SetEnabled(const Value: Boolean); begin if Value <> Enabled then begin FEnabled := Value; Changed; end; end; {$ENDREGION} {$REGION 'protected methods'} procedure TZeroMQSettings.Changed; begin FOnChanged.Invoke(Self); end; {$ENDREGION} {$REGION 'public methods'} procedure TZeroMQSettings.Assign(Source: TPersistent); var LSettings: TZeroMQSettings; begin if Source is TZeroMQSettings then begin LSettings := TZeroMQSettings(Source); Enabled := LSettings.Enabled; PollingInterval := LSettings.PollingInterval; FEndpoints.Assign(LSettings.Endpoints); end else inherited Assign(Source); end; {$ENDREGION} end.
unit DataObjectUnit; interface uses REST.Json.Types, System.Generics.Collections, SysUtils, Generics.Defaults, JSONNullableAttributeUnit, EnumsUnit, AddressUnit, RouteParametersUnit, DirectionUnit, CommonTypesUnit, NullableBasicTypesUnit, LinksUnit, TrackingHistoryUnit, DirectionPathPointUnit; type TDataObjectRoute = class; TDataObjectRouteArray = TArray<TDataObjectRoute>; /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Optimization_response.dtd /// </remarks> TDataObject = class strict private [JSONName('optimization_problem_id')] FOptimizationProblemId: String; [JSONName('state')] FState: Integer; [JSONName('user_errors')] FUserErrors: TStringArray; [JSONName('sent_to_background')] [Nullable] FIsSentToBackground: NullableBoolean; [JSONName('addresses')] FAddresses: TAddressesArray; [JSONName('parameters')] FParameters: TRouteParameters; [JSONName('routes')] FRoutes: TDataObjectRouteArray; [JSONName('links')] FLinks: TLinks; [JSONName('tracking_history')] FTrackingHistories: TTrackingHistoryArray; function GetState: TOptimizationState; procedure SetState(const Value: TOptimizationState); public constructor Create; destructor Destroy; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// Optimization which generated this route /// </summary> property OptimizationProblemId: String read FOptimizationProblemId write FOptimizationProblemId; /// <summary> /// An optimization problem can be at one state at any given time /// Initial = 1 /// MatrixProcessing = 2 /// Optimizing = 3 /// Optimized = 4 /// Error = 5 /// ComputingDirections = 6 /// </summary> property State: TOptimizationState read GetState write SetState; /// <summary> /// User Errors /// </summary> property UserErrors: TStringArray read FUserErrors write FUserErrors; /// <summary> /// If true it means the solution was not returned (it is being computed in the background) /// </summary> property IsSentToBackground: NullableBoolean read FIsSentToBackground write FIsSentToBackground; /// <summary> /// Route Addresses /// </summary> property Addresses: TAddressesArray read FAddresses; procedure AddAddress(Address: TAddress); /// <summary> /// Route Parameters /// </summary> property Parameters: TRouteParameters read FParameters write FParameters; /// <summary> /// Routes /// </summary> property Routes: TDataObjectRouteArray read FRoutes; procedure AddRoute(Route: TDataObjectRoute); /// <summary> /// Links to the GET operations for the optimization problem /// </summary> property Links: TLinks read FLinks write FLinks; /// <summary> /// A collection of device tracking data with coordinates, speed, and timestamps /// </summary> property TrackingHistories: TTrackingHistoryArray read FTrackingHistories write FTrackingHistories; end; TDataObjectList = TObjectList<TDataObject>; TDataObjectRoute = class(TDataObject) strict private [JSONName('route_id')] FRouteId: String; [JSONName('member_id')] [Nullable] FMemberId: NullableString; [JSONName('member_email')] [Nullable] FMemberEmail: NullableString; [JSONName('vehicle_alias')] [Nullable] FVehicleAlias: NullableString; [JSONName('driver_alias')] [Nullable] FDriverAlias: NullableString; [JSONName('route_cost')] [Nullable] FRouteCost: NullableDouble; [JSONName('route_revenue')] [Nullable] FRouteRevenue: NullableDouble; [JSONName('net_revenue_per_distance_unit')] [Nullable] FNetRevenuePerDistanceUnit: NullableDouble; [JSONName('created_timestamp')] [Nullable] FCreatedTimestamp: NullableInteger; [JSONName('mpg')] [Nullable] FMpg: NullableString; [JSONName('trip_distance')] [Nullable] FTripDistance: NullableDouble; [JSONName('gas_price')] [Nullable] FGasPrice: NullableDouble; [JSONName('route_duration_sec')] [Nullable] FRouteDurationSec: NullableInteger; [JSONName('directions')] FDirections: TDirectionArray; [JSONName('path')] FDirectionPathPoints: TDirectionPathPointArray; public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; overload; constructor Create(RouteId: String); overload; function Equals(Obj: TObject): Boolean; override; property RouteId: String read FRouteId write FRouteId; property MemberId: NullableString read FMemberId write FMemberId; property MemberEmail: NullableString read FMemberEmail write FMemberEmail; property VehicleAlias: NullableString read FVehicleAlias write FVehicleAlias; property DriverAlias: NullableString read FDriverAlias write FDriverAlias; property RouteCost: NullableDouble read FRouteCost write FRouteCost; property RouteRevenue: NullableDouble read FRouteRevenue write FRouteRevenue; property NetRevenuePerDistanceUnit: NullableDouble read FNetRevenuePerDistanceUnit write FNetRevenuePerDistanceUnit; property CreatedTimestamp: NullableInteger read FCreatedTimestamp write FCreatedTimestamp; property Mpg: NullableString read FMpg write FMpg; property TripDistance: NullableDouble read FTripDistance write FTripDistance; property GasPrice: NullableDouble read FGasPrice write FGasPrice; property RouteDurationSec: NullableInteger read FRouteDurationSec write FRouteDurationSec; /// <summary> /// Edge by edge turn-by-turn directions. /// Note: For round-trip routes (parameters.rt = true), the return to the start address is returned as well /// </summary> property Directions: TDirectionArray read FDirections write FDirections; /// <summary> /// Edge-wise path to be drawn on the map /// </summary> property Path: TDirectionPathPointArray read FDirectionPathPoints write FDirectionPathPoints; end; TDataObjectRouteList = TObjectList<TDataObjectRoute>; function SortRoutes(Routes: TDataObjectRouteArray): TDataObjectRouteArray; implementation uses UtilsUnit; function SortRoutes(Routes: TDataObjectRouteArray): TDataObjectRouteArray; begin SetLength(Result, Length(Routes)); if Length(Routes) = 0 then Exit; TArray.Copy<TDataObjectRoute>(Routes, Result, Length(Routes)); TArray.Sort<TDataObjectRoute>(Result, TComparer<TDataObjectRoute>.Construct( function (const Route1, Route2: TDataObjectRoute): Integer begin Result := String.Compare(Route1.RouteId, Route2.RouteId); end)); end; { TDataObject } procedure TDataObject.AddAddress(Address: TAddress); begin SetLength(FAddresses, Length(FAddresses) + 1); FAddresses[High(FAddresses)] := Address; end; procedure TDataObject.AddRoute(Route: TDataObjectRoute); begin SetLength(FRoutes, Length(FRoutes) + 1); FRoutes[High(FRoutes)] := Route; end; constructor TDataObject.Create; begin FState := 0; FIsSentToBackground := NullableBoolean.Null; SetLength(FUserErrors, 0); SetLength(FAddresses, 0); FParameters := nil; SetLength(FRoutes, 0); FLinks := nil; SetLength(FTrackingHistories, 0); end; destructor TDataObject.Destroy; var i: integer; begin for i := Length(FAddresses) - 1 downto 0 do FreeAndNil(FAddresses[i]); for i := Length(FRoutes) - 1 downto 0 do FreeAndNil(FRoutes[i]); inherited; end; function TDataObject.Equals(Obj: TObject): Boolean; var Other: TDataObject; i: integer; SortedAddresses1, SortedAddresses2: TAddressesArray; SortedUserErrors1, SortedUserErrors2: TStringArray; SortedRoutes1, SortedRoutes2: TDataObjectRouteArray; SortedTrackingHistory1, SortedTrackingHistory2: TTrackingHistoryArray; begin Result := False; if not (Obj is TDataObject) then Exit; Other := TDataObject(Obj); Result := (FOptimizationProblemId = Other.FOptimizationProblemId) and (FState = Other.FState) and (FIsSentToBackground = Other.FIsSentToBackground) and (FParameters.Equals(Other.FParameters)) and (FLinks.Equals(Other.FLinks)); if (not Result) then Exit; Result := False; if (Length(UserErrors) <> Length(Other.UserErrors)) or (Length(Addresses) <> Length(Other.Addresses)) or (Length(Routes) <> Length(Other.Routes)) or (Length(TrackingHistories) <> Length(Other.TrackingHistories)) then Exit; SortedUserErrors1 := TUtils.SortStringArray(UserErrors); SortedUserErrors2 := TUtils.SortStringArray(Other.UserErrors); for i := 0 to Length(SortedUserErrors1) - 1 do if not SortedUserErrors1[i].Equals(SortedUserErrors2[i]) then Exit; SortedAddresses1 := AddressUnit.SortAddresses(Addresses); SortedAddresses2 := AddressUnit.SortAddresses(Other.Addresses); for i := 0 to Length(SortedAddresses1) - 1 do if (not SortedAddresses1[i].Equals(SortedAddresses2[i])) then Exit; SortedRoutes1 := SortRoutes(Routes); SortedRoutes2 := SortRoutes(Other.Routes); for i := 0 to Length(SortedRoutes1) - 1 do if (not SortedRoutes1[i].Equals(SortedRoutes2[i])) then Exit; SortedTrackingHistory1 := TrackingHistoryUnit.SortTrackingHistory(TrackingHistories); SortedTrackingHistory2 := TrackingHistoryUnit.SortTrackingHistory(Other.TrackingHistories); for i := 0 to Length(SortedTrackingHistory1) - 1 do if (not SortedTrackingHistory1[i].Equals(SortedTrackingHistory2[i])) then Exit; Result := True; end; { TDataObjectRoute } function TDataObject.GetState: TOptimizationState; begin Result := TOptimizationState(FState); end; procedure TDataObject.SetState(const Value: TOptimizationState); begin FState := Integer(Value); end; constructor TDataObjectRoute.Create; begin FRouteId := EmptyStr; FMemberId := NullableString.Null; FMemberEmail := NullableString.Null; FVehicleAlias := NullableString.Null; FDriverAlias := NullableString.Null; FRouteCost := NullableDouble.Null; FRouteRevenue := NullableDouble.Null; FNetRevenuePerDistanceUnit := NullableDouble.Null; FCreatedTimestamp := NullableInteger.Null; FMpg := NullableString.Null; FTripDistance := NullableDouble.Null; FGasPrice := NullableDouble.Null; FRouteDurationSec := NullableInteger.Null; SetLength(FDirections, 0); SetLength(FDirectionPathPoints, 0); end; { TDataObjectRoute } constructor TDataObjectRoute.Create(RouteId: String); begin Create; FRouteId := RouteId; end; function TDataObjectRoute.Equals(Obj: TObject): Boolean; var Other: TDataObjectRoute; SortedDirections1, SortedDirections2: TDirectionArray; SortedDirectionPathPoints1, SortedDirectionPathPoints2: TDirectionPathPointArray; i: integer; begin Result := inherited Equals(Obj); if not Result then Exit; if not (Obj is TDataObjectRoute) then Exit; Other := TDataObjectRoute(Obj); Result := (RouteId = Other.RouteId) and (MemberId = Other.MemberId) and (MemberEmail = Other.MemberEmail) and (VehicleAlias = Other.VehicleAlias) and (DriverAlias = Other.DriverAlias) and (RouteCost = Other.RouteCost) and (RouteRevenue = Other.RouteRevenue) and (NetRevenuePerDistanceUnit = Other.NetRevenuePerDistanceUnit) and (CreatedTimestamp = Other.CreatedTimestamp) and (Mpg = Other.Mpg) and (TripDistance = Other.TripDistance) and (GasPrice = Other.GasPrice) and (RouteDurationSec = Other.RouteDurationSec); if (not Result) then Exit; if (Length(Directions) <> Length(Other.Directions)) or (Length(Path) <> Length(Other.Path)) then Exit; SortedDirections1 := DirectionUnit.SortDirections(Directions); SortedDirections2 := DirectionUnit.SortDirections(Other.Directions); for i := 0 to Length(SortedDirections1) - 1 do if (not SortedDirections1[i].Equals(SortedDirections2[i])) then Exit; SortedDirectionPathPoints1 := DirectionPathPointUnit.SortDirectionPathPoints(Path); SortedDirectionPathPoints2 := DirectionPathPointUnit.SortDirectionPathPoints(Other.Path); for i := 0 to Length(SortedDirectionPathPoints1) - 1 do if (not SortedDirectionPathPoints1[i].Equals(SortedDirectionPathPoints2[i])) then Exit; Result := True; end; end.
unit vg_dsgn_styles; interface uses {$IFDEF WIN32} Registry, {$ENDIF} {$IFNDEF FPC} Windows, {$ELSE} LCLType, {$ENDIF} SysUtils, Classes, Graphics, Controls, Forms, TypInfo, Dialogs, vg_scene, vg_layouts, vg_inspector, vg_treeview, vg_controls, vg_objects, vg_dsgn, ExtCtrls, StdCtrls, vg_listbox, vg_textbox, vgComponent, vgCustomResources, vgCustomObject, vgCustomControl, vgScenePrim, vgObject, vgVisualObject; type TvgStyleDesigner = class(TForm) vgScene1: TvgScene; Root1: TvgBackground; ObjectsTree: TvgTreeView; vgScene2: TvgScene; Root2: TvgBackground; Inspector: TvgInspector; DesignScene: TvgScene; vgScene3: TvgScene; Root4: TvgBackground; OpenDialog1: TOpenDialog; Button1: TvgButton; SaveDialog1: TSaveDialog; Button2: TvgButton; btnClear: TvgButton; btnLoadDefault: TvgButton; btnBack: TvgButton; rectBack: TvgRectangle; vgBrushDialog1: TvgBrushDialog; Button3: TvgButton; Button4: TvgButton; btnCancel: TvgButton; ClearTimer: TTimer; Resources1: TvgResources; textFilter: TvgTextBoxClearBtn; Splitter1: TSplitter; Splitter2: TSplitter; vgScene4: TvgScene; Root3: TvgBackground; StatusBar1: TvgStatusBar; Label1: TvgLabel; procedure ObjectsTreeChange(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure btnLoadDefaultClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnBackClick(Sender: TObject); procedure ObjectsTreeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure ClearTimerTimer(Sender: TObject); procedure ObjectsTreeDragChange(SourceItem, DestItem: TvgTreeViewItem; Allow: Boolean); procedure InspectorChangeProperty(Sender: TObject; PropertyName: String); procedure ObjectsTreeChangeCheck(Sender: TObject); procedure DesignRootDragOver(Sender: TObject; const Data: TvgDragObject; const Point: TvgPoint; var Accept: Boolean); procedure textFilterChangeTracking(Sender: TObject); private { Private declarations } FDragObj: TvgObject; FResource: TvgResources; procedure UpdateTree; procedure LoadFromStrings(Str: TStrings); procedure SaveToStrings(Str: TStrings); procedure DoDeleteButton(Sender: TObject); procedure DoVisCheck(Sender: TObject); procedure DeleteObject(AObject: TvgObject; FreeObject: boolean); procedure TreeItemApplyResource(Sender: TObject); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public { Public declarations } end; var vgStyleDesigner: TvgStyleDesigner; function DesignResources(AResource: TvgResources; Current: string): boolean; implementation {$IFNDEF FPC} {$R *.dfm} {$ELSE} {$R *.lfm} {$ENDIF} type TvgHackVisual = class(TvgVisualObject); TvgHackBackground = class(TvgBackground); TvgStyleIDEDesigner = class(TvgDesigner) private public procedure SelectObject(ADesigner: TComponent; AObject: TvgObject; MultiSelection: array of TvgObject); override; procedure Modified(ADesigner: TComponent); override; function UniqueName(ADesigner: TComponent; ClassName: string): string; override; function IsSelected(ADesigner: TComponent; const AObject: TObject): boolean; override; procedure AddObject(AObject: TvgObject); override; procedure DeleteObject(AObject: TvgObject); override; end; { TvgStyleIDEDesigner } procedure TvgStyleIDEDesigner.Modified(ADesigner: TComponent); begin end; function TvgStyleIDEDesigner.IsSelected(ADesigner: TComponent; const AObject: TObject): boolean; begin Result := false; end; procedure TvgStyleIDEDesigner.SelectObject(ADesigner: TComponent; AObject: TvgObject; MultiSelection: array of TvgObject); begin if AObject = vgStyleDesigner.DesignScene.Root then Exit; vgStyleDesigner.Inspector.SelectedObject := AObject; if vgStyleDesigner.Inspector.SelectedObject is TvgObject then TvgObject(vgStyleDesigner.Inspector.SelectedObject).AddFreeNotify(vgStyleDesigner); if AObject.TagObject <> nil then begin vgStyleDesigner.ObjectsTree.Selected := TvgTreeViewItem(AObject.TagObject); end; end; function TvgStyleIDEDesigner.UniqueName(ADesigner: TComponent; ClassName: string): string; begin Result := ''; end; function DesignResources(AResource: TvgResources; Current: string): boolean; var SaveDesigner: TvgDesigner; S: string; begin Result := false; if AResource <> nil then begin SaveDesigner := vgDesigner; vgDesigner := TvgStyleIDEDesigner.Create(Application); vgStyleDesigner := TvgStyleDesigner.Create(Application); {$IFDEF WIN32} with TRegistry.Create do begin RootKey := HKEY_CURRENT_USER; if OpenKey('Software\ksdev\vgstyledesigner', true) then begin if ReadString('position') <> '' then begin vgStyleDesigner.Position := poDesigned; with vgStringToRect(ReadString('position')) do begin vgStyleDesigner.Left := round(left); vgStyleDesigner.Top := round(top); vgStyleDesigner.Width := round(right); vgStyleDesigner.Height := round(bottom); end; end; if ReadString('left') <> '' then vgStyleDesigner.vgScene1.width := round(vgStrToFloat(ReadString('left'))); if ReadString('right') <> '' then vgStyleDesigner.vgScene2.width := round(vgStrToFloat(ReadString('right'))); end; Free; end; {$ENDIF} {$IFDEF FPC} Application.ProcessMessages; {$ENDIF} vgStyleDesigner.DesignScene.DesignTime := true; vgStyleDesigner.FResource := AResource; if vgStyleDesigner.DesignScene.Root <> nil then TvgObject(vgStyleDesigner.DesignScene.Root).DeleteChildren; AResource.FillStrings; vgStyleDesigner.LoadFromStrings(AResource.Resource); vgStyleDesigner.ObjectsTree.CollapseAll; if (vgStyleDesigner.DesignScene.Root <> nil) and (TvgObject(vgStyleDesigner.DesignScene.Root).FindResource(Current) <> nil) then vgDesigner.SelectObject(nil, TvgObject(vgStyleDesigner.DesignScene.Root).FindResource(Current), []); if vgStyleDesigner.ShowModal = mrOk then begin vgStyleDesigner.SaveToStrings(AResource.Resource); Result := true; end; {$IFDEF WIN32} with TRegistry.Create do begin RootKey := HKEY_CURRENT_USER; if OpenKey('Software\ksdev\vgstyledesigner', true) then begin WriteString('position', vgRectToString(vgRect(vgStyleDesigner.Left, vgStyleDesigner.Top, vgStyleDesigner.Width, vgStyleDesigner.Height))); WriteString('left', vgFloatToStr(vgStyleDesigner.vgScene1.width)); WriteString('right', vgFloatToStr(vgStyleDesigner.vgScene2.width)); end; Free; end; {$ENDIF} FreeAndNil(vgStyleDesigner.vgScene1); FreeAndNil(vgStyleDesigner.DesignScene); FreeAndNil(vgStyleDesigner.vgScene2); FreeAndNil(vgStyleDesigner.vgScene3); FreeAndNil(vgStyleDesigner); vgStyleDesigner := nil; FreeAndNil(vgDesigner); vgDesigner := SaveDesigner; end; end; procedure TvgStyleIDEDesigner.AddObject(AObject: TvgObject); begin inherited; vgStyleDesigner.UpdateTree; end; procedure TvgStyleIDEDesigner.DeleteObject(AObject: TvgObject); begin inherited; end; { TvgStyleDesigner } procedure TvgStyleDesigner.textFilterChangeTracking(Sender: TObject); begin UpdateTree; end; procedure TvgStyleDesigner.UpdateTree; procedure ProcessObject(Obj: TvgObject; Node: TvgTreeViewItem); var i: integer; N: TvgTreeViewItem; S: AnsiString; begin S := Obj.ResourceName; if S = '' then S := Obj.ClassName else S := S + ': ' + Obj.ClassName; if (textFilter.Text <> '') and (Obj.Parent = DesignScene.Root) then begin if Pos(textFilter.Text, S) = 0 then Exit; end; if Obj = DesignScene.Root then begin N := nil; end else if Node <> nil then begin N := TvgTreeViewItem.Create(Self); N.Parent := Node; N.Text := S; N.TagObject := Obj; N.Resource := 'objecttreeitemstyle'; N.OnApplyResource := TreeItemApplyResource; if Obj.IsVisual then N.IsChecked := not TvgVisualObject(Obj.Visual).Locked; end else begin N := TvgTreeViewItem.Create(Self); N.Parent := ObjectsTree; N.Text := S; N.TagObject := Obj; N.Resource := 'objecttreeitemstyle'; N.OnApplyResource := TreeItemApplyResource; if Obj.IsVisual then N.IsChecked := not TvgVisualObject(Obj.Visual).Locked; end; Obj.TagObject := N; if Obj.isVisual and (Obj.Parent = DesignScene.Root) then begin TvgVisualObject(Obj.Visual).DesignHide := true; // center with Obj.Visual do begin SetBounds(Trunc((DesignScene.Width - Width) / 2), Trunc((DesignScene.Height - Height) / 2), Width, Height); end; end; if Obj.ChildrenCount > 0 then for i := 0 to Obj.ChildrenCount - 1 do begin if (DesignScene.Root is TvgBackground) and (Obj.Children[i] = TvgHackBackground(DesignScene.Root).FResourceLink) then Continue; ProcessObject(Obj.Children[i], N); end; end; begin if DesignScene.Root <> nil then begin ObjectsTree.Clear; ObjectsTree.BeginUpdate; ProcessObject(TvgObject(DesignScene.Root), nil); ObjectsTree.EndUpdate; DesignScene.AddUpdateRect(vgRect(0, 0, 1000, 1000)); end; end; procedure TvgStyleDesigner.TreeItemApplyResource(Sender: TObject); begin TvgTreeViewItem(Sender).Binding['deletebutton'] := EventToVariant(DoDeleteButton); TvgTreeViewItem(Sender).Binding['vischeck'] := EventToVariant(DoVisCheck); if TvgTreeViewItem(Sender).FindBinding('vischeck') <> nil then begin TvgObject(TvgTreeViewItem(Sender).FindBinding('vischeck')).TagObject := TvgTreeViewItem(Sender).TagObject; TvgVisualObject(TvgTreeViewItem(Sender).FindBinding('vischeck')).Visible := TvgTreeViewItem(Sender).TagObject is TvgVisualObject; if TvgTreeViewItem(Sender).TagObject is TvgVisualObject then TvgTreeViewItem(Sender).Binding['vischeck'] := TvgVisualObject(TvgTreeViewItem(Sender).TagObject).Visible; end; if not (TvgTreeViewItem(Sender).TagObject is TvgVisualObject) then TvgVisualObject(TvgTreeViewItem(Sender).FindResource('check')).Visible := false; end; procedure TvgStyleDesigner.DoVisCheck(Sender: TObject); begin TvgVisualObject(TvgObject(Sender).TagObject).Visible := TvgObject(Sender).Data; end; procedure TvgStyleDesigner.ObjectsTreeChange(Sender: TObject); var New, Old: TvgObject; begin if (ObjectsTree.Selected <> nil) and (ObjectsTree.Selected.TagObject <> nil) then begin Old := TvgObject(Inspector.SelectedObject); if (Old <> nil) and (Old.Parent <> nil) then while Old.Parent <> DesignScene.Root do Old := Old.Parent; New := TvgObject(ObjectsTree.Selected.TagObject); while New.Parent <> DesignScene.Root do New := New.Parent; if New.IsVisual then begin // center TvgVisualObject(New.Visual).Position.X := round((DesignScene.Width - TvgVisualObject(New.Visual).Width) / 2); TvgVisualObject(New.Visual).Position.Y := round((DesignScene.Height - TvgVisualObject(New.Visual).Height) / 2); // if (Old <> nil) and (Old.IsVisual) then begin if Old <> DesignScene.Root then TvgVisualObject(Old.Visual).DesignHide := true end else if (Old <> nil) and (Old.Parent <> nil) and (Old.Parent.IsVisual) then begin if Old.Parent <> DesignScene.Root then TvgVisualObject(Old.Parent.Visual).DesignHide := true; end; if New <> DesignScene.Root then TvgVisualObject(New.Visual).DesignHide := false; end else begin if (New <> nil) and (New.Parent <> nil) and (New.Parent.IsVisual) then begin TvgVisualObject(New.Parent.Visual).DesignHide := false; end; end; Inspector.SelectedObject := TvgObject(ObjectsTree.Selected.TagObject); if TvgObject(ObjectsTree.Selected.TagObject).isVisual then DesignScene.Selected := TvgVisualObject(ObjectsTree.Selected.TagObject); end; end; procedure TvgStyleDesigner.Button1Click(Sender: TObject); var S: TStrings; begin { Load style } if OpenDialog1.Execute then begin S := TStringList.Create; S.LoadFromFile(OpenDialog1.FileName); LoadFromStrings(S); FreeAndNil(S); end; end; procedure TvgStyleDesigner.Button2Click(Sender: TObject); var S: TStrings; begin { Save style } if SaveDialog1.Execute then begin S := TStringList.Create; SaveToStrings(S); S.SaveToFile(SaveDialog1.FileName); FreeAndNil(S); end; end; procedure TvgStyleDesigner.LoadFromStrings(Str: TStrings); var S: TStream; i: integer; Root: TvgObject; begin S := TMemoryStream.Create; try Inspector.SelectedObject := nil; DesignScene.Selected := nil; ObjectsTree.Selected := nil; Str.SaveToStream(S); if S.Position > 0 then begin S.Position := 0; if DesignScene.Root <> nil then TObject(DesignScene.Root).Free; Root := CreateObjectFromStream(nil, S); DesignScene.AddObject(Root); for i := 0 to Root.ChildrenCount - 1 do if Root.Children[i].isVisual then begin { TvgVisualObject(Root.FChildren[i]).Position.X := random(400); TvgVisualObject(Root.FChildren[i]).Position.Y := random(400);} TvgVisualObject(Root.Children[i]).Locked := false; end; if Root.ChildrenCount > 0 then vgDesigner.SelectObject(nil, Root.Children[0], []); UpdateTree; DesignScene.RealignRoot; if Root is TvgBackground then begin btnBack.Visible := true; rectBack.Fill.Assign(TvgBackground(Root).Fill); end else btnBack.Visible := false; end; finally FreeAndNil(S); end; end; procedure TvgStyleDesigner.SaveToStrings(Str: TStrings); var S: TStream; i: integer; Root: TvgObject; begin { Save style } S := TMemoryStream.Create; try Root := TvgObject(DesignScene.Root); Str.Clear; for i := 0 to Root.ChildrenCount - 1 do if Root.Children[i].isVisual then begin TvgVisualObject(Root.Children[i]).Locked := false; end; Root.SaveToStream(S); S.Position := 0; Str.LoadFromStream(S); finally FreeAndNil(S); end; end; procedure TvgStyleDesigner.Button3Click(Sender: TObject); begin { apply } if FResource <> nil then SaveToStrings(FResource.Resource); end; procedure TvgStyleDesigner.btnClearClick(Sender: TObject); begin { clear } btnClear.Enabled := false; ClearTimer.Enabled := true; end; procedure TvgStyleDesigner.ClearTimerTimer(Sender: TObject); var R: TvgBackground; begin ClearTimer.Enabled := false; Inspector.SelectedObject := nil; DesignScene.Selected := nil; ObjectsTree.Selected := nil; TObject(DesignScene.Root).Free; R := TvgBackground.Create(nil); DesignScene.AddObject(R); UpdateTree; btnClear.Enabled := true; end; procedure TvgStyleDesigner.btnLoadDefaultClick(Sender: TObject); var i: integer; S: TStream; Root: TvgObject; begin { Default } if DefaultStyles = nil then Exit; Inspector.SelectedObject := nil; DesignScene.Selected := nil; ObjectsTree.Selected := nil; Root := nil; {$IFDEF FPC} if System.FindResource(HInstance, PChar('defaultvgstyle'), RT_RCDATA) <> 0 then {$ELSE} if Windows.FindResource(HInstance, PChar('defaultvgstyle'), RT_RCDATA) <> 0 then {$ENDIF} begin S := TResourceStream.Create(HInstance, 'defaultvgstyle', RT_RCDATA); Root := CreateObjectFromBinStream(nil, S); FreeAndNil(S); end; TObject(DesignScene.Root).Free; DesignScene.AddObject(Root); for i := 0 to Root.ChildrenCount - 1 do if Root.Children[i].isVisual then begin TvgVisualObject(Root.Children[i]).Locked := false; end; if Root.ChildrenCount > 0 then vgDesigner.SelectObject(nil, Root.Children[0], []); UpdateTree; DesignScene.RealignRoot; if Root is TvgBackground then begin btnBack.Visible := true; rectBack.Fill.Assign(TvgBackground(Root).Fill); end else btnBack.Visible := false; end; procedure TvgStyleDesigner.FormCreate(Sender: TObject); begin OpenDialog1.Filter := 'VGScene style|*.vgstyle'; SaveDialog1.Filter := 'VGScene style|*.vgstyle'; end; procedure TvgStyleDesigner.DeleteObject(AObject: TvgObject; FreeObject: boolean); var A, P: TvgObject; Sel: TvgTreeViewItem; begin if AObject <> nil then begin AObject.RemoveFreeNotify(vgStyleDesigner); Sel := TvgTreeViewItem(AObject.TagObject); A := AObject; P := A.Parent; if P <> nil then begin Inspector.SelectedObject := P; if P.TagObject <> nil then ObjectsTree.Selected := TvgTreeViewItem(P.TagObject); end else begin Inspector.SelectedObject := nil; if P.TagObject <> nil then ObjectsTree.Selected := nil; end; Sel.Release; if FreeObject then A.Release else A.TagObject := nil; ObjectsTree.Realign; end; end; procedure TvgStyleDesigner.btnBackClick(Sender: TObject); begin vgBrushDialog1.Brush.Assign(rectBack.Fill); if vgBrushDialog1.Execute then begin rectBack.Fill.Assign(vgBrushDialog1.Brush); if (DesignScene.Root <> nil) and (DesignScene.Root is TvgBackground) then TvgBackground(DesignScene.Root).Fill.Assign(vgBrushDialog1.Brush); TvgBackground(DesignScene.Root).Repaint; end; end; procedure TvgStyleDesigner.DoDeleteButton(Sender: TObject); begin if ObjectsTree.Selected = nil then Exit; if (Sender is TvgSpeedButton) then begin// fixed fast click deletebutton TvgSpeedButton(Sender).Enabled := False; end; DeleteObject(TvgObject(ObjectsTree.Selected.TagObject), true); end; procedure TvgStyleDesigner.ObjectsTreeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if (Button = mbRight) then begin DesignScene.OpenDesignPopup; end; end; procedure TvgStyleDesigner.ObjectsTreeDragChange(SourceItem, DestItem: TvgTreeViewItem; Allow: Boolean); begin if DestItem = nil then TvgObject(SourceItem.TagObject).Parent := TvgObject(DesignScene.Root) else TvgObject(SourceItem.TagObject).Parent := TvgObject(DestItem.TagObject); end; procedure TvgStyleDesigner.InspectorChangeProperty(Sender: TObject; PropertyName: String); begin if vgStyleDesigner.Inspector.SelectedObject = nil then Exit; if TvgTreeViewItem(TvgObject(vgStyleDesigner.Inspector.SelectedObject).TagObject) = nil then Exit; if PropertyName = 'ResourceName' then begin TvgTreeViewItem(TvgObject(vgStyleDesigner.Inspector.SelectedObject).TagObject).Text := GetPropValue(vgStyleDesigner.Inspector.SelectedObject, PropertyName) + ': ' + vgStyleDesigner.Inspector.SelectedObject.ClassName; end; end; procedure TvgStyleDesigner.Notification(AComponent: TComponent; Operation: TOperation); begin inherited ; if (Operation = opRemove) and (AComponent is TvgObject) and Assigned(TvgObject(AComponent).Scene) and (TvgObject(AComponent).Scene.GetComponent = DesignScene) then DeleteObject(TvgObject(AComponent), false); end; procedure TvgStyleDesigner.ObjectsTreeChangeCheck(Sender: TObject); begin if (ObjectsTree.Selected <> nil) and (ObjectsTree.Selected.TagObject <> nil) and (TvgObject(ObjectsTree.Selected.TagObject).IsVisual) then begin TvgVisualObject(ObjectsTree.Selected.TagObject).Locked := not ObjectsTree.Selected.IsChecked; end; end; procedure TvgStyleDesigner.DesignRootDragOver(Sender: TObject; const Data: TvgDragObject; const Point: TvgPoint; var Accept: Boolean); begin Accept := true; end; end.
program skipblanks(input, output); const BLANK = ' '; var ch : char; procedure skipblanks; begin repeat read(ch) until ch <> BLANK; end; begin skipblanks; writeln(ch); end.
unit G2Mobile.Model.TitulosCliente; interface uses FMX.ListView, uDmDados, uRESTDWPoolerDB, System.SysUtils, IdSSLOpenSSLHeaders, FireDAC.Comp.Client, FMX.Dialogs, FMX.ListView.Appearances, FMX.ListView.Types, System.Classes, Datasnap.DBClient, FireDAC.Comp.DataSet, Data.DB, FMX.Objects, uFrmUtilFormate, Form_Mensagem, FMX.Grid, G2Mobile.Controller.Clientes; const CONST_DELETETITULOS = ' DELETE FROM titulos_cliente'; CONST_DELETEITENSTITULO = ' DELETE FROM venda_titulos'; CONST_BUSCATITULOSCLIENTE = ' SELECT c.num_ped, CAST( c.parcela AS varchar) + ''/'' + CAST(c.num_parc AS varchar)as parcelas, c.data_venc, c.data_emis, c.vlr_tit, c.cod_cliente, p.cod_vend, ' + ' case when (select dateadd(day, dias_carencia, c.data_venc) from t_config where dias_carencia is not null) <= getdate() and status = ''A'' then ''V'' else status end as status ' + ' FROM v_contas_receb c left outer join t_pessoa p on (c.cod_cliente = p.cod_pessoa) where c.num_ped is not null and c.status = ''A'' '; CONST_BUSCAITENSTITULO = ' select ti.cod_pedcar, ti.cod_prod, ' + ' isnull(sum(ti.quantidade), 0) as qtd_ped, ' + ' isnull(sum(th.qtd_tot), 0) as qtd_tot, ' + ' isnull(sum(th.pes_tot), 0) as pes_tot, ' + ' isnull(sum(ti.preco_unit), 0) as vlr_unit, ' + ' ti.tipo_pes AS unid, ' + ' isnull(sum(round(convert(numeric(14, 4), isnull(case tpr.tipo_calc when 0 then th.pes_tot when 1 then th.qtd_tot end, 0)*(ti.preco_unit-ti.desconto)), 2)), 0) as vlr_tot ' + ' from t_pedidovenda tp left outer join v_pessoa tc on (tp.cod_cliente = tc.cod_pessoa) left outer join v_prestador ts on (tp.cod_prest = ts.cod_prest) ' + ' left outer join t_centro_custo tu on (tp.cod_cc = tu.cod_cc) left outer join t_vendedor tv on (tp.cod_vend = tv.cod_vend), ' + ' t_pedidovendaitens ti ' + ' left outer join t_produto tpr on (tpr.cod_prod = ti.cod_prod) ' + ' left outer join (select tt.cod_pedcar, tt.num_item, isnull(count(tt.cod_pedcar), 0)+isnull(sum(tm.quant)-count(tm.item_pes), 0) as qtd_tot, isnull(sum(tt.peso), 0) as pes_tot from t_tendal tt ' + ' left outer join t_tendal_multi tm on (tt.cod_pedcar = tm.cod_pedcar and tt.num_item = tm.num_item and tt.item_pes = tm.item_pes) group by tt.cod_pedcar, tt.num_item) th on (th.cod_pedcar = ti.cod_pedcar and th.num_item = ti.num_item) ' + ' where tp.cod_pedcar = ti.cod_pedcar ' + ' and ti.cod_pedcar in (select num_ped from v_contas_receb c left outer join t_pessoa p on (c.cod_cliente = p.cod_pessoa) where status = ''A'''; CONST_INSERTTITULOSCLIENTES = ' INSERT INTO titulos_cliente (num_ped, parcelas, data_venc, data_emis, vlr_tit, status, cod_cliente, cod_vend) VALUES ' + ' (:num_ped, :parcelas, :data_venc, :data_emis, :vlr_tit, :status, :cod_cliente, :cod_vend) '; CONST_INSERTITENSTITULO = ' INSERT INTO venda_titulos (cod_pedcar, cod_prod, qtd_ped, qtd_tot, pes_tot, vlr_tot, unid, vlr_unit) VALUES ' + ' (:cod_pedcar, :cod_prod, :qtd_ped, :qtd_tot, :pes_tot, :vlr_tot, :unid, :vlr_unit) '; CONST_POPULALISTVIEWTITULO = 'SELECT * FROM titulos_cliente WHERE COD_CLIENTE = :COD_CLIENTE'; CONST_POPULALISTVIEWITENSTITULO = 'select v.*, p.desc_ind from venda_titulos v left outer join produto p on (v.cod_prod = p.cod_prod) where cod_pedcar = :codpedcar'; type TModelTitulosCliente = class(TInterfacedObject, iModelTitulosCliente) private FQry : TFDQuery; FRdwSQLTemp: TRESTDWClientSQL; FCodVend : Integer; FCodCliente: Integer; FCodPedcar : Integer; public constructor create; destructor destroy; override; class function new: iModelTitulosCliente; function CodVend(value: Integer): iModelTitulosCliente; function CodCliente(value: Integer): iModelTitulosCliente; function CodPedcar(value: Integer): iModelTitulosCliente; function DeleteTitulos: iModelTitulosCliente; function DeleteItensTitulo: iModelTitulosCliente; function BuscaTitulosServidor(DataSet: TFDMemTable): iModelTitulosCliente; function BuscaItensTituloServidor(DataSet: TFDMemTable): iModelTitulosCliente; function GravaTitulosSqlite(DataSet: TFDMemTable): iModelTitulosCliente; function GravaItensTituloSqlite(DataSet: TFDMemTable): iModelTitulosCliente; function PopulaListView(value: TListView; aberta, vencida: Timage): iModelTitulosCliente; function PopulaItemTituloStringGrid(Grid: TStringGrid): iModelTitulosCliente; end; implementation { TModelTitulosCliente } class function TModelTitulosCliente.new: iModelTitulosCliente; begin result := self.create; end; constructor TModelTitulosCliente.create; begin FQry := TFDQuery.create(nil); FQry.Connection := DmDados.ConexaoInterna; FQry.FetchOptions.RowsetSize := 50000; FQry.Active := false; FQry.SQL.Clear; FRdwSQLTemp := TRESTDWClientSQL.create(nil); FRdwSQLTemp.DataBase := DmDados.RESTDWDataBase1; FRdwSQLTemp.BinaryRequest := True; FRdwSQLTemp.FormatOptions.MaxStringSize := 10000; FRdwSQLTemp.Active := false; FRdwSQLTemp.SQL.Clear; end; destructor TModelTitulosCliente.destroy; begin FreeAndNil(FQry); FreeAndNil(FRdwSQLTemp); inherited; end; function TModelTitulosCliente.DeleteTitulos: iModelTitulosCliente; begin result := self; FQry.ExecSQL(CONST_DELETETITULOS); end; function TModelTitulosCliente.DeleteItensTitulo: iModelTitulosCliente; begin result := self; FQry.ExecSQL(CONST_DELETEITENSTITULO); end; function TModelTitulosCliente.BuscaTitulosServidor(DataSet: TFDMemTable): iModelTitulosCliente; begin result := self; FRdwSQLTemp.SQL.Add(CONST_BUSCATITULOSCLIENTE); if FCodVend <> 0 then FRdwSQLTemp.SQL.Add(' and p.cod_vend = ' + FCodVend.ToString); FRdwSQLTemp.Active := True; FRdwSQLTemp.RecordCount; DataSet.CopyDataSet(FRdwSQLTemp, [coStructure, coRestart, coAppend]); end; function TModelTitulosCliente.CodCliente(value: Integer): iModelTitulosCliente; begin result := self; FCodCliente := value; end; function TModelTitulosCliente.CodPedcar(value: Integer): iModelTitulosCliente; begin result := self; FCodPedcar := value; end; function TModelTitulosCliente.CodVend(value: Integer): iModelTitulosCliente; begin result := self; FCodVend := value; end; function TModelTitulosCliente.GravaTitulosSqlite(DataSet: TFDMemTable): iModelTitulosCliente; var I: Integer; begin result := self; DataSet.First; FQry.Active := false; for I := 0 to DataSet.RecordCount - 1 do begin FQry.SQL.Text := CONST_INSERTTITULOSCLIENTES; FQry.ParamByName('num_ped').AsInteger := DataSet.FieldByName('num_ped').AsInteger; FQry.ParamByName('parcelas').AsString := DataSet.FieldByName('parcelas').AsString; FQry.ParamByName('data_venc').AsDateTime := DataSet.FieldByName('data_venc').AsDateTime; FQry.ParamByName('data_emis').AsDateTime := DataSet.FieldByName('data_emis').AsDateTime; FQry.ParamByName('vlr_tit').AsFloat := DataSet.FieldByName('vlr_tit').AsFloat; FQry.ParamByName('status').AsString := DataSet.FieldByName('status').AsString; FQry.ParamByName('cod_cliente').AsInteger := DataSet.FieldByName('cod_cliente').AsInteger; FQry.ParamByName('cod_vend').AsInteger := DataSet.FieldByName('cod_vend').AsInteger; FQry.ExecSQL; DataSet.Next; end; end; function TModelTitulosCliente.BuscaItensTituloServidor(DataSet: TFDMemTable): iModelTitulosCliente; begin result := self; FRdwSQLTemp.SQL.Add(CONST_BUSCAITENSTITULO); if FCodVend <> 0 then FRdwSQLTemp.SQL.Add(' and p.cod_vend = ' + FCodVend.ToString); FRdwSQLTemp.SQL.Add(') group by ti.cod_prod, tpr.tipo_calc, ti.cod_pedcar, ti.tipo_pes '); FRdwSQLTemp.Active := True; FRdwSQLTemp.RecordCount; DataSet.CopyDataSet(FRdwSQLTemp, [coStructure, coRestart, coAppend]); end; function TModelTitulosCliente.GravaItensTituloSqlite(DataSet: TFDMemTable): iModelTitulosCliente; var I: Integer; begin result := self; DataSet.First; FQry.Active := false; for I := 0 to DataSet.RecordCount - 1 do begin FQry.SQL.Text := CONST_INSERTITENSTITULO; FQry.ParamByName('cod_pedcar').AsInteger := DataSet.FieldByName('cod_pedcar').AsInteger; FQry.ParamByName('cod_prod').AsInteger := DataSet.FieldByName('cod_prod').AsInteger; FQry.ParamByName('qtd_ped').AsInteger := DataSet.FieldByName('qtd_ped').AsInteger; FQry.ParamByName('qtd_tot').AsInteger := DataSet.FieldByName('qtd_tot').AsInteger; FQry.ParamByName('unid').AsInteger := DataSet.FieldByName('unid').AsInteger; FQry.ParamByName('vlr_unit').AsFloat := DataSet.FieldByName('vlr_unit').AsFloat; FQry.ParamByName('vlr_tot').AsFloat := DataSet.FieldByName('vlr_tot').AsFloat; FQry.ParamByName('pes_tot').AsFloat := DataSet.FieldByName('pes_tot').AsFloat; FQry.ExecSQL; DataSet.Next; end; end; function TModelTitulosCliente.PopulaListView(value: TListView; aberta, vencida: Timage): iModelTitulosCliente; var x : Integer; item : TListViewItem; txt : TListItemText; img : TListItemImage; color: Cardinal; begin result := self; try FQry.SQL.Text := CONST_POPULALISTVIEWTITULO; FQry.ParamByName('COD_CLIENTE').AsInteger := FCodCliente; FQry.Open; FQry.First; value.Items.Clear; value.BeginUpdate; for x := 0 to FQry.RecordCount - 1 do begin item := value.Items.Add; if FQry.FieldByName('status').AsString.Equals('A') then color := $FF3498DB else color := $FFFF0000; with item do begin txt := TListItemText(Objects.FindDrawable('codped')); txt.Text := formatfloat('0000', FQry.FieldByName('num_ped').AsFloat); txt.TagString := FQry.FieldByName('num_ped').AsString; txt.TextColor := color; txt := TListItemText(Objects.FindDrawable('status')); if FQry.FieldByName('status').AsString.Equals('A') then txt.Text := 'Status: ABERTO' else txt.Text := 'Status: VENCIDO'; txt.TextColor := color; txt := TListItemText(Objects.FindDrawable('parcelas')); txt.Text := 'Parcelas: ' + FQry.FieldByName('parcelas').AsString; txt.TextColor := color; txt := TListItemText(Objects.FindDrawable('validade')); txt.Text := 'Dt. Venc.: ' + FormatDateTime('DD/MM/YYYY', FQry.FieldByName('data_venc').AsDateTime); txt.TextColor := color; txt := TListItemText(Objects.FindDrawable('valor')); txt.Text := 'Valor: ' + formatfloat('R$#,##0.00', FQry.FieldByName('vlr_tit').AsFloat); txt.TextColor := color; txt := TListItemText(Objects.FindDrawable('datapedido')); txt.Text := 'Dt. Ped.: ' + FormatDateTime('DD/MM/YYYY', FQry.FieldByName('data_emis').AsDateTime); txt.TextColor := color; img := TListItemImage(Objects.FindDrawable('Image7')); if FQry.FieldByName('status').AsString.Equals('A') then img.Bitmap := aberta.Bitmap else img.Bitmap := vencida.Bitmap end; FQry.Next end; finally value.EndUpdate; end; end; function TModelTitulosCliente.PopulaItemTituloStringGrid(Grid: TStringGrid): iModelTitulosCliente; var I: Integer; begin result := self; FQry.SQL.Text := CONST_POPULALISTVIEWITENSTITULO; FQry.ParamByName('codpedcar').AsInteger := FCodPedcar; FQry.Open; for I := 0 to FQry.RecordCount - 1 do begin with Grid do begin RowCount := RowCount + 1; Row := RowCount - 1; Cells[0, Row] := FQry.FieldByName('cod_prod').AsString; Cells[1, Row] := FQry.FieldByName('desc_ind').AsString; case FQry.FieldByName('unid').AsInteger of 0: Cells[2, Row] := 'UND'; 1: Cells[2, Row] := 'PESO'; end; Cells[3, Row] := formatfloat('0000', FQry.FieldByName('qtd_ped').AsFloat); Cells[4, Row] := formatfloat('0000', FQry.FieldByName('qtd_tot').AsFloat); Cells[5, Row] := formatfloat('#,##0.000', FQry.FieldByName('pes_tot').AsFloat); Cells[6, Row] := formatfloat('#,##0.00', FQry.FieldByName('vlr_unit').AsFloat); Cells[7, Row] := formatfloat('#,##0.00', FQry.FieldByName('vlr_tot').AsFloat); end; FQry.Next; end; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpSecT283FieldElement; {$I ..\..\..\..\Include\CryptoLib.inc} interface uses ClpNat, ClpNat320, ClpECFieldElement, ClpIECFieldElement, ClpSecT283Field, ClpISecT283FieldElement, ClpBigInteger, ClpArrayUtils, ClpCryptoLibTypes; resourcestring SInvalidValueForSecT283FieldElement = 'Value Invalid for SecT283FieldElement "%s"'; type TSecT283FieldElement = class(TAbstractF2mFieldElement, ISecT283FieldElement) strict private function GetM: Int32; inline; function GetRepresentation: Int32; inline; function GetK1: Int32; inline; function GetK2: Int32; inline; function GetK3: Int32; inline; function Equals(const other: ISecT283FieldElement): Boolean; reintroduce; overload; strict protected var Fx: TCryptoLibUInt64Array; function GetFieldName: string; override; function GetFieldSize: Int32; override; function GetIsOne: Boolean; override; function GetIsZero: Boolean; override; function GetX: TCryptoLibUInt64Array; inline; property X: TCryptoLibUInt64Array read GetX; public constructor Create(); overload; constructor Create(const X: TBigInteger); overload; constructor Create(const X: TCryptoLibUInt64Array); overload; function TestBitZero: Boolean; override; function ToBigInteger(): TBigInteger; override; function Add(const b: IECFieldElement): IECFieldElement; override; function AddOne(): IECFieldElement; override; function Subtract(const b: IECFieldElement): IECFieldElement; override; function Multiply(const b: IECFieldElement): IECFieldElement; override; function MultiplyMinusProduct(const b, X, y: IECFieldElement) : IECFieldElement; override; function MultiplyPlusProduct(const b, X, y: IECFieldElement) : IECFieldElement; override; function Divide(const b: IECFieldElement): IECFieldElement; override; function Negate(): IECFieldElement; override; function Square(): IECFieldElement; override; function SquareMinusProduct(const X, y: IECFieldElement) : IECFieldElement; override; function SquarePlusProduct(const X, y: IECFieldElement) : IECFieldElement; override; function SquarePow(pow: Int32): IECFieldElement; override; function Trace(): Int32; override; function Invert(): IECFieldElement; override; /// <summary> /// return a sqrt root - the routine verifies that the calculation /// returns the right value - if <br />none exists it returns null. /// </summary> function Sqrt(): IECFieldElement; override; function Equals(const other: IECFieldElement): Boolean; overload; override; function GetHashCode(): {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI}override; property IsZero: Boolean read GetIsZero; property IsOne: Boolean read GetIsOne; property FieldName: string read GetFieldName; property FieldSize: Int32 read GetFieldSize; property Representation: Int32 read GetRepresentation; property M: Int32 read GetM; property k1: Int32 read GetK1; property k2: Int32 read GetK2; property k3: Int32 read GetK3; end; implementation { TSecT283FieldElement } function TSecT283FieldElement.Add(const b: IECFieldElement): IECFieldElement; var z: TCryptoLibUInt64Array; begin z := TNat320.Create64(); TSecT283Field.Add(Fx, (b as ISecT283FieldElement).X, z); result := TSecT283FieldElement.Create(z); end; function TSecT283FieldElement.AddOne: IECFieldElement; var z: TCryptoLibUInt64Array; begin z := TNat320.Create64(); TSecT283Field.AddOne(Fx, z); result := TSecT283FieldElement.Create(z); end; constructor TSecT283FieldElement.Create(const X: TBigInteger); begin if ((not(X.IsInitialized)) or (X.SignValue < 0) or (X.BitLength > 283)) then begin raise EArgumentCryptoLibException.CreateResFmt (@SInvalidValueForSecT283FieldElement, ['x']); end; Inherited Create(); Fx := TSecT283Field.FromBigInteger(X); end; constructor TSecT283FieldElement.Create; begin Inherited Create(); Fx := TNat320.Create64(); end; constructor TSecT283FieldElement.Create(const X: TCryptoLibUInt64Array); begin Inherited Create(); Fx := X; end; function TSecT283FieldElement.Divide(const b: IECFieldElement): IECFieldElement; begin result := Multiply(b.Invert()); end; function TSecT283FieldElement.Equals(const other: ISecT283FieldElement) : Boolean; begin if ((Self as ISecT283FieldElement) = other) then begin result := true; Exit; end; if (other = Nil) then begin result := false; Exit; end; result := TNat320.Eq64(Fx, other.X); end; function TSecT283FieldElement.Equals(const other: IECFieldElement): Boolean; begin result := Equals(other as ISecT283FieldElement); end; function TSecT283FieldElement.GetFieldName: string; begin result := 'SecT283Field'; end; function TSecT283FieldElement.GetFieldSize: Int32; begin result := 283; end; function TSecT283FieldElement.GetHashCode: {$IFDEF DELPHI}Int32; {$ELSE}PtrInt; {$ENDIF DELPHI} begin result := 2831275 xor TArrayUtils.GetArrayHashCode(Fx, 0, 5); end; function TSecT283FieldElement.GetIsOne: Boolean; begin result := TNat320.IsOne64(Fx); end; function TSecT283FieldElement.GetIsZero: Boolean; begin result := TNat320.IsZero64(Fx); end; function TSecT283FieldElement.GetK1: Int32; begin result := 5; end; function TSecT283FieldElement.GetK2: Int32; begin result := 7; end; function TSecT283FieldElement.GetK3: Int32; begin result := 12; end; function TSecT283FieldElement.GetM: Int32; begin result := 283; end; function TSecT283FieldElement.GetRepresentation: Int32; begin result := TF2mFieldElement.Ppb; end; function TSecT283FieldElement.GetX: TCryptoLibUInt64Array; begin result := Fx; end; function TSecT283FieldElement.Invert: IECFieldElement; var z: TCryptoLibUInt64Array; begin z := TNat320.Create64(); TSecT283Field.Invert(Fx, z); result := TSecT283FieldElement.Create(z); end; function TSecT283FieldElement.Multiply(const b: IECFieldElement) : IECFieldElement; var z: TCryptoLibUInt64Array; begin z := TNat320.Create64(); TSecT283Field.Multiply(Fx, (b as ISecT283FieldElement).X, z); result := TSecT283FieldElement.Create(z); end; function TSecT283FieldElement.MultiplyMinusProduct(const b, X, y: IECFieldElement): IECFieldElement; begin result := MultiplyPlusProduct(b, X, y); end; function TSecT283FieldElement.MultiplyPlusProduct(const b, X, y: IECFieldElement): IECFieldElement; var ax, bx, xx, yx, tt, z: TCryptoLibUInt64Array; begin ax := Fx; bx := (b as ISecT283FieldElement).X; xx := (X as ISecT283FieldElement).X; yx := (y as ISecT283FieldElement).X; tt := TNat.Create64(9); TSecT283Field.MultiplyAddToExt(ax, bx, tt); TSecT283Field.MultiplyAddToExt(xx, yx, tt); z := TNat320.Create64(); TSecT283Field.Reduce(tt, z); result := TSecT283FieldElement.Create(z); end; function TSecT283FieldElement.Negate: IECFieldElement; begin result := Self as IECFieldElement; end; function TSecT283FieldElement.Sqrt: IECFieldElement; var z: TCryptoLibUInt64Array; begin z := TNat320.Create64(); TSecT283Field.Sqrt(Fx, z); result := TSecT283FieldElement.Create(z); end; function TSecT283FieldElement.Square: IECFieldElement; var z: TCryptoLibUInt64Array; begin z := TNat320.Create64(); TSecT283Field.Square(Fx, z); result := TSecT283FieldElement.Create(z); end; function TSecT283FieldElement.SquareMinusProduct(const X, y: IECFieldElement) : IECFieldElement; begin result := SquarePlusProduct(X, y); end; function TSecT283FieldElement.SquarePlusProduct(const X, y: IECFieldElement) : IECFieldElement; var ax, xx, yx, tt, z: TCryptoLibUInt64Array; begin ax := Fx; xx := (X as ISecT283FieldElement).X; yx := (y as ISecT283FieldElement).X; tt := TNat.Create64(9); TSecT283Field.SquareAddToExt(ax, tt); TSecT283Field.MultiplyAddToExt(xx, yx, tt); z := TNat320.Create64(); TSecT283Field.Reduce(tt, z); result := TSecT283FieldElement.Create(z); end; function TSecT283FieldElement.SquarePow(pow: Int32): IECFieldElement; var z: TCryptoLibUInt64Array; begin if (pow < 1) then begin result := Self as IECFieldElement; Exit; end; z := TNat320.Create64(); TSecT283Field.SquareN(Fx, pow, z); result := TSecT283FieldElement.Create(z); end; function TSecT283FieldElement.Subtract(const b: IECFieldElement) : IECFieldElement; begin // Addition and subtraction are the same in F2m result := Add(b); end; function TSecT283FieldElement.TestBitZero: Boolean; begin result := (Fx[0] and UInt64(1)) <> UInt64(0); end; function TSecT283FieldElement.ToBigInteger: TBigInteger; begin result := TNat320.ToBigInteger64(Fx); end; function TSecT283FieldElement.Trace: Int32; begin result := Int32(TSecT283Field.Trace(Fx)); end; end.
unit CommunicationTypes; interface uses Generics.Collections, Classes, Rtti, BaseObject; type {$METHODINFO ON} TObjectStruct = class(TBaseObject) private fObjectClass: String; fObjectName: String; published property ObjectName :String read fObjectName write fObjectName; property ObjectClass:String read fObjectClass write fObjectClass; end; TObjectArray = array of TObjectStruct; TObjectStructList = class(TBaseObject) private FObjects: TObjectArray; public procedure Add(aObject: TObjectStruct); function Count: Integer; published property Objects: TObjectArray read FObjects write FObjects; end; TStringValue = class(TBaseObject) private FValue: string; FVarType: TVarType; published property Value : string read FValue write FValue; property VarType: TVarType read FVarType write FVarType; end; //TVariantArray = array of Variant; not supported //TVariantArray = array of string; gives errors? TVariantArray = array of TStringValue; TVariantList = class(TBaseObject) private FVariants: TVariantArray; public procedure Add(aValue: Variant); function Count: Integer; published property Variants: TVariantArray read FVariants write FVariants; end; TRemoteCall = class(TObjectStruct) private FArguments: TVariantList; FObjectList: TObjectStructList; FFunctionName: string; FResults: TVariantList; FRemoteFunction: string; FMsgWParam: Integer; FWndMessage: Integer; FMsgLParam: Integer; FExists: boolean; FTimeout: Integer; FExceptionClass: string; FExceptionMsg: string; published property ExceptionClass: string read FExceptionClass write FExceptionClass; property ExceptionMsg : string read FExceptionMsg write FExceptionMsg; property FunctionName: string read FFunctionName write FFunctionName; property RemoteFunction: string read FRemoteFunction write FRemoteFunction; property ObjectList: TObjectStructList read FObjectList write FObjectList; property Arguments : TVariantList read FArguments write FArguments; property Results : TVariantList read FResults write FResults; property Timeout: Integer read FTimeout write FTimeout; property WndMessage: Integer read FWndMessage write FWndMessage; property MsgWParam : Integer read FMsgWParam write FMsgWParam; property MsgLParam : Integer read FMsgLParam write FMsgLParam; property Exists: boolean read FExists write FExists; end; implementation uses Variants, SysUtils; { TObjectStructList } procedure TObjectStructList.Add(aObject: TObjectStruct); begin SetLength(FObjects, Length(FObjects)+1 ); FObjects[Length(FObjects)-1] := aObject; end; function TObjectStructList.Count: Integer; begin Result := Length(FObjects); end; { TVariantList } procedure TVariantList.Add(aValue: Variant); var v: TStringValue; begin SetLength(FVariants, Length(FVariants)+1 ); v := TStringValue.Create; v.Value := aValue; v.VarType := VarType(aValue); FVariants[Length(FVariants)-1] := v; end; function TVariantList.Count: Integer; begin Result := Length(FVariants); end; end.
unit ComplexScrollByLines; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Модуль: "w:/common/components/gui/Garant/Daily/ComplexScrollByLines.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::ComplexScrollByLines // // Тест вида - прокрутили на несколько строк вниз, а потом на несколько вверх. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses TextEditorVisitor, PrimTextLoad_Form ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TComplexScrollByLines = {abstract} class(TTextEditorVisitor) {* Тест вида - прокрутили на несколько строк вниз, а потом на несколько вверх. } protected // realized methods procedure DoVisit(aForm: TPrimTextLoadForm); override; {* Обработать текст } protected // overridden protected methods function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } protected // protected methods function GetScrollLineCount2Down: Integer; virtual; abstract; {* количество строк для прокрутки вниз } function GetScrollLineCount2Up: Integer; virtual; abstract; {* количество строк для прокрутки вверх } end;//TComplexScrollByLines {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TComplexScrollByLines procedure TComplexScrollByLines.DoVisit(aForm: TPrimTextLoadForm); //#UC START# *4BE419AF0217_4C1B135F02B0_var* //#UC END# *4BE419AF0217_4C1B135F02B0_var* begin //#UC START# *4BE419AF0217_4C1B135F02B0_impl* ScrollByLine(aForm, GetScrollLineCount2Down, False, False); ScrollByLine(aForm, GetScrollLineCount2Up, True, False); CheckTopAnchor(aForm.Text.View); //#UC END# *4BE419AF0217_4C1B135F02B0_impl* end;//TComplexScrollByLines.DoVisit function TComplexScrollByLines.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TComplexScrollByLines.GetFolder function TComplexScrollByLines.GetModelElementGUID: AnsiString; {-} begin Result := '4C1B135F02B0'; end;//TComplexScrollByLines.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
unit udmNFe; interface uses Windows, Forms, Messages, SysUtils, Variants, Classes, Graphics, Controls, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS, DBClient,LibGeral, uMatVars, ACBrNFeDANFEClass, ACBrNFe, pcnConversao, ACBrNFeDANFEFR, ACBrBase, ACBrDFe, pcnConversaoNFe, ACBrNFeDANFEFRDM, blcksock, ACBrDFeSSL, ACBrMail; type TdmNFe = class(TdmPadrao) qryManutencaoFIL_COBR: TStringField; qryManutencaoNOTA: TFloatField; qryManutencaoSERIE: TStringField; qryManutencaoSITUACAO: TStringField; qryManutencaoCHAVE: TStringField; qryManutencaoOPERADOR: TStringField; qryManutencaoARQUIVO_NFE: TBlobField; qryManutencaoPROTOCOLO: TStringField; qryLocalizacaoFIL_COBR: TStringField; qryLocalizacaoNOTA: TFloatField; qryLocalizacaoSERIE: TStringField; qryLocalizacaoSITUACAO: TStringField; qryLocalizacaoCHAVE: TStringField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoARQUIVO_NFE: TBlobField; qryLocalizacaoPROTOCOLO: TStringField; cdsNFe: TClientDataSet; cdsNFecUF: TIntegerField; cdsNFecNF: TStringField; cdsNFeNatOp: TStringField; cdsNFeMod: TStringField; cdsNFeindPag: TIntegerField; cdsNFeSerie: TIntegerField; cdsNFenNF: TIntegerField; cdsNFedEmi: TDateField; cdsNFedSaiEnt: TDateField; cdsNFehSaiEnt: TTimeField; cdsNFetpNF: TIntegerField; cdsNFecMunFG: TIntegerField; cdsNFetpImp: TIntegerField; cdsNFetpEmis: TIntegerField; cdsNFecDV: TIntegerField; cdsNFetpAmb: TIntegerField; cdsNFefinNFe: TIntegerField; cdsNFeprocEmi: TIntegerField; cdsNFeverProc: TStringField; cdsNFeEmitxNome: TStringField; cdsNFeEmitxFant: TStringField; cdsNFeEmitxLgr: TStringField; cdsNFeEmitNro: TStringField; cdsNFeEmitCpl: TStringField; cdsNFeEmitxBairro: TStringField; cdsNFeEmitcMun: TStringField; cdsNFeEmitxMun: TStringField; cdsNFeEmitUF: TStringField; cdsNFeEmitCep: TStringField; cdsNFecEmitPais: TStringField; cdsNFeEmitxPais: TStringField; cdsNFeEmitFone: TStringField; cdsNFeEmitEmail: TStringField; cdsNFeEmitCNPJ: TStringField; cdsNFeEmitIE: TStringField; cdsNFeDestCNPJ: TStringField; cdsNFeDestxNome: TStringField; cdsNFeDestFant: TStringField; cdsNFeDestxLgr: TStringField; cdsNFeDestNro: TStringField; cdsNFeDestCpl: TStringField; cdsNFeDestxBairro: TStringField; cdsNFeDestcMun: TIntegerField; cdsNFeDestxMun: TStringField; cdsNFeDestUF: TStringField; cdsNFeDestCep: TStringField; cdsNFeDestcPais: TIntegerField; cdsNFeDestxPais: TStringField; cdsNFeDestFone: TStringField; cdsNFeDestIE: TStringField; cdsNFeDestEmail: TStringField; cdsNFeTotvBC: TFloatField; cdsNFeTotvICMS: TFloatField; cdsNFeTotvBCST: TFloatField; cdsNFeTotvST: TFloatField; cdsNFeTotvProd: TFloatField; cdsNFeTotvFrete: TFloatField; cdsNFeTotvSeg: TFloatField; cdsNFeTotvDesc: TFloatField; cdsNFeTotvII: TFloatField; cdsNFeTotvIPI: TFloatField; cdsNFeTotvNF: TFloatField; cdsNFeTotvPIS: TFloatField; cdsNFeTotvCOFINS: TFloatField; cdsNFeTotvOUTRO: TFloatField; cdsNFeTranspModFrete: TIntegerField; cdsNFeTranspxCNPJ: TStringField; cdsNFeTranspxNome: TStringField; cdsNFeTranspIE: TStringField; cdsNFeTranspxEnder: TStringField; cdsNFeTranpxMun: TStringField; cdsNFeTranspUF: TStringField; cdsNFeTranspqVol: TIntegerField; cdsNFeTranspesp: TStringField; cdsNFeTranspmarca: TStringField; cdsNFeTransppesoL: TFloatField; cdsNFeTransppesoB: TFloatField; cdsNFeTranspvNota: TFloatField; cdsNFeInfAdicinfCpl: TStringField; cdsNFeChave: TStringField; cdsNFeFatnFat: TStringField; cdsNFeFatvOrig: TFloatField; cdsNFeFatvDesc: TFloatField; cdsNFeFatvLiq: TFloatField; cdsNFeISSTotvServ: TFloatField; cdsNFeISSTotvBC: TFloatField; cdsNFeISSTotvISS: TFloatField; cdsNFeISSTotvPIS: TFloatField; cdsNFeISSTotvCOFINS: TFloatField; cdsNFeTranspVeiplaca: TStringField; cdsNFeTranspVeiuf: TStringField; cdsItemNFe: TClientDataSet; cdsItemNFenItem: TIntegerField; cdsItemNFecProd: TStringField; cdsItemNFexProd: TStringField; cdsItemNFeCFOP: TStringField; cdsItemNFeqCom: TFloatField; cdsItemNFevUnit: TFloatField; cdsItemNFevProd: TFloatField; cdsItemNFeuCom: TStringField; cdsItemNFeNCM: TStringField; cdsItemNFeICMSOrig: TStringField; cdsItemNFeICMSCST: TStringField; cdsItemNFeICMSvBC: TFloatField; cdsItemNFeICMSpICMS: TFloatField; cdsItemNFeICMSvICMS: TFloatField; cdsItemNFeIPIcEnq: TStringField; cdsItemNFeIPICST: TStringField; cdsItemNFeIPIvBC: TFloatField; cdsItemNFeIPIpIPI: TFloatField; cdsItemNFeIPIvIPI: TFloatField; cdsItemNFePISCST: TStringField; cdsItemNFePISvBC: TFloatField; cdsItemNFePISpPIS: TFloatField; cdsItemNFePISvPIS: TFloatField; cdsItemNFeCOFINSCST: TStringField; cdsItemNFeCOFINSvBC: TFloatField; cdsItemNFeCOFINSpCOFINS: TFloatField; cdsItemNFeCOFINSvCOFINS: TFloatField; cdsItemNFeICMSvBC_ST: TFloatField; cdsItemNFeICMSpICMS_ST: TFloatField; cdsItemNFeICMSvICMS_ST: TFloatField; cdsFatura: TClientDataSet; cdsFaturanDup: TStringField; cdsFaturadVenc: TDateField; cdsFaturavDup: TFloatField; qryManutencaoXML_CANC: TBlobField; qryLocalizacaoXML_CANC: TBlobField; OpenDialog1: TOpenDialog; cdsItemNFeLOTE: TStringField; cdsItemNFeCOMPRIMENTO: TFloatField; cdsItemNFeLARGURA: TFloatField; cdsItemNFeALTURA: TFloatField; cdsItemNFeIMPORTACAO: TStringField; cdsItemNFeNRO_PEDIDO: TStringField; cdsItemNFeNRO_SERIE: TStringField; cdsItemNFeC_CONTABIL: TStringField; cdsItemNFeNRO_PROJETO: TStringField; cdsItemNFeNRO_NETWORK: TStringField; cdsItemNFeC_ATIVIDADE: TStringField; cdsItemNFePESO_REAL: TFloatField; cdsItemNFePESO_CUB: TFloatField; cdsItemNFeRUA: TStringField; cdsItemNFeNUMERO: TFloatField; cdsItemNFeANDAR: TFloatField; cdsItemNFeAPARTAMENTO: TFloatField; qryManutencaoNRO_RECIBO: TStringField; qryLocalizacaoNRO_RECIBO: TStringField; cdsItemNFeESPECIE: TStringField; cdsItemNFeQTD_ESPECIE: TFloatField; cdsItemDetalhe: TClientDataSet; cdsItemDetalhenItem: TIntegerField; cdsItemDetalhecProd: TStringField; cdsItemDetalhexProd: TStringField; cdsItemDetalheCFOP: TStringField; cdsItemDetalheqCom: TFloatField; cdsItemDetalhevUnit: TFloatField; cdsItemDetalhevProd: TFloatField; cdsItemDetalheuCom: TStringField; cdsItemDetalheNCM: TStringField; cdsItemDetalheICMSOrig: TStringField; cdsItemDetalheICMSCST: TStringField; cdsItemDetalheICMSvBC: TFloatField; cdsItemDetalheICMSpICMS: TFloatField; cdsItemDetalheICMSvICMS: TFloatField; cdsItemDetalheIPIcEnq: TStringField; cdsItemDetalheIPICST: TStringField; cdsItemDetalheIPIvBC: TFloatField; cdsItemDetalheIPIpIPI: TFloatField; cdsItemDetalheIPIvIPI: TFloatField; cdsItemDetalhePISCST: TStringField; cdsItemDetalhePISvBC: TFloatField; cdsItemDetalhePISpPIS: TFloatField; cdsItemDetalhePISvPIS: TFloatField; cdsItemDetalheCOFINSCST: TStringField; cdsItemDetalheCOFINSvBC: TFloatField; cdsItemDetalheCOFINSpCOFINS: TFloatField; cdsItemDetalheCOFINSvCOFINS: TFloatField; cdsItemDetalheICMSvBC_ST: TFloatField; cdsItemDetalheICMSpICMS_ST: TFloatField; cdsItemDetalheICMSvICMS_ST: TFloatField; cdsItemDetalheLOTE: TStringField; cdsItemDetalheCOMPRIMENTO: TFloatField; cdsItemDetalheLARGURA: TFloatField; cdsItemDetalheALTURA: TFloatField; cdsItemDetalheIMPORTACAO: TStringField; cdsItemDetalheNRO_PEDIDO: TStringField; cdsItemDetalheNRO_SERIE: TStringField; cdsItemDetalheC_CONTABIL: TStringField; cdsItemDetalheNRO_PROJETO: TStringField; cdsItemDetalheNRO_NETWORK: TStringField; cdsItemDetalheC_ATIVIDADE: TStringField; cdsItemDetalhePESO_REAL: TFloatField; cdsItemDetalhePESO_CUB: TFloatField; cdsItemDetalheRUA: TStringField; cdsItemDetalheNUMERO: TFloatField; cdsItemDetalheANDAR: TFloatField; cdsItemDetalheAPARTAMENTO: TFloatField; cdsItemDetalheQTD_ESPECIE: TFloatField; cdsItemDetalheESPECIE: TStringField; cdsItemNFeREF_CLIENTE: TStringField; cdsItemDetalheREF_CLIENTE: TStringField; cdsItemNFeCEST: TStringField; cdsItemNFevDesconto: TFloatField; ACBrNFe1: TACBrNFe; ACBrNFeDANFEFR1: TACBrNFeDANFEFR; ACBrMail1: TACBrMail; cdsItemNFecEAN: TStringField; cdsItemNFecEANTrib: TStringField; procedure DataModuleCreate(Sender: TObject); private FNota: real; FSituacao: string; FEmissora: string; FSerie: string; FChave: string; FNroFim: real; FNroInicial: real; public lEnviarEmail: Boolean; smtp_host: string; smtp_porta: string; smtp_usuario: string; smtp_email: string; smtp_senha: string; smtp_UtilizaSSL: Boolean; smtp_EnviarPDF: Boolean; smtp_PedirConfirmacao: Boolean; smtp_AguardarEnvio: Boolean; smtp_UtilizaTLS: Boolean; smtp_Nome: string; procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; procedure ManterCliente(AAtualizarDados: Boolean = False); procedure ManterProduto; procedure LerConfiguracao; procedure ConfiguraEmail(sEndPrincipal: String); property Emissora: string read FEmissora write FEmissora; property Nota: real read FNota write FNota; property Serie: string read FSerie write FSerie; property Situacao: string read FSituacao write FSituacao; property Chave: string read FChave write FChave; property NroInicial: real read FNroInicial write FNroInicial; property NroFim: real read FNroFim write FNroFim; function LocalizaPorChave(DataSet: TDataSet = nil): Boolean; function LocalizarPorFaixa(DataSet: TDataSet = nil): Boolean; function ImportarNFe_Completa(ANomeArquivo: String = ''; AConteudoXML: string = ''): ArrayOfOleVariant; function ImportarNFe(ANomeArquivo: String = ''; AConteudoXML: string = ''): Boolean; end; const PASTA_ARQUIVO = 'mmyyyy'; var dmNFe: TdmNFe; implementation {$R *.dfm} { TdmCfopItem } uses udmCliente, udmCidades, udmVariaveis, udmConfigSMTP, udmProduto, udmPrincipal; procedure TdmNFe.ConfiguraEmail(sEndPrincipal: String); begin AcbrMail1.AddAddress(sEndPrincipal); AcbrMail1.Host := smtp_host; AcbrMail1.Port := smtp_porta; AcbrMail1.Password := smtp_senha; AcbrMail1.From := smtp_email; AcbrMail1.Username := smtp_email; AcbrMail1.SetSSL := smtp_UtilizaSSL; AcbrMail1.SetTLS := smtp_UtilizaTLS; AcbrMail1.ReadingConfirmation := smtp_PedirConfirmacao; AcbrMail1.UseThread := true; AcbrMail1.IsHTML := True; end; procedure TdmNFe.DataModuleCreate(Sender: TObject); var str: TMemoryStream; begin inherited; CriarDataSet(cdsNFe); CriarDataSet(cdsItemNFe); CriarDataSet(cdsFatura); str := TMemoryStream.Create; RecuperarFR3('DANFeRetrato.fr3', str); str.SaveToFile(ExtractFileDir(Application.ExeName)+'\Report\DANFeRetrato.fr3'); str.Free; str := nil; str := TMemoryStream.Create; RecuperarFR3('NFe_EVENTOS.fr3', str); str.SaveToFile(ExtractFileDir(Application.ExeName)+'\Report\NFe_EVENTOS.fr3'); str.Free; str := nil; end; function TdmNFe.ImportarNFe(ANomeArquivo, AConteudoXML: string): Boolean; var i: Integer; j: Integer; volCount : Integer; sArquivo: string; tipoPagamento : string; st: TStringStream; label FimFunction; begin Result := False; sArquivo := ''; LimparDataSet(cdsNFe); LimparDataSet(cdsItemNFe); LimparDataSet(cdsFatura); OpenDialog1.Title := 'Selecione a NFE'; OpenDialog1.DefaultExt := '*.XML'; OpenDialog1.Filter := 'Arquivos XML (*.XML)|*.XML|Arquivos NFE (*-nfe.XML)|*-nfe.XML|Todos os Arquivos (*.*)|*.*'; OpenDialog1.InitialDir := 'c:\NFe'; if not TemValor(AConteudoXML) then begin if TemValor(ANomeArquivo) and FileExists(ANomeArquivo) then sArquivo := ANomeArquivo else begin if OpenDialog1.Execute then sArquivo := OpenDialog1.FileName; end; if (sArquivo <> '') then begin ACBrNFe1.NotasFiscais.Clear; if not FileExists(sArquivo) then begin Application.MessageBox(PwideChar('Arquivo Importado não pode ser carregado novamente!'), 'Atenção', MB_OK + MB_ICONWARNING); goto FimFunction; end; ACBrNFe1.NotasFiscais.LoadFromFile(sArquivo); if UpperCase(Copy(ExtractFileName(sArquivo), 1, 8)) = 'BAIXADO_' then begin Application.MessageBox(PwideChar('Arquivo Importado não pode ser carregado novamente!'), 'Atenção', MB_OK + MB_ICONWARNING); goto FimFunction; end; end; end else begin ACBrNFe1.NotasFiscais.Clear; ACBrNFe1.NotasFiscais.LoadFromString(AConteudoXML); end; if ACBrNFe1.NotasFiscais.Count > 0 then begin for i := 0 to ACBrNFe1.NotasFiscais.Count - 1 do begin with ACBrNFe1.NotasFiscais.Items[i].NFe do begin cdsNFe.Append; //NF + Emitente cdsNFecUF.AsInteger := ide.cUF; cdsNFecNF.AsString := IntToStr(Ide.cNF); cdsNFeNatOp.AsString := Ide.natOp; cdsNFeMod.AsString := '55'; tipoPagamento := pcnConversao.IndpagToStr(Ide.indPag); if tipoPagamento <> '' then cdsNFeindPag.AsInteger := StrToInt(tipoPagamento); cdsNFeSerie.AsString := IntToStr(Ide.serie); cdsNFenNF.AsInteger := Ide.nNF; cdsNFedEmi.AsDateTime := Ide.dEmi; cdsNFedSaiEnt.AsDateTime := Ide.dSaiEnt; cdsNFehSaiEnt.AsDateTime := Ide.hSaiEnt; cdsNFetpNF.AsInteger := StrToInt(tpNFToStr(Ide.tpNF)); cdsNFecMunFG.AsInteger := Ide.cMunFG; cdsNFetpImp.AsInteger := StrToInt(TpImpToStr(Ide.tpImp)); cdsNFetpEmis.AsInteger := StrToInt(TpEmisToStr(Ide.tpEmis)); cdsNFecDV.AsInteger := Ide.cDV; cdsNFetpAmb.AsInteger := StrToInt(TpAmbToStr(Ide.tpAmb)); cdsNFefinNFe.AsInteger := StrToInt(FinNFeToStr(Ide.finNFe)); cdsNFeprocEmi.AsInteger := StrToInt(procEmiToStr(Ide.procEmi)); cdsNFeEmitxNome.AsString := Emit.xNome; cdsNFeEmitxFant.AsString := Emit.xFant; cdsNFeEmitxLgr.AsString := Emit.EnderEmit.xLgr; cdsNFeEmitNro.AsString := Emit.EnderEmit.nro; cdsNFeEmitCpl.AsString := Emit.EnderEmit.xCpl; cdsNFeEmitxBairro.AsString := Emit.EnderEmit.xBairro; cdsNFeEmitcMun.AsInteger := Emit.EnderEmit.cMun; cdsNFeEmitxMun.AsString := Emit.EnderEmit.xMun; cdsNFeEmitUF.AsString := Emit.EnderEmit.UF; cdsNFeEmitCep.AsString := IntToStr(Emit.EnderEmit.CEP); cdsNFecEmitPais.AsString := IntToStr(Emit.EnderEmit.cPais); cdsNFeEmitxPais.AsString := Emit.EnderEmit.xPais; cdsNFeEmitFone.AsString := Emit.EnderEmit.fone; // cdsNFeEmitEmail.AsString := Emit.EnderEmit. cdsNFeEmitCNPJ.AsString := Emit.CNPJCPF; cdsNFeEmitIE.AsString := Emit.IE; //Destinatario if TemValor(dest.idEstrangeiro) then cdsNFeDestCNPJ.AsString := dest.idEstrangeiro else cdsNFeDestCNPJ.AsString := Dest.CNPJCPF; cdsNFeDestxNome.AsString := Dest.xNome; //cdsNFeDestFant.AsString := Dest. cdsNFeDestxLgr.AsString := Dest.EnderDest.xLgr; cdsNFeDestNro.AsString := Dest.EnderDest.nro; cdsNFeDestCpl.AsString := Dest.EnderDest.xCpl; cdsNFeDestxBairro.AsString := Dest.EnderDest.xBairro; cdsNFeDestcMun.AsInteger := Dest.EnderDest.cMun; cdsNFeDestxMun.AsString := Dest.EnderDest.xMun; cdsNFeDestUF.AsString := Dest.EnderDest.UF; cdsNFeDestCep.AsString := IntToStr(Dest.EnderDest.CEP); cdsNFeDestcPais.AsString := IntToStr(Dest.EnderDest.cPais); cdsNFeDestxPais.AsString := Dest.EnderDest.xPais; cdsNFeDestFone.AsString := Dest.EnderDest.fone; cdsNFeDestIE.AsString := Dest.IE; cdsNFeDestEmail.AsString := Dest.Email; //Total de Impostos cdsNFeTotvBC.AsFloat := Total.ICMSTot.vBC; cdsNFeTotvICMS.AsFloat := Total.ICMSTot.vICMS; cdsNFeTotvBCST.AsFloat := Total.ICMSTot.vBCST; cdsNFeTotvST.AsFloat := Total.ICMSTot.vST; cdsNFeTotvProd.AsFloat := Total.ICMSTot.vProd; cdsNFeTotvFrete.AsFloat := Total.ICMSTot.vFrete; cdsNFeTotvSeg.AsFloat := Total.ICMSTot.vSeg; cdsNFeTotvDesc.AsFloat := Total.ICMSTot.vDesc; cdsNFeTotvII.AsFloat := Total.ICMSTot.vII; cdsNFeTotvIPI.AsFloat := Total.ICMSTot.vIPI; cdsNFeTotvNF.AsFloat := Total.ICMSTot.vNF; cdsNFeTotvPIS.AsFloat := Total.ICMSTot.vPIS; cdsNFeTotvCOFINS.AsFloat := Total.ICMSTot.vCOFINS; cdsNFeTotvOUTRO.AsFloat := Total.ICMSTot.vOutro; cdsNFeISSTotvServ.AsFloat := Total.ISSQNtot.vServ; cdsNFeISSTotvBC.AsFloat := Total.ISSQNtot.vBC; cdsNFeISSTotvISS.AsFloat := Total.ISSQNtot.vISS; cdsNFeISSTotvPIS.AsFloat := Total.ISSQNtot.vPIS; cdsNFeISSTotvCOFINS.AsFloat := Total.ISSQNtot.vCOFINS; // Transpordora e informações de garga(peso, vol, esp) cdsNFeTranspModFrete.AsInteger := StrToInt(modFreteToStr(Transp.modFrete)); cdsNFeTranspxCNPJ.AsString := Transp.Transporta.CNPJCPF; cdsNFeTranspxNome.AsString := Transp.Transporta.xNome; cdsNFeTranspIE.AsString := Transp.Transporta.IE; cdsNFeTranspxEnder.AsString := Transp.Transporta.xEnder; cdsNFeTranpxMun.AsString := Transp.Transporta.xMun; cdsNFeTranspUF.AsString := Transp.Transporta.UF; if Transp.Vol.Count > 0 then begin cdsNFeTranspesp.AsString := Transp.Vol.Items[0].esp; cdsNFeTranspmarca.AsString := Transp.Vol.Items[0].marca; for volCount := 0 to Transp.Vol.Count - 1 do begin cdsNFeTranspqVol.AsInteger := cdsNFeTranspqVol.AsInteger + Transp.Vol.Items[volCount].qVol; cdsNFeTransppesoL.AsFloat := cdsNFeTransppesoL.AsInteger + Transp.Vol.Items[volCount].pesoL; cdsNFeTransppesoB.AsFloat := cdsNFeTransppesoB.AsInteger + Transp.Vol.Items[volCount].pesoB; end; end; cdsNFeTranspVeiplaca.AsString := Transp.veicTransp.placa; cdsNFeTranspVeiuf.AsString := Transp.veicTransp.UF; case Transp.modFrete of mfContaEmitente: cdsNFeTranspModFrete.AsInteger := 0; mfContaDestinatario: cdsNFeTranspModFrete.AsInteger := 1; mfContaTerceiros: cdsNFeTranspModFrete.AsInteger := 2; mfSemFrete: cdsNFeTranspModFrete.AsInteger := 9; end; cdsNFeInfAdicinfCpl.AsString := InfAdic.infCpl; cdsNFeChave.AsString := procNFe.chNFe; cdsNFeFatnFat.AsString := Cobr.Fat.nFat; cdsNFeFatvOrig.AsFloat := Cobr.Fat.vOrig; cdsNFeFatvDesc.AsFloat := Cobr.Fat.vDesc; cdsNFeFatvLiq.AsFloat := Cobr.Fat.vLiq; for j := 0 to Det.Count - 1 do begin with Det.Items[j] do begin cdsItemNFe.Append; cdsItemNFenItem.AsInteger := Prod.nItem; cdsItemNFecProd.AsString := Prod.cProd; cdsItemNFexProd.AsString := Prod.xProd; cdsItemNFeCFOP.AsString := Prod.CFOP; cdsItemNFeqCom.AsFloat := Prod.qCom; cdsItemNFevUnit.AsFloat := Prod.vUnCom; cdsItemNFevProd.AsFloat := Prod.vProd; cdsItemNFeuCom.AsString := Prod.uCom; cdsItemNFeNCM.AsString := Prod.NCM; cdsItemNFevDesconto.AsFloat := Prod.vDesc; //if Prod.CEST <> '' then // cdsItemNFeCEST.AsString := Prod.CEST; // Prod.xPed with Imposto do begin with ICMS do begin cdsItemNFeICMSOrig.AsString := OrigToStr(orig); cdsItemNFeICMSCST.AsString := OrigToStr(orig) + CSTICMSToStr(CST); cdsItemNFeICMSvBC.AsFloat := vBC; cdsItemNFeICMSpICMS.AsFloat := pICMS; cdsItemNFeICMSvICMS.AsFloat := vICMS; cdsItemNFeICMSvBC_ST.AsFloat := vBCST; cdsItemNFeICMSpICMS_ST.AsFloat := pICMSST; cdsItemNFeICMSvICMS_ST.AsFloat := vICMSST; end; with IPI do begin cdsItemNFeIPIcEnq.AsString := cEnq; cdsItemNFeIPICST.AsString := CSTIPIToStr(CST); cdsItemNFeIPIvBC.AsFloat := vBC; cdsItemNFeIPIpIPI.AsFloat := pIPI; cdsItemNFeIPIvIPI.AsFloat := vIPI; end; with PIS do begin cdsItemNFePISCST.AsString := CSTPISToStr(CST); cdsItemNFePISvBC.AsFloat := vBC; cdsItemNFePISpPIS.AsFloat := pPIS; cdsItemNFePISvPIS.AsFloat := vPIS; end; with COFINS do begin cdsItemNFeCOFINSCST.AsString := CSTCOFINSToStr(CST); cdsItemNFeCOFINSvBC.AsFloat := vBC; cdsItemNFeCOFINSpCOFINS.AsFloat := pCOFINS; cdsItemNFeCOFINSvCOFINS.AsFloat := vCOFINS; end; end; cdsItemNFe.Post; end; end; with Transp do begin if modFrete = mfContaEmitente then cdsNFeTranspModFrete.AsInteger := 0 else cdsNFeTranspModFrete.AsInteger := 1; cdsNFeTranspxNome.AsString := Transporta.xNome; cdsNFeTranspxCNPJ.AsString := Transporta.CNPJCPF; end; cdsNFeTranspvNota.AsFloat := Total.ICMSTot.vNF; cdsNFeInfAdicinfCpl.AsString := InfAdic.infCpl; end; cdsNfe.Post; end; if sArquivo <> '' then RenameFile(sArquivo, ExtractFilePath(sArquivo) + 'baixado_' + ExtractFileName(sArquivo)); end; FimFunction: Result := not cdsNFe.IsEmpty; end; function TdmNFe.ImportarNFe_Completa(ANomeArquivo: String = ''; AConteudoXML: string = ''): ArrayOfOleVariant; var i: Integer; j: Integer; volCount: Integer; sArquivo: string; tipoPagamento : string; st: TStringStream; label FimFunction; begin sArquivo := ''; LimparDataSet(cdsNFe); LimparDataSet(cdsItemNFe); LimparDataSet(cdsFatura); OpenDialog1.Title := 'Selecione a NFE'; OpenDialog1.DefaultExt := '*.XML'; OpenDialog1.Filter := 'Arquivos XML (*.XML)|*.XML|Arquivos NFE (*-nfe.XML)|*-nfe.XML|Todos os Arquivos (*.*)|*.*'; OpenDialog1.InitialDir := 'c:\NFe'; if not TemValor(AConteudoXML) then begin if TemValor(ANomeArquivo) and FileExists(ANomeArquivo) then sArquivo := ANomeArquivo else begin if OpenDialog1.Execute then sArquivo := OpenDialog1.FileName; end; if (sArquivo <> '') then begin ACBrNFe1.NotasFiscais.Clear; if not FileExists(sArquivo) then begin Application.MessageBox(PwideChar('Arquivo Importado não pode ser carregado novamente!'), 'Atenção', MB_OK + MB_ICONWARNING); goto FimFunction; end; ACBrNFe1.NotasFiscais.LoadFromFile(sArquivo); if UpperCase(Copy(ExtractFileName(sArquivo), 1, 8)) = 'BAIXADO_' then begin Application.MessageBox(PwideChar('Arquivo Importado não pode ser carregado novamente!'), 'Atenção', MB_OK + MB_ICONWARNING); goto FimFunction; end; end; end else begin // st := TStringStream.Create(AConteudoXML); ACBrNFe1.NotasFiscais.Clear; ACBrNFe1.NotasFiscais.LoadFromString(AConteudoXML); end; if ACBrNFe1.NotasFiscais.Count > 0 then begin for i := 0 to ACBrNFe1.NotasFiscais.Count - 1 do begin with ACBrNFe1.NotasFiscais.Items[i].NFe do begin cdsNFe.Append; //NF + Emitente cdsNFecUF.AsInteger := ide.cUF; cdsNFecNF.AsString := IntToStr(Ide.cNF); cdsNFeNatOp.AsString := Ide.natOp; cdsNFeMod.AsString := '55'; tipoPagamento := pcnConversao.IndpagToStr(Ide.indPag); cdsNFeindPag.AsInteger := StrToInt(tipoPagamento); cdsNFeSerie.AsString := IntToStr(Ide.serie); cdsNFenNF.AsInteger := Ide.nNF; cdsNFedEmi.AsDateTime := Ide.dEmi; cdsNFedSaiEnt.AsDateTime := Ide.dSaiEnt; cdsNFehSaiEnt.AsDateTime := Ide.hSaiEnt; cdsNFetpNF.AsInteger := StrToInt(tpNFToStr(Ide.tpNF)); cdsNFecMunFG.AsInteger := Ide.cMunFG; cdsNFetpImp.AsInteger := StrToInt(TpImpToStr(Ide.tpImp)); cdsNFetpEmis.AsInteger := StrToInt(TpEmisToStr(Ide.tpEmis)); cdsNFecDV.AsInteger := Ide.cDV; cdsNFetpAmb.AsInteger := StrToInt(TpAmbToStr(Ide.tpAmb)); cdsNFefinNFe.AsInteger := StrToInt(FinNFeToStr(Ide.finNFe)); cdsNFeprocEmi.AsInteger := StrToInt(procEmiToStr(Ide.procEmi)); cdsNFeEmitxNome.AsString := Emit.xNome; cdsNFeEmitxFant.AsString := Emit.xFant; cdsNFeEmitxLgr.AsString := Emit.EnderEmit.xLgr; cdsNFeEmitNro.AsString := Emit.EnderEmit.nro; cdsNFeEmitCpl.AsString := Emit.EnderEmit.xCpl; cdsNFeEmitxBairro.AsString := Emit.EnderEmit.xBairro; cdsNFeEmitcMun.AsInteger := Emit.EnderEmit.cMun; cdsNFeEmitxMun.AsString := Emit.EnderEmit.xMun; cdsNFeEmitUF.AsString := Emit.EnderEmit.UF; cdsNFeEmitCep.AsString := IntToStr(Emit.EnderEmit.CEP); cdsNFecEmitPais.AsString := IntToStr(Emit.EnderEmit.cPais); cdsNFeEmitxPais.AsString := Emit.EnderEmit.xPais; cdsNFeEmitFone.AsString := Emit.EnderEmit.fone; // cdsNFeEmitEmail.AsString := Emit.EnderEmit. cdsNFeEmitCNPJ.AsString := Emit.CNPJCPF; cdsNFeEmitIE.AsString := Emit.IE; //Destinatario cdsNFeDestCNPJ.AsString := Dest.CNPJCPF; cdsNFeDestxNome.AsString := Dest.xNome; //cdsNFeDestFant.AsString := Dest. cdsNFeDestxLgr.AsString := Dest.EnderDest.xLgr; cdsNFeDestNro.AsString := Dest.EnderDest.nro; cdsNFeDestCpl.AsString := Dest.EnderDest.xCpl; cdsNFeDestxBairro.AsString := Dest.EnderDest.xBairro; cdsNFeDestcMun.AsInteger := Dest.EnderDest.cMun; cdsNFeDestxMun.AsString := Dest.EnderDest.xMun; cdsNFeDestUF.AsString := Dest.EnderDest.UF; cdsNFeDestCep.AsString := IntToStr(Dest.EnderDest.CEP); cdsNFeDestcPais.AsString := IntToStr(Dest.EnderDest.cPais); cdsNFeDestxPais.AsString := Dest.EnderDest.xPais; cdsNFeDestFone.AsString := Dest.EnderDest.fone; cdsNFeDestIE.AsString := Dest.IE; cdsNFeDestEmail.AsString := Dest.Email; //Total de Impostos cdsNFeTotvBC.AsFloat := Total.ICMSTot.vBC; cdsNFeTotvICMS.AsFloat := Total.ICMSTot.vICMS; cdsNFeTotvBCST.AsFloat := Total.ICMSTot.vBCST; cdsNFeTotvST.AsFloat := Total.ICMSTot.vST; cdsNFeTotvProd.AsFloat := Total.ICMSTot.vProd; cdsNFeTotvFrete.AsFloat := Total.ICMSTot.vFrete; cdsNFeTotvSeg.AsFloat := Total.ICMSTot.vSeg; cdsNFeTotvDesc.AsFloat := Total.ICMSTot.vDesc; cdsNFeTotvII.AsFloat := Total.ICMSTot.vII; cdsNFeTotvIPI.AsFloat := Total.ICMSTot.vIPI; cdsNFeTotvNF.AsFloat := Total.ICMSTot.vNF; cdsNFeTotvPIS.AsFloat := Total.ICMSTot.vPIS; cdsNFeTotvCOFINS.AsFloat := Total.ICMSTot.vCOFINS; cdsNFeTotvOUTRO.AsFloat := Total.ICMSTot.vOutro; cdsNFeISSTotvServ.AsFloat := Total.ISSQNtot.vServ; cdsNFeISSTotvBC.AsFloat := Total.ISSQNtot.vBC; cdsNFeISSTotvISS.AsFloat := Total.ISSQNtot.vISS; cdsNFeISSTotvPIS.AsFloat := Total.ISSQNtot.vPIS; cdsNFeISSTotvCOFINS.AsFloat := Total.ISSQNtot.vCOFINS; // Transpordora e informações de garga(peso, vol, esp) cdsNFeTranspModFrete.AsInteger := StrToInt(modFreteToStr(Transp.modFrete)); cdsNFeTranspxCNPJ.AsString := Transp.Transporta.CNPJCPF; cdsNFeTranspxNome.AsString := Transp.Transporta.xNome; cdsNFeTranspIE.AsString := Transp.Transporta.IE; cdsNFeTranspxEnder.AsString := Transp.Transporta.xEnder; cdsNFeTranpxMun.AsString := Transp.Transporta.xMun; cdsNFeTranspUF.AsString := Transp.Transporta.UF; if Transp.Vol.Count > 0 then begin cdsNFeTranspesp.AsString := Transp.Vol.Items[0].esp; cdsNFeTranspmarca.AsString := Transp.Vol.Items[0].marca; for volCount := 0 to Transp.Vol.Count - 1 do begin cdsNFeTranspqVol.AsInteger := cdsNFeTranspqVol.AsInteger + Transp.Vol.Items[volCount].qVol; cdsNFeTransppesoL.AsFloat := cdsNFeTransppesoL.AsInteger + Transp.Vol.Items[volCount].pesoL; cdsNFeTransppesoB.AsFloat := cdsNFeTransppesoB.AsInteger + Transp.Vol.Items[volCount].pesoB; end; end; cdsNFeTranspVeiplaca.AsString := Transp.veicTransp.placa; cdsNFeTranspVeiuf.AsString := Transp.veicTransp.UF; case Transp.modFrete of mfContaEmitente: cdsNFeTranspModFrete.AsInteger := 0; mfContaDestinatario: cdsNFeTranspModFrete.AsInteger := 1; mfContaTerceiros: cdsNFeTranspModFrete.AsInteger := 2; mfSemFrete: cdsNFeTranspModFrete.AsInteger := 9; end; cdsNFeInfAdicinfCpl.AsString := InfAdic.infCpl; cdsNFeChave.AsString := procNFe.chNFe; cdsNFeFatnFat.AsString := Cobr.Fat.nFat; cdsNFeFatvOrig.AsFloat := Cobr.Fat.vOrig; cdsNFeFatvDesc.AsFloat := Cobr.Fat.vDesc; cdsNFeFatvLiq.AsFloat := Cobr.Fat.vLiq; for j := 0 to Det.Count - 1 do begin with Det.Items[j] do begin cdsItemNFe.Append; cdsItemNFenItem.AsInteger := Prod.nItem; cdsItemNFecProd.AsString := Prod.cProd; cdsItemNFexProd.AsString := Prod.xProd; cdsItemNFeCFOP.AsString := Prod.CFOP; cdsItemNFeqCom.AsFloat := Prod.qCom; cdsItemNFevUnit.AsFloat := Prod.vUnCom; cdsItemNFevProd.AsFloat := Prod.vProd; cdsItemNFevDesconto.AsFloat := Prod.vDesc; cdsItemNFeuCom.AsString := Prod.uCom; cdsItemNFeNCM.AsString := Prod.NCM; cdsItemNFeCEST.AsString := Prod.CEST; if Prod.cEAN <> 'SEM GTIN' then cdsItemNFecEAN.AsString := Prod.cEAN; if Prod.cEANTrib <> 'SEM GTIN' then cdsItemNFecEANTrib.AsString := Prod.cEANTrib; // Prod.xPed with Imposto do begin with ICMS do begin cdsItemNFeICMSOrig.AsString := OrigToStr(orig); cdsItemNFeICMSCST.AsString := OrigToStr(orig) + CSTICMSToStr(CST); cdsItemNFeICMSvBC.AsFloat := vBC; cdsItemNFeICMSpICMS.AsFloat := pICMS; cdsItemNFeICMSvICMS.AsFloat := vICMS; cdsItemNFeICMSvBC_ST.AsFloat := vBCST; cdsItemNFeICMSpICMS_ST.AsFloat := pICMSST; cdsItemNFeICMSvICMS_ST.AsFloat := vICMSST; end; with IPI do begin cdsItemNFeIPIcEnq.AsString := cEnq; cdsItemNFeIPICST.AsString := CSTIPIToStr(CST); cdsItemNFeIPIvBC.AsFloat := vBC; cdsItemNFeIPIpIPI.AsFloat := pIPI; cdsItemNFeIPIvIPI.AsFloat := vIPI; end; with PIS do begin cdsItemNFePISCST.AsString := CSTPISToStr(CST); cdsItemNFePISvBC.AsFloat := vBC; cdsItemNFePISpPIS.AsFloat := pPIS; cdsItemNFePISvPIS.AsFloat := vPIS; end; with COFINS do begin cdsItemNFeCOFINSCST.AsString := CSTCOFINSToStr(CST); cdsItemNFeCOFINSvBC.AsFloat := vBC; cdsItemNFeCOFINSpCOFINS.AsFloat := pCOFINS; cdsItemNFeCOFINSvCOFINS.AsFloat := vCOFINS; end; end; cdsItemNFe.Post; end; end; with Transp do begin if modFrete = mfContaEmitente then cdsNFeTranspModFrete.AsInteger := 0 else cdsNFeTranspModFrete.AsInteger := 1; cdsNFeTranspxNome.AsString := Transporta.xNome; cdsNFeTranspxCNPJ.AsString := Transporta.CNPJCPF; end; cdsNFeTranspvNota.AsFloat := Total.ICMSTot.vNF; cdsNFeInfAdicinfCpl.AsString := InfAdic.infCpl; end; cdsNfe.Post; end; if sArquivo <> '' then RenameFile(sArquivo, ExtractFilePath(sArquivo) + 'baixado_' + ExtractFileName(sArquivo)); end; FimFunction: result.Nota := cdsNFe.Data; result.Item := cdsItemNFe.Data; result.Fatura := cdsFatura.Data; end; procedure TdmNFe.LerConfiguracao; begin ACBrNFe1.Configuracoes.Geral.Salvar := False; if sSnh_NmUsuario = 'AMERICA' then if Perguntar('Salvar arquivos?') then begin ACBrNFe1.Configuracoes.Geral.Salvar := True; ACBrNFe1.Configuracoes.Arquivos.Salvar := True; end; //PASTA QUE SALVA O ARQUIVO XML DO NFE try ForceDirectories(sPath_Nfe + '\' + FormatDateTime(PASTA_ARQUIVO, Now)); //ACBrNFe1.NotasFiscais.Configuracoes.Geral.PathSalvar := sPath_Nfe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); ACBrNFe1.Configuracoes.Arquivos.PathSalvar := sPath_Nfe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); except //ACBrNFe1.NotasFiscais.Configuracoes.Geral.PathSalvar := sPath_Nfe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); ACBrNFe1.Configuracoes.Arquivos.PathSalvar := sPath_Nfe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); end; //PASTA QUE SALVA O PDF DO NFE try ForceDirectories(sPathPDF_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now)); ACBrNFe1.DANFE.PathPDF := sPathPDF_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); // ACBrNFeDANFEQR1.PathPDF := sPathPDF_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); except ACBrNFe1.DANFE.PathPDF := sPathPDF_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); // ACBrNFeDANFEQR1.PathPDF := sPathPDF_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); end; //PASTA QUE SALVA O ARQUIVO XML DO CCe try ForceDirectories(sPathCCe_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now)); //ACBrNFe1.Configuracoes.Arquivos.PathCCe := sPathCCe_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); ACBrNFe1.Configuracoes.Arquivos.PathEvento := sPathCCe_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); except //ACBrNFe1.Configuracoes.Arquivos.PathCCe := sPathCCe_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); ACBrNFe1.Configuracoes.Arquivos.PathEvento := sPathCCe_NFe + '\' + FormatDateTime(PASTA_ARQUIVO, Now); end; ACBrNFe1.DANFE.NumCopias := iNumCopiasNFe; ACBrNFe1.DANFE.Usuario := sSnh_NmUsuario; ACBrNFe1.DANFE.Sistema := 'Processado por www.americasoft.com.br'; ACBrNFe1.DANFE.Logo := sCaminhoLogo_NFe; ACBrNFe1.DANFE.MostrarPreview := lVisualizarDANFE; ACBrNFe1.DANFE.CasasDecimais._qCom := iNroDecimaisArmazem; ACBrNFe1.DANFE.CasasDecimais._vUnCom := iNroDecimaisArmazem; if TemValor(sImpressoraPadraoNFe) then ACBrNFe1.DANFE.Impressora := sImpressoraPadraoNFe; if sCertDigitalNumeroSerie <> '' then begin if sCertDigitalCaminhoPFX <> '' then begin ACBRNfe1.Configuracoes.Geral.SSLLib := libWinCrypt; ACBrNFe1.Configuracoes.Certificados.ArquivoPFX := sCertDigitalCaminhoPFX; end; ACBrNFe1.Configuracoes.Certificados.NumeroSerie := sCertDigitalNumeroSerie; ACBrNFe1.Configuracoes.Certificados.Senha := sCertDigitalSenha; end else ACBrNFe1.Configuracoes.Certificados.NumeroSerie := ACBrNFe1.SSL.SelecionarCertificado; ACBrNFeDANFEFR1.FastFile := PathWithDelim(ExtractFilePath(Application.ExeName)) + 'Report\DANFeRetrato.fr3'; ACBrNFeDANFEFR1.FastFileEvento := PathWithDelim(ExtractFilePath(Application.ExeName)) + 'Report\NFe_EVENTOS.fr3'; // if cdsNotaSCAN.AsBoolean = True then // ACBrNFe1.Configuracoes.Geral.FormaEmissao := teSCAN // else // ACBrNFe1.Configuracoes.Geral.FormaEmissao := teNormal; ACBrNFe1.Configuracoes.WebServices.UF := dmVariaveis.qryManutencaoESTADO.AsString; ACBrNFe1.Configuracoes.WebServices.Visualizar := True; ACBrNFe1.Configuracoes.WebServices.ProxyHost := sProxyServer; ACBrNFe1.Configuracoes.WebServices.ProxyPort := IntToStr(iProxyPort); ACBrNFe1.Configuracoes.WebServices.ProxyUser := sProxyUsername; ACBrNFe1.Configuracoes.WebServices.ProxyPass := sProxyPassword; ACBrNFe1.Configuracoes.Arquivos.PathSchemas := sPathSchemas_NFe; with dmConfigSMTP do begin Codigo := 'NFE'; if Localizar then begin smtp_host := qryLocalizacaoHOST.AsString; smtp_porta := IntToStr(qryLocalizacaoPORTA.AsInteger); smtp_usuario := qryLocalizacaoUSUARIO.AsString; smtp_email := qryLocalizacaoEMAIL.AsString; smtp_senha := qryLocalizacaoSENHA.AsString; smtp_UtilizaSSL := qryLocalizacaoSSL.AsString = 'T'; smtp_UtilizaTLS := qryLocalizacaoTLS.AsString = 'T'; smtp_PedirConfirmacao := qryLocalizacaoCONFIRMACAO.AsString = 'T'; smtp_AguardarEnvio := qryLocalizacaoAGUARDAR.AsString = 'T'; smtp_EnviarPDF := qryLocalizacaoENVIARPDF.AsString = 'T'; smtp_Nome := qryLocalizacaoNOME.AsString; end; end; lEnviarEmail := (Length(Trim(smtp_host)) > 0) and (Length(Trim(smtp_porta)) > 0) and (Length(Trim(smtp_usuario)) > 0) and (Length(Trim(smtp_senha)) > 0) and (Length(Trim(smtp_email)) > 0); if lNfeAmbienteTestes then ACBrNFe1.Configuracoes.WebServices.Ambiente := taHomologacao else ACBrNFe1.Configuracoes.WebServices.Ambiente := taProducao; //if isEmpresa(ML) OR isEmpresa(EMANSSINI) OR isEmpresa(Bandeira) then ACBrNFe1.SSL.SSlType := LT_TLSv1_2; end; function TdmNFe.LocalizaPorChave(DataSet: TDataSet): Boolean; begin inherited; if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add('SELECT * FROM STWARMTNFE'); SQL.Add('WHERE FIL_COBR = :FIL_COBR AND CHAVE = :CHAVE'); SQL.Add(' AND SERIE = :SERIE AND SITUACAO = :SITUACAO'); ParamByName('FIL_COBR').AsString := Emissora; ParamByName('CHAVE').AsString := Chave; ParamByName('SERIE').AsString := Copy(Serie,1,2); ParamByName('SITUACAO').AsString := Situacao; Open; Result := not IsEmpty; end; end; function TdmNFe.LocalizarPorFaixa(DataSet: TDataSet): Boolean; begin inherited; if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin FetchAll := True; SQL.Clear; SQL.Add('SELECT * FROM STWARMTNFE'); SQL.Add('WHERE FIL_COBR = :FIL_COBR '); SQL.Add(' AND NOTA BETWEEN :INICIO AND :FIM'); SQL.Add('ORDER BY FIL_COBR, NOTA'); ParamByName('FIL_COBR').AsString := FEmissora; ParamByName('INICIO').AsFloat := FNroInicial; ParamByName('FIM').AsFloat := FNroFim; Open; Result := not IsEmpty; end; end; procedure TdmNFe.ManterCliente(AAtualizarDados: Boolean); var sFilial:String; begin if not Assigned(dmCliente) then dmCliente := TdmCliente.Create(Application); if not Assigned(dmPrincipal) then dmPrincipal := TdmPrincipal.Create(Application); if not Assigned(dmCidades) then dmCidades := TdmCidades.Create(Application); with dmCidades do begin Cidade := TratarNomeMunicipio(cdsNFeEmitxMun.AsString); Estado := UpperCase(cdsNFeEmitUF.AsString); sFilial := ''; if Localizar then sFilial := dmCidades.qryLocalizacaoFILIAL.AsString else sFilial := dmVariaveis.qryManutencaoFILIAL.AsString; end; //REMETENTE with dmCliente do begin if cdsNFeEmitCNPJ.AsString <> '' then begin Cod_Cliente := Formata_CgcCpf(cdsNFeEmitCNPJ.AsString);; if not Localizar(qryManutencao) then begin qryManutencao.Append; qryManutencaoCGC.AsString := Formata_CgcCpf(cdsNFeEmitCNPJ.AsString); qryManutencaoCGC_PAG.AsString := Formata_CgcCpf(cdsNFeEmitCNPJ.AsString); if not TemValor(cdsNFeEmitIE.AsString) then qryManutencaoINSC_EST.AsString := 'ISENTO' else qryManutencaoINSC_EST.AsString := Formata_Inscricao(cdsNFeEmitIE.AsString, UpperCase(cdsNFeEmitUF.AsString)); if IsCpf(qryManutencaoCGC.AsString) then qryManutencaoCONTRIB.AsString := 'F' else qryManutencaoCONTRIB.AsString := 'J'; qryManutencaoVENDEDOR.AsFLoat := 0; qryManutencaoFILIAL.AsString := sFilial; qryManutencaoCATEGORIA.AsInteger := 2; qryManutencaoBLOQUEIO.AsString := 'F'; qryManutencaoINADIMPLENTE.AsString := 'F'; qryManutencaoFRT_DIRIGIDO.AsString := 'F'; qryManutencaoDT_INCLUSAO.AsDateTime := pegarDataHoraServidor; if lUtilizaNumCodContail then qryManutencaoCODCONTABIL.AsString := IntToStr(dmPrincipal.GeraNumerador(sSnh_Filial, 'COD_CONTABIL')); end else if AAtualizarDados then qryManutencao.Edit; if qryManutencao.State in [dsEdit,dsInsert] then begin qryManutencaoNOME.AsString := UpperCase(Trim(cdsNFeEmitxNome.AsString)); qryManutencaoFANTASIA.AsString := UpperCase(Trim(cdsNFeEmitxNome.AsString)); qryManutencaoENDERECO.AsString := UpperCase(Trim(cdsNFeEmitxLgr.AsString)); qryManutencaoEND_NRO.AsString := UpperCase(Trim(cdsNFeEmitNro.AsString)); qryManutencaoEND_COMPL.AsString := UpperCase(Trim(cdsNFeEmitCpl.AsString)); qryManutencaoBAIRRO.AsString := TratarNomeMunicipio(cdsNFeEmitxBairro.AsString); qryManutencaoCIDADE.AsString := TratarNomeMunicipio(cdsNFeEmitxMun.AsString); qryManutencaoESTADO.AsString := UpperCase(cdsNFeEmitUF.AsString); qryManutencaoCEP.AsString := FormatFloat('00000-000', StrToInt(cdsNFeEmitCep.AsString)); qryManutencaoTEL1.AsString := FormatarTelefone(cdsNFeEmitFone.AsString); qryManutencaoULT_ACESSO.AsDateTime := pegarDataHoraServidor; qryManutencaoOPERADOR.AsString := 'IMPORTACAO NFE'; qryManutencaoDT_ALTERACAO.AsDateTime := pegarDataHoraServidor; qryManutencao.Post; end; end; end; //DESTINATARIO with dmCliente do begin with dmCidades do begin Cidade := TratarNomeMunicipio(cdsNFeDestxMun.AsString); Estado := UpperCase(cdsNFeDestUF.AsString); sFilial := ''; if Localizar then sFilial := dmCidades.qryLocalizacaoFILIAL.AsString else sFilial := dmVariaveis.qryManutencaoFILIAL.AsString; end; if cdsNFeDestCNPJ.AsString <> '' then begin Cod_Cliente := Formata_CgcCpf(cdsNFeDestCNPJ.AsString);; if not Localizar(qryManutencao) then begin qryManutencao.Append; qryManutencaoNOME.AsString := UpperCase(Trim(cdsNFeDestxNome.AsString)); qryManutencaoCGC.AsString := Formata_CgcCpf(cdsNFeDestCNPJ.AsString); qryManutencaoCGC_PAG.AsString := Formata_CgcCpf(cdsNFeDestCNPJ.AsString); if not TemValor(cdsNFeDestIE.AsString) then qryManutencaoINSC_EST.AsString := 'ISENTO' else qryManutencaoINSC_EST.AsString := Formata_Inscricao(cdsNFeDestIE.AsString, cdsNFeDestUF.AsString); if IsCpf(qryManutencaoCGC.AsString) then qryManutencaoCONTRIB.AsString := 'F' else qryManutencaoCONTRIB.AsString := 'J'; qryManutencaoVENDEDOR.AsFLoat := 0; qryManutencaoFILIAL.AsString := sFilial; qryManutencaoCATEGORIA.AsInteger := 2; qryManutencaoBLOQUEIO.AsString := 'F'; qryManutencaoINADIMPLENTE.AsString := 'F'; qryManutencaoFRT_DIRIGIDO.AsString := 'F'; qryManutencaoDT_INCLUSAO.AsDateTime := pegarDataHoraServidor; if lUtilizaNumCodContail then qryManutencaoCODCONTABIL.AsString := IntToStr(dmPrincipal.GeraNumerador(sSnh_Filial, 'COD_CONTABIL')); end else if AAtualizarDados then qryManutencao.Edit; if qryManutencao.State in [dsEdit,dsInsert] then begin qryManutencaoNOME.AsString := UpperCase(Trim(cdsNFeDestxNome.AsString)); qryManutencaoFANTASIA.AsString := UpperCase(Trim(cdsNFeDestxNome.AsString)); qryManutencaoENDERECO.AsString := UpperCase(Trim(cdsNFeDestxLgr.AsString)); qryManutencaoEND_NRO.AsString := UpperCase(Trim(cdsNFeDestNro.AsString)); qryManutencaoEND_COMPL.AsString := UpperCase(Trim(cdsNFeDestCpl.AsString)); qryManutencaoBAIRRO.AsString := TratarNomeMunicipio(cdsNFeDestxBairro.AsString); qryManutencaoCIDADE.AsString := TratarNomeMunicipio(cdsNFeDestxMun.AsString); qryManutencaoESTADO.AsString := UpperCase(cdsNFeDestUF.AsString); qryManutencaoCEP.AsString := FormatFloat('00000-000', StrToInt(cdsNFeDestCep.AsString)); qryManutencaoTEL1.AsString := FormatarTelefone(cdsNFeDestFone.AsString); qryManutencaoULT_ACESSO.AsDateTime := pegarDataHoraServidor; qryManutencaoOPERADOR.AsString := 'IMPORTACAO NFE'; qryManutencaoDT_ALTERACAO.AsDateTime := pegarDataHoraServidor; qryManutencao.Post; end; end; end; end; procedure TdmNFe.ManterProduto; begin if not Assigned(dmProduto) then dmProduto := TdmProduto.Create(Application); with dmProduto do begin Cod_Produto := cdsItemNFecProd.AsString; if not Localizar(qryManutencao) then Cod_Produto := cdsItemNFexProd.AsString; if not Localizar(qryManutencao) then begin qryManutencao.Insert; qryManutencaoCODIGO.AsString := UpperCase(cdsItemNFecProd.AsString); qryManutencaoDESCRICAO.AsString := UpperCase(cdsItemNFexProd.AsString); qryManutencaoUNID_ESTQ.AsString := UpperCase(cdsItemNFeuCom.AsString); qryManutencaoUNID_COBR.AsString := UpperCase(cdsItemNFeuCom.AsString); qryManutencaoMOEDA.AsString := 'R$'; qryManutencaoFATURAMENTO.Value := 'SALDO MÉDIO'; qryManutencaoPERIGOSO.Value := 'F'; qryManutencaoCONTROLADO_PF.Value := 'F'; qryManutencaoCONTROLADO_EX.Value := 'F'; qryManutencaoCONTROLADO_SSP.Value := 'F'; qryManutencaoVLR_UNID.AsFloat := cdsItemNFevUnit.AsFloat; qryManutencaoDT_ALTERACAO.AsDateTime := pegarDataHoraServidor; qryManutencaoOPERADOR.AsString := sSnh_NmUsuario; qryManutencaoVLR_MERCADO.AsFloat := cdsItemNFevUnit.AsFloat; qryManutencaoKG_REAL.AsFloat := 0; qryManutencaoM3.AsFloat := 0; qryManutencaoLOTE.AsString := ''; qryManutencaoFLAG_MODULO.AsInteger := 0; qryManutencaoCOD_NCM.AsString := cdsItemNFeNCM.AsString; qryManutencaoCST_PIS.AsString := cdsItemNFePISCST.AsString; qryManutencaoCST_COFINS.AsString := cdsItemNFeCOFINSCST.AsString; qryManutencaoCST_IPI.AsString := cdsItemNFeIPICST.AsString; qryManutencaoALIQ_PIS.AsFloat := cdsItemNFePISpPIS.AsFloat; qryManutencaoALIQ_COFINS.AsFloat := cdsItemNFeCOFINSpCOFINS.AsFloat; qryManutencaoALIQ_IPI.AsFloat := cdsItemNFeIPIpIPI.AsFloat; qryManutencaoALIQ_ICMS.AsFloat := cdsItemNFeICMSpICMS.AsFloat; qryManutencaoALIQ_ICMS_ST.AsFloat := 0; qryManutencaoRED_BC_IPI.AsFloat := 0; qryManutencaoRED_BC_ICMS.AsFloat := 0; qryManutencao.Post; end; end; end; procedure TdmNFe.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add('SELECT * FROM STWARMTNFE'); SQL.Add('WHERE FIL_COBR = :FIL_COBR AND NOTA = :NOTA'); SQL.Add(' AND SERIE = :SERIE AND SITUACAO = :SITUACAO'); ParamByName('FIL_COBR').AsString := FEmissora; ParamByName('NOTA').AsFloat := FNota; ParamByName('SERIE').AsString := Copy(FSerie,1,2); ParamByName('SITUACAO').AsString := FSituacao; end; end; procedure TdmNFe.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add('SELECT * FROM STWARMTNFE'); end; end; end.
{---------------------------------------------------------------------------- esdsound.pas ESound non-visual component for Lazarus Written by Anthony Maro with help from Andrew Johnson NOTE: Included in gamepack for convenience, no credit to be taken from Tony. Initial Release November 14, 2002 THIS COMPONENT IS FREEWARE - USE AS YOU WILL TO FURTHER LINUX If you release sourcecode that uses this control, please credit me or leave this header intact. If you release a compiled application that uses this code, please credit me somewhere in a little bitty location so I can at least get bragging rights! This code 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. Component Use: Drop it on your form. (Duh!) At runtime, call the play method giving a filename (with full path) to play it. If you want to have instant access to the sounds (instead of the short delay the first time you play them) call the cachesample method as in: ESDSound1.CacheSample('/usr/share/sounds/mysound.wav','shortname'); Then you can play the cached sample with: ESDSound1.Play('shortname'); The shortname is CASE SENSITIVE! When the control is enabled it keeps an open connection to the esound sound server. Set it to disabled to close that connection and unload the esdlib library. Set it to enabled to reload the library and connect to the sound server ---------------------------------------------------------------------------} unit esdsound; {$mode objfpc}{$H+} interface uses Classes, SysUtils, {$IFDEF UNIX} + oldlinux, +{$ENDIF} + lresources; + +const + ESD_BUF_SIZE = 4 * 1024; + ESD_KEY_LEN = 16; + ESD_DEFAULT_PORT = 16001; + ESD_DEFAULT_RATE = 44100; + ESD_NAME_MAX = 128; + ESD_ENDIAN_KEY = (ord('E') shl 24) + (ord('N') shl 16) + (ord('D') shl 8) + (ord('N')); + ESD_MASK_BITS = $000F; + ESD_BITS8 = $0000; + ESD_BITS16 = $0001; + ESD_MASK_CHAN = $00F0; + ESD_MONO = $0010; + ESD_STEREO = $0020; + ESD_MASK_MODE = $0F00; + ESD_STREAM = $0000; + ESD_SAMPLE = $0100; + ESD_ADPCM = $0200; + ESD_MASK_FUNC = $F000; + ESD_PLAY = $1000; + ESD_MONITOR = $0000; + ESD_RECORD = $2000; + ESD_STOP = $0000; + ESD_LOOP = $2000; + +type + Tesd_proto = (ESD_PROTO_CONNECT,ESD_PROTO_LOCK,ESD_PROTO_UNLOCK, + ESD_PROTO_STREAM_PLAY,ESD_PROTO_STREAM_REC, + ESD_PROTO_STREAM_MON,ESD_PROTO_SAMPLE_CACHE, + ESD_PROTO_SAMPLE_FREE,ESD_PROTO_SAMPLE_PLAY, + ESD_PROTO_SAMPLE_LOOP,ESD_PROTO_SAMPLE_STOP, + ESD_PROTO_SAMPLE_KILL,ESD_PROTO_STANDBY, + ESD_PROTO_RESUME,ESD_PROTO_SAMPLE_GETID, + ESD_PROTO_STREAM_FILT,ESD_PROTO_SERVER_INFO, + ESD_PROTO_ALL_INFO,ESD_PROTO_SUBSCRIBE, + ESD_PROTO_UNSUBSCRIBE,ESD_PROTO_STREAM_PAN, + ESD_PROTO_SAMPLE_PAN,ESD_PROTO_STANDBY_MODE, + ESD_PROTO_LATENCY,ESD_PROTO_MAX); + +type + Pesd_format_t = ^Tesd_format_t; + Tesd_format_t = longint; + + Pesd_proto_t = ^Tesd_proto_t; + Tesd_proto_t = longint; + + Poctet = ^Toctet; + Toctet = byte; + + TSoundFile = class(TObject) + private + FFileName: String; + FHandle: Longint; + FName: String; + procedure SetFileName(const AValue: String); + procedure SetHandle(const AValue: Longint); + public + property FileName: String read FFileName write SetFileName; + property Name: String read FName write FName; + property Handle: Longint read FHandle write SetHandle; + end; + PSoundFile = ^TSoundFile; + + TESDSound = class(TComponent) + private + //functions from DLL's + esd_audio_open: function:Longint; cdecl; + esd_file_cache: function (esd:longint; name_prefix:Pchar; filename:Pchar):longint; cdecl; + esd_lock: function (esd:longint):longint; cdecl; + esd_unlock: function(esd:longint):longint; cdecl; + esd_audio_close: procedure; cdecl; + esd_sample_cache: function(esd:longint; format:Tesd_format_t; rate:longint; length:longint; name:Pchar):longint;cdecl; + esd_sample_play: function(esd:longint; sample:longint):longint;cdecl; + esd_open_sound: function(host:Pchar):longint;cdecl; + esd_sample_getid: function(esd:longint; name:Pchar):longint;cdecl; + esd_close: function(esd:longint):longint;cdecl; + + esdlib: Pointer; + FEnabled: Boolean; + FHandle: Longint; + SoundFiles: PSoundFile; // dunno about this one + NumSoundFiles: Integer; + procedure SetEnabled(const AValue: Boolean); + procedure SetHandle(const AValue: Longint); + function initsound: Boolean; +{$IFDEF UNIX} + function LoadLibrary(Aname: PChar): Pointer; + procedure CloseLibrary(AHandle: Pointer); + procedure LoadProcAddress(AHandle: Pointer; Aname: PChar; Address: Pointer); +{$ENDIF} + public + Constructor Create(AOwner: TComponent); override; + Destructor Destroy; override; + procedure Play(ASample: String); + property Handle: Longint read FHandle write SetHandle; + function CacheSample(ASample, AName: String): Boolean; + published + Property Enabled: Boolean read FEnabled write SetEnabled; + end; + +procedure Register; + +implementation + +{$IFDEF UNIX} + +{LINKLIB m} + +function dlopen(AFile: PChar; mode: LongInt): Pointer; cdecl; external 'dl'; +function dlclose(handle: Pointer): LongInt; cdecl; external 'dl'; +function dlsym(handle: Pointer; name:PChar): Pointer; cdecl; external 'dl'; + +{$ENDIF} + +{ TESDSound } + +{$IFDEF UNIX} + +function TESDSound.LoadLibrary(Aname: PChar): Pointer; +begin + {$ifdef debug} + if ShowDebug > 0 then writeln('TESDSound::LoadLibrary'); + {$endif} + try + Result := dlopen(Aname, 1); + except + end; +end; + +procedure TESDSound.CloseLibrary(AHandle: Pointer); +begin + {$ifdef debug} + if ShowDebug > 0 then writeln('TESDSound::CloseLibrary'); + {$endif} + + if assigned(AHandle) Then dlclose(AHandle); + +end; + +procedure TESDSound.LoadProcAddress(AHandle: Pointer; Aname: PChar; + Address: Pointer); +begin + PPointer(Address)^ := dlsym(Ahandle, AName); +end; + +{$ENDIF} + +function TESDSound.initsound: Boolean; +begin +{$IFDEF UNIX} + {$ifdef debug} + if ShowDebug > 0 then writeln('TESDSound::InitSound'); + {$endif} + // load the sound libraries, if possible + try + esdlib := LoadLibrary('libesd.so.0'); + if longint(esdlib) < 1 then esdlib := LoadLibrary('libesd.so'); // try this too + + if longint(esdlib) > 0 then begin + LoadProcAddress(esdlib, 'esd_audio_open', @esd_audio_open); + LoadProcAddress(esdlib, 'esd_file_cache', @esd_file_cache); + LoadProcAddress(esdlib, 'esd_lock', @esd_lock); + LoadProcAddress(esdlib, 'esd_unlock', @esd_unlock); + LoadProcAddress(esdlib, 'esd_audio_close', @esd_audio_close); + LoadProcAddress(esdlib, 'esd_audio_open', @esd_audio_open); + LoadProcAddress(esdlib, 'esd_sample_cache', @esd_sample_cache); + LoadProcAddress(esdlib, 'esd_sample_play', @esd_sample_play); + LoadProcAddress(esdlib, 'esd_open_sound', @esd_open_sound); + LoadProcAddress(esdlib, 'esd_sample_getid', @esd_sample_getid); + LoadProcAddress(esdlib, 'esd_close', @esd_close); + Result := True; + end else result := False; + except + Result := False; + end; +{$ENDIF} +end; + + +procedure TESDSound.SetEnabled(const AValue: Boolean); +begin +{$IFDEF UNIX} + {$ifdef debug} + if ShowDebug > 0 then writeln('TESDSound::SetEnabled'); + {$endif} + if FEnabled=AValue then exit; + if AValue = false then begin + FEnabled := AValue; + if not(csDesigning in componentstate) then begin + if handle > 0 then begin + //esd_audio_close; + esd_close(handle); + end; + closelibrary(esdlib); + end; // if not designing + exit; + end; + + if not(csDesigning in componentstate) then begin + InitSound; + handle := esd_open_sound(nil); + if handle > 0 then FEnabled := True; + FEnabled := True; + end else FEnabled := AValue; +{$ENDIF} +end; + +procedure TESDSound.SetHandle(const AValue: Longint); +begin + if FHandle=AValue then exit; + FHandle:=AValue; +end; + +constructor TESDSound.Create(AOwner: TComponent); +begin + {$ifdef debug} + if ShowDebug > 0 then writeln('TESDSound::Create'); + {$endif} + + Reallocmem(SoundFiles, 0); + NumSoundFiles := 0; + + inherited Create(AOwner); + +end; + + +destructor TESDSound.Destroy; +var + I: Integer; +begin +{$IFDEF UNIX} + {$ifdef debug} + if ShowDebug > 0 then writeln('TESDSound::Destroy'); + {$endif} + if handle > 0 then begin + esd_close(handle); + end; + closelibrary(esdlib); + if NumSoundFiles > 0 then begin + for I := 0 to NumSoundFiles-1 do begin SoundFiles[i].Free; end; end; {$ENDIF} ReallocMem(SoundFiles, 0); inherited Destroy; end; procedure TESDSound.Play(ASample: String); var I: Integer; begin {$IFDEF UNIX} if not(FEnabled) then begin // error raise exception.create('TESDSound:Play sample while disabled'); exit; end; if NumSoundFiles > 0 then begin for I := 0 to NumSoundFiles - 1 do begin // first look at the name if SoundFiles[I].Name = ASample then begin // found it! if SoundFiles[i].Handle > 0 then begin esd_sample_play(handle, SoundFiles[i].Handle); exit; end; end else if SoundFiles[i].FileName = ASample then begin // found it by filename! if SOundFiles[i].Handle > 0 then begin esd_sample_play(handle, SoundFiles[i].Handle); exit; end; end; // if found by filename end; end; // didn't find it so try caching it... if CacheSample(ASample, ASample) then begin // got it... try to play it... if NumSoundFiles > 0 then begin for I := 0 to NumSoundFiles - 1 do begin // first look at the name if SoundFiles[I].Name = ASample then begin // found it! if SoundFiles[i].Handle > 0 then begin esd_sample_play(handle, SoundFiles[i].Handle); exit; end; end else if SoundFiles[i].FileName = ASample then begin // found it by filename! if SOundFiles[i].Handle > 0 then begin esd_sample_play(handle, SoundFiles[i].Handle); exit; end; // if handle > 0 end; // if found by filename end; // for I end; // if numsoundfiles > 0 end; // oh well, I give up... just leave {$ENDIF} end; function TESDSound.CacheSample(ASample, AName: String): Boolean; var I: Integer; MySoundFile: TSoundFile; begin {$IFDEF UNIX} {$ifdef debug} if ShowDebug > 0 then writeln('TESDSound::CacheSample "'+ASample+'" as "'+AName+'"'); {$endif} if not(FEnabled) then begin // error raise exception.create('TESDSound:Cache sample while disabled'); exit; end; // see if it's already cached... if NumSoundFiles > 0 then begin for I := 0 to NumSoundFiles - 1 do begin if SoundFiles[I].Name = AName then begin // see if it's changing the file to use if SoundFiles[i].FileName = ASample then exit; // nope // change the file... // I don't know how to release the cache, so just cache the new one SoundFiles[i].Handle := esd_File_Cache(handle,'',PChar(ASample)); if SoundFiles[i].Handle < 1 then Result := False else Result := True; exit; end; // if found the name end; // loop I end; // if possibly cached... // not loaded, so cache it NumSoundFiles := NumSoundFiles + 1; ReallocMem(SoundFiles,sizeof(TSoundFile) * NumSoundFiles); MySoundFile := TSoundFile.Create; SoundFiles[NumSoundFiles-1] := MySoundFile; with MySoundFile do begin Name := AName; FileName := ASample; end; MySoundFile.Handle := esd_File_Cache(handle,'', pchar(ASample)); if MySoundFile.Handle < 1 then Result := False else Result := True; {$ENDIF} end; { TSoundFile } procedure TSoundFile.SetFileName(const AValue: String); begin if FFileName=AValue then exit; FFileName:=AValue; end; procedure TSoundFile.SetHandle(const AValue: Longint); begin if FHandle=AValue then exit; FHandle:=AValue; end; procedure Register; begin RegisterComponents('GamePack',[TESDSound]); end; initialization {$I esdsound.lrs} end.
unit LIB.Material; interface //#################################################################### ■ uses System.Classes, System.UITypes, System.Math.Vectors, System.Messaging, FMX.Graphics, FMX.Types3D, LUX, LUX.FMX.Material; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMyMaterial TMyMaterial = class( TLuxMaterial ) private protected _FMatrixMVP :TShaderVarMatrix3D; _FMatrixMV :TShaderVarMatrix3D; _TIMatrixMV :TShaderVarMatrix3D; _Light :TShaderVarLight; _EyePos :TShaderVarVector3D; _Opacity :TShaderVarSingle; _EmisLight :TShaderVarColorF; _AmbiLight :TShaderVarColorF; _DiffRatio :TShaderVarColorF; _SpecRatio :TShaderVarColorF; _SpecShiny :TShaderVarSingle; _ProjImage :TShaderVarTexture; _ProjMatrix :TShaderVarMatrix3D; _ProjAngleW :TShaderVarSingle; _ProjAngleH :TShaderVarSingle; ///// メソッド procedure DoApply( const Context_:TContext3D ); override; public constructor Create; override; destructor Destroy; override; ///// プロパティ property EmisLight :TShaderVarColorF read _EmisLight ; property AmbiLight :TShaderVarColorF read _AmbiLight ; property DiffRatio :TShaderVarColorF read _DiffRatio ; property SpecRatio :TShaderVarColorF read _SpecRatio ; property SpecShiny :TShaderVarSingle read _SpecShiny ; property ProjImage :TShaderVarTexture read _ProjImage ; property ProjMatrix :TShaderVarMatrix3D read _ProjMatrix; property ProjAngleW :TShaderVarSingle read _ProjAngleW; property ProjAngleH :TShaderVarSingle read _ProjAngleH; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMyMaterialSource TMyMaterialSource = class( TLuxMaterialSource<TMyMaterial> ) private _ContextResetId :Integer; ///// メソッド procedure ContextResetHandler( const Sender_:TObject; const Msg_:TMessage ); protected _ProjImage :TBitmap; ///// アクセス function GetEmisLight :TAlphaColorF; procedure SetEmisLight( const EmisLight_:TAlphaColorF ); function GetAmbiLight :TAlphaColorF; procedure SetAmbiLight( const AmbiLight_:TAlphaColorF ); function GetDiffRatio :TAlphaColorF; procedure SetDiffRatio( const DiffRatio_:TAlphaColorF ); function GetSpecRatio :TAlphaColorF; procedure SetSpecRatio( const SpecRatio_:TAlphaColorF ); function GetSpecShiny :Single; procedure SetSpecShiny( const SpecShiny_:Single ); procedure SetProjImage( const ProjImage_:TBitmap ); function GetProjMatrix :TMatrix3D; procedure SetProjMatrix( const ProjMatrix_:TMatrix3D ); function GetProjAngleW :Single; procedure SetProjAngleW( const ProjAngleW_:Single ); function GetProjAngleH :Single; procedure SetProjAngleH( const ProjAngleH_:Single ); ///// メソッド procedure DoProjImageChanged( Sender_:TObject ); public constructor Create( Owner_:TComponent ); override; destructor Destroy; override; ///// プロパティ property EmisLight :TAlphaColorF read GetEmisLight write SetEmisLight ; property AmbiLight :TAlphaColorF read GetAmbiLight write SetAmbiLight ; property DiffRatio :TAlphaColorF read GetDiffRatio write SetDiffRatio ; property SpecRatio :TAlphaColorF read GetSpecRatio write SetSpecRatio ; property SpecShiny :Single read GetSpecShiny write SetSpecShiny ; property ProjImage :TBitmap read _ProjImage write SetProjImage ; property ProjMatrix :TMatrix3D read GetProjMatrix write SetProjMatrix; property ProjAngleW :Single read GetProjAngleW write SetProjAngleW; property ProjAngleH :Single read GetProjAngleH write SetProjAngleH; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses System.SysUtils, System.Math; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMyMaterial //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TMyMaterial.DoApply( const Context_:TContext3D ); begin inherited; with Context_ do begin SetShaders( _ShaderV.Shader, _ShaderP.Shader ); _FMatrixMVP.Value := CurrentModelViewProjectionMatrix; _FMatrixMV .Value := CurrentMatrix; _TIMatrixMV.Value := CurrentMatrix.Inverse.Transpose; _Light .Value := Lights[ 0 ]; _EyePos .Value := CurrentCameraInvMatrix.M[ 3 ]; _Opacity .Value := CurrentOpacity; end; _ShaderV.SendVars( Context_ ); _ShaderP.SendVars( Context_ ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TMyMaterial.Create; begin inherited; _FMatrixMVP := TShaderVarMatrix3D.Create( '_FMatrixMVP' ); _FMatrixMV := TShaderVarMatrix3D.Create( '_FMatrixMV' ); _TIMatrixMV := TShaderVarMatrix3D.Create( '_IMatrixMV' ); _Light := TShaderVarLight .Create( '_Light' ); _EyePos := TShaderVarVector3D.Create( '_EyePos' ); _Opacity := TShaderVarSingle .Create( '_Opacity' ); _EmisLight := TShaderVarColorF .Create( '_EmisLight' ); _AmbiLight := TShaderVarColorF .Create( '_AmbiLight' ); _DiffRatio := TShaderVarColorF .Create( '_DiffRatio' ); _SpecRatio := TShaderVarColorF .Create( '_SpecRatio' ); _SpecShiny := TShaderVarSingle .Create( '_SpecShiny' ); _ProjImage := TShaderVarTexture .Create( '_ProjImage' ); _ProjMatrix := TShaderVarMatrix3D.Create( '_ProjMatrix' ); _ProjAngleW := TShaderVarSingle .Create( '_ProjAngleW' ); _ProjAngleH := TShaderVarSingle .Create( '_ProjAngleH' ); _ShaderV.Vars := [ _FMatrixMVP, _FMatrixMV , _TIMatrixMV ]; _ShaderP.Vars := [ _FMatrixMVP, _FMatrixMV , _TIMatrixMV, _Light , _EyePos , _Opacity , _EmisLight , _AmbiLight , _DiffRatio , _SpecRatio , _SpecShiny , _ProjImage , _ProjMatrix, _ProjAngleW, _ProjAngleH ]; _EmisLight .Value := TAlphaColorF.Create( 0, 0, 0 ); _AmbiLight .Value := TAlphaColorF.Create( 0.1, 0.1, 0.1 ); _DiffRatio .Value := TAlphaColorF.Create( 1, 1, 1 ); _SpecRatio .Value := TAlphaColorF.Create( 1, 1, 1 ); _SpecShiny .Value := 50; _ProjAngleW.Value := DegToRad( 20 ); _ProjAngleH.Value := DegToRad( 20 ); end; destructor TMyMaterial.Destroy; begin _FMatrixMVP.Free; _FMatrixMV .Free; _TIMatrixMV.Free; _Light .Free; _EyePos .Free; _Opacity .Free; _EmisLight .Free; _AmbiLight .Free; _DiffRatio .Free; _SpecRatio .Free; _SpecShiny .Free; _ProjImage .Free; _ProjMatrix.Free; _ProjAngleW.Free; _ProjAngleH.Free; inherited; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMyMaterialSource //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private /////////////////////////////////////////////////////////////////////// メソッド procedure TMyMaterialSource.ContextResetHandler( const Sender_:TObject; const Msg_:TMessage ); begin DoProjImageChanged( Self ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TMyMaterialSource.GetEmisLight :TAlphaColorF; begin Result := _Material.EmisLight.Value; end; procedure TMyMaterialSource.SetEmisLight( const EmisLight_:TAlphaColorF ); begin _Material.EmisLight.Value := EmisLight_; end; function TMyMaterialSource.GetAmbiLight :TAlphaColorF; begin Result := _Material.AmbiLight.Value; end; procedure TMyMaterialSource.SetAmbiLight( const AmbiLight_:TAlphaColorF ); begin _Material.AmbiLight.Value := AmbiLight_; end; function TMyMaterialSource.GetDiffRatio: TAlphaColorF; begin Result := _Material.DiffRatio.Value; end; procedure TMyMaterialSource.SetDiffRatio( const DiffRatio_:TAlphaColorF ); begin _Material.DiffRatio.Value := DiffRatio_; end; function TMyMaterialSource.GetSpecRatio :TAlphaColorF; begin Result := _Material.SpecRatio.Value; end; procedure TMyMaterialSource.SetSpecRatio( const SpecRatio_:TAlphaColorF ); begin _Material.SpecRatio.Value := SpecRatio_; end; function TMyMaterialSource.GetSpecShiny :Single; begin Result := _Material.SpecShiny.Value; end; procedure TMyMaterialSource.SetSpecShiny( const SpecShiny_:Single ); begin _Material.SpecShiny.Value := SpecShiny_; end; procedure TMyMaterialSource.SetProjImage( const ProjImage_:TBitmap ); begin _ProjImage.Assign( ProjImage_ ); end; function TMyMaterialSource.GetProjMatrix :TMatrix3D; begin Result := _Material.ProjMatrix.Value; end; procedure TMyMaterialSource.SetProjMatrix( const ProjMatrix_:TMatrix3D ); begin _Material.ProjMatrix.Value := ProjMatrix_; end; function TMyMaterialSource.GetProjAngleW :Single; begin Result := _Material.ProjAngleW.Value; end; procedure TMyMaterialSource.SetProjAngleW( const ProjAngleW_:Single ); begin _Material.ProjAngleW.Value := ProjAngleW_; end; function TMyMaterialSource.GetProjAngleH :Single; begin Result := _Material.ProjAngleH.Value; end; procedure TMyMaterialSource.SetProjAngleH( const ProjAngleH_:Single ); begin _Material.ProjAngleH.Value := ProjAngleH_; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TMyMaterialSource.DoProjImageChanged( Sender_:TObject ); begin if not _ProjImage.IsEmpty then _Material.ProjImage.Value := TTextureBitmap( _ProjImage ).Texture; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TMyMaterialSource.Create( Owner_:TComponent ); begin inherited; _ContextResetId := TMessageManager.DefaultManager.SubscribeToMessage( TContextResetMessage, ContextResetHandler ); _ProjImage := TTextureBitmap.Create; _ProjImage.OnChange := DoProjImageChanged; end; destructor TMyMaterialSource.Destroy; begin FreeAndNil( _ProjImage ); TMessageManager.DefaultManager.Unsubscribe( TContextResetMessage, _ContextResetId ); inherited; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //######################################################## 初期化 finalization //########################################################## 最終化 end. //######################################################################### ■
unit HideForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) procedure Button1Click(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure FormCreate(Sender: TObject); private Button1: TButton; Edit1: TEdit; ListBox1: TListBox; end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); begin ListBox1.Items.Add (Edit1.Text); end; procedure TForm1.Edit1Change(Sender: TObject); begin Button1.Enabled := Length (Edit1.Text) <> 0; end; procedure TForm1.FormCreate(Sender: TObject); begin Button1 := FindComponent ('Button1') as TButton; Edit1 := FindComponent ('Edit1') as TEdit; ListBox1 := FindComponent ('ListBox1') as TListBox; end; initialization RegisterClasses ([TButton, TEdit, TListBox]); end.
program BINTREEDEMO; type Tree = ^TreeNode; TreeNode = record weight : integer; count : integer; left : Tree; right : Tree end; var root : Tree; var tn : Tree; var gw, trh : integer; procedure MkTreeNode(w : integer; var t : Tree); var pp : Tree; begin new(pp); with pp^ do begin weight := w; count := 1; left := nil; right := nil end; t := pp end; (* insert new node n to the binary search tree specified by t. *) procedure InsertNode(n : Tree; var t : Tree); var tw : integer; begin if t <> nil then begin tw := t^.weight; if tw = n^.weight then begin inc(t^.count); dispose(n) end else if tw > n^.weight then InsertNode(n, t^.left) else InsertNode(n, t^.right); end else t := n; end; function TreeHeight(rt : Tree) : integer; var lh, rh, hh : integer; begin if rt = nil then hh := 0 else begin lh := TreeHeight(rt^.left); rh := TreeHeight(rt^.right); if lh >= rh then hh := 1 + lh else hh := 1 + rh end; TreeHeight := hh end; procedure PrintTree(indent : string; l : integer; t : Tree); begin if t <> nil then begin writeln(indent, 'weight: ', t^.weight, ' count: ', t^.count, ' @ line: ', l); PrintTree(indent, l+1, t^.left); PrintTree(indent + indent, l+1, t^.right) end end; begin root := nil; tn := nil; gw := 4; MkTreeNode(gw, tn); InsertNode(tn, root); gw := 2; MkTreeNode(gw, tn); InsertNode(tn, root); gw := 3; MkTreeNode(gw, tn); InsertNode(tn, root); gw := 5; MkTreeNode(gw, tn); InsertNode(tn, root); gw := 2; MkTreeNode(gw, tn); InsertNode(tn, root); PrintTree(' ', 1, root); trh := TreeHeight(root); writeln('height of the tree: ', trh) end.
unit DataDriverPing; interface uses Classes, SysUtils, XSuperObject, GlobalTypes, IdHTTP, IdGlobal, IdMultipartFormData, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL; type TPinger = class(TThread) public HTTPClient: TIdHTTP; IdSSLIOHandlerSocketOpenSSL1: TIdSSLIOHandlerSocketOpenSSL; SSL: boolean; Packet: ISuperObject; PingResult : Boolean; DataVers: integer; constructor Create(Item: ISuperObject); procedure Execute; override; function RequestToServer: ISuperObject; procedure OnStopWork(Sender: TObject); end; implementation uses Constants, Service, ClientUnit; constructor TPinger.Create(Item: ISuperObject); begin inherited Create(False); FreeOnTerminate := True; Packet := Item.Clone; OnTerminate := OnStopWork; PingResult := False; HTTPClient := TIdHTTP.Create(nil); IdSSLIOHandlerSocketOpenSSL1 := TIdSSLIOHandlerSocketOpenSSL.Create(nil); HTTPClient.IOHandler := IdSSLIOHandlerSocketOpenSSL1; HTTPClient.Request.Accept := 'json'; HTTPClient.Request.AcceptCharSet := 'utf-8'; HTTPClient.Request.CharSet := 'utf-8'; HTTPClient.Request.ContentType := 'application/json'; end; procedure TPinger.Execute; var Resp: ISuperObject; begin Resp := RequestToServer; if Resp <> nil then begin if Resp.S[KEY_MES_TYPE] = MESSAGE_ERROR then PingResult := False; end; end; function TPinger.RequestToServer: ISuperObject; var ToSend, ToRead : TStringStream; Dest: string; TX, RX: string; i: integer; begin Result := nil; DataVers := 1; ToRead := TStringStream.Create; Packet.I[KEY_DEV_ID] := MCore.ID; Packet.I[KEY_DEV_CLASS] := MCore.DevClass; Packet.I[KEY_CLIENT_TYPE] := MCore.DevClass; Packet.S['dev_uid'] := MCore.ServerUID; Packet.S[KEY_DEST_UID] := DataServer.DevUID; TX := Packet.AsJSON; ToSend := TStringStream.Create(TX, TEncoding.UTF8); Dest := DataServer.Host + ':' + IntToStr(DataServer.Port); if SSL then Dest := 'https://' + Dest else Dest := 'http://' + Dest; try HTTPClient.Post(Dest, ToSend, ToRead); RX := ToRead.DataString; if RX = '' then begin Result := nil; end else begin Result := SO(RX); DataVers := Result.I[KEY_DATAVERS]; PingResult := True; end; except PingResult := False; end; ToSend.Free; ToRead.Free; HTTPClient.Free; end; procedure TPinger.OnStopWork(Sender: TObject); begin DataServer.OnWork := PingResult; if DataVers = 0 then DataServer.DataVersion := 0; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerOctetStringParser; {$I ..\Include\CryptoLib.inc} interface uses Classes, ClpStreams, ClpCryptoLibTypes, ClpBerOctetString, ClpConstructedOctetStream, ClpIAsn1StreamParser, ClpIProxiedInterface, ClpIBerOctetStringParser, ClpIAsn1OctetStringParser; resourcestring SConvertError = 'EIOCryptoLibException Converting Stream to Byte Array: %s'; type TBerOctetStringParser = class(TInterfacedObject, IAsn1OctetStringParser, IAsn1Convertible, IBerOctetStringParser) strict private var F_parser: IAsn1StreamParser; public constructor Create(const parser: IAsn1StreamParser); function GetOctetStream(): TStream; inline; function ToAsn1Object(): IAsn1Object; end; implementation { TBerOctetStringParser } constructor TBerOctetStringParser.Create(const parser: IAsn1StreamParser); begin Inherited Create(); F_parser := parser; end; function TBerOctetStringParser.GetOctetStream: TStream; begin result := TConstructedOctetStream.Create(F_parser); end; function TBerOctetStringParser.ToAsn1Object: IAsn1Object; var LStream: TStream; begin try LStream := GetOctetStream(); try result := TBerOctetString.Create(TStreams.ReadAll(LStream)); finally LStream.Free; end; except on e: EIOCryptoLibException do begin raise EAsn1ParsingCryptoLibException.CreateResFmt(@SConvertError, [e.Message]); end; end; end; end.
unit UCTRLSyncronization; {$mode delphi} { Copyright (c) 2018 by Herman Schoenfeld Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. Acknowledgements: - Albert Molina: portions of code copied from https://github.com/PascalCoin/PascalCoin/blob/master/Units/Forms/UFRMWallet.pas } interface {$I ..\config.inc} uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ComCtrls, UCommon.UI; type { TCTRLSyncronization } TCTRLSyncronization = class(TApplicationForm) btnOpenWallet: TButton; Label16: TLabel; Label4: TLabel; lblCurrentDifficultyCaption2: TLabel; lblNetProtocolVersion: TLabel; lblTotalAccountsLabel: TLabel; Label8: TLabel; lblBlocksFound: TLabel; lblTotalAccountsValue: TLabel; lblTotalBlocksValue: TLabel; lblTotalBlocksLabel: TLabel; lblBlockAgeValue: TLabel; lblBlockAgeLabel: TLabel; lblBlockTargetValue: TLabel; lblProtocolVersion: TLabel; lblBlockTargetLabel: TLabel; lblCurrentDifficultyCaption1: TLabel; lblMinersClientsValue: TLabel; lblMiningStatusCaption: TLabel; lblNodeStatus: TLabel; lblPendingOperationsValue: TLabel; lblPendingOperationsLabel: TLabel; lblReceivedMessages: TLabel; lblTimeAverage: TLabel; lblTimeAverageAux: TLabel; procedure btnOpenWalletClick(Sender:TObject); procedure lblReceivedMessagesClick(Sender:TObject); private { private declarations } FMinedBlocksCount: Integer; public { public declarations } procedure UpdateNodeStatus; procedure UpdateBlockChainState; procedure SetMinedBlocksCount(const Value: Integer); procedure OnFinishedLoadingDatabase; Property MinedBlocksCount : Integer read FMinedBlocksCount write SetMinedBlocksCount; end; implementation {$R *.lfm} uses UNetProtocol,UTime,UConst, UUserInterface; {%region Methods} procedure TCTRLSyncronization.UpdateNodeStatus; Var status : AnsiString; begin if not TUserInterface.Started then exit; If Not Assigned(TUserInterface.Node) then begin lblNodeStatus.Font.Color := clRed; lblNodeStatus.Caption := 'Initializing...'; end else begin If TUserInterface.Node.IsReady(status) then begin if TNetData.NetData.NetStatistics.ActiveConnections>0 then begin lblNodeStatus.Font.Color := clGreen; if TNetData.NetData.IsDiscoveringServers then begin lblNodeStatus.Caption := 'Discovering servers'; end else if TNetData.NetData.IsGettingNewBlockChainFromClient then begin lblNodeStatus.Caption := 'Obtaining new blockchain'; end else begin lblNodeStatus.Caption := 'Running'; end; end else begin lblNodeStatus.Font.Color := clRed; lblNodeStatus.Caption := 'Alone in the world...'; end; end else begin lblNodeStatus.Font.Color := clRed; lblNodeStatus.Caption := status; end; end; lblProtocolVersion.Caption := Format('%d (%d)', [TUserInterface.Node.Bank.SafeBox.CurrentProtocol,CT_BlockChain_Protocol_Available]); lblNetProtocolVersion.Caption := Format('%d (%d)', [CT_NetProtocol_Version, CT_NetProtocol_Available]); if NOT btnOpenWallet.Enabled then begin lblNodeStatus.Caption := 'Please wait until finished - ' + lblNodeStatus.Caption; end; end; procedure TCTRLSyncronization.UpdateBlockChainState; Var f, favg : real; begin if not TUserInterface.Started then exit; UpdateNodeStatus; if Assigned(TUserInterface.Node) then begin if TUserInterface.Node.Bank.BlocksCount>0 then begin lblTotalBlocksValue.Caption := Inttostr(TUserInterface.Node.Bank.BlocksCount)+' (0..'+Inttostr(TUserInterface.Node.Bank.BlocksCount-1)+')'; ; end else lblTotalBlocksValue.Caption := '(none)'; lblTotalAccountsValue.Caption := Inttostr(TUserInterface.Node.Bank.AccountsCount); lblBlockAgeValue.Caption := UnixTimeToLocalElapsedTime(TUserInterface.Node.Bank.LastOperationBlock.timestamp); lblPendingOperationsValue.Caption := Inttostr(TUserInterface.Node.Operations.Count); lblBlockTargetValue.Caption := InttoHex(TUserInterface.Node.Operations.OperationBlock.compact_target,8); favg := TUserInterface.Node.Bank.GetActualTargetSecondsAverage(CT_CalcNewTargetBlocksAverage); f := (CT_NewLineSecondsAvg - favg) / CT_NewLineSecondsAvg; lblTimeAverage.Caption := 'Last '+Inttostr(CT_CalcNewTargetBlocksAverage)+': '+FormatFloat('0.0',favg)+' sec. (Optimal '+Inttostr(CT_NewLineSecondsAvg)+'s) Deviation '+FormatFloat('0.00%',f*100); if favg>=CT_NewLineSecondsAvg then begin lblTimeAverage.Font.Color := clNavy; end else begin lblTimeAverage.Font.Color := clOlive; end; lblTimeAverageAux.Caption := Format('Last %d: %s sec. - %d: %s sec. - %d: %s sec. - %d: %s sec. - %d: %s sec.',[ CT_CalcNewTargetBlocksAverage * 2 ,FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage(CT_CalcNewTargetBlocksAverage * 2)), ((CT_CalcNewTargetBlocksAverage * 3) DIV 2) ,FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage((CT_CalcNewTargetBlocksAverage * 3) DIV 2)), ((CT_CalcNewTargetBlocksAverage DIV 4)*3),FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage(((CT_CalcNewTargetBlocksAverage DIV 4)*3))), CT_CalcNewTargetBlocksAverage DIV 2,FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage(CT_CalcNewTargetBlocksAverage DIV 2)), CT_CalcNewTargetBlocksAverage DIV 4,FormatFloat('0.0',TUserInterface.Node.Bank.GetActualTargetSecondsAverage(CT_CalcNewTargetBlocksAverage DIV 4))]); end else begin lblTotalBlocksValue.Caption := ''; lblTotalAccountsValue.Caption := ''; lblBlockAgeValue.Caption := ''; lblPendingOperationsValue.Caption := ''; lblBlockTargetValue.Caption := ''; lblTimeAverage.Caption := ''; lblTimeAverageAux.Caption := ''; end; if (Assigned(TUserInterface.PoolMiningServer)) And (TUserInterface.PoolMiningServer.Active) then begin If TUserInterface.PoolMiningServer.ClientsCount>0 then begin lblMinersClientsValue.Caption := IntToStr(TUserInterface.PoolMiningServer.ClientsCount)+' connected JSON-RPC clients'; lblMinersClientsValue.Font.Color := clNavy; end else begin lblMinersClientsValue.Caption := 'No JSON-RPC clients'; lblMinersClientsValue.Font.Color := clDkGray; end; MinedBlocksCount := TUserInterface.PoolMiningServer.ClientsWins; end else begin MinedBlocksCount := 0; lblMinersClientsValue.Caption := 'JSON-RPC server not active'; lblMinersClientsValue.Font.Color := clRed; end; end; procedure TCTRLSyncronization.SetMinedBlocksCount(const Value: Integer); begin FMinedBlocksCount := Value; lblBlocksFound.Caption := Inttostr(Value); if Value>0 then lblBlocksFound.Font.Color := clGreen else lblBlocksFound.Font.Color := clDkGray; end; procedure TCTRLSyncronization.OnFinishedLoadingDatabase; begin btnOpenWallet.Enabled:=true; TUserInterface.ShowWallet; end; {%endregion} {%region Handlers: widgets } procedure TCTRLSyncronization.lblReceivedMessagesClick(Sender:TObject); begin TUserInterface.ShowMessagesForm; end; procedure TCTRLSyncronization.btnOpenWalletClick(Sender:TObject); begin TUserInterface.ShowWallet; end; {%endregion} end.
unit Solid.Samples.DIP.Books.Step1; interface uses System.IOUtils; type { TPdfBook } TPdfBook = class private FPath: string; public constructor Create(const APath: string); function Read: TArray<Byte>; end; { TPdfBookReader } TPdfBookReader = class private FBook: TPdfBook; public constructor Create(ABook: TPdfBook); procedure Display; end; implementation { TPdfBook } constructor TPdfBook.Create(const APath: string); begin inherited Create; FPath := APath; end; function TPdfBook.Read: TArray<Byte>; begin Result := TFile.ReadAllBytes(FPath); end; { TPdfBookReader } constructor TPdfBookReader.Create(ABook: TPdfBook); begin inherited Create; FBook := ABook; end; procedure TPdfBookReader.Display; var LData: TArray<Byte>; begin LData := FBook.Read; // TODO end; end.
unit mebdd_worker_groups; (* Taken from http://stackoverflow.com/questions/8288525/how-to-get-windows-user-privileges-information-with-lazarus-free-pascal *) {$MODE OBJFPC} interface uses Windows; const SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)); SECURITY_BUILTIN_DOMAIN_RID = $00000020; DOMAIN_ALIAS_RID_ADMINS = $00000220; DOMAIN_ALIAS_RID_USERS = $00000221; DOMAIN_ALIAS_RID_GUESTS = $00000222; DOMAIN_ALIAS_RID_POWER_USERS= $00000223; function UserInGroup(Group :DWORD) : Boolean; implementation uses SysUtils, Classes; function CheckTokenMembership(TokenHandle: THandle; SidToCheck: PSID; var IsMember: BOOL): BOOL; stdcall; external advapi32; function UserInGroup(Group :DWORD) : Boolean; var pIdentifierAuthority :TSIDIdentifierAuthority; pSid : Windows.PSID; IsMember : BOOL; begin pIdentifierAuthority := SECURITY_NT_AUTHORITY; Result := AllocateAndInitializeSid(pIdentifierAuthority,2, SECURITY_BUILTIN_DOMAIN_RID, Group, 0, 0, 0, 0, 0, 0, pSid); try if Result then if not CheckTokenMembership(0, pSid, IsMember) then //passing 0 means which the function will be use the token of the calling thread. Result:= False else Result:=IsMember; finally FreeSid(pSid); end; end; end.
{*******************************************************} { } { Delphi Runtime Library } { } { Copyright(c) 1995-2015 Embarcadero Technologies, Inc. } { } {*******************************************************} unit np.NetEncoding; {$Z1} interface uses Classes, SysUtils; type TNetEncoding = class private class var FBase64Encoding: TNetEncoding; FHTMLEncoding: TNetEncoding; FURLEncoding: TNetEncoding; class function GetBase64Encoding: TNetEncoding; static; class function GetHTMLEncoding: TNetEncoding; static; class function GetURLEncoding: TNetEncoding; static; // class destructor Destroy; protected function DoDecode(const Input, Output: TStream): Integer; overload; virtual; function DoDecode(const Input: TBytes): TBytes; overload; virtual; function DoDecode(const Input: string): string; overload; virtual; abstract; function DoEncode(const Input, Output: TStream): Integer; overload; virtual; function DoEncode(const Input: TBytes): TBytes; overload; virtual; function DoEncode(const Input: string): string; overload; virtual; abstract; function DoDecodeStringToBytes(const Input: string): TBytes; virtual; function DoEncodeBytesToString(const Input: TBytes): string; overload; virtual; function DoEncodeBytesToString(const Input: Pointer; Size: Integer): string; overload; virtual; public function Decode(const Input, Output: TStream): Integer; overload; function Decode(const Input: TBytes): TBytes; overload; function Decode(const Input: string): string; overload; function Encode(const Input, Output: TStream): Integer; overload; function Encode(const Input: TBytes): TBytes; overload; function Encode(const Input: string): string; overload; function DecodeStringToBytes(const Input: string): TBytes; function EncodeBytesToString(const Input: TBytes): string; overload; function EncodeBytesToString(const Input: Pointer; Size: Integer): string; overload; class property Base64: TNetEncoding read GetBase64Encoding; class property HTML: TNetEncoding read GetHTMLEncoding; class property URL: TNetEncoding read GetURLEncoding; end; TBase64Encoding = class(TNetEncoding) protected const kCharsPerLine = 76; DecodeTable: array[0..79] of Int8 = ( 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51); EncodeTable: array[0..63] of Byte = ( Ord('A'),Ord('B'),Ord('C'),Ord('D'),Ord('E'),Ord('F'),Ord('G'),Ord('H'),Ord('I'),Ord('J'),Ord('K'),Ord('L'),Ord('M'), Ord('N'),Ord('O'),Ord('P'),Ord('Q'),Ord('R'),Ord('S'),Ord('T'),Ord('U'),Ord('V'),Ord('W'),Ord('X'),Ord('Y'),Ord('Z'), Ord('a'),Ord('b'),Ord('c'),Ord('d'),Ord('e'),Ord('f'),Ord('g'),Ord('h'),Ord('i'),Ord('j'),Ord('k'),Ord('l'),Ord('m'), Ord('n'),Ord('o'),Ord('p'),Ord('q'),Ord('r'),Ord('s'),Ord('t'),Ord('u'),Ord('v'),Ord('w'),Ord('x'),Ord('y'),Ord('z'), Ord('0'),Ord('1'),Ord('2'),Ord('3'),Ord('4'),Ord('5'),Ord('6'),Ord('7'),Ord('8'),Ord('9'),Ord('+'),Ord('/')); type TEncodeStep = (EncodeStepA, EncodeStepB, EncodeStepC); TDecodeStep = (DecodeStepA, DecodeStepB, DecodeStepC, DecodeStepD); TEncodeState = record Step: TEncodeStep; Result: Byte; StepCount: Integer; end; TDecodeState = record Step: TDecodeStep; Result: Byte; end; protected FCharsPerline: Integer; FLineSeparator: string; procedure InitEncodeState(var State: TEncodeState); procedure InitDecodeState(var State: TDecodeState); function EstimateEncodeLength(const InputLength: UInt64): UInt64; function EstimateDecodeLength(const InputLength: UInt64): UInt64; function DecodeValue(const Code: Byte): Integer; inline; function EncodeValue(const Code: Integer): Byte; inline; function EncodeBytes(Input, Output: PByte; InputLen: Integer; CharSize: SmallInt; LineSeparator: array of Byte; var State: TEncodeState): Integer; function EncodeBytesEnd(Output: PByte; CharSize: SmallInt; var State: TEncodeState): Integer; function DecodeBytes(Input, Output: PByte; InputLen: Integer; CharSize: SmallInt; var State: TDecodeState): Integer; function DoDecode(const Input, Output: TStream): Integer; override; function DoDecode(const Input: TBytes): TBytes; overload; override; function DoDecode(const Input: string): string; overload; override; function DoEncode(const Input, Output: TStream): Integer; override; function DoEncode(const Input: TBytes): TBytes; overload; override; function DoEncode(const Input: string): string; overload; override; function DoDecodeStringToBytes(const Input: string): TBytes; override; function DoEncodeBytesToString(const Input: TBytes): string; overload; override; function DoEncodeBytesToString(const Input: Pointer; Size: Integer): string; overload; override; public constructor Create; overload; virtual; constructor Create(CharsPerLine: Integer); overload; virtual; constructor Create(CharsPerLine: Integer; LineSeparator: string); overload; virtual; end; TURLEncoding = class(TNetEncoding) protected function DoDecode(const Input: string): string; overload; override; function DoEncode(const Input: string): string; overload; override; end; THTMLEncoding = class(TNetEncoding) protected function DoDecode(const Input: string): string; overload; override; function DoEncode(const Input: string): string; overload; override; end; EHTTPException = class(Exception) end; implementation uses {$IFDEF MSWINDOWS} WinApi.Windows, {$ENDIF} RTLConsts; type TPointerStream = class(TCustomMemoryStream) public constructor Create(P: Pointer; Size: Integer); function Write(const Buffer; Count: LongInt): LongInt; override; end; { TNetEncoding } function TNetEncoding.DoDecode(const Input: TBytes): TBytes; begin if Length(Input) > 0 then Result := TEncoding.UTF8.GetBytes(DoDecode(TEncoding.UTF8.GetString(Input))) else SetLength(Result, 0); end; function TNetEncoding.DoDecode(const Input, Output: TStream): Integer; var InBuf: TBytes; OutBuf: TBytes; begin if Input.Size > 0 then begin SetLength(InBuf, Input.Size); Input.Read(InBuf[0], Input.Size); OutBuf := DoDecode(InBuf); Result := Length(OutBuf); Output.Write(OutBuf, Result); SetLength(InBuf, 0); end else Result := 0; end; function TNetEncoding.DoDecodeStringToBytes(const Input: string): TBytes; begin Result := TEncoding.UTF8.GetBytes(DoDecode(Input)); end; function TNetEncoding.Decode(const Input: TBytes): TBytes; begin Result := DoDecode(Input); end; function TNetEncoding.Decode(const Input, Output: TStream): Integer; begin Result := DoDecode(Input, Output); end; function TNetEncoding.Decode(const Input: string): string; begin Result := DoDecode(Input); end; function TNetEncoding.DecodeStringToBytes(const Input: string): TBytes; begin Result := DoDecodeStringToBytes(Input); end; //class destructor TNetEncoding.Destroy; //begin // FreeAndNil(FBase64Encoding); // FreeAndNil(FHTMLEncoding); // FreeAndNil(FURLEncoding); //end; function TNetEncoding.DoEncode(const Input: TBytes): TBytes; begin if Length(Input) > 0 then Result := TEncoding.UTF8.GetBytes(DoEncode(TEncoding.UTF8.GetString(Input))) else SetLength(Result, 0); end; function TNetEncoding.DoEncodeBytesToString(const Input: TBytes): string; begin Result := TEncoding.UTF8.GetString(DoEncode(Input)); end; function TNetEncoding.Encode(const Input: TBytes): TBytes; begin Result := DoEncode(Input); end; function TNetEncoding.Encode(const Input, Output: TStream): Integer; begin Result := DoEncode(Input, Output); end; function TNetEncoding.Encode(const Input: string): string; begin Result := DoEncode(Input); end; function TNetEncoding.EncodeBytesToString(const Input: TBytes): string; begin Result := DoEncodeBytesToString(Input); end; function TNetEncoding.EncodeBytesToString(const Input: Pointer; Size: Integer): string; begin Result := DoEncodeBytesToString(Input, Size); end; function TNetEncoding.DoEncodeBytesToString(const Input: Pointer; Size: Integer): string; var InStr: TPointerStream; OutStr: TBytesStream; begin InStr := TPointerStream.Create(Input, Size); try OutStr := TBytesStream.Create; try Encode(InStr, OutStr); SetString(Result, PChar(OutStr.Memory), OutStr.Size); finally OutStr.Free; end; finally InStr.Free; end; end; function TNetEncoding.DoEncode(const Input, Output: TStream): Integer; var InBuf: TBytes; OutBuf: TBytes; begin if Input.Size > 0 then begin SetLength(InBuf, Input.Size); Input.Read(InBuf[0], Input.Size); OutBuf := DoEncode(InBuf); Result := Length(OutBuf); Output.Write(OutBuf, Result); SetLength(InBuf, 0); end else Result := 0; end; class function TNetEncoding.GetBase64Encoding: TNetEncoding; var LEncoding: TBase64Encoding; begin if FBase64Encoding = nil then begin LEncoding := TBase64Encoding.Create; // if InterlockedCompareExchangePointer(Pointer(FBase64Encoding), Pointer(LEncoding), nil) <> nil then if AtomicCmpExchange(Pointer(FBase64Encoding), Pointer(LEncoding), nil) <> nil then LEncoding.Free; {$IFDEF AUTOREFCOUNT} FBase64Encoding.__ObjAddRef; {$ENDIF AUTOREFCOUNT} end; Result := FBase64Encoding; end; class function TNetEncoding.GetHTMLEncoding: TNetEncoding; var LEncoding: THTMLEncoding; begin if FHTMLEncoding = nil then begin LEncoding := THTMLEncoding.Create; if AtomicCmpExchange(Pointer(FHTMLEncoding), Pointer(LEncoding), nil) <> nil then LEncoding.Free; {$IFDEF AUTOREFCOUNT} FHTMLEncoding.__ObjAddRef; {$ENDIF AUTOREFCOUNT} end; Result := FHTMLEncoding; end; class function TNetEncoding.GetURLEncoding: TNetEncoding; var LEncoding: TURLEncoding; begin if FURLEncoding = nil then begin LEncoding := TURLEncoding.Create; if AtomicCmpExchange(Pointer(FURLEncoding), Pointer(LEncoding), nil) <> nil then LEncoding.Free; {$IFDEF AUTOREFCOUNT} FURLEncoding.__ObjAddRef; {$ENDIF AUTOREFCOUNT} end; Result := FURLEncoding; end; { TBase64Encoding } function TBase64Encoding.DecodeValue(const Code: Byte): Integer; var LCode: Integer; begin LCode := Code - 43; if (LCode < 0) or (LCode > 80) then Result := -1 else Result := DecodeTable[LCode]; end; function TBase64Encoding.EncodeValue(const Code: Integer): Byte; begin Result := EncodeTable[Code]; end; function TBase64Encoding.EstimateDecodeLength(const InputLength: UInt64): UInt64; begin Result := InputLength div 4 * 3 + 4; end; function TBase64Encoding.EstimateEncodeLength(const InputLength: UInt64): UInt64; begin Result := InputLength div 3 * 4 + 4; if FCharsPerLine > 0 then Result := Result + Result div FCharsPerLine * Length(FLineSeparator); end; function TBase64Encoding.DoDecode(const Input: TBytes): TBytes; const CharSize = SizeOf(Byte); var Len: Integer; State: TDecodeState; begin if Length(Input) > 0 then begin SetLength(Result, EstimateDecodeLength(Length(Input))); InitDecodeState(State); Len := DecodeBytes(@Input[0], PByte(Result), Length(Input) * CharSize, CharSize, State); SetLength(Result, Len); end else SetLength(Result, 0) end; constructor TBase64Encoding.Create; begin Create(kCharsPerLine, sLineBreak); end; constructor TBase64Encoding.Create(CharsPerLine: Integer); begin Create(CharsPerLine, sLineBreak); end; constructor TBase64Encoding.Create(CharsPerLine: Integer; LineSeparator: string); begin FCharsPerline := CharsPerLine; FLineSeparator := LineSeparator; end; function TBase64Encoding.DecodeBytes(Input, Output: PByte; InputLen: Integer; CharSize: SmallInt; var State: TDecodeState): Integer; var POut: PByte; Fragment: Integer; P, PEnd: PByte; begin POut := Output; P := Input; PEnd := P + InputLen; POut^ := State.Result; while True do begin case State.Step of DecodeStepA: begin repeat if P = PEnd then begin State.Result := POut^; Exit(POut - Output); end; Fragment := DecodeValue(Ord(P^)); Inc(P, CharSize); until (Fragment >= 0) ; POut^ := (Fragment and $03F) shl 2; State.Step := DecodeStepB; end; DecodeStepB: begin repeat if P = PEnd then begin State.Result := POut^; Exit(POut - Output); end; Fragment := DecodeValue(Ord(P^)); Inc(P, CharSize); until (Fragment >= 0) ; POut^ := (POut^ or ((Fragment and $030) shr 4)); Inc(POut); POut^ := ((Fragment and $00F) shl 4); State.Step := DecodeStepC; end; DecodeStepC: begin repeat if P = PEnd then begin State.Result := POut^; Exit(POut - Output); end; Fragment := DecodeValue(Ord(P^)); Inc(P, CharSize); until (Fragment >= 0) ; POut^ := (POut^ or ((Fragment and $03C) shr 2)); Inc(POut); POut^ := ((Fragment and $003) shl 6); State.Step := DecodeStepD; end; DecodeStepD: begin repeat if P = PEnd then begin State.Result := POut^; Exit(POut - Output); end; Fragment := DecodeValue(Ord(P^)); Inc(P, CharSize); until (Fragment >= 0) ; POut^ := (POut^ or (Fragment and $03F)); Inc(POut); State.Step := DecodeStepA; end; end; end; end; function TBase64Encoding.DoDecode(const Input, Output: TStream): Integer; var InBuf: array[0..1023] of Byte; OutBuf: array[0..767] of Byte; BytesRead, BytesWrite: Integer; State: TDecodeState; begin InitDecodeState(State); Result := 0; repeat BytesRead := Input.Read(InBuf[0], Length(InBuf)); BytesWrite := DecodeBytes(@InBuf[0], @OutBuf[0], BytesRead, 1, State); Output.Write(Outbuf, BytesWrite); Result := Result + BytesWrite; until BytesRead = 0; end; function TBase64Encoding.DoDecode(const Input: string): string; begin Result := TEncoding.UTF8.GetString(DoDecodeStringToBytes(Input)); end; function TBase64Encoding.DoDecodeStringToBytes(const Input: string): TBytes; const CharSize = SizeOf(Char); var Len: Integer; State: TDecodeState; begin SetLength(Result, EstimateDecodeLength(Length(Input))); InitDecodeState(State); Len := DecodeBytes(PByte(Input), PByte(Result), Length(Input) * CharSize, CharSize, State); SetLength(Result, Len); end; function TBase64Encoding.DoEncode(const Input: TBytes): TBytes; const CharSize = SizeOf(Byte); var Len: Integer; State: TEncodeState; LineSeparator: TBytes; begin if Length(Input) > 0 then begin LineSeparator := TEncoding.UTF8.GetBytes(FLineSeparator); SetLength(Result, EstimateEncodeLength(Length(Input))); InitEncodeState(State); Len := EncodeBytes(@Input[0], PByte(Result), Length(Input), CharSize, LineSeparator, State); Len := EncodeBytesEnd(PByte(PByte(Result) + Len), CharSize, State) + Len; SetLength(Result, Len); end else SetLength(Result, 0) end; function TBase64Encoding.EncodeBytesEnd(Output: PByte; CharSize: SmallInt; var State: TEncodeState): Integer; var POut: PByte; begin POut := Output; case State.Step of EncodeStepB: begin POut^ := EncodeTable[State.Result]; Inc(POut, CharSize); POut^ := Byte('='); Inc(POut, CharSize); POut^ := Byte('='); Inc(POut, CharSize); end; EncodeStepC: begin POut^ := EncodeTable[State.Result]; Inc(POut, CharSize); POut^ := Byte('='); Inc(POut, CharSize); end; end; Result := POut - Output; end; function TBase64Encoding.EncodeBytes(Input, Output: PByte; InputLen: Integer; CharSize: SmallInt; LineSeparator: array of Byte; var State: TEncodeState): Integer; var B, C: Byte; P, PEnd, POut: PByte; begin P := Input; PEnd := P + InputLen; POut := Output; C := State.Result; while P <> PEnd do begin case State.Step of EncodeStepA: begin B := P^; Inc(P); C := (B and $FC) shr 2; POut^ := EncodeValue(C); Inc(POut, CharSize); C := (B and $3) shl 4; State.Step := EncodeStepB; end; EncodeStepB: begin B := P^; Inc(P); C := C or (B and $F0) shr 4; POut^ := EncodeValue(C); Inc(POut, CharSize); C := (B and $F) shl 2; State.Step := EncodeStepC; end; EncodeStepC: begin B := P^; Inc(P); C := C or (B and $C0) shr 6; POut^ := EncodeValue(C); Inc(POut, CharSize); C := (B and $3F) shr 0; POut^ := EncodeValue(C); Inc(POut, CharSize); Inc(State.StepCount); if (FCharsPerLine > 0) and (State.StepCount >= FCharsPerLine/4) then begin Move(LineSeparator[0], POut^, Length(LineSeparator)); Inc(POut, Length(LineSeparator)); State.StepCount := 0; end; State.Step := EncodeStepA; end; end; end; State.Result := C; Exit(POut - Output); end; function TBase64Encoding.DoEncodeBytesToString(const Input: TBytes): string; begin if Length(Input) > 0 then Result := EncodeBytesToString(@Input[0], Length(Input)) else Result := ''; end; function TBase64Encoding.DoEncode(const Input, Output: TStream): Integer; var InBuf: array[0..767] of Byte; OutBuf: array[0..1023] of Byte; BytesRead, BytesWrite: Integer; State: TEncodeState; LineSeparator: TBytes; begin LineSeparator := TEncoding.UTF8.GetBytes(FLineSeparator); InitEncodeState(State); Result := 0; repeat BytesRead := Input.Read(InBuf[0], Length(InBuf)); BytesWrite := EncodeBytes(@InBuf[0], @OutBuf[0], BytesRead, 1, LineSeparator, State); Output.Write(Outbuf, BytesWrite); Result := Result + BytesWrite; until BytesRead = 0; BytesWrite := EncodeBytesEnd(@OutBuf[0], 1, State); Result := Result + BytesWrite; Output.Write(Outbuf, BytesWrite); end; function TBase64Encoding.DoEncode(const Input: string): string; begin Result := DoEncodeBytesToString(TEncoding.UTF8.GetBytes(Input)); end; function TBase64Encoding.DoEncodeBytesToString(const Input: Pointer; Size: Integer): string; const CharSize = SizeOf(Char); var Len: Integer; State: TEncodeState; LineSeparator: TBytes; Estimate: Integer; begin LineSeparator := TEncoding.Unicode.GetBytes(FLineSeparator); Estimate := EstimateEncodeLength(Size); SetLength(Result, Estimate); FillChar(PChar(Result)^, Estimate * CharSize, 0); InitEncodeState(State); Len := EncodeBytes(Input, PByte(Result), Size, CharSize, LineSeparator, State); Len := EncodeBytesEnd(PByte(PByte(Result) + Len), CharSize, State) + Len; SetLength(Result, Len div CharSize); end; procedure TBase64Encoding.InitDecodeState(var State: TDecodeState); begin State.Step := DecodeStepA; State.Result := 0; end; procedure TBase64Encoding.InitEncodeState(var State: TEncodeState); begin State.Step := EncodeStepA; State.Result := 0; State.StepCount := 0; end; { TURLEncoding } function TURLEncoding.DoDecode(const Input: string): string; function DecodeHexChar(const C: Char): Byte; begin case C of '0'..'9': Result := Ord(C) - Ord('0'); 'A'..'F': Result := Ord(C) - Ord('A') + 10; 'a'..'f': Result := Ord(C) - Ord('a') + 10; else raise EConvertError.Create(''); end; end; function DecodeHexPair(const C1, C2: Char): Byte; inline; begin Result := DecodeHexChar(C1) shl 4 + DecodeHexChar(C2) end; var Sp, Cp: PChar; I: Integer; Bytes: TBytes; begin SetLength(Bytes, Length(Input) * 4); I := 0; Sp := PChar(Input); Cp := Sp; try while Sp^ <> #0 do begin case Sp^ of '+': Bytes[I] := Byte(' '); '%': begin Inc(Sp); // Look for an escaped % (%%) if (Sp)^ = '%' then Bytes[I] := Byte('%') else begin // Get an encoded byte, may is a single byte (%<hex>) // or part of multi byte (%<hex>%<hex>...) character Cp := Sp; Inc(Sp); if ((Cp^ = #0) or (Sp^ = #0)) then raise EHTTPException.CreateFmt('ErrorDecodingURLText', [Cp - PChar(Input)]); Bytes[I] := DecodeHexPair(Cp^, Sp^) end; end; else // Accept single and multi byte characters if Ord(Sp^) < 128 then Bytes[I] := Byte(Sp^) else I := I + TEncoding.UTF8.GetBytes(String(Sp^), 1, 1, Bytes, I) - 1; end; Inc(I); Inc(Sp); end; except on E: EConvertError do raise EConvertError.CreateFmt('InvalidURLEncodedChar', [Char('%') + Cp^ + Sp^, Cp - PChar(Input)]) end; SetLength(Bytes, I); Result := TEncoding.UTF8.GetString(Bytes); end; function TURLEncoding.DoEncode(const Input: string): string; // The NoConversion set contains characters as specificed in RFC 1738 and // should not be modified unless the standard changes. const NoConversion = [Ord('A')..Ord('Z'), Ord('a')..Ord('z'), Ord('*'), Ord('@'), Ord('.'), Ord('_'), Ord('-'), Ord('0')..Ord('9'), Ord('$'), Ord('!'), Ord(''''), Ord('('), Ord(')'),ord('/'),ord('='),ord('&'),ord('?'),ord(':')]; procedure AppendByte(B: Byte; var Buffer: PChar); const Hex = '0123456789ABCDEF'; begin Buffer[0] := '%'; Buffer[1] := Hex[B shr 4 + 1]; Buffer[2] := Hex[B and $F + 1]; Inc(Buffer, 3); end; var Sp, Rp: PChar; MultibyteChar: TBytes; I, ByteCount: Integer; begin // Characters that require more than 1 byte are translated as "percent-encoded byte" // which will be encoded with 3 chars per byte -> %XX // Example: U+00D1 ($F1 in CodePage 1252) // UTF-8 representation: $C3 $91 (2 bytes) // URL encode representation: %C3%91 // // So the worst case is 4 bytes(max) per Char, and 3 characters to represent each byte SetLength(Result, Length(Input) * 4 * 3); Sp := PChar(Input); Rp := PChar(Result); SetLength(MultibyteChar, 4); while Sp^ <> #0 do begin if Ord(Sp^) in NoConversion then begin Rp^ := Sp^; Inc(Rp) end else {if Sp^ = ' ' then begin Rp^ := '+'; Inc(Rp) end else} begin if (Ord(Sp^) < 128) then // Single byte char AppendByte(Ord(Sp^), Rp) else begin // Multi byte char ByteCount := TEncoding.UTF8.GetBytes(String(Sp^), 1, 1, MultibyteChar, 0); for I := 0 to ByteCount - 1 do AppendByte(MultibyteChar[I], Rp); end end; Inc(Sp); end; SetLength(Result, Rp - PChar(Result)); end; { THTMLEncoding } function THTMLEncoding.DoEncode(const Input: string): string; var Sp, Rp: PChar; begin SetLength(Result, Length(Input) * 10); Sp := PChar(Input); Rp := PChar(Result); // Convert: &, <, >, " while Sp^ <> #0 do begin case Sp^ of '&': begin StrCopy(Rp, '&amp;'); Inc(Rp, 5); end; '<': begin StrCopy(Rp, '&lt;'); Inc(Rp, 4); end; '>': begin StrCopy(Rp, '&gt;'); Inc(Rp, 4); end; '"': begin StrCopy(Rp, '&quot;'); Inc(Rp, 6); end; else begin Rp^ := Sp^; Inc(Rp); end; end; Inc(Sp); end; SetLength(Result, Rp - PChar(Result)); end; function THTMLEncoding.DoDecode(const Input: string): string; var Sp, Rp, Cp, Tp: PChar; S: string; I, Code: Integer; begin SetLength(Result, Length(Input)); Sp := PChar(Input); Rp := PChar(Result); Cp := Sp; try while Sp^ <> #0 do begin case Sp^ of '&': begin Cp := Sp; Inc(Sp); case Sp^ of 'a': if AnsiStrPos(Sp, 'amp;') = Sp then { do not localize } begin Inc(Sp, 3); Rp^ := '&'; end; 'l', 'g': if (AnsiStrPos(Sp, 'lt;') = Sp) or (AnsiStrPos(Sp, 'gt;') = Sp) then { do not localize } begin Cp := Sp; Inc(Sp, 2); while (Sp^ <> ';') and (Sp^ <> #0) do Inc(Sp); if Cp^ = 'l' then Rp^ := '<' else Rp^ := '>'; end; 'q': if AnsiStrPos(Sp, 'quot;') = Sp then { do not localize } begin Inc(Sp, 4); Rp^ := '"'; end; '#': begin Tp := Sp; Inc(Tp); while (Sp^ <> ';') and (Sp^ <> #0) do Inc(Sp); SetString(S, Tp, Sp - Tp); Val(S, I, Code); if I >= $10000 then begin // DoDecode surrogate pair Rp^ := Char(((I - $10000) div $400) + $D800); Inc(Rp); Rp^ := Char(((I - $10000) and $3FF) + $DC00); end else Rp^ := Chr((I)); end; else raise EConvertError.CreateFmt('InvalidHTMLEncodedChar', [Cp^ + Sp^, Cp - PChar(Input)]) end; end else Rp^ := Sp^; end; Inc(Rp); Inc(Sp); end; except on E: EConvertError do raise EConvertError.CreateFmt('InvalidHTMLEncodedChar', [Cp^ + Sp^, Cp - PChar(Input)]) end; SetLength(Result, Rp - PChar(Result)); end; { TPointerStream } constructor TPointerStream.Create(P: Pointer; Size: Integer); begin SetPointer(P, Size); end; function TPointerStream.Write(const Buffer; Count: LongInt): LongInt; var Pos, EndPos, Size: LongInt; Mem: Pointer; begin Pos := Self.Position; if (Pos >= 0) and (Count > 0) then begin EndPos := Pos + Count; Size := Self.Size; if EndPos > Size then raise EStreamError.CreateRes(@SMemoryStreamError); Mem := Self.Memory; System.Move(Buffer, Pointer(Longint(Mem) + Pos)^, Count); Self.Position := Pos; Result := Count; Exit; end; Result := 0; end; initialization finalization //No Class destructor freeAndNil( TNetEncoding.FBase64Encoding ); freeAndNil( TNetEncoding.FHTMLEncoding); freeAndNil( TNetEncoding.FURLEncoding); end.
unit eAtasOrais.Controller.Factory; interface uses eAtasOrais.Controller.interfaces; Type TControllerFactory = Class(TInterfacedObject, iControllerFactory) Private Public Constructor Create; Destructor Destroy; Override; Class function New: iControllerFactory; Function Configuracao : iControllerConfiguracao; Function Periodos : iControllerPeriodos; Function turmas : iControllerTurmas; Function alunos : iControllerAlunos; Function Funcoes : iControllerFuncoes; Function Professores : iControllerProfessores; Function Atas : iControllerAtas; End; implementation uses eAtasOrais.Controller.Alunos, eAtasOrais.Controller.configuracao, eAtasOrais.Controller.periodos, eAtasOrais.Controller.turmas, eAtasOrais.Controller.Funcoes, eAtasOrais.Controller.Professores, eAtasOrais.Controller.Atas; { TControllerFactory } function TControllerFactory.alunos: iControllerAlunos; begin Result := tControllerAlunos.New; end; function TControllerFactory.Atas: iControllerAtas; begin Result := tControllerAtas.new; end; function TControllerFactory.Configuracao: iControllerConfiguracao; begin Result := tControllerConfiguracao.New; end; constructor TControllerFactory.Create; begin end; destructor TControllerFactory.Destroy; begin inherited; end; function TControllerFactory.Funcoes: iControllerFuncoes; begin Result := tcontrollerfuncoes.new; end; class function TControllerFactory.New: iControllerFactory; begin Result := Self.Create; end; function TControllerFactory.Periodos: iControllerPeriodos; begin Result := tcontrollerPeriodos.New; end; function TControllerFactory.Professores: iControllerProfessores; begin result := tcontrollerProfessores.New; end; function TControllerFactory.turmas: iControllerTurmas; begin Result := tControllerTurmas.New; end; end.
unit MFichas.Controller.Venda.Metodos.CancelarItem; interface uses MFichas.Controller.Venda.Interfaces, MFichas.Model.Venda.Interfaces; type TControllerVendaMetodosCancelarItem = class(TInterfacedObject, iControllervendaMetodosCancelarItem) private [weak] FParent: iControllerVenda; FModel : iModelVenda; FIndex : Integer; constructor Create(AParent: iControllerVenda; AModel: iModelVenda); public destructor Destroy; override; class function New(AParent: iControllerVenda; AModel: iModelVenda): iControllervendaMetodosCancelarItem; function Index(AIndex: Integer): iControllerVendaMetodosCancelarItem; function Executar : iControllerVendaMetodosCancelarItem; function &End : iControllerVendaMetodos; end; implementation { TControllerVendaMetodosCancelarItem } function TControllerVendaMetodosCancelarItem.&End: iControllerVendaMetodos; begin Result := FParent.Metodos; end; constructor TControllerVendaMetodosCancelarItem.Create(AParent: iControllerVenda; AModel: iModelVenda); begin FParent := AParent; FModel := AModel; end; destructor TControllerVendaMetodosCancelarItem.Destroy; begin inherited; end; function TControllerVendaMetodosCancelarItem.Executar: iControllerVendaMetodosCancelarItem; begin Result := Self; FModel .Item .Metodos .Cancelar .Index(FIndex) .&End .&End; end; function TControllerVendaMetodosCancelarItem.Index( AIndex: Integer): iControllerVendaMetodosCancelarItem; begin Result := Self; FIndex := AIndex; end; class function TControllerVendaMetodosCancelarItem.New(AParent: iControllerVenda; AModel: iModelVenda): iControllervendaMetodosCancelarItem; begin Result := Self.Create(AParent, AModel); end; end.
unit l3Defaults; {* Значения по умолчанию библиотеки L3. } { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3Defaults - } { Начат: 10.09.2001 15:33 } { $Id: l3Defaults.pas,v 1.24 2012/11/01 09:42:57 lulin Exp $ } // $Log: l3Defaults.pas,v $ // Revision 1.24 2012/11/01 09:42:57 lulin // - забыл точку с запятой. // // Revision 1.23 2012/11/01 07:45:08 lulin // - делаем возможность логирования процесса загрузки модулей. // // Revision 1.22 2012/10/26 19:42:24 lulin // - вычищаем поддержку ветки редактора. // // Revision 1.21 2011/09/02 12:28:55 lulin // {RequestLink:281523254}. // // Revision 1.20 2011/08/29 18:14:24 lulin // {RequestLink:278833302}. // // Revision 1.19 2011/08/29 14:46:18 lulin // - правим эталоны из-за уменьшения шрифта по-умолчанию для preformatted-параграфов. // // Revision 1.18 2011/08/26 16:34:02 lulin // {RequestLink:278833302}. // // Revision 1.17 2011/08/26 14:47:02 lulin // {RequestLink:278833302}. // // Revision 1.16 2011/07/13 17:39:10 lulin // {RequestLink:228688745}. // // Revision 1.15 2011/07/04 16:18:49 vkuprovich // {RequestLink:269082891} // Убираем излишние комментарии // // Revision 1.14 2011/06/17 11:59:10 lulin // {RequestLink:228688486}. // // Revision 1.13 2011/04/20 10:45:22 lulin // {RequestLink:263294701}. // // Revision 1.12 2011/03/21 14:03:29 lulin // {RequestLink:228691765}. // // Revision 1.11 2011/03/17 15:27:50 lulin // {RequestLink:228691765}. // // Revision 1.10 2011/03/16 18:24:24 lulin // {RequestLink:228688510}. // - используем новый синий цвет фона. // // Revision 1.9 2010/09/23 09:35:14 lulin // {RequestLink:234361479}. // // Revision 1.8 2010/01/19 12:09:14 lulin // {RequestLink:178717037}. // // Revision 1.7 2008/09/09 15:40:14 lulin // - удалены ненужные свойства. // // Revision 1.6 2008/06/16 13:55:08 lulin // - рисуем схему EVD на модели. // // Revision 1.5 2007/01/12 13:48:16 lulin // - cleanup. // // Revision 1.4 2006/12/04 13:43:57 oman // - fix: Константа для определения минимальной печатной области // вынесена в l3/ev (cq23103) // // Revision 1.3 2005/05/24 14:50:09 lulin // - готовим модуль evGraph к переезду в L3. // // Revision 1.2 2005/03/28 08:35:10 mmorozov // new behaviour: для Немезиса def_ANSIDOSFontName = 'Courier New'; // // Revision 1.1 2001/09/10 11:38:44 law // - split unit: evDef -> evDef + l3Defaults. // {$Include l3Define.inc } interface uses Graphics, l3Const ; const c_MainMenuColor = $00A95800; def_PaperColor = clWhite; {* - цвет бумаги. } def_Zoom = 100; def_cmPaperWidth = 2100; def_cmPaperHeight = 2970; def_cmPaperLeft = 150; def_cmPaperRight = 150; def_cmPaperTop = 200; def_cmPaperBottom = 200; def_cmMinPrintArea = 300; def_cmPrintableWidth = def_cmPaperWidth - def_cmPaperLeft - def_cmPaperRight; def_cmNormalParaStyleWidth = def_cmPrintableWidth; def_FrameWidth = l3Inch div 144; def_FirstIndent = l3Inch div 2; def_FirstLineIndent = def_FirstIndent; def_LineSpacing = 100; def_BigLineSpacing = {150}125; def_PrintingLineSpacing = def_BigLineSpacing; var def_inchPrintableWidth : Integer = 0; def_inchPaperWidth : Integer = 0; def_inchPaperHeight : Integer = 0; def_inchPaperBottom : Integer = 0; def_inchMinPrintArea : Integer = 0; def_inchPaperLeft : Integer = 0; def_inchPaperRight : Integer = 0; def_inchPaperTop : Integer = 0; def_inchNormalParaStyleWidth : Integer = 0; const cGarant2011ToolbarsColor = $00F9F8FA; cGarant2011BackColor = $00F9F8FA; cGarant2011GradientStartColor = $CF9560; cGarant2011GradientEndColor = $E1B484; cGarant2011SelectionColor = $B87040; cGarant2011LinkColor = $00800000; cGarant2011BorderColor = $A95C1D; cGarant2011InnerBorderColor = $DBAA76; cGarant2011KZBorderColor = $E7B294; cGarant2011KZInnerBorderColor = $EFCFBD; cGarant2011CollapsedPanelColor = $E0C9B1; cWarningMessageColor = $F6E1D2; resourcestring def_ANSIDOSFontName = 'Courier New'; def_WingdingsFontName = 'Wingdings'; implementation uses l3UnitsTools ; initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\l3Defaults.pas initialization enter'); {$EndIf} def_inchPaperLeft := l3Cm2Inch(def_cmPaperLeft); def_inchPaperRight := l3Cm2Inch(def_cmPaperRight); def_inchPaperTop := l3Cm2Inch(def_cmPaperTop); def_inchPrintableWidth := l3Cm2Inch(def_cmPrintableWidth); def_inchPaperWidth := l3Cm2Inch(def_cmPaperWidth); def_inchPaperHeight := l3Cm2Inch(def_cmPaperHeight); def_inchPaperBottom := l3Cm2Inch(def_cmPaperBottom); def_inchMinPrintArea := l3Cm2Inch(def_cmMinPrintArea); def_inchNormalParaStyleWidth := l3Cm2Inch(def_cmNormalParaStyleWidth); {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\L3\l3Defaults.pas initialization leave'); {$EndIf} end.
program minigzip; { minigzip.c -- simulate gzip using the zlib compression library Copyright (C) 1995-1998 Jean-loup Gailly. minigzip is a minimal implementation of the gzip utility. This is only an example of using zlib and isn't meant to replace the full-featured gzip. No attempt is made to deal with file systems limiting names to 14 or 8+3 characters, etc... Error checking is very limited. So use minigzip only for testing; use gzip for the real thing. On MSDOS, use only on file names without extension or in pipe mode. Pascal tranlastion based on code contributed by Francisco Javier Crespo Copyright (C) 1998 by Jacques Nomssi Nzali For conditions of distribution and use, see copyright notice in readme.txt } uses gzio; const BUFLEN = 16384 ; GZ_SUFFIX = '.gz' ; {$DEFINE MAXSEF_64K} var buf : packed array [0..BUFLEN-1] of byte; { Global uses BSS instead of stack } prog : string; { ERROR ===================================================================== Display error message and exit ============================================================================} procedure error (msg:string); begin writeln (prog,': ',msg); halt(1); end; { GZ_COMPRESS =============================================================== Compress input to output then close both files ============================================================================} procedure gz_compress (var infile:file; outfile:gzFile); var len : cardinal; ioerr : integer; err : integer; begin while true do begin {$I-} blockread (infile, buf, BUFLEN, len); {$I+} ioerr := IOResult; if (ioerr <> 0) then begin writeln ('read error: ',ioerr); halt(1); end; if (len = 0) then break; if (gzwrite (outfile, @buf, len) <> len) then error (gzerror (outfile, err)); end; {WHILE} close (infile); if (gzclose (outfile) <> 0{Z_OK}) then error ('gzclose error'); end; { GZ_UNCOMPRESS ============================================================= Uncompress input to output then close both files ============================================================================} procedure gz_uncompress (infile:gzFile; var outfile:file); var len : longint; written : cardinal; ioerr : integer; err : integer; begin while true do begin len := gzread (infile, @buf, BUFLEN); if (len < 0) then error (gzerror (infile, err)); if (len = 0) then break; {$I-} blockwrite (outfile, buf, len, written); {$I+} if (written <> len) then error ('write error'); end; {WHILE} {$I-} close (outfile); {$I+} ioerr := IOResult; if (ioerr <> 0) then begin writeln ('close error: ',ioerr); halt(1); end; if (gzclose (infile) <> 0{Z_OK}) then error ('gzclose error'); end; { FILE_COMPRESS ============================================================= Compress the given file: create a corresponding .gz file and remove the original ============================================================================} procedure file_compress (filename:string; mode:string); var infile : file; outfile : gzFile; ioerr : integer; outname : string; begin Assign (infile, filename); {$I-} Reset (infile,1); {$I+} ioerr := IOResult; if (ioerr <> 0) then begin writeln ('open error: ',ioerr); halt(1); end; outname := filename + GZ_SUFFIX; outfile := gzopen (outname, mode); if (outfile = NIL) then begin writeln (prog,': can''t gzopen ',outname); halt(1); end; gz_compress(infile, outfile); erase (infile); end; { FILE_UNCOMPRESS =========================================================== Uncompress the given file and remove the original ============================================================================} procedure file_uncompress (filename:string); var inname : string; outname : string; infile : gzFile; outfile : file; ioerr : integer; len : integer; begin len := Length(filename); if (copy(filename,len-2,3) = GZ_SUFFIX) then begin inname := filename; outname := copy(filename,0,len-3); end else begin inname := filename + GZ_SUFFIX; outname := filename; end; infile := gzopen (inname, 'r'); if (infile = NIL) then begin writeln (prog,': can''t gzopen ',inname); halt(1); end; Assign (outfile, outname); {$I-} Rewrite (outfile,1); {$I+} ioerr := IOResult; if (ioerr <> 0) then begin writeln ('open error: ',ioerr); halt(1); end; gz_uncompress (infile, outfile); { erase (infile); } end; { MINIGZIP =================================================================} var uncompr : boolean; outmode : string[20]; i : integer; option : string; begin uncompr := false; outmode := 'w6 '; prog := ParamStr(0); if (ParamCount = 0) then begin writeln ('Error: STDIO/STDOUT not supported yet'); writeln; writeln ('Usage: minigzip [-d] [-f] [-h] [-1 to -9] <file>'); writeln (' -d : decompress'); writeln (' -f : compress with Z_FILTERED'); writeln (' -h : compress with Z_HUFFMAN_ONLY'); writeln (' -1 to -9 : compression level'); exit; end; for i:=1 to ParamCount do begin option := ParamStr(i); if (option = '-d') then uncompr := true; if (option = '-f') then outmode[3] := 'f'; if (option = '-h') then outmode[3] := 'h'; if (option[1] = '-') and (option[2] >= '1') and (option[2] <= '9') then outmode[2] := option[2]; end; if (uncompr = true) then file_uncompress (ParamStr(ParamCount)) else file_compress (ParamStr(ParamCount), outmode); end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://localhost:1024/SoapDataServer7.soapdataserver/wsdl/Isampledatamodule // Encoding : utf-8 // Version : 1.0 // (10/30/2002 5:57:10 PM - 1.33.2.5) // ************************************************************************ // unit ISampleDataModule1; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns, SOAPMidas; 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" // ************************************************************************ // // Namespace : urn:SoapDataServerDataModule-Isampledatamodule // soapAction: urn:SoapDataServerDataModule-Isampledatamodule#GetRecordCount // transport : http://schemas.xmlsoap.org/soap/http // style : rpc // binding : Isampledatamodulebinding // service : Isampledatamoduleservice // port : IsampledatamodulePort // URL : http://localhost:1024/SoapDataServer7.soapdataserver/soap/Isampledatamodule // ************************************************************************ // Isampledatamodule = interface(IAppServerSOAP) ['{C5D7FC60-E74E-5ADE-6512-CA6C23A7E6AE}'] function GetRecordCount: Integer; stdcall; end; implementation initialization InvRegistry.RegisterInterface(TypeInfo(Isampledatamodule), 'urn:SoapDataServerDataModule-Isampledatamodule', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(Isampledatamodule), 'urn:SoapDataServerDataModule-Isampledatamodule#GetRecordCount'); end.
unit GX_ActionBroker; { All editor toolbar buttons will get their actions from this broker. This broker also provides transparent access to the Open Tools API's ActionList. Note: Except for adding a method or two to facilitate notification of dynamic menu item enabling and disabling, these interfaces should be stable and cover all use cases. } interface {$I GX_CondDefine.inc} uses Classes, ActnList, Graphics, Actions, GX_Actions; type IGxActionBroker = interface(IUnknown) ['{EC7632E1-D1A3-11D3-A944-DA3A65000000}'] function GetActions(Index: Integer): TContainedAction; function GetActionCount: Integer; // Finds an action in the list of available actions // Includes all actions registered / requested via // GExperts and the actions contained in the IDE's // action list. // Note that by finding an IDE action and querying // for its category name, it is possible to group // a GExperts action into the same category as a // given IDE action. function FindAction(const ActionName: string): TContainedAction; // Register an existing action with the action broker. // The action will be added to the IDE's action list, // making it available to every interested party. // Note that the registered action needs to implement // the IGxAction interface. function RegisterAction(Action: TContainedAction): IGxAction; // Request and register a newly created action interface // instance that represents an activity that does not live in // the GExperts menu. // After requesting, in particular Caption and OnExecute // need to be set to make the Action "useful" function RequestAction(const ActionName: string; Bitmap: Graphics.TBitmap = nil): IGxAction; // Request and register an action interface instance // that represents an activity that lives in the GExperts menu. // After requesting, in particular Caption and OnExecute // need to be set to make the Action "useful" function RequestMenuAction(const ActionName: string; Bitmap: Graphics.TBitmap): IGxMenuAction; // Fill Categories with the all of the action categories procedure GetCategories(Categories: TStrings); ///<summary> /// Generates the name for a menu action as set by RequestMenuAction /// (by prefixing GExpertsActionCategory) </summary> function GenerateMenuActionName(const AActionName: string): string; ///<summary> /// Generates the name for a menu action as set by RequestAction /// (by prefixing GExpertsActionCategory + GxGenericActionQualifier </summary> function GenerateActionName(const AActionName: string): string; // Access to all actions available to the broker; this // includes GExperts's own actions as well as the IDE's // actions. Do not hold on to an action instance for // any prolonged period of time. property Actions[Index: Integer]: TContainedAction read GetActions; property ActionCount: Integer read GetActionCount; end; // Get an instance to the GExperts action broker. function GxActionBroker: IGxActionBroker; const // Do not localize. GxGenericActionQualifier = 'Tools'; GExpertsActionCategory = 'GExperts'; resourcestring SNoButtonCategory = '(None)'; SAllButtonsCategory = '(All)'; implementation uses Windows, SysUtils, Forms, Menus, Rescaler, ToolsAPI, GX_GxUtils, GX_IdeUtils, GX_OtaUtils, GX_KbdShortCutBroker, GX_GenericClasses, GX_GenericUtils, Contnrs, GX_DbugIntf; type // Special action that implements menu actions. TGxMenuAction = class(TGxCustomAction, IUnknown, IGxAction, IGxMenuAction) private FAssociatedMenuItem: TMenuItem; procedure SetShortCut(Value: TShortCut); {$ifdef GX_VER240_up} override; {$endif} protected function GetAssociatedMenuItem: TMenuItem; end; type TGxToolsAction = class(TGxCustomAction, IUnknown, IGxAction) private procedure SetShortCut(Value: TShortCut); {$ifdef GX_VER240_up} override; {$endif} procedure doOnExecute(Sender: TObject); end; type TGxActionBroker = class(TSingletonInterfacedObject, IGxActionBroker) private FGxActionList: TObjectList; procedure ClearGxActionList; function GetIdeActionList: TCustomActionList; function GetActionOwner: TCustomForm; procedure RegisterActionWithIde(const AAction: TCustomAction; Bitmap: Graphics.TBitmap); protected // IGxActionBroker function GetActions(Index: Integer): TContainedAction; function GetActionCount: Integer; function FindAction(const Name: string): TContainedAction; function RegisterAction(Action: TContainedAction): IGxAction; function RequestAction(const ActionName: string; Bitmap: Graphics.TBitmap = nil): IGxAction; function RequestMenuAction(const ActionName: string; Bitmap: Graphics.TBitmap): IGxMenuAction; procedure GetCategories(Categories: TStrings); function GenerateMenuActionName(const AActionName: string): string; function GenerateActionName(const AActionName: string): string; public constructor Create; destructor Destroy; override; end; var PrivateGxActionBroker: TGxActionBroker; function GxActionBroker: IGxActionBroker; begin if not Assigned(PrivateGxActionBroker) then PrivateGxActionBroker := TGxActionBroker.Create; Result := PrivateGxActionBroker; end; procedure FreeGxActionBroker; begin FreeAndNil(PrivateGxActionBroker); end; { TGxActionBroker } procedure TGxActionBroker.ClearGxActionList; var i: Integer; begin if Assigned(FGxActionList) then begin for i := 0 to FGxActionList.Count-1 do FGxActionList[i].Free; FGxActionList.Clear; end; end; constructor TGxActionBroker.Create; begin inherited Create; FGxActionList := TObjectList.Create(False); end; destructor TGxActionBroker.Destroy; begin ClearGxActionList; FreeAndNil(FGxActionList); inherited Destroy; end; function TGxActionBroker.FindAction(const Name: string): TContainedAction; var TempAction: TContainedAction; ActionList: TCustomActionList; i: Integer; begin Result := nil; ActionList := GetIdeActionList; Assert(Assigned(ActionList)); for i := 0 to ActionList.ActionCount-1 do begin TempAction := ActionList.Actions[i]; Assert(Assigned(TempAction)); if SameText(TempAction.Name, Name) then begin Result := TempAction; Break; end; end; end; function TGxActionBroker.GenerateActionName(const AActionName: string): string; begin Result := GExpertsActionCategory + GxGenericActionQualifier + AActionName; end; function TGxActionBroker.GenerateMenuActionName(const AActionName: string): string; begin Result := GExpertsActionCategory + AActionName; end; function TGxActionBroker.GetActionCount: Integer; begin Result := GetIdeActionList.ActionCount; end; function TGxActionBroker.GetActionOwner: TCustomForm; begin Result := GetIdeMainForm; end; function TGxActionBroker.GetActions(Index: Integer): TContainedAction; begin Result := GetIdeActionList.Actions[Index]; end; function TGxActionBroker.GetIdeActionList: TCustomActionList; var NTAServices: INTAServices; begin Assert(Assigned(BorlandIDEServices)); NTAServices := BorlandIDEServices as INTAServices; Assert(Assigned(NTAServices)); Result := NTAServices.ActionList; Assert(Assigned(Result)); end; function TGxActionBroker.RegisterAction(Action: TContainedAction): IGxAction; begin Result := nil; Assert(False, 'Unimplemented function: TGxActionBroker.RegisterAction'); end; function CreateScaledBitmap(Bitmap: Graphics.TBitmap): Graphics.TBitmap; const RequiredWidth = 16; RequiredHeight = 16; var R: TRect; TempBitmap: Graphics.TBitmap; begin Result := Graphics.TBitmap.Create; if (Bitmap.Width = RequiredWidth) and (Bitmap.Height = RequiredHeight) then Result.Assign(Bitmap) else begin // TempBitmap stores a copy of the bitmap but with a transparent color // of clBtnFace. This prevents the rescaling of the image edges // from being discolored by the (usually odd) transparent color. TempBitmap := Graphics.TBitmap.Create; try TempBitmap.Height := Bitmap.Height; TempBitmap.Width := Bitmap.Width; TempBitmap.Canvas.Brush.Color := clBtnFace; TempBitmap.Transparent := True; R.TopLeft := Point(0, 0); R.BottomRight := Point(Bitmap.Height+1, Bitmap.Width+1); TempBitmap.Canvas.FillRect(R); Bitmap.Transparent := True; TempBitmap.Canvas.Draw(0, 0, Bitmap); Result.Width := RequiredWidth; Result.Height := RequiredHeight; Result.Transparent := True; if not Rescaler.Rescale(TempBitmap, Result, False) then Result.Canvas.StretchDraw(Rect(0, 0, Result.Width, Result.Height), TempBitmap); finally FreeAndNil(TempBitmap); end; end; end; procedure TGxActionBroker.RegisterActionWithIde(const AAction: TCustomAction; Bitmap: Graphics.TBitmap); const GxBitmapSuffix = 'GxImage'; // Do not localize. var NTAServices: INTAServices; ReadyBitmap: Graphics.TBitmap; BitmapName: string; begin if IsStandAlone then Exit; Assert(Assigned(AAction)); AAction.ActionList := GetIdeActionList; if Assigned(Bitmap) then begin NTAServices := BorlandIDEServices as INTAServices; Assert(Assigned(NTAServices)); ReadyBitmap := CreateScaledBitmap(Bitmap); try BitmapName := AAction.Name + GxBitmapSuffix; {$IFDEF GX_VER170_up} ReadyBitmap.Transparent := False; // Prevent invisible enabled icons in XE6 (disabled ones might still be invisible/ghosted) {$ENDIF} if ReadyBitmap.Transparent then AAction.ImageIndex := NTAServices.AddMasked(ReadyBitmap, ReadyBitmap.TransparentColor, BitmapName) else AAction.ImageIndex := NTAServices.AddMasked(ReadyBitmap, GXTransparencyColor, BitmapName); finally FreeAndNil(ReadyBitmap); end; end; end; function TGxActionBroker.RequestAction(const ActionName: string; Bitmap: Graphics.TBitmap = nil): IGxAction; var GxToolsAction: TGxToolsAction; begin Assert(Length(ActionName) > 0); Assert(IsValidIdent(ActionName)); GxToolsAction := TGxToolsAction.Create(GetActionOwner); GxToolsAction.Category := GExpertsActionCategory; GxToolsAction.Name := GenerateActionName(ActionName); RegisterActionWithIde(GxToolsAction, Bitmap); Result := GxToolsAction; end; function TGxActionBroker.RequestMenuAction(const ActionName: string; Bitmap: Graphics.TBitmap): IGxMenuAction; const MenuItemAppendix = '_MenuItem'; // Do not localize. var GxMenuAction: TGxMenuAction; begin Assert(Length(ActionName) > 0); GxMenuAction := TGxMenuAction.Create(GetActionOwner); GxMenuAction.Category := GExpertsActionCategory; GxMenuAction.Name := GenerateMenuActionName(ActionName); GxMenuAction.FAssociatedMenuItem := TMenuItem.Create(GxMenuAction); GxMenuAction.FAssociatedMenuItem.Name := GxMenuAction.Name + MenuItemAppendix; GxMenuAction.FAssociatedMenuItem.Action := GxMenuAction; RegisterActionWithIde(GxMenuAction, Bitmap); Result := GxMenuAction; end; procedure TGxActionBroker.GetCategories(Categories: TStrings); var i: Integer; Category: string; begin Assert(Assigned(Categories)); Categories.Clear; for i := 0 to GxActionBroker.ActionCount - 1 do begin Category := GxActionBroker.Actions[i].Category; if Trim(Category) = '' then Category := SNoButtonCategory; EnsureStringInList(Categories, Category); end; end; { TGxMenuAction } function TGxMenuAction.GetAssociatedMenuItem: TMenuItem; begin Result := FAssociatedMenuItem; end; procedure TGxMenuAction.SetShortCut(Value: TShortCut); begin if Assigned(IdeShortCut) and (IdeShortCut.ShortCut <> Value) then IdeShortCut := nil; // Unregisters the shortcut with the IDE if Value <> 0 then begin if Assigned(FAssociatedMenuItem) and not Assigned(IdeShortCut) then begin IdeShortCut := GxKeyboardShortCutBroker.RequestMenuShortCut(OnExecute, FAssociatedMenuItem); Assert(Assigned(IdeShortCut)); IdeShortCut.ShortCut := Value; end; end; inherited; end; { TGxToolsAction } procedure TGxToolsAction.doOnExecute(Sender: TObject); begin if Assigned(OnExecute) then OnExecute(Sender); end; procedure TGxToolsAction.SetShortCut(Value: TShortCut); begin // Not necessary under Delphi 5/6 since the callbacks never happen anyway if RunningDelphi7OrGreater then begin if Assigned(IdeShortCut) and (IdeShortCut.ShortCut <> Value) then IdeShortCut := nil; // Unregisters the shortcut with the IDE if Value <> 0 then begin if not Assigned(IdeShortCut) then begin {$IFOPT D+} if not Assigned(OnExecute) then SendDebugError(Self.ClassName + '(' + Self.Caption + ') tried to register a shortcut but OnExecute was not assigned.'); {$ENDIF} IdeShortCut := GxKeyboardShortCutBroker.RequestOneKeyShortCut(doOnExecute, Value); Assert(Assigned(IdeShortCut)); end; end; end; inherited SetShortCut(Value); end; initialization finalization FreeGxActionBroker; end.
unit MVCFramework.Middleware.Compression; interface uses MVCFramework, MVCFramework.Logger; type TCompressionMiddleware = class(TInterfacedObject, IMVCMiddleware) private fCompressionThreshold: Integer; protected procedure OnAfterControllerAction(Context: TWebContext; const AActionNAme: string; const Handled: Boolean); procedure OnBeforeRouting(Context: TWebContext; var Handled: Boolean); procedure OnBeforeControllerAction(Context: TWebContext; const AControllerQualifiedClassName: string; const AActionNAme: string; var Handled: Boolean); public constructor Create(aCompressionThreshold: Integer = 1024); virtual; end; implementation uses System.SysUtils, System.ZLib, System.Classes; { TMVCSalutationMiddleware } constructor TCompressionMiddleware.Create(aCompressionThreshold: Integer); begin inherited Create; fCompressionThreshold := aCompressionThreshold; end; procedure TCompressionMiddleware.OnAfterControllerAction(Context: TWebContext; const AActionNAme: string; const Handled: Boolean); var lMemStream: TMemoryStream; lContentStream: TStream; lAcceptEncoding: string; lEncodings: TArray<string>; lItem: string; lFound: Boolean; begin lContentStream := Context.Response.RawWebResponse.ContentStream; if (lContentStream = nil) or (lContentStream.Size <= fCompressionThreshold) then Exit; lAcceptEncoding := Context.Request.Headers['Accept-Encoding'].ToLower.Trim; if lAcceptEncoding.IsEmpty then Exit; lFound := False; lEncodings := lAcceptEncoding.Split([',']); for lItem in lEncodings do begin if lItem.Trim = 'deflate' then begin lFound := True; Break; end; end; if not lFound then Exit; lContentStream.Position := 0; lMemStream := TMemoryStream.Create; try ZCompressStream(Context.Response.RawWebResponse.ContentStream, lMemStream); lMemStream.Position := 0; except lMemStream.Free; raise; end; Context.Response.Content := ''; Context.Response.RawWebResponse.ContentStream := lMemStream; Context.Response.RawWebResponse.ContentEncoding := 'deflate'; end; procedure TCompressionMiddleware.OnBeforeControllerAction(Context: TWebContext; const AControllerQualifiedClassName, AActionNAme: string; var Handled: Boolean); begin // do nothing end; procedure TCompressionMiddleware.OnBeforeRouting(Context: TWebContext; var Handled: Boolean); begin // do nothing end; end.
(******************************************************************* * * TTCalc.Pas 1.2 * * Arithmetic and Vectorial Computations (specification) * * Copyright 1996 David Turner, Robert Wilhelm and Werner Lemberg * * This file is part of the FreeType project, and may only be used * modified and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify or distribute * this file you indicate that you have read the license and * understand and accept it fully. * * NOTES : All vector operations were moved to the interpreter * ******************************************************************) unit TTCalc; interface {$I TTCONFIG.INC} type (* IntN types : *) (* *) (* These types are used as a way to garantee the size of some *) (* specific integers. *) (* *) (* Of course, they are equivalent to Short, UShort, Long, etc .. *) (* but parts of this unit could be used by different programs. *) (* *) (* Define the 16-bit type *) {$IFDEF BORLANDPASCAL} Int16 = Integer; Word16 = Word; (* 16-bits unsigned *) {$ENDIF} {$IFDEF DELPHI16} Int16 = Integer; Word16 = Word; (* 16-bits unsigned *) {$ENDIF} {$IFDEF DELPHI32} Int16 = SmallInt; Word16 = Word; (* 16-bits unsigned *) {$ENDIF} {$IFDEF FPC} Int16 = SmallInt; Word16 = Word; (* 16-bits unsigned *) {$ENDIF} Int32 = Integer; (* 32 bits integer *) Word32 = Cardinal; (* 32 bits 'unsigned'. Note that there's *) (* no unsigned long in Pascal.. *) (* As cardinals are only 31 bits !! *) // No need to define our own type, just use the build-in one { Int64 = record (* 64 "" *) Lo, Hi : LongInt; end;} function MulDiv( A, B, C : Int32 ): Int32; function MulDiv_Round( A, B, C : Int32 ): Int32; procedure Add64( var X, Y, Z : Int64 ); procedure Sub64( var X, Y, Z : Int64 ); procedure MulTo64( X, Y : Int32; var Z : Int64 ); function Div64by32( var X : Int64; Y : Int32 ) : Int32; function Order64( var Z : Int64 ) : integer; function Order32( Z : Int32 ) : integer; function Sqrt32( L : Int32 ): LongInt; function Sqrt64( L : Int64 ): LongInt; {$IFDEF TEST} procedure Neg64( var x : Int64 ); procedure DivMod64by32( var X : Int64; Y : Int32; var Q, R : Int32 ); {$ENDIF} implementation uses Math; (* add support for Virtual Pascal inline assembly *) {$IFDEF VIRTUALPASCAL} {$I TTCALC2.INC} {$ENDIF} (* add support for Delphi 2 and 3 inline assembly *) {$IFDEF DELPHI32} {$I TTCALC3.INC} {$ENDIF} (* add support for Borland Pascal and Turbo Pascal inline assembly *) {$IFDEF BORLANDPASCAL} {$I TTCALC1.INC} {$ENDIF} (* Delphi 16 uses the same inline assembly than Borland Pascal *) {$IFDEF DELPHI16} {$I TTCALC1.INC} {$ENDIF} (* add support for Free Pascal inline assembly *) {$IFDEF FPC} {$I TTCALC4.INC} {$ENDIF} (*****************************************************************) (* *) (* MulDiv : computes A*B/C with an intermediate 64 bits *) (* precision. *) (* *) (*****************************************************************) function MulDiv( a, b, c : Int32 ) : Int32; var s : Int32; temp : Int64; begin s := a; a := abs(a); s := s xor b; b := abs(b); s := s xor c; c := abs(c); MulTo64( a, b, temp ); c := Div64by32( temp, c ); if s < 0 then c := -c; MulDiv := c; end; (*****************************************************************) (* *) (* MulDiv : computes A*B/C with an intermediate 64 bits *) (* _Round precision and rounding. *) (* *) (*****************************************************************) function MulDiv_Round( a, b, c : Int32 ) : Int32; var s : Int32; temp, temp2 : Int64; begin s := a; a := abs(a); s := s xor b; b := abs(b); s := s xor c; c := abs(c); MulTo64( a, b, temp ); temp2 := c div 2;; { temp2.hi := 0; temp2.lo := c div 2;} Add64( temp, temp2, temp ); c := Div64by32( temp, c ); if s < 0 then c := -c; MulDiv_Round := c; end; (**********************************************************) (* Negation *) procedure Neg64( var x : Int64 ); begin x := -x; end; { begin (* Remember that -(0x80000000) == 0x80000000 with 2-complement! *) (* We take care of that here. *) x.hi := x.hi xor $FFFFFFFF; x.lo := x.lo xor $FFFFFFFF; inc( x.lo ); if x.lo = 0 then begin inc( x.hi ); if x.hi = $80000000 then (* check -MaxInt32-1 *) begin dec( x.lo ); (* we return $7FFFFFFF *) dec( x.hi ); end; end; end; } (**********************************************************) (* MSB index ( return -1 for 0 ) *) function Order64( var Z : Int64 ) : integer; var b : integer; begin b := 0; while Z <> 0 do begin Z := Z shr 1; inc( b ); end; Result := b-1; end; {original begin if Z.Hi <> 0 then Order64 := 32 + Order32( Z.Hi ) else Order64 := Order32( Z.Lo ); end;} (**********************************************************) (* MSB index ( return -1 for 0 ) *) function Order32( Z : Int32 ) : integer; var b : integer; begin b := 0; while Z <> 0 do begin Z := Z shr 1; inc( b ); end; Order32 := b-1; end; const Roots : array[0..62] of LongInt = ( 1, 1, 2, 3, 4, 5, 8, 11, 16, 22, 32, 45, 64, 90, 128, 181, 256, 362, 512, 724, 1024, 1448, 2048, 2896, 4096, 5892, 8192, 11585, 16384, 23170, 32768, 46340, 65536, 92681, 131072, 185363, 262144, 370727, 524288, 741455, 1048576, 1482910, 2097152, 2965820, 4194304, 5931641, 8388608, 11863283, 16777216, 23726566, 33554432, 47453132, 67108864, 94906265, 134217728, 189812531, 268435456, 379625062, 536870912, 759250125, 1073741824, 1518500250, 2147483647 ); (**************************************************) (* Integer Square Root *) function Sqrt32( L : Int32 ): LongInt; var R, S : LongInt; begin if L<=0 then Sqrt32:=0 else if L=1 then Sqrt32:=1 else begin R:=Roots[ Order32(L) ]; Repeat S:=R; R:=( R+ L div R ) shr 1; until ( R <= S ) and ( R*R <= L ); Sqrt32:=R; end; end; (**************************************************) (* Integer Square Root *) function Sqrt64( L : Int64 ): LongInt; begin Result := Round(sqrt(L)); end; {var L2 : Int64; R, S : LongInt; begin if L.Hi < 0 then Sqrt64:=0 else begin S := Order64(L); if S = 0 then Sqrt64:=1 else begin R := Roots[S]; Repeat S := R; R := ( R+Div64by32(L,R) ) shr 1; if ( R > S ) then continue; MulTo64( R, R, L2 ); Sub64 ( L, L2, L2 ); until ( L2.Hi >= 0 ); Sqrt64 := R; end end end;} end.
unit Unit3; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation; type TForm3 = class(TForm) ToolBar1: TToolBar; btnReset: TButton; btnOK: TButton; Layout1: TLayout; RoundRect1: TRoundRect; Path1: TPath; Rectangle1: TRectangle; Label1: TLabel; procedure RoundRect1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); procedure RoundRect1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); procedure btnOKClick(Sender: TObject); procedure btnResetClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form3: TForm3; implementation {$R *.fmx} procedure TForm3.btnOKClick(Sender: TObject); var B: TBrushBitmap; begin B := TBrushBitmap.Create; B.Bitmap.Assign(Path1.MakeScreenshot); B.Bitmap.Resize(trunc(path1.Width), trunc(path1.Height)); rectangle1.Fill.Kind := Tbrushkind.Bitmap; rectangle1.Fill.Bitmap.Assign(B); path1.Data.Clear; end; procedure TForm3.btnResetClick(Sender: TObject); begin rectangle1.Fill.Kind := TBrushKind.None; path1.Data.Clear; layout1.Repaint; end; procedure TForm3.RoundRect1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin if ssLeft in Shift then Path1.Data.MoveTo(TpointF.Create(X,Y)); end; procedure TForm3.RoundRect1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single); begin if ssLeft in Shift then begin path1.Data.LineTo(TpointF.Create(X,Y)); RoundRect1.Repaint; end; end; end.
unit FileConverter; { Преобразователь форматов } { $Id: FileConverter.pas,v 1.1 2011/06/23 07:01:33 narry Exp $ } // $Log: FileConverter.pas,v $ // Revision 1.1 2011/06/23 07:01:33 narry // Консольная версия RTF2NSRC (253668575) // interface type TInOutFormat = (ifUnknown, ifRTF, ifNSR, ifDOC, ifEVD); TFileConverter = class(TObject) procedure WriteHelp; private f_FileMask: string; f_InFormat: TInOutFormat; f_OutFormat: TInOutFormat; procedure ConvertFiles; function ConvertOneFile(const InName: String): Boolean; function GetFormat(const InName: String): TInOutFormat; procedure ReadParameters; procedure SetDefaultParameters; public procedure Run; end; implementation uses ddFileIterator, SysUtils, evdWriter, ddNSRC_w, ddDOCReader, k2TagGen, evEvdRd, ddRTFWriter, Math, evSimpleTextPainter, k2Reader, ddNSRC_R; procedure TFileConverter.ConvertFiles; begin with TddFileIterator.Make(ExtractFilePath(f_Filemask), ExtractFileName(f_FileMask)) do try IterateFiles(ConvertOneFile); ExitCode:= IfThen(IterateStatus, 0, 1); finally Free; end; end; function TFileConverter.ConvertOneFile(const InName: String): Boolean; var l_Gen: Tk2TagGenerator; begin l_Gen:= nil; try case f_OutFormat of ifRTF : l_Gen:= TevRTFObjectGenerator.SetTo(l_Gen, ChangeFileExt(InName, '.rtf')); ifNSR : begin l_Gen:= TddNSRCGenerator.SetTo(l_Gen, ChangeFileExt(InName, '.nsr')); TevSimpleTextPainter.SetTo(l_Gen); end; ifEVD : l_Gen:= TevdNativeWriter.SetTo(l_Gen, ChangeFileExt(InName, '.evd')); end; case f_InFormat of ifRTF, ifDOC: begin l_Gen:= TddDocReader.SetTo(l_Gen, InName); TddDocReader(l_Gen).LightVersion:= True; end; // ifDOC ifNSR: l_Gen:= TCustomNSRCReader.SetTo(l_Gen, InName); ifEVD: l_Gen:= TevEvdReader.SetTo(l_Gen, InName); end; Tk2CustomFileParser(l_Gen).Execute; finally FreeAndNil(l_Gen); end; end; function TFileConverter.GetFormat(const InName: String): TInOutFormat; var S: String; begin S:= UpperCase(ExtractFileExt(InName)); if S = '.RTF' then Result:= ifRTF else if (S = '.NSR') then Result:= ifNSR else if (S = '.DOC') then Result:= ifDOC else if (S = '.EVD') then Result:= ifEVD else Result:= ifUnknown; end; procedure TFileConverter.ReadParameters; var l_Format: String; begin // Должен быть как минимум один параметр - имя файла if ParamCount > 0 then begin f_FileMask:= ParamStr(1); f_InFormat:= GetFormat(f_FileMask); l_Format:= ParamStr(2); if length(l_Format) = 2 then begin // Формат зависит от значения if l_Format[2] = 'r' then f_OutFormat:= ifRTF else if l_Format[2] = 'n' then f_OutFormat:= ifNSR else if l_Format[2] = 'e' then f_OutFormat:= ifEVD; end; // length(l_Format = 2) end // ParamCount > 0 else WriteHelp; end; procedure TFileConverter.Run; begin SetDefaultParameters; ReadParameters; if (f_Informat <> ifUnknown) and (f_OutFormat <> ifUnknown) and (f_InFormat <> f_OutFormat) then ConvertFiles else ExitCode:= 1; end; procedure TFileConverter.SetDefaultParameters; begin f_InFormat:= ifUnknown; f_OutFormat:= ifNSR; f_FileMask:= ''; end; procedure TFileConverter.WriteHelp; begin Writeln('FileConverter. Garant file format converter.'); Writeln(''); Writeln('Usage:'); Writeln('FileConverter <filename> [-n|-r|-e]'); Writeln(' <filename> - source filename or mask'); Writeln(' -n|-r|-e - destination format'); Writeln(' -n - nsrc (default)'); Writeln(' -r - rtf'); Writeln(' -e - evd'); end; end.
unit akMSHTML; interface uses Classes, MSHTML, shdocvw, BigIni; type THTMLConfigManager = class private fParamList: TStringList; fIniParams: TStringList; fFile: string; fParam: TWebBrowser; FProcessMode: Integer; procedure SetParametersOfSelect(const Doc: IHTMLDocument2; FromSL: TStringList); procedure SetParametersOfInput(const Doc: IHTMLDocument2; FromSL: TStringList); procedure GetParametersOfSelect(const Doc: IHTMLDocument2; OutSL: TStringList); procedure GetParametersOfInput(const Doc: IHTMLDocument2; OutSL: TStringList); procedure SetProcessMode(const Value: Integer); public constructor Create(Param: TWebBrowser); destructor Destroy; override; // Если 0 - работаем в режиме для chm2web (var должен быть в начале всех // названий переменных и т.п. . Если 1 - берем все ID элементов как есть. property ProcessMode: Integer read FProcessMode write SetProcessMode; // Возвращает значения всех полей. Можно использовать для определения // изменилось поле или нет. procedure GetVariables(const doc: IHTMLDocument2; const arr: TStrings); procedure LoadFromFile(fl: string); procedure SaveToFile(fn: string); procedure FillFormsFromIni; procedure FillFormsFromList(list: TStringList); procedure Clear; property WebControl: TWebBrowser read fParam write fParam; property CurrentFile: string read fFile; function GetParameters: string; procedure SetParameters(vals: string); end; implementation uses SysUtils; function QuoteStrings(str: string): string; begin { int := StrToIntDef(str, -1025); if int = -1025 then Result := #1 + str + #1 else Result := IntToStr(int); Result := StringReplace(Result, ' ', #127, [rfReplaceAll]); } Result := str; end; procedure THTMLConfigManager.Clear; begin fParamList.Clear; fFile := ''; end; constructor THTMLConfigManager.Create(Param: TWebBrowser); begin fParamList := nil; fIniParams := nil; fProcessMode := 0; inherited Create; fParamList := TStringList.Create; fIniParams := TStringList.Create; WebControl := Param; Clear; end; destructor THTMLConfigManager.Destroy; begin if Assigned(fIniParams) then fIniParams.Free; if Assigned(fParamList) then fParamList.Free; inherited; end; function THTMLConfigManager.GetParameters: string; var Doc: IHTMLDocument2; i: Integer; begin fParamList.BeginUpdate; try fParamList.Clear; Doc := WebControl.Document as IHTMLDocument2; GetParametersOfSelect(Doc, fParamList); GetParametersOfInput(Doc, fParamList); finally fParamList.EndUpdate; end; Result := StringReplace(fParamList.CommaText, '"', '', [rfReplaceAll]); Result := StringReplace(Result, #1, '"', [rfReplaceAll]); end; procedure THTMLConfigManager.GetParametersOfInput(const Doc: IHTMLDocument2; OutSL: TStringList); var i: Integer; ElCol: IHTMLElementCollection; Els: IHTMLInputElement; nm: string; begin ElCol := Doc.all.tags('input') as IHTMLElementCollection; for i := 0 to ElCol.length - 1 do begin Els := ElCol.item(i, 0) as IHTMLInputElement; nm := Els.name;//(Els as IHTMLElement).getAttribute('name', 0); if Copy(nm, 1, 4) = 'cvar' then begin if ELs.Checked then OutSL.Values[nm] := 'true' else OutSL.Values[nm] := 'false'; end else OutSL.Values[nm] := QuoteStrings(Els.value); end; end; procedure THTMLConfigManager.GetParametersOfSelect(const Doc: IHTMLDocument2; OutSL: TStringList); var i, m: Integer; ElCol, OpCol: IHTMLElementCollection; El: IHTMLElement; ElS: IHTMLSelectElement; ElO: IHTMLOptionElement; nm: string; begin ElCol := Doc.all.tags('select') as IHTMLElementCollection; for i := 0 to ElCol.length - 1 do begin Els := ElCol.item(i, 0) as IHTMLSelectElement; OpCol := ((Els.options as IHTMLElement).all) as IHTMLElementCollection; for m := 0 to OpCol.length - 1 do begin ElO := (OpCol.item(m, 0) as IHTMLOptionElement); if ElO.selected then begin nm := Els.name;//getAttribute('name', 0); if Copy(nm, 1, 3) = 'var' then begin OutSL.Values[nm] := QuoteStrings(ELO.text); OutSL.Values['q' + nm] := IntToStr(ELO.index); end; end; end; end; end; procedure THTMLConfigManager.LoadFromFile(fl: string); var ini: TBigIniFile; begin fFile := fl; ini := TBigIniFile.Create(fFile); with ini do try fIniParams.Clear; ReadSectionValues('VAR', fIniParams); finally Free; end; end; procedure THTMLConfigManager.SaveToFile(fn: string); var ini: TBigIniFile; i: Integer; tmps, nm: string; nms: TStringList; dc: IHTMLDocument2; begin fFile := fn; if fFile = '' then exit; ini := TBigIniFile.Create(fFile); with ini do try fIniParams.Clear; nms := TStringList.Create; try dc := WebControl.Document as IHTMLDocument2; GetParametersOfSelect(dc, nms); GetParametersOfInput(dc, nms); for i := 0 to nms.Count - 1 do begin nm := nms.Names[i]; WriteString('VAR', nm, Trim(nms.Values[nm])); end; finally nms.Free; end; for i := 0 to fIniParams.Count - 1 do begin nm := fIniParams.Names[i]; WriteString('VAR', nm, fIniParams.Values[nm]); end; finally Free; end; end; procedure THTMLConfigManager.SetParameters(vals: string); begin end; procedure THTMLConfigManager.SetParametersOfInput( const Doc: IHTMLDocument2; FromSL: TStringList); var i: Integer; ElCol: IHTMLElementCollection; Els: IHTMLInputElement; nm: string; begin ElCol := Doc.all.tags('input') as IHTMLElementCollection; for i := 0 to ElCol.length - 1 do begin Els := ElCol.item(i, 0) as IHTMLInputElement; nm := Els.name;//lgetAttribute('name', 0); if (Copy(nm, 1, 3) = 'var') or (fProcessMode <> 0) then begin if FromSL.Values['c' + nm] <> '' then Els.checked := FromSL.Values['c' + nm] = 'true'; //'YES'; if FromSL.Values[nm] <> '' then Els.value := FromSL.Values[nm]; end; end; end; procedure THTMLConfigManager.SetParametersOfSelect( const Doc: IHTMLDocument2; FromSL: TStringList); var i: Integer; ElCol, OpCol: IHTMLElementCollection; ElS: IHTMLSelectElement; ElO: IHTMLOptionElement; nm: string; ind: Integer; begin {$IFDEF ASRT}lg.lassert($3CC82D8B, Assigned(Doc), ''); {$ENDIF} ElCol := Doc.all.tags('select') as IHTMLElementCollection; for i := 0 to ElCol.length - 1 do begin Els := ElCol.item(i, 0) as IHTMLSelectElement; nm := Els.name;//getAttribute('name', 0); OpCol := ((Els.options as IHTMLElement).all) as IHTMLElementCollection; ind := StrToIntDef(FromSL.Values['q' + nm], -1); if ind <> -1 then begin ElO := (OpCol.item(ind, 0) as IHTMLOptionElement); ELO.selected := true; end; end; end; procedure THTMLConfigManager.FillFormsFromIni; begin FillFormsFromList(fIniParams); end; procedure THTMLConfigManager.GetVariables(const doc: IHTMLDocument2; const arr: TStrings); begin arr.Clear; GetParametersOfSelect(doc, TStringList(arr)); GetParametersOfInput(doc, TStringList(arr)); end; procedure THTMLConfigManager.FillFormsFromList(list: TStringList); var dc: IHTMLDocument2; begin dc := WebControl.Document as IHTMLDocument2; SetParametersOfSelect(dc, list); SetParametersOfInput(dc, list); end; procedure THTMLConfigManager.SetProcessMode(const Value: Integer); begin FProcessMode := Value; end; end.
unit nsDictionTree; {* Дерево толкового словаря. } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Diction\nsDictionTree.pas" // Стереотип: "SimpleClass" // Элемент модели: "TnsDictionTree" MUID: (46836BA203A1) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3IntfUses , nsDataResetTreeStruct , bsTypes , CommonDictionInterfaces , l3TreeInterfaces , bsInterfaces , l3Interfaces , DynamicTreeUnit , afwInterfaces , nsFilterableTreeStruct ; type TnsDictionTree = class(TnsDataResetTreeStruct) {* Дерево толкового словаря. } private f_DictionKind: TnsDictionKind; protected function pm_GetLanguage: TbsLanguage; virtual; function DictFilters: InsLayeredTreeFilters; function ReAqurieUnfilteredRoot: INodeBase; override; function MakeChildNode(const aChild: INodeBase): Il3SimpleNode; override; constructor CreateFiltered(const aNewRoot: INodeBase; aSource: TnsFilterableTreeStruct; const aFilters: Il3TreeFilters); override; function MakeFilters: Il3TreeFilters; override; procedure FillFilters(const aFilters: Il3TreeFilters; const anAdapterFilters: InsAdapterFilters); override; function SettingsID: TafwSettingId; override; procedure BeforeReset; override; public constructor Create(aKind: TnsDictionKind; const aRoot: INodeBase; aShowRoot: Boolean; aOneLevel: Boolean = False); reintroduce; class function Make(aKind: TnsDictionKind; aLang: TbsLanguage; const anActiveContext: Il3CString = nil; CalcPartialContext: Boolean = False): Il3SimpleTree; private property Language: TbsLanguage read pm_GetLanguage; public property DictionKind: TnsDictionKind read f_DictionKind; end;//TnsDictionTree {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3ImplUses , nsDictListChild , bsConvert , SysUtils , nsLayeredTreeFilters , nsConst , nsLayerFilter , l3String , nsDictCache , nsMedicDictCache , nsINodeOneLevelWrap , nsDayTipsDictCache //#UC START# *46836BA203A1impl_uses* //#UC END# *46836BA203A1impl_uses* ; function TnsDictionTree.pm_GetLanguage: TbsLanguage; //#UC START# *490823D301BE_46836BA203A1get_var* //#UC END# *490823D301BE_46836BA203A1get_var* begin //#UC START# *490823D301BE_46836BA203A1get_impl* Assert(Assigned(DictFilters.Layer)); Result := bsAdapterToBusiness(DictFilters.Layer.LayerID); //#UC END# *490823D301BE_46836BA203A1get_impl* end;//TnsDictionTree.pm_GetLanguage constructor TnsDictionTree.Create(aKind: TnsDictionKind; const aRoot: INodeBase; aShowRoot: Boolean; aOneLevel: Boolean = False); //#UC START# *556C49A400D8_46836BA203A1_var* //#UC END# *556C49A400D8_46836BA203A1_var* begin //#UC START# *556C49A400D8_46836BA203A1_impl* inherited Create(aRoot, aShowRoot, aOneLevel); f_DictionKind := aKind; //#UC END# *556C49A400D8_46836BA203A1_impl* end;//TnsDictionTree.Create class function TnsDictionTree.Make(aKind: TnsDictionKind; aLang: TbsLanguage; const anActiveContext: Il3CString = nil; CalcPartialContext: Boolean = False): Il3SimpleTree; //#UC START# *490823A102D3_46836BA203A1_var* var l_Tree: TnsDictionTree; l_Filterable: Il3FilterableTree; l_TreeFilters: InsLayeredTreeFilters; l_Current: Integer; l_ContainsLang: Boolean; //#UC END# *490823A102D3_46836BA203A1_var* begin //#UC START# *490823A102D3_46836BA203A1_impl* case aKind of ns_dkDiction: l_ContainsLang := TnsDictCache.Instance.ContainsLang(aLang); ns_dkMedic, ns_dkDayTips: l_ContainsLang := True;//TnsCommonDictCache.Instance.ContainsLang(aLang); else Assert(False); end; if l_ContainsLang then begin case aKind of ns_dkDiction: l_Tree := Create(aKind, TnsDictCache.Instance.Root, False); ns_dkMedic: l_Tree := Create(aKind, TnsMedicDictCache.Instance.Root, False); ns_dkDayTips: l_Tree := Create(aKind, TnsDayTipsDictCache.Instance.Root, False); else Assert(False); end; try if aKind = ns_dkDiction then begin l_Filterable := l_Tree; Supports(l_Tree.CloneFilters, InsLayeredTreeFilters, l_TreeFilters); Result := l_Filterable.MakeFiltered(l_TreeFilters.SetLayer(TnsLayerFilter.Make(bsBusinessToAdapter(aLang))), nil, l_Current, True); end else Result := l_Tree; if not l3IsNil(anActiveContext) and (Supports(Result, Il3FilterableTree, l_Filterable)) then begin Result := l_Filterable.MakeFiltered(l_Filterable.CloneFilters.SetContext(anActiveContext), nil, l_Current, True, CalcPartialContext); if not Assigned(Result) or (Result.CountView <= 0) then Result := l_Filterable as Il3SimpleTree; end; finally; FreeAndNil(l_Tree); end; end else Result := nil; //#UC END# *490823A102D3_46836BA203A1_impl* end;//TnsDictionTree.Make function TnsDictionTree.DictFilters: InsLayeredTreeFilters; //#UC START# *4908241B0118_46836BA203A1_var* //#UC END# *4908241B0118_46836BA203A1_var* begin //#UC START# *4908241B0118_46836BA203A1_impl* Supports(Filters, InsLayeredTreeFilters, Result); //#UC END# *4908241B0118_46836BA203A1_impl* end;//TnsDictionTree.DictFilters function TnsDictionTree.ReAqurieUnfilteredRoot: INodeBase; //#UC START# *48FF64F60078_46836BA203A1_var* //#UC END# *48FF64F60078_46836BA203A1_var* begin //#UC START# *48FF64F60078_46836BA203A1_impl* Result := TnsDictCache.Instance.Root; //#UC END# *48FF64F60078_46836BA203A1_impl* end;//TnsDictionTree.ReAqurieUnfilteredRoot function TnsDictionTree.MakeChildNode(const aChild: INodeBase): Il3SimpleNode; //#UC START# *48FEE50002EB_46836BA203A1_var* //#UC END# *48FEE50002EB_46836BA203A1_var* begin //#UC START# *48FEE50002EB_46836BA203A1_impl* if f_DictionKind = ns_dkDiction then Result := TnsDictListChild.Make(aChild, Language) else Result := TnsINodeOneLevelWrap.Make(aChild); //#UC END# *48FEE50002EB_46836BA203A1_impl* end;//TnsDictionTree.MakeChildNode constructor TnsDictionTree.CreateFiltered(const aNewRoot: INodeBase; aSource: TnsFilterableTreeStruct; const aFilters: Il3TreeFilters); //#UC START# *48FF458602EC_46836BA203A1_var* //#UC END# *48FF458602EC_46836BA203A1_var* begin //#UC START# *48FF458602EC_46836BA203A1_impl* Assert(aSource is TnsDictionTree); inherited CreateFiltered(aNewRoot, aSource, aFilters); f_DictionKind := TnsDictionTree(aSource).DictionKind; //#UC END# *48FF458602EC_46836BA203A1_impl* end;//TnsDictionTree.CreateFiltered function TnsDictionTree.MakeFilters: Il3TreeFilters; //#UC START# *48FF4C25031E_46836BA203A1_var* //#UC END# *48FF4C25031E_46836BA203A1_var* begin //#UC START# *48FF4C25031E_46836BA203A1_impl* Result := TnsLayeredTreeFilters.Make; //#UC END# *48FF4C25031E_46836BA203A1_impl* end;//TnsDictionTree.MakeFilters procedure TnsDictionTree.FillFilters(const aFilters: Il3TreeFilters; const anAdapterFilters: InsAdapterFilters); //#UC START# *48FF520E03A0_46836BA203A1_var* var l_Filters: InsLayeredTreeFilters; //#UC END# *48FF520E03A0_46836BA203A1_var* begin //#UC START# *48FF520E03A0_46836BA203A1_impl* inherited FillFilters(aFilters, anAdapterFilters); if Supports(aFilters, InsLayeredTreeFilters, l_Filters) and Assigned(l_Filters.Layer) then anAdapterFilters.Layer.SetLayer(l_Filters.Layer.LayerID); //#UC END# *48FF520E03A0_46836BA203A1_impl* end;//TnsDictionTree.FillFilters function TnsDictionTree.SettingsID: TafwSettingId; //#UC START# *48FF56D003E6_46836BA203A1_var* //#UC END# *48FF56D003E6_46836BA203A1_var* begin //#UC START# *48FF56D003E6_46836BA203A1_impl* Result := gi_cpDiction; //#UC END# *48FF56D003E6_46836BA203A1_impl* end;//TnsDictionTree.SettingsID procedure TnsDictionTree.BeforeReset; //#UC START# *48FF64E700E5_46836BA203A1_var* //#UC END# *48FF64E700E5_46836BA203A1_var* begin //#UC START# *48FF64E700E5_46836BA203A1_impl* inherited; TnsDictCache.Instance.ClearCache; //#UC END# *48FF64E700E5_46836BA203A1_impl* end;//TnsDictionTree.BeforeReset {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clSspiTls; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clSspi, clCryptAPI, clCertificate, clWUtils; type TclCertificateVerifyFlag = (cfIgnoreCommonNameInvalid, cfIgnoreDateInvalid, cfIgnoreUnknownAuthority, cfIgnoreRevocation, cfIgnoreWrongUsage); TclCertificateVerifyFlags = set of TclCertificateVerifyFlag; TclTlsFlag = (tfUseSSL2, tfUseSSL3, tfUseTLS, tfUseTLS11, tfUseTLS12); TclTlsFlags = set of TclTlsFlag; TclSspiReturnCode = (rcOK, rcError, rcReAuthNeeded, rcAuthContinueNeeded, rcAuthDataNeeded, rcAuthMoreDataNeeded, rcCompleteNeeded, rcContinueNeeded, rcClosingNeeded, rcMoreDataNeeded, rcEncodeNeeded, rcContinueAndMoreDataNeeded, rcCredentialNeeded); {$IFDEF LOGGER} const clSspiReturnCodes: array[TclSspiReturnCode] of string = ('rcOK', 'rcError', 'rcReAuthNeeded', 'rcAuthContinueNeeded', 'rcAuthDataNeeded', 'rcAuthMoreDataNeeded', 'rcCompleteNeeded', 'rcContinueNeeded', 'rcClosingNeeded', 'rcMoreDataNeeded', 'rcEncodeNeeded', 'rcContinueAndMoreDataNeeded', 'rcCredentialNeeded'); {$ENDIF} type TclTlsSspi = class(TclSspi) private FPackageNo: Integer; FCredHandle: TCredHandle; FCtxtHandle: TCtxtHandle; FStreamSizes: TSecPkgContext_StreamSizes; FStatusCode: SECURITY_STATUS; FPeerCertificate: TclCertificate; FCertified: Boolean; FCertificateFlags: TclCertificateVerifyFlags; FTLSFlags: TclTlsFlags; FCSP: string; FCSPPtr: PclChar; function GetCSP: PclChar; function GetStreamSizes: TSecPkgContext_StreamSizes; function GetPackageNo: Integer; procedure EnumerateSecurityPackages(var APackagesCount: Cardinal; var APackageInfoArray: PSecPkgInfo); procedure SetCSP(const Value: string); protected procedure FreeSChannelCred(var ASecData: TSChannel_Cred); procedure FreePeerCertificate; procedure DeleteContext; procedure DeleteCredentials; function GenCredentials(ACertificates: TclCertificateList; AllowEmptyCred: Boolean; var ASecData: TSChannel_Cred; ACredentialUse: Cardinal): Boolean; function GetPackageName: PclChar; public constructor Create; destructor Destroy; override; function EndSession(ABuffer: TStream): TclSspiReturnCode; virtual; abstract; function GenContext(ABuffer: TStream; ACertificates: TclCertificateList; AllowEmptyCred: Boolean): TclSspiReturnCode; virtual; abstract; function Encrypt(ASource, ADestination: TStream; ASourceSize: Integer): TclSspiReturnCode; function Decrypt(ASource, ADestination, AExtraBuffer: TStream): TclSspiReturnCode; property CredHandle: TCredHandle read FCredHandle; property CtxtHandle: TCtxtHandle read FCtxtHandle; property StreamSizes: TSecPkgContext_StreamSizes read GetStreamSizes; property PeerCertificate: TclCertificate read FPeerCertificate; property Certified: Boolean read FCertified; property StatusCode: SECURITY_STATUS read FStatusCode; property CertificateFlags: TclCertificateVerifyFlags read FCertificateFlags write FCertificateFlags; property TLSFlags: TclTlsFlags read FTLSFlags write FTLSFlags; property CSP: string read FCSP write SetCSP; end; TclTlsClientSspi = class(TclTlsSspi) private FTargetName: string; FNewConversation: Boolean; function VerifyServerCertificate: Boolean; function ContinueConversation(var ASecData: TSChannel_Cred; ABuffer: TStream; ACertificates: TclCertificateList; AllowEmptyCred: Boolean): TclSspiReturnCode; function NewConversation(var ASecData: TSChannel_Cred; ABuffer: TStream): TclSspiReturnCode; public constructor Create; function EndSession(ABuffer: TStream): TclSspiReturnCode; override; function GenContext(ABuffer: TStream; ACertificates: TclCertificateList; AllowEmptyCred: Boolean): TclSspiReturnCode; override; property TargetName: string read FTargetName write FTargetName; end; TclTlsServerSspi = class(TclTlsSspi) private FNewConversation: Boolean; FRequireClientCertificate: Boolean; procedure GetClientCertificate; public constructor Create; function EndSession(ABuffer: TStream): TclSspiReturnCode; override; function GenContext(ABuffer: TStream; ACertificates: TclCertificateList; AllowEmptyCred: Boolean): TclSspiReturnCode; override; property RequireClientCertificate: Boolean read FRequireClientCertificate write FRequireClientCertificate; end; const PACKAGE_NAMES: array[0..3] of PclChar = ( 'Microsoft Unified Security Protocol Provider', 'Microsoft SSL 3.0', 'NTLM', 'Negotiate'); function CheckSspiError(AErrorCode: SECURITY_STATUS): TclSspiReturnCode; overload; function CheckSspiError(AErrorCode, ADefaultError: SECURITY_STATUS): TclSspiReturnCode; overload; procedure SetSspiErrorIf(ACondition: Boolean; AErrorCode, ADefaultError: SECURITY_STATUS); implementation uses clUtils{$IFDEF LOGGER},clLogger{$ENDIF}{$IFDEF DELPHIXE4}, System.AnsiStrings{$ENDIF}; {$IFDEF DELPHIXE4} function StrComp(const Str1, Str2: PclChar): Integer; begin Result := System.AnsiStrings.StrComp(Str1, Str2); end; {$ENDIF} function CheckSspiError(AErrorCode: SECURITY_STATUS): TclSspiReturnCode; begin Result := CheckSspiError(AErrorCode, AErrorCode); end; function CheckSspiError(AErrorCode, ADefaultError: SECURITY_STATUS): TclSspiReturnCode; begin case AErrorCode of SEC_E_INCOMPLETE_MESSAGE: Result := rcMoreDataNeeded; SEC_I_CONTINUE_NEEDED: Result := rcContinueNeeded; SEC_I_COMPLETE_NEEDED: Result := rcCompleteNeeded; SEC_I_RENEGOTIATE: Result := rcReAuthNeeded; SEC_I_END_SESSION: Result := rcClosingNeeded; SEC_E_OK: Result := rcOK; else begin Result := rcError; RaiseSspiError(AErrorCode, ADefaultError); end; end; end; procedure SetSspiErrorIf(ACondition: Boolean; AErrorCode, ADefaultError: SECURITY_STATUS); begin if ACondition then begin CheckSspiError(AErrorCode, ADefaultError); end; end; { TclTlsSspi } function TclTlsSspi.GetStreamSizes: TSecPkgContext_StreamSizes; var scRet: SECURITY_STATUS; begin if (FStreamSizes.cbHeader = 0) then begin scRet := FunctionTable.QueryContextAttributes(@FCtxtHandle, SECPKG_ATTR_STREAM_SIZES, @FStreamSizes); SetSspiErrorIf(scRet <> SEC_E_OK, scRet, SSPI_E_QueryPackageInfoFailed); end; Result := FStreamSizes; end; procedure TclTlsSspi.SetCSP(const Value: string); begin if (FCSP <> Value) then begin FCSP := Value; FreeMem(FCSPPtr); FCSPPtr := nil; end; end; function TclTlsSspi.GetCSP: PclChar; var s: TclString; len: Integer; begin Result := FCSPPtr; if (Result <> nil) then Exit; if (Trim(CSP) <> '') then begin s := GetTclString(CSP); len := Length(s); GetMem(FCSPPtr, len + SizeOf(TclChar)); system.Move(PclChar(s)^, FCSPPtr^, len); FCSPPtr[len] := #0; end; Result := FCSPPtr; end; function TclTlsSspi.GetPackageName: PclChar; begin if (Trim(CSP) <> '') then begin Result := GetCSP(); end else begin Result := PACKAGE_NAMES[FPackageNo]; end; end; function TclTlsSspi.GetPackageNo: Integer; var I, J: Integer; PackagesCount: Cardinal; PackageInfoArray: PSecPkgInfo; begin EnumerateSecurityPackages(PackagesCount, PackageInfoArray); try Result := Length(PACKAGE_NAMES); for J := 0 to PackagesCount - 1 do begin for I := 0 to Length(PACKAGE_NAMES) - 1 do begin if (StrComp(PSecPkgInfo(TclIntPtr(PackageInfoArray) + SizeOf(TSecPkgInfo) * J).Name, PACKAGE_NAMES[I]) = 0) then begin if (I < Result) then Result := I; Break; end; end; end; finally FunctionTable.FreeContextBuffer(PackageInfoArray); end; SetSspiErrorIf(Result >= Length(PACKAGE_NAMES), SSPI_E_PackageNotFound, SSPI_E_PackageNotFound); end; function TclTlsSspi.Encrypt(ASource, ADestination: TStream; ASourceSize: Integer): TclSspiReturnCode; var oldDstPos: Int64; i, batchSize, srcCurPos, cbMessage, toWrite: Integer; batch, pStart: PclChar; buffers: array[0..3] of TSecBuffer; msg: TSecBufferDesc; begin {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'EncryptMessage', ASource, ASource.Position); {$ENDIF} Result := rcOk; oldDstPos := ADestination.Position; batchSize := ASourceSize; if (batchSize > Integer(StreamSizes.cbMaximumMessage)) then begin batchSize := Integer(StreamSizes.cbMaximumMessage); end; batchSize := batchSize + Integer(StreamSizes.cbHeader) + Integer(StreamSizes.cbTrailer); GetMem(batch, batchSize); try srcCurPos := 0; msg.ulVersion := SECBUFFER_VERSION; msg.cBuffers := 4; msg.pBuffers := @buffers; while(srcCurPos < ASourceSize) do begin cbMessage := ASourceSize - srcCurPos; if (cbMessage > Integer(StreamSizes.cbMaximumMessage)) then begin cbMessage := Integer(StreamSizes.cbMaximumMessage); end; buffers[0].cbBuffer := StreamSizes.cbHeader; buffers[0].BufferType := SECBUFFER_STREAM_HEADER; buffers[0].pvBuffer := batch; buffers[1].cbBuffer := cbMessage; buffers[1].BufferType := SECBUFFER_DATA; buffers[1].pvBuffer := PclChar(TclIntPtr(batch) + Integer(StreamSizes.cbHeader)); buffers[2].cbBuffer := StreamSizes.cbTrailer; buffers[2].BufferType := SECBUFFER_STREAM_TRAILER; buffers[2].pvBuffer := PclChar(TclIntPtr(batch) + Integer(StreamSizes.cbHeader) + cbMessage); buffers[3].cbBuffer := 0; buffers[3].BufferType := SECBUFFER_EMPTY; buffers[3].pvBuffer := nil; ASource.Read(buffers[1].pvBuffer^, cbMessage); srcCurPos := srcCurPos + cbMessage; if (Win32Platform <> VER_PLATFORM_WIN32_WINDOWS) then begin FStatusCode := FunctionTable.EncryptMessage(@FCtxtHandle, nil, @msg, 0); end else begin FStatusCode := FunctionTable.SealMessage(@FCtxtHandle, nil, @msg, 0); end; {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'EncryptMessage'); {$ENDIF} Result := CheckSspiError(FStatusCode); toWrite := 0; pStart := nil; for i := 0 to 2 do begin if (buffers[i].pvBuffer <> nil) then begin if (pStart = nil) then begin pStart := buffers[i].pvBuffer; end; toWrite := toWrite + Integer(buffers[i].cbBuffer); end; end; if (pStart <> nil) and (toWrite > 0) then begin ADestination.Write(pStart^, toWrite); end; end; finally FreeMem(batch); if (ASource.Position >= ASourceSize) then begin ASource.Position := ASource.Position - ASourceSize; end; ADestination.Position := oldDstPos; end; end; function TclTlsSspi.Decrypt(ASource, ADestination, AExtraBuffer: TStream): TclSspiReturnCode; var i, size: Integer; pbBuffPtr, pbIoBuffer: PclChar; cbIoBufferSize: Cardinal; Msg: TSecBufferDesc; Buffers: array[0..3] of TSecBuffer; HasDecodedData, InExtraLoop: Boolean; begin InExtraLoop := False; HasDecodedData := False; {$IFNDEF DELPHIX101} Result := rcOk; {$ENDIF} size := ASource.Size - ASource.Position; GetMem(pbIoBuffer, size); try pbBuffPtr := pbIoBuffer; ASource.Read(pbIoBuffer^, size); ASource.Position := ASource.Position - size; cbIoBufferSize := size; repeat if (cbIoBufferSize < 6) then begin if HasDecodedData then begin AExtraBuffer.Size := 0; AExtraBuffer.Write(pbBuffPtr^, cbIoBufferSize); AExtraBuffer.Position := AExtraBuffer.Position - Integer(cbIoBufferSize); Result := rcContinueAndMoreDataNeeded; end else begin Result := rcMoreDataNeeded; end; break; end; Buffers[0].pvBuffer := pbBuffPtr; Buffers[0].cbBuffer := cbIoBufferSize; Buffers[0].BufferType := SECBUFFER_DATA; Buffers[1].BufferType := SECBUFFER_EMPTY; Buffers[2].BufferType := SECBUFFER_EMPTY; Buffers[3].BufferType := SECBUFFER_EMPTY; Msg.ulVersion := SECBUFFER_VERSION; Msg.cBuffers := Length(Buffers); Msg.pBuffers := @Buffers; if (Win32Platform <> VER_PLATFORM_WIN32_WINDOWS) then begin FStatusCode := FunctionTable.DecryptMessage(@FCtxtHandle, @Msg, 0, nil); end else begin FStatusCode := FunctionTable.UnSealMessage(@FCtxtHandle, @Msg, 0, nil); end; {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'DecryptMessage'); {$ENDIF} Result := CheckSspiError(FStatusCode); for i := Low(Buffers) to High(Buffers) do begin case Buffers[i].BufferType of SECBUFFER_DATA: begin if (Result = rcMoreDataNeeded) or (Result = rcClosingNeeded) then begin AExtraBuffer.Size := 0; AExtraBuffer.Write(Buffers[i].pvBuffer^, Buffers[i].cbBuffer); AExtraBuffer.Position := AExtraBuffer.Position - Integer(Buffers[i].cbBuffer); if (Result <> rcClosingNeeded) then begin Result := rcContinueAndMoreDataNeeded; end; end else begin HasDecodedData := True; ADestination.Write(Buffers[i].pvBuffer^, Buffers[i].cbBuffer); {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'DecryptMessage : ADestination.Write', Buffers[i].pvBuffer, Buffers[i].cbBuffer); {$ENDIF} end; InExtraLoop := False; end; SECBUFFER_EXTRA: begin cbIoBufferSize := Buffers[i].cbBuffer; pbBuffPtr := Buffers[i].pvBuffer; InExtraLoop := True; end; SECBUFFER_MISSING: begin if HasDecodedData then begin AExtraBuffer.Size := 0; AExtraBuffer.Write(pbBuffPtr^, cbIoBufferSize); {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'DecryptMessage : AExtraBuffer.Write', pbBuffPtr, cbIoBufferSize); {$ENDIF} AExtraBuffer.Position := AExtraBuffer.Position - Integer(cbIoBufferSize); Result := rcContinueAndMoreDataNeeded; end else begin Result := rcMoreDataNeeded; end; InExtraLoop := False; break; end; end; end; until not InExtraLoop; finally FreeMem(pbIoBuffer); end; end; procedure TclTlsSspi.EnumerateSecurityPackages(var APackagesCount: Cardinal; var APackageInfoArray: PSecPkgInfo); var ss: SECURITY_STATUS; begin ss := FunctionTable.EnumerateSecurityPackages(APackagesCount, PSecPkgInfo(APackageInfoArray)); SetSspiErrorIf(ss < SEC_E_OK, ss, SSPI_E_QueryPackageInfoFailed); end; procedure TclTlsSspi.DeleteContext; begin if ((FCtxtHandle.dwLower <> 0) or (FCtxtHandle.dwUpper <> 0)) then begin FunctionTable.DeleteSecurityContext(@FCtxtHandle); FCtxtHandle.dwLower := 0; FCtxtHandle.dwUpper := 0; end; end; procedure TclTlsSspi.DeleteCredentials; begin if ((FCredHandle.dwLower <> 0) or (FCredHandle.dwUpper <> 0)) then begin FunctionTable.FreeCredentialHandle(@FCredHandle); FCredHandle.dwLower := 0; FCredHandle.dwUpper := 0; end; end; constructor TclTlsSspi.Create; begin inherited Create(); FPackageNo := GetPackageNo(); TLSFlags := [tfUseTLS]; end; function TclTlsSspi.GenCredentials(ACertificates: TclCertificateList; AllowEmptyCred: Boolean; var ASecData: TSChannel_Cred; ACredentialUse: Cardinal): Boolean; var i: Integer; p: ^PCCERT_CONTEXT; tsExpiry: TTimeStamp; begin DeleteCredentials(); if AllowEmptyCred then begin Result := True; end else begin Result := (ACertificates.Count > 0); if not Result then Exit; end; if (ACertificates.Count > 0) then begin ASecData.cCreds := ACertificates.Count; FreeSChannelCred(ASecData); GetMem(ASecData.paCred, SizeOf(PCCERT_CONTEXT) * ACertificates.Count); for i := 0 to ACertificates.Count - 1 do begin p := Pointer(TclIntPtr(ASecData.paCred) + SizeOf(PCCERT_CONTEXT) * i); p^ := ACertificates[i].Context; end; end; FStatusCode := FunctionTable.AcquireCredentialsHandle( nil, // use the default principal GetPackageName(), ACredentialUse, nil, // use the default LOGON id @ASecData, nil, // no callback function needed to get a key nil, // no callback function arguments needed @FCredHandle, @tsExpiry); {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'AcquireCredentialsHandle, package name: %s', nil, [GetString_(GetPackageName())]); {$ENDIF} SetSspiErrorIf(FStatusCode < SEC_E_OK, FStatusCode, SSPI_E_AcquireFailed); end; procedure TclTlsSspi.FreePeerCertificate; begin FPeerCertificate.Free(); FPeerCertificate := nil; end; procedure TclTlsSspi.FreeSChannelCred(var ASecData: TSChannel_Cred); begin if (ASecData.paCred <> nil) then begin FreeMem(ASecData.paCred); ASecData.paCred := nil; end; end; destructor TclTlsSspi.Destroy; begin FreePeerCertificate(); DeleteContext(); DeleteCredentials(); inherited Destroy(); end; { TclTlsClientSspi } constructor TclTlsClientSspi.Create; begin inherited Create(); FTargetName := FloatToStr(Now); FCertified := False; FNewConversation := True; end; function TclTlsClientSspi.EndSession(ABuffer: TStream): TclSspiReturnCode; var OutBuffer: TSecBufferDesc; OutBuffers: array[0..1] of TSecBuffer; dwSSPIFlags, dwSSPIOutFlags: DWORD; tsExpiry: TTimeStamp; dwType: Cardinal; begin FNewConversation := True; FCertified := False; if ((FCtxtHandle.dwLower = 0) and (FCtxtHandle.dwUpper = 0)) then begin DeleteContext(); DeleteCredentials(); Result := rcOk; Exit; end; dwType := SCHANNEL_SHUTDOWN; dwSSPIFlags := ISC_REQ_SEQUENCE_DETECT + ISC_REQ_REPLAY_DETECT + ISC_REQ_CONFIDENTIALITY + ISC_REQ_EXTENDED_ERROR + ISC_REQ_ALLOCATE_MEMORY + ISC_REQ_STREAM; OutBuffer.ulVersion := SECBUFFER_VERSION; OutBuffer.cBuffers := 1; OutBuffer.pBuffers := @OutBuffers; OutBuffers[0].cbBuffer := sizeof(dwType); OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffers[0].pvBuffer := @dwType; FStatusCode := FunctionTable.ApplyControlToken(@FCtxtHandle, @OutBuffer); CheckSspiError(FStatusCode); OutBuffers[0].pvBuffer := nil; OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffers[0].cbBuffer := 0; OutBuffer.cBuffers := 1; OutBuffer.pBuffers := @OutBuffers; OutBuffer.ulVersion := SECBUFFER_VERSION; try FStatusCode := FunctionTable.InitializeSecurityContext( @FCredHandle, @FCtxtHandle, nil, dwSSPIFlags, 0, 0, nil, 0, @FCtxtHandle, @OutBuffer, @dwSSPIOutFlags, @tsExpiry); {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'InitializeSecurityContext'); {$ENDIF} Result := CheckSspiError(FStatusCode); if ((OutBuffers[0].pvBuffer <> nil) and (OutBuffers[0].cbBuffer <> 0)) then begin ABuffer.Size := 0; ABuffer.Write(OutBuffers[0].pvBuffer^, OutBuffers[0].cbBuffer); ABuffer.Position := 0; Result := rcCompleteNeeded; end; finally if (OutBuffers[0].pvBuffer <> nil) then begin FunctionTable.FreeContextBuffer(OutBuffers[0].pvBuffer); end; DeleteContext(); DeleteCredentials(); end; end; function TclTlsClientSspi.GenContext(ABuffer: TStream; ACertificates: TclCertificateList; AllowEmptyCred: Boolean): TclSspiReturnCode; var secData: TSChannel_Cred; begin ZeroMemory(@secData, Sizeof(secData)); try secData.dwVersion := SCHANNEL_CRED_VERSION; secData.dwFlags := SCH_CRED_MANUAL_CRED_VALIDATION + SCH_CRED_NO_DEFAULT_CREDS; secData.grbitEnabledProtocols := 0; if (tfUseSSL2 in TLSFlags) and (not (tfUseTLS12 in TLSFlags)) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_SSL2_CLIENT; end; if (tfUseSSL3 in TLSFlags) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_SSL3_CLIENT; end; if (tfUseTLS in TLSFlags) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_TLS1_CLIENT; end; if (tfUseTLS11 in TLSFlags) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_TLS1_1_CLIENT; end; if (tfUseTLS12 in TLSFlags) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_TLS1_2_CLIENT; end; if (FStatusCode = SEC_I_INCOMPLETE_CREDENTIALS) then begin if not GenCredentials(ACertificates, AllowEmptyCred, secData, SECPKG_CRED_OUTBOUND) then begin Result := rcCredentialNeeded; Exit; end; end; FStatusCode := SEC_I_CONTINUE_NEEDED; if FNewConversation then begin FNewConversation := False; Result := NewConversation(secData, ABuffer); end else begin Result := ContinueConversation(secData, ABuffer, ACertificates, AllowEmptyCred); end; if not FCertified and (Result in [rcOK, rcEncodeNeeded]) then begin FCertified := VerifyServerCertificate(); end; finally FreeSChannelCred(secData); end; end; function TclTlsClientSspi.NewConversation(var ASecData: TSChannel_Cred; ABuffer: TStream): TclSspiReturnCode; var OutBuffer: TSecBufferDesc; OutBuffers: array[0..1] of TSecBuffer; dwSSPIFlags, dwSSPIOutFlags: DWORD; tsExpiry: TTimeStamp; s: TclString; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'NewConversation');{$ENDIF} dwSSPIFlags := ISC_REQ_SEQUENCE_DETECT + ISC_REQ_REPLAY_DETECT + ISC_REQ_CONFIDENTIALITY + ISC_REQ_EXTENDED_ERROR + ISC_REQ_ALLOCATE_MEMORY + ISC_REQ_STREAM; DeleteCredentials(); FStatusCode := FunctionTable.AcquireCredentialsHandle( nil, // use the default principal GetPackageName(), SECPKG_CRED_OUTBOUND, nil, // use the default LOGON id @ASecData, nil, // no callback function needed to get a key nil, // no callback function arguments needed @FCredHandle, @tsExpiry); {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'AcquireCredentialsHandle, package name: %s', nil, [GetString_(GetPackageName())]); {$ENDIF} SetSspiErrorIf(FStatusCode < SEC_E_OK, FStatusCode, SSPI_E_AcquireFailed); OutBuffer.ulVersion := SECBUFFER_VERSION; OutBuffer.cBuffers := 1; OutBuffer.pBuffers := @OutBuffers; OutBuffers[0].cbBuffer := 0; OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffers[0].pvBuffer := nil; try s := GetTclString(TargetName); FStatusCode := FunctionTable.InitializeSecurityContext( @FCredHandle, nil, PclChar(s), dwSSPIFlags, 0, 0, nil, 0, @FCtxtHandle, @OutBuffer, @dwSSPIOutFlags, @tsExpiry ); {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'InitializeSecurityContext'); {$ENDIF} CheckSspiError(FStatusCode); ABuffer.Size := 0; ABuffer.Write(OutBuffers[0].pvBuffer^, OutBuffers[0].cbBuffer); ABuffer.Position := 0; {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'NewConversation, OutBuffers[0].pvBuffer', OutBuffers[0].pvBuffer, OutBuffers[0].cbBuffer); clPutLogMessage(Self, edInside, 'NewConversation, after InitializeSecurityContext dwSSPIOutFlags = $%x', nil, [dwSSPIOutFlags]); {$ENDIF} Result := rcAuthContinueNeeded; finally if (OutBuffers[0].pvBuffer <> nil) then begin FunctionTable.FreeContextBuffer(OutBuffers[0].pvBuffer); end; end; {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'NewConversation'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'NewConversation', E); raise; end; end;{$ENDIF} end; function TclTlsClientSspi.ContinueConversation(var ASecData: TSChannel_Cred; ABuffer: TStream; ACertificates: TclCertificateList; AllowEmptyCred: Boolean): TclSspiReturnCode; var InBuffer: TSecBufferDesc; InBuffers: array[0..1] of TSecBuffer; OutBuffer: TSecBufferDesc; OutBuffers: array[0..1] of TSecBuffer; dwSSPIFlags, dwSSPIOutFlags: DWORD; tsExpiry: TTimeStamp; NeedToRead: Boolean; buf: PclChar; size: Integer; s: TclString; begin {$IFDEF LOGGER}try clPutLogMessage(Self, edEnter, 'ContinueConversation');{$ENDIF} {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'ContinueConversation, ABuffer.Position = %d, ABuffer.Size = %d', nil, [ABuffer.Position, ABuffer.Size]); {$ENDIF} NeedToRead := False; Result := rcError; dwSSPIFlags := ISC_REQ_SEQUENCE_DETECT + ISC_REQ_REPLAY_DETECT + ISC_REQ_CONFIDENTIALITY + ISC_REQ_EXTENDED_ERROR + ISC_REQ_ALLOCATE_MEMORY + ISC_REQ_STREAM; buf := nil; try while ((FStatusCode = SEC_I_CONTINUE_NEEDED) or (FStatusCode = SEC_E_INCOMPLETE_MESSAGE) or (FStatusCode = SEC_I_INCOMPLETE_CREDENTIALS)) do begin {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'ContinueConversation, under while FStatusCode = $%x', nil, [Integer(FStatusCode)]); {$ENDIF} if (ABuffer.Size = 0) or (FStatusCode = SEC_E_INCOMPLETE_MESSAGE) then begin if NeedToRead then begin Result := rcAuthMoreDataNeeded; Break; end else begin NeedToRead := True; end; end; OutBuffer.ulVersion := SECBUFFER_VERSION; OutBuffer.cBuffers := 2; OutBuffer.pBuffers := @OutBuffers; OutBuffers[0].cbBuffer := 0; OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffers[0].pvBuffer := nil; OutBuffers[1].cbBuffer := 0; OutBuffers[1].BufferType := SECBUFFER_EMPTY; OutBuffers[1].pvBuffer := nil; InBuffer.ulVersion := SECBUFFER_VERSION; InBuffer.cBuffers := 2; InBuffer.pBuffers := @InBuffers; FreeMem(buf); buf := nil; size := ABuffer.Size - ABuffer.Position; if (size > 0) then begin GetMem(buf, size); ABuffer.Read(buf^, size); ABuffer.Position := ABuffer.Position - size; end; InBuffers[0].cbBuffer := size; InBuffers[0].BufferType := SECBUFFER_TOKEN; InBuffers[0].pvBuffer := buf; {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'ContinueConversation, InBuffers[0].pvBuffer', InBuffers[0].pvBuffer, InBuffers[0].cbBuffer); {$ENDIF} InBuffers[1].cbBuffer := 0; InBuffers[1].BufferType := SECBUFFER_EMPTY; InBuffers[1].pvBuffer := nil; s := GetTclString(TargetName); FStatusCode := FunctionTable.InitializeSecurityContext( @FCredHandle, @FCtxtHandle, PclChar(s), dwSSPIFlags, 0, 0, @InBuffer, 0, @FCtxtHandle, @OutBuffer, @dwSSPIOutFlags, @tsExpiry ); {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'InitializeSecurityContext'); clPutLogMessage(Self, edInside, 'ContinueConversation, after InitializeSecurityContext FStatusCode = $%x', nil, [Integer(FStatusCode)]); clPutLogMessage(Self, edInside, 'ContinueConversation, OutBuffers[0].pvBuffer', OutBuffers[0].pvBuffer, OutBuffers[0].cbBuffer); if (InBuffers[1].BufferType = SECBUFFER_EXTRA) then begin clPutLogMessage(Self, edInside, 'ContinueConversation, InBuffers[1] = SECBUFFER_EXTRA (' + IntToStr(InBuffers[1].cbBuffer)); end else begin clPutLogMessage(Self, edInside, 'ContinueConversation, InBuffers[1] = no extra data'); end; clPutLogMessage(Self, edInside, 'ContinueConversation, after InitializeSecurityContext dwSSPIOutFlags = $%x', nil, [dwSSPIOutFlags]); {$ENDIF} if (FStatusCode = SEC_E_OK) or (FStatusCode = SEC_I_CONTINUE_NEEDED) or (FAILED(FStatusCode) and ((dwSSPIOutFlags and ISC_RET_EXTENDED_ERROR) <> 0)) then begin if (OutBuffers[0].cbBuffer <> 0) and (OutBuffers[0].pvBuffer <> nil) then begin ABuffer.Size := 0; ABuffer.Write(OutBuffers[0].pvBuffer^, OutBuffers[0].cbBuffer); ABuffer.Position := 0; FunctionTable.FreeContextBuffer(OutBuffers[0].pvBuffer); OutBuffers[0].pvBuffer := nil; Result := rcAuthContinueNeeded; {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'ContinueConversation, inside if (FStatusCode = SEC_E_OK) or..., ABuffer.Position = %d, ABuffer.Size = %d', nil, [ABuffer.Position, ABuffer.Size]); {$ENDIF} Break; end; end; if (FStatusCode = SEC_E_INCOMPLETE_MESSAGE) then begin Result := rcAuthMoreDataNeeded; Break; end; if (FStatusCode = SEC_E_OK) then begin Result := rcOk; if (InBuffers[1].BufferType = SECBUFFER_EXTRA) then begin ABuffer.Position := ABuffer.Size - Integer(InBuffers[1].cbBuffer); Result := rcEncodeNeeded; end; Break; end; if (FStatusCode = SEC_I_INCOMPLETE_CREDENTIALS) then begin if not GenCredentials(ACertificates, AllowEmptyCred, ASecData, SECPKG_CRED_OUTBOUND) then begin Result := rcCredentialNeeded; end; NeedToRead := False; FStatusCode := SEC_I_INCOMPLETE_CREDENTIALS; if (Result = rcCredentialNeeded) then begin Break; end else begin continue; end; end; CheckSspiError(FStatusCode); if (InBuffers[1].BufferType = SECBUFFER_EXTRA) then begin ABuffer.Position := ABuffer.Size - Integer(InBuffers[1].cbBuffer); end else begin ABuffer.Size := 0; end; end; finally FreeMem(buf); end; {$IFDEF LOGGER} clPutLogMessage(Self, edInside, 'ContinueConversation, before end, ABuffer.Position = %d, ABuffer.Size = %d', nil, [ABuffer.Position, ABuffer.Size]); {$ENDIF} {$IFDEF LOGGER}clPutLogMessage(Self, edLeave, 'ContinueConversation'); except on E: Exception do begin clPutLogMessage(Self, edLeave, 'ContinueConversation', E); raise; end; end;{$ENDIF} end; function TclTlsClientSspi.VerifyServerCertificate: Boolean; const SECURITY_FLAG_IGNORE_REVOCATION = $00000080; SECURITY_FLAG_IGNORE_UNKNOWN_CA = $00000100; SECURITY_FLAG_IGNORE_WRONG_USAGE = $00000200; SECURITY_FLAG_IGNORE_CERT_CN_INVALID = $00001000; SECURITY_FLAG_IGNORE_CERT_DATE_INVALID = $00002000; var polHttps: HTTPSPolicyCallbackData; PolicyPara: CERT_CHAIN_POLICY_PARA; PolicyStatus: CERT_CHAIN_POLICY_STATUS; ChainPara: CERT_CHAIN_PARA; pChainContext: PCCERT_CHAIN_CONTEXT; remoteCertContext: PCCERT_CONTEXT; pwszServerName: PWCHAR; cchServerName: DWORD; begin FreePeerCertificate(); Result := True; cchServerName := MultiByteToWideChar(CP_ACP, 0, PclChar(GetTclString(TargetName)), -1, nil, 0); GetMem(pwszServerName, cchServerName * sizeof(WCHAR)); try SetSspiErrorIf(pwszServerName = nil, SEC_E_OUTOFMEMORY, SEC_E_OUTOFMEMORY); MultiByteToWideChar(CP_ACP, 0, PclChar(GetTclString(TargetName)), -1, pwszServerName, cchServerName); ZeroMemory(@ChainPara, sizeof(ChainPara)); ChainPara.cbSize := sizeof(ChainPara); FStatusCode := FunctionTable.QueryContextAttributes(@FCtxtHandle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, @remoteCertContext); CheckSspiError(FStatusCode); FPeerCertificate := TclCertificate.Create(remoteCertContext); pChainContext := nil; try SetSspiErrorIf( not CertGetCertificateChain( 0, remoteCertContext, nil, remoteCertContext^.hCertStore, @ChainPara, 0, nil, @pChainContext), SECURITY_STATUS(GetLastError()), SSPI_E_WhileVerify); ZeroMemory(@polHttps, sizeof(HTTPSPolicyCallbackData)); polHttps.cbSize := sizeof(HTTPSPolicyCallbackData); polHttps.dwAuthType := AUTHTYPE_SERVER; polHttps.fdwChecks := 0; if cfIgnoreCommonNameInvalid in CertificateFlags then polHttps.fdwChecks := polHttps.fdwChecks or SECURITY_FLAG_IGNORE_CERT_CN_INVALID; if cfIgnoreDateInvalid in CertificateFlags then polHttps.fdwChecks := polHttps.fdwChecks or SECURITY_FLAG_IGNORE_CERT_DATE_INVALID; if cfIgnoreUnknownAuthority in CertificateFlags then polHttps.fdwChecks := polHttps.fdwChecks or SECURITY_FLAG_IGNORE_UNKNOWN_CA; if cfIgnoreRevocation in CertificateFlags then polHttps.fdwChecks := polHttps.fdwChecks or SECURITY_FLAG_IGNORE_REVOCATION; if cfIgnoreWrongUsage in CertificateFlags then polHttps.fdwChecks := polHttps.fdwChecks or SECURITY_FLAG_IGNORE_WRONG_USAGE; polHttps.pwszServerName := pwszServerName; ZeroMemory(@PolicyPara, sizeof(PolicyPara)); PolicyPara.cbSize := sizeof(PolicyPara); PolicyPara.pvExtraPolicyPara := @polHttps; ZeroMemory(@PolicyStatus, sizeof(PolicyStatus)); PolicyStatus.cbSize := sizeof(PolicyStatus); SetSspiErrorIf( not CertVerifyCertificateChainPolicy( CERT_CHAIN_POLICY_SSL, pChainContext, @PolicyPara, @PolicyStatus), SECURITY_STATUS(GetLastError()), SSPI_E_WhileVerify); if (PolicyStatus.dwError <> 0) then begin FStatusCode := Longint(PolicyStatus.dwError); Result := False; end; finally if (pChainContext <> nil) then begin CertFreeCertificateChain(pChainContext); end; if (remoteCertContext <> nil) then CertFreeCertificateContext(remoteCertContext); end; finally FreeMem(pwszServerName); end; end; { TclTlsServerSspi } constructor TclTlsServerSspi.Create; begin inherited Create(); FNewConversation := True; FRequireClientCertificate := False; end; function TclTlsServerSspi.EndSession(ABuffer: TStream): TclSspiReturnCode; var OutBuffer: TSecBufferDesc; OutBuffers: array[0..1] of TSecBuffer; dwSSPIFlags, dwSSPIOutFlags: DWORD; tsExpiry: TTimeStamp; dwType: Cardinal; begin FNewConversation := True; FCertified := False; if ((FCtxtHandle.dwLower = 0) and (FCtxtHandle.dwUpper = 0)) then begin DeleteContext(); DeleteCredentials(); Result := rcOk; Exit; end; dwType := SCHANNEL_SHUTDOWN; dwSSPIFlags := ASC_REQ_SEQUENCE_DETECT + ASC_REQ_REPLAY_DETECT + ASC_REQ_CONFIDENTIALITY + ASC_REQ_EXTENDED_ERROR + ASC_REQ_ALLOCATE_MEMORY + ASC_REQ_STREAM; OutBuffer.ulVersion := SECBUFFER_VERSION; OutBuffer.cBuffers := 1; OutBuffer.pBuffers := @OutBuffers; OutBuffers[0].cbBuffer := sizeof(dwType); OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffers[0].pvBuffer := @dwType; FStatusCode := FunctionTable.ApplyControlToken(@FCtxtHandle, @OutBuffer); CheckSspiError(FStatusCode); OutBuffers[0].pvBuffer := nil; OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffers[0].cbBuffer := 0; OutBuffer.cBuffers := 1; OutBuffer.pBuffers := @OutBuffers; OutBuffer.ulVersion := SECBUFFER_VERSION; try FStatusCode := FunctionTable.AcceptSecurityContext( @FCredHandle, @FCtxtHandle, nil, dwSSPIFlags, 0, nil, @OutBuffer, @dwSSPIOutFlags, @tsExpiry ); Result := CheckSspiError(FStatusCode); if ((OutBuffers[0].pvBuffer <> nil) and (OutBuffers[0].cbBuffer <> 0)) then begin ABuffer.Size := 0; ABuffer.Write(OutBuffers[0].pvBuffer^, OutBuffers[0].cbBuffer); ABuffer.Position := 0; Result := rcCompleteNeeded; end; finally if (OutBuffers[0].pvBuffer <> nil) then begin FunctionTable.FreeContextBuffer(OutBuffers[0].pvBuffer); end; DeleteContext(); DeleteCredentials(); end; end; function TclTlsServerSspi.GenContext(ABuffer: TStream; ACertificates: TclCertificateList; AllowEmptyCred: Boolean): TclSspiReturnCode; var InBuffer: TSecBufferDesc; InBuffers: array[0..1] of TSecBuffer; OutBuffer: TSecBufferDesc; OutBuffers: array[0..1] of TSecBuffer; dwSSPIFlags, dwSSPIOutFlags: DWORD; tsExpiry: TTimeStamp; pCtxt: PCtxtHandle; secData: TSChannel_Cred; buf: PclChar; begin ZeroMemory(@secData, Sizeof(secData)); try secData.dwVersion := SCHANNEL_CRED_VERSION; secData.dwFlags := 0; secData.grbitEnabledProtocols := 0; if (tfUseSSL2 in TLSFlags) and (not (tfUseTLS12 in TLSFlags)) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_SSL2_SERVER; end; if (tfUseSSL3 in TLSFlags) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_SSL3_SERVER; end; if (tfUseTLS in TLSFlags) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_TLS1_SERVER; end; if (tfUseTLS11 in TLSFlags) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_TLS1_1_SERVER; end; if (tfUseTLS12 in TLSFlags) then begin secData.grbitEnabledProtocols := secData.grbitEnabledProtocols or SP_PROT_TLS1_2_SERVER; end; if FNewConversation then begin if not GenCredentials(ACertificates, AllowEmptyCred, secData, SECPKG_CRED_INBOUND) then begin Result := rcCredentialNeeded; Exit; end; end; OutBuffer.ulVersion := SECBUFFER_VERSION; OutBuffer.cBuffers := 1; OutBuffer.pBuffers := @OutBuffers; OutBuffers[0].cbBuffer := 0; OutBuffers[0].BufferType := SECBUFFER_TOKEN; OutBuffers[0].pvBuffer := nil; buf := nil; try FStatusCode := SEC_I_CONTINUE_NEEDED; dwSSPIFlags := ASC_REQ_SEQUENCE_DETECT + ASC_REQ_REPLAY_DETECT + ASC_REQ_CONFIDENTIALITY + ASC_REQ_EXTENDED_ERROR + ASC_REQ_ALLOCATE_MEMORY + ASC_REQ_STREAM; if RequireClientCertificate then begin dwSSPIFlags := dwSSPIFlags or ASC_REQ_MUTUAL_AUTH; end; InBuffer.ulVersion := SECBUFFER_VERSION; InBuffer.cBuffers := 1; InBuffer.pBuffers := @InBuffers; if (ABuffer.Size > 0) then begin GetMem(buf, ABuffer.Size); ABuffer.Position := 0; ABuffer.Read(buf^, ABuffer.Size); end; InBuffers[0].cbBuffer := ABuffer.Size; InBuffers[0].BufferType := SECBUFFER_TOKEN; InBuffers[0].pvBuffer := buf; pCtxt := nil; if not FNewConversation then begin pCtxt := @FCtxtHandle; end; FStatusCode := FunctionTable.AcceptSecurityContext( @FCredHandle, pCtxt, @InBuffer, dwSSPIFlags, 0, @FCtxtHandle, @OutBuffer, @dwSSPIOutFlags, @tsExpiry ); CheckSspiError(FStatusCode); if (FStatusCode = SEC_I_COMPLETE_NEEDED) or (FStatusCode = SEC_I_COMPLETE_AND_CONTINUE) then begin FStatusCode := FunctionTable.CompleteAuthToken(@FCtxtHandle, @OutBuffer); CheckSspiError(FStatusCode); end; ABuffer.Size := 0; ABuffer.Write(OutBuffers[0].pvBuffer^, OutBuffers[0].cbBuffer); ABuffer.Position := 0; finally if (OutBuffers[0].pvBuffer <> nil) then begin FunctionTable.FreeContextBuffer(OutBuffers[0].pvBuffer); end; FreeMem(buf); end; FNewConversation := False; if (SEC_I_CONTINUE_NEEDED = FStatusCode) or (SEC_I_COMPLETE_AND_CONTINUE = FStatusCode) then begin Result := rcAuthContinueNeeded; end else begin if RequireClientCertificate and (not FCertified) then begin GetClientCertificate(); end; Result := rcOk; FCertified := True; end; finally FreeSChannelCred(secData); end; end; procedure TclTlsServerSspi.GetClientCertificate; var remoteCertContext: PCCERT_CONTEXT; begin remoteCertContext := nil; try FStatusCode := FunctionTable.QueryContextAttributes(@FCtxtHandle, SECPKG_ATTR_REMOTE_CERT_CONTEXT, @remoteCertContext); CheckSspiError(FStatusCode); FPeerCertificate := TclCertificate.Create(remoteCertContext); finally if (remoteCertContext <> nil) then CertFreeCertificateContext(remoteCertContext); end; end; end.
unit ReverseGeocodeAddressUnit; interface uses SysUtils, BaseExampleUnit, DirectionPathPointUnit; type TReverseGeocodeAddress = class(TBaseExample) public procedure Execute(Location: TDirectionPathPoint); end; implementation uses GeocodingUnit; procedure TReverseGeocodeAddress.Execute(Location: TDirectionPathPoint); var ErrorString: String; Geocoding: TGeocodingList; i: integer; begin Geocoding := Route4MeManager.Geocoding.ReverseGeocodeAddress(Location, ErrorString); try WriteLn(''); if (Geocoding.Count > 0) then begin WriteLn('ReverseGeocodeAddress executed successfully'); for i := 0 to Geocoding.Count - 1 do if Geocoding[i].Destination.IsNotNull then WriteLn(Format('Destination: %s', [Geocoding[i].Destination.Value])); end else WriteLn(Format('ReverseGeocodeAddress error: "%s"', [ErrorString])); finally FreeAndNil(Geocoding); end; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: TSysLogServer class encapsulate the server side of the SysLog protocol as described in RFC3164. Creation: September 2009 Version: 1.01 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 2009 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: Feb 08, 2010 V1.01 F. Piette used SYSLOG_NILVALUE instead of '-'. Tested this value for hostname and process which can be nil. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsSysLogServer; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ALIGN 8} {$I OverbyteIcsDefs.inc} interface uses Windows, SysUtils, Classes, Winsock, OverbyteIcsWinSock, OverbyteIcsSysLogDefs, OverbyteIcsWSocket; type TSysLogServerDataAvailable = procedure (Sender : TObject; const SrcIP, SrcPort : AnsiString; const RawMessage : AnsiString) of object; ESysLogParseException = class(Exception); TSysLogData = record PID : Integer; PRI : Integer; Facility : TSysLogFacility; Severity : TSysLogSeverity; Text : AnsiString; Process : String; HostName : String; Year : Word; Month : Word; Day : Word; Hour : Word; Minute : Word; Second : Word; MilliSec : Word; TimeString : String; RFC5424 : Boolean; // The remaining members are only valid when an RFC5424 message is received MsgVer : Integer; MsgID : String; StructData : String; TZBias : TDateTime; end; TSysLogServer = class(TComponent) protected FUdpSocket : TWSocket; FAddr : String; FPort : String; FRelaxedSyntax : Boolean; FOnDataAvailable : TSysLogServerDataAvailable; procedure UdpDataAvailable(Sender: TObject; ErrCode : Word); public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Listen; procedure Close; procedure ParseRawMessage(const RawMessage : AnsiString; out DecodedMessage : TSysLogData); procedure ParseRawMessageRFC3164(const RawMessage : AnsiString; out DecodedMessage : TSysLogData); procedure ParseRawMessageRFC5424(const RawMessage : AnsiString; out DecodedMessage : TSysLogData); procedure HandleMalformedMessage(const RawMessage : AnsiString; out DecodedMessage : TSysLogData; Offset : Integer = 1); published property Addr : String read FAddr write FAddr; property Port : String read FPort write FPort; property RelaxedSyntax : Boolean read FRelaxedSyntax write FRelaxedSyntax; property OnDataAvailable : TSysLogServerDataAvailable read FOnDataAvailable write FOnDataAvailable; end; implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TSysLogServer.Create(AOwner: TComponent); begin inherited Create(AOwner); FUdpSocket := TWSocket.Create(Self); FPort := '514'; FAddr := '0.0.0.0'; // isten on all interfaces FRelaxedSyntax := TRUE; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TSysLogServer.Destroy; begin FreeAndNil(FUdpSocket); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogServer.Listen; begin FUdpSocket.Proto := 'udp'; FUdpSocket.Port := FPort; FUdpSocket.Addr := FAddr; FUdpSocket.OnDataAvailable := UdpDataAvailable; FUdpSocket.Listen; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogServer.Close; begin FUdpSocket.Close; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetDigits(const RawMessage : AnsiString; var Index : Integer) : String; var I : Integer; begin I := Index; while (Index > 0) and (Index <= Length(RawMessage)) and (RawMessage[Index] >= '0') and (RawMessage[Index] <= '9') do Inc(Index); if Index <= I then Result := '' else Result := String(Copy(RawMessage, I, Index - I)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} // Accept alphanumeric, underline and dot characters function GetWord(const RawMessage : AnsiString; var Index : Integer) : String; var I : Integer; begin I := Index; while (Index > 0) and (Index <= Length(RawMessage)) and ( ((RawMessage[Index] >= 'A') and (RawMessage[Index] <= 'Z')) or ((RawMessage[Index] >= 'a') and (RawMessage[Index] <= 'z')) or ((RawMessage[Index] >= '0') and (RawMessage[Index] <= '9')) or (RawMessage[Index] = '.') or (RawMessage[Index] = '-') or (RawMessage[Index] = '_') ) do Inc(Index); if Index <= I then Result := '' else Result := String(Copy(RawMessage, I, Index - I)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure SkipSpaces(const RawMessage : AnsiString; var Index : Integer); begin while (Index > 0) and (Index <= Length(RawMessage)) and (RawMessage[Index] = ' ') do Inc(Index); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetStructData( const RawMessage : AnsiString; var Index : Integer) : String; var I : Integer; Bracket : Integer; begin Result := ''; Bracket := 0; I := Index; while (Index > 0) and (Index <= Length(RawMessage)) do begin if RawMessage[Index] = '[' then begin Inc(Bracket); end else if RawMessage[Index] = ']' then begin Dec(Bracket); Inc(Index); if (Index <= Length(RawMessage)) and (RawMessage[Index] = '[') then begin Continue; end; break; end else if RawMessage[Index] = '\' then begin if RawMessage[Index + 1] in ['"', '\', ']'] then Inc(Index); end; Inc(Index); end; if Bracket <> 0 then raise ESysLogParseException.Create( 'SysLog message has invalid structured data ("' + String(RawMessage) + '"'); if Index <= I then Result := '' else Result := String(Copy(RawMessage, I, Index - I)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IsDigit(const Ch : AnsiChar) : Boolean; begin Result := (Ch >= '0') and (Ch <= '9'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogServer.ParseRawMessage( const RawMessage : AnsiString; out DecodedMessage : TSysLogData); var Index : Integer; PRI : String; Buf : AnsiString; begin // RFC 5424 has version number immediately after PRI while RFC 3164 // has a time stamp starting by the month name. Version number has maximum // 2 digits. // RFC5424: <13>1 2009-09-23T14:30:45.003+02:00.... // RFC3164: <13>Sep 23 14:30:45.... if (Length(RawMessage) > 0) and (RawMessage[1] <> '<') then begin // Simplified SysLog message is handled by RFC3164 variant ParseRawMessageRFC3164(RawMessage, DecodedMessage); end else begin Index := 2; PRI := GetDigits(RawMessage, Index); if (Index > Length(RawMessage)) or (RawMessage[Index] <> '>') then raise ESysLogParseException.Create( 'SysLog message has invalid PRI delimiter ("' + String(RawMessage) + '"'); Inc(Index); if Index > Length(RawMessage) then raise ESysLogParseException.Create( 'SysLog message too short ("' + String(RawMessage) + '"'); Buf := Copy(RawMessage, Index, 21); if (Length(Buf) = 21) and (IsDigit(RawMessage[Index])) and (RawMessage[Index + 1] = ' ') and (IsDigit(RawMessage[Index + 2])) and (IsDigit(RawMessage[Index + 3])) and (IsDigit(RawMessage[Index + 4])) and (IsDigit(RawMessage[Index + 5])) and (RawMessage[Index + 6] = '-') and (IsDigit(RawMessage[Index + 7])) and (IsDigit(RawMessage[Index + 8])) and (RawMessage[Index + 9] = '-') and (IsDigit(RawMessage[Index + 10])) and (IsDigit(RawMessage[Index + 11])) and (RawMessage[Index + 12] = 'T') and (IsDigit(RawMessage[Index + 13])) and (IsDigit(RawMessage[Index + 14])) and (RawMessage[Index + 15] = ':') and (IsDigit(RawMessage[Index + 16])) and (IsDigit(RawMessage[Index + 17])) and (RawMessage[Index + 18] = ':') and (IsDigit(RawMessage[Index + 19])) and (IsDigit(RawMessage[Index + 20])) then ParseRawMessageRFC5424(RawMessage, DecodedMessage) else ParseRawMessageRFC3164(RawMessage, DecodedMessage); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogServer.ParseRawMessageRFC5424( const RawMessage : AnsiString; out DecodedMessage : TSysLogData); var Index : Integer; Index1 : Integer; PRI : String; NPRI : Integer; SVer : String; SYear : String; SMonth : String; SDay : String; SHour : String; SMinute : String; SSecond : String; SMSec : String; Delim : AnsiChar; SPID : String; begin DecodedMessage.RFC5424 := TRUE; // <13>1 2009-09-13T16:44:31.000+02:00 Toshiba3 OverbyteIcsSysLogClientDemo 5448 ID47 [exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"] Hello http://www.OverByte.be if Length(RawMessage) < 21 then raise ESysLogParseException.Create( 'SysLog message too short ("' + String(RawMessage) + '"'); if RawMessage[1] <> '<' then raise ESysLogParseException.Create( 'SysLog message must start with ''<'' ("' + String(RawMessage) + '"'); Index := 2; PRI := GetDigits(RawMessage, Index); if (Index > Length(RawMessage)) or (RawMessage[Index] <> '>') then raise ESysLogParseException.Create( 'SysLog message has invalid PRI delimiter ("' + String(RawMessage) + '"'); if PRI = '' then raise ESysLogParseException.Create( 'SysLog message has invalid PRI ("' + String(RawMessage) + '"'); NPRI := StrToIntDef(PRI, -1); if (NPRI < (Ord(Low(TSysLogFacility)) * 8 + Ord(Low(TSysLogSeverity)))) or (NPRI > (Ord(High(TSysLogFacility)) * 8 + Ord(High(TSysLogSeverity)))) then raise ESysLogParseException.Create( 'SysLog message has invalid PRI ("' + String(RawMessage) + '"'); DecodedMessage.PRI := NPRI; DecodedMessage.Severity := TSysLogSeverity(NPRI mod 8); DecodedMessage.Facility := TSysLogFacility(NPRI div 8); Inc(Index); if (RawMessage[Index] < '0') and (RawMessage[Index] > '9') then raise ESysLogParseException.Create( 'SysLog message has invalid version number ("' + String(RawMessage) + '"'); SVer := GetDigits(RawMessage, Index); DecodedMessage.MsgVer := StrToIntDef(SVer, -1); if DecodedMessage.MsgVer <> 1 then raise ESysLogParseException.Create( 'SysLog message has unsupported version number ("' + String(RawMessage) + '"'); if (Index > Length(RawMessage)) or (RawMessage[Index] <> ' ') then raise ESysLogParseException.Create( 'SysLog message has missing space after version ("' + String(RawMessage) + '"'); Inc(Index); // 2009-09-13T16:44:31.000+02:00 Index1 := Index; SYear := GetDigits(RawMessage, Index); if (SYear = '') or (Index > Length(RawMessage)) or (RawMessage[Index] <> '-') then raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); Inc(Index); SMonth := GetDigits(RawMessage, Index);; if (SMonth = '') or (Index > Length(RawMessage)) or (RawMessage[Index] <> '-') then raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); Inc(Index); SDay := GetDigits(RawMessage, Index); if (SDay = '') or (Index > Length(RawMessage)) or (RawMessage[Index] <> 'T') then raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); Inc(Index); SHour := GetDigits(RawMessage, Index); if (SHour = '') or (Index > Length(RawMessage)) or (RawMessage[Index] <> ':') then raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); Inc(Index); SMinute := GetDigits(RawMessage, Index); if (SMinute = '') or (Index > Length(RawMessage)) or (RawMessage[Index] <> ':') then raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); Inc(Index); SSecond := GetDigits(RawMessage, Index); if (SSecond = '') or (Index > Length(RawMessage)) then raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); Delim := RawMessage[Index]; if Delim = '.' then begin Inc(Index); SMSec := GetDigits(RawMessage, Index); Delim := RawMessage[Index]; end else begin SMSec := '0'; end; SMsec := '0' + DecimalSeparator + SMSec; DecodedMessage.Year := StrToInt(SYear); DecodedMessage.Month := StrToInt(SMonth); DecodedMessage.Day := StrToInt(SDay); DecodedMessage.Hour := StrToInt(SHour); DecodedMessage.Minute := StrToInt(SMinute); DecodedMessage.Second := StrToInt(SSecond); DecodedMessage.MilliSec := Trunc(1000 * StrToFloat(SMsec)); case Delim of 'Z', ' ' : DecodedMessage.TZBias := 0; '+', '-' : begin Inc(Index); SHour := GetDigits(RawMessage, Index); if (SHour = '') or (Index > Length(RawMessage)) or (RawMessage[Index] <> ':') then raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); Inc(Index); SMinute := GetDigits(RawMessage, Index); if (SMinute = '') or (Index > Length(RawMessage)) or (RawMessage[Index] <> ' ') then raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); DecodedMessage.TZBias := EncodeTime(StrToInt(SHour), StrToInt(SMinute), 0, 0); if Delim = '-' then DecodedMessage.TZBias := -DecodedMessage.TZBias; end; else raise ESysLogParseException.Create( 'SysLog message has invalid date format ("' + String(RawMessage) + '"'); end; DecodedMessage.TimeString := String(Copy(RawMessage, Index1, Index - Index1)); if (Index > Length(RawMessage)) or (RawMessage[Index] <> ' ') then raise ESysLogParseException.Create( 'SysLog message has missing space after date ("' + String(RawMessage) + '"'); SkipSpaces(RawMessage, Index); if RawMessage[Index] = SYSLOG_NILVALUE then DecodedMessage.HostName := '' else DecodedMessage.HostName := GetWord(RawMessage, Index); SkipSpaces(RawMessage, Index); if RawMessage[Index] = SYSLOG_NILVALUE then DecodedMessage.Process := '' else DecodedMessage.Process := GetWord(RawMessage, Index); SkipSpaces(RawMessage, Index); if Index > Length(RawMessage) then raise ESysLogParseException.Create( 'SysLog message too short ("' + String(RawMessage) + '"'); if RawMessage[Index] = SYSLOG_NILVALUE then begin DecodedMessage.PID := 0; Inc(Index); end else begin SPID := GetDigits(RawMessage, Index); DecodedMessage.PID := StrToIntDef(SPID, 0); end; if RawMessage[Index] <> ' ' then raise ESysLogParseException.Create( 'SysLog message has invalid PID delimter ("' + String(RawMessage) + '"'); SkipSpaces(RawMessage, Index); DecodedMessage.MsgID := GetWord(RawMessage, Index); SkipSpaces(RawMessage, Index); Delim := RawMessage[Index]; if Delim = '[' then DecodedMessage.StructData := GetStructData(RawMessage, Index) else DecodedMessage.StructData := ''; if (Index <= Length(RawMessage)) and (RawMessage[Index] = ' ') then Inc(Index); if Index > Length(RawMessage) then DecodedMessage.Text := '' else DecodedMessage.Text := Copy(RawMessage, Index, MAXINT); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogServer.HandleMalformedMessage( const RawMessage : AnsiString; out DecodedMessage : TSysLogData; Offset : Integer = 1); var Today : TDateTime; MilliSec : Word; begin DecodedMessage.PID := 0; DecodedMessage.Facility := SYSLOG_FACILITY_USER; DecodedMessage.Severity := SYSLOG_SEVERITY_NOTICE; DecodedMessage.PRI := Ord(DecodedMessage.Facility) * 8 + Ord(DecodedMessage.Severity); DecodedMessage.Text := Copy(RawMessage, Offset, MAXINT); DecodedMessage.Process := ''; DecodedMessage.HostName := ''; Today := Now; DecodeDate(Today, DecodedMessage.Year, DecodedMessage.Month, DecodedMessage.Day); DecodeTime(Today, DecodedMessage.Hour, DecodedMessage.Minute, DecodedMessage.Second, MilliSec); DecodedMessage.TimeString := Format('%s %2d %02.2d:%02.2d:%02.2d', [SysLogMonthNames[DecodedMessage.Month], DecodedMessage.Day, DecodedMessage.Hour, DecodedMessage.Minute, DecodedMessage.Second]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogServer.ParseRawMessageRFC3164( const RawMessage : AnsiString; out DecodedMessage : TSysLogData); var Index : Integer; PRI : String; NPRI : Integer; IPRI : Integer; MonthName : String; SDay : String; SHour : String; SMinute : String; SSecond : String; SPID : String; Today : TDateTime; begin DecodedMessage.RFC5424 := FALSE; // <13>Sep 8 14:37:40 MyHostName MyProcess[1234]: This is my message text if (Length(RawMessage) > 0) and (RawMessage[1] <> '<') then begin // There is a special case where the syslog message is just the text if FRelaxedSyntax then begin HandleMalformedMessage(RawMessage, DecodedMessage); Exit; end else raise ESysLogParseException.Create( 'SysLog message has invalid priority ("' + String(RawMessage) + '")'); end; if Length(RawMessage) < 21 then raise ESysLogParseException.Create( 'SysLog message too short ("' + String(RawMessage) + '")'); if RawMessage[1] <> '<' then raise ESysLogParseException.Create( 'SysLog message must start with ''<'' ("' + String(RawMessage) + '")'); Index := 2; PRI := GetDigits(RawMessage, Index); if (Index > Length(RawMessage)) or (RawMessage[Index] <> '>') then raise ESysLogParseException.Create( 'SysLog message has invalid PRI delimiter ("' + String(RawMessage) + '")'); if PRI = '' then raise ESysLogParseException.Create( 'SysLog message has invalid PRI ("' + String(RawMessage) + '")'); NPRI := StrToIntDef(PRI, -1); if (NPRI < (Ord(Low(TSysLogFacility)) * 8 + Ord(Low(TSysLogSeverity)))) or (NPRI > (Ord(High(TSysLogFacility)) * 8 + Ord(High(TSysLogSeverity)))) then raise ESysLogParseException.Create( 'SysLog message has invalid PRI ("' + String(RawMessage) + '")'); DecodedMessage.PRI := NPRI; DecodedMessage.Severity := TSysLogSeverity(NPRI mod 8); DecodedMessage.Facility := TSysLogFacility(NPRI div 8); Inc(Index); IPRI := Index; Today := Now; DecodeDate(Today, DecodedMessage.Year, DecodedMessage.Month, DecodedMessage.Day); MonthName := GetWord(RawMessage, Index); if Length(MonthName) <> 3 then begin if FRelaxedSyntax then begin HandleMalformedMessage(RawMessage, DecodedMessage, IPRI); Exit; end else raise ESysLogParseException.Create( 'SysLog message has invalid month in date ("' + String(RawMessage) + '")'); end; if (Index > Length(RawMessage)) or (RawMessage[Index] <> ' ') then raise ESysLogParseException.Create( 'SysLog message has missing space after month name in date ("' + String(RawMessage) + '")'); DecodedMessage.Month := 1; while (DecodedMessage.Month <= 12) and (not SameText(SysLogMonthNames[DecodedMessage.Month], MonthName)) do Inc(DecodedMessage.Month); if DecodedMessage.Month > 12 then begin // We have a bad month name. Assume we have a malformed SysLog message if FRelaxedSyntax then begin HandleMalformedMessage(RawMessage, DecodedMessage, IPRI); Exit; end else raise ESysLogParseException.Create( 'SysLog message has invalid month in date ("' + String(RawMessage) + '")'); end; SkipSpaces(RawMessage, Index); SDay := GetDigits(RawMessage, Index); if (Index > Length(RawMessage)) or (RawMessage[Index] <> ' ') then raise ESysLogParseException.Create( 'SysLog message has missing space after day in date ("' + String(RawMessage) + '")'); DecodedMessage.Day := StrToIntDef(SDay, -1); if (DecodedMessage.Day <= 0) or (DecodedMessage.Day > 31) then raise ESysLogParseException.Create( 'SysLog message has invalid day number ("' + String(RawMessage) + '")'); // <13>Sep 8 14:37:40 MyHostName MyProcess[1234]: This is my message text SkipSpaces(RawMessage, Index); SHour := GetDigits(RawMessage, Index); if (Index > Length(RawMessage)) or (RawMessage[Index] <> ':') then raise ESysLogParseException.Create( 'SysLog message has invalid time delimiter ("' + String(RawMessage) + '")'); DecodedMessage.Hour := StrToIntDef(SHour, 99); Inc(Index); SMinute := GetDigits(RawMessage, Index); if (Index > Length(RawMessage)) or (RawMessage[Index] <> ':') then raise ESysLogParseException.Create( 'SysLog message has invalid time delimiter ("' + String(RawMessage) + '")'); DecodedMessage.Minute := StrToIntDef(SMinute, 99); Inc(Index); SSecond := GetDigits(RawMessage, Index); if (Index > Length(RawMessage)) or (RawMessage[Index] <> ' ') then raise ESysLogParseException.Create( 'SysLog message has missing space after time ("' + String(RawMessage) + '")'); DecodedMessage.Second := StrToIntDef(SSecond, 99); if (DecodedMessage.Hour > 23) or (DecodedMessage.Minute > 59) or (DecodedMessage.Second > 59) then raise ESysLogParseException.Create( 'SysLog message has invalid time ("' + String(RawMessage) + '")'); DecodedMessage.TimeString := Format('%s %2d %02.2d:%02.2d:%02.2d', [SysLogMonthNames[DecodedMessage.Month], DecodedMessage.Day, DecodedMessage.Hour, DecodedMessage.Minute, DecodedMessage.Second]); SkipSpaces(RawMessage, Index); DecodedMessage.HostName := GetWord(RawMessage, Index); SkipSpaces(RawMessage, Index); DecodedMessage.Process := GetWord(RawMessage, Index); if (Index <= Length(RawMessage)) and (RawMessage[Index] = '[') then begin Inc(Index); SPID := GetDigits(RawMessage, Index); DecodedMessage.PID := StrToIntDef(SPID, 0); if RawMessage[Index] <> ']' then raise ESysLogParseException.Create( 'SysLog message has invalid PID delimter ("' + String(RawMessage) + '")'); Inc(Index); end; if (Index > Length(RawMessage)) or (RawMessage[Index] <> ':') then raise ESysLogParseException.Create( 'SysLog message has invalid content delimiter ("' + String(RawMessage) + '")'); Inc(Index); if (Index <= Length(RawMessage)) and (RawMessage[Index] = ' ') then Inc(Index); if Index > Length(RawMessage) then DecodedMessage.Text := '' else DecodedMessage.Text := Copy(RawMessage, Index, MAXINT); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TSysLogServer.UdpDataAvailable(Sender: TObject; ErrCode: Word); var RawMessage : AnsiString; Len : Integer; Src : TSockAddrIn; SrcLen : Integer; SrcIP : AnsiString; SrcPort : AnsiString; begin SrcLen := SizeOf(Src); Len := FUdpSocket.RcvdCount; SetLength(RawMessage, Len); Len := FUdpSocket.ReceiveFrom(@RawMessage[1], Length(RawMessage), Src, SrcLen); if Len < 0 then Exit; SetLength(RawMessage, Len); SrcIP := StrPas(inet_ntoa(Src.sin_addr)); SrcPort := AnsiString(IntToStr(ntohs(Src.sin_port))); if Assigned(FOnDataAvailable) then FOnDataAvailable(Self, SrcIP, SrcPort, RawMessage); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
program Smile; uses graphabc; {Процедура для рисования неизменяемых частей смайла - тела, глаз, носа} procedure DrawSmileStaticParts(); begin {Рисуем тело смайла} SetBrushColor(clYellow); Circle(300, 250, 120); {Рисуем глаза смайла} SetBrushColor(clBlack); Circle(250, 210, 20); Circle(350, 210, 20); {Рисуем зрачки смайла} SetBrushColor(clRed); Circle(250, 210, 10); Circle(350, 210, 10); SetBrushColor(clBlack); {Рисуем брови смайла} Line(250,170,270,190); Line(350,170,330,190); {Рисуем нос смайла} Circle(300, 270, 15); end; {Процедура для рисования подвижной части смайла - рта} procedure DrawAnimatedSmileParts(i : integer); begin {Рисуем рот смайла} Arc(300, 240, 90 , 0 - i, -180 + i); end; {Процедура для рисования всего смайла} procedure DrawSmile(i : integer); begin {Рисуем неизменяемые части смайла - тело, глаза, нос} DrawSmileStaticParts(); {Рисуем подвижную часть смайла - рот} DrawAnimatedSmileParts(i); end; var i : integer; begin {Устанавливаем параметры окна программы} SetWindowSize(600, 500); SetWindowTitle('AniSmile'); SetPenWidth(4); while true do begin for i := 0 to 180 do begin ClearWindow(); {Рисуем смайл} DrawSmile(i); Sleep(50); end; end; end.
unit MainForm; interface uses {$REGION 'system'} Winapi.Windows, Winapi.Messages, IniFiles, System.SysUtils, System.Variants, System.Classes, System.ImageList, System.UITypes, System.Actions, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Menus, Vcl.ComCtrls, Vcl.ImgList, Vcl.ToolWin, Vcl.ActnMan, Vcl.ActnCtrls, Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, WUpdate, JvChangeNotify, JvComponentBase, JvMenus, JvExControls, JvExComCtrls, JvToolBar, JvBaseDlg, JvSelectDirectory, JvDragDrop, JvSearchFiles, JvFormMagnet, JvPageList, JvPageListTreeView, JvExStdCtrls, JvRichEdit, ShellAPI, Generics.Collections, {$ENDREGION} {$REGION 'kostyas311'} PluginManager, PluginAPI, ActionHandler, ActionHandler.Scripts, ActionHandler.Programs, ActionHandler.Plugins, GlobalData, FWZipReader; {$ENDREGION} type TApplicationHelper = class helper for TApplication public function GetComponentsPath(): string; function GetPluginsPath(): string; function GetTemporyPath(): string; function GetDLLPath(): string; function GetHelpPath(): string; procedure PrepareApplicationPaths(); procedure RegisterModules(hk: TActionHandlerKind; Path: string); procedure UpdateModules(); end; TFmMain = class(TForm) WebUpdate: TWebUpdate; ilMain: TImageList; ilGroups: TImageList; ilToolBar: TImageList; pcMain: TPageControl; amComponents: TActionManager; acInstallComponent: TAction; OpenDialog: TOpenDialog; acDeleteComponent: TAction; acDownload: TAction; JvSelectDirectory: TJvSelectDirectory; pnlBottomInfo: TPanel; LinkLabel1: TLinkLabel; lblComputerID: TLabel; JvFormMagnet: TJvFormMagnet; lvPrograms: TListView; lvDefaultUtils: TListView; lvMacros: TListView; lvPlugins: TListView; tv: TJvPageListTreeView; JvPageList: TJvPageList; JvStandardPage1: TJvStandardPage; JvStandardPage2: TJvStandardPage; JvStandardPage3: TJvStandardPage; JvStandardPage4: TJvStandardPage; DragDropMacros: TJvDragDrop; pmMacros: TPopupMenu; pmiMacrosUpdate: TMenuItem; pmiMacrosDelete: TMenuItem; DragDropPrograms: TJvDragDrop; DragDropPlugin: TJvDragDrop; DragDropPackacge: TJvDragDrop; Splitter1: TSplitter; pnlMain: TPanel; tbUtils: TTabSheet; pmTree: TPopupMenu; pmAddCatalog: TMenuItem; JvStandardPage5: TJvStandardPage; RichEdit: TJvRichEdit; btnAddHelp: TMenuItem; OpenDialogHelp: TOpenDialog; JvStandardPage6: TJvStandardPage; lvCommon: TListView; btnAddToFav: TButton; procedure FormCreate(Sender: TObject); procedure btnAddHelpClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); procedure pcMainResize(Sender: TObject); procedure ListItemDblClick(Sender: TObject); procedure DragDropMacrosDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure pmiMacrosUpdateClick(Sender: TObject); procedure pmiMacrosDeleteClick(Sender: TObject); procedure lvMacrosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DragDropProgramsDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure DragDropPluginDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure DragDropPackacgeDrop(Sender: TObject; Pos: TPoint; Value: TStrings); procedure tvDblClick(Sender: TObject); procedure pmAddCatalogClick(Sender: TObject); procedure tvDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure btnAddToFavClick(Sender: TObject); private FNodeMain: TTreeNode; FNodePackages: TTreeNode; FNodeHelp: TTreeNode; function GetActiveListView(): TListView; procedure UpdateView(); procedure GrabPackages(); procedure RegisterInstructions(); procedure CreateItem(Ind: Integer; LV: TListView); procedure InstallPackage(Package: string); procedure UpdateModules(); procedure ListViewDeleteSelected(LV: TListView); procedure DoDragDropComponent(TargetPath: string; ActionKind: TActionHandlerKind; Files: TStrings; Ext: string); function NodeExists(Name: string): Boolean; procedure PrepareTreeNodes(); public procedure Run(ActionName: string); function IsPackageInstalled(FileName: string): Boolean; end; var FmMain: TFmMain; implementation const IMG_ACTIONS: array [TActionHandlerKind] of Integer = (0, 1, 2, 3); IMG_FOLDER = 5; {$R *.dfm} procedure TFmMain.LinkLabel1LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType); begin ShellExecute(0, nil, PChar(Link), nil, nil, SW_SHOWNORMAL); end; procedure TFmMain.ListItemDblClick(Sender: TObject); begin if TListView(Sender).Selected <> nil then ActionHandlerManager.Run(TListView(Sender).Selected.GroupID); end; procedure TFmMain.ListViewDeleteSelected(LV: TListView); begin if (LV <> nil) and (LV.Selected <> nil) then begin LV.Items.BeginUpdate; if MessageDlg('Вы действительно хотите удалить ' + LV.Selected.Caption + '?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin if LV = lvMacros then DeleteFile(Application.GetPluginsPath + LV.Selected.Caption) else if LV = lvPrograms then DeleteFile(Application.GetComponentsPath + LV.Selected.Caption); LV.DeleteSelected; end; LV.Items.EndUpdate; end; end; procedure TFmMain.lvMacrosKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_DELETE then ListViewDeleteSelected(Sender as TListView); end; procedure TFmMain.RegisterInstructions; var SR: TSearchRec; Node: TTreeNode; begin if FindFirst(Application.GetHelpPath + '*.rtf', faAnyFile, SR) = 0 then begin while FNodeHelp.HasChildren do FNodeHelp.DeleteChildren; repeat Node := tv.Items.AddChild(FNodeHelp, SR.Name); Node.SelectedIndex := 10; Node.ImageIndex := 10; Node.Data := PInteger(7); TJvPageIndexNode(Node).PageIndex := 4; until FindNext(SR) <> 0; FindClose(SR); end; end; procedure TFmMain.Run(ActionName: string); var I: Integer; begin for I := 0 to ActionHandlerManager.RegisteredCount - 1 do if AnsiSameText(ActionName, ActionHandlerManager.Handlers[I].HandlerName) then begin ActionHandlerManager.Run(I); Break; end; end; procedure TFmMain.tvDblClick(Sender: TObject); begin if (tv.Selected <> nil) then begin if (tv.Selected.Data = PInteger(6)) then begin if MessageDlg('Установить данный пакет?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin InstallPackage(tv.Selected.Text); tv.Selected.Delete; end; end else if (tv.Selected.Data = PInteger(7)) then begin RichEdit.Lines.LoadFromFile(Application.GetHelpPath + tv.Selected.Text); end; end; end; procedure TFmMain.tvDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin if Source is TListItem then begin ShowMessage('Hello'); end; end; procedure TFmMain.UpdateModules; begin Application.UpdateModules; RegisterInstructions; UpdateView; end; procedure TFmMain.UpdateView; var I: Integer; Ini: TIniFile; begin lvPrograms.Clear; lvDefaultUtils.Clear; lvMacros.Clear; lvPlugins.Clear; Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'reg.ini'); try for I := 0 to ActionHandlerManager.RegisteredCount - 1 do begin case ActionHandlerManager.Handlers[I].HandlerKind of hkRemoteProgram: CreateItem(I, lvPrograms); hkScript: CreateItem(I, lvMacros); hkDefault: CreateItem(I, lvDefaultUtils); hkPlugin: CreateItem(I, lvPlugins); end; if Ini.ReadBool('favorits', ActionHandlerManager.Handlers[I].HandlerName, false) or Ini.ReadBool('favorits', ExtractFileName(ActionHandlerManager.Handlers[I].HandlerName), false) then CreateItem(I, lvCommon); end; finally Ini.Free; end; end; procedure TFmMain.btnAddToFavClick(Sender: TObject); var LV: TListView; Item: TListItem; FavItem: TListItem; Ini: TIniFile; begin LV := Self.GetActiveListView; if LV <> nil then begin Item := LV.Selected; if Item <> nil then begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'reg.ini'); try if not Ini.ReadBool('favorits', Item.Caption, False) then begin Ini.WriteBool('favorits', Item.Caption, True); FavItem := lvCommon.Items.Add; FavItem.Assign(Item); FavItem.Data := Item.Data; FavItem.ImageIndex := Item.ImageIndex; end else Exit; finally Ini.Free; end; end; end; end; procedure TFmMain.CreateItem(Ind: Integer; LV: TListView); var Item: TListItem; begin Item := LV.Items.Add; case ActionHandlerManager.Handlers[Ind].HandlerKind of hkScript, hkRemoteProgram: Item.Caption := ExtractFileName(ActionHandlerManager.Handlers[Ind].HandlerName) else Item.Caption := ActionHandlerManager.Handlers[Ind].HandlerName; end; Item.GroupID := Ind; Item.ImageIndex := IMG_ACTIONS[ActionHandlerManager.Handlers[Ind].HandlerKind]; end; procedure TFmMain.DoDragDropComponent(TargetPath: string; ActionKind: TActionHandlerKind; Files: TStrings; Ext: string); var I: Integer; F: Boolean; begin F := False; for I := 0 to Files.Count - 1 do if AnsiSameText(ExtractFileExt(Files[I]), Ext) then begin CopyFile(PChar(Files[I]), PChar(TargetPath + ExtractFileName(Files[I])), True); F := True; end; if F then begin MessageDlg('Компоненты установлены.', mtInformation, [mbOK], 0); if ActionKind <> TActionHandlerKind(-1) then begin Application.RegisterModules(ActionKind, TargetPath + '*' + Ext); UpdateView; end; end; end; procedure TFmMain.DragDropMacrosDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin DoDragDropComponent(Application.GetPluginsPath, hkScript, Value, '.gss'); end; procedure TFmMain.DragDropPackacgeDrop(Sender: TObject; Pos: TPoint; Value: TStrings); var I: Integer; Node: TTreeNode; begin for I := 0 to Value.Count - 1 do if AnsiSameText(ExtractFileExt(Value[I]), '.gcomp') and not FileExists(ExtractFilePath(Application.ExeName) + ExtractFileName(Value[I])) then begin CopyFile(PChar(Value[I]), PChar(ExtractFilePath(Application.ExeName) + ExtractFileName(Value[I])), True); Node := tv.Items.AddChild(nil, ExtractFileName(Value[I])); Node.ImageIndex := 6; Node.SelectedIndex := 6; end; end; procedure TFmMain.DragDropPluginDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin DoDragDropComponent(Application.GetDLLPath, hkPlugin, Value, SPluginExt); end; procedure TFmMain.DragDropProgramsDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin DoDragDropComponent(Application.GetComponentsPath, hkRemoteProgram, Value, '.exe'); end; procedure TFmMain.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFmMain.FormCreate(Sender: TObject); begin {$IFDEF RELEASE} if WebUpdate.NewVersionAvailable then begin if MessageDlg('Доступна новая версия программы. Обновить?', mtConfirmation, [mbOK, mbCancel], 0) = mrOk then begin WebUpdate.DoUpdate; end; end; {$ENDIF} lvPrograms.OnDblClick := ListItemDblClick; lvDefaultUtils.OnDblClick := ListItemDblClick; lvMacros.OnDblClick := ListItemDblClick; lvPlugins.OnDblClick := ListItemDblClick; PrepareTreeNodes; UpdateModules; GrabPackages; lblComputerID.Caption := 'ID: ' + IntToStr(GlobalData.GetComputerID); end; function TFmMain.GetActiveListView: TListView; begin case JvPageList.ActivePageIndex of 0: Result := lvPrograms; 1: Result := lvDefaultUtils; 2: Result := lvMacros; 3: Result := lvPlugins else Result := nil; end; end; procedure TFmMain.GrabPackages; var SR: TSearchRec; Node: TTreeNode; LS: TStringList; I: Integer; Ini: TIniFile; CommonPath: string; begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'reg.ini'); try LS := TStringList.Create; try Ini.ReadSection('paths', LS); if LS.Count = 0 then LS.Add(ExtractFilePath(Application.ExeName)); for I := 0 to LS.Count - 1 do begin CommonPath := IncludeTrailingPathDelimiter(Ini.ReadString('paths', LS[I], EmptyStr)); if CommonPath = EmptyStr then Continue; if FindFirst(CommonPath + '*.gcomp', faAnyFile, SR) = 0 then begin try repeat if not IsPackageInstalled(CommonPath + SR.Name) then begin if not NodeExists(CommonPath + SR.Name) then begin Node := tv.Items.AddChild(FNodePackages, CommonPath + SR.Name); Node.ImageIndex := 6; Node.SelectedIndex := 6; Node.Data := PInteger(6); end; end; until FindNext(SR) <> 0; finally FindClose(SR); end; end; end; finally LS.Free; end; finally Ini.Free end; end; procedure TFmMain.InstallPackage(Package: string); var Zip: TFWZipReader; F: Boolean; begin Zip := TFWZipReader.Create; try Zip.LoadFromFile(Package); Zip.ExtractAll(ExtractFilePath(Application.ExeName)); F := True; finally Zip.Free; end; if F then begin UpdateModules; // DeleteFile(h(Application.ExeName) + Package); GlobalData.InstallPackage(Package); MessageDlg('Пакет установлен', mtInformation, [mbOK], 0); end; end; function TFmMain.IsPackageInstalled(FileName: string): Boolean; begin Result := CheckPackageInstalled(FileName); end; procedure TFmMain.btnAddHelpClick(Sender: TObject); begin if OpenDialogHelp.Execute then begin CopyFile(PChar(OpenDialogHelp.FileName), PChar(Application.GetHelpPath + ExtractFileName(OpenDialogHelp.FileName)), True); RegisterInstructions; end; end; function TFmMain.NodeExists(Name: string): Boolean; var I: Integer; begin Result := False; for I := 0 to FNodePackages.Count - 1 do if AnsiSameText(FNodePackages.Item[I].Text, Name) then Exit(True); end; procedure TFmMain.pcMainResize(Sender: TObject); begin pcMain.Height := self.Height - 90; end; procedure TFmMain.pmAddCatalogClick(Sender: TObject); var Ini: TIniFile; begin if JvSelectDirectory.Execute then begin Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'reg.ini'); try if not Ini.ValueExists('paths', IntToStr(GlobalData.GetStringHash(JvSelectDirectory.Directory))) then begin Ini.WriteString('paths', IntToStr(GlobalData.GetStringHash(JvSelectDirectory.Directory)), JvSelectDirectory.Directory); MessageDlg('Каталог добавлен', mtInformation, [mbOK], 0); GrabPackages; end; finally Ini.Free; end; end; end; procedure TFmMain.pmiMacrosDeleteClick(Sender: TObject); begin ListViewDeleteSelected(GetActiveListView()); end; procedure TFmMain.pmiMacrosUpdateClick(Sender: TObject); begin UpdateModules; end; procedure TFmMain.PrepareTreeNodes; var Node: TTreeNode; I: Integer; begin FNodeMain := tv.Items.AddChild(nil, 'Менеджер утилит'); FNodeMain.SelectedIndex := 4; FNodeMain.ImageIndex := 4; FNodeMain.Expanded := True; TJvPageIndexNode(FNodeMain).PageIndex := -1; FNodePackages := tv.Items.AddChild(nil, 'Доступные компоненты'); FNodePackages.SelectedIndex := 8; FNodePackages.ImageIndex := 8; FNodePackages.Expanded := True; TJvPageIndexNode(FNodePackages).PageIndex := -1; FNodeHelp := tv.Items.AddChild(nil, 'Инструкции'); FNodeHelp.SelectedIndex := 10; FNodeHelp.ImageIndex := 10; FNodeHelp.Expanded := True; TJvPageIndexNode(FNodeHelp).PageIndex := -1; Node := tv.Items.AddChild(FNodeMain, 'Избранное'); Node.SelectedIndex := 12; Node.ImageIndex := 12; TJvPageIndexNode(Node).PageIndex := 5; Node := tv.Items.AddChild(FNodeMain, 'Внешние программы'); Node.SelectedIndex := 0; Node.ImageIndex := 0; TJvPageIndexNode(Node).PageIndex := 0; Node := tv.Items.AddChild(FNodeMain, 'Встроенные утилиты'); Node.SelectedIndex := 2; Node.ImageIndex := 2; TJvPageIndexNode(Node).PageIndex := 1; Node := tv.Items.AddChild(FNodeMain, 'Макросы'); Node.SelectedIndex := 1; Node.ImageIndex := 1; TJvPageIndexNode(Node).PageIndex := 2; Node := tv.Items.AddChild(FNodeMain, 'Плагины'); Node.SelectedIndex := 3; Node.ImageIndex := 3; TJvPageIndexNode(Node).PageIndex := 3; for I := 0 to tv.Items.Count - 1 do tv.Items[I].Expanded := True; end; { TApplicationHelper } function TApplicationHelper.GetComponentsPath: string; begin Result := ExtractFilePath(ExeName) + 'Components\'; end; function TApplicationHelper.GetDLLPath: string; begin Result := ExtractFilePath(ExeName) + 'Dll\'; end; function TApplicationHelper.GetHelpPath: string; begin Result := ExtractFilePath(ExeName) + 'Help\'; end; function TApplicationHelper.GetPluginsPath: string; begin Result := ExtractFilePath(ExeName) + 'Plugins\'; end; function TApplicationHelper.GetTemporyPath: string; begin Result := ExtractFilePath(ExeName) + 'Temp\'; end; procedure TApplicationHelper.PrepareApplicationPaths; begin ForceDirectories(GetComponentsPath()); ForceDirectories(GetPluginsPath()); ForceDirectories(GetTemporyPath()); ForceDirectories(GetDLLPath()); ForceDirectories(GetHelpPath()); end; procedure TApplicationHelper.RegisterModules(hk: TActionHandlerKind; Path: string); var SR: TSearchRec; I: Integer; begin if hk = hkPlugin then begin PluginManager.Plugins.LoadPlugins(Path, SPluginExt); for I := 0 to Plugins.Count - 1 do ActionHandlerManager.RegisterActionHandler(Plugins.Items[I].Description, hkPlugin, TExcelImportPluginsActionHandler, Pointer(Plugins.Items[I])); end else begin if FindFirst(Path, faAnyFile, SR) = 0 then begin repeat case hk of hkRemoteProgram: ActionHandlerManager.RegisterActionHandler(Application.GetComponentsPath + SR.Name, hk, TProgramActionHandler); hkScript: ActionHandlerManager.RegisterActionHandler(Application.GetPluginsPath + SR.Name, hk, TScriptActionHandler); end; until FindNext(SR) <> 0; end; end; end; procedure TApplicationHelper.UpdateModules; begin RegisterModules(hkRemoteProgram, Application.GetComponentsPath + '*.exe'); RegisterModules(hkScript, Application.GetPluginsPath + '*.gss'); RegisterModules(hkPlugin, Application.GetDLLPath); end; end.
unit PXT.Canvas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, PXT.Types, PXT.Graphics, PXT.Controls, Vcl.StdCtrls; type TGameCanvas = object(TCanvas) procedure Create(Device: TDevice); procedure Draw(ATexture: TTexture; X, Y: Single; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure Draw(ATexture: TTexture; X, Y: Single; Mirror: Boolean; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawScale(ATexture: TTexture; X, Y: Single; ScaleX, ScaleY: Single; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawColor1(ATexture: TTexture; X, Y: Single; Mirror: Boolean; const AColors: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawColor1(ATexture: TTexture; X, Y, ScaleX, ScaleY: Single; Mirror: Boolean; const AColors: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawStretch(ATexture: TTexture; X, Y, Width, Height: Single; Mirror: Boolean; const AColors: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawStretch(ATexture: TTexture; X, Y, Width, Height: Single; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawPortion(ATexture: TTexture; X, Y, SrcX1, SrcY1, SrcX2, SrcY2: Integer; Mirror: Boolean; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawPattern(ATexture: TTexture; X, Y: Single; PatternIndex, PatternWidth, PatternHeight: Integer; Mirror: Boolean; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawPattern(ATexture: TTexture; X, Y, ScaleX, ScaleY: Single; PatternIndex, PatternWidth, PatternHeight: Integer; Mirror: Boolean; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawPatternRotate(ATexture: TTexture; X, Y, Angle, Scale: Single; PatternIndex, PatternWidth, PatternHeight: Integer; Mirror: Boolean; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawRotateC(ATexture: TTexture; X, Y: Single; const Angle, Scale: Single; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); overload; procedure DrawRotate(ATexture: TTexture; X, Y, CenterX, CenterY: Single; const Angle, Scale: Single; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); procedure DrawHue(ATexture: TTexture; Hue: Byte; X, Y: Single; Mirror: Boolean; AEffect: TBlendingEffect = TBlendingEffect.Normal); procedure DrawSaturation(ATexture: TTexture; Saturation: Byte; X, Y: Single; Mirror: Boolean; AEffect: TBlendingEffect = TBlendingEffect.Normal); procedure DrawTarget(var ATexture: TTexture; Width, Height: Integer; Proc: TProc); procedure DrawTargetStatic(var ATexture: TTexture; Width, Height: Integer; Proc: TProc); end; function GetA(const Color: LongWord): Byte; inline; function GetR(const Color: LongWord): Byte; inline; function GetG(const Color: LongWord): Byte; inline; function GetB(const Color: LongWord): Byte; inline; function ARGB(const A, R, G, B: Byte): LongWord; inline; implementation uses GameTypes; procedure TGameCanvas.Create; begin TCanvas(Self) := CanvasInit(Device); end; procedure TGameCanvas.Draw(ATexture: TTexture; X, Y: Single; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin Draw(ATexture, X, Y, False, AEffect); end; procedure TGameCanvas.Draw(ATexture: TTexture; X, Y: Single; Mirror: Boolean; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var TexCoord: TQuad; var Width := ATexture.Parameters.Width; var Height := ATexture.Parameters.Height; if Mirror then TexCoord := QuadUnity.Mirror else TexCoord := QuadUnity; Quad(ATexture, PXT.Types.Quad(X, Y, Width, Height), TexCoord, $FFFFFFFF, AEffect); end; procedure TGameCanvas.DrawScale(ATexture: TTexture; X, Y: Single; ScaleX, ScaleY: Single; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var Width := ATexture.Parameters.Width; var Height := ATexture.Parameters.Height; Quad(ATexture, PXT.Types.Quad(X, Y, Width * ScaleX, Height * ScaleY), QuadUnity, $FFFFFFFF, AEffect); end; procedure TGameCanvas.DrawColor1(ATexture: TTexture; X, Y: Single; Mirror: Boolean; const AColors: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var TexCoord: TQuad; var Width := ATexture.Parameters.Width; var Height := ATexture.Parameters.Height; if Mirror then TexCoord := QuadUnity.Mirror else TexCoord := QuadUnity; Quad(ATexture, PXT.Types.Quad(X, Y, Width, Height), TexCoord, AColors, AEffect); end; procedure TGameCanvas.DrawColor1(ATexture: TTexture; X, Y, ScaleX, ScaleY: Single; Mirror: Boolean; const AColors: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var TexCoord: TQuad; var Width := ATexture.Parameters.Width; var Height := ATexture.Parameters.Height; if Mirror then TexCoord := QuadUnity.Mirror else TexCoord := QuadUnity; Quad(ATexture, PXT.Types.Quad(X, Y, Width * ScaleX, Height * ScaleY), TexCoord, AColors, AEffect); end; procedure TGameCanvas.DrawStretch(ATexture: TTexture; X, Y, Width, Height: Single; Mirror: Boolean; const AColors: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var TexCoord: TQuad; if Mirror then TexCoord := QuadUnity.Mirror else TexCoord := QuadUnity; Quad(ATexture, PXT.Types.Quad(X, Y, Width, Height), TexCoord, AColors, AEffect); end; procedure TGameCanvas.DrawStretch(ATexture: TTexture; X, Y, Width, Height: Single; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin DrawStretch(ATexture, X, Y, Width, Height, False, $FFFFFFFF, AEffect); end; procedure TGameCanvas.DrawPortion(ATexture: TTexture; X, Y, SrcX1, SrcY1, SrcX2, SrcY2: Integer; Mirror: Boolean; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var TexCoord := PXT.Types.Quad(IntRectBDS(SrcX1, SrcY1, SrcX2, SrcY2)); if Mirror then TexCoord := TexCoord.Mirror; QuadRegion(ATexture, PXT.Types.Quad(X, Y, SrcX2 - SrcX1, SrcY2 - SrcY1), TexCoord, AColor, AEffect); end; function SetPattern(ATexture: TTexture; PatternIndex, PatternWidth, PatternHeight: Integer): TQuad; begin var FTexWidth := ATexture.Parameters.Width; var FTexHeight := ATexture.Parameters.Height; var ColCount := FTexWidth div PatternWidth; var RowCount := FTexHeight div PatternHeight; var FPatternIndex := PatternIndex; if FPatternIndex < 0 then FPatternIndex := 0; if FPatternIndex >= RowCount * ColCount then FPatternIndex := RowCount * ColCount - 1; var Left := (FPatternIndex mod ColCount) * PatternWidth; var Right := Left + PatternWidth; var Top := (FPatternIndex div ColCount) * PatternHeight; var Bottom := Top + PatternHeight; var FWidth := Right - Left; var FHeight := Bottom - Top; var X1 := Left; var Y1 := Top; var X2 := (Left + FWidth); var Y2 := (Top + FHeight); Result := PXT.Types.Quad(IntRectBDS(Round(X1), Round(Y1), Round(X2), Round(Y2))); end; procedure TGameCanvas.DrawPattern(ATexture: TTexture; X, Y: Single; PatternIndex, PatternWidth, PatternHeight: Integer; Mirror: Boolean; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var TexCoord := SetPattern(ATexture, PatternIndex, PatternWidth, PatternHeight); if Mirror then TexCoord := TexCoord.Mirror; QuadRegion(ATexture, PXT.Types.Quad(X, Y, PatternWidth, PatternHeight), TexCoord, AColor, AEffect); end; procedure TGameCanvas.DrawPattern(ATexture: TTexture; X, Y, ScaleX, ScaleY: Single; PatternIndex, PatternWidth, PatternHeight: Integer; Mirror: Boolean; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var TexCoord := SetPattern(ATexture, PatternIndex, PatternWidth, PatternHeight); if Mirror then TexCoord := TexCoord.Mirror; QuadRegion(ATexture, PXT.Types.Quad(X, Y, PatternWidth * ScaleX, PatternHeight * ScaleY), TexCoord, AColor, AEffect); end; procedure TGameCanvas.DrawPatternRotate(ATexture: TTexture; X, Y, Angle, Scale: Single; PatternIndex, PatternWidth, PatternHeight: Integer; Mirror: Boolean; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var TexCoord := SetPattern(ATexture, PatternIndex, PatternWidth, PatternHeight); if Mirror then TexCoord := TexCoord.Mirror; QuadRegion(ATexture, TQuad.Rotated(Point2f(X, Y), Point2f(PatternWidth, PatternHeight), Angle, Scale), TexCoord, AColor, AEffect); end; procedure TGameCanvas.DrawRotateC(ATexture: TTexture; X, Y: Single; const Angle, Scale: Single; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var Width := ATexture.Parameters.Width; var Height := ATexture.Parameters.Height; Quad(ATexture, TQuad.Rotated(Point2f(X, Y), Point2f(Width, Height), Angle, Scale), QuadUnity, AColor, AEffect); end; procedure TGameCanvas.DrawRotate(ATexture: TTexture; X, Y, CenterX, CenterY: Single; const Angle, Scale: Single; const AColor: TColorRect; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin var Width := ATexture.Parameters.Width; var Height := ATexture.Parameters.Height; Quad(ATexture, TQuad.Rotated(Point2f(X, Y), Point2f(Width, Height), Point2f(CenterX, CenterY), Angle, Scale), QuadUnity, AColor, AEffect); end; procedure TGameCanvas.DrawHue(ATexture: TTexture; Hue: Byte; X, Y: Single; Mirror: Boolean; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin Attributes := [TCanvasAttribute.ColorAdjust]; DrawColor1(ATexture, X, Y, Mirror, ARGB(255, 128, 128, Hue), AEffect); end; procedure TGameCanvas.DrawSaturation(ATexture: TTexture; Saturation: Byte; X, Y: Single; Mirror: Boolean; AEffect: TBlendingEffect = TBlendingEffect.Normal); begin Attributes := [TCanvasAttribute.ColorAdjust]; DrawColor1(ATexture, X, Y, Mirror, ARGB(255, 128, Saturation, 128), AEffect); end; procedure TGameCanvas.DrawTarget(var ATexture: TTexture; Width, Height: Integer; Proc: TProc); begin if ATexture.Initialized then ATexture.Free; var Parameters: TTextureParameters; FillChar(Parameters, SizeOf(TTextureParameters), 0); Parameters.Width := Width; Parameters.Height := Height; Parameters.Attributes := TextureDrawable or TexturePremultipliedAlpha; Parameters.Multisamples := 0; Parameters.Format := TPixelFormat.BGRA8; ATexture := TextureInit(FDevice, Parameters); ATexture.Clear; ATexture.BeginScene; BeginScene; Proc; var LRenderState := FDevice.RenderingState; LRenderState.BlendAlpha.Dest := TBlendFactor.InvSourceAlpha; FDevice.RenderingState := LRenderState; EndScene; ATexture.EndScene; end; procedure TGameCanvas.DrawTargetStatic(var ATexture: TTexture; Width, Height: Integer; Proc: TProc); begin if not ATexture.Initialized then begin var Parameters: TTextureParameters; FillChar(Parameters, SizeOf(TTextureParameters), 0); Parameters.Width := Width; Parameters.Height := Height; Parameters.Attributes := TextureDrawable or TexturePremultipliedAlpha; Parameters.Format := TPixelFormat.BGRA8; ATexture := TextureInit(FDevice, Parameters); end; ATexture.Clear(FloatColor($0)); ATexture.BeginScene; BeginScene; Proc; var LRenderState := FDevice.RenderingState; LRenderState.BlendAlpha.Dest := TBlendFactor.InvSourceAlpha; FDevice.RenderingState := LRenderState; EndScene; ATexture.EndScene; end; function GetA(const Color: LongWord): Byte; inline; begin Result := Color shr 24; end; function GetR(const Color: LongWord): Byte; inline; begin Result := (Color shr 16) and $FF; end; function GetG(const Color: LongWord): Byte; inline; begin Result := (Color shr 8) and $FF; end; function GetB(const Color: LongWord): Byte; inline; begin Result := Color and $FF; end; function ARGB(const A, R, G, B: Byte): LongWord; inline; begin Result := (A shl 24) or (B shl 16) or (G shl 8) or R; end; end.
unit Quick.OAuth; interface uses Quick.HttpClient, Quick.HttpServer.Request, Quick.HttpServer.Response, Quick.HttpServer, Quick.Threads, Quick.OAuth.Utils, SysUtils; type TOAuthToken = class private fAccessTokenExpiration: integer; fAccessToken: string; fRefreshToken: string; fRetrieveDateTime: TDateTime; public property AccessToken: string read fAccessToken write fAccessToken; property AccessTokenExpiration: integer read fAccessTokenExpiration write fAccessTokenExpiration; property RefreshToken: string read fRefreshToken write fRefreshToken; property RetrieveDateTime: TDateTime read fRetrieveDateTime write fRetrieveDateTime; end; TOnSaveToken = procedure (const aToken: TOAuthToken) of object; TOnLoadToken = procedure (var aToken: TOAuthToken) of object; TOnAuthorizationCompleted = reference to procedure (const aToken: TOAuthToken); TOnRefreshCompleted = reference to procedure (const aToken: TOAuthToken); {$M+} TOAuthBase = class private fToken: TOAuthToken; fOnAuthorizationCompleted: TOnAuthorizationCompleted; fOnRefreshCompleted: TOnRefreshCompleted; fAccessTokenParam: string; fAuthCodeParam: string; fAuthErrorParam: string; fExpirationParam: string; fRefreshTokenParam: string; fCallbackURL: string; fServer: THttpServer; fClient: TJsonHttpClient; fOnSaveToken: TOnSaveToken; fOnLoadToken: TOnLoadToken; procedure ExchangeAuthForAccessToken (const aAuthToken: string); procedure RefreshAccessToken (const aRefreshToken: string); function GetAccessToken: string; function IsTokenValid: boolean; protected // Abstract function CreateAuthorizationRequest: string; virtual; abstract; function CreateAuthToAccessRequest (const aAuthToken: string): string; virtual; abstract; function CreateRefreshRequest (const aRefreshToken: string): string; virtual; abstract; // Available function CreateAuthorizationHTMLPage (const aAuthorised: boolean): string; virtual; procedure OnProcessRequest(aRequest: IHttpRequest; aResponse: IHttpResponse); virtual; public constructor Create; destructor Destroy; override; // Methods procedure Authorize(const aOnAuthorizationCompleted: TOnAuthorizationCompleted = nil); procedure RefreshToken (const aOnRefreshCompleted: TOnRefreshCompleted = nil); // Properties property AccessTokenParam: string read fAccessTokenParam write fAccessTokenParam; property AuthCodeParam: string read fAuthCodeParam write fAuthCodeParam; property AuthErrorParam: string read fAuthErrorParam write fAuthErrorParam; property ExpirationParam: string read fExpirationParam write fExpirationParam; property RefreshTokenParam: string read fRefreshTokenParam write fRefreshTokenParam; property CallbackURL: string read fCallbackURL write fCallbackURL; property AccessToken: string read GetAccessToken; published // Events property OnSaveToken: TOnSaveToken read fOnSaveToken write fOnSaveToken; property OnLoadToken: TOnLoadToken read fOnLoadToken write fOnLoadToken; end; {$M-} EOAuthException = class (Exception); implementation uses System.JSON, System.DateUtils, System.Types; {$I QuickLib.INC} constructor TOAuthBase.Create; begin inherited Create; fClient:=TJsonHttpClient.Create; {$IFNDEF DELPHIRX101_UP} fServer:=nil; {$ENDIF} fToken:=TOAuthToken.Create; fToken.AccessToken:=''; fToken.AccessTokenExpiration:=0; fToken.RefreshToken:=''; fToken.RetrieveDateTime:=EncodeDateTime(1900, 1, 1, 23, 59, 00, 00); end; function TOAuthBase.CreateAuthorizationHTMLPage( const aAuthorised: boolean): string; begin if aAuthorised then result:='Access Authorised! You can now close this page and return to the application' else result:='Access Denied!'; end; destructor TOAuthBase.Destroy; begin fClient.Free; fServer.Free; fToken.Free; inherited; end; procedure TOAuthBase.ExchangeAuthForAccessToken(const aAuthToken: string); var resp: IHttpRequestResponse; accToken: string; refrToken: string; expiry: integer; begin fToken.AccessToken:=''; fToken.AccessTokenExpiration:=0; try case GetMethodFromRequest(CreateAuthToAccessRequest(aAuthToken)) of rmGET: resp:=fClient.Get(GetCleanRequest(CreateAuthToAccessRequest(aAuthToken))); rmPOST: resp:=fClient.Post(GetCleanRequest(CreateAuthToAccessRequest(aAuthToken)), ''); end; if (assigned(resp)) and (resp.StatusCode = 200) then begin if Assigned(resp.Response) then begin if resp.Response.TryGetValue(AccessTokenParam, accToken) then fToken.AccessToken:=accToken; if resp.Response.TryGetValue(ExpirationParam, expiry) then fToken.AccessTokenExpiration:=expiry; if resp.Response.TryGetValue(RefreshTokenParam, refrToken) then fToken.RefreshToken:=refrToken; fToken.RetrieveDateTime:=Now; if Assigned(fOnSaveToken) then fOnSaveToken(fToken); if Assigned(fOnAuthorizationCompleted) then fOnAuthorizationCompleted(fToken); end; end else raise EOAuthException.Create('Something went wrong. Please try again'); except raise EOAuthException.Create('Something went wrong. Please try again'); end; end; procedure TOAuthBase.OnProcessRequest(aRequest: IHttpRequest; aResponse: IHttpResponse); begin fToken.AccessToken:=''; fToken.AccessTokenExpiration:=0; if aRequest.UnparsedParams.Contains(AuthErrorParam) then aResponse.ContentText:= CreateAuthorizationHTMLPage(false) else if aRequest.UnparsedParams.Contains(AuthCodeParam) then begin ExchangeAuthForAccessToken(aRequest.Query[AuthCodeParam].AsString); aResponse.ContentText:= CreateAuthorizationHTMLPage(true); end; end; procedure TOAuthBase.RefreshAccessToken(const aRefreshToken: string); var resp: IHttpRequestResponse; accToken: string; expiry: integer; begin try case GetMethodFromRequest(CreateRefreshRequest(aRefreshToken)) of rmGET: resp:=fClient.Get(GetCleanRequest(CreateRefreshRequest(aRefreshToken))); rmPOST: resp:=fClient.Post(GetCleanRequest(CreateRefreshRequest(aRefreshToken)), ''); end; if (assigned(resp)) and (resp.StatusCode = 200) then begin if Assigned(resp.Response) then begin if resp.Response.TryGetValue(AccessTokenParam, accToken) then fToken.AccessToken:=accToken; if resp.Response.TryGetValue(ExpirationParam, expiry) then fToken.AccessTokenExpiration:=expiry; fToken.RetrieveDateTime:=Now; if Assigned(fOnSaveToken) then fOnSaveToken(fToken); end; end else raise EOAuthException.Create('Something went wrong. Please try again'); except raise EOAuthException.Create('Something went wrong. Please try again'); end; end; procedure TOAuthBase.RefreshToken(const aOnRefreshCompleted: TOnRefreshCompleted = nil); begin fOnRefreshCompleted:=aOnRefreshCompleted; if Assigned(fOnLoadToken) then fOnLoadToken(fToken); if fToken.AccessToken = '' then Authorize(TOnAuthorizationCompleted(fOnRefreshCompleted)) else begin GetAccessToken; if Assigned(fOnRefreshCompleted) then fOnRefreshCompleted(fToken); end; end; procedure TOAuthBase.Authorize(const aOnAuthorizationCompleted: TOnAuthorizationCompleted = nil); begin fOnAuthorizationCompleted:=aOnAuthorizationCompleted; if Assigned(fOnLoadToken) then fOnLoadToken(fToken); if IsTokenValid then Exit; fClient:=TJsonHttpClient.Create; if Assigned(fServer) then fServer.Stop; FreeAndNil(fServer); fServer:=THttpServer.Create(GetDomain(fCallbackURL), GetPort(fCallbackURL), false, nil); try fServer.OnNewRequest:=OnProcessRequest; fServer.Start; OpenURL(GetCleanRequest(CreateAuthorizationRequest)); except fServer.Stop; FreeAndNil(fServer); end; end; function TOAuthBase.GetAccessToken: string; begin result:=''; if IsTokenValid then result:=fToken.AccessToken else RefreshAccessToken(fToken.RefreshToken); end; function TOAuthBase.IsTokenValid: boolean; var expDate: TDateTime; begin expDate:=IncSecond(fToken.RetrieveDateTime, fToken.AccessTokenExpiration); result:= CompareDateTime(expDate, Now) = GreaterThanValue; end; end.
unit sdlstreams; { $Id: sdlstreams.pas,v 1.1 2004/02/05 00:08:20 savage Exp $ } {******************************************************************} { } { SDL - Simple DirectMedia Layer } { Copyright (C) 1997, 1998, 1999, 2000, 2001 Sam Lantinga } { } { Portions created by Chris Bruner are } { Copyright (C) 2002 Chris Bruner. } { } { Contributor(s) } { -------------- } { } { } { Obtained through: } { Joint Endeavour of Delphi Innovators ( Project JEDI ) } { } { You may retrieve the latest version of this file at the Project } { JEDI home page, located at http://delphi-jedi.org } { } { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/NPL/NPL-1_1Final.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } { } { Description } { ----------- } { Shows how to use OpenGL to do 2D and 3D with the SDL libraries } { } { } { Requires } { -------- } { SDL runtime libary somewhere in your path } { The Latest SDL runtime can be found on http://www.libsdl.org } { } { Programming Notes } { ----------------- } { } { } { } { } { } { Revision History } { ---------------- } { January 11 2002 - CB : Software embraced and extended by } { Chris Bruner of Crystal Software } { (Canada) Inc. } { } { February 11 2002 - DL : Added FreePascal support as suggested } { by "QuePasha Pepe" <mrkroket@hotmail.com> } { } {******************************************************************} { $Log: sdlstreams.pas,v $ Revision 1.1 2004/02/05 00:08:20 savage Module 1.0 release } {$i jedi-sdl.inc} interface uses Classes, SysUtils, sdl, sdlutils; {$IFDEF FPC} type EinvalidContainer=class(Exception); {$ENDIF} function LoadSDLBMPFromStream( Stream : TStream ) : PSDL_Surface; procedure SaveSDLBMPToStream( SDL_Surface : PSDL_Surface; stream : TStream ); function SDL_Swap16( D : UInt16 ) : Uint16; function SDL_Swap32( D : UInt32 ) : Uint32; function SDLStreamSetup( stream : TStream ) : PSDL_RWops; // this only closes the SDL_RWops part of the stream, not the stream itself procedure SDLStreamCloseRWops( SDL_RWops : PSDL_RWops ); implementation function SDL_Swap16( D : UInt16 ) : Uint16; begin Result := ( D shl 8 ) or ( D shr 8 ); end; function SDL_Swap32( D : UInt32 ) : Uint32; begin Result := ( ( D shl 24 ) or ( ( D shl 8 ) and $00FF0000 ) or ( ( D shr 8 ) and $0000FF00 ) or ( D shr 24 ) ); end; (*function SDL_Swap64(D : UInt64) : Uint64; var hi,lo : Uint32; begin // Separate into high and low 32-bit resultues and swap them lo := Uint32(D and $0FFFFFFFF); // bloody pascal is too tight in it's type checking! D := D shr 32; hi = Uint32((D and $FFFFFFFF)); result = SDL_Swap32(lo); result := result shl 32; result := result or SDL_Swap32(hi); end; *) function SdlStreamSeek( context : PSDL_RWops; offset : Integer; whence : Integer ) : integer; cdecl; var stream : TStream; origin : Word; begin stream := TStream( context.unknown ); if ( stream = nil ) then raise EInvalidContainer.Create( 'SDLStreamSeek on nil' ); case whence of 0 : origin := soFromBeginning; // Offset is from the beginning of the resource. Seek moves to the position Offset. Offset must be >= 0. 1 : origin := soFromCurrent; // Offset is from the current position in the resource. Seek moves to Position + Offset. 2 : origin := soFromEnd; else origin := soFromBeginning; // just in case end; Result := stream.Seek( offset, origin ); end; function SDLStreamWrite( context : PSDL_RWops; Ptr : Pointer; size : Integer; num : Integer ) : Integer; cdecl; var stream : TStream; begin stream := TStream( context.unknown ); if ( stream = nil ) then raise EInvalidContainer.Create( 'SDLStreamWrite on nil' ); try Result := stream.Write( Ptr^, Size * num ) div size; except Result := -1; end; end; function SdlStreamRead( context : PSDL_RWops; Ptr : Pointer; size : Integer; maxnum : Integer ) : Integer; cdecl; var stream : TStream; begin stream := TStream( context.unknown ); if ( stream = nil ) then raise EInvalidContainer.Create( 'SDLStreamRead on nil' ); try Result := stream.read( Ptr^, Size * maxnum ) div size; except Result := -1; end; end; function SDLStreamClose( context : PSDL_RWops ) : Integer; cdecl; var stream : TStream; begin stream := TStream( context.unknown ); if ( stream = nil ) then raise EInvalidContainer.Create( 'SDLStreamClose on nil' ); stream.Free; Result := 1; end; function SDLStreamSetup( stream : TStream ) : PSDL_RWops; begin result := SDL_AllocRW; if ( result = nil ) then raise EInvalidContainer.Create( 'could not create SDLStream on nil' ); result.unknown := TUnknown( stream ); result.seek := SDLStreamSeek; result.read := SDLStreamRead; result.write := SDLStreamWrite; result.close := SDLStreamClose; Result.type_ := 2; // TUnknown end; // this only closes the SDL part of the stream, not the context procedure SDLStreamCloseRWops( SDL_RWops : PSDL_RWops ); begin SDL_FreeRW( SDL_RWops ); end; function LoadSDLBMPFromStream( stream : TStream ) : PSDL_Surface; var SDL_RWops : PSDL_RWops; begin SDL_RWops := SDLStreamSetup( stream ); result := SDL_LoadBMP_RW( SDL_RWops, 0 ); SDLStreamCloseRWops( SDL_RWops ); end; procedure SaveSDLBMPToStream( SDL_Surface : PSDL_Surface; stream : TStream ); var SDL_RWops : PSDL_RWops; begin SDL_RWops := SDLStreamSetup( stream ); SDL_SaveBMP_RW( SDL_Surface, SDL_RWops, 0 ); SDLStreamCloseRWops( SDL_RWops ); end; end.
unit tmsUSheetNameList; {$INCLUDE ..\FLXCOMPILER.INC} interface uses Classes, SysUtils, tmsXlsMessages, Contnrs, tmsUFlxMessages; type TWideContainer= record S: UTF16String; n: integer; end; PWideContainer= ^TWideContainer; TSheetNameList=class(TList) //Items are TWideContainer private protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; function GetFullName(const S: UTF16String; const N: integer): UTF16String; public procedure Add(const aName: UTF16String); //Error if duplicated entry function AddUniqueName(const aName: UTF16String): UTF16String; class function MakeValidSheetName(const aName: UTF16String): UTF16String; procedure DeleteSheet(const SheetName: UTF16String); procedure Rename(const OldName, NewName: UTF16String); function FindRootString(const S: UTF16String; out Index: Integer): Boolean; virtual; function FindFullString(const S: UTF16String; out Index: Integer): Boolean; virtual; end; implementation { TSheetNameList } procedure TSheetNameList.Add(const aName: UTF16String); var InsPos: integer; Itm: PWideContainer; begin if FindFullString(AName, InsPos) then raise Exception.CreateFmt(ErrDuplicatedSheetName, [string(aName)]); New(Itm); Itm.S:=aName; Itm.n:=0; Insert( InsPos, Itm ); end; class function TSheetNameList.MakeValidSheetName(const aName: UTF16String): UTF16String; var Min: integer; begin Min:=Length(aName); if Min>31 then Min:=31; Result:=Copy(aName, 1, Min); Result:= StringReplace(Result, '/','_', [rfReplaceAll]); Result:= StringReplace(Result, '\','_', [rfReplaceAll]); Result:= StringReplace(Result, '?','_', [rfReplaceAll]); Result:= StringReplace(Result, '[','_', [rfReplaceAll]); Result:= StringReplace(Result, ']','_', [rfReplaceAll]); Result:= StringReplace(Result, '*','_', [rfReplaceAll]); Result:= StringReplace(Result, ':','.', [rfReplaceAll]); end; function TSheetNameList.AddUniqueName(const aName: UTF16String): UTF16String; var InsPos: integer; Itm: PWideContainer; n:integer; begin n:=0; if FindRootString(aName, InsPos) then begin n:=PWideContainer(Items[InsPos]).n+1; while FindFullString(GetFullName(aName, n), InsPos) do inc(n); end; New(Itm); Itm.S:=aName; Itm.n:=n; Insert( InsPos, Itm ); Result:=GetFullName(aName,n); end; function MyCompareWideStrings(const s1,s2: UTF16String): integer; var i:integer; begin Result:=0; if Length(S1)<Length(S2) then Result:=-1 else if Length(S1)>Length(S2) then Result:=1 else for i:=1 to Length(S1) do begin if S1[i]=S2[i] then continue else if S1[i]<S2[i] then Result:=-1 else Result:=1; exit; end; end; procedure TSheetNameList.DeleteSheet(const SheetName: UTF16String); var Idx1: integer; begin if not FindFullString(SheetName, Idx1) then raise Exception.CreateFmt(ErrDuplicatedSheetName, [SheetName]); Delete(Idx1); end; function TSheetNameList.FindFullString(const S: UTF16String; out Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := Count - 1; while L <= H do begin I := (L + H) shr 1; C := MyCompareWideStrings(GetFullName(PWideContainer(Items[I]).S, PWideContainer(Items[I]).N), S); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; end; end; end; Index := L; end; function TSheetNameList.FindRootString(const S: UTF16String; out Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := Count - 1; while L <= H do begin I := (L + H) shr 1; C := MyCompareWideStrings(PWideContainer(Items[I]).S, S); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; end; end; end; Index := L; end; function TSheetNameList.GetFullName(const S: UTF16String; const N: integer): UTF16String; begin if n=0 then Result:= S else Result:= S+IntToStr(n); end; procedure TSheetNameList.Notify(Ptr: Pointer; Action: TListNotification); begin if Action = lnDeleted then Dispose(PWideContainer(Ptr)); inherited Notify(Ptr, Action); end; procedure TSheetNameList.Rename(const OldName, NewName: UTF16String); var Idx1, Idx2: integer; begin if OldName=NewName then exit; if not FindFullString(OldName, Idx1) then raise Exception.CreateFmt(ErrDuplicatedSheetName, [OldName]); if FindFullString(NewName, Idx2) then raise Exception.CreateFmt(ErrDuplicatedSheetName, [string(NewName)]); Delete(Idx1); Add(NewName); end; end.