text
stringlengths
14
6.51M
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TThreadFunc = function (hThread: THandle): DWORD; stdcall; TForm3 = class(TForm) ProcessListBox: TListBox; Label1: TLabel; Button1: TButton; OutDir: TEdit; Label2: TLabel; SpeedButton1: TSpeedButton; LogMemo: TMemo; Label3: TLabel; SuspendCheck: TCheckBox; WriteCheck: TCheckBox; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private { Private declarations } f_Report: TStream; f_Buffer: Pointer; f_BufferSize: Cardinal; procedure FillProcessList(aList: TListBox); procedure MakeDump(const outDir, aProcessName: String; aProcessID: DWORD; SuspendThreads, WriteDump: Boolean); procedure DumpRegion(aProcess: THandle; const anInfo: TMemoryBasicInformation; const OutDir: String; WriteDump: Boolean); procedure ClearLog; procedure AddToLog(const aStr: String); procedure AddToReport(const aFile: TSTream; const aStr: String); procedure CheckBufferSize(aNewSize: Cardinal); procedure FreeBuffer; procedure ProcessThreads(aSnapShot: THandle; aFunc: TThreadFunc); public { Public declarations } end; var Form3: TForm3; implementation uses TlHelp32, FileCtrl, l3FileUtils; {$R *.dfm} { TForm3 } procedure TForm3.FillProcessList(aList: TListBox); var l_SnapShot: THandle; l_Entry: TProcessEntry32; begin aList.Items.Clear; l_SnapShot := CreateToolHelp32SnapShot(TH32CS_SNAPPROCESS, 0); try l_Entry.dwSize := SizeOf(l_Entry); if Process32First(l_SnapShot, l_Entry) then begin repeat aList.Items.AddObject(ExtractFileName(l_Entry.szExeFile), Pointer(l_Entry.th32ProcessID)); until not Process32Next(l_SnapShot, l_Entry); end; finally CloseHandle(l_SnapShot); end; end; procedure TForm3.FormCreate(Sender: TObject); begin FillProcessList(ProcessListBox); OutDir.Text := ExtractFilePath(ParamStr(0)); end; procedure TForm3.Button1Click(Sender: TObject); var l_OutDir: String; begin if ProcessListBox.ItemIndex = -1 then raise Exception.Create('Unspecified process'); l_OutDir := OutDir.Text; if l_OutDir = '' then l_OutDir := ExtractFilePath(ParamStr(0)); ForceDirectories(l_OutDir); if not DirectoryExists(l_OutDir) then raise Exception.Create('Unspecified out folder'); MakeDump(l_OutDir, ProcessListBox.Items[ProcessListBox.ItemIndex], DWORD(ProcessListBox.Items.Objects[ProcessListBox.ItemIndex]), SuspendCheck.Checked, WriteCheck.Checked); end; procedure TForm3.MakeDump(const outDir, aProcessName: String; aProcessID: DWORD; SuspendThreads, WriteDump: Boolean); var l_SnapShot: THandle; l_Process: THandle; l_Info: TMemoryBasicInformation; l_Ptr: PAnsiChar; l_Res: LongWord; l_Module: TModuleEntry32; begin DeleteFilesByMask(outDir, '*.MemDump'); ClearLog; f_Report := TFileStream.Create(ConcatDirName(OutDir, ChangeFileExt(ExtractFileName(aProcessName), '.MemDump')), fmCreate); try l_SnapShot := CreateToolHelp32SnapShot(TH32CS_SNAPMODULE or TH32CS_SNAPTHREAD or TH32CS_SNAPHEAPLIST, aProcessID); try if SuspendThreads then ProcessThreads(l_SnapShot, SuspendThread); try AddToLog(Format('Making Dump for process %s (%d)', [aProcessName, aProcessID])); l_Module.dwSize := SizeOf(l_Module); if Module32First(l_SnapShot, l_Module) then begin AddToLog(Format('MODULE %s %s', [l_Module.szModule, l_Module.szExePath])); if l_Module.th32ProcessID <> aProcessID then raise Exception.Create('Process failed'); end else begin AddToLog('Protected or 64-bit process. Unable to dump'); Exit; end; l_Process := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, aProcessID); try if l_Process = 0 then RaiseLastOSError; CheckBufferSize(10*1024*1024); l_Ptr := Pointer(0); l_Res := VirtualQueryEx(l_Process, l_Ptr, l_Info, SizeOf(l_Info)); if l_Res <> SizeOf(l_Info) then RaiseLastOSError; while l_Res = SizeOf(l_Info) do begin DumpRegion(l_Process, l_Info, OutDir, WriteDump); Inc(l_Ptr, l_Info.RegionSize); l_Res := VirtualQueryEx(l_Process, l_Ptr, l_Info, SizeOf(l_Info)); end; finally CloseHandle(l_Process); end; finally if SuspendThreads then ProcessThreads(l_SnapShot, ResumeThread); end; finally CLoseHandle(l_SnapShot); end; finally FreeAndNil(f_Report); end; end; procedure TForm3.SpeedButton1Click(Sender: TObject); var l_Dir: String; begin l_Dir := OutDir.Text; if SelectDirectory('Out folder', '', l_Dir) then OutDir.Text := l_Dir; end; procedure TForm3.DumpRegion(aProcess: THandle; const anInfo: TMemoryBasicInformation; const OutDir: String; WriteDump: Boolean); var l_State: String; l_End: PAnsiChar; l_Protect: String; l_Size: Cardinal; l_RegionReport: TStream; begin case anInfo.State of MEM_COMMIT: l_State := '[COMMITED]'; MEM_FREE: l_State := '[FREE]'; MEM_RESERVE: l_State := '[RESERVED]'; else l_State := '[UNKNOWN]'; end; if (anInfo.Protect and (PAGE_EXECUTE or PAGE_EXECUTE_READ)) <> 0 then l_Protect := '[EXECUTABLE] ' else l_Protect := ''; l_End := PAnsiChar(anInfo.BaseAddress) + anInfo.RegionSize; if Cardinal(l_End) < Cardinal(anInfo.BaseAddress) then begin AddToLog(Format('[INVALID REGION ] %p-%p %s', [anInfo.BaseAddress, Pointer(l_End), FormatFloat('#,##0', anInfo.RegionSize)])); Abort; end; AddToLog(Format('%s%p-%p %s %s', [l_Protect, anInfo.BaseAddress, Pointer(l_End), l_State, FormatFloat('#,##0', anInfo.RegionSize)])); if WriteDump then begin CheckBufferSize(anInfo.RegionSize); if anInfo.State = MEM_COMMIT then begin if ReadProcessMemory(aProcess, anInfo.BaseAddress, f_Buffer, anInfo.RegionSize, l_Size) then begin Assert(anInfo.RegionSize = l_Size); l_RegionReport := TFileStream.Create(ConcatDirName(OutDir, Format('%p [%s].MemDump', [anInfo.BaseAddress, FormatFloat('#,##0', anInfo.RegionSize)])), fmCreate); try l_RegionReport.Write(f_Buffer^, l_Size); finally FreeAndNil(l_RegionReport); end; end else AddToLog(Format('FAILED - %s', [SysErrorMessage(GetLastError)])); end; end; end; procedure TForm3.AddToLog(const aStr: String); begin LogMemo.Lines.Add(aStr); AddToReport(f_Report, aStr); end; procedure TForm3.AddToReport(const aFile: TSTream; const aStr: String); const cCRLF: AnsiString = #13#10; begin if aStr <> '' then aFile.Write(aStr[1], Length(aStr)*SizeOf(aStr[1])); aFile.Write(cCRLF[1], Length(cCRLF)); end; procedure TForm3.ClearLog; begin LogMemo.Lines.Clear; end; procedure TForm3.CheckBufferSize(aNewSize: Cardinal); begin if aNewSize > f_BufferSize then begin FreeBuffer; f_Buffer := AllocMem(aNewSize); f_BufferSize := aNewSize; end; end; procedure TForm3.FreeBuffer; begin FreeMem(f_Buffer); f_BufferSize := 0; end; const THREAD_SUSPEND_RESUME = $0002; function OpenThread(dwDesiredAccess: dword; bInheritHandle: bool; dwThreadId: dword):dword; stdcall; external 'kernel32.dll'; procedure TForm3.ProcessThreads(aSnapShot: THandle; aFunc: TThreadFunc); var l_Info: TThreadEntry32; l_Thread: THandle; begin l_Info.dwSize := SizeOf(l_Info); if Thread32First(aSnapShot, l_Info) then repeat l_Thread := OpenThread(THREAD_SUSPEND_RESUME, False, l_Info.th32ThreadID); Assert(l_Thread <> 0); try aFunc(l_Info.th32ThreadID) finally CloseHandle(l_Thread); end; until not Thread32Next(aSnapShot, l_Info); end; end.
unit MdiChilds.DTXView; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxCustomData, cxStyles, cxTL, cxTLdxBarBuiltInMenu, JvComponentBase, JvDragDrop, cxInplaceContainer, Vcl.StdCtrls, Vcl.ExtCtrls, DataTable, ActionHandler; type TFmDTXView = class(TFmProcess) tl: TcxTreeList; DragDrop: TJvDragDrop; Label1: TLabel; Edit1: TEdit; procedure DragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); private { Private declarations } public procedure UpdateView(AFileName: string); end; TDTXViewActionHandler = class (TAbstractActionHandler) public procedure ExecuteAction(UserData: Pointer = nil); override; end; var FmDTXView: TFmDTXView; implementation {$R *.dfm} procedure TFmDTXView.DragDropDrop(Sender: TObject; Pos: TPoint; Value: TStrings); begin if Value.Count > 0 then UpdateView(Value[0]); end; procedure TFmDTXView.UpdateView(AFileName: string); var Table: TFormattedStringDataTable; I: Integer; Row: TTableRow<string>; Node: TcxTreeListNode; begin tl.Clear; tl.BeginUpdate; Table := TFormattedStringDataTable.Create; try Table.LoadFromFile(AFileName); Edit1.Text := Table.Cipher; for I := 0 to Table.ColumnsCount - 1 do With tl.CreateColumn() do begin Caption.Text := Table.Columns[I]; DataBinding.ValueType := 'string'; end; for Row in Table.Rows do begin Node := tl.Add; for I := 0 to Table.ColumnsCount - 1 do Node.Values[I] := Row[I]; end; finally tl.EndUpdate; Table.Free; end; end; { TDTXViewActionHandler } procedure TDTXViewActionHandler.ExecuteAction(UserData: Pointer); begin TFmDTXView.Create(Application).Show; end; begin ActionHandlerManager.RegisterActionHandler('Просмотр DTX', hkDefault, TDTXViewActionHandler); end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.BitBtn; interface {$SCOPEDENUMS ON} uses System.Classes, System.UITypes, FMX.Types, FMX.Controls, FMX.Objects, FMX.StdCtrls, FMX.Graphics; type { TfgCustomBitBtn } /// <summary> /// Тип кнопки с картинкой: /// <para> /// <c>StylizedGlyph</c> - Картинка для кнопки берется из StyleBook по /// имени стиля /// </para> /// <para> /// <c>CustomGlyph</c> - Картинка для кнопки берется из TfgBitBtn.Glyph /// </para> /// <para> /// <c>Остальные</c> - Картинка для кнопки берется текущего стиля по заранее /// заданному имени стиля /// </para> /// </summary> TfgBitBtnKind = (Custom, OK, Cancel, Help, Yes, No, Close, Retry, Ignore); TfgCustomBitBtn = class (TSpeedButton) public const DEFAULT_KIND = TfgBitBtnKind.Custom; private FKind: TfgBitBtnKind; FStyleImage: TImage; FMousePressed: Boolean; procedure SetKind(const Value: TfgBitBtnKind); function GetIsMousePressed: Boolean; function GetStyleText: TControl; protected procedure UpdateGlyph; virtual; procedure DoImageLinkChanged(Sender: TObject); { Style } procedure ApplyStyle; override; procedure FreeStyle; override; function GetDefaultStyleLookupName: string; override; property StyleImage: TImage read FStyleImage; property StyleText: TControl read GetStyleText; { Mouse Events } procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); override; public constructor Create(AOwner: TComponent); override; public property IsMousePressed: Boolean read GetIsMousePressed; property Kind: TfgBitBtnKind read FKind write SetKind default DEFAULT_KIND; end; { TfgBitBtn } TfgBitBtn = class (TfgCustomBitBtn) published property Kind; property GroupName; { TfgCustomButton } property Align; property Action; property Anchors; property AutoTranslate default True; property CanFocus default True; property CanParentFocus; property ClipChildren default False; property ClipParent default False; property Cursor default crDefault; property DisableFocusEffect; property DragMode default TDragMode.dmManual; property EnableDragHighlight default True; property Enabled default True; property Font; property Height; property HelpContext; property HelpKeyword; property HelpType; property HitTest default True; property StaysPressed default False; property IsPressed default False; property Locked default False; property Padding; property ModalResult default mrNone; property Opacity; property Margins; property PopupMenu; property Position; property RepeatClick default False; property RotationAngle; property RotationCenter; property Scale; property StyleLookup; property TabOrder; property Text; property TextAlign default TTextAlign.Center; property TouchTargetExpansion; property Visible default True; property Width; property WordWrap default False; property OnApplyStyleLookup; property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; property OnKeyDown; property OnKeyUp; property OnCanFocus; property OnClick; property OnDblClick; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; end; implementation uses System.SysUtils, FMX.Styles; const BITBTN_KIND_STYLES : array [TfgBitBtnKind] of string = ('', 'imgOk', 'imgCancel', 'imgHelp', 'imgYes', 'imgNo', 'imgClose', 'imgRetry', 'imgIgnore'); { TfgCustomBitBtn } procedure TfgCustomBitBtn.ApplyStyle; var T: TFmxObject; begin inherited ApplyStyle; T := FindStyleResource('glyph'); if Assigned(T) and (T is TImage) then begin FStyleImage := T as TImage; UpdateGlyph; end; end; constructor TfgCustomBitBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); FKind := DEFAULT_KIND; end; procedure TfgCustomBitBtn.DoImageLinkChanged(Sender: TObject); begin UpdateGlyph; end; procedure TfgCustomBitBtn.FreeStyle; begin FStyleImage := nil; inherited FreeStyle; end; function TfgCustomBitBtn.GetDefaultStyleLookupName: string; begin Result := 'buttonstyle'; end; function TfgCustomBitBtn.GetIsMousePressed: Boolean; begin Result := FMousePressed; end; function TfgCustomBitBtn.GetStyleText: TControl; begin if TextObject <> nil then Result := TextObject else Result := nil; end; procedure TfgCustomBitBtn.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin FMousePressed := True; StartTriggerAnimation(Self, 'IsMousePressed'); inherited MouseDown(Button, Shift, X, Y); end; procedure TfgCustomBitBtn.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited MouseUp(Button, Shift, X, Y); FMousePressed := False; StartTriggerAnimation(Self, 'IsMousePressed'); end; procedure TfgCustomBitBtn.SetKind(const Value: TfgBitBtnKind); begin if FKind <> Value then begin FKind := Value; UpdateGlyph; end; end; procedure TfgCustomBitBtn.UpdateGlyph; procedure FindAndSetStandartButtonKind(const AStyleName: string); var StyleObject: TFmxObject; Finded: Boolean; Style: TFmxObject; begin // Выбираем ветку стиля: // - Если для формы указан StyleBook, то берем его. // - Если для формы не задан StyleBook, то берем стиль по умолчанию if Assigned(Scene.StyleBook) then Style := Scene.StyleBook.Style else Style := TStyleManager.ActiveStyleForScene(Scene); // Ищем стиль по указанному имени в текущей ветки стиля StyleObject := Style.FindStyleResource(AStyleName); Finded := Assigned(StyleObject) and (StyleObject is TImage); if Finded then FStyleImage.Bitmap.Assign(TImage(StyleObject).Bitmap); FStyleImage.Visible := Finded; end; begin if not Assigned(FStyleImage) then Exit; // case Kind of // TfgBitBtnKind.Custom: FindAndSetGlyph; // else FindAndSetStandartButtonKind(BITBTN_KIND_STYLES[Kind]); // end; FStyleImage.Visible := not FStyleImage.Bitmap.IsEmpty; end; initialization RegisterFmxClasses([TfgCustomBitBtn, TfgBitBtn]); end.
// Simple types used in the code formatter // Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html) // Contributors: Thomas Mueller (http://www.dummzeuch.de) unit GX_CodeFormatterTypes; {$I GX_CondDefine.inc} interface uses SysUtils, GX_CollectionLikeLists; type ECodeFormatter = class(Exception); type TWordType = (wtLineFeed, wtSpaces, wtHalfComment, wtHalfStarComment, wtHalfOutComment, wtFullComment, wtFullOutComment, wtString, wtErrorString, wtOperator, wtWord, wtNumber, wtHexNumber, wtNothing, wtAsm, wtCompDirective); EFormatException = class(Exception); TProgressEvent = procedure(Sender: TObject; Progress: Integer) of object; const Maxline = 1024; // the maximum line length of the Delphi editor // CRLF = #13#10#0; NotPrintable = [#1..#8, #10..#14, #16..#19, #22..#31]; {not printable chars} Tab = #9; ftNothing = 0; ftSpaceBefore = $01; ftSpaceAfter = $02; ftSpaceBoth = $03; ftUpperCase = $04; ftLowerCase = $08; ftFirstUp = $10; type TSpaceBefore = (spNone, spBefore, spAfter, spBoth); TReservedType = (rtNothing, rtReserved, rtOper, rtDirective, rtIf, rtDo, rtWhile, rtOn, rtVar, rtType, rtProcedure, rtAsm, rtTry, rtExcept, rtEnd, rtBegin, rtCase, rtOf, rtLineFeed, rtColon, rtSemiColon, rtThen, rtClass, rtClassDecl, rtProgram, rtRepeat, rtUntil, rtRecord, rtPrivate, rtElse, rtIfElse, rtInterface, rtImplementation, rtLeftBr, rtRightBr, rtLeftHook, rtRightHook, rtMathOper, rtEqualOper, rtMinus, rtPlus, rtLogOper, rtEquals, rtForward, rtDefault, rtInitialization, rtComma, rtUses, rtProcDeclare, rtFuncDirective, rtAbsolute, rtComment, rtRecCase, rtDot, rtCompIf, rtDotDot, rtCompElse, rtCompEndif); const NoReservedTypes = [rtNothing, rtComma, rtColon, rtLineFeed, rtDefault, rtFuncDirective, rtAbsolute, rtComment, rtLeftBr, rtRightBr, rtForward, rtCompIf, rtCompElse, rtCompEndif, rtPrivate]; StandardDirectives = [rtDefault, rtAbsolute, rtPrivate, rtFuncDirective, rtAbsolute, rtForward]; type {: determines a word's casing: * rfLowerCase = all lowercase * rfUpperCase = all uppercase * rfFirstUp = first character upper case, all other lowercase * rfUnchanged = do not change anything } TCase = (rfLowerCase, rfUpperCase, rfFirstUp, rfUnchanged); {: stores a single reserved word with its associated type } TReservedRec = record ReservedType: TReservedType; Words: PChar; end; type TFeedBegin = (Unchanged, Hanging, NewLine); {: how to use the captialization file } TFillMode = ( fmUnchanged, {: do not use the capitalization file } fmAddNewWord, {: add new words, but do not use for capitalization } fmUse, {: use for capitalization, but do not add words } fmExceptDirect, {: exclude directives } fmAddUse, {: add new words, and use for capitalization } fmAddUseExcept); {: add new words, but do not use for capitalization, exclude directivs } // this could probably be replaced by: // TFillModeOptions = (fmAddNew, fmUse, fmExceptDirectives } // TFillMode = set of TFillMode // which would make it more readable TCommentArray = array[0..20] of Char; {easier to save} {: stores all possible settings for the formatting engine } TSettings = packed record ShortCut: Word; {: used only in the old expert: keyboard shortcut } SpaceOperators: TSpaceBefore; {: spaces around operators } SpaceColon: TSpaceBefore; {: spaces around colonds ":" } SpaceSemiColon: TSpaceBefore; {: spaces around semicolons ";" } SpaceComma: TSpaceBefore; {: spaces around commas "," } SpaceLeftBr: TSpaceBefore; {: spaces around left brackets "(" } SpaceRightBr: TSpaceBefore; {: spaces around right brackets ")" } SpaceLeftHook: TSpaceBefore; {: spaces around left hooks (what's a hook?) } SpaceRightHook: TSpaceBefore; {: spaces around right hooks (what's a hook?) } SpaceEqualOper: TSpaceBefore; {: spaces around equal operator "=" } UpperCompDirectives: Boolean; {: uppercase compiler directives } UpperNumbers: Boolean; {: uppercase (hex) numbers } ReservedCase: TCase; {: case for reserved words } StandDirectivesCase: TCase; {: case for standard directives } ChangeIndent: Boolean; NoIndentElseIf: Boolean; indentBegin: Boolean; IndentTry: Boolean; IndentTryElse: Boolean; IndentCaseElse: Boolean; IndentComments: Boolean; IndentCompDirectives: Boolean; BlankProc: Boolean; {: blank line between main procedures } BlankSubProc: Boolean; {: blank line between sub procedures } RemoveDoubleBlank: Boolean; {: remove double blank lines } SpacePerIndent: Integer; {: number of spaces per indent } FeedRoundBegin: TFeedBegin; FeedBeforeEnd: Boolean; FeedAfterThen: Boolean; ExceptSingle: Boolean; FeedAfterVar: Boolean; FeedEachUnit: Boolean; NoFeedBeforeThen: Boolean; FeedElseIf: Boolean; {: line feed between else and if } FillNewWords: TFillMode; {: how to use the capitalization file } FeedAfterSemiColon: Boolean; StartCommentOut: TCommentArray; {: special comment to start unformatted section } EndCommentOut: TCommentArray; {: special comment to end unformatted section } CommentFunction: Boolean; {: add a function comment } CommentUnit: Boolean; {: add a unit comment } WrapLines: Boolean; {: wrap long lines } WrapPosition: Byte; {: wrap position for long lines } AlignCommentPos: Byte; {: position to align comments } AlignComments: Boolean; {: turn on comment alignment } AlignVarPos: Byte; {: position to align variant/constant declarations (the colon) } AlignVar: Boolean; {: turn on variable/constant alignment } end; const NReservedWords = 107; {IndentProcedure = True;} type TReservedArray = array[0..NReservedWords - 1] of TReservedRec; const {: stores all known reserved words in lower case with their associated type, must be ordered perfectly on words!! NOTE: This is for Delphi 2005, there are some words that aren't reserved in earlier Delphi versions, maybe that should be configurable? That could be done by converting this list into a oObjects.TStrCollection which only contains those words that are known for the configured Delphi version. } ReservedArray: TReservedArray = ( (ReservedType: rtAbsolute; Words: 'absolute'), (ReservedType: rtFuncDirective; Words: 'abstract'), (ReservedType: rtOper; Words: 'and'), (ReservedType: rtReserved; Words: 'array'), (ReservedType: rtOper; Words: 'as'), (ReservedType: rtAsm; Words: 'asm'), (ReservedType: rtFuncDirective; Words: 'assembler'), (ReservedType: rtPrivate; Words: 'automated'), (ReservedType: rtBegin; Words: 'begin'), (ReservedType: rtCase; Words: 'case'), (ReservedType: rtFuncDirective; Words: 'cdecl'), (ReservedType: rtClass; Words: 'class'), (ReservedType: rtVar; Words: 'const'), (ReservedType: rtProcedure; Words: 'constructor'), (ReservedType: rtUses; Words: 'contains'), (ReservedType: rtDefault; Words: 'default'), (ReservedType: rtFuncDirective; Words: 'deprecated'), (ReservedType: rtProcedure; Words: 'destructor'), (ReservedType: rtFuncDirective; Words: 'dispid'), (ReservedType: rtInterface; Words: 'dispinterface'), (ReservedType: rtOper; Words: 'div'), (ReservedType: rtDo; Words: 'do'), (ReservedType: rtOper; Words: 'downto'), (ReservedType: rtFuncDirective; Words: 'dynamic'), (ReservedType: rtElse; Words: 'else'), (ReservedType: rtEnd; Words: 'end'), (ReservedType: rtExcept; Words: 'except'), (ReservedType: rtFuncDirective; Words: 'export'), (ReservedType: rtUses; Words: 'exports'), (ReservedType: rtForward; Words: 'external'), (ReservedType: rtFuncDirective; Words: 'far'), (ReservedType: rtReserved; Words: 'file'), (ReservedType: rtInitialization; Words: 'finalization'), (ReservedType: rtExcept; Words: 'finally'), (ReservedType: rtWhile; Words: 'for'), (ReservedType: rtForward; Words: 'forward'), (ReservedType: rtProcedure; Words: 'function'), (ReservedType: rtReserved; Words: 'goto'), (ReservedType: rtIf; Words: 'if'), (ReservedType: rtImplementation; Words: 'implementation'), (ReservedType: rtFuncDirective; Words: 'implements'), (ReservedType: rtOper; Words: 'in'), (ReservedType: rtFuncDirective; Words: 'index'), (ReservedType: rtReserved; Words: 'inherited'), (ReservedType: rtInitialization; Words: 'initialization'), (ReservedType: rtDirective; Words: 'inline'), (ReservedType: rtInterface; Words: 'interface'), (ReservedType: rtOper; Words: 'is'), (ReservedType: rtVar; Words: 'label'), (ReservedType: rtFuncDirective; Words: 'library'), (ReservedType: rtFuncDirective; Words: 'message'), (ReservedType: rtOper; Words: 'mod'), (ReservedType: rtFuncDirective; Words: 'name'), (ReservedType: rtFuncDirective; Words: 'near'), (ReservedType: rtReserved; Words: 'nil'), (ReservedType: rtFuncDirective; Words: 'nodefault'), (ReservedType: rtOper; Words: 'not'), (ReservedType: rtClass; Words: 'object'), (ReservedType: rtOf; Words: 'of'), (ReservedType: rtOn; Words: 'on'), (ReservedType: rtOper; Words: 'or'), (ReservedType: rtReserved; Words: 'out'), (ReservedType: rtFuncDirective; Words: 'overload'), (ReservedType: rtFuncDirective; Words: 'override'), (ReservedType: rtReserved; Words: 'packed'), (ReservedType: rtFuncDirective; Words: 'pascal'), (ReservedType: rtFuncDirective; Words: 'platform'), (ReservedType: rtPrivate; Words: 'private'), (ReservedType: rtProcedure; Words: 'procedure'), (ReservedType: rtProgram; Words: 'program'), (ReservedType: rtProcedure; Words: 'property'), (ReservedType: rtPrivate; Words: 'protected'), (ReservedType: rtPrivate; Words: 'public'), (ReservedType: rtPrivate; Words: 'published'), (ReservedType: rtReserved; Words: 'raise'), (ReservedType: rtFuncDirective; Words: 'read'), (ReservedType: rtFuncDirective; Words: 'readonly'), (ReservedType: rtRecord; Words: 'record'), (ReservedType: rtFuncDirective; Words: 'register'), (ReservedType: rtFuncDirective; Words: 'reintroduce'), (ReservedType: rtRepeat; Words: 'repeat'), (ReservedType: rtUses; Words: 'requires'), (ReservedType: rtFuncDirective; Words: 'resident'), (ReservedType: rtVar; Words: 'resourcestring'), (ReservedType: rtFuncDirective; Words: 'safecall'), (ReservedType: rtReserved; Words: 'set'), (ReservedType: rtOper; Words: 'shl'), (ReservedType: rtOper; Words: 'shr'), (ReservedType: rtFuncDirective; Words: 'stdcall'), (ReservedType: rtFuncDirective; Words: 'stored'), (ReservedType: rtPrivate; Words: 'strict'), (ReservedType: rtReserved; Words: 'string'), (ReservedType: rtThen; Words: 'then'), (ReservedType: rtVar; Words: 'threadvar'), (ReservedType: rtOper; Words: 'to'), (ReservedType: rtTry; Words: 'try'), (ReservedType: rtType; Words: 'type'), (ReservedType: rtProgram; Words: 'unit'), (ReservedType: rtUntil; Words: 'until'), (ReservedType: rtUses; Words: 'uses'), (ReservedType: rtVar; Words: 'var'), (ReservedType: rtFuncDirective; Words: 'virtual'), (ReservedType: rtWhile; Words: 'while'), (ReservedType: rtWhile; Words: 'with'), (ReservedType: rtFuncDirective; Words: 'write'), (ReservedType: rtFuncDirective; Words: 'writeonly'), (ReservedType: rtOper; Words: 'xor') ); type {: a TStrCollection that compares case insensitively } TKeywordColl = class(TStrCollection) public {: compares Key1 and Key2 as strings, case insensitively } function Compare(Key1, Key2: Pointer): Integer; override; end; {: changes the string case as specified in aCase @param aStr is the input string @param aCase is a TCase specifying the desired case @returns the modified string } function AdjustCase(aStr: string; aCase: TCase): string; implementation function AdjustCase(aStr: string; aCase: TCase): string; var i: Integer; begin case aCase of rfUpperCase: Result := UpperCase(aStr); rfLowerCase: Result := LowerCase(aStr); rfFirstUp: begin Result := LowerCase(aStr); i := 1; while Result[i] in [' ', Tab] do Inc(i); Result[i] := UpCase(Result[i]); end; else Result := aStr; end; end; { TKeywordColl } function TKeywordColl.Compare(Key1, Key2: Pointer): Integer; begin Result := StrIComp(Key1, Key2); end; end.
unit dmdItensCartaCorrecao; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, dmdPadrao, DBTables, DB; type TdmodItensCartaCorrecao = class(TdmodPadrao) qryManutencaoFIL_CARTA: TStringField; qryManutencaoNRO_CARTA: TIntegerField; qryManutencaoCOD_OCORRENCIA: TSmallintField; qryManutencaoHISTORICO: TMemoField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryLocalizacaoFIL_CARTA: TStringField; qryLocalizacaoNRO_CARTA: TIntegerField; qryLocalizacaoCOD_OCORRENCIA: TSmallintField; qryLocalizacaoHISTORICO: TMemoField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryManutencaoNM_OCORRENCIA: TStringField; qryLocalizacaoNM_OCORRENCIA: TStringField; qryManutencaoSEQUENCIA: TIntegerField; qryManutencaoDIGEST_VALUE: TStringField; qryManutencaoPROTOCOLO: TStringField; qryManutencaoXML_EVENTO: TBlobField; qryLocalizacaoSEQUENCIA: TIntegerField; qryLocalizacaoDIGEST_VALUE: TStringField; qryLocalizacaoPROTOCOLO: TStringField; qryLocalizacaoXML_EVENTO: TBlobField; procedure DataModuleDestroy(Sender: TObject); procedure qryManutencaoCalcFields(DataSet: TDataSet); private sCod_Emissora : String; rNro_Carta : Real; iCod_Ocorrencia : Integer; function GetCodigo: Integer; function GetEmissora: String; function GetNro_Carta: Real; procedure SetCodigo(const Value: Integer); procedure SetEmissora(const Value: String); procedure SetNro_Carta(const Value: Real); public procedure MontaSQLBusca(DataSet :TDataSet = Nil); override; procedure MontaSQLRefresh; override; property Emissora :String read GetEmissora write SetEmissora; property Nro_Carta :Real read GetNro_Carta write SetNro_Carta; property Cod_Ocorrencia :Integer read GetCodigo write SetCodigo; function LocalizarPorCarta(DataSet: TDataSet = Nil) :Boolean; end; var dmodItensCartaCorrecao: TdmodItensCartaCorrecao; implementation uses dmdHistOcorrencias; {$R *.dfm} { TdmodItensCartaCorrecao } function TdmodItensCartaCorrecao.GetCodigo: Integer; begin Result := iCod_Ocorrencia; end; function TdmodItensCartaCorrecao.GetEmissora: String; begin Result := sCod_Emissora; end; function TdmodItensCartaCorrecao.GetNro_Carta: Real; begin Result := rNro_Carta; end; procedure TdmodItensCartaCorrecao.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TQuery) do begin SQL.Clear; SQL.Add('SELECT * FROM STWFATTITMC'); SQL.Add('WHERE ( FIL_CARTA = :FIL_CARTA ) AND ( NRO_CARTA = :NRO_CARTA ) AND ( COD_OCORRENCIA = :COD_OCORRENCIA )'); SQL.Add('ORDER BY FIL_CARTA, NRO_CARTA, COD_OCORRENCIA'); Params[ 0].AsString := sCod_Emissora; Params[ 1].AsFloat := rNro_Carta; Params[ 2].AsInteger := iCod_Ocorrencia; end; end; procedure TdmodItensCartaCorrecao.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add('SELECT * FROM STWFATTITMC'); SQL.Add('ORDER BY FIL_CARTA, NRO_CARTA, COD_OCORRENCIA'); end; end; procedure TdmodItensCartaCorrecao.SetCodigo(const Value: Integer); begin iCod_Ocorrencia := Value; end; procedure TdmodItensCartaCorrecao.SetEmissora(const Value: String); begin sCod_Emissora := Value; end; procedure TdmodItensCartaCorrecao.SetNro_Carta(const Value: Real); begin rNro_Carta := Value; end; procedure TdmodItensCartaCorrecao.DataModuleDestroy(Sender: TObject); begin inherited; dmodItensCartaCorrecao := Nil; end; function TdmodItensCartaCorrecao.LocalizarPorCarta( DataSet: TDataSet): Boolean; begin if DataSet = Nil then DataSet := qryLocalizacao; with (DataSet as TQuery) do begin Close; Unprepare; SQL.Clear; SQL.Add('SELECT * FROM STWFATTITMC'); SQL.Add('WHERE ( FIL_CARTA = :FIL_CARTA ) AND ( NRO_CARTA = :NRO_CARTA )'); SQL.Add('ORDER BY FIL_CARTA, NRO_CARTA, COD_OCORRENCIA'); Params[ 0].AsString := sCod_Emissora; Params[ 1].AsFloat := rNro_Carta; Prepare; Open; Result := Not IsEmpty; end; end; procedure TdmodItensCartaCorrecao.qryManutencaoCalcFields( DataSet: TDataSet); begin inherited; if Not UtilizaCalculados then exit; if (DataSet as TQuery).State in [dsInsert, dsEdit] then exit; if Not Assigned(dmodHistOcorrencias) then dmodHistOcorrencias := TdmodHistOcorrencias.Create(Application); dmodHistOcorrencias.Cod_Ocorrencia := (DataSet as TQuery).FieldByName('COD_OCORRENCIA').AsInteger; if dmodHistOcorrencias.Localizar then (DataSet as TQuery).FieldByName('NM_OCORRENCIA').AsString := dmodHistOcorrencias.qryLocalizacaoDESCRICAO.AsString; end; end.
unit Variant1D; interface uses Classes; type VariantTernary1D = class(TPersistent) private data: array of Variant; fq,fqmin1: Integer; //число тритов fT,fN: Integer; //полное число элементов (total) и макс/мин значение (-N;N) base: Integer; //смещение нулевого отсчета function getValue(i: Integer): Variant; procedure set_value(i: Integer; value: Variant); public procedure Assign(asource: TPersistent); override; procedure Set_Length(aT: Integer); procedure inversion; property Value[i: Integer]: Variant read getValue write set_value; default; property N: Integer read fN; property T: Integer read fT; procedure GeneralFFT(isInverse: Boolean); procedure FFT; procedure Convolute(response: VariantTernary1D); procedure CyclicConvolute(response: VariantTernary1D); procedure LinearConvolute(response: VariantTernary1D); procedure inverseFFT; function AsString: string; constructor Create; end; implementation uses math,streaming_class_lib,VarCmplx,Variants; (* VariantTernary1D *) constructor VariantTernary1D.Create; begin inherited Create; Set_Length(0); end; procedure VariantTernary1D.Set_Length(aT: Integer); begin assert(aT>-1,'Set_Length: negative argument'); if aT=0 then begin fq:=-1; fqmin1:=-2; fT:=0; fN:=-1; SetLength(data,0); end else begin fq:=math.Ceil(ln(aT)/ln(3)); fqmin1:=fq-1; fT:=Round(power(3,fq)); fN:=(fT-1) div 2; SetLength(data,T); base:=fN; end; end; function VariantTernary1D.getValue(i: Integer): Variant; begin assert((i<=fN) and (i>=-fN),'getValue index out of range'); Result:=data[base+i]; end; procedure VariantTernary1D.set_Value(i: Integer; value: Variant); begin assert((i<=fN) and (i>=-fN),'set_Value index out of range'); data[base+i]:=value; end; procedure VariantTernary1D.inversion; var i,k,j,ma,ik: Integer; begin i:=0; ma:=fN-2; ik:=fT div 3; for j:=1 to ma do begin k:=ik; i:=i+k; while i>fN do begin i:=i-3*k; k:=k div 3; i:=i+k; end; if (j<i) then begin SwapVariants(data[base+i],data[base+j]); SwapVariants(data[base-i],data[base-j]); end else if (i<0) then SwapVariants(data[base+i],data[base+j]); end; end; procedure VariantTernary1D.GeneralFFT(isInverse: Boolean); var sgn,N1,M1,T1,k,j,incr,big_incr,i: Integer; Ph,TwoPi: Real; //W - фазовый множитель, r,i - действ. и мнимое знач. xsum,ysum,xdif,ydif,ax,ay : Real; xp,xm,x0: Variant; w,wn: Variant; //поворот на pi/3 и -pi/3 incW, Tw,Twm: Variant; //twiddle factor (фаз. множитель) и его приращ //p1,0,m1 - +1,0,-1 соотв begin if isInverse then sgn:=1 else sgn:=-1; w:=VarComplexCreate(-0.5,-sqrt(3)/2*sgn); wn:=VarComplexConjugate(w); TwoPi:=2*pi*sgn; inversion; T1:=fT; N1:=fN; incr:=1; while N1>0 do begin T1:=T1 div 3; N1:=(T1-1) div 2; big_incr:=incr*3; //для внутреннего цикла M1:=(incr-1) div 2; //для внешнего //отдельно обработаем i=0, там фазовый множ. не нужен for k:=-N1 to N1 do begin j:=base+big_incr*k; //отдельно обраб. нулевое значение - там не нужно фаз. множителей x0:=data[j]; xp:=data[j+incr]; xm:=data[j-incr]; data[j]:=x0+xp+xm; data[j+incr]:=x0+xp*w+xm*wn; data[j-incr]:=x0+xp*wn+xm*w; end; //шаг фазового множителя: 2pi/incr; //на первой итерации просто 2pi, но там цикл и не запустится //на второй итер: Ph:=TwoPi/big_incr; incW:=VarComplexCreate(cos(Ph),-sin(Ph)); Tw:=VarComplexCreate(1); for i:=1 to M1 do begin //пересчитываем фазовый множитель, потом делаем циклы для i и -i Tw:=Tw*incW; Twm:=VarComplexConjugate(Tw); for k:=-N1 to N1 do begin //итерация для +i j:=base+i+big_incr*k; //x0,y0 - без изменений x0:=data[j]; xp:=data[j+incr]*Tw; xm:=data[j-incr]*Twm; data[j]:=x0+xp+xm; data[j+incr]:=x0+xp*w+xm*wn; data[j-incr]:=x0+xp*wn+xm*w; //Теперь, то же самое для элемента -i j:=base-i+big_incr*k; //x0,y0 - без изменений x0:=data[j]; xp:=data[j+incr]*Twm; xm:=data[j-incr]*Tw; data[j]:=x0+xp+xm; data[j+incr]:=x0+xp*w+xm*wn; data[j-incr]:=x0+xp*wn+xm*w; end; end; //конец одного слоя incr:=big_incr; end; end; procedure VariantTernary1D.FFT; var i: Integer; begin GeneralFFT(false); for i:=0 to fT-1 do data[i]:=data[i]/fT; end; procedure VariantTernary1D.inverseFFT; begin GeneralFFT(true); end; procedure VariantTernary1D.Assign(aSource: TPersistent); var s: VariantTernary1D absolute aSource; begin if aSource is VariantTernary1D then begin data:=Copy(s.data); fN:=s.fN; fT:=s.fT; fq:=s.fq; fqmin1:=s.fqmin1; base:=s.base; end else inherited; end; procedure VariantTernary1D.Convolute(response: VariantTernary1D); var cresp: VariantTernary1D; i: Integer; begin cresp:=VariantTernary1D.Create; cresp.Assign(response); cresp.GeneralFFT(false); //без деления на N FFT; for i:=0 to fT-1 do data[i]:=data[i]*cresp.data[i]; cresp.Free; inverseFFT; //обратное end; procedure VariantTernary1D.LinearConvolute(response: VariantTernary1D); var i,j: Integer; temp: VariantTernary1D; const zero: Real=0.0; begin temp:=VariantTernary1D.Create; temp.Set_Length(fT); for i:=-fN to fN do begin temp[i]:=zero; for j:=-response.fN to response.fN do if (i-j>=-fN) and (i-j<=fN) then temp[i]:=temp[i]+Value[i-j]*response[j]; end; Assign(temp); temp.Free; end; procedure VariantTernary1D.CyclicConvolute(response: VariantTernary1D); var i,j,k: Integer; temp: VariantTernary1D; const zero: Real=0.0; begin temp:=VariantTernary1D.Create; temp.Set_Length(fT); for i:=-fN to fN do begin temp[i]:=zero; for j:=-response.fN to response.fN do begin k:=i-j; if k>fN then k:=k-fT else if k<-fN then k:=k+fT; temp[i]:=temp[i]+value[k]*response[j]; end; end; Assign(temp); temp.Free; end; function VariantTernary1D.AsString: string; var i: Integer; begin for i:=0 to fT-1 do Result:=Result+VarToStr(data[i])+';'; 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.17 7/13/04 6:46:36 PM RLebeau Added support for BoundPortMin/Max propeties } { Rev 1.16 6/6/2004 12:49:40 PM JPMugaas Removed old todo's for things that have already been done. } { Rev 1.15 5/6/2004 6:04:44 PM JPMugaas Attempt to reenable TransparentProxy.Bind. } { Rev 1.14 5/5/2004 2:08:40 PM JPMugaas Reenabled Socks Listen for TIdSimpleServer. } { Rev 1.13 2004.02.03 4:16:52 PM czhower For unit name changes. } { Rev 1.12 2004.01.20 10:03:34 PM czhower InitComponent } { Rev 1.11 1/2/2004 12:02:16 AM BGooijen added OnBeforeBind/OnAfterBind } { Rev 1.10 1/1/2004 10:57:58 PM BGooijen Added IPv6 support } { Rev 1.9 10/26/2003 10:08:44 PM BGooijen Compiles in DotNet } { Rev 1.8 10/20/2003 03:04:56 PM JPMugaas Should now work without Transparant Proxy. That still needs to be enabled. } { Rev 1.7 2003.10.14 9:57:42 PM czhower Compile todos } { Rev 1.6 2003.10.11 5:50:12 PM czhower -VCL fixes for servers -Chain suport for servers (Super core) -Scheduler upgrades -Full yarn support } { Rev 1.5 2003.09.30 1:23:02 PM czhower Stack split for DotNet } { Rev 1.4 5/16/2003 9:25:36 AM BGooijen TransparentProxy support } { Rev 1.3 3/29/2003 5:55:04 PM BGooijen now calls AfterAccept } { Rev 1.2 3/23/2003 11:24:46 PM BGooijen changed cast from TIdIOHandlerStack to TIdIOHandlerSocket } { Rev 1.1 1-6-2003 21:39:00 BGooijen The handle to the listening socket was not closed when accepting a connection. This is fixed by merging the responsible code from 9.00.11 Rev 1.0 11/13/2002 08:58:40 AM JPMugaas } unit IdSimpleServer; interface {$i IdCompilerDefines.inc} uses Classes, IdException, IdGlobal, IdSocketHandle, IdTCPConnection, IdStackConsts, IdIOHandler; const ID_ACCEPT_WAIT = 1000; type TIdSimpleServer = class(TIdTCPConnection) protected FAbortedRequested: Boolean; FAcceptWait: Integer; FBoundIP: String; FBoundPort: TIdPort; FBoundPortMin: TIdPort; FBoundPortMax: TIdPort; FIPVersion: TIdIPVersion; FListenHandle: TIdStackSocketHandle; FListening: Boolean; FOnBeforeBind: TNotifyEvent; FOnAfterBind: TNotifyEvent; // procedure Bind; procedure DoBeforeBind; virtual; procedure DoAfterBind; virtual; function GetBinding: TIdSocketHandle; procedure InitComponent; override; procedure SetIOHandler(AValue: TIdIOHandler); override; procedure SetIPVersion(const AValue: TIdIPVersion); public procedure Abort; virtual; procedure BeginListen; virtual; procedure CreateBinding; procedure EndListen; virtual; procedure Listen(ATimeout: Integer = IdTimeoutDefault); virtual; // property AcceptWait: Integer read FAcceptWait write FAcceptWait default ID_ACCEPT_WAIT; published property BoundIP: string read FBoundIP write FBoundIP; property BoundPort: TIdPort read FBoundPort write FBoundPort; property BoundPortMin: TIdPort read FBoundPortMin write FBoundPortMin; property BoundPortMax: TIdPort read FBoundPortMax write FBoundPortMax; property Binding: TIdSocketHandle read GetBinding; property IPVersion: TIdIPVersion read FIPVersion write SetIPVersion; property OnBeforeBind: TNotifyEvent read FOnBeforeBind write FOnBeforeBind; property OnAfterBind: TNotifyEvent read FOnAfterBind write FOnAfterBind; end; EIdCannotUseNonSocketIOHandler = class(EIdException); implementation uses IdExceptionCore, IdIOHandlerStack, IdIOHandlerSocket, IdResourceStringsCore, IdStack; { TIdSimpleServer } procedure TIdSimpleServer.Abort; begin FAbortedRequested := True; end; procedure TIdSimpleServer.BeginListen; begin // Must be before IOHandler as it resets it if not Assigned(Binding) then begin EndListen; CreateBinding; end; if Socket.TransparentProxy.Enabled then begin Socket.Binding.IP := BoundIP; Socket.TransparentProxy.Bind(FIOHandler, BoundPort); end else begin Bind; Binding.Listen(1); end; FListening := True; end; procedure TIdSimpleServer.Bind; begin with Binding do begin try DoBeforeBind; IPVersion := Self.FIPVersion; // needs to be before AllocateSocket, because AllocateSocket uses this AllocateSocket; FListenHandle := Handle; IP := BoundIP; Port := BoundPort; ClientPortMin := BoundPortMin; ClientPortMax := BoundPortMax; Bind; DoAfterBind; except FListenHandle := Id_INVALID_SOCKET; raise; end; end; end; procedure TIdSimpleServer.CreateBinding; begin if not Assigned(IOHandler) then begin CreateIOHandler(); end; IOHandler.Open; end; procedure TIdSimpleServer.DoBeforeBind; begin if Assigned(FOnBeforeBind) then begin FOnBeforeBind(self); end; end; procedure TIdSimpleServer.DoAfterBind; begin if Assigned(FOnAfterBind) then begin FOnAfterBind(self); end; end; procedure TIdSimpleServer.EndListen; begin FAbortedRequested := False; FListening := False; end; function TIdSimpleServer.GetBinding: TIdSocketHandle; begin if Assigned(Socket) then begin Result := Socket.Binding; end else begin Result := nil; end; end; procedure TIdSimpleServer.SetIOHandler(AValue: TIdIOHandler); begin if Assigned(AValue) then begin if not (AValue is TIdIOHandlerSocket) then begin raise EIdCannotUseNonSocketIOHandler.Create(RSCannotUseNonSocketIOHandler); end; end; inherited SetIOHandler(AValue); end; procedure TIdSimpleServer.SetIPVersion(const AValue: TIdIPVersion); begin FIPVersion := AValue; if Assigned(Socket) then begin Socket.IPVersion := AValue; end; end; procedure TIdSimpleServer.Listen(ATimeout: Integer = IdTimeoutDefault); var LAccepted: Boolean; function DoListenTimeout(ALTimeout: Integer; AUseProxy: Boolean): Boolean; var LSleepTime: Integer; begin LSleepTime := AcceptWait; if ALTimeout = IdTimeoutDefault then begin ALTimeout := IdTimeoutInfinite; end; if ALTimeout = IdTimeoutInfinite then begin repeat if AUseProxy then begin Result := Socket.TransparentProxy.Listen(IOHandler, LSleepTime); end else begin Result := Binding.Select(LSleepTime); end; until Result or FAbortedRequested; Exit; end; while ALTimeout > LSleepTime do begin if AUseProxy then begin Result := Socket.TransparentProxy.Listen(IOHandler, LSleepTime); end else begin Result := Binding.Select(LSleepTime); end; if Result or FAbortedRequested then begin Exit; end; Dec(ALTimeout, LSleepTime); end; if AUseProxy then begin Result := Socket.TransparentProxy.Listen(IOHandler, ALTimeout); end else begin Result := Binding.Select(ALTimeout); end; end; begin if not FListening then begin BeginListen; end; if Socket.TransparentProxy.Enabled then begin LAccepted := DoListenTimeout(ATimeout, True); end else begin LAccepted := DoListenTimeout(ATimeout, False); if LAccepted then begin Binding.Accept(Binding.Handle); IOHandler.AfterAccept; end; // This is now protected. Disconnect replaces it - but it also calls shutdown. // Im not sure we want to call shutdown here? Need to investigate before fixing // this. GStack.Disconnect(FListenHandle); FListenHandle := Id_INVALID_SOCKET; end; if not LAccepted then begin raise EIdAcceptTimeout.Create(RSAcceptTimeout); end; end; procedure TIdSimpleServer.InitComponent; begin inherited InitComponent; FAcceptWait := ID_ACCEPT_WAIT; FListenHandle := Id_INVALID_SOCKET; end; end.
unit Ragna.Criteria.Impl; {$IF DEFINED(FPC)} {$MODE DELPHI}{$H+} {$ENDIF} interface uses {$IFDEF UNIDAC}Uni{$ELSE}FireDAC.Comp.Client, FireDAC.Stan.Param{$ENDIF}, StrUtils, Data.DB, System.Hash, Ragna.Criteria.Intf, Ragna.Types; type TDefaultCriteria = class(TInterfacedObject, ICriteria) private FQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}; procedure Where(const AField: string); procedure &Or(const AField: string); procedure &And(const AField: string); procedure Like(const AValue: string); procedure &Equals(const AValue: Int64); reintroduce; overload; procedure &Equals(const AValue: Boolean); reintroduce; overload; procedure &Equals(const AValue: string); reintroduce; overload; procedure Order(const AField: string); public constructor Create(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}); end; TManagerCriteria = class private FCriteria: ICriteria; function GetDrive(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}): string; function GetInstanceCriteria(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}): ICriteria; public constructor Create(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}); property Criteria: ICriteria read FCriteria write FCriteria; end; implementation uses FireDAC.Stan.Intf, SysUtils; procedure TDefaultCriteria.&And(const AField: string); const PHRASE = '%s %s'; begin FQuery.SQL.Add(Format(PHRASE, [TOperatorType.AND.ToString, AField])); end; procedure TDefaultCriteria.&Or(const AField: string); const PHRASE = ' %s %s'; begin FQuery.SQL.Add(Format(PHRASE, [TOperatorType.OR.ToString, AField])); end; constructor TDefaultCriteria.Create(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}); begin FQuery := AQuery; end; procedure TDefaultCriteria.Equals(const AValue: Boolean); const PHRASE = '%s %s'; begin FQuery.SQL.Add(Format(PHRASE, [TOperatorType.EQUALS.ToString, BoolToStr(AValue, True)])); end; procedure TDefaultCriteria.Equals(const AValue: Int64); const PHRASE = '%s %d'; begin FQuery.SQL.Add(Format(PHRASE, [TOperatorType.EQUALS.ToString, AValue])); end; procedure TDefaultCriteria.Equals(const AValue: string); const PHRASE = '%s ''%s'''; begin FQuery.SQL.Add(Format(PHRASE, [TOperatorType.EQUALS.ToString, AValue])); end; procedure TDefaultCriteria.Like(const AValue: string); const PHRASE = ' %s %s'; var LKeyParam: string; LParam: {$IFDEF UNIDAC}TUniParam{$ELSE}TFDParam{$ENDIF}; begin LKeyParam := THashMD5.Create.HashAsString; FQuery.SQL.Text := FQuery.SQL.Text + Format(PHRASE, [TOperatorType.LIKE.ToString, ':' + LKeyParam]); LParam := FQuery.ParamByName(LKeyParam); LParam.DataType := ftString; if Pos('%', AValue) <= 0 then LParam.Value := AValue + '%' else LParam.Value := AValue; end; procedure TDefaultCriteria.Where(const AField: string); const PHRASE = '%s %s'; begin FQuery.SQL.Add(Format(PHRASE, [TOperatorType.WHERE.ToString, AField])); end; procedure TDefaultCriteria.Order(const AField: string); const PHRASE = '%s %s'; begin FQuery.SQL.Add(Format(PHRASE, [TOperatorType.ORDER.ToString, AField])); end; constructor TManagerCriteria.Create(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}); begin FCriteria := GetInstanceCriteria(AQuery); end; function TManagerCriteria.GetDrive(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}): string; {$IFDEF UNIDAC} begin Result := AQuery.Connection.ProviderName; end; {$ELSE} var LDef: IFDStanConnectionDef; begin Result := AQuery.Connection.DriverName; if Result.IsEmpty and not AQuery.Connection.ConnectionDefName.IsEmpty then begin LDef := FDManager.ConnectionDefs.FindConnectionDef(AQuery.Connection.ConnectionDefName); if LDef = nil then raise Exception.Create('ConnectionDefs "' + AQuery.Connection.ConnectionDefName + '" not found'); Result := LDef.Params.DriverID; end; end; {$ENDIF} function TManagerCriteria.GetInstanceCriteria(const AQuery: {$IFDEF UNIDAC}TUniQuery{$ELSE}TFDQuery{$ENDIF}): ICriteria; begin case AnsiIndexStr(GetDrive(AQuery), ['PG']) of 0: Result := TDefaultCriteria.Create(AQuery); else Result := TDefaultCriteria.Create(AQuery); end; end; end.
unit UBlockChain; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} { Copyright (c) 2016 by Albert Molina Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of Pascal Coin, a P2P crypto currency without need of historical operations. If you like it, consider a donation using BitCoin: 16K3HCZRhFUtM8GdWRcfKeaa6KsuyxZaYk } interface uses Classes, UCrypto, UAccounts, ULog, UThread, SyncObjs, UOperationBlock, UOperationsHashTree, UOperationResume; {$I config.inc} { Bank BlockChain: Safe Box content: (See Unit "UAccounts.pas" to see pascal code) +--------------+--------------------------------------------------+------------+------------+ + BlockAccount + Each BlockAccount has N "Account" + Timestamp + Block Hash + + +--------------------------------------------------+ + + + + Addr B0 + Public key + Balance + updated + n_op + + + + + Addr B1 + Public key + Balance + updated + n_op + + + + + ...... + + + + + Addr B4 + Public key + Balance + updated + n_op + + + +--------------+---------+----------------------------------------+------------+------------+ + 0 + 0 + pk_aaaaaaa + 100.0000 + 0 + 0 + 1461701856 + Sha256() + + + 1 + pk_aaaaaaa + 0.0000 + 0 + 0 + + = h1111111 + + + 2 + pk_aaaaaaa + 0.0000 + 0 + 0 + + + + + 3 + pk_aaaaaaa + 0.0000 + 0 + 0 + + + + + 4 + pk_aaaaaaa + 0.0000 + 0 + 0 + + + +--------------+---------+----------------------------------------+------------+------------+ + 1 + 5 + pk_bbbbbbb + 100.0000 + 0 + 0 + 1461702960 + Sha256() + + + 6 + pk_bbbbbbb + 0.0000 + 0 + 0 + + = h2222222 + + + 7 + pk_bbbbbbb + 0.0000 + 0 + 0 + + + + + 8 + pk_bbbbbbb + 0.0000 + 0 + 0 + + + + + 9 + pk_bbbbbbb + 0.0000 + 0 + 0 + + + +--------------+---------+----------------------------------------+------------+------------+ + ................ + +--------------+---------+----------------------------------------+------------+------------+ + 5 + 25 + pk_bbbbbbb + 100.0000 + 0 + 0 + 1461713484 + Sha256() + + + 26 + pk_bbbbbbb + 0.0000 + 0 + 0 + + = h3333333 + + + 27 + pk_bbbbbbb + 0.0000 + 0 + 0 + + + + + 28 + pk_bbbbbbb + 0.0000 + 0 + 0 + + + + + 29 + pk_bbbbbbb + 0.0000 + 0 + 0 + + + +--------------+---------+----------------------------------------+------------+------------+ + Safe Box Hash : Sha256(h1111111 + h2222222 + ... + h3333333) = sbh_A1 + +-------------------------------------------------------------------------------------------+ BlockChain: To generate a BlockChain (block X) we need the previous "Safe Box Hash" (the Safe Box Hash number X-1, generated when BlockChain X-1 was generated) Each BlockChain block generates a new "Safe Box" with a new "Safe Box Hash" With this method, Safe Box is unique after a BlockChain, so we can assume that a hard coded Safe Box X is the same that to load all previous BlockChain from 0 to X. Conclusion: It's not necessary historical operations (block chains) to work with Pascal Coin Some BlockChain fields: +-------+-----------------+----------+------+-----+-----+------------+--------+-------+---------------+---------------+-----------------+---------------+-----------------------+ + Block + Account key + reward + fee + protocols + timestamp + target + nonce + Miner Payload + safe box hash + operations hash + Proof of Work + Operations stream + +-------+-----------------+----------+------+-----+-----+------------+--------+-------+---------------+---------------+-----------------+---------------+-----------------------+ + 0 + (hard coded) + 100.0000 + 0 + 1 + 0 + 1461701856 + trgt_1 + ... + (Hard coded) + (Hard coded) + Sha256(Operat.) + 000000C3F5... + Operations of block 0 + +-------+-----------------+----------+------+-----+-----+------------+--------+-------+---------------+---------------+-----------------+---------------+-----------------------+ + 1 + hhhhhhhhhhhhhhh + 100.0000 + 0 + 1 + 0 + 1461701987 + trgt_1 + ... + ... + SFH block 0 + Sha256(Operat.) + 000000A987... + Operations of block 1 + +-------+-----------------+----------+------+-----+-----+------------+--------+-------+---------------+---------------+-----------------+---------------+-----------------------+ + 2 + iiiiiiiiiiiiiii + 100.0000 + 0.43 + 1 + 0 + 1461702460 + trgt_1 + ... + ... + SFH block 1 + Sha256(Operat.) + 0000003A1C... + Operations of block 2 + +-------+-----------------+----------+------+-----+-----+------------+--------+-------+---------------+---------------+-----------------+---------------+-----------------------+ + ..... + +-------+-----------------+----------+------+-----+-----+------------+--------+-------+---------------+---------------+-----------------+---------------+-----------------------+ Considerations: - Account Key: Is a public key that will have all new generated Accounts of the Safe Box - Protocols are 2 values: First indicate protocol of this block, second future candidate protocol that is allowed by miner who made this. (For protocol upgrades) - Safe Box Has: Each Block of the Bloch Chain is made in base of a previous Safe Box. This value hard codes consistency - Operations Stream includes all the operations that will be made to the Safe Box after this block is generated. A hash value of Operations stream is "Operations Hash" Operations: Each Block of the Block Chain has its owns operations that will be used to change Safe Box after block is completed and included in BlockChain Operations of actual Protocol (version 1) can be one of this: - Transaction from 1 account to 1 account - Change AccountKey of an account - Recover balance from an unused account (lost keys) Each Operation has a Hash value that is used to generate "Operations Hash". Operations Hash is a Sha256 of all the Operations included inside it hashed like a Merkle Tree. In unit "UOpTransaction.pas" you can see how each Operation Works. } implementation uses {Messages, } SysUtils, Variants, {Graphics,} {Controls, Forms,} Dialogs, {StdCtrls,} UTime, UConst, UOpTransaction; initialization finalization end.
{ Subroutine SST_W_C_SMENT_START * * Set up for writing the start of a new statement. The write pointer will be * tabbed to the current indentation level, and the level will be incremented * by one. This way any continuation lines for this statement will automatically * be indented one level more than the first line of the statement. * * The current statement state is pushed onto the stack and a new state * created that will be used for any nested statements. * * This subroutine is intended to be used together with SST_W_C_SMENT_END. } module sst_w_c_SMENT_START; define sst_w_c_sment_start; %include 'sst_w_c.ins.pas'; procedure sst_w_c_sment_start; {set for writing start of a new statement} var frame_p: frame_sment_p_t; {points to new stack frame} begin util_stack_push ( {create stack frame for this statement} sst_stack, sizeof(frame_p^), frame_p); frame_p^.pos_before := sst_out.dyn_p^; {save position at start of statement} frame_p^.prev_p := frame_sment_p; {save pointer to previous sment stack frame} frame_sment_p := frame_p; {set new stack frame as current} sst_w.tab_indent^; {go to current indentation level} sst_w.indent^; {set indentation level for continuation lines} end;
unit WorkforceSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, ExtCtrls, InternationalizerComponent; const tidCurrBlock = 'CurrBlock'; tidSecurityId = 'SecurityId'; tidTrouble = 'Trouble'; tidSalaries0 = 'Salaries0'; tidWorkForcePrice0 = 'WorkForcePrice0'; tidSalaryValues0 = 'SalaryValues0'; tidWorkers0 = 'Workers0'; tidWorkersK0 = 'WorkersK0'; tidWorkersMax0 = 'WorkersMax0'; tidWorkersCap0 = 'WorkersCap0'; tidSalaries1 = 'Salaries1'; tidWorkForcePrice1 = 'WorkForcePrice1'; tidSalaryValues1 = 'SalaryValues'; tidWorkers1 = 'Workers1'; tidWorkersK1 = 'WorkersK1'; tidWorkersMax1 = 'WorkersMax1'; tidWorkersCap1 = 'WorkersCap1'; tidSalaries2 = 'Salaries2'; tidWorkForcePrice2 = 'WorkForcePrice2'; tidSalaryValues2 = 'SalaryValues2'; tidWorkers2 = 'Workers2'; tidWorkersK2 = 'WorkersK2'; tidWorkersMax2 = 'WorkersMax2'; tidWorkersCap2 = 'WorkersCap2'; tidMinSalaries0 = 'MinSalaries0'; tidMinSalaries1 = 'MinSalaries1'; tidMinSalaries2 = 'MinSalaries2'; const facStoppedByTycoon = $04; type TWorkforceSheetHandler = class; TWorkforceSheetViewer = class(TVisualControl) pnLow: TPanel; pnMiddle: TPanel; pnHigh: TPanel; Panel4: TPanel; FirstLabel: TLabel; Label2: TLabel; lbHiTitle: TLabel; lbMiTitle: TLabel; lbLoTitle: TLabel; Label6: TLabel; Workers0: TLabel; Workers1: TLabel; Workers2: TLabel; WorkersK0: TLabel; WorkersK1: TLabel; WorkersK2: TLabel; Salaries0: TLabel; Salaries1: TLabel; Salaries2: TLabel; xfer_Salaries0: TPercentEdit; xfer_Salaries1: TPercentEdit; xfer_Salaries2: TPercentEdit; tRefresh: TTimer; InternationalizerComponent1: TInternationalizerComponent; procedure xfer_Salaries0Change(Sender: TObject); procedure xfer_Salaries0MoveBar(Sender: TObject); procedure xfer_Salaries1MoveBar(Sender: TObject); procedure xfer_Salaries2MoveBar(Sender: TObject); procedure RenderWorkForce(Sender : TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TWorkforceSheetHandler; end; TWorkforceSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TWorkforceSheetViewer; fCurrBlock : integer; fOwnsFacility : boolean; fWFPrices : array[0..2] of single; fMaxJobs : array[0..2] of integer; public procedure SetContainer(aContainer : IPropertySheetContainerHandler); override; function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure threadedGetWorkforce(const parms : array of const); procedure threadedRenderWorkforce(const parms : array of const); procedure threadedSetSalaries(const parms : array of const); end; var WorkforceSheetViewer: TWorkforceSheetViewer; function WorkforceSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, FiveViewUtils, Protocol, SheetUtils, {$IFDEF VER140} Variants, {$ENDIF} Literals; {$R *.DFM} function CvtToMoney(str : string) : single; begin if str <> '' then try result := StrToFloat(str); except result := 0; end else result := 0; end; function CvtToInt(str : string) : integer; begin if str <> '' then try result := StrToInt(str); except result := 0; end else result := 0; end; // TWorkforceSheetHandler procedure TWorkforceSheetHandler.SetContainer(aContainer : IPropertySheetContainerHandler); begin inherited; end; function TWorkforceSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TWorkforceSheetViewer.Create(Owner); fControl.fHandler := self; result := fControl; end; function TWorkforceSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TWorkforceSheetHandler.RenderProperties(Properties : TStringList); var aux : string; begin fCurrBlock := CvtToInt(Properties.Values[tidCurrBlock]); fOwnsFacility := GrantAccess( fContainer.GetClientView.getSecurityId, Properties.Values[tidSecurityId] ); fWFPrices[0] := CvtToMoney(Properties.Values[tidWorkForcePrice0]); fWFPrices[1] := CvtToMoney(Properties.Values[tidWorkForcePrice1]); fWFPrices[2] := CvtToMoney(Properties.Values[tidWorkForcePrice2]); fControl.xfer_Salaries0.Enabled := fOwnsFacility; fControl.xfer_Salaries1.Enabled := fOwnsFacility; fControl.xfer_Salaries2.Enabled := fOwnsFacility; aux := Properties.Values[tidWorkersMax0]; fMaxJobs[0] := CvtToInt(aux); if (Properties.Values[tidWorkersCap0] = '') or (Properties.Values[tidWorkersCap0] = '0') then begin fControl.Workers0.Font.Color := fControl.FirstLabel.Font.Color; fControl.Workers0.Caption := GetLiteral('Literal160'); fControl.WorkersK0.Font.Color := fControl.FirstLabel.Font.Color; fControl.WorkersK0.Caption := GetLiteral('Literal161'); fControl.Salaries0.Font.Color := fControl.FirstLabel.Font.Color; fControl.Salaries0.Caption := GetLiteral('Literal162'); fControl.xfer_Salaries0.Visible := false; end else begin fControl.Workers0.Font.Color := clWhite; fControl.Workers0.Caption := GetFormattedLiteral('Literal163', [Properties.Values[tidWorkers0], aux]); fControl.WorkersK0.Font.Color := clWhite; fControl.WorkersK0.Caption := Properties.Values[tidWorkersK0] + '%'; fControl.xfer_Salaries0.Value := CvtToInt(Properties.Values[tidSalaries0]); fControl.Salaries0.Font.Color := clWhite; fControl.xfer_Salaries0.Visible := true; fControl.xfer_Salaries0.MidValue := CvtToInt(Properties.Values[tidMinSalaries0]); end; aux := Properties.Values[tidWorkersMax1]; fMaxJobs[1] := CvtToInt(aux); if (Properties.Values[tidWorkersCap1] = '') or (Properties.Values[tidWorkersCap1] = '0') then begin fControl.Workers1.Font.Color := fControl.FirstLabel.Font.Color; fControl.Workers1.Caption := GetLiteral('Literal164'); fControl.WorkersK1.Font.Color := fControl.FirstLabel.Font.Color; fControl.WorkersK1.Caption := GetLiteral('Literal165'); fControl.Salaries1.Font.Color := fControl.FirstLabel.Font.Color; fControl.Salaries1.Caption := GetLiteral('Literal166'); fControl.xfer_Salaries1.Visible := false; end else begin fControl.Workers1.Font.Color := clWhite; fControl.Workers1.Caption := GetFormattedLiteral('Literal167', [Properties.Values[tidWorkers1], aux]); fControl.WorkersK1.Font.Color := clWhite; fControl.WorkersK1.Caption := Properties.Values[tidWorkersK1] + '%'; fControl.xfer_Salaries1.Value := CvtToInt(Properties.Values[tidSalaries1]); fControl.Salaries1.Font.Color := clWhite; fControl.xfer_Salaries1.Visible := true; fControl.xfer_Salaries1.MidValue := CvtToInt(Properties.Values[tidMinSalaries1]); end; aux := Properties.Values[tidWorkersMax2]; fMaxJobs[2] := CvtToInt(aux); if (Properties.Values[tidWorkersCap2] = '') or (Properties.Values[tidWorkersCap2] = '0') then begin fControl.Workers2.Font.Color := fControl.FirstLabel.Font.Color; fControl.Workers2.Caption := GetLiteral('Literal168'); fControl.WorkersK2.Font.Color := fControl.FirstLabel.Font.Color; fControl.WorkersK2.Caption := GetLiteral('Literal169'); fControl.Salaries2.Font.Color := fControl.FirstLabel.Font.Color; fControl.Salaries2.Caption := GetLiteral('Literal170'); fControl.xfer_Salaries2.Visible := false; end else begin fControl.Workers2.Font.Color := clWhite; fControl.Workers2.Caption := GetFormattedLiteral('Literal171', [Properties.Values[tidWorkers2], aux]); fControl.WorkersK2.Font.Color := clWhite; fControl.WorkersK2.Caption := Properties.Values[tidWorkersK2] + '%'; fControl.xfer_Salaries2.Value := CvtToInt(Properties.Values[tidSalaries2]); fControl.Salaries2.Font.Color := clWhite; fControl.xfer_Salaries2.Visible := true; fControl.xfer_Salaries2.MidValue := CvtToInt(Properties.Values[tidMinSalaries2]); end; fControl.tRefresh.Enabled := true; end; procedure TWorkforceSheetHandler.SetFocus; begin if not fLoaded then begin inherited; fControl.tRefresh.Enabled := false; Threads.Fork(threadedGetProperties, priHigher, [fLastUpdate]); end; end; procedure TWorkforceSheetHandler.Clear; begin inherited; fControl.tRefresh.Enabled := false; fControl.Workers0.Caption := NA; fControl.Workers1.Caption := NA; fControl.Workers2.Caption := NA; fControl.WorkersK0.Caption := NA; fControl.WorkersK1.Caption := NA; fControl.WorkersK2.Caption := NA; fControl.Salaries0.Caption := NA; fControl.Salaries1.Caption := NA; fControl.Salaries2.Caption := NA; fControl.xfer_Salaries0.Value := 0; fControl.xfer_Salaries1.Value := 0; fControl.xfer_Salaries2.Value := 0; fControl.xfer_Salaries0.Enabled := false; fControl.xfer_Salaries1.Enabled := false; fControl.xfer_Salaries2.Enabled := false; end; procedure TWorkforceSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList; Update : integer absolute parms[0].vInteger; Prop : TStringList; begin try Names := TStringList.Create; try Names.Add(tidCurrBlock); Names.Add(tidSecurityId); Names.Add(tidSalaries0); Names.Add(tidWorkForcePrice0); Names.Add(tidSalaryValues0); Names.Add(tidWorkers0); Names.Add(tidWorkersK0); Names.Add(tidWorkersMax0); Names.Add(tidWorkersCap0); Names.Add(tidSalaries1); Names.Add(tidWorkForcePrice1); Names.Add(tidSalaryValues1); Names.Add(tidWorkers1); Names.Add(tidWorkersK1); Names.Add(tidWorkersMax1); Names.Add(tidWorkersCap1); Names.Add(tidSalaries2); Names.Add(tidWorkForcePrice2); Names.Add(tidSalaryValues2); Names.Add(tidWorkers2); Names.Add(tidWorkersK2); Names.Add(tidWorkersMax2); Names.Add(tidWorkersCap2); Names.Add(tidMinSalaries0); Names.Add(tidMinSalaries1); Names.Add(tidMinSalaries2); // Cache properties if Update = fLastUpdate then Prop := fContainer.GetProperties(Names) else Prop := nil; if Update = fLastUpdate then Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; finally Names.Free; end; except end; end; procedure TWorkforceSheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if parms[1].vInteger = fLastUpdate then RenderProperties(Prop); finally Prop.Free; end; except end; end; procedure TWorkforceSheetHandler.threadedGetWorkforce(const parms : array of const); var Proxy : OleVariant; hiVal : integer; miVal : integer; loVal : integer; begin try //Lock; try Proxy := fContainer.GetMSProxy; if (parms[0].vInteger = fLastUpdate) and not VarIsEmpty(Proxy) and (fCurrBlock <> 0) then begin Proxy.BindTo(fCurrBlock); if fMaxJobs[0] > 0 then hiVal := Proxy.RDOGetWorkers(integer(0)) else hiVal := 0; Proxy.BindTo(fCurrBlock); if fMaxJobs[1] > 0 then miVal := Proxy.RDOGetWorkers(integer(1)) else miVal := 0; Proxy.BindTo(fCurrBlock); if fMaxJobs[2] > 0 then loVal := Proxy.RDOGetWorkers(integer(2)) else loVal := 0; end else begin hiVal := 0; miVal := 0; loVal := 0; end; finally //Unlock; end; if parms[0].vInteger = fLastUpdate then Threads.Join(threadedRenderWorkforce, [hiVal, miVal, loVal, parms[0].vInteger]); except end; end; procedure TWorkforceSheetHandler.threadedRenderWorkforce(const parms : array of const); begin if parms[3].vInteger = fLastUpdate then begin if fMaxJobs[0] > 0 then fControl.Workers0.Caption := GetFormattedLiteral('Literal172', [parms[0].vInteger, fMaxJobs[0]]); if fMaxJobs[1] > 0 then fControl.Workers1.Caption := GetFormattedLiteral('Literal173', [parms[1].vInteger, fMaxJobs[1]]); if fMaxJobs[2] > 0 then fControl.Workers2.Caption := GetFormattedLiteral('Literal174', [parms[2].vInteger, fMaxJobs[2]]); end; end; procedure TWorkforceSheetHandler.threadedSetSalaries(const parms : array of const); var Proxy : OleVariant; begin if (fLastUpdate = parms[0].vInteger) and (fCurrBlock <> 0) and fOwnsFacility then try Proxy := fContainer.GetMSProxy; Proxy.BindTo(fCurrBlock); Proxy.WaitForAnswer := false; Proxy.RDOSetSalaries(parms[1].vInteger, parms[2].vInteger, parms[3].vInteger); except end; end; // TWorkforceSheetViewer procedure TWorkforceSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TWorkforceSheetViewer.xfer_Salaries0Change(Sender: TObject); begin Threads.Fork(fHandler.threadedSetSalaries, priNormal, [fHandler.fLastUpdate, xfer_Salaries0.Value, xfer_Salaries1.Value, xfer_Salaries2.Value]); end; procedure TWorkforceSheetViewer.xfer_Salaries0MoveBar(Sender: TObject); begin Salaries0.Caption := '$' + FloatToStr(fHandler.fWFPrices[0]*xfer_Salaries0.Value/100) + ' ( ' + IntToStr(xfer_Salaries0.Value) + ' %)'; end; procedure TWorkforceSheetViewer.xfer_Salaries1MoveBar(Sender: TObject); begin Salaries1.Caption := '$' + FloatToStr(fHandler.fWFPrices[1]*xfer_Salaries1.Value/100) + ' ( ' + IntToStr(xfer_Salaries1.Value) + ' %)'; end; procedure TWorkforceSheetViewer.xfer_Salaries2MoveBar(Sender: TObject); begin Salaries2.Caption := '$' + FloatToStr(fHandler.fWFPrices[2]*xfer_Salaries2.Value/100) + ' ( ' + IntToStr(xfer_Salaries2.Value) + ' %)'; end; procedure TWorkforceSheetViewer.RenderWorkForce(Sender : TObject); begin Threads.Fork(fHandler.threadedGetWorkforce, priNormal, [fHandler.fLastUpdate]); end; // WorkforceSheetHandlerCreator function WorkforceSheetHandlerCreator : IPropertySheetHandler; begin result := TWorkforceSheetHandler.Create; end; initialization SheetHandlerRegistry.RegisterSheetHandler('Workforce', WorkforceSheetHandlerCreator); end.
unit Pinger; interface uses SysUtils,WinSock,Windows; type ip_option_information = record // Информация заголовка IP (Наполнение // этой структуры и формат полей описан в RFC791. Ttl : u_char; // Время жизни (используется traceroute-ом) Tos : u_char; // Тип обслуживания, обычно 0 Flags : u_char; // Флаги заголовка IP, обычно 0 OptionsSize : u_char; // Размер данных в заголовке, обычно 0, максимум 40 OptionsData : PChar; // Указатель на данные end; icmp_echo_reply = record Address : DWORD; // Адрес отвечающего Status : u_long; // IP_STATUS (см. ниже) RTTime : u_long; // Время между эхо-запросом и эхо-ответом // в миллисекундах DataSize : u_short; // Размер возвращенных данных Reserved : u_short; // Зарезервировано Data : Pointer; // Указатель на возвращенные данные Options : ip_option_information; // Информация из заголовка IP end; PIPINFO = ^ip_option_information; PVOID = Pointer; function Ping(const IPStr:AnsiString; IP,Timeout:Cardinal):Integer; function IcmpCreateFile() : THandle; stdcall; external 'ICMP.DLL' name 'IcmpCreateFile'; function IcmpCloseHandle(IcmpHandle : THandle) : BOOL; stdcall; external 'ICMP.DLL' name 'IcmpCloseHandle'; function IcmpSendEcho( IcmpHandle : THandle; // handle, возвращенный IcmpCreateFile() DestAddress : u_long; // Адрес получателя (в сетевом порядке) RequestData : PVOID; // Указатель на посылаемые данные RequestSize : Word; // Размер посылаемых данных RequestOptns : PIPINFO; // Указатель на посылаемую структуру // ip_option_information (может быть nil) ReplyBuffer : PVOID; // Указатель на буфер, содержащий ответы. ReplySize : DWORD; // Размер буфера ответов Timeout : DWORD // Время ожидания ответа в миллисекундах ) : DWORD; stdcall; external 'ICMP.DLL' name 'IcmpSendEcho'; implementation //Коды ошибок в поле Status структуры icmp_echo_reply, если ответ не является "эхо-ответом" //(IP_STATUS): const IP_STATUS_BASE = 11000; IP_SUCCESS = 0; IP_BUF_TOO_SMALL = 11001; IP_DEST_NET_UNREACHABLE = 11002; IP_DEST_HOST_UNREACHABLE = 11003; IP_DEST_PROT_UNREACHABLE = 11004; IP_DEST_PORT_UNREACHABLE = 11005; IP_NO_RESOURCES = 11006; IP_BAD_OPTION = 11007; IP_HW_ERROR = 11008; IP_PACKET_TOO_BIG = 11009; IP_REQ_TIMED_OUT = 11010; IP_BAD_REQ = 11011; IP_BAD_ROUTE = 11012; IP_TTL_EXPIRED_TRANSIT = 11013; IP_TTL_EXPIRED_REASSEM = 11014; IP_PARAM_PROBLEM = 11015; IP_SOURCE_QUENCH = 11016; IP_OPTION_TOO_BIG = 11017; IP_BAD_DESTINATION = 11018; IP_ADDR_DELETED = 11019; IP_SPEC_MTU_CHANGE = 11020; IP_MTU_CHANGE = 11021; IP_UNLOAD = 11022; IP_GENERAL_FAILURE = 11050; MAX_IP_STATUS = IP_GENERAL_FAILURE; IP_PENDING = 11255; function Ping(const IPStr:AnsiString; IP,Timeout:Cardinal):Integer; type T4Byte=packed array[0..3] of Byte; var WrapIP:T4Byte absolute IP; hIP : THandle; pingBuffer : array [0..31] of Char; pIpe : ^icmp_echo_reply; pHostEn : PHostEnt; wVersionRequested : WORD; lwsaData : WSAData; error : DWORD; destAddress : In_Addr; begin Result:=0; pIpe:=nil; hIP:=0; try GetMem( pIpe, sizeof(icmp_echo_reply) + sizeof(pingBuffer)); // Создаем handle hIP := IcmpCreateFile(); pIpe.Data := @pingBuffer; pIpe.DataSize := sizeof(pingBuffer); wVersionRequested := MakeWord(1,1); error := WSAStartup(wVersionRequested,lwsaData); if (error <> 0) then exit; try pHostEn := gethostbyname(PChar(IPStr)); error := WSAGetLastError(); Result:=error; if (error <> 0) then exit; destAddress := PInAddr(pHostEn^.h_addr_list^)^; // Посылаем ping-пакет IcmpSendEcho(hIP, destAddress.S_addr, @pingBuffer, sizeof(pingBuffer), Nil, pIpe, sizeof(icmp_echo_reply) + sizeof(pingBuffer), Timeout ); error := GetLastError(); if (error <> 0) or (WrapIP[0]<>T4Byte(pIpe.Address)[3]) or (WrapIP[1]<>T4Byte(pIpe.Address)[2]) or (WrapIP[2]<>T4Byte(pIpe.Address)[1]) or (WrapIP[3]<>T4Byte(pIpe.Address)[0]) then error:=IP_DEST_HOST_UNREACHABLE; Result:=error; finally WSACleanup(); end; finally if hIP<>0 then IcmpCloseHandle(hIP); if pIpe<>nil then FreeMem(pIpe); end; end; end.
unit DAO.FaixaPeso; interface uses DAO.Base, Model.FaixaPeso, Generics.Collections, System.Classes; type TFaixaPesoDAO = class(TDAO) public function Insert(aFaixas: Model.FaixaPeso.TFaixaPeso): Boolean; function Update(aFaixas: Model.FaixaPeso.TFaixaPeso): Boolean; function Delete(sFiltro: String): Boolean; function FindFaixa(sFiltro: String): TObjectList<Model.FaixaPeso.TFaixaPeso>; end; const TABLENAME = 'tbfaixapeso'; implementation uses System.SysUtils, FireDAC.Comp.Client, Data.DB; function TFaixaPesoDAO.Insert(aFaixas: TFaixaPeso): Boolean; var sSQL : System.string; begin Result := False; aFaixas.ID := GetKeyValue(TABLENAME,'ID_VERBA'); sSQL := 'INSERT INTO ' + TABLENAME + ' '+ '(ID_VERBA, QTD_PESO_INICIAL, QTD_PESO_FINAL, DES_LOG) ' + 'VALUES ' + '(:ID, :INICIAL, :FINAL, :LOG);'; Connection.ExecSQL(sSQL,[aFaixas.ID, aFaixas.PesoInicial, aFaixas.PesoFinal, aFaixas.Log], [ftInteger, ftFloat, ftFloat, ftString]); Result := True; end; function TFaixaPesoDAO.Update(aFaixas: TFaixaPeso): Boolean; var sSQL: System.string; begin Result := False; sSQL := 'UPDATE ' + TABLENAME + ' ' + 'SET ' + 'QTD_PESO_INICIAL = :INICIAL, QTD_PESO_FINAL = :FINAL, DES_LOG = :LOG ' + 'WHERE ID_VERBA = :ID;'; Connection.ExecSQL(sSQL,[aFaixas.PesoInicial, aFaixas.PesoFinal, aFaixas.Log, aFaixas.ID], [ftFloat, ftFloat, ftString, ftInteger]); Result := True; end; function TFaixaPesoDAO.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 TFaixaPesoDAO.FindFaixa(sFiltro: string): TObjectList<Model.FaixaPeso.TFaixaPeso>; var FDQuery: TFDQuery; faixas: TObjectList<TFaixaPeso>; 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(); faixas := TObjectList<TFaixaPeso>.Create(); while not FDQuery.Eof do begin faixas.Add(TFaixaPeso.Create(FDQuery.FieldByName('ID_VERBA').AsInteger, FDQuery.FieldByName('QTD_PESO_INICIAL').AsFloat, FDQuery.FieldByName('QTD_PESO_FINAL').AsFloat, FDQuery.FieldByName('DES_LOG').AsString)); FDQuery.Next; end; finally FDQuery.Free; end; Result := faixas; end; end.
unit DAO.Acessos; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.Acessos, Vcl.ActnList; type TAcessosDAO = class private FConexao: TConexao; public constructor Create; destructor Destroy; function Inserir(AAcessos: TAcessos): Boolean; function Excluir(AAcessos: TAcessos): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; function AcessoExiste(aParam: array of variant): Boolean; function VerificaAcesso(iMenu: Integer; iUsuario: Integer): Boolean; function VerificaModulo(iModulo: Integer; iUsuario: Integer): Boolean; function VerificaSistema(iSistema: Integer; iUsuario: Integer): Boolean; end; const TABLENAME = 'usuarios_acessos'; implementation { TAcessosDAO } function TAcessosDAO.AcessoExiste(aParam: array of variant): Boolean; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_SISTEMA = :PCOD_SISTEMA AND COD_MODULO = :PCOD_MODULO AND COD_MENU = :PCOD_MENU AND ' + 'COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_SISTEMA').AsInteger := aParam[1]; FDQuery.ParamByName('PCOD_MODULO').AsString := aParam[2]; FDQuery.ParamByName('PCOD_MENU').AsInteger := aParam[3]; FDQuery.ParamByName('PCOD_USUARIO').AsInteger := aParam[4]; FDQuery.Open(); Result := (not FDQuery.IsEmpty); finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TAcessosDAO.Create; begin FConexao := TConexao.Create; end; destructor TAcessosDAO.Destroy; begin FConexao.Free; end; function TAcessosDAO.Excluir(AAcessos: TAcessos): Boolean; var FDQuery : TFDQuery; begin try FDQuery := FConexao.ReturnQuery; Result := False; if AAcessos.Sistema = -1 then begin FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + ' WHERE COD_USUARIO = :PCOD_USUARIO', [AAcessos.Usuario]); end else begin FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + 'WHERE COD_SISTEMA = :PCOD_SISTEMA AND COD_MODULO = :PCOD_MODULO AND ' + 'COD_MENU = :PCOD_MENU AND COD_USUARIO = :PCOD_USUARIO', [AAcessos.Sistema, AAcessos.Modulo, AAcessos.Menu, AAcessos.Usuario]); end; Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TAcessosDAO.Inserir(AAcessos: TAcessos): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + ' (COD_SISTEMA, COD_MODULO, COD_MENU, COD_USUARIO) VALUES ' + '(:PCOD_SISTEMA, :PCOD_MODULO, :PCOD_MENU, :PCOD_USUARIO)', [AAcessos.Sistema, AAcessos.Modulo, AAcessos.Menu, AAcessos.Usuario]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TAcessosDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin if not Assigned(FDQuery) then begin FDQuery := FConexao.ReturnQuery(); end; if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'MODULO' then begin FDQuery.SQL.Add('WHERE COD_MODULO = :PCOD_MODULO AND COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_MODULO').AsInteger := aParam[1]; FDQuery.ParamByName('PCOD_USUARIO').AsInteger := aParam[2]; end; if aParam[0] = 'SISTEMA' then begin FDQuery.SQL.Add('WHERE COD_SISTEMA = :PCOD_SISTEMA AND COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_SISTEMA').AsInteger := aParam[1]; FDQuery.ParamByName('PCOD_USUARIO').AsInteger := aParam[2]; end; if aParam[0] = 'MENU' then begin FDQuery.SQL.Add('WHERE COD_MENU = :PCOD_MENU AND COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_MENU').AsInteger := aParam[1]; FDQuery.ParamByName('PCOD_USUARIO').AsInteger := aParam[2]; end; if aParam[0] = 'USUARIO' then begin FDQuery.SQL.Add('WHERE COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_USUARIO').AsInteger := aParam[1]; end; if aParam[0] = 'ACESSO' then begin FDQuery.SQL.Add('WHERE COD_SISTEMA = :PCOD_SISTEMA AND COD_MODULO = :PCOD_MODULO AND COD_MENU = :PCOD_MENU AND ' + 'COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_SISTEMA').AsInteger := aParam[1]; FDQuery.ParamByName('PCOD_MODULO').AsString := aParam[2]; FDQuery.ParamByName('PCOD_MENU').AsInteger := aParam[3]; FDQuery.ParamByName('PCOD_USUARIO').AsInteger := aParam[4]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; FDQuery.Open(); Result := FDQuery; end; function TAcessosDAO.VerificaAcesso(iMenu, iUsuario: Integer): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Add('select * from ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_MENU = :PCOD_MENU AND COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_MENU').AsInteger := iMenu; FDQuery.ParamByName('PCOD_USUARIO').AsInteger := iUsuario; FDQuery.Open(); Result := not FDQuery.IsEmpty; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TAcessosDAO.VerificaModulo(iModulo, iUsuario: Integer): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Add('select * from ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_MODULO = :PCOD_MODULO AND COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_MODULO').AsInteger := iModulo; FDQuery.ParamByName('PCOD_USUARIO').AsInteger := iUsuario; FDQuery.Open(); Result := not FDQuery.IsEmpty; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TAcessosDAO.VerificaSistema(iSistema, iUsuario: Integer): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Add('select * from ' + TABLENAME); FDQuery.SQL.Add('WHERE COD_SISTEMA = :PCOD_SISTEMA AND COD_USUARIO = :PCOD_USUARIO'); FDQuery.ParamByName('PCOD_SISTEMA').AsInteger := iSistema; FDQuery.ParamByName('PCOD_USUARIO').AsInteger := iUsuario; FDQuery.Open(); Result := not FDQuery.IsEmpty; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
(* * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Initial Developer of this code is John Hansen. * Portions created by John Hansen are Copyright (C) 2009 John Hansen. * All Rights Reserved. * *) unit ParamUtils; interface uses Classes; function ParamSwitch(S: String; bIgnoreCase : Boolean = true; const cmdLine : string = ''): Boolean; function ParamValue(S: String; bIgnoreCase : Boolean = true; const cmdLine : string = ''): String; function ParamIntValue(S: String; def : Integer = -1; bIgnoreCase : Boolean = true; const cmdLine : string = ''): Integer; function JCHParamStr(Index: Integer; const cmdLine : string = ''): string; function JCHParamCount(const cmdLine : string = ''): Integer; function getFilenameParam(const cmdLine : string = '') : string; procedure LoadParamDefinitions(aStrings : TStrings; const cmdLine : string = ''); implementation uses SysUtils; function CharNext(P : PChar) : PChar; begin Result := P; Inc(Result); end; function GetParamStr(P: PChar; var Param: string): PChar; var i, Len: Integer; Start, S, Q: PChar; begin while True do begin while (P[0] <> #0) and (P[0] <= ' ') do P := CharNext(P); if (P[0] = '"') and (P[1] = '"') then Inc(P, 2) else Break; end; Len := 0; Start := P; while P[0] > ' ' do begin if P[0] = '"' then begin P := CharNext(P); while (P[0] <> #0) and (P[0] <> '"') do begin Q := CharNext(P); Inc(Len, Q - P); P := Q; end; if P[0] <> #0 then P := CharNext(P); end else begin Q := CharNext(P); Inc(Len, Q - P); P := Q; end; end; SetLength(Param, Len); P := Start; S := Pointer(Param); i := 0; while P[0] > ' ' do begin if P[0] = '"' then begin P := CharNext(P); while (P[0] <> #0) and (P[0] <> '"') do begin Q := CharNext(P); while P < Q do begin S[i] := P^; Inc(P); Inc(i); end; end; if P[0] <> #0 then P := CharNext(P); end else begin Q := CharNext(P); while P < Q do begin S[i] := P^; Inc(P); Inc(i); end; end; end; Result := P; end; function JCHParamStr(Index: Integer; const cmdLine : string): string; var P: PChar; begin Result := ''; if (Index = 0) or (cmdLine = '') then Result := ParamStr(Index) else begin P := PChar(cmdLine); while True do begin P := GetParamStr(P, Result); if (Index = 0) or (Result = '') then Break; Dec(Index); end; end; end; function JCHParamCount(const cmdLine : string): Integer; var P: PChar; S: string; begin Result := 0; S := ''; if cmdLine = '' then Result := ParamCount else begin P := GetParamStr(PChar(cmdLine), S); while True do begin P := GetParamStr(P, S); if S = '' then Break; Inc(Result); end; end; end; function ParamSwitch(S: String; bIgnoreCase : Boolean; const cmdLine : string): Boolean; var I: Integer; P: String; begin Result := False ; if bIgnoreCase then S := UpperCase(S); for I := 0 to JCHParamCount(cmdLine) do begin P := JCHParamStr(I, cmdLine); if bIgnoreCase then P := UpperCase(P); if (P=S) or (Pos(S+'=',P)=1) then begin Result := True ; Break; end; end; end; function ParamValue(S: String; bIgnoreCase : Boolean; const cmdLine : string): String; var I : Integer; P, val: String; begin Result := '' ; if bIgnoreCase then S := UpperCase(S); for I := 0 to JCHParamCount(cmdLine) do begin val := JCHParamStr(I, cmdLine); if bIgnoreCase then P := UpperCase(val) else P := val; if (Pos(S+'=',P)<>0) then begin Result := Copy(val,Length(S)+2,MaxInt); Break; end; end; end; function ParamIntValue(S: String; def : integer; bIgnoreCase : Boolean; const cmdLine : string): Integer; begin Result := StrToIntDef(ParamValue(S, bIgnoreCase, cmdLine), def); end; function getFilenameParam(const cmdLine : string) : string; var i : Integer; tmp : string; begin Result := ''; for i := 1 to JCHParamCount(cmdLine) do begin tmp := JCHParamStr(i, cmdLine); if Pos('-', tmp) = 1 then Continue; // a switch // the first parameter that is not a switch is the filename Result := tmp; Break; end; end; procedure LoadParamDefinitions(aStrings : TStrings; const cmdLine : string); var I : Integer; P: String; begin for I := 0 to JCHParamCount(cmdLine) do begin P := JCHParamStr(I, cmdLine); if Pos('-D=', P) = 1 then begin // this is a #define System.Delete(P, 1, 3); if Pos('=', P) = 0 then P := P + '=1'; aStrings.Add(P); end; end; end; end.
unit ApplicationUnit; {$WARN SYMBOL_PLATFORM OFF} interface uses Windows, SysUtils, ComObj, ActiveX, AxCtrls, Classes, OpcBridgeServer_TLB, StdVcl, StrUtils; type TApplication = class(TAutoObject, IConnectionPointContainer, IApplication) private { Private declarations } FConnectionPoints: TConnectionPoints; FConnectionPoint: TConnectionPoint; FEvents: IApplicationEvents; { note: FEvents maintains a *single* event sink. For access to more than one event sink, use FConnectionPoint.SinkList, and iterate through the list of sinks. } public procedure Initialize; override; protected { Protected declarations } property ConnectionPoints: TConnectionPoints read FConnectionPoints implements IConnectionPointContainer; procedure EventSinkChanged(const EventSink: IUnknown); override; procedure InitOPC; safecall; procedure FinitOPC; safecall; function AddServer(const ServerName: WideString): Integer; safecall; procedure RemoveServer(const ServerName: WideString); safecall; function AddGroup(const ServerName, GroupName: WideString): Integer; safecall; procedure RemoveGroup(const ServerName, GroupName: WideString); safecall; function AddItem(const ServerName, GroupName, ItemName: WideString): Integer; safecall; procedure RemoveItem(const ServerName, GroupName, ItemName: WideString); safecall; function FetchItem(const ServerName, GroupName, ItemName: WideString): WideString; safecall; function GetServers: WideString; safecall; function GetProps(const Server: WideString): WideString; safecall; end; implementation uses ComCtrls, ComServ, OPCtypes, OPCDA, OPCenum, OPCutils; const RPC_C_AUTHN_LEVEL_NONE = 1; RPC_C_IMP_LEVEL_IMPERSONATE = 3; EOAC_NONE = 0; INVALIDOPCHANDLE = -2147023174; var Enabled: boolean; ServerNames: TStringList; Servers: TInterfaceList; GroupNames: TStringList; Groups: TInterfaceList; GroupHandles: TList; ItemNames: TStringList; ItemsTypeCDT: TList; ItemHandles: TList; //------------------------------ procedure TApplication.EventSinkChanged(const EventSink: IUnknown); begin FEvents := EventSink as IApplicationEvents; end; procedure TApplication.Initialize; begin inherited Initialize; FConnectionPoints := TConnectionPoints.Create(Self); if AutoFactory.EventTypeInfo <> nil then FConnectionPoint := FConnectionPoints.CreateConnectionPoint( AutoFactory.EventIID, ckSingle, EventConnect) else FConnectionPoint := nil; end; procedure TApplication.InitOPC; begin // this is for DCOM: // without this, callbacks from the server may get blocked, depending on // DCOM configuration settings CoInitializeSecurity( nil, // points to security descriptor -1, // count of entries in asAuthSvc nil, // array of names to register nil, // reserved for future use RPC_C_AUTHN_LEVEL_NONE, // the default authentication level for proxies RPC_C_IMP_LEVEL_IMPERSONATE,// the default impersonation level for proxies nil, // used only on Windows 2000 EOAC_NONE, // additional client or server-side capabilities nil // reserved for future use ); ServerNames := TStringList.Create; Servers := TInterfaceList.Create; GroupNames := TStringList.Create; Groups := TInterfaceList.Create; GroupHandles := TList.Create; ItemNames := TStringList.Create; ItemsTypeCDT := TList.Create; ItemHandles := TList.Create; Enabled := True; //not Failed(HR); // Failed to initialize DCOM security end; procedure TApplication.FinitOPC; var i, j, k: Integer; ServerName, GroupName, ItemName: string; begin for i := ServerNames.Count - 1 downto 0 do begin ServerName := ServerNames[i]; for j := GroupNames.Count - 1 downto 0 do begin GroupName := GroupNames[j]; Delete(GroupName, 1, Length(ServerName)); for k := ItemNames.Count - 1 downto 0 do begin ItemName := ItemNames[k]; Delete(ItemName, 1, Length(ServerName) + Length(GroupName)); RemoveItem(ServerName, GroupName, ItemName); end; RemoveGroup(ServerName, PChar(GroupName)); end; RemoveServer(ServerName); end; ItemsTypeCDT.Free; ItemHandles.Free; ItemNames.Free; GroupHandles.Free; Groups.Free; GroupNames.Free; Servers.Free; ServerNames.Free; end; function TApplication.AddServer(const ServerName: WideString): Integer; var EnumOPC: IOPCServer; begin if Enabled then begin Result := ServerNames.IndexOf(ServerName); if Result < 0 then begin // Connect OPC server try EnumOPC := CreateComObject(ProgIDToClassID(ServerName)) as IOPCServer; if EnumOPC <> nil then Result := ServerNames.AddObject(ServerName, TObject(Servers.Add(EnumOPC))); except Result := -1; end; end; end else Result := -1; end; procedure TApplication.RemoveServer(const ServerName: WideString); var EnumOPC: IOPCServer; IndexServer: integer; begin if Enabled then begin IndexServer := ServerNames.IndexOf(ServerName); if IndexServer >= 0 then begin IndexServer := Integer(ServerNames.Objects[IndexServer]); EnumOPC := Servers.Items[IndexServer] as IOPCServer; if EnumOPC <> nil then begin Servers.Items[IndexServer] := nil; Servers.Delete(IndexServer); ServerNames.Delete(IndexServer); end; end; end; end; function TApplication.AddGroup(const ServerName, GroupName: WideString): Integer; var HR: HResult; EnumOPC: IOPCServer; IndexServer, IndexGroup: integer; ServerGroupName: string; GroupIf: IOPCItemMgt; GroupHandle: OPCHANDLE; begin if Enabled then begin IndexServer := AddServer(ServerName); if IndexServer >= 0 then begin EnumOPC := Servers.Items[Integer(ServerNames.Objects[IndexServer])] as IOPCServer; if EnumOPC <> nil then begin ServerGroupName := ServerName + GroupName; IndexGroup := GroupNames.IndexOf(ServerGroupName); if IndexGroup < 0 then begin // now add an group to the OPC server HR := ServerAddGroup(EnumOPC, GroupName, True, 500, 0, GroupIf, GroupHandle); if Succeeded(HR) then begin IndexGroup := Groups.Add(GroupIf); GroupHandles.Add(Pointer(GroupHandle)); GroupNames.AddObject(ServerGroupName, TObject(IndexGroup)); Result := IndexGroup; end else Result := -1; end else Result := IndexGroup; end else Result := -1; end else Result := -1; end else Result := -1; end; procedure TApplication.RemoveGroup(const ServerName, GroupName: WideString); var EnumOPC: IOPCServer; GroupHandle: OPCHANDLE; IndexServer, IndexGroup: integer; ServerGroupName: string; begin if Enabled then begin IndexServer := ServerNames.IndexOf(ServerName); if IndexServer >= 0 then begin EnumOPC := Servers.Items[Integer(ServerNames.Objects[IndexServer])] as IOPCServer; if EnumOPC <> nil then begin ServerGroupName := ServerName + GroupName; IndexGroup := GroupNames.IndexOf(ServerGroupName); if IndexGroup >= 0 then begin GroupHandle := OPCHANDLE(GroupHandles[IndexGroup]); if GroupHandle <> 0 then begin EnumOPC.RemoveGroup(GroupHandle, False); GroupHandles.Delete(IndexGroup); Groups.Delete(IndexGroup); GroupNames.Delete(IndexGroup); end; end; end; end; end; end; function TApplication.AddItem(const ServerName, GroupName, ItemName: WideString): Integer; var HR: HResult; GroupIf: IOPCItemMgt; ItemHandle: OPCHANDLE; ItemTypeCDT: TVarType; ServerGroupItemName: string; IndexGroup, IndexItem: integer; begin if Enabled then begin IndexGroup := AddGroup(ServerName, GroupName); if IndexGroup >= 0 then begin GroupIf := Groups[IndexGroup] as IOPCItemMgt; if GroupIf <> nil then begin ServerGroupItemName := string(ServerName) + string(GroupName) + string(ItemName); IndexItem := ItemNames.IndexOf(ServerGroupItemName); if IndexItem < 0 then begin // now add an item to the group HR := GroupAddItem(GroupIf, ItemName, 0, VT_EMPTY, ItemHandle, ItemTypeCDT); if Succeeded(HR) then begin IndexItem := ItemHandles.Add(Pointer(ItemHandle)); ItemsTypeCDT.Add(Pointer(ItemTypeCDT)); ItemNames.AddObject(ServerGroupItemName, TObject(IndexItem)); Result := IndexItem; end else Result := -1; end else Result := IndexItem; end else Result := -1; end else Result := -1; end else Result := -1; end; procedure TApplication.RemoveItem(const ServerName, GroupName, ItemName: WideString); var GroupIf: IOPCItemMgt; ItemHandle: OPCHANDLE; GroupIndex, ItemIndex: Integer; begin if Enabled then begin GroupIndex := GroupNames.IndexOf(string(ServerName) + string(GroupName)); if GroupIndex >= 0 then begin GroupIf := Groups[GroupIndex] as IOPCItemMgt; if GroupIf <> nil then begin ItemIndex := ItemNames.IndexOf(string(ServerName) + string(GroupName) + string(ItemName)); if ItemIndex >= 0 then begin ItemHandle := OPCHANDLE(ItemHandles[ItemIndex]); if ItemHandle <> 0 then begin GroupRemoveItem(GroupIf, ItemHandle); ItemsTypeCDT.Delete(ItemIndex); ItemHandles.Delete(ItemIndex); ItemNames.Delete(ItemIndex); end; end; end; end; end; end; function TApplication.FetchItem(const ServerName, GroupName, ItemName: WideString): WideString; var HR: HResult; GroupIf: IOPCItemMgt; ItemHandle: OPCHANDLE; ItemValue: string; ItemQuality: Word; ItemTime: TFileTime; GroupIndex, ItemIndex: integer; Quality: string; SystemTime: TSystemTime; begin Result := '0;BAD;00:00:00'; if Enabled then begin GroupIndex := AddGroup(ServerName, GroupName); if GroupIndex >= 0 then begin GroupIf := Groups[GroupIndex] as IOPCItemMgt; if GroupIf <> nil then begin ItemIndex := AddItem(ServerName, GroupName, ItemName); if ItemIndex >= 0 then begin ItemHandle := OPCHANDLE(ItemHandles[ItemIndex]); if ItemHandle <> 0 then begin // now try to read the item value synchronously HR := ReadOPCGroupItemValue(GroupIf, ItemHandle, ItemValue, ItemQuality, ItemTime); if Succeeded(HR) then begin case ItemQuality and OPC_QUALITY_MASK of OPC_QUALITY_GOOD: Quality := 'GOOD'; OPC_QUALITY_UNCERTAIN: Quality := 'UNCERTAIN'; else Quality := 'BAD'; end; FileTimeToSystemTime(ItemTime, SystemTime); Result := ItemValue + ';' + Quality + ';' + FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', SystemTimeToDateTime(SystemTime)); end; end; end; end; end; end; end; function TApplication.GetServers: WideString; var OPCServerList: TOPCServerList; CATIDs: array of TGUID; L: TStringList; i: integer; function AddListOfServers(G: TGUID; Name: string): string; var L: TStringList; i: integer; begin Result := ''; SetLength(CATIDs, 1); CATIDs[0] := G; try L := TStringList.Create; OPCServerList := TOPCServerList.Create('', False, CATIDs); try OPCServerList.Update; L.Assign(OPCServerList.Items); L.Sort; for i := 0 to L.Count - 1 do Result := Result + Name + '=' + L[i] + ';'; finally OPCServerList.Free; L.Free; end; except Result := ''; end; end; begin Result := ''; SetLength(CATIDs, 0); try L := TStringList.Create; OPCServerList := TOPCServerList.Create('', True, CATIDs); try OPCServerList.Update; L.Assign(OPCServerList.Items); L.Sort; for i := 0 to L.Count - 1 do Result := Result + 'Registry=' + L[i] + ';'; finally OPCServerList.Free; L.Free; end; except Result := ''; end; Result := Result + AddListOfServers(CATID_OPCDAServer10, 'OPC DA1.0'); Result := Result + AddListOfServers(CATID_OPCDAServer20, 'OPC DA2.0'); Result := Result + AddListOfServers(CATID_OPCDAServer30, 'OPC DA3.0'); Result := Result + AddListOfServers(CATID_XMLDAServer10, 'XML DA1.0'); end; function TApplication.GetProps(const Server: WideString): WideString; var i: integer; Tags: TStringList; EnumOPC: IOPCServer; EnumProperties: IOPCBrowseServerAddressSpace; Alloc: IMalloc; NST: OPCNAMESPACETYPE; HR: HResult; EnumString: IEnumString; Res: PWideChar; VarType: TVarType; function StrToVarType(Value: WideString): TVarType; begin if Value = 'string' then Result := varOleStr else if Value = 'integer' then Result := varInteger else if Value = 'double' then Result := varDouble else Result := varEmpty; end; function Clear(value: string): string; begin Result := StrUtils.AnsiReplaceStr(value,#13#10,''); end; function UseCDT(EnumOPC: IOPCServer; ItemId: string): TVarType; var HR: HResult; PropertyInfo: IOPCItemProperties; pdwCount: Cardinal; ppPropertyIDs: PDWORDARRAY; ppDescriptions: POleStrList; ppvtDataTypes: PVarTypeList; ppvData: POleVariantArray; ppErrors: PResultList; I: Integer; begin Result := VT_EMPTY; PropertyInfo := EnumOPC as IOPCItemProperties; if PropertyInfo <> nil then begin HR := PropertyInfo.QueryAvailableProperties( PWideChar(WideString(ItemId)), pdwCount, ppPropertyIDs, ppDescriptions, ppvtDataTypes); if Succeeded(HR) then begin HR := PropertyInfo.GetItemProperties(PWideChar(WideString(ItemId)), pdwCount, ppPropertyIDs, ppvData, ppErrors); if Succeeded(HR) then begin for I := 0 to pdwCount - 1 do if ppPropertyIDs <> nil then begin if (ppvData <> nil) then begin if ppPropertyIDs[i] = OPC_PROP_CDT then begin //расшифровка канонического типа данных try Result := ppvData[i]; except Result := StrToVarType(ppvData[i]); end; Break; end; end; end; end; end; end; end; procedure BrowseBranch(EnumProperties: IOPCBrowseServerAddressSpace); var EnumString: IEnumString; HR: HResult; BrowseID: PWideChar; aItemID: PWideChar; celtFetched: LongInt; begin HR := EnumProperties.BrowseOpcItemIds(OPC_LEAF, '', VT_EMPTY, 0, EnumString); if HR <> S_FALSE then begin OleCheck(HR); while EnumString.Next(1, BrowseID, @celtFetched) = S_OK do begin OleCheck(EnumProperties.GetItemID(BrowseID, aItemID)); VarType := UseCDT(EnumOPC, aItemID); Tags.Append(Clear(string(aItemID)) + '=' + IntToStr(VarType)); Alloc.Free(aItemID); Alloc.Free(BrowseID); end end; HR := EnumProperties.BrowseOpcItemIds(OPC_BRANCH, '', VT_EMPTY, 0, EnumString); if HR <> S_FALSE then begin OleCheck(HR); while EnumString.Next(1, BrowseID, nil) = S_OK do begin OleCheck(EnumProperties.ChangeBrowsePosition(OPC_BROWSE_DOWN, BrowseID)); Alloc.Free(BrowseID); BrowseBranch(EnumProperties); OleCheck(EnumProperties.ChangeBrowsePosition(OPC_BROWSE_UP, '')); end end end; begin Result := ''; i := AddServer(Server); if i < 0 then Exit; EnumOPC := Servers[i] as IOPCServer; EnumProperties := EnumOPC as IOPCBrowseServerAddressSpace; CoGetMalloc(1, Alloc); // Получение типа дерева в переменную NST: .._FLAT - список, иначе дерево. OleCheck(EnumProperties.QueryOrganization(NST)); Tags := TStringList.Create; try if NST = OPC_NS_FLAT then begin // обработка списка HR := EnumProperties.BrowseOpcItemIds(OPC_FLAT, '', VT_EMPTY, 0, EnumString); if HR <> S_FALSE then begin OleCheck(HR); while EnumString.Next(1, Res, nil) = S_OK do begin VarType := UseCDT(EnumOPC, Res); Tags.Append(Clear(string(Res)) + '=' + IntToStr(VarType)); Alloc.Free(Res); end end end else begin // обработка дерева HR := EnumProperties.ChangeBrowsePosition(OPC_BROWSE_TO, ''); if HR = E_INVALIDARG then repeat HR := EnumProperties.ChangeBrowsePosition(OPC_BROWSE_UP, '') until HR <> S_OK else OleCheck(HR); BrowseBranch(EnumProperties); end; Tags.Sort; Tags.Delimiter := ';'; Result := Tags.DelimitedText; finally Tags.Free; end; end; initialization TAutoObjectFactory.Create(ComServer, TApplication, Class_Application, ciMultiInstance, tmApartment); end.
{ Copyright (c) 2016, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } unit ooFactory.List; interface uses SysUtils, Generics.Collections, ooFactory.Item.Intf; type EFactoryList = class(Exception) end; TFactoryList<T> = class(TObject) strict private type {$IFDEF FPC} IFactoryItemT = IFactoryItem<T>; _TFactoryList = TList<IFactoryItemT>; {$ELSE} _TFactoryList = TList<IFactoryItem<T>>; {$ENDIF} strict private _List: _TFactoryList; public function Add(Item: IFactoryItem<T>): Integer; function IndexOf(const Key: TFactoryKey): Integer; function Exists(const Key: TFactoryKey): Boolean; function Find(const Key: TFactoryKey): T; function Count: Integer; constructor Create; destructor Destroy; override; end; implementation function TFactoryList<T>.IndexOf(const Key: TFactoryKey): Integer; var i: Integer; begin Result := - 1; for i := 0 to Pred(_List.Count) do if CompareText(Key, _List.Items[i].Key) = 0 then begin Result := i; Break; end; end; function TFactoryList<T>.Exists(const Key: TFactoryKey): Boolean; begin Result := IndexOf(Key) <> - 1; end; function TFactoryList<T>.Add(Item: IFactoryItem<T>): Integer; begin if Exists(Item.Key) then raise EFactoryList.Create(Format('Key class "%s" already exists!', [Item.Key])) else Result := _List.Add(Item); end; function TFactoryList<T>.Find(const Key: TFactoryKey): T; var IndexFounded: Integer; begin Result := default(T); IndexFounded := IndexOf(Key); if IndexFounded < 0 then raise EFactoryList.Create(Format('Key class "%s" not found!', [Key])) else Result := _List.Items[IndexFounded].ClassType; end; function TFactoryList<T>.Count: Integer; begin Result := _List.Count; end; constructor TFactoryList<T>.Create; begin _List := _TFactoryList.Create; end; destructor TFactoryList<T>.Destroy; begin _List.Free; inherited; end; end.
{******************************************************************************* 作者: dmzn@163.com 2009-6-27 描述: 带背景窗体 *******************************************************************************} unit UBgFormBase; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, UImageControl, UTransPanel; type TfBgFormBase = class(TForm) ClientPanel1: TZnTransPanel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); protected FValidRect: TRect; FCanClose: Boolean; public procedure CloseForm(const nRes: TModalResult = mrCancel); function FindBgItem(const nPos: TImageControlPosition): TImageControl; end; implementation {$R *.dfm} procedure TfBgFormBase.FormCreate(Sender: TObject); var nP: PImageItemData; begin FCanClose := False; DoubleBuffered := True; if WindowState = wsMaximized then begin with TImageControl.Create(Self) do begin Parent := Self; Align := alTop; Position := cpTop; end; with TImageControl.Create(Self) do begin Parent := Self; Align := alBottom; Position := cpBottom; end; with TImageControl.Create(Self) do begin Parent := Self; Align := alLeft; Position := cpLeft; end; with TImageControl.Create(Self) do begin Parent := Self; Align := alRight; Position := cpRight; end; with TImageControl.Create(Self) do begin Parent := Self; Align := alClient; Position := cpClient; nP := GetItemData(0); end; end else begin with TImageControl.Create(Self) do begin Parent := Self; Align := alClient; Position := cpForm; nP := GetItemData(0); end; end; ClientPanel1.BringToFront; FValidRect := Rect(0, 0, 0, 0); if not Assigned(nP) then Exit; FValidRect := nP.FCtrlRect; ClientPanel1.Align := alNone; ClientPanel1.Left := FValidRect.Left; ClientPanel1.Top := FValidRect.Top; if WindowState = wsMaximized then begin ClientPanel1.Width := Screen.Width - FValidRect.Left - FValidRect.Right; ClientPanel1.Height := Screen.Height - FValidRect.Top - FValidRect.Bottom; end else begin Self.Width := ClientPanel1.Left + ClientPanel1.Width + FValidRect.Right; Self.Height := ClientPanel1.Top + ClientPanel1.Height + FValidRect.Bottom; end; end; procedure TfBgFormBase.FormClose(Sender: TObject; var Action: TCloseAction); begin if FCanClose or (ModalResult <> mrNone) then Action := caFree else Action := caNone; end; //Desc: 关闭窗口 procedure TfBgFormBase.CloseForm(const nRes: TModalResult); begin if fsModal in FFormState then begin ModalResult := nRes; end else begin FCanClose := True; Close; end; end; procedure TfBgFormBase.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then begin Key := 0; Close; end; end; function TfBgFormBase.FindBgItem(const nPos: TImageControlPosition): TImageControl; var i,nCount: integer; begin Result := nil; nCount := ControlCount - 1; for i:=0 to nCount do if (Controls[i] is TImageControl) and (TImageControl(Controls[i]).Position = nPos) then begin Result := TImageControl(Controls[i]); Break; end; end; end.
unit TTSTRAKTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSTRAKRecord = record PLenderNum: String[4]; PTrackCode: String[8]; PModCount: Integer; PDescription: String[30]; PPrintNotify: Boolean; PNotifyLead: Integer; PPrintOfficer: Boolean; POfficerLead: Integer; PLastScanDate: String[10]; PLastTotal: Integer; PPushToHistory: Boolean; PRiskFactor: String[2]; //Risk Factor End; TTTSTRAKBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSTRAKRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSTRAK = (TTSTRAKPrimaryKey, TTSTRAKByDesc); TTTSTRAKTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFTrackCode: TStringField; FDFModCount: TIntegerField; FDFDescription: TStringField; FDFPrintNotify: TBooleanField; FDFNotifyLead: TIntegerField; FDFPrintOfficer: TBooleanField; FDFOfficerLead: TIntegerField; FDFLastScanDate: TStringField; FDFLastTotal: TIntegerField; FDFTemplate: TBlobField; FDFPushToHistory: TBooleanField; FDFRiskFactor :TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPPrintNotify(const Value: Boolean); function GetPPrintNotify:Boolean; procedure SetPNotifyLead(const Value: Integer); function GetPNotifyLead:Integer; procedure SetPPrintOfficer(const Value: Boolean); function GetPPrintOfficer:Boolean; procedure SetPOfficerLead(const Value: Integer); function GetPOfficerLead:Integer; procedure SetPLastScanDate(const Value: String); function GetPLastScanDate:String; procedure SetPLastTotal(const Value: Integer); function GetPLastTotal:Integer; procedure SetPPushToHistory(const Value: Boolean); function GetPPushToHistory:Boolean; procedure SetPRiskFactor(const Value: String); function GetPRiskFactor:String; procedure SetEnumIndex(Value: TEITTSTRAK); function GetEnumIndex: TEITTSTRAK; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSTRAKRecord; procedure StoreDataBuffer(ABuffer:TTTSTRAKRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFTrackCode: TStringField read FDFTrackCode; property DFModCount: TIntegerField read FDFModCount; property DFDescription: TStringField read FDFDescription; property DFPrintNotify: TBooleanField read FDFPrintNotify; property DFNotifyLead: TIntegerField read FDFNotifyLead; property DFPrintOfficer: TBooleanField read FDFPrintOfficer; property DFOfficerLead: TIntegerField read FDFOfficerLead; property DFLastScanDate: TStringField read FDFLastScanDate; property DFLastTotal: TIntegerField read FDFLastTotal; property DFTemplate: TBlobField read FDFTemplate; property DFPushToHistory: TBooleanField read FDFPushToHistory; property DFRiskFactor:TStringField read FDFRiskFactor; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PModCount: Integer read GetPModCount write SetPModCount; property PDescription: String read GetPDescription write SetPDescription; property PPrintNotify: Boolean read GetPPrintNotify write SetPPrintNotify; property PNotifyLead: Integer read GetPNotifyLead write SetPNotifyLead; property PPrintOfficer: Boolean read GetPPrintOfficer write SetPPrintOfficer; property POfficerLead: Integer read GetPOfficerLead write SetPOfficerLead; property PLastScanDate: String read GetPLastScanDate write SetPLastScanDate; property PLastTotal: Integer read GetPLastTotal write SetPLastTotal; property PPushToHistory: Boolean read GetPPushToHistory write SetPPushToHistory; property PRiskFactor : String read GetPRiskFactor write SetPRiskFactor; published property Active write SetActive; property EnumIndex: TEITTSTRAK read GetEnumIndex write SetEnumIndex; end; { TTTSTRAKTable } procedure Register; implementation procedure TTTSTRAKTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFPrintNotify := CreateField( 'PrintNotify' ) as TBooleanField; FDFNotifyLead := CreateField( 'NotifyLead' ) as TIntegerField; FDFPrintOfficer := CreateField( 'PrintOfficer' ) as TBooleanField; FDFOfficerLead := CreateField( 'OfficerLead' ) as TIntegerField; FDFLastScanDate := CreateField( 'LastScanDate' ) as TStringField; FDFLastTotal := CreateField( 'LastTotal' ) as TIntegerField; FDFTemplate := CreateField( 'Template' ) as TBlobField; FDFPushToHistory := CreateField( 'PushToHistory' ) as TBooleanField; FDFRiskFactor := CreateField('RiskFactor' ) as TStringField; end; { TTTSTRAKTable.CreateFields } procedure TTTSTRAKTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSTRAKTable.SetActive } procedure TTTSTRAKTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSTRAKTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSTRAKTable.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSTRAKTable.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSTRAKTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSTRAKTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSTRAKTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSTRAKTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSTRAKTable.SetPPrintNotify(const Value: Boolean); begin DFPrintNotify.Value := Value; end; function TTTSTRAKTable.GetPPrintNotify:Boolean; begin result := DFPrintNotify.Value; end; procedure TTTSTRAKTable.SetPNotifyLead(const Value: Integer); begin DFNotifyLead.Value := Value; end; function TTTSTRAKTable.GetPNotifyLead:Integer; begin result := DFNotifyLead.Value; end; procedure TTTSTRAKTable.SetPPrintOfficer(const Value: Boolean); begin DFPrintOfficer.Value := Value; end; function TTTSTRAKTable.GetPPrintOfficer:Boolean; begin result := DFPrintOfficer.Value; end; procedure TTTSTRAKTable.SetPOfficerLead(const Value: Integer); begin DFOfficerLead.Value := Value; end; function TTTSTRAKTable.GetPOfficerLead:Integer; begin result := DFOfficerLead.Value; end; procedure TTTSTRAKTable.SetPLastScanDate(const Value: String); begin DFLastScanDate.Value := Value; end; function TTTSTRAKTable.GetPLastScanDate:String; begin result := DFLastScanDate.Value; end; procedure TTTSTRAKTable.SetPLastTotal(const Value: Integer); begin DFLastTotal.Value := Value; end; function TTTSTRAKTable.GetPRiskFactor: String; begin result := DFRiskFactor.Value ; end; procedure TTTSTRAKTable.SetPRiskFactor(const Value: String); begin DFRiskFactor.Value := Value; end; function TTTSTRAKTable.GetPLastTotal:Integer; begin result := DFLastTotal.Value; end; procedure TTTSTRAKTable.SetPPushToHistory(const Value: Boolean); begin DFPushToHistory.Value := Value; end; function TTTSTRAKTable.GetPPushToHistory:Boolean; begin result := DFPushToHistory.Value; end; procedure TTTSTRAKTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('TrackCode, String, 8, N'); Add('ModCount, Integer, 0, N'); Add('Description, String, 30, N'); Add('PrintNotify, Boolean, 0, N'); Add('NotifyLead, Integer, 0, N'); Add('PrintOfficer, Boolean, 0, N'); Add('OfficerLead, Integer, 0, N'); Add('LastScanDate, String, 10, N'); Add('LastTotal, Integer, 0, N'); Add('Template, Memo, 0, N'); Add('PushToHistory, Boolean, 0, N'); Add('RiskFactor,String,2,N'); end; end; procedure TTTSTRAKTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;TrackCode, Y, Y, N, N'); Add('ByDesc, LenderNum;Description, N, N, Y, N'); end; end; procedure TTTSTRAKTable.SetEnumIndex(Value: TEITTSTRAK); begin case Value of TTSTRAKPrimaryKey : IndexName := ''; TTSTRAKByDesc : IndexName := 'ByDesc'; end; end; function TTTSTRAKTable.GetDataBuffer:TTTSTRAKRecord; var buf: TTTSTRAKRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PTrackCode := DFTrackCode.Value; buf.PModCount := DFModCount.Value; buf.PDescription := DFDescription.Value; buf.PPrintNotify := DFPrintNotify.Value; buf.PNotifyLead := DFNotifyLead.Value; buf.PPrintOfficer := DFPrintOfficer.Value; buf.POfficerLead := DFOfficerLead.Value; buf.PLastScanDate := DFLastScanDate.Value; buf.PLastTotal := DFLastTotal.Value; buf.PPushToHistory := DFPushToHistory.Value; buf.PRiskFactor := DFRiskFactor.Value; result := buf; end; procedure TTTSTRAKTable.StoreDataBuffer(ABuffer:TTTSTRAKRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFTrackCode.Value := ABuffer.PTrackCode; DFModCount.Value := ABuffer.PModCount; DFDescription.Value := ABuffer.PDescription; DFPrintNotify.Value := ABuffer.PPrintNotify; DFNotifyLead.Value := ABuffer.PNotifyLead; DFPrintOfficer.Value := ABuffer.PPrintOfficer; DFOfficerLead.Value := ABuffer.POfficerLead; DFLastScanDate.Value := ABuffer.PLastScanDate; DFLastTotal.Value := ABuffer.PLastTotal; DFPushToHistory.Value := ABuffer.PPushToHistory; DFRiskFactor.value := ABuffer.PRiskFactor; end; function TTTSTRAKTable.GetEnumIndex: TEITTSTRAK; var iname : string; begin result := TTSTRAKPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSTRAKPrimaryKey; if iname = 'BYDESC' then result := TTSTRAKByDesc; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSTRAKTable, TTTSTRAKBuffer ] ); end; { Register } function TTTSTRAKBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..12] of string = ('LENDERNUM','TRACKCODE','MODCOUNT','DESCRIPTION','PRINTNOTIFY','NOTIFYLEAD' ,'PRINTOFFICER','OFFICERLEAD','LASTSCANDATE','LASTTOTAL','PUSHTOHISTORY' ,'RISKFACTOR' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 12) and (flist[x] <> s) do inc(x); if x <= 12 then result := x else result := 0; end; function TTTSTRAKBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftString; 5 : result := ftBoolean; 6 : result := ftInteger; 7 : result := ftBoolean; 8 : result := ftInteger; 9 : result := ftString; 10 : result := ftInteger; 11 : result := ftBoolean; 12 : result := ftString; end; end; function TTTSTRAKBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PTrackCode; 3 : result := @Data.PModCount; 4 : result := @Data.PDescription; 5 : result := @Data.PPrintNotify; 6 : result := @Data.PNotifyLead; 7 : result := @Data.PPrintOfficer; 8 : result := @Data.POfficerLead; 9 : result := @Data.PLastScanDate; 10 : result := @Data.PLastTotal; 11 : result := @Data.PPushToHistory; 12 : result := @Data.PRiskFactor; end; end; end.
unit ZMReader; // ZMReader.pas - Loads a Zip file (* *************************************************************************** TZipMaster VCL originally by Chris Vleghert, Eric W. Engler. Present Maintainers and Authors Roger Aelbrecht and Russell Peters. Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler Copyright (C) 1992-2008 Eric W. Engler Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht Copyright (C) 2014, 2015 Russell Peters and Roger Aelbrecht The MIT License (MIT) Copyright (c) 2015 delphizip Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. contact: problems AT delphizip DOT org updates: http://www.delphizip.org *************************************************************************** *) // modified 2015-04-27 {$INCLUDE '.\ZipVers.inc'} interface uses {$IFDEF VERDXE2up} // Delphi XE2 or newer System.Classes, WinApi.Windows, {$ELSE} Classes, Windows, {$ENDIF} ZipMstr, ZMBody, ZMDirectory, ZMEOC, ZMEntryReader, ZMStructs; type TZMReader = class(TZMDirectory) private FEOCFileTime: TFileTime; function GetItems(Index: Integer): TZMEntryReader; procedure LoadEntries; function LoadSFXStub(const ZipName: string): Integer; function LoadTheZip: Integer; function Open1(EOConly: Boolean): Integer; function OpenLast(EOConly: Boolean; OpenRes: Integer): Integer; function OpenLastExt(FName: string; EOConly: Boolean): Integer; function OpenLastFind(var FMVolume: Boolean; const Fname, Path: string; var TmpNumbering: TZipNumberScheme; EOConly: Boolean): Integer; function OpenLastFixed(const BaseName: string; var PartNbr: Integer; EOConly: Boolean): Integer; function OpenLastPart(const BaseName, Path: string): Integer; function OpenLastVerify(PartNbr: Integer): Integer; function PossibleBase(var FName: string; const RequestedName: string): Integer; function VerifyPossible(const FN: string): Integer; property EOCFileTime: TFileTime read FEOCFileTime write FEOCFileTime; public function LoadZip: Integer; function OpenZip(EOConly, NoLoad: Boolean): Integer; function VerifyOpen: Integer; property Items[Index: Integer]: TZMEntryReader read GetItems; default; end; implementation uses {$IFDEF VERDXE2up} // Delphi XE2 or newer System.SysUtils, {$ELSE} SysUtils, {$IFNDEF UNICODE}ZMCompat, {$ENDIF} {$ENDIF} ZMCore, ZMFileIO, ZMMsg, ZMDiags, ZMXcpt, ZMUtils, ZMNameUtils, ZMWinFuncsU, ZMWinFuncsA, ZMUTF8, ZMCRC, ZMFStream, ZMCentral; const __UNIT__ = 50; const _U_ = (__UNIT__ shl ZERR_LINE_SHIFTS); const AllSpec: string = '*.*'; AnySpec: string = '*'; function FindAnyPart(const BaseName: string; Compat: Boolean): string; var Fs: string; N: Integer; NN: string; R: Integer; SRec: _Z_TSearchRec; begin Result := ''; if Compat then Fs := BaseName + '.z??*' else Fs := BaseName + '???.zip'; R := _Z_FindFirst(Fs, FaAnyFile, SRec); while R = 0 do begin if Compat then begin Fs := UpperCase(Copy(ExtractFileExt(SRec.Name), 3, 20)); if Fs = 'IP' then NN := '99999' else NN := Fs; end else NN := Copy(SRec.Name, Length(SRec.Name) - 6, 3); N := StrToIntDef(NN, 0); if N > 0 then begin Result := SRec.Name; // possible name Break; end; R := _Z_FindNext(SRec); end; _Z_FindClose(SRec); end; function TZMReader.GetItems(Index: Integer): TZMEntryReader; begin Result := TZMEntryReader(Entries[Index]); end; procedure TZMReader.LoadEntries; var I: Integer; NewEntry: TZMEntryReader; R: Integer; begin if TotalEntries < 1 then Exit; for I := 0 to (TotalEntries - 1) do begin NewEntry := TZMEntryReader.Create(Self); Add(NewEntry); R := NewEntry.Read; if R < 0 then raise EZipMaster.CreateMsg(Body, R, 0); if R > 0 then Z64 := True; {$IFDEF DEBUG} if Verbosity >= ZvTrace then DiagFmt(ZT_List, [I, NewEntry.FileName], _U_ + 162); {$ENDIF} // Notify user, when needed, of the NextSelected entry in the ZipDir. if Assigned(OnChange) then OnChange(Self, I, ZccAdd); // change event to give TZipDirEntry // Calculate the earliest Local Header start if SFXOfs > NewEntry.RelOffLocalHdr then SFXOfs := NewEntry.RelOffLocalHdr; Guage.Advance(1); CheckCancel; end; // for; end; function TZMReader.LoadSFXStub(const ZipName: string): Integer; var FN: string; Size: Integer; begin Stub := nil; FN := ZipName; Result := CheckSFXType(Stream, FN, Size); if Result >= CstSFX17 then begin if Seek(0, SoBeginning) <> 0 then Exit; Stub := TMemoryStream.Create; try if ReadTo(Stub, Size) <> Size then Stub := nil; except Stub := nil; end; end; end; function TZMReader.LoadTheZip: Integer; begin LastWriteTime(FEOCFileTime); InferNumbering; Info := Info or Zfi_EOC; Result := LoadZip; if Result = 0 then begin Info := Info or Zfi_Loaded or Zfi_DidLoad; SaveFileInformation; // get details end; end; function TZMReader.LoadZip: Integer; var LiE: Integer; OffsetDiff: Int64; Sgn: Cardinal; begin if not IsOpen then begin Result := Body.PrepareErrMsg(ZE_FileOpen, [ArchiveName], _U_ + 219); Exit; end; Result := ZMError(ZE_UnknownError, _U_ + 222); if (Info and Zfi_EOC) = 0 then Exit; // should not get here if eoc has not been read LiE := 1; OffsetDiff := 0; ClearEntries; if Assigned(OnChange) then OnChange(Self, 0, ZccBegin); SOCOfs := CentralOffset; try OffsetDiff := CentralOffset; // Do we have to request for a previous disk first? if DiskNr <> CentralDiskNo then begin SeekDisk(CentralDiskNo, False); File_Size := Seek(0, SoEnd); end else if not Z64 then begin // Due to the fact that v1.3 and v1.4x programs do not change the archives // EOC and CEH records in case of a SFX conversion (and back) we have to // make this extra check. OffsetDiff := File_Size - (Integer(CentralSize) + SizeOf(TZipEndOfCentral) + ZipCommentLen); end; SOCOfs := OffsetDiff; // save the location of the Start Of Central dir SFXOfs := Cardinal(OffsetDiff); if SFXOfs <> SOCOfs then SFXOfs := 0; // initialize this - we will reduce it later if File_Size = 22 then SFXOfs := 0; if CentralOffset <> OffsetDiff then begin // We need this in the ConvertXxx functions. Body.ShowErrorEx(ZW_WrongZipStruct, _U_ + 260); CheckSeek(CentralOffset, SoBeginning, ZMError(ZE_ReadZipError, _U_ + 261)); CheckRead(Sgn, 4, ZMError(ZE_CEHBadRead, _U_ + 262)); if Sgn = CentralFileHeaderSig then begin SOCOfs := CentralOffset; // TODO warn - central size error end; end; // Now we can go to the start of the Central directory. CheckSeek(SOCOfs, SoBeginning, ZMError(ZE_ReadZipError, _U_ + 271)); Guage.NewItem(ZP_Loading, TotalEntries); // Read every entry: The central header and save the information. {$IFDEF DEBUG} DiagFmt(ZT_ListExpectingFiles, [TotalEntries], _U_ + 275); {$ENDIF} LoadEntries; LiE := 0; // finished ok Result := 0; Info := (Info and not(Zfi_MakeMask)) or Zfi_Loaded; finally Guage.EndBatch; if LiE = 1 then begin ArchiveName := ''; SFXOfs := 0; File_Close; end else begin CentralOffset := SOCOfs; // corrected // Correct the offset for v1.3 and 1.4x SFXOfs := SFXOfs + Cardinal(OffsetDiff - CentralOffset); end; // Let the user's program know we just refreshed the zip dir contents. if Assigned(OnChange) then OnChange(Self, Count, ZccEnd); end; end; function TZMReader.Open1(EOConly: Boolean): Integer; var FN: string; Res: Integer; SfxType: Integer; begin SfxType := 0; // keep compiler happy ReqFileName := ArchiveName; FN := ArchiveName; Result := OpenEOC(FN, EOConly); if (Result >= 0) and (Sig = ZfsDOS) then begin // found sfx eoc SfxType := LoadSFXStub(FN); end; if IsExtStream then Exit; // must have eoc // wasn't found or looking for 'detached' last part if not(SpExactName in Span.Options) then begin if (Result >= 0) and (SfxType >= CstDetached) then begin // it is last part of detached sfx File_Close; // Get proper path and name ArchiveName := ChangeFileExt(FN, '.zip'); // find last part Result := -ZE_NoInFile; end; if Result < 0 then begin Res{ult} := OpenLast(EOConly, Result); if Res >= 0 then Result := Res; // ignore OpenLast errors end; end; end; // GetLastVolume function TZMReader.OpenLast(EOConly: Boolean; OpenRes: Integer): Integer; var BaseName: string; Ext: string; FMVolume: Boolean; OrigName: string; PartNbr: Integer; Path: string; Possible: Integer; TmpNumbering: TZipNumberScheme; WasNoFile: Boolean; begin Result := AbsErr(OpenRes); WasNoFile := Result = ZE_NoInFile; PartNbr := -1; Result := 0; Possible := 0; FMVolume := False; OrigName := ArchiveName; // save it WorkDrive.DriveStr := ArchiveName; Path := ExtractFilePath(ArchiveName); Numbering := ZnsNone; // unknown as yet TmpNumbering := ZnsNone; try WorkDrive.HasMedia(False); // check valid drive if WasNoFile then BaseName := ChangeFileExt(ArchiveName, '') // remove extension else begin // file exists but is not last part of zip Possible := PossibleBase(BaseName, ArchiveName); if Possible < 0 then Result := OpenLastExt(BaseName + '.zip', EOConly) else if Possible > 0 then WasNoFile := True; end; if WasNoFile then begin // file did not exist maybe it is a multi volume FMVolume := True; Ext := ExtractFileExt(ArchiveName); if CompareText(Ext, EXT_ZIP) = 0 then begin // get the 'base' name for numbered names // remove extension // if no file exists with exact name on harddisk then only Multi volume parts are possible if WorkDrive.DriveIsFixed then // filename is of type ArchiveXXX.zip // MV files are series with consecutive partnbrs in filename, // highest number has EOC Result := OpenLastFixed(BaseName, PartNbr, EOConly) else // do we have an MV archive copied to a removable disk // accept any MV filename on disk - then we ask for last part Result := OpenLastPart(BaseName, Path); end//; else Result := OpenRes; end; // if not exists if Result >= 0 then begin // zip file exists or we got an acceptable part in multivolume or split // archive // use class variable for other functions Result := OpenLastFind(FMVolume, BaseName, Path, TmpNumbering, EOConly); if FMVolume then // got a multi volume part so we need more checks Result := OpenLastVerify(PartNbr); end; finally if Result < 0 then begin File_Close; // close filehandle if OpenLast ArchiveName := ''; // don't use the file end else if (Numbering <> ZnsVolume) and (TmpNumbering <> ZnsNone) then Numbering := TmpNumbering; end; if (Result >= 0) and (Possible <> 0) then begin ArchiveName := BaseName + '.ZIP'; ReqFileName := ArchiveName; DiagStr(ZT_UsingBaseNameOfMultiPartZip, ArchiveName, _U_ + 423); end; end; function TZMReader.OpenLastExt(FName: string; EOConly: Boolean): Integer; var StampLast: Integer; StampPart: Integer; begin StampPart := Integer(File_Age(ArchiveName)); StampLast := Integer(File_Age(FName)); if (StampPart = -1) or (StampLast = -1) or ((StampPart <> StampLast) and not(SpAnyTime in Span.Options)) then begin // not found or stamp does not match Result := ZMError(ZE_NoInFile, _U_ + 438); Exit; end; Result := OpenEOC(FName, EOConly); if Result >= 0 then begin // found possible last part Numbering := ZnsExt; end; end; function TZMReader.OpenLastFind(var FMVolume: Boolean; const Fname, Path: string; var TmpNumbering: TZipNumberScheme; EOConly: Boolean): Integer; var SName: string; begin Result := 0; // zip file exists or we got an acceptable part in multivolume or split // archive // use class variable for other functions while not IsOpen do // only open if found last part on hd begin // does this part contains the central dir Result := OpenEOC(ArchiveName, EOConly); // don't LoadZip on success if Result >= 0 then Break; // found a 'last' disk if WorkDrive.DriveIsFixed then begin if (not FMVolume) and (AbsErr(Result) <> ZE_FileOpen) then Result := ZMError(ZE_NoValidZip, _U_ + 467); Break; // file with EOC is not on fixed disk end; // it is not the disk with central dir so ask for the last disk NewDisk := True; // new last disk DiskNr := -1; // read operation CheckForDisk(False, False); // does the request for new disk if FMVolume and not FileExists(ArchiveName) then begin // we have removable disks with multi volume archives // get the file name on this disk TmpNumbering := ZnsName; // only if part and last part inserted SName := FindAnyPart(Fname, False); if SName = '' then begin SName := FindAnyPart(Fname, True); TmpNumbering := ZnsExt; // only if last part inserted end; if SName = '' then // none begin Result := ZMError(ZE_NoInFile, _U_ + 486); // no file with likely name FMVolume := False; Break; end; ArchiveName := Path + SName; end; end; // while; end; function TZMReader.OpenLastFixed(const BaseName: string; var PartNbr: Integer; EOConly: Boolean): Integer; var Finding: Boolean; S: string; Stamp: Integer; StampTmp: Integer; begin Result := 0; // default failure // filename is of type ArchiveXXX.zip // MV files are series with consecutive partnbrs in filename, // highest number has EOC Finding := True; Stamp := -1; while Finding and (PartNbr < 1000) do begin if KeepAlive then begin Diag(ZT_OpenLastUserAbort, _U_ + 514); Result := Body.PrepareErrMsg(ZE_FileOpen, [ArchiveName], _U_ + 515); Exit; // cancelled end; // add part number and extension to base name S := BaseName + Copy(IntToStr(1002 + PartNbr), 2, 3) + EXT_ZIPL; StampTmp := Integer(File_Age(S)); if (StampTmp = -1) or ((Stamp <> -1) and (StampTmp <> Stamp)) then begin // not found or stamp does not match Result := ZMError(ZE_NoInFile, _U_ + 524); Exit; end; if (PartNbr = -1) and not(SpAnyTime in Span.Options) then Stamp := StampTmp; Inc(PartNbr); ArchiveName := S; Result := OpenEOC(ArchiveName, EOConly); if Result >= 0 then begin // found possible last part Finding := False; if (TotalDisks - 1) <> PartNbr then begin // was not last disk File_Close; // should happen in 'finally' Result := Body.PrepareErrMsg(ZE_FileOpen, [ArchiveName], _U_ + 539); Exit; end; Numbering := ZnsName; end; end; // while if not IsOpen then Result := ZMError(ZE_NoInFile, _U_ + 546) // not found else begin // should be the same as s ArchiveName := BaseName + Copy(IntToStr(1001 + PartNbr), 2, 3) + EXT_ZIPL; // check if filename.z01 exists then it is part of MV with compat names // and cannot be used if (FileExists(ChangeFileExt(ArchiveName, '.z01'))) then begin // ambiguous - cannot be used File_Close; // should happen in 'finally' Result := Body.PrepareErrMsg(ZE_FileOpen, [ArchiveName], _U_ + 557); end; end; end; function TZMReader.OpenLastPart(const BaseName, Path: string): Integer; var SName: string; begin Result := 0; // do we have an MV archive copied to a removable disk // accept any MV filename on disk - then we ask for last part SName := FindAnyPart(BaseName, False); // try numbered name if SName = '' then SName := FindAnyPart(BaseName, True); // try numbered extension if SName = '' then // none Result := ZMError(ZE_NoInFile, _U_ + 573) // no file with likely name else ArchiveName := Path + SName; end; function TZMReader.OpenLastVerify(PartNbr: Integer): Integer; begin // is this first file of a multi-part Result := 0; if (Sig <> ZfsMulti) and ((TotalDisks = 1) and (PartNbr >= 0)) then Result := Body.PrepareErrMsg(ZE_FileOpen, [ArchiveName], _U_ + 582) else // part and EOC equal? if WorkDrive.DriveIsFixed and (TotalDisks <> (PartNbr + 1)) then begin File_Close; // should happen in 'finally' Result := ZMError(ZE_NoValidZip, _U_ + 588); end; end; function TZMReader.OpenZip(EOConly, NoLoad: Boolean): Integer; var FN: string; Possible: Integer; R: Integer; begin // verify disk loaded ClearFileInformation; Possible := 0; Info := (Info and Zfi_MakeMask) or Zfi_Loading; if IsExtStream or WorkDrive.DriveIsFixed or WorkDrive.HasMedia(False) then begin if IsExtStream then FN := '<stream>' else FN := ArchiveName; DiagStr(ZT_OpeningZip, FN, _U_ + 608); Result := Open1(EOConly); if (Result >= 0) and (TotalDisks > 1) and not EOConly then begin MultiDisk := True; if Unattended and WorkDrive.DriveIsFloppy and not Assigned(Master.OnGetNextDisk) then Result := ZMError(ZE_NoUnattSpan, _U_ + 615) else if not IsExtStream then begin IsMultiPart := True; DiagStr(ZT_OpenedMultiPartZip, FN, _U_ + 620); if Numbering = ZnsNone then begin // numbering is not known yet FN := ChangeFileExt(ArchiveName, ''); Possible := PossibleBase(FN, ArchiveName); if (Possible > 0) and (Possible <> (DiskNr + 1)) then Possible := 0; if Possible > 0 then Possible := VerifyPossible(FN); end; end; end; if (Result >= 0) and not(EOConly or NoLoad) then begin if (Result and EOCBadComment) <> 0 then Body.ShowErrorEx(ZW_EOCCommentLen, _U_ + 636); if (Result and EOCBadStruct) <> 0 then Body.ShowErrorEx(ZW_WrongZipStruct, _U_ + 638); if IsExtStream and (TotalDisks > 1) then raise EZipMaster.CreateMsg(Body, ZE_StreamNoSupport, _U_ + 640); R := LoadTheZip; if R < 0 then Result := R; end; // adjust name if (Result >= 0) and (Possible <> 0) then begin ArchiveName := FN + '.ZIP'; ReqFileName := ArchiveName; DiagStr(ZT_UsingBaseNameOfMultiPartZip, ArchiveName, _U_ + 650); end; end else Result := -ZE_NoInFile; OpenRet := Result; DiagErr(dfAll + ZT_OpenZipReturns, Result, _U_+656); // if IsTrace then // begin // if Result < 0 then // DiagErr(ZT_OpenError, Result, _U_ + 369) //// DiagStr(ZT_OpenError, ZipLoadStr(Result), _U_ + 369) // else // DiagInt(ZT_OpenStatus, Result, _U_ + 372); //// DiagFmt(ZT_OpenStatus, [Result], _U_ + 371); // end; end; // returns 0 _ not valid, <0 _ numbered extension, >0 _ numbered name function TZMReader.PossibleBase(var FName: string; const RequestedName: string): Integer; const Digits = ['0'..'9']; var Extn: string; FileName: string; I: Integer; Len: Integer; N: Integer; NNN: string; begin Result := 0; Extn := UpperCase(ExtractFileExt(Name)); if (Length(Extn) <> 4) or (Extn[2] <> 'Z') then Exit; if CharInSet(Extn[3], Digits) and CharInSet(Extn[4], Digits) then Result := -1 else if (Extn[3] = 'I') and (Extn[4] = 'P') then begin for I := Length(RequestedName) - 4 downto Length(RequestedName) - 6 do if (I < 2) or not CharInSet(RequestedName[I], Digits) then Exit; FileName := ExtractNameOfFile(RequestedName); if Length(FileName) > 3 then begin // needs 3 digits NNN := Copy(FileName, Length(FileName) - 2, 3); if TryStrToInt(NNN, N) then Result := N; end; end; if Result <> 0 then begin Len := Length(RequestedName) - Length(Extn); if Result > 0 then Len := Len - 3; FName := Copy(RequestedName, 1, Len); end; end; function TZMReader.VerifyOpen: Integer; var Ft: TFileTime; begin Result := 0; if not IsOpen and not File_Open('', FmOpenRead or FmShareDenyWrite) then begin Result := Body.PrepareErrMsg(ZE_FileOpen, [ArchiveName], _U_ + 719); Exit; end; if LastWriteTime(Ft) then begin LastWriteTime(FEOCFileTime); if CompareFileTime(EOCFileTime, Ft) <> 0 then Result := Body.PrepareErrMsg(ZE_FileChanged, [Name], _U_ + 726); end; end; function TZMReader.VerifyPossible(const FN: string): Integer; var Stamp: Cardinal; begin Result := 0; Stamp := File_Age(ChangeFileExt(ArchiveName, '.z01')); if Stamp <> Cardinal(-1) then Exit; // ambiguous - named extension exists Stamp := File_Age(FN + '001.zip'); if Stamp = Cardinal(-1) then Exit; // first part not found if (not(SpAnyTime in Span.Options)) or (File_Age(ArchiveName) = Stamp) then Result := 1; end; end.
unit PrimDocNumberQuery_Form; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/PrimDocNumberQuery_Form.pas" // Начат: 02.10.2009 21:19 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMForm::Class>> F1 Работа с документом и списком документов::Document::View::OpenDocumentByNumber::PrimDocNumberQuery // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses l3Interfaces {$If not defined(NoVCM)} , vcmEntityForm {$IfEnd} //not NoVCM , eeCheckBox {$If defined(Nemesis)} , nscComboBox {$IfEnd} //Nemesis , NavigationInterfaces, vtLabel {$If not defined(NoScripts)} , kwBynameControlPush {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts , vcmExternalInterfaces {a}, vcmInterfaces {a}, vcmBase {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type TPrimDocNumberQueryForm = {form} class(TvcmEntityForm) private // private fields f_Label1 : TvtLabel; {* Поле для свойства Label1} f_edNumber : TnscComboBox; {* Поле для свойства edNumber} f_cbInternal : TeeCheckBox; {* Поле для свойства cbInternal} protected procedure MakeControls; override; protected // overridden protected methods {$If not defined(NoVCM)} procedure DoInit(aFromHistory: Boolean); override; {* Инициализация формы. Для перекрытия в потомках } {$IfEnd} //not NoVCM {$If not defined(NoVCM)} procedure InitControls; override; {* Процедура инициализации контролов. Для перекрытия в потомках } {$IfEnd} //not NoVCM procedure ClearFields; override; protected // protected fields f_Results : InsOpenDocOnNumberData; protected // protected methods function Save: Boolean; procedure LoadHistory(const aHistory: Il3CString); procedure SaveHistory(aLastNumber: LongInt; var aHistory: AnsiString); public // public methods class function Make(const aData: InsOpenDocOnNumberData; const aParams : IvcmMakeParams = nil; aZoneType : TvcmZoneType = vcm_ztAny; aUserType : TvcmEffectiveUserType = 0; aDataSource : IvcmFormDataSource = nil): IvcmEntityForm; reintroduce; public // public properties property Label1: TvtLabel read f_Label1; {* Номер документа: } property edNumber: TnscComboBox read f_edNumber; property cbInternal: TeeCheckBox read f_cbInternal; {* Внутренний номер в базе } end;//TPrimDocNumberQueryForm {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses nsUtils, nsTypes, SysUtils, bsTypesNew, l3String, Controls, Forms {$If not defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} //not NoScripts , StdRes {a}, l3Base {a} ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} const { DocNumberQuery Const } c_HistoryFormat = 'DDDDDDDDDD'; c_HistoryCapacity = 10; type Tkw_PrimDocNumberQuery_Control_Label1 = class(TtfwControlString) {* Слово словаря для идентификатора контрола Label1 ---- *Пример использования*: [code] контрол::Label1 TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_PrimDocNumberQuery_Control_Label1 // start class Tkw_PrimDocNumberQuery_Control_Label1 {$If not defined(NoScripts)} function Tkw_PrimDocNumberQuery_Control_Label1.GetString: AnsiString; {-} begin Result := 'Label1'; end;//Tkw_PrimDocNumberQuery_Control_Label1.GetString {$IfEnd} //not NoScripts type Tkw_PrimDocNumberQuery_Control_Label1_Push = class(TkwBynameControlPush) {* Слово словаря для контрола Label1 ---- *Пример использования*: [code] контрол::Label1:push pop:control:SetFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_PrimDocNumberQuery_Control_Label1_Push // start class Tkw_PrimDocNumberQuery_Control_Label1_Push {$If not defined(NoScripts)} procedure Tkw_PrimDocNumberQuery_Control_Label1_Push.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushString('Label1'); inherited; end;//Tkw_PrimDocNumberQuery_Control_Label1_Push.DoDoIt {$IfEnd} //not NoScripts type Tkw_PrimDocNumberQuery_Control_edNumber = class(TtfwControlString) {* Слово словаря для идентификатора контрола edNumber ---- *Пример использования*: [code] контрол::edNumber TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_PrimDocNumberQuery_Control_edNumber // start class Tkw_PrimDocNumberQuery_Control_edNumber {$If not defined(NoScripts)} function Tkw_PrimDocNumberQuery_Control_edNumber.GetString: AnsiString; {-} begin Result := 'edNumber'; end;//Tkw_PrimDocNumberQuery_Control_edNumber.GetString {$IfEnd} //not NoScripts type Tkw_PrimDocNumberQuery_Control_edNumber_Push = class(TkwBynameControlPush) {* Слово словаря для контрола edNumber ---- *Пример использования*: [code] контрол::edNumber:push pop:control:SetFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_PrimDocNumberQuery_Control_edNumber_Push // start class Tkw_PrimDocNumberQuery_Control_edNumber_Push {$If not defined(NoScripts)} procedure Tkw_PrimDocNumberQuery_Control_edNumber_Push.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushString('edNumber'); inherited; end;//Tkw_PrimDocNumberQuery_Control_edNumber_Push.DoDoIt {$IfEnd} //not NoScripts type Tkw_PrimDocNumberQuery_Control_cbInternal = class(TtfwControlString) {* Слово словаря для идентификатора контрола cbInternal ---- *Пример использования*: [code] контрол::cbInternal TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_PrimDocNumberQuery_Control_cbInternal // start class Tkw_PrimDocNumberQuery_Control_cbInternal {$If not defined(NoScripts)} function Tkw_PrimDocNumberQuery_Control_cbInternal.GetString: AnsiString; {-} begin Result := 'cbInternal'; end;//Tkw_PrimDocNumberQuery_Control_cbInternal.GetString {$IfEnd} //not NoScripts type Tkw_PrimDocNumberQuery_Control_cbInternal_Push = class(TkwBynameControlPush) {* Слово словаря для контрола cbInternal ---- *Пример использования*: [code] контрол::cbInternal:push pop:control:SetFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} procedure DoDoIt(const aCtx: TtfwContext); override; {$IfEnd} //not NoScripts end;//Tkw_PrimDocNumberQuery_Control_cbInternal_Push // start class Tkw_PrimDocNumberQuery_Control_cbInternal_Push {$If not defined(NoScripts)} procedure Tkw_PrimDocNumberQuery_Control_cbInternal_Push.DoDoIt(const aCtx: TtfwContext); {-} begin aCtx.rEngine.PushString('cbInternal'); inherited; end;//Tkw_PrimDocNumberQuery_Control_cbInternal_Push.DoDoIt {$IfEnd} //not NoScripts function TPrimDocNumberQueryForm.Save: Boolean; //#UC START# *4C863FCD0121_4AC63602020E_var* var l_DocId : Integer; l_PosId : Integer; l_PosType : TDocumentPositionType; l_Wrong : Boolean; l_History : String; //#UC END# *4C863FCD0121_4AC63602020E_var* begin //#UC START# *4C863FCD0121_4AC63602020E_impl* Result := false; nsParseDocumentNumber(edNumber.Text, l_DocId, l_PosId, l_PosType, l_Wrong); if l_Wrong then begin Say(msg_WrongDocumentNumber); edNumber.SetFocus; Exit; end;//l_Wrong SaveHistory(l_DocId, l_History); // Передаем результат в вызывающую операцию if (f_Results <> nil) then begin f_Results.Done := true; f_Results.DocID := l_DocId; f_Results.PosID := l_PosID; f_Results.PosType := l_PosType; f_Results.Internal := cbInternal.Checked; f_Results.History := nsCStr(l_History); end;//f_Results <> nil Result := true; //#UC END# *4C863FCD0121_4AC63602020E_impl* end;//TPrimDocNumberQueryForm.Save procedure TPrimDocNumberQueryForm.LoadHistory(const aHistory: Il3CString); //#UC START# *51B9E1A00192_4AC63602020E_var* var l_DocNumberHistory: packed array [0..c_HistoryCapacity-1] of Longint; I: LongInt; //#UC END# *51B9E1A00192_4AC63602020E_var* begin //#UC START# *51B9E1A00192_4AC63602020E_impl* if not l3IsNil(aHistory) then begin l3FormatStringToRec(l3Str(aHistory), l_DocNumberHistory, c_HistoryFormat); for I := 0 to c_HistoryCapacity - 1 do if (l_DocNumberHistory[I] <> 0) then edNumber.Items.Add(IntToStr(l_DocNumberHistory[I])); end;//aHistory <> '' //#UC END# *51B9E1A00192_4AC63602020E_impl* end;//TPrimDocNumberQueryForm.LoadHistory class function TPrimDocNumberQueryForm.Make(const aData: InsOpenDocOnNumberData; const aParams : IvcmMakeParams = nil; aZoneType : TvcmZoneType = vcm_ztAny; aUserType : TvcmEffectiveUserType = 0; aDataSource : IvcmFormDataSource = nil): IvcmEntityForm; procedure AfterCreate(aForm : TPrimDocNumberQueryForm); begin with aForm do begin //#UC START# *51B9E27000CD_4AC63602020E_impl* if (aData.PosID <> 0) then begin case aData.PosType of dptSub: edNumber.Text := nsCStr(IntToStr(aData.DocID) + cPosDelimiter + IntToStr(aData.PosID)); dptPara: edNumber.Text := nsCStr(IntToStr(aData.DocID) + cPosDelimiter + cParaPrefix + IntToStr(aData.PosID)); dptNone, dptMarker, dptBookmark, dptMark, dptDocumentPlace: edNumber.Text := nsCStr(IntToStr(aData.DocID)); end; end else edNumber.Text := nsCStr(IntToStr(aData.DocID)); cbInternal.Checked := aData.Internal; LoadHistory(aData.History); f_Results := aData; //#UC END# *51B9E27000CD_4AC63602020E_impl* end;//with aForm end; var l_AC : TvcmInitProc; l_ACHack : Pointer absolute l_AC; begin l_AC := l3LocalStub(@AfterCreate); try Result := inherited Make(aParams, aZoneType, aUserType, nil, aDataSource, vcm_utAny, l_AC); finally l3FreeLocalStub(l_ACHack); end;//try..finally end; procedure TPrimDocNumberQueryForm.SaveHistory(aLastNumber: LongInt; var aHistory: AnsiString); //#UC START# *51B9E2AC030D_4AC63602020E_var* var l_DocNumberHistory: packed array [0..c_HistoryCapacity-1] of Longint; l_tmpNum, l_ArrayPos, I: LongInt; //#UC END# *51B9E2AC030D_4AC63602020E_var* begin //#UC START# *51B9E2AC030D_4AC63602020E_impl* l3FillChar(l_DocNumberHistory, SizeOf(l_DocNumberHistory)); l_ArrayPos := 0; l_DocNumberHistory[l_ArrayPos] := aLastNumber; inc(l_ArrayPos); for I := 0 to edNumber.Items.Count - 1 do if l_ArrayPos < c_HistoryCapacity then begin l_tmpNum := StrToInt(edNumber.Items[I].AsString); if l_tmpNum <> aLastNumber then begin l_DocNumberHistory[l_ArrayPos] := l_tmpNum; inc(l_ArrayPos); end; end; aHistory := l3RecToFormatString(l_DocNumberHistory, c_HistoryFormat); //#UC END# *51B9E2AC030D_4AC63602020E_impl* end;//TPrimDocNumberQueryForm.SaveHistory {$If not defined(NoVCM)} procedure TPrimDocNumberQueryForm.DoInit(aFromHistory: Boolean); //#UC START# *49803F5503AA_4AC63602020E_var* //#UC END# *49803F5503AA_4AC63602020E_var* begin //#UC START# *49803F5503AA_4AC63602020E_impl* inherited; Position := poScreenCenter; //#UC END# *49803F5503AA_4AC63602020E_impl* end;//TPrimDocNumberQueryForm.DoInit {$IfEnd} //not NoVCM {$If not defined(NoVCM)} procedure TPrimDocNumberQueryForm.InitControls; //#UC START# *4A8E8F2E0195_4AC63602020E_var* //#UC END# *4A8E8F2E0195_4AC63602020E_var* begin //#UC START# *4A8E8F2E0195_4AC63602020E_impl* inherited; BorderIcons := [biSystemMenu]; BorderStyle := bsDialog; ClientHeight := 56; ClientWidth := 279; with Label1 do begin Left := 8; Top := 11; AutoSize := False; Width := 110; Height := 16; end; with edNumber do begin Left := 120; Top := 8; Width := 153; Height := 21; TabOrder := 0; end; with cbInternal do begin Left := 8; Top := 34; Width := 265; Height := 17; TabOrder := 1; end; //#UC END# *4A8E8F2E0195_4AC63602020E_impl* end;//TPrimDocNumberQueryForm.InitControls {$IfEnd} //not NoVCM procedure TPrimDocNumberQueryForm.ClearFields; {-} begin f_Results := nil; inherited; end;//TPrimDocNumberQueryForm.ClearFields procedure TPrimDocNumberQueryForm.MakeControls; begin inherited; f_Label1 := TvtLabel.Create(Self); f_Label1.Name := 'Label1'; f_Label1.Parent := Self; f_Label1.Caption := 'Номер документа:'; f_edNumber := TnscComboBox.Create(Self); f_edNumber.Name := 'edNumber'; f_edNumber.Parent := Self; f_cbInternal := TeeCheckBox.Create(Self); f_cbInternal.Name := 'cbInternal'; f_cbInternal.Parent := Self; f_cbInternal.Caption := 'Внутренний номер в базе'; end; {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_PrimDocNumberQuery_Control_Label1 Tkw_PrimDocNumberQuery_Control_Label1.Register('контрол::Label1', TvtLabel); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_PrimDocNumberQuery_Control_Label1_Push Tkw_PrimDocNumberQuery_Control_Label1_Push.Register('контрол::Label1:push'); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_PrimDocNumberQuery_Control_edNumber Tkw_PrimDocNumberQuery_Control_edNumber.Register('контрол::edNumber', TnscComboBox); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_PrimDocNumberQuery_Control_edNumber_Push Tkw_PrimDocNumberQuery_Control_edNumber_Push.Register('контрол::edNumber:push'); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_PrimDocNumberQuery_Control_cbInternal Tkw_PrimDocNumberQuery_Control_cbInternal.Register('контрол::cbInternal', TeeCheckBox); {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_PrimDocNumberQuery_Control_cbInternal_Push Tkw_PrimDocNumberQuery_Control_cbInternal_Push.Register('контрол::cbInternal:push'); {$IfEnd} //not Admin AND not Monitorings end.
unit BackUpMgr_TLB; { This file contains pascal declarations imported from a type library. This file will be written during each import or refresh of the type library editor. Changes to this file will be discarded during the refresh process. } { BackUpMgr Library } { Version 1.0 } interface uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL; const LIBID_BackUpMgr: TGUID = '{7E819380-5C05-11D4-8C56-0048546B6CD9}'; const { Component class GUIDs } Class_BackUpManager: TGUID = '{7E819382-5C05-11D4-8C56-0048546B6CD9}'; type { Forward declarations: Interfaces } IBackUpManager = interface; IBackUpManagerDisp = dispinterface; { Forward declarations: CoClasses } BackUpManager = IBackUpManager; { Dispatch interface for BackUpManager Object } IBackUpManager = interface(IDispatch) ['{7E819381-5C05-11D4-8C56-0048546B6CD9}'] function Get_ServersDir: WideString; safecall; procedure Set_ServersDir(const Value: WideString); safecall; procedure EnumBackups; safecall; function GetBackupName(i: Integer): WideString; safecall; function SetCurrentBackup(idx: Integer): WordBool; safecall; function Get_WorldName: WideString; safecall; procedure Set_WorldName(const Value: WideString); safecall; function Get_BackupCount: Integer; safecall; function GetBackupDate(i: Integer): WideString; safecall; function GetBackupSize(i: Integer): WideString; safecall; property ServersDir: WideString read Get_ServersDir write Set_ServersDir; property WorldName: WideString read Get_WorldName write Set_WorldName; property BackupCount: Integer read Get_BackupCount; end; { DispInterface declaration for Dual Interface IBackUpManager } IBackUpManagerDisp = dispinterface ['{7E819381-5C05-11D4-8C56-0048546B6CD9}'] property ServersDir: WideString dispid 1; procedure EnumBackups; dispid 2; function GetBackupName(i: Integer): WideString; dispid 3; function SetCurrentBackup(idx: Integer): WordBool; dispid 4; property WorldName: WideString dispid 5; property BackupCount: Integer readonly dispid 6; function GetBackupDate(i: Integer): WideString; dispid 7; function GetBackupSize(i: Integer): WideString; dispid 8; end; { BackUpManagerObject } CoBackUpManager = class class function Create: IBackUpManager; class function CreateRemote(const MachineName: string): IBackUpManager; end; implementation uses ComObj; class function CoBackUpManager.Create: IBackUpManager; begin Result := CreateComObject(Class_BackUpManager) as IBackUpManager; end; class function CoBackUpManager.CreateRemote(const MachineName: string): IBackUpManager; begin Result := CreateRemoteComObject(MachineName, Class_BackUpManager) as IBackUpManager; end; end.
{ This file is part of the Free Component Library (FCL) Copyright (c) 2018 by Michael Van Canneyt Unit tests for Pascal-to-Javascript precompile class. See the file COPYING.FPC, included in this distribution, for details about the copyright. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ********************************************************************** Examples: ./testpas2js --suite=TTestPrecompile.TestPC_EmptyUnit } unit tcfiler; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpcunit, testregistry, jstree, PasTree, PScanner, PParser, PasResolveEval, PasResolver, PasUseAnalyzer, Pas2jsUseAnalyzer, FPPas2Js, Pas2JsFiler, tcmodules; type { TCustomTestPrecompile } TCustomTestPrecompile = Class(TCustomTestModule) private FAnalyzer: TPas2JSAnalyzer; FInitialFlags: TPCUInitialFlags; FPCUReader: TPCUReader; FPCUWriter: TPCUWriter; FRestAnalyzer: TPas2JSAnalyzer; procedure OnFilerGetSrc(Sender: TObject; aFilename: string; out p: PChar; out Count: integer); function OnConverterIsElementUsed(Sender: TObject; El: TPasElement): boolean; function OnConverterIsTypeInfoUsed(Sender: TObject; El: TPasElement): boolean; function OnRestConverterIsElementUsed(Sender: TObject; El: TPasElement): boolean; function OnRestConverterIsTypeInfoUsed(Sender: TObject; El: TPasElement): boolean; function OnRestResolverFindUnit(const aUnitName: String): TPasModule; protected procedure SetUp; override; procedure TearDown; override; function CreateConverter: TPasToJSConverter; override; procedure ParseUnit; override; procedure WriteReadUnit; virtual; procedure StartParsing; override; function CheckRestoredObject(const Path: string; Orig, Rest: TObject): boolean; virtual; procedure CheckRestoredJS(const Path, Orig, Rest: string); virtual; // check restored parser+resolver procedure CheckRestoredResolver(Original, Restored: TPas2JSResolver); virtual; procedure CheckRestoredDeclarations(const Path: string; Orig, Rest: TPasDeclarations); virtual; procedure CheckRestoredSection(const Path: string; Orig, Rest: TPasSection); virtual; procedure CheckRestoredModule(const Path: string; Orig, Rest: TPasModule); virtual; procedure CheckRestoredScopeReference(const Path: string; Orig, Rest: TPasScope); virtual; procedure CheckRestoredElementBase(const Path: string; Orig, Rest: TPasElementBase); virtual; procedure CheckRestoredResolveData(const Path: string; Orig, Rest: TResolveData); virtual; procedure CheckRestoredPasScope(const Path: string; Orig, Rest: TPasScope); virtual; procedure CheckRestoredModuleScope(const Path: string; Orig, Rest: TPas2JSModuleScope); virtual; procedure CheckRestoredIdentifierScope(const Path: string; Orig, Rest: TPasIdentifierScope); virtual; procedure CheckRestoredSectionScope(const Path: string; Orig, Rest: TPas2JSSectionScope); virtual; procedure CheckRestoredInitialFinalizationScope(const Path: string; Orig, Rest: TPas2JSInitialFinalizationScope); virtual; procedure CheckRestoredEnumTypeScope(const Path: string; Orig, Rest: TPasEnumTypeScope); virtual; procedure CheckRestoredRecordScope(const Path: string; Orig, Rest: TPasRecordScope); virtual; procedure CheckRestoredClassScope(const Path: string; Orig, Rest: TPas2JSClassScope); virtual; procedure CheckRestoredProcScope(const Path: string; Orig, Rest: TPas2JSProcedureScope); virtual; procedure CheckRestoredScopeRefs(const Path: string; Orig, Rest: TPasScopeReferences); virtual; procedure CheckRestoredPropertyScope(const Path: string; Orig, Rest: TPasPropertyScope); virtual; procedure CheckRestoredResolvedReference(const Path: string; Orig, Rest: TResolvedReference); virtual; procedure CheckRestoredEvalValue(const Path: string; Orig, Rest: TResEvalValue); virtual; procedure CheckRestoredCustomData(const Path: string; RestoredEl: TPasElement; Orig, Rest: TObject); virtual; procedure CheckRestoredReference(const Path: string; Orig, Rest: TPasElement); virtual; procedure CheckRestoredElOrRef(const Path: string; Orig, OrigProp, Rest, RestProp: TPasElement); virtual; procedure CheckRestoredAnalyzerElement(const Path: string; Orig, Rest: TPasElement); virtual; procedure CheckRestoredElement(const Path: string; Orig, Rest: TPasElement); virtual; procedure CheckRestoredElementList(const Path: string; Orig, Rest: TFPList); virtual; procedure CheckRestoredElementArray(const Path: string; Orig, Rest: TPasElementArray); virtual; procedure CheckRestoredElRefList(const Path: string; OrigParent: TPasElement; Orig: TFPList; RestParent: TPasElement; Rest: TFPList; AllowInSitu: boolean); virtual; procedure CheckRestoredPasExpr(const Path: string; Orig, Rest: TPasExpr); virtual; procedure CheckRestoredUnaryExpr(const Path: string; Orig, Rest: TUnaryExpr); virtual; procedure CheckRestoredBinaryExpr(const Path: string; Orig, Rest: TBinaryExpr); virtual; procedure CheckRestoredPrimitiveExpr(const Path: string; Orig, Rest: TPrimitiveExpr); virtual; procedure CheckRestoredBoolConstExpr(const Path: string; Orig, Rest: TBoolConstExpr); virtual; procedure CheckRestoredParamsExpr(const Path: string; Orig, Rest: TParamsExpr); virtual; procedure CheckRestoredProcedureExpr(const Path: string; Orig, Rest: TProcedureExpr); virtual; procedure CheckRestoredRecordValues(const Path: string; Orig, Rest: TRecordValues); virtual; procedure CheckRestoredPasExprArray(const Path: string; Orig, Rest: TPasExprArray); virtual; procedure CheckRestoredArrayValues(const Path: string; Orig, Rest: TArrayValues); virtual; procedure CheckRestoredResString(const Path: string; Orig, Rest: TPasResString); virtual; procedure CheckRestoredAliasType(const Path: string; Orig, Rest: TPasAliasType); virtual; procedure CheckRestoredPointerType(const Path: string; Orig, Rest: TPasPointerType); virtual; procedure CheckRestoredSpecializedType(const Path: string; Orig, Rest: TPasSpecializeType); virtual; procedure CheckRestoredInlineSpecializedExpr(const Path: string; Orig, Rest: TInlineSpecializeExpr); virtual; procedure CheckRestoredGenericTemplateType(const Path: string; Orig, Rest: TPasGenericTemplateType); virtual; procedure CheckRestoredRangeType(const Path: string; Orig, Rest: TPasRangeType); virtual; procedure CheckRestoredArrayType(const Path: string; Orig, Rest: TPasArrayType); virtual; procedure CheckRestoredFileType(const Path: string; Orig, Rest: TPasFileType); virtual; procedure CheckRestoredEnumValue(const Path: string; Orig, Rest: TPasEnumValue); virtual; procedure CheckRestoredEnumType(const Path: string; Orig, Rest: TPasEnumType); virtual; procedure CheckRestoredSetType(const Path: string; Orig, Rest: TPasSetType); virtual; procedure CheckRestoredVariant(const Path: string; Orig, Rest: TPasVariant); virtual; procedure CheckRestoredRecordType(const Path: string; Orig, Rest: TPasRecordType); virtual; procedure CheckRestoredClassType(const Path: string; Orig, Rest: TPasClassType); virtual; procedure CheckRestoredArgument(const Path: string; Orig, Rest: TPasArgument); virtual; procedure CheckRestoredProcedureType(const Path: string; Orig, Rest: TPasProcedureType); virtual; procedure CheckRestoredResultElement(const Path: string; Orig, Rest: TPasResultElement); virtual; procedure CheckRestoredFunctionType(const Path: string; Orig, Rest: TPasFunctionType); virtual; procedure CheckRestoredStringType(const Path: string; Orig, Rest: TPasStringType); virtual; procedure CheckRestoredVariable(const Path: string; Orig, Rest: TPasVariable); virtual; procedure CheckRestoredExportSymbol(const Path: string; Orig, Rest: TPasExportSymbol); virtual; procedure CheckRestoredConst(const Path: string; Orig, Rest: TPasConst); virtual; procedure CheckRestoredProperty(const Path: string; Orig, Rest: TPasProperty); virtual; procedure CheckRestoredMethodResolution(const Path: string; Orig, Rest: TPasMethodResolution); virtual; procedure CheckRestoredProcNameParts(const Path: string; Orig, Rest: TPasProcedure); virtual; procedure CheckRestoredProcedure(const Path: string; Orig, Rest: TPasProcedure); virtual; procedure CheckRestoredOperator(const Path: string; Orig, Rest: TPasOperator); virtual; procedure CheckRestoredAttributes(const Path: string; Orig, Rest: TPasAttributes); virtual; public property Analyzer: TPas2JSAnalyzer read FAnalyzer; property RestAnalyzer: TPas2JSAnalyzer read FRestAnalyzer; property PCUWriter: TPCUWriter read FPCUWriter write FPCUWriter; property PCUReader: TPCUReader read FPCUReader write FPCUReader; property InitialFlags: TPCUInitialFlags read FInitialFlags; end; { TTestPrecompile } TTestPrecompile = class(TCustomTestPrecompile) published procedure Test_Base256VLQ; procedure TestPC_EmptyUnit; procedure TestPC_Const; procedure TestPC_Var; procedure TestPC_Enum; procedure TestPC_Set; procedure TestPC_Set_InFunction; procedure TestPC_SetOfAnonymousEnumType; procedure TestPC_Record; procedure TestPC_Record_InFunction; procedure TestPC_RecordAdv; procedure TestPC_JSValue; procedure TestPC_Array; procedure TestPC_ArrayOfAnonymous; procedure TestPC_Array_InFunction; procedure TestPC_Proc; procedure TestPC_Proc_Nested; procedure TestPC_Proc_LocalConst; procedure TestPC_Proc_UTF8; procedure TestPC_Proc_Arg; procedure TestPC_ProcType; procedure TestPC_Proc_Anonymous; procedure TestPC_Proc_ArrayOfConst; procedure TestPC_Class; procedure TestPC_ClassForward; procedure TestPC_ClassConstructor; procedure TestPC_ClassDestructor; procedure TestPC_ClassDispatchMessage; procedure TestPC_Initialization; procedure TestPC_BoolSwitches; procedure TestPC_ClassInterface; procedure TestPC_Attributes; procedure TestPC_UseUnit; procedure TestPC_UseUnit_Class; procedure TestPC_UseIndirectUnit; end; function CompareListOfProcScopeRef(Item1, Item2: Pointer): integer; implementation function CompareListOfProcScopeRef(Item1, Item2: Pointer): integer; var Ref1: TPasScopeReference absolute Item1; Ref2: TPasScopeReference absolute Item2; begin Result:=CompareText(Ref1.Element.Name,Ref2.Element.Name); if Result<>0 then exit; Result:=ComparePointer(Ref1.Element,Ref2.Element); end; { TCustomTestPrecompile } procedure TCustomTestPrecompile.OnFilerGetSrc(Sender: TObject; aFilename: string; out p: PChar; out Count: integer); var i: Integer; aModule: TTestEnginePasResolver; Src: String; begin for i:=0 to ResolverCount-1 do begin aModule:=Resolvers[i]; if aModule.Filename<>aFilename then continue; Src:=aModule.Source; p:=PChar(Src); Count:=length(Src); end; end; function TCustomTestPrecompile.OnConverterIsElementUsed(Sender: TObject; El: TPasElement): boolean; begin Result:=Analyzer.IsUsed(El); end; function TCustomTestPrecompile.OnConverterIsTypeInfoUsed(Sender: TObject; El: TPasElement): boolean; begin Result:=Analyzer.IsTypeInfoUsed(El); end; function TCustomTestPrecompile.OnRestConverterIsElementUsed(Sender: TObject; El: TPasElement): boolean; begin Result:=RestAnalyzer.IsUsed(El); end; function TCustomTestPrecompile.OnRestConverterIsTypeInfoUsed(Sender: TObject; El: TPasElement): boolean; begin Result:=RestAnalyzer.IsTypeInfoUsed(El); end; function TCustomTestPrecompile.OnRestResolverFindUnit(const aUnitName: String ): TPasModule; function FindRestUnit(Name: string): TPasModule; var i: Integer; CurEngine: TTestEnginePasResolver; CurUnitName: String; begin for i:=0 to ResolverCount-1 do begin CurEngine:=Resolvers[i]; CurUnitName:=ExtractFileUnitName(CurEngine.Filename); {$IFDEF VerbosePCUFiler} //writeln('TCustomTestPrecompile.FindRestUnit Checking ',i,'/',ResolverCount,' ',CurEngine.Filename,' ',CurUnitName); {$ENDIF} if CompareText(Name,CurUnitName)=0 then begin Result:=CurEngine.Module; if Result<>nil then begin {$IFDEF VerbosePCUFiler} //writeln('TCustomTestPrecompile.FindRestUnit Found parsed module: ',Result.Filename); {$ENDIF} exit; end; {$IFDEF VerbosePCUFiler} writeln('TCustomTestPrecompile.FindRestUnit PARSING unit "',CurEngine.Filename,'"'); {$ENDIF} Fail('not parsed'); end; end; end; var DefNamespace: String; begin if (Pos('.',aUnitName)<1) then begin DefNamespace:=GetDefaultNamespace; if DefNamespace<>'' then begin Result:=FindRestUnit(DefNamespace+'.'+aUnitName); if Result<>nil then exit; end; end; Result:=FindRestUnit(aUnitName); end; procedure TCustomTestPrecompile.SetUp; begin inherited SetUp; FInitialFlags:=TPCUInitialFlags.Create; FAnalyzer:=TPas2JSAnalyzer.Create; Analyzer.Resolver:=Engine; Analyzer.Options:=Analyzer.Options+[paoImplReferences]; Converter.OnIsElementUsed:=@OnConverterIsElementUsed; Converter.OnIsTypeInfoUsed:=@OnConverterIsTypeInfoUsed; end; procedure TCustomTestPrecompile.TearDown; begin FreeAndNil(FAnalyzer); FreeAndNil(FPCUWriter); FreeAndNil(FPCUReader); FreeAndNil(FInitialFlags); inherited TearDown; end; function TCustomTestPrecompile.CreateConverter: TPasToJSConverter; begin Result:=inherited CreateConverter; Result.Options:=Result.Options+[coStoreImplJS]; end; procedure TCustomTestPrecompile.ParseUnit; begin inherited ParseUnit; Analyzer.AnalyzeModule(Module); end; procedure TCustomTestPrecompile.WriteReadUnit; var ms: TMemoryStream; PCU, RestJSSrc, OrigJSSrc: string; // restored classes: RestResolver: TTestEnginePasResolver; RestFileResolver: TFileResolver; RestScanner: TPas2jsPasScanner; RestParser: TPasParser; RestConverter: TPasToJSConverter; RestJSModule: TJSSourceElements; begin ConvertUnit; FPCUWriter:=TPCUWriter.Create; FPCUReader:=TPCUReader.Create; ms:=TMemoryStream.Create; RestParser:=nil; RestScanner:=nil; RestResolver:=nil; RestFileResolver:=nil; RestConverter:=nil; RestJSModule:=nil; try try PCUWriter.OnGetSrc:=@OnFilerGetSrc; PCUWriter.OnIsElementUsed:=@OnConverterIsElementUsed; PCUWriter.WritePCU(Engine,Converter,InitialFlags,ms,false); except on E: Exception do begin {$IFDEF VerbosePas2JS} writeln('TCustomTestPrecompile.WriteReadUnit WRITE failed'); {$ENDIF} Fail('Write failed('+E.ClassName+'): '+E.Message); end; end; try PCU:=''; SetLength(PCU,ms.Size); System.Move(ms.Memory^,PCU[1],length(PCU)); writeln('TCustomTestPrecompile.WriteReadUnit PCU START-----'); writeln(PCU); writeln('TCustomTestPrecompile.WriteReadUnit PCU END-------'); RestFileResolver:=TFileResolver.Create; RestScanner:=TPas2jsPasScanner.Create(RestFileResolver); InitScanner(RestScanner); RestResolver:=TTestEnginePasResolver.Create; RestResolver.Filename:=Engine.Filename; RestResolver.AddObjFPCBuiltInIdentifiers(btAllJSBaseTypes,bfAllJSBaseProcs); RestResolver.OnFindUnit:=@OnRestResolverFindUnit; RestParser:=TPasParser.Create(RestScanner,RestFileResolver,RestResolver); RestParser.Options:=po_tcmodules; RestResolver.CurrentParser:=RestParser; ms.Position:=0; PCUReader.ReadPCU(RestResolver,ms); if not PCUReader.ReadContinue then Fail('ReadContinue=false, pending used interfaces'); except on E: Exception do begin {$IFDEF VerbosePas2JS} writeln('TCustomTestPrecompile.WriteReadUnit READ failed'); {$ENDIF} Fail('Read failed('+E.ClassName+'): '+E.Message); end; end; // analyze FRestAnalyzer:=TPas2JSAnalyzer.Create; FRestAnalyzer.Resolver:=RestResolver; try RestAnalyzer.AnalyzeModule(RestResolver.RootElement); except on E: Exception do begin {$IFDEF VerbosePas2JS} writeln('TCustomTestPrecompile.WriteReadUnit ANALYZEMODULE failed'); {$ENDIF} Fail('AnalyzeModule precompiled failed('+E.ClassName+'): '+E.Message); end; end; // check parser+resolver+analyzer CheckRestoredResolver(Engine,RestResolver); // convert using the precompiled procs RestConverter:=CreateConverter; RestConverter.Options:=Converter.Options; RestConverter.OnIsElementUsed:=@OnRestConverterIsElementUsed; RestConverter.OnIsTypeInfoUsed:=@OnRestConverterIsTypeInfoUsed; try RestJSModule:=RestConverter.ConvertPasElement(RestResolver.RootElement,RestResolver) as TJSSourceElements; except on E: Exception do begin {$IFDEF VerbosePas2JS} writeln('TCustomTestPrecompile.WriteReadUnit CONVERTER failed'); {$ENDIF} Fail('Convert precompiled failed('+E.ClassName+'): '+E.Message); end; end; OrigJSSrc:=JSToStr(JSModule); RestJSSrc:=JSToStr(RestJSModule); if OrigJSSrc<>RestJSSrc then begin writeln('TCustomTestPrecompile.WriteReadUnit OrigJSSrc:---------START'); writeln(OrigJSSrc); writeln('TCustomTestPrecompile.WriteReadUnit OrigJSSrc:---------END'); writeln('TCustomTestPrecompile.WriteReadUnit RestJSSrc:---------START'); writeln(RestJSSrc); writeln('TCustomTestPrecompile.WriteReadUnit RestJSSrc:---------END'); CheckDiff('WriteReadUnit JS diff',OrigJSSrc,RestJSSrc); end; finally RestJSModule.Free; RestConverter.Free; FreeAndNil(FRestAnalyzer); RestParser.Free; RestScanner.Free; if (RestResolver<>nil) and (RestResolver.RootElement<>nil) then begin RestResolver.RootElement.ReleaseUsedUnits; RestResolver.RootElement.Release{$IFDEF CheckPasTreeRefCount}('CreateElement'){$ENDIF}; end; RestResolver.Free; // free parser before resolver RestFileResolver.Free; ms.Free; end; end; procedure TCustomTestPrecompile.StartParsing; begin inherited StartParsing; FInitialFlags.ParserOptions:=Parser.Options; FInitialFlags.ModeSwitches:=Scanner.CurrentModeSwitches; FInitialFlags.BoolSwitches:=Scanner.CurrentBoolSwitches; FInitialFlags.ConverterOptions:=Converter.Options; FInitialFlags.TargetPlatform:=Converter.Globals.TargetPlatform; FInitialFlags.TargetProcessor:=Converter.Globals.TargetProcessor; // ToDo: defines end; function TCustomTestPrecompile.CheckRestoredObject(const Path: string; Orig, Rest: TObject): boolean; begin if Orig=nil then begin if Rest<>nil then Fail(Path+': Orig=nil Rest='+GetObjName(Rest)); exit(false); end else if Rest=nil then Fail(Path+': Orig='+GetObjName(Orig)+' Rest=nil'); if Orig.ClassType<>Rest.ClassType then Fail(Path+': Orig='+GetObjName(Orig)+' Rest='+GetObjName(Rest)); Result:=true; end; procedure TCustomTestPrecompile.CheckRestoredJS(const Path, Orig, Rest: string); var OrigList, RestList: TStringList; i: Integer; begin if Orig=Rest then exit; writeln('TCustomTestPrecompile.CheckRestoredJS ORIG START--------------'); writeln(Orig); writeln('TCustomTestPrecompile.CheckRestoredJS ORIG END----------------'); writeln('TCustomTestPrecompile.CheckRestoredJS REST START--------------'); writeln(Rest); writeln('TCustomTestPrecompile.CheckRestoredJS REST END----------------'); OrigList:=TStringList.Create; RestList:=TStringList.Create; try OrigList.Text:=Orig; RestList.Text:=Rest; for i:=0 to OrigList.Count-1 do begin if i>=RestList.Count then Fail(Path+' missing: '+OrigList[i]); writeln(' ',i,': '+OrigList[i]); end; if OrigList.Count<RestList.Count then Fail(Path+' too much: '+RestList[OrigList.Count]); finally OrigList.Free; RestList.Free; end; end; procedure TCustomTestPrecompile.CheckRestoredResolver(Original, Restored: TPas2JSResolver); var OrigParser, RestParser: TPasParser; begin AssertNotNull('CheckRestoredResolver Original',Original); AssertNotNull('CheckRestoredResolver Restored',Restored); if Original.ClassType<>Restored.ClassType then Fail('CheckRestoredResolver Original='+Original.ClassName+' Restored='+Restored.ClassName); CheckRestoredElement('RootElement',Original.RootElement,Restored.RootElement); OrigParser:=Original.CurrentParser; RestParser:=Restored.CurrentParser; if OrigParser.Options<>RestParser.Options then Fail('CheckRestoredResolver Parser.Options'); if OrigParser.Scanner.CurrentBoolSwitches<>RestParser.Scanner.CurrentBoolSwitches then Fail('CheckRestoredResolver Scanner.BoolSwitches'); if OrigParser.Scanner.CurrentModeSwitches<>RestParser.Scanner.CurrentModeSwitches then Fail('CheckRestoredResolver Scanner.ModeSwitches'); end; procedure TCustomTestPrecompile.CheckRestoredDeclarations(const Path: string; Orig, Rest: TPasDeclarations); var i: Integer; OrigDecl, RestDecl: TPasElement; SubPath: String; begin for i:=0 to Orig.Declarations.Count-1 do begin OrigDecl:=TPasElement(Orig.Declarations[i]); if i>=Rest.Declarations.Count then AssertEquals(Path+'.Declarations.Count',Orig.Declarations.Count,Rest.Declarations.Count); RestDecl:=TPasElement(Rest.Declarations[i]); SubPath:=Path+'['+IntToStr(i)+']'; if OrigDecl.Name<>'' then SubPath:=SubPath+'"'+OrigDecl.Name+'"' else SubPath:=SubPath+'?noname?'; CheckRestoredElement(SubPath,OrigDecl,RestDecl); end; AssertEquals(Path+'.Declarations.Count',Orig.Declarations.Count,Rest.Declarations.Count); end; procedure TCustomTestPrecompile.CheckRestoredSection(const Path: string; Orig, Rest: TPasSection); begin if length(Orig.UsesClause)>0 then ; // ToDo CheckRestoredDeclarations(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredModule(const Path: string; Orig, Rest: TPasModule); procedure CheckInitFinal(const Path: string; OrigBlock, RestBlock: TPasImplBlock); begin CheckRestoredObject(Path,OrigBlock,RestBlock); if OrigBlock=nil then exit; CheckRestoredCustomData(Path+'.CustomData',RestBlock,OrigBlock.CustomData,RestBlock.CustomData); end; begin if not (Orig.CustomData is TPas2JSModuleScope) then Fail(Path+'.CustomData is not TPasModuleScope'+GetObjName(Orig.CustomData)); CheckRestoredElement(Path+'.InterfaceSection',Orig.InterfaceSection,Rest.InterfaceSection); CheckRestoredElement(Path+'.ImplementationSection',Orig.ImplementationSection,Rest.ImplementationSection); if Orig is TPasProgram then CheckRestoredElement(Path+'.ProgramSection',TPasProgram(Orig).ProgramSection,TPasProgram(Rest).ProgramSection) else if Orig is TPasLibrary then CheckRestoredElement(Path+'.LibrarySection',TPasLibrary(Orig).LibrarySection,TPasLibrary(Rest).LibrarySection); CheckInitFinal(Path+'.InitializationSection',Orig.InitializationSection,Rest.InitializationSection); CheckInitFinal(Path+'.FnializationSection',Orig.FinalizationSection,Rest.FinalizationSection); end; procedure TCustomTestPrecompile.CheckRestoredScopeReference(const Path: string; Orig, Rest: TPasScope); begin if not CheckRestoredObject(Path,Orig,Rest) then exit; CheckRestoredReference(Path+'.Element',Orig.Element,Rest.Element); end; procedure TCustomTestPrecompile.CheckRestoredElementBase(const Path: string; Orig, Rest: TPasElementBase); begin CheckRestoredObject(Path+'.CustomData',Orig.CustomData,Rest.CustomData); end; procedure TCustomTestPrecompile.CheckRestoredResolveData(const Path: string; Orig, Rest: TResolveData); begin CheckRestoredElementBase(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredPasScope(const Path: string; Orig, Rest: TPasScope); begin CheckRestoredReference(Path+'.VisibilityContext',Orig.VisibilityContext,Rest.VisibilityContext); CheckRestoredResolveData(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredModuleScope(const Path: string; Orig, Rest: TPas2JSModuleScope); begin AssertEquals(Path+'.FirstName',Orig.FirstName,Rest.FirstName); if Orig.Flags<>Rest.Flags then Fail(Path+'.Flags'); if Orig.BoolSwitches<>Rest.BoolSwitches then Fail(Path+'.BoolSwitches'); CheckRestoredReference(Path+'.AssertClass',Orig.AssertClass,Rest.AssertClass); CheckRestoredReference(Path+'.AssertDefConstructor',Orig.AssertDefConstructor,Rest.AssertDefConstructor); CheckRestoredReference(Path+'.AssertMsgConstructor',Orig.AssertMsgConstructor,Rest.AssertMsgConstructor); CheckRestoredReference(Path+'.RangeErrorClass',Orig.RangeErrorClass,Rest.RangeErrorClass); CheckRestoredReference(Path+'.RangeErrorConstructor',Orig.RangeErrorConstructor,Rest.RangeErrorConstructor); CheckRestoredReference(Path+'.SystemTVarRec',Orig.SystemTVarRec,Rest.SystemTVarRec); CheckRestoredReference(Path+'.SystemVarRecs',Orig.SystemVarRecs,Rest.SystemVarRecs); CheckRestoredPasScope(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredIdentifierScope( const Path: string; Orig, Rest: TPasIdentifierScope); var OrigList: TFPList; i: Integer; OrigIdentifier, RestIdentifier: TPasIdentifier; begin OrigList:=nil; try OrigList:=Orig.GetLocalIdentifiers; for i:=0 to OrigList.Count-1 do begin OrigIdentifier:=TPasIdentifier(OrigList[i]); RestIdentifier:=Rest.FindLocalIdentifier(OrigIdentifier.Identifier); if RestIdentifier=nil then Fail(Path+'.Local['+OrigIdentifier.Identifier+'] Missing RestIdentifier Orig='+OrigIdentifier.Identifier); repeat AssertEquals(Path+'.Local.Identifier',OrigIdentifier.Identifier,RestIdentifier.Identifier); CheckRestoredReference(Path+'.Local',OrigIdentifier.Element,RestIdentifier.Element); if OrigIdentifier.Kind<>RestIdentifier.Kind then Fail(Path+'.Local['+OrigIdentifier.Identifier+'] Orig='+PCUIdentifierKindNames[OrigIdentifier.Kind]+' Rest='+PCUIdentifierKindNames[RestIdentifier.Kind]); if OrigIdentifier.NextSameIdentifier=nil then begin if RestIdentifier.NextSameIdentifier<>nil then Fail(Path+'.Local['+OrigIdentifier.Identifier+'] Too many RestIdentifier.NextSameIdentifier='+GetObjName(RestIdentifier.Element)); break; end else begin if RestIdentifier.NextSameIdentifier=nil then Fail(Path+'.Local['+OrigIdentifier.Identifier+'] Missing RestIdentifier.NextSameIdentifier Orig='+GetObjName(OrigIdentifier.NextSameIdentifier.Element)); end; if CompareText(OrigIdentifier.Identifier,OrigIdentifier.NextSameIdentifier.Identifier)<>0 then Fail(Path+'.Local['+OrigIdentifier.Identifier+'] Cur.Identifier<>Next.Identifier '+OrigIdentifier.Identifier+'<>'+OrigIdentifier.NextSameIdentifier.Identifier); OrigIdentifier:=OrigIdentifier.NextSameIdentifier; RestIdentifier:=RestIdentifier.NextSameIdentifier; until false; end; finally OrigList.Free; end; CheckRestoredPasScope(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredSectionScope(const Path: string; Orig, Rest: TPas2JSSectionScope); var i: Integer; OrigUses, RestUses: TPas2JSSectionScope; OrigHelperEntry, RestHelperEntry: TPRHelperEntry; begin if Orig.BoolSwitches<>Rest.BoolSwitches then Fail(Path+'.BoolSwitches Orig='+BoolSwitchesToStr(Orig.BoolSwitches)+' Rest='+BoolSwitchesToStr(Rest.BoolSwitches)); if Orig.ModeSwitches<>Rest.ModeSwitches then Fail(Path+'.ModeSwitches'); AssertEquals(Path+' UsesScopes.Count',Orig.UsesScopes.Count,Rest.UsesScopes.Count); for i:=0 to Orig.UsesScopes.Count-1 do begin OrigUses:=TPas2JSSectionScope(Orig.UsesScopes[i]); if not (TObject(Rest.UsesScopes[i]) is TPas2JSSectionScope) then Fail(Path+'.UsesScopes['+IntToStr(i)+'] Rest='+GetObjName(TObject(Rest.UsesScopes[i]))); RestUses:=TPas2JSSectionScope(Rest.UsesScopes[i]); if OrigUses.ClassType<>RestUses.ClassType then Fail(Path+'.UsesScopes['+IntToStr(i)+'] Orig='+GetObjName(OrigUses)+' Rest='+GetObjName(RestUses)); CheckRestoredReference(Path+'.UsesScopes['+IntToStr(i)+']',OrigUses.Element,RestUses.Element); end; AssertEquals(Path+' length(Helpers)',length(Orig.Helpers),length(Rest.Helpers)); for i:=0 to length(Orig.Helpers)-1 do begin OrigHelperEntry:=TPRHelperEntry(Orig.Helpers[i]); RestHelperEntry:=TPRHelperEntry(Rest.Helpers[i]); if OrigHelperEntry.ClassType<>RestHelperEntry.ClassType then Fail(Path+'.Helpers['+IntToStr(i)+'] Orig='+GetObjName(OrigHelperEntry)+' Rest='+GetObjName(RestHelperEntry)); AssertEquals(Path+'.Helpers['+IntToStr(i)+'].Added',OrigHelperEntry.Added,RestHelperEntry.Added); CheckRestoredReference(Path+'.Helpers['+IntToStr(i)+'].Helper',OrigHelperEntry.Helper,RestHelperEntry.Helper); CheckRestoredReference(Path+'.Helpers['+IntToStr(i)+'].HelperForType',OrigHelperEntry.HelperForType,RestHelperEntry.HelperForType); end; AssertEquals(Path+'.Finished',Orig.Finished,Rest.Finished); CheckRestoredIdentifierScope(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredInitialFinalizationScope( const Path: string; Orig, Rest: TPas2JSInitialFinalizationScope); begin CheckRestoredScopeRefs(Path+'.References',Orig.References,Rest.References); if Orig.JS<>Rest.JS then CheckRestoredJS(Path+'.JS',Orig.JS,Rest.JS); end; procedure TCustomTestPrecompile.CheckRestoredEnumTypeScope(const Path: string; Orig, Rest: TPasEnumTypeScope); begin CheckRestoredReference(Path+'.CanonicalSet',Orig.CanonicalSet,Rest.CanonicalSet); CheckRestoredIdentifierScope(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredRecordScope(const Path: string; Orig, Rest: TPasRecordScope); begin CheckRestoredReference(Path+'.DefaultProperty',Orig.DefaultProperty,Rest.DefaultProperty); CheckRestoredIdentifierScope(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredClassScope(const Path: string; Orig, Rest: TPas2JSClassScope); var i, j: Integer; OrigObj, RestObj: TObject; OrigMap, RestMap: TPasClassIntfMap; SubPath: String; begin CheckRestoredScopeReference(Path+'.AncestorScope',Orig.AncestorScope,Rest.AncestorScope); CheckRestoredElement(Path+'.CanonicalClassOf',Orig.CanonicalClassOf,Rest.CanonicalClassOf); CheckRestoredReference(Path+'.DirectAncestor',Orig.DirectAncestor,Rest.DirectAncestor); CheckRestoredReference(Path+'.DefaultProperty',Orig.DefaultProperty,Rest.DefaultProperty); if Orig.Flags<>Rest.Flags then Fail(Path+'.Flags'); AssertEquals(Path+'.AbstractProcs.length',length(Orig.AbstractProcs),length(Rest.AbstractProcs)); for i:=0 to length(Orig.AbstractProcs)-1 do CheckRestoredReference(Path+'.AbstractProcs['+IntToStr(i)+']',Orig.AbstractProcs[i],Rest.AbstractProcs[i]); CheckRestoredReference(Path+'.NewInstanceFunction',Orig.NewInstanceFunction,Rest.NewInstanceFunction); AssertEquals(Path+'.GUID',Orig.GUID,Rest.GUID); AssertEquals(Path+'.DispatchField',Orig.DispatchField,Rest.DispatchField); AssertEquals(Path+'.DispatchStrField',Orig.DispatchStrField,Rest.DispatchStrField); CheckRestoredObject('.Interfaces',Orig.Interfaces,Rest.Interfaces); if Orig.Interfaces<>nil then begin AssertEquals(Path+'.Interfaces.Count',Orig.Interfaces.Count,Rest.Interfaces.Count); for i:=0 to Orig.Interfaces.Count-1 do begin SubPath:=Path+'.Interfaces['+IntToStr(i)+']'; OrigObj:=TObject(Orig.Interfaces[i]); RestObj:=TObject(Rest.Interfaces[i]); CheckRestoredObject(SubPath,OrigObj,RestObj); if OrigObj is TPasProperty then CheckRestoredReference(SubPath+'(TPasProperty)', TPasProperty(OrigObj),TPasProperty(RestObj)) else if OrigObj is TPasClassIntfMap then begin OrigMap:=TPasClassIntfMap(OrigObj); RestMap:=TPasClassIntfMap(RestObj); repeat AssertNotNull(SubPath+'.Intf Orig',OrigMap.Intf); CheckRestoredObject(SubPath+'.Intf',OrigMap.Intf,RestMap.Intf); SubPath:=SubPath+'.Map('+OrigMap.Intf.Name+')'; CheckRestoredObject(SubPath+'.Element',OrigMap.Element,RestMap.Element); CheckRestoredObject(SubPath+'.Procs',OrigMap.Procs,RestMap.Procs); if OrigMap.Procs=nil then begin if OrigMap.Intf.Members.Count>0 then Fail(SubPath+' expected '+IntToStr(OrigMap.Intf.Members.Count)+' procs, but Procs=nil'); end else for j:=0 to OrigMap.Procs.Count-1 do begin OrigObj:=TObject(OrigMap.Procs[j]); RestObj:=TObject(RestMap.Procs[j]); CheckRestoredReference(SubPath+'.Procs['+IntToStr(j)+']',TPasElement(OrigObj),TPasElement(RestObj)); end; AssertEquals(Path+'.Procs.Count',OrigMap.Procs.Count,RestMap.Procs.Count); CheckRestoredObject(SubPath+'.AncestorMap',OrigMap.AncestorMap,RestMap.AncestorMap); OrigMap:=OrigMap.AncestorMap; RestMap:=RestMap.AncestorMap; until OrigMap=nil; end else Fail(SubPath+' unknown class '+GetObjName(OrigObj)); end; end; CheckRestoredIdentifierScope(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredProcScope(const Path: string; Orig, Rest: TPas2JSProcedureScope); var i: Integer; begin CheckRestoredReference(Path+'.DeclarationProc',Orig.DeclarationProc,Rest.DeclarationProc); CheckRestoredReference(Path+'.ImplProc',Orig.ImplProc,Rest.ImplProc); CheckRestoredScopeRefs(Path+'.References',Orig.References,Rest.References); if Orig.BodyJS<>Rest.BodyJS then CheckRestoredJS(Path+'.BodyJS',Orig.BodyJS,Rest.BodyJS); CheckRestoredObject(Path+'.GlobalJS',Orig.GlobalJS,Rest.GlobalJS); if Orig.GlobalJS<>nil then begin for i:=0 to Orig.GlobalJS.Count-1 do begin if i>=Rest.GlobalJS.Count then Fail(Path+'.GlobalJS['+IntToStr(i)+'] missing: '+Orig.GlobalJS[i]); CheckRestoredJS(Path+'.GlobalJS['+IntToStr(i)+']',Orig.GlobalJS[i],Rest.GlobalJS[i]); end; if Orig.GlobalJS.Count<Rest.GlobalJS.Count then Fail(Path+'.GlobalJS['+IntToStr(i)+'] too much: '+Rest.GlobalJS[Orig.GlobalJS.Count]); end; if Rest.DeclarationProc=nil then begin AssertEquals(Path+'.ResultVarName',Orig.ResultVarName,Rest.ResultVarName); CheckRestoredReference(Path+'.OverriddenProc',Orig.OverriddenProc,Rest.OverriddenProc); CheckRestoredScopeReference(Path+'.ClassScope',Orig.ClassRecScope,Rest.ClassRecScope); CheckRestoredElement(Path+'.SelfArg',Orig.SelfArg,Rest.SelfArg); if Orig.Flags<>Rest.Flags then Fail(Path+'.Flags'); if Orig.BoolSwitches<>Rest.BoolSwitches then Fail(Path+'.BoolSwitches'); if Orig.ModeSwitches<>Rest.ModeSwitches then Fail(Path+'.ModeSwitches'); //CheckRestoredIdentifierScope(Path,Orig,Rest); end else begin // ImplProc end; end; procedure TCustomTestPrecompile.CheckRestoredScopeRefs(const Path: string; Orig, Rest: TPasScopeReferences); var OrigList, RestList: TFPList; i: Integer; OrigRef, RestRef: TPasScopeReference; begin CheckRestoredObject(Path,Orig,Rest); if Orig=nil then exit; OrigList:=nil; RestList:=nil; try OrigList:=Orig.GetList; RestList:=Rest.GetList; OrigList.Sort(@CompareListOfProcScopeRef); RestList.Sort(@CompareListOfProcScopeRef); for i:=0 to OrigList.Count-1 do begin OrigRef:=TPasScopeReference(OrigList[i]); if i>=RestList.Count then Fail(Path+'['+IntToStr(i)+'] Missing in Rest: "'+OrigRef.Element.Name+'"'); RestRef:=TPasScopeReference(RestList[i]); CheckRestoredReference(Path+'['+IntToStr(i)+'].Name="'+OrigRef.Element.Name+'"',OrigRef.Element,RestRef.Element); if OrigRef.Access<>RestRef.Access then AssertEquals(Path+'['+IntToStr(i)+']"'+OrigRef.Element.Name+'".Access', PCUPSRefAccessNames[OrigRef.Access],PCUPSRefAccessNames[RestRef.Access]); end; if RestList.Count>OrigList.Count then begin i:=OrigList.Count; RestRef:=TPasScopeReference(RestList[i]); Fail(Path+'['+IntToStr(i)+'] Too many in Rest: "'+RestRef.Element.Name+'"'); end; finally OrigList.Free; RestList.Free; end; end; procedure TCustomTestPrecompile.CheckRestoredPropertyScope(const Path: string; Orig, Rest: TPasPropertyScope); begin CheckRestoredReference(Path+'.AncestorProp',Orig.AncestorProp,Rest.AncestorProp); CheckRestoredIdentifierScope(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredResolvedReference( const Path: string; Orig, Rest: TResolvedReference); var C: TClass; begin if Orig.Flags<>Rest.Flags then Fail(Path+'.Flags'); if Orig.Access<>Rest.Access then AssertEquals(Path+'.Access',PCUResolvedRefAccessNames[Orig.Access],PCUResolvedRefAccessNames[Rest.Access]); if not CheckRestoredObject(Path+'.Context',Orig.Context,Rest.Context) then exit; if Orig.Context<>nil then begin C:=Orig.Context.ClassType; if C=TResolvedRefCtxConstructor then CheckRestoredReference(Path+'.Context[TResolvedRefCtxConstructor].Typ', TResolvedRefCtxConstructor(Orig.Context).Typ, TResolvedRefCtxConstructor(Rest.Context).Typ); end; CheckRestoredScopeReference(Path+'.WithExprScope',Orig.WithExprScope,Rest.WithExprScope); CheckRestoredReference(Path+'.Declaration',Orig.Declaration,Rest.Declaration); CheckRestoredResolveData(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredEvalValue(const Path: string; Orig, Rest: TResEvalValue); var i: Integer; begin if not CheckRestoredObject(Path,Orig,Rest) then exit; if Orig.Kind<>Rest.Kind then Fail(Path+'.Kind'); if not CheckRestoredObject(Path+'.Element',Orig.Element,Rest.Element) then exit; CheckRestoredReference(Path+'.IdentEl',Orig.IdentEl,Rest.IdentEl); case Orig.Kind of revkNone: Fail(Path+'.Kind=revkNone'); revkCustom: Fail(Path+'.Kind=revkNone'); revkNil: ; revkBool: AssertEquals(Path+'.B',TResEvalBool(Orig).B,TResEvalBool(Rest).B); revkInt: AssertEquals(Path+'.Int',TResEvalInt(Orig).Int,TResEvalInt(Rest).Int); revkUInt: if TResEvalUInt(Orig).UInt<>TResEvalUInt(Rest).UInt then Fail(Path+'.UInt'); revkFloat: AssertEquals(Path+'.FloatValue',TResEvalFloat(Orig).FloatValue,TResEvalFloat(Rest).FloatValue); revkString: AssertEquals(Path+'.S,Raw',TResEvalString(Orig).S,TResEvalString(Rest).S); revkUnicodeString: AssertEquals(Path+'.S,UTF16',String(TResEvalUTF16(Orig).S),String(TResEvalUTF16(Rest).S)); revkEnum: begin AssertEquals(Path+'.Index',TResEvalEnum(Orig).Index,TResEvalEnum(Rest).Index); CheckRestoredReference(Path+'.ElType',TResEvalEnum(Orig).ElType,TResEvalEnum(Rest).ElType); end; revkRangeInt: begin if TResEvalRangeInt(Orig).ElKind<>TResEvalRangeInt(Rest).ElKind then Fail(Path+'.Int/ElKind'); CheckRestoredReference(Path+'.Int/ElType',TResEvalRangeInt(Orig).ElType,TResEvalRangeInt(Rest).ElType); AssertEquals(Path+'.Int/RangeStart',TResEvalRangeInt(Orig).RangeStart,TResEvalRangeInt(Rest).RangeStart); AssertEquals(Path+'.Int/RangeEnd',TResEvalRangeInt(Orig).RangeEnd,TResEvalRangeInt(Rest).RangeEnd); end; revkRangeUInt: begin if TResEvalRangeUInt(Orig).RangeStart<>TResEvalRangeUInt(Rest).RangeStart then Fail(Path+'.UInt/RangeStart'); if TResEvalRangeUInt(Orig).RangeEnd<>TResEvalRangeUInt(Rest).RangeEnd then Fail(Path+'.UInt/RangeEnd'); end; revkSetOfInt: begin if TResEvalSet(Orig).ElKind<>TResEvalSet(Rest).ElKind then Fail(Path+'.SetInt/ElKind'); CheckRestoredReference(Path+'.SetInt/ElType',TResEvalSet(Orig).ElType,TResEvalSet(Rest).ElType); AssertEquals(Path+'.SetInt/RangeStart',TResEvalSet(Orig).RangeStart,TResEvalSet(Rest).RangeStart); AssertEquals(Path+'.SetInt/RangeEnd',TResEvalSet(Orig).RangeEnd,TResEvalSet(Rest).RangeEnd); AssertEquals(Path+'.SetInt/length(Items)',length(TResEvalSet(Orig).Ranges),length(TResEvalSet(Rest).Ranges)); for i:=0 to length(TResEvalSet(Orig).Ranges)-1 do begin AssertEquals(Path+'.SetInt/Items['+IntToStr(i)+'].RangeStart', TResEvalSet(Orig).Ranges[i].RangeStart,TResEvalSet(Rest).Ranges[i].RangeStart); AssertEquals(Path+'.SetInt/Items['+IntToStr(i)+'].RangeEnd', TResEvalSet(Orig).Ranges[i].RangeEnd,TResEvalSet(Rest).Ranges[i].RangeEnd); end; end; end; end; procedure TCustomTestPrecompile.CheckRestoredCustomData(const Path: string; RestoredEl: TPasElement; Orig, Rest: TObject); var C: TClass; begin if not CheckRestoredObject(Path,Orig,Rest) then exit; C:=Orig.ClassType; if C=TResolvedReference then CheckRestoredResolvedReference(Path+'[TResolvedReference]',TResolvedReference(Orig),TResolvedReference(Rest)) else if C=TPas2JSModuleScope then CheckRestoredModuleScope(Path+'[TPas2JSModuleScope]',TPas2JSModuleScope(Orig),TPas2JSModuleScope(Rest)) else if C=TPas2JSSectionScope then CheckRestoredSectionScope(Path+'[TPas2JSSectionScope]',TPas2JSSectionScope(Orig),TPas2JSSectionScope(Rest)) else if C=TPas2JSInitialFinalizationScope then CheckRestoredInitialFinalizationScope(Path+'[TPas2JSInitialFinalizationScope]',TPas2JSInitialFinalizationScope(Orig),TPas2JSInitialFinalizationScope(Rest)) else if C=TPasEnumTypeScope then CheckRestoredEnumTypeScope(Path+'[TPasEnumTypeScope]',TPasEnumTypeScope(Orig),TPasEnumTypeScope(Rest)) else if C=TPasRecordScope then CheckRestoredRecordScope(Path+'[TPasRecordScope]',TPasRecordScope(Orig),TPasRecordScope(Rest)) else if C=TPas2JSClassScope then CheckRestoredClassScope(Path+'[TPas2JSClassScope]',TPas2JSClassScope(Orig),TPas2JSClassScope(Rest)) else if C=TPas2JSProcedureScope then CheckRestoredProcScope(Path+'[TPas2JSProcedureScope]',TPas2JSProcedureScope(Orig),TPas2JSProcedureScope(Rest)) else if C=TPasPropertyScope then CheckRestoredPropertyScope(Path+'[TPasPropertyScope]',TPasPropertyScope(Orig),TPasPropertyScope(Rest)) else if C.InheritsFrom(TResEvalValue) then CheckRestoredEvalValue(Path+'['+Orig.ClassName+']',TResEvalValue(Orig),TResEvalValue(Rest)) else Fail(Path+': unknown CustomData "'+GetObjName(Orig)+'" El='+GetObjName(RestoredEl)); end; procedure TCustomTestPrecompile.CheckRestoredReference(const Path: string; Orig, Rest: TPasElement); begin if not CheckRestoredObject(Path,Orig,Rest) then exit; AssertEquals(Path+'.Name',Orig.Name,Rest.Name); if Orig is TPasUnresolvedSymbolRef then exit; // compiler types and procs are the same in every unit -> skip checking unit CheckRestoredReference(Path+'.Parent',Orig.Parent,Rest.Parent); end; procedure TCustomTestPrecompile.CheckRestoredElOrRef(const Path: string; Orig, OrigProp, Rest, RestProp: TPasElement); begin if not CheckRestoredObject(Path,OrigProp,RestProp) then exit; if Orig<>OrigProp.Parent then begin if Rest=RestProp.Parent then Fail(Path+' Orig "'+GetObjName(OrigProp)+'" is reference Orig.Parent='+GetObjName(Orig)+', Rest "'+GetObjName(RestProp)+'" is insitu'); CheckRestoredReference(Path,OrigProp,RestProp); end else CheckRestoredElement(Path,OrigProp,RestProp); end; procedure TCustomTestPrecompile.CheckRestoredAnalyzerElement( const Path: string; Orig, Rest: TPasElement); var OrigUsed, RestUsed: TPAElement; begin //writeln('TCustomTestPrecompile.CheckRestoredAnalyzerElement ',GetObjName(RestAnalyzer)); if RestAnalyzer=nil then exit; if Orig.ClassType=TPasArgument then exit; OrigUsed:=Analyzer.FindUsedElement(Orig); //writeln('TCustomTestPrecompile.CheckRestoredAnalyzerElement ',GetObjName(Orig),'=',OrigUsed<>nil,' ',GetObjName(Rest),'=',RestAnalyzer.FindUsedElement(Rest)<>nil); if OrigUsed<>nil then begin RestUsed:=RestAnalyzer.FindUsedElement(Rest); if RestUsed=nil then Fail(Path+': used in OrigAnalyzer, but not used in RestAnalyzer'); if OrigUsed.Access<>RestUsed.Access then AssertEquals(Path+'->Analyzer.Access',dbgs(OrigUsed.Access),dbgs(RestUsed.Access)); end else if RestAnalyzer.IsUsed(Rest) then begin Fail(Path+': not used in OrigAnalyzer, but used in RestAnalyzer'); end; end; procedure TCustomTestPrecompile.CheckRestoredElement(const Path: string; Orig, Rest: TPasElement); var C: TClass; AModule: TPasModule; begin //writeln('TCustomTestPrecompile.CheckRestoredElement START Orig=',GetObjName(Orig),' Rest=',GetObjName(Rest)); if not CheckRestoredObject(Path,Orig,Rest) then exit; //writeln('TCustomTestPrecompile.CheckRestoredElement CheckRestoredObject Orig=',GetObjName(Orig),' Rest=',GetObjName(Rest)); AModule:=Orig.GetModule; if AModule<>Module then Fail(Path+' wrong module: Orig='+GetObjName(AModule)+' '+GetObjName(Module)); AssertEquals(Path+'.Name',Orig.Name,Rest.Name); AssertEquals(Path+'.SourceFilename',Orig.SourceFilename,Rest.SourceFilename); AssertEquals(Path+'.SourceLinenumber',Orig.SourceLinenumber,Rest.SourceLinenumber); //AssertEquals(Path+'.SourceEndLinenumber',Orig.SourceEndLinenumber,Rest.SourceEndLinenumber); if Orig.Visibility<>Rest.Visibility then Fail(Path+'.Visibility '+PCUMemberVisibilityNames[Orig.Visibility]+' '+PCUMemberVisibilityNames[Rest.Visibility]); if Orig.Hints<>Rest.Hints then Fail(Path+'.Hints'); AssertEquals(Path+'.HintMessage',Orig.HintMessage,Rest.HintMessage); //writeln('TCustomTestPrecompile.CheckRestoredElement Checking Parent... Orig=',GetObjName(Orig),' Rest=',GetObjName(Rest)); CheckRestoredReference(Path+'.Parent',Orig.Parent,Rest.Parent); //writeln('TCustomTestPrecompile.CheckRestoredElement Checking CustomData... Orig=',GetObjName(Orig),' Rest=',GetObjName(Rest)); CheckRestoredCustomData(Path+'.CustomData',Rest,Orig.CustomData,Rest.CustomData); C:=Orig.ClassType; if C=TUnaryExpr then CheckRestoredUnaryExpr(Path,TUnaryExpr(Orig),TUnaryExpr(Rest)) else if C=TBinaryExpr then CheckRestoredBinaryExpr(Path,TBinaryExpr(Orig),TBinaryExpr(Rest)) else if C=TPrimitiveExpr then CheckRestoredPrimitiveExpr(Path,TPrimitiveExpr(Orig),TPrimitiveExpr(Rest)) else if C=TBoolConstExpr then CheckRestoredBoolConstExpr(Path,TBoolConstExpr(Orig),TBoolConstExpr(Rest)) else if (C=TNilExpr) or (C=TInheritedExpr) or (C=TSelfExpr) then CheckRestoredPasExpr(Path,TPasExpr(Orig),TPasExpr(Rest)) else if C=TParamsExpr then CheckRestoredParamsExpr(Path,TParamsExpr(Orig),TParamsExpr(Rest)) else if C=TProcedureExpr then CheckRestoredProcedureExpr(Path,TProcedureExpr(Orig),TProcedureExpr(Rest)) else if C=TRecordValues then CheckRestoredRecordValues(Path,TRecordValues(Orig),TRecordValues(Rest)) else if C=TArrayValues then CheckRestoredArrayValues(Path,TArrayValues(Orig),TArrayValues(Rest)) // TPasDeclarations is a base class // TPasUsesUnit is checked in usesclause // TPasSection is a base class else if C=TPasResString then CheckRestoredResString(Path,TPasResString(Orig),TPasResString(Rest)) // TPasType is a base clas else if (C=TPasAliasType) or (C=TPasTypeAliasType) or (C=TPasClassOfType) then CheckRestoredAliasType(Path,TPasAliasType(Orig),TPasAliasType(Rest)) else if C=TPasPointerType then CheckRestoredPointerType(Path,TPasPointerType(Orig),TPasPointerType(Rest)) else if C=TPasSpecializeType then CheckRestoredSpecializedType(Path,TPasSpecializeType(Orig),TPasSpecializeType(Rest)) else if C=TInlineSpecializeExpr then CheckRestoredInlineSpecializedExpr(Path,TInlineSpecializeExpr(Orig),TInlineSpecializeExpr(Rest)) else if C=TPasGenericTemplateType then CheckRestoredGenericTemplateType(Path,TPasGenericTemplateType(Orig),TPasGenericTemplateType(Rest)) else if C=TPasRangeType then CheckRestoredRangeType(Path,TPasRangeType(Orig),TPasRangeType(Rest)) else if C=TPasArrayType then CheckRestoredArrayType(Path,TPasArrayType(Orig),TPasArrayType(Rest)) else if C=TPasFileType then CheckRestoredFileType(Path,TPasFileType(Orig),TPasFileType(Rest)) else if C=TPasEnumValue then CheckRestoredEnumValue(Path,TPasEnumValue(Orig),TPasEnumValue(Rest)) else if C=TPasEnumType then CheckRestoredEnumType(Path,TPasEnumType(Orig),TPasEnumType(Rest)) else if C=TPasSetType then CheckRestoredSetType(Path,TPasSetType(Orig),TPasSetType(Rest)) else if C=TPasVariant then CheckRestoredVariant(Path,TPasVariant(Orig),TPasVariant(Rest)) else if C=TPasRecordType then CheckRestoredRecordType(Path,TPasRecordType(Orig),TPasRecordType(Rest)) else if C=TPasClassType then CheckRestoredClassType(Path,TPasClassType(Orig),TPasClassType(Rest)) else if C=TPasArgument then CheckRestoredArgument(Path,TPasArgument(Orig),TPasArgument(Rest)) else if C=TPasProcedureType then CheckRestoredProcedureType(Path,TPasProcedureType(Orig),TPasProcedureType(Rest)) else if C=TPasResultElement then CheckRestoredResultElement(Path,TPasResultElement(Orig),TPasResultElement(Rest)) else if C=TPasFunctionType then CheckRestoredFunctionType(Path,TPasFunctionType(Orig),TPasFunctionType(Rest)) else if C=TPasStringType then CheckRestoredStringType(Path,TPasStringType(Orig),TPasStringType(Rest)) else if C=TPasVariable then CheckRestoredVariable(Path,TPasVariable(Orig),TPasVariable(Rest)) else if C=TPasExportSymbol then CheckRestoredExportSymbol(Path,TPasExportSymbol(Orig),TPasExportSymbol(Rest)) else if C=TPasConst then CheckRestoredConst(Path,TPasConst(Orig),TPasConst(Rest)) else if C=TPasProperty then CheckRestoredProperty(Path,TPasProperty(Orig),TPasProperty(Rest)) else if C=TPasMethodResolution then CheckRestoredMethodResolution(Path,TPasMethodResolution(Orig),TPasMethodResolution(Rest)) else if (C=TPasProcedure) or (C=TPasFunction) or (C=TPasConstructor) or (C=TPasClassConstructor) or (C=TPasDestructor) or (C=TPasClassDestructor) or (C=TPasClassProcedure) or (C=TPasClassFunction) then CheckRestoredProcedure(Path,TPasProcedure(Orig),TPasProcedure(Rest)) else if (C=TPasOperator) or (C=TPasClassOperator) then CheckRestoredOperator(Path,TPasOperator(Orig),TPasOperator(Rest)) else if (C=TPasModule) or (C=TPasProgram) or (C=TPasLibrary) then CheckRestoredModule(Path,TPasModule(Orig),TPasModule(Rest)) else if C.InheritsFrom(TPasSection) then CheckRestoredSection(Path,TPasSection(Orig),TPasSection(Rest)) else if C=TPasAttributes then CheckRestoredAttributes(Path,TPasAttributes(Orig),TPasAttributes(Rest)) else Fail(Path+': unknown class '+C.ClassName); CheckRestoredAnalyzerElement(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredElementList(const Path: string; Orig, Rest: TFPList); var OrigItem, RestItem: TObject; i: Integer; SubPath: String; begin if not CheckRestoredObject(Path,Orig,Rest) then exit; AssertEquals(Path+'.Count',Orig.Count,Rest.Count); for i:=0 to Orig.Count-1 do begin SubPath:=Path+'['+IntToStr(i)+']'; OrigItem:=TObject(Orig[i]); if not (OrigItem is TPasElement) then Fail(SubPath+' Orig='+GetObjName(OrigItem)); RestItem:=TObject(Rest[i]); if not (RestItem is TPasElement) then Fail(SubPath+' Rest='+GetObjName(RestItem)); //writeln('TCustomTestPrecompile.CheckRestoredElementList ',GetObjName(OrigItem),' ',GetObjName(RestItem)); SubPath:=Path+'['+IntToStr(i)+']"'+TPasElement(OrigItem).Name+'"'; CheckRestoredElement(SubPath,TPasElement(OrigItem),TPasElement(RestItem)); end; end; procedure TCustomTestPrecompile.CheckRestoredElementArray(const Path: string; Orig, Rest: TPasElementArray); var OrigItem, RestItem: TPasElement; i: Integer; SubPath: String; begin AssertEquals(Path+'.length',length(Orig),length(Rest)); for i:=0 to length(Orig)-1 do begin SubPath:=Path+'['+IntToStr(i)+']'; OrigItem:=Orig[i]; if not (OrigItem is TPasElement) then Fail(SubPath+' Orig='+GetObjName(OrigItem)); RestItem:=Rest[i]; if not (RestItem is TPasElement) then Fail(SubPath+' Rest='+GetObjName(RestItem)); //writeln('TCustomTestPrecompile.CheckRestoredElementList ',GetObjName(OrigItem),' ',GetObjName(RestItem)); SubPath:=Path+'['+IntToStr(i)+']"'+TPasElement(OrigItem).Name+'"'; CheckRestoredElement(SubPath,TPasElement(OrigItem),TPasElement(RestItem)); end; end; procedure TCustomTestPrecompile.CheckRestoredElRefList(const Path: string; OrigParent: TPasElement; Orig: TFPList; RestParent: TPasElement; Rest: TFPList; AllowInSitu: boolean); var OrigItem, RestItem: TObject; i: Integer; SubPath: String; begin if not CheckRestoredObject(Path,Orig,Rest) then exit; AssertEquals(Path+'.Count',Orig.Count,Rest.Count); for i:=0 to Orig.Count-1 do begin SubPath:=Path+'['+IntToStr(i)+']'; OrigItem:=TObject(Orig[i]); if not (OrigItem is TPasElement) then Fail(SubPath+' Orig='+GetObjName(OrigItem)); RestItem:=TObject(Rest[i]); if not (RestItem is TPasElement) then Fail(SubPath+' Rest='+GetObjName(RestItem)); if AllowInSitu then CheckRestoredElOrRef(SubPath,OrigParent,TPasElement(OrigItem),RestParent,TPasElement(RestItem)) else CheckRestoredReference(SubPath,TPasElement(OrigItem),TPasElement(RestItem)); end; end; procedure TCustomTestPrecompile.CheckRestoredPasExpr(const Path: string; Orig, Rest: TPasExpr); begin if Orig.Kind<>Rest.Kind then Fail(Path+'.Kind'); if Orig.OpCode<>Rest.OpCode then Fail(Path+'.OpCode'); CheckRestoredElement(Path+'.Format1',Orig.format1,Rest.format1); CheckRestoredElement(Path+'.Format2',Orig.format2,Rest.format2); end; procedure TCustomTestPrecompile.CheckRestoredUnaryExpr(const Path: string; Orig, Rest: TUnaryExpr); begin CheckRestoredElement(Path+'.Operand',Orig.Operand,Rest.Operand); CheckRestoredPasExpr(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredBinaryExpr(const Path: string; Orig, Rest: TBinaryExpr); begin CheckRestoredElement(Path+'.left',Orig.left,Rest.left); CheckRestoredElement(Path+'.right',Orig.right,Rest.right); CheckRestoredPasExpr(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredPrimitiveExpr(const Path: string; Orig, Rest: TPrimitiveExpr); begin AssertEquals(Path+'.Value',Orig.Value,Rest.Value); CheckRestoredPasExpr(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredBoolConstExpr(const Path: string; Orig, Rest: TBoolConstExpr); begin AssertEquals(Path+'.Value',Orig.Value,Rest.Value); CheckRestoredPasExpr(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredParamsExpr(const Path: string; Orig, Rest: TParamsExpr); begin CheckRestoredElement(Path+'.Value',Orig.Value,Rest.Value); CheckRestoredPasExprArray(Path+'.Params',Orig.Params,Rest.Params); CheckRestoredPasExpr(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredProcedureExpr(const Path: string; Orig, Rest: TProcedureExpr); begin CheckRestoredProcedure(Path+'$Ano',Orig.Proc,Rest.Proc); CheckRestoredPasExpr(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredRecordValues(const Path: string; Orig, Rest: TRecordValues); var i: Integer; begin AssertEquals(Path+'.Fields.length',length(Orig.Fields),length(Rest.Fields)); for i:=0 to length(Orig.Fields)-1 do begin AssertEquals(Path+'.Field['+IntToStr(i)+'].Name',Orig.Fields[i].Name,Rest.Fields[i].Name); CheckRestoredElement(Path+'.Field['+IntToStr(i)+'].ValueExp',Orig.Fields[i].ValueExp,Rest.Fields[i].ValueExp); end; CheckRestoredPasExpr(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredPasExprArray(const Path: string; Orig, Rest: TPasExprArray); var i: Integer; begin AssertEquals(Path+'.length',length(Orig),length(Rest)); for i:=0 to length(Orig)-1 do CheckRestoredElement(Path+'['+IntToStr(i)+']',Orig[i],Rest[i]); end; procedure TCustomTestPrecompile.CheckRestoredArrayValues(const Path: string; Orig, Rest: TArrayValues); begin CheckRestoredPasExprArray(Path+'.Values',Orig.Values,Rest.Values); CheckRestoredPasExpr(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredResString(const Path: string; Orig, Rest: TPasResString); begin CheckRestoredElement(Path+'.Expr',Orig.Expr,Rest.Expr); end; procedure TCustomTestPrecompile.CheckRestoredAliasType(const Path: string; Orig, Rest: TPasAliasType); begin CheckRestoredElOrRef(Path+'.DestType',Orig,Orig.DestType,Rest,Rest.DestType); CheckRestoredElement(Path+'.Expr',Orig.Expr,Rest.Expr); end; procedure TCustomTestPrecompile.CheckRestoredPointerType(const Path: string; Orig, Rest: TPasPointerType); begin CheckRestoredElOrRef(Path+'.DestType',Orig,Orig.DestType,Rest,Rest.DestType); end; procedure TCustomTestPrecompile.CheckRestoredSpecializedType( const Path: string; Orig, Rest: TPasSpecializeType); begin CheckRestoredElementList(Path+'.Params',Orig.Params,Rest.Params); CheckRestoredElOrRef(Path+'.DestType',Orig,Orig.DestType,Rest,Rest.DestType); end; procedure TCustomTestPrecompile.CheckRestoredInlineSpecializedExpr( const Path: string; Orig, Rest: TInlineSpecializeExpr); begin CheckRestoredElement(Path+'.Name',Orig.NameExpr,Rest.NameExpr); CheckRestoredElementList(Path+'.Params',Orig.Params,Rest.Params); end; procedure TCustomTestPrecompile.CheckRestoredGenericTemplateType( const Path: string; Orig, Rest: TPasGenericTemplateType); begin CheckRestoredElementArray(Path+'.Constraints',Orig.Constraints,Rest.Constraints); end; procedure TCustomTestPrecompile.CheckRestoredRangeType(const Path: string; Orig, Rest: TPasRangeType); begin CheckRestoredElement(Path+'.RangeExpr',Orig.RangeExpr,Rest.RangeExpr); end; procedure TCustomTestPrecompile.CheckRestoredArrayType(const Path: string; Orig, Rest: TPasArrayType); begin CheckRestoredPasExprArray(Path+'.Ranges',Orig.Ranges,Rest.Ranges); CheckRestoredElementList(Path+'.GenericTemplateTypes',Orig.GenericTemplateTypes,Rest.GenericTemplateTypes); if Orig.PackMode<>Rest.PackMode then Fail(Path+'.PackMode Orig='+PCUPackModeNames[Orig.PackMode]+' Rest='+PCUPackModeNames[Rest.PackMode]); CheckRestoredElOrRef(Path+'.ElType',Orig,Orig.ElType,Rest,Rest.ElType); end; procedure TCustomTestPrecompile.CheckRestoredFileType(const Path: string; Orig, Rest: TPasFileType); begin CheckRestoredElOrRef(Path+'.ElType',Orig,Orig.ElType,Rest,Rest.ElType); end; procedure TCustomTestPrecompile.CheckRestoredEnumValue(const Path: string; Orig, Rest: TPasEnumValue); begin CheckRestoredElement(Path+'.Value',Orig.Value,Rest.Value); end; procedure TCustomTestPrecompile.CheckRestoredEnumType(const Path: string; Orig, Rest: TPasEnumType); begin CheckRestoredElementList(Path+'.Values',Orig.Values,Rest.Values); end; procedure TCustomTestPrecompile.CheckRestoredSetType(const Path: string; Orig, Rest: TPasSetType); begin CheckRestoredElOrRef(Path+'.EnumType',Orig,Orig.EnumType,Rest,Rest.EnumType); AssertEquals(Path+'.IsPacked',Orig.IsPacked,Rest.IsPacked); end; procedure TCustomTestPrecompile.CheckRestoredVariant(const Path: string; Orig, Rest: TPasVariant); begin CheckRestoredElementList(Path+'.Values',Orig.Values,Rest.Values); CheckRestoredElement(Path+'.Members',Orig.Members,Rest.Members); end; procedure TCustomTestPrecompile.CheckRestoredRecordType(const Path: string; Orig, Rest: TPasRecordType); begin CheckRestoredElementList(Path+'.GenericTemplateTypes',Orig.GenericTemplateTypes,Rest.GenericTemplateTypes); if Orig.PackMode<>Rest.PackMode then Fail(Path+'.PackMode Orig='+PCUPackModeNames[Orig.PackMode]+' Rest='+PCUPackModeNames[Rest.PackMode]); CheckRestoredElementList(Path+'.Members',Orig.Members,Rest.Members); CheckRestoredElOrRef(Path+'.VariantEl',Orig,Orig.VariantEl,Rest,Rest.VariantEl); CheckRestoredElementList(Path+'.Variants',Orig.Variants,Rest.Variants); CheckRestoredElementList(Path+'.GenericTemplateTypes',Orig.GenericTemplateTypes,Rest.GenericTemplateTypes); end; procedure TCustomTestPrecompile.CheckRestoredClassType(const Path: string; Orig, Rest: TPasClassType); begin CheckRestoredElementList(Path+'.GenericTemplateTypes',Orig.GenericTemplateTypes,Rest.GenericTemplateTypes); if Orig.PackMode<>Rest.PackMode then Fail(Path+'.PackMode Orig='+PCUPackModeNames[Orig.PackMode]+' Rest='+PCUPackModeNames[Rest.PackMode]); if Orig.ObjKind<>Rest.ObjKind then Fail(Path+'.ObjKind Orig='+PCUObjKindNames[Orig.ObjKind]+' Rest='+PCUObjKindNames[Rest.ObjKind]); if Orig.InterfaceType<>Rest.InterfaceType then Fail(Path+'.ObjKind Orig='+PCUClassInterfaceTypeNames[Orig.InterfaceType]+' Rest='+PCUClassInterfaceTypeNames[Rest.InterfaceType]); CheckRestoredReference(Path+'.AncestorType',Orig.AncestorType,Rest.AncestorType); CheckRestoredReference(Path+'.HelperForType',Orig.HelperForType,Rest.HelperForType); AssertEquals(Path+'.IsForward',Orig.IsForward,Rest.IsForward); AssertEquals(Path+'.IsExternal',Orig.IsExternal,Rest.IsExternal); // irrelevant: IsShortDefinition CheckRestoredElement(Path+'.GUIDExpr',Orig.GUIDExpr,Rest.GUIDExpr); CheckRestoredElementList(Path+'.Members',Orig.Members,Rest.Members); AssertEquals(Path+'.Modifiers',Orig.Modifiers.Text,Rest.Modifiers.Text); CheckRestoredElRefList(Path+'.Interfaces',Orig,Orig.Interfaces,Rest,Rest.Interfaces,false); CheckRestoredElementList(Path+'.GenericTemplateTypes',Orig.GenericTemplateTypes,Rest.GenericTemplateTypes); AssertEquals(Path+'.ExternalNameSpace',Orig.ExternalNameSpace,Rest.ExternalNameSpace); AssertEquals(Path+'.ExternalName',Orig.ExternalName,Rest.ExternalName); end; procedure TCustomTestPrecompile.CheckRestoredArgument(const Path: string; Orig, Rest: TPasArgument); begin if Orig.Access<>Rest.Access then Fail(Path+'.Access Orig='+PCUArgumentAccessNames[Orig.Access]+' Rest='+PCUArgumentAccessNames[Rest.Access]); CheckRestoredElOrRef(Path+'.ArgType',Orig,Orig.ArgType,Rest,Rest.ArgType); CheckRestoredElement(Path+'.ValueExpr',Orig.ValueExpr,Rest.ValueExpr); end; procedure TCustomTestPrecompile.CheckRestoredProcedureType(const Path: string; Orig, Rest: TPasProcedureType); begin CheckRestoredElementList(Path+'.GenericTemplateTypes',Orig.GenericTemplateTypes,Rest.GenericTemplateTypes); CheckRestoredElementList(Path+'.Args',Orig.Args,Rest.Args); if Orig.CallingConvention<>Rest.CallingConvention then Fail(Path+'.CallingConvention Orig='+PCUCallingConventionNames[Orig.CallingConvention]+' Rest='+PCUCallingConventionNames[Rest.CallingConvention]); if Orig.Modifiers<>Rest.Modifiers then Fail(Path+'.Modifiers'); end; procedure TCustomTestPrecompile.CheckRestoredResultElement(const Path: string; Orig, Rest: TPasResultElement); begin CheckRestoredElOrRef(Path+'.ResultType',Orig,Orig.ResultType,Rest,Rest.ResultType); end; procedure TCustomTestPrecompile.CheckRestoredFunctionType(const Path: string; Orig, Rest: TPasFunctionType); begin CheckRestoredElement(Path+'.ResultEl',Orig.ResultEl,Rest.ResultEl); CheckRestoredProcedureType(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredStringType(const Path: string; Orig, Rest: TPasStringType); begin AssertEquals(Path+'.LengthExpr',Orig.LengthExpr,Rest.LengthExpr); end; procedure TCustomTestPrecompile.CheckRestoredVariable(const Path: string; Orig, Rest: TPasVariable); begin CheckRestoredElOrRef(Path+'.VarType',Orig,Orig.VarType,Rest,Rest.VarType); if Orig.VarModifiers<>Rest.VarModifiers then Fail(Path+'.VarModifiers'); CheckRestoredElement(Path+'.LibraryName',Orig.LibraryName,Rest.LibraryName); CheckRestoredElement(Path+'.ExportName',Orig.ExportName,Rest.ExportName); CheckRestoredElement(Path+'.AbsoluteExpr',Orig.AbsoluteExpr,Rest.AbsoluteExpr); CheckRestoredElement(Path+'.Expr',Orig.Expr,Rest.Expr); end; procedure TCustomTestPrecompile.CheckRestoredExportSymbol(const Path: string; Orig, Rest: TPasExportSymbol); begin CheckRestoredElement(Path+'.ExportName',Orig.ExportName,Rest.ExportName); CheckRestoredElement(Path+'.ExportIndex',Orig.ExportIndex,Rest.ExportIndex); end; procedure TCustomTestPrecompile.CheckRestoredConst(const Path: string; Orig, Rest: TPasConst); begin AssertEquals(Path+'.IsConst',Orig.IsConst,Rest.IsConst); CheckRestoredVariable(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredProperty(const Path: string; Orig, Rest: TPasProperty); begin CheckRestoredElement(Path+'.IndexExpr',Orig.IndexExpr,Rest.IndexExpr); CheckRestoredElement(Path+'.ReadAccessor',Orig.ReadAccessor,Rest.ReadAccessor); CheckRestoredElement(Path+'.WriteAccessor',Orig.WriteAccessor,Rest.WriteAccessor); CheckRestoredElement(Path+'.DispIDExpr',Orig.DispIDExpr,Rest.DispIDExpr); CheckRestoredPasExprArray(Path+'.Implements',Orig.Implements,Rest.Implements); CheckRestoredElement(Path+'.StoredAccessor',Orig.StoredAccessor,Rest.StoredAccessor); CheckRestoredElement(Path+'.DefaultExpr',Orig.DefaultExpr,Rest.DefaultExpr); CheckRestoredElementList(Path+'.Args',Orig.Args,Rest.Args); // not needed: ReadAccessorName, WriteAccessorName, ImplementsName, StoredAccessorName AssertEquals(Path+'.DispIDReadOnly',Orig.DispIDReadOnly,Rest.DispIDReadOnly); AssertEquals(Path+'.IsDefault',Orig.IsDefault,Rest.IsDefault); AssertEquals(Path+'.IsNodefault',Orig.IsNodefault,Rest.IsNodefault); CheckRestoredVariable(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredMethodResolution( const Path: string; Orig, Rest: TPasMethodResolution); begin AssertEquals(Path+'.ProcClass',Orig.ProcClass,Rest.ProcClass); CheckRestoredElement(Path+'.InterfaceName',Orig.InterfaceName,Rest.InterfaceName); CheckRestoredElement(Path+'.InterfaceProc',Orig.InterfaceProc,Rest.InterfaceProc); CheckRestoredElement(Path+'.ImplementationProc',Orig.ImplementationProc,Rest.ImplementationProc); end; procedure TCustomTestPrecompile.CheckRestoredProcNameParts(const Path: string; Orig, Rest: TPasProcedure); var OrigNameParts, RestNameParts: TProcedureNameParts; i: Integer; SubPath: String; OrigTemplates, RestTemplates: TFPList; begin OrigNameParts:=Orig.NameParts; RestNameParts:=Rest.NameParts; AssertEquals(Path+'.NameParts<>nil',OrigNameParts<>nil,RestNameParts<>nil); if OrigNameParts<>nil then begin AssertEquals(Path+'.NameParts.Count',OrigNameParts.Count,RestNameParts.Count); for i:=0 to OrigNameParts.Count-1 do begin SubPath:=Path+'.NameParts['+IntToStr(i)+']'; AssertEquals(SubPath+'.Name',TProcedureNamePart(OrigNameParts[i]).Name,TProcedureNamePart(RestNameParts[i]).Name); OrigTemplates:=TProcedureNamePart(OrigNameParts[i]).Templates; RestTemplates:=TProcedureNamePart(RestNameParts[i]).Templates; CheckRestoredObject(SubPath+'.Templates',OrigTemplates,RestTemplates); if OrigTemplates=nil then continue; CheckRestoredElementList(SubPath+'.Templates',OrigTemplates,RestTemplates); end; end; end; procedure TCustomTestPrecompile.CheckRestoredProcedure(const Path: string; Orig, Rest: TPasProcedure); var RestScope, OrigScope: TPas2JSProcedureScope; begin CheckRestoredObject(Path+'.CustomData',Orig.CustomData,Rest.CustomData); OrigScope:=Orig.CustomData as TPas2JSProcedureScope; RestScope:=Rest.CustomData as TPas2JSProcedureScope; if OrigScope=nil then exit; // msIgnoreInterfaces CheckRestoredReference(Path+'.CustomData[TPas2JSProcedureScope].DeclarationProc', OrigScope.DeclarationProc,RestScope.DeclarationProc); AssertEquals(Path+'.CustomData[TPas2JSProcedureScope].ResultVarName',OrigScope.ResultVarName,RestScope.ResultVarName); if RestScope.DeclarationProc=nil then begin CheckRestoredProcNameParts(Path,Orig,Rest); CheckRestoredElement(Path+'.ProcType',Orig.ProcType,Rest.ProcType); CheckRestoredElement(Path+'.PublicName',Orig.PublicName,Rest.PublicName); CheckRestoredElement(Path+'.LibrarySymbolName',Orig.LibrarySymbolName,Rest.LibrarySymbolName); CheckRestoredElement(Path+'.LibraryExpr',Orig.LibraryExpr,Rest.LibraryExpr); CheckRestoredElement(Path+'.DispIDExpr',Orig.DispIDExpr,Rest.DispIDExpr); AssertEquals(Path+'.AliasName',Orig.AliasName,Rest.AliasName); if Orig.Modifiers<>Rest.Modifiers then Fail(Path+'.Modifiers'); AssertEquals(Path+'.MessageName',Orig.MessageName,Rest.MessageName); if Orig.MessageType<>Rest.MessageType then Fail(Path+'.MessageType Orig='+PCUProcedureMessageTypeNames[Orig.MessageType]+' Rest='+PCUProcedureMessageTypeNames[Rest.MessageType]); end else begin // ImplProc end; // ToDo: Body end; procedure TCustomTestPrecompile.CheckRestoredOperator(const Path: string; Orig, Rest: TPasOperator); begin if Orig.OperatorType<>Rest.OperatorType then Fail(Path+'.OperatorType Orig='+PCUOperatorTypeNames[Orig.OperatorType]+' Rest='+PCUOperatorTypeNames[Rest.OperatorType]); AssertEquals(Path+'.TokenBased',Orig.TokenBased,Rest.TokenBased); CheckRestoredProcedure(Path,Orig,Rest); end; procedure TCustomTestPrecompile.CheckRestoredAttributes(const Path: string; Orig, Rest: TPasAttributes); begin CheckRestoredPasExprArray(Path+'.Calls',Orig.Calls,Rest.Calls); end; { TTestPrecompile } procedure TTestPrecompile.Test_Base256VLQ; procedure Test(i: TMaxPrecInt); var s: String; p: PByte; j: TMaxPrecInt; begin s:=EncodeVLQ(i); p:=PByte(s); j:=DecodeVLQ(p); if i<>j then Fail('Encode/DecodeVLQ OrigIndex='+IntToStr(i)+' Code="'+s+'" NewIndex='+IntToStr(j)); end; procedure TestStr(i: TMaxPrecInt; Expected: string); var Actual: String; begin Actual:=EncodeVLQ(i); AssertEquals('EncodeVLQ('+IntToStr(i)+')',Expected,Actual); end; var i: Integer; begin TestStr(0,#0); TestStr(1,#2); TestStr(-1,#3); for i:=-8200 to 8200 do Test(i); Test(High(TMaxPrecInt)); Test(High(TMaxPrecInt)-1); Test(Low(TMaxPrecInt)+2); Test(Low(TMaxPrecInt)+1); //Test(Low(TMaxPrecInt)); such a high number is not needed by pastojs end; procedure TTestPrecompile.TestPC_EmptyUnit; begin StartUnit(false); Add([ 'interface', 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Const; begin StartUnit(false); Add([ 'interface', 'const', ' Three = 3;', ' FourPlusFive: longint = 4+5 deprecated ''deprtext'';', ' Four: byte = +6-2*2 platform;', ' Affirmative = true;', ' BFalse = false;', // bool lit ' NotBFalse = not BFalse;', // boolconst ' UnaryMinus = -3;', // unary minus ' FloatA = -31.678E-012;', // float lit ' HighInt = High(longint);', // func params, built-in function ' s = ''abc'';', // string lit ' c: char = s[1];', // array params ' a: array[1..2] of longint = (3,4);', // anonymous array, range, array values ' PI: Double; external name ''Math.PI'';', 'resourcestring', ' rs = ''rs'';', 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Var; begin StartUnit(false); Add([ 'interface', 'var', ' FourPlusFive: longint = 4+5 deprecated ''deprtext'';', ' e: double external name ''Math.e'';', ' AnoArr: array of longint = (1,2,3);', ' s: string = ''aaaäö'';', ' s2: string = ''😊'';', // 1F60A ' a,b: array of longint;', 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Enum; begin StartUnit(false); Add([ 'interface', 'type', ' TEnum = (red,green,blue);', ' TEnumRg = green..blue;', ' TArrOfEnum = array of TEnum;', ' TArrOfEnumRg = array of TEnumRg;', ' TArrEnumOfInt = array[TEnum] of longint;', 'var', ' HighEnum: TEnum = high(TEnum);', 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Set; begin StartUnit(false); Add([ 'interface', 'type', ' TEnum = (red,green,blue);', ' TEnumRg = green..blue;', ' TEnumAlias = TEnum;', // alias ' TSetOfEnum = set of TEnum;', ' TSetOfEnumRg = set of TEnumRg;', ' TSetOfDir = set of (west,east);', 'var', ' Empty: TSetOfEnum = [];', // empty set lit ' All: TSetOfEnum = [low(TEnum)..pred(high(TEnum)),high(TEnum)];', // full set lit, range in set 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Set_InFunction; begin StartUnit(false); Add([ 'interface', 'procedure DoIt;', 'implementation', 'procedure DoIt;', 'type', ' TEnum = (red,green,blue);', ' TEnumRg = green..blue;', ' TEnumAlias = TEnum;', // alias ' TSetOfEnum = set of TEnum;', ' TSetOfEnumRg = set of TEnumRg;', ' TSetOfDir = set of (west,east);', 'var', ' Empty: TSetOfEnum = [];', // empty set lit ' All: TSetOfEnum = [low(TEnum)..pred(high(TEnum)),high(TEnum)];', // full set lit, range in set ' Dirs: TSetOfDir;', 'begin', ' Dirs:=[east];', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_SetOfAnonymousEnumType; begin StartUnit(false); Add([ 'interface', 'type', ' TSetOfDir = set of (west,east);', 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Record; begin StartUnit(false); Add([ '{$ModeSwitch externalclass}', 'interface', 'type', ' TRec = record', ' i: longint;', ' s: string;', ' b: boolean external name ''ext'';', ' end;', ' P = pointer;', // alias type to built-in type ' TArrOfRec = array of TRec;', 'var', ' r: TRec;', // full set lit, range in set 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Record_InFunction; begin StartUnit(false); Add([ 'interface', 'procedure DoIt;', 'implementation', 'procedure DoIt;', 'type', ' TRec = record', ' i: longint;', ' s: string;', ' end;', ' P = ^TRec;', ' TArrOfRec = array of TRec;', 'var', ' r: TRec;', 'begin', 'end;']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_RecordAdv; begin StartUnit(false); Add([ '{$ModeSwitch advancedrecords}', 'interface', 'type', ' TRec = record', ' private', ' FInt: longint;', ' procedure SetInt(Value: longint);', ' function GetItems(Value: word): word;', ' procedure SetItems(Index, Value: word);', ' public', ' property Int: longint read FInt write SetInt default 3;', ' property Items[Index: word]: word read GetItems write SetItems; default;', ' end;', 'var', ' r: trec;', 'implementation', 'procedure TRec.SetInt(Value: longint);', 'begin', 'end;', 'function TRec.GetItems(Value: word): word;', 'begin', 'end;', 'procedure TRec.SetItems(Index, Value: word);', 'begin', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_JSValue; begin StartUnit(false); Add([ 'interface', 'var', ' p: pointer = nil;', // pointer, nil lit ' js: jsvalue = 13 div 4;', // jsvalue 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Array; begin StartUnit(false); Add([ 'interface', 'type', ' TEnum = (red,green);', ' TArrInt = array of longint;', ' TArrInt2 = array[1..2] of longint;', ' TArrEnum1 = array[red..green] of longint;', ' TArrEnum2 = array[TEnum] of longint;', 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_ArrayOfAnonymous; begin StartUnit(false); Add([ 'interface', 'var', ' a: array of pointer;', 'implementation']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Array_InFunction; begin StartUnit(false); Add([ 'interface', 'procedure DoIt;', 'implementation', 'procedure DoIt;', 'type', ' TArr = array[1..2] of word;', 'var', ' arr: TArr;', 'begin', ' arr[2]:=arr[1];', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Proc; begin StartUnit(false); Add([ 'interface', ' function Abs(d: double): double; external name ''Math.Abs'';', ' function GetIt(d: double): double;', ' procedure DoArgs(const a; var b: array of char; out c: jsvalue); inline;', ' procedure DoMulti(a,b: byte);', 'implementation', 'var k: double;', 'function GetIt(d: double): double;', 'var j: double;', 'begin', ' j:=Abs(d+k);', ' Result:=j;', 'end;', 'procedure DoArgs(const a; var b: array of char; out c: jsvalue); inline;', 'begin', 'end;', 'procedure DoMulti(a,b: byte);', 'begin', 'end;', 'procedure NotUsed;', 'begin', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Proc_Nested; begin StartUnit(false); Add([ 'interface', ' function GetIt(d: longint): longint;', 'implementation', 'var k: double;', 'function GetIt(d: longint): longint;', 'var j: double;', ' function GetSum(a,b: longint): longint; forward;', ' function GetMul(a,b: longint): longint; ', ' begin', ' Result:=a*b;', ' end;', ' function GetSum(a,b: longint): longint;', ' begin', ' Result:=a+b;', ' end;', ' procedure NotUsed;', ' begin', ' end;', 'begin', ' Result:=GetMul(GetSum(d,2),3);', 'end;', 'procedure NotUsed;', 'begin', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Proc_LocalConst; begin StartUnit(false); Add([ 'interface', 'function GetIt(d: double): double;', 'implementation', 'function GetIt(d: double): double;', 'const', ' c: double = 3.3;', ' e: double = 2.7;', // e is not used 'begin', ' Result:=d+c;', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Proc_UTF8; begin StartUnit(false); Add([ 'interface', 'function DoIt: string;', 'implementation', 'function DoIt: string;', 'const', ' c = ''äöü😊'';', 'begin', ' Result:=''ÄÖÜ😊''+c;', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Proc_Arg; begin StartUnit(false); Add([ 'interface', 'procedure DoIt(var a; out b,c: longint; const e,f: array of byte; g: boolean = true);', 'implementation', 'procedure DoIt(var a; out b,c: longint; const e,f: array of byte; g: boolean = true);', 'begin', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_ProcType; begin StartUnit(false); Add([ '{$modeswitch arrayoperators}', 'interface', 'type', ' TProc = procedure;', ' TArrProc = array of tproc;', 'procedure Mark;', 'procedure DoIt(const a: TArrProc);', 'implementation', 'procedure Mark;', 'var', ' p: TProc;', ' a: TArrProc;', 'begin', ' DoIt([@Mark,p]+a);', 'end;', 'procedure DoIt(const a: TArrProc);', 'begin', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Proc_Anonymous; begin StartUnit(false); Add([ 'interface', 'type', ' TFunc = reference to function(w: word): word;', ' function GetIt(f: TFunc): longint;', 'implementation', 'var k: byte;', 'function GetIt(f: TFunc): longint;', 'begin', ' f:=function(w: word): word', ' var j: byte;', ' function GetMul(a,b: longint): longint; ', ' begin', ' Result:=a*b;', ' end;', ' begin', ' Result:=j*GetMul(1,2)*k;', ' end;', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Proc_ArrayOfConst; begin StartUnit(true,[supTVarRec]); Add([ 'interface', 'procedure Fly(arr: array of const);', 'implementation', 'procedure Fly(arr: array of const);', 'begin', ' if arr[1].VType=1 then ;', ' if arr[2].VInteger=1 then ;', ' Fly([true,0.3]);', 'end;', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Class; begin StartUnit(false); Add([ 'interface', 'type', ' TObject = class', ' protected', ' FInt: longint;', ' procedure SetInt(Value: longint); virtual; abstract;', ' public', ' property Int: longint read FInt write SetInt default 3;', ' end;', ' TBird = class', ' protected', ' procedure SetInt(Value: longint); override;', ' published', ' property Int;', ' end;', 'var', ' o: tobject;', 'implementation', 'procedure TBird.SetInt(Value: longint);', 'begin', 'end;' ]); WriteReadUnit; end; procedure TTestPrecompile.TestPC_ClassForward; begin Converter.Options:=Converter.Options-[coNoTypeInfo]; StartUnit(false); Add([ 'interface', 'type', ' TObject = class end;', ' TFish = class;', ' TBird = class;', ' TBirdClass = class of TBird;', ' TFish = class', ' B: TBird;', ' end;', ' TBird = class', ' F: TFish;', ' end;', ' TFishClass = class of TFish;', 'var', ' b: tbird;', ' f: tfish;', ' bc: TBirdClass;', ' fc: TFishClass;', 'implementation', 'end.' ]); WriteReadUnit; end; procedure TTestPrecompile.TestPC_ClassConstructor; begin StartUnit(false); Add([ 'interface', 'type', ' TObject = class', ' constructor Create; virtual;', ' end;', ' TBird = class', ' constructor Create; override;', ' end;', 'procedure DoIt;', 'implementation', 'constructor TObject.Create;', 'begin', 'end;', 'constructor TBird.Create;', 'begin', ' inherited;', 'end;', 'procedure DoIt;', 'var b: TBird;', 'begin', ' b:=TBird.Create;', 'end;', 'end.' ]); WriteReadUnit; end; procedure TTestPrecompile.TestPC_ClassDestructor; begin StartUnit(false); Add([ 'interface', 'type', ' TObject = class', ' destructor Destroy; virtual;', ' end;', ' TBird = class', ' destructor Destroy; override;', ' end;', 'procedure DoIt;', 'implementation', 'destructor TObject.Destroy;', 'begin', 'end;', 'destructor TBird.Destroy;', 'begin', ' inherited;', 'end;', 'procedure DoIt;', 'var b: TBird;', 'begin', ' b.Destroy;', 'end;', 'end.' ]); WriteReadUnit; end; procedure TTestPrecompile.TestPC_ClassDispatchMessage; begin StartUnit(false); Add([ 'interface', 'type', ' {$DispatchField DispInt}', ' {$DispatchStrField DispStr}', ' TObject = class', ' end;', ' THopMsg = record', ' DispInt: longint;', ' end;', ' TPutMsg = record', ' DispStr: string;', ' end;', ' TBird = class', ' procedure Fly(var Msg); virtual; abstract; message 2;', ' procedure Run; overload; virtual; abstract;', ' procedure Run(var Msg); overload; message ''Fast'';', ' procedure Hop(var Msg: THopMsg); virtual; abstract; message 3;', ' procedure Put(var Msg: TPutMsg); virtual; abstract; message ''foo'';', ' end;', 'implementation', 'procedure TBird.Run(var Msg);', 'begin', 'end;', 'end.', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Initialization; begin StartUnit(false); Add([ 'interface', 'implementation', 'type', ' TCaption = string;', ' TRec = record h: string; end;', 'var', ' s: TCaption;', ' r: TRec;', 'initialization', ' s:=''ö😊'';', ' r.h:=''Ä😊'';', 'end.', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_BoolSwitches; begin StartUnit(false); Add([ 'interface', '{$R+}', '{$C+}', 'type', ' TObject = class', '{$C-}', ' procedure DoIt;', ' end;', '{$C+}', 'implementation', '{$R-}', 'procedure TObject.DoIt;', 'begin', 'end;', '{$C-}', 'initialization', '{$R+}', 'end.', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_ClassInterface; begin StartUnit(false); Add([ 'interface', '{$interfaces corba}', 'type', ' IUnknown = interface', ' end;', ' IFlying = interface', ' procedure SetItems(Index: longint; Value: longint);', ' end;', ' IBird = interface(IFlying)', ' [''{D44C1F80-44F9-4E88-8443-C518CCDC1FE8}'']', ' function GetItems(Index: longint): longint;', ' property Items[Index: longint]: longint read GetItems write SetItems;', ' end;', ' TObject = class', ' end;', ' TBird = class(TObject,IBird)', ' strict private', ' function IBird.GetItems = RetItems;', ' function RetItems(Index: longint): longint; virtual; abstract;', ' procedure SetItems(Index: longint; Value: longint); virtual; abstract;', ' end;', ' TEagle = class(TObject,IBird)', ' strict private', ' FBird: IBird;', ' property Bird: IBird read FBird implements IBird;', ' end;', 'implementation', 'end.', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_Attributes; begin StartUnit(false); Add([ 'interface', '{$modeswitch PrefixedAttributes}', 'type', ' TObject = class', ' constructor Create;', ' end;', ' TCustomAttribute = class', ' constructor Create(Id: word);', ' end;', ' [Missing]', ' TBird = class', ' [TCustom]', ' FField: word;', ' end;', ' TRec = record', ' [TCustom]', ' Size: word;', ' end;', 'var', ' [TCustom, TCustom(3)]', ' o: TObject;', 'implementation', '[TCustom]', 'constructor TObject.Create; begin end;', 'constructor TCustomAttribute.Create(Id: word); begin end;', 'end.', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_UseUnit; begin AddModuleWithIntfImplSrc('unit2.pp', LinesToStr([ 'type', ' TColor = longint;', ' TRec = record h: TColor; end;', ' TEnum = (red,green);', 'var', ' c: TColor;', ' r: TRec;', ' e: TEnum;']), LinesToStr([ ''])); StartUnit(true); Add([ 'interface', 'uses unit2;', 'var', ' i: system.longint;', ' e2: TEnum;', 'implementation', 'initialization', ' c:=1;', ' r.h:=2;', ' e:=red;', 'end.', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_UseUnit_Class; begin AddModuleWithIntfImplSrc('unit2.pp', LinesToStr([ 'type', ' TObject = class', ' private', ' FA: longint;', ' public', ' type', ' TEnum = (red,green);', ' public', ' i: longint;', ' e: TEnum;', ' procedure DoIt; virtual; abstract;', ' property A: longint read FA write FA;', ' end;', 'var', ' o: TObject;']), LinesToStr([ ''])); StartUnit(true); Add([ 'interface', 'uses unit2;', 'var', ' b: TObject;', 'implementation', 'initialization', ' o.DoIt;', ' o.i:=b.A;', ' o.e:=red;', 'end.', '']); WriteReadUnit; end; procedure TTestPrecompile.TestPC_UseIndirectUnit; begin AddModuleWithIntfImplSrc('unit2.pp', LinesToStr([ 'type', ' TObject = class', ' public', ' i: longint;', ' end;']), LinesToStr([ ''])); AddModuleWithIntfImplSrc('unit1.pp', LinesToStr([ 'uses unit2;', 'var o: TObject;']), LinesToStr([ ''])); StartUnit(true); Add([ 'interface', 'uses unit1;', 'implementation', 'initialization', ' o.i:=3;', 'end.', '']); WriteReadUnit; end; Initialization RegisterTests([TTestPrecompile]); RegisterPCUFormat; end.
unit GX_Zipper; interface {$I GX_CondDefine.inc} {$WARN SYMBOL_PLATFORM OFF} uses Classes, // The Abbrevia units below are in the Comps\Abbrevia directory in the GExperts // source code. See http://sourceforge.net/projects/tpabbrevia/ for more info. AbArcTyp, AbZipTyp; type TGXZipItem = TAbZipItem; TGXZipper = class(TAbZipArchive) private function GetIncludePath: Boolean; procedure SetIncludePath(const Value: Boolean); procedure ZipProc(Sender: TObject; Item: TAbArchiveItem; OutStream: TStream); procedure ZipFromStreamProc(Sender: TObject; Item: TAbArchiveItem; OutStream, InStream: TStream); public function CreateItem(const FileSpec: string): TAbArchiveItem; override; constructor Create(const FileName: string; Mode: Word ); override; procedure AddFiles(Files: TStrings); property IncludePath: Boolean read GetIncludePath write SetIncludePath; end; implementation uses SysUtils, AbZipPrc, GX_GenericUtils; { TGXZipper } procedure TGXZipper.AddFiles(Files: TStrings); var i: Integer; begin for i := 0 to Files.Count - 1 do begin if FileNameHasWildcards(Files[i]) then AddFilesEx(Files[i], '', faHidden) else Add(CreateItem(Files[i])); end; end; constructor TGXZipper.Create(const FileName: string; Mode: Word); begin inherited Create(FileName, Mode); InsertHelper := ZipProc; InsertFromStreamHelper := ZipFromStreamProc; end; function TGXZipper.CreateItem(const FileSpec: string): TAbArchiveItem; begin Result := inherited CreateItem(FileSpec); Result.DiskFileName := FileSpec; end; function TGXZipper.GetIncludePath: Boolean; begin Result := not (soStripPath in StoreOptions); end; procedure TGXZipper.SetIncludePath(const Value: Boolean); begin if Value then Exclude(FStoreOptions, soStripPath) else Include(FStoreOptions, soStripPath); end; procedure TGXZipper.ZipFromStreamProc(Sender: TObject; Item: TAbArchiveItem; OutStream, InStream: TStream); begin AbZipFromStream(TAbZipArchive(Sender), TAbZipItem(Item), OutStream, InStream); end; procedure TGXZipper.ZipProc(Sender: TObject; Item: TAbArchiveItem; OutStream: TStream); begin AbZip(TAbZipArchive(Sender), TAbZipItem(Item), OutStream); end; end.
{*******************************************************************} { CRC32 calculation of file } { for Delphi 3.0,4.0,5.0,6.0 - C++Builder 3,4,5 } { version 1.3 - August 2001 } { } { written by } { TMS Software } { copyright © 2001 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The source } { code remains property of the writer and may not be distributed } { freely as such. } {*******************************************************************} unit wucrc32; interface uses Windows; function CRC32ChecksumOfFile(Filename:string): Integer; implementation const READBUFFERSIZE = 4096; const CRCSeed = $ffffffff; CRC32tab : Array[0..255] of DWord = ( $00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3, $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91, $1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7, $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63, $8d080df5, $3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59, $26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f, $2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d, $76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433, $7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01, $6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457, $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65, $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb, $4369e96a, $346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9, $5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f, $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad, $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683, $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1, $f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7, $fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b, $d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79, $cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f, $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d, $9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785, $05005713, $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777, $88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45, $a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db, $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9, $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf, $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d ); function CRC32(value: Byte; crc: DWord) : DWord; begin Result := CRC32Tab[Byte(crc xor DWord(value))] xor ((crc shr 8) and $00ffffff); end; Function CRCend( crc : DWord ): DWord; begin CRCend := (crc xor CRCSeed); end; {$OVERFLOWCHECKS OFF} function CRC32ChecksumOfFile(Filename:string): Integer; var fh: THandle; buf: array[0..READBUFFERSIZE-1] of Byte; NumRead,i,TmpRes : DWORD; begin TmpRes := CRCSeed; fh := CreateFile(pchar(FileName),GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN,0); if fh > 0 then begin repeat if ReadFile(fh,buf,READBUFFERSIZE,numread, nil) then for i := 1 to numread do begin TmpRes := TmpRes + CRC32(buf[i-1],TmpRes) end else NumRead := 0; until NumRead <> READBUFFERSIZE; CloseHandle(fh); end; TmpRes := CRCEnd(TmpRes); Result := Integer(TmpRes); end; {$OVERFLOWCHECKS ON} end.
unit PercentEdit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, stdctrls; type TPercentEdit = class(TGraphicControl) public constructor Create(AOwner : TComponent); override; destructor Destroy; override; private fTopColor : TColor; fBottomColor : TColor; fOutNibColor : TColor; fInNibColor : TColor; fOutBorderColor : TColor; fInBorderColor : TColor; fMinPerc : integer; fMaxPerc : integer; fValue : integer; fMidValue : integer; fBarHeight : integer; fTopMargin : integer; fOnMoveBar : TNotifyEvent; fOnChange : TNotifyEvent; fLabel : TLabel; fLineColor : TColor; // Range fRanged : boolean; fRangeFromColor : TColor; fRangeToColor : TColor; private fBitmap : TBitmap; fNibOffset : word; fMidOffset : word; fRetValue : boolean; fOldValue : integer; private procedure RenderToBmp; procedure DrawAll; procedure DrawNibble(R : TRect); procedure DrawLines(R : TRect; midLine : boolean); procedure DrawNumber(var R : TRect; number : string; flag : boolean); function DrawNumbers(R : TRect) : boolean; procedure SetNibble(x : integer); protected procedure Paint; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; procedure Loaded; override; protected procedure CMTextChange(var Message: TMessage); message CM_TEXTCHANGED; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; 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; private procedure SetTopColor(aColor : TColor); procedure SetBottomColor(aColor : TColor); procedure SetOutNibColor(aColor : TColor); procedure SetInNibColor(aColor : TColor); procedure SetOutBorderColor(aColor : TColor); procedure SetInBorderColor(aColor : TColor); procedure SetMinPerc(aValue : integer); procedure SetMaxPerc(aValue : integer); procedure SetValue(aValue : integer); procedure SetMidValue(aValue : integer); procedure SetBarHeight(aHeight : integer); procedure SetTopMargin(aMargin : integer); //procedure SetBorderMargin(aMargin : integer); procedure SetLabel(aLabel : TLabel); procedure SetLineColor(aColor : TColor); procedure SetRanged(value : boolean); procedure SetRangeFromColor(aColor : TColor); procedure SetRangeToColor(aColor : TColor); public procedure ReturnValue; published property TopColor : TColor read fTopColor write SetTopColor; property BottomColor : TColor read fBottomColor write SetBottomColor; property OutNibColor : TColor read fOutNibColor write SetOutNibColor; property InNibColor : TColor read fInNibColor write SetInNibColor; property OutBorderColor : TColor read fOutBorderColor write SetOutBorderColor; property InBorderColor : TColor read fInBorderColor write SetInBorderColor; property MinPerc : integer read fMinPerc write SetMinPerc; property MaxPerc : integer read fMaxPerc write SetMaxPerc; property Value : integer read fValue write SetValue; property MidValue : integer read fMidValue write SetMidValue; property BarHeight : integer read fBarHeight write SetBarHeight; property TopMargin : integer read fTopMargin write SetTopMargin; property OnMoveBar : TNotifyEvent read fOnMoveBar write fOnMoveBar; property OnChange : TNotifyEvent read fOnChange write fOnChange; property ValueLabel : TLabel read fLabel write SetLabel; property LineColor : TColor read fLineColor write SetLineColor; //property BorderMargin : integer read fBorderMargin write SetBorderMargin; // Range property Ranged : boolean read fRanged write SetRanged; property RangeFromColor : TColor read fRangeFromColor write SetRangeFromColor; property RangeToColor : TColor read fRangeToColor write SetRangeToColor; property Align; property DragCursor; property DragMode; property Enabled; property Font; property ParentFont; //property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation uses GradientUtils, Literals; // TPercentEdit constructor TPercentEdit.Create(AOwner : TComponent); begin inherited; fTopColor := $080808; fBottomColor := clBlack; fOutNibColor := $050607; fInNibColor := $090709; fOutBorderColor := $283934; fInBorderColor := $979797; fMinPerc := 0; fMaxPerc := 100; fValue := 50; fBarHeight := 12; fBitmap := TBitmap.Create; fTopMargin := 8; //fBorderMargin := 5; end; destructor TPercentEdit.Destroy; begin fBitmap.Free; inherited; end; procedure TPercentEdit.RenderToBmp; begin GradientUtils.Gradient(fBitmap.Canvas, fTopColor, fBottomColor, false, Rect(0, 0, pred(fBitmap.Width), pred(fBitmap.Height))); if fRanged and (fMidOffset > fBarHeight) then GradientUtils.Gradient(fBitmap.Canvas, fRangeFromColor, fRangeToColor, false, Rect(0, 0, fMidOffset - fBarHeight + 1, pred(fBitmap.Height))); end; procedure TPercentEdit.DrawAll; begin RenderToBmp; Refresh; end; procedure TPercentEdit.DrawLines(R : TRect; midLine : boolean); begin Canvas.Pen.Color := Font.Color; Canvas.MoveTo(R.Left + 1, R.Bottom); Canvas.LineTo(R.Left + 1, R.Bottom + fBarHeight div 2); Canvas.MoveTo(R.Right - 1, R.Bottom); Canvas.LineTo(R.Right - 1, R.Bottom + fBarHeight div 2); if midLine then if not fRanged then begin Canvas.MoveTo(fMidOffset, R.Bottom); Canvas.LineTo(fMidOffset, R.Bottom + fBarHeight div 2); end else if fMidOffset > 1 + Canvas.TextWidth(IntToStr(fMidValue)) div 2 then begin Canvas.Pen.Color := fRangeToColor; Canvas.MoveTo(fMidOffset, R.Bottom); Canvas.LineTo(fMidOffset, R.Bottom + fBarHeight div 2); end; end; procedure TPercentEdit.DrawNibble(R : TRect); var Points : array[0..3] of TPoint; begin Points[0].x := fNibOffset - fBarHeight; Points[0].y := R.Top + fBarHeight div 2; Points[1].x := Points[0].x + fBarHeight; Points[1].y := Points[0].y - fBarHeight; Points[2].x := Points[1].x + fBarHeight; Points[2].y := Points[1].y + fBarHeight; Points[3].x := Points[2].x - fBarHeight; Points[3].y := Points[2].y + fBarHeight; Canvas.Pen.Color := fOutBorderColor; Canvas.Brush.Color := fOutNibColor; Canvas.Polygon(Points); inc(Points[0].x, fBarHeight div 2); inc(Points[1].y, fBarHeight div 2); dec(Points[2].x, fBarHeight div 2); dec(Points[3].y, fBarHeight div 2); Canvas.Pen.Color := fInBorderColor; Canvas.Brush.Color := fInNibColor; Canvas.Polygon(Points); end; procedure TPercentEdit.DrawNumber(var R : TRect; number : string; flag : boolean); begin Canvas.Font := Font; if flag then Canvas.Font.Color := fRangeToColor; Windows.DrawText(Canvas.Handle, pchar(number), -1, R, DT_CALCRECT + DT_SINGLELINE + DT_CENTER); Windows.DrawText(Canvas.Handle, pchar(number), -1, R, DT_SINGLELINE + DT_CENTER); end; function TPercentEdit.DrawNumbers(R : TRect) : boolean; var aux : string; C : TRect; fnum : integer; lnum : integer; nwth : integer; begin Canvas.Font.Color := Font.Color; Canvas.Brush.Style := bsClear; aux := IntToStr(fMinPerc); C.Top := R.Bottom + fBarHeight; C.Left := fBarHeight div 2; DrawNumber(C, aux, false); fnum := c.Right; aux := IntToStr(fMaxPerc); C.Left := Width - Canvas.TextWidth(aux) - fBarHeight; lnum := C.Left; DrawNumber(C, aux, false); aux := IntToStr(fMidValue); nwth := Canvas.TextWidth(aux); C.Left := fMidOffset - nwth div 2; result := (fnum < C.Left - 1) and (C.Left + nwth + 1 < lnum); if result then DrawNumber(C, aux, fRanged); end; procedure TPercentEdit.SetNibble(x : integer); var perc : single; rgth : integer; begin rgth := Width - fBarHeight; if x > rgth then x := rgth else if x < fBarHeight then x := fBarHeight; perc := (x - fBarHeight)/(rgth - fBarHeight); SetValue(round(perc*(fMaxPerc - fMinPerc))); end; { function TPercentEdit.GetMidOffset : integer; var perc : single; barSize : integer; begin barSize := pred(Width) - 2*fBarHeight; perc := (fMidValue - fMinPerc)/(fMaxPerc - fMinPerc); result := fBarHeight + round(perc*barSize); end; } procedure TPercentEdit.Paint; var S : TRect; R : TRect; m : boolean; begin R := Rect(0, 0, pred(fBitmap.Width), pred(fBitmap.Height)); S := R; OffsetRect(R, fBarHeight, fTopMargin); Canvas.CopyRect(R, fBitmap.Canvas, S); DrawNibble(R); m := DrawNumbers(R); DrawLines(R, m); end; procedure TPercentEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; fBitmap.Width := Width - 2*fBarHeight; SetValue(fValue); end; procedure TPercentEdit.Loaded; begin inherited; fBitmap.Height := fBarHeight; end; procedure TPercentEdit.CMTextChange(var Message: TMessage); begin try if (Text <> '') and (Text <> GetLiteral('Literal418')) then Value := StrToInt(Text) else Value := fMinPerc; except end; end; procedure TPercentEdit.CMMouseEnter(var Message: TMessage); begin end; procedure TPercentEdit.CMMouseLeave(var Message: TMessage); begin end; procedure TPercentEdit.CMFontChanged(var Message: TMessage); begin Refresh; end; procedure TPercentEdit.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TPercentEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Enabled then SetNibble(X); end; procedure TPercentEdit.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited; if Enabled and (ssLeft in Shift) then SetNibble(X); end; procedure TPercentEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Enabled and Assigned(fOnChange) then begin fOnChange(self); if fRetValue then SetValue(fOldValue); end; end; procedure TPercentEdit.SetTopColor(aColor : TColor); begin if fTopColor <> aColor then begin fTopColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.SetBottomColor(aColor : TColor); begin if fBottomColor <> aColor then begin fBottomColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.SetOutNibColor(aColor : TColor); begin if fOutNibColor <> aColor then begin fOutNibColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.SetInNibColor(aColor : TColor); begin if fInNibColor <> aColor then begin fInNibColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.SetOutBorderColor(aColor : TColor); begin if fOutBorderColor <> aColor then begin fOutBorderColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.SetInBorderColor(aColor : TColor); begin if fInBorderColor <> aColor then begin fInBorderColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.SetMinPerc(aValue : integer); begin if (aValue < fMaxPerc) and (fMinPerc <> aValue) then begin fMinPerc := aValue; SetValue(fValue); end; end; procedure TPercentEdit.SetMaxPerc(aValue : integer); begin if (aValue > fMinPerc) and (fMaxPerc <> aValue) then begin fMaxPerc := aValue; SetValue(fValue); end; end; procedure TPercentEdit.SetValue(aValue : integer); var barSize : integer; perc : single; strVal : string; begin fOldValue := fValue; if aValue >= fMaxPerc then begin fValue := fMaxPerc; fNibOffset := fBarHeight + fBitmap.Width - fBarHeight; end else if aValue <= fMinPerc then begin fValue := fMinPerc; fNibOffset := fBarHeight + fBarHeight; end else fValue := aValue; barSize := pred(Width) - 2*fBarHeight; perc := (fValue - fMinPerc)/(fMaxPerc - fMinPerc); fNibOffset := fBarHeight + round(perc*barSize); perc := (fMidValue - fMinPerc)/(fMaxPerc - fMinPerc); fMidOffset := fBarHeight + round(perc*barSize); strVal := IntToStr(fValue) + '%'; Hint := strVal; DrawAll; if fLabel <> nil then fLabel.Caption := strVal; if Assigned(fOnMoveBar) then fOnMoveBar(self); fRetValue := false; end; procedure TPercentEdit.SetMidValue(aValue : integer); begin if fMidValue <> aValue then begin if (aValue < fMinPerc) or (aValue > fMaxPerc) then fMidValue := (fMaxPerc - fMinPerc) div 2 else fMidValue := aValue; SetValue(fValue); end; end; procedure TPercentEdit.SetBarHeight(aHeight : integer); begin if aHeight <> fBarHeight then begin fBitmap.Height := aHeight; fBitmap.Width := Width - 2*aHeight; fBarHeight := aHeight; SetValue(fValue); end; end; procedure TPercentEdit.SetTopMargin(aMargin : integer); begin if fTopMargin <> aMargin then begin fTopMargin := aMargin; SetValue(fValue); end; end; { procedure TPercentEdit.SetBorderMargin(aMargin : integer); begin if fBarHeight <> aMargin then begin fBarHeight := aMargin; fBitmap.Width := Width - 2*fBarHeight; SetValue(fValue); end; end; } procedure TPercentEdit.SetLabel(aLabel : TLabel); begin fLabel := aLabel; if fLabel <> nil then fLabel.Caption := IntToStr(fValue) + '%'; end; procedure TPercentEdit.SetLineColor(aColor : TColor); begin if fLineColor <> aColor then begin fLineColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.SetRanged(value : boolean); begin if fRanged <> value then begin fRanged := value; SetValue(fValue); end; end; procedure TPercentEdit.SetRangeFromColor(aColor : TColor); begin if aColor <> fRangeFromColor then begin fRangeFromColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.SetRangeToColor(aColor : TColor); begin if aColor <> fRangeToColor then begin fRangeToColor := aColor; SetValue(fValue); end; end; procedure TPercentEdit.ReturnValue; begin fRetValue := true; end; procedure Register; begin RegisterComponents('Five', [TPercentEdit]); end; end.
unit l3Diff; // Модуль: "w:\common\components\rtl\Garant\L3\l3Diff.pas" // Стереотип: "UtilityPack" // Элемент модели: "l3Diff" MUID: (5644774902C8) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses ; type Tl3DiffCompareFunc = function(I: Integer; J: Integer): Boolean; Tl3DiffOperation = ( l3diffSame , l3diffDeleted , l3diffAdded );//Tl3DiffOperation Tl3DiffReportRec = record rOp: Tl3DiffOperation; rLeftIdx: Integer; rRightIdx: Integer; end;//Tl3DiffReportRec Tl3DiffReportProc = procedure(const aRR: Tl3DiffReportRec); procedure l3DoDiff(aCountLeft: Integer; aCountRight: Integer; aCompareFunc: Tl3DiffCompareFunc; aReportProc: Tl3DiffReportProc); implementation uses l3ImplUses , Math , l3Base //#UC START# *5644774902C8impl_uses* //#UC END# *5644774902C8impl_uses* ; procedure l3DoDiff(aCountLeft: Integer; aCountRight: Integer; aCompareFunc: Tl3DiffCompareFunc; aReportProc: Tl3DiffReportProc); //#UC START# *56447A0802A9_5644774902C8_var* var l_LCSMatrix: PIntegerArray; l_Size: Integer; I, J: Integer; procedure PutAt(aLeft, aRight: Integer; aValue: Integer); var l_Idx: Integer; begin // Assert((aLeft >= 0) and (aLeft < aCountLeft) and (aRight >= 0) and (aRight < aCountRight)); l_Idx := aRight * aCountLeft + aLeft; // Assert(l_Idx < aCountLeft*aCountRight); l_LCSMatrix^[l_Idx] := aValue; end; function GetAt(aLeft, aRight: Integer): Integer; begin if (aLeft < 0) or (aRight < 0) then Result := 0 else Result := l_LCSMatrix^[aRight * aCountLeft + aLeft]; end; function RR(const aOp: Tl3DiffOperation; const aLI, aRI: Integer): Tl3DiffReportRec; begin Result.rOp := aOp; Result.rLeftIdx := aLI; Result.rRightIdx := aRI; end; procedure DoDiff(aL, aR: Integer); begin if (aL >= 0) and (aR >= 0) and aCompareFunc(aL, aR) then begin DoDiff(aL-1, aR-1); aReportProc(RR(l3diffSame, aL, aR)); end else if (aR >= 0) and ((aL < 0) or (GetAt(aL, aR-1) >= GetAt(aL-1, aR))) then begin DoDiff(aL, aR-1); aReportProc(RR(l3diffAdded, aL, aR)); end else if (aL >= 0) and ((aR < 0) or (GetAt(aL, aR-1) < GetAt(aL-1, aR))) then begin DoDiff(aL-1, aR); aReportProc(RR(l3diffDeleted, aL, aR)); end; end; //#UC END# *56447A0802A9_5644774902C8_var* begin //#UC START# *56447A0802A9_5644774902C8_impl* l_Size := aCountLeft * aCountRight * SizeOf(Integer); l3System.GetLocalMem(l_LCSMatrix, l_Size); try l3FillChar(l_LCSMatrix^, l_Size); // строим матрицу for I := 0 to aCountLeft-1 do begin for J := 0 to aCountRight-1 do begin if aCompareFunc(I,J) then PutAt(I,J, GetAt(I-1, J-1) + 1) else PutAt(I,J, Max(GetAt(I, J-1), GetAt(I-1, J))); end; end; // пробегаем по матрице и строим дифф DoDiff(aCountLeft-1, aCountRight-1); finally l3System.FreeLocalMem(l_LCSMatrix); end; //#UC END# *56447A0802A9_5644774902C8_impl* end;//l3DoDiff end.
unit f2ScnSaveLoad; interface uses d2dTypes, d2dInterfaces, d2dApplication, d2dGUI, d2dUtils, d2dFont, f2Application, f2Scene, f2SaveLoadManager, f2Context; type Tf2SaveLoadMode = (slmSave, slmLoad); Tf2SaveLoadScene = class(Tf2Scene) private f_BGColor: Td2dColor; f_CaptionColor: Td2dColor; f_CaptionFont: Id2dFont; f_GUI: Td2dGUI; f_Captions : array[0..cMaxSlotsNum] of string; f_DT : array[0..cMaxSlotsNum] of TDateTime; f_CaptionX: Integer; f_CaptionY: Integer; f_Mode: Tf2SaveLoadMode; f_Selected: Integer; function pm_GetCaptions(aIndex: Integer): string; procedure pm_SetCaptions(aIndex: Integer; const Value: string); procedure ButtonClickHandler(aSender: TObject); procedure DoBack(aSender: TObject); function pm_GetDT(Index: Integer): TDateTime; procedure pm_SetDT(Index: Integer; const Value: TDateTime); protected procedure DoFrame(aDelta: Single); override; procedure DoLoad; override; procedure DoProcessEvent(var theEvent: Td2dInputEvent); override; procedure DoRender; override; procedure DoUnload; override; public property Captions[aIndex: Integer]: string read pm_GetCaptions write pm_SetCaptions; property DT[Index: Integer]: TDateTime read pm_GetDT write pm_SetDT; property Mode: Tf2SaveLoadMode read f_Mode write f_Mode; property Selected: Integer read f_Selected; end; implementation uses SimpleXML, d2dCore, f2FontLoad, f2Skins, d2dGUIButtons, SysUtils, f2Decorators; // START resource string wizard section resourcestring c_sSaveload = 'saveload'; c_sBgcolor = 'bgcolor'; c_sCaptioncolor = 'captioncolor'; c_sCaptionfont = 'captionfont'; c_sButtons = 'buttons'; c_sFrame = 'frame'; c_sBackButton = 'backbutton'; // END resource string wizard section const c_Captions : array [Tf2SaveLoadMode] of string = ('Сохранение игры', 'Загрузка игры'); procedure Tf2SaveLoadScene.ButtonClickHandler(aSender: TObject); begin f_Selected := Td2dControl(aSender).Tag; StopAsChild; end; procedure Tf2SaveLoadScene.DoBack(aSender: TObject); begin StopAsChild; end; procedure Tf2SaveLoadScene.DoFrame(aDelta: Single); var l_MouseDecorator: Tf2BaseDecorator; begin l_MouseDecorator := Context.GetMouseDecorator; gD2DE.HideMouse := l_MouseDecorator <> nil; if l_MouseDecorator <> nil then begin l_MouseDecorator.PosX := gD2DE.MouseX; l_MouseDecorator.PosY := gD2DE.MouseY; end; f_GUI.FrameFunc(aDelta); end; procedure Tf2SaveLoadScene.DoLoad; var I: Integer; l_BackButton: Td2dBitButton; l_ButtonHeight: Integer; l_Frame: Id2dFramedButtonView; l_Root: IXmlNode; l_Node: IXmlNode; l_Buttons: array[0..cMaxSlotsNum] of Td2dFramedTextButton; l_ButtonsNum: Integer; l_ButtonX: Integer; l_ButtonY: Integer; l_Caption: string; l_MaxWidth: Single; l_CaptionGap, l_ButtonsGap: Integer; l_DTS: string; l_FullHeight: Integer; l_MaxAllowedWidth: Integer; l_Size: Td2dPoint; begin l_Root := F2App.Skin.XML.DocumentElement.SelectSingleNode(c_sSaveload); if l_Root <> nil then begin f_BGColor := Td2dColor(l_Root.GetHexAttr(c_sBgcolor, $C0000000)); f_CaptionColor := Td2dColor(l_Root.GetHexAttr(c_sCaptioncolor, $FFFFBB4F)); if l_Root.AttrExists(c_sCaptionfont) then f_CaptionFont := F2App.Skin.Fonts[l_Root.GetAttr(c_sCaptionfont)]; l_Node := l_Root.SelectSingleNode(c_sButtons); if l_Node <> nil then if l_Node.AttrExists(c_sFrame) then l_Frame := F2App.Skin.Frames[l_Node.GetAttr(c_sFrame)]; l_BackButton := LoadButton(l_Root, c_sBackButton); end else begin f_BGColor := $C0000000; f_CaptionColor := $FFFFBB4F; l_BackButton := nil; end; if f_CaptionFont = nil then f_CaptionFont := F2App.DefaultTextFont; if l_Frame = nil then l_Frame := F2App.DefaultButtonView; f_GUI := Td2dGUI.Create; if l_BackButton = nil then l_BackButton := Td2dBitButton.Create(700, 55, F2App.DefaultTexture, 564, 97, 45, 45); with l_BackButton do begin CanBeFocused := False; OnClick := DoBack; end; f_GUI.AddControl(l_BackButton); l_MaxAllowedWidth := gD2DE.ScreenWidth - l_Frame.MinWidth; l_MaxWidth := 0; FillChar(l_Buttons, SizeOf(l_Buttons), 0); for I := 0 to cMaxSlotsNum do begin if (I = 0) and ((f_Captions[0] = '') or (f_Mode = slmSave)) then Continue; if f_Captions[I] = '' then l_Caption := '' else begin DateTimeToString(l_DTS, 'd mmm yyyy, hh:nn:ss', DT[I]); l_DTS := ' ('+l_DTS+')'; l_Caption := l_Frame.CorrectCaptionEx(f_Captions[I], l_MaxAllowedWidth, l_DTS); end; l_Buttons[I] := Td2dFramedTextButton.Create(0, 0, l_Frame, l_Caption); if l_Buttons[I].Caption = '' then begin l_Buttons[I].Caption := '[пусто]'; if f_Mode = slmLoad then l_Buttons[I].Enabled := False; end; l_Buttons[I].Tag := I; l_Buttons[I].OnClick := ButtonClickHandler; l_Buttons[I].AutoFocus := True; if l_MaxWidth < l_Buttons[I].Width then l_MaxWidth := l_Buttons[I].Width; f_GUI.AddControl(l_Buttons[I]); end; l_CaptionGap := Round(l_Buttons[1].Height / 2); l_ButtonsGap := Round(l_Buttons[1].Height / 7); f_CaptionFont.CalcSize(c_Captions[f_Mode], l_Size); f_CaptionX := Round((gD2DE.ScreenWidth - l_Size.X) / 2); l_FullHeight := Round(l_Size.Y) + l_CaptionGap; if l_Buttons[0] <> nil then l_ButtonsNum := cMaxSlotsNum + 1 else l_ButtonsNum := cMaxSlotsNum; l_ButtonHeight := Round(l_Buttons[1].Height); l_FullHeight := l_FullHeight + (l_ButtonHeight * l_ButtonsNum) + (l_ButtonsGap * (l_ButtonsNum-1)); f_CaptionY := (gD2DE.ScreenHeight - l_FullHeight) div 2; l_ButtonY := f_CaptionY + Round(l_Size.Y) + l_CaptionGap; l_ButtonX := (gD2DE.ScreenWidth - Round(l_MaxWidth)) div 2; for I := 0 to cMaxSlotsNum do begin if l_Buttons[I] = nil then Continue; with l_Buttons[I] do begin AutoSize := False; Width := l_MaxWidth; X := l_ButtonX; Y := l_ButtonY; l_ButtonY := l_ButtonY + l_ButtonHeight + l_ButtonsGap; end; end; f_Selected := -1; end; procedure Tf2SaveLoadScene.DoProcessEvent(var theEvent: Td2dInputEvent); begin if theEvent.EventType = INPUT_KEYDOWN then begin if theEvent.KeyCode = D2DK_ESCAPE then begin DoBack(Self); Processed(theEvent); end; if theEvent.KeyCode = D2DK_DOWN then begin f_GUI.FocusNext; Processed(theEvent); end; if theEvent.KeyCode = D2DK_UP then begin f_GUI.FocusPrev; Processed(theEvent); end; end; f_GUI.ProcessEvent(theEvent); end; procedure Tf2SaveLoadScene.DoRender; var l_MouseDecorator: Tf2BaseDecorator; begin D2DRenderFilledRect(D2DRect(0, 0, gD2DE.ScreenWidth, gD2DE.ScreenHeight), f_BGColor); f_CaptionFont.Color := f_CaptionColor; f_CaptionFont.Render(f_CaptionX, f_CaptionY, c_Captions[f_Mode]); f_GUI.Render; l_MouseDecorator := Context.GetMouseDecorator; gD2DE.HideMouse := l_MouseDecorator <> nil; if l_MouseDecorator <> nil then l_MouseDecorator.Render; end; procedure Tf2SaveLoadScene.DoUnload; begin FreeAndNil(f_GUI); end; function Tf2SaveLoadScene.pm_GetCaptions(aIndex: Integer): string; begin Result := f_Captions[aIndex]; end; function Tf2SaveLoadScene.pm_GetDT(Index: Integer): TDateTime; begin Result := f_DT[Index]; end; procedure Tf2SaveLoadScene.pm_SetCaptions(aIndex: Integer; const Value: string); begin f_Captions[aIndex] := Value; end; procedure Tf2SaveLoadScene.pm_SetDT(Index: Integer; const Value: TDateTime); begin f_DT[Index] := Value; end; end.
unit JSONDictionaryIntermediateObjectUnit; interface uses Classes, SysUtils, System.Generics.Collections, System.Rtti, REST.JsonReflect, CommonTypesUnit; type TStringPair = TPair<String,String>; TDictionaryStringIntermediateObject = class private // This field can not be renamed FDictionaryIntermediateObject: TArrayStringPair; function GetPair(Key: String; List: TArrayStringPair; out Pair: TStringPair): boolean; public constructor Create; destructor Destroy; override; // This class method need for JSON unmarshaling class function FromJsonString(JsonString: String): TDictionaryStringIntermediateObject; function Equals(Obj: TObject): Boolean; override; procedure Add(Key: String; Value: String); end; TIntegerPair = TPair<String,Integer>; TDictionaryIntegerIntermediateObject = class private // This field can not be renamed FDictionaryIntermediateObject: TArray<TIntegerPair>; function GetPair(Key: String; List: TArray<TIntegerPair>; out Pair: TIntegerPair): boolean; public constructor Create; destructor Destroy; override; // This class method need for JSON unmarshaling class function FromJsonString(JsonString: String): TDictionaryIntegerIntermediateObject; function Equals(Obj: TObject): Boolean; override; procedure Add(Key: String; Value: integer); end; implementation function GetPairs(JsonString: String): TArrayStringPair; var i, j: integer; sl: TStringList; Pair: String; begin SetLength(Result, 0); JsonString := copy(JsonString, 2, Length(JsonString) - 2); sl := TStringList.Create; try ExtractStrings([','], [' '], PWideChar(JsonString), sl); for i := 0 to sl.Count - 1 do begin Pair := StringReplace(sl[i], '"', '', [rfReplaceAll]); j := pos(':', Pair); if (j = 0) then raise Exception.Create(Format('String %s is not correct JSON-string', [JsonString])); SetLength(Result, Length(Result) + 1); Result[High(Result)].Key := copy(Pair, 1, j-1); Result[High(Result)].Value := copy(Pair, j+1, Length(Pair) - j); end; finally FreeAndNil(sl); end; end; { TNullableDictionaryStringIntermediateObject } procedure TDictionaryStringIntermediateObject.Add(Key, Value: String); begin SetLength(FDictionaryIntermediateObject, Length(FDictionaryIntermediateObject) + 1); FDictionaryIntermediateObject[High(FDictionaryIntermediateObject)].Key := Key; FDictionaryIntermediateObject[High(FDictionaryIntermediateObject)].Value := Value; end; constructor TDictionaryStringIntermediateObject.Create; begin SetLength(FDictionaryIntermediateObject, 0); end; destructor TDictionaryStringIntermediateObject.Destroy; begin Finalize(FDictionaryIntermediateObject); inherited; end; function TDictionaryStringIntermediateObject.Equals(Obj: TObject): Boolean; var Other: TDictionaryStringIntermediateObject; Pair: TStringPair; OtherPair: TStringPair; begin Result := False; if not (Obj is TDictionaryStringIntermediateObject) then Exit; Other := TDictionaryStringIntermediateObject(Obj); if (Length(FDictionaryIntermediateObject) <> Length(Other.FDictionaryIntermediateObject)) then Exit; for Pair in FDictionaryIntermediateObject do begin if not GetPair(Pair.Key, Other.FDictionaryIntermediateObject, OtherPair) then Exit; if (Pair.Value <> OtherPair.Value) then Exit; end; Result := True; end; class function TDictionaryStringIntermediateObject.FromJsonString( JsonString: String): TDictionaryStringIntermediateObject; var Pair: TStringPair; begin Result := TDictionaryStringIntermediateObject.Create; for Pair in GetPairs(JsonString) do Result.Add(Pair.Key, Pair.Value); end; function TDictionaryStringIntermediateObject.GetPair(Key: String; List: TArrayStringPair; out Pair: TStringPair): boolean; var APair: TStringPair; begin Result := False; for APair in List do if (APair.Key = Key) then begin Pair := APair; Exit(True); end; end; { TNullableDictionaryIntegerIntermediateObject } procedure TDictionaryIntegerIntermediateObject.Add(Key: String; Value: integer); begin SetLength(FDictionaryIntermediateObject, Length(FDictionaryIntermediateObject) + 1); FDictionaryIntermediateObject[High(FDictionaryIntermediateObject)].Key := Key; FDictionaryIntermediateObject[High(FDictionaryIntermediateObject)].Value := Value; end; constructor TDictionaryIntegerIntermediateObject.Create; begin SetLength(FDictionaryIntermediateObject, 0); end; destructor TDictionaryIntegerIntermediateObject.Destroy; begin Finalize(FDictionaryIntermediateObject); inherited; end; function TDictionaryIntegerIntermediateObject.Equals(Obj: TObject): Boolean; var Other: TDictionaryIntegerIntermediateObject; Pair: TIntegerPair; OtherPair: TIntegerPair; begin Result := False; if not (Obj is TDictionaryIntegerIntermediateObject) then Exit; Other := TDictionaryIntegerIntermediateObject(Obj); if (Length(FDictionaryIntermediateObject) <> Length(Other.FDictionaryIntermediateObject)) then Exit; for Pair in FDictionaryIntermediateObject do begin if not GetPair(Pair.Key, Other.FDictionaryIntermediateObject, OtherPair) then Exit; if (Pair.Value <> OtherPair.Value) then Exit; end; Result := True; end; class function TDictionaryIntegerIntermediateObject.FromJsonString( JsonString: String): TDictionaryIntegerIntermediateObject; var Pair: TStringPair; begin Result := TDictionaryIntegerIntermediateObject.Create; for Pair in GetPairs(JsonString) do Result.Add(Pair.Key, StrToInt(Pair.Value)); end; function TDictionaryIntegerIntermediateObject.GetPair(Key: String; List: TArray<TIntegerPair>; out Pair: TIntegerPair): boolean; var APair: TIntegerPair; begin Result := False; for APair in List do if (APair.Key = Key) then begin Pair := APair; Exit(True); end; end; end.
unit TTSGUARTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSGUARRecord = record PLenderNum: String[4]; PLoanNum: String[20]; PCifNum: String[20]; PModCount: Integer; PCifY: String[1]; PCifN: String[1]; End; TTTSGUARBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSGUARRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSGUAR = (TTSGUARPrimaryKey, TTSGUARbyCif); TTTSGUARTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFLoanNum: TStringField; FDFCifNum: TStringField; FDFModCount: TIntegerField; FDFCifY: TStringField; FDFCifN: TStringField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCifNum(const Value: String); function GetPCifNum:String; procedure SetPModCount(const Value: Integer); function GetPModCount:Integer; procedure SetPCifY(const Value: String); function GetPCifY:String; procedure SetPCifN(const Value: String); function GetPCifN:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSGUAR); function GetEnumIndex: TEITTSGUAR; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSGUARRecord; procedure StoreDataBuffer(ABuffer:TTTSGUARRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFLoanNum: TStringField read FDFLoanNum; property DFCifNum: TStringField read FDFCifNum; property DFModCount: TIntegerField read FDFModCount; property DFCifY: TStringField read FDFCifY; property DFCifN: TStringField read FDFCifN; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCifNum: String read GetPCifNum write SetPCifNum; property PModCount: Integer read GetPModCount write SetPModCount; property PCifY: String read GetPCifY write SetPCifY; property PCifN: String read GetPCifN write SetPCifN; published property Active write SetActive; property EnumIndex: TEITTSGUAR read GetEnumIndex write SetEnumIndex; end; { TTTSGUARTable } procedure Register; implementation function TTTSGUARTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSGUARTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSGUARTable.GenerateNewFieldName } function TTTSGUARTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSGUARTable.CreateField } procedure TTTSGUARTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFCifNum := CreateField( 'CifNum' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TIntegerField; FDFCifY := CreateField( 'CifY' ) as TStringField; FDFCifN := CreateField( 'CifN' ) as TStringField; end; { TTTSGUARTable.CreateFields } procedure TTTSGUARTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSGUARTable.SetActive } procedure TTTSGUARTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSGUARTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSGUARTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSGUARTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSGUARTable.SetPCifNum(const Value: String); begin DFCifNum.Value := Value; end; function TTTSGUARTable.GetPCifNum:String; begin result := DFCifNum.Value; end; procedure TTTSGUARTable.SetPModCount(const Value: Integer); begin DFModCount.Value := Value; end; function TTTSGUARTable.GetPModCount:Integer; begin result := DFModCount.Value; end; procedure TTTSGUARTable.SetPCifY(const Value: String); begin DFCifY.Value := Value; end; function TTTSGUARTable.GetPCifY:String; begin result := DFCifY.Value; end; procedure TTTSGUARTable.SetPCifN(const Value: String); begin DFCifN.Value := Value; end; function TTTSGUARTable.GetPCifN:String; begin result := DFCifN.Value; end; procedure TTTSGUARTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('LoanNum, String, 20, N'); Add('CifNum, String, 20, N'); Add('ModCount, Integer, 0, N'); Add('CifY, String, 1, N'); Add('CifN, String, 1, N'); end; end; procedure TTTSGUARTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;LoanNum;CifNum, Y, Y, N, N'); Add('byCif, LenderNum;CifNum;LoanNum, N, N, Y, N'); end; end; procedure TTTSGUARTable.SetEnumIndex(Value: TEITTSGUAR); begin case Value of TTSGUARPrimaryKey : IndexName := ''; TTSGUARbyCif : IndexName := 'byCif'; end; end; function TTTSGUARTable.GetDataBuffer:TTTSGUARRecord; var buf: TTTSGUARRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PLoanNum := DFLoanNum.Value; buf.PCifNum := DFCifNum.Value; buf.PModCount := DFModCount.Value; buf.PCifY := DFCifY.Value; buf.PCifN := DFCifN.Value; result := buf; end; procedure TTTSGUARTable.StoreDataBuffer(ABuffer:TTTSGUARRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFLoanNum.Value := ABuffer.PLoanNum; DFCifNum.Value := ABuffer.PCifNum; DFModCount.Value := ABuffer.PModCount; DFCifY.Value := ABuffer.PCifY; DFCifN.Value := ABuffer.PCifN; end; function TTTSGUARTable.GetEnumIndex: TEITTSGUAR; var iname : string; begin result := TTSGUARPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSGUARPrimaryKey; if iname = 'BYCIF' then result := TTSGUARbyCif; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSGUARTable, TTTSGUARBuffer ] ); end; { Register } function TTTSGUARBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..6] of string = ('LENDERNUM','LOANNUM','CIFNUM','MODCOUNT','CIFY','CIFN' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 6) and (flist[x] <> s) do inc(x); if x <= 6 then result := x else result := 0; end; function TTTSGUARBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftString; 6 : result := ftString; end; end; function TTTSGUARBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PLoanNum; 3 : result := @Data.PCifNum; 4 : result := @Data.PModCount; 5 : result := @Data.PCifY; 6 : result := @Data.PCifN; end; end; end.
{ rzfswizard x1nixmzeng (July 2012) July 21st Added data checksum (although unchecked in client) July 15th Added some structure comments and function descriptions } unit rzFileSys; interface // Optional debugging features // { $DEFINE EXPORT_MSFDEC} // Dump the decompressed MSF data { $DEFINE EXPORT_FILELIST} // Save a plaintext file with the filenames { $DEFINE EXPORT_MSFTEST} // Dump the new MSF data uses Dialogs, ComCtrls, SysUtils, Classes, libMSF, ULZMADecoder, ULZMAEncoder; type uint32 = Cardinal; uint16 = Word; (*************************************** Static MSF file entry structure 20-bytes (2 bytes of padding) ****************************************) FILEINDEX_ENTRY = packed record size, // Uncompressed filesize offset, // Data offset in MRF zsize // Compressed filesize in MRF file : uint32; lenMRFN, // Length of MRF filename lenName, // Length of this filename dataHash, // Uncompressed data checksum _padding_ // Structure alignment : uint16; end; (*************************************** MRF entry as used by rzfswizard 36-bytes ****************************************) MSF_ENTRY = record mrfOwner, // Index to MrfFiles tstringlist mrfIndex, // Part number (0 == '.mrf', 1 == '.001', etc) fileIndex // Index to FileList tstringlist : uint32; entryData // Raw fileindex data : FILEINDEX_ENTRY; replaceW // Path to file replacement (when not empty '') : String; end; (*************************************** MSF class to handle data inside fileindex.msf ***************************************) type MSF = class private MrfFiles, // Array of unique MRF files FileList // Array of each filename in the system (large!) : TStringList; FileEntries// Raw static MRF info (stored this way for exporting) : array of MSF_ENTRY; Files // Actual number of files in the system (use FileList count?) : uint32; function AddMrfFile( str : string ) : Cardinal; function GetMrfIndex( str : string) : Cardinal; procedure ExportIndex( FIndex: TMemoryStream ); procedure ImportIndex( FIndex: TMemoryStream ); public constructor Create; destructor Destroy; override; procedure CleanUp; function GetMrfPartName( index: cardinal ): string; function SaveFileIndex( FileName: String ) : Boolean; function LoadFileIndex( FileName: String ) : Boolean; function FileCount() : Integer; function GetMrfList() : TStringList; function GetMrfPartCount(mrfIndex2: Cardinal): Cardinal; function GetFilesForMrf(mrfIndex: Cardinal): Cardinal; function GetTotalSizeForMrf(mrfIndex: Cardinal): Cardinal; function GetTotalZSizeForMrf(mrfIndex: Cardinal): Cardinal; procedure AddFilesToList( grid: TListItems; mrfIndex: cardinal ); procedure ReplaceFile( mrfIndex, fileIndex: Cardinal; const fName: String ); procedure InsertFile( mrfIndex : Cardinal; const fName: String ); function CountFileReplacements(): Cardinal; // did return stringlist end; (*************************************** Class to handle MRF patching ***************************************) MSFPatcher = class(TThread) public fpacked: TMemoryStream; private myStatus: integer; msfi : ^MSF; log : TStringList; isOver : Boolean; protected procedure Execute; override; public constructor Create; destructor Destroy; procedure SetMSF(var msfindex: MSF); function finishedPatch(): Boolean; function getProgress: integer; function getLogMessages(): TStringList; end; function UnLZMA(inFile: TMemoryStream; outSize:Cardinal): TMemoryStream; function PackLZMA(inFile: TMemoryStream): TMemoryStream; implementation // Locate the file extension from a filename // function StripExt(From:String):String; begin Result:= Copy(From, 0, Length(From)-Length(ExtractFileExt(From))); end; // MSF class constructor // constructor MSF.Create; begin inherited Create; // Make hash table if it does not exist if not libMSF.msfGetHashTable() then begin libMSF.msfMakeHashTable(); end; // Setup array SetLength(FileEntries, 0); Files := 0; end; // Destroy allocated classes // procedure MSF.CleanUp; begin // Destroy string arrays if MrfFiles <> nil then MrfFiles.Clear; MrfFiles.Free; if FileList <> nil then FileList.Clear; FileList.Free; // Clear array SetLength(FileEntries, 0); Files := 0; end; // MSF class destructor // destructor MSF.Destroy; begin CleanUp; // Destroy base class inherited Destroy; end; // Add unique MRF names into the MSF filename array // The built-in duplicate methods are not used on purpose! function MSF.AddMrfFile( str : string ) : Cardinal; var i: integer; begin // Copy the filename without the extension (if there is one) str := Copy(str, 0, length(str)-length(Extractfileext(str))); // Starting from the back, check the filename has been previously added for i := MrfFiles.Count downto 1 do begin if MrfFiles.Strings[i-1] = str then begin // Filename has already been added, so return the index and exit Result := i-1; Exit; end; end; // Filename does not exist, so push it back (add() returns the index) Result := MrfFiles.Add( str ); end; // Determine the MRF part index from a filename // function MSF.GetMrfIndex( str: string ) : Cardinal; var i: integer; const MRF_NOT_SPLIT = 0; begin // Initially not split (where extension = '.mrf') Result := MRF_NOT_SPLIT; str := ExtractFileExt(str); if ( length(Str) > 0 ) and ( str <> '.mrf' ) then begin i := 1; // start past the leading period // atoi : while ( i < length(str) ) and ( str[i+1] in ['0'..'9'] ) do begin Result := 10 * Result + (ord(str[i+1])-48); inc(i); end; end; end; // Parse the unpacked fileindex.msf data // procedure MSF.ImportIndex( FIndex: TMemoryStream ); var fRec : FILEINDEX_ENTRY; fn, mrfn: string; begin // todo: strip any existing data so another index can be reloaded Files := 0; // First, loop through and determine the file count // (this is much faster than re-allocating memory 25K times) // while (FIndex.Position < FIndex.Size) do begin FIndex.Read( fRec, SizeOf( FILEINDEX_ENTRY ) ); FIndex.Seek( fRec.lenMRFN + fRec.lenName, soCurrent ); inc(Files); end; // Allocate the array size SetLength(FileEntries, Files); FIndex.Position := 0; Files := 0; // Then loop through reading each entry while (FIndex.Position < FIndex.Size) do begin with FileEntries[Files] do begin // Read structures: // #1 FIndex.Read( entryData, SizeOf(FILEINDEX_ENTRY) ); // #2 (MRF filename string) SetLength(mrfn, entryData.lenMRFN); FIndex.Read(pchar(mrfn)^, entryData.lenMRFN); // #3 (filename string) SetLength(fn, entryData.lenName); FIndex.Read(pchar(fn)^, entryData.lenName); // Store data: // All filenames are unique, so get their own entry FileList.Add(fn); // Update remaining FileEntries properties fileIndex:= FileList.Count-1; mrfOwner := AddMrfFile(mrfn); mrfIndex := GetMrfIndex(mrfn); replaceW := ''; Inc(Files); end; end; {$IFDEF EXPORT_FILELIST} // Log the unique filenames to file FileList.SaveToFile('filelist.txt'); {$ENDIF} end; // Unpack the MSF data from file // function MSF.LoadFileIndex( FileName: String ) : Boolean; var FIndex : TFileStream; unSize : Cardinal; UnpackBuf, tmpBuffer: TMemoryStream; begin Result := False; // Check the file exists if not FileExists( FileName ) then Exit; // Open the file for reading FIndex := TFileStream.Create( FileName, fmOpenRead ); // Get the uncompressed size FIndex.Read(unSize, 4); // Copy this data to its own buffer UnpackBuf := TMemoryStream.Create; UnpackBuf.CopyFrom(FIndex, FIndex.Size - 4); FIndex.Free; // Unscramble the data UnpackBuf.Position := 0; libMSF.msfUnscramble(Byte(UnpackBuf.Memory^), UnpackBuf.Size); // Unpack in memory tmpBuffer := UnLZMA(UnpackBuf, unSize); UnpackBuf.Free; // NEW Check to avoid attempting to read invalid data // Check expected size if tmpBuffer.Size <> unSize then begin tmpBuffer.Free; Result := false; Exit; end; // Import the file data tmpBuffer.Position := 0; {$IFDEF EXPORT_MSFDEC} tmpBuffer.SaveToFile('flist_debug.msf'); {$ENDIF} if tmpBuffer.Size > 0 then begin // Destroy existing data CleanUp; // Create the string arrays MrfFiles := TStringList.Create; FileList := TStringList.Create; ImportIndex( tmpBuffer ); end; Result := ( tmpBuffer.Size > 0 ); // Clear the buffers tmpBuffer.Free; end; // Get the MRF extension based on the part index // function MSF.GetMrfPartName( index: cardinal ): string; begin if index = 0 then result := '.mrf' else result := format('.%.3d',[index]); end; // Create the fileindex.msf data structure // procedure MSF.ExportIndex( FIndex: TMemoryStream ); var i: Cardinal; tmp: string; begin for i:=1 to Files do begin // Write the stored FILEINDEX_ENTRY structure FIndex.Write( FileEntries[i-1].entryData, sizeof( FILEINDEX_ENTRY ) ); // Write the MRF filename: // #1 Find the filename (TODO: CHECK LENGTH) tmp := MrfFiles[ FileEntries[i-1].mrfOwner ]; // #2 Get the file extension tmp := tmp + GetMrfPartName( FileEntries[i-1].mrfIndex ); // #3 Write the string FIndex.Write( tmp[1], length(tmp) ); // Write the filename: // #1 Get the string (TODO: CHECK LENGTH) tmp := FileList.Strings[i-1]; // #2 Write the string FIndex.Write( tmp[1], length(tmp) ); end; // Housekeeping! tmp := ''; end; // Pack the MSF data from file TODO // function MSF.SaveFileIndex( FileName: String ) : Boolean; var FIndex : TMemoryStream; // output file tmpBuffer1, tmpBuffer2: TMemoryStream; unpack_size: cardinal; begin tmpBuffer1 := TMemoryStream.Create; // Create the fileindex.msf structure ExportIndex( tmpBuffer1 ); {$IFDEF EXPORT_MSFTEST} tmpBuffer1.SaveToFile('msf_rebuild.msf'); {$ENDIF} // Save the raw filesize unpack_size := tmpBuffer1.Size; // Pack in memory tmpBuffer2 := PackLZMA( tmpBuffer1 ); tmpBuffer1.Free; // Scramble the data tmpBuffer2.Position := 0; libMSF.msfScramble(Byte(tmpBuffer2.Memory^), tmpBuffer2.Size); FIndex := TMemoryStream.Create; // Write unpacked size FIndex.Write(unpack_size, 4); // Write compressed+scrambled data FIndex.CopyFrom(tmpBuffer2, tmpBuffer2.Size); tmpBuffer2.Free; // Save packed data FIndex.SaveToFile( FileName ); FIndex.Free; Result := True; end; // Count the number of files in the system // function MSF.FileCount : Integer; begin Result := Files; end; // Return the unique MRF filenames // function MSF.GetMrfList() : TStringList; begin Result := MrfFiles; end; // Count the number of parts from a MRF filename list // function MSF.GetMrfPartCount(mrfIndex2: Cardinal): Cardinal; var i: Cardinal; begin Result := 0; for i:=1 to Files do with FileEntries[i-1] do if ( mrfOwner = mrfIndex2 ) and( mrfIndex > Result ) then Result := mrfIndex; Inc(Result); end; // Count the files inside a MRF from a MRF filename index // function MSF.GetFilesForMrf(mrfIndex: Cardinal): Cardinal; var i: Cardinal; begin Result := 0; for i:=1 to Files do if FileEntries[i-1].mrfOwner = mrfIndex then inc(Result); end; // Count the total filesize of files inside a MRF // function MSF.GetTotalSizeForMrf(mrfIndex: Cardinal): Cardinal; var i: Cardinal; begin Result := 0; for i:=1 to Files do if FileEntries[i-1].mrfOwner = mrfIndex then inc( Result, FileEntries[i-1].entryData.size ); end; // Count the total compressed size of files inside a MRF // function MSF.GetTotalZSizeForMrf(mrfIndex: Cardinal): Cardinal; var i: Cardinal; begin Result := 0; for i:=1 to Files do if FileEntries[i-1].mrfOwner = mrfIndex then inc( Result, FileEntries[i-1].entryData.zsize ); end; // Export the file list from MRF index // procedure MSF.AddFilesToList( grid: TListItems; mrfIndex: cardinal ); var i: Cardinal; function IntToSize( int: Cardinal ): String; var i: integer; const TAGS : array[0..3] of string = ( ' b', ' Kb', ' Mb', ' Gb' // fixed the typo here ( was Tb ! ) ); begin i := 0; while int > 1000 do begin int := int div 1000; inc(i); end; Result := IntToStr( int ) + TAGS[i]; end; begin for i:=1 to Files do if FileEntries[i-1].mrfOwner = mrfIndex then begin with grid.Add do begin { NAME SIZE REPLACEMENT } Caption := FileList[i-1]; SubItems.Add(IntToSize(FileEntries[i-1].entryData.size)); if length(FileEntries[i-1].replaceW) > 0 then SubItems.Add( FileEntries[i-1].replaceW ) else SubItems.Add('<none>'); end; end; end; // Mark a file for replacement // procedure MSF.ReplaceFile( mrfIndex, fileIndex: Cardinal; const fName:String ); var i,fc: cardinal; begin fc:=0; for i:=1 to Files do if FileEntries[i-1].mrfOwner = mrfIndex then begin if( fc = fileIndex ) then begin FileEntries[i-1].replaceW := fName; Exit; end; inc(fc); end; end; procedure MSF.InsertFile( mrfIndex : Cardinal; const fName: String ); begin { Inc(Files); SetLength(FileEntries, Files); FileEntries[Files-1].mrfOwner := mrfIndex; FileEntries[Files-1].mrfIndex := 0; // store in first part FileEntries[Files-1].fileIndex:= Files; FileEntries[Files-1].entryData. // .. and mark for replacement, so it gets copied FileEntries[Files-1].replaceW := fName; } end; // Count the number of marked files for replacement // function MSF.CountFileReplacements(): Cardinal; var i: integer; begin Result := 0; for i:=1 to Files do if FileEntries[i-1].replaceW <> '' then inc(Result); end; // Unpack a file in memory // function UnLZMA(inFile: TMemoryStream; outSize:Cardinal): TMemoryStream; var decoder:TLZMADecoder; begin Result := TMemoryStream.Create; decoder := TLZMADecoder.Create; try decoder.SetDictionarySize( $10000 ); // 2^16 decoder.SetLcLpPb(3,0,2); decoder.Code(inFile, Result, outSize); finally decoder.Free; end; end; // Pack file in memory // function PackLZMA(inFile: TMemoryStream): TMemoryStream; var encoder:TLZMAEncoder; begin encoder := TLZMAEncoder.Create; encoder.SetDictionarySize($10000); // 2^16 encoder.SetLcLpPb(3,0,2); Result := TMemoryStream.Create; inFile.Position :=0; encoder.Code(inFile, Result, inFile.Size, -1); encoder.Free; end; constructor MSFPatcher.Create; begin inherited Create(True); // Create log list log:=TStringList.Create(); isOver := false; end; destructor MSFPatcher.Destroy; begin // Null pointer value if msfi <> nil then msfi := nil; // Free log log.Free; end; procedure MSFPatcher.SetMSF(var msfindex: MSF); begin msfi:=@msfindex; end; { TODO MSFPatcher procedure which can make the file changes from the same MSF part # } procedure MSFPatcher.Execute; var i,j, deltaSize : integer; checksum : word; plist: array of integer; mrf, base : string; filesize, ofilesize :cardinal; tmp, lzfile:TMemoryStream; fs1, fs2 : TFileStream; entry, entry2 : ^MSF_ENTRY; begin assert( msfi <> nil ); isOver := False; // Reset status myStatus := 0; // We want an array of file indexes to patch SetLength(plist, 0); // Make the array of file replacement indexes j:=0; for i:=1 to msfi.FileCount do begin if msfi.FileEntries[i-1].replaceW <> '' then begin // todo: check file still exists (maybe later down) SetLength(plist, j+1); plist[j] := i-1; inc(j); end; end; // Ensure we're at the fileindex.msf directory from tab #1 base := GetCurrentDir(); if base[length(base)-1] <> '\' then base := base + '\'; // Log the current directory log.Add('Filesystem base: "'+base+'"'); // For each marked replacement for i:=1 to j do begin entry := @(msfi.FileEntries[ plist[i-1] ]); // Check replacement still exists if not fileexists( entry.replaceW ) then begin log.Add('ERROR: Unable to open "'+entry.replaceW+'"'); entry := nil; end; if entry <> nil then begin // Make MRF container name mrf := msfi.MrfFiles[ entry.mrfOwner ] + msfi.GetMrfPartName( entry.mrfIndex ); // Check MRF exists in base system mrf := base + mrf; // todo: update slashes if not fileexists( mrf ) then begin log.Add('ERROR: Unable to open "'+mrf+'"'); entry := nil; end; end; if entry <> nil then begin log.Add('Compressing '+entry.replaceW + '..'); // Load the new file tmp := TMemoryStream.Create; tmp.LoadFromFile( entry.replaceW ); // Handle the filesize ofilesize := tmp.Size; if ofilesize = 0 then begin // Nothing to pack log.Add('WARNING: File is blank'); checksum := 0; end else begin // Pack the file checksum := libMSF.msfChecksum(Byte(tmp.Memory^), tmp.Size); // hash lzfile := PackLZMA(tmp); // compress tmp.Free; lzfile.Position:=0; libMSF.msfScramble(Byte(lzfile.Memory^), lzfile.Size); // scramble end; // Patch MRF (this must be done when filesize is 0 too) log.Add('Patching '+mrf+'..'); // TODO: find a temporary name instead of deleting potential user data if fileexists(mrf+'_') then deletefile(mrf+'_'); // Rename the existing MRF data RenameFile(mrf,mrf+'_'); fs1 := TFileStream.Create(mrf, fmCreate); // New MRF we create fs2 := TFileStream.Create(mrf+'_', fmOpenRead); // MRF we just renamed // Check if we need to copy any preceeding data if entry.entryData.offset > 0 then begin // Copy all the data before the offset fs1.CopyFrom( fs2, entry.entryData.offset ); // Seek to the new position fs2.Seek( entry.entryData.offset, soBeginning ); end; filesize := 0; // Check we can copy the new file to the MRF (not when size = 0) if ofilesize > 0 then begin lzfile.Position := 0; fs1.CopyFrom( lzfile, lzfile.Size ); filesize := lzfile.Size; // size of new file - size of current deltaSize := lzfile.Size - entry.entryData.zsize; lzfile.Free; end else begin // zsize is now 0, so the difference is the original size deltaSize := -entry.entryData.zsize; end; // Copy any trailing data fs2.Seek( entry.entryData.offset + entry.entryData.zsize, soBeginning ); if fs2.Position <> fs2.Size then fs1.CopyFrom( fs2, fs2.Size-fs2.Position ); // Finally: fs1.Free; fs2.Free; // now delete fs2 (temporary file) if fileexists(mrf+'_') then deletefile(mrf+'_'); entry.entryData.size := ofilesize; entry.entryData.zsize := filesize; entry.entryData.dataHash:= checksum; // Update offsets in database if deltaSize <> 0 then begin for j:=plist[i-1]+2 to msfi.FileCount() do begin entry2 := @(msfi.FileEntries[ j-1 ]); // update the offsets for files in the same mrf if ( entry2.mrfOwner = entry.mrfOwner ) and ( entry2.mrfIndex = entry.mrfIndex ) then begin // bugfix: wrong sign here entry2.entryData.offset := entry2.entryData.offset+deltaSize; end; end; end; log.Add('File patched!'); mystatus := i; end; end; // Write the MSF index log.Add('Exporting fileindex.msf..'); msfi.SaveFileIndex(base+'fileindex.msf'); log.Add('File index has been saved!'); SetLength(plist,0); // Re-import file index log.Add('Reloading file index..'); msfi.LoadFileIndex(base+'fileindex.msf'); log.Add('File index re-imported!'); // Mark the end of patching isOver := True; end; function MSFPatcher.finishedPatch(): Boolean; begin Result := isOver; end; function MSFPatcher.getProgress: integer; begin Result := myStatus; end; function MSFPatcher.getLogMessages(): TStringList; begin assert( log <> nil ); Result := log; end; end.
unit seta_sprites; interface uses {$IFDEF WINDOWS}windows,{$ELSE IF}main_engine,{$ENDIF} gfx_engine; type tfunction=function(code:word;color:word):word; tseta_sprites=class constructor create(sprite_gfx,screen_gfx,bank_size:byte;sprite_mask:word;code_cb:tfunction=nil); destructor free; public control:array[0..3] of byte; bg_flag:byte; spritelow,spritehigh:array[0..$1fff] of byte; spritey:array[0..$2ff] of byte; bank_size,sprite_gfx,screen_gfx:byte; sprite_mask:word; procedure reset; procedure draw_sprites; procedure tnzs_eof; private code_cb:tfunction; procedure update_background; procedure update_sprites; end; var seta_sprite0:tseta_sprites; implementation constructor tseta_sprites.create(sprite_gfx,screen_gfx,bank_size:byte;sprite_mask:word;code_cb:tfunction=nil); begin self.bank_size:=bank_size; self.sprite_gfx:=sprite_gfx; self.screen_gfx:=screen_gfx; self.sprite_mask:=sprite_mask; self.code_cb:=code_cb; end; destructor tseta_sprites.free; begin end; procedure tseta_sprites.reset; begin self.control[0]:=0; self.control[1]:=$ff; self.control[2]:=$ff; self.control[3]:=$ff; self.bg_flag:=0; end; procedure tseta_sprites.update_background; var startcol,ctrl,ctrl2,column,tot,x,y,atrib:byte; upperbits,bank_inc:word; f,nchar,color,sx,sy:word; flipx,flipy,trans:boolean; begin ctrl2:=self.control[1]; tot:=ctrl2 and $f; if tot=0 then exit; if (tot=1) then tot:=16; ctrl:=self.control[0]; bank_inc:=((ctrl2 xor (not(ctrl2) shl 1)) and $40)*self.bank_size; upperbits:=self.control[2]+(self.control[3] shl 8); startcol:=(ctrl and $3)*4; trans:=(self.bg_flag and $80)=0; for column:=0 to (tot-1) do begin for y:=0 to 15 do begin for x:=0 to 1 do begin f:=$20*((column+startcol) and $f)+2*y+x; atrib:=self.spritehigh[bank_inc+$400+f]; nchar:=self.spritelow[bank_inc+$400+f]+((atrib and $3f) shl 8); if @self.code_cb<>nil then nchar:=self.code_cb(nchar,self.spritehigh[bank_inc+$600+f]) and self.sprite_mask else nchar:=nchar and self.sprite_mask; color:=(self.spritehigh[bank_inc+$600+f] and $f8) shl 1; sx:=(x*$10)+self.spritey[$204+(column*$10)]-(256*(upperbits and 1)); if (ctrl and $40)<>0 then begin sy:=238-(y*$10)+self.spritey[$200+(column*$10)]+1; flipx:=(atrib and $80)=0; flipy:=(atrib and $40)=0; end else begin flipx:=(atrib and $80)<>0; flipy:=(atrib and $40)<>0; sy:=(y*$10)+256-(self.spritey[$200+(column*$10)])+1; end; if trans then begin put_gfx_sprite(nchar,color,flipx,flipy,self.sprite_gfx); actualiza_gfx_sprite(sx,sy,self.screen_gfx,self.sprite_gfx); end else begin put_gfx_flip(sx,sy,nchar,color,self.screen_gfx,self.sprite_gfx,flipx,flipy); end; end; end; upperbits:=upperbits shr 1; end; end; procedure tseta_sprites.update_sprites; var ctrl2,atrib,sy:byte; nchar,color,sx,f,bank_inc:word; flipx,flipy:boolean; begin ctrl2:=self.control[1]; bank_inc:=((ctrl2 xor (not(ctrl2) shl 1)) and $40)*self.bank_size; //512 sprites for f:=$1ff downto 0 do begin atrib:=self.spritehigh[bank_inc+f]; nchar:=(self.spritelow[bank_inc+f]+((atrib and $3f) shl 8)) and self.sprite_mask; color:=(self.spritehigh[bank_inc+$200+f] and $f8) shl 1; sx:=self.spritelow[bank_inc+$200+f]-((self.spritehigh[bank_inc+$200+f] and 1) shl 8); if (self.control[0] and $40)<>0 then begin sy:=self.spritey[f]+2; flipx:=(atrib and $80)=0; flipy:=(atrib and $40)=0; end else begin sy:=240-self.spritey[f]+2; flipx:=(atrib and $80)<>0; flipy:=(atrib and $40)<>0; end; put_gfx_sprite(nchar,color,flipx,flipy,self.sprite_gfx); actualiza_gfx_sprite(sx,sy,self.screen_gfx,self.sprite_gfx); end; end; procedure tseta_sprites.draw_sprites; begin self.update_background; self.update_sprites; end; procedure tseta_sprites.tnzs_eof; begin if (self.control[1] and $20)=0 then begin if (self.control[1] and $40)<>0 then begin copymemory(@self.spritelow[$0],@self.spritelow[$800],$400); copymemory(@self.spritehigh[$0],@self.spritehigh[$800],$400); end else begin copymemory(@self.spritelow[$800],@self.spritelow[$0],$400); copymemory(@self.spritehigh[$800],@self.spritehigh[$0],$400); end; copymemory(@self.spritelow[$400],@self.spritelow[$c00],$400); copymemory(@self.spritehigh[$400],@self.spritehigh[$c00],$400); end; end; end.
unit UnitGUI; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DB, ADODB , ICDsearcher , ICDtranslator, Grids ; type TApplicationGUIForm = class(TForm) lbCriteria: TLabel; edCriteria: TEdit; btSearch: TButton; cbLng: TComboBox; lbResults: TLabel; lbNResults: TLabel; edNResults: TEdit; sgResults: TStringGrid; procedure btSearchClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure sgResultsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); private { Déclarations privées } FSearcher: TICDSearcher; function getLngChoosen: TICDlng; procedure fillComboLng; procedure clearGrid; procedure fillGrid; procedure clearAndFillGrid; public { Déclarations publiques } end; var ApplicationGUIForm: TApplicationGUIForm; implementation uses ICDrecord, ICDconst, TypInfo; {$R *.dfm} procedure TApplicationGUIForm.clearGrid; begin sgResults.RowCount := 1; sgResults.Cells[0,0] := ''; sgResults.Cells[1,0] := ''; end; procedure TApplicationGUIForm.fillGrid; var vLng: TICDlng; vRec: TICDRecord; i: integer; begin sgResults.ColWidths[0] := 50; sgResults.ColWidths[1] := 500; i := -1; for vRec in FSearcher.results do begin inc(i); if i>0 then sgResults.RowCount := sgResults.RowCount + 1; sgResults.Cells[0,i] := vRec.codeICD10; vLng := getLngChoosen; if vLng = lng_fr then sgResults.Cells[1,i] := vRec.frDescription else sgResults.Cells[1,i] := vRec.nlDescription; end; end; procedure TApplicationGUIForm.clearAndFillGrid; begin clearGrid; fillGrid; end; procedure TApplicationGUIForm.btSearchClick(Sender: TObject); var vnRecords: integer; vCriteria: string; vCode: string; vLng: TICDlng; vRec: TICDRecord; Save_Cursor: TCursor; begin Save_Cursor := Screen.Cursor; Screen.Cursor := crHourGlass; vLng := getLngChoosen; vnRecords := strtoint(edNResults.Text); vCriteria := edCriteria.Text; FSearcher.criteria := vCriteria; FSearcher.lng := vLng; FSearcher.top := vnRecords; try FSearcher.ComputeResult; finally clearAndFillGrid; Screen.Cursor := Save_Cursor; if FSearcher.errorMessage <> '' then showmessage(FSearcher.errorMessage); end; end; procedure TApplicationGUIForm.fillComboLng; var iLng: integer; begin cbLng.Items.Clear; for iLng := ord(Low(TICDlng)) to ord(high(TICDlng)) do cbLng.items.Add(TICDtranslator.GUItranslate(TICDlng(iLng))); cbLng.ItemIndex := 0; end; procedure TApplicationGUIForm.FormCreate(Sender: TObject); begin edCriteria.Text := CST_INI_CRITERIA; // initialize to test fillComboLng; FSearcher := TICDSearcher.Create('', lng_fr, CST_INI_SEARCH_NUMBER); end; procedure TApplicationGUIForm.FormDestroy(Sender: TObject); begin FSearcher.Free; end; function TApplicationGUIForm.getLngChoosen: TICDlng; begin result := TICDlng(cbLng.ItemIndex); end; procedure TApplicationGUIForm.sgResultsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin // end; end.
program ch8(data7, out7); { Chapter 8 Assignment Alberto Villalobos April 2, 2014 Description: This programs simulates a refinery's pressure monitoring system. Input: A file that contains intervals to check and line separated value groups. Output: A file that contains the output of pressures, warnings and summary. level 0: Initialize variables Reset File Read number of intervals Read five pressure values Keep sum of values Keep lowest of values Keep highest of values Print Warnings Print Highest and lowest Print average (sum/amount of values) } {main program type} type ary = array[1..6] of integer; {main program vars} var data7, out7: Text; intervalCount, i, intervals, a, b, c, d, e, f: Integer; pressures : ary; {print separator} procedure printSeparator(); begin writeln(out7,'------------------------------------'); end; procedure printProcess(var pressures:ary); var highest, lowest, sum, count : Integer; average: Real; begin highest :=0; lowest := 99999; sum:= 0; {get lowest and highest, also print everything} for count := 1 to 6 do begin sum:= sum + pressures[count]; writeln(out7,'Process':7, count:4, 'pressure:':12,pressures[count]:8); if pressures[count] > highest then begin highest := pressures[count]; end; if pressures[count] < lowest then begin lowest := pressures[count]; end; end; {get average} average := sum / 6; {print summary} if highest > 5000 then begin writeln(out7,'Danger! Overpressure of: ', highest); end; if lowest < 14 then begin writeln(out7,'Danger! Vacumum of: ', lowest); end; writeln(out7,'Low pressure is: ',lowest); writeln(out7,'High pressure is: ',highest); writeln(out7,'average pressure is: ', average:6:0); end; {main program} begin intervalCount:=0; Reset(data7,'datafiles/data7.dat'); Rewrite(out7, 'outputfiles/out7.dat'); read(data7, intervals); writeln(out7,'Number of Intervals to monitor:',intervals:4); printSeparator(); readln(data7); while (not eof(data7)) and (intervalCount < intervals) do begin {read all pressures} for i := 1 to 6 do begin read(data7, pressures[i]); end; printProcess(pressures); printSeparator(); {read new line} readln(data7); intervalCount:=intervalCount+1; end; end.
unit AddCircleTerritoryUnit; interface uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit; type TAddCircleTerritory = class(TBaseExample) public function Execute: NullableString; end; implementation uses TerritoryContourUnit; function TAddCircleTerritory.Execute: NullableString; var ErrorString: String; TerritoryName, TerritoryColor: String; TerritoryContour: TTerritoryContour; TerritoryId: NullableString; begin TerritoryName := 'Circle Territory'; TerritoryColor := 'ff0000'; TerritoryContour := TTerritoryContour.MakeCircleContour( 37.5697528227865, -77.4783325195313, 5000); TerritoryId := Route4MeManager.Territory.Add( TerritoryName, TerritoryColor, TerritoryContour, ErrorString); WriteLn(''); if (TerritoryId.IsNotNull) then begin WriteLn('AddCircleTerritory executed successfully'); WriteLn(Format('Territory ID: %s', [TerritoryId.Value])); end else WriteLn(Format('AddCircleTerritory error: "%s"', [ErrorString])); Result := TerritoryId; end; end.
unit IndyClientUnit; {$I IdCompilerDefines.inc} interface procedure RunTest(URL: string); implementation // see // https://www.indyproject.org/2016/01/10/new-tidhttp-flags-and-onchunkreceived-event/ // https://www.html5rocks.com/en/tutorials/eventsource/basics/ uses IdHTTP, IdGlobal, SysUtils; type { TIndySSEClient } TIndySSEClient = class(TObject) private EventStream: TIdEventStream; IdHTTP: TIdHTTP; ChunkCount: Integer; SSE_URL: string; protected procedure MyOnWrite(const ABuffer: TIdBytes; AOffset, ACount: Longint; var VResult: Longint); public constructor Create(const URL: string); destructor Destroy; override; procedure Run; end; procedure RunTest; var Client: TIndySSEClient; begin WriteLn('URL for Server-sent events: ' + URL); Client := TIndySSEClient.Create(URL); try try Client.Run; except on E: Exception do WriteLn(E.Message); end; finally Client.Free; end; end; { TIndySSEClient } constructor TIndySSEClient.Create; begin inherited Create; SSE_URL := URL; EventStream := TIdEventStream.Create; EventStream.OnWrite := MyOnWrite; IdHTTP := TIdHTTP.Create; IdHTTP.Request.Accept := 'text/event-stream'; IdHTTP.Request.CacheControl := 'no-store'; end; destructor TIndySSEClient.Destroy; begin IdHTTP.Free; EventStream.Free; inherited; end; procedure TIndySSEClient.Run; begin IdHTTP.Get(SSE_URL, EventStream); end; procedure TIndySSEClient.MyOnWrite; begin WriteLn('Received ' + IntToStr(Length(ABuffer)) + ' bytes'); WriteLn; WriteLn(IndyTextEncoding_UTF8.GetString(ABuffer)); Inc(ChunkCount); if ChunkCount > 2 then begin WriteLn('Closing connection'); IdHTTP.Disconnect; end; end; end.
unit u812Firmware; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Gauges, StdCtrls, Buttons, RzButton, RzCmboBx, RzLabel, ExtCtrls, RzPanel, RzRadGrp,iniFiles, Menus; type Tfm812Firmware = class(TForm) GroupBox1: TGroupBox; RzLabel41: TRzLabel; btnClose: TRzBitBtn; btnFirmwareUpdate: TRzBitBtn; ed_FirmwareFile: TEdit; btn_FileSearch: TBitBtn; GroupBox2: TGroupBox; Gauge_812F00: TGauge; lb_gauge: TLabel; Group_812: TRzCheckGroup; SaveDialog1: TSaveDialog; Ktt812FirmwareDownloadStart: TTimer; KTT812ENQTimer: TTimer; Memo1: TMemo; PopupMenu1: TPopupMenu; N1: TMenuItem; Panel1: TPanel; Panel4: TPanel; Panel5: TPanel; Panel6: TPanel; Panel7: TPanel; MessageTimer: TTimer; procedure btnCloseClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Group_812Change(Sender: TObject; Index: Integer; NewState: TCheckBoxState); procedure btnFirmwareUpdateClick(Sender: TObject); procedure btn_FileSearchClick(Sender: TObject); procedure Ktt812FirmwareDownloadStartTimer(Sender: TObject); procedure KTT812ENQTimerTimer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure N1Click(Sender: TObject); procedure MessageTimerTimer(Sender: TObject); private L_cKTT812Firmware : Array[0..256 * 1024] of char; L_stKTT812OFFSET : string; L_nLastPage : integer; L_bENQStop : Boolean; L_bMainFirmWareDownLoadFail : Boolean; KTT812FIRMWARECMDList:TStringList; KTT812DownloadList : TStringList; { Private declarations } procedure Ecu_GroupCreate; function CheckArmMode:Boolean; Function KTT812FileLoad(aFileName:string):Boolean; procedure KTT812FirmWareMemoryClear; Function KTT812FirmWareMemorySave(aData:string):Boolean; Function KTT812MemoryFileSave:Boolean; procedure KTT812MainControlerFirmWareUpdate; function KTT812FirmWareStart:Boolean; function GetKTT812FlashDataLen : integer; procedure BroadKTT812FileDownLoad; procedure FirmwareUpdateEnd; procedure KTT812ExtendBroadCastStart(a812ControlerNum:string); Function Get812ControlerNum(CheckGroup:TRZCheckGroup):String; procedure DeviceFirmWareDownloadComplete(aEcuID:string); procedure DeviceFirmWareDownloadFailed(aEcuID,aFailState:string); public { Public declarations } procedure ProcessKTT812FlashData(aData:string); procedure ProcessKTT812FlashDataEnd; procedure ProcessKTT812EcuFirmWareDownloadComplete(aECUID:string); procedure ProcessKTT812EcuFirmWareDownloadFailed(aECUID,aFailState:string); procedure GageMonitor(aEcuID,aPacketData:string); end; var fm812Firmware: Tfm812Firmware; implementation uses uUtil, dllFunction, uCommon, uSocket, uMain; {$R *.dfm} procedure Tfm812Firmware.btnCloseClick(Sender: TObject); begin Close; end; procedure Tfm812Firmware.Ecu_GroupCreate; var i : integer; nIndex : integer; begin Group_812.Items.Clear; for I:= 0 to 15 do begin Group_812.Items.Add(FillZeroNumber(i,2)); nIndex := DeviceList.IndexOf(FillZeroNumber(i,2)); if nIndex > -1 then begin if TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT812 then begin if TCurrentDeviceState(DeviceList.Objects[nIndex]).Connected then begin if i <> 0 then Group_812.ItemChecked[i]:= True; end; end; end; end; Group_812.ItemChecked[0]:= True; end; procedure Tfm812Firmware.FormCreate(Sender: TObject); var ini_fun : TiniFile; begin Ecu_GroupCreate; KTT812FIRMWARECMDList := TStringList.Create; KTT812DownloadList := TStringList.Create; fmMain.L_bKTT812FirmwareDownLoadShow := True; Try ini_fun := TiniFile.Create(ExtractFileDir(Application.ExeName) + '\ztcs.INI'); ed_FirmwareFile.Text := ini_fun.ReadString('812FirmWare','FileName',''); Finally ini_fun.Free; End; if FileExists(ed_FirmwareFile.Text) then btnFirmwareUpdate.Enabled := True; end; procedure Tfm812Firmware.Group_812Change(Sender: TObject; Index: Integer; NewState: TCheckBoxState); var nIndex : integer; bChek : Boolean; i : integer; begin if Index = 0 then begin // if Not G_b812MainFirmWareDownloadComplete then // Group_812.ItemChecked[Index]:= True; { if Group_812.ItemChecked[Index] then begin for i := 1 to Group_812.Items.Count - 1 do begin if Group_812.ItemChecked[i] then bChek := True; Group_812.ItemChecked[i]:= False; end; end; } end else begin if NewState = cbUnchecked then Exit; nIndex := DeviceList.IndexOf(FillZeroNumber(Index,2)); if nIndex < 0 then begin Group_812.ItemChecked[Index]:= False; showmessage('등록되지 않은 컨트롤러입니다.'); Exit; end; {if Not TCurrentDeviceState(DeviceList.Objects[nIndex]).Connected then begin Group_812.ItemChecked[Index]:= False; showmessage('해당 컨트롤러는 통신연결 상태가 아닙니다.'); Exit; end;} if (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = KTT811) or (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = ICU100) or (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = ICU200) or (TCurrentDeviceState(DeviceList.Objects[nIndex]).DeviceType = ACC100) then begin Group_812.ItemChecked[Index]:= False; showmessage('KTT811G 컨트롤러가 아닙니다.'); Exit; end; if Group_812.ItemChecked[Index] then begin {if Group_812.ItemChecked[0] then begin Group_812.ItemChecked[0] := False; bChek := True; end; } end; end; //if bChek then showmessage('주장치와 가입자확장기는 동시에 업그레이드 할 수 없습니다.' + #13 + '가입자확장기는 주장치 펌웨어 업그레이드 후 진행하여 주세요'); end; procedure Tfm812Firmware.btnFirmwareUpdateClick(Sender: TObject); var bArmMode : Boolean; i : integer; bFirmwareStart : Boolean; st812ControlerNum : string; begin //bArmMode := CheckArmMode; btnFirmwareUpdate.Enabled := False; {if bArmMode then begin showmessage('경계중인 컨트롤러가 있습니다.펌웨어 업데이트를 진행 하시려면 모든 컨트롤러를 해제모드로 변경 하셔야 합니다.'); btnFirmwareUpdate.Enabled := True; Exit; end; } if Not FileExists(ed_FirmwareFile.Text) then begin showmessage('파일이 존재하지 않습니다.'); btnFirmwareUpdate.Enabled := True; Exit; end; if Not KTT812FileLoad(ed_FirmwareFile.Text) then begin showmessage('메모리 로드에 실패 했습니다.'); btnFirmwareUpdate.Enabled := True; Exit; end; btnClose.Enabled := False; GroupBox1.Enabled := False; MessageTimer.Enabled := True; if Group_812.ItemChecked[0] then begin L_bMainFirmWareDownLoadFail := False; KTT812MainControlerFirmWareUpdate; Delay(1000); for i := 0 to 10 do begin if L_bMainFirmWareDownLoadFail then Exit; bFirmwareStart := KTT812FirmWareStart; if bFirmwareStart then break; KTT812MainControlerFirmWareUpdate;//STX 전문을 다시 한번 전송 Delay(1000); end; if Not bFirmwareStart then begin showmessage('Firmware 가능 버젼인지 확인 하여 주세요.'); FirmwareUpdateEnd; end; end else begin fmMain.ReconnectSocketTimer.Enabled := True; st812ControlerNum := Get812ControlerNum(Group_812); dmSocket.KTT812BroadFirmWareStarting := False; //한번이라도 응답 오면 성공한것임 KTT812ExtendBroadCastStart(st812ControlerNum); end; end; procedure Tfm812Firmware.btn_FileSearchClick(Sender: TObject); begin SaveDialog1.Title:= 'FTP 다운로드 파일 찾기'; SaveDialog1.DefaultExt:= ''; SaveDialog1.Filter := 'HEX files (*.hex)|*.hex'; if SaveDialog1.Execute then begin ed_FirmwareFile.Text := SaveDialog1.FileName; btnFirmwareUpdate.Enabled := True; end; end; function Tfm812Firmware.CheckArmMode: Boolean; var i : integer; nIndex : integer; begin result := False; for i := 0 to 15 do begin if Group_812.ItemChecked[i] then begin nIndex := DeviceList.IndexOf(FillZeroNumber(i,2)); if nIndex < 0 then continue; if TCurrentDeviceState(DeviceList.Objects[nIndex]).AlarmMode = cmArm then result := True; end; end; end; function Tfm812Firmware.KTT812FileLoad(aFileName: string): Boolean; var KTT812FirmWareList : TStringList; i : integer; stTemp : string; begin result := False; KTT812FirmWareMemoryClear; KTT812FirmWareList := TStringList.create; Try KTT812FirmWareList.LoadFromFile(aFileName); for i := 0 to KTT812FirmWareList.Count - 1 do begin if Not KTT812FirmWareMemorySave(KTT812FirmWareList.Strings[i]) then Exit;; end; Finally KTT812FirmWareList.Free; End; result := True; end; procedure Tfm812Firmware.KTT812FirmWareMemoryClear; var i : integer; begin for i := 0 to HIGH(L_cKTT812Firmware) do begin L_cKTT812Firmware[i] := Char(StrToIntDef('$FF',0)); end; L_stKTT812OFFSET := ''; end; function Tfm812Firmware.KTT812FirmWareMemorySave(aData: string): Boolean; var stASCIIData : string; stDataLen : string; nDataLen : integer; stCSData : string; stMakeCSData : string; stStartAddress : string; stGubun : string; stData : string; nStartAddress : integer; i : integer; begin //Intel hex File 을 메모리에 로드 하자 result := False; stDataLen := copy(aData,2,2); nDataLen := Hex2Dec(stDataLen); stStartAddress := copy(aData,4,4); stGubun := copy(aData,8,2); stData := copy(aData,10,nDataLen * 2); stCSData := copy(aData,10 + (nDataLen * 2) ,2); stASCIIData := Hex2Ascii(stDataLen + stStartAddress + stGubun + stData); stMakeCSData := MakeCSData(stASCIIData,G_nProgramType); if stCSData <> stMakeCSData then Exit; delete(stASCIIData,1,4); //순수 Data 영역만 남기자. result := True; if stGubun = '01' then Exit; // File End; if stGubun = '02' then //OFFSET을 추출하여 StartAddress를 추출 하자. begin L_stKTT812OFFSET := stData + '0'; Exit; end else if stGubun = '03' then //OFFSET을 추출하여 StartAddress를 추출 하자. begin L_stKTT812OFFSET := stData; if Length(L_stKTT812OFFSET) < 8 then L_stKTT812OFFSET := FillZeroStrNum(L_stKTT812OFFSET,8,False); Exit; end else if stGubun = '04' then //OFFSET을 추출하여 StartAddress를 추출 하자. begin L_stKTT812OFFSET := stData; if Length(L_stKTT812OFFSET) < 8 then L_stKTT812OFFSET := FillZeroStrNum(L_stKTT812OFFSET,8,False); Exit; end else if stGubun = '05' then //OFFSET을 추출하여 StartAddress를 추출 하자. begin L_stKTT812OFFSET := stData; if Length(L_stKTT812OFFSET) < 8 then L_stKTT812OFFSET := FillZeroStrNum(L_stKTT812OFFSET,8,False); Exit; end; if L_stKTT812OFFSET <> '' then begin nStartAddress := Hex2Dec(L_stKTT812OFFSET) + Hex2Dec(stStartAddress) end else nStartAddress := Hex2Dec(stStartAddress); for i := nStartAddress to nStartAddress + nDataLen - 1 do begin if i > HIGH(L_cKTT812Firmware) then Exit; L_cKTT812Firmware[i] := stASCIIData[i - nStartAddress + 1]; end; end; function Tfm812Firmware.KTT812MemoryFileSave: Boolean; var st: string; iFileHandle: Integer; begin { iFileHandle := FileOpen('c:\812KTFirmware.log', fmOpenWrite); FileSeek(iFileHandle,0,0); FileWrite(iFileHandle, L_cKTT812Firmware[0], HIGH(L_cKTT812Firmware) + 1); Fileclose(iFileHandle); } end; procedure Tfm812Firmware.KTT812MainControlerFirmWareUpdate; var stData : string; begin //KTT812MemoryFileSave; stData := 'fw10'; stData := stData + '1'; //Monitoring stData := stData + '1'; //Gauge stData := stData + ' 60000000000000000'; //메인 펌웨어 업데이트 dmSocket.DirectSendPacket('00','R',stData,True); fmMain.ReconnectSocketTimer.Enabled := False; end; function Tfm812Firmware.KTT812FirmWareStart:Boolean; var stAsciiData : string; stHexData : string; FirstTickCount : LongInt; begin result := False; dmSocket.KTT812FirmwareDownLoadType := True; //KTT812FirmWareDownLoadType 진입 L_nLastPage := GetKTT812FlashDataLen; Gauge_812F00.MaxValue := L_nLastPage; stAsciiData:= 'Fbu010000000,' + FillZeroNumber2(L_nLastPage,7) + ' 1000000000000000'; stHexData := ASCII2Hex(stAsciiData); L_bENQStop := True; //ENQ는 전송 하지 말자. //dmSocket.KTT812FirmwareStarting := False; //한번이라도 펌웨어 진행이 되면 계속 진행 시킴 KTT812FIRMWARECMDList.Add('20' + stHexData); Ktt812FirmwareDownloadStart.Interval := 500; Ktt812FirmwareDownloadStart.Enabled := True; while KTT812FIRMWARECMDList.Count > 0 do begin Application.ProcessMessages; end; Delay(500); if Not dmSocket.KTT812FirmwareStarting then Exit; //10회 재시도 하자. dmSocket.SendBufferClear; result := True; Delay(1000); stAsciiData:= 'Fbi014F00004F0000FD00004B0000F80000FD0000' ; stHexData := ASCII2Hex(stAsciiData); dmSocket.KTT812FirmwareStarting := False; FirstTickCount := GetTickCount; while Not dmSocket.KTT812FirmwareStarting do begin KTT812FIRMWARECMDList.Add('20' + stHexData); //여기에서 부터 펌웨어 데이터 BroadCast 한다. while KTT812FIRMWARECMDList.Count > 0 do begin Application.ProcessMessages; end; end; //Delay(1000); Ktt812FirmwareDownloadStart.Interval := 200; BroadKTT812FileDownLoad; Ktt812FirmwareDownloadStart.Interval := 500; stAsciiData:= 'Fbc014F00004F0000FD00004B0000F80000FD0000' ; stHexData := ASCII2Hex(stAsciiData); dmSocket.KTT812FirmwareStarting := False; while Not dmSocket.KTT812FirmwareStarting do begin KTT812FIRMWARECMDList.Add('20' + stHexData); //여기에서 부터 펌웨어 데이터 BroadCast 한다. while KTT812FIRMWARECMDList.Count > 0 do begin Application.ProcessMessages; end; end; L_bENQStop := False; end; function Tfm812Firmware.GetKTT812FlashDataLen: integer; var i : integer; nStartPosition : integer; cCheck : Char; nDataLen : integer; nPageLen : integer; begin result := 0; cCheck := char(Hex2Dec('FF')); nStartPosition := Hex2Dec64('3F000') - 1; for i := nStartPosition downto 0 do begin if L_cKTT812Firmware[i] <> cCheck then begin nDataLen := i; break; end; end; nPageLen := nDataLen div KTT812PAGESIZE; if (nDataLen mod KTT812PAGESIZE) = 0 then result := nPageLen else result := nPageLen + 1; end; procedure Tfm812Firmware.Ktt812FirmwareDownloadStartTimer(Sender: TObject); var stCmd : string; stData : string; begin if KTT812FIRMWARECMDList.Count < 1 then begin if Not dmSocket.KTT812FirmwareDownLoadType then begin Ktt812FirmwareDownloadStart.Enabled := False; //Timer 종료 후 Exit; end; if Not L_bENQStop then begin Ktt812FirmwareDownloadStart.Interval := 200; //전송 모드로 진입 KTT812ENQTimer.Interval := 400; if KTT812ENQTimer.Enabled = False then KTT812ENQTimer.Enabled := True; //ENQ Timer 호출 end; Exit; end; Try KTT812ENQTimer.Enabled := False; Ktt812FirmwareDownloadStart.Enabled := False; if dmsocket.SocketOutSenting then begin dmsocket.SocketOutSenting := False; Exit; end; dmsocket.SocketOutSenting := True; stData := KTT812FIRMWARECMDList.Strings[0]; KTT812FIRMWARECMDList.Delete(0); stCmd := copy(stData,1,2); Delete(stData,1,2); dmSocket.SendKTT812FirmWarePacket(stCmd,stData); Finally Ktt812FirmwareDownloadStart.Enabled := True; End; end; procedure Tfm812Firmware.KTT812ENQTimerTimer(Sender: TObject); begin if L_bENQStop then exit; if KTT812FIRMWARECMDList.IndexOf('05') < 0 then KTT812FIRMWARECMDList.Add('05'); end; procedure Tfm812Firmware.BroadKTT812FileDownLoad; var nStartPosition : int64; stAsciiData : string; i : integer; stHexData : string; nPage : integer; begin lb_gauge.Caption := 'MCU BroadCast'; for nPage := 0 to L_nLastPage - 1 do begin nStartPosition := nPage * KTT812PAGESIZE; stAsciiData := ''; for i := nStartPosition to nStartPosition + KTT812PAGESIZE -1 do begin stAsciiData := stAsciiData + L_cKTT812Firmware[i]; end; stAsciiData := 'Fbd01' + FillzeroNumber2(nPage + 1,7) + stAsciiData; stHexData := Ascii2Hex(stAsciiData); KTT812FIRMWARECMDList.Add('2A' + stHexData); while KTT812FIRMWARECMDList.Count > 0 do begin Application.ProcessMessages; end; Gauge_812F00.Progress := nPage + 1; end; end; procedure Tfm812Firmware.FormClose(Sender: TObject; var Action: TCloseAction); var ini_fun : TiniFile; begin dmSocket.KTT812FirmwareDownLoadType := False; fmMain.L_bKTT812FirmwareDownLoadShow := False; Try ini_fun := TiniFile.Create(ExtractFileDir(Application.ExeName) + '\ztcs.INI'); ini_fun.WriteString('812FirmWare','FileName',ed_FirmwareFile.Text); Finally ini_fun.Free; End; end; procedure Tfm812Firmware.ProcessKTT812FlashData(aData: string); var nStartPosition : int64; stAsciiData : string; i : integer; stHexData : string; nPage : int64; begin if Not isDigit(aData) then Exit; Gauge_812F00.Progress := strtoint(aData); lb_gauge.Caption := 'MCU FlashData'; nPage := strtoint(aData) - 1; nStartPosition := nPage * KTT812PAGESIZE; stAsciiData := ''; for i := nStartPosition to nStartPosition + KTT812PAGESIZE -1 do begin stAsciiData := stAsciiData + L_cKTT812Firmware[i]; end; stAsciiData := 'FfD01' + aData + stAsciiData; stHexData := Ascii2Hex(stAsciiData); KTT812FIRMWARECMDList.Add('20' + stHexData); end; procedure Tfm812Firmware.ProcessKTT812FlashDataEnd; var stAsciiData : string; st812ControlerNum : string; begin stAsciiData := 'FFX01'; KTT812FIRMWARECMDList.Add('20' + Ascii2Hex(stAsciiData)); Gauge_812F00.Progress := Gauge_812F00.MaxValue; //이부분은 나중에 수정 //FirmwareUpdateEnd; //fmMain.ReconnectSocketTimer.Enabled := True; st812ControlerNum := Get812ControlerNum(Group_812); DeviceFirmWareDownloadComplete('00'); G_b812MainFirmWareDownloadComplete := True; //메인 펌웨어 다운로드 완료. dmSocket.KTT812BroadFirmWareStarting := False; //한번이라도 응답 오면 성공한것임 KTT812ExtendBroadCastStart(st812ControlerNum); end; procedure Tfm812Firmware.FirmwareUpdateEnd; begin GroupBox1.Enabled := True; btnClose.Enabled := True; btnFirmwareUpdate.Enabled := True; MessageTimer.Enabled := False; Panel1.Visible := False; end; procedure Tfm812Firmware.KTT812ExtendBroadCastStart(a812ControlerNum:string); var stDeviceID : string; stData : string; PastTime : dword; nRetryCount : integer; begin stData := 'fw10'; stData := stData + '1'; stData := stData + '1'; //st812ControlerNum := Get812ControlerNum(Group_812); a812ControlerNum[1] := '0'; if copy(a812ControlerNum,1,16) = '0000000000000000' then begin FirmwareUpdateEnd; Exit; end; stData := stData + ' ' + a812ControlerNum; //브로드캐스트 펌웨어 업데이트 nRetryCount := 0; While Not dmSocket.KTT812BroadFirmWareStarting do begin if Not dmSocket.SocketConnected then begin dmSocket.KTT812BufferClear; delay(3000); continue; end; dmSocket.DirectSendPacket('00','R',stData,True); Delay(10000); inc(nRetryCount); if nRetryCount > 10 then begin showmessage('응답이 없습니다. 재시도 하세요.'); btnFirmwareUpdate.Enabled := True; Exit; end; end; { dmSocket.DirectSendPacket('00','R',stData,True); PastTime := GetTickCount + 10000; //1초간 대기하자 while Not dmSocket.KTT812BroadFirmWareStarting do begin if GetTickCount > PastTime then break; //1000밀리동안 응답 없으면 실패로 처리함 Application.ProcessMessages; end; if Not dmSocket.KTT812BroadFirmWareStarting then begin showmessage('응답이 없습니다. 재시도 하세요.'); btnFirmwareUpdate.Enabled := True; end; } end; function Tfm812Firmware.Get812ControlerNum( CheckGroup: TRZCheckGroup): String; var nTemp : array[0..8, 0..7] of Integer; i,j,k : Integer; stTemp: String; stHex:String; nDecimal: Integer; FirmWare812Gauge : TGauge; FirmWare812Label : TLabel; begin stHex := '0'; for i:=1 to 15 do begin stHex := stHex + '0'; end; KTT812DownloadList.Clear; //체크 되어 있는 위치에 데이터를 넣는다. for k:= 0 to 15 do begin if CheckGroup.ItemChecked[k] = True then begin stHex[k+1] := '6'; KTT812DownloadList.Add(FillZeroNumber(k,2)); end; end; Result:=stHex; end; procedure Tfm812Firmware.ProcessKTT812EcuFirmWareDownloadComplete( aECUID: string); begin DeviceFirmWareDownloadComplete(aEcuID); end; procedure Tfm812Firmware.DeviceFirmWareDownloadComplete(aEcuID: string); var nIndex : integer; begin memo1.Lines.Add(aEcuid + ':Download Completed'); if aEcuID = '00' then begin While KTT812FIRMWARECMDList.Count > 0 do begin Application.ProcessMessages; end; end else FirmwareUpdateEnd; nIndex := KTT812DownloadList.IndexOf(aEcuID); if nIndex > -1 then KTT812DownloadList.Delete(nIndex); if KTT812DownloadList.Count = 0 then begin FirmwareUpdateEnd; //메인 펌웨어 업데이트 종료 end; end; procedure Tfm812Firmware.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 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,' '); lb_gauge.Caption := 'ECU DownLoad'; if isDigit(stMax) and isdigit(stPrograss) then begin Gauge_812F00.MaxValue := strtoint(stMax); Gauge_812F00.Progress := strtoint(stPrograss); end; Application.ProcessMessages; end; procedure Tfm812Firmware.DeviceFirmWareDownloadFailed(aEcuID, aFailState: string); var nIndex : integer; begin if aEcuID = '00' then begin L_bMainFirmWareDownLoadFail := True; showmessage('메인컨트롤러의 [' + aFailState + '] 상태로 펌웨어 업데이트가 종료 됩니다.'); KTT812DownloadList.Clear; FirmwareUpdateEnd; Exit; end; nIndex := KTT812DownloadList.IndexOf(aEcuID); if nIndex > -1 then memo1.Lines.Add(aEcuid + ':[' + aFailState + ']Download Failed'); if nIndex > -1 then KTT812DownloadList.Delete(nIndex); if KTT812DownloadList.Count = 0 then begin FirmwareUpdateEnd; end; end; procedure Tfm812Firmware.ProcessKTT812EcuFirmWareDownloadFailed(aECUID, aFailState: string); begin DeviceFirmWareDownloadFailed(aEcuID,aFailState); end; procedure Tfm812Firmware.N1Click(Sender: TObject); begin Close; end; procedure Tfm812Firmware.MessageTimerTimer(Sender: TObject); begin Panel1.Visible := Not Panel1.Visible; end; end.
unit Model.PlanilhaBaixasTFO; interface uses Generics.Collections, System.Classes, System.SysUtils, System.StrUtils; type TPlanilhaBaixasTFO = class private FCodigoClienteTFO: integer; FDataEntrega: TDate; FPesoCobrado: double; FDataPrevisaoEntrega: TDate; FDescricaoTipoPeso: string; FCodigoAgenteTFO: integer; FNomeEntregador: string; FObseervacoes: string; FDataUltimaAtribuicao: TDateTime; FDocumento: string; FHoraEntrega: TTime; FGrauRelacionamento: string; FNomeUsuario: string; FNumeroPedido: string; FDataDigitacao: TDate; FRecebedor: string; FNomeAgenteTFO: string; FNNRemessa: string; FCodigoEntregador: integer; FMensagemProcesso: string; FPlanilha: TObjectList<TPlanilhaBaixasTFO>; public property NNRemessa: string read FNNRemessa write FNNRemessa; property DataEntrega: TDate read FDataEntrega write FDataEntrega; property HoraEntrega: TTime read FHoraEntrega write FHoraEntrega; property Recebedor: string read FRecebedor write FRecebedor; property GrauRelacionamento: string read FGrauRelacionamento write FGrauRelacionamento; property Documento: string read FDocumento write FDocumento; property CodigoEntregador: integer read FCodigoEntregador write FCodigoEntregador; property NomeEntregador: string read FNomeEntregador write FNomeEntregador; property DataUltimaAtribuicao: TDateTime read FDataUltimaAtribuicao write FDataUltimaAtribuicao; property Obseervacoes: string read FObseervacoes write FObseervacoes; property NomeUsuario: string read FNomeUsuario write FNomeUsuario; property DataDigitacao: TDate read FDataDigitacao write FDataDigitacao; property CodigoClienteTFO: integer read FCodigoClienteTFO write FCodigoClienteTFO; property NumeroPedido: string read FNumeroPedido write FNumeroPedido; property DataPrevisaoEntrega: TDate read FDataPrevisaoEntrega write FDataPrevisaoEntrega; property CodigoAgenteTFO: integer read FCodigoAgenteTFO write FCodigoAgenteTFO; property NomeAgenteTFO: string read FNomeAgenteTFO write FNomeAgenteTFO; property PesoCobrado: double read FPesoCobrado write FPesoCobrado; property DescricaoTipoPeso: string read FDescricaoTipoPeso write FDescricaoTipoPeso; property MensagemProcesso: string read FMensagemProcesso; property Planilha: TObjectList<TPlanilhaBaixasTFO> read FPlanilha; function GetPlanilha(sFile: String): boolean; end; implementation { TPlanilhaBaixasTFO } uses Common.Utils; function TPlanilhaBaixasTFO.GetPlanilha(sFile: String): boolean; var ArquivoCSV: TextFile; sLinha, sCampo: string; sDetalhe: TStringList; i: integer; begin Result := False; if not FileExists(sFile) then begin FMensagemProcesso := 'Arquivo ' + sFile + ' não foi encontrado!'; Exit; end; FPlanilha := TObjectList<TPlanilhaBaixasTFO>.Create; AssignFile(ArquivoCSV, sFile); if sFile.IsEmpty then begin FMensagemProcesso := 'Arquivo ' + sFile + ' não foi encontrado!'; CloseFile(ArquivoCSV); Exit; end; sDetalhe := TStringList.Create; sDetalhe.StrictDelimiter := True; sDetalhe.Delimiter := ';'; Reset(ArquivoCSV); Readln(ArquivoCSV, sLinha); if Copy(sLinha, 0, 22) <> 'CONSULTA DE PROTOCOLOS' then begin FMensagemProcesso := 'Arquivo informado não foi identificado como a Planilha de Baixas de Protocolos TFO!'; CloseFile(ArquivoCSV); Exit; end; sDetalhe.DelimitedText := sLinha; if sDetalhe.Count <> 19 then begin FMensagemProcesso := 'Quantidade de Colunas não indica ser da Planilha de Baixas de Protocolos TFO!'; CloseFile(ArquivoCSV); Exit; end; i := 0; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha + ';'; if TUtils.ENumero(sDetalhe[0]) then begin FPlanilha.Add(TPlanilhaBaixasTFO.Create); i := Pred(FPlanilha.Count); FPlanilha[i].NNRemessa := sDetalhe[0]; FPlanilha[i].DataEntrega := StrToDateDef(sDetalhe[1],StrToDate('31/12/1899')); FPlanilha[i].HoraEntrega := StrToTimeDef(sDetalhe[2],StrToTime('23:59:59')); FPlanilha[i].Recebedor := sDetalhe[3]; FPlanilha[i].GrauRelacionamento := sDetalhe[4]; FPlanilha[i].Documento:= sDetalhe[5]; FPlanilha[i].CodigoEntregador := StrToIntDef(sDetalhe[6], 0); FPlanilha[i].NomeEntregador := sDetalhe[7]; FPlanilha[i].DataUltimaAtribuicao := StrToDateTimeDef(sDetalhe[8], StrToDateTime('31/12/1899 23:59:59')); FPlanilha[i].Obseervacoes := sDetalhe[9]; FPlanilha[i].NomeUsuario := sDetalhe[10]; FPlanilha[i].DataDigitacao := StrToDateDef(Copy(sDetalhe[11],0,10), StrToDateTime('31/12/1899')); FPlanilha[i].CodigoClienteTFO := StrToInt(sDetalhe[12]); FPlanilha[i].NumeroPedido := sDetalhe[13]; FPlanilha[i].DataPrevisaoEntrega := StrToDateDef(sDetalhe[14], StrToDate('31/12/1899')); FPlanilha[i].CodigoAgenteTFO := StrToInt(sDetalhe[15]); FPlanilha[i].NomeAgenteTFO := sDetalhe[16]; sCampo := sDetalhe[17]; sCampo := ReplaceStr(sCampo, ' KG', ''); sCampo := ReplaceStr(sCampo, '.', ','); FPlanilha[i].PesoCobrado := StrToFloatDef(sCampo,0); FPlanilha[i].DescricaoTipoPeso := sDetalhe[18]; end; end; CloseFile(ArquivoCSV); if FPlanilha.Count = 0 then begin FMensagemProcesso := 'Nenhuma informação foi importada da planilha!'; Exit; end; Result := True; end; end.
program oddEven1(input, output); var k : integer; procedure announceOddEven(i: integer); var isEven : boolean; procedure odd(n: integer; var b : boolean); forward; procedure even(n : integer; var b : boolean); begin if n = 0 then b := true else odd(n - 1, b) end; { even } procedure odd; begin if n = 0 then b := false else even(n - 1, b) end; { odd } begin even(i, isEven); if isEven then writeln('The value was even.') else writeln('The value was odd.') end; { announceOddEven } begin write('Value of k: '); read(k); announceOddEven(k); end.
// **************************************************************************** // * An Outlook style sidebar component for Delphi. // **************************************************************************** // * Copyright 2001-2005, Bitvadász Kft. All Rights Reserved. // **************************************************************************** // * This component can be freely used and distributed in commercial and // * private environments, provied this notice is not modified in any way. // **************************************************************************** // * Feel free to contact me if you have any questions, comments or suggestions // * at support@maxcomponents.net // **************************************************************************** // * Description: // * // * The TmxOutlookBar 100% native VCL component with many added features to // * support the look, feel, and behavior introduced in Microsoft Office 97, // * 2000, and new Internet Explorer. It has got many features including // * scrolling headers, icon highlighting and positioning, small and large // * icons,gradient and bitmap Backgrounds. The header sections and buttons // * can be added, deleted and moved at design time. The header tabs can // * have individual font, alignment, tabcolor, glyph, tiled Background // * images. And many many more posibilities. // **************************************************************************** Unit mxOutlookBarReg; Interface {$I max.inc} // ************************************************************************************* // ** Component registration // ************************************************************************************* Procedure Register; Implementation {$IFDEF DELPHI4_UP} {$R *.DCR} {$ENDIF} // ************************************************************************************* // ** List of used units // ************************************************************************************* Uses SysUtils, Classes, {$IFDEF Delphi6_up} DesignIntf, DesignEditors, {$ELSE}Dsgnintf,{$ENDIF} Dialogs, Forms, mxOutlookBarAbout, mxOutlookBar; Type {$IFNDEF DELPHI4_UP} IDesigner = TDesigner; {$ELSE} {$IFDEF DELPHI6_UP} TFormDesigner = IDesigner; {$ELSE} TFormDesigner = IFormDesigner; {$ENDIF} {$ENDIF} TDesigner = IDesigner; // ************************************************************************************* // ** Component Editor // ************************************************************************************* TmxOutlookBarEditor = Class( TComponentEditor ) Function GetVerbCount: integer; Override; Function GetVerb( Index: integer ): String; Override; Procedure ExecuteVerb( Index: integer ); Override; End; // ************************************************************************************* // ** GetVerbCount // ************************************************************************************* Function TmxOutlookBarEditor.GetVerbCount: integer; Begin Result := 5; End; // ************************************************************************************* // ** GetVerb // ************************************************************************************* Function TmxOutlookBarEditor.GetVerb( Index: integer ): String; Begin Case Index Of 0: Result := 'TmxOutlookBar (C) 2001-2005 Bitvadász Kft.'; 1: Result := '&Add header'; 2: Result := '&Add button'; 3: Result := '-'; 4: Result := 'Arrange buttons'; End; End; // ************************************************************************************* // ** ExecuteVerb // ************************************************************************************* Procedure TmxOutlookBarEditor.ExecuteVerb( Index: integer ); Var ComponentDesigner: TFormDesigner; OutlookSideBar: TmxOutlookBar; OutlookSideBarHeader: TmxOutlookBarHeader; OutlookButton: TOutlookButton; Begin ComponentDesigner := Designer; Case Index Of 0: ShowAboutBox( 'TmxOutlookBar Component' ); 1: Begin If ( Component Is TmxOutlookBar ) Then OutlookSideBar := ( Component As TmxOutlookBar ) Else OutlookSideBar := ( TmxOutlookBarHeader( Component ).Parent As TmxOutlookBar ); {$IFDEF DELPHI6_UP} OutlookSideBarHeader := TmxOutlookBarHeader.Create( ComponentDesigner.Root ); {$ELSE} OutlookSideBarHeader := TmxOutlookBarHeader.Create( ComponentDesigner.Form ); {$ENDIF} With OutlookSideBarHeader Do Begin Name := ComponentDesigner.UniqueName( 'Header' ); //TmxOutlookBarHeader.ClassName ); Caption := Name; Parent := OutlookSideBar; HeaderSettings.HeaderColor := OutlookSideBar.HeaderSettings.HeaderColor; End; OutlookSideBar.ActiveHeader := OutlookSideBarHeader; OutlookSideBar.Invalidate; ComponentDesigner.SelectComponent( OutlookSideBarHeader ); End; 2: Begin If ( Component Is TmxOutlookBarHeader ) Then Begin OutlookSideBarHeader := ( Component As TmxOutlookBarHeader ); {$IFDEF Delphi6_UP} OutlookButton := TOutlookButton.Create( ComponentDesigner.Root ); {$ELSE} OutlookButton := TOutlookButton.Create( ComponentDesigner.Form ); {$ENDIF} With OutlookButton Do Begin Name := ComponentDesigner.UniqueName( 'Button' ); Caption := Name; End; OutlookSideBarHeader.AddButton( OutlookButton ); ComponentDesigner.SelectComponent( OutlookButton ); End Else MessageDlg( 'You cannot add button to this component type. Please select or add a TmxOutlookBarHeader component before.', mtError, [ mbOK ], 0 ); End; 4: Begin If ( Component Is TmxOutlookBarHeader ) Then ( Component As TmxOutlookBarHeader ).SortButtons Else MessageDlg( 'Please select a TmxOutlookBarHeader component before.', mtError, [ mbOK ], 0 ); End; End; ComponentDesigner.Modified; End; // ************************************************************************************* // ** Register, 4/5/01 11:46:42 AM // ************************************************************************************* Procedure Register; Begin RegisterComponents( 'Max', [ TmxOutlookBar ] ); RegisterClasses( [ TmxOutlookBarHeader, TOutlookButton, TScrollButton, TmxOutlookBarHeader ]); RegisterComponentEditor( TmxOutlookBar, TmxOutlookBarEditor ); RegisterComponentEditor( TmxOutlookBarHeader, TmxOutlookBarEditor ); End; End.
unit l3FormattedLines; {* Список отформатированных строк. } { Библиотека "Эверест" } { Автор: Люлин А.В. © } { Модуль: l3FormattedLines - } { Начат: 18.07.2002 16:59 } { $Id: l3FormattedLines.pas,v 1.27 2014/02/18 13:34:30 lulin Exp $ } // $Log: l3FormattedLines.pas,v $ // Revision 1.27 2014/02/18 13:34:30 lulin // - избавляемся от ненужного списка. // // Revision 1.26 2013/04/04 11:33:02 lulin // - портируем. // // Revision 1.25 2012/10/26 19:42:24 lulin // - вычищаем поддержку ветки редактора. // // Revision 1.24 2011/05/23 14:25:46 dinishev // Bug fix: не открывались документы в Арчи в векте. // // Revision 1.23 2011/05/19 10:36:07 lulin // {RequestLink:266409354}. // // Revision 1.22 2011/05/18 18:01:07 lulin // {RequestLink:266409354}. // // Revision 1.21 2009/07/21 15:10:18 lulin // - bug fix: не собирался и не работал Архивариус в ветке. // // Revision 1.20 2008/02/20 18:35:00 lulin // - упрощаем наследование. // // Revision 1.19 2008/02/20 10:47:13 lulin // - удалена ненужная базовая функция очистки. // // Revision 1.18 2008/02/05 09:58:12 lulin // - выделяем базовые объекты в отдельные файлы и переносим их на модель. // // Revision 1.17 2007/10/29 14:16:06 oman // - fix: Более правильная починка ЦК16480 (cq27213) // // Revision 1.16 2007/08/14 19:31:59 lulin // - оптимизируем очистку памяти. // // Revision 1.15 2007/04/17 13:26:32 lulin // - bug fix: надписи на кнопках иногда нарезались не по словам, а внутри слова (CQ OIT5-25068). // // Revision 1.14 2007/04/09 08:30:28 lulin // - переименовываем класс в соответствии с библиотекой. // // Revision 1.13 2007/04/09 08:14:33 lulin // - cleanup. // // Revision 1.12 2007/04/09 07:12:17 lulin // - bug fix: неправильно обращались с юникодными символами. // // Revision 1.11 2007/04/03 14:18:12 lulin // - не пытаемся переформатировать однострочные заголовки. // // Revision 1.10 2007/04/03 13:52:56 lulin // - увеличиваем ширину кнопки так, чтобы текст в итоге влез, без всяких многоточий. // // Revision 1.9 2007/03/26 11:23:23 voba // - bug fix от Шуры // // Revision 1.8 2007/01/30 15:24:24 lulin // - текст ноды - теперь более простого типа. // // Revision 1.7 2007/01/10 15:22:25 lulin // - cleanup. // // Revision 1.6 2006/12/01 15:51:04 lulin // - cleanup. // // Revision 1.5 2006/01/31 13:59:01 mmorozov // - add comments; // // Revision 1.4 2006/01/31 13:55:56 mmorozov // - bugfix: при разбиении текста на строки, последовательно идущие символы конца строки (#10) и перевода каретки (#13) в любом порядке воспринимаются как перевод строки (CQ: 16480); // // Revision 1.3 2005/09/08 11:56:41 fireton // - откат предыдущих изменений (надо) // // Revision 1.2 2005/09/08 11:51:40 fireton // - change: TextExtend заменен на KerningTextExtend при подсчете размеров текста // // Revision 1.1 2005/05/24 13:53:33 lulin // - rename unit: evFormattedLines -> l3FormattedLines. // // Revision 1.18.4.2 2005/05/24 13:43:29 lulin // - rename unit: evLineAr -> l3LineArray. // // Revision 1.18.4.1 2005/05/18 12:42:46 lulin // - отвел новую ветку. // // Revision 1.17.2.2 2005/05/18 12:32:08 lulin // - очередной раз объединил ветку с HEAD. // // Revision 1.17.2.1 2005/04/28 09:18:29 lulin // - объединил с веткой B_Tag_Box. // // Revision 1.17.4.1 2005/04/26 14:30:39 lulin // - ускоряем l3Free и _l3Use. // // Revision 1.18 2005/04/28 15:03:37 lulin // - переложил ветку B_Tag_Box в HEAD. // // Revision 1.17.4.1 2005/04/26 14:30:39 lulin // - ускоряем l3Free и _l3Use. // // Revision 1.17 2005/04/07 13:45:23 mmorozov // bugfix: для пустой строки в MesuareStr не вычислялся размер (используем AverageCharHeight); // // Revision 1.16 2005/03/29 17:03:39 lulin // - пытаемся поменьше делать телодвижений при имерении длины строки. // // Revision 1.15 2005/02/22 12:27:39 lulin // - рефакторинг работы с Tl3Point и Tl3Rect. // // Revision 1.14 2005/02/18 18:59:20 lulin // - bug fix: параграф-дерево неправильно форматировался для вывода по принтерной канве. // // Revision 1.13 2005/02/18 18:06:32 lulin // - вызываем более быстрый метод поиска конца нарезаемой строки. // // Revision 1.12 2004/12/09 12:49:51 lulin // - bug fix: в Unicode-строках не учитывались Enter'ы. // // Revision 1.11 2004/12/08 08:49:39 lulin // - bug fix: было зависание при маленьких ширинах. // // Revision 1.10 2004/12/07 10:21:29 lulin // - добавлен Assert(aWidth >= 0). // // Revision 1.9 2004/12/04 11:54:05 mmorozov // bugfix: при разбиении текста по доступной ширине не правильно вычислялась длинна строки для unicode строк; // // Revision 1.8 2004/06/02 07:51:09 law // - bug fix: не собирался AllEverestComponents. // // Revision 1.7 2004/04/20 08:04:45 law // - bug fix: не компилировалось, в связи с изменениями Tl3PCharLen для Unicode. // // Revision 1.6 2003/05/12 09:20:23 law // - rename proc: ev_plIsNil -> l3IsNil. // // Revision 1.5 2003/04/15 15:13:57 law // - bug fix: не компилировался Эверест. // // Revision 1.4 2002/07/23 11:05:23 law // - new behavior: нарезаем на строки с учетом еще и cc_HardEnter. // // Revision 1.3 2002/07/19 05:38:36 law // - new behavior: сделана нарезка на строки с учетом cc_SoftEnter. // // Revision 1.2 2002/07/18 16:29:27 law // - new behavior: сделана нарезка на строки (пока без учета cc_SoftEnter). // // Revision 1.1 2002/07/18 13:06:46 law // - new unit: evFormattedLines. // {$Include l3Define.inc } interface uses l3Types, l3Interfaces, l3InternalInterfaces, l3Base, l3ObjectRefList, l3ProtoObjectRefList, l3ProtoPersistentRefList ; type Tl3FormattedLines = class(Tl3ProtoObjectRefList, Il3MultiLines) {* Список отформатированных строк. } private // internal fields f_HasBreakInWord : Boolean; public // public methods constructor Create; reintroduce; {-} function FormatLine(const aCanvas : Il3InfoCanvas; aLine : Long; const aStr : Tl3PCharLenPrim; aWidth : Long; const aMeasureCanvas : Il3InfoCanvas = nil): Tl3Inch; {-} function IsSingle: Boolean; {-} function HasBreakInWord: Boolean; {-} end;//Tl3FormattedLines implementation uses l3Chars, l3Units, l3Utils, l3String, l3LineArray ; // start class Tl3FormattedLines constructor Tl3FormattedLines.Create; //reintroduce; {-} begin f_HasBreakInWord := false; Make; end; function Tl3FormattedLines.FormatLine(const aCanvas : Il3InfoCanvas; aLine : Long; const aStr : Tl3PCharLenPrim; aWidth : Long; const aMeasureCanvas : Il3InfoCanvas = nil): Tl3Inch; {-} procedure AddEmpty; begin//AddEmpty if (aLine >= Count) then Count := Succ(aLine); Items[aLine] := nil; end;//AddEmpty function AddLines: TevBaseLineArray; begin//AddLines if (aLine >= Count) then Count := Succ(aLine); Result := Items[aLine] As TevBaseLineArray; if (Result = nil) then begin Result := TevBaseLineArray.Create; try Items[aLine] := Result; finally Result := Result.Free; end;//try..finally end//Result = nil else Result.Count := 0; end;//AddLines function AveHeight: Integer; begin// if (aMeasureCanvas = nil) OR (aMeasureCanvas = aCanvas) then Result := aCanvas.AverageCharHeight else begin aMeasureCanvas.Font := aCanvas.Font; Result := aMeasureCanvas.AverageCharHeight; end;//aMeasureCanvas = nil end;//AveHeight var l_Extent : Tl3Point; procedure MeasureStr(const aStr : Tl3PCharLenPrim; aEnter : Boolean); var lCanvas : Il3InfoCanvas; begin//MeasureStr l3FillChar(l_Extent, SizeOf(l_Extent), 0); if (aMeasureCanvas = nil) OR (aMeasureCanvas = aCanvas) then lCanvas := aCanvas else begin aMeasureCanvas.Font := aCanvas.Font; lCanvas := aMeasureCanvas; end; if l3IsNil(aStr) then l_Extent.Y := lCanvas.AverageCharHeight else l_Extent := lCanvas.TextExtent(aStr); if aEnter then Inc(l_Extent.P.X, 2 * lCanvas.AverageCharWidth); end;//MeasureStr var l_WrappedStr : Tl3PCharLen; l_Lines : TevBaseLineArray; l_Str : Tl3PCharLen; procedure DoAdd(aEnter: Boolean); begin//DoAdd MeasureStr(l_WrappedStr, aEnter); if (aStr.SCodePage = CP_Unicode) then l_Lines.Add((l_Str.S - aStr.S) div SizeOf(WideChar), l_Extent) else l_Lines.Add(l_Str.S - aStr.S, l_Extent); Inc(Result, l_Extent.Y); end;//DoAdd var l_SoftEnterCount : Long; l_WrapPos : Long; l_SoftEnterIndex : Long; {-позиция SoftEnter'а} l_NoTabs : Boolean; l_Char : AnsiChar; l_NextChar : AnsiChar; l_CRLFAdjust : Long; begin //Assert(aWidth >= 0); with aCanvas do begin if (aWidth < AverageCharWidth) then begin Result := AveHeight; AddEmpty; end//aWidth < AverageCharWidth else if l3IsNil(aStr) then begin Result := AveHeight; AddEmpty; end//l3IsNil(aStr) else begin l_Extent := TextExtent(aStr); l_SoftEnterCount := l3CountOfChar(cc_SoftEnter, aStr); Inc(l_SoftEnterCount, l3CountOfChar(cc_HardEnter, aStr)); if (l_Extent.X > aWidth) OR (l_SoftEnterCount > 0) then begin // - здесь нарезаем на строки Result := 0; Tl3PCharLenPrim(l_Str) := aStr; l_Lines := AddLines; l_NoTabs := false; while (l_Str.SLen > 0) do begin l_WrapPos := Pos2IndexQ(aWidth, l_Str, l_NoTabs); //l_WrapPos := Pos2Index(aWidth, l_Str); l_WrappedStr := l_Str; if (l_WrapPos = 0) then begin // - защита от бесконечного цикла if (Result = 0) then begin Result := AveHeight; AddEmpty; end;//Result = 0 break; end;//l_WrapPos = 0 with l_WrappedStr do begin if (l_WrapPos >= l_Str.SLen) then SLen := l_WrapPos else SLen := l3Utils.l3FindNextLine(l_WrappedStr, l_WrapPos); if (l_SoftEnterCount > 0) then begin {-еще есть SoftEnter'ы - надо их обработать} l_SoftEnterIndex := l3CharSetPresentEx(S, l_WrapPos, [cc_SoftEnter, cc_HardEnter], SCodePage); if (l_SoftEnterIndex >= 0) then begin Dec(l_SoftEnterCount); if SCodePage = CP_Unicode then l_Char := l3WideToChar(PWideChar(S)[l_SoftEnterIndex]) else l_Char := PAnsiChar(S)[l_SoftEnterIndex]; if l_SoftEnterIndex < SLen then begin if SCodePage = CP_Unicode then l_NextChar := l3WideToChar(PWideChar(S)[l_SoftEnterIndex + 1]) else l_NextChar := PAnsiChar(S)[l_SoftEnterIndex + 1]; end else l_NextChar := #0; if (l_Char = cc_HardEnter) and (l_NextChar = cc_SoftEnter) then l_CRLFAdjust := 1 else l_CRLFAdjust := 0; SLen := l_SoftEnterIndex; l_Str.InitPart(S, l_SoftEnterIndex + 1 + l_CRLFAdjust, l_Str.SLen - (SLen + 1) + l_SoftEnterIndex + 1, SCodePage); DoAdd(True); if (l_Str.SLen = 0) then break // - строка закончилась else continue; // - продолжаем форматировать остаток строки end;{l_SoftEnterIndex >= 0} end;{l_SoftEnterCount > 0} l_Str.Shift(SLen); end;//with l_WrappedStr if (l_Str.SLen > 0) AND not l3IsChar(l_WrappedStr, l_WrappedStr.SLen - 1, cc_HardSpace) then f_HasBreakInWord := true; DoAdd(False); end;//while (l_Str.SLen > 0) end else begin MeasureStr(aStr, false); Result := l_Extent.Y; AddEmpty; end;//l_Extent.X > aWidth end;//l3IsNil(aStr) end;//with aCanvas end; function Tl3FormattedLines.IsSingle: Boolean; {-} begin Result := (Count < 1) OR (First = nil) OR (TevBaseLineArray(First).Count <= 1); end; function Tl3FormattedLines.HasBreakInWord: Boolean; {-} begin Result := f_HasBreakInWord; end; end.
unit View.CadastroGeral; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, cxClasses, dxLayoutContainer, dxLayoutControl, cxContainer, cxEdit, dxLayoutcxEditAdapters, cxLabel, cxTextEdit, cxMaskEdit, cxDropDownEdit, Vcl.ComCtrls, dxCore, cxDateUtils, cxCalendar, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxDBEdit, cxCheckBox, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxNavigator, cxDBNavigator, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, dxDateRanges, cxDataControllerConditionalFormattingRulesManagerDialog, cxDBData, cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, System.Actions, Vcl.ActnList, dxBar, cxMemo, Common.ENum, Common.Utils, Control.Bancos, Control.Cadastro, Control.Estados, Control.CadastroEnderecos, Control.CadastroContatos, System.DateUtils ; type Tview_CadastroGeral = class(TForm) layoutControlPadraoGroup_Root: TdxLayoutGroup; layoutControlPadrao: TdxLayoutControl; maskEditID: TcxMaskEdit; layoutItemMaskID: TdxLayoutItem; comboBoxTipoPessoa: TcxComboBox; layoutItemComboBoxTipoPessoa: TdxLayoutItem; dxLayoutAutoCreatedGroup1: TdxLayoutAutoCreatedGroup; maskEditCPCNPJ: TcxMaskEdit; layoutItemCPFCNPJ: TdxLayoutItem; textEditNome: TcxTextEdit; layoutItemTextEditNome: TdxLayoutItem; layoutControlDadosGroup_Root: TdxLayoutGroup; layoutControlDados: TdxLayoutControl; layoutItemDadosGeral: TdxLayoutItem; layoutGroupPessoaFisica: TdxLayoutGroup; textEditRG: TcxTextEdit; layoutItemRG: TdxLayoutItem; textEditExpedidor: TcxTextEdit; layoutItemExpedidorRG: TdxLayoutItem; dateEditDataRG: TcxDateEdit; layoutItemDataRG: TdxLayoutItem; lookupComboBoxUFRG: TcxLookupComboBox; layoutItemUFRG: TdxLayoutItem; dateEditNascimento: TcxDateEdit; layoutItemNascimento: TdxLayoutItem; layoutGroupFisica1: TdxLayoutGroup; layoutGroupFisica2: TdxLayoutGroup; textEditNomePai: TcxTextEdit; layoutItemNomePai: TdxLayoutItem; textEditNomeMae: TcxTextEdit; layoutItemNomeMae: TdxLayoutItem; layoutGroupFisica3: TdxLayoutGroup; textEditNaturalidade: TcxTextEdit; layoutItemNaturalidade: TdxLayoutItem; lookupComboBoxNaturalidade: TcxLookupComboBox; layoutItemUFNaturalidade: TdxLayoutItem; layoutGroupFisica4: TdxLayoutGroup; textEditSegurancaCNH: TcxTextEdit; layoutItemCodigoSeguranca: TdxLayoutItem; textEditNumeroCNH: TcxTextEdit; layoutItemNumeroCNH: TdxLayoutItem; textEditRegistroCNH: TcxTextEdit; layoutItemRegistroCNH: TdxLayoutItem; textEditCategoriaCNH: TcxTextEdit; layoutItemCategoriaCNH: TdxLayoutItem; layoutGroupFisica5: TdxLayoutGroup; dateEditEmissaoCNH: TcxDateEdit; layoutItemDataEmissao: TdxLayoutItem; dateEditValidadeCNH: TcxDateEdit; layoutItemValidadeCNH: TdxLayoutItem; dateEditPrimeiraCNH: TcxDateEdit; layoutItemPrimeiraCNH: TdxLayoutItem; lookupComboBoxUFCNH: TcxLookupComboBox; layoutItemUFCNH: TdxLayoutItem; layoutGroupPessoaJuridica: TdxLayoutGroup; layoutGroupJuridica1: TdxLayoutGroup; textEditNomeFantasia: TcxTextEdit; layoutItemNomeFantasia: TdxLayoutItem; layoutGroupJuridica2: TdxLayoutGroup; textEditIE: TcxTextEdit; layoutItemIE: TdxLayoutItem; textEditIEST: TcxTextEdit; layoutItemIEST: TdxLayoutItem; textEditIM: TcxTextEdit; layoutItemIM: TdxLayoutItem; textEditCNAE: TcxTextEdit; layoutItemCNAE: TdxLayoutItem; comboBoxCRT: TcxComboBox; layoutItemCRT: TdxLayoutItem; layoutControlComplementoGroup_Root: TdxLayoutGroup; layoutControlComplemento: TdxLayoutControl; layoutItemComplemento: TdxLayoutItem; layoutGroupEnderecos: TdxLayoutGroup; layoutGroupContatos: TdxLayoutGroup; layoutGroupDadosBancarios: TdxLayoutGroup; memTableEnderecos: TFDMemTable; memTableEnderecosid_cadastro: TIntegerField; memTableEnderecosdes_tipo_endereco: TStringField; memTableEnderecosnum_cep: TStringField; memTableEnderecosdes_logradouro: TStringField; memTableEnderecosnum_logradouro: TStringField; memTableEnderecosdes_complemento: TStringField; memTableEnderecosnom_bairro: TStringField; memTableEnderecosnom_cidade: TStringField; memTableEnderecosuf_estado: TStringField; dsEnderecos: TDataSource; layoutGroupEndereco1: TdxLayoutGroup; dbComboBoxTipoEndereco: TcxDBComboBox; layoutItemTipoEndereco: TdxLayoutItem; LayoutGroupEndereco2: TdxLayoutGroup; dbMaskEditCEP: TcxDBMaskEdit; layoutItemCEP: TdxLayoutItem; dbTextEditEndereco: TcxDBTextEdit; layoutItemEndereco: TdxLayoutItem; dbTextEditNumero: TcxDBTextEdit; layoutItemNumero: TdxLayoutItem; dbTextEditComplemento: TcxDBTextEdit; layoutItemComplementoEndewreco: TdxLayoutItem; layoutGroupEndereco3: TdxLayoutGroup; dbTextEditBairro: TcxDBTextEdit; layoutItemBairro: TdxLayoutItem; dbTextEditCidade: TcxDBTextEdit; layoutItemCidade: TdxLayoutItem; dbLookupComboBoxUFEndereco: TcxDBLookupComboBox; layoutItemUFEndereco: TdxLayoutItem; memTableEnderecosseq_endereco: TIntegerField; memTableEnderecosdom_correspondencia: TIntegerField; memTableEnderecosdes_referencia: TStringField; layoutGroupEndereco4: TdxLayoutGroup; dbTextEditReferencia: TcxDBTextEdit; layoutItemReferencia: TdxLayoutItem; dbNavigatorEnderecos: TcxDBNavigator; layoutItemNavegadorEndereco: TdxLayoutItem; gridContatosDBTableView1: TcxGridDBTableView; gridContatosLevel1: TcxGridLevel; gridContatos: TcxGrid; layoutItemContatos: TdxLayoutItem; memTableContatos: TFDMemTable; memTableContatosid: TIntegerField; memTableContatosseq_contato: TIntegerField; memTableContatosdes_contato: TStringField; memTableContatosnum_telefone: TStringField; memTableContatosdes_email: TStringField; dsContatos: TDataSource; gridContatosDBTableView1id: TcxGridDBColumn; gridContatosDBTableView1seq_contato: TcxGridDBColumn; gridContatosDBTableView1des_contato: TcxGridDBColumn; gridContatosDBTableView1num_telefone: TcxGridDBColumn; gridContatosDBTableView1des_email: TcxGridDBColumn; LayoutGroupDadosBancarios1: TdxLayoutGroup; comboBoxFormaPagamento: TcxComboBox; layoutItemFormaPagamento: TdxLayoutItem; comboBoxTipoConta: TcxComboBox; layoutItemTipoConta: TdxLayoutItem; layoutGroupDadosBancarios2: TdxLayoutGroup; lookupComboBoxBanco: TcxLookupComboBox; layoutItemBanco: TdxLayoutItem; textEditAgencia: TcxTextEdit; layoutItemAgencia: TdxLayoutItem; textEditConta: TcxTextEdit; layoutItemConta: TdxLayoutItem; layoutGroupDadosBancarios3: TdxLayoutGroup; textEditFavorecido: TcxTextEdit; layoutItemFavorecido: TdxLayoutItem; maskEditCPFCNPJFavorecido: TcxMaskEdit; layoutItemCPFCNPJFavorecido: TdxLayoutItem; LayoutGrouPDadosBancarios4: TdxLayoutGroup; textEditChavePIX: TcxTextEdit; layoutItemChavePIX: TdxLayoutItem; actionListCadastro: TActionList; actionIncluir: TAction; actionEditar: TAction; actionLocalizar: TAction; actionCancelar: TAction; actionGravar: TAction; actionDocumentosVencidos: TAction; actionVencimentoGR: TAction; actionFechar: TAction; layoutGroupMaster: TdxLayoutGroup; layoutGroupCadastro: TdxLayoutGroup; actionFichaDIRECT: TAction; actionSolicitarGR: TAction; actionContrato: TAction; barManagerCadastro: TdxBarManager; barManagerCadastroBar1: TdxBar; dxBarButton1: TdxBarButton; dxBarButton2: TdxBarButton; dxBarButton3: TdxBarButton; dxBarButton4: TdxBarButton; dxBarButton5: TdxBarButton; dxBarSubItem1: TdxBarSubItem; dxBarSubItem2: TdxBarSubItem; dxBarButton6: TdxBarButton; dxBarButton7: TdxBarButton; dxBarButton8: TdxBarButton; dxBarButton9: TdxBarButton; dxBarButton10: TdxBarButton; dxBarButton11: TdxBarButton; dxBarButton12: TdxBarButton; dxBarButton13: TdxBarButton; layoutGroupComplementos: TdxLayoutGroup; layoutGroupGR: TdxLayoutGroup; checkBoxStatusGR: TcxCheckBox; layoutItemStatusGR: TdxLayoutItem; textEditEmpresaGR: TcxTextEdit; layoutItemEmpresaGR: TdxLayoutItem; dateEditValidadeGR: TcxDateEdit; layoutItemValidadeGR: TdxLayoutItem; textEditNumeroConsultaGR: TcxTextEdit; layoutItemNumeroConsultaGR: TdxLayoutItem; layoutGroupObs: TdxLayoutGroup; memoObservacoes: TcxMemo; layoutItemObservacoes: TdxLayoutItem; memTableEstados: TFDMemTable; memTableEstadosuf_estado: TStringField; memTableEstadosnom_estado: TStringField; memTableBancos: TFDMemTable; memTableBancoscod_banco: TStringField; memTableBancosnom_banco: TStringField; dsEstados: TDataSource; dsBancos: TDataSource; dbCheckBoxCorrespondencia: TcxDBCheckBox; layoutItemCorrespondencia: TdxLayoutItem; procedure comboBoxTipoPessoaPropertiesChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure actionIncluirExecute(Sender: TObject); procedure actionLocalizarExecute(Sender: TObject); procedure actionEditarExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure actionCancelarExecute(Sender: TObject); private { Private declarations } procedure ClearFields; procedure SetupFields(FCadastro: TCadastroControl); procedure PopulaBancos; procedure PopulaEstados; procedure PesquisaCadastro; procedure PopulaEnderecos(iCadastro: Integer); procedure PopulaContatos(iCadastro: Integer); procedure Modo; function ValidaDados(): boolean; public { Public declarations } end; var view_CadastroGeral: Tview_CadastroGeral; FAcao : TAcao; implementation {$R *.dfm} uses View.PesquisarPessoas; procedure Tview_CadastroGeral.actionCancelarExecute(Sender: TObject); begin if FAcao <> tacIndefinido then begin FAcao := tacIndefinido; Modo; end; end; procedure Tview_CadastroGeral.actionEditarExecute(Sender: TObject); begin Facao := tacAlterar; Modo; comboBoxTipoPessoa.SetFocus; end; procedure Tview_CadastroGeral.actionIncluirExecute(Sender: TObject); begin FAcao := tacIncluir; Modo; comboBoxTipoPessoa.SetFocus; end; procedure Tview_CadastroGeral.actionLocalizarExecute(Sender: TObject); begin PesquisaCadastro; end; procedure Tview_CadastroGeral.ClearFields; begin maskEditID.EditValue := 0; comboBoxTipoPessoa.ItemIndex := 0; maskEditCPCNPJ.Clear; textEditNome.Clear; textEditRG.Clear; textEditExpedidor.Clear; dateEditDataRG.Clear; lookupComboBoxUFRG.Clear; dateEditNascimento.Clear; textEditNomePai.Clear; textEditNomeMae.Clear; textEditNaturalidade.Clear; lookupComboBoxNaturalidade.Clear; textEditSegurancaCNH.Clear; textEditNumeroCNH.Clear; textEditRegistroCNH.Clear; textEditCategoriaCNH.Clear; dateEditEmissaoCNH.Clear; dateEditValidadeCNH.Clear; dateEditPrimeiraCNH.Clear; lookupComboBoxUFCNH.Clear; textEditNomeFantasia.Clear; textEditIE.Clear; textEditIEST.Clear; textEditIM.Clear; textEditCNAE.Clear; comboBoxCRT.ItemIndex := 0; if memTableEnderecos.Active then memTableEnderecos.Close; if memTableContatos.Active then memTableContatos.Close; comboBoxFormaPagamento.ItemIndex := 0; comboBoxTipoConta.ItemIndex := 0; lookupComboBoxBanco.Clear; textEditAgencia.Clear; textEditConta.Clear; textEditFavorecido.Clear; maskEditCPFCNPJFavorecido.Clear; textEditChavePIX.Clear; checkBoxStatusGR.Checked := False; textEditEmpresaGR.Clear; dateEditValidadeGR.Clear; textEditNumeroConsultaGR.Clear; memoObservacoes.Lines.Clear; end; procedure Tview_CadastroGeral.comboBoxTipoPessoaPropertiesChange(Sender: TObject); begin if comboBoxTipoPessoa.ItemIndex = 1 then begin layoutGroupPessoaFisica.MakeVisible; maskEditCPFCNPJFavorecido.Properties.ReadOnly := False; maskEditCPCNPJ.Properties.EditMask := '!000\.000\.000\-00;1; '; maskEditCPCNPJ.Properties.IgnoreMaskBlank := True; maskEditCPFCNPJFavorecido.Properties.EditMask := '!000\.000\.000\-00;1; '; maskEditCPFCNPJFavorecido.Properties.IgnoreMaskBlank := True; end else if comboBoxTipoPessoa.ItemIndex = 2 then begin layoutGroupPessoaJuridica.MakeVisible; maskEditCPFCNPJFavorecido.Properties.ReadOnly := False; maskEditCPCNPJ.Properties.EditMask := '!00\.000\.000\/0000\-00;1; '; maskEditCPCNPJ.Properties.IgnoreMaskBlank := True; maskEditCPFCNPJFavorecido.Properties.EditMask := '!000\.000\.000\-00;1; '; maskEditCPFCNPJFavorecido.Properties.IgnoreMaskBlank := True; end else begin layoutGroupPessoaFisica.MakeVisible; maskEditCPFCNPJFavorecido.Properties.ReadOnly := True; maskEditCPCNPJ.Properties.EditMask := '!000\.000\.000\-00;1; '; maskEditCPCNPJ.Properties.IgnoreMaskBlank := True; maskEditCPFCNPJFavorecido.Properties.EditMask := '!000\.000\.000\-00;1; '; maskEditCPFCNPJFavorecido.Properties.IgnoreMaskBlank := True; end; end; procedure Tview_CadastroGeral.FormClose(Sender: TObject; var Action: TCloseAction); begin if memTableEnderecos.Active then memTableEnderecos.Close; if memTableContatos.Active then memTableContatos.Close; Action := caFree; view_CadastroGeral := nil; end; procedure Tview_CadastroGeral.FormShow(Sender: TObject); begin PopulaBancos; PopulaEstados; FAcao := tacIndefinido; Modo; end; procedure Tview_CadastroGeral.Modo; begin if FAcao = tacIndefinido then begin ClearFields; actionIncluir.Enabled := True; actionEditar.Enabled := False; actionLocalizar.Enabled := True; actionCancelar.Enabled := False; actionGravar.Enabled := False; actionDocumentosVencidos.Enabled := True; actionVencimentoGR.Enabled := True; actionFichaDIRECT.Enabled := False; actionSolicitarGR.Enabled := False; actionContrato.Enabled := False; maskEditID.Properties.ReadOnly := True; comboBoxTipoPessoa.Properties.ReadOnly := True; maskEditCPCNPJ.Properties.ReadOnly := True; textEditNome.Properties.ReadOnly := True; textEditRG.Properties.ReadOnly := True; textEditExpedidor.Properties.ReadOnly := True; dateEditDataRG.Properties.ReadOnly := True; dateEditNascimento.Properties.ReadOnly := True; textEditNomePai.Properties.ReadOnly := True; textEditNomeMae.Properties.ReadOnly := True; textEditNaturalidade.Properties.ReadOnly := True; lookupComboBoxNaturalidade.Properties.ReadOnly := True; textEditSegurancaCNH.Properties.ReadOnly := True; textEditNumeroCNH.Properties.ReadOnly := True; textEditRegistroCNH.Properties.ReadOnly := True; textEditCategoriaCNH.Properties.ReadOnly := True; dateEditEmissaoCNH.Properties.ReadOnly := True; dateEditValidadeCNH.Properties.ReadOnly := True; dateEditPrimeiraCNH.Properties.ReadOnly := True; lookupComboBoxUFCNH.Properties.ReadOnly := True; textEditNomeFantasia.Properties.ReadOnly := True; textEditIE.Properties.ReadOnly := True; textEditIEST.Properties.ReadOnly := True; textEditIM.Properties.ReadOnly := True; textEditCNAE.Properties.ReadOnly := True; comboBoxCRT.Properties.ReadOnly := True; comboBoxFormaPagamento.Properties.ReadOnly := True; comboBoxTipoConta.Properties.ReadOnly := True; lookupComboBoxBanco.Properties.ReadOnly := True; textEditAgencia.Properties.ReadOnly := True; textEditConta.Properties.ReadOnly := True; textEditFavorecido.Properties.ReadOnly := True; maskEditCPFCNPJFavorecido.Properties.ReadOnly := True; textEditChavePIX.Properties.ReadOnly := True; checkBoxStatusGR.Properties.ReadOnly := True; textEditEmpresaGR.Properties.ReadOnly := True; dateEditValidadeGR.Properties.ReadOnly := True; textEditNumeroConsultaGR.Properties.ReadOnly := True; memoObservacoes.Properties.ReadOnly := True; dsEnderecos.AutoEdit := False; dsContatos.AutoEdit := False; end else if FAcao = tacIncluir then begin ClearFields; actionIncluir.Enabled := False; actionEditar.Enabled := False; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := True; actionDocumentosVencidos.Enabled := False; actionVencimentoGR.Enabled := False; actionFichaDIRECT.Enabled := False; actionSolicitarGR.Enabled := False; actionContrato.Enabled := False; maskEditID.Properties.ReadOnly := True; comboBoxTipoPessoa.Properties.ReadOnly := False; maskEditCPCNPJ.Properties.ReadOnly := True; textEditNome.Properties.ReadOnly := False; textEditRG.Properties.ReadOnly := False; textEditExpedidor.Properties.ReadOnly := False; dateEditDataRG.Properties.ReadOnly := False; dateEditNascimento.Properties.ReadOnly := False; textEditNomePai.Properties.ReadOnly := False; textEditNomeMae.Properties.ReadOnly := False; textEditNaturalidade.Properties.ReadOnly := False; lookupComboBoxNaturalidade.Properties.ReadOnly := False; textEditSegurancaCNH.Properties.ReadOnly := False; textEditNumeroCNH.Properties.ReadOnly := False; textEditRegistroCNH.Properties.ReadOnly := False; textEditCategoriaCNH.Properties.ReadOnly := False; dateEditEmissaoCNH.Properties.ReadOnly := False; dateEditValidadeCNH.Properties.ReadOnly := False; dateEditPrimeiraCNH.Properties.ReadOnly := False; lookupComboBoxUFCNH.Properties.ReadOnly := False; textEditNomeFantasia.Properties.ReadOnly := False; textEditIE.Properties.ReadOnly := False; textEditIEST.Properties.ReadOnly := False; textEditIM.Properties.ReadOnly := False; textEditCNAE.Properties.ReadOnly := False; comboBoxCRT.Properties.ReadOnly := False; comboBoxFormaPagamento.Properties.ReadOnly := False; comboBoxTipoConta.Properties.ReadOnly := False; lookupComboBoxBanco.Properties.ReadOnly := False; textEditAgencia.Properties.ReadOnly := False; textEditConta.Properties.ReadOnly := False; textEditFavorecido.Properties.ReadOnly := False; maskEditCPFCNPJFavorecido.Properties.ReadOnly := False; textEditChavePIX.Properties.ReadOnly := False; checkBoxStatusGR.Properties.ReadOnly := False; textEditEmpresaGR.Properties.ReadOnly := False; dateEditValidadeGR.Properties.ReadOnly := False; textEditNumeroConsultaGR.Properties.ReadOnly := False; memoObservacoes.Properties.ReadOnly := False; dsEnderecos.AutoEdit := True; dsContatos.AutoEdit := True; end else if FAcao = tacAlterar then begin actionIncluir.Enabled := False; actionEditar.Enabled := False; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := True; actionDocumentosVencidos.Enabled := False; actionVencimentoGR.Enabled := False; actionFichaDIRECT.Enabled := False; actionSolicitarGR.Enabled := False; actionContrato.Enabled := False; maskEditID.Properties.ReadOnly := True; comboBoxTipoPessoa.Properties.ReadOnly := True; maskEditCPCNPJ.Properties.ReadOnly := True; textEditNome.Properties.ReadOnly := False; textEditRG.Properties.ReadOnly := False; textEditExpedidor.Properties.ReadOnly := False; dateEditDataRG.Properties.ReadOnly := False; dateEditNascimento.Properties.ReadOnly := False; textEditNomePai.Properties.ReadOnly := False; textEditNomeMae.Properties.ReadOnly := False; textEditNaturalidade.Properties.ReadOnly := False; lookupComboBoxNaturalidade.Properties.ReadOnly := False; textEditSegurancaCNH.Properties.ReadOnly := False; textEditNumeroCNH.Properties.ReadOnly := False; textEditRegistroCNH.Properties.ReadOnly := False; textEditCategoriaCNH.Properties.ReadOnly := False; dateEditEmissaoCNH.Properties.ReadOnly := False; dateEditValidadeCNH.Properties.ReadOnly := False; dateEditPrimeiraCNH.Properties.ReadOnly := False; lookupComboBoxUFCNH.Properties.ReadOnly := False; textEditNomeFantasia.Properties.ReadOnly := False; textEditIE.Properties.ReadOnly := False; textEditIEST.Properties.ReadOnly := False; textEditIM.Properties.ReadOnly := False; textEditCNAE.Properties.ReadOnly := False; comboBoxCRT.Properties.ReadOnly := False; comboBoxFormaPagamento.Properties.ReadOnly := False; comboBoxTipoConta.Properties.ReadOnly := False; lookupComboBoxBanco.Properties.ReadOnly := False; textEditAgencia.Properties.ReadOnly := False; textEditConta.Properties.ReadOnly := False; textEditFavorecido.Properties.ReadOnly := False; maskEditCPFCNPJFavorecido.Properties.ReadOnly := False; textEditChavePIX.Properties.ReadOnly := False; checkBoxStatusGR.Properties.ReadOnly := False; textEditEmpresaGR.Properties.ReadOnly := False; dateEditValidadeGR.Properties.ReadOnly := False; textEditNumeroConsultaGR.Properties.ReadOnly := False; memoObservacoes.Properties.ReadOnly := False; dsEnderecos.AutoEdit := True; dsContatos.AutoEdit := True; end else if FAcao = tacPesquisa then begin actionIncluir.Enabled := False; actionEditar.Enabled := True; actionLocalizar.Enabled := False; actionCancelar.Enabled := True; actionGravar.Enabled := False; actionDocumentosVencidos.Enabled := True; actionVencimentoGR.Enabled := True; actionFichaDIRECT.Enabled := True; actionSolicitarGR.Enabled := True; actionContrato.Enabled := True; maskEditID.Properties.ReadOnly := True; comboBoxTipoPessoa.Properties.ReadOnly := True; maskEditCPCNPJ.Properties.ReadOnly := True; textEditNome.Properties.ReadOnly := True; textEditRG.Properties.ReadOnly := True; textEditExpedidor.Properties.ReadOnly := True; dateEditDataRG.Properties.ReadOnly := True; dateEditNascimento.Properties.ReadOnly := True; textEditNomePai.Properties.ReadOnly := True; textEditNomeMae.Properties.ReadOnly := True; textEditNaturalidade.Properties.ReadOnly := True; lookupComboBoxNaturalidade.Properties.ReadOnly := True; textEditSegurancaCNH.Properties.ReadOnly := True; textEditNumeroCNH.Properties.ReadOnly := True; textEditRegistroCNH.Properties.ReadOnly := True; textEditCategoriaCNH.Properties.ReadOnly := True; dateEditEmissaoCNH.Properties.ReadOnly := True; dateEditValidadeCNH.Properties.ReadOnly := True; dateEditPrimeiraCNH.Properties.ReadOnly := True; lookupComboBoxUFCNH.Properties.ReadOnly := True; textEditNomeFantasia.Properties.ReadOnly := True; textEditIE.Properties.ReadOnly := True; textEditIEST.Properties.ReadOnly := True; textEditIM.Properties.ReadOnly := True; textEditCNAE.Properties.ReadOnly := True; comboBoxCRT.Properties.ReadOnly := True; comboBoxFormaPagamento.Properties.ReadOnly := True; comboBoxTipoConta.Properties.ReadOnly := True; lookupComboBoxBanco.Properties.ReadOnly := True; textEditAgencia.Properties.ReadOnly := True; textEditConta.Properties.ReadOnly := True; textEditFavorecido.Properties.ReadOnly := True; maskEditCPFCNPJFavorecido.Properties.ReadOnly := True; textEditChavePIX.Properties.ReadOnly := True; checkBoxStatusGR.Properties.ReadOnly := True; textEditEmpresaGR.Properties.ReadOnly := True; dateEditValidadeGR.Properties.ReadOnly := True; textEditNumeroConsultaGR.Properties.ReadOnly := True; memoObservacoes.Properties.ReadOnly := True; dsEnderecos.AutoEdit := False; dsContatos.AutoEdit := False; end; end; procedure Tview_CadastroGeral.PesquisaCadastro; var sSQL: String; sWhere: String; aParam: array of variant; sQuery: String; cadastro : TCadastroControl; begin try sSQL := ''; sWhere := ''; cadastro := TCadastroControl.Create; if not Assigned(View_PesquisarPessoas) then begin View_PesquisarPessoas := TView_PesquisarPessoas.Create(Application); end; View_PesquisarPessoas.dxLayoutItem1.Visible := True; View_PesquisarPessoas.dxLayoutItem2.Visible := True; sSQL := 'select ' + 'num_cnpj as "CPF/CNPJ", cod_cadastro as ID, des_nome_razao as Nome, nom_fantasia as Alias, num_rg_ie as "RG/IE", ' + 'num_registro_cnh as "Registro CNH" ' + 'from ' + cadastro.Cadastro.NomeTabela + ';'; sWhere := 'where num_cpf_cnpj like "%param%" or cod_cadastro like "paraN" or ' + 'des_nome_razao like "%param%" or nom_fantasia like "%param%" or ' + 'num_registro_cnh like "%param%";'; View_PesquisarPessoas.sSQL := sSQL; View_PesquisarPessoas.sWhere := sWhere; View_PesquisarPessoas.bOpen := False; View_PesquisarPessoas.Caption := 'Localizar Cadastros'; if View_PesquisarPessoas.ShowModal = mrOK then begin sQuery := 'cod_cadastro = ' + View_PesquisarPessoas.qryPesquisa.Fields[1].AsString; SetLength(aParam,2); aparam := ['FILTRO', sQuery]; if cadastro.Localizar(aParam) then begin if not cadastro.SetupModel(cadastro.Cadastro.Query) then begin Application.MessageBox('Ocorreu um problema ao exibir as informações!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end else begin FAcao := tacPesquisa; SetupFields(cadastro); //Modo; end; end else begin Application.MessageBox('Cadastro não localizado!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; Finalize(aParam); end; finally cadastro.Free; View_PesquisarPessoas.qryPesquisa.Close; View_PesquisarPessoas.tvPesquisa.ClearItems; FreeAndNil(View_PesquisarPessoas); end; end; procedure Tview_CadastroGeral.PopulaBancos; var FBancos : TBancosControl; aParam : array of variant; begin try FBancos := TBancosControl.Create; SetLength(aParam,3); aParam := ['APOIO','*','']; if FBancos.LocalizarExt(aParam) then begin if memTableBancos.Active then begin memTableBancos.Close; end; memTableBancos.Data := FBancos.Bancos.Query; FBancos.Bancos.Query.Close; FBancos.Bancos.Query.Connection.Close; end; Finalize(aParam); finally FBancos.Free; end; end; procedure Tview_CadastroGeral.PopulaContatos(iCadastro: Integer); var FContatos : TCadastroContatosControl; aParam: array of variant; begin try FContatos := TCadastroContatosControl.Create; if memTableContatos.Active then begin memTableContatos.Close; end; SetLength(aParam,2); aParam := ['ID',iCadastro]; if FContatos.Localizar(aParam) then begin memTableContatos.CopyDataSet(FContatos.Contatos.Query); end; FContatos.Contatos.Query.Close; FContatos.Contatos.Query.Connection.Close; finally FContatos.Free; end; end; procedure Tview_CadastroGeral.PopulaEnderecos(iCadastro: Integer); var FEnderecos : TCadastroEnderecosControl; aParam: array of variant; begin try FEnderecos := TCadastroEnderecosControl.Create; if memTableEnderecos.Active then begin memTableEnderecos.Close; end; SetLength(aParam,2); aParam := ['ID',iCadastro]; if FEnderecos.Localizar(aParam) then begin memTableEnderecos.CopyDataSet(Fenderecos.Enderecos.Query); end; Fenderecos.Enderecos.Query.Close; Fenderecos.Enderecos.Query.Connection.Close; finally FEnderecos.Free; end; end; procedure Tview_CadastroGeral.PopulaEstados; var FEstados : TEstadosControl; aParam : array of variant; begin try FEstados := TEstadosControl.Create; SetLength(aParam,3); aParam := ['APOIO','*','']; if FEstados.PesquisarExt(aParam) then begin if memTableEstados.Active then begin memTableEstados.Close; end; memTableEstados.Data := FEstados.Estados.Query; FEstados.Estados.Query.Close; FEstados.Estados.Query.Connection.Close; end; Finalize(aParam); finally FEstados.Free; end; end; procedure Tview_CadastroGeral.SetupFields(FCadastro: TCadastroControl); begin maskEditID.EditValue := FCadastro.Cadastro.Cadastro; comboBoxTipoPessoa.Text := FCadastro.Cadastro.Doc; maskEditCPCNPJ.EditValue := FCadastro.Cadastro.CPFCNPJ; textEditNome.Text := FCadastro.Cadastro.Nome; textEditRG.Text := FCadastro.Cadastro.IERG; textEditExpedidor.Text := FCadastro.Cadastro.EmissorRG; dateEditDataRG.Date := FCadastro.Cadastro.EMissaoRG; dateEditNascimento.Date := FCadastro.Cadastro.Nascimento; textEditNomePai.Text := FCadastro.Cadastro.Pai; textEditNomeMae.Text := FCadastro.Cadastro.Mae; textEditNaturalidade.Text := FCadastro.Cadastro.CidadeNascimento; lookupComboBoxNaturalidade.EditValue := FCadastro.Cadastro.UFNascimento; textEditSegurancaCNH.Text := FCadastro.Cadastro.CodigoCNH; textEditNumeroCNH.Text := FCadastro.Cadastro.NumeroCNH; textEditRegistroCNH.Text := FCadastro.Cadastro.RegistroCNH; textEditCategoriaCNH.Text := FCadastro.Cadastro.CategoriaCNH; dateEditEmissaoCNH.Date := FCadastro.Cadastro.EmissaoCNH; dateEditValidadeCNH.Date := FCadastro.Cadastro.ValidadeCNH; dateEditPrimeiraCNH.Date := FCadastro.Cadastro.DataPrimeiraCNH; lookupComboBoxUFCNH.EditValue := FCadastro.Cadastro.UFCNH; textEditNomeFantasia.Text := FCadastro.Cadastro.Fantasia; textEditIE.Text := FCadastro.Cadastro.IERG; textEditIEST.Text := FCadastro.Cadastro.IEST; textEditIM.Text := FCadastro.Cadastro.IM; textEditCNAE.Text := FCadastro.Cadastro.CNAE; comboBoxCRT.ItemIndex := FCadastro.Cadastro.CRT; comboBoxFormaPagamento.Text := FCadastro.Cadastro.FormaPagamento; comboBoxTipoConta.Text := FCadastro.Cadastro.TipoConta; lookupComboBoxBanco.EditValue := FCadastro.Cadastro.Banco; textEditAgencia.Text := FCadastro.Cadastro.AgenciaConta; textEditConta.Text := FCadastro.Cadastro.NumeroConta; textEditFavorecido.Text := FCadastro.Cadastro.NomeFavorecido; maskEditCPFCNPJFavorecido.Text := FCadastro.Cadastro.CPFCNPJFavorecido; textEditChavePIX.Text := FCadastro.Cadastro.Chave; checkBoxStatusGR.EditValue := FCadastro.Cadastro.GV; textEditEmpresaGR.Text := FCadastro.Cadastro.EmpresaGR; dateEditValidadeGR.Date := FCadastro.Cadastro.DataGV; textEditNumeroConsultaGR.Text := FCadastro.Cadastro.NumeroConsultaGR; memoObservacoes.Text := FCadastro.Cadastro.Obs; if memTableEnderecos.Active then memTableEnderecos.Close; PopulaEnderecos(FCadastro.Cadastro.Cadastro); if memTableContatos.Active then memTableContatos.Close; PopulaContatos(FCadastro.Cadastro.Cadastro); end; function Tview_CadastroGeral.ValidaDados: boolean; var FCadastro : TCadastroControl; begin try Result := False; FCadastro := TCadastroControl.Create; if FAcao = tacIncluir then begin if comboBoxTipoPessoa.ItemIndex = 1 then begin if not Common.Utils.TUtils.CPF(maskEditCPCNPJ.Text) then begin Application.MessageBox('CPF incorreto!','Atenção',MB_OK + MB_ICONEXCLAMATION); maskEditCPCNPJ.SetFocus; Exit; end; end else if comboBoxTipoPessoa.ItemIndex = 2 then begin if not Common.Utils.TUtils.CNPJ(maskEditCPCNPJ.Text) then begin Application.MessageBox('CNPJ incorreto!','Atenção',MB_OK + MB_ICONEXCLAMATION); maskEditCPCNPJ.SetFocus; Exit; end; end else begin Application.MessageBox('Informe o tipo de pessoa!','Atenção',MB_OK + MB_ICONEXCLAMATION); comboBoxTipoPessoa.SetFocus; Exit; end; end; if textEditNome.Text = '' then begin Application.MessageBox('Informe o nome ou razão social!','Atenção',MB_OK + MB_ICONEXCLAMATION); textEditNome.SetFocus; Exit; end; if comboBoxTipoPessoa.ItemIndex = 2 then begin if textEditNomeFantasia.Text = '' then begin Application.MessageBox('Informe o nome fantasia!','Atenção',MB_OK + MB_ICONEXCLAMATION); textEditNomeFantasia.SetFocus; Exit; end; if maskEditCPFCNPJFavorecido.Text <> '' then begin if not Common.Utils.TUtils.CPF(maskEditCPFCNPJFavorecido.Text) then begin Application.MessageBox('CPF do Favorecido incorreto!','Atenção',MB_OK + MB_ICONEXCLAMATION); maskEditCPFCNPJFavorecido.SetFocus; Exit; end; end; end; if comboBoxTipoPessoa.ItemIndex = 1 then begin if Facao = tacIncluir then begin if textEditRG.Text <> '' then begin if textEditExpedidor.Text = '' then begin Application.MessageBox('Informe o orgão expedidor do RG!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); textEditExpedidor.SetFocus; Exit; end; if dateEditDataRG.Date = 0 then begin Application.MessageBox('Informe o data da emissão do RG!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); dateEditDataRG.SetFocus; Exit; end; if dateEditDataRG.Date > Now then begin Application.MessageBox('Data da emissão do RG inválida!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); dateEditDataRG.SetFocus; Exit; end; if lookupComboBoxUFRG.Text = '' then begin Application.MessageBox('Informe a UF do RG!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); lookupComboBoxUFRG.SetFocus; Exit; end; end else begin textEditExpedidor.Clear; dateEditDataRG.Clear; lookupComboBoxUFRG.Clear; end; if dateEditNascimento.Date <> 0 then begin if dateEditNascimento.Date >= Now then begin Application.MessageBox('Data de nascimento inválida!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); dateEditNascimento.SetFocus; Exit; end; if YearsBetween(Now,dateEditNascimento.Date) < 18 then begin if Application.MessageBox('Data de nascimento indica que pessoa é menor! Ignorar?', 'Atenção', MB_YESNO + MB_ICONEXCLAMATION + MB_DEFBUTTON2) = IDNO then begin dateEditNascimento.SetFocus; Exit; end; end; end; end; if maskEditCPFCNPJFavorecido.Text <> '' then begin if not Common.Utils.TUtils.CNPJ(maskEditCPFCNPJFavorecido.Text) then begin Application.MessageBox('CNPJ do Favorecido incorreto!','Atenção',MB_OK + MB_ICONEXCLAMATION); maskEditCPFCNPJFavorecido.SetFocus; Exit; end; end; if textEditNaturalidade.Text <> '' then begin if lookupComboBoxNaturalidade.Text = '' then begin Application.MessageBox('Informe a UF da naturalidade da Pessoa!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); lookupComboBoxNaturalidade.SetFocus; Exit; end; end; if textEditRegistroCNH.Text <> '' then begin if Length(textEditRegistroCNH.Text) <> 11 then begin Application.MessageBox('Quantidade de caracteres do número do registro da CNH incorreto!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); textEditRegistroCNH.SetFocus; Exit; end; if Length(textEditNumeroCNH.Text) <> 10 then begin Application.MessageBox('Quantidade de caracteres do número da cédula da CNH incorreto!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); textEditNumeroCNH.SetFocus; Exit; end; if Length(textEditSegurancaCNH.Text) <> 11 then begin Application.MessageBox('Quantidade de caracteres do código de segurança da CNH incorreto!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); textEditSegurancaCNH.SetFocus; Exit; end; if textEditCategoriaCNH.Text = '' then begin Application.MessageBox('Informe a categoria da CNH!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); textEditCategoriaCNH.SetFocus; Exit; end; if lookupComboBoxUFCNH.Text = '' then begin Application.MessageBox('Informe UF da CNH!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); lookupComboBoxUFRG.SetFocus; Exit; end; if dateEditEmissaoCNH.Date = 0 then begin Application.MessageBox('Informe a data da emissão da CNH!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); dateEditEmissaoCNH.SetFocus; Exit; end; if dateEditValidadeCNH.Date < Now then begin Application.MessageBox('Data da validade da CNH inválida!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); dateEditValidadeCNH.SetFocus; Exit; end; if dateEditPrimeiraCNH.Date = 0 then begin Application.MessageBox('Informe a data da primeira da CNH!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); dateEditPrimeiraCNH.SetFocus; Exit; end; if dateEditPrimeiraCNH.Date > Now then begin Application.MessageBox('Data da primeira da CNH inválida!', 'Atenção', MB_OK + MB_ICONEXCLAMATION); dateEditPrimeiraCNH.SetFocus; Exit; end; end else begin textEditSegurancaCNH.Clear; textEditNumeroCNH.Clear; textEditRegistroCNH.Clear; textEditCategoriaCNH.Clear; dateEditEmissaoCNH.Clear; dateEditValidadeCNH.Clear; dateEditPrimeiraCNH.Clear; lookupComboBoxUFCNH.Clear; end; end; Result := True; finally FCadastro.Free; end; end; end.
unit FileUtilsObj; interface uses ComObj, NewsFileUtils_TLB, SysUtils; type TFolderIterator = class(TAutoObject, IFolderIterator) public destructor Destroy; override; protected function FindFirst(const aPath: WideString): WideString; safecall; function FindNext: WideString; safecall; procedure FindClose; safecall; function Get_LangId: WideString; safecall; procedure Set_LangId(const Value: WideString); safecall; private fSearchRec : TSearchRec; fRecValid : boolean; fLangId : string; protected property LangId : widestring read Get_LangId; end; implementation uses ComServ, NewsRegistry, Registry, Windows; destructor TFolderIterator.Destroy; begin FindClose; inherited; end; function TFolderIterator.FindFirst(const aPath: WideString): WideString; function GlobalizePath( path : string ) : string; var Reg : TRegistry; begin if (pos( ':', path ) = 0) and (path[1] <> '\') then try Reg := TRegistry.Create; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey( tidRegKey_News, false ) then result := Format( Reg.ReadString( 'Path' ), [LangId] ) + path else result := path; finally Reg.Free; end; except result := path; end else result := path; end; var path : string; begin FindClose; path := GlobalizePath( aPath ); if SysUtils.FindFirst( path, faAnyFile, fSearchRec ) = 0 then begin result := fSearchRec.Name; fRecValid := true; end else begin result := ''; FindClose; end; end; function TFolderIterator.FindNext: WideString; begin if SysUtils.FindNext( fSearchRec ) = 0 then result := fSearchRec.Name else begin result := ''; FindClose; end; end; procedure TFolderIterator.FindClose; begin if fRecValid then begin SysUtils.FindClose( fSearchRec ); fRecValid := false; end; end; function TFolderIterator.Get_LangId: WideString; begin if fLangId <> '' then result := fLangId else result := '0'; end; procedure TFolderIterator.Set_LangId(const Value: WideString); begin fLangId := Value; end; initialization TAutoObjectFactory.Create(ComServer, TFolderIterator, Class_FolderIterator, ciMultiInstance); end.
namespace Sugar.RegularExpressions; interface type &Group = public class protected fLength: Integer; fStart: Integer; fText: String; public constructor(aStart: Integer; aLength: Integer; aText: String); property &End: Integer read fStart + fLength - 1; property Length: Integer read fLength; property Start: Integer read fStart; property Text: String read fText; end; implementation constructor &Group(aStart: Integer; aLength: Integer; aText: String); begin fLength := aLength; fStart := aStart; fText := aText; end; end.
unit FFSAdvStringGrid; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, AdvGrid, registry, FFSTypes,advedit,dcEdit; type TGetDataRecords = procedure ( Rows : array of integer; Fields:TStringList; csvList:TStringList) of object; TGetRowCount = procedure (Sender:TObject; var NewRowCount:integer) of object; TdcEditLink = class(TEditLink) private fEdit :TdcEdit; fEditColor:TColor; fModifiedColor: TColor; fEditType : TAdvEditType; fSuffix : string; fPrefix : string; fEditAlign: TEditAlign; fShowModified: boolean; fPrecision: integer; protected procedure EditExit(Sender:TObject); public procedure CreateEditor(aParent:TWinControl); override; procedure DestroyEditor; override; function GetEditorValue:string; override; procedure SetEditorValue(s:string); override; function GetEditControl:TWinControl; override; procedure SetProperties; override; constructor Create(aOwner:TComponent); override; published property EditAlign:TEditAlign read fEditAlign write fEditAlign; property EditColor:TColor read fEditColor write fEditColor; property ModifiedColor:TColor read fModifiedColor write fModifiedColor; property EditType:TAdvEditType read fEditType write fEditType; property Prefix:string read fPrefix write fPrefix; property ShowModified:boolean read fShowModified write fShowModified; property Suffix:string read fSuffix write fSuffix; property Precision:integer read fPrecision write fPrecision; end; TFFSAdvStringGrid = class(TAdvStringGrid) private FOnGetDataRecords: TGetDataRecords; FFieldNames : TStringList; FOnGetRowCount : TGetRowCount; FSaveRegSection : string; FSaveRegKey : string; FCurrencyFormat : string; FOnUpdateCell : TClickCellEvent; FOnRecordInsert : TNotifyEvent; FOnRecordEdit : TNotifyEvent; FOnRecordDelete : TNotifyEvent; FFFSRowCount : integer; FOnBeforeGetRecords: TNotifyEvent; FOnAfterGetRecords : TNotifyEvent; FFFSRowHighlightColor: TFieldsColorScheme; FFFSRowLowlightColor : TFieldsColorScheme; FAlternateRowsColors : Boolean; FUseFFSColorScheme : boolean; TempList : TStringList; FLastColMinWidth : integer; procedure MsgFFSColorChange(var Msg: TMessage); message Msg_FFSColorChange; procedure SetOnGetDataRecords(const Value: TGetDataRecords); procedure SetFieldNames(const Value: TStringList); procedure SetOnGetRowCount(const Value: TGetRowCount); procedure FillData; procedure SetSaveRegKey(const Value: string); procedure SetSaveRegSection(const Value: string); procedure SetCurrencyFormat(const Value: string); function GetCurrency(ACol, ARow: integer): Currency; procedure SetCurrency(ACol, ARow: integer; const Value: Currency); procedure SetOnUpdateCell(const Value: TClickCellEvent); procedure SetOnRecordDelete(const Value: TNotifyEvent); procedure SetOnRecordEdit(const Value: TNotifyEvent); procedure SetOnRecordInsert(const Value: TNotifyEvent); procedure SetFFSRowCount(const Value: integer); procedure SetOnAfterGetRecords(const Value: TNotifyEvent); procedure SetOnBeforeGetRecords(const Value: TNotifyEvent); procedure SetFFSRowHighlightColor(const Value: TFieldsColorScheme); procedure SetFFSRowLowlightColor(const Value: TFieldsColorScheme); procedure SetAlternateRowsColors(const Value: Boolean); procedure SetUseFFSColorScheme(const Value: boolean); function GetExtCommaText(i: integer): String; procedure SetExtCommaText(i: integer; const Value: String); { Private declarations } protected { Protected declarations } procedure GetCellColor(ACol,ARow:integer;AState: TGridDrawState; ABrush: TBrush; AFont: TFont); override; procedure ColumnMoved(FromIndex, ToIndex: Longint); override; procedure UpdateCell(ACol,ARow:integer); override; procedure KeyPress(var Key:Char);override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; public { Public declarations } constructor create(AOwner:TComponent);override; destructor destroy;override; procedure TopLeftChanged; override; procedure Refresh; procedure LoadFromCSVStringList(AStringList:TStringList); procedure SaveColumnSettings; procedure LoadColumnSettings; property Currency[ACol,ARow:integer]:Currency read GetCurrency write SetCurrency; property FFSRowCount:integer read FFFSRowCount write SetFFSRowCount; procedure FitLastColumn; function IsBlank:boolean; property ExtCommaText[i:integer]:String read GetExtCommaText write SetExtCommaText; published { Published declarations } property AlternateRowsColors : Boolean read FAlternateRowsColors write SetAlternateRowsColors default True; property FFSRowHighlightColor:TFieldsColorScheme read FFFSRowHighlightColor write SetFFSRowHighlightColor; property FFSRowLowlightColor: TFieldsColorScheme read FFFSRowLowlightColor write SetFFSRowLowlightColor; property FieldNames:TStringList read FFieldNames write SetFieldNames; property OnGetDataRecords:TGetDataRecords read FOnGetDataRecords write SetOnGetDataRecords; property OnGetRowCount:TGetRowCount read FOnGetRowCount write SetOnGetRowCount; property SaveRegKey:string read FSaveRegKey write SetSaveRegKey; property SaveRegSection:string read FSaveRegSection write SetSaveRegSection; property CurrencyFormat:string read FCurrencyFormat write SetCurrencyFormat; property OnUpdateCell:TClickCellEvent read FOnUpdateCell write SetOnUpdateCell; property OnRecordInsert:TNotifyEvent read FOnRecordInsert write SetOnRecordInsert; property OnRecordDelete:TNotifyEvent read FOnRecordDelete write SetOnRecordDelete; property OnRecordEdit:TNotifyEvent read FOnRecordEdit write SetOnRecordEdit; property OnBeforeGetRecords:TNotifyEvent read FOnBeforeGetRecords write SetOnBeforeGetRecords; property OnAfterGetRecords:TNotifyEvent read FOnAfterGetRecords write SetOnAfterGetRecords; property UseFFSColorScheme:boolean read FUseFFSColorScheme write SetUseFFSColorScheme; end; procedure Register; implementation uses AdvUtil; const rkey = 'Software\'; procedure Register; begin RegisterComponents('FFS Common', [TdcEditLink, TFFSAdvStringGrid]); end; { TFFSAdvStringGrid } constructor TFFSAdvStringGrid.create(AOwner: TComponent); begin inherited; FFieldNames := TStringList.Create; DefaultRowHeight := 18; Options := [goDrawFocusSelected,goRowSelect]; BorderStyle :=bsNone; FFSRowLowlightColor := fcsGridLowlight; FFSRowHighlightColor := fcsGridHighlight; FAlternateRowsColors := True; TempList := TStringList.create; FLastColMinWidth := 0; end; destructor TFFSAdvStringGrid.destroy; begin TempList.Free; FFieldNames.Free; inherited; end; procedure TFFSAdvStringGrid.Refresh; var nr : integer; begin if assigned(OnGetRowCount) then begin ClearRows(fixedRows, RowCount); nr := 0; OnGetRowCount(self,nr); if nr = 0 then nr := 1; RowCount := nr + fixedRows; end; FillData; end; procedure TFFSAdvStringGrid.SetFieldNames(const Value: TStringList); begin FFieldNames.assign(Value); ColCount := FieldNames.Count; end; procedure TFFSAdvStringGrid.SetOnGetDataRecords(const Value: TGetDataRecords); begin FOnGetDataRecords := Value; end; procedure TFFSAdvStringGrid.SetOnGetRowCount(const Value: TGetRowCount); begin FOnGetRowCount := Value; end; procedure TFFSAdvStringGrid.FillData; var x,t,y : integer; n : array of integer; count : integer; s : TStringList; commacomp : string; dsl : TStringList; begin commacomp := ''; for x := 1 to colcount - 1 do commacomp := commacomp + ','; count := 0; t := toprow-1; for x := 1 to VisibleRowCount do begin if rows[x+t].CommaText = commacomp then begin inc(count); setlength(n,count); n[count-1] := x+t; end; end; if (count > 0) and (assigned(OnGetDataRecords)) then begin BeginUpdate; if assigned(OnBeforeGetRecords) then OnBeforeGetRecords(self); s := TStringList.create; dsl := TStringList.create; try OnGetDataRecords(n, FieldNames, s); for x := 0 to count-1 do begin if s.count > x then dsl.CommaText := s[x] else dsl.Clear; for y := 0 to (NumHiddenColumns + ColCount - 1) do if dsl.count > y then AllCells[y,n[x]] := dsl[y] else AllCells[y,n[x]] := ''; end; finally dsl.free; s.free; EndUpdate; end; if assigned(OnAfterGetRecords) then OnAfterGetRecords(self); end; end; procedure TFFSAdvStringGrid.TopLeftChanged; begin inherited; if csDesigning in componentstate then exit; FillData; end; procedure TFFSAdvStringGrid.LoadFromCSVStringList(AStringList: TStringList); var x,y : integer; sl : TStringList; begin sl := TStringList.create; try if AStringList.Count = 0 then RowCount := 2 else RowCount := FixedRows + AStringList.Count; ClearRows(1,1); for x := 0 to AstringList.count - 1 do begin sl.CommaText := AStringList[x]; for y := 0 to sl.Count - 1 do begin if y < (ColCount+NumHiddenColumns) then AllCells[y,FixedRows+x] := sl[y]; end; end; finally sl.free; end; end; procedure TFFSAdvStringGrid.SetSaveRegKey(const Value: string); begin FSaveRegKey := Value; end; procedure TFFSAdvStringGrid.SetSaveRegSection(const Value: string); begin FSaveRegSection := Value; end; procedure TFFSAdvStringGrid.LoadColumnSettings; var reg : TRegistry; xs : string; x : integer; fullkey : string; rcol : integer; hcount : integer; begin if (trim(saveregkey) = '') or (trim(saveRegSection) = '') then exit; reg := TRegistry.Create; fullkey := rkey+SaveRegKey+'\'+SaveRegSection; if reg.OpenKey(fullkey,false) then begin ColumnHeaders.Clear; fieldnames.clear; hcount := 0; for x := 0 to (colcount + NumHiddenColumns - 1) do begin xs := inttostr(x); try ColumnHeaders.Add(reg.ReadString('Header' + xs)); FieldNames.Add(reg.Readstring('Field' + xs)); if IsHiddenColumn(x) then inc(hcount); rcol := x - hcount; if not IsHiddenColumn(x) then ColWidths[rcol] := reg.ReadInteger('Width' + xs); except end; end; reg.CloseKey; end; reg.Free; end; procedure TFFSAdvStringGrid.SaveColumnSettings; var reg : TRegistry; xs : string; x : integer; fullkey : string; dat : string; wd : integer; hcount : integer; begin if (trim(saveregkey) = '') or (trim(saveRegSection) = '') then exit; reg := TRegistry.Create; fullkey := rkey+SaveRegKey+'\'+SaveRegSection; reg.OpenKey(fullkey,true); hcount := 0; for x := 0 to (colcount + NumHiddenColumns - 1) do begin if IsHiddenColumn(x) then inc(hcount); xs := inttostr(x); dat := ColumnHeaders[x]; reg.WriteString('Header' + xs, dat); dat := fieldnames[x]; reg.writestring('Field' + xs, dat); if not IsHiddenColumn(x) then wd := colwidths[x-HCount] else wd := DefaultColWidth; reg.WriteInteger('Width' + xs, wd); end; reg.CloseKey; reg.Free; end; procedure TFFSAdvStringGrid.ColumnMoved(FromIndex, ToIndex: Integer); var rfrom, rto : integer; temp : string; begin inherited; rfrom := RealColIndex(FromIndex); rto := RealColIndex(ToIndex); // fieldnames temp := fieldnames[rfrom]; fieldnames.Delete(rfrom); fieldnames.Insert(rto, temp); // column headers temp := columnHeaders[rfrom]; ColumnHeaders.Delete(rfrom); ColumnHeaders.Insert(rto, temp); end; procedure TFFSAdvStringGrid.SetCurrencyFormat(const Value: string); begin FCurrencyFormat := Value; end; function TFFSAdvStringGrid.GetCurrency(ACol, ARow: integer): Currency; var s:string; res:double; code:integer; begin s:=cells[acol,arow]; if (s='') then s:='0'; val(removeseps(s),res,code); if (code<>0) then raise EAdvGridError.Create('Cell does not contain currency value'); result := res; end; procedure TFFSAdvStringGrid.SetCurrency(ACol, ARow: integer; const Value: Currency); begin cells[acol,arow]:= formatCurr(fCurrencyFormat,value); end; procedure TFFSAdvStringGrid.SetOnUpdateCell(const Value: TClickCellEvent); begin FOnUpdateCell := Value; end; procedure TFFSAdvStringGrid.UpdateCell(ACol, ARow: integer); begin if assigned(OnUpdateCell) then OnUpdateCell(self, ARow, ACol); inherited; end; procedure TFFSAdvStringGrid.SetOnRecordDelete(const Value: TNotifyEvent); begin FOnRecordDelete := Value; end; procedure TFFSAdvStringGrid.SetOnRecordEdit(const Value: TNotifyEvent); begin FOnRecordEdit := Value; end; procedure TFFSAdvStringGrid.SetOnRecordInsert(const Value: TNotifyEvent); begin FOnRecordInsert := Value; end; procedure TFFSAdvStringGrid.KeyDown(var Key: Word; Shift: TShiftState); begin if not (goEditing in Options) then begin // insert check if (shift = []) and (key = vk_Insert) and (Assigned(FOnRecordInsert)) then begin key := 0; FOnRecordInsert(self); end; // delete check if (shift = []) and (key = vk_Delete) and (Assigned(FOnRecordDelete)) then begin key := 0; FOnRecordDelete(self); end; end; // now inherited inherited; end; procedure TFFSAdvStringGrid.KeyPress(var Key: Char); begin if not (goEditing in Options) then begin if (Key = #13) and (Assigned(FOnRecordEdit)) then begin Key := #0; FOnRecordEdit(self); end; end; inherited; end; procedure TFFSAdvStringGrid.SetFFSRowCount(const Value: integer); begin FFFSRowCount := Value; if FFSRowCount = 0 then rowcount := 1 + FixedRows + FixedFooters else rowcount := FFSRowcount + FixedRows + FixedFooters; if FFSRowcount = 0 then ClearRows(FixedRows,1); end; procedure TFFSAdvStringGrid.FitLastColumn; var cw, x : integer; begin if FLastColMinWidth = 0 then FLastColMinWidth := ColWidths[ColCount-1]; cw := 0; for x := 0 to ColCount - 2 do inc(cw, ColWidths[x]); inc(cw,colcount*GridLineWidth); if self.clientwidth - cw >= FLastColMinWidth then ColWidths[colcount-1] := self.ClientWidth - cw; end; procedure TFFSAdvStringGrid.SetOnAfterGetRecords( const Value: TNotifyEvent); begin FOnAfterGetRecords := Value; end; procedure TFFSAdvStringGrid.SetOnBeforeGetRecords( const Value: TNotifyEvent); begin FOnBeforeGetRecords := Value; end; function TFFSAdvStringGrid.IsBlank: boolean; var commacomp : string; x : integer; begin commacomp := ''; if rowcount = 1 + fixedrows then begin for x := 1 to colcount - 1 do commacomp := commacomp + ','; result := (rows[1].CommaText = commacomp); end else result := false; end; procedure TFFSAdvStringGrid.MsgFFSColorChange(var Msg: TMessage); begin if UseFFSColorScheme then begin font.color := FFSColor[fcsDataText]; FixedColor := FFSColor[fcsGridTitlebar]; SelectionColor := FFSColor[fcsGridSelect]; FFSRowLowlightColor := fcsGridLowlight; FFSRowHighlightColor := fcsGridHighlight; end; end; procedure TFFSAdvStringGrid.SetFFSRowHighlightColor( const Value: TFieldsColorScheme); begin FFFSRowHighlightColor := Value; invalidate; end; procedure TFFSAdvStringGrid.SetFFSRowLowlightColor( const Value: TFieldsColorScheme); begin FFFSRowLowlightColor := Value; if UseFFSColorScheme then Color := FFSColor[FFSRowLowlightColor]; invalidate; end; procedure TFFSAdvStringGrid.GetCellColor(ACol,ARow:integer;AState: TGridDrawState; ABrush: TBrush; AFont: TFont); begin inherited; if UseFFSColorScheme then begin if FAlternateRowsColors then begin if gdFixed in AState then exit else if Odd(ARow) then begin if gdSelected in AState then AFont.Color := clWhite else begin ABrush.Color := FFSColor[FFSRowHighlightColor]; AFont.Color := clBlack; end; end else if gdSelected in AState then AFont.Color := clWhite else begin ABrush.Color := FFSColor[FFSRowLowlightColor]; AFont.Color := clBlack; end; end; end; if assigned(OnGetCellColor) then OnGetCellColor(self,ARow,ACol,AState,ABrush,AFont); end; procedure TFFSAdvStringGrid.SetAlternateRowsColors(const Value: Boolean); begin FAlternateRowsColors := Value; end; procedure TFFSAdvStringGrid.SetUseFFSColorScheme(const Value: boolean); begin FUseFFSColorScheme := Value; if FUseFFSColorScheme then begin FixedColor := FFSColor[fcsGridTitlebar]; SelectionColor := FFSColor[fcsGridSelect]; end; end; function TFFSAdvStringGrid.GetExtCommaText(i: integer): String; var x : integer; begin result := ''; if i >= rowcount then exit; if i < 0 then exit; TempList.Clear; for x := 1 to ColCount+NumHiddenColumns do TempList.Add(AllCells[x-1,i]); result := TempList.CommaText; end; procedure TFFSAdvStringGrid.SetExtCommaText(i: integer; const Value: String); var x : integer; Lesser : integer; begin if i >= rowcount then exit; if i < 0 then exit; TempList.Clear; TempList.CommaText := value; Lesser := ColCount+NumHiddenColumns; while TempList.count < Lesser do TempList.add(''); for x := 1 to Lesser do AllCells[x-1,i] := TempList[x-1]; end; { TdcEditLink } constructor TdcEditLink.Create(aOwner: TComponent); begin inherited; WantKeyLeftRight:=true; WantKeyHomeEnd:=true; EditColor:=clWindow; ModifiedColor:=clRed; EditType:=etString; end; procedure TdcEditLink.CreateEditor(aParent: TWinControl); begin fEdit:=TdcEdit.Create(Grid); fEdit.ShowModified:=true; fEdit.ModifiedColor:=clRed; fEdit.BorderStyle := bsNone; fEdit.OnKeydown:= EditKeyDown; fEdit.OnExit := EditExit; fEdit.Width:=0; fEdit.Height:=0; fEdit.Parent:=aParent; fEdit.Color:=EditColor; fEdit.EditType :=etString; WantKeyLeftRight:=true; WantKeyHomeEnd:=true; end; procedure TdcEditLink.DestroyEditor; begin if assigned(fEdit) then fEdit.Free; fEdit:=nil; inherited; end; procedure TdcEditLink.EditExit(Sender: TObject); begin HideEditor; end; function TdcEditLink.GetEditControl: TWinControl; begin result:=fEdit; end; function TdcEditLink.GetEditorValue: string; begin if (fEdit.Signed) and (fEdit.EditType = etMoney) then if fEdit.FloatValue < 0 then fEdit.Text := ''; result:=fEdit.Text; end; procedure TdcEditLink.SetEditorValue(s: string); begin fEdit.Text := s; end; procedure TdcEditLink.SetProperties; begin inherited; fEdit.Color := fEditColor; fEdit.FocusColor := fEditColor; fEdit.EditAlign := fEditAlign; fEdit.ModifiedColor := fModifiedColor; fEdit.Prefix := fPrefix; fEdit.Suffix := fSuffix; fEdit.EditType := fEditType; fEdit.Signed := (fEdit.EditType = etMoney); fEdit.ShowModified := fShowModified; if fPrecision > 0 then fEdit.MaxLength := 12; fEdit.Precision := fPrecision; end; end.
unit glr_gui; {$i defines.inc} interface uses glr_core, glr_render, glr_render2d, glr_scene, glr_math, glr_utils; type TglrGuiElement = class; TglrGuiBooleanCallback = procedure (Sender: TglrGuiElement; aValue: Boolean) of object; TglrGuiIntegerCallback = procedure (Sender: TglrGuiElement; aValue: Integer) of object; TglrGuiInputCallback = procedure (Sender: TglrGuiElement; Event: PglrInputEvent) of object; // Internal usage only TglrGuiElementType = (guiUnknown, guiLabel, guiLayout, guiButton, guiCheckBox, guiSlider); { TglrGuiElement } TglrGuiElement = class (TglrSprite) protected fType: TglrGuiElementType; fNormalTextureRegion, fOverTextureRegion, fClickedTextureRegion, fDisabledTextureRegion: PglrTextureRegion; fIsMouseOver: Boolean; fEnabled, fFocused: Boolean; procedure SetRot(const aRot: Single); override; procedure SetWidth(const aWidth: Single); override; procedure SetHeight(const aHeight: Single); override; procedure SetPP(const aPP: TglrVec2f); override; procedure SetNormalTextureRegion(const aTextureRegion: PglrTextureRegion); procedure SetEnabled(const aValue: Boolean); procedure SetFocused(const aValue: Boolean); procedure ProcessInput(Event: PglrInputEvent); virtual; function IsHit(X, Y: Single): Boolean; virtual; public // Input events OnClick, OnTouchDown, OnTouchUp, OnTouchMove, OnMouseOver, OnMouseOut: TglrGuiInputCallback; // Other events OnEnable, OnFocus: TglrGuiBooleanCallback; ZIndex: Integer; HitBox: TglrBB; // Texture regions for various states of button property NormalTextureRegion: PglrTextureRegion read fNormalTextureRegion write SetNormalTextureRegion; property OverTextureRegion: PglrTextureRegion read fOverTextureRegion write fOverTextureRegion; property ClickedTextureRegion: PglrTextureRegion read fClickedTextureRegion write fClickedTextureRegion; property DisabledTextureRegion: PglrTextureRegion read fDisabledTextureRegion write fDisabledTextureRegion; property IsMouseOver: Boolean read fIsMouseOver; property Enabled: Boolean read fEnabled write SetEnabled; property Focused: Boolean read fFocused write SetFocused; procedure UpdateHitBox(); procedure SetDefaultVertices(); override; constructor Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); override; overload; end; TglrGuiLabelPlacement = ( lpLeft, lpRight, lpTop, lpBottom, lpTopLeft, lpBottomLeft, lpTopRight, lpBottomRight ); { TglrGuiLabel } TglrGuiLabel = class (TglrGuiElement) protected fPlacement: TglrGuiLabelPlacement; fElement: TglrGuiElement; fTextLabelOffset: TglrVec2f; procedure SetVisible(const aVisible: Boolean); override; procedure SetElementFor(aElement: TglrGuiElement); procedure SetPlacement(aPlacement: TglrGuiLabelPlacement); procedure SetTextLabelOffset(aOffset: TglrVec2f); procedure UpdatePlacement(); public TextLabel: TglrText; constructor Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); override; destructor Destroy(); override; procedure SetFor(Element: TglrGuiElement; Placement: TglrGuiLabelPlacement; Offset: TglrVec2f); property TextLabelOffset: TglrVec2f read fTextLabelOffset write SetTextLabelOffset; property ElementFor: TglrGuiElement read fElement write SetElementFor; property Placement: TglrGuiLabelPlacement read fPlacement write SetPlacement; end; TglrGuiElementsList = TglrObjectList<TglrGuiElement>; { TglrGuiLayout } { 2014-12-24 : Draft version, do not use } TglrGuiLayout = class (TglrGuiElement) protected fX1, fX2, fY1, fY2: Single; fElements: TglrGuiElementsList; procedure SetWidth(const aWidth: Single); override; procedure SetHeight(const aHeight: Single); override; procedure SetVisible(const aVisible: Boolean); override; procedure UpdatePatchesPosition(); public Patches: array[0..7] of TglrSprite; //9th patch is element itself (center one) constructor Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); override; overload; destructor Destroy(); override; procedure SetNinePatchBorders(x1, x2, y1, y2: Single); procedure AddElement(aElement: TglrGuiElement); procedure RemoveElement(aElement: TglrGuiElement); procedure SetTextureRegion(aRegion: PglrTextureRegion; aAdjustSpriteSize: Boolean = True); override; procedure SetVerticesColor(aColor: TglrVec4f); override; procedure SetVerticesAlpha(aAlpha: Single); override; end; { TglrGuiButton } TglrGuiButton = class (TglrGuiElement) protected procedure SetVisible(const aVisible: Boolean); override; public TextLabel: TglrText; procedure SetVerticesColor(aColor: TglrVec4f); override; procedure SetVerticesAlpha(aAlpha: Single); override; constructor Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); override; overload; destructor Destroy(); override; end; { TglrGuiSlider } TglrGuiSlider = class (TglrGuiElement) protected fTouchedMe: Boolean; fMinValue, fMaxValue, fValue: Integer; procedure SetVisible(const aVisible: Boolean); override; procedure SetWidth(const aWidth: Single); override; procedure SetHeight(const aHeight: Single); override; procedure ProcessInput(Event: PglrInputEvent); override; function IsHit(X, Y: Single): Boolean; override; procedure SetValue(NewValue: Integer); procedure SetValueFromTouch(TouchX: Integer); procedure SetMinValue(const NewMinValue: Integer); procedure SetMaxValue(const NewMaxValue: Integer); procedure UpdateChildObjects(); public Fill: TglrSprite; Button: TglrGuiElement; ValueLabel: TglrGuiLabel; // ValueLabelOffset: TglrVec2f; ChangeTexCoords: Boolean; OnValueChanged: TglrGuiIntegerCallback; constructor Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); override; overload; destructor Destroy(); override; procedure SetVerticesColor(aColor: TglrVec4f); override; procedure SetVerticesAlpha(aAlpha: Single); override; property Value: Integer read fValue write SetValue; property MinValue: Integer read fValue write SetMinValue; property MaxValue: Integer read fValue write SetMaxValue; end; { TglrGuiCheckBox } TglrGuiCheckBox = class (TglrGuiElement) protected fChecked: Boolean; procedure SetChecked(const aChecked: Boolean); procedure SetVisible(const aVisible: Boolean); override; procedure ProcessInput(Event: PglrInputEvent); override; public Check: TglrSprite; OnCheck: TglrGuiBooleanCallback; constructor Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); override; overload; destructor Destroy(); override; property Checked: Boolean read fChecked write SetChecked; procedure SetVerticesAlpha(aAlpha: Single); override; procedure SetVerticesColor(aColor: TglrVec4f); override; end; { TglrGuiManager } TglrGuiManager = class (TglrGuiElementsList) protected fFontBatch: TglrFontBatch; fSpriteBatch: TglrSpriteBatch; fMaterial: TglrMaterial; procedure SetFocused(aElement: TglrGuiElement); public Focused: TglrGuiElement; constructor Create(Material: TglrMaterial; Font: TglrFont; aCapacity: LongInt = 4); reintroduce; destructor Destroy(); override; procedure ProcessInput(Event: PglrInputEvent; GuiCamera: TglrCamera); procedure Update(const dt: Double); procedure Render(); end; implementation { TglrGuiElement } procedure TglrGuiElement.SetRot(const aRot: Single); begin inherited SetRot(aRot); UpdateHitBox(); end; procedure TglrGuiElement.SetWidth(const aWidth: Single); begin inherited SetWidth(aWidth); UpdateHitBox(); end; procedure TglrGuiElement.SetHeight(const aHeight: Single); begin inherited SetHeight(aHeight); UpdateHitBox(); end; procedure TglrGuiElement.SetPP(const aPP: TglrVec2f); begin inherited SetPP(aPP); UpdateHitBox(); end; procedure TglrGuiElement.SetNormalTextureRegion( const aTextureRegion: PglrTextureRegion); begin fNormalTextureRegion := aTextureRegion; if (aTextureRegion <> nil) then SetTextureRegion(aTextureRegion); end; procedure TglrGuiElement.SetEnabled(const aValue: Boolean); begin if fEnabled = aValue then Exit(); fEnabled := aValue; if Assigned(OnEnable) then OnEnable(Self, aValue); if fEnabled then begin if Assigned(NormalTextureRegion) then SetTextureRegion(NormalTextureRegion); end else if Assigned(DisabledTextureRegion) then SetTextureRegion(DisabledTextureRegion); end; procedure TglrGuiElement.SetFocused(const aValue: Boolean); begin if fFocused = aValue then Exit(); fFocused := aValue; if Assigned(OnFocus) then OnFocus(Self, aValue); end; procedure TglrGuiElement.ProcessInput(Event: PglrInputEvent); begin // Warning! Implemented partially! case Event.InputType of itTouchDown: if IsHit(Event.X, Event.Y) then begin if Assigned(OnTouchDown) then OnTouchDown(Self, Event); if Assigned(ClickedTextureRegion) then SetTextureRegion(ClickedTextureRegion); Focused := True; end else Focused := False; itTouchUp: if IsHit(Event.X, Event.Y) then begin if Assigned(OnTouchUp) then OnTouchUp(Self, Event); if Assigned(OverTextureRegion) then SetTextureRegion(OverTextureRegion); if Focused then if Assigned(OnClick) then OnClick(Self, Event); end else if Assigned(NormalTextureRegion) then SetTextureRegion(NormalTextureRegion); itTouchMove: begin if IsHit(Event.X, Event.Y) then begin if Assigned(OnTouchMove) then OnTouchMove(Self, Event); if not fIsMouseOver then begin fIsMouseOver := True; if Assigned(OnMouseOver) then OnMouseOver(Self, Event); if Assigned(OverTextureRegion) then SetTextureRegion(OverTextureRegion); end; end else begin if fIsMouseOver then begin fIsMouseOver := False; if Assigned(OnMouseOut) then OnMouseOut(Self, Event); if Assigned(NormalTextureRegion) then SetTextureRegion(NormalTextureRegion); end; end; end; end; end; function TglrGuiElement.IsHit(X, Y: Single): Boolean; var i: Integer; Point, p1, p2: TglrVec2f; absMatrix: TglrMat4f; intersect: Boolean; begin // First check out bounding box x -= Position.x; y -= Position.y; with HitBox do Result := (x >= Left) and (x <= Right) and (y >= Top) and (y <= Bottom); if not Result then Exit(); // If Point is in bounding box, then make a raycasts Result := False; absMatrix := AbsoluteMatrix; Point := Vec2f(X + Position.x, Y + Position.y); for i := 0 to 3 do begin p1 := Vec2f(absMatrix * Vertices[i].vec); p2 := Vec2f(absMatrix * Vertices[(i + 1) mod 4].vec); intersect := ((p1.y > Point.y) <> (p2.y > Point.y)) and (Point.x < (p2.x - p1.x) * (Point.y - p1.y) / (p2.y - p1.y) + p1.x); if (intersect) then Result := not Result; end; Exit(Result); end; procedure TglrGuiElement.UpdateHitBox; begin HitBox.Bottom := Max(Vertices[0].vec.y, Vertices[1].vec.y) + Position.y; HitBox.Top := Min(Vertices[2].vec.y, Vertices[3].vec.y) - Position.y; HitBox.Right := Max(Vertices[0].vec.x, Vertices[3].vec.x) + Position.x; HitBox.Left := Min(Vertices[1].vec.x, Vertices[2].vec.x) - Position.x; end; procedure TglrGuiElement.SetDefaultVertices; begin inherited SetDefaultVertices; UpdateHitBox(); end; constructor TglrGuiElement.Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); begin inherited Create(aWidth, aHeight, aPivotPoint); UpdateHitBox(); fFocused := False; fEnabled := True; fIsMouseOver := False; fType := guiUnknown; ZIndex := 0; NormalTextureRegion := nil; OverTextureRegion := nil; ClickedTextureRegion := nil; DisabledTextureRegion := nil; end; { TglrGuiLabel } procedure TglrGuiLabel.SetElementFor(aElement: TglrGuiElement); begin if fElement = aElement then Exit; fElement := aElement; UpdatePlacement(); end; procedure TglrGuiLabel.SetPlacement(aPlacement: TglrGuiLabelPlacement); begin if fPlacement = aPlacement then Exit; fPlacement := aPlacement; UpdatePlacement(); end; procedure TglrGuiLabel.SetTextLabelOffset(aOffset: TglrVec2f); begin fTextLabelOffset := aOffset; UpdatePlacement(); end; procedure TglrGuiLabel.UpdatePlacement; begin Parent := fElement; TextLabel.Position.Reset(); with TextLabel do case fPlacement of lpLeft: begin PivotPoint := Vec2f(1.0, 0.5); Position.x := fElement.Width * (0.0 - fElement.PivotPoint.x); end; lpRight: begin PivotPoint := Vec2f(0.0, 0.5); Position.x := fElement.Width * (1.0 - fElement.PivotPoint.x); end; lpTop: begin PivotPoint := Vec2f(0.5, 1.0); Position.y := fElement.Height * (0.0 - fElement.PivotPoint.y); end; lpBottom: begin PivotPoint := Vec2f(0.5, 0.0);; Position.y := fElement.Height * (1.0 - fElement.PivotPoint.y); end; lpTopLeft: begin PivotPoint := Vec2f(0.0, 1.0); Position.x := fElement.Width * (0.0 - fElement.PivotPoint.x); Position.y := fElement.Height * (0.0 - fElement.PivotPoint.y); end; lpTopRight: begin PivotPoint := Vec2f(1.0, 1.0); Position.x := fElement.Width * (1.0 - fElement.PivotPoint.x); Position.y := fElement.Height * (0.0 - fElement.PivotPoint.y); end; lpBottomLeft: begin PivotPoint := Vec2f(0.0, 0.0); Position.x := fElement.Width * (0.0 - fElement.PivotPoint.x); Position.y := fElement.Height * (1.0 - fElement.PivotPoint.y); end; lpBottomRight: begin PivotPoint := Vec2f(1.0, 0.0); Position.x := fElement.Width * (1.0 - fElement.PivotPoint.x); Position.y := fElement.Height * (1.0 - fElement.PivotPoint.y); end; end; TextLabel.Position += Vec3f(TextLabelOffset, 0); end; procedure TglrGuiLabel.SetVisible(const aVisible: Boolean); begin // inherited SetVisible(aVisible); TextLabel.Visible := aVisible; end; constructor TglrGuiLabel.Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); begin TextLabel := TglrText.Create('Label'); TextLabel.Parent := Self; inherited Create(aWidth, aHeight, aPivotPoint); fType := guiLabel; fVisible := False; fPlacement := lpLeft; fElement := nil; fTextLabelOffset := Vec2f(0, 0); end; destructor TglrGuiLabel.Destroy; begin TextLabel.Free(); inherited Destroy; end; procedure TglrGuiLabel.SetFor(Element: TglrGuiElement; Placement: TglrGuiLabelPlacement; Offset: TglrVec2f); begin fPlacement := Placement; fElement := Element; fTextLabelOffset := Offset; UpdatePlacement(); end; { TglrGuiLayout } procedure TglrGuiLayout.SetWidth(const aWidth: Single); begin inherited SetWidth(aWidth); Patches[1].Width := Width; Patches[6].Width := Width; UpdatePatchesPosition(); end; procedure TglrGuiLayout.SetHeight(const aHeight: Single); begin inherited SetHeight(aHeight); Patches[3].Height := Height; Patches[4].Height := Height; UpdatePatchesPosition(); end; procedure TglrGuiLayout.SetVisible(const aVisible: Boolean); var i: Integer; begin inherited SetVisible(aVisible); for i := 0 to Length(Patches) - 1 do Patches[i].Visible := aVisible; for i := 0 to fElements.Count - 1 do fElements[i].Visible := aVisible; end; procedure TglrGuiLayout.SetVerticesColor(aColor: TglrVec4f); var i: Integer; begin inherited SetVerticesColor(aColor); for i := 0 to Length(Patches) - 1 do Patches[i].SetVerticesColor(aColor); end; procedure TglrGuiLayout.SetVerticesAlpha(aAlpha: Single); var i: Integer; begin inherited SetVerticesAlpha(aAlpha); for i := 0 to Length(Patches) - 1 do Patches[i].SetVerticesAlpha(aAlpha); end; procedure TglrGuiLayout.UpdatePatchesPosition; var pp: TglrVec2f; begin pp := Vec2f(0.5, 0.5); Patches[0].Position := Vec3f(-Width * pp.x, -Height * pp.y, 1); Patches[1].Position := Vec3f( 0, -Height * pp.y, 1); Patches[2].Position := Vec3f( Width * pp.x, -Height * pp.y, 1); Patches[3].Position := Vec3f(-Width * pp.x, 0, 1); Patches[4].Position := Vec3f( Width * pp.x, 0, 1); Patches[5].Position := Vec3f(-Width * pp.x, Height * pp.y, 1); Patches[6].Position := Vec3f( 0, Height * pp.y, 1); Patches[7].Position := Vec3f( Width * pp.x, Height * pp.y, 1); end; constructor TglrGuiLayout.Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); var i: Integer; begin for i := 0 to Length(Patches) - 1 do begin Patches[i] := TglrSprite.Create(Width, Height, aPivotPoint{ * 3 - vec2f(1, 1)}); Patches[i].Visible := False; Patches[i].Parent := Self; end; inherited Create(aWidth, aHeight, aPivotPoint * 3 - vec2f(1, 1)); fType := guiLayout; UpdatePatchesPosition(); fElements := TglrGuiElementsList.Create(); end; destructor TglrGuiLayout.Destroy; var i: Integer; begin for i := 0 to Length(Patches) - 1 do Patches[i].Free(); fElements.Free(False); inherited Destroy; end; procedure TglrGuiLayout.SetNinePatchBorders(x1, x2, y1, y2: Single); var i: Integer; begin fX1 := x1; fX2 := x2; fY1 := y1; fY2 := y2; for i := 0 to Length(Patches) - 1 do Patches[i].Visible := True; if (NormalTextureRegion) <> nil then SetTextureRegion(NormalTextureRegion, False); end; procedure TglrGuiLayout.AddElement(aElement: TglrGuiElement); begin fElements.Add(aElement); aElement.Parent := Self; end; procedure TglrGuiLayout.RemoveElement(aElement: TglrGuiElement); begin fElements.Delete(aElement); aElement.Parent := nil; end; procedure TglrGuiLayout.SetTextureRegion(aRegion: PglrTextureRegion; aAdjustSpriteSize: Boolean); function ChangeTextureRegion(aFrom: PglrTextureRegion; x, y, w, h: Single): PglrTextureRegion; begin Result := aFrom; with Result^ do begin tx := x; ty := y; tw := w; th := h; end; end; var cx1, cx2, cy1, cy2: Single; patchRegion: TglrTextureRegion; begin if (fX2 <= 0) or (fY2 <= 0) then inherited SetTextureRegion(aRegion, aAdjustSpriteSize) else begin patchRegion := aRegion^; cx1 := aRegion.tw * fX1; cx2 := aRegion.tw * fX2; cy1 := aRegion.th * fY1; cy2 := aRegion.th * fY2; with aRegion^ do begin Patches[0].SetTextureRegion(ChangeTextureRegion(@patchRegion, tx, ty, cx1, cy1), aAdjustSpriteSize); Patches[1].SetTextureRegion(ChangeTextureRegion(@patchRegion, tx + cx1, ty, cx2 - cx1, cy1), aAdjustSpriteSize); Patches[2].SetTextureRegion(ChangeTextureRegion(@patchRegion, tx + cx2, ty, tw - cx2, cy1), aAdjustSpriteSize); Patches[3].SetTextureRegion(ChangeTextureRegion(@patchRegion, tx, ty + cy1, cx1, cy2 - cy1), aAdjustSpriteSize); inherited SetTextureRegion(ChangeTextureRegion( @patchRegion, tx + cx1, ty + cy1, cx2 - cx1, cy2 - cy1), aAdjustSpriteSize); Patches[4].SetTextureRegion(ChangeTextureRegion(@patchRegion, tx + cx2, ty + cy1, tw - cx2, cy2 - cy1), aAdjustSpriteSize); Patches[5].SetTextureRegion(ChangeTextureRegion(@patchRegion, tx, ty + cy2, cx1, th - cy2), aAdjustSpriteSize); Patches[6].SetTextureRegion(ChangeTextureRegion(@patchRegion, tx + cx1, ty + cy2, cx2 - cx1, th - cy2), aAdjustSpriteSize); Patches[7].SetTextureRegion(ChangeTextureRegion(@patchRegion, tx + cx2, ty + cy2, tw - cx2, th - cy2), aAdjustSpriteSize); end; end; end; { TglrGuiButton } procedure TglrGuiButton.SetVisible(const aVisible: Boolean); begin inherited SetVisible(aVisible); TextLabel.Visible := aVisible; end; procedure TglrGuiButton.SetVerticesColor(aColor: TglrVec4f); begin inherited SetVerticesColor(aColor); // Color sets up independently //if (TextLabel <> nil) then // TextLabel.Color := aColor; end; procedure TglrGuiButton.SetVerticesAlpha(aAlpha: Single); begin inherited SetVerticesAlpha(aAlpha); TextLabel.Color.w := aAlpha; end; constructor TglrGuiButton.Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); begin TextLabel := TglrText.Create(); inherited Create(aWidth, aHeight, aPivotPoint); fType := guiButton; TextLabel.Parent := Self; end; destructor TglrGuiButton.Destroy; begin TextLabel.Free(); inherited Destroy; end; { TglrGuiSlider } procedure TglrGuiSlider.UpdateChildObjects; var percentage: Single; FillTextureRegion: PglrTextureRegion; begin percentage := fValue / (fMaxValue - fMinValue); // Set slider button position Button.Position.x := Width * (percentage - PivotPoint.x); Button.Position.y := Height * (0.5 - PivotPoint.y); //Set slider fill params Fill.Width := percentage * Width; Fill.Position.x := -Width * PivotPoint.x; Fill.Position.y := Height * (0.5 - PivotPoint.y); if ChangeTexCoords then begin FillTextureRegion := Fill.GetTextureRegion(); if Assigned(FillTextureRegion) then with FillTextureRegion^ do if not Rotated then begin Fill.Vertices[0].tex.x := tx + (tw * percentage); Fill.Vertices[1].tex.x := Fill.Vertices[0].tex.x; end else begin Fill.Vertices[0].tex.y := ty + (th * percentage); Fill.Vertices[1].tex.y := Fill.Vertices[0].tex.y; end; end; end; procedure TglrGuiSlider.SetVisible(const aVisible: Boolean); begin inherited SetVisible(aVisible); Button.Visible := aVisible; Fill.Visible := aVisible; end; procedure TglrGuiSlider.SetWidth(const aWidth: Single); begin inherited SetWidth(aWidth); UpdateChildObjects(); end; procedure TglrGuiSlider.SetHeight(const aHeight: Single); begin inherited SetHeight(aHeight); UpdateChildObjects(); end; procedure TglrGuiSlider.ProcessInput(Event: PglrInputEvent); begin inherited ProcessInput(Event); Button.ProcessInput(Event); case Event.InputType of itTouchDown: begin fTouchedMe := IsHit(Event.X, Event.Y); if (fTouchedMe) then SetValueFromTouch(Event.X); end; itTouchUp: fTouchedMe := False; itTouchMove: if (fTouchedMe) then SetValueFromTouch(Event.X); end; end; procedure TglrGuiSlider.SetValue(NewValue: Integer); begin NewValue := Clamp(NewValue, fMinValue, fMaxValue); if NewValue <> fValue then begin if Assigned(OnValueChanged) then OnValueChanged(Self, NewValue); fValue := NewValue; ValueLabel.TextLabel.Text := Convert.ToString(fValue); end; UpdateChildObjects(); end; procedure TglrGuiSlider.SetValueFromTouch(TouchX: Integer); var percentage, posX: Single; begin posX := Self.AbsoluteMatrix.Pos.x; percentage := (TouchX - posX) / Width + PivotPoint.x; Value := Round((fMaxValue - fMinValue) * percentage); end; procedure TglrGuiSlider.SetMinValue(const NewMinValue: Integer); begin if (NewMinValue > fMaxValue) then Log.Write(lError, 'GuiSlider: min value can not be greater than max value') else begin fMinValue := NewMinValue; Value := Value; end; end; procedure TglrGuiSlider.SetMaxValue(const NewMaxValue: Integer); begin if (NewMaxValue < fMinValue) then Log.Write(lError, 'GuiSlider: max value can not be less than min value') else begin fMaxValue := NewMaxValue; Value := Value; end; end; function TglrGuiSlider.IsHit(X, Y: Single): Boolean; begin Result := inherited IsHit(X, Y) or Button.IsHit(X, Y); end; constructor TglrGuiSlider.Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); begin Button := TglrGuiElement.Create(1, 1, Vec2f(0.5, 0.5)); Fill := TglrSprite.Create(aWidth, aHeight, Vec2f(0.0, 0.5)); ValueLabel := TglrGuiLabel.Create(); inherited Create(aWidth, aHeight, aPivotPoint); fType := guiSlider; Button.Parent := Self; Fill.Parent := Self; ValueLabel.SetFor(Self, lpTop, Vec2f(0, -15)); OnValueChanged := nil; ChangeTexCoords := True; fMinValue := 0; fMaxValue := 100; SetValue(50); end; destructor TglrGuiSlider.Destroy; begin Button.Free(); Fill.Free(); ValueLabel.Free(); inherited Destroy; end; procedure TglrGuiSlider.SetVerticesColor(aColor: TglrVec4f); begin inherited SetVerticesColor(aColor); // Color sets up independently //if (Fill <> nil) then // Fill.SetVerticesColor(aColor); //if (Button <> nil) then // Button.SetVerticesColor(aColor); end; procedure TglrGuiSlider.SetVerticesAlpha(aAlpha: Single); begin inherited SetVerticesAlpha(aAlpha); Fill.SetVerticesAlpha(aAlpha); Button.SetVerticesAlpha(aAlpha); ValueLabel.SetVerticesAlpha(aAlpha); end; { TglrGuiCheckBox } procedure TglrGuiCheckBox.SetChecked(const aChecked: Boolean); begin Check.Visible := aChecked; if (fChecked <> aChecked) then begin fChecked := aChecked; if Assigned(OnCheck) then OnCheck(Self, fChecked); end; end; procedure TglrGuiCheckBox.SetVisible(const aVisible: Boolean); begin inherited SetVisible(aVisible); Check.Visible := aVisible; end; procedure TglrGuiCheckBox.ProcessInput(Event: PglrInputEvent); begin inherited ProcessInput(Event); if (Event.InputType = itTouchUp) and Focused then Checked := not Checked; end; constructor TglrGuiCheckBox.Create(aWidth, aHeight: Single; aPivotPoint: TglrVec2f); begin Check := TglrSprite.Create(aWidth, aHeight, aPivotPoint); inherited Create(aWidth, aHeight, aPivotPoint); fType := guiCheckBox; Check.Parent := Self; OnCheck := nil; SetChecked(False); end; destructor TglrGuiCheckBox.Destroy; begin Check.Free(); inherited Destroy; end; procedure TglrGuiCheckBox.SetVerticesAlpha(aAlpha: Single); begin inherited SetVerticesAlpha(aAlpha); Check.SetVerticesAlpha(aAlpha); end; procedure TglrGuiCheckBox.SetVerticesColor(aColor: TglrVec4f); begin inherited SetVerticesColor(aColor); Check.SetVerticesColor(aColor); end; { TglrGuiManager } procedure TglrGuiManager.SetFocused(aElement: TglrGuiElement); begin if (Focused <> nil) then Focused.Focused := False; if (aElement <> nil) then aElement.Focused := True; Focused := aElement; end; constructor TglrGuiManager.Create(Material: TglrMaterial; Font: TglrFont; aCapacity: LongInt); begin inherited Create(aCapacity); Focused := nil; fMaterial := Material; fSpriteBatch := TglrSpriteBatch.Create(); fFontBatch := TglrFontBatch.Create(Font); end; destructor TglrGuiManager.Destroy; begin fSpriteBatch.Free(); fFontBatch.Free(); inherited Destroy; end; procedure TglrGuiManager.ProcessInput(Event: PglrInputEvent; GuiCamera: TglrCamera); var i: Integer; touchVec: TglrVec3f; begin // WIP, don't kill me touchVec := GuiCamera.AbsoluteMatrix * Vec3f(Event.X, Event.Y, 0); for i := 0 to FCount - 1 do if FItems[i].Enabled then // Send ProcessInput for keys and wheel to focused only elements // Other messages - to all elements if (not (Event.InputType in [itKeyDown, itKeyUp, itWheel])) or (FItems[i].Focused) then FItems[i].ProcessInput(Event); end; procedure TglrGuiManager.Update(const dt: Double); begin end; procedure TglrGuiManager.Render; var i, j: Integer; b: TglrGuiButton; s: TglrGuiSlider; c: TglrGuiCheckBox; begin // Render sprites fMaterial.Bind(); fSpriteBatch.Start(); for i := 0 to FCount - 1 do case FItems[i].fType of guiLayout: begin fSpriteBatch.Draw(FItems[i]); for j := 0 to 7 do fSpriteBatch.Draw(TglrGuiLayout(FItems[i]).Patches[j]); end; guiSlider: begin s := TglrGuiSlider(FItems[i]); s.Fill.Position.z := s.Position.z - 1; s.Button.Position.z := s.Position.z + 1; fSpriteBatch.Draw(s); fSpriteBatch.Draw(s.Fill); fSpriteBatch.Draw(s.Button); end; guiLabel: ; guiCheckBox: begin c := TglrGuiCheckBox(fItems[i]); c.Check.Position.z := c.Position.z + 1; fSpriteBatch.Draw(c); fSpriteBatch.Draw(c.Check); end else fSpriteBatch.Draw(FItems[i]); end; fSpriteBatch.Finish(); // Render any text in components fFontBatch.Start(); for i := 0 to FCount - 1 do // GuiButton has Text object if (FItems[i].fType = guiButton) then begin b := TglrGuiButton(FItems[i]); b.TextLabel.Position.z := b.Position.z + 1; fFontBatch.Draw(b.TextLabel); end // For slider we render it's value text else if (FItems[i].fType = guiSlider) then begin s := TglrGuiSlider(FItems[i]); s.ValueLabel.Position.z := s.Button.Position.z + 1; fFontBatch.Draw(s.ValueLabel.TextLabel); end // GuiLabel has Text object else if (FItems[i].fType = guiLabel) then fFontBatch.Draw(TglrGuiLabel(FItems[i]).TextLabel); fFontBatch.Finish(); end; end.
unit Behavior3.Project; interface uses System.Classes, System.Generics.Collections, System.Generics.Defaults, System.JSON, Behavior3.Core.BehaviorTree, Behavior3.NodeTypes; type TB3Project = class(TObject) private protected public Name: String; Description: String; Path: String; Trees: TB3BehaviorTreeDictionary; constructor Create; virtual; destructor Destroy; override; procedure Load(Data: String; NodeTypes: TB3NodeTypes = NIL); overload; virtual; procedure Load(JsonTree: TJSONObject; NodeTypes: TB3NodeTypes = NIL); overload; virtual; procedure LoadFromStream(Stream: TStream; NodeTypes: TB3NodeTypes = NIL); overload; virtual; procedure LoadFromFile(Filename: String; NodeTypes: TB3NodeTypes = NIL); end; implementation { TB3Project } uses System.SysUtils; constructor TB3Project.Create; begin inherited; Trees := TB3BehaviorTreeDictionary.Create([doOwnsValues]); end; destructor TB3Project.Destroy; begin Trees.Free; inherited; end; procedure TB3Project.Load(Data: String; NodeTypes: TB3NodeTypes); var JsonTree: TJSONObject; begin JsonTree := TJSONObject.ParseJSONValue(Data, False) as TJSONObject; try Load(JsonTree, NodeTypes); finally JsonTree.Free; end; end; procedure TB3Project.Load(JsonTree: TJSONObject; NodeTypes: TB3NodeTypes); var JsonNode: TJSONObject; ClassNodeTypes: TB3NodeTypes; begin // If not yet assigned NodeTypes (or wrong class type) then create and use global B3NodeTypes if Assigned(NodeTypes) then ClassNodeTypes := TB3NodeTypes(NodeTypes) else begin if not Assigned(B3NodeTypes) then B3NodeTypes := TB3NodeTypes.Create; ClassNodeTypes := B3NodeTypes; end; Name := JsonTree.GetValue('name', Name); Description := JsonTree.GetValue('description', Description); Path := JsonTree.GetValue('path', Path); // Load all trees JsonNode := JsonTree.Get('data').JsonValue as TJSONObject; Trees.Load(JsonNode, ClassNodeTypes); end; procedure TB3Project.LoadFromStream(Stream: TStream; NodeTypes: TB3NodeTypes); var StreamReader: TStreamReader; Data: String; begin StreamReader := TStreamReader.Create(Stream); try Data := StreamReader.ReadToEnd; Load(Data, NodeTypes); finally StreamReader.Free; end; end; procedure TB3Project.LoadFromFile(Filename: String; NodeTypes: TB3NodeTypes); var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead + fmShareDenyWrite); try LoadFromStream(Stream, NodeTypes); finally Stream.Free; end; end; end.
unit ULicencaVO; interface uses uTableName, uKeyField, System.SysUtils, System.Generics.Collections; type [TableName('Licenca')] TLicencaVO = class private FDataAtualizacao: TDate; FIPExterno: string; FQtdeUsuario: Integer; FCNPJCPF: string; FId: Integer; FEmpresa: string; FQtdeEstacao: Integer; FBuild: string; FIPLocal: string; FCodigo: Integer; FIdCliente: Integer; FRazaoSocial: string; FQuantidadeRegistros: Integer; procedure SetBuild(const Value: string); procedure SetCNPJCPF(const Value: string); procedure SetDataAtualizacao(const Value: TDate); procedure SetEmpresa(const Value: string); procedure SetId(const Value: Integer); procedure SetIPExterno(const Value: string); procedure SetIPLocal(const Value: string); procedure SetQtdeEstacao(const Value: Integer); procedure SetQtdeUsuario(const Value: Integer); procedure SetCodigo(const Value: Integer); procedure SetIdCliente(const Value: Integer); procedure SetRazaoSocial(const Value: string); procedure SetQuantidadeRegistros(const Value: Integer); public [keyField('Lic_Id')] property Id: Integer read FId write SetId; [FieldName('Lic_Codigo')] property Codigo: Integer read FCodigo write SetCodigo; [FieldName('Lic_CNPJCPF')] property CNPJCPF: string read FCNPJCPF write SetCNPJCPF; [FieldName('Lic_Empresa')] property Empresa: string read FEmpresa write SetEmpresa; [FieldName('Lic_qtdeEstacao')] property QtdeEstacao: Integer read FQtdeEstacao write SetQtdeEstacao; [FieldName('Lic_QtdeUsuario')] property QtdeUsuario: Integer read FQtdeUsuario write SetQtdeUsuario; [FieldName('Lic_IPExterno')] property IPExterno: string read FIPExterno write SetIPExterno; [FieldDate('Lic_DataAtualizacao')] property DataAtualizacao: TDate read FDataAtualizacao write SetDataAtualizacao; [FieldName('Lic_Build')] property Build: string read FBuild write SetBuild; [FieldName('Lic_IPLocal')] property IPLocal: string read FIPLocal write SetIPLocal; [FieldNull('Lic_Cliente')] property IdCliente: Integer read FIdCliente write SetIdCliente; property RazaoSocial: string read FRazaoSocial write SetRazaoSocial; // property QuantidadeRegistros: Integer read FQuantidadeRegistros write SetQuantidadeRegistros; end; TListaLicenca = TObjectList<TLicencaVO>; implementation { TLicencaVO } procedure TLicencaVO.SetBuild(const Value: string); begin FBuild := Value; end; procedure TLicencaVO.SetCNPJCPF(const Value: string); begin FCNPJCPF := Value; end; procedure TLicencaVO.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TLicencaVO.SetDataAtualizacao(const Value: TDate); begin FDataAtualizacao := Value; end; procedure TLicencaVO.SetEmpresa(const Value: string); begin FEmpresa := Value; end; procedure TLicencaVO.SetId(const Value: Integer); begin FId := Value; end; procedure TLicencaVO.SetIdCliente(const Value: Integer); begin FIdCliente := Value; end; procedure TLicencaVO.SetIPExterno(const Value: string); begin FIPExterno := Value; end; procedure TLicencaVO.SetIPLocal(const Value: string); begin FIPLocal := Value; end; procedure TLicencaVO.SetQtdeEstacao(const Value: Integer); begin FQtdeEstacao := Value; end; procedure TLicencaVO.SetQtdeUsuario(const Value: Integer); begin FQtdeUsuario := Value; end; procedure TLicencaVO.SetQuantidadeRegistros(const Value: Integer); begin FQuantidadeRegistros := Value; end; procedure TLicencaVO.SetRazaoSocial(const Value: string); begin FRazaoSocial := Value; end; end.
{!DOCTOPIC}{ Sorting functions } {!DOCREF} { @method: procedure se.SortTBA(var Arr: TByteArray); @desc: Sorts the array from low to high } procedure SimbaExt.SortTBA(var Arr: TByteArray); begin exp_SortTBA(Arr); end; {!DOCREF} { @method: procedure se.SortTIA(var Arr: TIntArray); @desc: Sorts the array from low to high } procedure SimbaExt.SortTIA(var Arr: TIntArray); begin exp_SortTIA(Arr); end; {!DOCREF} { @method: procedure se.SortTFA(var Arr: TFloatArray); @desc: Sorts the array from low to high } procedure SimbaExt.SortTFA(var Arr: TFloatArray); begin exp_SortTFA(Arr); end; {!DOCREF} { @method: procedure se.SortTDA(var Arr: TDoubleArray); @desc: Sorts the array from low to high } procedure SimbaExt.SortTDA(var Arr: TDoubleArray); begin exp_SortTDA(Arr); end; {!DOCREF} { @method: procedure se.SortTEA(var Arr: TExtArray); @desc: Sorts the array from low to high } procedure SimbaExt.SortTEA(var Arr: TExtArray); begin exp_SortTEA(Arr); end; //TPA {!DOCREF} { @method: procedure se.SortTPA(var Arr: TPointArray); @desc: Sorts the TPA from low to high defined by the distnace from Point(0,0) / 'Magnitude' } procedure SimbaExt.SortTPA(var Arr: TPointArray); begin exp_SortTPA(Arr); end; {!DOCREF} { @method: procedure se.SortTPAFrom(var Arr: TPointArray; const From:TPoint); @desc: Sorts the TPA from low to high defined by the distnace from the given TPoint 'from' } procedure SimbaExt.SortTPAFrom(var Arr: TPointArray; const From:TPoint); begin exp_SortTPAFrom(Arr, From); end; {!DOCREF} { @method: procedure se.SortTPAByRow(var Arr: TPointArray); @desc: Sorts the TPA by Row. } procedure SimbaExt.SortTPAByRow(var Arr: TPointArray); begin exp_SortTPAByRow(Arr); end; {!DOCREF} { @method: procedure se.SortTPAByColumn(var Arr: TPointArray); @desc: Sorts the TPA by Column. } procedure SimbaExt.SortTPAByColumn(var Arr: TPointArray); begin exp_SortTPAByColumn(Arr); end; {!DOCREF} { @method: procedure se.SortTPAByX(var Arr: TPointArray); @desc: Sorts the TPA from low to high by each points X-position. } procedure SimbaExt.SortTPAByX(var Arr: TPointArray); begin exp_SortTPAByX(Arr); end; {!DOCREF} { @method: procedure se.SortTPAByY(var Arr: TPointArray); @desc: Sorts the TPA from low to high by each points Y-position. } procedure SimbaExt.SortTPAByY(var Arr: TPointArray); begin exp_SortTPAByY(Arr); end; //TSA {!DOCREF} { @method: procedure se.SortTSA(var Arr: TStringArray; IgnoreCase:Boolean=False); @desc: Sorts an array of strings lexicographically, in other words it will ber sorted by it's ASCII value. If ignoreCase is True then it will igonere if the strings contain lower or upper case when compared } procedure SimbaExt.SortTSA(var Arr: TStringArray; IgnoreCase:Boolean=False); begin exp_SortTSA(Arr,IgnoreCase); end; {!DOCREF} { @method: procedure se.SortTSANatural(var Arr: TStringArray); @desc: Sorts an array of strings in a more logical manner. Sort lexically (case insesitive), but will sort numeral parts numerically } procedure SimbaExt.SortTSANatural(var Arr: TStringArray); begin exp_SortTSANatural(Arr); end; //ATPA {!DOCREF} { @method: procedure se.SortATPAByLength(var Arr: T2dPointArray); @desc: Sorts an 'Array of TPointArray' from low to high by array length } procedure SimbaExt.SortATPAByLength(var Arr: T2dPointArray); begin exp_SortATPAByLength(Arr); end; {!DOCREF} { @method: procedure se.SortATPAByMean(var Arr: T2DPointArray); @desc: Sorts an 'Array of TPointArray' from low to high by array mean } procedure SimbaExt.SortATPAByMean(var Arr: T2DPointArray); begin exp_SortATPAByMean(Arr); end; {!DOCREF} { @method: procedure se.SortATPAByFirst(var Arr: T2DPointArray); @desc: Sorts an 'Array of TPointArray' from low to high by arrays first item } procedure SimbaExt.SortATPAByFirst(var Arr: T2DPointArray); begin exp_SortATPAByFirst(Arr); end; {!DOCREF} { @method: procedure se.SortATPAByIndex(var Arr: T2DPointArray; Index: Int32); @desc: Sorts an 'Array of TPointArray' from low to high by the selected array item } procedure SimbaExt.SortATPAByIndex(var Arr: T2DPointArray; Index: Int32); begin exp_SortATPAByIndex(Arr, Index); end; //ATBA {!DOCREF} { @method: procedure se.SortATBAByLength(var Arr: T2DByteArray); @desc: Sorts an 'Array of TByteArray' from low to high by array length } procedure SimbaExt.SortATBAByLength(var Arr: T2DByteArray); begin exp_SortATBAByLength(Arr); end; {!DOCREF} { @method: procedure se.SortATIAByMean(var Arr: T2DByteArray); @desc: Sorts an 'Array of TByteArray' from low to high by array mean } procedure SimbaExt.SortATBAByMean(var Arr: T2DByteArray); begin exp_SortATBAByMean(Arr); end; {!DOCREF} { @method: procedure se.SortATBAByFirst(var Arr: T2DByteArray); @desc: Sorts an 'Array of TByteArray' from low to high by arrays first item } procedure SimbaExt.SortATBAByFirst(var Arr: T2DByteArray); begin exp_SortATBAByFirst(Arr); end; {!DOCREF} { @method: procedure se.SortATBAByIndex(var Arr: T2DByteArray; Index: Int32); @desc: Sorts an 'Array of TByteArray' from low to high by the selected array item } procedure SimbaExt.SortATBAByIndex(var Arr: T2DByteArray; Index: Int32); begin exp_SortATBAByIndex(Arr, Index); end; //ATIA {!DOCREF} { @method: procedure se.SortATIAByLength(var Arr: T2DIntArray); @desc: Sorts an 'Array of TIntArray' from low to high by array length } procedure SimbaExt.SortATIAByLength(var Arr: T2DIntArray); begin exp_SortATIAByLength(Arr); end; {!DOCREF} { @method: procedure se.SortATIAByMean(var Arr: T2DIntArray); @desc: Sorts an 'Array of TIntArray' from low to high by array mean } procedure SimbaExt.SortATIAByMean(var Arr: T2DIntArray); begin exp_SortATIAByMean(Arr); end; {!DOCREF} { @method: procedure se.SortATIAByFirst(var Arr: T2DIntArray); @desc: Sorts an 'Array of TIntArray' from low to high by arrays first item } procedure SimbaExt.SortATIAByFirst(var Arr: T2DIntArray); begin exp_SortATIAByFirst(Arr); end; {!DOCREF} { @method: procedure se.SortATIAByIndex(var Arr: T2DIntArray; Index: Int32); @desc: Sorts an 'Array of TIntArray' from low to high by the selected array item } procedure SimbaExt.SortATIAByIndex(var Arr: T2DIntArray; Index: Int32); begin exp_SortATIAByIndex(Arr, Index); end; //ATEA {!DOCREF} { @method: procedure se.SortATEAByLength(var Arr: T2DExtArray); @desc: Sorts an 'Array of TExtArray' from low to high by array length } procedure SimbaExt.SortATEAByLength(var Arr: T2DExtArray); begin exp_SortATEAByLength(Arr); end; {!DOCREF} { @method: procedure se.SortATEAByMean(var Arr: T2DExtArray); @desc: Sorts an 'Array of TExtArray' from low to high by array mean } procedure SimbaExt.SortATEAByMean(var Arr: T2DExtArray); begin exp_SortATEAByMean(Arr); end; {!DOCREF} { @method: procedure se.SortATEAByFirst(var Arr: T2DExtArray); @desc: Sorts an 'Array of TExtArray' from low to high by arrays first item } procedure SimbaExt.SortATEAByFirst(var Arr: T2DExtArray); begin exp_SortATEAByFirst(Arr); end; {!DOCREF} { @method: procedure se.SortATIAByIndex(var Arr: T2DExtArray; Index: Int32); @desc: Sorts an 'Array of TExtArray' from low to high by the selected array item } procedure SimbaExt.SortATEAByIndex(var Arr: T2DExtArray; Index: Int32); begin exp_SortATEAByIndex(Arr, Index); end;
unit odaBasicXML; {******************************************************************************} { Author : Loda } { Create Date : 20060728 } { } { Description : varios class and utils for basic manipulations of } { XML file and nodes } { } { Define Use : [none] } { Side Effect : call CoInitialize } { } { see region Internal_Doc } { } {******************************************************************************} {******************************************************************************} { Navigation Flags : } { (search for this text in interface and implentation) } { } { Internal_Doc } { UTILS_XML_METHODE } { _TBasicXMLFile_ } { _TCustomXMLFile_ } { } {******************************************************************************} interface uses xmldoc, Classes, XMLIntf, Variants; type TBasicXMLFile = class private { _TBasicXMLFile_ Manage a XML file. FileName is not tested ! The file must exist. ReadOnly Attribut not tested: SaveToDisk can raise! } function getAutoSave : Boolean; procedure setAutoSave(value : boolean); protected fFileName : String; XMLDocument:TXMLDocument; dm:tDataModule; function getRootNode : IXMLNode; public class procedure CreateEmptyFile(FileName : String); constructor Create(FileName : String); virtual; destructor Destroy();override; procedure SaveToDisk; // Auto Save OnDestroy property AutoSave : Boolean read getAutoSave write setAutoSave; property RootNode : IXMLNode read getRootnode; end; TCustomXMLFile = class(TBasicXMLFile) private { _TCustomXMLFile_ Manage a XML file. Root.SubNode can be acces and create by RootSubNode property. FileName is not tested ! The file must exist. ReadOnly Attribut not tested: SaveToDisk can raise! } function getRootSubNode(NodeName : String) : IXMLNode; // remplace the Node "NodeName" by a copy of Value procedure setRootSubNode(NodeName : String; Value : IXMLNode); public // Child of RootNode, // when writing: create a copy then return the wroted node. property RootSubNode [NodeName : String] : IXMLNode read getRootSubNode write setRootSubNode; end; ////////////////////////////////////////////////////////////////////////////// // UTILS_XML_METHODE ////////////////////////////////////////////////////////////////////////////// { getPath Get the path of the node. "climb" the tree until the root node. (the root (1st) node won't be include in the returned path) } function getPath (node : IXMLNode; PATH_SEP : Char = '.') : string; //////////////////////////////////////////////////////////////////////////////// { getNode return the node situed at the specified path. path is relative to RootNode. RootNode must not be included in path (the path start at RootNode.ChildNodes) if not found or error, return nil.} function getNode (RootNode : IXMLNode; Path : string ; PATH_SEP : Char = '.') : IXMLNode; //////////////////////////////////////////////////////////////////////////////// { TryGetAttrib Try to read an attribut, if we cannot : return false and Value = unassigned. } function TryGetAttrib( Node : IXMLNode; AttribName : String; out Value : OleVariant) : Boolean; //////////////////////////////////////////////////////////////////////////////// { GetAttrib read an attribut, if we cannot : return DefaultValue } function GetAttrib( Node : IXMLNode; AttribName : String; DefaultValue : OleVariant) : OleVariant; //////////////////////////////////////////////////////////////////////////////// { odaCloneNode copy all children of srcNode in dstNode. copy all the attributes of srcNode in dstNode (created because CloneNode return a Node with the same NodeName) Param: Deep : pass to CloneNode methode. EraseDst : True : dstNode will be empty by method False : the existing node/attrib are keep. } procedure odaCloneNode(srcNode, dstNode : IXMLNode; Deep : Boolean ; EraseDst : Boolean = true); //////////////////////////////////////////////////////////////////////////////// implementation {Internal_Doc}{ The Class TBasicXMLFile don't create the file. The file MUST exist. If necessary, create it by hand, with CreateEmptyFile } uses ActiveX, xmldom; //////////////////////////////////////////////////////////////////////////////// // Internal_Tools //////////////////////////////////////////////////////////////////////////////// procedure SplitPath (Input: string; SEP : Char ; out Strings: TStringList); { convert a path with SEP in a StringList. remove extra SEP. Please, free Strings after use. } var i : integer; begin Strings := TStringList.Create; Strings.Delimiter := SEP; Strings.DelimitedText := Input; //remove extra SEP for i := Strings.Count-1 downto 0 do begin if Strings[i] = '' then strings.Delete(i); end; end; { _TBasicXMLFile_ } constructor TBasicXMLFile.Create(FileName : String); begin inherited create; dm:=tdatamodule.create(nil); XMLDocument:=TXMLDocument.Create(dm); fFileName := FileName; with XMLDocument do begin DomVendor:=GetDOMVendor('MSXML'); //Note: if option [doNodeAutoIndent] is set with MSXML, // Node.Clone change the type during copy !?! LoadFromFile(fFileName); Active := True; end; end; destructor TBasicXMLFile.Destroy; begin XMLDocument.Free; //I don't really know why, but the destroy isn't automatic dm.Free; inherited destroy; end; class procedure TBasicXMLFile.CreateEmptyFile(FileName: String); var F : TextFile; begin try AssignFile(F, FileName); Rewrite(F); //create and write WriteLn(F,'<?xml version="1.0" encoding="UTF-8"?>'); WriteLn(F,'<root>'); WriteLn(F,'</root>'); finally CloseFile(F); end; end; procedure TBasicXMLFile.SaveToDisk; {raise if the file is read only} begin XMLDocument.SaveToFile(fFileName); end; function TBasicXMLFile.getRootNode: IXMLNode; begin Result := XMLDocument.DocumentElement; end; function TBasicXMLFile.getAutoSave: Boolean; begin result := doAutoSave in XMLDocument.Options; end; procedure TBasicXMLFile.setAutoSave(value: boolean); begin if value then XMLDOcument.Options := XMLDOcument.Options + [doAutoSave] else XMLDOcument.Options := XMLDOcument.Options - [doAutoSave]; end; { _TCustomXMLFile_ } function TCustomXMLFile.getRootSubNode(NodeName: String): IXMLNode; begin Result := RootNode.ChildNodes.FindNode(NodeName); end; procedure TCustomXMLFile.setRootSubNode(NodeName: String; Value: IXMLNode); var node : IXMLNode; begin // get existing node node := getRootSubNode(NodeName); // if not existing, create it. if not assigned(node) then begin node := RootNode.AddChild(NodeName); end; // copy (remplace) content odaCloneNode(value, node, true, true); end; ////////////////////////////////////////////////////////////////////////////// // UTILS_XML_METHODE ////////////////////////////////////////////////////////////////////////////// function getPath (node : IXMLNode; PATH_SEP : Char = '.') :string; { Get the path of the node. "climb" the tree until the root node. (the root (1st) node won't be include in the returned path) } begin result := ''; if not Assigned(node) then exit; result := node.nodename; if Node.ParentNode <> nil then while node.ParentNode.ParentNode <> nil do begin // climb and note result := node.ParentNode.NodeName + PATH_SEP + result; node := node.ParentNode; end;//while end; function getNode (RootNode : IXMLNode; Path : string ; PATH_SEP : Char = '.') : IXMLNode; { return the node situed at the specified path. if not found or error, return nil. RootNode must not be included in path (the path start at RootNode) } var i : integer; node : IXMLNode; NodeNameList : TStringList; begin result := nil; if not Assigned(RootNode) then exit; SplitPath (Path, PATH_SEP, NodeNameList); try if NodeNameList.Count = 0 then exit; node := RootNode; for i := 0 to NodeNameList.count-1 do begin if not Assigned(node) then exit; //wrong path node := node.ChildNodes.FindNode(NodeNameList[i]); end; Result := node; finally NodeNameList.free; end; end; function TryGetAttrib( Node : IXMLNode; AttribName : String; out Value : OleVariant) : Boolean; begin Result := false; Value := unassigned; if not Assigned(Node) then exit; if not node.HasAttribute(AttribName) then exit; Value := Node.Attributes[AttribName]; Result := true; end; function GetAttrib( Node : IXMLNode; AttribName : String; DefaultValue : OleVariant) : OleVariant; begin if not TryGetAttrib(Node, AttribName, Result) then Result := DefaultValue; end; procedure odaCloneNode(srcNode, dstNode : IXMLNode; Deep : Boolean ; EraseDst : Boolean = true); var i : integer; begin if not Assigned(srcNode) then exit; if not Assigned(dstNode) then exit; if EraseDst then begin dstNode.childNodes.Clear; dstNode.AttributeNodes.Clear; end; for i := 0 to srcNode.ChildNodes.count-1 do begin dstNode.childNodes.Add(srcNode.childNodes.get(i).CloneNode(deep)); end; for i := 0 to srcNode.AttributeNodes.count-1 do begin dstNode.AttributeNodes.Add(srcNode.AttributeNodes.get(i).CloneNode(deep)); end; end; initialization CoInitialize(nil); finalization CoUnInitialize; end.
unit TransparentWindows; interface uses Windows, Messages, Controls, Classes, WinUtils, Rects, VCLUtils; // High level routines procedure ParentChanged( aControl : TWinControl ); // Low level routines procedure ClearControlHooks( aControl : TWinControl ); procedure AddControlHook( aControl, aHookedControl : TWinControl ); implementation type PWndProcInfo = ^TWndProcInfo; TWndProcInfo = record Control : TWinControl; HookedControl : TWinControl; Handle : HWND; WndProcData : integer; end; var fWindows : TList; // Hook all children of 'aParent' (except 'aControl') that intersect with ClipRect.. procedure HookControl( aControl, aParent: TWinControl; const ClipRect : TRect ); var i : integer; Rect : TRect; Ctl : TWinControl; begin AddControlHook( aControl, aParent ); try for i := 0 to aParent.ControlCount - 1 do begin Ctl := TWinControl( aParent.Controls[i] ); if (Ctl is TWinControl) and (Ctl <> aControl) and Ctl.Visible and IntersectRect( Rect, ScreenRect( Ctl ), ClipRect ) then HookControl( aControl, Ctl, ClipRect ); end; except end; end; procedure ParentChanged( aControl : TWinControl ); var Rect : TRect; begin ClearControlHooks( aControl ); if aControl.Parent <> nil then begin Rect := ScreenRect( aControl ); HookControl( aControl, aControl.Parent, Rect ); end; end; function PaintWndProc( WinHandle : HWND; Msg : integer; wPar : WPARAM; lPar : LPARAM ) : LRESULT; stdcall; var WinRect : TRect; i : integer; begin try i := 0; while ( i < fWindows.Count ) and ( PWndProcInfo(fWindows.Items[i]).Handle <> WinHandle ) do inc( i ); with PWndProcInfo( fWindows.Items[i] )^ do begin if ( Msg = WM_PAINT ) and GetUpdateRect( WinHandle, WinRect, false ) then begin OffsetRect( WinRect, HookedControl.Left - Control.Left +1, HookedControl.Top - Control.Top +1 ); InvalidateRect( Control.Handle, @WinRect, false ); end; Result := CallWindowProc( PrevWndProc( WndProcData ), WinHandle, Msg, wPar, lPar ); end; except Result := 0; end; end; procedure ClearControlHooks( aControl : TWinControl ); var i : integer; begin with fWindows do begin i := Count - 1; while i >= 0 do with PWndProcInfo( Items[i] )^ do begin if Control = aControl then begin RestoreWndProc( Handle, WndProcData ); dispose( Items[i] ); Delete( i ); end; dec( i ); end; end; end; procedure AddControlHook( aControl, aHookedControl : TWinControl ); var Info : PWndProcInfo; begin with fWindows do begin new( Info ); with Info^ do begin Control := aControl; HookedControl := aHookedControl; Handle := HookedControl.Handle; WndProcData := ChangeWndProc( Handle, @PaintWndProc ); end; fWindows.Add( Info ); end; end; initialization fWindows := TList.Create; finalization fWindows.Free; end.
Program categoria_natacao; {Faça um programa que receba a idade de um nadador e mostre sua categoria, usando as regras a seguir. Para idade inferior a 5, deverá mostrar mensagem. Infantil 5 a 7 Juvenil 8 a 10 Adolescente 11 a 15 Adulto 16 a 30 Sênior Acima de 30} var idade_nadador : integer; Begin write('Informe a idade do nadador: '); readln(idade_nadador); if idade_nadador > 30 then writeln('Categoria - Sênior') else if idade_nadador >= 16 then writeln('Categoria - Adulto') else if idade_nadador >= 11 then writeln('Categoria - Adolescente') else if idade_nadador >= 8 then writeln('Categoria - Juvenil') else if idade_nadador >= 5 then writeln('Categoria - Infantil') else writeln('Para menores de 05(cinco) anos não há categoria.'); readln; End.
unit UFormScanner; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, Grids; type TGetStringsEvent = procedure(Sender:TObject; SS:TStrings) of object; TFormScanner = class(TForm) stStatus: TStaticText; gbControls: TGroupBox; Label1: TLabel; meStartTime: TMaskEdit; Label2: TLabel; meStopTime: TMaskEdit; BtnStart: TButton; sgLog: TStringGrid; BtnSpy: TButton; procedure BtnStartClick(Sender: TObject); procedure sgLogClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); function IsShortCut(var Message: TWMKey): Boolean; override; procedure sgLogMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure sgLogColumnMoved(Sender: TObject; FromIndex, ToIndex: Integer); procedure FormDestroy(Sender: TObject); private { Private declarations } CurCol,CurRow,CursorRow:Integer; StrBuf:String; ColOrder:TList; public { Public declarations } OnStart:TNotifyEvent; OnGetRow:TGetStringsEvent; OnCaptureKey:TKeyPressEvent; OnIsShortCut:function(var Msg:TWMKey):Boolean of object; StartTime,StopTime:TDateTime; procedure Log(Msg:String); procedure SortRows; end; var FormScanner: TFormScanner; implementation uses UScanner; {$R *.DFM} procedure TFormScanner.BtnStartClick(Sender: TObject); begin try StartTime:=StrToDateTime(meStartTime.EditText); if Sender = BtnStart then begin StopTime:=StrToDateTime(meStopTime.EditText); if StopTime<=StartTime then raise Exception.Create('Задан неверный временной интервал'); end else StopTime:=0; except on E:Exception do begin Application.MessageBox( PChar(E.Message),'Ошибка',MB_OK or MB_ICONHAND ); exit; end; end; if Sender=BtnStart then begin BtnSpy.Visible:=False; BtnStart.Enabled:=False; end else begin BtnStart.Visible:=False; BtnSpy.Enabled:=False; meStopTime.Visible:=False; end; gbControls.Enabled:=False; if Assigned(OnStart) then OnStart(Self); end; procedure TFormScanner.Log(Msg: String); var c:Char; i:Integer; begin i:=1; while i<=Length(Msg) do begin c:=Msg[i]; case c of #9,#13: begin if sgLog.RowCount<=CurRow then begin sgLog.RowCount:=CurRow+1; if CurRow=1 then sgLog.FixedRows:=1; end; if sgLog.ColCount<=CurCol then begin sgLog.ColCount:=CurCol+1; end; sgLog.Cells[CurCol,CurRow]:=StrBuf; StrBuf:=''; if c=#9 then Inc(CurCol) else begin Inc(CurRow); CurCol:=0; end end; #0..#8,#10..#12,#14..#31:; else StrBuf:=StrBuf+c; end; Inc(i); end; if ColOrder.Count<sgLog.ColCount then begin ColOrder.Count:=sgLog.ColCount; for i:=0 to ColOrder.Count-1 do ColOrder[i]:=Pointer(i); end; end; procedure TFormScanner.sgLogClick(Sender: TObject); var Row:TStringList; OCO:array of Integer; // Original Columns Order i:Integer; begin if Assigned(OnGetRow) and (sgLog.Row<>CursorRow) then begin CursorRow:=sgLog.Row; SetLength(OCO,ColOrder.Count); for i:=0 to High(OCO) do OCO[Integer(ColOrder[i])]:=i; Row:=TStringList.Create; for i:=0 to High(OCO) do Row.Add(sgLog.Cells[OCO[i],CursorRow]); OnGetRow(Self,Row); Row.Free; end; end; procedure TFormScanner.FormCreate(Sender: TObject); begin Left:=GetSystemMetrics(SM_CXFULLSCREEN)+GetSystemMetrics(SM_CXBORDER)-Width;; Top:=GetSystemMetrics(SM_CYFULLSCREEN)+GetSystemMetrics(SM_CYCAPTION)-Height; ColOrder:=TList.Create; end; procedure TFormScanner.FormKeyPress(Sender: TObject; var Key: Char); begin if not BtnStart.Enabled and Assigned(OnCaptureKey) then OnCaptureKey(Self,Key); end; function TFormScanner.IsShortCut(var Message: TWMKey): Boolean; begin Result:=assigned(OnIsShortCut) and OnIsShortCut(Message) or inherited IsShortCut(Message); end; procedure TFormScanner.SortRows; var Rows,Row:TStringList; i:Integer; begin Rows:=TStringList.Create; Rows.Sorted:=True; Rows.Duplicates:=dupAccept; for i:=1 to sgLog.RowCount-1 do begin Row:=TStringList.Create; Row.Assign(sgLog.Rows[i]); Rows.AddObject(Row.Text,Row) end; for i:=1 to sgLog.RowCount-1 do begin Row:=TStringList(Rows.Objects[i-1]); sgLog.Rows[i].Assign(Row); Row.Free; end; Rows.Free; end; procedure TFormScanner.sgLogMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Col,Row:Integer; begin sgLog.MouseToCell(X,Y,Col,Row); if Row=0 then SortRows; end; procedure TFormScanner.sgLogColumnMoved(Sender: TObject; FromIndex, ToIndex: Integer); var P:Pointer; begin P:=ColOrder[FromIndex]; ColOrder.Delete(FromIndex); ColOrder.Insert(ToIndex,P); end; procedure TFormScanner.FormDestroy(Sender: TObject); begin ColOrder.Free; FormScanner:=nil; end; end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StColl.pas 4.04 *} {*********************************************************} {* SysTools: Huge, sparse collection class *} {*********************************************************} {$I StDefine.inc} {Notes: - STCOLL generally follows the standards set by Borland's TP6 TCollection. All elements in the collection are pointers. Elements can be inserted, deleted, and accessed by index number. The size of the collection grows dynamically as needed. However, STCOLL is implemented in a different fashion that gives it more capacity and higher efficiency in some ways. - STCOLL theoretically allows up to 2 billion elements. The collection is "sparse" in the sense that most of the memory is allocated only when a value is assigned to an element in the collection. - STCOLL is implemented as a linked list of pointers to pages. Each page can hold a fixed number of collection elements, the size being specified when the TStCollection is created. Only when an element with a given index is written to is a page descriptor and a page allocated for it. However, the first page is allocated when the collection is created. - The larger the page size, the faster it is to access a given index and the less memory overhead is used for management of the collection. If the page size is at least as large as the number of elements added to the collection, TStCollection works just like Borland's old TCollection. Inserting elements in the middle of very large pages can be slow, however, because lots of data must be shifted to make room for each new element. Conversely, if the page size is 1, TStCollection acts much like a traditional linked list. - The page size is limited to 16380 elements in 16-bit mode, or 536 million elements in 32-bit mode. - STCOLL uses the DisposeData procedure of TStContainer to determine how to free elements in the collection. By default, it does nothing. - AtFree and Free do not exist in TStCollection. Instead the AtDelete and Delete methods will also dispose of the element if the DisposeData property of the class has been set. - The Count property returns the index (plus one) of the highest element inserted or put. - AtInsert can insert an item at any index, even larger than Count+1. AtPut also can put an item at any index. - If the At function is called for any non-negative index whose value has not been explicitly assigned using Insert or AtInsert, it returns nil. - For the non-sorted collection, IndexOf compares the data pointers directly, for exact equality, without using any Comparison function. - TStSortedCollection allows duplicate nodes only if its Duplicates property is set. - The Efficiency property returns a measure of how fully the collection is using the memory pages it has allocated. It returns a number in the range of 0 to 100 (percent). Calling TStSortedCollection.Insert, AtInsert, Delete, or AtDelete can result in a low efficiency. After a series of calls to these methods it is often worthwhile to call the Pack method to increase the efficiency as much as possible. } unit StColl; {-} interface uses Windows, Classes, StConst, StBase, StList; type {.Z+} PPointerArray = ^TPointerArray; TPointerArray = array[0..(StMaxBlockSize div SizeOf(Pointer))-1] of Pointer; TPageDescriptor = class(TStListNode) protected {PageElements count is stored in inherited Data field} pdPage : PPointerArray; {Pointer to page data} pdStart : Integer; {Index of first element in page} pdCount : Integer; {Number of elements used in page} public constructor Create(AData : Pointer); override; destructor Destroy; override; end; {.Z-} TCollIterateFunc = function (Container : TStContainer; Data : Pointer; OtherData : Pointer) : Boolean; TStCollection = class(TStContainer) {.Z+} protected colPageList : TStList; {List of page descriptors} colPageElements : Integer; {Number of elements in a page} colCachePage : TPageDescriptor; {Page last found by At} procedure colAdjustPagesAfter(N : TPageDescriptor; Delta : Integer); procedure colAtInsertInPage(N : TPageDescriptor; PageIndex : Integer; AData : Pointer); procedure colAtDeleteInPage(N : TPageDescriptor; PageIndex : Integer); function colGetCount : Integer; function colGetEfficiency : Integer; procedure ForEachPointer(Action : TIteratePointerFunc; OtherData : pointer); override; function StoresPointers : boolean; override; {.Z-} public constructor Create(PageElements : Integer); virtual; {-Initialize a collection with given page size and allocate first page} destructor Destroy; override; {-Free a collection} procedure LoadFromStream(S : TStream); override; {-Load a collection's data from a stream} procedure StoreToStream(S : TStream); override; {-Write a collection and its data to a stream} procedure Clear; override; {-Deallocate all pages and free all items} procedure Assign(Source: TPersistent); override; {-Assign another container's contents to this one} procedure Pack; {-Squeeze collection elements into the least memory possible} function At(Index : Integer) : Pointer; {-Return the element at a given index} function IndexOf(Data : Pointer) : Integer; virtual; {-Return the index of the first item with given data} procedure AtInsert(Index : Integer; Data : Pointer); {-Insert a new element at a given index and move following items down} procedure AtPut(Index : Integer; Data : Pointer); {-Replace element at given index with new data} procedure Insert(Data : Pointer); virtual; {-Insert item at the end of the collection} procedure AtDelete(Index : Integer); {-Remove element at a given index, move following items up, free element} procedure Delete(Data : Pointer); {-Delete the first item with the given data} function Iterate(Action : TCollIterateFunc; Up : Boolean; OtherData : Pointer) : Pointer; {-Call Action for all the non-nil elements, returning the last data} property Count : Integer {-Return the index of the highest assigned item, plus one} read colGetCount; property Efficiency : Integer {-Return the overall percent Efficiency of the pages} read colGetEfficiency; property Items[Index : Integer] : Pointer {-Return the Index'th node, 0-based} read At write AtPut; default; end; {.Z+} TSCSearch = (SCSPageEmpty, SCSLessThanThisPage, SCSInThisPageRange, SCSFound, SCSGreaterThanThisPage); {.Z-} TStSortedCollection = class(TStCollection) {.Z+} protected FDuplicates : Boolean; function scSearchPage(AData : Pointer; N : TPageDescriptor; var PageIndex : Integer) : TSCSearch; procedure scSetDuplicates(D : Boolean); {.Z-} public procedure LoadFromStream(S : TStream); override; {-Load a sorted collection's data from a stream} procedure StoreToStream(S : TStream); override; {-Write a collection and its data to a stream} function IndexOf(Data : Pointer) : Integer; override; {-Return the index of the first item with given data} procedure Insert(Data : Pointer); override; {-Insert item in sorted position} property Duplicates : Boolean {-Determine whether sorted collection allows duplicate data} read FDuplicates write scSetDuplicates; end; {======================================================================} implementation function AssignData(Container : TStContainer; Data, OtherData : Pointer) : Boolean; far; var OurColl : TStCollection absolute OtherData; begin OurColl.Insert(Data); Result := true; end; constructor TPageDescriptor.Create(AData : Pointer); begin inherited Create(AData); GetMem(pdPage, Integer(Data)*SizeOf(Pointer)); FillChar(pdPage^, Integer(Data)*SizeOf(Pointer), 0); end; destructor TPageDescriptor.Destroy; begin if Assigned(pdPage) then FreeMem(pdPage, Integer(Data)*SizeOf(Pointer)); inherited Destroy; end; {----------------------------------------------------------------------} procedure TStCollection.Assign(Source: TPersistent); begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} {The only containers that we allow to be assigned to a collection are - a SysTools linked list (TStList) - a SysTools binary search tree (TStTree) - another SysTools collection (TStCollection, TStSortedCollection)} if not AssignPointers(Source, AssignData) then inherited Assign(Source); {$IFDEF ThreadSafe} finally LeaveCS; end;{try..finally} {$ENDIF} end; function TStCollection.At(Index : Integer) : Pointer; var Start : Integer; N : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Index < 0 then RaiseContainerError(stscBadIndex); N := colCachePage; if Index >= N.pdStart then {search up} repeat with N do begin Start := pdStart; if Index < Start then begin {element has not been set} colCachePage := N; break; end else if Index < Start+pdCount then begin {element is in this page} colCachePage := N; Result := pdPage^[Index-Start]; Exit; end; end; N := TPageDescriptor(N.FNext); until not Assigned(N) else begin {search down} N := TPageDescriptor(N.FPrev); while Assigned(N) do begin with N do begin Start := pdStart; if (Index >= Start+pdCount) then begin {element has not been set} colCachePage := N; break; end else if Index >= Start then begin {element is in this page} colCachePage := N; Result := pdPage^[Index-Start]; Exit; end; end; N := TPageDescriptor(N.FPrev); end; end; {not found, leave cache page unchanged} Result := nil; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.AtDelete(Index : Integer); var Start : Integer; N : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Index < 0 then RaiseContainerError(stscBadIndex); N := colCachePage; if Index >= N.pdStart then repeat with N do begin Start := pdStart; if Index < Start then begin {element has not been set, nothing to free} Dec(pdStart); colAdjustPagesAfter(N, -1); colCachePage := N; Exit; end else if Index < Start+pdCount then begin {element is in this page} colCachePage := N; colAtDeleteInPage(N, Index-Start); Exit; end; end; N := TPageDescriptor(N.FNext); until not Assigned(N) else begin {search down} N := TPageDescriptor(N.FPrev); while Assigned(N) do begin with N do begin Start := pdStart; if Index >= Start+pdCount then begin {element has not been set, nothing to free} Dec(pdStart); colAdjustPagesAfter(N, -1); colCachePage := N; Exit; end else if Index >= Start then begin {element is in this page} colCachePage := N; colAtDeleteInPage(N, Index-Start); Exit; end; end; N := TPageDescriptor(N.FPrev); end; end; {index not found, nothing to delete} {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.AtInsert(Index : Integer; Data : Pointer); var Start : Integer; NC : Integer; N : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Index < 0 then RaiseContainerError(stscBadIndex); N := TPageDescriptor(colPageList.Head); while Assigned(N) do begin Start := N.pdStart; if Index < Start then begin {current page has indexes greater than the specified one} if Start-Index <= colPageElements-N.pdCount then begin {room to squeeze element into this page} NC := Start-Index; Move(N.pdPage^[0], N.pdPage^[NC], N.pdCount*SizeOf(Pointer)); FillChar(N.pdPage^[1], (NC-1)*SizeOf(Pointer), 0); Inc(N.pdCount, NC); end else begin {insert on a new page before this one} N := TPageDescriptor(colPageList.PlaceBefore(Pointer(colPageElements), N)); N.pdCount := 1; end; N.pdStart := Index; N.pdPage^[0] := Data; colAdjustPagesAfter(N, +1); Exit; end else if Index < Start+colPageElements then if (not Assigned(N.FNext)) or (Index < TPageDescriptor(N.FNext).pdStart) then begin {should be inserted on this page} colAtInsertInPage(N, Index-Start, Data); Exit; end; N := TPageDescriptor(N.FNext); end; {should be inserted after all existing pages} N := TPageDescriptor(colPageList.Append(Pointer(colPageElements))); N.pdStart := Index; N.pdCount := 1; N.pdPage^[0] := Data; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.AtPut(Index : Integer; Data : Pointer); var Start : Integer; N, T : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Index < 0 then RaiseContainerError(stscBadIndex); {special case for putting to end of collection} T := TPageDescriptor(colPageList.Tail); if Index = T.pdStart+T.pdCount then begin if T.pdCount >= colPageElements then begin {last page is full, add another} Start := T.pdStart+colPageElements; T := TPageDescriptor(colPageList.Append(Pointer(colPageElements))); T.pdStart := Start; {T.pdCount := 0;} end; T.pdPage^[T.pdCount] := Data; inc(T.pdCount); Exit; end; N := colCachePage; if Index >= N.pdStart then {search up} repeat Start := N.pdStart; if Index < Start then begin {element has not been set before} N := TPageDescriptor(colPageList.PlaceBefore(Pointer(colPageElements), N)); N.pdStart := Index; N.pdCount := 1; N.pdPage^[0] := Data; colCachePage := N; Exit; end else if Index < Start+N.pdCount then begin {element fits in this page} colCachePage := N; N.pdPage^[Index-Start] := Data; Exit; end else if (N = T) and (Index < Start+colPageElements) then begin {element fits in last page} colCachePage := N; N.pdPage^[Index-Start] := Data; N.pdCount := Index-Start+1; Exit; end; N := TPageDescriptor(N.FNext); until not Assigned(N) else begin {search down} N := TPageDescriptor(N.FPrev); while Assigned(N) do begin Start := N.pdStart; if (Index >= Start+N.pdCount) then begin {element has not been set before} N := TPageDescriptor(colPageList.PlaceBefore(Pointer(colPageElements), N)); N.pdStart := Index; N.pdCount := 1; N.pdPage^[0] := Data; colCachePage := N; Exit; end else if Index >= Start then begin {element is in this page} colCachePage := N; N.pdPage^[Index-Start] := Data; Exit; end; N := TPageDescriptor(N.FPrev); end; end; {an element after all existing ones} N := TPageDescriptor(colPageList.Append(Pointer(colPageElements))); colCachePage := N; N.pdStart := Index; N.pdCount := 1; N.pdPage^[0] := Data; Exit; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.Clear; var I : Integer; N, P : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := TPageDescriptor(colPageList.Head); colCachePage := N; while Assigned(N) do begin for I := 0 to N.pdCount-1 do DoDisposeData(N.pdPage^[I]); P := TPageDescriptor(N.FNext); if N = colCachePage then begin {keep the first page, which is now empty} N.pdCount := 0; N.pdStart := 0; end else {delete all other pages} colPageList.Delete(N); N := P; end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.colAdjustPagesAfter(N : TPageDescriptor; Delta : Integer); begin N := TPageDescriptor(N.FNext); while Assigned(N) do begin inc(N.pdStart, Delta); N := TPageDescriptor(N.FNext); end; end; procedure TStCollection.colAtDeleteInPage(N : TPageDescriptor; PageIndex : Integer); begin with N do begin {free the element} DoDisposeData(pdPage^[PageIndex]); Move(pdPage^[PageIndex+1], pdPage^[PageIndex], (colPageElements-PageIndex-1)*SizeOf(Pointer)); Dec(pdCount); colAdjustPagesAfter(N, -1); if (pdCount = 0) and (colPageList.Count > 1) then begin {delete page if at least one page will remain} if N = colCachePage then begin colCachePage := TPageDescriptor(colPageList.Head); if N = colCachePage then colCachePage := TPageDescriptor(N.FNext); end; colPageList.Delete(N); end; end; end; procedure TStCollection.colAtInsertInPage(N : TPageDescriptor; PageIndex : Integer; AData : Pointer); var P : TPageDescriptor; PC : Integer; begin with N do if pdCount >= colPageElements then begin {page is full, add another} P := TPageDescriptor(colPageList.Place(Pointer(colPageElements), N)); {new page starts with element after the new one} P.pdStart := pdStart+PageIndex+1; PC := colPageElements-PageIndex; Move(pdPage^[PageIndex], P.pdPage^[0], PC*SizeOf(Pointer)); pdPage^[PageIndex] := AData; pdCount := PageIndex+1; P.pdCount := PC; colAdjustPagesAfter(P, +1); end else begin {room to add on this page} if pdCount > PageIndex then begin Move(pdPage^[PageIndex], pdPage^[PageIndex+1], (pdCount-PageIndex)*SizeOf(Pointer)); colAdjustPagesAfter(N, +1); inc(pdCount); end else begin FillChar(pdPage^[pdCount], (PageIndex-pdCount)*SizeOf(Pointer), 0); colAdjustPagesAfter(N, PageIndex+1-pdCount); pdCount := PageIndex+1; end; pdPage^[PageIndex] := AData; end; end; function TStCollection.colGetCount : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} with TPageDescriptor(colPageList.Tail) do Result := pdStart+pdCount; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStCollection.colGetEfficiency : Integer; var Pages, ECount : Integer; N : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} ECount := 0; Pages := 0; N := TPageDescriptor(colPageList.Head); while Assigned(N) do begin with N do begin inc(Pages); inc(ECount, N.pdCount); end; N := TPageDescriptor(N.FNext); end; Result := (100*ECount) div (Pages*colPageElements); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.ForEachPointer(Action : TIteratePointerFunc; OtherData : pointer); var I : Integer; N : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := TPageDescriptor(colPageList.Head); while Assigned(N) do begin with N do for I := 0 to pdCount-1 do if (pdPage^[I] <> nil) then if not Action(Self, pdPage^[I], OtherData) then begin Exit; end; N := TPageDescriptor(N.FNext); end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStCollection.StoresPointers : boolean; begin Result := true; end; constructor TStCollection.Create(PageElements : Integer); begin CreateContainer(TStNode, 0); if (PageElements = 0) then RaiseContainerError(stscBadSize); colPageList := TStList.Create(TPageDescriptor); colPageElements := PageElements; {start with one empty page} colPageList.Append(Pointer(colPageElements)); colCachePage := TPageDescriptor(colPageList.Head); end; procedure TStCollection.Delete(Data : Pointer); var Index : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} Index := IndexOf(Data); if Index >= 0 then AtDelete(Index); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; destructor TStCollection.Destroy; begin Clear; colPageList.Free; IncNodeProtection; inherited Destroy; end; function TStCollection.IndexOf(Data : Pointer) : Integer; var I : Integer; N : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := TPageDescriptor(colPageList.Head); while Assigned(N) do begin for I := 0 to N.pdCount-1 do if N.pdPage^[I] = Data then begin colCachePage := N; Result := N.pdStart+I; Exit; end; N := TPageDescriptor(N.FNext); end; IndexOf := -1; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.Insert(Data : Pointer); var Start : Integer; N : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := TPageDescriptor(colPageList.Tail); if N.pdCount >= colPageElements then begin {last page is full, add another} Start := N.pdStart+colPageElements; N := TPageDescriptor(colPageList.Append(Pointer(colPageElements))); N.pdStart := Start; {N.pdCount := 0;} end; N.pdPage^[N.pdCount] := Data; inc(N.pdCount); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStCollection.Iterate(Action : TCollIterateFunc; Up : Boolean; OtherData : Pointer) : Pointer; var I : Integer; N : TPageDescriptor; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if Up then begin N := TPageDescriptor(colPageList.Head); while Assigned(N) do begin with N do for I := 0 to pdCount-1 do if (pdPage^[I] <> nil) then if not Action(Self, pdPage^[I], OtherData) then begin Result := pdPage^[I]; Exit; end; N := TPageDescriptor(N.FNext); end; end else begin N := TPageDescriptor(colPageList.Tail); while Assigned(N) do begin with N do for I := pdCount-1 downto 0 do if (pdPage^[I] <> nil) then if not Action(Self, pdPage^[I], OtherData) then begin Result := pdPage^[I]; Exit; end; N := TPageDescriptor(N.FPrev); end; end; Result := nil; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.Pack; var N, P : TPageDescriptor; NC : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} colCachePage := TPageDescriptor(colPageList.Head); N := colCachePage; while Assigned(N) do begin while Assigned(N.FNext) and (N.pdCount < colPageElements) do begin {there is a page beyond this page and room to add to this page} P := TPageDescriptor(N.FNext); if N.pdStart+N.pdCount = P.pdStart then begin {next page has contiguous elements} NC := colPageElements-N.pdCount; if NC > P.pdCount then NC := P.pdCount; move(P.pdPage^[0], N.pdPage^[N.pdCount], NC*SizeOf(Pointer)); move(P.pdPage^[NC], P.pdPage^[0], (P.pdCount-NC)*SizeOf(Pointer)); inc(N.pdCount, NC); dec(P.pdCount, NC); if P.pdCount = 0 then colPageList.Delete(P) else inc(P.pdStart, NC); end else {pages aren't contiguous, can't merge} break; end; N := TPageDescriptor(N.FNext); end; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStCollection.LoadFromStream(S : TStream); var Data : pointer; Reader : TReader; PageElements : integer; Index : Integer; StreamedClass : TPersistentClass; StreamedClassName : string; begin Clear; Reader := TReader.Create(S, 1024); try with Reader do begin StreamedClassName := ReadString; StreamedClass := GetClass(StreamedClassName); if (StreamedClass = nil) then RaiseContainerErrorFmt(stscUnknownClass, [StreamedClassName]); if (not IsOrInheritsFrom(StreamedClass, Self.ClassType)) or (not IsOrInheritsFrom(TStCollection, StreamedClass)) then RaiseContainerError(stscWrongClass); PageElements := ReadInteger; if (PageElements <> colPageElements) then begin colPageList.Clear; colPageElements := PageElements; colPageList.Append(Pointer(colPageElements)); colCachePage := TPageDescriptor(colPageList.Head); end; ReadListBegin; while not EndOfList do begin Index := ReadInteger; Data := DoLoadData(Reader); AtPut(Index, Data); end; ReadListEnd; end; finally Reader.Free; end; end; procedure TStCollection.StoreToStream(S : TStream); var Writer : TWriter; N : TPageDescriptor; i : integer; begin Writer := TWriter.Create(S, 1024); try with Writer do begin WriteString(Self.ClassName); WriteInteger(colPageElements); WriteListBegin; N := TPageDescriptor(colPageList.Head); while Assigned(N) do begin with N do for i := 0 to pdCount-1 do if (pdPage^[i] <> nil) then begin WriteInteger(pdStart + i); DoStoreData(Writer, pdPage^[i]); end; N := TPageDescriptor(N.FNext); end; WriteListEnd; end; finally Writer.Free; end; end; {----------------------------------------------------------------------} function TStSortedCollection.IndexOf(Data : Pointer) : Integer; var N : TPageDescriptor; PageIndex : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} if (Count = 0) then begin Result := -1; Exit; end; N := colCachePage; if DoCompare(Data, N.pdPage^[0]) >= 0 then begin {search up} repeat case scSearchPage(Data, N, PageIndex) of SCSFound : begin colCachePage := N; Result := N.pdStart+PageIndex; Exit; end; SCSGreaterThanThisPage : {keep on searching} ; else {can't be anywhere else in the collection} break; end; N := TPageDescriptor(N.FNext); until not Assigned(N); end else begin {search down} N := TPageDescriptor(N.FPrev); while Assigned(N) do begin case scSearchPage(Data, N, PageIndex) of SCSFound : begin colCachePage := N; Result := N.pdStart+PageIndex; Exit; end; SCSLessThanThisPage : {keep on searching} ; else {can't be anywhere else in the collection} break; end; N := TPageDescriptor(N.FPrev); end; end; Result := -1; {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; procedure TStSortedCollection.Insert(Data : Pointer); var N : TPageDescriptor; PageIndex : Integer; begin {$IFDEF ThreadSafe} EnterCS; try {$ENDIF} N := TPageDescriptor(colPageList.Head); while Assigned(N) do begin case scSearchPage(Data, N, PageIndex) of SCSPageEmpty, SCSInThisPageRange, SCSLessThanThisPage : begin colAtInsertInPage(N, PageIndex, Data); Exit; end; SCSFound : if FDuplicates then begin colAtInsertInPage(N, PageIndex, Data); Exit; end else RaiseContainerError(stscDupNode); end; N := TPageDescriptor(N.FNext); end; {greater than all other items} inherited Insert(Data); {$IFDEF ThreadSafe} finally LeaveCS; end; {$ENDIF} end; function TStSortedCollection.scSearchPage(AData : Pointer; N : TPageDescriptor; var PageIndex : Integer) : TSCSearch; var L, R, M, Comp : Integer; begin with N do if pdCount = 0 then begin Result := SCSPageEmpty; PageIndex := 0; end else if DoCompare(AData, pdPage^[0]) < 0 then begin Result := SCSLessThanThisPage; PageIndex := 0; end else if DoCompare(AData, pdPage^[pdCount-1]) > 0 then Result := SCSGreaterThanThisPage else begin {data might be in this page, check using binary search} Result := SCSInThisPageRange; L := 0; R := pdCount-1; repeat M := (L+R) div 2; Comp := DoCompare(AData, pdPage^[M]); if Comp > 0 then L := M+1 else begin R := M-1; if Comp = 0 then begin PageIndex := M; Result := SCSFound; if not FDuplicates then {force exit from repeat loop} L := M; {else loop to find first of a group of duplicate nodes} end; end; until L > R; if Result = SCSInThisPageRange then begin {not found in page, return where it would be inserted} PageIndex := M; if Comp > 0 then inc(PageIndex); end; end; end; procedure TStSortedCollection.scSetDuplicates(D : Boolean); begin if FDuplicates <> D then if D then FDuplicates := True else if FCount <> 0 then RaiseContainerError(stscBadDups) else FDuplicates := False; end; procedure TStSortedCollection.LoadFromStream(S : TStream); var Data : pointer; Reader : TReader; PageElements : integer; StreamedClass : TPersistentClass; StreamedClassName : string; begin Clear; Reader := TReader.Create(S, 1024); try with Reader do begin StreamedClassName := ReadString; StreamedClass := GetClass(StreamedClassName); if (StreamedClass = nil) then RaiseContainerErrorFmt(stscUnknownClass, [StreamedClassName]); if (not IsOrInheritsFrom(StreamedClass, Self.ClassType)) or (not IsOrInheritsFrom(TStCollection, StreamedClass)) then RaiseContainerError(stscWrongClass); PageElements := ReadInteger; if (PageElements <> colPageElements) then begin colPageList.Clear; colPageElements := PageElements; colPageList.Append(Pointer(colPageElements)); colCachePage := TPageDescriptor(colPageList.Head); end; FDuplicates := ReadBoolean; ReadListBegin; while not EndOfList do begin ReadInteger; {read & discard index number} Data := DoLoadData(Reader); Insert(Data); end; ReadListEnd; end; finally Reader.Free; end; end; procedure TStSortedCollection.StoreToStream(S : TStream); var Writer : TWriter; N : TPageDescriptor; i : integer; begin Writer := TWriter.Create(S, 1024); try with Writer do begin WriteString(Self.ClassName); WriteInteger(colPageElements); WriteBoolean(FDuplicates); WriteListBegin; N := TPageDescriptor(colPageList.Head); while Assigned(N) do begin with N do for i := 0 to pdCount-1 do if (pdPage^[i] <> nil) then begin WriteInteger(pdStart + i); DoStoreData(Writer, pdPage^[i]); end; N := TPageDescriptor(N.FNext); end; WriteListEnd; end; finally Writer.Free; end; end; end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.AVFFT; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.Def, CP.FFT, { ffMPEG - libAV } libavcodec_avfft; type { TFFTAV } TFFTAV = class(TFFTLib) private m_rdft_ctx: PRDFTContext; FInput: PFFTSample; public constructor Create(frame_size: integer; window: TDoubleArray); destructor Destroy; override; procedure ComputeFrame(input: TSmallintArray; var frame: TFFTFrame); override; end; implementation uses libavutil_mem; { TFFTAV } procedure TFFTAV.ComputeFrame(input: TSmallintArray; var frame: TFFTFrame); var i: integer; begin // this is ApplyWindow for i := 0 to FFrameSize - 1 do begin TSingleArray(FInput)[i] := input[i] * FWindow[i] * 1.0; end; av_rdft_calc(m_rdft_ctx, FInput); frame.Data[0] := TSingleArray(FInput)[0] * TSingleArray(FInput)[0]; frame.Data[FFrameSizeH] := TSingleArray(FInput)[1] * TSingleArray(FInput)[1]; for i := 1 to FFrameSizeH - 1 do begin frame.Data[i] := TSingleArray(FInput)[2 * i] * TSingleArray(FInput)[2 * i] + TSingleArray(FInput)[2 * i + 1] * TSingleArray(FInput)[2 * i + 1]; end; end; constructor TFFTAV.Create(frame_size: integer; window: TDoubleArray); var bits: integer; begin FFrameSize := frame_size; FFrameSizeH := frame_size div 2; FWindow := window; FInput := av_mallocz(sizeof(single) * frame_size); bits := -1; while frame_size > 0 do begin inc(bits); frame_size := frame_size shr 1; end; m_rdft_ctx := av_rdft_init(bits, DFT_R2C); end; destructor TFFTAV.Destroy; begin av_rdft_end(m_rdft_ctx); av_free(FInput); SetLength(FWindow, 0); inherited; end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@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. * ********************************************************************************************************************** * TERRA_ObjectArray * Implements a generic thread safe array of objects *********************************************************************************************************************** } Unit TERRA_ObjectArray; {$I terra.inc} Interface Uses TERRA_String, TERRA_Utils, TERRA_Collections; Type ObjectArray = Class(Collection) Protected _Objects:Array Of CollectionObject; Procedure RemoveDiscardedItems(); Override; Public Constructor Create(Options:Cardinal; ShareItemsWith:ObjectArray); Function GetIterator:Iterator; Override; Procedure Clear(); Override; Function Add(Item:CollectionObject):Boolean; Function Delete(Item:CollectionObject):Boolean; Function GetItemByIndex(Index:Integer):CollectionObject; Override; End; Implementation Uses TERRA_Log; Type ObjectArrayIterator = Class(Iterator) Protected Function ObtainNext:CollectionObject; Override; End; { ObjectArray } Constructor ObjectArray.Create(Options:Cardinal; ShareItemsWith:ObjectArray); Begin _SortOrder := collection_Unsorted; _ItemCount := 0; Self.Init(Options, ShareItemsWith); End; Function ObjectArray.Add(Item: CollectionObject): Boolean; Begin If Item = Nil Then Begin Result := False; Exit; End; Self.Lock(); Item.Link(Self); Inc(_ItemCount); SetLength(_Objects, _ItemCount); _Objects[Pred(_ItemCount)] := Item; Self.Unlock(); Result := True; End; Function ObjectArray.Delete(Item: CollectionObject): Boolean; Var I:Integer; Begin Result := False; If Item = Nil Then Exit; Self.Lock(); { For I:=0 To Pred(_ItemCount) Do If (_Objects[I] = Item) Then Begin _Objects[I].Discard(); Result := True; Break; End;} I := 0; While I<_ItemCount Do If (_Objects[I] = Item) Then Begin _Objects[I] := _Objects[Pred(_ItemCount)]; Dec(_ItemCount); End Else Inc(I); Self.Unlock(); End; Procedure ObjectArray.RemoveDiscardedItems; Var I:Integer; Begin I := 0; While I<_ItemCount Do If (_Objects[I].Discarded) Then Begin _Objects[I] := _Objects[Pred(_ItemCount)]; Dec(_ItemCount); End Else Inc(I); End; Procedure ObjectArray.Clear; Begin Self.Lock(); _ItemCount := 0; Self.Unlock(); End; Function ObjectArray.GetItemByIndex(Index: Integer): CollectionObject; Begin If (Index<0) Or (Index>=_ItemCount) Then Result := Nil Else Result := _Objects[Index]; End; Function ObjectArray.GetIterator: Iterator; Begin Result := ObjectArrayIterator.Create(Self); End; { ObjectArrayIterator } Function ObjectArrayIterator.ObtainNext: CollectionObject; Begin If (Self.Index< Self.Collection.Count) Then Result := ObjectArray(Self.Collection)._Objects[Self.Index] Else Result := Nil; End; End.
{ File: CFNetwork/CFProxySupport.h Contains: Support for computing which proxy applies when Version: CFNetwork-219~1 Copyright: © 2006 by Apple Computer, Inc., all rights reserved } { Pascal Translation: Gale R Paeper, <gpaeper@empirenet.com>, 2008 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CFProxySupport; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes, CFArray, CFBase, CFDictionary, CFURL, CFError, CFRunLoop, CFStream; {$ALIGN POWER} { These APIs return arrays of dictionaries, where each dictionary describes a single proxy. The arrays represent the order in which the proxies should be tried - try to download the URL using the first entry in the array, and if that fails, try using the second entry, and so on. The keys to the proxy dictionaries follow the function declarations; every proxy dictionary will have an entry for kCFProxyTypeKey. If the type is anything except kCFProxyTypeAutoConfigurationURL, the dictionary will also have entries for the proxy's host and port (under kCFProxyHostNameKey and kCFProxyPortNumberKey respectively). If the type is kCFProxyTypeAutoConfigurationURL, it will have an entry for kCFProxyAutoConfigurationURLKey. The keys for username and password are optional and will only be present if the username or password could be extracted from the information passed in (i.e. either the URL itself or the proxy dictionary supplied). These APIs do not consult any external credential stores (such as the Keychain). } { * CFNetworkCopyProxiesForURL() * * Discussion: * Given a URL and a proxy dictionary, determines the ordered list * of proxies that should be used to download the given URL. * * Parameters: * * url: * The URL to be accessed * * proxySettings: * A dictionary describing the available proxy settings; the * dictionary's format should match that described in and returned * by SystemConfiguration.framework * * Result: * An array of dictionaries; each dictionary describes a single * proxy. See the comment at the top of this file for how to * interpret the returned dictionaries. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } function CFNetworkCopyProxiesForURL( url: CFURLRef; proxySettings: CFDictionaryRef ): CFArrayRef; external name '_CFNetworkCopyProxiesForURL'; (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * CFProxyAutoConfigurationResultCallback * * Discussion: * Callback function to be called when a PAC file computation * (initiated by either CFNetworkExecuteProxyAutoConfigurationScript * or CFNetworkExecuteProxyAutoConfigurationURL) has completed. * * Parameters: * * client: * The client reference passed in to * CFNetworkExecuteProxyAutoConfigurationScript or * CFNetworkExecuteProxyAutoConfigurationURL * * proxyList: * Upon success, the list of proxies returned by the * autoconfiguration script. The list has the same format as * returned by CFProxyCopyProxiesForURL, above, except that no * entry may be of type kCFProxyTypeAutoConfigurationURL. Note * that if the client wishes to keep this list, they must retain * it when they receive this callback. * * error: * Upon failure, an error object explaining the failure. } type CFProxyAutoConfigurationResultCallback = procedure( client: UnivPtr; proxyList: CFArrayRef; error: CFErrorRef ); { * CFNetworkCopyProxiesForAutoConfigurationScript() * * Discussion: * Begins the process of executing proxyAutoConfigurationScript to * determine the correct proxy to use to retrieve targetURL. The * caller should schedule the returned run loop source; when the * results are found, the caller's callback will be called via the * run loop, passing a valid proxyList and NULL error upon success, * or a NULL proxyList and valid error on failure. The caller * should invalidate the returned run loop source if it wishes to * terminate the request before completion. * * Parameters: * * proxyAutoConfigurationScript: * A CFString containing the code of the script to be executed. * * targetURL: * The URL that should be input in to the autoconfiguration script * * Result: * An array of dictionaries describing the proxies returned by the * script. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } function CFNetworkCopyProxiesForAutoConfigurationScript( proxyAutoConfigurationScript: CFStringRef; targetURL: CFURLRef ): CFArrayRef; external name '_CFNetworkCopyProxiesForAutoConfigurationScript'; (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * CFNetworkExecuteProxyAutoConfigurationURL() * * Discussion: * As CFNetworkExecuteProxyAutoConfigurationScript(), above, except * that CFNetworkExecuteProxyAutoConfigurationURL will additionally * download the contents of proxyAutoConfigURL, convert it to a * JavaScript string, and then execute that script. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } function CFNetworkExecuteProxyAutoConfigurationURL( proxyAutoConfigURL: CFURLRef; targetURL: CFURLRef; cb: CFProxyAutoConfigurationResultCallback; var clientContext: CFStreamClientContext ): CFRunLoopSourceRef; external name '_CFNetworkExecuteProxyAutoConfigurationURL'; (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyTypeKey * * Discussion: * Key for the type of proxy being represented; value will be one of * the kCFProxyType constants listed below. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyTypeKey: CFStringRef; external name '_kCFProxyTypeKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyHostNameKey * * Discussion: * Key for the proxy's hostname; value is a CFString. Note that * this may be an IPv4 or IPv6 dotted-IP string. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyHostNameKey: CFStringRef; external name '_kCFProxyHostNameKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyPortNumberKey * * Discussion: * Key for the proxy's port number; value is a CFNumber specifying * the port on which to contact the proxy * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyPortNumberKey: CFStringRef; external name '_kCFProxyPortNumberKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyAutoConfigurationURLKey * * Discussion: * Key for the proxy's PAC file location; this key is only present * if the proxy's type is kCFProxyTypeAutoConfigurationURL. Value * is a CFURL specifying the location of a proxy auto-configuration * file * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyAutoConfigurationURLKey: CFStringRef; external name '_kCFProxyAutoConfigurationURLKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyUsernameKey * * Discussion: * Key for the username to be used with the proxy; value is a * CFString. Note that this key will only be present if the username * could be extracted from the information passed in. No external * credential stores (like the Keychain) are consulted. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyUsernameKey: CFStringRef; external name '_kCFProxyUsernameKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyPasswordKey * * Discussion: * Key for the password to be used with the proxy; value is a * CFString. Note that this key will only be present if the username * could be extracted from the information passed in. No external * credential stores (like the Keychain) are consulted. * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyPasswordKey: CFStringRef; external name '_kCFProxyPasswordKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { Possible values for kCFProxyTypeKey: kCFProxyTypeNone - no proxy should be used; contact the origin server directly kCFProxyTypeHTTP - the proxy is an HTTP proxy kCFProxyTypeHTTPS - the proxy is a tunneling proxy as used for HTTPS kCFProxyTypeSOCKS - the proxy is a SOCKS proxy kCFProxyTypeFTP - the proxy is an FTP proxy kCFProxyTypeAutoConfigurationURL - the proxy is specified by a proxy autoconfiguration (PAC) file } { * kCFProxyTypeNone * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyTypeNone: CFStringRef; external name '_kCFProxyTypeNone'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyTypeHTTP * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyTypeHTTP: CFStringRef; external name '_kCFProxyTypeHTTP'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyTypeHTTPS * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyTypeHTTPS: CFStringRef; external name '_kCFProxyTypeHTTPS'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyTypeSOCKS * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyTypeSOCKS: CFStringRef; external name '_kCFProxyTypeSOCKS'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyTypeFTP * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyTypeFTP: CFStringRef; external name '_kCFProxyTypeFTP'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) { * kCFProxyTypeAutoConfigurationURL * * Availability: * Mac OS X: in version 10.5 and later in CoreServices.framework * CarbonLib: not available * Non-Carbon CFM: not available } var kCFProxyTypeAutoConfigurationURL: CFStringRef; external name '_kCFProxyTypeAutoConfigurationURL'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER *) end.
unit ManifestCostMaster; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, DBGrids, currEdit, BmDtEdit, NUMMIBmDateEdit, DB; type TManifestCostMaster_Form = class(TForm) PartsStockMaster_Label: TLabel; MonthlyPOMaster_DBGrid: TDBGrid; ManagementButtons_Panel: TPanel; Insert_Button: TButton; Update_Button: TButton; Search_Button: TButton; Clear_Button: TButton; Close_Button: TButton; Delete_Button: TButton; ManifestCost_Panel: TPanel; BasisUnitPrice_Label: TLabel; AssyCode_Label: TLabel; InTransit_Label: TLabel; Arrival_Label: TLabel; SizeCode_Label: TLabel; AssyCode_ComboBox: TComboBox; CostStart_NUMMIBmDateEdit: TNUMMIBmDateEdit; CostEnd_NUMMIBmDateEdit: TNUMMIBmDateEdit; AssyCost_MaskEdit: TcurrEdit; MAnifestCost_DataSource: TDataSource; AssyManifestID_ComboBox: TComboBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Clear_ButtonClick(Sender: TObject); procedure Search_ButtonClick(Sender: TObject); procedure Delete_ButtonClick(Sender: TObject); procedure Update_ButtonClick(Sender: TObject); procedure Insert_ButtonClick(Sender: TObject); procedure MAnifestCost_DataSourceDataChange(Sender: TObject; Field: TField); private { Private declarations } procedure SetDetailBoxes; procedure HoldDetails(fFromGrid: Boolean); function SearchGrid(AssyCode: String): Boolean; procedure GetParts(tablename, selectfieldname, fPartType, returnfieldname: String; ComboBox: TComboBox); public { Public declarations } function Execute:boolean; end; var ManifestCostMaster_Form: TManifestCostMaster_Form; implementation uses DataModule; {$R *.dfm} procedure TManifestCostMaster_Form.SetDetailBoxes; begin With Data_Module do Begin try SearchCombo(AssyCode_ComboBox, AssyCode); //AssyCode_ComboBox.Text:=AssyCode; SearchCombo(AssyManifestID_ComboBox, AssyManifestNo); //AssyCode_ComboBox.Text:=AssyManifestNo; CostStart_NUMMIBmDateEdit.Date:=StrTodate(copy(POStart,5,2)+'/'+copy(POStart,7,2)+'/'+copy(POStart,1,4)); CostEnd_NUMMIBmDateEdit.Date:=StrTodate(copy(POEnd,5,2)+'/'+copy(POEnd,7,2)+'/'+copy(POEnd,1,4)); AssyCost_MaskEdit.Text:=FormatFloat('$#######0.0000', AssyCost); except on e:exception do begin end; end; End; //With end; procedure TManifestCostMaster_Form.HoldDetails(fFromGrid: Boolean); var ftempprice:string; ftempdouble:double; begin If fFromGrid Then Begin with MonthlyPOMaster_DBGrid.DataSource.DataSet do begin Data_Module.RecordID := Fields[0].AsInteger; Fields[0].Visible:=FALSE; Data_Module.AssyCode := Fields[1].AsString; Data_Module.AssyManifestNo := Fields[2].AsString; Data_Module.POStart := Fields[3].AsString; Data_Module.POEnd := Fields[4].AsString; Data_Module.AssyCost := Fields[5].AsFloat; end; End Else Begin With Data_Module do Begin POStart:=formatdatetime('yyyymmdd',CostStart_NUMMIBmDateEdit.Date); POEnd:=formatdatetime('yyyymmdd',CostEnd_NUMMIBmDateEdit.Date); AssyCode:=AssyCode_ComboBox.Text; AssyManifestNo := AssyManifestID_ComboBox.Text; fTempPrice := AssyCost_MaskEdit.Text; //the 2 in the copy statement is to skip the dollar sign fTempPrice := Trim(Copy(fTempPrice, 2, Length(fTempPrice))); If Not TryStrToFloat(fTempPrice, fTempDouble) Then begin ShowMessage('Invalid assembly cost'); AssyCost_MaskEdit.SetFocus; end Else AssyCost := fTempDouble; //StrToFloat(BasisUnitPrice_Edit.Text); End; //With End; end; function TManifestCostMaster_Form.SearchGrid(AssyCode: String): Boolean; begin Result := False; Data_Module.ClearControls(ManifestCost_Panel); try With Data_Module.Inv_DataSet Do Begin Filtered := False; if AssyCode <> ' ' then Filter := '[Assy] LIKE ' + QuotedStr(AssyCode); Filtered := True; If RecordCount > 0 Then Begin HoldDetails(True); Result := True; End; End; //With except on e:exception do ShowMessage('Error in Search' + #13 + e.Message); end; //try...except end; procedure TManifestCostMaster_Form.GetParts(tablename, selectfieldname, fPartType, returnfieldname: String; ComboBox: TComboBox); var fTableAndWhere: String; Begin try try if selectfieldname <> '' then fTableAndWhere := tablename+' WHERE '+selectfieldname+' = ' + QuotedStr(fPartType) else fTableAndWhere := tablename; Data_Module.SelectSingleField(fTableAndWhere, returnfieldname, ComboBox); except On e:exception do Begin MessageDlg('Unable to get a list of parts.', mtError, [mbOK], 0); End; end; //try...except finally end; //try...finally end; function TManifestCostMaster_Form.Execute:boolean; begin Result:= True; try try ShowModal; except On E:Exception do begin showMessage('Unable to generate Manifest Cost screen.' + #13 + 'ERROR:' + #13 + E.Message); end; end; finally If ModalResult = mrCancel Then Result:= False; end; end; procedure TManifestCostMaster_Form.FormCreate(Sender: TObject); var i:integer; begin AssyManifestID_ComboBox.Items.Clear; AssyManifestID_ComboBox.Items.Add(' '); for i:=1 to 99 do begin if i<10 then AssyManifestID_ComboBox.Items.Add('0'+IntToStr(i)) else AssyManifestID_ComboBox.Items.Add(IntToStr(i)); end; With Data_Module do Begin Inv_DataSet.Filter:=''; Inv_DataSet.Filtered:=FALSE; GetManifestCostInfo; ManifestCost_DataSource.DataSet:=Inv_DataSet; Data_Module.ClearControls(ManifestCost_Panel); Data_Module.Inv_DataSet.Filtered := False; End; //With end; procedure TManifestCostMaster_Form.FormShow(Sender: TObject); begin AssyCode_ComboBox.SetFocus; GetParts('INV_FORECAST_DETAIL_INF', '', '', 'VC_ASSY_PART_NUMBER_CODE', AssyCode_ComboBox); Data_Module.Inv_DataSet.First; end; procedure TManifestCostMaster_Form.Clear_ButtonClick(Sender: TObject); begin with Data_Module do begin Inv_Dataset.Filtered:=False; ClearControls(ManifestCost_Panel); end; AssyCode_ComboBox.SetFocus; end; procedure TManifestCostMaster_Form.Search_ButtonClick(Sender: TObject); var ffound:boolean; begin If (Trim(AssyCode_ComboBox.Text ) = '') Then ShowMessage('Please enter a assembly code before searching.') Else Begin fFound := SearchGrid(AssyCode_ComboBox.Text); If fFound Then Begin SetDetailBoxes; End Else Begin ShowMessage('No matches were found for your query.'); End; end; AssyCode_ComboBox.SetFocus; end; procedure TManifestCostMaster_Form.Delete_ButtonClick(Sender: TObject); begin HoldDetails(False); If MessageDlg('Are you sure you wish to delete Assy Number '+ Data_Module.AssyCode + #13 + 'From '+ Data_Module.POStart + #13 + 'To '+ Data_Module.POEnd + #13 + ' from the database?', mtWarning, [mbYes, mbNo], 0) = mrYes Then Begin Data_Module.DeleteManifestCostInfo; Data_Module.GetManifestCostInfo; Data_Module.ClearControls(ManifestCost_Panel); Data_Module.Inv_DataSet.Filtered := False; Data_Module.Inv_DataSet.First; End; AssyCode_ComboBox.SetFocus; end; procedure TManifestCostMaster_Form.Update_ButtonClick(Sender: TObject); var Assy,SMan,EMan:string; begin with Data_Module do begin HoldDetails(False); UpdateManifestCostInfo; Assy:=AssyCode; SMan:=POStart; EMan:=POEnd; GetManifestCostInfo; Inv_Dataset.Filtered := False; Inv_DataSet.Locate('Assy;Start Manifest;End Manifest',VarArrayOf([Assy,SMan,EMan]),[]); end; SetDetailBoxes; AssyCode_ComboBox.SetFocus; end; procedure TManifestCostMaster_Form.Insert_ButtonClick(Sender: TObject); var Assy,SMan,EMan:string; begin HoldDetails(False); with Data_Module do begin If Not InsertManifestCostInfo Then MessageDlg('Unable to INSERT ' + Data_Module.AssyCode, mtInformation, [mbOk], 0) else begin Assy:=AssyCode; SMan:=POStart; EMan:=POEnd; GetManifestCostInfo; Inv_Dataset.Filtered := False; Inv_DataSet.Locate('Assy;Start Manifest;End Manifest',VarArrayOf([Assy,SMan,EMan]),[]); end; end; SetDetailBoxes; AssyCode_ComboBox.SetFocus; end; procedure TManifestCostMaster_Form.MAnifestCost_DataSourceDataChange( Sender: TObject; Field: TField); begin HoldDetails(True); SetDetailBoxes; end; end.
unit IdFTPListParsePCTCP; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase; type TIdPCTCPFTPListItem = class(TIdFTPListItem); TIdFTPLPPCTCPNet = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; (*HPPEMIT '#pragma link "IdFTPListParseWinQVTNET"'*) // 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 "IdFTPListParseWinQVTNET"'*) { THis is a parser for "PC/TCP v 2.11 ftpsrv.exe". This was a part of the PC/TCP suite from FTP Software Inc. based on http://www.farmanager.com/viewvc/plugins/ftp/trunk/lib/DirList/pr_pctcp.cpp?revision=275&view=markup&pathrev=788 Note that no source-code was used, just the listing data. PC/TCP ftpsrv.exe looks like 1 2 3 4 5 6 0123456789012345678901234567890123456789012345678901234567890 ------------------------------------------------------------- 1 2 3 4 5 6 123456789012345678901234567890123456789012345678901234567890 ------------------------------------------------------------- 40774 IO.SYS Tue May 31 06:22:00 1994 38138 MSDOS.SYS Tue May 31 06:22:00 1994 54645 COMMAND.COM Tue May 31 06:22:00 1994 <dir> UTIL Thu Feb 20 09:55:02 2003 } implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; { TIdFTPLPPCTCPNet } class function TIdFTPLPPCTCPNet.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var LData : String; begin Result := False; if AListing.Count > 0 then begin LData := AListing[0]; //size or dir Result := (LData ='<dir>') or IsNumeric(Trim(Copy(LData,1,10))); //file name if Result then begin Result := Trim(Copy(LData,11,19))<> ''; end; //day of week if Result then begin Result := StrToDay(Trim(Copy(LData,31,7))) > 0; end; //month if Result then begin Result := StrToMonth(Copy(LData,38,3)) > 0; end; //day if Result then begin Result := StrToIntDef(Copy(LData,42,2),0) > 0; end; //time if Result then begin Result := IsHHMMSS(Copy(LData,45,8),':'); end; //year if Result then begin Result := IsNumeric(Trim(Copy(LData,54,4))); end; end; end; class function TIdFTPLPPCTCPNet.GetIdent: String; begin Result := 'PC/TCP ftpsrv.exe'; end; class function TIdFTPLPPCTCPNet.MakeNewItem( AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdPCTCPFTPListItem.Create(AOwner); end; class function TIdFTPLPPCTCPNet.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LData : String; LPt : String; LMonth : Word; LDay : Word; LYear : Word; begin Result := False; LData := TrimLeft(AItem.Data); LPt := Fetch(LData); //dir or file size if LPt = '<dir>' then begin AItem.ItemType := ditDirectory; AItem.SizeAvail := False; end else begin if IsNumeric(LPt) then begin AItem.Size := StrToIntDef(LPt,0); AItem.SizeAvail := True; end else begin exit; end; end; //file name LData := TrimLeft(LData); LPt := Fetch(LData); if LPt = '' then begin Exit; end else begin AItem.FileName := LPt; end; //Day of week LData := TrimLeft(LData); LPt := Fetch(LData); if StrToDay(LPt) < 1 then begin exit; end; //month LData := TrimLeft(LData); LPt := Fetch(LData); LMOnth := StrToMonth(LPt); if LMonth < 1 then begin exit; end; //day LData := TrimLeft(LData); LPt := Fetch(LData); LDay := StrToIntDef(LPt,0); if LDay = 0 then begin exit; end; //time LData := TrimLeft(LData); LPt := Fetch(LData); if not IsHHMMSS(LPt,':') then begin exit; end; AItem.ModifiedDate := TimeHHMMSS(LPt); //year LData := TrimLeft(LData); LPt := Fetch(LData); LYear := StrToIntDef(LPt,$FFFF); if LYear = $FFFF then begin Exit; end; LYear := Y2Year(LYear); AItem.ModifiedDate := AItem.ModifiedDate + EncodeDate(LYear,LMonth,LDay); AItem.ModifiedAvail := True; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPPCTCPNet); finalization UnRegisterFTPListParser(TIdFTPLPPCTCPNet); end.
unit GX_KibitzComp; {$I GX_CondDefine.inc} {$IFDEF GX_VER150_up} // Delphi 7+ {$DEFINE GX_KIBITZ_OTA} {$ENDIF GX_VER150_up} interface uses Classes, ToolsAPI; procedure GetKibitzSymbols(const SourceEditor: IOTASourceEditor; const EditControl: TObject; const EditView: IOTAEditView; const XPos, YPos: Integer; const SourceString, TrailingCharacters: string; Strings: TStrings); function KibitzEnabled: Boolean; function KibitzOta: Boolean; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} Windows, SysUtils, GX_OtaUtils, GX_IdeUtils, GX_GenericUtils; type PObject = ^TObject; TSymbols = packed array[0..(MaxInt div SizeOf(Integer)) - 1] of Integer; PSymbols = ^TSymbols; TUnknowns = packed array [0..(MaxInt div SizeOf(Byte)) - 1] of Byte; PUnknowns = ^TUnknowns; // Verified for D6, should work for D7 now as well TKibitzResult = packed record {$IFDEF GX_VER150_up} KibitzDataArray: array [0..82] of Integer; {$ELSE} KibitzDataArray: array [0..81] of Integer; {$ENDIF} KibitzDataStr: AnsiString; KibitzReserveArray: array[0..255] of Integer; end; {$IFNDEF GX_KIBITZ_OTA} const {$IFDEF VER140} CorIdeLibName = 'coreide60.bpl'; {$IFDEF BCB} DphIdeLibName = 'bcbide60.bpl'; {$ELSE not BCB} DphIdeLibName = 'delphide60.bpl'; {$ENDIF BCB} dccLibName = 'dcc60.dll'; {$DEFINE LibNamesDefined} {$ENDIF VER140} // dphideXX.bpl // Codcmplt.TCodeCompletionManger.GetKibitzInfo(XPos, YPos: Integer; var KibitzResult: TKibitzResult); GetKibitzInfoName = '@Codcmplt@TCodeCompletionManager@GetKibitzInfo$qqriir22Comtypes@TKibitzResult'; // Codcmplt.CodeCompletionManager: TCodeCompletionManager; CodeCompletionManagerName = '@Codcmplt@CodeCompletionManager'; // dccXX.dll // KibitzGetValidSymbols(var KibitzResult: TKibitzResult; Symbols: PSymbols; Unknowns: PUnknowns; SymbolCount: Integer): Integer; stdcall; KibitzGetValidSymbolsName = 'KibitzGetValidSymbols'; // corideXX.bpl // Comdebug.CompGetSymbolText(Symbol: PSymbols; var S: string; Unknown: Word); stdcall; CompGetSymbolTextName = '@Comdebug@CompGetSymbolText$qqsp16Comtypes@TSymbolr17System@AnsiStringus'; type TGetKibitzInfoProc = procedure(Self: TObject; XPos, YPos: Integer; var KibitzResult: TKibitzResult); register; TKibitzGetValidSymbolsProc = function(var KibitzResult: TKibitzResult; Symbols: PSymbols; Unknowns: PUnknowns; SymbolCount: Integer): Integer; stdcall; TCompGetSymbolTextProc = procedure(Symbol: Integer {Comtypes::TSymbol*}; var S: string; Unknown: Word); stdcall; var GetKibitzInfo: TGetKibitzInfoProc; KibitzGetValidSymbols: TKibitzGetValidSymbolsProc; CompGetSymbolText: TCompGetSymbolTextProc; CodeCompletionManager: PObject; {$ENDIF GX_KIBITZ_OTA} var HaveInitialized: Boolean = False; PrivateKibitzEnabled: Boolean = False; {$IFNDEF GX_KIBITZ_OTA} var CorIdeModule: HModule; DphIdeModule: HModule; dccModule: HModule; {$ENDIF GX_KIBITZ_OTA} function Initialize: Boolean; begin if HaveInitialized then begin Result := PrivateKibitzEnabled; Exit; end; Result := False; HaveInitialized := True; if IsStandAlone or RunningCPPBuilder then Exit; {$IFDEF GX_KIBITZ_OTA} if (BorlandIDEServices = nil) then begin {$IFOPT D+}SendDebugError('BorlandIDEServices unavailable');{$ENDIF} Exit; end; if not Supports(BorlandIDEServices, IOTACodeInsightServices) then begin {$IFOPT D+}SendDebugError('BorlandIDEServices does not support IOTACodeInsightServices');{$ENDIF} Exit; end; {$ELSE not GX_KIBITZ_OTA} DphIdeModule := LoadPackage(DphIdeLibName); if DphIdeModule = 0 then begin {$IFOPT D+}SendDebugError('Failed to load DphIdeModule');{$ENDIF} Exit; end; CodeCompletionManager := GetProcAddress(DphIdeModule, CodeCompletionManagerName); if not Assigned(CodeCompletionManager) then begin {$IFOPT D+}SendDebugError('Failed to load CodeCompletionManager from DphIdeModule');{$ENDIF} Exit; end; GetKibitzInfo := GetProcAddress(DphIdeModule, GetKibitzInfoName); if not Assigned(GetKibitzInfo) then begin {$IFOPT D+}SendDebugError('Failed to load GetKibitzInfo from DphIdeModule');{$ENDIF} Exit; end; dccModule := LoadLibrary(dccLibName); if dccModule = 0 then begin {$IFOPT D+}SendDebugError('Failed to load dccModule');{$ENDIF} Exit; end; KibitzGetValidSymbols := GetProcAddress(dccModule, KibitzGetValidSymbolsName); if not Assigned(KibitzGetValidSymbols) then begin {$IFOPT D+}SendDebugError('Failed to load KibitzGetValidSymbols from dccModule');{$ENDIF} Exit; end; CorIdeModule := LoadPackage(CorIdeLibName); if CorIdeModule = 0 then begin {$IFOPT D+}SendDebugError('Failed to load CorIdeModule');{$ENDIF} Exit; end; CompGetSymbolText := GetProcAddress(CorIdeModule, CompGetSymbolTextName); if not Assigned(CompGetSymbolText) then begin {$IFOPT D+}SendDebugError('Failed to load CompGetSymbolText');{$ENDIF} Exit; end; {$ENDIF GX_KIBITZ_OTA} // If everything succeeded set KibitzEnabled to True. PrivateKibitzEnabled := True; Result := KibitzEnabled; end; function KibitzEnabled: Boolean; begin Initialize; Result := PrivateKibitzEnabled; end; function KibitzOta: Boolean; begin {$IFDEF GX_KIBITZ_OTA} Result := True; {$ELSE} Result := False; {$ENDIF} end; procedure Finalize; begin {$IFNDEF GX_KIBITZ_OTA} if CorIdeModule <> 0 then begin UnLoadPackage(CorIdeModule); CorIdeModule := 0; end; if dccModule <> 0 then begin FreeLibrary(dccModule); dccModule := 0; end; if DphIdeModule <> 0 then begin UnLoadPackage(DphIdeModule); DphIdeModule := 0; end; {$ENDIF GX_KIBITZ_OTA} end; // XPos starts a 0; YPos at 1. procedure GetKibitzSymbols(const SourceEditor: IOTASourceEditor; const EditControl: TObject; const EditView: IOTAEditView; const XPos, YPos: Integer; const SourceString, TrailingCharacters: string; Strings: TStrings); {$IFDEF GX_KIBITZ_OTA} var NewCharPos: TOTACharPos; NewCursorPos: TOTAEditPos; OldCursorPos: TOTAEditPos; ManagerIndex: Integer; CodeInsightServices: IOTACodeInsightServices; CodeInsightManager: IOTACodeInsightManager; procedure AddManagerSymbolsToList(CurrentCodeInsightManager: IOTACodeInsightManager); var Allow: Boolean; ElementAttribute: Integer; LineFlag: Integer; FirstChar: Char; CodeInsightType: TOTACodeInsightType; InvokeType: TOTAInvokeType; ValidChars: TSysCharSet; CodeInsightSymbolList: IOTACodeInsightSymbolList; SymbolCount: Integer; SymbolIndex: Integer; Symbol: string; DisplayParams: Boolean; begin if not CurrentCodeInsightManager.Enabled then Exit; if not CurrentCodeInsightManager.HandlesFile(SourceEditor.FileName) then Exit; CodeInsightServices.SetQueryContext(EditView, CodeInsightManager); try Allow := True; CurrentCodeInsightManager.AllowCodeInsight(Allow, #0); if not Allow then Exit; // otherwise you will get an AV in 'InvokeCodeCompletion' EditView.GetAttributeAtPos(EditView.CursorPos, False, ElementAttribute, LineFlag); {$IFNDEF GX_VER150_up} if TrailingCharacters = '' then FirstChar := #0 else FirstChar := TrailingCharacters[1]; {$ELSE} // Without this, Delphi 7 and 2005 pop up a dialog stating "Unable to invoke // Code Completion due to errors in source code" with unknown identifiers FirstChar := CodeInsightKeySymbolHint; {$ENDIF GX_VER150_up} CurrentCodeInsightManager.GetCodeInsightType(FirstChar, ElementAttribute, CodeInsightType, InvokeType); (* There is a bug here that you can reproduce as follows: 1. Drop a TButton on a form (Button1) 2. Double click on Button1 3. between the begin/end pair, enter this code: 'Buttn1.' (withoout quotes) //exp: CurrentCodeInsightManager.InvokeCodeCompletion returns 'True' //act: CurrentCodeInsightManager.InvokeCodeCompletion returns' False' and you get an error message indicating that the code does not compile: 'Unable to invoke Code Completion due to errors in source code' 4. between the begin/end pair, enter this code: 'Buttn1 ' //exp: CurrentCodeInsightManager.InvokeCodeCompletion returns 'True' //act: CurrentCodeInsightManager.InvokeCodeCompletion returns 'True' and 'Buttn1 ' gets replaced by 'Button1 ' I tried some tricks around this: - replace any InvokeType=itTimer by InvokeType=itManual (does not resolve) - ignore the "False" result from "InvokeCodeCompletion" (does not resolve - the resulting symbol list is zero (0) symbols long - don't call "CurrentCodeInsightManager.GetCodeInsightType" (error message comes in a dialog, in stead of the messages pane) - replace "FirstChar = '.'" with "FirstChar := ' '" (error message comes in a dialog, instead of the messages pane) One solution might be to (temporarily) replace the '.' in the code editor with a ' ', and at the end restore the '.', but this adds to the undo stack. *) // Not used, but the IDE calls it in this order, and the calling order might be important. ValidChars := CurrentCodeInsightManager.EditorTokenValidChars(False); try Symbol := SourceString; if not CurrentCodeInsightManager.InvokeCodeCompletion(InvokeType, Symbol) then Exit; try CurrentCodeInsightManager.GetSymbolList(CodeInsightSymbolList); if (CodeInsightSymbolList = nil) then Exit; SymbolCount := CodeInsightSymbolList.Count; // Expand string list to the needed capacity so that it does not // have to be resized while adding symbols in the loop below. Strings.Capacity := (Strings.Capacity - Strings.Count) + SymbolCount; for SymbolIndex := 0 to SymbolCount - 1 do Strings.Add(CodeInsightSymbolList.GetSymbolText(SymbolIndex)); finally DisplayParams := False; CurrentCodeInsightManager.Done(False, DisplayParams); end; except on E: Exception do {$IFOPT D+}SendDebugError('Exception: ' + E.Message);{$ENDIF} end; finally if RunningBDS2006OrGreater {and (StrContains('pascal', CodeInsightManager.Name))} then CodeInsightServices.SetQueryContext(nil, CodeInsightManager) else CodeInsightServices.SetQueryContext(nil, nil); // This crashes BDS 2006 for some reason? end; end; begin Initialize; // Exit if kibitzing is not enabled, or the IDE is debugging. if (not KibitzEnabled) or GxOtaCurrentlyDebugging then Exit; NewCharPos.CharIndex := XPos; NewCharPos.Line := YPos; EditView.ConvertPos(False, NewCursorPos, NewCharPos); OldCursorPos := EditView.CursorPos; try // finally restore cursor position CodeInsightServices := (BorlandIDEServices as IOTACodeInsightServices); // Due to a bug in OTA, you sometimes cannot request the // GetCurrentCodeInsightManager - it just returns 'nil' CodeInsightServices.GetCurrentCodeInsightManager(CodeInsightManager); if (CodeInsightManager = nil) then begin // So we ask all the managers to provide their list of symbols for ManagerIndex := 0 to CodeInsightServices.CodeInsightManagerCount - 1 do begin CodeInsightManager := CodeInsightServices.CodeInsightManager[ManagerIndex]; AddManagerSymbolsToList(CodeInsightManager); end; end else AddManagerSymbolsToList(CodeInsightManager); finally EditView.CursorPos := OldCursorPos; end; end; {$ELSE} var KibitzResult: TKibitzResult; SymbolCount: Integer; Unknowns: PUnknowns; Symbols: PSymbols; i: Integer; S: string; OldEditControl: TObject; MagicEditControlHolder: PObject; begin Initialize; // Exit if kibitzing is not enabled, or the IDE is debugging. if (not KibitzEnabled) or GxOtaCurrentlyDebugging then Exit; // Save the old edit control (I don't know if it is necessary but it won't do harm). MagicEditControlHolder := PObject(PAnsiChar(CodeCompletionManager^) + 4); OldEditControl := MagicEditControlHolder^; Assert((OldEditControl = nil) or (OldEditControl.ClassName = 'TEditControl')); MagicEditControlHolder^ := EditControl; try // Get general kibitzinfo. GetKibitzInfo(CodeCompletionManager^, XPos, YPos, KibitzResult); case Byte(KibitzResult.KibitzDataArray[0]) of $0B, $08, $09: Exit; else // Get valid symbol count. SymbolCount := KibitzGetValidSymbols(KibitzResult, nil, nil, MaxInt); // Allocate memory for symbols. GetMem(Symbols, SymbolCount * 4); try GetMem(Unknowns, SymbolCount); try // Get symbols. KibitzGetValidSymbols(KibitzResult, Symbols, Unknowns, SymbolCount); // Expand string list to the needed capacity // so that it does not have to be resized // while adding symbols in the loop below. Strings.Capacity := (Strings.Capacity - Strings.Count) + SymbolCount; Strings.BeginUpdate; try for i := 0 to SymbolCount - 1 do begin // Get the name of the symbol. CompGetSymbolText(Symbols^[i], S, 2); // Add the retrieved string to the list. Strings.Add(S); end; finally Strings.EndUpdate; end; finally FreeMem(Unknowns); end; finally FreeMem(Symbols); end; end; finally // Restore the old edit control MagicEditControlHolder^ := OldEditControl; end; end; {$ENDIF GX_KIBITZ_OTA} initialization finalization Finalize; end.
{ File: MacLocales.p Contains: Types & prototypes for locale functions Version: Technology: Mac OS 9.0 Release: Universal Interfaces 3.4.2 Copyright: © 1998-2002 by Apple Computer, Inc., all rights reserved. Bugs?: For bug reports, consult the following page on the World Wide Web: http://www.freepascal.org/bugs.html } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit MacLocales; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,MacErrors; {$ALIGN MAC68K} { ------------------------------------------------------------------------------------------------- TYPES & CONSTANTS ------------------------------------------------------------------------------------------------- } type LocaleRef = ^SInt32; { an opaque 32-bit type } LocaleRefPtr = ^LocaleRef; { when a var xx:LocaleRef parameter can be nil, it is changed to xx: LocaleRefPtr } LocalePartMask = UInt32; const { bit set requests the following: } kLocaleLanguageMask = $00000001; { ISO 639-1 or -2 language code (2 or 3 letters) } kLocaleLanguageVariantMask = $00000002; { custom string for language variant } kLocaleScriptMask = $00000004; { ISO 15924 script code (2 letters) } kLocaleScriptVariantMask = $00000008; { custom string for script variant } kLocaleRegionMask = $00000010; { ISO 3166 country/region code (2 letters) } kLocaleRegionVariantMask = $00000020; { custom string for region variant } kLocaleAllPartsMask = $0000003F; { all of the above } type LocaleOperationClass = FourCharCode; { constants for LocaleOperationClass are in UnicodeUtilities interfaces } LocaleOperationVariant = FourCharCode; LocaleAndVariantPtr = ^LocaleAndVariant; LocaleAndVariant = record locale: LocaleRef; opVariant: LocaleOperationVariant; end; LocaleNameMask = UInt32; const { bit set requests the following: } kLocaleNameMask = $00000001; { name of locale } kLocaleOperationVariantNameMask = $00000002; { name of LocaleOperationVariant } kLocaleAndVariantNameMask = $00000003; { all of the above } { ------------------------------------------------------------------------------------------------- function PROTOTYPES ------------------------------------------------------------------------------------------------- } { Convert to or from LocaleRefs (and related utilities) } { * LocaleRefFromLangOrRegionCode() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleRefFromLangOrRegionCode(lang: LangCode; region: RegionCode; var locale: LocaleRef): OSStatus; external name '_LocaleRefFromLangOrRegionCode'; { * LocaleRefFromLocaleString() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleRefFromLocaleString(localeString: ConstCStringPtr; var locale: LocaleRef): OSStatus; external name '_LocaleRefFromLocaleString'; { * LocaleRefGetPartString() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleRefGetPartString(locale: LocaleRef; partMask: LocalePartMask; maxStringLen: ByteCount; var partString: char): OSStatus; external name '_LocaleRefGetPartString'; { * LocaleStringToLangAndRegionCodes() * * Availability: * Non-Carbon CFM: in LocalesLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleStringToLangAndRegionCodes(localeString: ConstCStringPtr; var lang: LangCode; var region: RegionCode): OSStatus; external name '_LocaleStringToLangAndRegionCodes'; { Enumerate locales for a LocaleOperationClass } { * LocaleOperationCountLocales() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleOperationCountLocales(opClass: LocaleOperationClass; var localeCount: ItemCount): OSStatus; external name '_LocaleOperationCountLocales'; { * LocaleOperationGetLocales() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleOperationGetLocales(opClass: LocaleOperationClass; maxLocaleCount: ItemCount; var actualLocaleCount: ItemCount; var localeVariantList: LocaleAndVariant): OSStatus; external name '_LocaleOperationGetLocales'; { Get names for a locale (or a region's language) } { * LocaleGetName() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleGetName(locale: LocaleRef; opVariant: LocaleOperationVariant; nameMask: LocaleNameMask; displayLocale: LocaleRef; maxNameLen: UniCharCount; var actualNameLen: UniCharCount; displayName: UniCharPtr): OSStatus; external name '_LocaleGetName'; { * LocaleCountNames() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleCountNames(locale: LocaleRef; opVariant: LocaleOperationVariant; nameMask: LocaleNameMask; var nameCount: ItemCount): OSStatus; external name '_LocaleCountNames'; { * LocaleGetIndName() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleGetIndName(locale: LocaleRef; opVariant: LocaleOperationVariant; nameMask: LocaleNameMask; nameIndex: ItemCount; maxNameLen: UniCharCount; var actualNameLen: UniCharCount; displayName: UniCharPtr; var displayLocale: LocaleRef): OSStatus; external name '_LocaleGetIndName'; { * LocaleGetRegionLanguageName() * * Availability: * Non-Carbon CFM: in LocalesLib 9.0 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleGetRegionLanguageName(region: RegionCode; var languageName: Str255): OSStatus; external name '_LocaleGetRegionLanguageName'; { Get names for a LocaleOperationClass } { * LocaleOperationGetName() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleOperationGetName(opClass: LocaleOperationClass; displayLocale: LocaleRef; maxNameLen: UniCharCount; var actualNameLen: UniCharCount; displayName: UniCharPtr): OSStatus; external name '_LocaleOperationGetName'; { * LocaleOperationCountNames() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleOperationCountNames(opClass: LocaleOperationClass; var nameCount: ItemCount): OSStatus; external name '_LocaleOperationCountNames'; { * LocaleOperationGetIndName() * * Availability: * Non-Carbon CFM: in LocalesLib 8.6 and later * CarbonLib: in CarbonLib 1.0 and later * Mac OS X: in version 10.0 and later } function LocaleOperationGetIndName(opClass: LocaleOperationClass; nameIndex: ItemCount; maxNameLen: UniCharCount; var actualNameLen: UniCharCount; displayName: UniCharPtr; var displayLocale: LocaleRef): OSStatus; external name '_LocaleOperationGetIndName'; {$ALIGN MAC68K} end.
unit InfoRULE78Table; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoRULE78Record = record PTerm: String[3]; PMonths: String[3]; PPercent: Currency; End; TInfoRULE78Class2 = class public PTerm: String[3]; PMonths: String[3]; PPercent: Currency; End; // function CtoRInfoRULE78(AClass:TInfoRULE78Class):TInfoRULE78Record; // procedure RtoCInfoRULE78(ARecord:TInfoRULE78Record;AClass:TInfoRULE78Class); TInfoRULE78Buffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoRULE78Record; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoRULE78 = (InfoRULE78PrimaryKey); TInfoRULE78Table = class( TDBISAMTableAU ) private FDFTerm: TStringField; FDFMonths: TStringField; FDFPercent: TCurrencyField; procedure SetPTerm(const Value: String); function GetPTerm:String; procedure SetPMonths(const Value: String); function GetPMonths:String; procedure SetPPercent(const Value: Currency); function GetPPercent:Currency; procedure SetEnumIndex(Value: TEIInfoRULE78); function GetEnumIndex: TEIInfoRULE78; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoRULE78Record; procedure StoreDataBuffer(ABuffer:TInfoRULE78Record); property DFTerm: TStringField read FDFTerm; property DFMonths: TStringField read FDFMonths; property DFPercent: TCurrencyField read FDFPercent; property PTerm: String read GetPTerm write SetPTerm; property PMonths: String read GetPMonths write SetPMonths; property PPercent: Currency read GetPPercent write SetPPercent; published property Active write SetActive; property EnumIndex: TEIInfoRULE78 read GetEnumIndex write SetEnumIndex; end; { TInfoRULE78Table } TInfoRULE78Query = class( TDBISAMQueryAU ) private FDFTerm: TStringField; FDFMonths: TStringField; FDFPercent: TCurrencyField; procedure SetPTerm(const Value: String); function GetPTerm:String; procedure SetPMonths(const Value: String); function GetPMonths:String; procedure SetPPercent(const Value: Currency); function GetPPercent:Currency; protected procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoRULE78Record; procedure StoreDataBuffer(ABuffer:TInfoRULE78Record); property DFTerm: TStringField read FDFTerm; property DFMonths: TStringField read FDFMonths; property DFPercent: TCurrencyField read FDFPercent; property PTerm: String read GetPTerm write SetPTerm; property PMonths: String read GetPMonths write SetPMonths; property PPercent: Currency read GetPPercent write SetPPercent; published property Active write SetActive; end; { TInfoRULE78Table } procedure Register; implementation procedure TInfoRULE78Table.CreateFields; begin FDFTerm := CreateField( 'Term' ) as TStringField; FDFMonths := CreateField( 'Months' ) as TStringField; FDFPercent := CreateField( 'Percent' ) as TCurrencyField; end; { TInfoRULE78Table.CreateFields } procedure TInfoRULE78Table.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoRULE78Table.SetActive } procedure TInfoRULE78Table.SetPTerm(const Value: String); begin DFTerm.Value := Value; end; function TInfoRULE78Table.GetPTerm:String; begin result := DFTerm.Value; end; procedure TInfoRULE78Table.SetPMonths(const Value: String); begin DFMonths.Value := Value; end; function TInfoRULE78Table.GetPMonths:String; begin result := DFMonths.Value; end; procedure TInfoRULE78Table.SetPPercent(const Value: Currency); begin DFPercent.Value := Value; end; function TInfoRULE78Table.GetPPercent:Currency; begin result := DFPercent.Value; end; procedure TInfoRULE78Table.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Term, String, 3, N'); Add('Months, String, 3, N'); Add('Percent, Currency, 0, N'); end; end; procedure TInfoRULE78Table.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Term;Months, Y, Y, N, N'); end; end; procedure TInfoRULE78Table.SetEnumIndex(Value: TEIInfoRULE78); begin case Value of InfoRULE78PrimaryKey : IndexName := ''; end; end; function TInfoRULE78Table.GetDataBuffer:TInfoRULE78Record; var buf: TInfoRULE78Record; begin fillchar(buf, sizeof(buf), 0); buf.PTerm := DFTerm.Value; buf.PMonths := DFMonths.Value; buf.PPercent := DFPercent.Value; result := buf; end; procedure TInfoRULE78Table.StoreDataBuffer(ABuffer:TInfoRULE78Record); begin DFTerm.Value := ABuffer.PTerm; DFMonths.Value := ABuffer.PMonths; DFPercent.Value := ABuffer.PPercent; end; function TInfoRULE78Table.GetEnumIndex: TEIInfoRULE78; var iname : string; begin result := InfoRULE78PrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoRULE78PrimaryKey; end; procedure TInfoRULE78Query.CreateFields; begin FDFTerm := CreateField( 'Term' ) as TStringField; FDFMonths := CreateField( 'Months' ) as TStringField; FDFPercent := CreateField( 'Percent' ) as TCurrencyField; end; { TInfoRULE78Query.CreateFields } procedure TInfoRULE78Query.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoRULE78Query.SetActive } procedure TInfoRULE78Query.SetPTerm(const Value: String); begin DFTerm.Value := Value; end; function TInfoRULE78Query.GetPTerm:String; begin result := DFTerm.Value; end; procedure TInfoRULE78Query.SetPMonths(const Value: String); begin DFMonths.Value := Value; end; function TInfoRULE78Query.GetPMonths:String; begin result := DFMonths.Value; end; procedure TInfoRULE78Query.SetPPercent(const Value: Currency); begin DFPercent.Value := Value; end; function TInfoRULE78Query.GetPPercent:Currency; begin result := DFPercent.Value; end; function TInfoRULE78Query.GetDataBuffer:TInfoRULE78Record; var buf: TInfoRULE78Record; begin fillchar(buf, sizeof(buf), 0); buf.PTerm := DFTerm.Value; buf.PMonths := DFMonths.Value; buf.PPercent := DFPercent.Value; result := buf; end; procedure TInfoRULE78Query.StoreDataBuffer(ABuffer:TInfoRULE78Record); begin DFTerm.Value := ABuffer.PTerm; DFMonths.Value := ABuffer.PMonths; DFPercent.Value := ABuffer.PPercent; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoRULE78Table, TInfoRULE78Query, TInfoRULE78Buffer ] ); end; { Register } function TInfoRULE78Buffer.FieldNameToIndex(s:string):integer; const flist:array[1..3] of string = ('TERM','MONTHS','PERCENT' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 3) and (flist[x] <> s) do inc(x); if x <= 3 then result := x else result := 0; end; function TInfoRULE78Buffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftCurrency; end; end; function TInfoRULE78Buffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PTerm; 2 : result := @Data.PMonths; 3 : result := @Data.PPercent; end; end; end.
unit GlassedBuffers; // This is a patch! OK? This is the only way I found to draw glassed vector graphics. interface uses Windows, SpriteImages, SpeedBmp, ColorTableMgr, GDI, Palettes; procedure CreateBuffer(Width, Height : integer); procedure ResizeBuffer(NewWidth, NewHeight : integer); procedure FreeBuffer; function GetBuffer(Width, Height : integer) : TSpeedBitmap; procedure SetupBufferBackground(const ClipRect : TRect); procedure RenderBuffer(Dest : TSpeedBitmap; const ClipRect : TRect); implementation uses Classes, Graphics, BitBlt, Dibs; var PalettedBuffer : TSpeedBitmap; FrameImage : TFrameImage; RGBPalette : TRGBPalette; PaletteInfo : TPaletteInfo; procedure CreateBuffer(Width, Height : integer); var BuffPal : TBufferPalette; i : integer; begin PalettedBuffer := TSpeedBitmap.CreateSized(Width, Height, 8); PalettedBuffer.TransparentColor := clBlack; PalettedBuffer.Canvas.Brush.Color := clBlack; PalettedBuffer.Canvas.FillRect(Rect(0, 0, Width - 1, Height - 1)); FrameImage := TFrameImage.Create(Width, Height); FrameImage.NewFrames(1); FrameImage.FrameDelay[0] := 0; FrameImage.TranspIndx := PalettedBuffer.TransparentIndx; PaletteInfo := TPaletteInfo.Create; FrameImage.PaletteInfo := PaletteInfo; BuffPal := PalettedBuffer.BufferPalette; with BuffPal.Palette do begin for i := 0 to pred(NumberOfEntries) do begin RGBPalette[i].rgbRed := Entries[i].peRed; RGBPalette[i].rgbGreen := Entries[i].peGreen; RGBPalette[i].rgbBlue := Entries[i].peBlue; RGBPalette[i].rgbReserved := 0; end; PaletteInfo.AttachPalette(@RGBPalette, NumberOfEntries); end; end; procedure ResizeBuffer(NewWidth, NewHeight : integer); begin PalettedBuffer.NewSize(NewWidth, NewHeight, 8); PalettedBuffer.TransparentColor := clBlack; PalettedBuffer.Canvas.Brush.Color := clBlack; PalettedBuffer.Canvas.FillRect(Rect(0, 0, NewWidth - 1, NewHeight - 1)); FrameImage.Free; FrameImage := TFrameImage.Create(NewWidth, NewHeight); FrameImage.NewFrames(1); FrameImage.FrameDelay[0] := 0; FrameImage.TranspIndx := PalettedBuffer.TransparentIndx; FrameImage.PaletteInfo := PaletteInfo; end; procedure FreeBuffer; begin PaletteInfo.Free; FrameImage.Free; PalettedBuffer.Free; end; function GetBuffer(Width, Height : integer) : TSpeedBitmap; begin if PalettedBuffer <> nil then begin if (PalettedBuffer.Width <> Width) or (PalettedBuffer.Height <> Height) then ResizeBuffer(Width, Height); end else CreateBuffer(Width, Height); Result := PalettedBuffer; end; procedure SetupBufferBackground(const ClipRect : TRect); var SrcWidth : integer; begin if PalettedBuffer.TopDown then SrcWidth := PalettedBuffer.StorageWidth else SrcWidth := -PalettedBuffer.StorageWidth; PalettedBuffer.Canvas.Brush.Color := clBlack; PalettedBuffer.Canvas.FillRect(ClipRect); BltCopyOpaque(PalettedBuffer.PixelAddr[ClipRect.Left, ClipRect.Top], FrameImage.PixelAddr[ClipRect.Left, ClipRect.Top, 0], ClipRect.Right - ClipRect.Left, ClipRect.Bottom - ClipRect.Top, SrcWidth, FrameImage.StorageWidth); end; procedure RenderBuffer(Dest : TSpeedBitmap; const ClipRect : TRect); var SrcWidth : integer; begin if PalettedBuffer.TopDown then SrcWidth := PalettedBuffer.StorageWidth else SrcWidth := -PalettedBuffer.StorageWidth; BltCopyOpaque(PalettedBuffer.PixelAddr[ClipRect.Left, ClipRect.Top], FrameImage.PixelAddr[ClipRect.Left, ClipRect.Top, 0], ClipRect.Right - ClipRect.Left, ClipRect.Bottom - ClipRect.Top, SrcWidth, FrameImage.StorageWidth); FrameImage.Draw(0, 0, 1, 0, ClipRect, Dest, nil); end; end.
unit CFHelpers; { Unit of handy routines for use with Core Foundation. CFStrToAnsiStr was adapted from the Lazarus CarbonProc unit's CFStringToStr function. License: Modified LGPL. Note that objects returned by functions with "Create" or "Copy" in the function name need to be released by the calling code. For example, CFStringCreateWithCString is called in AnsiStrToCFStr, meaning this applies to code that calls AnsiStrToCFStr as well. FreeCFRef and FreeAndNilCFRef are convenience routines provided for that purpose. See Apple docs for more information on the so-called Create Rule and Get Rule: https://developer.apple.com/library/mac/#documentation/CoreFoundation/ Conceptual/CFMemoryMgmt/Concepts/Ownership.html } {$MODE Delphi} interface uses MacOSAll; function CFStrToAnsiStr(cfStr : CFStringRef; encoding : CFStringEncoding = kCFStringEncodingWindowsLatin1): AnsiString; procedure AnsiStrToCFStr(const aStr : AnsiString; out cfStr : CFStringRef; encoding : CFStringEncoding = kCFStringEncodingWindowsLatin1); procedure FreeCFRef(var cfRef: CFTypeRef); procedure FreeAndNilCFRef(var cfRef : CFTypeRef); implementation function CFStrToAnsiStr(cfStr : CFStringRef; encoding : CFStringEncoding = kCFStringEncodingWindowsLatin1): AnsiString; {Convert CFString to AnsiString. If encoding is not specified, use CP1252 by default.} var StrPtr : Pointer; StrRange : CFRange; StrSize : CFIndex; begin if cfStr = nil then begin Result := ''; Exit; end; {First try the optimized function} StrPtr := CFStringGetCStringPtr(cfStr, encoding); if StrPtr <> nil then {Succeeded?} Result := PChar(StrPtr) else {Use slower approach - see comments in CFString.pas} begin StrRange.location := 0; StrRange.length := CFStringGetLength(cfStr); {Determine how long resulting string will be} CFStringGetBytes(cfStr, StrRange, encoding, Ord('?'), False, nil, 0, StrSize); SetLength(Result, StrSize); {Expand string to needed length} if StrSize > 0 then {Convert string?} CFStringGetBytes(cfStr, StrRange, encoding, Ord('?'), False, @Result[1], StrSize, StrSize); end; end; {CFStrToAnsiStr} procedure AnsiStrToCFStr(const aStr : AnsiString; out cfStr : CFStringRef; encoding : CFStringEncoding = kCFStringEncodingWindowsLatin1); {Create CFString from AnsiString. If encoding is not specified, use CP1252 by default. Note: Calling code is responsible for calling CFRelease on returned CFString. Presumably that's the reason why CarbonProc unit's CreateCFString is a procedure, so you don't use it in an expression and leave the CFString dangling.} begin cfStr := CFStringCreateWithCString(nil, Pointer(PChar(aStr)), encoding); end; procedure FreeCFRef(var cfRef : CFTypeRef); {Convenience routine to free a CF reference so you don't have to check if it's nil.} begin if Assigned(cfRef) then CFRelease(cfRef); end; procedure FreeAndNilCFRef(var cfRef : CFTypeRef); {Convenience routine to free a CF reference and set it to nil.} begin FreeCFRef(cfRef); cfRef := nil; end; end.
//==================================================================// // 工作量网上查询接口申明单元: // 功能描述:为了实现教师从网上自助查询自己的工作量而设置的接口。 // 接口名称:Ijxgzl // 接口引用:http://url/jxgzl/jxgzlWebSrv.dll/soap/Ijxgzl // 或者:http://url/jxgzl/jxgzlWebSrv.dll/wsdl/Ijxgzl //==================================================================// { Invokable interface IjxgzlSrv } unit uJxgzlIntf; interface uses InvokeRegistry, Types, SOAPHTTPClient; type { Invokable interfaces must derive from IInvokable } Ijxgzl = interface(IInvokable) ['{FDC1B1DE-71B9-4064-9A4E-D2AA07E02A72}'] { Methods of Invokable interface must not use the default } { calling convention; stdcall is recommended } function RegIsOK:Boolean;stdcall;//系统是否注册 function SrvIsOK:Boolean;stdcall; //服务器是否准备好/是否可用 //判断WEB Server是否为合法的用户接入服务器IP(即WEB服务器IP验证) function IsValidIP:Boolean;stdcall; //判断服务器当前是否可以进行网上报名,如果允许网上报名则返回字符串:OK ;如果不允许,则返回不允许的原因,如服务关闭、IP不正确、不在报名时间内等等 function IsCanNetPrintZKZ:Boolean;stdcall; function GetXnXqList:string;stdcall; //通过职工号和学年学期获取工作量信息,返回XML格式的DataSet值 function GetJxgzlInfo(const sNo,sXnxq:string;const iRecCount,iPage:Integer):string;stdcall; function GetJxgzlRecordCount(const sNo,sXnxq:string):Integer;stdcall; //得到教学工作量信息 function GetJxgzlDelta(const id:string):string;stdcall; function TeacherLoginByNo(const sNo,sXM:string):Boolean;stdcall;//通过职工号登录 function TeacherLoginBySfzh(const sfzh,sXM:string):Boolean;stdcall;//通过身份证号登录 //获取公告通知,RecCount为希望获取的记录数目,结果返回XML格式的DataSet值。 function GetBullitInfo(const RecCount:Integer=5):string;stdcall; //获取帮助信息,返回结果为一个多行的字符串值。行与行之间用回车换行符分隔,即通常的#13#10符 function GetHelpInfo:string;stdcall; //获取用户的网银配置信息:UserDM:商户代码 UserAccount:商户帐号,BankSrvUrl:网银支付接口地址,BankWapSrvUrl:手机支付接口地址 //获取成功返回True,否则返回False function GetUserNetBankInfo(out UserDM,UserAccount,BankSrvUrl,BankWapSrvUrl:string):Boolean;stdcall; //得到用户(商户)代码 function GetUserDM:string;stdcall; //得到用户(商户)帐号 function GetUserAccount:string;stdcall; //得到网银支付接口网址 function GetBankSrvUrl:string;stdcall; //得到手机支付接口网址 function GetBankWapSrvUrl:string;stdcall; end; function GetIjxgzl(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): Ijxgzl; implementation function GetIjxgzl(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): Ijxgzl; const defWSDL = 'http://localhost/jxgzl/jxgzlWebSrv.dll/wsdl/Ijxgzl'; defURL = 'http://localhost/jxgzl/jxgzlWebSrv.dll/soap/Ijxgzl'; defSvc = 'Ijxgzlservice'; defPrt = 'IjxgzlPort'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; RIO.HTTPWebNode.UseUTF8InHeader := True; try Result := (RIO as Ijxgzl); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization { Invokable interfaces must be registered } InvRegistry.RegisterInterface(TypeInfo(Ijxgzl)); end.
unit FlashUtils; {* Утилиты для работы с Flash-схемами } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Common\FlashUtils.pas" // Стереотип: "UtilityPack" // Элемент модели: "FlashUtils" MUID: (4981A3DC007E) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3IntfUses {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoFlash)} , vtShockwaveFlashEx {$IfEnd} // NOT Defined(NoFlash) ; function nsCanMakeFlashActiveX: Boolean; {* Проверяет - возможно ли создать компонент для показа flash-ролика } function nsMakeFlashActiveX(aParent: TWinControl; aForSplash: Boolean; out aFlash: TvtShockwaveFlashEx): Boolean; {* Создаёт компонент для показа flash-ролика } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings)} uses l3ImplUses , SysUtils , ComObj , Windows , Registry //#UC START# *4981A3DC007Eimpl_uses* //#UC END# *4981A3DC007Eimpl_uses* ; function nsCanMakeFlashActiveX: Boolean; {* Проверяет - возможно ли создать компонент для показа flash-ролика } //#UC START# *4981A569031D_4981A3DC007E_var* var l_Flash: TvtShockwaveFlashEx; //#UC END# *4981A569031D_4981A3DC007E_var* begin //#UC START# *4981A569031D_4981A3DC007E_impl* Result := nsMakeFlashActiveX(nil, false, l_Flash); FreeAndNil(l_Flash); //#UC END# *4981A569031D_4981A3DC007E_impl* end;//nsCanMakeFlashActiveX function nsMakeFlashActiveX(aParent: TWinControl; aForSplash: Boolean; out aFlash: TvtShockwaveFlashEx): Boolean; {* Создаёт компонент для показа flash-ролика } //#UC START# *4981A58A0168_4981A3DC007E_var* const c_ClassIDKey: string = '\SOFTWARE\Classes\CLSID\{D27CDB6E-AE6D-11cf-96B8-444553540000}'; c_TypeLibKey: string = '\SOFTWARE\Classes\TypeLib\{D27CDB6B-AE6D-11CF-96B8-444553540000}'; var l_Registry: TRegistry; // для загрузки Flash "руками" необходимо поместить часть информации в реестр перед этим //#UC END# *4981A58A0168_4981A3DC007E_var* begin //#UC START# *4981A58A0168_4981A3DC007E_impl* aFlash := nil; try l_Registry := TRegistry.Create; try l_Registry.RootKey := HKEY_CURRENT_USER; // l_Registry.OpenKey(c_ClassIDKey, True); l_Registry.OpenKey('MiscStatus', True); l_Registry.WriteString('', '0'); l_Registry.OpenKey('1', True); l_Registry.WriteString('', '131473'); // l_Registry.OpenKey(c_TypeLibKey, True); l_Registry.OpenKey('1.0', True); l_Registry.WriteString('', 'Shockwave Flash'); l_Registry.OpenKey('0\win32', True); l_Registry.WriteString('', 'flash.ocx'); // l_Registry.OpenKey(c_TypeLibKey, True); l_Registry.OpenKey('1.0\FLAGS', True); l_Registry.WriteString('', '0'); // aFlash := TvtShockwaveFlashEx.Create(aParent); // Работаем с flash только если поддерживается загрузка из потока // (<K> - 108626065): aFlash.Menu := False; if aFlash.IsLoadFromStreamSupported then with aFlash do begin Width := 2; Height := 2; Parent := aParent; Align := alClient; if not aForSplash then begin NeedDropAlignOnLoad := True; ScaleMode := 3; // NoScale AlignMode := 15{5}; // LTRB{LeftTop} (* http://www.delphiflash.com/using-tshockwaveflash/tshockwaveflash-properties#a2 AlignMode Integer value from range 0..15. This is the same as SAlign. 0 - no align, 1 - L, 2 - R, 3 - LR, 4 - T, 5 - LT, 6 - TR, 7 - LTR, 8 - B, 9 - LB, 10 - RB, 11 - LRB, 12 - TB, 13 - LTB, 14 - TRB, 15 - LTRB. *) end;//aForSplash end//with aFlash do else FreeAndNil(aFlash); finally try l_Registry.DeleteKey(c_TypeLibKey); l_Registry.DeleteKey(c_ClassIDKey); finally FreeAndNil(l_Registry); end; end; except on E: EOleSysError do begin FreeAndNil(aFlash); end; end;//try..except Result := aFlash <> nil; //#UC END# *4981A58A0168_4981A3DC007E_impl* end;//nsMakeFlashActiveX {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) end.
{ CoreGraphics - CGPath.h * Copyright (c) 2001-2002 Apple Computer, Inc. * All rights reserved. } { Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGPath; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CGBase,CGAffineTransforms,CFBase,CGGeometry; {$ALIGN POWER} type CGMutablePathRef = ^SInt32; { an opaque 32-bit type } type CGPathRef = ^SInt32; { an opaque 32-bit type } { Return the CFTypeID for CGPathRefs. } function CGPathGetTypeID: CFTypeID; external name '_CGPathGetTypeID'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Create a mutable path. } function CGPathCreateMutable: CGMutablePathRef; external name '_CGPathCreateMutable'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Create a copy of `path'. } function CGPathCreateCopy( path: CGPathRef ): CGPathRef; external name '_CGPathCreateCopy'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Create a mutable copy of `path'. } function CGPathCreateMutableCopy( path: CGPathRef ): CGMutablePathRef; external name '_CGPathCreateMutableCopy'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Equivalent to `CFRetain(path)', except it doesn't crash (as CFRetain * does) if `path' is NULL. } function CGPathRetain( path: CGPathRef ): CGPathRef; external name '_CGPathRetain'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Equivalent to `CFRelease(path)', except it doesn't crash (as CFRelease * does) if `path' is NULL. } procedure CGPathRelease( path: CGPathRef ); external name '_CGPathRelease'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Return true if `path1' is equal to `path2'; false otherwise. } function CGPathEqualToPath( path1: CGPathRef; path2: CGPathRef ): CBool; external name '_CGPathEqualToPath'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {** Path construction functions. **} { Move the current point to `(x, y)' in `path' and begin a new subpath. * If `m' is non-NULL, then transform `(x, y)' by `m' first. } procedure CGPathMoveToPoint( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; x: Float32; y: Float32 ); external name '_CGPathMoveToPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Append a straight line segment from the current point to `(x, y)' in * `path' and move the current point to `(x, y)'. If `m' is non-NULL, then * transform `(x, y)' by `m' first. } procedure CGPathAddLineToPoint( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; x: Float32; y: Float32 ); external name '_CGPathAddLineToPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Append a quadratic curve from the current point to `(x, y)' with control * point `(cpx, cpy)' in `path' and move the current point to `(x, y)'. If * `m' is non-NULL, then transform all points by `m' first. } procedure CGPathAddQuadCurveToPoint( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; cpx: Float32; cpy: Float32; x: Float32; y: Float32 ); external name '_CGPathAddQuadCurveToPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Append a cubic Bezier curve from the current point to `(x,y)' with * control points `(cp1x, cp1y)' and `(cp2x, cp2y)' in `path' and move the * current point to `(x, y)'. If `m' is non-NULL, then transform all points * by `m' first. } procedure CGPathAddCurveToPoint( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; cp1x: Float32; cp1y: Float32; cp2x: Float32; cp2y: Float32; x: Float32; y: Float32 ); external name '_CGPathAddCurveToPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Append a line from the current point to the starting point of the * current subpath of `path' and end the subpath. } procedure CGPathCloseSubpath( path: CGMutablePathRef ); external name '_CGPathCloseSubpath'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {** Path construction convenience functions. **} { Add `rect' to `path'. If `m' is non-NULL, then first transform `rect' by * `m' before adding it to `path'. } procedure CGPathAddRect( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; rect: CGRect ); external name '_CGPathAddRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Add each rectangle specified by `rects', an array of `count' CGRects, to * `path'. If `m' is non-NULL, then first transform each rectangle by `m' * before adding it to `path'. } procedure CGPathAddRects( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; {const} rects: {variable-size-array} CGRectPtr; count: size_t ); external name '_CGPathAddRects'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Move to the first element of `points', an array of `count' CGPoints, and * append a line from each point to the next point in `points'. If `m' is * non-NULL, then first transform each point by `m'. } procedure CGPathAddLines( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; {const} points: {variable-size-array} CGPointPtr; count: size_t ); external name '_CGPathAddLines'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Add an ellipse (an oval) inside `rect' to `path'. The ellipse is * approximated by a sequence of Bezier curves. The center of the ellipse * is the midpoint of `rect'. If `rect' is square, then the ellipse will * be circular with radius equal to one-half the width (equivalently, * one-half the height) of `rect'. If `rect' is rectangular, then the * major- and minor-axes will be the `width' and `height' of rect. The * ellipse forms a complete subpath of `path' --- that is, it begins with a * "move to" and ends with a "close subpath" --- oriented in the clockwise * direction. If `m' is non-NULL, then the constructed Bezier curves * representing the ellipse will be transformed by `m' before they are * added to `path'. } procedure CGPathAddEllipseInRect( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; rect: CGRect ); external name '_CGPathAddEllipseInRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Add an arc of a circle to `path', possibly preceded by a straight line * segment. The arc is approximated by a sequence of cubic Bezier * curves. `(x, y)' is the center of the arc; `radius' is its radius; * `startAngle' is the angle to the first endpoint of the arc; `endAngle' * is the angle to the second endpoint of the arc; and `clockwise' is true * if the arc is to be drawn clockwise, false otherwise. `startAngle' and * `endAngle' are measured in radians. If `m' is non-NULL, then the * constructed Bezier curves representing the arc will be transformed by * `m' before they are added to `path'. } procedure CGPathAddArc( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; x: Float32; y: Float32; radius: Float32; startAngle: Float32; endAngle: Float32; clockwise: CBool ); external name '_CGPathAddArc'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Add an arc of a circle to `path', possibly preceded by a straight line * segment. The arc is approximated by a sequence of cubic Bezier curves. * `radius' is the radius of the arc. The resulting arc is tangent to the * line from the current point of `path' to `(x1, y1)', and the line from * `(x1, y1)' to `(x2, y2)'. If `m' is non-NULL, then the constructed * Bezier curves representing the arc will be transformed by `m' before * they are added to `path'. } procedure CGPathAddArcToPoint( path: CGMutablePathRef; const (*var*) m: CGAffineTransform; x1: Float32; y1: Float32; x2: Float32; y2: Float32; radius: Float32 ); external name '_CGPathAddArcToPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Add `path2' to `path1'. If `m' is non-NULL, then the points in `path2' * will be transformed by `m' before they are added to `path1'.} procedure CGPathAddPath( path1: CGMutablePathRef; const (*var*) m: CGAffineTransform; path2: CGPathRef ); external name '_CGPathAddPath'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {** Path information functions. **} { Return true if `path' contains no elements, false otherwise. } function CGPathIsEmpty( path: CGPathRef ): CBool; external name '_CGPathIsEmpty'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Return true if `path' represents a rectangle, false otherwise. } function CGPathIsRect( path: CGPathRef; var rect: CGRect ): CBool; external name '_CGPathIsRect'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Return the current point of the current subpath of `path'. If there is * no current point, then return CGPointZero. } function CGPathGetCurrentPoint( path: CGPathRef ): CGPoint; external name '_CGPathGetCurrentPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Return the bounding box of `path'. The bounding box is the smallest * rectangle completely enclosing all points in the path, including control * points for Bezier and quadratic curves. If the path is empty, then * return CGRectNull. } function CGPathGetBoundingBox( path: CGPathRef ): CGRect; external name '_CGPathGetBoundingBox'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) { Return true if `point' is contained in `path'; false otherwise. A point * is contained in a path if it is inside the painted region when the path * is filled; if `eoFill' is true, then the even-odd fill rule is used to * evaluate the painted region of the path, otherwise, the winding-number * fill rule is used. If `m' is non-NULL, then the point is transformed by * `m' before determining whether the path contains it. } function CGPathContainsPoint( path: CGPathRef; const (*var*) m: CGAffineTransform; point: CGPoint; eoFill: CBool ): CBool; external name '_CGPathContainsPoint'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) type CGPathElementType = SInt32; const kCGPathElementMoveToPoint = 0; kCGPathElementAddLineToPoint = 1; kCGPathElementAddQuadCurveToPoint = 2; kCGPathElementAddCurveToPoint = 3; kCGPathElementCloseSubpath = 4; type CGPathElement = record typ: CGPathElementType; points: CGPointPtr; end; type CGPathApplierFunction = procedure( info: UnivPtr; const (*var*) element: CGPathElement ); procedure CGPathApply( path: CGPathRef; info: UnivPtr; func: CGPathApplierFunction ); external name '_CGPathApply'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) end.
unit FrameDataCompareViewer; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, BaseApp, BaseForm, VirtualTrees, ExtCtrls, define_dealItem, db_dealItem, QuickList_Int, BaseRule, Rule_CYHT, Rule_BDZX, Rule_Boll, Rule_Std, Rule_MA, StockDayDataAccess, UIDealItemNode, StockDetailDataAccess; type TDataViewerData = record StockItem: PStockItemNode; StockDayDataAccess_163: StockDayDataAccess.TStockDayDataAccess; StockDayDataAccess_Sina: StockDayDataAccess.TStockDayDataAccess; StockDayDataAccess_SinaW: StockDayDataAccess.TStockDayDataAccess; StockDayList: TALIntegerList; end; TfmeDataCompareViewer = class(TfrmBase) pnMain: TPanel; pnTop: TPanel; pnData: TPanel; pnDataTop: TPanel; pnlDatas: TPanel; vtDayDatas: TVirtualStringTree; procedure vtDayDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); protected fDataViewerData: TDataViewerData; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Initialize(App: TBaseApp); override; procedure SetData(ADataType: integer; AData: Pointer); override; procedure SetStockItem(AStockItem: PStockItemNode); end; implementation {$R *.dfm} uses BaseStockApp, Define_DataSrc, define_price, //UtilsLog, define_stock_quotes, define_dealstore_file, StockDayData_Load, StockDetailData_Load, db_DealItem_Load; type TDayColumns = ( colIndex, colDate163, colDateSina, colDateSinaW, colOpen, colClose, colHigh, colLow, colDayVolume, colDayAmount, colWeight ); PStockDayDataNode = ^TStockDayDataNode; TStockDayDataNode = record DayIndex: integer; QuoteData_163: PRT_Quote_Day; QuoteData_Sina: PRT_Quote_Day; QuoteData_SinaW: PRT_Quote_Day; end; const DayColumnsText: array[TDayColumns] of String = ( 'Index', '日期163', '日期Sina', '日期SinaW', '开盘', '收盘', '最高', '最低', '成交量', '成交金额', '权重' //, 'BOLL', 'UP', 'LP' //, 'SK', 'SD' ); DayColumnsWidth: array[TDayColumns] of integer = ( 60, 80, 80, 80, 0, 0, 0, 0, 0, 0, 0 //, 'BOLL', 'UP', 'LP' //, 'SK', 'SD' ); constructor TfmeDataCompareViewer.Create(AOwner: TComponent); begin inherited; //fStockDetailDataAccess := nil; FillChar(fDataViewerData, SizeOf(fDataViewerData), 0); fDataViewerData.StockDayList := TALIntegerList.Create; //fRule_Boll_Price := nil; //fRule_CYHT_Price := nil; //fRule_BDZX_Price := nil; end; destructor TfmeDataCompareViewer.Destroy; begin fDataViewerData.StockDayList.Clear; fDataViewerData.StockDayList.Free; inherited; end; procedure TfmeDataCompareViewer.SetData(ADataType: integer; AData: Pointer); begin SetStockItem(AData); end; procedure TfmeDataCompareViewer.SetStockItem(AStockItem: PStockItemNode); var i: integer; tmpIndex: Integer; tmpStockDataNode: PStockDayDataNode; tmpStockData: PRT_Quote_Day; tmpNode: PVirtualNode; tmpStr: string; begin vtDayDatas.BeginUpdate; try vtDayDatas.Clear; if nil = AStockItem then begin exit; end; if fDataViewerData.StockItem <> AStockItem then begin fDataViewerData.StockDayDataAccess_163 := nil; fDataViewerData.StockDayDataAccess_sina := nil; fDataViewerData.StockDayDataAccess_sinaw := nil; end; // if nil <> AStockItem.StockDayDataAccess then // fDataViewerData.StockDayDataAccess_163 := AStockItem.StockDayDataAccess; if nil = fDataViewerData.StockDayDataAccess_163 then begin fDataViewerData.StockDayDataAccess_163 := TStockDayDataAccess.Create(FilePath_DBType_Item, AStockItem.StockItem, Src_163, weightNone); StockDayData_Load.LoadStockDayData(App, fDataViewerData.StockDayDataAccess_163); end; if nil = fDataViewerData.StockDayDataAccess_sina then begin fDataViewerData.StockDayDataAccess_sina := TStockDayDataAccess.Create(FilePath_DBType_Item, AStockItem.StockItem, Src_Sina, weightNone); StockDayData_Load.LoadStockDayData(App, fDataViewerData.StockDayDataAccess_sina); end; if nil = fDataViewerData.StockDayDataAccess_SinaW then begin fDataViewerData.StockDayDataAccess_SinaW := TStockDayDataAccess.Create(FilePath_DBType_Item, AStockItem.StockItem, Src_Sina, weightBackward); StockDayData_Load.LoadStockDayData(App, fDataViewerData.StockDayDataAccess_SinaW); end; tmpStr := ''; fDataViewerData.StockDayList.Clear; //Log('', '163 recordcount:' + IntToStr(fDataViewerData.StockDayDataAccess_163.RecordCount)); for i := fDataViewerData.StockDayDataAccess_163.RecordCount - 1 downto 0 do begin tmpStockData := fDataViewerData.StockDayDataAccess_163.RecordItem[i]; tmpNode := vtDayDatas.AddChild(nil); fDataViewerData.StockDayList.AddObject(tmpStockData.DealDate.Value, TObject(tmpNode)); tmpStockDataNode := vtDayDatas.GetNodeData(tmpNode); if '' = tmpStr then begin tmpStr := FormatDateTime('yyyymmdd', tmpStockData.DealDate.Value); end; tmpStockDataNode.QuoteData_163 := tmpStockData; tmpStockDataNode.QuoteData_Sina := nil; tmpStockDataNode.QuoteData_SinaW := nil; tmpStockDataNode.DayIndex := i; end; //Log('', 'sina recordcount:' + IntToStr(fDataViewerData.StockDayDataAccess_sina.RecordCount)); for i := fDataViewerData.StockDayDataAccess_Sina.RecordCount - 1 downto 0 do begin tmpStockData := fDataViewerData.StockDayDataAccess_Sina.RecordItem[i]; tmpIndex := fDataViewerData.StockDayList.IndexOf(tmpStockData.DealDate.Value); if 0 <= tmpIndex then begin tmpNode := PVirtualNode(fDataViewerData.StockDayList.Objects[tmpIndex]); tmpStockDataNode := vtDayDatas.GetNodeData(tmpNode); tmpStockDataNode.QuoteData_Sina := tmpStockData; end; end; //Log('', 'sinaw recordcount:' + IntToStr(fDataViewerData.StockDayDataAccess_SinaW.RecordCount)); for i := fDataViewerData.StockDayDataAccess_SinaW.RecordCount - 1 downto 0 do begin tmpStockData := fDataViewerData.StockDayDataAccess_SinaW.RecordItem[i]; tmpIndex := fDataViewerData.StockDayList.IndexOf(tmpStockData.DealDate.Value); if 0 <= tmpIndex then begin tmpNode := PVirtualNode(fDataViewerData.StockDayList.Objects[tmpIndex]); tmpStockDataNode := vtDayDatas.GetNodeData(tmpNode); tmpStockDataNode.QuoteData_SinaW := tmpStockData; end; end; finally vtDayDatas.EndUpdate; end; end; procedure TfmeDataCompareViewer.Initialize(App: TBaseApp); var col_day: TDayColumns; tmpCol: TVirtualTreeColumn; begin inherited; vtDayDatas.NodeDataSize := SizeOf(TStockDayDataNode); vtDayDatas.OnGetText := vtDayDatasGetText; vtDayDatas.Header.Options := [hoColumnResize, hoVisible]; vtDayDatas.Header.Columns.Clear; for col_day := low(TDayColumns) to high(TDayColumns) do begin tmpCol := vtDayDatas.Header.Columns.Add; tmpCol.Text := DayColumnsText[col_day]; if 0 = DayColumnsWidth[col_day] then begin tmpCol.Width := 120; end else begin tmpCol.Width := DayColumnsWidth[col_day]; end; end; end; procedure TfmeDataCompareViewer.vtDayDatasGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString); var tmpNodeData: PStockDayDataNode; begin CellText := ''; tmpNodeData := Sender.GetNodeData(Node); if nil <> tmpNodeData then begin if Integer(colIndex) = Column then begin CellText := IntToStr(tmpNodeData.DayIndex); exit; end; if Integer(colDate163) = Column then begin if nil <> tmpNodeData.QuoteData_163 then begin CellText := FormatDateTime('yyyymmdd', tmpNodeData.QuoteData_163.DealDate.Value); end; exit; end; if Integer(colDateSina) = Column then begin if nil <> tmpNodeData.QuoteData_Sina then begin CellText := FormatDateTime('yyyymmdd', tmpNodeData.QuoteData_Sina.DealDate.Value); end; exit; end; if Integer(colDateSinaW) = Column then begin if nil <> tmpNodeData.QuoteData_SinaW then begin CellText := FormatDateTime('yyyymmdd', tmpNodeData.QuoteData_SinaW.DealDate.Value); end; exit; end; if Integer(colOpen) = Column then begin if nil <> tmpNodeData.QuoteData_163 then begin CellText := IntToStr(tmpNodeData.QuoteData_163.PriceRange.PriceOpen.Value); end; if nil <> tmpNodeData.QuoteData_SinaW then begin CellText := CellText + '/' + IntToStr(tmpNodeData.QuoteData_SinaW.PriceRange.PriceOpen.Value); end; exit; end; if Integer(colClose) = Column then begin if nil <> tmpNodeData.QuoteData_163 then begin CellText := IntToStr(tmpNodeData.QuoteData_163.PriceRange.PriceClose.Value); end; if nil <> tmpNodeData.QuoteData_SinaW then begin CellText := CellText + '/' + IntToStr(tmpNodeData.QuoteData_SinaW.PriceRange.PriceClose.Value); end; exit; end; if Integer(colHigh) = Column then begin if nil <> tmpNodeData.QuoteData_163 then begin CellText := IntToStr(tmpNodeData.QuoteData_163.PriceRange.PriceHigh.Value); end; if nil <> tmpNodeData.QuoteData_SinaW then begin CellText := CellText + '/' + IntToStr(tmpNodeData.QuoteData_SinaW.PriceRange.PriceHigh.Value); end; exit; end; if Integer(colLow) = Column then begin if nil <> tmpNodeData.QuoteData_163 then begin CellText := IntToStr(tmpNodeData.QuoteData_163.PriceRange.PriceLow.Value); end; if nil <> tmpNodeData.QuoteData_SinaW then begin CellText := CellText + '/' + IntToStr(tmpNodeData.QuoteData_SinaW.PriceRange.PriceLow.Value); end; exit; end; if Integer(colDayVolume) = Column then begin if nil <> tmpNodeData.QuoteData_163 then begin CellText := IntToStr(tmpNodeData.QuoteData_163.DealVolume); end; if nil <> tmpNodeData.QuoteData_SinaW then begin CellText := CellText + '/' + IntToStr(tmpNodeData.QuoteData_SinaW.DealVolume); end; exit; end; if Integer(colDayAmount) = Column then begin if nil <> tmpNodeData.QuoteData_163 then begin CellText := IntToStr(tmpNodeData.QuoteData_163.DealAmount); end; if nil <> tmpNodeData.QuoteData_SinaW then begin CellText := CellText + '/' + IntToStr(tmpNodeData.QuoteData_SinaW.DealAmount); end; exit; end; if Integer(colWeight) = Column then begin if nil <> tmpNodeData.QuoteData_163 then begin CellText := IntToStr(tmpNodeData.QuoteData_163.Weight.Value); end; if nil <> tmpNodeData.QuoteData_SinaW then begin CellText := CellText + '/' + IntToStr(tmpNodeData.QuoteData_SinaW.Weight.Value); end; exit; end; end; end; end.
{5. Realizar un programa que lea números enteros desde teclado. La lectura debe finalizar cuando se ingrese el número 100, el cual debe procesarse. Informar en pantalla: ◦ El número máximo leído. ◦ El número mínimo leído. ◦ La suma total de los números leídos. } program ejercicio5; var num, max, min, suma: Integer; begin suma:= 0; min:= 9999; max:= -1; repeat write('Ingrese un numero: '); readln(num); suma:= suma + num; if num >= max then max:= num; if num < min then min:= num; until num = 100; writeln('La suma de los numeros leidos es: ', suma); writeln('El numero maximo leido es: ', max); writeln('El numero minimo leido es: ', min); readln(); end.
unit UNetServer; interface uses UTCPIP, UConst; type { TNetServer } TNetServer = Class(TNetTcpIpServer) private protected Procedure OnNewIncommingConnection(Sender : TObject; Client : TNetTcpIpClient); override; procedure SetActive(const Value: Boolean); override; procedure SetMaxConnections(AValue: Integer); override; public Constructor Create; override; End; implementation uses UNetServerClient, UTickCount, ULog, UNetData, UNetTransferType, UNetProtocolConst, Windows, SysUtils, UPtrInt, UPlatform; { TNetServer } constructor TNetServer.Create; begin inherited; MaxConnections := CT_MaxClientsConnected; NetTcpIpClientClass := TBufferedNetTcpIpClient; Port := CT_NetServer_Port; end; procedure TNetServer.OnNewIncommingConnection(Sender : TObject; Client : TNetTcpIpClient); Var n : TNetServerClient; DebugStep : String; tc : TTickCount; begin DebugStep := ''; Try if Not Client.Connected then exit; // NOTE: I'm in a separate thread // While in this function the ClientSocket connection will be active, when finishes the ClientSocket will be destroyed TLog.NewLog(ltInfo,Classname,'Starting ClientSocket accept '+Client.ClientRemoteAddr); n := TNetServerClient.Create; Try DebugStep := 'Assigning client'; n.SetClient(Client); PascalNetData.IncStatistics(1,1,0,0,0,0); PascalNetData.NodeServersAddresses.CleanBlackList(False); DebugStep := 'Checking blacklisted'; if (PascalNetData.NodeServersAddresses.IsBlackListed(Client.RemoteHost)) then begin // Invalid! TLog.NewLog(ltinfo,Classname,'Refusing Blacklist ip: '+Client.ClientRemoteAddr); n.SendError(TNetTransferType.ntp_autosend,CT_NetOp_Error, 0,CT_NetError_IPBlackListed,'Your IP is blacklisted:'+Client.ClientRemoteAddr); // Wait some time before close connection sleep(5000); end else begin DebugStep := 'Processing buffer and sleep...'; while (n.Connected) And (Active) do begin n.DoProcessBuffer; Sleep(10); end; end; Finally Try TLog.NewLog(ltdebug,Classname,'Finalizing ServerAccept '+IntToHex(PtrInt(n),8)+' '+n.ClientRemoteAddr); DebugStep := 'Disconnecting NetServerClient'; n.Connected := false; tc := TPlatform.GetTickCount; Repeat sleep(10); // 1.5.4 -> To prevent that not client disconnected (and not called OnDisconnect), increase sleep time Until (Not n.Connected) Or (tc + 5000 < TPlatform.GetTickCount); sleep(5); DebugStep := 'Assigning old client'; n.SetClient( NetTcpIpClientClass.Create ); // (Nil) ); sleep(500); // Delay - Sleep time before destroying (1.5.3) DebugStep := 'Freeing NetServerClient'; Finally n.Free; End; End; Except On E:Exception do begin TLog.NewLog(lterror,ClassName,'Exception processing client thread at step: '+DebugStep+' - ('+E.ClassName+') '+E.Message); end; End; end; procedure TNetServer.SetActive(const Value: Boolean); begin if Value then begin TLog.NewLog(ltinfo,Classname,'Activating server on port '+IntToStr(Port)); end else begin TLog.NewLog(ltinfo,Classname,'Closing server'); end; inherited; if Active then begin // PascalCoinNode.AutoDiscoverNodes(CT_Discover_IPs); end else if Assigned(PascalNetData) then begin PascalNetData.DisconnectClients; end; end; procedure TNetServer.SetMaxConnections(AValue: Integer); begin inherited SetMaxConnections(AValue); PascalNetData.MaxConnections:=AValue; end; end.
unit CompWizard; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Compiler Script Wizard form $jrsoftware: issrc/Projects/CompWizard.pas,v 1.68 2011/04/16 05:51:19 jr Exp $ } interface {$I VERSION.INC} uses Windows, Forms, Classes, Graphics, StdCtrls, ExtCtrls, Controls, Dialogs, UIStateForm, NewStaticText, DropListBox, NewCheckListBox; type TWizardPage = (wpWelcome, wpAppInfo, wpAppDir, wpAppFiles, wpAppIcons, wpAppDocs, wpLanguages, wpCompiler, wpISPP, wpFinished); TWizardFormResult = (wrNone, wrEmpty, wrComplete); TWizardForm = class(TUIStateForm) CancelButton: TButton; NextButton: TButton; BackButton: TButton; Notebook1: TNotebook; Notebook2: TNotebook; Bevel: TBevel; WelcomeImage: TImage; WelcomeLabel1: TNewStaticText; PnlMain: TPanel; Bevel1: TBevel; PageNameLabel: TNewStaticText; PageDescriptionLabel: TNewStaticText; InnerImage: TImage; FinishedLabel: TNewStaticText; FinishedImage: TImage; WelcomeLabel2: TNewStaticText; EmptyCheck: TCheckBox; WelcomeLabel3: TNewStaticText; AppNameLabel: TNewStaticText; AppNameEdit: TEdit; AppVersionLabel: TNewStaticText; AppVersionEdit: TEdit; AppDirNameLabel: TNewStaticText; AppRootDirComboBox: TComboBox; AppRootDirEdit: TEdit; AppDirNameEdit: TEdit; NotDisableDirPageCheck: TCheckBox; AppRootDirLabel: TNewStaticText; AppPublisherLabel: TNewStaticText; AppPublisherEdit: TEdit; OtherLabel: TNewStaticText; NotCreateAppDirCheck: TCheckBox; AppFilesLabel: TNewStaticText; AppFilesListBox: TDropListBox; AppFilesAddButton: TButton; AppFilesEditButton: TButton; AppFilesRemoveButton: TButton; AppURLLabel: TNewStaticText; AppURLEdit: TEdit; AppExeLabel: TNewStaticText; AppExeEdit: TEdit; AppExeRunCheck: TCheckBox; AppExeButton: TButton; AppGroupNameLabel: TNewStaticText; AppGroupNameEdit: TEdit; NotDisableProgramGroupPageCheck: TCheckBox; AllowNoIconsCheck: TCheckBox; AppExeIconsLabel: TNewStaticText; DesktopIconCheck: TCheckBox; QuickLaunchIconCheck: TCheckBox; CreateUninstallIconCheck: TCheckBox; CreateURLIconCheck: TCheckBox; AppLicenseFileLabel: TNewStaticText; AppLicenseFileEdit: TEdit; AppLicenseFileButton: TButton; AppInfoBeforeFileLabel: TNewStaticText; AppInfoBeforeFileEdit: TEdit; AppInfoBeforeFileButton: TButton; AppInfoAfterFileLabel: TNewStaticText; AppInfoAfterFileEdit: TEdit; AppInfoAfterFileButton: TButton; RequiredLabel1: TNewStaticText; RequiredLabel2: TNewStaticText; AppFilesAddDirButton: TButton; ISPPCheck: TCheckBox; ISPPLabel: TLabel; OutputDirLabel: TNewStaticText; OutputDirEdit: TEdit; OutputBaseFileNameLabel: TNewStaticText; OutputBaseFileNameEdit: TEdit; SetupIconFileLabel: TNewStaticText; SetupIconFileEdit: TEdit; PasswordLabel: TNewStaticText; PasswordEdit: TEdit; SetupIconFileButton: TButton; EncryptionCheck: TCheckBox; OutputDirButton: TButton; LanguagesLabel: TNewStaticText; LanguagesList: TNewCheckListBox; AllLanguagesButton: TButton; NoLanguagesButton: TButton; NoAppExeCheck: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormDestroy(Sender: TObject); procedure NextButtonClick(Sender: TObject); procedure BackButtonClick(Sender: TObject); procedure FileButtonClick(Sender: TObject); procedure AppRootDirComboBoxChange(Sender: TObject); procedure NotCreateAppDirCheckClick(Sender: TObject); procedure AppExeButtonClick(Sender: TObject); procedure AppFilesListBoxClick(Sender: TObject); procedure AppFilesListBoxDblClick(Sender: TObject); procedure AppFilesAddButtonClick(Sender: TObject); procedure NotDisableProgramGroupPageCheckClick(Sender: TObject); procedure AppFilesEditButtonClick(Sender: TObject); procedure AppFilesRemoveButtonClick(Sender: TObject); procedure AppFilesAddDirButtonClick(Sender: TObject); procedure AppFilesListBoxDropFile(Sender: TDropListBox; const FileName: String); procedure PasswordEditChange(Sender: TObject); procedure OutputDirButtonClick(Sender: TObject); procedure AllLanguagesButtonClick(Sender: TObject); procedure NoLanguagesButtonClick(Sender: TObject); procedure NoAppExeCheckClick(Sender: TObject); private CurPage: TWizardPage; FWizardName: String; FWizardFiles: TList; FLanguages: TStringList; FResult: TWizardFormResult; FResultScript: String; function FixLabel(const S: String): String; procedure SetWizardName(const WizardName: String); function ISPPInstalled: Boolean; function ISCryptInstalled: Boolean; procedure CurPageChanged; function SkipCurPage: Boolean; procedure AddWizardFile(const Source: String; const RecurseSubDirs, CreateAllSubDirs: Boolean); procedure UpdateWizardFiles; procedure UpdateWizardFilesButtons; procedure UpdateAppExeControls; procedure GenerateScript; public property WizardName: String write SetWizardName; property Result: TWizardFormResult read FResult; property ResultScript: String read FResultScript; end; implementation {$R *.DFM} uses SysUtils, ShlObj, {$IFNDEF Delphi3orHigher} Ole2, {$ELSE} ActiveX, {$ENDIF} PathFunc, CmnFunc, CmnFunc2, VerInfo, BrowseFunc, CompMsgs, CompWizardFile, CompForm; type TConstant = record Constant, Description: String; end; const NotebookPages: array[TWizardPage, 0..1] of Integer = ((0, -1), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (2, -1)); PageCaptions: array[TWizardPage] of String = (SWizardWelcome, SWizardAppInfo, SWizardAppDir, SWizardAppFiles, SWizardAppIcons, SWizardAppDocs, SWizardLanguages, SWizardCompiler, SWizardISPP, SWizardFinished); PageDescriptions: array[TWizardPage] of String = ('', SWizardAppInfo2, SWizardAppDir2, SWizardAppFiles2, SWizardAppIcons2, SWizardAppDocs2, SWizardLanguages2, SWizardCompiler2, SWizardISPP2, ''); RequiredLabelVisibles: array[TWizardPage] of Boolean = (False, True, True, True, True, False, True, False, False, False); AppRootDirs: array[0..0] of TConstant = ( ( Constant: '{pf}'; Description: 'Program Files folder') ); LanguagesDefaultIsl = 'Default.isl'; LanguagesDefaultIslDescription = 'English'; EnabledColors: array[Boolean] of TColor = (clBtnFace, clWindow); function EscapeAmpersands(const S: String): String; begin Result := S; StringChangeEx(Result, '&', '&&', True); end; function TWizardForm.FixLabel(const S: String): String; begin Result := S; {don't localize these} StringChange(Result, '[name]', FWizardName); end; procedure TWizardForm.SetWizardName(const WizardName: String); begin FWizardName := WizardName; end; function TWizardForm.ISPPInstalled(): Boolean; begin Result := NewFileExists(PathExtractPath(NewParamStr(0)) + 'ISPP.dll'); end; function TWizardForm.ISCryptInstalled(): Boolean; begin Result := NewFileExists(PathExtractPath(NewParamStr(0)) + 'iscrypt.dll'); end; { --- } {$IFDEF IS_D7} type TNotebookAccess = class(TNotebook); {$ENDIF} procedure TWizardForm.FormCreate(Sender: TObject); procedure MakeBold(const Ctl: TNewStaticText); begin Ctl.Font.Style := [fsBold]; end; function SpaceLanguageName(const LanguageName: String): String; var I: Integer; begin Result := ''; for I := 1 to Length(LanguageName) do begin if (I <> 1) and CharInSet(LanguageName[I], ['A'..'Z']) then Result := Result + ' '; Result := Result + LanguageName[I]; end; end; var SearchRec: TSearchRec; I: Integer; begin FResult := wrNone; FWizardName := SWizardDefaultName; FWizardFiles := TList.Create; FLanguages := TStringList.Create; //note: *.isl will also match .islu files if FindFirst(PathExtractPath(NewParamStr(0)) + 'Languages\*.isl', faAnyFile, SearchRec) = 0 then begin repeat FLanguages.Add(SearchRec.Name); until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; FLanguages.Sort; FLanguages.Insert(0, LanguagesDefaultIsl); InitFormFont(Self); if FontExists('Verdana') then WelcomeLabel1.Font.Name := 'Verdana'; {$IFDEF IS_D7} TNotebookAccess(Notebook1).ParentBackground := False; PnlMain.ParentBackground := False; {$ENDIF} MakeBold(PageNameLabel); MakeBold(RequiredLabel1); MakeBold(AppNameLabel); MakeBold(AppVersionLabel); MakeBold(AppRootDirLabel); MakeBold(AppDirNameLabel); MakeBold(AppExeLabel); MakeBold(AppGroupNameLabel); MakeBold(LanguagesLabel); FinishedImage.Picture := WelcomeImage.Picture; RequiredLabel2.Left := RequiredLabel1.Left + RequiredLabel1.Width; { AppInfo } AppNameEdit.Text := 'My Program'; AppVersionEdit.Text := '1.5'; AppPublisherEdit.Text := 'My Company, Inc.'; AppURLEdit.Text := 'http://www.example.com/'; { AppDir } for I := Low(AppRootDirs) to High(AppRootDirs) do AppRootDirComboBox.Items.Add(AppRootDirs[I].Description); AppRootDirComboBox.Items.Add('(Custom)'); AppRootDirComboBox.ItemIndex := 0; AppRootDirEdit.Enabled := False; AppRootDirEdit.Color := clBtnFace; NotDisableDirPageCheck.Checked := True; { AppFiles } AppExeEdit.Text := PathExtractPath(NewParamStr(0)) + 'Examples\MyProg.exe'; AppExeRunCheck.Checked := True; UpdateWizardFilesButtons; { AppIcons } NotDisableProgramGroupPageCheck.Checked := True; DesktopIconCheck.Checked := True; { Languages } for I := 0 to FLanguages.Count-1 do begin if FLanguages[I] <> LanguagesDefaultIsl then LanguagesList.AddCheckBox(SpaceLanguageName(PathChangeExt(FLanguages[I], '')), '', 0, False, True, False, True, TObject(I)) else LanguagesList.AddCheckBox(LanguagesDefaultIslDescription, '', 0, True, True, False, True, TObject(I)); end; { Compiler } OutputBaseFileNameEdit.Text := 'setup'; EncryptionCheck.Visible := ISCryptInstalled; EncryptionCheck.Checked := True; EncryptionCheck.Enabled := False; { ISPP } ISPPLabel.Caption := FixLabel(SWizardISPPLabel); ISPPCheck.Caption := SWizardISPPCheck; ISPPCheck.Checked := ISPPInstalled; CurPage := Low(TWizardPage); CurPageChanged; end; procedure TWizardForm.FormShow(Sender: TObject); begin Caption := FWizardName; WelcomeLabel1.Caption := FixLabel(WelcomeLabel1.Caption); FinishedLabel.Caption := FixLabel(FinishedLabel.Caption); end; procedure TWizardForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if ModalResult = mrCancel then CanClose := MsgBox(FixLabel(SWizardCancelMessage), FWizardName, mbConfirmation, MB_YESNO) = idYes; end; procedure TWizardForm.FormDestroy(Sender: TObject); var I: Integer; begin FLanguages.Free; for I := 0 to FWizardFiles.Count-1 do Dispose(FWizardFiles[i]); FWizardFiles.Free; end; { --- } procedure TWizardForm.CurPageChanged; { Call this whenever the current page is changed } begin Notebook1.PageIndex := NotebookPages[CurPage, 0]; if NotebookPages[CurPage, 1] <> -1 then Notebook2.PageIndex := NotebookPages[CurPage, 1]; { Set button visibility and captions } BackButton.Visible := not (CurPage = wpWelcome); if CurPage = wpFinished then NextButton.Caption := SWizardFinishButton else NextButton.Caption := SWizardNextButton; RequiredLabel1.Visible := RequiredLabelVisibles[CurPage]; RequiredLabel2.Visible := RequiredLabel1.Visible; { Set the Caption to match the current page's title } PageNameLabel.Caption := PageCaptions[CurPage]; PageDescriptionLabel.Caption := PageDescriptions[CurPage]; if CurPage in [wpWelcome, wpFinished] then Notebook1.Color := clWindow else Notebook1.Color := clBtnFace; { Adjust focus } case CurPage of wpAppInfo: ActiveControl := AppNameEdit; wpAppDir: begin if AppRootDirComboBox.Enabled then ActiveControl := AppRootDirComboBox else ActiveControl := NotCreateAppDirCheck; end; wpAppFiles: begin if AppExeEdit.Enabled then ActiveControl := AppExeEdit else ActiveControl := AppFilesListBox; end; wpAppIcons: ActiveControl := AppGroupNameEdit; wpAppDocs: ActiveControl := AppLicenseFileEdit; wpLanguages: ActiveControl := LanguagesList; wpCompiler: ActiveControl := OutputDirEdit; wpISPP: ActiveControl := ISPPCheck; end; end; function TWizardForm.SkipCurPage: Boolean; begin if ((CurPage = wpAppIcons) and NotCreateAppDirCheck.Checked) or ((CurPage = wpLanguages) and not (FLanguages.Count > 1)) or ((CurPage = wpISPP) and not ISPPInstalled) or (not (CurPage in [wpWelcome, wpFinished]) and EmptyCheck.Checked) then Result := True else Result := False; end; procedure TWizardForm.NextButtonClick(Sender: TObject); function CheckAppInfoPage: Boolean; begin Result := False; if AppNameEdit.Text = '' then begin MsgBox(SWizardAppNameError, '', mbError, MB_OK); ActiveControl := AppNameEdit; end else if AppVersionEdit.Text = '' then begin MsgBox(SWizardAppVersionError, '', mbError, MB_OK); ActiveControl := AppVersionEdit; end else Result := True; end; function CheckAppDirPage: Boolean; begin Result := False; if not NotCreateAppDirCheck.Checked and (AppRootDirComboBox.ItemIndex = AppRootDirComboBox.Items.Count-1) and (AppRootDirEdit.Text = '') then begin MsgBox(SWizardAppRootDirError, '', mbError, MB_OK); ActiveControl := AppRootDirEdit; end else if not NotCreateAppDirCheck.Checked and (AppDirNameEdit.Text = '') then begin MsgBox(SWizardAppDirNameError, '', mbError, MB_OK); ActiveControl := AppDirNameEdit; end else Result := True; end; function CheckAppFilesPage: Boolean; begin Result := False; if AppExeEdit.Enabled and (AppExeEdit.Text = '') then begin MsgBox(SWizardAppExeError, '', mbError, MB_OK); ActiveControl := AppExeEdit; end else Result := True; end; function CheckAppIconsPage: Boolean; begin Result := False; if AppGroupNameEdit.Text = '' then begin MsgBox(SWizardAppGroupNameError, '', mbError, MB_OK); ActiveControl := AppGroupNameEdit; end else Result := True; end; function CheckLanguagesPage: Boolean; var I: Integer; begin Result := False; for I := 0 to LanguagesList.Items.Count-1 do begin if LanguagesList.Checked[I] then begin Result := True; Exit; end; end; MsgBox(SWizardLanguagesSelError, '', mbError, MB_OK); ActiveControl := LanguagesList; end; begin case CurPage of wpAppInfo: if not CheckAppInfoPage then Exit; wpAppDir: if not CheckAppDirPage then Exit; wpAppFiles: if not CheckAppFilesPage then Exit; wpAppIcons: if not CheckAppIconsPage then Exit; wpLanguages: if not CheckLanguagesPage then Exit; end; repeat if CurPage = wpFinished then begin GenerateScript; ModalResult := mrOk; Exit; end; Inc(CurPage); { Even if we're skipping a page, we should still update it } case CurPage of wpAppDir: if AppDirNameEdit.Text = '' then AppDirNameEdit.Text := AppNameEdit.Text; wpAppIcons: begin if AppGroupNameEdit.Text = '' then AppGroupNameEdit.Text := AppNameEdit.Text; CreateURLIconCheck.Enabled := AppURLEdit.Text <> ''; end; end; until not SkipCurPage; CurPageChanged; end; procedure TWizardForm.BackButtonClick(Sender: TObject); begin if CurPage = Low(TWizardPage) then Exit; { Go to the previous page } Dec(CurPage); while SkipCurPage do Dec(CurPage); CurPageChanged; end; {---} procedure TWizardForm.AddWizardFile(const Source: String; const RecurseSubDirs, CreateAllSubDirs: Boolean); var WizardFile: PWizardFile; begin New(WizardFile); WizardFile.Source := Source; WizardFile.RecurseSubDirs := RecurseSubDirs; WizardFile.CreateAllSubDirs := CreateAllSubDirs; WizardFile.DestRootDirIsConstant := True; if not NotCreateAppDirCheck.Checked then WizardFile.DestRootDir := '{app}' else WizardFile.DestRootDir := '{win}'; WizardFile.DestSubDir := ''; FWizardFiles.Add(WizardFile); end; procedure TWizardForm.UpdateWizardFiles; var WizardFile: PWizardFile; I: Integer; begin AppFilesListBox.Items.BeginUpdate; AppFilesListBox.Items.Clear; for I := 0 to FWizardFiles.Count-1 do begin WizardFile := FWizardFiles[i]; AppFilesListBox.Items.Add(WizardFile.Source); end; AppFilesListBox.Items.EndUpdate; UpdateHorizontalExtent(AppFilesListBox); end; procedure TWizardForm.UpdateWizardFilesButtons; var Enabled: Boolean; begin Enabled := AppFilesListBox.ItemIndex >= 0; AppFilesEditButton.Enabled := Enabled; AppFilesRemoveButton.Enabled := Enabled; end; procedure TWizardForm.UpdateAppExeControls; var Enabled: Boolean; begin Enabled := not NotCreateAppDirCheck.Checked; NoAppExeCheck.Enabled := Enabled; Enabled := Enabled and not NoAppExeCheck.Checked; AppExeLabel.Enabled := Enabled; AppExeEdit.Enabled := Enabled; AppExeEdit.Color := EnabledColors[Enabled]; AppExeButton.Enabled := Enabled; AppExeRunCheck.Enabled := Enabled; AppExeIconsLabel.Enabled := Enabled; DesktopIconCheck.Enabled := Enabled; QuickLaunchIconCheck.Enabled := Enabled; if Enabled then AppExeLabel.Font.Style := AppExeLabel.Font.Style + [fsBold] else AppExeLabel.Font.Style := AppExeLabel.Font.Style - [fsBold]; end; {---} procedure TWizardForm.AppRootDirComboBoxChange(Sender: TObject); begin if AppRootDirComboBox.ItemIndex = AppRootDirComboBox.Items.Count-1 then begin AppRootDirEdit.Enabled := True; AppRootDirEdit.Color := clWindow; ActiveControl := AppRootDirEdit; end else begin AppRootDirEdit.Enabled := False; AppRootDirEdit.Color := clBtnFace; end; end; procedure TWizardForm.NotCreateAppDirCheckClick(Sender: TObject); var Enabled: Boolean; begin Enabled := not NotCreateAppDirCheck.Checked; { AppDir } AppRootDirLabel.Enabled := Enabled; AppRootDirComboBox.Enabled := Enabled; AppRootDirComboBox.Color := EnabledColors[Enabled]; AppRootDirEdit.Enabled := Enabled and (AppRootDirComboBox.ItemIndex = AppRootDirComboBox.Items.Count-1); AppRootDirEdit.Color := EnabledColors[AppRootDirEdit.Enabled]; AppDirNameLabel.Enabled := Enabled; AppDirNameEdit.Enabled := Enabled; AppDirNameEdit.Color := EnabledColors[Enabled]; NotDisableDirPageCheck.Enabled := Enabled; if Enabled then begin AppRootDirLabel.Font.Style := AppRootDirLabel.Font.Style + [fsBold]; AppDirNameLabel.Font.Style := AppRootDirLabel.Font.Style + [fsBold]; end else begin AppRootDirLabel.Font.Style := AppRootDirLabel.Font.Style - [fsBold]; AppDirNameLabel.Font.Style := AppRootDirLabel.Font.Style - [fsBold]; end; { AppFiles } UpdateAppExeControls; end; procedure TWizardForm.AppExeButtonClick(Sender: TObject); var FileName: String; begin FileName := AppExeEdit.Text; if NewGetOpenFileName('', FileName, PathExtractPath(FileName), SWizardAppExeFilter, SWizardAppExeDefaultExt, Handle) then AppExeEdit.Text := FileName; end; procedure TWizardForm.NoAppExeCheckClick(Sender: TObject); begin UpdateAppExeControls; end; procedure TWizardForm.AppFilesListBoxClick(Sender: TObject); begin UpdateWizardFilesButtons; end; procedure TWizardForm.AppFilesListBoxDblClick(Sender: TObject); begin if AppFilesEditButton.Enabled then AppFilesEditButton.Click; end; procedure TWizardForm.AppFilesAddButtonClick(Sender: TObject); var FileList: TStringList; I: Integer; begin FileList := TStringList.Create; try if NewGetOpenFileNameMulti('', FileList, '', SWizardAllFilesFilter, '', Handle) then begin FileList.Sort; for I := 0 to FileList.Count-1 do AddWizardFile(FileList[I], False, False); UpdateWizardFiles; end; finally FileList.Free; end; end; procedure TWizardForm.AppFilesAddDirButtonClick(Sender: TObject); var Path: String; Recurse: Boolean; begin Path := ''; if BrowseForFolder(SWizardAppFiles3, Path, Handle, False) then begin case MsgBox(Format(SWizardAppFilesSubDirsMessage, [Path]), '', mbConfirmation, MB_YESNOCANCEL) of IDYES: Recurse := True; IDNO: Recurse := False; else Exit; end; AddWizardFile(AddBackslash(Path) + '*', Recurse, Recurse); UpdateWizardFiles; end; end; procedure TWizardForm.AppFilesListBoxDropFile(Sender: TDropListBox; const FileName: String); begin if DirExists(FileName) then AddWizardFile(AddBackslash(FileName) + '*', True, True) else AddWizardFile(FileName, False, False); UpdateWizardFiles; UpdateWizardFilesButtons; end; procedure TWizardForm.AppFilesEditButtonClick(Sender: TObject); var WizardFileForm: TWizardFileForm; Index: Integer; begin WizardFileForm := TWizardFileForm.Create(Application); try Index := AppFilesListBox.ItemIndex; WizardFileForm.AllowAppDestRootDir := not NotCreateAppDirCheck.Checked; WizardFileForm.WizardFile := FWizardFiles[Index]; if WizardFileForm.ShowModal = mrOK then begin UpdateWizardFiles; AppFilesListBox.ItemIndex := Index; AppFilesListBox.TopIndex := Index; UpdateWizardFilesButtons; end; finally WizardFileForm.Free; end; end; procedure TWizardForm.AppFilesRemoveButtonClick(Sender: TObject); var I: Integer; begin I := AppFilesListBox.ItemIndex; Dispose(FWizardFiles[I]); FWizardFiles.Delete(I); UpdateWizardFiles; UpdateWizardFilesButtons; end; procedure TWizardForm.NotDisableProgramGroupPageCheckClick( Sender: TObject); begin AllowNoIconsCheck.Enabled := NotDisableProgramGroupPageCheck.Checked; end; procedure TWizardForm.FileButtonClick(Sender: TObject); var Edit: TEdit; Filter, DefaultExt, FileName: String; begin if Sender = AppLicenseFileButton then Edit := AppLicenseFileEdit else if Sender = AppInfoBeforeFileButton then Edit := AppInfoBeforeFileEdit else if Sender = AppInfoAfterFileButton then Edit := AppInfoAfterFileEdit else Edit := SetupIconFileEdit; if Sender <> SetupIconFileButton then begin Filter := SWizardAppDocsFilter; DefaultExt := SWizardAppDocsDefaultExt; end else begin Filter := SWizardCompilerSetupIconFileFilter; DefaultExt := SWizardCompilerSetupIconFileDefaultExt; end; FileName := Edit.Text; if NewGetOpenFileName('', FileName, PathExtractPath(FileName), Filter, DefaultExt, Handle) then Edit.Text := FileName; end; procedure TWizardForm.OutputDirButtonClick(Sender: TObject); var Path: String; begin Path := OutputDirEdit.Text; if PathDrivePartLength(Path) = 0 then Path := ''; { don't pass in a relative path to BrowseForFolder } if BrowseForFolder(SWizardCompilerOutputDir, Path, Handle, True) then OutputDirEdit.Text := Path; end; procedure TWizardForm.PasswordEditChange(Sender: TObject); begin EncryptionCheck.Enabled := PasswordEdit.Text <> ''; end; procedure TWizardForm.AllLanguagesButtonClick(Sender: TObject); var I: Integer; begin for I := 0 to LanguagesList.Items.Count-1 do LanguagesList.Checked[I] := True; end; procedure TWizardForm.NoLanguagesButtonClick(Sender: TObject); var I: Integer; begin for I := 0 to LanguagesList.Items.Count-1 do LanguagesList.Checked[I] := False; end; { --- } procedure TWizardForm.GenerateScript; var Script, ISPP, Setup, Languages, Tasks, Files, INI, Icons, Run, UninstallDelete: String; WizardFile: PWizardFile; I: Integer; AppExeName, AppAmpEscapedName, LanguageName, LanguageMessagesFile: String; begin Script := ''; AppExeName := PathExtractName(AppExeEdit.Text); AppAmpEscapedName := EscapeAmpersands(AppNameEdit.Text); if ISPPCheck.Checked then begin { Setup ISPP usage. Change the edits to reflect ISPP usage. A bit ugly but for now it works. } ISPP := '#define MyAppName "' + AppNameEdit.Text + '"' + SNewLine + '#define MyAppVersion "' + AppVersionEdit.Text + '"' + SNewLine; if AppDirNameEdit.Text = AppNameEdit.Text then AppDirNameEdit.Text := '{#MyAppName}'; if AppGroupNameEdit.Text = AppNameEdit.Text then AppGroupNameEdit.Text := '{#MyAppName}'; AppNameEdit.Text := '{#MyAppName}'; AppAmpEscapedName := '{#StringChange(MyAppName, ''&'', ''&&'')}'; AppVersionEdit.Text := '{#MyAppVersion}'; if AppPublisherEdit.Text <> '' then begin ISPP := ISPP + '#define MyAppPublisher "' + AppPublisherEdit.Text + '"' + SNewLine; AppPublisherEdit.Text := '{#MyAppPublisher}'; end; if AppURLEdit.Text <> '' then begin ISPP := ISPP + '#define MyAppURL "' + AppURLEdit.Text + '"' + SNewLine; AppURLEdit.Text := '{#MyAppURL}'; end; { Special ones } if not NoAppExeCheck.Checked then begin ISPP := ISPP + '#define MyAppExeName "' + AppExeName + '"' + SNewLine; AppExeName := '{#MyAppExeName}'; end; end else ISPP := ''; Setup := '[Setup]' + SNewLine; Languages := '[Languages]' + SNewLine; Tasks := '[Tasks]' + SNewLine; Files := '[Files]' + SNewLine; INI := '[INI]' + SNewLine; Icons := '[Icons]' + SNewLine; Run := '[Run]' + SNewLine; UninstallDelete := '[UninstallDelete]' + SNewLine; if not EmptyCheck.Checked then begin Setup := Setup + ( '; NOTE: The value of AppId uniquely identifies this application.' + SNewLine + '; Do not use the same AppId value in installers for other applications.' + SNewLine + '; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)' + SNewLine); Setup := Setup + 'AppId={' + GenerateGuid + SNewLine; { AppInfo } Setup := Setup + 'AppName=' + AppNameEdit.Text + SNewLine; Setup := Setup + 'AppVersion=' + AppVersionEdit.Text + SNewLine; Setup := Setup + ';AppVerName=' + AppNameEdit.Text + ' ' + AppVersionEdit.Text + SNewLine; if AppPublisherEdit.Text <> '' then Setup := Setup + 'AppPublisher=' + AppPublisherEdit.Text + SNewLine; if AppURLEdit.Text <> '' then begin Setup := Setup + 'AppPublisherURL=' + AppURLEdit.Text + SNewLine; Setup := Setup + 'AppSupportURL=' + AppURLEdit.Text + SNewLine; Setup := Setup + 'AppUpdatesURL=' + AppURLEdit.Text + SNewLine; end; { AppDir } if not NotCreateAppDirCheck.Checked then begin if AppRootDirComboBox.ItemIndex = AppRootDirComboBox.Items.Count-1 then Setup := Setup + 'DefaultDirName=' + AddBackslash(AppRootDirEdit.Text) + AppDirNameEdit.Text + SNewLine else Setup := Setup + 'DefaultDirName=' + AddBackslash(AppRootDirs[AppRootDirComboBox.ItemIndex].Constant) + AppDirNameEdit.Text + SNewLine; if not NotDisableDirPageCheck.Checked then Setup := Setup + 'DisableDirPage=yes' + SNewLine; end else begin Setup := Setup + 'CreateAppDir=no' + SNewLine; end; { AppFiles } if not NotCreateAppDirCheck.Checked and not NoAppExeCheck.Checked then begin Files := Files + 'Source: "' + AppExeEdit.Text + '"; DestDir: "{app}"; Flags: ignoreversion' + SNewLine; if AppExeRunCheck.Checked then begin if CompareText(PathExtractExt(AppExeEdit.Text), '.exe') = 0 then Run := Run + 'Filename: "{app}\' + AppExeName + '"; Description: "{cm:LaunchProgram,' + AppAmpEscapedName + '}"; Flags: nowait postinstall skipifsilent' + SNewLine else Run := Run + 'Filename: "{app}\' + AppExeName + '"; Description: "{cm:LaunchProgram,' + AppAmpEscapedName + '}"; Flags: shellexec postinstall skipifsilent' + SNewLine; end; end; for I := 0 to FWizardFiles.Count-1 do begin WizardFile := FWizardFiles[I]; Files := Files + 'Source: "' + WizardFile.Source + '"; DestDir: "' + RemoveBackslashUnlessRoot(AddBackslash(WizardFile.DestRootDir) + WizardFile.DestSubDir) + '"; Flags: ignoreversion'; if WizardFile.RecurseSubDirs then Files := Files + ' recursesubdirs'; if WizardFile.CreateAllSubDirs then Files := Files + ' createallsubdirs'; Files := Files + SNewLine; end; { AppGroup } if not NotCreateAppDirCheck.Checked then begin Setup := Setup + 'DefaultGroupName=' + AppGroupNameEdit.Text + SNewLine; if not NoAppExeCheck.Checked then Icons := Icons + 'Name: "{group}\' + AppNameEdit.Text + '"; Filename: "{app}\' + AppExeName + '"' + SNewLine; if not NotDisableProgramGroupPageCheck.Checked then Setup := Setup + 'DisableProgramGroupPage=yes' + SNewLine; if AllowNoIconsCheck.Checked and NotDisableProgramGroupPageCheck.Checked then Setup := Setup + 'AllowNoIcons=yes' + SNewLine; if CreateURLIconCheck.Enabled and CreateURLIconCheck.Checked then Icons := Icons + 'Name: "{group}\{cm:ProgramOnTheWeb,' + AppNameEdit.Text + '}"; Filename: "' + AppURLEdit.Text + '"' + SNewLine; if CreateUninstallIconCheck.Checked then Icons := Icons + 'Name: "{group}\{cm:UninstallProgram,' + AppNameEdit.Text + '}"; Filename: "{uninstallexe}"' + SNewLine; if DesktopIconCheck.Enabled and DesktopIconCheck.Checked then begin Tasks := Tasks + 'Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked' + SNewLine; Icons := Icons + 'Name: "{commondesktop}\' + AppNameEdit.Text + '"; Filename: "{app}\' + AppExeName + '"; Tasks: desktopicon' + SNewLine; end; if QuickLaunchIconCheck.Enabled and QuickLaunchIconCheck.Checked then begin Tasks := Tasks + 'Name: "quicklaunchicon"; Description: "{cm:CreateQuickLaunchIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked; OnlyBelowVersion: 0,6.1' + SNewLine; Icons := Icons + 'Name: "{userappdata}\Microsoft\Internet Explorer\Quick Launch\' + AppNameEdit.Text + '"; Filename: "{app}\' + AppExeName + '"; Tasks: quicklaunchicon' + SNewLine; end; end; { AppDocs } if AppLicenseFileEdit.Text <> '' then Setup := Setup + 'LicenseFile=' + AppLicenseFileEdit.Text + SNewLine; if AppInfoBeforeFileEdit.Text <> '' then Setup := Setup + 'InfoBeforeFile=' + AppInfoBeforeFileEdit.Text + SNewLine; if AppInfoAfterFileEdit.Text <> '' then Setup := Setup + 'InfoAfterFile=' + AppInfoAfterFileEdit.Text + SNewLine; { Languages} if FLanguages.Count > 1 then begin for I := 0 to LanguagesList.Items.Count-1 do begin if LanguagesList.Checked[I] then begin LanguageMessagesFile := FLanguages[Integer(LanguagesList.ItemObject[I])]; if LanguageMessagesFile <> LanguagesDefaultIsl then begin LanguageName := LanguagesList.Items[I]; LanguageMessagesFile := 'Languages\' + LanguageMessagesFile; end else LanguageName := LanguagesDefaultIslDescription; StringChange(LanguageName, ' ', ''); LanguageName := LowerCase(LanguageName); Languages := Languages + 'Name: "' + LanguageName + '"; MessagesFile: "compiler:' + LanguageMessagesFile + '"' + SNewLine; end; end; end; { Compiler } if OutputDirEdit.Text <> '' then Setup := Setup + 'OutputDir=' + OutputDirEdit.Text + SNewLine; if OutputBaseFileNameEdit.Text <> '' then Setup := Setup + 'OutputBaseFilename=' + OutputBaseFileNameEdit.Text + SNewLine; if SetupIconFileEdit.Text <> '' then Setup := Setup + 'SetupIconFile=' + SetupIconFileEdit.Text + SNewLine; if PasswordEdit.Text <> '' then begin Setup := Setup + 'Password=' + PasswordEdit.Text + SNewLine; if ISCryptInstalled and EncryptionCheck.Checked then Setup := Setup + 'Encryption=yes' + SNewLine; end; { Other } Setup := Setup + 'Compression=lzma' + SNewLine; Setup := Setup + 'SolidCompression=yes' + SNewLine; { Build script } if ISPP <> '' then Script := Script + ISPP + SNewLine; Script := Script + Setup + SNewLine; if Length(Languages) > Length('[Languages]')+2 then Script := Script + Languages + SNewLine; if Length(Tasks) > Length('[Tasks]')+2 then Script := Script + Tasks + SNewLine; if Length(Files) > Length('[Files]')+2 then Script := Script + Files + '; NOTE: Don''t use "Flags: ignoreversion" on any shared system files' + SNewLine2; if Length(INI) > Length('[INI]')+2 then Script := Script + INI + SNewLine; if Length(Icons) > Length('[Icons]')+2 then Script := Script + Icons + SNewLine; if Length(Run) > Length('[Run]')+2 then Script := Script + Run + SNewLine; if Length(UninstallDelete) > Length('[UninstallDelete]')+2 then Script := Script + UninstallDelete + SNewLine; FResult := wrComplete; end else begin Script := Script + Setup + SNewLine; FResult := wrEmpty; end; FResultScript := FixLabel(SWizardScriptHeader) + SNewLine2 + Script; end; { --- } end.
unit ts.Core.VTNode; {$MODE DELPHI} interface uses VirtualTrees; { Documentation TVTNode is a type designed to be used as the data structure where each treenode in a treeview is pointing to. For any treenode (of type PVirtualNode) this can be obtained by the following method defined in TBaseVirtualStringTree: function GetNodeData<T>(pNode: PVirtualNode): T; type TMyData = class ... end; } type { TVTNode } TVTNode<T> = class private FCheckState : TCheckState; FCheckType : TCheckType; FData : T; FHint : string; FImageIndex : Integer; FOwnsObject : Boolean; FText : string; FTree : TCustomVirtualStringTree; FVNode : PVirtualNode; private function SearchTree(ANode: TVTNode<T>; const AData: T): TVTNode<T>; protected {$REGION 'property access methods'} function GetCheckState: TCheckState; function GetCheckType: TCheckType; function GetChildCount: UInt32; function GetData: T; function GetHint: string; function GetImageIndex: Integer; function GetIndex: Integer; function GetItem(AIndex: UInt32): TVTNode<T>; function GetLevel: Integer; function GetOwnsObject: Boolean; function GetText: string; virtual; function GetTree: TCustomVirtualStringTree; function GetVisible: Boolean; function GetVNode: PVirtualNode; procedure SetCheckState(const Value: TCheckState); procedure SetCheckType(const Value: TCheckType); procedure SetData(const Value: T); procedure SetHint(const Value: string); procedure SetImageIndex(const Value: Integer); procedure SetOwnsObject(AValue: Boolean); procedure SetText(const Value: string); virtual; procedure SetVisible(const Value: Boolean); procedure SetVNode(const Value: PVirtualNode); {$ENDREGION} public constructor Create( ATree : TCustomVirtualStringTree; const AData : T; AOwnsObject : Boolean = True; AParentVNode : PVirtualNode = nil; const AText : string = '' ); overload; virtual; constructor Create( ATree : TCustomVirtualStringTree; AOwnsObject : Boolean = True; AParentVNode : PVirtualNode = nil; const AText : string = '' ); overload; virtual; procedure BeforeDestruction; override; function Add(const AData: T; AOwnsObject: Boolean = True): TVTNode<T>; function Find(const AData: T): TVTNode<T>; { Points to the corresponding node of the virtual treeview. } property VNode: PVirtualNode read GetVNode write SetVNode; property ChildCount: UInt32 read GetChildCount; { User defined data that is associated with the current node. } property Data: T read GetData write SetData; property CheckState: TCheckState read GetCheckState write SetCheckState; property CheckType: TCheckType read GetCheckType write SetCheckType; property ImageIndex: Integer read GetImageIndex write SetImageIndex; property Items[AIndex: UInt32]: TVTNode<T> read GetItem; default; property Index: Integer read GetIndex; property Level: Integer read GetLevel; { If Data is of a class type, this determines if Data is freed when TVTNode instance is freed. } property OwnsObject: Boolean read GetOwnsObject write SetOwnsObject; property Text: string read GetText write SetText; property Tree: TCustomVirtualStringTree read GetTree; property Hint: string read GetHint write SetHint; property Visible: Boolean read GetVisible write SetVisible; end; implementation uses SysUtils, ts.Core.Logger; {$REGION 'construction and destruction'} constructor TVTNode<T>.Create(ATree: TCustomVirtualStringTree; const AData: T; AOwnsObject: Boolean; AParentVNode: PVirtualNode; const AText: string); begin FTree := ATree; FData := AData; FOwnsObject := AOwnsObject; FText := AText; if not Assigned(AParentVNode) then // create rootnode FVNode := FTree.AddChild(nil, Self); end; constructor TVTNode<T>.Create(ATree: TCustomVirtualStringTree; AOwnsObject: Boolean; AParentVNode: PVirtualNode; const AText: string); begin FTree := ATree; FData := Default(T); FOwnsObject := AOwnsObject; FText := AText; if not Assigned(AParentVNode) then // create rootnode FVNode := FTree.AddChild(nil, Self); end; procedure TVTNode<T>.BeforeDestruction; begin if (GetTypekind(T) = tkClass) and OwnsObject then FreeAndNil(FData); FTree := nil; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'property access methods'} function TVTNode<T>.GetCheckState: TCheckState; begin if Assigned(VNode) then FCheckState := VNode.CheckState; Result := FCheckState; end; procedure TVTNode<T>.SetCheckState(const Value: TCheckState); begin FCheckState := Value; if Assigned(VNode) then VNode.CheckState := Value; end; function TVTNode<T>.GetCheckType: TCheckType; begin if Assigned(VNode) then FCheckType := VNode.CheckType; Result := FCheckType; end; procedure TVTNode<T>.SetCheckType(const Value: TCheckType); begin FCheckType := Value; if Assigned(VNode) then VNode.CheckType := Value; end; function TVTNode<T>.GetChildCount: UInt32; begin if Assigned(VNode) then Result := VNode.ChildCount else Result := 0; end; function TVTNode<T>.GetData: T; begin Result := FData; end; procedure TVTNode<T>.SetData(const Value: T); begin FData := Value; end; function TVTNode<T>.GetHint: string; begin Result := FHint; end; procedure TVTNode<T>.SetHint(const Value: string); begin FHint := Value; end; function TVTNode<T>.GetImageIndex: Integer; begin Result := FImageIndex; end; procedure TVTNode<T>.SetImageIndex(const Value: Integer); begin FImageIndex := Value; end; function TVTNode<T>.GetIndex: Integer; begin if Assigned(VNode) then Result := VNode.Index else Result := 0; end; function TVTNode<T>.GetOwnsObject: Boolean; begin Result := FOwnsObject; end; procedure TVTNode<T>.SetOwnsObject(AValue: Boolean); begin FOwnsObject := aValue; end; function TVTNode<T>.GetTree: TCustomVirtualStringTree; begin Result := FTree; end; function TVTNode<T>.GetItem(AIndex: UInt32): TVTNode<T>; var I : UInt32; VN : PVirtualNode; begin VN := VNode.FirstChild; if AIndex > 0 then begin for I := 0 to AIndex - 1 do begin VN := VN.NextSibling; end; end; Result := TVTNode<T>(FTree.GetNodeData(VN)^); end; function TVTNode<T>.GetLevel: Integer; begin if Assigned(FTree) and Assigned(FVNode) then begin Result := FTree.GetNodeLevel(VNode); end else Result := 0; end; function TVTNode<T>.GetText: string; begin Result := FText; end; procedure TVTNode<T>.SetText(const Value: string); begin FText := Value; end; function TVTNode<T>.GetVisible: Boolean; begin if Assigned(FTree) and Assigned(FVNode) then begin Result := FTree.IsVisible[VNode]; end else Result := False; end; procedure TVTNode<T>.SetVisible(const Value: Boolean); begin if Assigned(FTree) and Assigned(FVNode) then begin FTree.IsVisible[VNode] := Value; end; end; function TVTNode<T>.GetVNode: PVirtualNode; begin Result := FVNode; end; procedure TVTNode<T>.SetVNode(const Value: PVirtualNode); begin if Value <> VNode then begin FVNode := Value; if Assigned(FVNode) then begin FVNode.CheckState := FCheckState; FVNode.CheckType := FCheckType; end; end; end; {$ENDREGION} {$REGION 'private methods'} { Search with recursion. } function TVTNode<T>.SearchTree(ANode: TVTNode<T>;const AData: T): TVTNode<T>; var I : Integer; LFound : Boolean; LItem : TVTNode<T>; begin I := 0; LFound := False; while (I < ANode.ChildCount) and not LFound do begin LItem := ANode.Items[I]; if LItem.Data = AData then begin Result := LItem; LFound := True; end else begin LItem := SearchTree(LItem, AData); LFound := Assigned(LItem); end; Inc(I); end; end; {$ENDREGION} {$REGION 'public methods'} function TVTNode<T>.Add(const AData: T; AOwnsObject: Boolean): TVTNode<T>; var LVTNode : TVTNode<T>; LVNode : PVirtualNode; begin if Assigned(FTree) then begin Logger.Send('Assigned AData', Assigned(AData)); Logger.Send('Assigned VNode', Assigned(VNode)); if not Assigned(VNode) then // create root node if it does not exist begin VNode := FTree.AddChild(nil, Self); end; LVTNode := TVTNode<T>.Create(FTree, AData, AOwnsObject, VNode); LVNode := FTree.AddChild(VNode, LVTNode); LVTNode.VNode := LVNode; Result := LVTNode; end else Result := nil; end; function TVTNode<T>.Find(const AData: T): TVTNode<T>; begin Result := SearchTree(Self, AData); end; {$ENDREGION} end.
unit CardEdit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, DBCtrls, Buttons, ExtCtrls, bddatamodule, DB, sqldb, MetaData, StdCtrls; type TInsert_help = record FLookUpComboBox: TDBLookupComboBox; FLst_Source: TDataSource; FLst_query: TSQLQuery; end; TCom_Proc = procedure of object; { TCardEditForm } TCardEditForm = class(TForm) Datasource1: TDatasource; Card_edit_datasource: TDatasource; Save_Button: TSpeedButton; Edit_Box: TScrollBox; SQLQuery1: TSQLQuery; Card_Edit_SQLQuery: TSQLQuery; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure Edit_PanelClick(Sender: TObject); procedure Save_ButtonClick(Sender: TObject); constructor Create(Atable: TTable_Info; Aproc: TCom_Proc; ACurrent_Record_ID: string; def_filters: array of integer); private fdef_filters: array of integer; FCurrent_Table: TTable_Info; FRefresh_Reference: TCom_Proc; FCurrent_Record_ID: string; FInsert_list: array of TInsert_help; FEdits_list: array of Tedit; FGenerator_Value: string; FLabels_list: array of TLabel; { private declarations } public { public declarations } end; const trash_Value = '-300'; var CardEditForm: TCardEditForm; implementation {$R *.lfm} { TCardEditForm } procedure TCardEditForm.FormShow(Sender: TObject); var i: integer; begin if FCurrent_Record_ID = '0' then begin FCurrent_Record_ID := trash_Value; Self.Caption := 'Добавление'; end else self.Caption := ' Изменение'; with Card_Edit_SQLQuery do begin Close; sql.Text := 'select * from ' + FCurrent_Table.FTable_Name + ' where id = ' + FCurrent_Record_ID; Open; end; for i := 1 to High(FCurrent_Table.FFields) do begin SetLength(FLabels_list, Length(FLabels_list) + 1); FLabels_list[High(FLabels_list)] := TLabel.Create(Edit_Box); with FLabels_list[High(FLabels_list)] do begin Parent := Edit_Box; top := 10 + ((i - 1) * 2) * 25; left := 10; Height := 25; Width := 200; Caption := FCurrent_Table.FFields[i].FRu_Name + ':'; end; if (FCurrent_Table.FFields[i] is TReference_Field_Info) then begin SetLength(FInsert_list, Length(FInsert_list) + 1); FInsert_list[High(FInsert_list)].FLst_query := TSQLQuery.Create(Edit_Box); with FInsert_list[High(FInsert_list)].FLst_query do begin DataBase := Data_Module.IBConnection1; Transaction := Data_Module.SQLTransaction1; Close; sql.Text := 'select * from ' + FCurrent_Table.FFields[i].Get_Source_Table; Open; end; FInsert_list[High(FInsert_list)].FLst_Source := TDataSource.Create(Edit_Box); FInsert_list[High(FInsert_list)].FLst_Source.DataSet := FInsert_list[High(FInsert_list)].FLst_query; FInsert_list[High(FInsert_list)].FLookUpComboBox := TDBLookupComboBox.Create(Edit_Box); with FInsert_list[High(FInsert_list)].FLookUpComboBox do begin Parent := Edit_Box; top := 10 + (i * 2 - 1) * 25; left := 10; Height := 25; DataSource := Card_edit_datasource; ListSource := FInsert_list[High(FInsert_list)].FLst_Source; Width := 200; ListField := FCurrent_Table.FFields[i].Get_Inner_Field; DataField := FCurrent_Table.FFields[i].FName; KeyField := 'ID'; Style := csDropDownList; end; end else begin SetLength(FEdits_list, Length(FEdits_list) + 1); FEdits_list[high(FEdits_list)] := TEdit.Create(Edit_Box); with FEdits_list[high(FEdits_list)] do begin parent := Edit_Box; top := 10 + (i * 2 - 1) * 25; left := 10; Height := 25; Width := 200; Caption := Card_Edit_SQLQuery.FieldByName( FCurrent_Table.FFields[i].FName).Text; tag := i; end; end; end; end; procedure TCardEditForm.Edit_PanelClick(Sender: TObject); begin end; procedure TCardEditForm.FormCreate(Sender: TObject); begin end; procedure TCardEditForm.Save_ButtonClick(Sender: TObject); var i: integer; param: string; Sql_Edit: string; Empty_Field: boolean; begin for i := 0 to High(FInsert_list) do if FInsert_list[i].FLookUpComboBox.Caption = '' then begin ShowMessage('заполните все поля'); exit; end; for i := 0 to High(FEdits_list) do if Fedits_List[i].Caption = '' then begin ShowMessage('заполните все поля'); exit; end; if (FCurrent_Record_ID = trash_Value) and (Length(FEdits_list) = 0) then begin with SQLQuery1 do begin Close; sql.Text := 'select next value for ' + FCurrent_Table.FGenerator_Name + ' from RDB$DATABASE'; Open; FGenerator_Value := FieldByName('Gen_id').Text; end; with Card_Edit_SQLQuery do begin FieldByName('Id').Text := FGenerator_Value; Open; ApplyUpdates; end; end else with Card_Edit_SQLQuery do begin Open; ApplyUpdates; end; if length(FEdits_list) > 0 then with Card_Edit_SQLQuery do begin Close; if FCurrent_Record_ID = trash_Value then sql.Text := ' insert into ' + FCurrent_Table.FTable_Name + ' values( next value for ' + FCurrent_Table.FGenerator_Name + ',' else Sql.Text := ' update ' + FCurrent_Table.FTable_Name + ' set '; for i := 0 to High(FEdits_list) do begin param := 'param' + IntToStr(i); if FCurrent_Record_ID = trash_Value then sql.Text := sql.Text + ' :' + param + ',' else Sql.Text := Sql.Text + FCurrent_Table.FFields[FEdits_list[i].tag].FName + ' = :' + param + ','; Params.ParamByName(param).AsString := FEdits_list[i].Caption; end; //sql.Text:=Copy(sql.Text, 1, Length(sql.Text)-2); sql.Text := Copy(sql.Text, 1, Length(SQL.Text) - 3); //ShowMessage(sql.Text); if FCurrent_Record_ID = trash_Value then sql.Text := sql.Text + ' )' else Sql.Text := Sql.Text + ' where id = ' + FCurrent_Record_ID; ExecSQL; end; Data_Module.SQLTransaction1.Commit; FRefresh_Reference; Self.Close; end; constructor TCardEditForm.Create(Atable: TTable_Info; Aproc: TCom_Proc; ACurrent_Record_ID: string; def_filters: array of integer); var i:integer; begin FCurrent_Table := Atable; FRefresh_Reference := Aproc; FCurrent_Record_ID := ACurrent_Record_ID; inherited Create(nil); for i:=0 to High(def_filters) do fdef_filters[i] := def_filters[i]; end; end.
unit TFGame; interface uses GVDLL, SysUtils; type TTFGame = class; TTFGameScene = class private FGame : TTFGame; function GetRez: Integer; protected property Rez: Integer read GetRez; public constructor Create(AOwner: TTFGame); procedure LoadResources; virtual; abstract; procedure FreeResources; virtual; abstract; destructor Destroy; override; procedure Update(ElapsedTime: Single); virtual; abstract; procedure Render; virtual; abstract; procedure HandleEvent(Event: Integer; Data: Pointer); virtual; procedure SendEventToGame(Event: Integer; Data: Pointer); property Game: TTFGame read FGame; end; TTFSpriteEngine = class; TTFGameSprite = class private FEntity: Integer; FDetectCollisions: Boolean; procedure SetDetectCollisions(const Value: Boolean); procedure SetPos(const Value: TGVVector); function GetPos: TGVVector; protected property Entity: Integer read FEntity; public constructor Create(aSprite: Integer; spPage, spGroup: Cardinal; Mju: Extended=6; MSB: Integer=10; AT: Byte=70); destructor Destroy; override; procedure OnCollide(DumpedInto: TTFGameSprite; Point: TGVVector); virtual; procedure Render; virtual; procedure Update(ElapsedTime: Single); virtual; property DetectCollisions: Boolean read FDetectCollisions write SetDetectCollisions; property Pos: TGVVector read GetPos write SetPos; end; TTFSpriteEngine = class private FSprites: array of TTFGameSprite; FCount : Integer; function GetSprite(Index: Integer): TTFGameSprite; public property Sprites[Index: Integer]: TTFGameSprite read GetSprite; end; TTFPlayer = class private FScene: TTFGameScene; public property Scene: TTFGameScene read FScene; constructor Create(aOwner: TTFGameScene); procedure Update(ElapsedTime: Single); virtual; abstract; // updates player actions at screen end; { === TTFGame =========================================================== } { TTFGameScreen } TTFGameScreen = record Caption : string; Width : Cardinal; Height : Cardinal; Bpp : Cardinal; Windowed: Boolean; end; PGVGameScreen = ^TTFGameScreen; { TTFGameViewport } TTFGameViewport = record X : Cardinal; Y : Cardinal; Width : Cardinal; Height: Cardinal; end; PGVGameViewport = ^TTFGameViewport; { TTFGameAudio } TTFGameAudio = record MusicVol : Single; SfxVol : Single; MusicPath: string; end; PGVGameAudio = ^TTFGameAudio; { Аналог TApplication - инициализанция, основной цикл работы приложения, использующего Game Vision SDK. В наследнике необходимо перекрыть методы LoadConfig, SaveConfig } TTFGame = class private FScenes : array of TTFGameScene; FElapsedTime : Single; FFrameRate : Cardinal; FScreen : TTFGameScreen; FViewport : TTFGameViewport; FAudio : TTFGameAudio; FSceneCount : Integer; FCurrentScene : Integer; FRezFileName : string; FRez : Integer; function GetScreen : PGVGameScreen; function GetViewport: PGVGameViewport; function GetAudio : PGVGameAudio; function GetScene(Index: Integer): TTFGameScene; function GetCurrentScene: Integer; procedure SetCurrentScene(const Value: Integer); function GetCaption: String; function GetColorDeep: Integer; function GetHeight: Integer; function GetWidth: Integer; function GetWindowed: Boolean; procedure SetCaption(const Value: String); procedure SetColorDeep(const Value: Integer); procedure SetHeight(const Value: Integer); procedure SetWidth(const Value: Integer); procedure SetWindowed(const Value: Boolean); public property Scenes[Index:Integer]: TTFGameScene read GetScene; property CurrentScene: Integer read GetCurrentScene write SetCurrentScene; property ElapsedTime: Single read FElapsedTime; property FrameRate : Cardinal read FFrameRate; property Screen : PGVGameScreen read GetScreen; property Viewport : PGVGameViewport read GetViewport; property Audio : PGVGameAudio read GetAudio; property Rez : Integer read FRez; public constructor Create(aRezFile: string); destructor Destroy; override; function AddScene(AScene: TTFGameScene): Integer; procedure LoadConfig; virtual; procedure SaveConfig; virtual; procedure SystemsInit; virtual; procedure SystemsDone; virtual; procedure PreRender; virtual; procedure PostRender; virtual; procedure Run; procedure HandleEvent(Event: Integer; Data: Pointer); virtual; { --- Audio Routines ------------------------------------------------ } procedure AdjustSfxVol(aDelta: Single); procedure AdjustMusicVol(aDelta: Single); public property Caption: String read GetCaption write SetCaption; property Width: Integer read GetWidth write SetWidth; property Height: Integer read GetHeight write SetHeight; property ColorDeep: Integer read GetColorDeep write SetColorDeep; property Windowed: Boolean read GetWindowed write SetWindowed; end; implementation { === TTFGame =========================================================== } function TTFGame.GetScreen: PGVGameScreen; begin Result := @FScreen; end; function TTFGame.GetViewport: PGVGameViewport; begin Result := @FViewport; end; function TTFGame.GetAudio: PGVGameAudio; begin Result := @FAudio; end; constructor TTFGame.Create(aRezFile: string); begin inherited Create; FScenes := nil; FElapsedTime := 0; FFrameRate := 0; FillChar(FScreen, SizeOf(FScreen), 0); FillChar(FViewport, SizeOf(FViewport), 0); FillChar(FAudio, SizeOf(FAudio), 0); FRezFileName := aRezFile; LoadConfig; SystemsInit; end; destructor TTFGame.Destroy; begin SystemsDone; SaveConfig; inherited Destroy; end; procedure TTFGame.LoadConfig; begin end; procedure TTFGame.SaveConfig; begin end; procedure TTFGame.PreRender; begin end; procedure TTFGame.PostRender; begin end; procedure TTFGame.Run; var SC : TTFGameScene; begin if FSceneCount = 0 then Exit; FCurrentScene := 0; // enter game loop repeat // let windows do its thing; GV_App_ProcessMessages; // if the render / appwindow contex is not ready just let windows // process messages if not GV_RenderDevice_IsReady then continue; SC := FScenes[FCurrentScene]; // start rendering if GV_RenderDevice_StartFrame then begin // pre render PreRender; SC.Render; // post render PostRender; // stop rendering GV_RenderDevice_EndFrame; end; // show frame buffer GV_RenderDevice_ShowFrame; // update input GV_Input_Update; // update timing GV_Timer_Update; FElapsedTime := GV_Timer_ElapsedTime; FFrameRate := GV_Timer_FrameRate; SC.Update(FElapsedTime); // loop until app is terminated until GV_App_IsTerminated; end; procedure TTFGame.AdjustMusicVol(aDelta: Single); begin with Audio^ do begin MusicVol := MusicVol + aDelta; GV_ClampValueSingle(MusicVol, 0.0, 1.0); GV_MusicPlayer_SetSongVol(MusicVol); end; end; procedure TTFGame.AdjustSfxVol(aDelta: Single); begin with Audio^ do begin SfxVol := SfxVol + aDelta; GV_ClampValueSingle(SfxVol, 0.0, 1.0); GV_Audio_SetMasterSfxVol(SfxVol); end; end; { TTFGameScene } constructor TTFGameScene.Create(AOwner: TTFGame); begin inherited Create; FGame := AOwner; LoadResources; end; function TTFGame.GetScene(Index: Integer): TTFGameScene; begin Result := FScenes[Index]; end; destructor TTFGameScene.Destroy; begin FreeResources; inherited; end; function TTFGame.AddScene(AScene: TTFGameScene): Integer; begin Inc(FSceneCount); if FSceneCount > Length(FScenes) then SetLength(FScenes, Length(FScenes)+10); FScenes[FSceneCount-1] := AScene; Result := FSceneCount - 1; end; function TTFGame.GetCurrentScene: Integer; begin Result := FCurrentScene; end; procedure TTFGame.SetCurrentScene(const Value: Integer); begin FCurrentScene := Value; end; procedure TTFGame.SystemsDone; begin if FRez <> -1 then GV_RezFile_CloseArchive(FRez); GV_Input_Close; // shutdown graphics GV_RenderDevice_RestoreMode; // shutdown app window GV_AppWindow_Close; // dispose resources GV_Entity_Done; GV_Polygon_Done; GV_Image_Done; GV_Font_Done; GV_Sprite_Done; GV_Texture_Done; GV_RezFile_Done; GV_Done; end; procedure TTFGame.SystemsInit; begin {$IFDEF DEBUG} GV_Init; {$ELSE} GV_Init(GV_LogFile_Priority_Critical); {$ENDIF} // alloc resources GV_RezFile_Init(256); GV_Texture_Init(256); GV_Font_Init(256); GV_Sprite_Init(256); GV_Image_Init(256); GV_Polygon_Init(256); GV_Entity_Init(256); if FRezFileName <> '' then FRez := GV_RezFile_OpenArchive(FRezFileName) else FRez := -1; GV_AppWindow_Open(FScreen.Caption, FScreen.Width, FScreen.Height); GV_AppWindow_Show; GV_RenderDevice_SetMode(GV_AppWindow_GetHandle, FScreen.Width, FScreen.Height, FScreen.Bpp, FScreen.Windowed, GV_SwapEffect_Discard); // init input GV_Input_Open(GV_AppWindow_GetHandle, FScreen.Windowed); end; function TTFGameScene.GetRez: Integer; begin Result := FGame.FRez; end; procedure TTFGameScene.HandleEvent(Event: Integer; Data: Pointer); begin // process your scene messages here end; procedure TTFGame.HandleEvent(Event: Integer; Data: Pointer); begin // process your game events here end; procedure TTFGameScene.SendEventToGame(Event: Integer; Data: Pointer); begin FGame.HandleEvent(Event, Data); end; { TTFPlayer } constructor TTFPlayer.Create(aOwner: TTFGameScene); begin inherited Create; FScene := aOwner; end; { TTFGameSprite } constructor TTFGameSprite.Create(aSprite: Integer; spPage, spGroup: Cardinal; Mju: Extended; MSB: Integer; AT: Byte); begin FEntity := GV_Entity_Create(aSprite, spPage, spGroup); GV_Entity_SetRenderState(FEntity, GV_RenderState_Image); GV_Entity_PolyPointTrace(FEntity, Mju, MSB, AT); end; destructor TTFGameSprite.Destroy; begin GV_Entity_Dispose(FEntity); inherited; end; function TTFGameSprite.GetPos: TGVVector; begin GV_Entity_GetPos(FEntity, @Result.X, @Result.Y); end; procedure TTFGameSprite.OnCollide(DumpedInto: TTFGameSprite; Point: TGVVector); begin end; procedure TTFGameSprite.Render; begin GV_Entity_Render(FEntity); end; procedure TTFGameSprite.SetDetectCollisions(const Value: Boolean); begin FDetectCollisions := Value; end; procedure TTFGameSprite.SetPos(const Value: TGVVector); begin GV_Entity_SetPos(FEntity, Value.X, Value.Y); end; procedure TTFGameSprite.Update(ElapsedTime: Single); begin end; { TTFSpriteEngine } function TTFSpriteEngine.GetSprite(Index: Integer): TTFGameSprite; begin Result := FSprites[Index]; end; function TTFGame.GetCaption: String; begin Result:= Screen^.Caption; end; function TTFGame.GetColorDeep: Integer; begin Result:= Screen^.BPP; end; function TTFGame.GetHeight: Integer; begin Result:= Screen^.Height; end; function TTFGame.GetWidth: Integer; begin Result:= Screen^.Width; end; function TTFGame.GetWindowed: Boolean; begin Result:= Screen^.Windowed; end; procedure TTFGame.SetCaption(const Value: String); begin if Screen^.Caption <> Value then Screen^.Caption:= Value; end; procedure TTFGame.SetColorDeep(const Value: Integer); begin if Screen^.BPP <> Value then Screen^.BPP:= Value; end; procedure TTFGame.SetHeight(const Value: Integer); begin if Screen^.Height <> Value then Screen^.Height:= Value; end; procedure TTFGame.SetWidth(const Value: Integer); begin if Screen^.Width <> Value then Screen^.Width:= Value; end; procedure TTFGame.SetWindowed(const Value: Boolean); begin if Screen^.Windowed <> Value then Screen^.Windowed:= Value; end; end.
unit TestActivitiesSamplesUnit; interface uses TestFramework, Classes, SysUtils, DateUtils, BaseTestOnlineExamplesUnit, EnumsUnit; type TTestActivitiesSamples = class(TTestOnlineExamples) private function GetRouteId: String; procedure CheckActivitiesWithInvalidRouteId(ActivityType: TActivityType); procedure CheckActivitiesWithRouteId(ActivityType: TActivityType; RouteId: String); function CheckActivitiesWithoutRouteId(ActivityType: TActivityType; IsNullNow: boolean = False): String; published procedure GetAllActivities; procedure GetTeamActivities; procedure GetAreaAddedActivities; procedure GetAreaUpdatedActivities; procedure GetAreaRemovedActivities; procedure GetDestinationDeletedActivities; procedure GetDestinationOutOfSequenceActivities; procedure GetDriverArrivedEarlyActivities; procedure GetDriverArrivedLateActivities; procedure GetDriverArrivedOnTimeActivities; procedure GetGeofenceLeftActivities; procedure GetGeofenceEnteredActivities; procedure GetDestinationInsertedActivities; procedure GetDestinationMarkedAsDepartedActivities; procedure GetDestinationMarkedAsVisitedActivities; procedure GetMemberCreatedActivities; procedure GetMemberDeletedActivities; procedure GetMemberModifiedActivities; procedure GetDestinationMovedActivities; procedure GetNoteInsertedActivities; procedure GetRouteDeletedActivities; procedure GetRouteOptimizedActivities; procedure GetRouteOwnerChangedActivities; procedure GetDestinationUpdatedActivities; procedure LogSpecificMessage; end; implementation uses ActivityUnit, CommonTypesUnit, DataObjectUnit; procedure TTestActivitiesSamples.GetAreaAddedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atAreaAdded; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetAreaRemovedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atAreaRemoved; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetAreaUpdatedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atAreaUpdated; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.CheckActivitiesWithInvalidRouteId( ActivityType: TActivityType); var RouteId: String; Activities: TActivityList; Limit, Offset, Total: integer; ErrorString: String; begin RouteId := 'qwe'; Limit := 2; Offset := 0; Activities := FRoute4MeManager.ActivityFeed.GetActivities(RouteId, ActivityType, Limit, Offset, Total, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckEquals(0, Total); CheckEquals(0, Activities.Count); finally FreeAndNil(Activities); end; end; function TTestActivitiesSamples.CheckActivitiesWithoutRouteId( ActivityType: TActivityType; IsNullNow: boolean = False): String; var Activities: TActivityList; ErrorString: String; Total: integer; Limit, Offset: integer; i: integer; begin Result := EmptyStr; Limit := 2; Offset := 0; Activities := FRoute4MeManager.ActivityFeed.GetActivities( ActivityType, Limit, Offset, Total, ErrorString); try if (Activities.Count > 0) then for i := 0 to Activities.Count - 1 do if Activities[0].RouteId.IsNotNull then begin Result := Activities[0].RouteId; Break; end; CheckEquals(EmptyStr, ErrorString); if (IsNullNow) then begin CheckEquals(0, Total); CheckEquals(0, Activities.Count); end else begin CheckTrue(Total > 0); CheckTrue((Activities.Count > 0) and (Activities.Count <= Limit)); end; finally FreeAndNil(Activities); end; end; procedure TTestActivitiesSamples.CheckActivitiesWithRouteId( ActivityType: TActivityType; RouteId: String); var Activities: TActivityList; ErrorString: String; Total: integer; Limit, Offset: integer; begin Limit := 2; Offset := 0; Activities := FRoute4MeManager.ActivityFeed.GetActivities( RouteId, ActivityType, Limit, Offset, Total, ErrorString); try CheckEquals(EmptyStr, ErrorString); CheckTrue(Total > 0); CheckTrue((Activities.Count > 0) and (Activities.Count <= Limit)); finally FreeAndNil(Activities); end; end; procedure TTestActivitiesSamples.GetDestinationDeletedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atDeleteDestination; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDestinationInsertedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atInsertDestination; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDestinationMarkedAsDepartedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atMarkDestinationDeparted; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDestinationMarkedAsVisitedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atMarkDestinationVisited; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDestinationMovedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atMoveDestination; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDestinationOutOfSequenceActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atDestinationOutSequence; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType, True); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDestinationUpdatedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atUpdateDestinations; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDriverArrivedEarlyActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atDriverArrivedEarly; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType, True); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDriverArrivedLateActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atDriverArrivedLate; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetDriverArrivedOnTimeActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atDriverArrivedOnTime; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType, False); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetGeofenceEnteredActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atGeofenceEntered; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType, True); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetGeofenceLeftActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atGeofenceLeft; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType, True); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetAllActivities; var ErrorString: String; Activities: TActivityList; ActivityIds: TStringArray; i: integer; Limit, Offset: integer; Total: integer; Expected: String; begin Limit := 5; Offset := 0; Activities := FRoute4MeManager.ActivityFeed.GetAllActivities( Limit, Offset, Total, ErrorString); try CheckNotNull(Activities, '1. Activities=null'); CheckEquals(EmptyStr, ErrorString, '1. ErrorString <> ""'); CheckEquals(5, Activities.Count, '1. Activities.Count'); CheckTrue(Total > 0, '1. Total'); SetLength(ActivityIds, Activities.Count); Expected := EmptyStr; for i := 0 to Activities.Count - 1 do begin ActivityIds[i] := Activities[i].Id; Expected := Expected + Activities[i].Id + '; '; end; finally FreeAndNil(Activities); end; Limit := 2; Offset := 0; Activities := FRoute4MeManager.ActivityFeed.GetAllActivities( Limit, Offset, Total, ErrorString); try CheckNotNull(Activities, '2. Activities=null'); CheckEquals(EmptyStr, ErrorString, '2. ErrorString <> ""'); CheckEquals(2, Activities.Count, '2. Activities.Count'); CheckTrue(Total > 0, '2. Total'); CheckTrue((ActivityIds[0] = Activities[0].Id) or (ActivityIds[1] = Activities[0].Id), '2. ActivityId0. Actual: ' + Activities[0].Id + '; Expected: ' + Expected); CheckTrue((ActivityIds[1] = Activities[1].Id) or (ActivityIds[0] = Activities[1].Id), '2. ActivityId1. Actual: ' + Activities[1].Id + '; Expected: ' + Expected); finally FreeAndNil(Activities); end; Limit := 2; Offset := 2; Activities := FRoute4MeManager.ActivityFeed.GetAllActivities( Limit, Offset, Total, ErrorString); try CheckNotNull(Activities, '3. Activities=null'); CheckEquals(EmptyStr, ErrorString, '3. ErrorString <> ""'); CheckEquals(2, Activities.Count, '3. Activities.Count'); CheckTrue(Total > 0, '3. Total'); CheckTrue((ActivityIds[2] = Activities[0].Id) or (ActivityIds[3] = Activities[0].Id), '3. ActivityId0. Actual: ' + Activities[0].Id + '; Expected: ' + Expected); CheckTrue((ActivityIds[3] = Activities[1].Id) or (ActivityIds[2] = Activities[1].Id), '3. ActivityId1. Actual: ' + Activities[1].Id + '; Expected: ' + Expected); finally FreeAndNil(Activities); end; Limit := 2; Offset := Total; Activities := FRoute4MeManager.ActivityFeed.GetAllActivities( Limit, Offset, Total, ErrorString); try CheckNotNull(Activities, '4. Activities=null'); CheckEquals(EmptyStr, ErrorString, '4. ErrorString <> ""'); CheckEquals(0, Activities.Count, '4. Activities.Count'); CheckTrue(Total > 0, '4. Total'); finally FreeAndNil(Activities); end; end; function TTestActivitiesSamples.GetRouteId: String; var Routes: TDataObjectRouteList; ErrorString: String; begin // по этому Id 13 activities есть в базе Result := 'B15C0ED469425DBD5FC3B04DAFF2A54D'; Result := '4A840163D74804552EEAFC75EC1E50BD'; //4 { Routes := FRoute4MeManager.Route.GetList(20, 2, ErrorString); try CheckTrue(Routes.Count > 0); Result := Routes[0].RouteId; finally FreeAndNil(Routes); end; } end; procedure TTestActivitiesSamples.GetTeamActivities; var ErrorString: String; Activities: TActivityList; ActivityIds: TStringArray; i: integer; Limit, Offset: integer; Total: integer; RouteId: String; begin RouteId := GetRouteId(); Limit := 5; Offset := 0; Activities := FRoute4MeManager.ActivityFeed.GetTeamActivities( RouteId, Limit, Offset, Total, ErrorString); try CheckNotNull(Activities); CheckEquals(EmptyStr, ErrorString); CheckEquals(5, Activities.Count); CheckTrue(Total > 0); SetLength(ActivityIds, Activities.Count); for i := 0 to Activities.Count - 1 do ActivityIds[i] := Activities[i].Id; finally FreeAndNil(Activities); end; Limit := 2; Offset := 0; Activities := FRoute4MeManager.ActivityFeed.GetTeamActivities( RouteId, Limit, Offset, Total, ErrorString); try CheckNotNull(Activities); CheckEquals(EmptyStr, ErrorString); CheckEquals(2, Activities.Count); CheckTrue(Total > 0); CheckTrue(ActivityIds[0] = Activities[0].Id); CheckTrue(ActivityIds[1] = Activities[1].Id); finally FreeAndNil(Activities); end; Limit := 2; Offset := 2; Activities := FRoute4MeManager.ActivityFeed.GetTeamActivities( RouteId, Limit, Offset, Total, ErrorString); try CheckNotNull(Activities); CheckEquals(EmptyStr, ErrorString); CheckEquals(2, Activities.Count); CheckTrue(Total > 0); CheckTrue(ActivityIds[2] = Activities[0].Id); CheckTrue(ActivityIds[3] = Activities[1].Id); finally FreeAndNil(Activities); end; Limit := 2; Offset := Total; Activities := FRoute4MeManager.ActivityFeed.GetTeamActivities( RouteId, Limit, Offset, Total, ErrorString); try CheckNotNull(Activities); CheckEquals(EmptyStr, ErrorString); CheckEquals(0, Activities.Count); CheckTrue(Total > 0); finally FreeAndNil(Activities); end; RouteId := 'qwe'; Limit := 5; Offset := 0; Activities := FRoute4MeManager.ActivityFeed.GetTeamActivities( RouteId, Limit, Offset, Total, ErrorString); try CheckNotNull(Activities); CheckEquals(EmptyStr, ErrorString); CheckEquals(0, Activities.Count); CheckEquals(0, Total); finally FreeAndNil(Activities); end; end; procedure TTestActivitiesSamples.LogSpecificMessage; var RouteId: String; Message: String; ErrorString: String; begin // An empty message is an error RouteId := 'qwe'; Message := EmptyStr; CheckFalse( FRoute4MeManager.ActivityFeed.LogSpecificMessage(RouteId, Message, ErrorString)); CheckNotEquals(EmptyStr, ErrorString); // An empty message is an error RouteId := GetRouteId(); CheckFalse( FRoute4MeManager.ActivityFeed.LogSpecificMessage(RouteId, Message, ErrorString)); CheckNotEquals(EmptyStr, ErrorString); Message := 'T 5est'; // Non-existent RouteId is error RouteId := 'qwe2321sadas'; // todo 1: при несуществующем RouteId все равно сервер возвращает True. Спросил у Олега CheckTrue( FRoute4MeManager.ActivityFeed.LogSpecificMessage(RouteId, Message, ErrorString)); CheckEquals(EmptyStr, ErrorString); RouteId := GetRouteId(); CheckTrue( FRoute4MeManager.ActivityFeed.LogSpecificMessage(RouteId, Message, ErrorString)); CheckEquals(EmptyStr, ErrorString); end; procedure TTestActivitiesSamples.GetMemberCreatedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atMemberCreated; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetMemberDeletedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atMemberDeleted; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetMemberModifiedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atMemberModified; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType, True); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetNoteInsertedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atNoteInsert; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetRouteDeletedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atRouteDelete; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetRouteOptimizedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atRouteOptimized; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; procedure TTestActivitiesSamples.GetRouteOwnerChangedActivities; var RouteId: String; ActivityType: TActivityType; begin ActivityType := TActivityType.atRouteOwnerChanged; CheckActivitiesWithInvalidRouteId(ActivityType); RouteId := CheckActivitiesWithoutRouteId(ActivityType, True); if (RouteId <> EmptyStr) then CheckActivitiesWithRouteId(ActivityType, RouteId); end; initialization RegisterTest('Examples\Online\Activities\', TTestActivitiesSamples.Suite); end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit OraRole; interface uses Classes, SysUtils, Ora, OraStorage, DB,DBQuery, Forms, Dialogs, VirtualTable; type Role = record GRANTEE, GRANTED_ROLE, PASSWORD_REQUIRED : string; GRANTED, ADMIN_OPTION, DEFAULT_ROLE: boolean; end; TRole = ^Role; TRoleList = class(TObject) private FRoleList: TList; FOraSession: TOraSession; FDSRoleList: TVirtualTable; FGRANTEE: String; function GetRole(Index: Integer): TRole; procedure SetRole(Index: Integer; Role: TRole); function GetRoleCount: Integer; function GetRoles: string; public procedure RoleAdd(Role: TRole); procedure RoleDelete(Index: Integer); property RoleCount: Integer read GetRoleCount; property RoleItems[Index: Integer]: TRole read GetRole write SetRole; procedure CopyFrom(RoleList: TRoleList); function FindByRole(GrantedRole: string): integer; property GRANTEE: String read FGRANTEE write FGRANTEE; property DSRoleList: TVirtualTable read FDSRoleList; property OraSession: TOraSession read FOraSession write FOraSession; constructor Create; destructor Destroy; override; procedure SetDDL; function GetDDL: string; function GetAlterDDL(ARoleList: TRoleList): string; function Role(RoleScript: string) : boolean; end; function GetRoles: string; implementation uses util, frmSchemaBrowser; {********************** TRole ***********************************} function GetRoles: string; begin result := 'select * from dba_roles '; end; constructor TRoleList.Create; begin FRoleList := TList.Create; FDSRoleList := TVirtualTable.Create(nil); end; destructor TRoleList.Destroy; var i : Integer; FRole: TRole; begin try if FRoleList.Count > 0 then begin for i := FRoleList.Count - 1 downto 0 do begin FRole := FRoleList.Items[i]; Dispose(FRole); end; end; finally FRoleList.Free; end; FDSRoleList.Free; inherited; end; function TRoleList.GetRoles: string; begin result := 'SELECT GRANTEE, ROLE, decode(granted_role,'''', ''NO'',''YES'') granted, ' +' nvl(admin_option,''NO'') admin_option, ' +' nvl(default_role,''NO'') default_role ' +' FROM SYS.dba_role_privs drp, SYS.dba_roles ROLES ' +' WHERE drp.granted_role(+) = ROLES.ROLE ' +' AND ROLES.password_required <> ''GLOBAL'' ' +' AND drp.grantee(+) = :pName ' +' ORDER BY ROLES.ROLE'; end; procedure TRoleList.RoleAdd(Role: TRole); begin FRoleList.Add(Role); end; procedure TRoleList.RoleDelete(Index: Integer); begin TObject(FRoleList.Items[Index]).Free; FRoleList.Delete(Index); end; function TRoleList.GetRole(Index: Integer): TRole; begin Result := FRoleList.Items[Index]; end; procedure TRoleList.SetRole(Index: Integer; Role: TRole); begin if Assigned(Role) then FRoleList.Items[Index] := Role; end; function TRoleList.GetRoleCount: Integer; begin Result := FRoleList.Count; end; procedure TRoleList.CopyFrom(RoleList: TRoleList); var i: integer; begin FOraSession := RoleList.OraSession; FGRANTEE := RoleList.GRANTEE; for i := 0 to RoleList.RoleCount -1 do FRoleList.Add(TRole(RoleList.RoleItems[i])); end; function TRoleList.FindByRole(GrantedRole: string): integer; var i: integer; begin result := -1; for i := 0 to FRoleList.Count -1 do begin if (TRole(FRoleList[i]).GRANTED_ROLE = GrantedRole) then begin result := i; exit; end; end; end; procedure TRoleList.SetDDL; var FRole: TRole; q: TOraQuery; begin q := TOraQuery.Create(nil); q.Session := FOraSession; q.SQL.Text := GetRoles; q.ParamByName('pName').AsString := FGRANTEE; q.Open; CopyDataSet(q, FDSRoleList); while not q.Eof do begin if q.FieldByName('GRANTEE').AsString = FGRANTEE then begin new(FRole); FRole^.GRANTEE := q.FieldByName('GRANTEE').AsString; FRole^.GRANTED_ROLE := q.FieldByName('ROLE').AsString; FRole^.PASSWORD_REQUIRED := ''; FRole^.GRANTED := q.FieldByName('GRANTED').AsString = 'YES'; FRole^.ADMIN_OPTION := q.FieldByName('ADMIN_OPTION').AsString = 'YES'; FRole^.DEFAULT_ROLE := q.FieldByName('DEFAULT_ROLE').AsString = 'YES'; RoleAdd(FRole); end; q.Next; end; q.close; end; function TRoleList.GetDDL: string; var i: integer; FRole: TRole; s,s1: string; begin s := ''; s1 := ''; with self do begin for i := 0 to GetRoleCount -1 do begin FRole := RoleItems[i]; if FRole.GRANTEE <> '' then begin s := ''; if FRole.GRANTED then s := ln+ 'GRANT '+FRole.GRANTED_ROLE +' TO '+FRole.GRANTEE; if FRole.ADMIN_OPTION then s := s + ' WITH ADMIN OPTION '; if s <> '' then s := s + ';'; result := result + s; if FRole.DEFAULT_ROLE then s1 := s1 + FRole.GRANTED_ROLE+','; end; end; end; //with self if s1 <> '' then begin delete(s1,length(s1),1); result := result + ln + 'ALTER USER '+FRole.GRANTEE+' DEFAULT ROLE '+s1+';'; end; end; function TRoleList.GetAlterDDL(ARoleList: TRoleList): string; var i: integer; FRole: TRole; s,s1: string; begin s := ''; s1 := ''; with self do begin for i := 0 to GetRoleCount -1 do begin FRole := RoleItems[i]; if FRole.GRANTEE <> '' then begin if AroleList.FindByRole(FRole.GRANTED_ROLE) >= 0 then begin if not FRole.GRANTED then result := result + ln+ 'REWORK '+FRole.GRANTED_ROLE +' FROM '+FRole.GRANTEE +';'; end else begin s := ''; if FRole.GRANTED then s := ln+ 'GRANT '+FRole.GRANTED_ROLE +' TO '+FRole.GRANTEE; if FRole.ADMIN_OPTION then s := s + ' WITH ADMIN OPTION '; if s <> '' then s := s + ';'; result := result + s; end; if (FRole.GRANTED) and (FRole.DEFAULT_ROLE) then s1 := s1 + FRole.GRANTED_ROLE+','; end; end; end; //with self if (result <> '') and (s1 <> '') then begin delete(s1,length(s1),1); result := result + ln + 'ALTER USER '+FRole.GRANTEE+' DEFAULT ROLE '+s1+';'; end; end; function TRoleList.Role(RoleScript: string) : boolean; begin result := ExecSQL(RoleScript, '', FOraSession); end; end.
unit XPTheme; { Inno Setup Copyright (C) 1997-2007 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Enables themes on Windows XP/Vista, and disables DPI scaling on Vista. Used only by the Setup and SetupLdr projects. Note: XPTheme must be included as the first unit in the program's "uses" clause so that its code runs before any VCL initialization code. } interface implementation {$R XPTheme.res} uses Windows; { Avoid including Variants (via CommCtrl) in SetupLdr (SetupLdr uses XPTheme), saving 26 KB. } procedure InitCommonControls; external comctl32 name 'InitCommonControls'; initialization { Work around bug in Windows XP Gold & SP1: If the application manifest specifies COMCTL32.DLL version 6.0 (to enable visual styles), we must call InitCommonControls() to ensure that we actually link to COMCTL32.DLL, otherwise calls to MessageBox() fail. (XP SP2 appears to fix this.) Programs that don't statically link to COMCTL32, like SetupLdr, need this. (Actually, that's not completely true -- SetupLdr uses RedirFunc, which loads SHELL32.DLL, which in turn loads COMCTL32.DLL. But let's not rely on that undocumented behavior.) } InitCommonControls; end.
unit Pessoa.Impl; interface type TPessoa = class(TObject) private FNome: string; class var FInstance: TPessoa; protected constructor CreateInstance; public constructor Create; destructor Destroy; override; class function GetInstance: TPessoa; class procedure ReleaseInstance; function Nome: string; overload; function Nome(AValue: string): string; overload; end; implementation uses System.SysUtils; { TPessoa } constructor TPessoa.Create; begin inherited Create; raise Exception.CreateFmt('Access class %s through GetInstance only', [ClassName]); end; constructor TPessoa.CreateInstance; begin inherited Create; end; destructor TPessoa.Destroy; begin inherited Destroy; end; class function TPessoa.GetInstance: TPessoa; begin if not Assigned(FInstance) then FInstance := CreateInstance; Result := FInstance; end; class procedure TPessoa.ReleaseInstance; begin FInstance.Free; end; function TPessoa.Nome: string; begin Result := FNome; end; function TPessoa.Nome(AValue: string): string; begin FNome := AValue; end; end.
unit fcImgBtn; { // // Components : TfcImageBtn // // Copyright (c) 1999 by Woll2Woll Software } interface {$i fcIfDef.pas} uses Windows, Messages, Classes, Controls, Forms, Graphics, StdCtrls, CommCtrl, Buttons, Dialogs, Math, Consts, SysUtils, fcCommon, fcText, fcButton, fcBitmap, fcChangeLink, fcImager {$ifdef fcDelphi4up} ,ImgList, ActnList {$endif}; type TfcDitherStyle = (dsDither, dsBlendDither, dsFill); TfcImgDownOffsets = class(TfcOffsets) private FImageDownX: Integer; FImageDownY: Integer; protected procedure AssignTo(Dest: TPersistent); override; public constructor Create(AControl: TfcCustomBitBtn); published property ImageDownX: Integer read FImageDownX write FImageDownX default 2; property ImageDownY: Integer read FImageDownY write FImageDownY default 2; end; TfcCustomImageBtn = class (TfcCustomBitBtn) private // Property Storage Variables FDitherColor: TColor; FDitherStyle: TfcDitherStyle; FImage: TfcBitmap; FImageDown: TfcBitmap; FImageChangeLink: TfcChangeLink; FExtImage: TComponent; FExtImageDown: TComponent; FTransparentColor: TColor; // Property Access Methods function GetOffsets: TfcImgDownOffsets; function GetParentClipping: Boolean; function GetRespectPalette: Boolean; procedure SetDitherColor(Value: TColor); procedure SetDitherStyle(Value: TfcDitherStyle); procedure SetExtImage(Value: TComponent); procedure SetExtImageDown(Value: TComponent); procedure SetImage(Value: TfcBitmap); procedure SetImageDown(Value: TfcBitmap); procedure SetOffsets(Value: TfcImgDownOffsets); procedure SetParentClipping(Value: Boolean); procedure SetRespectPalette(Value: Boolean); procedure SetTransparentColor(Value: TColor); protected procedure Draw3DLines(SrcBitmap, DstBitmap: TfcBitmap; TransColor: TColor; Down: Boolean); procedure SetExtImages(Value: TComponent; var Prop: TComponent); // Virtual Methods procedure WndProc(var Message: TMessage); override; function CreateRegion(DoImplementation: Boolean; Down: Boolean): HRgn; override; function CreateOffsets: TfcOffsets; override; function GetTransparentColor(Down: Boolean): TColor; function ObtainImage(DownImage: Boolean): TfcBitmap; virtual; function StoreRegionData: Boolean; override; procedure AssignTo(Dest: TPersistent); override; procedure CreateWnd; override; procedure DestroyWnd; override; procedure GetSizedImage(SourceBitmap: TfcBitmap; DestBitmap: TfcBitmap; ShadeStyle: TfcShadeStyle; ForRegion: Boolean); virtual; procedure ImageChanged(Sender: TObject); virtual; procedure ExtImageDestroying(Sender: TObject); procedure Notification(AComponent: TComponent; Operation: TOperation); override; function UseRegions: boolean; override; public Patch: Variant; constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ColorAtPoint(APoint: TPoint): TColor; virtual; function IsMultipleRegions: Boolean; override; procedure GetDrawBitmap(DrawBitmap: TfcBitmap; ForRegion: Boolean; ShadeStyle: TfcShadeStyle; Down: Boolean); override; procedure SplitImage; virtual; procedure SizeToDefault; override; // Public Properties property DitherColor: TColor read FDitherColor write SetDitherColor; property DitherStyle: TfcDitherStyle read FDitherStyle write SetDitherStyle; property ExtImage: TComponent read FExtImage write SetExtImage; property ExtImageDown: TComponent read FExtImageDown write SetExtImageDown; property Image: TfcBitmap read FImage write SetImage; property ImageDown: TfcBitmap read FImageDown write SetImageDown; property Offsets: TfcImgDownOffsets read GetOffsets write SetOffsets; property ParentClipping: Boolean read GetParentClipping write SetParentClipping; property RespectPalette: Boolean read GetRespectPalette write SetRespectPalette default False; property TransparentColor: TColor read FTransparentColor write SetTransparentColor; end; TfcImageBtn = class(TfcCustomImageBtn) published {$ifdef fcDelphi4Up} property Action; property Anchors; property Constraints; {$endif} property AllowAllUp; property Cancel; property Caption; property Color; property Default; property DitherColor; property DitherStyle; property DragCursor; //3/31/99 - PYW - Exposed DragCursor and DragKind properties. {$ifdef fcDelphi4Up} property DragKind; {$endif} property DragMode; property Down; property Font; property Enabled; property ExtImage; property ExtImageDown; property Glyph; property GroupIndex; property Image; property ImageDown; property Kind; property Layout; property Margin; property ModalResult; property NumGlyphs; property Offsets; property Options; property ParentClipping; property ParentFont; property ParentShowHint; property PopupMenu; property RespectPalette; property ShadeColors; property ShadeStyle; property ShowHint; {$ifdef fcDelphi4Up} property SmoothFont; {$endif} property Style; property Spacing; property TabOrder; property TabStop; property TextOptions; property TransparentColor; property Visible; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseEnter; property OnMouseLeave; property OnMouseMove; property OnMouseUp; property OnSelChange; property OnStartDrag; end; implementation {$r-} constructor TfcImgDownOffsets.Create(AControl: TfcCustomBitBtn); begin inherited; FImageDownX := 2; FImageDownY := 2; end; procedure TfcImgDownOffsets.AssignTo(Dest: TPersistent); begin if Dest is TfcImgDownOffsets then with Dest as TfcImgDownOffsets do begin ImageDownX := self.ImageDownX; ImageDownY := self.ImageDownY; end; inherited; end; constructor TfcCustomImageBtn.Create(AOwner: TComponent); begin inherited Create(AOwner); FDitherColor := clWhite; FImage := TfcBitmap.Create; FImage.OnChange := ImageChanged; FImageDown := TfcBitmap.Create; FImageDown.OnChange := ImageChanged; FTransparentColor := clNone; FImageChangeLink := TfcChangeLink.Create; FImageChangeLink.OnChange := ImageChanged; Color := clNone; end; destructor TfcCustomImageBtn.Destroy; begin FImage.Free; FImageDown.Free; FImageChangeLink.Free; inherited Destroy; end; function TfcCustomImageBtn.IsMultipleRegions: Boolean; begin result := (not ObtainImage(False).Empty and not ObtainImage(True).Empty) or (ShadeStyle = fbsRaised); if result and (FTransparentColor=clNullColor) then result:= false; end; function TfcCustomImageBtn.StoreRegionData: Boolean; begin result := True; end; // Added Down parameter to fix bug. - 4/6/99 function TfcCustomImageBtn.GetTransparentColor(Down: Boolean): TColor; begin if FTransparentColor <> clNullColor then begin if FTransparentColor = clNone then begin if Down and not ObtainImage(True).Empty then result := fcGetStdColor(ObtainImage(True).Pixels[0, 0]) else result:= fcGetStdColor(ObtainImage(False).Pixels[0, 0]); result := ColorToRGB(result) and $00FFFFFF; end else result := FTransparentColor; end else result := clNullColor; end; function TfcCustomImageBtn.ObtainImage(DownImage: Boolean): TfcBitmap; begin if (not DownImage and (FExtImage <> nil)) and not (csDestroying in FExtImage.ComponentState) then begin result := Image; if FExtImage is TfcCustomImager then with FExtImage as TfcCustomImager do begin if WorkBitmap.Empty and not PictureEmpty then Resized; result := WorkBitmap; end else if FExtImage is TfcCustomImageBtn then with FExtImage as TfcCustomImageBtn do result := Image; end else if DownImage and (FExtImageDown <> nil) and not (csDestroying in FExtImageDown.ComponentState) then begin result := ImageDown; if FExtImageDown is TfcCustomImager then with FExtImageDown as TfcCustomImager do begin if WorkBitmap.Empty and not PictureEmpty then Resized; result := WorkBitmap; end else if FExtImageDown is TfcCustomImageBtn then with FExtImageDown as TfcCustomImageBtn do result := ImageDown; end else if DownImage then result := ImageDown else result := Image; end; function TfcCustomImageBtn.CreateOffsets: TfcOffsets; begin result := TfcImgDownOffsets.Create(self); end; function TfcCustomImageBtn.CreateRegion(DoImplementation: Boolean; Down: Boolean): HRgn; var SizedImage: TfcBitmap; Rgn: HRGN; begin if TransparentColor = clNullColor then begin result := 0; Exit; end; result := inherited CreateRegion(False, Down); if not DoImplementation or (result <> 0) or ObtainImage(False).Empty then Exit; SizedImage := TfcBitmap.Create; SizedImage.RespectPalette := RespectPalette; GetSizedImage(ObtainImage(Down and not ObtainImage(True).Empty), SizedImage, ShadeStyle, True); result := fcRegionFromBitmap(SizedImage, GetTransparentColor(Down)); if ShadeStyle = fbsRaised then begin Rgn := CreateRectRgn(0, 0, 10, 10); if CombineRgn(Rgn, result, 0, RGN_COPY) = ERROR then Exit; OffsetRgn(Rgn, 2, 2); if Down then CombineRgn(result, Rgn, 0, RGN_COPY) else CombineRgn(result, Rgn, result, RGN_OR); DeleteObject(Rgn); end; SizedImage.Free; SaveRegion(result, Down); end; procedure TfcCustomImageBtn.SetDitherColor(Value: TColor); begin if FDitherColor <> Value then begin FDitherColor := Value; Invalidate; end; end; procedure TfcCustomImageBtn.SetDitherStyle(Value: TfcDitherStyle); begin if FDitherStyle <> Value then begin FDitherStyle := Value; Invalidate; end; end; procedure TfcCustomImageBtn.SetImage(Value: TfcBitmap); begin if Value <> nil then ExtImage := nil; FImage.Assign(Value); if not Down or ObtainImage(True).Empty then RecreateWnd; end; procedure TfcCustomImageBtn.SetImageDown(Value: TfcBitmap); begin if Value <> nil then ExtImageDown := nil; FImageDown.Assign(Value); if Down then RecreateWnd; end; procedure TfcCustomImageBtn.SetExtImages(Value: TComponent; var Prop: TComponent); begin if Prop <> nil then begin if Prop is TfcCustomImager then (Prop as TfcCustomImager).UnRegisterChanges(FImageChangeLink) else if Prop is TfcCustomImageBtn then (Prop as TfcCustomImageBtn).UnRegisterChanges(FImageChangeLink); end; Prop := Value; if Value <> nil then begin if Value is TfcCustomImager then (Value as TfcCustomImager).RegisterChanges(FImageChangeLink) else if Value is TfcCustomImageBtn then (Value as TfcCustomImageBtn).Image.RegisterChanges(FImageChangeLink); Value.FreeNotification(self); end; RecreateWnd; end; procedure TfcCustomImageBtn.SetExtImage(Value: TComponent); begin if Value <> nil then Image.Clear; SetExtImages(Value, FExtImage); end; procedure TfcCustomImageBtn.SetExtImageDown(Value: TComponent); begin if Value <> nil then ImageDown.Clear; SetExtImages(Value, FExtImageDown); end; procedure TfcCustomImageBtn.Draw3DLines(SrcBitmap, DstBitmap: TfcBitmap; TransColor: TColor; Down: Boolean); var WorkingBm{, DstBm}: TfcBitmap; DstPixels, SrcPixels: PfcPLines; StartPt, EndPt, OldEndPt: TPoint; Col, Row: Integer; ABtnHighlight, ABtn3DLight, ABtnShadow, ABtnBlack: TfcColor; BitmapSize: TSize; function CheckPoint(p: TPoint): TPoint; begin result := p; if result.x < 0 then result.x := 0; if result.y < 0 then result.y := 0; if result.x > BitmapSize.cx - 1 then result.x := BitmapSize.cx - 1; if result.y > BitmapSize.cy - 1 then result.y := BitmapSize.cy - 1; end; function PointValid(x, y: Integer): Boolean; begin result := not ((x < 0) or (y < 0) or (x >= BitmapSize.cx) or (y >= BitmapSize.cy)); end; procedure GetFirstPixelColor(CurrentCol, CurrentRow: Integer; var ResultPt: TPoint; AColor: TColor; NotColor: Boolean; SearchForward: Boolean); var i, MaxIncr: Integer; CurColor: TColor; begin if SearchForward then MaxIncr := fcMin(BitmapSize.cx - CurrentCol, BitmapSize.cy - CurrentRow) else MaxIncr := fcMin(CurrentCol, CurrentRow); for i := 0 to MaxIncr - 1 do begin with SrcPixels[CurrentRow, CurrentCol] do CurColor := RGB(r, g, b); if ((CurColor = AColor) and not NotColor) or ((CurColor <> AColor) and NotColor) then begin ResultPt.x := CurrentCol; ResultPt.y := CurrentRow; if not NotColor then ResultPt := CheckPoint(Point(ResultPt.x - 1, ResultPt.y - 1)); Break; end; if SearchForward then inc(CurrentCol) else dec(CurrentCol); if SearchForward then inc(CurrentRow) else dec(CurrentRow); end; end; procedure DrawHighlights(ABtnBlack, ABtnShadow, ABtn3dLight, ABtnHighlight: TfcColor); var AEndPt, AStartPt: TPoint; begin AEndPt := EndPt; AStartPt := StartPt; if (boFocusable in Options) and (Focused) then AStartPt := Point(AStartPt.x + 1, AStartPt.y + 1); with Point(AEndPt.x - 1, AEndPt.y - 1) do if PointValid(x, y) then DstPixels[y, x] := ABtnShadow; with Point(AStartPt.x + 1, AStartPt.y + 1) do if PointValid(x, y) then DstPixels[y, x] := ABtn3dLight; with Point(AEndPt.x, AEndPt.y) do if PointValid(x, y) then DstPixels[y, x] := ABtnBlack; with Point(AStartPt.x, AStartPt.y) do if PointValid(x, y) then DstPixels[y, x] := ABtnHighlight; if (boFocusable in Options) and (Focused) and Down then with Point(AStartPt.x - 1, AStartPt.y - 1) do if PointValid(x, y) then DstPixels[y, x] := fcGetColor(clBlack); end; begin if SrcBitmap.Empty or (SrcBitmap.Width <> DstBitmap.Width) or (SrcBitmap.Height <> DstBitmap.Height) then Exit; // Must convert to BGR values because apparantly that's what PixBuf is... ABtnHighlight := fcGetColor(ColorToRGB(ShadeColors.BtnHighlight)); ABtn3dLight := fcGetColor(ColorToRGB(ShadeColors.Btn3dLight)); ABtnShadow := fcGetColor(ColorToRGB(ShadeColors.BtnShadow)); ABtnBlack := fcGetColor(ColorToRGB(ShadeColors.BtnBlack)); BitmapSize.cx := SrcBitmap.Width; BitmapSize.cy := SrcBitmap.Height; WorkingBm := TfcBitmap.Create; WorkingBm.Assign(SrcBitmap); // DstBm := nil; { if DstBitmap = SrcBitmap then WorkingPixels := WorkingBm.Pixels else begin DstBm := TfcBitmap.Create; DstBm.Assign(DstBitmap); WorkingPixels := DstBm.Pixels; end;} SrcPixels := WorkingBm.Pixels; DstPixels := DstBitmap.Pixels; if TransColor = -1 then TransColor := fcGetStdColor(WorkingBm.Pixels[0, 0]); try // Work Diagonally from top right of image to Top left of image Col := BitmapSize.cx - 1; Row := 0; while Row < WorkingBm.Height do begin // Find the first non transparent pixel EndPt := Point(Col - 1, Row - 1); repeat StartPt := Point(-1, -1); GetFirstPixelColor(EndPt.x + 1, EndPt.y + 1, StartPt, TransColor, True, True); if (StartPt.x <> -1) and (StartPt.y <> -1) then begin OldEndPt := EndPt; EndPt := CheckPoint(Point(Col + fcMin(BitmapSize.cx - 1 - Col, BitmapSize.cy - 1 - Row), Row + fcMin(BitmapSize.cx - 1 - Col, BitmapSize.cy - 1 - Row))); GetFirstPixelColor(StartPt.x + 1, StartPt.y + 1, EndPt, TransColor, False, True); if Focused or Default then begin StartPt := Point(StartPt.x + 1, StartPt.y + 1); EndPt := Point(EndPt.x - 1, EndPt.y - 1); end; if not Down then DrawHighlights(ABtnBlack, ABtnShadow, ABtn3dLight, ABtnHighlight) else DrawHighlights(ABtnHighlight, ABtn3dLight, ABtnShadow, ABtnBlack); if Focused or Default then begin StartPt := Point(StartPt.x - 1, StartPt.y - 1); EndPt := Point(EndPt.x + 1, EndPt.y + 1); DstPixels[StartPt.y, StartPt.x] := ABtnBlack; DstPixels[EndPt.y, EndPt.x] := ABtnBlack; end; end; until (StartPt.x = -1) and (StartPt.y = -1); if Col > 0 then dec(Col) else inc(Row); end; { if SrcBitmap = DstBitmap then DstBitmap.Canvas.Draw(0, 0, WorkingBm) else begin DstBitmap.Canvas.Draw(0, 0, DstBm); DstBm.Free; end;} finally WorkingBm.Free; end; end; function TfcCustomImageBtn.ColorAtPoint(APoint: TPoint): TColor; var Bitmap: TfcBitmap; begin Bitmap := TfcBitmap.Create; try GetDrawBitmap(Bitmap, False, ShadeStyle, Down); result := Bitmap.Canvas.Pixels[APoint.x, APoint.y]; finally Bitmap.Free; end; end; procedure TfcCustomImageBtn.GetDrawBitmap(DrawBitmap: TfcBitmap; ForRegion: Boolean; ShadeStyle: TfcShadeStyle; Down: Boolean); var TempImage: TfcBitmap; Offset: TPoint; begin DrawBitmap.SetSize(Width, Height); if RespectPalette then begin CopyMemory(@DrawBitmap.Colors, @ObtainImage(False).Colors, SizeOf(ObtainImage(False).Colors)); DrawBitmap.RespectPalette := True; end; //3/16/99 - PYW - Raises canvas draw error when anchors cause width or height to be <=0 with DrawBitmap do if (Width <=0) or (Height<=0) then exit; if ObtainImage(False).Empty then with DrawBitmap do begin Canvas.Brush.Color := clBtnFace; Canvas.Pen.Style := psDashDot; Canvas.Pen.Color := clBlack; Canvas.Rectangle(0, 0, Width, Height); Exit; end; Offset := Point(0, 0); // Offset used if drawing shadows, etc. TempImage := TfcBitmap.Create; // Temp image stores a copy of either Image or ImageDown TempImage.RespectPalette := RespectPalette; if not Down or ObtainImage(True).Empty then GetSizedImage(ObtainImage(False), TempImage, ShadeStyle, ForRegion) // If the button is not down or there is no down image else GetSizedImage(ObtainImage(True), TempImage, ShadeStyle, ForRegion); // defined then use the up image, otherwise use the down image. try if Down and ObtainImage(True).Empty then Offset := Point(Offsets.ImageDownX, Offsets.ImageDownY); // Offset for Upper-left shadow if (ShadeStyle = fbsHighlight) or ((ShadeStyle = fbsFlat) and MouseInControl(-1, -1, False)) then begin DrawBitmap.Canvas.Draw(Offset.x, Offset.y, TempImage); Draw3dLines(TempImage, DrawBitmap, GetTransparentColor(Down), Down); Offset := Point(-1, -1); end else begin DrawBitmap.Canvas.Brush.Color := ShadeColors.Shadow; DrawBitmap.Canvas.FillRect(Rect(0, 0, Width, Height)); // Fill in with shadow color end; if (Offset.x <> -1) and (Offset.y <> -1) then begin if TransparentColor <> clNullColor then begin TempImage.Transparent := True; TempImage.TransparentColor := GetTransparentColor(Down); end; DrawBitmap.Canvas.Draw(Offset.x, Offset.y, TempImage) end; finally TempImage.Free; // Clean up temp bitmaps end; end; procedure TfcCustomImageBtn.SplitImage; var Bitmap, Bitmap2: TfcBitmap; ARgn: HRGN; begin if not ObtainImage(False).Empty then begin Bitmap := TfcBitmap.Create; Bitmap2 := TfcBitmap.Create; GetDrawBitmap(Bitmap, False, fbsHighlight, False); GetDrawBitmap(Bitmap2, False, fbsHighlight, True); ARgn := CreateRegion(True, Down); fcClipBitmapToRegion(Bitmap2, ARgn); DeleteObject(ARgn); ObtainImage(False).Assign(Bitmap); ImageDown.Assign(Bitmap2); Bitmap.Free; Bitmap2.Free; RecreateWnd; end; end; procedure TfcCustomImageBtn.SizeToDefault; var Rect: TRect; begin if not ObtainImage(False).Empty then begin Width := ObtainImage(False).Width; Height := ObtainImage(False).Height; Rect := BoundsRect; if Parent <> nil then InvalidateRect(Parent.Handle, @Rect, True); end; end; procedure TfcCustomImageBtn.AssignTo(Dest: TPersistent); begin if Dest is TfcCustomImageBtn then with Dest as TfcCustomImageBtn do begin DitherColor := self.DitherColor; DitherStyle := self.DitherStyle; { Image := self.Image; ImageDown := self.ImageDown; DONT CHANGE THIS!!!} ExtImage := self; ExtImageDown := self; Offsets.Assign(self.Offsets); RespectPalette := self.RespectPalette; TransparentColor := self.TransparentColor; end; inherited; end; procedure TfcCustomImageBtn.CreateWnd; begin if Image.Sleeping then Image.Wake; inherited; ApplyRegion; end; procedure TfcCustomImageBtn.DestroyWnd; begin inherited; Image.Sleep; end; procedure TfcCustomImageBtn.GetSizedImage(SourceBitmap: TfcBitmap; DestBitmap: TfcBitmap; ShadeStyle: TfcShadeStyle; ForRegion: Boolean); var s: TSize; Rgn: HRGN; BlendColor: TColor; begin Rgn := 0; s := fcSize(Width, Height); //3/16/99 - PYW - Raises canvas draw error when anchors cause width or height to be <=0 if (Width <=0) or (Height<=0) then exit; if ShadeStyle = fbsRaised then s := fcSize(Width - 2, Height - 2); DestBitmap.SetSize(s.cx, s.cy); if not ForRegion and ((Color <> clNone) or ((GroupIndex > 0) and Down and (DitherColor <> clNone) and ObtainImage(True).Empty)) then Rgn := CreateRegion(True, Down); DestBitmap.Canvas.StretchDraw(Rect(0, 0, s.cx, s.cy), SourceBitmap); if not ForRegion and (Color <> clNone) then begin SelectClipRgn(DestBitmap.Canvas.Handle, Rgn); DestBitmap.TransparentColor := GetTransparentColor(Down); with fcBitmap.fcGetColor(Color) do DestBitmap.Colorize(r, g, b); end; if (GroupIndex > 0) and Down and (DitherColor <> clNone) and not ForRegion and ObtainImage(True).Empty then begin if ShadeStyle = fbsRaised then OffsetRgn(Rgn, -2, -2); SelectClipRgn(DestBitmap.Canvas.Handle, Rgn); if DitherStyle in [dsDither, dsBlendDither] then begin if DitherStyle = dsBlendDither then BlendColor := clNone else BlendColor := clSilver; fcDither(DestBitmap.Canvas, Rect(0, 0, Width, Height), BlendColor, DitherColor); end else begin DestBitmap.Canvas.Brush.Color := DitherColor; DestBitmap.Canvas.FillRect(Rect(0, 0, Width, Height)); end; end; if Rgn <> 0 then begin SelectClipRgn(DestBitmap.Canvas.Handle, 0); DeleteObject(Rgn); end; end; procedure TfcCustomImageBtn.ImageChanged(Sender: TObject); var ARgnData: PfcRegionData; r: TRect; begin ARgnData := nil; if Sender = ObtainImage(False) then ARgnData := @FRegionData else if Sender = ObtainImage(True) then ARgnData := @FDownRegionData; if ARgnData <> nil then ClearRegion(ARgnData); (Sender as TfcBitmap).IgnoreChange := True; ApplyRegion; (Sender as TfcBitmap).IgnoreChange := False; r := BoundsRect; if Parent <> nil then InvalidateRect(Parent.Handle, @r, True); Invalidate; end; procedure TfcCustomImageBtn.ExtImageDestroying(Sender: TObject); begin if Sender = FExtImage then FExtImage := nil; end; procedure TfcCustomImageBtn.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) then begin if (AComponent = FExtImage) then FExtImage := nil else if (AComponent = FExtImageDown) then FExtImageDown := nil; end; end; function TfcCustomImageBtn.GetOffsets: TfcImgDownOffsets; begin result := TfcImgDownOffsets(inherited Offsets); end; function TfcCustomImageBtn.GetParentClipping: Boolean; begin result := False; if Parent <> nil then result := GetWindowLong(Parent.Handle, GWL_STYLE) and WS_CLIPCHILDREN = WS_CLIPCHILDREN; end; function TfcCustomImageBtn.GetRespectPalette: Boolean; begin result := ObtainImage(False).RespectPalette; end; procedure TfcCustomImageBtn.SetOffsets(Value: TfcImgDownOffsets); begin inherited Offsets := Value; end; procedure TfcCustomImageBtn.SetParentClipping(Value: Boolean); begin if Parent <> nil then begin if Value then SetWindowLong(Parent.Handle, GWL_STYLE, GetWindowLong(Parent.Handle, GWL_STYLE) or WS_CLIPCHILDREN) else SetWindowLong(Parent.Handle, GWL_STYLE, GetWindowLong(Parent.Handle, GWL_STYLE) and not WS_CLIPCHILDREN); end; end; procedure TfcCustomImageBtn.SetRespectPalette(Value: Boolean); begin ObtainImage(False).RespectPalette := Value; ObtainImage(True).RespectPalette := Value; Invalidate; end; procedure TfcCustomImageBtn.SetTransparentColor(Value: TColor); var Rect: TRect; begin if FTransparentColor <> Value then begin FTransparentColor := Value; RecreateWnd; Rect := BoundsRect; if Parent <> nil then InvalidateRect(Parent.Handle, @Rect, True); end; end; function TfcCustomImageBtn.UseRegions: boolean; begin result:= (FTransparentColor<>clNullColor) end; procedure TfcCustomImageBtn.WndProc(var Message: TMessage); begin inherited; end; {$r+} end.
{====================================================} { } { EldoS Visual Components } { } { Copyright (c) 1998-2003, EldoS Corporation } { } {====================================================} {$include elpack2.inc} {$ifdef ELPACK_SINGLECOMP} {$I ElPack.inc} {$else} {$ifdef LINUX} {$I ../ElPack.inc} {$else} {$I ..\ElPack.inc} {$endif} {$endif} unit ElCalendarDefs; interface uses ElTools, Classes, SysUtils, {$ifdef VCL_6_USED} Types, {$endif} Graphics, Controls ; type TElCalendarCellType = (cctDayName, cctWeekNum, cctToday, cctOtherMonth, cctWeekEnd, cctInPeriod, cctHoliday, cctEmpty, cctSelected); TElCalendarCellTypes = set of TElCalendarCellType; TBeforeCellDrawEvent = procedure(Sender : TObject; Canvas : TCanvas; RowNum, ColNum : integer; Date : TDateTime; CellType : TElCalendarCellTypes) of object; TDayOfWeek = 0..6; TElWeekEndDay = (Sun, Mon, Tue, Wed, Thu, Fri, Sat); TElWeekEndDays = set of TElWeekEndDay; TElHolidayEvent = procedure(Sender : TObject; ADay, AMonth, AYear : word; var IsHoliday : boolean) of object; TElHoliday = class(TCollectionItem) private FDescription : string; FFixedDate : Boolean; FDay : Word; FDayOfWeek : Word; FMonth : Word; FIsRest : Boolean; procedure SetFixedDate(newValue : Boolean); procedure SetDay(newValue : Word); procedure SetDayOfWeek(newValue : Word); procedure SetMonth(newValue : Word); procedure SetIsRest(newValue : Boolean); public constructor Create(Collection : TCollection); override; destructor Destroy; override; procedure Assign(Source : TPersistent); override; procedure SaveToStream(Stream : TStream); procedure LoadFromStream(Stream : TStream); published property FixedDate : Boolean read FFixedDate write SetFixedDate default True; property Day : Word read FDay write SetDay; property DayOfWeek : Word read FDayOfWeek write SetDayOfWeek; property Month : Word read FMonth write SetMonth; property IsRest : Boolean read FIsRest write SetIsRest; property Description : string read FDescription write FDescription; end; TElHolidays = class(TCollection) private FOwner : TPersistent; function GetItems(Index : integer) : TElHoliday; procedure SetItems(Index : integer; newValue : TElHoliday); protected function GetOwner : TPersistent; override; procedure Update(Item : TCollectionItem); override; public constructor Create(AOwner : TComponent); function Add : TElHoliday; procedure SaveToStream(Stream : TStream); procedure LoadFromStream(Stream : TStream); property Items[Index : integer] : TElHoliday read GetItems write SetItems; default; end; implementation procedure TElHoliday.Assign(Source : TPersistent); begin if Source is TElHoliday then begin with Source as TElHoliday do begin Self.FFixedDate := FFixedDate; Self.FDay := FDay; Self.FDayOfWeek := FDayOfWeek; Self.FMonth := FMonth; Self.FIsRest := FIsRest; Self.FDescription := FDescription; end; end else inherited; end; constructor TElHoliday.Create; begin inherited; FFixedDate := True; FDay := 1; FMonth := 1; Description := 'New Year Day'; FIsRest := true; end; destructor TElHoliday.Destroy; begin inherited; end; procedure TElHoliday.SetFixedDate(newValue : Boolean); begin if (FFixedDate <> newValue) then begin FFixedDate := newValue; Self.Changed(False); end; {if} end; procedure TElHoliday.SetDay(newValue : Word); begin if (FDay <> newValue) then begin if (newValue > 31) or (newValue < 1) then raise Exception.Create('Day should be between 1 and the number of days in the month'); FDay := newValue; Changed(False); end; {if} end; procedure TElHoliday.SetDayOfWeek(newValue : Word); begin if (FDayOfWeek <> newValue) then begin if (newValue > 6) then raise Exception.Create('Day of Week number should be between 0 and 6'); FDayOfWeek := newValue; Changed(False); end; {if} end; procedure TElHoliday.SetMonth(newValue : Word); begin if (FMonth <> newValue) then begin if (newValue > 12) or (newValue < 1) then raise Exception.Create('Month number should be between 1 and 12'); FMonth := newValue; Changed(False); end; {if} end; procedure TElHoliday.SetIsRest(newValue : Boolean); begin if (FIsRest <> newValue) then begin FIsRest := newValue; Changed(False); end; {if} end; procedure TElHoliday.SaveToStream(Stream : TStream); begin Stream.WriteBuffer(FIsRest, SizeOf(FIsRest)); Stream.WriteBuffer(FMonth, SizeOf(FMonth)); Stream.WriteBuffer(FDayOfWeek, SizeOf(FDayOfWeek)); Stream.WriteBuffer(FDay, SizeOf(FDay)); Stream.WriteBuffer(FFixedDate, SizeOf(FFixedDate)); WriteStringToStream(Stream, FDescription); end; procedure TElHoliday.LoadFromStream(Stream : TStream); begin Stream.ReadBuffer(FIsRest, SizeOf(FIsRest)); Stream.ReadBuffer(FMonth, SizeOf(FMonth)); Stream.ReadBuffer(FDayOfWeek, SizeOf(FDayOfWeek)); Stream.ReadBuffer(FDay, SizeOf(FDay)); Stream.ReadBuffer(FFixedDate, SizeOf(FFixedDate)); ReadStringFromStream(Stream, FDescription); end; function TElHolidays.GetItems(Index : integer) : TElHoliday; begin Result := TElHoliday(inherited GetItem(Index)); end; procedure TElHolidays.SetItems(Index : integer; newValue : TElHoliday); begin inherited SetItem(Index, newValue); end; function TElHolidays.GetOwner : TPersistent; begin Result := FOwner; end; procedure TElHolidays.Update(Item : TCollectionItem); begin if Assigned(FOwner) and (FOwner is TControl) and (not (csDestroying in TControl(FOwner).ComponentState)) then TControl(FOwner).Invalidate; end; function TElHolidays.Add : TElHoliday; begin Result := TElHoliday(inherited Add); end; procedure TElHolidays.SaveToStream(Stream : TStream); var i : integer; begin i := Count; Stream.WriteBuffer(i, SizeOf(integer)); for i := 0 to Count - 1 do // Iterate begin Items[i].SaveToStream(Stream); end; // for end; procedure TElHolidays.LoadFromStream(Stream : TStream); var i, j : integer; AHoliday : TElHoliday; begin Clear; Stream.ReadBuffer(i, SizeOf(integer)); for j := 0 to i - 1 do // Iterate begin AHoliday := Add; AHoliday.LoadFromStream(Stream); end; // for end; constructor TElHolidays.Create(AOwner : TComponent); begin FOwner := AOwner; inherited Create(TElHoliday); end; end.
unit uLicencaItensVO; interface uses uTableName, uKeyField, System.SysUtils, System.Generics.Collections; type [TableName('Licenca_Itens')] TLicencaItensVO = class private FDataLcto: TDate; FCNPJCPF: string; FId: Integer; FDataUtilizacao: TDate; FLicenca: string; FSituacao: string; FLicencaUtilizada: string; FCodigo: Integer; FIdCliente: Integer; FRazaoSocial: string; FUtilizadaTela: string; FSituacaoTela: string; procedure SetCNPJCPF(const Value: string); procedure SetDataLcto(const Value: TDate); procedure SetDataUtilizacao(const Value: TDate); procedure SetId(const Value: Integer); procedure SetLicenca(const Value: string); procedure SetSituacao(const Value: string); procedure SetLicencaUtilizada(const Value: string); procedure SetCodigo(const Value: Integer); function GetSituacao: string; function GetLicencaUtilizada: string; procedure SetIdCliente(const Value: Integer); procedure SetRazaoSocial(const Value: string); function GetSituacaoTela: string; function GetUtilizadaTela: string; procedure SetSituacaoTela(const Value: string); procedure SetUtilizadaTela(const Value: string); public [KeyField('LicIte_Id')] property Id: Integer read FId write SetId; [FieldName('LicIte_Codigo')] property Codigo: Integer read FCodigo write SetCodigo; [FieldName('LicIte_CNPJCPF')] property CNPJCPF: string read FCNPJCPF write SetCNPJCPF; [FieldDate('LicIte_DataLcto')] property DataLcto: TDate read FDataLcto write SetDataLcto; [FieldName('LicIte_Licenca')] property Licenca: string read FLicenca write SetLicenca; [FieldDate('LicIte_DataUtilizacao')] property DataUtilizacao: TDate read FDataUtilizacao write SetDataUtilizacao; [FieldName('LicIte_Situacao')] property Situacao: string read GetSituacao write SetSituacao; [FieldName('LicIte_Utilizada')] property LicencaUtilizada: string read GetLicencaUtilizada write SetLicencaUtilizada; [FieldNull('LicIte_Cliente')] property IdCliente: Integer read FIdCliente write SetIdCliente; property RazaoSocial: string read FRazaoSocial write SetRazaoSocial; property SituacaoTela: string read GetSituacaoTela write SetSituacaoTela; property UtilizadaTela: string read GetUtilizadaTela write SetUtilizadaTela; end; TListaLicencaItens = TObjectList<TLicencaItensVO>; implementation { TLicencaItensVO } function TLicencaItensVO.GetLicencaUtilizada: string; begin Result := FLicencaUtilizada; // if FLicencaUtilizada = 'S' then // Result := 'Sim' // else if FLicencaUtilizada = 'N' then // Result := 'Não' // else // Result := FLicencaUtilizada; end; function TLicencaItensVO.GetSituacao: string; begin Result := FSituacao; // if FSituacao = '1' then // Result := 'Normal' // else if FSituacao = '2' then // Result := 'Inutiliz.' // else // Result := FSituacao; end; function TLicencaItensVO.GetSituacaoTela: string; begin if FSituacaoTela = '1' then Result := 'Normal' else if FSituacaoTela = '2' then Result := 'Inutiliz.' else Result := FSituacaoTela; end; function TLicencaItensVO.GetUtilizadaTela: string; begin end; procedure TLicencaItensVO.SetCNPJCPF(const Value: string); begin FCNPJCPF := Value; end; procedure TLicencaItensVO.SetCodigo(const Value: Integer); begin FCodigo := Value; end; procedure TLicencaItensVO.SetDataLcto(const Value: TDate); begin FDataLcto := Value; end; procedure TLicencaItensVO.SetDataUtilizacao(const Value: TDate); begin FDataUtilizacao := Value; end; procedure TLicencaItensVO.SetId(const Value: Integer); begin FId := Value; end; procedure TLicencaItensVO.SetIdCliente(const Value: Integer); begin FIdCliente := Value; end; procedure TLicencaItensVO.SetLicenca(const Value: string); begin FLicenca := Value; end; procedure TLicencaItensVO.SetLicencaUtilizada(const Value: string); begin FLicencaUtilizada := Value; end; procedure TLicencaItensVO.SetRazaoSocial(const Value: string); begin FRazaoSocial := Value; end; procedure TLicencaItensVO.SetSituacao(const Value: string); begin FSituacao := Value; end; procedure TLicencaItensVO.SetSituacaoTela(const Value: string); begin end; procedure TLicencaItensVO.SetUtilizadaTela(const Value: string); begin end; end.
unit GetUsersUnit; interface uses SysUtils, BaseExampleUnit; type TGetUsers = class(TBaseExample) public procedure Execute; end; implementation uses UserUnit; procedure TGetUsers.Execute; var ErrorString: String; Users: TUserList; begin Users := Route4MeManager.User.Get(ErrorString); try WriteLn(''); if (Users.Count > 0) then begin WriteLn(Format('GetUsers executed successfully, %d users returned', [Users.Count])); WriteLn(''); end else WriteLn(Format('GetUsers error: "%s"', [ErrorString])); finally FreeAndNil(Users); end; end; end.
unit phpgd2; interface const php_gd2 = 'php_gd2.dll'; function imagecreatefromjpeg(filename:PAnsiChar): Integer; cdecl; external php_gd2 name 'imagecreatefromjpeg'; function imagecreatefrompng(filename:PAnsiChar): Integer; cdecl; external php_gd2; //clq 调用这个函数后最后接着调用 imagesavealpha,这样才能存出透明的 png 图片 //新建一个真彩色图像 function imagecreatetruecolor(x_size:Integer; y_size:Integer):Integer; cdecl; external php_gd2; function imagepng(im:Integer; outfilename:PAnsiChar): Integer; cdecl; external php_gd2; //设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息(与单一透明色相反)。 //要使用本函数,必须将 alphablending 清位(imagealphablending($im, false))。 //指的是不要使用混色模式,直接使用 alpha 值 procedure imagesavealpha(im:Integer; save:Integer); cdecl; external php_gd2; // imagealphablending() 允许在真彩色图像上使用两种不同的绘画模式。 // 在混色(blending)模式下,alpha 通道色彩成分提供给所有的绘画函数,例如 imagesetpixel() 决定底层的颜色应在何种程度上被允许照射透过。作为结果,GD 自动将该点现有的颜色和画笔颜色混合,并将结果储存在图像中。结果的像素是不透明的。 // 在非混色模式下,画笔颜色连同其 alpha 通道信息一起被拷贝,替换掉目标像素。混色模式在画调色板图像时不可用。 // 如果 blendmode 为 TRUE,则启用混色模式,否则关闭。成功时返回 TRUE, 或者在失败时返回 FALSE //clq 还是有点难懂的,总之操作透明的 png 得不到想要的结果时可以切换下试试//默认是打开的 procedure imagealphablending(im:Integer; blend:Integer); cdecl; external php_gd2; // bool imageantialias ( resource $image , bool $enabled ) // 对线段和多边形启用快速画图抗锯齿方法。不支持 alpha 部分。使用直接混色操作。仅用于真彩色图像。 // 不支持线宽和风格。 // 使用抗锯齿和透明背景色可能出现未预期的结果。混色方法把背景色当成任何其它颜色使用。缺乏 alpha 部分的支持导致不允许基于 alpha 抗锯齿 function imageantialias(im:Integer; alias{enabled=1}:Integer):Integer; cdecl; external php_gd2; //imagecopyresampled http://php.net/imageantialias 有个例子说明可以用 imagecopyresampled 复制图像,这样会自动有 aa 效果 //分配颜色 imagecolorallocatealpha() 的行为和 imagecolorallocate() 相同,但多了一个额外的透明度参数 alpha,其值从 0 到 127。0 表示完全不透明,127 表示完全透明。 function imagecolorallocatealpha(im:Integer; red:Integer; green:Integer; blue:Integer; alpha:Integer):Integer; cdecl; external php_gd2; //画线 procedure imageline(im:Integer; x1:Integer; y1:Integer; x2:Integer; y2:Integer; color:Integer); cdecl; external php_gd2; //设置画线的宽度,不过似乎不是每个绘图函数下都起作用 procedure imagesetthickness(im:Integer; thick:Integer); cdecl; external php_gd2; //画一椭圆并填充到指定的 image//cx,cy 应该是圆心的位置 procedure imagefilledellipse(im:Integer; cx:Integer; cy:Integer; width:Integer; height:Integer; color:Integer); cdecl; external php_gd2; //画一个 aa 边界的圆//cr 是半径? procedure ex_imageSmoothCircle(im:Integer; cx:Integer; cy:Integer; cr:Integer; color:Integer); cdecl; external php_gd2; //按 imageSmoothCircle 算法做的支持 alpha 通道 procedure ex_imageSmoothCircle_alpha(im:Integer; cx:Integer; cy:Integer; cr:Integer; color:Integer); cdecl; external php_gd2; //imagedestroy() 释放与 image 关联的内存 procedure imagedestroy(im:Integer); cdecl; external php_gd2; //如果 font 是 1,2,3,4 或 5,则使用内置字体,否则使用 imageloadfont() 装载字体 procedure imagestring(im:Integer; _font:Integer; x:Integer; y:Integer; str:PAnsiChar; color:Integer); cdecl; external php_gd2; //imagettftext — 用 TrueType 字体向图像 //imagefttext — 使用 FreeType 2 字体将文本写入图像写入文本//size 字体大小, angle 角度(一般是0) function imagettftext(im:Integer; size:Double; angle:Double; x:Integer; y:Integer; color:Integer; fontfile:PAnsiChar; text:PAnsiChar):PAnsiChar; cdecl; external php_gd2; //图片宽,高 function imagesx(im:Integer):Integer; cdecl; external php_gd2; function imagesy(im:Integer):Integer; cdecl; external php_gd2; //将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。 function imagecopyresampled(im_dst, im_src:Integer; dstX , dstY , srcX , srcY , dstW , dstH , srcW , srcH:Integer):Integer; cdecl; external php_gd2; //设置某个点的像素颜色 //PHP_FUNCTION(imagesetpixel) procedure imagesetpixel(im:Integer; x:Integer; y:Integer; color:Integer); cdecl; external php_gd2; //可以认为是 imagegetpixel function imagecolorat(im:Integer; x:Integer; y:Integer):Integer; cdecl; external php_gd2; //将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。 function imagecopyresampled2(im_dst, im_src:Integer; dstX , dstY , srcX , srcY , dstW , dstH , srcW , srcH:Integer):Integer; //cdecl; external php_gd2; //解析出一个颜色的 rgba 值//注意应该输出的指针就是 8 位的整数,位数不对的话应该会乱码的//尽量保存原来的 rgb 值,少用这个函数 //GD_API void ex_color2rgb(gdImagePtr img, int color, uint8 * r8, uint8 * g8, uint8 * b8, uint8 * a8); procedure ex_color2rgb(img:Integer; color:Integer; r8:PByte; g8:PByte; b8:PByte; a8:PByte); cdecl; external php_gd2; implementation //与 "aaline手工画线" 一样,算法思想都来自 "计算机图形学原理及实践—C语言描述.pdf" ,基本上是其的简化版本算法//虽然是简化效果已经不错了 //将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。 //这个简单的算法似乎比 php 的 gdImageCopyResized 好//用来做放大肯定是没问题的,缩小的话,其实再取一下相邻的值就可以了,至于取多少个相邻像素可以直接按像素来(完全没必要使用网上说的插值算法) function imagecopyresampled2(im_dst, im_src:Integer; dstX , dstY , srcX , srcY , dstW , dstH , srcW , srcH:Integer):Integer; //cdecl; external php_gd2; var w,h:integer; i,j:integer; i2,j2:integer; c, c2:Integer; r8, g8, b8, a8:Byte; pix_count:Integer;//计算缩小了多少倍,就是要取相邻的多少个像素点//有个潜在的 bug, 如果缩小得非常多就会在 rgb 合并是溢出,不过可以忽略这种情况 pix_count_square:Integer;//平方数//只是为优化而已 //计算一个点的像素值//取4个点的平均值//这是固定取 4 个点的算法,效果倒也还可以 function GetAAPixel(x,y:Integer):Integer; var xsrc,ysrc:Integer; r, g, b, a:Integer;//rgb 值的总和 xadd,yadd:Integer; //取多少个点的值来算当前这个点 xsrc2,ysrc2:Integer;//避免越界 //pix_count:Integer;//计算缩小了多少倍,就是要取相邻的多少个像素点//有个潜在的 bug, 如果缩小得非常多就会在 rgb 合并是溢出,不过可以忽略这种情况 //pix_count_square:Integer;//平方数//只是为优化而已 begin r := 0; g := 0; b := 0; a := 0; //算出这个代表应该是原图的什么位置 xsrc := Trunc(x * srcW / w); ysrc := Trunc(y * srcH / h); //-------------------------------------------------- //为优化速度,计算应该放在函数体外 // pix_count := srcW div dstW;//其实应该用浮点数,但是那样太慢了 // // if pix_count<1 then pix_count := 1; // //if pix_count<2 then pix_count := 2; //如果要放大的效果好点,可以用这个 // // pix_count_square := pix_count * pix_count; //-------------------------------------------------- for xadd := 0 to pix_count-1 do begin for yadd := 0 to pix_count-1 do begin xsrc2 := xsrc + xadd; ysrc2 := ysrc + yadd;//避免越界 if xsrc2>srcW-1 then xsrc2 := srcW-1; if ysrc2>srcH-1 then ysrc2 := srcH-1; c := imagecolorat(im_src, xsrc2, ysrc2); ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 r := r + r8; g := g + g8; b := b + b8; a := a + a8; end; end; // c := imagecolorat(im_src, xsrc, ysrc); // ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 // // r := r + r8; g := g + g8; b := b + b8; a := a + a8; //c2 := imagecolorallocatealpha(im_dst, r, g, b, a);//很快 //c2 := imagecolorallocatealpha(im_dst, r div 4, g div 4, b div 4, a div 4);//很快 c2 := imagecolorallocatealpha(im_dst, r div pix_count_square, g div pix_count_square, b div pix_count_square, a div pix_count_square);//很快 Result := c2; end; begin Result := 1; w := imagesx(im_dst); h := imagesy(im_dst); //-------------------------------------------------- //为优化速度,计算应该放在函数体外 pix_count := srcW div dstW;//其实应该用浮点数,但是那样太慢了 if pix_count<1 then pix_count := 1; if pix_count<2 then pix_count := 2; //如果要放大的效果好点,可以用这个 pix_count_square := pix_count * pix_count; //-------------------------------------------------- for i := 0 to w-1 do begin for j := 0 to h-1 do begin c := imagecolorat(im_src, i, j); ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 //-------------------------------------------------- //算出这个代表应该是原图的什么位置 i2 := Trunc(i * srcW / w); j2 := Trunc(j * srcH / h); c := imagecolorat(im_src, i2, j2); ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 //-------------------------------------------------- //c2 := imagecolorallocatealpha(im_dst, r8, g8, b8, a8);//很快 c2 := GetAAPixel(i, j); imagesetpixel(im_dst, i, j, c2);//很快 end; end; end; //取两个像素计算平均值(因为是平面,所以实际上是4个像素的平均值),可以用在要求不高的地方 function imagecopyresampled2_2(im_dst, im_src:Integer; dstX , dstY , srcX , srcY , dstW , dstH , srcW , srcH:Integer):Integer; //cdecl; external php_gd2; var w,h:integer; i,j:integer; i2,j2:integer; c, c2:Integer; r8, g8, b8, a8:Byte; //计算一个点的像素值//取4个点的平均值//这是固定取 4 个点的算法,效果倒也还可以 function GetAAPixel(x,y:Integer):Integer; var xsrc,ysrc:Integer; r, g, b, a:Integer;//rgb 值的总和 xadd,yadd:Integer; //取多少个点的值来算当前这个点 xsrc2,ysrc2:Integer;//避免越界 begin r := 0; g := 0; b := 0; a := 0; //算出这个代表应该是原图的什么位置 xsrc := Trunc(x * srcW / w); ysrc := Trunc(y * srcH / h); for xadd := 0 to 2-1 do begin for yadd := 0 to 2-1 do begin xsrc2 := xsrc + xadd; ysrc2 := ysrc + yadd;//避免越界 if xsrc2>srcW-1 then xsrc2 := srcW-1; if ysrc2>srcH-1 then ysrc2 := srcH-1; c := imagecolorat(im_src, xsrc2, ysrc2); ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 r := r + r8; g := g + g8; b := b + b8; a := a + a8; end; end; // c := imagecolorat(im_src, xsrc, ysrc); // ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 // // r := r + r8; g := g + g8; b := b + b8; a := a + a8; //c2 := imagecolorallocatealpha(im_dst, r, g, b, a);//很快 c2 := imagecolorallocatealpha(im_dst, r div 4, g div 4, b div 4, a div 4);//很快 Result := c2; end; begin Result := 1; w := imagesx(im_dst); h := imagesy(im_dst); for i := 0 to w-1 do begin for j := 0 to h-1 do begin c := imagecolorat(im_src, i, j); ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 //-------------------------------------------------- //算出这个代表应该是原图的什么位置 i2 := Trunc(i * srcW / w); j2 := Trunc(j * srcH / h); c := imagecolorat(im_src, i2, j2); ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 //-------------------------------------------------- //c2 := imagecolorallocatealpha(im_dst, r8, g8, b8, a8);//很快 c2 := GetAAPixel(i, j); imagesetpixel(im_dst, i, j, c2);//很快 end; end; end; //第一个,很快的算法//只是简单地取坐标像素,缩小的话会丢失像素值,不过用来放大是没问题的 function imagecopyresampled2_1(im_dst, im_src:Integer; dstX , dstY , srcX , srcY , dstW , dstH , srcW , srcH:Integer):Integer; //cdecl; external php_gd2; var w,h:integer; i,j:integer; i2,j2:integer; c, c2:Integer; r8, g8, b8, a8:Byte; begin Result := 1; w := imagesx(im_dst); h := imagesy(im_dst); for i := 0 to w-1 do begin for j := 0 to h-1 do begin c := imagecolorat(im_src, i, j); ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 //-------------------------------------------------- //算出这个代表应该是原图的什么位置 i2 := Trunc(i * srcW / w); j2 := Trunc(j * srcH / h); c := imagecolorat(im_src, i2, j2); ex_color2rgb(im_src, c, @r8, @g8, @b8, @a8);//很快 //-------------------------------------------------- c2 := imagecolorallocatealpha(im_dst, r8, g8, b8, a8);//很快 imagesetpixel(im_dst, i, j, c);//很快 end; end; end; end.
//---------------------------------------------------------------- // Most of these functions are taken from "Mini Webbrowser Demo", // which is available on http://torry.net. // Some functions are added later by AT as stated in the comments. // The original WBFuncs.pas unit caption is below: //---------------------------------------------------------------- (**************************************************************) (* *) (* TWebbrowser functions by toms *) (* Version 1.9 *) (* E-Mail: tom@swissdelphicenter.ch *) (* *) (* Contributors: www.swissdelphicenter.ch *) (* *) (* *) (**************************************************************) {$I ATViewerOptions.inc} //ATViewer options {$I Compilers.inc} //Compiler defines unit ATxWBProc; interface uses {$ifdef IE4X} WebBrowser4_TLB {$else} SHDocVw {$endif}; //From WBFuncs.pas: procedure WB_Wait(WB: TWebbrowser); procedure WB_SetFocus(WB: TWebbrowser); procedure WB_Set3DBorderStyle(WB: TWebBrowser; bValue: Boolean); procedure WB_Copy(WB: TWebbrowser); procedure WB_SelectAll(WB: TWebbrowser); procedure WB_ShowPrintDialog(WB: TWebbrowser); procedure WB_ShowPrintPreview(WB: TWebbrowser); procedure WB_ShowPageSetup(WB: TWebbrowser); procedure WB_ShowFindDialog(WB: TWebbrowser); //Added by AT: procedure WB_NavigateBlank(WB: TWebbrowser); procedure WB_NavigateFilename(WB: TWebbrowser; const FileName: WideString; DoWait: Boolean); procedure WB_SelectNone(WB: TWebbrowser); function WB_GetScrollTop(WB: TWebbrowser): Integer; procedure WB_SetScrollTop(WB: TWebbrowser; Value: Integer); function WB_GetScrollHeight(WB: TWebbrowser): Integer; procedure WB_IncreaseFont(WB: TWebbrowser; Increment: Boolean); {$ifdef OFFLINE} procedure WB_SetGlobalOffline(AValue: Boolean); function WB_GetGlobalOffline: Boolean; {$endif} var WB_MessagesEnabled: Boolean = False; //Can be set to True for debugging purposes implementation uses Windows, SysUtils, {$ifdef COMPILER_6_UP} Variants, {$endif} ActiveX, MSHTML, Forms, OleCtrls, ATxFProc, Dialogs; type TWBFontSize = 0..4; //---------------------------------------------------------------------------- procedure MsgError(const Msg: WideString); begin if WB_MessagesEnabled then MessageBoxW(0, PWideChar(Msg), 'Webbrowser Error', MB_OK or MB_ICONERROR or MB_TASKMODAL); end; //---------------------------------------------------------------------------- function InvokeCMD(WB: TWebbrowser; nCmdID: DWORD): Boolean; overload; forward; function InvokeCMD(WB: TWebbrowser; InvokeIE: Boolean; Value1, Value2: Integer; var vaIn, vaOut: OleVariant): Boolean; overload; forward; const CGID_WebBrowser: TGUID = '{ED016940-BD5B-11cf-BA4E-00C04FD70816}'; HTMLID_FIND = 1; function InvokeCMD(WB: TWebbrowser; nCmdID: DWORD): Boolean; var vaIn, vaOut: OleVariant; begin Result := InvokeCMD(WB, True, nCmdID, 0, vaIn, vaOut); end; function InvokeCMD(WB: TWebbrowser; InvokeIE: Boolean; Value1, Value2: Integer; var vaIn, vaOut: OleVariant): Boolean; var CmdTarget: IOleCommandTarget; PtrGUID: PGUID; begin Result:= False; New(PtrGUID); if InvokeIE then PtrGUID^ := CGID_WebBrowser else PtrGuid := PGUID(nil); if WB.ControlInterface.Document <> nil then try WB.ControlInterface.Document.QueryInterface(IOleCommandTarget, CmdTarget); if CmdTarget <> nil then try CmdTarget.Exec(PtrGuid, Value1, Value2, vaIn, vaOut); Result:= True; finally CmdTarget._Release; end; except end; Dispose(PtrGUID); end; //---------------------------------------------------------------------------- procedure WB_Wait(WB: TWebbrowser); begin while (WB.ReadyState <> READYSTATE_COMPLETE) and not (Application.Terminated) do begin Application.ProcessMessages; Sleep(0); end; end; //---------------------------------------------------------------------------- function WB_DocumentLoaded(WB: TWebbrowser): Boolean; var Doc: IHTMLDocument2; begin Result := False; if Assigned(WB) then if WB.ControlInterface.Document <> nil then begin WB.ControlInterface.Document.QueryInterface(IHTMLDocument2, Doc); Result := Assigned(Doc); end; end; //---------------------------------------------------------------------------- procedure WB_SetFocus(WB: TWebbrowser); begin try if WB_DocumentLoaded(WB) then (WB.ControlInterface.Document as IHTMLDocument2).ParentWindow.Focus; except MsgError('Cannot focus the WebBrowser control.'); end; end; //---------------------------------------------------------------------------- procedure WB_Set3DBorderStyle(WB: TWebBrowser; bValue: Boolean); { bValue: True: Show a 3D border style False: Show no border } var Document: IHTMLDocument2; Element: IHTMLElement; StrBorderStyle: AnsiString; begin if Assigned(WB) then if WB_DocumentLoaded(WB) then try Document := WB.ControlInterface.Document as IHTMLDocument2; if Assigned(Document) then begin Element := Document.Body; if Element <> nil then begin case bValue of False: StrBorderStyle := 'none'; True: StrBorderStyle := ''; end; Element.Style.BorderStyle := StrBorderStyle; end; end; except MsgError('Cannot change border style for WebBrowser control.'); end; end; //---------------------------------------------------------------------------- procedure WB_Copy(WB: TWebbrowser); var vaIn, vaOut: Olevariant; begin InvokeCmd(WB, FALSE, OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut); end; //---------------------------------------------------------------------------- procedure WB_SelectAll(WB: TWebbrowser); var vaIn, vaOut: Olevariant; begin InvokeCmd(WB, FALSE, OLECMDID_SELECTALL, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut); end; //---------------------------------------------------------------------------- procedure WB_SelectNone(WB: TWebbrowser); var vaIn, vaOut: Olevariant; begin InvokeCmd(WB, FALSE, OLECMDID_CLEARSELECTION, OLECMDEXECOPT_DODEFAULT, vaIn, vaOut); end; //---------------------------------------------------------------------------- procedure WB_ShowPrintDialog(WB: TWebbrowser); var OleCommandTarget: IOleCommandTarget; Command: TOleCmd; Success: HResult; Param: OleVariant; begin if WB_DocumentLoaded(WB) then begin WB.ControlInterface.Document.QueryInterface(IOleCommandTarget, OleCommandTarget); Command.cmdID := OLECMDID_PRINT; if OleCommandTarget.QueryStatus(nil, 1, @Command, nil) <> S_OK then begin //ShowMessage('Nothing to print'); Exit; end; if (Command.cmdf and OLECMDF_ENABLED) <> 0 then begin Success := OleCommandTarget.Exec(nil, OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, Param, Param); if Success = S_OK then begin end; { //AT case Success of S_OK: ; OLECMDERR_E_CANCELED: ShowMessage('Canceled by user'); else ShowMessage('Error while printing'); end; } end end; end; //---------------------------------------------------------------------------- procedure WB_ShowPrintPreview(WB: TWebbrowser); var vaIn, vaOut: OleVariant; begin if WB_DocumentLoaded(WB) then try // Execute the print preview command. WB.ControlInterface.ExecWB(OLECMDID_PRINTPREVIEW, OLECMDEXECOPT_DONTPROMPTUSER, vaIn, vaOut); except MsgError('Cannot show Print Preview for WebBrowser control.'); end; end; //---------------------------------------------------------------------------- procedure WB_ShowPageSetup(WB: TWebbrowser); var vaIn, vaOut: OleVariant; begin if WB_DocumentLoaded(WB) then try // Execute the page setup command. WB.ControlInterface.ExecWB(OLECMDID_PAGESETUP, OLECMDEXECOPT_PROMPTUSER, vaIn, vaOut); except MsgError('Cannot show Print Setup for WebBrowser control.'); end; end; //---------------------------------------------------------------------------- procedure WB_ShowFindDialog(WB: TWebbrowser); begin InvokeCMD(WB, HTMLID_FIND); end; //---------------------------------------------------------------------------- function WB_GetZoom(WB: TWebBrowser): TWBFontSize; var vaIn, vaOut: OleVariant; begin result := 0; if WB_DocumentLoaded(WB) then begin vaIn := EmptyParam; //was null InvokeCmd(WB, FALSE, OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, vaIn, vaOut); result := vaOut; end; end; //---------------------------------------------------------------------------- procedure WB_SetZoom(WB: TWebBrowser; Size: TWBFontSize); var V: OleVariant; begin if WB_DocumentLoaded(WB) then begin V := Size; WB.ExecWB(OLECMDID_ZOOM, OLECMDEXECOPT_DODEFAULT, V); end; end; //------------------------------------------------------ // Added by AT: procedure WB_NavigateBlank(WB: TWebbrowser); begin try WB.Navigate('about:blank'); WB_Wait(WB); except MsgError('Cannot navigate to blank page in WebBrowser control.'); end; end; //---------------------------------------------------------------------------- procedure WB_NavigateFilename(WB: TWebbrowser; const FileName: WideString; DoWait: Boolean); var fn, fnT: WideString; begin try fn := FileName; //workaround: WebBrowser badly opens mht Unicode name if (ExtractFileExt(fn) = '.mht') and (WideString(AnsiString(fn)) <> fn) then begin fnT := FTempPath + 'UV.mht'; FDelete(fnT); FFileCopy(fn, fnT); fn := fnT; end; WB.Navigate('file:///' + fn); //Prefix mandatory if DoWait then WB_Wait(WB); except MsgError('Cannot navigate in WebBrowser control.'); end; end; //---------------------------------------------------------------------------- function GetBodyElement(WB: TWebbrowser): IHTMLElement2; var Dispatch: IDispatch; begin Result := nil; if WB_DocumentLoaded(WB) then try Dispatch := (WB.ControlInterface.Document as IHTMLDocument2).Body; if Assigned(Dispatch) then Dispatch.QueryInterface(IHTMLElement2, Result); except MsgError('Cannot get body element in WebBrowser control.'); end; end; //---------------------------------------------------------------------------- function WB_GetScrollTop(WB: TWebbrowser): Integer; var Element: IHTMLElement2; begin Result := 0; try Element := GetBodyElement(WB); if Assigned(Element) then Result := Element.ScrollTop; except MsgError('Cannot get scroll state in WebBrowser control.'); end; end; //---------------------------------------------------------------------------- procedure WB_SetScrollTop(WB: TWebbrowser; Value: Integer); var Element: IHTMLElement2; begin try Element := GetBodyElement(WB); if Assigned(Element) then Element.ScrollTop := Value; except MsgError('Cannot scroll in WebBrowser control.'); end; end; //---------------------------------------------------------------------------- function WB_GetScrollHeight(WB: TWebbrowser): Integer; var Element: IHTMLElement2; begin Result := 0; try Element := GetBodyElement(WB); if Assigned(Element) then Result := Element.ScrollHeight; except MsgError('Cannot get scroll state in WebBrowser control.'); end; end; //---------------------------------------------------------------------------- procedure WB_IncreaseFont(WB: TWebbrowser; Increment: Boolean); var N: TWBFontSize; begin N := WB_GetZoom(WB); if Increment then begin if N < High(TWBFontSize) then WB_SetZoom(WB, Succ(N)); end else begin if N > Low(TWBFontSize) then WB_SetZoom(WB, Pred(N)); end; end; //---------------------------------------------------------------------------- {$ifdef OFFLINE} { Declarations from WinInet.pas } type TInternetConnectedInfo = record dwConnectedState: DWORD; dwFlags: DWORD; end; const INTERNET_STATE_CONNECTED = $00000001; { connected state (mutually exclusive with disconnected) } INTERNET_STATE_DISCONNECTED = $00000002; { disconnected from network } INTERNET_STATE_DISCONNECTED_BY_USER = $00000010; { disconnected by user request } INTERNET_STATE_IDLE = $00000100; { no network requests being made (by Wininet) } INTERNET_STATE_BUSY = $00000200; { network requests being made (by Wininet) } INTERNET_OPTION_CONNECTED_STATE = 50; ISO_FORCE_DISCONNECTED = $00000001; type HINTERNET = Pointer; TInternetSetOption = function (hInet: HINTERNET; dwOption: DWORD; lpBuffer: Pointer; dwBufferLength: DWORD): BOOL; stdcall; TInternetQueryOption = function (hInet: HINTERNET; dwOption: DWORD; lpBuffer: Pointer; var lpdwBufferLength: DWORD): BOOL; stdcall; var HLib: THandle = 0; InternetSetOption: TInternetSetOption = nil; InternetQueryOption: TInternetQueryOption = nil; { Custom definitions } type TWebOfflineMode = (woUnknown, woOfflineOn, woOfflineOff); var WebInitialOffline: TWebOfflineMode = woUnknown; function InitWinInetDLL: Boolean; begin Result := False; try if HLib <> 0 then Exit; HLib := LoadLibrary('wininet.dll'); if HLib <> 0 then begin InternetSetOption := GetProcAddress(HLib, 'InternetSetOptionA'); InternetQueryOption:= GetProcAddress(HLib, 'InternetQueryOptionA'); end; finally Result := (HLib <> 0) and Assigned(InternetSetOption) and Assigned(InternetQueryOption); end; end; procedure FreeWinInetDLL; begin if HLib <> 0 then begin //Restore initial offline status if WebInitialOffline <> woUnknown then WB_SetGlobalOffline(WebInitialOffline = woOfflineOn); //Unload DLL FreeLibrary(HLib); HLib := 0; InternetSetOption := nil; InternetQueryOption := nil; end; end; //---------------------------------------------------------------------------- procedure WB_SetGlobalOffline(AValue: Boolean); var ci: TInternetConnectedInfo; dwSize: DWORD; begin //Load DLL if not InitWinInetDLL then Exit; //Remember initial offline status if WebInitialOffline = woUnknown then begin if WB_GetGlobalOffline then WebInitialOffline := woOfflineOn else WebInitialOffline := woOfflineOff; end; //Set the option dwSize := SizeOf(ci); if AValue then begin ci.dwConnectedState := INTERNET_STATE_DISCONNECTED_BY_USER; ci.dwFlags := ISO_FORCE_DISCONNECTED; InternetSetOption(nil, INTERNET_OPTION_CONNECTED_STATE, @ci, dwSize); end else begin ci.dwConnectedState := INTERNET_STATE_CONNECTED; ci.dwFlags := 0; InternetSetOption(nil, INTERNET_OPTION_CONNECTED_STATE, @ci, dwSize); end; end; //---------------------------------------------------------------------------- function WB_GetGlobalOffline: Boolean; var dwState: DWORD; dwSize: DWORD; begin //Load DLL if not InitWinInetDLL then begin Result := False; Exit end; //Get the option dwState := 0; dwSize := SizeOf(dwState); Result := False; if (InternetQueryOption(nil, INTERNET_OPTION_CONNECTED_STATE, @dwState, dwSize)) then if ((dwState and INTERNET_STATE_DISCONNECTED_BY_USER) <> 0) then Result := True; end; {$endif} initialization OleInitialize(nil); finalization {$ifdef OFFLINE} FreeWinInetDLL; {$endif} OleUninitialize; FDelete(FTempPath + 'UV.mht'); end.
unit TTSNOTLISTTAGTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSNOTLISTTAGRecord = record PCifFlag: String[1]; PLoanNum: String[20]; PTrackCode: String[8]; PCategorySub: Integer; PSeparateBy: String[10]; PSortBy: String[120]; End; TTTSNOTLISTTAGBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSNOTLISTTAGRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSNOTLISTTAG = (TTSNOTLISTTAGPrimaryKey, TTSNOTLISTTAGBySort); TTTSNOTLISTTAGTable = class( TDBISAMTableAU ) private FDFCifFlag: TStringField; FDFLoanNum: TStringField; FDFTrackCode: TStringField; FDFCategorySub: TIntegerField; FDFSeparateBy: TStringField; FDFSortBy: TStringField; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPTrackCode(const Value: String); function GetPTrackCode:String; procedure SetPCategorySub(const Value: Integer); function GetPCategorySub:Integer; procedure SetPSeparateBy(const Value: String); function GetPSeparateBy:String; procedure SetPSortBy(const Value: String); function GetPSortBy:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSNOTLISTTAG); function GetEnumIndex: TEITTSNOTLISTTAG; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSNOTLISTTAGRecord; procedure StoreDataBuffer(ABuffer:TTTSNOTLISTTAGRecord); property DFCifFlag: TStringField read FDFCifFlag; property DFLoanNum: TStringField read FDFLoanNum; property DFTrackCode: TStringField read FDFTrackCode; property DFCategorySub: TIntegerField read FDFCategorySub; property DFSeparateBy: TStringField read FDFSeparateBy; property DFSortBy: TStringField read FDFSortBy; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PTrackCode: String read GetPTrackCode write SetPTrackCode; property PCategorySub: Integer read GetPCategorySub write SetPCategorySub; property PSeparateBy: String read GetPSeparateBy write SetPSeparateBy; property PSortBy: String read GetPSortBy write SetPSortBy; published property Active write SetActive; property EnumIndex: TEITTSNOTLISTTAG read GetEnumIndex write SetEnumIndex; end; { TTTSNOTLISTTAGTable } procedure Register; implementation function TTTSNOTLISTTAGTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSNOTLISTTAGTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSNOTLISTTAGTable.GenerateNewFieldName } function TTTSNOTLISTTAGTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSNOTLISTTAGTable.CreateField } procedure TTTSNOTLISTTAGTable.CreateFields; begin FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFTrackCode := CreateField( 'TrackCode' ) as TStringField; FDFCategorySub := CreateField( 'CategorySub' ) as TIntegerField; FDFSeparateBy := CreateField( 'SeparateBy' ) as TStringField; FDFSortBy := CreateField( 'SortBy' ) as TStringField; end; { TTTSNOTLISTTAGTable.CreateFields } procedure TTTSNOTLISTTAGTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSNOTLISTTAGTable.SetActive } procedure TTTSNOTLISTTAGTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSNOTLISTTAGTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSNOTLISTTAGTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSNOTLISTTAGTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSNOTLISTTAGTable.SetPTrackCode(const Value: String); begin DFTrackCode.Value := Value; end; function TTTSNOTLISTTAGTable.GetPTrackCode:String; begin result := DFTrackCode.Value; end; procedure TTTSNOTLISTTAGTable.SetPCategorySub(const Value: Integer); begin DFCategorySub.Value := Value; end; function TTTSNOTLISTTAGTable.GetPCategorySub:Integer; begin result := DFCategorySub.Value; end; procedure TTTSNOTLISTTAGTable.SetPSeparateBy(const Value: String); begin DFSeparateBy.Value := Value; end; function TTTSNOTLISTTAGTable.GetPSeparateBy:String; begin result := DFSeparateBy.Value; end; procedure TTTSNOTLISTTAGTable.SetPSortBy(const Value: String); begin DFSortBy.Value := Value; end; function TTTSNOTLISTTAGTable.GetPSortBy:String; begin result := DFSortBy.Value; end; procedure TTTSNOTLISTTAGTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('CifFlag, String, 1, N'); Add('LoanNum, String, 20, N'); Add('TrackCode, String, 8, N'); Add('CategorySub, Integer, 0, N'); Add('SeparateBy, String, 10, N'); Add('SortBy, String, 120, N'); end; end; procedure TTTSNOTLISTTAGTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, CifFlag;LoanNum;TrackCode;CategorySub, Y, Y, N, N'); Add('BySort, SeparateBy;SortBy, N, N, Y, N'); end; end; procedure TTTSNOTLISTTAGTable.SetEnumIndex(Value: TEITTSNOTLISTTAG); begin case Value of TTSNOTLISTTAGPrimaryKey : IndexName := ''; TTSNOTLISTTAGBySort : IndexName := 'BySort'; end; end; function TTTSNOTLISTTAGTable.GetDataBuffer:TTTSNOTLISTTAGRecord; var buf: TTTSNOTLISTTAGRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCifFlag := DFCifFlag.Value; buf.PLoanNum := DFLoanNum.Value; buf.PTrackCode := DFTrackCode.Value; buf.PCategorySub := DFCategorySub.Value; buf.PSeparateBy := DFSeparateBy.Value; buf.PSortBy := DFSortBy.Value; result := buf; end; procedure TTTSNOTLISTTAGTable.StoreDataBuffer(ABuffer:TTTSNOTLISTTAGRecord); begin DFCifFlag.Value := ABuffer.PCifFlag; DFLoanNum.Value := ABuffer.PLoanNum; DFTrackCode.Value := ABuffer.PTrackCode; DFCategorySub.Value := ABuffer.PCategorySub; DFSeparateBy.Value := ABuffer.PSeparateBy; DFSortBy.Value := ABuffer.PSortBy; end; function TTTSNOTLISTTAGTable.GetEnumIndex: TEITTSNOTLISTTAG; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := TTSNOTLISTTAGPrimaryKey; if iname = 'BYSORT' then result := TTSNOTLISTTAGBySort; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSNOTLISTTAGTable, TTTSNOTLISTTAGBuffer ] ); end; { Register } function TTTSNOTLISTTAGBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..6] of string = ('CIFFLAG','LOANNUM','TRACKCODE','CATEGORYSUB','SEPARATEBY','SORTBY' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 6) and (flist[x] <> s) do inc(x); if x <= 6 then result := x else result := 0; end; function TTTSNOTLISTTAGBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftString; 6 : result := ftString; end; end; function TTTSNOTLISTTAGBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCifFlag; 2 : result := @Data.PLoanNum; 3 : result := @Data.PTrackCode; 4 : result := @Data.PCategorySub; 5 : result := @Data.PSeparateBy; 6 : result := @Data.PSortBy; end; end; end.
unit AdvCardListAdvEditLink; interface uses Classes, Spin, Controls, AdvCardList, AdvEdit, Forms, Graphics; type { TAdvCardListSpinEditLink } TAdvCardListAdvEditLink = class(TCardListEditLink) private FAdvEdit: TAdvEdit; FEditType: TAdvEditType; FShowModified: Boolean; FModifiedColor: TColor; FMaxLength: Integer; FPrecision: Integer; FPrefix, FSuffix: string; FLookup: TLookupSettings; procedure SetLookup(const Value: TLookupSettings); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function CreateControl: TWinControl; override; procedure SetProperties; override; procedure SetSelection(SelStart, SelLength: integer); override; procedure SetFocus; override; procedure ValueToControl(value: variant); override; function ControlToValue: variant; override; published property EditType: TAdvEditType read FEditType write FEditType; property Lookup: TLookupSettings read FLookup write SetLookup; property MaxLength: Integer read FMaxLength write FMaxLength default 0; property ModifiedColor: TColor read FModifiedColor write FModifiedColor default clRed; property Precision: Integer read FPrecision write FPrecision default 0; property Prefix: string read FPrefix write FPrefix; property ShowModified: Boolean read FShowModified write FShowModified default false; property Suffix: string read FSuffix write FSuffix; end; procedure Register; implementation procedure Register; begin RegisterComponents('TMS CardList', [TAdvCardListAdvEditLink]); end; { TCardListSpinEditLink } function TAdvCardListAdvEditLink.ControlToValue: variant; begin Result := FAdvEdit.Text; end; constructor TAdvCardListAdvEditLink.Create(AOwner: TComponent); begin inherited; FShowModified := false; FModifiedColor := clRed; FMaxLength := 0; FLookup := TLookupSettings.Create; end; function TAdvCardListAdvEditLink.CreateControl: TWinControl; begin FAdvEdit := TAdvEdit.Create(nil); Result := FAdvEdit; end; destructor TAdvCardListAdvEditLink.Destroy; begin FLookup.Free; inherited; end; procedure TAdvCardListAdvEditLink.SetFocus; begin FAdvEdit.SetFocus; end; procedure TAdvCardListAdvEditLink.SetLookup(const Value: TLookupSettings); begin FLookup.Assign(Value); end; procedure TAdvCardListAdvEditLink.SetProperties; begin inherited; FAdvEdit.OnKeyDown := ControlKeyDown; FAdvEdit.EditType := FEditType; FAdvEdit.BorderStyle := bsNone; FAdvEdit.ShowModified := FShowModified; FAdvEdit.ModifiedColor := FModifiedColor; FAdvEdit.MaxLength := FMaxLength; FAdvEdit.Prefix := FPrefix; FAdvEdit.Suffix := FSuffix; FAdvEdit.Precision := FPrecision; FAdvEdit.Lookup.Assign(FLookup); end; procedure TAdvCardListAdvEditLink.SetSelection(SelStart, SelLength: integer); begin FAdvEdit.SelStart := SelStart; FAdvEdit.SelLength := SelLength; end; procedure TAdvCardListAdvEditLink.ValueToControl(value: variant); begin FAdvEdit.Text := value; end; end.
Unit mte.component.network; {----------------------------------------------------------} { Developed by Muhammad Ajmal p } { ajumalp@gmail.com } { pajmal@hotmail.com } { ajmal@erratums.com } {----------------------------------------------------------} {$mode objfpc}{$H+} Interface Uses Classes, SysUtils, fphttpclient, fphttp, fphttpserver; Type { TMTEHTTPServerThread } TMTEHTTPServerThread = Class(TThread) Strict Private FOnExecute: TNotifyEvent; Public Constructor Create; Reintroduce; Destructor Destroy; Override; Procedure Execute; Override; Property Terminated; Property OnExecute: TNotifyEvent Read FOnExecute Write FOnExecute; End; { TMTEHttpClient } TMTEHttpClient = Class(TFPCustomHttpServer) Strict Private FCanExecute: Boolean; FServerThread: TMTEHTTPServerThread; Procedure DoOnExecute(aSender: TObject); Procedure DoOnTerminate(aSender: TObject); Public Constructor Create(aOwner: TComponent); Override; Destructor Destroy; Override; Procedure StopServer; Procedure StartServer; Published Property Active; Property Port; Property QueueSize; Property OnAllowConnect; Property Threaded; Property OnRequest; Property OnRequestError; Property OnAcceptIdle; End; TMTEHttpServer = Class(TFPHttpServer) End; Implementation { TMTEHttpClient } Procedure TMTEHttpClient.DoOnExecute(aSender: TObject); Begin If FCanExecute Then Active := True; End; Procedure TMTEHttpClient.DoOnTerminate(aSender: TObject); Begin FServerThread := Nil; End; Constructor TMTEHttpClient.Create(aOwner: TComponent); Begin Inherited Create(aOwner); // Set a time out to deactivate server { Ajmal } AcceptIdleTimeout := 1; Threaded := True; FCanExecute := False; End; Destructor TMTEHttpClient.Destroy; Begin FCanExecute := False; StopServer; If Assigned(FServerThread) Then Begin FServerThread.FreeOnTerminate := False; FServerThread.Free; End; Threaded := False; Inherited Destroy; End; Procedure TMTEHttpClient.StopServer; Begin If Not Active Then Exit; Try Active := False; Except If Active Then Raise; // Do nothing here { Ajaml } End; End; Procedure TMTEHttpClient.StartServer; Begin If Active Then Exit; FCanExecute := False; Try If Not Assigned(FServerThread) Then Begin FServerThread := TMTEHTTPServerThread.Create; FServerThread.OnTerminate := @DoOnTerminate; FServerThread.FreeOnTerminate := True; FServerThread.OnExecute := @DoOnExecute; End; Finally FCanExecute := True; End; FServerThread.Start; End; { TMTEHTTPServerThread } Constructor TMTEHTTPServerThread.Create; Begin Inherited Create(True); FOnExecute := Nil; End; Destructor TMTEHTTPServerThread.Destroy; Begin Inherited Destroy; End; Procedure TMTEHTTPServerThread.Execute; Begin If Assigned(FOnExecute) Then FOnExecute(Self); End; End.
unit Controller.Vendas; interface uses Controller.Interfaces, Model.Interfaces, Controller.Observer.Interfaces; type TControllerVendas = class(TInterfacedObject, iControllerVenda) private FItem : iControllerItens; FModel : iModelVenda; FObserverItem : iSubjectItem; public constructor Create; destructor Destroy; override; class function New : iControllerVenda; function Item : iControllerItens; function Model : iModelVenda; function ObserverItem : iSubjectItem; end; implementation uses Controller.Item, Model.Venda, Controller.Observer.Item; constructor TControllerVendas.Create; begin FModel := TModelVenda.New; FObserverItem := TControllerObserverItem.New; FItem := TControllerItem.New(Self); FModel.ObserverItem(FObserverItem); end; destructor TControllerVendas.Destroy; begin inherited; end; function TControllerVendas.Item: iControllerItens; begin Result := FItem; end; function TControllerVendas.Model: iModelVenda; begin Result := FModel; end; class function TControllerVendas.New : iControllerVenda; begin Result := Self.Create; end; function TControllerVendas.ObserverItem: iSubjectItem; begin Result := FObserverItem; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, Androidapi.JNI.BluetoothAdapter, Androidapi.JNI.JavaTypes, Androidapi.JNIBridge, FMX.ListBox, FMX.Layouts, FMX.Memo, FMX.Edit, FMX.Objects, FMX.ListView.Types, FMX.ListView, System.Rtti, FMX.Grid, Data.Bind.GenData, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.ObjectScope; type TForm1 = class(TForm) reload: TButton; Label1: TLabel; ListView1: TListView; procedure FormShow(Sender: TObject); procedure ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); private { private declarations } public { public declarations } targetMACAddress:string; // MAC address of selected device ostream:JOutputStream; istream:JInputstream; uid:JUUID; // UUID for SPP traffic Sock:JBluetoothSocket; Adapter:JBluetoothAdapter; // Local BLUETOOTH adapter remoteDevice:JBluetoothDevice; end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.FormShow(Sender: TObject); var s:string; i:integer; list:TStringList; begin list:=TStringList.Create; s:=checkBluetooth; // Make sure bluetooth is enabled if pos('disabled',s)<>0 then begin ShowMessage('Please turn on Bluetooth :D and Retry'); exit end; // This is the well known SPP UUID for connection to a Bluetooth serial device uid:=TJUUID.JavaClass.fromString(stringtojstring('00001101-0000-1000-8000-00805F9B34FB')); list.Clear; list.AddStrings(getbonded); // produce a list of bonded/paired devices listview1.Items.Clear; // clear list and rebuild it listview1.BeginUpdate; for i := 0 to list.Count-1 do begin listview1.Items.Add; listview1.Items.Item[i].Text:=list[i].Split(['='])[0]; listview1.Items.Item[i].Detail:=list[i].Split(['='])[1]; end; listview1.EndUpdate end; procedure TForm1.ListView1ItemClick(const Sender: TObject; const AItem: TListViewItem); begin ShowMessage('You selected: '+Aitem.Text); // depending on the bluetooth device selected - do something with it targetMACAddress:=Aitem.Detail; if trim(targetMACAddress)='' then exit; Adapter:=TJBluetoothAdapter.JavaClass.getDefaultAdapter; remoteDevice:=Adapter.getRemoteDevice(stringtojstring(targetMACAddress)); sock:=remoteDevice.createRfcommSocketToServiceRecord(UID); try sock.connect; except ShowMessage('Could not connect to BlueTooth device'); end; if not sock.isConnected then begin ShowMessage('Failed to connect to Try again...'); exit; end; listview1.Visible:=false; // hide the chooser label1.Visible:=false; // hide the chooser reload.Visible:=false; // hide the chooser end; end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : C:\clientes\AFIP - Factura electronica\MTXCAService.xml // >Import : C:\clientes\AFIP - Factura electronica\MTXCAService.xml:0 // Encoding : UTF-8 // Version : 1.0 // (23/12/2010 15:18:17 - - $Rev: 7300 $) // ************************************************************************ // unit MTXCAService; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; const IS_OPTN = $0001; IS_UNBD = $0002; IS_UNQL = $0008; 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. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:long - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:short - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:int - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:date - "http://www.w3.org/2001/XMLSchema"[Gbl] // !:decimal - "http://www.w3.org/2001/XMLSchema"[Gbl] DummyResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ExceptionResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Flt][GblCplx] } AutorizarComprobanteRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } AuthRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ComprobanteAsociadoType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } AutorizarComprobanteResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } CodigoDescripcionType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } SolicitarCAEARequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } SolicitudCAEAType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } SolicitarCAEAResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } InformarComprobanteCAEARequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarUltimoComprobanteAutorizadoRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultaUltimoComprobanteAutorizadoRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } InformarComprobanteCAEAResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } CAEAResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ComprobanteCAEResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ComprobanteCAEAResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ConsultarTiposComprobanteRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarPuntosVentaCAEARequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarComprobanteRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultaComprobanteRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ConsultarPuntosVentaRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarAlicuotasIVARequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarCondicionesIVARequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarCotizacionMonedaRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarMonedasRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarTiposDocumentoRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarUnidadesMedidaRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarUltimoComprobanteAutorizadoResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarTiposComprobanteResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarTiposDocumentoResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarAlicuotasIVAResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarCondicionesIVAResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarUnidadesMedidaResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarMonedasResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } CodigoDescripcionStringType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ConsultarComprobanteResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ItemType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } SubtotalIVAType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } OtroTributoType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ComprobanteType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ConsultarPuntosVentaResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } PuntoVentaType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ConsultarCotizacionMonedaResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarPuntosVentaCAERequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } InformarCAEANoUtilizadoRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } InformarCAEANoUtilizadoResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarTiposTributoRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarTiposTributoResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } InformarCAEANoUtilizadoPtoVtaRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } InformarCAEANoUtilizadoPtoVtaResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarCAEARequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarCAEAResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarPtosVtaCAEANoInformadosRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarPtosVtaCAEANoInformadosResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarCAEAEntreFechasRequestType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } ConsultarCAEAEntreFechasResponseType = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblCplx] } dummyResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } exceptionResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Flt][GblElm] } autorizarComprobanteResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } autorizarComprobanteRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } solicitarCAEAResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } solicitarCAEARequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } informarComprobanteCAEAResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarUltimoComprobanteAutorizadoResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } informarComprobanteCAEARequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarUltimoComprobanteAutorizadoRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarPuntosVentaCAEAResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarPuntosVentaRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarPuntosVentaCAEARequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarTiposComprobanteResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarTiposComprobanteRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarComprobanteResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarComprobanteRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarTiposDocumentoRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarTiposDocumentoResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarAlicuotasIVARequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarAlicuotasIVAResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarCondicionesIVARequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarCondicionesIVAResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarMonedasRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarMonedasResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarCotizacionMonedaRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarCotizacionMonedaResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarUnidadesMedidaRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarUnidadesMedidaResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarPuntosVentaResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarPuntosVentaCAERequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarPuntosVentaCAEResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } informarCAEANoUtilizadoResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } informarCAEANoUtilizadoRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarTiposTributoResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarTiposTributoRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } informarCAEANoUtilizadoPtoVtaRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } informarCAEANoUtilizadoPtoVtaResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarCAEARequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarCAEAResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarPtosVtaCAEANoInformadosRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarPtosVtaCAEANoInformadosResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarCAEAEntreFechasRequest = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } consultarCAEAEntreFechasResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Lit][GblElm] } comprobanteAsociado = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Alias] } otroTributo = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Alias] } item = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Alias] } subtotalIVA = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Alias] } codigoDescripcion = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Alias] } codigoDescripcion2 = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Alias] } puntoVenta = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Alias] } CAEAResponse = class; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[Alias] } { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblSmpl] } ResultadoSimpleType = (A, O, R); { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblSmpl] } CodigoTipoAutorizacionSimpleType = (A2, E); { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblSmpl] } SiNoSimpleType = (S, N); // ************************************************************************ // // XML : DummyResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // DummyResponseType = class(TRemotable) private Fappserver: WideString; Fauthserver: WideString; Fdbserver: WideString; public constructor Create; override; published property appserver: WideString Index (IS_UNQL) read Fappserver write Fappserver; property authserver: WideString Index (IS_UNQL) read Fauthserver write Fauthserver; property dbserver: WideString Index (IS_UNQL) read Fdbserver write Fdbserver; end; // ************************************************************************ // // XML : ExceptionResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Fault // ************************************************************************ // ExceptionResponseType = class(ERemotableException) private Fexception: WideString; Fexception_Specified: boolean; procedure Setexception(Index: Integer; const AWideString: WideString); function exception_Specified(Index: Integer): boolean; published property exception: WideString Index (IS_OPTN or IS_UNQL) read Fexception write Setexception stored exception_Specified; end; // ************************************************************************ // // XML : AutorizarComprobanteRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // AutorizarComprobanteRequestType = class(TRemotable) private FauthRequest: AuthRequestType; FcomprobanteCAERequest: ComprobanteType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property comprobanteCAERequest: ComprobanteType Index (IS_UNQL) read FcomprobanteCAERequest write FcomprobanteCAERequest; end; // ************************************************************************ // // XML : AuthRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // AuthRequestType = class(TRemotable) private Ftoken: WideString; Fsign: WideString; FcuitRepresentada: Int64; published property token: WideString Index (IS_UNQL) read Ftoken write Ftoken; property sign: WideString Index (IS_UNQL) read Fsign write Fsign; property cuitRepresentada: Int64 Index (IS_UNQL) read FcuitRepresentada write FcuitRepresentada; end; ArrayComprobantesAsociadosType = array of comprobanteAsociado; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } NumeroPuntoVentaSimpleType = type Smallint; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblSmpl] } NumeroComprobanteSimpleType = type Int64; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblSmpl] } // ************************************************************************ // // XML : ComprobanteAsociadoType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // ComprobanteAsociadoType = class(TRemotable) private FcodigoTipoComprobante: Smallint; FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; FnumeroComprobante: NumeroComprobanteSimpleType; published property codigoTipoComprobante: Smallint Index (IS_UNQL) read FcodigoTipoComprobante write FcodigoTipoComprobante; property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; property numeroComprobante: NumeroComprobanteSimpleType Index (IS_UNQL) read FnumeroComprobante write FnumeroComprobante; end; ArrayOtrosTributosType = array of otroTributo; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ArrayItemsType = array of item; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ArraySubtotalesIVAType = array of subtotalIVA; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } ArrayCodigosDescripcionesType = array of codigoDescripcion; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } // ************************************************************************ // // XML : AutorizarComprobanteResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // AutorizarComprobanteResponseType = class(TRemotable) private Fresultado: ResultadoSimpleType; FcomprobanteResponse: ComprobanteCAEResponseType; FcomprobanteResponse_Specified: boolean; FarrayObservaciones: ArrayCodigosDescripcionesType; FarrayObservaciones_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetcomprobanteResponse(Index: Integer; const AComprobanteCAEResponseType: ComprobanteCAEResponseType); function comprobanteResponse_Specified(Index: Integer): boolean; procedure SetarrayObservaciones(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayObservaciones_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property resultado: ResultadoSimpleType Index (IS_UNQL) read Fresultado write Fresultado; property comprobanteResponse: ComprobanteCAEResponseType Index (IS_OPTN or IS_UNQL) read FcomprobanteResponse write SetcomprobanteResponse stored comprobanteResponse_Specified; property arrayObservaciones: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayObservaciones write SetarrayObservaciones stored arrayObservaciones_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : CodigoDescripcionType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // CodigoDescripcionType = class(TRemotable) private Fcodigo: Smallint; Fdescripcion: WideString; published property codigo: Smallint Index (IS_UNQL) read Fcodigo write Fcodigo; property descripcion: WideString Index (IS_UNQL) read Fdescripcion write Fdescripcion; end; // ************************************************************************ // // XML : SolicitarCAEARequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // SolicitarCAEARequestType = class(TRemotable) private FauthRequest: AuthRequestType; FsolicitudCAEA: SolicitudCAEAType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property solicitudCAEA: SolicitudCAEAType Index (IS_UNQL) read FsolicitudCAEA write FsolicitudCAEA; end; // ************************************************************************ // // XML : SolicitudCAEAType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // SolicitudCAEAType = class(TRemotable) private Fperiodo: Integer; Forden: Smallint; published property periodo: Integer Index (IS_UNQL) read Fperiodo write Fperiodo; property orden: Smallint Index (IS_UNQL) read Forden write Forden; end; // ************************************************************************ // // XML : SolicitarCAEAResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // SolicitarCAEAResponseType = class(TRemotable) private FCAEAResponse: CAEAResponseType; FCAEAResponse_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetCAEAResponse(Index: Integer; const ACAEAResponseType: CAEAResponseType); function CAEAResponse_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property CAEAResponse: CAEAResponseType Index (IS_OPTN or IS_UNQL) read FCAEAResponse write SetCAEAResponse stored CAEAResponse_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : InformarComprobanteCAEARequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // InformarComprobanteCAEARequestType = class(TRemotable) private FauthRequest: AuthRequestType; FcomprobanteCAEARequest: ComprobanteType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property comprobanteCAEARequest: ComprobanteType Index (IS_UNQL) read FcomprobanteCAEARequest write FcomprobanteCAEARequest; end; // ************************************************************************ // // XML : ConsultarUltimoComprobanteAutorizadoRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarUltimoComprobanteAutorizadoRequestType = class(TRemotable) private FauthRequest: AuthRequestType; FconsultaUltimoComprobanteAutorizadoRequest: ConsultaUltimoComprobanteAutorizadoRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property consultaUltimoComprobanteAutorizadoRequest: ConsultaUltimoComprobanteAutorizadoRequestType Index (IS_UNQL) read FconsultaUltimoComprobanteAutorizadoRequest write FconsultaUltimoComprobanteAutorizadoRequest; end; // ************************************************************************ // // XML : ConsultaUltimoComprobanteAutorizadoRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // ConsultaUltimoComprobanteAutorizadoRequestType = class(TRemotable) private FcodigoTipoComprobante: Smallint; FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; published property codigoTipoComprobante: Smallint Index (IS_UNQL) read FcodigoTipoComprobante write FcodigoTipoComprobante; property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; end; // ************************************************************************ // // XML : InformarComprobanteCAEAResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // InformarComprobanteCAEAResponseType = class(TRemotable) private Fresultado: ResultadoSimpleType; FfechaProceso: TXSDate; FcomprobanteCAEAResponse: ComprobanteCAEAResponseType; FcomprobanteCAEAResponse_Specified: boolean; FarrayObservaciones: ArrayCodigosDescripcionesType; FarrayObservaciones_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetcomprobanteCAEAResponse(Index: Integer; const AComprobanteCAEAResponseType: ComprobanteCAEAResponseType); function comprobanteCAEAResponse_Specified(Index: Integer): boolean; procedure SetarrayObservaciones(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayObservaciones_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property resultado: ResultadoSimpleType Index (IS_UNQL) read Fresultado write Fresultado; property fechaProceso: TXSDate Index (IS_UNQL) read FfechaProceso write FfechaProceso; property comprobanteCAEAResponse: ComprobanteCAEAResponseType Index (IS_OPTN or IS_UNQL) read FcomprobanteCAEAResponse write SetcomprobanteCAEAResponse stored comprobanteCAEAResponse_Specified; property arrayObservaciones: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayObservaciones write SetarrayObservaciones stored arrayObservaciones_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : CAEAResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // CAEAResponseType = class(TRemotable) private FfechaProceso: TXSDate; FCAEA: Int64; Fperiodo: Integer; Forden: Smallint; FfechaDesde: TXSDate; FfechaHasta: TXSDate; FfechaTopeInforme: TXSDate; public destructor Destroy; override; published property fechaProceso: TXSDate Index (IS_UNQL) read FfechaProceso write FfechaProceso; property CAEA: Int64 Index (IS_UNQL) read FCAEA write FCAEA; property periodo: Integer Index (IS_UNQL) read Fperiodo write Fperiodo; property orden: Smallint Index (IS_UNQL) read Forden write Forden; property fechaDesde: TXSDate Index (IS_UNQL) read FfechaDesde write FfechaDesde; property fechaHasta: TXSDate Index (IS_UNQL) read FfechaHasta write FfechaHasta; property fechaTopeInforme: TXSDate Index (IS_UNQL) read FfechaTopeInforme write FfechaTopeInforme; end; // ************************************************************************ // // XML : ComprobanteCAEResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // ComprobanteCAEResponseType = class(TRemotable) private Fcuit: Int64; FcodigoTipoComprobante: Smallint; FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; FnumeroComprobante: NumeroComprobanteSimpleType; FfechaEmision: TXSDate; FCAE: Int64; FfechaVencimientoCAE: TXSDate; public destructor Destroy; override; published property cuit: Int64 Index (IS_UNQL) read Fcuit write Fcuit; property codigoTipoComprobante: Smallint Index (IS_UNQL) read FcodigoTipoComprobante write FcodigoTipoComprobante; property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; property numeroComprobante: NumeroComprobanteSimpleType Index (IS_UNQL) read FnumeroComprobante write FnumeroComprobante; property fechaEmision: TXSDate Index (IS_UNQL) read FfechaEmision write FfechaEmision; property CAE: Int64 Index (IS_UNQL) read FCAE write FCAE; property fechaVencimientoCAE: TXSDate Index (IS_UNQL) read FfechaVencimientoCAE write FfechaVencimientoCAE; end; // ************************************************************************ // // XML : ComprobanteCAEAResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // ComprobanteCAEAResponseType = class(TRemotable) private FCAEA: Int64; FcodigoTipoComprobante: Smallint; FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; FnumeroComprobante: NumeroComprobanteSimpleType; published property CAEA: Int64 Index (IS_UNQL) read FCAEA write FCAEA; property codigoTipoComprobante: Smallint Index (IS_UNQL) read FcodigoTipoComprobante write FcodigoTipoComprobante; property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; property numeroComprobante: NumeroComprobanteSimpleType Index (IS_UNQL) read FnumeroComprobante write FnumeroComprobante; end; // ************************************************************************ // // XML : ConsultarTiposComprobanteRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarTiposComprobanteRequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarPuntosVentaCAEARequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarPuntosVentaCAEARequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarComprobanteRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarComprobanteRequestType = class(TRemotable) private FauthRequest: AuthRequestType; FconsultaComprobanteRequest: ConsultaComprobanteRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property consultaComprobanteRequest: ConsultaComprobanteRequestType Index (IS_UNQL) read FconsultaComprobanteRequest write FconsultaComprobanteRequest; end; // ************************************************************************ // // XML : ConsultaComprobanteRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // ConsultaComprobanteRequestType = class(TRemotable) private FcodigoTipoComprobante: Smallint; FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; FnumeroComprobante: NumeroComprobanteSimpleType; published property codigoTipoComprobante: Smallint Index (IS_UNQL) read FcodigoTipoComprobante write FcodigoTipoComprobante; property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; property numeroComprobante: NumeroComprobanteSimpleType Index (IS_UNQL) read FnumeroComprobante write FnumeroComprobante; end; // ************************************************************************ // // XML : ConsultarPuntosVentaRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarPuntosVentaRequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarAlicuotasIVARequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarAlicuotasIVARequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarCondicionesIVARequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarCondicionesIVARequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarCotizacionMonedaRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarCotizacionMonedaRequestType = class(TRemotable) private FauthRequest: AuthRequestType; FcodigoMoneda: WideString; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property codigoMoneda: WideString Index (IS_UNQL) read FcodigoMoneda write FcodigoMoneda; end; // ************************************************************************ // // XML : ConsultarMonedasRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarMonedasRequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarTiposDocumentoRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarTiposDocumentoRequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarUnidadesMedidaRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarUnidadesMedidaRequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarUltimoComprobanteAutorizadoResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarUltimoComprobanteAutorizadoResponseType = class(TRemotable) private FnumeroComprobante: NumeroComprobanteSimpleType; FnumeroComprobante_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetnumeroComprobante(Index: Integer; const ANumeroComprobanteSimpleType: NumeroComprobanteSimpleType); function numeroComprobante_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property numeroComprobante: NumeroComprobanteSimpleType Index (IS_OPTN or IS_UNQL) read FnumeroComprobante write SetnumeroComprobante stored numeroComprobante_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarTiposComprobanteResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarTiposComprobanteResponseType = class(TRemotable) private FarrayTiposComprobante: ArrayCodigosDescripcionesType; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayTiposComprobante: ArrayCodigosDescripcionesType Index (IS_UNQL) read FarrayTiposComprobante write FarrayTiposComprobante; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarTiposDocumentoResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarTiposDocumentoResponseType = class(TRemotable) private FarrayTiposDocumento: ArrayCodigosDescripcionesType; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayTiposDocumento: ArrayCodigosDescripcionesType Index (IS_UNQL) read FarrayTiposDocumento write FarrayTiposDocumento; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarAlicuotasIVAResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarAlicuotasIVAResponseType = class(TRemotable) private FarrayAlicuotasIVA: ArrayCodigosDescripcionesType; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayAlicuotasIVA: ArrayCodigosDescripcionesType Index (IS_UNQL) read FarrayAlicuotasIVA write FarrayAlicuotasIVA; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarCondicionesIVAResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarCondicionesIVAResponseType = class(TRemotable) private FarrayCondicionesIVA: ArrayCodigosDescripcionesType; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayCondicionesIVA: ArrayCodigosDescripcionesType Index (IS_UNQL) read FarrayCondicionesIVA write FarrayCondicionesIVA; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarUnidadesMedidaResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarUnidadesMedidaResponseType = class(TRemotable) private FarrayUnidadesMedida: ArrayCodigosDescripcionesType; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayUnidadesMedida: ArrayCodigosDescripcionesType Index (IS_UNQL) read FarrayUnidadesMedida write FarrayUnidadesMedida; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; ArrayCodigosDescripcionesStringType = array of codigoDescripcion2; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } // ************************************************************************ // // XML : ConsultarMonedasResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarMonedasResponseType = class(TRemotable) private FarrayMonedas: ArrayCodigosDescripcionesStringType; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayMonedas: ArrayCodigosDescripcionesStringType Index (IS_UNQL) read FarrayMonedas write FarrayMonedas; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : CodigoDescripcionStringType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // CodigoDescripcionStringType = class(TRemotable) private Fcodigo: WideString; Fdescripcion: WideString; published property codigo: WideString Index (IS_UNQL) read Fcodigo write Fcodigo; property descripcion: WideString Index (IS_UNQL) read Fdescripcion write Fdescripcion; end; // ************************************************************************ // // XML : ConsultarComprobanteResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarComprobanteResponseType = class(TRemotable) private Fcomprobante: ComprobanteType; Fcomprobante_Specified: boolean; FarrayObservaciones: ArrayCodigosDescripcionesType; FarrayObservaciones_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setcomprobante(Index: Integer; const AComprobanteType: ComprobanteType); function comprobante_Specified(Index: Integer): boolean; procedure SetarrayObservaciones(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayObservaciones_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property comprobante: ComprobanteType Index (IS_OPTN or IS_UNQL) read Fcomprobante write Setcomprobante stored comprobante_Specified; property arrayObservaciones: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayObservaciones write SetarrayObservaciones stored arrayObservaciones_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; ImporteSubtotalSimpleType = TXSDecimal; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblSmpl] } DecimalSimpleType = TXSDecimal; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblSmpl] } // ************************************************************************ // // XML : ItemType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // ItemType = class(TRemotable) private FunidadesMtx: Integer; FunidadesMtx_Specified: boolean; FcodigoMtx: WideString; FcodigoMtx_Specified: boolean; Fcodigo: WideString; Fcodigo_Specified: boolean; Fdescripcion: WideString; Fcantidad: DecimalSimpleType; Fcantidad_Specified: boolean; FcodigoUnidadMedida: Smallint; FprecioUnitario: DecimalSimpleType; FprecioUnitario_Specified: boolean; FimporteBonificacion: DecimalSimpleType; FimporteBonificacion_Specified: boolean; FcodigoCondicionIVA: Smallint; FimporteIVA: ImporteSubtotalSimpleType; FimporteIVA_Specified: boolean; FimporteItem: ImporteSubtotalSimpleType; procedure SetunidadesMtx(Index: Integer; const AInteger: Integer); function unidadesMtx_Specified(Index: Integer): boolean; procedure SetcodigoMtx(Index: Integer; const AWideString: WideString); function codigoMtx_Specified(Index: Integer): boolean; procedure Setcodigo(Index: Integer; const AWideString: WideString); function codigo_Specified(Index: Integer): boolean; procedure Setcantidad(Index: Integer; const ADecimalSimpleType: DecimalSimpleType); function cantidad_Specified(Index: Integer): boolean; procedure SetprecioUnitario(Index: Integer; const ADecimalSimpleType: DecimalSimpleType); function precioUnitario_Specified(Index: Integer): boolean; procedure SetimporteBonificacion(Index: Integer; const ADecimalSimpleType: DecimalSimpleType); function importeBonificacion_Specified(Index: Integer): boolean; procedure SetimporteIVA(Index: Integer; const AImporteSubtotalSimpleType: ImporteSubtotalSimpleType); function importeIVA_Specified(Index: Integer): boolean; public destructor Destroy; override; published property unidadesMtx: Integer Index (IS_OPTN or IS_UNQL) read FunidadesMtx write SetunidadesMtx stored unidadesMtx_Specified; property codigoMtx: WideString Index (IS_OPTN or IS_UNQL) read FcodigoMtx write SetcodigoMtx stored codigoMtx_Specified; property codigo: WideString Index (IS_OPTN or IS_UNQL) read Fcodigo write Setcodigo stored codigo_Specified; property descripcion: WideString Index (IS_UNQL) read Fdescripcion write Fdescripcion; property cantidad: DecimalSimpleType Index (IS_OPTN or IS_UNQL) read Fcantidad write Setcantidad stored cantidad_Specified; property codigoUnidadMedida: Smallint Index (IS_UNQL) read FcodigoUnidadMedida write FcodigoUnidadMedida; property precioUnitario: DecimalSimpleType Index (IS_OPTN or IS_UNQL) read FprecioUnitario write SetprecioUnitario stored precioUnitario_Specified; property importeBonificacion: DecimalSimpleType Index (IS_OPTN or IS_UNQL) read FimporteBonificacion write SetimporteBonificacion stored importeBonificacion_Specified; property codigoCondicionIVA: Smallint Index (IS_UNQL) read FcodigoCondicionIVA write FcodigoCondicionIVA; property importeIVA: ImporteSubtotalSimpleType Index (IS_OPTN or IS_UNQL) read FimporteIVA write SetimporteIVA stored importeIVA_Specified; property importeItem: ImporteSubtotalSimpleType Index (IS_UNQL) read FimporteItem write FimporteItem; end; ImporteTotalSimpleType = TXSDecimal; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblSmpl] } // ************************************************************************ // // XML : SubtotalIVAType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // SubtotalIVAType = class(TRemotable) private Fcodigo: Smallint; Fimporte: ImporteTotalSimpleType; public destructor Destroy; override; published property codigo: Smallint Index (IS_UNQL) read Fcodigo write Fcodigo; property importe: ImporteTotalSimpleType Index (IS_UNQL) read Fimporte write Fimporte; end; // ************************************************************************ // // XML : OtroTributoType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // OtroTributoType = class(TRemotable) private Fcodigo: Smallint; Fdescripcion: WideString; Fdescripcion_Specified: boolean; FbaseImponible: ImporteTotalSimpleType; Fimporte: ImporteTotalSimpleType; procedure Setdescripcion(Index: Integer; const AWideString: WideString); function descripcion_Specified(Index: Integer): boolean; public destructor Destroy; override; published property codigo: Smallint Index (IS_UNQL) read Fcodigo write Fcodigo; property descripcion: WideString Index (IS_OPTN or IS_UNQL) read Fdescripcion write Setdescripcion stored descripcion_Specified; property baseImponible: ImporteTotalSimpleType Index (IS_UNQL) read FbaseImponible write FbaseImponible; property importe: ImporteTotalSimpleType Index (IS_UNQL) read Fimporte write Fimporte; end; // ************************************************************************ // // XML : ComprobanteType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // ComprobanteType = class(TRemotable) private FcodigoTipoComprobante: Smallint; FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; FnumeroComprobante: NumeroComprobanteSimpleType; FfechaEmision: TXSDate; FfechaEmision_Specified: boolean; FcodigoTipoAutorizacion: CodigoTipoAutorizacionSimpleType; FcodigoTipoAutorizacion_Specified: boolean; FcodigoAutorizacion: Int64; FcodigoAutorizacion_Specified: boolean; FfechaVencimiento: TXSDate; FfechaVencimiento_Specified: boolean; FcodigoTipoDocumento: Smallint; FcodigoTipoDocumento_Specified: boolean; FnumeroDocumento: Int64; FnumeroDocumento_Specified: boolean; FimporteGravado: ImporteTotalSimpleType; FimporteGravado_Specified: boolean; FimporteNoGravado: ImporteTotalSimpleType; FimporteNoGravado_Specified: boolean; FimporteExento: ImporteTotalSimpleType; FimporteExento_Specified: boolean; FimporteSubtotal: ImporteTotalSimpleType; FimporteOtrosTributos: ImporteTotalSimpleType; FimporteOtrosTributos_Specified: boolean; FimporteTotal: ImporteTotalSimpleType; FcodigoMoneda: WideString; FcotizacionMoneda: TXSDecimal; Fobservaciones: WideString; Fobservaciones_Specified: boolean; FcodigoConcepto: Smallint; FfechaServicioDesde: TXSDate; FfechaServicioDesde_Specified: boolean; FfechaServicioHasta: TXSDate; FfechaServicioHasta_Specified: boolean; FfechaVencimientoPago: TXSDate; FfechaVencimientoPago_Specified: boolean; FarrayComprobantesAsociados: ArrayComprobantesAsociadosType; FarrayComprobantesAsociados_Specified: boolean; FarrayOtrosTributos: ArrayOtrosTributosType; FarrayOtrosTributos_Specified: boolean; FarrayItems: ArrayItemsType; FarraySubtotalesIVA: ArraySubtotalesIVAType; FarraySubtotalesIVA_Specified: boolean; procedure SetfechaEmision(Index: Integer; const ATXSDate: TXSDate); function fechaEmision_Specified(Index: Integer): boolean; procedure SetcodigoTipoAutorizacion(Index: Integer; const ACodigoTipoAutorizacionSimpleType: CodigoTipoAutorizacionSimpleType); function codigoTipoAutorizacion_Specified(Index: Integer): boolean; procedure SetcodigoAutorizacion(Index: Integer; const AInt64: Int64); function codigoAutorizacion_Specified(Index: Integer): boolean; procedure SetfechaVencimiento(Index: Integer; const ATXSDate: TXSDate); function fechaVencimiento_Specified(Index: Integer): boolean; procedure SetcodigoTipoDocumento(Index: Integer; const ASmallint: Smallint); function codigoTipoDocumento_Specified(Index: Integer): boolean; procedure SetnumeroDocumento(Index: Integer; const AInt64: Int64); function numeroDocumento_Specified(Index: Integer): boolean; procedure SetimporteGravado(Index: Integer; const AImporteTotalSimpleType: ImporteTotalSimpleType); function importeGravado_Specified(Index: Integer): boolean; procedure SetimporteNoGravado(Index: Integer; const AImporteTotalSimpleType: ImporteTotalSimpleType); function importeNoGravado_Specified(Index: Integer): boolean; procedure SetimporteExento(Index: Integer; const AImporteTotalSimpleType: ImporteTotalSimpleType); function importeExento_Specified(Index: Integer): boolean; procedure SetimporteOtrosTributos(Index: Integer; const AImporteTotalSimpleType: ImporteTotalSimpleType); function importeOtrosTributos_Specified(Index: Integer): boolean; procedure Setobservaciones(Index: Integer; const AWideString: WideString); function observaciones_Specified(Index: Integer): boolean; procedure SetfechaServicioDesde(Index: Integer; const ATXSDate: TXSDate); function fechaServicioDesde_Specified(Index: Integer): boolean; procedure SetfechaServicioHasta(Index: Integer; const ATXSDate: TXSDate); function fechaServicioHasta_Specified(Index: Integer): boolean; procedure SetfechaVencimientoPago(Index: Integer; const ATXSDate: TXSDate); function fechaVencimientoPago_Specified(Index: Integer): boolean; procedure SetarrayComprobantesAsociados(Index: Integer; const AArrayComprobantesAsociadosType: ArrayComprobantesAsociadosType); function arrayComprobantesAsociados_Specified(Index: Integer): boolean; procedure SetarrayOtrosTributos(Index: Integer; const AArrayOtrosTributosType: ArrayOtrosTributosType); function arrayOtrosTributos_Specified(Index: Integer): boolean; procedure SetarraySubtotalesIVA(Index: Integer; const AArraySubtotalesIVAType: ArraySubtotalesIVAType); function arraySubtotalesIVA_Specified(Index: Integer): boolean; public destructor Destroy; override; published property codigoTipoComprobante: Smallint Index (IS_UNQL) read FcodigoTipoComprobante write FcodigoTipoComprobante; property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; property numeroComprobante: NumeroComprobanteSimpleType Index (IS_UNQL) read FnumeroComprobante write FnumeroComprobante; property fechaEmision: TXSDate Index (IS_OPTN or IS_UNQL) read FfechaEmision write SetfechaEmision stored fechaEmision_Specified; property codigoTipoAutorizacion: CodigoTipoAutorizacionSimpleType Index (IS_OPTN or IS_UNQL) read FcodigoTipoAutorizacion write SetcodigoTipoAutorizacion stored codigoTipoAutorizacion_Specified; property codigoAutorizacion: Int64 Index (IS_OPTN or IS_UNQL) read FcodigoAutorizacion write SetcodigoAutorizacion stored codigoAutorizacion_Specified; property fechaVencimiento: TXSDate Index (IS_OPTN or IS_UNQL) read FfechaVencimiento write SetfechaVencimiento stored fechaVencimiento_Specified; property codigoTipoDocumento: Smallint Index (IS_OPTN or IS_UNQL) read FcodigoTipoDocumento write SetcodigoTipoDocumento stored codigoTipoDocumento_Specified; property numeroDocumento: Int64 Index (IS_OPTN or IS_UNQL) read FnumeroDocumento write SetnumeroDocumento stored numeroDocumento_Specified; property importeGravado: ImporteTotalSimpleType Index (IS_OPTN or IS_UNQL) read FimporteGravado write SetimporteGravado stored importeGravado_Specified; property importeNoGravado: ImporteTotalSimpleType Index (IS_OPTN or IS_UNQL) read FimporteNoGravado write SetimporteNoGravado stored importeNoGravado_Specified; property importeExento: ImporteTotalSimpleType Index (IS_OPTN or IS_UNQL) read FimporteExento write SetimporteExento stored importeExento_Specified; property importeSubtotal: ImporteTotalSimpleType Index (IS_UNQL) read FimporteSubtotal write FimporteSubtotal; property importeOtrosTributos: ImporteTotalSimpleType Index (IS_OPTN or IS_UNQL) read FimporteOtrosTributos write SetimporteOtrosTributos stored importeOtrosTributos_Specified; property importeTotal: ImporteTotalSimpleType Index (IS_UNQL) read FimporteTotal write FimporteTotal; property codigoMoneda: WideString Index (IS_UNQL) read FcodigoMoneda write FcodigoMoneda; property cotizacionMoneda: TXSDecimal Index (IS_UNQL) read FcotizacionMoneda write FcotizacionMoneda; property observaciones: WideString Index (IS_OPTN or IS_UNQL) read Fobservaciones write Setobservaciones stored observaciones_Specified; property codigoConcepto: Smallint Index (IS_UNQL) read FcodigoConcepto write FcodigoConcepto; property fechaServicioDesde: TXSDate Index (IS_OPTN or IS_UNQL) read FfechaServicioDesde write SetfechaServicioDesde stored fechaServicioDesde_Specified; property fechaServicioHasta: TXSDate Index (IS_OPTN or IS_UNQL) read FfechaServicioHasta write SetfechaServicioHasta stored fechaServicioHasta_Specified; property fechaVencimientoPago: TXSDate Index (IS_OPTN or IS_UNQL) read FfechaVencimientoPago write SetfechaVencimientoPago stored fechaVencimientoPago_Specified; property arrayComprobantesAsociados: ArrayComprobantesAsociadosType Index (IS_OPTN or IS_UNQL) read FarrayComprobantesAsociados write SetarrayComprobantesAsociados stored arrayComprobantesAsociados_Specified; property arrayOtrosTributos: ArrayOtrosTributosType Index (IS_OPTN or IS_UNQL) read FarrayOtrosTributos write SetarrayOtrosTributos stored arrayOtrosTributos_Specified; property arrayItems: ArrayItemsType Index (IS_UNQL) read FarrayItems write FarrayItems; property arraySubtotalesIVA: ArraySubtotalesIVAType Index (IS_OPTN or IS_UNQL) read FarraySubtotalesIVA write SetarraySubtotalesIVA stored arraySubtotalesIVA_Specified; end; ArrayPuntosVentaType = array of puntoVenta; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } // ************************************************************************ // // XML : ConsultarPuntosVentaResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarPuntosVentaResponseType = class(TRemotable) private FarrayPuntosVenta: ArrayPuntosVentaType; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayPuntosVenta: ArrayPuntosVentaType Index (IS_UNQL) read FarrayPuntosVenta write FarrayPuntosVenta; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : PuntoVentaType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // PuntoVentaType = class(TRemotable) private FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; Fbloqueado: SiNoSimpleType; FfechaBaja: TXSDate; FfechaBaja_Specified: boolean; procedure SetfechaBaja(Index: Integer; const ATXSDate: TXSDate); function fechaBaja_Specified(Index: Integer): boolean; public destructor Destroy; override; published property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; property bloqueado: SiNoSimpleType Index (IS_UNQL) read Fbloqueado write Fbloqueado; property fechaBaja: TXSDate Index (IS_OPTN or IS_UNQL) read FfechaBaja write SetfechaBaja stored fechaBaja_Specified; end; // ************************************************************************ // // XML : ConsultarCotizacionMonedaResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarCotizacionMonedaResponseType = class(TRemotable) private FcotizacionMoneda: TXSDecimal; FcotizacionMoneda_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetcotizacionMoneda(Index: Integer; const ATXSDecimal: TXSDecimal); function cotizacionMoneda_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property cotizacionMoneda: TXSDecimal Index (IS_OPTN or IS_UNQL) read FcotizacionMoneda write SetcotizacionMoneda stored cotizacionMoneda_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarPuntosVentaCAERequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarPuntosVentaCAERequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : InformarCAEANoUtilizadoRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // InformarCAEANoUtilizadoRequestType = class(TRemotable) private FauthRequest: AuthRequestType; FCAEA: Int64; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property CAEA: Int64 Index (IS_UNQL) read FCAEA write FCAEA; end; // ************************************************************************ // // XML : InformarCAEANoUtilizadoResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // InformarCAEANoUtilizadoResponseType = class(TRemotable) private Fresultado: ResultadoSimpleType; FfechaProceso: TXSDate; FCAEA: Int64; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property resultado: ResultadoSimpleType Index (IS_UNQL) read Fresultado write Fresultado; property fechaProceso: TXSDate Index (IS_UNQL) read FfechaProceso write FfechaProceso; property CAEA: Int64 Index (IS_UNQL) read FCAEA write FCAEA; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarTiposTributoRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarTiposTributoRequestType = class(TRemotable) private FauthRequest: AuthRequestType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; end; // ************************************************************************ // // XML : ConsultarTiposTributoResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarTiposTributoResponseType = class(TRemotable) private FarrayTiposTributo: ArrayCodigosDescripcionesType; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayTiposTributo: ArrayCodigosDescripcionesType Index (IS_UNQL) read FarrayTiposTributo write FarrayTiposTributo; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : InformarCAEANoUtilizadoPtoVtaRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // InformarCAEANoUtilizadoPtoVtaRequestType = class(TRemotable) private FauthRequest: AuthRequestType; FCAEA: Int64; FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property CAEA: Int64 Index (IS_UNQL) read FCAEA write FCAEA; property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; end; // ************************************************************************ // // XML : InformarCAEANoUtilizadoPtoVtaResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // InformarCAEANoUtilizadoPtoVtaResponseType = class(TRemotable) private Fresultado: ResultadoSimpleType; FfechaProceso: TXSDate; FCAEA: Int64; FnumeroPuntoVenta: NumeroPuntoVentaSimpleType; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property resultado: ResultadoSimpleType Index (IS_UNQL) read Fresultado write Fresultado; property fechaProceso: TXSDate Index (IS_UNQL) read FfechaProceso write FfechaProceso; property CAEA: Int64 Index (IS_UNQL) read FCAEA write FCAEA; property numeroPuntoVenta: NumeroPuntoVentaSimpleType Index (IS_UNQL) read FnumeroPuntoVenta write FnumeroPuntoVenta; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarCAEARequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarCAEARequestType = class(TRemotable) private FauthRequest: AuthRequestType; FCAEA: Int64; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property CAEA: Int64 Index (IS_UNQL) read FCAEA write FCAEA; end; // ************************************************************************ // // XML : ConsultarCAEAResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarCAEAResponseType = class(TRemotable) private FCAEAResponse: CAEAResponseType; FCAEAResponse_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetCAEAResponse(Index: Integer; const ACAEAResponseType: CAEAResponseType); function CAEAResponse_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property CAEAResponse: CAEAResponseType Index (IS_OPTN or IS_UNQL) read FCAEAResponse write SetCAEAResponse stored CAEAResponse_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; ArrayCAEAResponseType = array of CAEAResponse; { "http://impl.service.wsmtxca.afip.gov.ar/service/"[GblCplx] } // ************************************************************************ // // XML : ConsultarPtosVtaCAEANoInformadosRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarPtosVtaCAEANoInformadosRequestType = class(TRemotable) private FauthRequest: AuthRequestType; FCAEA: Int64; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property CAEA: Int64 Index (IS_UNQL) read FCAEA write FCAEA; end; // ************************************************************************ // // XML : ConsultarPtosVtaCAEANoInformadosResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarPtosVtaCAEANoInformadosResponseType = class(TRemotable) private FarrayPuntosVenta: ArrayPuntosVentaType; FarrayPuntosVenta_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetarrayPuntosVenta(Index: Integer; const AArrayPuntosVentaType: ArrayPuntosVentaType); function arrayPuntosVenta_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayPuntosVenta: ArrayPuntosVentaType Index (IS_OPTN or IS_UNQL) read FarrayPuntosVenta write SetarrayPuntosVenta stored arrayPuntosVenta_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : ConsultarCAEAEntreFechasRequestType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarCAEAEntreFechasRequestType = class(TRemotable) private FauthRequest: AuthRequestType; FfechaDesde: TXSDate; FfechaHasta: TXSDate; public constructor Create; override; destructor Destroy; override; published property authRequest: AuthRequestType Index (IS_UNQL) read FauthRequest write FauthRequest; property fechaDesde: TXSDate Index (IS_UNQL) read FfechaDesde write FfechaDesde; property fechaHasta: TXSDate Index (IS_UNQL) read FfechaHasta write FfechaHasta; end; // ************************************************************************ // // XML : ConsultarCAEAEntreFechasResponseType, global, <complexType> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Serializtn: [xoLiteralParam] // Info : Wrapper // ************************************************************************ // ConsultarCAEAEntreFechasResponseType = class(TRemotable) private FarrayCAEAResponse: ArrayCAEAResponseType; FarrayCAEAResponse_Specified: boolean; FarrayErrores: ArrayCodigosDescripcionesType; FarrayErrores_Specified: boolean; Fevento: CodigoDescripcionType; Fevento_Specified: boolean; procedure SetarrayCAEAResponse(Index: Integer; const AArrayCAEAResponseType: ArrayCAEAResponseType); function arrayCAEAResponse_Specified(Index: Integer): boolean; procedure SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); function arrayErrores_Specified(Index: Integer): boolean; procedure Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); function evento_Specified(Index: Integer): boolean; public constructor Create; override; destructor Destroy; override; published property arrayCAEAResponse: ArrayCAEAResponseType Index (IS_OPTN or IS_UNQL) read FarrayCAEAResponse write SetarrayCAEAResponse stored arrayCAEAResponse_Specified; property arrayErrores: ArrayCodigosDescripcionesType Index (IS_OPTN or IS_UNQL) read FarrayErrores write SetarrayErrores stored arrayErrores_Specified; property evento: CodigoDescripcionType Index (IS_OPTN or IS_UNQL) read Fevento write Setevento stored evento_Specified; end; // ************************************************************************ // // XML : dummyResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // dummyResponse = class(DummyResponseType) private published end; // ************************************************************************ // // XML : exceptionResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Fault // ************************************************************************ // exceptionResponse = class(ExceptionResponseType) private published end; // ************************************************************************ // // XML : autorizarComprobanteResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // autorizarComprobanteResponse = class(AutorizarComprobanteResponseType) private published end; // ************************************************************************ // // XML : autorizarComprobanteRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // autorizarComprobanteRequest = class(AutorizarComprobanteRequestType) private published end; // ************************************************************************ // // XML : solicitarCAEAResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // solicitarCAEAResponse = class(SolicitarCAEAResponseType) private published end; // ************************************************************************ // // XML : solicitarCAEARequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // solicitarCAEARequest = class(SolicitarCAEARequestType) private published end; // ************************************************************************ // // XML : informarComprobanteCAEAResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // informarComprobanteCAEAResponse = class(InformarComprobanteCAEAResponseType) private published end; // ************************************************************************ // // XML : consultarUltimoComprobanteAutorizadoResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarUltimoComprobanteAutorizadoResponse = class(ConsultarUltimoComprobanteAutorizadoResponseType) private published end; // ************************************************************************ // // XML : informarComprobanteCAEARequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // informarComprobanteCAEARequest = class(InformarComprobanteCAEARequestType) private published end; // ************************************************************************ // // XML : consultarUltimoComprobanteAutorizadoRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarUltimoComprobanteAutorizadoRequest = class(ConsultarUltimoComprobanteAutorizadoRequestType) private published end; // ************************************************************************ // // XML : consultarPuntosVentaCAEAResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarPuntosVentaCAEAResponse = class(ConsultarPuntosVentaResponseType) private published end; // ************************************************************************ // // XML : consultarPuntosVentaRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarPuntosVentaRequest = class(ConsultarPuntosVentaRequestType) private published end; // ************************************************************************ // // XML : consultarPuntosVentaCAEARequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarPuntosVentaCAEARequest = class(ConsultarPuntosVentaCAEARequestType) private published end; // ************************************************************************ // // XML : consultarTiposComprobanteResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarTiposComprobanteResponse = class(ConsultarTiposComprobanteResponseType) private published end; // ************************************************************************ // // XML : consultarTiposComprobanteRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarTiposComprobanteRequest = class(ConsultarTiposComprobanteRequestType) private published end; // ************************************************************************ // // XML : consultarComprobanteResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarComprobanteResponse = class(ConsultarComprobanteResponseType) private published end; // ************************************************************************ // // XML : consultarComprobanteRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarComprobanteRequest = class(ConsultarComprobanteRequestType) private published end; // ************************************************************************ // // XML : consultarTiposDocumentoRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarTiposDocumentoRequest = class(ConsultarTiposDocumentoRequestType) private published end; // ************************************************************************ // // XML : consultarTiposDocumentoResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarTiposDocumentoResponse = class(ConsultarTiposDocumentoResponseType) private published end; // ************************************************************************ // // XML : consultarAlicuotasIVARequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarAlicuotasIVARequest = class(ConsultarAlicuotasIVARequestType) private published end; // ************************************************************************ // // XML : consultarAlicuotasIVAResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarAlicuotasIVAResponse = class(ConsultarAlicuotasIVAResponseType) private published end; // ************************************************************************ // // XML : consultarCondicionesIVARequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarCondicionesIVARequest = class(ConsultarCondicionesIVARequestType) private published end; // ************************************************************************ // // XML : consultarCondicionesIVAResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarCondicionesIVAResponse = class(ConsultarCondicionesIVAResponseType) private published end; // ************************************************************************ // // XML : consultarMonedasRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarMonedasRequest = class(ConsultarMonedasRequestType) private published end; // ************************************************************************ // // XML : consultarMonedasResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarMonedasResponse = class(ConsultarMonedasResponseType) private published end; // ************************************************************************ // // XML : consultarCotizacionMonedaRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarCotizacionMonedaRequest = class(ConsultarCotizacionMonedaRequestType) private published end; // ************************************************************************ // // XML : consultarCotizacionMonedaResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarCotizacionMonedaResponse = class(ConsultarCotizacionMonedaResponseType) private published end; // ************************************************************************ // // XML : consultarUnidadesMedidaRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarUnidadesMedidaRequest = class(ConsultarUnidadesMedidaRequestType) private published end; // ************************************************************************ // // XML : consultarUnidadesMedidaResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarUnidadesMedidaResponse = class(ConsultarUnidadesMedidaResponseType) private published end; // ************************************************************************ // // XML : consultarPuntosVentaResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarPuntosVentaResponse = class(ConsultarPuntosVentaResponseType) private published end; // ************************************************************************ // // XML : consultarPuntosVentaCAERequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarPuntosVentaCAERequest = class(ConsultarPuntosVentaCAERequestType) private published end; // ************************************************************************ // // XML : consultarPuntosVentaCAEResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarPuntosVentaCAEResponse = class(ConsultarPuntosVentaResponseType) private published end; // ************************************************************************ // // XML : informarCAEANoUtilizadoResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // informarCAEANoUtilizadoResponse = class(InformarCAEANoUtilizadoResponseType) private published end; // ************************************************************************ // // XML : informarCAEANoUtilizadoRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // informarCAEANoUtilizadoRequest = class(InformarCAEANoUtilizadoRequestType) private published end; // ************************************************************************ // // XML : consultarTiposTributoResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarTiposTributoResponse = class(ConsultarTiposTributoResponseType) private published end; // ************************************************************************ // // XML : consultarTiposTributoRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarTiposTributoRequest = class(ConsultarTiposTributoRequestType) private published end; // ************************************************************************ // // XML : informarCAEANoUtilizadoPtoVtaRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // informarCAEANoUtilizadoPtoVtaRequest = class(InformarCAEANoUtilizadoPtoVtaRequestType) private published end; // ************************************************************************ // // XML : informarCAEANoUtilizadoPtoVtaResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // informarCAEANoUtilizadoPtoVtaResponse = class(InformarCAEANoUtilizadoPtoVtaResponseType) private published end; // ************************************************************************ // // XML : consultarCAEARequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarCAEARequest = class(ConsultarCAEARequestType) private published end; // ************************************************************************ // // XML : consultarCAEAResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarCAEAResponse = class(ConsultarCAEAResponseType) private published end; // ************************************************************************ // // XML : consultarPtosVtaCAEANoInformadosRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarPtosVtaCAEANoInformadosRequest = class(ConsultarPtosVtaCAEANoInformadosRequestType) private published end; // ************************************************************************ // // XML : consultarPtosVtaCAEANoInformadosResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarPtosVtaCAEANoInformadosResponse = class(ConsultarPtosVtaCAEANoInformadosResponseType) private published end; // ************************************************************************ // // XML : consultarCAEAEntreFechasRequest, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarCAEAEntreFechasRequest = class(ConsultarCAEAEntreFechasRequestType) private published end; // ************************************************************************ // // XML : consultarCAEAEntreFechasResponse, global, <element> // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // Info : Wrapper // ************************************************************************ // consultarCAEAEntreFechasResponse = class(ConsultarCAEAEntreFechasResponseType) private published end; // ************************************************************************ // // XML : comprobanteAsociado, alias // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // comprobanteAsociado = class(ComprobanteAsociadoType) private published end; // ************************************************************************ // // XML : otroTributo, alias // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // otroTributo = class(OtroTributoType) private published end; // ************************************************************************ // // XML : item, alias // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // item = class(ItemType) private published end; // ************************************************************************ // // XML : subtotalIVA, alias // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // subtotalIVA = class(SubtotalIVAType) private published end; // ************************************************************************ // // XML : codigoDescripcion, alias // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // codigoDescripcion = class(CodigoDescripcionType) private published end; // ************************************************************************ // // XML : codigoDescripcion, alias // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // codigoDescripcion2 = class(CodigoDescripcionStringType) private published end; // ************************************************************************ // // XML : puntoVenta, alias // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // puntoVenta = class(PuntoVentaType) private published end; // ************************************************************************ // // XML : CAEAResponse, alias // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // ************************************************************************ // CAEAResponse = class(CAEAResponseType) private published end; // ************************************************************************ // // Namespace : http://impl.service.wsmtxca.afip.gov.ar/service/ // soapAction: http://impl.service.wsmtxca.afip.gov.ar/service/%operationName% // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : MTXCAServiceSoap11Binding // service : MTXCAService // port : MTXCAServiceHttpSoap11Endpoint // URL : https://fwshomo.afip.gov.ar/wsmtxca/services/MTXCAService // ************************************************************************ // MTXCAServicePortType = interface(IInvokable) ['{CE45775E-4B42-2FED-D0BF-02287F61DC20}'] // Cannot unwrap: // - More than one strictly out element was found function dummy: dummyResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function autorizarComprobante(const parameters: autorizarComprobanteRequest): autorizarComprobanteResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function solicitarCAEA(const parameters: solicitarCAEARequest): solicitarCAEAResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function informarComprobanteCAEA(const parameters: informarComprobanteCAEARequest): informarComprobanteCAEAResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarUltimoComprobanteAutorizado(const parameters: consultarUltimoComprobanteAutorizadoRequest): consultarUltimoComprobanteAutorizadoResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarComprobante(const parameters: consultarComprobanteRequest): consultarComprobanteResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarTiposComprobante(const parameters: consultarTiposComprobanteRequest): consultarTiposComprobanteResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarTiposDocumento(const parameters: consultarTiposDocumentoRequest): consultarTiposDocumentoResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarAlicuotasIVA(const parameters: consultarAlicuotasIVARequest): consultarAlicuotasIVAResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarCondicionesIVA(const parameters: consultarCondicionesIVARequest): consultarCondicionesIVAResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarMonedas(const parameters: consultarMonedasRequest): consultarMonedasResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarCotizacionMoneda(const parameters: consultarCotizacionMonedaRequest): consultarCotizacionMonedaResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarUnidadesMedida(const parameters: consultarUnidadesMedidaRequest): consultarUnidadesMedidaResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarTiposTributo(const parameters: consultarTiposTributoRequest): consultarTiposTributoResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarPuntosVenta(const parameters: consultarPuntosVentaRequest): consultarPuntosVentaResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarPuntosVentaCAE(const parameters: consultarPuntosVentaCAERequest): consultarPuntosVentaCAEResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarPuntosVentaCAEA(const parameters: consultarPuntosVentaCAEARequest): consultarPuntosVentaCAEAResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function informarCAEANoUtilizado(const parameters: informarCAEANoUtilizadoRequest): informarCAEANoUtilizadoResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function informarCAEANoUtilizadoPtoVta(const parameters: informarCAEANoUtilizadoPtoVtaRequest): informarCAEANoUtilizadoPtoVtaResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarPtosVtaCAEANoInformados(const parameters: consultarPtosVtaCAEANoInformadosRequest): consultarPtosVtaCAEANoInformadosResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarCAEA(const parameters: consultarCAEARequest): consultarCAEAResponse; stdcall; // Cannot unwrap: // - Input element wrapper name does not match operation's name // - More than one strictly out element was found function consultarCAEAEntreFechas(const parameters: consultarCAEAEntreFechasRequest): consultarCAEAEntreFechasResponse; stdcall; end; function GetMTXCAServicePortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): MTXCAServicePortType; implementation uses SysUtils; function GetMTXCAServicePortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): MTXCAServicePortType; const defWSDL = 'fe/MTXCAService.wsdl'; defURL = 'https://fwshomo.afip.gov.ar/wsmtxca/services/MTXCAService'; defSvc = 'MTXCAService'; defPrt = 'MTXCAServiceHttpSoap11Endpoint'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as MTXCAServicePortType); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; constructor DummyResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; procedure ExceptionResponseType.Setexception(Index: Integer; const AWideString: WideString); begin Fexception := AWideString; Fexception_Specified := True; end; function ExceptionResponseType.exception_Specified(Index: Integer): boolean; begin Result := Fexception_Specified; end; constructor AutorizarComprobanteRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor AutorizarComprobanteRequestType.Destroy; begin FreeAndNil(FauthRequest); FreeAndNil(FcomprobanteCAERequest); inherited Destroy; end; constructor AutorizarComprobanteResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor AutorizarComprobanteResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayObservaciones)-1 do FreeAndNil(FarrayObservaciones[I]); SetLength(FarrayObservaciones, 0); for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(FcomprobanteResponse); FreeAndNil(Fevento); inherited Destroy; end; procedure AutorizarComprobanteResponseType.SetcomprobanteResponse(Index: Integer; const AComprobanteCAEResponseType: ComprobanteCAEResponseType); begin FcomprobanteResponse := AComprobanteCAEResponseType; FcomprobanteResponse_Specified := True; end; function AutorizarComprobanteResponseType.comprobanteResponse_Specified(Index: Integer): boolean; begin Result := FcomprobanteResponse_Specified; end; procedure AutorizarComprobanteResponseType.SetarrayObservaciones(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayObservaciones := AArrayCodigosDescripcionesType; FarrayObservaciones_Specified := True; end; function AutorizarComprobanteResponseType.arrayObservaciones_Specified(Index: Integer): boolean; begin Result := FarrayObservaciones_Specified; end; procedure AutorizarComprobanteResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function AutorizarComprobanteResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure AutorizarComprobanteResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function AutorizarComprobanteResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor SolicitarCAEARequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor SolicitarCAEARequestType.Destroy; begin FreeAndNil(FauthRequest); FreeAndNil(FsolicitudCAEA); inherited Destroy; end; constructor SolicitarCAEAResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor SolicitarCAEAResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(FCAEAResponse); FreeAndNil(Fevento); inherited Destroy; end; procedure SolicitarCAEAResponseType.SetCAEAResponse(Index: Integer; const ACAEAResponseType: CAEAResponseType); begin FCAEAResponse := ACAEAResponseType; FCAEAResponse_Specified := True; end; function SolicitarCAEAResponseType.CAEAResponse_Specified(Index: Integer): boolean; begin Result := FCAEAResponse_Specified; end; procedure SolicitarCAEAResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function SolicitarCAEAResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure SolicitarCAEAResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function SolicitarCAEAResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor InformarComprobanteCAEARequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor InformarComprobanteCAEARequestType.Destroy; begin FreeAndNil(FauthRequest); FreeAndNil(FcomprobanteCAEARequest); inherited Destroy; end; constructor ConsultarUltimoComprobanteAutorizadoRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarUltimoComprobanteAutorizadoRequestType.Destroy; begin FreeAndNil(FauthRequest); FreeAndNil(FconsultaUltimoComprobanteAutorizadoRequest); inherited Destroy; end; constructor InformarComprobanteCAEAResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor InformarComprobanteCAEAResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayObservaciones)-1 do FreeAndNil(FarrayObservaciones[I]); SetLength(FarrayObservaciones, 0); for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(FfechaProceso); FreeAndNil(FcomprobanteCAEAResponse); FreeAndNil(Fevento); inherited Destroy; end; procedure InformarComprobanteCAEAResponseType.SetcomprobanteCAEAResponse(Index: Integer; const AComprobanteCAEAResponseType: ComprobanteCAEAResponseType); begin FcomprobanteCAEAResponse := AComprobanteCAEAResponseType; FcomprobanteCAEAResponse_Specified := True; end; function InformarComprobanteCAEAResponseType.comprobanteCAEAResponse_Specified(Index: Integer): boolean; begin Result := FcomprobanteCAEAResponse_Specified; end; procedure InformarComprobanteCAEAResponseType.SetarrayObservaciones(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayObservaciones := AArrayCodigosDescripcionesType; FarrayObservaciones_Specified := True; end; function InformarComprobanteCAEAResponseType.arrayObservaciones_Specified(Index: Integer): boolean; begin Result := FarrayObservaciones_Specified; end; procedure InformarComprobanteCAEAResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function InformarComprobanteCAEAResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure InformarComprobanteCAEAResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function InformarComprobanteCAEAResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; destructor CAEAResponseType.Destroy; begin FreeAndNil(FfechaProceso); FreeAndNil(FfechaDesde); FreeAndNil(FfechaHasta); FreeAndNil(FfechaTopeInforme); inherited Destroy; end; destructor ComprobanteCAEResponseType.Destroy; begin FreeAndNil(FfechaEmision); FreeAndNil(FfechaVencimientoCAE); inherited Destroy; end; constructor ConsultarTiposComprobanteRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarTiposComprobanteRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarPuntosVentaCAEARequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarPuntosVentaCAEARequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarComprobanteRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarComprobanteRequestType.Destroy; begin FreeAndNil(FauthRequest); FreeAndNil(FconsultaComprobanteRequest); inherited Destroy; end; constructor ConsultarPuntosVentaRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarPuntosVentaRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarAlicuotasIVARequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarAlicuotasIVARequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarCondicionesIVARequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarCondicionesIVARequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarCotizacionMonedaRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarCotizacionMonedaRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarMonedasRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarMonedasRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarTiposDocumentoRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarTiposDocumentoRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarUnidadesMedidaRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarUnidadesMedidaRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarUltimoComprobanteAutorizadoResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarUltimoComprobanteAutorizadoResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarUltimoComprobanteAutorizadoResponseType.SetnumeroComprobante(Index: Integer; const ANumeroComprobanteSimpleType: NumeroComprobanteSimpleType); begin FnumeroComprobante := ANumeroComprobanteSimpleType; FnumeroComprobante_Specified := True; end; function ConsultarUltimoComprobanteAutorizadoResponseType.numeroComprobante_Specified(Index: Integer): boolean; begin Result := FnumeroComprobante_Specified; end; procedure ConsultarUltimoComprobanteAutorizadoResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function ConsultarUltimoComprobanteAutorizadoResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure ConsultarUltimoComprobanteAutorizadoResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarUltimoComprobanteAutorizadoResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarTiposComprobanteResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarTiposComprobanteResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayTiposComprobante)-1 do FreeAndNil(FarrayTiposComprobante[I]); SetLength(FarrayTiposComprobante, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarTiposComprobanteResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarTiposComprobanteResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarTiposDocumentoResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarTiposDocumentoResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayTiposDocumento)-1 do FreeAndNil(FarrayTiposDocumento[I]); SetLength(FarrayTiposDocumento, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarTiposDocumentoResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarTiposDocumentoResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarAlicuotasIVAResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarAlicuotasIVAResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayAlicuotasIVA)-1 do FreeAndNil(FarrayAlicuotasIVA[I]); SetLength(FarrayAlicuotasIVA, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarAlicuotasIVAResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarAlicuotasIVAResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarCondicionesIVAResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarCondicionesIVAResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayCondicionesIVA)-1 do FreeAndNil(FarrayCondicionesIVA[I]); SetLength(FarrayCondicionesIVA, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarCondicionesIVAResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarCondicionesIVAResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarUnidadesMedidaResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarUnidadesMedidaResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayUnidadesMedida)-1 do FreeAndNil(FarrayUnidadesMedida[I]); SetLength(FarrayUnidadesMedida, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarUnidadesMedidaResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarUnidadesMedidaResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarMonedasResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarMonedasResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayMonedas)-1 do FreeAndNil(FarrayMonedas[I]); SetLength(FarrayMonedas, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarMonedasResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarMonedasResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarComprobanteResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarComprobanteResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayObservaciones)-1 do FreeAndNil(FarrayObservaciones[I]); SetLength(FarrayObservaciones, 0); for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(Fcomprobante); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarComprobanteResponseType.Setcomprobante(Index: Integer; const AComprobanteType: ComprobanteType); begin Fcomprobante := AComprobanteType; Fcomprobante_Specified := True; end; function ConsultarComprobanteResponseType.comprobante_Specified(Index: Integer): boolean; begin Result := Fcomprobante_Specified; end; procedure ConsultarComprobanteResponseType.SetarrayObservaciones(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayObservaciones := AArrayCodigosDescripcionesType; FarrayObservaciones_Specified := True; end; function ConsultarComprobanteResponseType.arrayObservaciones_Specified(Index: Integer): boolean; begin Result := FarrayObservaciones_Specified; end; procedure ConsultarComprobanteResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function ConsultarComprobanteResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure ConsultarComprobanteResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarComprobanteResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; destructor ItemType.Destroy; begin FreeAndNil(Fcantidad); FreeAndNil(FprecioUnitario); FreeAndNil(FimporteBonificacion); FreeAndNil(FimporteIVA); FreeAndNil(FimporteItem); inherited Destroy; end; procedure ItemType.SetunidadesMtx(Index: Integer; const AInteger: Integer); begin FunidadesMtx := AInteger; FunidadesMtx_Specified := True; end; function ItemType.unidadesMtx_Specified(Index: Integer): boolean; begin Result := FunidadesMtx_Specified; end; procedure ItemType.SetcodigoMtx(Index: Integer; const AWideString: WideString); begin FcodigoMtx := AWideString; FcodigoMtx_Specified := True; end; function ItemType.codigoMtx_Specified(Index: Integer): boolean; begin Result := FcodigoMtx_Specified; end; procedure ItemType.Setcodigo(Index: Integer; const AWideString: WideString); begin Fcodigo := AWideString; Fcodigo_Specified := True; end; function ItemType.codigo_Specified(Index: Integer): boolean; begin Result := Fcodigo_Specified; end; procedure ItemType.Setcantidad(Index: Integer; const ADecimalSimpleType: DecimalSimpleType); begin Fcantidad := ADecimalSimpleType; Fcantidad_Specified := True; end; function ItemType.cantidad_Specified(Index: Integer): boolean; begin Result := Fcantidad_Specified; end; procedure ItemType.SetprecioUnitario(Index: Integer; const ADecimalSimpleType: DecimalSimpleType); begin FprecioUnitario := ADecimalSimpleType; FprecioUnitario_Specified := True; end; function ItemType.precioUnitario_Specified(Index: Integer): boolean; begin Result := FprecioUnitario_Specified; end; procedure ItemType.SetimporteBonificacion(Index: Integer; const ADecimalSimpleType: DecimalSimpleType); begin FimporteBonificacion := ADecimalSimpleType; FimporteBonificacion_Specified := True; end; function ItemType.importeBonificacion_Specified(Index: Integer): boolean; begin Result := FimporteBonificacion_Specified; end; procedure ItemType.SetimporteIVA(Index: Integer; const AImporteSubtotalSimpleType: ImporteSubtotalSimpleType); begin FimporteIVA := AImporteSubtotalSimpleType; FimporteIVA_Specified := True; end; function ItemType.importeIVA_Specified(Index: Integer): boolean; begin Result := FimporteIVA_Specified; end; destructor SubtotalIVAType.Destroy; begin FreeAndNil(Fimporte); inherited Destroy; end; destructor OtroTributoType.Destroy; begin FreeAndNil(FbaseImponible); FreeAndNil(Fimporte); inherited Destroy; end; procedure OtroTributoType.Setdescripcion(Index: Integer; const AWideString: WideString); begin Fdescripcion := AWideString; Fdescripcion_Specified := True; end; function OtroTributoType.descripcion_Specified(Index: Integer): boolean; begin Result := Fdescripcion_Specified; end; destructor ComprobanteType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayComprobantesAsociados)-1 do FreeAndNil(FarrayComprobantesAsociados[I]); SetLength(FarrayComprobantesAsociados, 0); for I := 0 to Length(FarrayOtrosTributos)-1 do FreeAndNil(FarrayOtrosTributos[I]); SetLength(FarrayOtrosTributos, 0); for I := 0 to Length(FarrayItems)-1 do FreeAndNil(FarrayItems[I]); SetLength(FarrayItems, 0); for I := 0 to Length(FarraySubtotalesIVA)-1 do FreeAndNil(FarraySubtotalesIVA[I]); SetLength(FarraySubtotalesIVA, 0); FreeAndNil(FfechaEmision); FreeAndNil(FfechaVencimiento); FreeAndNil(FimporteGravado); FreeAndNil(FimporteNoGravado); FreeAndNil(FimporteExento); FreeAndNil(FimporteSubtotal); FreeAndNil(FimporteOtrosTributos); FreeAndNil(FimporteTotal); FreeAndNil(FcotizacionMoneda); FreeAndNil(FfechaServicioDesde); FreeAndNil(FfechaServicioHasta); FreeAndNil(FfechaVencimientoPago); inherited Destroy; end; procedure ComprobanteType.SetfechaEmision(Index: Integer; const ATXSDate: TXSDate); begin FfechaEmision := ATXSDate; FfechaEmision_Specified := True; end; function ComprobanteType.fechaEmision_Specified(Index: Integer): boolean; begin Result := FfechaEmision_Specified; end; procedure ComprobanteType.SetcodigoTipoAutorizacion(Index: Integer; const ACodigoTipoAutorizacionSimpleType: CodigoTipoAutorizacionSimpleType); begin FcodigoTipoAutorizacion := ACodigoTipoAutorizacionSimpleType; FcodigoTipoAutorizacion_Specified := True; end; function ComprobanteType.codigoTipoAutorizacion_Specified(Index: Integer): boolean; begin Result := FcodigoTipoAutorizacion_Specified; end; procedure ComprobanteType.SetcodigoAutorizacion(Index: Integer; const AInt64: Int64); begin FcodigoAutorizacion := AInt64; FcodigoAutorizacion_Specified := True; end; function ComprobanteType.codigoAutorizacion_Specified(Index: Integer): boolean; begin Result := FcodigoAutorizacion_Specified; end; procedure ComprobanteType.SetfechaVencimiento(Index: Integer; const ATXSDate: TXSDate); begin FfechaVencimiento := ATXSDate; FfechaVencimiento_Specified := True; end; function ComprobanteType.fechaVencimiento_Specified(Index: Integer): boolean; begin Result := FfechaVencimiento_Specified; end; procedure ComprobanteType.SetcodigoTipoDocumento(Index: Integer; const ASmallint: Smallint); begin FcodigoTipoDocumento := ASmallint; FcodigoTipoDocumento_Specified := True; end; function ComprobanteType.codigoTipoDocumento_Specified(Index: Integer): boolean; begin Result := FcodigoTipoDocumento_Specified; end; procedure ComprobanteType.SetnumeroDocumento(Index: Integer; const AInt64: Int64); begin FnumeroDocumento := AInt64; FnumeroDocumento_Specified := True; end; function ComprobanteType.numeroDocumento_Specified(Index: Integer): boolean; begin Result := FnumeroDocumento_Specified; end; procedure ComprobanteType.SetimporteGravado(Index: Integer; const AImporteTotalSimpleType: ImporteTotalSimpleType); begin FimporteGravado := AImporteTotalSimpleType; FimporteGravado_Specified := True; end; function ComprobanteType.importeGravado_Specified(Index: Integer): boolean; begin Result := FimporteGravado_Specified; end; procedure ComprobanteType.SetimporteNoGravado(Index: Integer; const AImporteTotalSimpleType: ImporteTotalSimpleType); begin FimporteNoGravado := AImporteTotalSimpleType; FimporteNoGravado_Specified := True; end; function ComprobanteType.importeNoGravado_Specified(Index: Integer): boolean; begin Result := FimporteNoGravado_Specified; end; procedure ComprobanteType.SetimporteExento(Index: Integer; const AImporteTotalSimpleType: ImporteTotalSimpleType); begin FimporteExento := AImporteTotalSimpleType; FimporteExento_Specified := True; end; function ComprobanteType.importeExento_Specified(Index: Integer): boolean; begin Result := FimporteExento_Specified; end; procedure ComprobanteType.SetimporteOtrosTributos(Index: Integer; const AImporteTotalSimpleType: ImporteTotalSimpleType); begin FimporteOtrosTributos := AImporteTotalSimpleType; FimporteOtrosTributos_Specified := True; end; function ComprobanteType.importeOtrosTributos_Specified(Index: Integer): boolean; begin Result := FimporteOtrosTributos_Specified; end; procedure ComprobanteType.Setobservaciones(Index: Integer; const AWideString: WideString); begin Fobservaciones := AWideString; Fobservaciones_Specified := True; end; function ComprobanteType.observaciones_Specified(Index: Integer): boolean; begin Result := Fobservaciones_Specified; end; procedure ComprobanteType.SetfechaServicioDesde(Index: Integer; const ATXSDate: TXSDate); begin FfechaServicioDesde := ATXSDate; FfechaServicioDesde_Specified := True; end; function ComprobanteType.fechaServicioDesde_Specified(Index: Integer): boolean; begin Result := FfechaServicioDesde_Specified; end; procedure ComprobanteType.SetfechaServicioHasta(Index: Integer; const ATXSDate: TXSDate); begin FfechaServicioHasta := ATXSDate; FfechaServicioHasta_Specified := True; end; function ComprobanteType.fechaServicioHasta_Specified(Index: Integer): boolean; begin Result := FfechaServicioHasta_Specified; end; procedure ComprobanteType.SetfechaVencimientoPago(Index: Integer; const ATXSDate: TXSDate); begin FfechaVencimientoPago := ATXSDate; FfechaVencimientoPago_Specified := True; end; function ComprobanteType.fechaVencimientoPago_Specified(Index: Integer): boolean; begin Result := FfechaVencimientoPago_Specified; end; procedure ComprobanteType.SetarrayComprobantesAsociados(Index: Integer; const AArrayComprobantesAsociadosType: ArrayComprobantesAsociadosType); begin FarrayComprobantesAsociados := AArrayComprobantesAsociadosType; FarrayComprobantesAsociados_Specified := True; end; function ComprobanteType.arrayComprobantesAsociados_Specified(Index: Integer): boolean; begin Result := FarrayComprobantesAsociados_Specified; end; procedure ComprobanteType.SetarrayOtrosTributos(Index: Integer; const AArrayOtrosTributosType: ArrayOtrosTributosType); begin FarrayOtrosTributos := AArrayOtrosTributosType; FarrayOtrosTributos_Specified := True; end; function ComprobanteType.arrayOtrosTributos_Specified(Index: Integer): boolean; begin Result := FarrayOtrosTributos_Specified; end; procedure ComprobanteType.SetarraySubtotalesIVA(Index: Integer; const AArraySubtotalesIVAType: ArraySubtotalesIVAType); begin FarraySubtotalesIVA := AArraySubtotalesIVAType; FarraySubtotalesIVA_Specified := True; end; function ComprobanteType.arraySubtotalesIVA_Specified(Index: Integer): boolean; begin Result := FarraySubtotalesIVA_Specified; end; constructor ConsultarPuntosVentaResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarPuntosVentaResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayPuntosVenta)-1 do FreeAndNil(FarrayPuntosVenta[I]); SetLength(FarrayPuntosVenta, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarPuntosVentaResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarPuntosVentaResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; destructor PuntoVentaType.Destroy; begin FreeAndNil(FfechaBaja); inherited Destroy; end; procedure PuntoVentaType.SetfechaBaja(Index: Integer; const ATXSDate: TXSDate); begin FfechaBaja := ATXSDate; FfechaBaja_Specified := True; end; function PuntoVentaType.fechaBaja_Specified(Index: Integer): boolean; begin Result := FfechaBaja_Specified; end; constructor ConsultarCotizacionMonedaResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarCotizacionMonedaResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(FcotizacionMoneda); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarCotizacionMonedaResponseType.SetcotizacionMoneda(Index: Integer; const ATXSDecimal: TXSDecimal); begin FcotizacionMoneda := ATXSDecimal; FcotizacionMoneda_Specified := True; end; function ConsultarCotizacionMonedaResponseType.cotizacionMoneda_Specified(Index: Integer): boolean; begin Result := FcotizacionMoneda_Specified; end; procedure ConsultarCotizacionMonedaResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function ConsultarCotizacionMonedaResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure ConsultarCotizacionMonedaResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarCotizacionMonedaResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarPuntosVentaCAERequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarPuntosVentaCAERequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor InformarCAEANoUtilizadoRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor InformarCAEANoUtilizadoRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor InformarCAEANoUtilizadoResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor InformarCAEANoUtilizadoResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(FfechaProceso); FreeAndNil(Fevento); inherited Destroy; end; procedure InformarCAEANoUtilizadoResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function InformarCAEANoUtilizadoResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure InformarCAEANoUtilizadoResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function InformarCAEANoUtilizadoResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarTiposTributoRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarTiposTributoRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarTiposTributoResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarTiposTributoResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayTiposTributo)-1 do FreeAndNil(FarrayTiposTributo[I]); SetLength(FarrayTiposTributo, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarTiposTributoResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarTiposTributoResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor InformarCAEANoUtilizadoPtoVtaRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor InformarCAEANoUtilizadoPtoVtaRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor InformarCAEANoUtilizadoPtoVtaResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor InformarCAEANoUtilizadoPtoVtaResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(FfechaProceso); FreeAndNil(Fevento); inherited Destroy; end; procedure InformarCAEANoUtilizadoPtoVtaResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function InformarCAEANoUtilizadoPtoVtaResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure InformarCAEANoUtilizadoPtoVtaResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function InformarCAEANoUtilizadoPtoVtaResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarCAEARequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarCAEARequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarCAEAResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarCAEAResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(FCAEAResponse); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarCAEAResponseType.SetCAEAResponse(Index: Integer; const ACAEAResponseType: CAEAResponseType); begin FCAEAResponse := ACAEAResponseType; FCAEAResponse_Specified := True; end; function ConsultarCAEAResponseType.CAEAResponse_Specified(Index: Integer): boolean; begin Result := FCAEAResponse_Specified; end; procedure ConsultarCAEAResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function ConsultarCAEAResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure ConsultarCAEAResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarCAEAResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarPtosVtaCAEANoInformadosRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarPtosVtaCAEANoInformadosRequestType.Destroy; begin FreeAndNil(FauthRequest); inherited Destroy; end; constructor ConsultarPtosVtaCAEANoInformadosResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarPtosVtaCAEANoInformadosResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayPuntosVenta)-1 do FreeAndNil(FarrayPuntosVenta[I]); SetLength(FarrayPuntosVenta, 0); for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarPtosVtaCAEANoInformadosResponseType.SetarrayPuntosVenta(Index: Integer; const AArrayPuntosVentaType: ArrayPuntosVentaType); begin FarrayPuntosVenta := AArrayPuntosVentaType; FarrayPuntosVenta_Specified := True; end; function ConsultarPtosVtaCAEANoInformadosResponseType.arrayPuntosVenta_Specified(Index: Integer): boolean; begin Result := FarrayPuntosVenta_Specified; end; procedure ConsultarPtosVtaCAEANoInformadosResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function ConsultarPtosVtaCAEANoInformadosResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure ConsultarPtosVtaCAEANoInformadosResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarPtosVtaCAEANoInformadosResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; constructor ConsultarCAEAEntreFechasRequestType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarCAEAEntreFechasRequestType.Destroy; begin FreeAndNil(FauthRequest); FreeAndNil(FfechaDesde); FreeAndNil(FfechaHasta); inherited Destroy; end; constructor ConsultarCAEAEntreFechasResponseType.Create; begin inherited Create; FSerializationOptions := [xoLiteralParam]; end; destructor ConsultarCAEAEntreFechasResponseType.Destroy; var I: Integer; begin for I := 0 to Length(FarrayCAEAResponse)-1 do FreeAndNil(FarrayCAEAResponse[I]); SetLength(FarrayCAEAResponse, 0); for I := 0 to Length(FarrayErrores)-1 do FreeAndNil(FarrayErrores[I]); SetLength(FarrayErrores, 0); FreeAndNil(Fevento); inherited Destroy; end; procedure ConsultarCAEAEntreFechasResponseType.SetarrayCAEAResponse(Index: Integer; const AArrayCAEAResponseType: ArrayCAEAResponseType); begin FarrayCAEAResponse := AArrayCAEAResponseType; FarrayCAEAResponse_Specified := True; end; function ConsultarCAEAEntreFechasResponseType.arrayCAEAResponse_Specified(Index: Integer): boolean; begin Result := FarrayCAEAResponse_Specified; end; procedure ConsultarCAEAEntreFechasResponseType.SetarrayErrores(Index: Integer; const AArrayCodigosDescripcionesType: ArrayCodigosDescripcionesType); begin FarrayErrores := AArrayCodigosDescripcionesType; FarrayErrores_Specified := True; end; function ConsultarCAEAEntreFechasResponseType.arrayErrores_Specified(Index: Integer): boolean; begin Result := FarrayErrores_Specified; end; procedure ConsultarCAEAEntreFechasResponseType.Setevento(Index: Integer; const ACodigoDescripcionType: CodigoDescripcionType); begin Fevento := ACodigoDescripcionType; Fevento_Specified := True; end; function ConsultarCAEAEntreFechasResponseType.evento_Specified(Index: Integer): boolean; begin Result := Fevento_Specified; end; initialization InvRegistry.RegisterInterface(TypeInfo(MTXCAServicePortType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'UTF-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(MTXCAServicePortType), 'http://impl.service.wsmtxca.afip.gov.ar/service/%operationName%'); InvRegistry.RegisterInvokeOptions(TypeInfo(MTXCAServicePortType), ioDocument); InvRegistry.RegisterInvokeOptions(TypeInfo(MTXCAServicePortType), ioLiteral); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'autorizarComprobante', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'solicitarCAEA', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'informarComprobanteCAEA', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarUltimoComprobanteAutorizado', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarComprobante', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarTiposComprobante', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarTiposDocumento', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarAlicuotasIVA', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarCondicionesIVA', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarMonedas', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarCotizacionMoneda', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarUnidadesMedida', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarTiposTributo', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarPuntosVenta', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarPuntosVentaCAE', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarPuntosVentaCAEA', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'informarCAEANoUtilizado', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'informarCAEANoUtilizadoPtoVta', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarPtosVtaCAEANoInformados', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarCAEA', 'parameters1', 'parameters'); InvRegistry.RegisterExternalParamName(TypeInfo(MTXCAServicePortType), 'consultarCAEAEntreFechas', 'parameters1', 'parameters'); RemClassRegistry.RegisterXSClass(DummyResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'DummyResponseType'); RemClassRegistry.RegisterSerializeOptions(DummyResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ExceptionResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ExceptionResponseType'); RemClassRegistry.RegisterXSClass(AutorizarComprobanteRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'AutorizarComprobanteRequestType'); RemClassRegistry.RegisterSerializeOptions(AutorizarComprobanteRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(AuthRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'AuthRequestType'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayComprobantesAsociadosType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ArrayComprobantesAsociadosType'); RemClassRegistry.RegisterXSInfo(TypeInfo(NumeroPuntoVentaSimpleType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'NumeroPuntoVentaSimpleType'); RemClassRegistry.RegisterXSInfo(TypeInfo(NumeroComprobanteSimpleType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'NumeroComprobanteSimpleType'); RemClassRegistry.RegisterXSClass(ComprobanteAsociadoType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ComprobanteAsociadoType'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOtrosTributosType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ArrayOtrosTributosType'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayItemsType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ArrayItemsType'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArraySubtotalesIVAType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ArraySubtotalesIVAType'); RemClassRegistry.RegisterXSInfo(TypeInfo(ResultadoSimpleType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ResultadoSimpleType'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayCodigosDescripcionesType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ArrayCodigosDescripcionesType'); RemClassRegistry.RegisterXSClass(AutorizarComprobanteResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'AutorizarComprobanteResponseType'); RemClassRegistry.RegisterSerializeOptions(AutorizarComprobanteResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(CodigoDescripcionType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'CodigoDescripcionType'); RemClassRegistry.RegisterXSClass(SolicitarCAEARequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'SolicitarCAEARequestType'); RemClassRegistry.RegisterSerializeOptions(SolicitarCAEARequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(SolicitudCAEAType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'SolicitudCAEAType'); RemClassRegistry.RegisterXSClass(SolicitarCAEAResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'SolicitarCAEAResponseType'); RemClassRegistry.RegisterSerializeOptions(SolicitarCAEAResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(InformarComprobanteCAEARequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'InformarComprobanteCAEARequestType'); RemClassRegistry.RegisterSerializeOptions(InformarComprobanteCAEARequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarUltimoComprobanteAutorizadoRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarUltimoComprobanteAutorizadoRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarUltimoComprobanteAutorizadoRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultaUltimoComprobanteAutorizadoRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultaUltimoComprobanteAutorizadoRequestType'); RemClassRegistry.RegisterXSClass(InformarComprobanteCAEAResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'InformarComprobanteCAEAResponseType'); RemClassRegistry.RegisterSerializeOptions(InformarComprobanteCAEAResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(CAEAResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'CAEAResponseType'); RemClassRegistry.RegisterXSClass(ComprobanteCAEResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ComprobanteCAEResponseType'); RemClassRegistry.RegisterXSClass(ComprobanteCAEAResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ComprobanteCAEAResponseType'); RemClassRegistry.RegisterXSClass(ConsultarTiposComprobanteRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarTiposComprobanteRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarTiposComprobanteRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarPuntosVentaCAEARequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarPuntosVentaCAEARequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarPuntosVentaCAEARequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarComprobanteRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarComprobanteRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarComprobanteRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultaComprobanteRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultaComprobanteRequestType'); RemClassRegistry.RegisterXSClass(ConsultarPuntosVentaRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarPuntosVentaRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarPuntosVentaRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarAlicuotasIVARequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarAlicuotasIVARequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarAlicuotasIVARequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarCondicionesIVARequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarCondicionesIVARequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarCondicionesIVARequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarCotizacionMonedaRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarCotizacionMonedaRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarCotizacionMonedaRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarMonedasRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarMonedasRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarMonedasRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarTiposDocumentoRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarTiposDocumentoRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarTiposDocumentoRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarUnidadesMedidaRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarUnidadesMedidaRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarUnidadesMedidaRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarUltimoComprobanteAutorizadoResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarUltimoComprobanteAutorizadoResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarUltimoComprobanteAutorizadoResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarTiposComprobanteResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarTiposComprobanteResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarTiposComprobanteResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarTiposDocumentoResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarTiposDocumentoResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarTiposDocumentoResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarAlicuotasIVAResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarAlicuotasIVAResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarAlicuotasIVAResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarCondicionesIVAResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarCondicionesIVAResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarCondicionesIVAResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarUnidadesMedidaResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarUnidadesMedidaResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarUnidadesMedidaResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayCodigosDescripcionesStringType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ArrayCodigosDescripcionesStringType'); RemClassRegistry.RegisterXSClass(ConsultarMonedasResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarMonedasResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarMonedasResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(CodigoDescripcionStringType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'CodigoDescripcionStringType'); RemClassRegistry.RegisterXSClass(ConsultarComprobanteResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarComprobanteResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarComprobanteResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSInfo(TypeInfo(CodigoTipoAutorizacionSimpleType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'CodigoTipoAutorizacionSimpleType'); RemClassRegistry.RegisterExternalPropName(TypeInfo(CodigoTipoAutorizacionSimpleType), 'A2', 'A'); RemClassRegistry.RegisterXSInfo(TypeInfo(ImporteSubtotalSimpleType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ImporteSubtotalSimpleType'); RemClassRegistry.RegisterXSInfo(TypeInfo(DecimalSimpleType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'DecimalSimpleType'); RemClassRegistry.RegisterXSClass(ItemType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ItemType'); RemClassRegistry.RegisterXSInfo(TypeInfo(ImporteTotalSimpleType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ImporteTotalSimpleType'); RemClassRegistry.RegisterXSClass(SubtotalIVAType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'SubtotalIVAType'); RemClassRegistry.RegisterXSClass(OtroTributoType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'OtroTributoType'); RemClassRegistry.RegisterXSClass(ComprobanteType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ComprobanteType'); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayPuntosVentaType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ArrayPuntosVentaType'); RemClassRegistry.RegisterXSClass(ConsultarPuntosVentaResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarPuntosVentaResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarPuntosVentaResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSInfo(TypeInfo(SiNoSimpleType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'SiNoSimpleType'); RemClassRegistry.RegisterXSClass(PuntoVentaType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'PuntoVentaType'); RemClassRegistry.RegisterXSClass(ConsultarCotizacionMonedaResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarCotizacionMonedaResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarCotizacionMonedaResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarPuntosVentaCAERequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarPuntosVentaCAERequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarPuntosVentaCAERequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(InformarCAEANoUtilizadoRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'InformarCAEANoUtilizadoRequestType'); RemClassRegistry.RegisterSerializeOptions(InformarCAEANoUtilizadoRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(InformarCAEANoUtilizadoResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'InformarCAEANoUtilizadoResponseType'); RemClassRegistry.RegisterSerializeOptions(InformarCAEANoUtilizadoResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarTiposTributoRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarTiposTributoRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarTiposTributoRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarTiposTributoResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarTiposTributoResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarTiposTributoResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(InformarCAEANoUtilizadoPtoVtaRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'InformarCAEANoUtilizadoPtoVtaRequestType'); RemClassRegistry.RegisterSerializeOptions(InformarCAEANoUtilizadoPtoVtaRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(InformarCAEANoUtilizadoPtoVtaResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'InformarCAEANoUtilizadoPtoVtaResponseType'); RemClassRegistry.RegisterSerializeOptions(InformarCAEANoUtilizadoPtoVtaResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarCAEARequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarCAEARequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarCAEARequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarCAEAResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarCAEAResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarCAEAResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayCAEAResponseType), 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ArrayCAEAResponseType'); RemClassRegistry.RegisterXSClass(ConsultarPtosVtaCAEANoInformadosRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarPtosVtaCAEANoInformadosRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarPtosVtaCAEANoInformadosRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarPtosVtaCAEANoInformadosResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarPtosVtaCAEANoInformadosResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarPtosVtaCAEANoInformadosResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarCAEAEntreFechasRequestType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarCAEAEntreFechasRequestType'); RemClassRegistry.RegisterSerializeOptions(ConsultarCAEAEntreFechasRequestType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(ConsultarCAEAEntreFechasResponseType, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'ConsultarCAEAEntreFechasResponseType'); RemClassRegistry.RegisterSerializeOptions(ConsultarCAEAEntreFechasResponseType, [xoLiteralParam]); RemClassRegistry.RegisterXSClass(dummyResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'dummyResponse'); RemClassRegistry.RegisterXSClass(exceptionResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'exceptionResponse'); RemClassRegistry.RegisterXSClass(autorizarComprobanteResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'autorizarComprobanteResponse'); RemClassRegistry.RegisterXSClass(autorizarComprobanteRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'autorizarComprobanteRequest'); RemClassRegistry.RegisterXSClass(solicitarCAEAResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'solicitarCAEAResponse'); RemClassRegistry.RegisterXSClass(solicitarCAEARequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'solicitarCAEARequest'); RemClassRegistry.RegisterXSClass(informarComprobanteCAEAResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'informarComprobanteCAEAResponse'); RemClassRegistry.RegisterXSClass(consultarUltimoComprobanteAutorizadoResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarUltimoComprobanteAutorizadoResponse'); RemClassRegistry.RegisterXSClass(informarComprobanteCAEARequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'informarComprobanteCAEARequest'); RemClassRegistry.RegisterXSClass(consultarUltimoComprobanteAutorizadoRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarUltimoComprobanteAutorizadoRequest'); RemClassRegistry.RegisterXSClass(consultarPuntosVentaCAEAResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarPuntosVentaCAEAResponse'); RemClassRegistry.RegisterXSClass(consultarPuntosVentaRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarPuntosVentaRequest'); RemClassRegistry.RegisterXSClass(consultarPuntosVentaCAEARequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarPuntosVentaCAEARequest'); RemClassRegistry.RegisterXSClass(consultarTiposComprobanteResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarTiposComprobanteResponse'); RemClassRegistry.RegisterXSClass(consultarTiposComprobanteRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarTiposComprobanteRequest'); RemClassRegistry.RegisterXSClass(consultarComprobanteResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarComprobanteResponse'); RemClassRegistry.RegisterXSClass(consultarComprobanteRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarComprobanteRequest'); RemClassRegistry.RegisterXSClass(consultarTiposDocumentoRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarTiposDocumentoRequest'); RemClassRegistry.RegisterXSClass(consultarTiposDocumentoResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarTiposDocumentoResponse'); RemClassRegistry.RegisterXSClass(consultarAlicuotasIVARequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarAlicuotasIVARequest'); RemClassRegistry.RegisterXSClass(consultarAlicuotasIVAResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarAlicuotasIVAResponse'); RemClassRegistry.RegisterXSClass(consultarCondicionesIVARequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarCondicionesIVARequest'); RemClassRegistry.RegisterXSClass(consultarCondicionesIVAResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarCondicionesIVAResponse'); RemClassRegistry.RegisterXSClass(consultarMonedasRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarMonedasRequest'); RemClassRegistry.RegisterXSClass(consultarMonedasResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarMonedasResponse'); RemClassRegistry.RegisterXSClass(consultarCotizacionMonedaRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarCotizacionMonedaRequest'); RemClassRegistry.RegisterXSClass(consultarCotizacionMonedaResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarCotizacionMonedaResponse'); RemClassRegistry.RegisterXSClass(consultarUnidadesMedidaRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarUnidadesMedidaRequest'); RemClassRegistry.RegisterXSClass(consultarUnidadesMedidaResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarUnidadesMedidaResponse'); RemClassRegistry.RegisterXSClass(consultarPuntosVentaResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarPuntosVentaResponse'); RemClassRegistry.RegisterXSClass(consultarPuntosVentaCAERequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarPuntosVentaCAERequest'); RemClassRegistry.RegisterXSClass(consultarPuntosVentaCAEResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarPuntosVentaCAEResponse'); RemClassRegistry.RegisterXSClass(informarCAEANoUtilizadoResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'informarCAEANoUtilizadoResponse'); RemClassRegistry.RegisterXSClass(informarCAEANoUtilizadoRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'informarCAEANoUtilizadoRequest'); RemClassRegistry.RegisterXSClass(consultarTiposTributoResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarTiposTributoResponse'); RemClassRegistry.RegisterXSClass(consultarTiposTributoRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarTiposTributoRequest'); RemClassRegistry.RegisterXSClass(informarCAEANoUtilizadoPtoVtaRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'informarCAEANoUtilizadoPtoVtaRequest'); RemClassRegistry.RegisterXSClass(informarCAEANoUtilizadoPtoVtaResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'informarCAEANoUtilizadoPtoVtaResponse'); RemClassRegistry.RegisterXSClass(consultarCAEARequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarCAEARequest'); RemClassRegistry.RegisterXSClass(consultarCAEAResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarCAEAResponse'); RemClassRegistry.RegisterXSClass(consultarPtosVtaCAEANoInformadosRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarPtosVtaCAEANoInformadosRequest'); RemClassRegistry.RegisterXSClass(consultarPtosVtaCAEANoInformadosResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarPtosVtaCAEANoInformadosResponse'); RemClassRegistry.RegisterXSClass(consultarCAEAEntreFechasRequest, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarCAEAEntreFechasRequest'); RemClassRegistry.RegisterXSClass(consultarCAEAEntreFechasResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'consultarCAEAEntreFechasResponse'); RemClassRegistry.RegisterXSClass(comprobanteAsociado, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'comprobanteAsociado'); RemClassRegistry.RegisterXSClass(otroTributo, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'otroTributo'); RemClassRegistry.RegisterXSClass(item, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'item'); RemClassRegistry.RegisterXSClass(subtotalIVA, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'subtotalIVA'); RemClassRegistry.RegisterXSClass(codigoDescripcion, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'codigoDescripcion'); RemClassRegistry.RegisterXSClass(codigoDescripcion2, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'codigoDescripcion2', 'codigoDescripcion'); RemClassRegistry.RegisterXSClass(puntoVenta, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'puntoVenta'); RemClassRegistry.RegisterXSClass(CAEAResponse, 'http://impl.service.wsmtxca.afip.gov.ar/service/', 'CAEAResponse'); end.
{ ORIGINAL FILE: edkErrorCode.h ------------------------------------------ |Emotiv Development Kit API return values| |Copyright (c) 2009 Emotiv Systems, Inc. | ------------------------------------------ Translated by LaKraven Studios Ltd (14th October 2011) Copyright (C) 2011, LaKraven Studios Ltd, All Rights Reserved Last Updated: 14th October 2011 } unit EDK.ErrorCodes; interface const EDK_OK = $0000; // Default success value EDK_UNKNOWN_ERROR = $0001; // An internal error occurred EDK_INVALID_DEV_ID_ERROR = $0002; // Invalid Developer ID EDK_INVALID_PROFILE_ARCHIVE = $0101; // The contents of the buffer supplied to EE_SetUserProfile aren't a valid, serialized EmoEngine profile. EDK_NO_USER_FOR_BASEPROFILE = $0102; // Returned from EE_EmoEngineEventGetUserId if the event supplied contains a base profile (which isn't associated with specific user). EDK_CANNOT_ACQUIRE_DATA = $0200; // The EmoEngine is unable to acquire EEG data for processing. EDK_BUFFER_TOO_SMALL = $0300; // The buffer supplied to the function isn't large enough EDK_OUT_OF_RANGE = $0301; // A parameter supplied to the function is out of range EDK_INVALID_PARAMETER = $0302; // One of the parameters supplied to the function is invalid EDK_PARAMETER_LOCKED = $0303; // The parameter value is currently locked by a running detection and cannot be modified at this time. EDK_COG_INVALID_TRAINING_ACTION = $0304; // The current training action is not in the list of expected training actions EDK_COG_INVALID_TRAINING_CONTROL = $0305; // The current training control is not in the list of expected training controls EDK_COG_INVALID_ACTIVE_ACTION = $0306; // One of the field in the action bits vector is invalid EDK_COG_EXCESS_MAX_ACTIONS = $0307; // The current action bits vector contains more action types than it is allowed EDK_EXP_NO_SIG_AVAILABLE = $0308; // A trained signature is not currently available for use - addition actions (including neutral) may be required EDK_FILESYSTEM_ERROR = $0309; // A filesystem error occurred that prevented the function from succeeding EDK_INVALID_USER_ID = $0400; // The user ID supplied to the function is invalid EDK_EMOENGINE_UNINITIALIZED = $0500; // The EDK needs to be initialized via EE_EngineConnect or EE_EngineRemoteConnect EDK_EMOENGINE_DISCONNECTED = $0501; // The connection with a remote instance of the EmoEngine (made via EE_EngineRemoteConnect) has been lost EDK_EMOENGINE_PROXY_ERROR = $0502; // The API was unable to establish a connection with a remote instance of the EmoEngine. EDK_NO_EVENT = $0600; // There are no new EmoEngine events at this time EDK_GYRO_NOT_CALIBRATED = $0700; // The gyro is not calibrated. Ask the user to stay still for at least 0.5s EDK_OPTIMIZATION_IS_ON = $0800; // Operation failure due to optimization EDK_RESERVED1 = $0900; // Reserved return value function EDK_ErrorToString(error: integer): string; procedure RaiseEdkError(error: integer); implementation uses SysUtils; procedure RaiseEdkError(error: integer); begin if error <> EDK_OK then begin raise Exception.Create(EDK_ErrorToString(Error)) at ReturnAddress; end; end; function EDK_ErrorToString(error: integer): string; begin case error of EDK_OK : Result := '0x0000 Default success value.'; EDK_UNKNOWN_ERROR : Result := '0x0001 An internal error occurred.'; EDK_INVALID_DEV_ID_ERROR : Result := '0x0002 Invalid Developer ID.'; EDK_INVALID_PROFILE_ARCHIVE : Result := '0x0101 The contents of the buffer supplied to EE_SetUserProfile aren''t a valid, serialized EmoEngine profile.'; EDK_NO_USER_FOR_BASEPROFILE : Result := '0x0102 Returned from EE_EmoEngineEventGetUserId if the event supplied contains a base profile (which isn''t associated with specific user).'; EDK_CANNOT_ACQUIRE_DATA : Result := '0x0200 The EmoEngine is unable to acquire EEG data for processing.'; EDK_BUFFER_TOO_SMALL : Result := '0x0300 The buffer supplied to the function isn''t large enough.'; EDK_OUT_OF_RANGE : Result := '0x0301 A parameter supplied to the function is out of range.'; EDK_INVALID_PARAMETER : Result := '0x0302 One of the parameters supplied to the function is invalid.'; EDK_PARAMETER_LOCKED : Result := '0x0303 The parameter value is currently locked by a running detection and cannot be modified at this time.'; EDK_COG_INVALID_TRAINING_ACTION : Result := '0x0304 The current training action is not in the list of expected training actions.'; EDK_COG_INVALID_TRAINING_CONTROL : Result := '0x0305 The current training control is not in the list of expected training controls.'; EDK_COG_INVALID_ACTIVE_ACTION : Result := '0x0306 One of the field in the action bits vector is invalid.'; EDK_COG_EXCESS_MAX_ACTIONS : Result := '0x0307 The current action bits vector contains more action types than it is allowed.'; EDK_EXP_NO_SIG_AVAILABLE : Result := '0x0308 A trained signature is not currently available for use - addition actions (including neutral) may be required.'; EDK_FILESYSTEM_ERROR : Result := '0x0309 A filesystem error occurred that prevented the function from succeeding.'; EDK_INVALID_USER_ID : Result := '0x0400 The user ID supplied to the function is invalid.'; EDK_EMOENGINE_UNINITIALIZED : Result := '0x0500 The EDK needs to be initialized via EE_EngineConnect or EE_EngineRemoteConnect.'; EDK_EMOENGINE_DISCONNECTED : Result := '0x0501 The connection with a remote instance of the EmoEngine (made via EE_EngineRemoteConnect) has been lost.'; EDK_EMOENGINE_PROXY_ERROR : Result := '0x0502 The API was unable to establish a connection with a remote instance of the EmoEngine.'; EDK_NO_EVENT : Result := '0x0600 There are no new EmoEngine events at this time.'; EDK_GYRO_NOT_CALIBRATED : Result := '0x0700 The gyro is not calibrated. Ask the user to stay still for at least 0.5s.'; EDK_OPTIMIZATION_IS_ON : Result := '0x0800 Operation failure due to optimization.'; EDK_RESERVED1 : Result := '0x0900 Reserved return value.'; end; end; end.
unit ErrorCodes; interface const errNoError = 0; errMalformedQuery = 1; errIllegalObject = 2; errUnexistentProperty = 3; errIllegalPropValue = 4; errUnexistentMethod = 5; errIllegalParamList = 6; errIllegalPropType = 7; errQueryTimedOut = 8; errIllegalFunctionRes = 9; errSendError = 10; errReceiveError = 11; errMalformedResult = 12; errQueryQueueOverflow = 13; errRDOServerNotInitialized = 14; errUnknownError = 15; errNoResult = 16; errServerBusy = 17; function CreateErrorMessage( ErrorCode : integer ) : string; implementation uses SysUtils; function CreateErrorMessage( ErrorCode : integer ) : string; begin if ErrorCode <> errNoError then Result := 'error ' + IntToStr( ErrorCode ) else Result := '' end; end.
unit evCustomEditorModelPart; {* Часть TevCustomEditor перенесённая на модель } // Модуль: "w:\common\components\gui\Garant\Everest\evCustomEditorModelPart.pas" // Стереотип: "GuiControl" // Элемент модели: "TevCustomEditorModelPart" MUID: (4B877C5101C1) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evMultiSelectEditorWindow ; type TevAllowParaType = ( {* Разрешённые типы параграфов } ev_aptTable , ev_aptSBS , ev_aptPicture , ev_aptFormula , ev_aptPageBreak );//TevAllowParaType TevAllowParaTypes = set of TevAllowParaType; {* Множество типов разрешённых параграфов } TevCustomEditorModelPart = class(TevMultiSelectEditorWindow) {* Часть TevCustomEditor перенесённая на модель } protected function pm_GetAllowParaType: TevAllowParaTypes; virtual; protected property AllowParaType: TevAllowParaTypes read pm_GetAllowParaType; end;//TevCustomEditorModelPart implementation uses l3ImplUses {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *4B877C5101C1impl_uses* //#UC END# *4B877C5101C1impl_uses* ; function TevCustomEditorModelPart.pm_GetAllowParaType: TevAllowParaTypes; //#UC START# *4B877E7B0330_4B877C5101C1get_var* //#UC END# *4B877E7B0330_4B877C5101C1get_var* begin //#UC START# *4B877E7B0330_4B877C5101C1get_impl* Result := [Low(TevAllowParaType) .. High(TevAllowParaType)]; //#UC END# *4B877E7B0330_4B877C5101C1get_impl* end;//TevCustomEditorModelPart.pm_GetAllowParaType initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TevCustomEditorModelPart); {* Регистрация TevCustomEditorModelPart } {$IfEnd} // NOT Defined(NoScripts) end.
unit evMergedCellFilter; {* фильтр для преобразования "подвисших" ячеек объединения в нормальный вид. } // Модуль: "w:\common\components\gui\Garant\Everest\evMergedCellFilter.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevMergedCellFilter" MUID: (49C21D090093) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , k2TagFilter , evCellsOffsets , evdTypes , k2Base , l3Variant ; type TevNeedAddTextPara = ( ev_natNo , ev_natYes , ev_natWaitMergeStatus );//TevNeedAddTextPara TevMergedCellFilter = class(Tk2TagFilter) {* фильтр для преобразования "подвисших" ячеек объединения в нормальный вид. } private f_CellsOffsets: TevCellsOffsets; {* Смещения для поиска ячеек. } f_MergeStatus: TevMergeStatus; f_HasChild: Boolean; {* Есть ли у ячейки хоть один дочерний. } f_CorrectedWidth: Boolean; {* Ширина была изменена. } f_NewWidth: Integer; {* Новая ширина ячейки. } f_NeedAddTextPara: TevNeedAddTextPara; {* Нужно ли проверять дочерние. } private function CellsOffsets: TevCellsOffsets; function IsTableCell: Boolean; procedure CheckCellWidth; {* Проверяет ширину ячейки и, если надо корректирует её. } protected procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DoStartChild(TypeID: Tk2Type); override; procedure DoAddAtomEx(AtomIndex: Integer; const Value: Ik2Variant); override; procedure DoCloseStructure(NeedUndo: Boolean); override; end;//TevMergedCellFilter implementation uses l3ImplUses , l3Base , Table_Const , TableRow_Const , TableCell_Const , k2Tags , SBSCell_Const , l3UnitsTools //#UC START# *49C21D090093impl_uses* //#UC END# *49C21D090093impl_uses* ; function TevMergedCellFilter.CellsOffsets: TevCellsOffsets; //#UC START# *4E4517310268_49C21D090093_var* //#UC END# *4E4517310268_49C21D090093_var* begin //#UC START# *4E4517310268_49C21D090093_impl* if f_CellsOffsets = nil then f_CellsOffsets := TevCellsOffsets.Create; Result := f_CellsOffsets; //#UC END# *4E4517310268_49C21D090093_impl* end;//TevMergedCellFilter.CellsOffsets function TevMergedCellFilter.IsTableCell: Boolean; //#UC START# *4FA3B42B01C6_49C21D090093_var* //#UC END# *4FA3B42B01C6_49C21D090093_var* begin //#UC START# *4FA3B42B01C6_49C21D090093_impl* Result := CurrentType.IsKindOf(k2_typTableCell) and not CurrentType.IsKindOf(k2_typSBSCell); //#UC END# *4FA3B42B01C6_49C21D090093_impl* end;//TevMergedCellFilter.IsTableCell procedure TevMergedCellFilter.CheckCellWidth; {* Проверяет ширину ячейки и, если надо корректирует её. } //#UC START# *517E60E501A8_49C21D090093_var* //#UC END# *517E60E501A8_49C21D090093_var* begin //#UC START# *517E60E501A8_49C21D090093_impl* // Делаем шире слишком тонкие ячейки: f_CorrectedWidth := (f_NewWidth > 0) and (f_NewWidth < evCellWidthEpsilon); if f_CorrectedWidth then f_NewWidth := evCellWidthEpsilon; // С отрицательной шириной поступаем также, как и в Немезисе - пусть юристы видят реальную картину! if not f_CorrectedWidth then begin f_CorrectedWidth := (f_NewWidth < 0); if f_CorrectedWidth then f_NewWidth := -f_NewWidth; end; // if not f_CorrectedWidth then //#UC END# *517E60E501A8_49C21D090093_impl* end;//TevMergedCellFilter.CheckCellWidth procedure TevMergedCellFilter.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_49C21D090093_var* //#UC END# *479731C50290_49C21D090093_var* begin //#UC START# *479731C50290_49C21D090093_impl* l3Free(f_CellsOffsets); inherited; //#UC END# *479731C50290_49C21D090093_impl* end;//TevMergedCellFilter.Cleanup procedure TevMergedCellFilter.DoStartChild(TypeID: Tk2Type); //#UC START# *4A2D1217037A_49C21D090093_var* //#UC END# *4A2D1217037A_49C21D090093_var* begin //#UC START# *4A2D1217037A_49C21D090093_impl* if (TypeID = k2_typTable) then begin if (f_CellsOffsets <> nil) then f_CellsOffsets.Clear; end; if (TypeID = k2_typTableRow) then begin f_MergeStatus := ev_msNone; CellsOffsets.ClearOffset; f_HasChild := False; end; // if (TypeID = k2_idTableRow) then if (TypeID = k2_typTableCell) then begin f_MergeStatus := ev_msNone; f_NeedAddTextPara := ev_natNo; f_HasChild := False; f_NewWidth := 0; end; // if (TypeID = k2_idTableCell) then if TopType[1].IsKindOf(k2_typTableCell) then f_HasChild := True; inherited; //#UC END# *4A2D1217037A_49C21D090093_impl* end;//TevMergedCellFilter.DoStartChild procedure TevMergedCellFilter.DoAddAtomEx(AtomIndex: Integer; const Value: Ik2Variant); //#UC START# *4A2D1634025B_49C21D090093_var* procedure lp_CheckOffset; begin f_NeedAddTextPara := ev_natNo; if f_CellsOffsets <> nil then f_CellsOffsets.CheckOffset(False); end; procedure lp_CheckNeedAddText; begin if f_NewWidth <> 0 then begin f_NeedAddTextPara := TevNeedAddTextPara(Ord(f_CellsOffsets = nil)); if f_NeedAddTextPara = ev_natNo then f_NeedAddTextPara := TevNeedAddTextPara(Ord(f_CellsOffsets.CheckParam)); end // if f_NewWidth = 0 then else f_NeedAddTextPara := ev_natWaitMergeStatus; end; //#UC END# *4A2D1634025B_49C21D090093_var* begin //#UC START# *4A2D1634025B_49C21D090093_impl* if IsTableCell then begin if (AtomIndex = k2_tiWidth) then begin f_NewWidth := Value.AsInteger; CheckCellWidth; CellsOffsets.SetWidth(f_NewWidth); if f_NeedAddTextPara = ev_natWaitMergeStatus then lp_CheckNeedAddText; if f_CorrectedWidth then Exit; end; // if (AtomIndex = k2_tiWidth) then if (AtomIndex = k2_tiMergeStatus) then begin f_MergeStatus := TevMergeStatus(VariantAsInteger(AtomIndex, Value)); case f_MergeStatus of ev_msHead: begin lp_CheckOffset; CellsOffsets.AddCellWidth; end; // ev_msHead ev_msNone: lp_CheckOffset; ev_msContinue: begin lp_CheckNeedAddText; if f_NeedAddTextPara = ev_natYes then Exit; end; // ev_msContinue: begin end; // case l_MergeStatus of end; // if (AtomIndex = k2_tiMergeStatus) then if (AtomIndex = k2_tiChildren) and (f_NeedAddTextPara = ev_natYes) then f_NeedAddTextPara := TevNeedAddTextPara(Ord(Value.AsInteger = 0)); end; // if CurrentType.IsKindOf(k2_typTableCell) then inherited; //#UC END# *4A2D1634025B_49C21D090093_impl* end;//TevMergedCellFilter.DoAddAtomEx procedure TevMergedCellFilter.DoCloseStructure(NeedUndo: Boolean); //#UC START# *4E45166B0156_49C21D090093_var* function lp_NeedAddChildTextPara: Boolean; begin Result := (f_NeedAddTextPara = ev_natYes) or ((f_MergeStatus = ev_msHead) and not f_HasChild); end; //#UC END# *4E45166B0156_49C21D090093_var* begin //#UC START# *4E45166B0156_49C21D090093_impl* if IsTableCell then begin if f_CorrectedWidth then Generator.AddIntegerAtom(k2_tiWidth, f_NewWidth); if lp_NeedAddChildTextPara and (Generator <> nil) then begin Generator.StartDefaultChild; try Generator.AddStringAtom(k2_tiText, ''); finally Generator.Finish; f_NeedAddTextPara := ev_natNo; end; end; // if f_CheckChildren and (Generator <> nil) then CellsOffsets.RecalcOffset; end; // if CurrentType.IsKindOf(k2_typTableCell) then inherited; //#UC END# *4E45166B0156_49C21D090093_impl* end;//TevMergedCellFilter.DoCloseStructure end.
unit MFichas.Model.GrupoProduto.Interfaces; interface uses MFichas.Model.Entidade.GRUPOPRODUTO, ORMBR.Container.ObjectSet.Interfaces, ORMBR.Container.DataSet.Interfaces, FireDAC.Comp.Client; type iModelGrupoProduto = interface; iModelGrupoProdutoMetodos = interface; iModelGrupoProdutoMetodosCadastrar = interface; iModelGrupoProdutoMetodosEditar = interface; iModelGrupoProdutoMetodosBuscar = interface; iModelGrupoProduto = interface ['{6AF44436-FC7C-4A59-930B-BD8D2A38AC15}'] function Metodos : iModelGrupoProdutoMetodos; function Entidade : TGRUPOPRODUTO; overload; function Entidade(AEntidade: TGRUPOPRODUTO): iModelGrupoProduto; overload; function DAO : iContainerObjectSet<TGRUPOPRODUTO>; function DAODataSet : iContainerDataSet<TGRUPOPRODUTO>; end; iModelGrupoProdutoMetodos = interface ['{71758538-4D50-4DF8-964D-454570EE0549}'] function Cadastrar: iModelGrupoProdutoMetodosCadastrar; function Editar : iModelGrupoProdutoMetodosEditar; function Buscar : iModelGrupoProdutoMetodosBuscar; function &End : iModelGrupoProduto; end; iModelGrupoProdutoMetodosCadastrar = interface ['{1E182DF8-3C14-47E9-B219-C7A706B2D951}'] function Descricao(ADescricao: String): iModelGrupoProdutoMetodosCadastrar; function &End : iModelGrupoProdutoMetodos; end; iModelGrupoProdutoMetodosEditar = interface ['{8185AAF8-08F3-4880-AF0A-AA4D337DE02C}'] function GUUID(AGUUID: String) : iModelGrupoProdutoMetodosEditar; function Descricao(ADescricao: String): iModelGrupoProdutoMetodosEditar; function AtivoInativo(AValue: Integer): iModelGrupoProdutoMetodosEditar; function &End : iModelGrupoProdutoMetodos; end; iModelGrupoProdutoMetodosBuscar = interface ['{D4C50BEF-1027-4A5E-A57A-30265A9DEC4C}'] function FDMemTable(AFDMemTable: TFDMemTable): iModelGrupoProdutoMetodosBuscar; function BuscarTodos : iModelGrupoProdutoMetodosBuscar; function BuscarTodosAtivos : iModelGrupoProdutoMetodosBuscar; function &End : iModelGrupoProdutoMetodos; end; implementation end.
Program OrdenarVector; const max=30; Type vector= array [1..max] of integer; Var A:vector; n:integer; {Dado un vector de números reales A, escriba un procedimiento ORDENAR que ordene los elementos del vector de tal forma que los números pares aparezcan antes que los números impares. Además, los números pares deberán estar ordenados de forma ascendente, mientras que los números impares deberán estar ordenados de forma descendente.} Procedure LlenarVectorManual(var A:vector; n:integer); var i:integer; begin for i:=1 to n do begin write('A[',i,'] => '); readln(A[i]); end; end; Procedure LlenarVectorRandom(var A:vector; n:integer); var i:integer; begin randomize; for i:=1 to n do begin A[i]:= random(9)+1; end; end; Procedure MostrarVector(var A:vector; n:integer); var i:integer; begin for i:=1 to n do begin write(A[i], ' '); end; writeln(' '); end; Function esPar(A:vector;i,n:integer;var p:integer;var haypares:boolean):integer; var j,par,cont:Integer; begin cont:=0; par:=0; for j:=i to n do begin if((A[j] mod 2) = 0) then begin par:=A[j]; p:=j; cont:=cont+1; end; end; if (cont=0) then begin haypares:=false; end; esPar:=par; end; Procedure Ordenar(var A:vector; n:integer); var aux,contpares,i,j,p,par,posultpar:integer; haypares:boolean; begin haypares:=true; contpares:=0; i:=1; while((i<=n) and (haypares)) do begin par:= esPar(A,i,n,p,haypares); if(haypares)then begin A[p]:= A[i]; A[i]:=par; contpares:=contpares+1; posultpar:=i; end; i:=i+1; end; write('El vector separado en pares/impares sin ordenar es=> '); MostrarVector(A,n); writeln('el ultimo par es=> ', A[posultpar],' con posicion => ', posultpar); //ordenar de menor los pares(barajas) if(contpares>1) then begin for i:=2 to posultpar do for j:=1 to i-1 do if (A[i] < A[j]) then begin aux:=A[i]; A[i]:=A[j]; A[j]:=aux; end; end; //ordenar de mayor a menor los impares(barajas) for i:=posultpar+2 to n do begin for j:=posultpar+1 to i-1 do if (A[i] > A[j]) then begin aux:=A[i]; A[i]:=A[j]; A[j]:=aux; end; end; end; Begin repeat writeln('Introduzca la dimension del vector'); readln(n); until(n<30); LlenarVectorRandom(A,n); //LlenarVectorManual(A,n); write('El vector es=> '); MostrarVector(A,n); Ordenar(A,n); write('El vector ordenado es=> '); MostrarVector(A,n); End.
{ Exercicio 83: Faça um algoritmo que receba a idade, o peso e o sexo de 10 pessoas. Calcule e imprima: a) total de homens; b) total de mulheres; c) média da idade dos homens; d) média dos pesos das mulheres. } { Solução em Portugol Algoritmo Exercicio ; Var peso: vetor[1..10] de real; idade: vetor[1..10] de inteiro; sexo: vetor[1..10] de caracter; media_peso_mulher,soma_peso_mulher,media_idade_homem: real; i,soma_idade_homem,homem,mulher: inteiro; Inicio soma_peso_mulher <- 0; soma_idade_homem <- 0; homem <- 0; mulher <- 0; exiba("Programa que armazena a idade, sexo, peso de 10 pessoas e exibe um relatório desses dados."); para i <- 1 até 10 faça exiba("Digite o sexo da pessoa:"); // Leitura dos dados. Sexo -> Idade -> Peso, com consistência de dados. leia(sexo[i]); enquanto((sexo[i] <> 'M') e (sexo[i] <> 'F'))faça exiba("Digite F para feminino e M para masculino"); leia(sexo[i]); fimenquanto; exiba("Digite a idade da pessoa:"); leia(idade[i]); enquanto(idade < 0)faça exiba("Digite uma idade válida:"); leia(idade[i]); fimenquanto; exiba("Digite o peso da pessoa:"); leia(peso[i]); enquanto(peso[i] < 0)faça exiba("Digite um peso válido:"); leia(peso[i]); fimenquanto; caso(sexo[i])de // Acumulando as quantidade de homens, mulheres, "F": Inicio // pesos das mulheres e idades dos homens. mulher <- mulher + 1; soma_peso_mulher <- soma_peso_mulher + peso[i]; Fim; "M": Inicio homem <- homem + 1; soma_idade_homem <- soma_idade_homem + idade[i]; Fim; fimcaso; fimpara; exiba("Quantidade de homens: ",homem); // Questão (a) exiba("Quantidade de mulheres: ",mulher); // Questão (b) se(homem > 0) // Questão (c) então Inicio media_idade_homem := soma_idade_homem/homem; exiba("A média de idade dos homens é de ", media_idade_homem:0:2," anos."); Fim senão exiba("Nenhum homem no grupo. Não é possível calcular a média."); se(mulher > 0) então Inicio // Questão (d) media_peso_mulher := soma_peso_mulher/mulher; exiba("A média de peso das mulheres é de ", media_peso_mulher:0:2," kg."); Fim senão exiba("Nenhuma mulher no grupo. Não é possível calcular a média."); Fim. } // Solução em Pascal Program Exercicio83; uses crt; Var peso: array[1..10] of real; idade: array[1..10] of integer; sexo: array[1..10] of char; media_peso_mulher,soma_peso_mulher,media_idade_homem: real; i,soma_idade_homem,homem,mulher: integer; Begin soma_peso_mulher := 0; soma_idade_homem := 0; homem := 0; mulher := 0; writeln('Programa que armazena a idade, sexo, peso de 10 pessoas e exibe um relatório desses dados.'); for i := 1 to 10 do Begin // Leitura dos dados. Sexo -> Idade -> Peso, com consistência de dados. writeln('Digite o sexo da pessoa:'); readln(sexo[i]); while((sexo[i] <> 'M') and (sexo[i] <> 'F'))do Begin writeln('Digite F para feminino ou M para masculino:'); readln(sexo[i]); End; writeln('Digite a idade da pessoa:'); readln(idade[i]); while(idade[i] < 0)do Begin writeln('Digite uma idade válida:'); readln(idade[i]); End; writeln('Digite o peso da pessoa:'); readln(peso[i]); while(peso[i] < 0)do Begin writeln('Digite um peso válido:'); readln(peso[i]); End; case(sexo[i])of // Acumulando as quantidade de homens, mulheres, 'F': Begin // pesos das mulheres e idades dos homens. mulher := mulher + 1; soma_peso_mulher := soma_peso_mulher + peso[i]; End; 'M': Begin homem := homem + 1; soma_idade_homem := soma_idade_homem + idade[i]; End; End; End; writeln('Quantidade de homens: ',homem); // Questão (a) writeln('Quantidade de mulheres: ',mulher); // Questão (b) if(homem > 0) // Questão (c) then Begin media_idade_homem := soma_idade_homem/homem; writeln('A média de idade dos homens é de ', media_idade_homem:0:2,' anos.'); End else writeln('Nenhum homem no grupo. Não é possível calcular a média.'); if(mulher > 0) then Begin // Questão (d) media_peso_mulher := soma_peso_mulher/mulher; writeln('A média de peso das mulheres é de ', media_peso_mulher:0:2,' kg.'); End else writeln('Nenhuma mulher no grupo. Não é possível calcular a média.'); repeat until keypressed; end.
unit TTSTDOCTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TTTSTDOCRecord = record PLenderNum: String[4]; PCifFlag: String[1]; PLoanNum: String[20]; PCollNum: Integer; PCategory: String[8]; PSubNum: SmallInt; PDocCount: Integer; PDescription: String[30]; PDateStamp: String[10]; End; TTTSTDOCBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TTTSTDOCRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEITTSTDOC = (TTSTDOCPrimaryKey); TTTSTDOCTable = class( TDBISAMTableAU ) private FDFLenderNum: TStringField; FDFCifFlag: TStringField; FDFLoanNum: TStringField; FDFCollNum: TIntegerField; FDFCategory: TStringField; FDFSubNum: TSmallIntField; FDFDocCount: TIntegerField; FDFDescription: TStringField; FDFDateStamp: TStringField; FDFImage: TBlobField; procedure SetPLenderNum(const Value: String); function GetPLenderNum:String; procedure SetPCifFlag(const Value: String); function GetPCifFlag:String; procedure SetPLoanNum(const Value: String); function GetPLoanNum:String; procedure SetPCollNum(const Value: Integer); function GetPCollNum:Integer; procedure SetPCategory(const Value: String); function GetPCategory:String; procedure SetPSubNum(const Value: SmallInt); function GetPSubNum:SmallInt; procedure SetPDocCount(const Value: Integer); function GetPDocCount:Integer; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPDateStamp(const Value: String); function GetPDateStamp:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEITTSTDOC); function GetEnumIndex: TEITTSTDOC; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TTTSTDOCRecord; procedure StoreDataBuffer(ABuffer:TTTSTDOCRecord); property DFLenderNum: TStringField read FDFLenderNum; property DFCifFlag: TStringField read FDFCifFlag; property DFLoanNum: TStringField read FDFLoanNum; property DFCollNum: TIntegerField read FDFCollNum; property DFCategory: TStringField read FDFCategory; property DFSubNum: TSmallIntField read FDFSubNum; property DFDocCount: TIntegerField read FDFDocCount; property DFDescription: TStringField read FDFDescription; property DFDateStamp: TStringField read FDFDateStamp; property DFImage: TBlobField read FDFImage; property PLenderNum: String read GetPLenderNum write SetPLenderNum; property PCifFlag: String read GetPCifFlag write SetPCifFlag; property PLoanNum: String read GetPLoanNum write SetPLoanNum; property PCollNum: Integer read GetPCollNum write SetPCollNum; property PCategory: String read GetPCategory write SetPCategory; property PSubNum: SmallInt read GetPSubNum write SetPSubNum; property PDocCount: Integer read GetPDocCount write SetPDocCount; property PDescription: String read GetPDescription write SetPDescription; property PDateStamp: String read GetPDateStamp write SetPDateStamp; published property Active write SetActive; property EnumIndex: TEITTSTDOC read GetEnumIndex write SetEnumIndex; end; { TTTSTDOCTable } procedure Register; implementation function TTTSTDOCTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TTTSTDOCTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TTTSTDOCTable.GenerateNewFieldName } function TTTSTDOCTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TTTSTDOCTable.CreateField } procedure TTTSTDOCTable.CreateFields; begin FDFLenderNum := CreateField( 'LenderNum' ) as TStringField; FDFCifFlag := CreateField( 'CifFlag' ) as TStringField; FDFLoanNum := CreateField( 'LoanNum' ) as TStringField; FDFCollNum := CreateField( 'CollNum' ) as TIntegerField; FDFCategory := CreateField( 'Category' ) as TStringField; FDFSubNum := CreateField( 'SubNum' ) as TSmallIntField; FDFDocCount := CreateField( 'DocCount' ) as TIntegerField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFDateStamp := CreateField( 'DateStamp' ) as TStringField; FDFImage := CreateField( 'Image' ) as TBlobField; end; { TTTSTDOCTable.CreateFields } procedure TTTSTDOCTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TTTSTDOCTable.SetActive } procedure TTTSTDOCTable.SetPLenderNum(const Value: String); begin DFLenderNum.Value := Value; end; function TTTSTDOCTable.GetPLenderNum:String; begin result := DFLenderNum.Value; end; procedure TTTSTDOCTable.SetPCifFlag(const Value: String); begin DFCifFlag.Value := Value; end; function TTTSTDOCTable.GetPCifFlag:String; begin result := DFCifFlag.Value; end; procedure TTTSTDOCTable.SetPLoanNum(const Value: String); begin DFLoanNum.Value := Value; end; function TTTSTDOCTable.GetPLoanNum:String; begin result := DFLoanNum.Value; end; procedure TTTSTDOCTable.SetPCollNum(const Value: Integer); begin DFCollNum.Value := Value; end; function TTTSTDOCTable.GetPCollNum:Integer; begin result := DFCollNum.Value; end; procedure TTTSTDOCTable.SetPCategory(const Value: String); begin DFCategory.Value := Value; end; function TTTSTDOCTable.GetPCategory:String; begin result := DFCategory.Value; end; procedure TTTSTDOCTable.SetPSubNum(const Value: SmallInt); begin DFSubNum.Value := Value; end; function TTTSTDOCTable.GetPSubNum:SmallInt; begin result := DFSubNum.Value; end; procedure TTTSTDOCTable.SetPDocCount(const Value: Integer); begin DFDocCount.Value := Value; end; function TTTSTDOCTable.GetPDocCount:Integer; begin result := DFDocCount.Value; end; procedure TTTSTDOCTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TTTSTDOCTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TTTSTDOCTable.SetPDateStamp(const Value: String); begin DFDateStamp.Value := Value; end; function TTTSTDOCTable.GetPDateStamp:String; begin result := DFDateStamp.Value; end; procedure TTTSTDOCTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNum, String, 4, N'); Add('CifFlag, String, 1, N'); Add('LoanNum, String, 20, N'); Add('CollNum, Integer, 0, N'); Add('Category, String, 8, N'); Add('SubNum, SmallInt, 0, N'); Add('DocCount, Integer, 0, N'); Add('Description, String, 30, N'); Add('DateStamp, String, 10, N'); Add('Image, Blob, 0, N'); end; end; procedure TTTSTDOCTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNum;CifFlag;LoanNum;CollNum;Category;SubNum;DocCount, Y, Y, Y, Y'); end; end; procedure TTTSTDOCTable.SetEnumIndex(Value: TEITTSTDOC); begin case Value of TTSTDOCPrimaryKey : IndexName := ''; end; end; function TTTSTDOCTable.GetDataBuffer:TTTSTDOCRecord; var buf: TTTSTDOCRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNum := DFLenderNum.Value; buf.PCifFlag := DFCifFlag.Value; buf.PLoanNum := DFLoanNum.Value; buf.PCollNum := DFCollNum.Value; buf.PCategory := DFCategory.Value; buf.PSubNum := DFSubNum.Value; buf.PDocCount := DFDocCount.Value; buf.PDescription := DFDescription.Value; buf.PDateStamp := DFDateStamp.Value; result := buf; end; procedure TTTSTDOCTable.StoreDataBuffer(ABuffer:TTTSTDOCRecord); begin DFLenderNum.Value := ABuffer.PLenderNum; DFCifFlag.Value := ABuffer.PCifFlag; DFLoanNum.Value := ABuffer.PLoanNum; DFCollNum.Value := ABuffer.PCollNum; DFCategory.Value := ABuffer.PCategory; DFSubNum.Value := ABuffer.PSubNum; DFDocCount.Value := ABuffer.PDocCount; DFDescription.Value := ABuffer.PDescription; DFDateStamp.Value := ABuffer.PDateStamp; end; function TTTSTDOCTable.GetEnumIndex: TEITTSTDOC; var iname : string; begin result := TTSTDOCPrimaryKey; iname := uppercase(indexname); if iname = '' then result := TTSTDOCPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'TTS Tables', [ TTTSTDOCTable, TTTSTDOCBuffer ] ); end; { Register } function TTTSTDOCBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..9] of string = ('LENDERNUM','CIFFLAG','LOANNUM','COLLNUM','CATEGORY','SUBNUM' ,'DOCCOUNT','DESCRIPTION','DATESTAMP' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 9) and (flist[x] <> s) do inc(x); if x <= 9 then result := x else result := 0; end; function TTTSTDOCBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftInteger; 5 : result := ftString; 6 : result := ftSmallInt; 7 : result := ftInteger; 8 : result := ftString; 9 : result := ftString; end; end; function TTTSTDOCBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNum; 2 : result := @Data.PCifFlag; 3 : result := @Data.PLoanNum; 4 : result := @Data.PCollNum; 5 : result := @Data.PCategory; 6 : result := @Data.PSubNum; 7 : result := @Data.PDocCount; 8 : result := @Data.PDescription; 9 : result := @Data.PDateStamp; end; end; end.
unit Jc.CryptS; interface uses Windows, Messages, SysUtils, Classes; type TCryptS = class private class var FInstance: TCryptS; private FKey: string; FText: string; FCriptoBin: string; FCriptoHex: string; function Invert(SText: string): string; function DecToHex(Number: Byte): string; function HexToDec(Number: string): Byte; function TextToCriptoBin(SText: string): string; function TextToCriptoHex(SText: string): string; function CriptoBinToText(SText: string): string; function CriptoHexToText(SText: string): string; public constructor Create(const Key: String); overload; constructor Create(); overload; destructor Destroy; override; class function New(const Key: String = ''): TCryptS; function Crypt(AValue: String): String; function Decrypt(AValue: String): String; end; implementation constructor TCryptS.Create(const Key: String); begin FKey := Key; end; constructor TCryptS.Create; begin FKey := 'YUQL23KL23DF90WI5E1JAS467NMCXXL6JAOAUWWMCL0AOMM4A4VZYW9KHJUI2347EJHJKDF3424SKL'; end; destructor TCryptS.Destroy; begin inherited; end; class function TCryptS.New(const Key: String): TCryptS; begin if FInstance = nil then begin if Key.Trim <> '' then FInstance := TCryptS.Create(Key) else FInstance := TCryptS.Create; end; result := FInstance; end; function TCryptS.Crypt(AValue: String): String; begin Result := TextToCriptoHex(AValue) end; function TCryptS.Decrypt(AValue: String): String; begin Result := CriptoHexToText(AValue) end; function TCryptS.TextToCriptoBin(SText: string): string; var SPos: Integer; BKey: Byte; S: string; begin SText := Invert(SText); Result := ''; for SPos := 1 to Length(SText) do begin S := Copy(FKey, (SPos mod Length(FKey)) + 1, 1); BKey := Ord(S[1]) + SPos; Result := Result + Chr(Ord(SText[SPos]) xor BKey); end; end; function TCryptS.CriptoBinToText(SText: string): string; var SPos: Integer; BKey: Byte; S: string; begin Result := ''; for SPos := 1 to Length(SText) do begin S := Copy(FKey, (SPos mod Length(FKey)) + 1, 1); BKey := Ord(S[1]) + SPos; Result := Result + Chr(Ord(SText[SPos]) xor BKey); end; Result := Invert(Result); end; function TCryptS.TextToCriptoHex(SText: string): string; var SPos: Integer; begin SText := TextToCriptoBin(SText); Result := ''; for SPos := 1 to Length(SText) do Result := Result + DecToHex(Ord(SText[SPos])); end; function TCryptS.CriptoHexToText(SText: string): string; var SPos: Integer; begin Result := ''; for SPos := 1 to (Length(SText) div 2) do Result := Result + Chr(HexToDec(Copy(SText, ((SPos * 2) - 1), 2))); Result := CriptoBinToText(Result); end; function TCryptS.Invert(SText: string): string; var Position: Integer; begin Result := ''; for Position := Length(SText) downto 1 do Result := Result + SText[Position]; end; function TCryptS.DecToHex(Number: Byte): string; begin Result := Copy('0123456789ABCDEF', (Number mod 16) + 1, 1); Number := Number div 16; Result := Copy('0123456789ABCDEF', (Number mod 16) + 1, 1) + Result end; function TCryptS.HexToDec(Number: string): Byte; begin Number := UpperCase(Number); Result := (Pos(Number[1], '0123456789ABCDEF') - 1) * 16; Result := Result + (Pos(Number[2], '0123456789ABCDEF') - 1); end; initialization finalization if TCryptS.FInstance <> nil then begin TCryptS.FInstance.Free; TCryptS.FInstance := nil; end; end.
unit SDDataTestForm; interface uses Windows, Forms, BaseForm, Classes, Controls, StdCtrls, Sysutils; type TfrmSDDataTest = class(TfrmBase) btnDownload163: TButton; btnDownloadSina: TButton; edtStockCode: TEdit; btnImportTDX: TButton; lbl1: TLabel; btnDownload163All: TButton; btnDownloadSinaAll: TButton; btnDownloadAll: TButton; btnDownloadXueqiu: TButton; btnDownloadXueqiuAll: TButton; btnDownloadQQ: TButton; btnDownloadQQAll: TButton; lbStock163: TEdit; lbStockSina: TEdit; lbStockXQ: TEdit; lbStockQQ: TEdit; btnShutDown: TButton; btTestMem: TButton; procedure btnDownload163Click(Sender: TObject); procedure btnDownloadSinaClick(Sender: TObject); procedure btnDownloadXueqiuClick(Sender: TObject); procedure btnDownload163AllClick(Sender: TObject); procedure btnDownloadSinaAllClick(Sender: TObject); procedure btnDownloadXueqiuAllClick(Sender: TObject); procedure btnDownloadQQClick(Sender: TObject); procedure btnDownloadQQAllClick(Sender: TObject); procedure btnDownloadAllClick(Sender: TObject); procedure btnShutDownClick(Sender: TObject); procedure btTestMemClick(Sender: TObject); private { Private declarations } function GetStockCode: integer; procedure RequestDownloadStockData(AStockCode, ADataSrc: integer); public { Public declarations } end; implementation {$R *.dfm} uses windef_msg, win.shutdown, define_price, define_datasrc, define_dealitem, define_StockDataApp, UtilsHttp, StockDayData_Get_Sina, BaseWinApp; function TfrmSDDataTest.GetStockCode: integer; begin Result := StrToIntDef(edtStockCode.Text, 0); end; procedure TfrmSDDataTest.RequestDownloadStockData(AStockCode, ADataSrc: integer); begin if IsWindow(TBaseWinApp(App).AppWindow) then begin PostMessage(TBaseWinApp(App).AppWindow, WM_Console_Command_Download, AStockCode, ADataSrc); end; end; procedure TfrmSDDataTest.btnDownloadAllClick(Sender: TObject); begin RequestDownloadStockData(0, 0); end; procedure TfrmSDDataTest.btnDownload163AllClick(Sender: TObject); begin RequestDownloadStockData(0, DataSrc_163); end; procedure TfrmSDDataTest.btnDownload163Click(Sender: TObject); begin RequestDownloadStockData(GetStockCode, DataSrc_163); end; procedure TfrmSDDataTest.btnDownloadQQAllClick(Sender: TObject); begin RequestDownloadStockData(0, DataSrc_QQ); end; procedure TfrmSDDataTest.btnDownloadQQClick(Sender: TObject); begin RequestDownloadStockData(GetStockCode, DataSrc_QQ); end; procedure TfrmSDDataTest.btnDownloadSinaAllClick(Sender: TObject); begin RequestDownloadStockData(0, DataSrc_Sina); end; procedure TfrmSDDataTest.btnDownloadSinaClick(Sender: TObject); begin RequestDownloadStockData(GetStockCode, DataSrc_Sina); end; procedure TfrmSDDataTest.btnDownloadXueqiuAllClick(Sender: TObject); begin RequestDownloadStockData(0, DataSrc_XQ); end; procedure TfrmSDDataTest.btnDownloadXueqiuClick(Sender: TObject); begin RequestDownloadStockData(GetStockCode, DataSrc_XQ); end; procedure TfrmSDDataTest.btnShutDownClick(Sender: TObject); begin inherited; win.shutdown.ShutDown; end; procedure TfrmSDDataTest.btTestMemClick(Sender: TObject); var tmpHttpClientSession: THttpClientSession; tmpStockItem: TRT_DealItem; begin inherited; // FillChar(tmpHttpClientSession, SizeOf(tmpHttpClientSession), 0); FillChar(tmpStockItem, SizeOf(tmpStockItem), 0); tmpStockItem.iCode := 600016; tmpStockItem.sCode := '600016'; GetStockDataDay_Sina(App, @tmpStockItem, weightBackward, @tmpHttpClientSession); end; end.