text
stringlengths
14
6.51M
unit InfraMVPVCLIntf; interface uses Types, Windows, Graphics, Classes, Controls, InfraCommonIntf, InfraMVPIntf, InfraValueTypeIntf; type IMVPMapperService = interface(IElement) ['{744FE4AA-FF4D-4410-BB26-F056A7FA65D9}'] function GetKeyInterceptor: IElement; function GetModelFromObject(Obj: TObject): IModel; function GetMouseInterceptor: IElement; procedure SetKeyInterceptor(const Value: IElement); procedure RegisterMVPItem(const Model: IModel; Obj: TObject); procedure RemoveMVPItem(Obj: TObject); procedure SetMouseInterceptor(const Value: IElement); property KeyInterceptor: IElement read GetKeyInterceptor write SetKeyInterceptor; property MouseInterceptor: IElement read GetMouseInterceptor write SetMouseInterceptor; end; // VCL Control events IMVPFormViewDestroyEvent = interface(IInfraEvent) ['{AA33A2A7-6028-496B-AFE3-67FC807FEC0F}'] end; IVCLNotifyEvent = interface(IInfraEvent) ['{EF39470E-1020-448F-A359-D9168560EF72}'] end; IVCLFormDestroyEvent = interface(IVCLNotifyEvent) ['{59EA8775-C5DC-4FAA-82F7-E50C7B1EEAEB}'] end; IVCLFormCloseEvent = interface(IVCLNotifyEvent) ['{86A4A034-B629-4B78-8696-3520A3784861}'] end; IClickEvent = interface(IVCLNotifyEvent) ['{8B04D140-8173-4C05-8B9F-B290C30C9C88}'] end; IVCLDblClickEvent = interface(IVCLNotifyEvent) ['{DA197AB2-E779-44A1-8C58-0248D850019E}'] end; IVCLDragEvent = interface(IInfraEvent) ['{9DECBBCE-1F87-42F2-8C64-66DB7F9EC1EF}'] function GetViewObject: IView; function GetX: Integer; function GetY: Integer; property ViewObject: IView read GetViewObject; property X: Integer read GetX; property Y: Integer read GetY; end; IVCLDragDropEvent = interface(IVCLDragEvent) ['{369D082D-788E-40C6-8362-5603F2D4F7E3}'] end; IVCLDragOverEvent = interface(IVCLDragEvent) ['{537510A4-7AC2-4A85-9631-FC0A9236E84F}'] function GetAccept: boolean; function GetState: TDragState; procedure SetAccept(Value: boolean); property Accept: boolean read GetAccept write SetAccept; property State: TDragState read GetState; end; IVCLEndDragEvent = interface(IVCLDragEvent) ['{1D639B4E-15A9-4005-9FAD-08E948D96719}'] end; IVCLMouseMoveEvent = interface(IInfraEvent) ['{2B4FF361-C8A9-4746-A0CB-8C8ABA45232F}'] function GetShift: TShiftState; function GetX: Integer; function GetY: Integer; property Shift: TShiftState read GetShift; property X: Integer read GetX; property Y: Integer read GetY; end; IVCLMouseEvent = interface(IVCLMouseMoveEvent) ['{4215552C-AA02-42F3-8073-1052FF67A956}'] function GetButton: TMouseButton; property Button: TMouseButton read GetButton; end; IVCLMouseDownEvent = interface(IVCLMouseEvent) ['{26BAD73F-F4F6-4DC8-9F62-F70FFD305359}'] end; IVCLMouseUpEvent = interface(IVCLMouseEvent) ['{2705147F-6EAA-4FC4-977F-DD86FE245059}'] end; IVCLStartDragEvent = interface(IInfraEvent) ['{E7C600B4-9E46-4C01-98AD-BEA472DFA624}'] function GetDragObject: TDragObject; procedure SetDragObject(Value: TDragObject); property DragObject: TDragObject read GetDragObject write SetDragObject; end; IContextPopupEvent = interface(IInfraEvent) ['{397AAE2F-A61D-45D2-8683-B2058836C7D2}'] function GetHandled: Boolean; function GetMousePos: TPoint; procedure SetHandled(bHandled: Boolean); property MousePos: TPoint read GetMousePos; property Handled: Boolean read GetHandled write SetHandled; end; // WinControl events IEnterEvent = interface(IVCLNotifyEvent) ['{C40A7730-31B9-4CB6-A567-618547D58DC8}'] end; IExitEvent = interface(IVCLNotifyEvent) ['{84DB211F-C279-4CA9-8411-A4007A53DD42}'] end; IKeyBoardEvent = Interface(IInfraEvent) ['{09FB8E9A-2DBF-421D-B63E-5AB2D7CE51E3}'] end; IKeyPressEvent = interface(IKeyBoardEvent) ['{E70E2294-96AC-4FF8-9C4F-1C518CE31E51}'] function GetKey: Char; procedure SetKey(AKey: Char); property Key: Char read GetKey write SetKey; end; IKeyEvent = interface(IKeyBoardEvent) ['{E0453B6C-5ADC-420F-9765-2BD59CD36A94}'] function GetKey: Word; function GetShift: TShiftState; procedure SetKey(AKey: Word); property Key: Word read GetKey write SetKey; property Shift: TShiftState read GetShift; end; IKeyDownEvent = interface(IKeyEvent) ['{5F882367-4FF6-4460-B5D8-55757C20B3EC}'] end; IKeyUpEvent = interface(IKeyEvent) ['{80E4479B-A4DA-482F-9548-D5A364139284}'] end; // Views ITextInterface = interface(IInterface) ['{40473959-0679-4658-B9DE-FA3070120E0B}'] function GetText: string; property Text: string read GetText; end; IVCLView = interface(IView) ['{6F0D7DB9-A4BC-46E5-AAC5-6A6FBF1B5510}'] function GetSubViewsIterator: IInfraIterator; function FindViewFromObject(VCLObject: TObject): IView; function GetObject: TObject; procedure SetObject(Value: TObject); property SubViewsIterator: IInfraIterator read GetSubViewsIterator; property VCLObject: TObject read GetObject write SetObject; end; IVCLControlView = interface(IVCLView) ['{9CE501A6-02B4-4BAA-A46A-80E4453854D6}'] function GetVisible: Boolean; procedure SetVisible(Value: Boolean); property Visible: Boolean read GetVisible write SetVisible; end; IVCLWinControlView = interface(IVCLControlView) ['{BA5A8F01-E953-43EE-9139-857DCDBAA990}'] end; IVCLCustomFormView = interface(IVCLWinControlView) ['{C17378B8-4DB0-4F0D-B450-4BFA55625AC6}'] procedure Close; procedure Hide; procedure Show; procedure Release; procedure ShowAndWait; end; IVCLCustomEditView = interface(IVCLWinControlView) ['{5EBB90D2-A95F-4704-9BAB-6487F0AA5134}'] function GetText: string; property Text: string read GetText; end; IVCLCutomEditChangeEvent = interface(IVCLNotifyEvent) ['{2583987B-2D6A-4A5E-A0C5-08322EE542E8}'] end; IVCLEditView = interface(IVCLCustomEditView) ['{297FE78C-F890-4FC4-ABA5-093A010145A1}'] end; // *** Create a view to this IVCLMaskEditView = interface(IVCLCustomEditView) ['{BDA83001-0370-4AA5-9F73-B9B297B4DE2E}'] end; IVCLEditNumberView = interface(IVCLMaskEditView) ['{7D52A40E-07E0-4190-8CC4-9CF767E6FF51}'] end; // *** label herda de graphiccontrol IVCLCustomLabelView = interface(IVCLControlView) ['{648AE194-66C0-4A1F-A3B1-CBE1CFF49790}'] function GetLabelText: string; property Caption: string read GetLabelText; end; IVCLCustomDateTimeView = interface(IVCLWinControlView) ['{38D5D094-1ABA-4FDD-88AC-228E645FA91D}'] function GetDateTime: TDateTime; property DateTime: TDateTime read GetDateTime; end; IVCLButtonControlView = interface(IVCLWinControlView) ['{4373E49E-DA52-4AAC-948D-33B6E27C4368}'] end; IVCLRadioButtonView = interface(IVCLButtonControlView) ['{F3235DA9-03E4-4F0B-B8A0-76F4E4F1860B}'] function GetChecked: IInfraBoolean; property Checked: IInfraBoolean read GetChecked; end; IVCLCustomCheckBoxView = interface(IVCLButtonControlView) ['{9FBC2F06-9EF6-4E4F-ADD9-D2C6078F607A}'] function GetState: IInfraBoolean; property State: IInfraBoolean read GetState; end; IVCLButtonView = interface(IVCLButtonControlView) ['{66A64B64-273A-46EF-8C93-5DD36A78392D}'] function GetCancel: Boolean; function GetClickCommand: ICommand; function GetDefault: Boolean; function GetModalResult: Integer; procedure SetCancel(Value: Boolean); procedure SetClickCommand(const Value: ICommand); procedure SetDefault(Value: Boolean); procedure SetModalResult(Value: Integer); property Cancel: Boolean read GetCancel write SetCancel; property ClickCommand: ICommand read GetClickCommand write SetClickCommand; property Default: Boolean read GetDefault write SetDefault; property ModalResult: Integer read GetModalResult write SetModalResult; end; IVCLCustomListBoxItemView = interface(IView) ['{850A40CA-3644-46DA-82B6-CB0F51A3C88A}'] function GetFeatureName: string; function GetValueForIndex(Index: Integer): IInfraType; // *** del procedure SetFeatureName(const Value: string); property FeatureName: string read GetFeatureName; // *** del write SetFeatureName; end; IVCLCustomListBoxView = interface(IVCLWinControlView) ['{FE864693-FABB-4CB4-8990-56EE42E04987}'] function GetCount: Integer; function GetItemIndex: Integer; function GetListItemView: IVCLCustomListBoxItemView; function GetOwnerDraw: boolean; procedure SetCount(Value: Integer); procedure SetListItemView(const Value: IVCLCustomListBoxItemView); procedure SetOwnerDraw(const Value: boolean); property Count: Integer read GetCount write SetCount; property ItemIndex: Integer read GetItemIndex; property ListItemView: IVCLCustomListBoxItemView read GetListItemView write SetListItemView; property OwnerDraw: boolean read GetOwnerDraw write SetOwnerDraw; end; IVCLMenuItemView = interface(IVCLView) ['{3B55FFE9-032C-4D39-B186-AF22A5F3C619}'] function GetClickCommand: ICommand; procedure SetClickCommand(const Value: ICommand); property ClickCommand: ICommand read GetClickCommand write SetClickCommand; end; IVCLMenuView = interface(IView) ['{3B55FFE9-032C-4D39-B186-AF22A5F3C619}'] function GetItems: IVCLMenuItemView; function GetOwnerDraw: boolean; procedure SetOwnerDraw(Value: boolean); property Items: IVCLMenuItemView read GetItems; property OwnerDraw: boolean read GetOwnerDraw write SetOwnerDraw; end; // Presenters ICustomFormPresenter = interface(IContainerPresenter) ['{D2D15D4B-B6CB-44E5-B422-B50098FDF6E2}'] procedure Execute; end; IFormPresenterReleaseOnClose = interface(ICustomFormPresenter) ['{E2B1548B-E1E2-4387-8AAF-A55ED1BA9C5A}'] function GetNewInstance(ID: TGUID; const Value: IInfraObject): IElement; end; IUndoableEditPresenter = interface(IElement) ['{DDFF9ECA-B39A-4DBA-AE7C-FE67C271B98A}'] procedure DoUndoableEdit(const ParentPresenter: IFormPresenterReleaseOnClose; const PresenterToEdit: IPresenter; EditPresenterInterface: TGUID); end; // interactors IExitEventModelUpdater = interface(IInteractor) ['{63CD8D1F-BF26-4468-A92F-21263A22FD1E}'] end; IClickEventModelUpdater = interface(IInteractor) ['{17B9EF5E-919F-4B64-BAA3-52096561F48D}'] end; IObjectSelectionUpdater = interface(IInteractor) ['{F2D1524A-ED7A-4CE9-B973-F72C32919ACC}'] end; IKeyBoardInteractor = interface(IInteractor) ['{4C696FD6-BA52-4D2D-AE3A-BD3CA7A8A888}'] end; IInputNumberInteractor = interface(IKeyBoardInteractor) ['{9BA45A52-9A6A-4C3D-9AB8-A070A5E7F566}'] function GetAcceptDecimals: boolean; function GetAcceptSignal: boolean; procedure SetAcceptDecimals(const Value: boolean); procedure SetAcceptSignal(const Value: boolean); property AcceptDecimals: boolean read GetAcceptDecimals write SetAcceptDecimals; property AcceptSignal: boolean read GetAcceptSignal write SetAcceptSignal; end; // commands ICloseFormCommand = interface(ICommand) ['{5A690237-1642-43DF-A222-D6C8DFD7D67C}'] end; ICloseFormWithOKCommand = interface(ICloseFormCommand) ['{07F39A8C-DDF6-4B4C-94EE-87828E6C64F9}'] end; // Renderer's IVCLCustomListBoxRenderer = interface(IRenderer) ['{F5BDAA5A-DC60-4EDC-96E6-3E4D2217CA4A}'] end; IVCLCustomListBoxItemRenderer = interface(IRenderer) ['{E692E638-89E5-46A7-B961-D1ADBB6A7DB6}'] function DoDataFind(const FindString: string): Integer; procedure DoGetData(Index: Integer; var Data: string); procedure DoDrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure DoDataObject(Index: Integer; var DataObject: TObject); procedure DoMeasureItem(Index: Integer; var Height: Integer); end; IVCLMenuItemRenderer = interface(IRenderer) ['{8E6D6E39-2A80-435E-8FD9-BC5345B98BDF}'] procedure DoAdvancedDrawItem(ACanvas: TCanvas; ARect: TRect; State: TOwnerDrawState); procedure DoDrawItem(ACanvas: TCanvas; ARect: TRect; Selected: Boolean); procedure DoMeasureItem(ACanvas: TCanvas; var Width, Height: Integer); end; function MVPMApperService: IMVPMapperService; implementation function MVPMApperService: IMVPMapperService; begin Result := ApplicationContext as IMVPMapperService; end; end.
unit UxlAppbar; interface uses Windows, UxlClasses, UxlWindow, UxlWinControl, ShellAPI; type TAnchorEdge = (aeLeft, aeTop, aeRight, aeBottom); TxlAppbar = class (TxlInterfacedObject, IMessageObserver) private FWin: TxlWindow; FEnabled: boolean; FAutoHide: boolean; g_uSide: UInt; procedure SetEnable (value: boolean); procedure SetAutoHide (value: boolean); procedure f_AppBarCallback (hwndAccessBar: HWND; uNotifyMsg, LPARAM: UINT); procedure AppBarPosChanged (pabd: TAPPBARDATA); procedure AppBarQuerySetPos (uEdge: UINT; lprc: TRECT; pabd: TAPPBARDATA); function f_GetEdge (ae: TAnchorEdge): UInt; public constructor Create (AWindow: TxlWindow); destructor Destroy (); override; function ProcessMessage (ASender: TxlWinControl; AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; procedure Anchor (ae: TAnchorEdge; rc: TRect); property Enabled: boolean read FEnabled write SetEnable; property AutoHide: boolean read FAutoHide write SetAutoHide; end; implementation uses UxlWinDef, UxlFunctions; constructor TxlAppbar.Create (AWindow: TxlWindow); begin FWin := AWindow; FWin.AddMessageObserver (self); end; destructor TxlAppbar.Destroy (); begin FWin.RemoveMessageObserver(self); inherited; end; procedure TxlAppbar.SetEnable (value: boolean); var pabd: TAppBarData; begin if value = FEnabled then exit; with pabd do begin cbsize := sizeof (pabd); hwnd := FWin.handle; end; if value then begin pabd.uCallBackMessage := APPBAR_CALLBACK; FEnabled := IntToBool (SHAppBarMessage (ABM_NEW, pabd)); g_uSide := ABE_TOP; end else begin SHAppBarMessage(ABM_REMOVE, pabd); FEnabled := false; end; end; function TxlAppbar.ProcessMessage (ASender: TxlWinControl; AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; begin case AMessage of APPBAR_CALLBACK: begin f_AppbarCallback (ASender.Handle, wparam, lparam); b_processed := true; end; else b_processed := false; end; end; procedure TxlAppbar.SetAutoHide (value: boolean); begin end; //--------------------------- function TxlAppbar.f_GetEdge (ae: TAnchorEdge): UInt; begin case ae of aeLeft: result := ABE_LEFT; aeTop: result := ABE_TOP; aeRight: result := ABE_RIGHT; else result := ABE_BOTTOM; end; end; procedure TxlAppbar.Anchor (ae: TAnchorEdge; rc: TRect); var pabd: TAppBarData; begin with pabd do begin cbsize := sizeof (pabd); hwnd := FWin.handle; end; AppBarQuerySetPos (f_GetEdge (ae), rc, pabd); end; procedure TxlAppbar.AppBarQuerySetPos (uEdge: UINT; lprc: TRECT; pabd: TAPPBARDATA); var iHeight, iWidth: integer; begin pabd.rc := lprc; pabd.uEdge := uEdge; // Copy the screen coordinates of the appbar's bounding rectangle into the APPBARDATA structure. if uEdge in [ABE_LEFT, ABE_RIGHT] then begin iWidth := pabd.rc.right - pabd.rc.left; pabd.rc.top := 0; pabd.rc.bottom := GetSystemMetrics(SM_CYSCREEN); end else begin iHeight := pabd.rc.bottom - pabd.rc.top; pabd.rc.left := 0; pabd.rc.right := GetSystemMetrics(SM_CXSCREEN); end; // Query the system for an approved size and position. SHAppBarMessage (ABM_QUERYPOS, pabd); // Adjust the rectangle, depending on the edge to which the appbar is anchored. case uEdge of ABE_LEFT: pabd.rc.right := pabd.rc.left + iWidth; ABE_RIGHT: pabd.rc.left := pabd.rc.right - iWidth; ABE_TOP: pabd.rc.bottom := pabd.rc.top + iHeight; ABE_BOTTOM: pabd.rc.top := pabd.rc.bottom - iHeight; end; // Pass the final bounding rectangle to the system. SHAppBarMessage(ABM_SETPOS, pabd); // Move and size the appbar so that it conforms to the bounding rectangle passed to the system. MoveWindow (pabd.hWnd, pabd.rc.left, pabd.rc.top, pabd.rc.right - pabd.rc.left, pabd.rc.bottom - pabd.rc.top, TRUE); end; procedure TxlAppbar.f_AppBarCallback (hwndAccessBar: HWND; uNotifyMsg, LPARAM: UINT); var abd: TAPPBARDATA; uState, us: UINT; begin abd.cbSize := sizeof(abd); abd.hWnd := hwndAccessBar; case uNotifyMsg of ABN_STATECHANGE: begin // Check to see if the taskbar's always-on-top state has changed and, if it has, change the appbar's state accordingly. uState := SHAppBarMessage(ABM_GETSTATE, abd); If (ABS_ALWAYSONTOP and uState) > 0 then us := HWND_TOPMOST else us := HWND_BOTTOM; SetWindowPos (hwndAccessBar, us, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE); end; ABN_FULLSCREENAPP: begin // A full-screen application has started, or the last full-screen application has closed. Set the appbar's z-order appropriately. if lParam > 0 then begin if (ABS_ALWAYSONTOP and uState) > 0 then us := HWND_TOPMOST else us := HWND_BOTTOM; SetWindowPos ( hwndAccessBar, us, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE) end else begin uState := SHAppBarMessage(ABM_GETSTATE, abd); if (uState and ABS_ALWAYSONTOP) > 0 then SetWindowPos (hwndAccessBar, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE); end; end; ABN_POSCHANGED: // The taskbar or another appbar has changed its size or position. AppBarPosChanged (abd); end; end; // AppBarPosChanged - adjusts the appbar's size and position. // pabd - address of an APPBARDATA structure that contains information used to adjust the size and position procedure TxlAppbar.AppBarPosChanged (pabd: TAPPBARDATA); var rc, rcWindow: TRECT; iHeight, iWidth: integer; begin with rc do begin top := 0; left := 0; right := GetSystemMetrics (SM_CXSCREEN); bottom := GetSystemMetrics (SM_CYSCREEN); end; GetWindowRect (pabd.hWnd, rcWindow); iHeight := rcWindow.bottom - rcWindow.top; iWidth := rcWindow.right - rcWindow.left; case g_uSide of ABE_TOP: rc.bottom := rc.top + iHeight; ABE_BOTTOM: rc.top := rc.bottom - iHeight; ABE_LEFT: rc.right := rc.left + iWidth; ABE_RIGHT: rc.left := rc.right - iWidth; end; AppBarQuerySetPos (g_uSide, rc, pabd); end; end.
program AlgLista5Ex4; // Exercicio 4 da lista 5 de algoritmos. Autor: Henrique Colodetti Escanferla. type vetor=array[1..9,1..9]of real; // Criação do tipo de variavel vetor bidimensional. var v:vetor; // Variaveis globais: v=> guardará numeros reais formando uma matriz quadrada. n:integer; // n=> tamanho da matriz quadrada que pode ser 1,2 ou 3. procedure ler_vetor(var v:vetor; var n:integer); // "ler_vetor" recebe vetor bidimensional quadrático, le seu tamanho e a entrada retornando vetor com a entrada. var i, j:integer; aux:real; // Variáveis locais: aux=> receberá a sequencia; i=> linha e j=> coluna. begin // Inicio deste procedimento. j:=0; // Começa com zero. while j<>n do // Loop das colunas. begin // Inicio deste loop. j:=j+1; // Coluna atual. i:=0; // Começa com zero. while i<>n do // Loop das linhas. begin // Inicio deste loop. i:=i+1; // Linha atual. read(aux); // Le nº da sequencia. v[i,j]:=aux; // Insere valor na cedula do vetor. end; // Fim deste loop. end; // Fim deste loop. end; // Fim deste procedimento. function determinante(v:vetor; n:integer):real; // "determinante" recebe vetor bidimensional quadrático, le sua ordem e conteúdo retornando seu determinante. begin // Inicio desta função. if n=3 then determinante:=(v[1,1]*v[2,2]*v[3,3])+(v[1,2]*v[2,3]*v[3,1])+(v[2,1]*v[3,2]*v[1,3]) -(v[1,3]*v[2,2]*v[3,1])-(v[1,2]*v[2,1]*v[3,3])-(v[2,3]*v[3,2]*v[1,1]) // Conforme a regra. else if n=2 then determinante:=(v[1,1]*v[2,2])-(v[1,2]*v[2,1]) // Conforme a regra. else determinante:=v[1,1]; // Conforme a regra. end; // Fim desta função. begin // Começo do processo. write('Digite a ordem da matriz quadrada: '); // Pedido de "n". readln(n); // Leitura de "n". write('Digite uma sequência de nºs reais: '); // Pedido da seq. de nºs da matriz. ler_vetor(v, n); // Chama-se "ler_vetor". writeln; // Pula linha na tela. writeln('O determinante da matriz inserida é de valor: ',determinante(v, n):5:2); // Chama-se "determinante" end. // Fim do processo.
unit QpFilterUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; type { TQpFilterFrame } TQpFilterFrame = class(TFrame) Bevel: TBevel; FilterLabel: TLabel; FilterCombo: TComboBox; procedure FilterComboChange(Sender: TObject); procedure FilterComboDropDown(Sender: TObject); private FFilterID: Integer; FOnChange: TNotifyEvent; procedure SetFilterID(AFilterID: Integer); procedure AssignFilterID(AFilterID: Integer); procedure RefreshFilters; procedure Changed; procedure FontChanged; procedure CMFontChanged(var Msg: TMessage); message CM_FONTCHANGED; public property FilterID: Integer read FFilterID write SetFilterID; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation uses QpFilterListUnit, Math, ExtraUnit; {$R *.dfm} { TQpFilterFrame } procedure TQpFilterFrame.SetFilterID(AFilterID: Integer); begin if FFilterID <> AFilterID then AssignFilterID(AFIlterID); end; procedure TQpFilterFrame.AssignFilterID(AFilterID: Integer); var Index: Integer; begin Index := FilterCombo.Items.IndexOfObject(Pointer(AFilterID)); if Index <> -1 then begin FilterCombo.ItemIndex := Index; FFilterID := AFilterID; Changed; end; end; procedure TQpFilterFrame.FilterComboChange(Sender: TObject); var FID: Integer; begin if FilterCombo.ItemIndex = FilterCombo.Items.Count - 1 then begin FilterListForm.FilterID := FilterID; FID := 0; if FilterListForm.ShowModal = mrOK then FID := FilterListForm.FilterID; RefreshFilters; AssignFilterID(FID); end else begin FFilterID := Integer(FilterCombo.Items.Objects[FilterCombo.ItemIndex]); Changed; end; end; procedure TQpFilterFrame.Changed; begin if Assigned(OnChange) then OnChange(Self); end; procedure TQpFilterFrame.FilterComboDropDown(Sender: TObject); begin RefreshFilters; end; procedure TQpFilterFrame.RefreshFilters; var NewListID: Integer; begin NewListID := FilterListForm.UpdateList(FilterCombo.Items, FilterCombo.Tag); if FilterCombo.Tag <> NewListID then begin AssignFilterID(FilterID); FilterCombo.Tag := NewListID; end; end; procedure TQpFilterFrame.CMFontChanged(var Msg: TMessage); begin inherited; if not (csLoading in ComponentState) and HandleAllocated then FontChanged; end; procedure TQpFilterFrame.FontChanged; begin FilterCombo.Top := 3 + FilterCombo.Height + 4; FilterCombo.Width := Max(150, TextWidth(Self, '<Нет ограничений>') + 2 * FilterCombo.Height); Width := ControlOffsetX(FilterCombo, 2); end; end.
{ Copyright © 1999 by Delphi 5 Developer's Guide - Xavier Pacheco and Steve Teixeira } unit MainFfm; interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type { First, define a procedural data type, this should reflect the procedure that is exported from the DLL. } TShowCalendar = function (AHandle: THandle; ACaption: String): TDateTime; StdCall; { Create a new exception class to reflect a failed DLL load } EDLLLoadError = class(Exception); TMainForm = class(TForm) lblDate: TLabel; btnGetCalendar: TButton; procedure btnGetCalendarClick(Sender: TObject); end; var MainForm: TMainForm; implementation {$R *.DFM} procedure TMainForm.btnGetCalendarClick(Sender: TObject); var LibHandle : THandle; ShowCalendar: TShowCalendar; begin { Attempt to load the DLL } LibHandle := LoadLibrary('CALENDARLIB.DLL'); try { If the load failed, LibHandle will be zero. If this occurs, raise an exception. } if LibHandle = 0 then raise EDLLLoadError.Create('Unable to Load DLL'); { If the code makes it here, the DLL loaded successfully, now obtain the link to the DLL's exported function so that it can be called. } @ShowCalendar := GetProcAddress(LibHandle, 'ShowCalendar'); { If the function is imported successfully, then set lblDate.Caption to reflect the returned date from the function. Otherwise, show the return raise an exception. } if not (@ShowCalendar = nil) then lblDate.Caption := DateToStr(ShowCalendar(Application.Handle, Caption)) else RaiseLastWin32Error; finally FreeLibrary(LibHandle); // Unload the DLL. end; end; end.
unit frameAttributes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fdac.framedoc, DBGridEhGrouping, ToolCtrlsEh, DBGridEhToolCtrls, DynVarsEh, ActnList, Menus, ImgList, DB, GridsEh, DBAxisGridsEh, DBGridEh, DBGridEhVk, ToolWin, ActnMan, ActnCtrls, ExtCtrls, ComCtrls, fdac.dmdoc, fdac.dmmain, dmattributes, VkVariableBinding, System.Actions, VkVariable, VariantUtils, {$IFDEF VER330}System.ImageList,{$ENDIF} EhLibVCL; type TAttributesFrame = class(TDocFrame) private { Private declarations } FId: Integer; FDmAttributes: TAttributesDm; procedure SetId(const Value: Integer); protected procedure FmEditOnActionUpdate(Sender: TObject);override; public { Public declarations } function GetCaption: String; override; class function GetDmDoc:TDocDm;override; constructor Create(AOwner: TComponent; ADocDm:TDocDm);override; property Id: Integer read FId write SetId; class function GetSelectedCaption(AVar: TVkVariableCollection):String;override; end; TAttributesFrameOAU = class(TAttributesFrame) public function GetCaption: String; override; constructor Create(AOwner: TComponent; ADocDm:TDocDm); override; end; TAttributesFrameOKU = class(TAttributesFrame) public function GetCaption: String; override; constructor Create(AOwner: TComponent; ADocDm:TDocDm); override; end; var AttributesFrame: TAttributesFrame; implementation uses systemconsts; {$R *.dfm} { TFrameAttributes } constructor TAttributesFrame.Create(AOwner: TComponent; ADocDm: TDocDm); begin inherited Create(AOwner, ADocDm); FmEdit.OnActionUpdate := FmEditOnActionUpdate; end; procedure TAttributesFrame.FmEditOnActionUpdate(Sender: TObject); var _Item: TVkVariableBinding; _Item2: TVkVariableBinding; _Item3: TVkVariableBinding; _ItemGroup: TVkVariableBinding; begin _Item := FmEdit.BindingList.FindVkVariableBinding('attributetype'); _Item2 := FmEdit.BindingList.FindVkVariableBinding('ndec'); _Item3 := FmEdit.BindingList.FindVkVariableBinding('nlen'); _ItemGroup := FmEdit.BindingList.FindVkVariableBinding('idgroup'); if Assigned(_Item) then begin if Assigned(_Item2) then begin if (_Item.Variable.AsLargeInt>1) then begin _Item2.oControl.Enabled := False; _Item3.oControl.Enabled := False end else begin _Item2.oControl.Enabled := _Item.Variable.AsLargeInt <> 0; _Item3.oControl.Enabled := True end; if Assigned(_ItemGroup) and Assigned(_ItemGroup.oControl) then _ItemGroup.oControl.Enabled := (_Item.Variable.AsLargeInt = TA_GROUP) or (_Item.Variable.AsLargeInt = TA_OBJECT); end; end; end; {function TFrameAttributes.GetCaption: String; begin Result := 'not defined' end; } function TAttributesFrame.GetCaption: String; begin if FId>0 then begin case MainDm.GetTypeGroup(FId) of IDGROUP_OKU: Result := 'Атрибуты объектов количественного учета'; IDGROUP_OAU: Result := 'Атрибуты объектов аналитического учета'; end; end; end; class function TAttributesFrame.GetDmDoc: TDocDm; begin Result := TAttributesDm.GetDm; end; class function TAttributesFrame.GetSelectedCaption(AVar: TVkVariableCollection): String; begin if Avar.Count>1 then inherited else begin if Avar.Count=1 then Result := IfVarEmpty( MainDm.QueryValue('SELECT name FROM attributelist WHERE idattribute=:idattribute',[Avar.Items[0].AsLargeInt]),'') else Result := 'not defined'; end; end; procedure TAttributesFrame.SetId(const Value: Integer); begin FId := Value; GetParentForm.Caption := GetCaption; FDmAttributes := TAttributesDm(DocDm); if not Prepare then begin FDmAttributes.Open(FId); ConfigureEdit; end; DataSource1.DataSet := FDmAttributes.MemTableEhDoc; end; { TFrameAttributesOAK } constructor TAttributesFrameOKU.Create(AOwner: TComponent; ADocDm: TDocDm); begin inherited; Id := ATTRIBUTES_OKU; end; { TFrameAttributesOAU } constructor TAttributesFrameOAU.Create(AOwner: TComponent; ADocDm: TDocDm); begin inherited; Id := ATTRIBUTES_OAU; end; function TAttributesFrameOAU.GetCaption: String; begin Result := 'Аттрибуты объектов аналитического учета'; end; function TAttributesFrameOKU.GetCaption: String; begin Result := 'Аттрибуты объектов количественного учета'; end; initialization RegisterClass(TAttributesFrame); RegisterClass(TAttributesFrameOAU); RegisterClass(TAttributesFrameOKU); end.
unit untfieldarraylist; {$mode objfpc}{$H+} interface uses Classes, SysUtils, untField; type { TArrayList } { TFieldArrayList } TFieldArrayList = class Items: array of Field; nLength:word; constructor Create; destructor Destroy; override; procedure Add(Value: Field); function Count: integer; function GetItems(Index: integer): Field; end; implementation constructor TFieldArrayList.Create; begin SetLength(Items, 0); end; destructor TFieldArrayList.Destroy; begin SetLength(Items, 0); inherited Destroy; end; procedure TFieldArrayList.Add(Value: Field); begin SetLength(Items, Length(Items) + 1); Items[Length(Items) - 1] := Value; end; function TFieldArrayList.Count: integer; begin Result := Length(Items); end; function TFieldArrayList.GetItems(Index: integer): Field; begin Result := Items[Index]; end; end.
{$mode objfpc} { tell compiler we're using object orientation } {$m+} { tell compiler we're using constructors } program usingClasses; type Rectangle = class private length, width: integer; public constructor create(l, w: integer); procedure setlength(l: integer); function getlength(): integer; procedure setwidth(w: integer); function getwidth(): integer; procedure draw; end; var r1: Rectangle; constructor Rectangle.create(l, w: integer); begin length := l; width := w; end; procedure Rectangle.setlength(l: integer); begin length := l; end; procedure Rectangle.setwidth(w: integer); begin width := w; end; function Rectangle.getlength(): integer; begin getlength := length; end; function Rectangle.getwidth(): integer; begin getwidth := width; end; procedure Rectangle.draw; var i, j: integer; begin for i := 1 to length do begin for j := 1 to width do write(' * '); writeln; end; end; begin { main } writeln; r1 := Rectangle.create(3, 7); writeln('draw rectangle: ', r1.getlength(), ' by ', r1.getwidth()); writeln; r1.draw; writeln; { change properties and draw again } r1.setlength(4); r1.setwidth(6); writeln('draw rectangle: ', r1.getlength(), ' by ', r1.getwidth()); writeln; r1.draw; writeln; end.
{$INCLUDE switches.pas} unit CustomAI; interface uses {$IFDEF DEBUG}SysUtils,{$ENDIF} // necessary for debug exceptions Protocol; type TNegoTime=(BeginOfTurn, EndOfTurn, EnemyCalled); TCustomAI=class public procedure Process(Command: integer; var Data); // overridables constructor Create(Nation: integer); virtual; destructor Destroy; override; procedure SetDataDefaults; virtual; procedure SetDataRandom; virtual; procedure OnBeforeEnemyAttack(UnitInfo: TUnitInfo; ToLoc, EndHealth, EndHealthDef: integer); virtual; procedure OnBeforeEnemyCapture(UnitInfo: TUnitInfo; ToLoc: integer); virtual; procedure OnAfterEnemyAttack; virtual; procedure OnAfterEnemyCapture; virtual; protected me: integer; // index of the controlled nation RO: ^TPlayerContext; Map: ^TTileList; MyUnit: ^TUnList; MyCity: ^TCityList; MyModel: ^TModelList; cixStateImp: array[imPalace..imSpacePort] of integer; // negotiation Opponent: integer; // nation i'm in negotiation with, -1 indicates no-negotiation mode MyAction, MyLastAction, OppoAction: integer; MyOffer, MyLastOffer, OppoOffer: TOffer; // overridables procedure DoTurn; virtual; procedure DoNegotiation; virtual; function ChooseResearchAdvance: integer; virtual; function ChooseStealAdvance: integer; virtual; function ChooseGovernment: integer; virtual; function WantNegotiation(Nation: integer; NegoTime: TNegoTime): boolean; virtual; function OnNegoRejected_CancelTreaty: boolean; virtual; // general functions function IsResearched(Advance: integer): boolean; function ResearchCost: integer; function ChangeAttitude(Nation, Attitude: integer): integer; function Revolution: integer; function ChangeRates(Tax,Lux: integer): integer; function PrepareNewModel(Domain: integer): integer; function SetNewModelFeature(F, Count: integer): integer; function AdvanceResearchable(Advance: integer): boolean; function AdvanceStealable(Advance: integer): boolean; function GetJobProgress(Loc: integer; var JobProgress: TJobProgressData): boolean; function DebugMessage(Level: integer; Text: string): boolean; function SetDebugMap(var DebugMap): boolean; // unit functions procedure Unit_FindMyDefender(Loc: integer; var uix: integer); procedure Unit_FindEnemyDefender(Loc: integer; var euix: integer); function Unit_Move(uix,ToLoc: integer): integer; function Unit_Step(uix,ToLoc: integer): integer; function Unit_Attack(uix,ToLoc: integer): integer; function Unit_DoMission(uix,MissionType,ToLoc: integer): integer; function Unit_MoveForecast(uix,ToLoc: integer; var RemainingMovement: integer): boolean; function Unit_AttackForecast(uix,ToLoc,AttackMovement: integer; var RemainingHealth: integer): boolean; function Unit_DefenseForecast(euix,ToLoc: integer; var RemainingHealth: integer): boolean; function Unit_Disband(uix: integer): integer; function Unit_StartJob(uix,NewJob: integer): integer; function Unit_SetHomeHere(uix: integer): integer; function Unit_Load(uix: integer): integer; function Unit_Unload(uix: integer): integer; function Unit_SelectTransport(uix: integer): integer; function Unit_AddToCity(uix: integer): integer; // city functions procedure City_FindMyCity(Loc: integer; var cix: integer); procedure City_FindEnemyCity(Loc: integer; var ecix: integer); function City_HasProject(cix: integer): boolean; function City_CurrentImprovementProject(cix: integer): integer; function City_CurrentUnitProject(cix: integer): integer; function City_GetTileInfo(cix,TileLoc: integer; var TileInfo: TTileInfo): integer; function City_GetReport(cix: integer; var Report: TCityReport): integer; function City_GetHypoReport(cix, HypoTiles, HypoTax, HypoLux: integer; var Report: TCityReport): integer; function City_GetReportNew(cix: integer; var Report: TCityReportNew): integer; function City_GetHypoReportNew(cix, HypoTiles, HypoTaxRate, HypoLuxuryRate: integer; var Report: TCityReportNew): integer; function City_GetAreaInfo(cix: integer; var AreaInfo: TCityAreaInfo): integer; function City_StartUnitProduction(cix,mix: integer): integer; function City_StartEmigration(cix,mix: integer; AllowDisbandCity, AsConscripts: boolean): integer; function City_StartImprovement(cix,iix: integer): integer; function City_Improvable(cix,iix: integer): boolean; function City_StopProduction(cix: integer): integer; function City_BuyProject(cix: integer): integer; function City_SellImprovement(cix,iix: integer): integer; function City_RebuildImprovement(cix,iix: integer): integer; function City_SetTiles(cix,NewTiles: integer): integer; procedure City_OptimizeTiles(cix: integer; ResourceWeights: cardinal = rwMaxGrowth); // negotiation function Nego_CheckMyAction: integer; private HaveTurned: boolean; UnwantedNego: set of 0..nPl-1; Contacted: set of 0..nPl-1; procedure StealAdvance; end; var Server: TServerCall; G: TNewGameData; RWDataSize, MapSize: integer; decompose24: cardinal; nodata: pointer; const CityOwnTile = 13; // = ab_to_V21(0,0) // additional return codes rLocationReached= $00010000; // Unit_Move: move was not interrupted, location reached rMoreTurns= $00020000; // Unit_Move: move was not interrupted, location not reached yet type TVicinity8Loc=array[0..7] of integer; TVicinity21Loc=array[0..27] of integer; procedure Init(NewGameData: TNewGameData); procedure ab_to_Loc(Loc0,a,b: integer; var Loc: integer); procedure Loc_to_ab(Loc0,Loc: integer; var a,b: integer); procedure ab_to_V8(a,b: integer; var V8: integer); procedure V8_to_ab(V8: integer; var a,b: integer); procedure ab_to_V21(a,b: integer; var V21: integer); procedure V21_to_ab(V21: integer; var a,b: integer); procedure V8_to_Loc(Loc0: integer; var VicinityLoc: TVicinity8Loc); procedure V21_to_Loc(Loc0: integer; var VicinityLoc: TVicinity21Loc); function Distance(Loc0,Loc1: integer): integer; implementation const ab_v8: array[-4..4] of integer = (5,6,7,4,-1,0,3,2,1); v8_a: array[0..7] of integer = (1,1,0,-1,-1,-1,0,1); v8_b: array[0..7] of integer = (0,1,1,1,0,-1,-1,-1); procedure ab_to_Loc(Loc0,a,b: integer; var Loc: integer); {relative location from Loc0} var y0: integer; begin assert((Loc0>=0) and (Loc0<MapSize) and (a-b+G.lx>=0)); y0:=cardinal(Loc0)*decompose24 shr 24; Loc:=(Loc0+(a-b+y0 and 1+G.lx+G.lx) shr 1) mod G.lx +G.lx*(y0+a+b); if Loc>=MapSize then Loc:=-$1000 end; procedure Loc_to_ab(Loc0,Loc: integer; var a,b: integer); {$IFDEF FPC} // freepascal var dx,dy: integer; begin dx:=((Loc mod G.lx *2 +Loc div G.lx and 1) -(Loc0 mod G.lx *2 +Loc0 div G.lx and 1)+3*G.lx) mod (2*G.lx) -G.lx; dy:=Loc div G.lx-Loc0 div G.lx; a:=(dx+dy) div 2; b:=(dy-dx) div 2; end; {$ELSE} // delphi register; asm push ebx // calculate push ecx div byte ptr [G] xor ebx,ebx mov bl,ah // ebx:=Loc0 mod G.lx mov ecx,eax and ecx,$000000FF // ecx:=Loc0 div G.lx mov eax,edx div byte ptr [G] xor edx,edx mov dl,ah // edx:=Loc mod G.lx and eax,$000000FF // eax:=Loc div G.lx sub edx,ebx // edx:=Loc mod G.lx-Loc0 mod G.lx mov ebx,eax sub ebx,ecx // ebx:=dy and eax,1 and ecx,1 add edx,edx add eax,edx sub eax,ecx // eax:=dx, not normalized pop ecx // normalize mov edx,dword ptr [G] cmp eax,edx jl @a sub eax,edx sub eax,edx jmp @ok @a: neg edx cmp eax,edx jnl @ok sub eax,edx sub eax,edx // return results @ok: mov edx,ebx sub edx,eax add eax,ebx sar edx,1 // edx:=b mov ebx,[b] mov [ebx],edx sar eax,1 // eax:=a mov [a],eax pop ebx end; {$ENDIF} procedure ab_to_V8(a,b: integer; var V8: integer); begin assert((abs(a)<=1) and (abs(b)<=1) and ((a<>0) or (b<>0))); V8:=ab_v8[2*b+b+a]; end; procedure V8_to_ab(V8: integer; var a,b: integer); begin a:=v8_a[V8]; b:=V8_b[V8]; end; procedure ab_to_V21(a,b: integer; var V21: integer); begin V21:=(a+b+3) shl 2+(a-b+3) shr 1; end; procedure V21_to_ab(V21: integer; var a,b: integer); var dx,dy: integer; begin dy:=V21 shr 2-3; dx:=V21 and 3 shl 1 -3 + (dy+3) and 1; a:=(dx+dy) div 2; b:=(dy-dx) div 2; end; procedure V8_to_Loc(Loc0: integer; var VicinityLoc: TVicinity8Loc); var x0,y0,lx: integer; begin lx:=G.lx; y0:=cardinal(Loc0)*decompose24 shr 24; x0:=Loc0-y0*lx; // Loc0 mod lx; VicinityLoc[1]:=Loc0+lx*2; VicinityLoc[3]:=Loc0-1; VicinityLoc[5]:=Loc0-lx*2; VicinityLoc[7]:=Loc0+1; inc(Loc0,y0 and 1); VicinityLoc[0]:=Loc0+lx; VicinityLoc[2]:=Loc0+lx-1; VicinityLoc[4]:=Loc0-lx-1; VicinityLoc[6]:=Loc0-lx; // world is round! if x0<lx-1 then begin if x0=0 then begin inc(VicinityLoc[3],lx); if y0 and 1=0 then begin inc(VicinityLoc[2],lx); inc(VicinityLoc[4],lx); end end end else begin dec(VicinityLoc[7],lx); if y0 and 1=1 then begin dec(VicinityLoc[0],lx); dec(VicinityLoc[6],lx); end end; // check south pole case G.ly-y0 of 1: begin VicinityLoc[0]:=-$1000; VicinityLoc[1]:=-$1000; VicinityLoc[2]:=-$1000; end; 2: VicinityLoc[1]:=-$1000; end end; procedure V21_to_Loc(Loc0: integer; var VicinityLoc: TVicinity21Loc); var dx,dy,bit,y0,xComp,yComp,xComp0,xCompSwitch: integer; dst: ^integer; begin y0:=cardinal(Loc0)*decompose24 shr 24; xComp0:=Loc0-y0*G.lx-1; // Loc0 mod G.lx -1 xCompSwitch:=xComp0-1+y0 and 1; if xComp0<0 then inc(xComp0,G.lx); if xCompSwitch<0 then inc(xCompSwitch,G.lx); xCompSwitch:=xCompSwitch xor xComp0; yComp:=G.lx*(y0-3); dst:=@VicinityLoc; bit:=1; for dy:=0 to 6 do if yComp<MapSize then begin xComp0:=xComp0 xor xCompSwitch; xComp:=xComp0; for dx:=0 to 3 do begin if bit and $67F7F76<>0 then dst^:=xComp+yComp else dst^:=-1; inc(xComp); if xComp>=G.lx then dec(xComp, G.lx); inc(dst); bit:=bit shl 1; end; inc(yComp,G.lx); end else begin for dx:=0 to 3 do begin dst^:=-$1000; inc(dst); end; end end; function Distance(Loc0,Loc1: integer): integer; var a,b,dx,dy: integer; begin Loc_to_ab(Loc0,Loc1,a,b); dx:=abs(a-b); dy:=abs(a+b); result:=dx+dy+abs(dx-dy) shr 1; end; procedure Init(NewGameData: TNewGameData); {$IFDEF DEBUG}var Loc: integer;{$ENDIF} begin G:=NewGameData; MapSize:=G.lx*G.ly; decompose24:=(1 shl 24-1) div G.lx +1; {$IFDEF DEBUG}for Loc:=0 to MapSize-1 do assert(cardinal(Loc)*decompose24 shr 24=cardinal(Loc div G.lx));{$ENDIF} end; constructor TCustomAI.Create(Nation: integer); begin inherited Create; me:=Nation; RO:=pointer(G.RO[Nation]); Map:=pointer(RO.Map); MyUnit:=pointer(RO.Un); MyCity:=pointer(RO.City); MyModel:=pointer(RO.Model); Opponent:=-1; end; destructor TCustomAI.Destroy; begin Server(sSetDebugMap,me,0,nodata^); end; procedure TCustomAI.Process(Command: integer; var Data); var Nation,NewResearch,NewGov,count,ad,cix,iix: integer; NegoTime: TNegoTime; begin case Command of cTurn, cContinue: begin if RO.Alive and (1 shl me)=0 then begin // I'm dead, huhu Server(sTurn,me,0,nodata^); exit end; if Command=cTurn then begin fillchar(cixStateImp, sizeof(cixStateImp), $FF); for cix:=0 to RO.nCity-1 do if MyCity[cix].Loc>=0 then for iix:=imPalace to imSpacePort do if MyCity[cix].Built[iix]>0 then cixStateImp[iix]:=cix; if RO.Happened and phChangeGov<>0 then begin NewGov:=ChooseGovernment; if NewGov>gAnarchy then Server(sSetGovernment,me,NewGov,nodata^); end; HaveTurned:=false; Contacted:=[]; end; if (Command=cContinue) and (MyAction=scContact) then begin if OnNegoRejected_CancelTreaty then if RO.Treaty[Opponent]>=trPeace then if Server(sCancelTreaty,me,0,nodata^)<rExecuted then assert(false) end else UnwantedNego:=[]; Opponent:=-1; repeat if HaveTurned then NegoTime:=EndOfTurn else NegoTime:=BeginOfTurn; if RO.Government<>gAnarchy then for Nation:=0 to nPl-1 do if (Nation<>me) and (1 shl Nation and RO.Alive<>0) and (RO.Treaty[Nation]>=trNone) and not (Nation in Contacted) and not (Nation in UnwantedNego) and (Server(scContact-sExecute + Nation shl 4, me, 0, nodata^)>=rExecuted) then if WantNegotiation(Nation, NegoTime) then begin if Server(scContact + Nation shl 4, me, 0, nodata^)>=rExecuted then begin include(Contacted, Nation); Opponent:=Nation; MyAction:=scContact; exit; end; end else include(UnwantedNego,Nation); if NegoTime=BeginOfTurn then begin DoTurn; HaveTurned:=true; Contacted:=[]; UnwantedNego:=[]; end else break; until false; if RO.Happened and phTech<>0 then begin NewResearch:=ChooseResearchAdvance; if NewResearch<0 then begin // choose random research count:=0; for ad:=0 to nAdv-1 do if AdvanceResearchable(ad) then begin inc(count); if random(count)=0 then NewResearch:=ad end end; Server(sSetResearch,me,NewResearch,nodata^) end; if Server(sTurn,me,0,nodata^)<rExecuted then assert(false); end; scContact: if WantNegotiation(integer(Data), EnemyCalled) then begin if Server(scDipStart, me, 0, nodata^)<rExecuted then assert(false); Opponent:=integer(Data); MyAction:=scDipStart; end else begin if Server(scReject, me, 0, nodata^)<rExecuted then assert(false); end; scDipStart, scDipNotice, scDipAccept, scDipCancelTreaty, scDipOffer, scDipBreak: begin OppoAction:=Command; if Command=scDipOffer then OppoOffer:=TOffer(Data); if Command=scDipStart then MyLastAction:=scContact else begin MyLastAction:=MyAction; MyLastOffer:=MyOffer; end; if (OppoAction=scDipCancelTreaty) or (OppoAction=scDipBreak) then MyAction:=scDipNotice else begin MyAction:=scDipOffer; MyOffer.nDeliver:=0; MyOffer.nCost:=0; end; DoNegotiation; assert((MyAction=scDipNotice) or (MyAction=scDipAccept) or (MyAction=scDipCancelTreaty) or (MyAction=scDipOffer) or (MyAction=scDipBreak)); if MyAction=scDipOffer then Server(MyAction, me, 0, MyOffer) else Server(MyAction, me, 0, nodata^); end; cShowEndContact: Opponent:=-1; end; end; {$HINTS OFF} procedure TCustomAI.SetDataDefaults; begin end; procedure TCustomAI.SetDataRandom; begin end; procedure TCustomAI.DoTurn; begin end; procedure TCustomAI.DoNegotiation; begin end; procedure TCustomAI.OnBeforeEnemyAttack(UnitInfo: TUnitInfo; ToLoc, EndHealth, EndHealthDef: integer); begin end; procedure TCustomAI.OnBeforeEnemyCapture(UnitInfo: TUnitInfo; ToLoc: integer); begin end; procedure TCustomAI.OnAfterEnemyAttack; begin end; procedure TCustomAI.OnAfterEnemyCapture; begin end; function TCustomAI.ChooseResearchAdvance: integer; begin result:=-1 end; function TCustomAI.ChooseStealAdvance: integer; begin result:=-1 end; function TCustomAI.ChooseGovernment: integer; begin result:=gDespotism end; function TCustomAI.WantNegotiation(Nation: integer; NegoTime: TNegoTime): boolean; begin result:=false; end; function TCustomAI.OnNegoRejected_CancelTreaty: boolean; begin result:=false; end; {$HINTS ON} procedure TCustomAI.StealAdvance; var Steal, ad, count: integer; begin Steal:=ChooseStealAdvance; if Steal<0 then begin // choose random advance count:=0; for ad:=0 to nAdv-1 do if AdvanceStealable(ad) then begin inc(count); if random(count)=0 then Steal:=ad end end; if Steal>=0 then Server(sStealTech,me,Steal,nodata^); RO.Happened:=RO.Happened and not phStealTech end; function TCustomAI.IsResearched(Advance: integer): boolean; begin result:= (Advance=preNone) or (Advance<>preNA) and (RO.Tech[Advance]>=tsApplicable) end; function TCustomAI.ResearchCost: integer; begin Server(sGetTechCost,me,0,result) end; function TCustomAI.ChangeAttitude(Nation, Attitude: integer): integer; begin result:=Server(sSetAttitude+Nation shl 4,me,Attitude,nodata^) end; function TCustomAI.Revolution: integer; begin result:=Server(sRevolution,me,0,nodata^); end; function TCustomAI.ChangeRates(Tax,Lux: integer): integer; begin result:=Server(sSetRates,me,Tax div 10 and $f+Lux div 10 and $f shl 4,nodata^) end; function TCustomAI.PrepareNewModel(Domain: integer): integer; begin result:=Server(sCreateDevModel,me,Domain,nodata^); end; function TCustomAI.SetNewModelFeature(F, Count: integer): integer; begin result:=Server(sSetDevModelCap+Count shl 4,me,F,nodata^) end; function TCustomAI.AdvanceResearchable(Advance: integer): boolean; begin result:= Server(sSetResearch-sExecute,me,Advance,nodata^)>=rExecuted; end; function TCustomAI.AdvanceStealable(Advance: integer): boolean; begin result:= Server(sStealTech-sExecute,me,Advance,nodata^)>=rExecuted; end; function TCustomAI.GetJobProgress(Loc: integer; var JobProgress: TJobProgressData): boolean; begin result:= Server(sGetJobProgress,me,Loc,JobProgress)>=rExecuted; end; function TCustomAI.DebugMessage(Level: integer; Text: string): boolean; begin Text:=copy('P'+char(48+me)+' '+Text,1,254); Server(sMessage,me,Level,pchar(Text)^); result:=true; // always returns true so that it can be used like // "assert(DebugMessage(...));" -> not compiled in release build end; function TCustomAI.SetDebugMap(var DebugMap): boolean; begin Server(sSetDebugMap, me, 0, DebugMap); result:=true; // always returns true so that it can be used like // "assert(SetDebugMap(...));" -> not compiled in release build end; procedure TCustomAI.Unit_FindMyDefender(Loc: integer; var uix: integer); begin if Server(sGetDefender,me,Loc,uix)<rExecuted then uix:=-1 end; procedure TCustomAI.Unit_FindEnemyDefender(Loc: integer; var euix: integer); begin euix:=RO.nEnemyUn-1; while (euix>=0) and (RO.EnemyUn[euix].Loc<>Loc) do dec(euix); end; function TCustomAI.Unit_Move(uix,ToLoc: integer): integer; var Step: integer; DestinationReached: boolean; Advice: TMoveAdviceData; begin assert((uix>=0) and (uix<RO.nUn) and (MyUnit[uix].Loc>=0)); // is a unit {Loc_to_ab(MyUnit[uix].Loc,ToLoc,a,b); assert((a<>0) or (b<>0)); if (a>=-1) and (a<=1) and (b>=-1) and (b<=1) then begin // move to adjacent tile !!!problem: if move is invalid, return codes are not consistent with other branch (eNoWay) Advice.nStep:=1; Advice.dx[0]:=a-b; Advice.dy[0]:=a+b; Advice.MoreTurns:=0; Advice.MaxHostile_MovementLeft:=MyUnit[uix].Movement; result:=eOK; end else} begin // move to non-adjacent tile, find shortest path Advice.ToLoc:=ToLoc; Advice.MoreTurns:=9999; Advice.MaxHostile_MovementLeft:=100; result:=Server(sGetMoveAdvice,me,uix,Advice); end; if result=eOk then begin DestinationReached:=false; Step:=0; repeat if result and (rExecuted or rUnitRemoved)=rExecuted then // check if destination reached if (ToLoc>=0) and (Advice.MoreTurns=0) and (Step=Advice.nStep-1) and ((Map[ToLoc] and (fUnit or fOwned)=fUnit) // attack or (Map[ToLoc] and (fCity or fOwned)=fCity) and ((MyModel[MyUnit[uix].mix].Domain<>dGround) // bombardment or (MyModel[MyUnit[uix].mix].Flags and mdCivil<>0))) then // can't capture begin DestinationReached:=true; break end // stop next to destination else if Step=Advice.nStep then DestinationReached:=true; // normal move -- stop at destination if (Step=Advice.nStep) or (result<>eOK) and (result<>eLoaded) then break; result:=Server(sMoveUnit+(Advice.dx[Step] and 7) shl 4 +(Advice.dy[Step] and 7) shl 7, me,uix,nodata^); inc(Step); if RO.Happened and phStealTech<>0 then StealAdvance; until false; if DestinationReached then if Advice.nStep=25 then result:=Unit_Move(uix,ToLoc) // Shinkansen else if Advice.MoreTurns=0 then result:=result or rLocationReached else result:=result or rMoreTurns; end end; function TCustomAI.Unit_Step(uix,ToLoc: integer): integer; var a,b: integer; begin Loc_to_ab(MyUnit[uix].Loc, ToLoc, a, b); assert(((a<>0) or (b<>0)) and (a>=-1) and (a<=1) and (b>=-1) and (b<=1)); result:=Server(sMoveUnit+((a-b) and 7) shl 4 +((a+b) and 7) shl 7, me, uix, nodata^); if RO.Happened and phStealTech<>0 then StealAdvance; end; function TCustomAI.Unit_Attack(uix,ToLoc: integer): integer; var a,b: integer; begin assert((uix>=0) and (uix<RO.nUn) and (MyUnit[uix].Loc>=0) // is a unit and ((Map[ToLoc] and (fUnit or fOwned)=fUnit) // is an attack or (Map[ToLoc] and (fCity or fOwned)=fCity) and (MyModel[MyUnit[uix].mix].Domain<>dGround))); // is a bombardment Loc_to_ab(MyUnit[uix].Loc,ToLoc,a,b); assert(((a<>0) or (b<>0)) and (a>=-1) and (a<=1) and (b>=-1) and (b<=1)); // attack to adjacent tile result:=Server(sMoveUnit+(a-b) and 7 shl 4 +(a+b) and 7 shl 7,me,uix,nodata^); end; function TCustomAI.Unit_DoMission(uix,MissionType,ToLoc: integer): integer; var a,b: integer; begin result:=Server(sSetSpyMission + MissionType shl 4,me,0,nodata^); if result>=rExecuted then begin assert((uix>=0) and (uix<RO.nUn) and (MyUnit[uix].Loc>=0) // is a unit and (MyModel[MyUnit[uix].mix].Kind=mkDiplomat)); // is a commando Loc_to_ab(MyUnit[uix].Loc,ToLoc,a,b); assert(((a<>0) or (b<>0)) and (a>=-1) and (a<=1) and (b>=-1) and (b<=1)); // city must be adjacent result:=Server(sMoveUnit-sExecute+(a-b) and 7 shl 4 +(a+b) and 7 shl 7,me,uix,nodata^); if result=eMissionDone then result:=Server(sMoveUnit+(a-b) and 7 shl 4 +(a+b) and 7 shl 7,me,uix,nodata^) else if (result<>eNoTime_Move) and (result<>eTreaty) and (result<>eNoTurn) then result:=eInvalid // not a special commando mission! end end; function TCustomAI.Unit_MoveForecast(uix,ToLoc: integer; var RemainingMovement: integer): boolean; var Advice: TMoveAdviceData; begin assert((uix>=0) and (uix<RO.nUn) and (MyUnit[uix].Loc>=0)); // is a unit Advice.ToLoc:=ToLoc; Advice.MoreTurns:=0; Advice.MaxHostile_MovementLeft:=100; if Server(sGetMoveAdvice,me,uix,Advice)=eOk then begin RemainingMovement:=Advice.MaxHostile_MovementLeft; result:=true end else begin RemainingMovement:=-1; result:=false end end; // negative RemainingHealth is remaining helth of defender if lost function TCustomAI.Unit_AttackForecast(uix,ToLoc,AttackMovement: integer; var RemainingHealth: integer): boolean; var BattleForecast: TBattleForecast; begin assert((uix>=0) and (uix<RO.nUn) and (MyUnit[uix].Loc>=0) // is a unit and (Map[ToLoc] and (fUnit or fOwned)=fUnit)); // is an attack RemainingHealth:=-$100; result:=false; if AttackMovement>=0 then with MyUnit[uix] do begin BattleForecast.pAtt:=me; BattleForecast.mixAtt:=mix; BattleForecast.HealthAtt:=Health; BattleForecast.ExpAtt:=Exp; BattleForecast.FlagsAtt:=Flags; BattleForecast.Movement:=AttackMovement; if Server(sGetBattleForecast,me,ToLoc,BattleForecast)>=rExecuted then begin if BattleForecast.EndHealthAtt>0 then RemainingHealth:=BattleForecast.EndHealthAtt else RemainingHealth:=-BattleForecast.EndHealthDef; result:=true end end end; function TCustomAI.Unit_DefenseForecast(euix,ToLoc: integer; var RemainingHealth: integer): boolean; var BattleForecast: TBattleForecast; begin assert((euix>=0) and (euix<RO.nEnemyUn) and (RO.EnemyUn[euix].Loc>=0) // is an enemy unit and (Map[ToLoc] and (fUnit or fOwned)=(fUnit or fOwned))); // is an attack RemainingHealth:=$100; result:=false; with RO.EnemyUn[euix] do begin BattleForecast.pAtt:=Owner; BattleForecast.mixAtt:=mix; BattleForecast.HealthAtt:=Health; BattleForecast.ExpAtt:=Exp; BattleForecast.FlagsAtt:=Flags; BattleForecast.Movement:=100; if Server(sGetBattleForecast,me,ToLoc,BattleForecast)>=rExecuted then begin if BattleForecast.EndHealthDef>0 then RemainingHealth:=BattleForecast.EndHealthDef else RemainingHealth:=-BattleForecast.EndHealthAtt; result:=true end end end; function TCustomAI.Unit_Disband(uix: integer): integer; begin result:=Server(sRemoveUnit,me,uix,nodata^) end; function TCustomAI.Unit_StartJob(uix,NewJob: integer): integer; begin result:=Server(sStartJob+NewJob shl 4,me,uix,nodata^) end; function TCustomAI.Unit_SetHomeHere(uix: integer): integer; begin result:=Server(sSetUnitHome,me,uix,nodata^) end; function TCustomAI.Unit_Load(uix: integer): integer; begin result:=Server(sLoadUnit,me,uix,nodata^) end; function TCustomAI.Unit_Unload(uix: integer): integer; begin result:=Server(sUnloadUnit,me,uix,nodata^) end; function TCustomAI.Unit_AddToCity(uix: integer): integer; begin result:=Server(sAddToCity,me,uix,nodata^) end; function TCustomAI.Unit_SelectTransport(uix: integer): integer; begin result:=Server(sSelectTransport,me,uix,nodata^) end; procedure TCustomAI.City_FindMyCity(Loc: integer; var cix: integer); begin if Map[Loc] and (fCity or fOwned)<>fCity or fOwned then cix:=-1 else begin cix:=RO.nCity-1; while (cix>=0) and (MyCity[cix].Loc<>Loc) do dec(cix); end end; procedure TCustomAI.City_FindEnemyCity(Loc: integer; var ecix: integer); begin if Map[Loc] and (fCity or fOwned)<>fCity then ecix:=-1 else begin ecix:=RO.nEnemyCity-1; while (ecix>=0) and (RO.EnemyCity[ecix].Loc<>Loc) do dec(ecix); end end; function TCustomAI.City_HasProject(cix: integer): boolean; begin result:= MyCity[cix].Project and (cpImp+cpIndex)<>cpImp+imTrGoods end; function TCustomAI.City_CurrentImprovementProject(cix: integer): integer; begin if MyCity[cix].Project and cpImp=0 then result:=-1 else begin result:=MyCity[cix].Project and cpIndex; if result=imTrGoods then result:=-1 end end; function TCustomAI.City_CurrentUnitProject(cix: integer): integer; begin if MyCity[cix].Project and cpImp<>0 then result:=-1 else result:=MyCity[cix].Project and cpIndex; end; function TCustomAI.City_GetTileInfo(cix,TileLoc: integer; var TileInfo: TTileInfo): integer; begin TileInfo.ExplCity:=cix; result:=Server(sGetHypoCityTileInfo,me,TileLoc,TileInfo) end; function TCustomAI.City_GetReport(cix: integer; var Report: TCityReport): integer; begin Report.HypoTiles:=-1; Report.HypoTax:=-1; Report.HypoLux:=-1; result:=Server(sGetCityReport,me,cix,Report) end; function TCustomAI.City_GetHypoReport(cix, HypoTiles, HypoTax, HypoLux: integer; var Report: TCityReport): integer; begin Report.HypoTiles:=HypoTiles; Report.HypoTax:=HypoTax; Report.HypoLux:=HypoLux; result:=Server(sGetCityReport,me,cix,Report) end; function TCustomAI.City_GetReportNew(cix: integer; var Report: TCityReportNew): integer; begin Report.HypoTiles:=-1; Report.HypoTaxRate:=-1; Report.HypoLuxuryRate:=-1; result:=Server(sGetCityReportNew,me,cix,Report) end; function TCustomAI.City_GetHypoReportNew(cix, HypoTiles, HypoTaxRate, HypoLuxuryRate: integer; var Report: TCityReportNew): integer; begin Report.HypoTiles:=HypoTiles; Report.HypoTaxRate:=HypoTaxRate; Report.HypoLuxuryRate:=HypoLuxuryRate; result:=Server(sGetCityReportNew,me,cix,Report) end; function TCustomAI.City_GetAreaInfo(cix: integer; var AreaInfo: TCityAreaInfo): integer; begin result:=Server(sGetCityAreaInfo,me,cix,AreaInfo) end; function TCustomAI.City_StartUnitProduction(cix,mix: integer): integer; begin if (MyCity[cix].Project and (cpImp+cpIndex)<>mix) then // not already producing that result:=Server(sSetCityProject,me,cix,mix) else result:=eInvalid; end; function TCustomAI.City_StartEmigration(cix,mix: integer; AllowDisbandCity, AsConscripts: boolean): integer; var NewProject: integer; begin NewProject:=mix; if AllowDisbandCity then NewProject:=NewProject or cpDisbandCity; if AsConscripts then NewProject:=NewProject or cpConscripts; result:=Server(sSetCityProject,me,cix,NewProject) end; function TCustomAI.City_StartImprovement(cix,iix: integer): integer; var NewProject: integer; begin NewProject:=iix+cpImp; if (MyCity[cix].Project and (cpImp+cpIndex)<>NewProject) then // not already producing that result:=Server(sSetCityProject,me,cix,NewProject) else result:=eInvalid; end; function TCustomAI.City_Improvable(cix,iix: integer): boolean; var NewProject: integer; begin NewProject:=iix+cpImp; result:= Server(sSetCityProject-sExecute,me,cix,NewProject)>=rExecuted; end; function TCustomAI.City_StopProduction(cix: integer): integer; var NewProject: integer; begin NewProject:=imTrGoods+cpImp; result:=Server(sSetCityProject,me,cix,NewProject) end; function TCustomAI.City_BuyProject(cix: integer): integer; begin result:=Server(sBuyCityProject,me,cix,nodata^) end; function TCustomAI.City_SellImprovement(cix,iix: integer): integer; begin result:=Server(sSellCityImprovement,me,cix,iix) end; function TCustomAI.City_RebuildImprovement(cix,iix: integer): integer; begin result:=Server(sRebuildCityImprovement,me,cix,iix) end; function TCustomAI.City_SetTiles(cix,NewTiles: integer): integer; begin result:=Server(sSetCityTiles,me,cix,NewTiles) end; procedure TCustomAI.City_OptimizeTiles(cix: integer; ResourceWeights: cardinal); var Advice: TCityTileAdviceData; begin Advice.ResourceWeights:=ResourceWeights; Server(sGetCityTileAdvice, me, cix, Advice); City_SetTiles(cix, Advice.Tiles); end; // negotiation function TCustomAI.Nego_CheckMyAction: integer; begin assert(Opponent>=0); // only allowed in negotiation mode assert((MyAction=scDipNotice) or (MyAction=scDipAccept) or (MyAction=scDipCancelTreaty) or (MyAction=scDipOffer) or (MyAction=scDipBreak)); if MyAction=scDipOffer then result:=Server(MyAction-sExecute, me, 0, MyOffer) else result:=Server(MyAction-sExecute, me, 0, nodata^); end; initialization nodata:=pointer(0); RWDataSize:=0; end.
unit Grijjy.TextToSpeech.Base; {< Base class for text-to-speech implementations } interface uses System.Classes, Grijjy.TextToSpeech; type { Base class that implements IgoTextToSpeech. Platform-specific implementations derive from this class. } TgoTextToSpeechBase = class abstract(TInterfacedObject, IgoTextToSpeech) {$REGION 'Internal Declarations'} private FAvailable: Boolean; FOnAvailable: TNotifyEvent; FOnSpeechStarted: TNotifyEvent; FOnSpeechFinished: TNotifyEvent; protected { IgoTextToSpeech } function _GetAvailable: Boolean; function _GetOnAvailable: TNotifyEvent; procedure _SetOnAvailable(const AValue: TNotifyEvent); function _GetOnSpeechFinished: TNotifyEvent; procedure _SetOnSpeechFinished(const AValue: TNotifyEvent); function _GetOnSpeechStarted: TNotifyEvent; procedure _SetOnSpeechStarted(const AValue: TNotifyEvent); function Speak(const AText: String): Boolean; virtual; abstract; procedure Stop; virtual; abstract; function IsSpeaking: Boolean; virtual; abstract; protected { Fires the FOn* events in the main thread } procedure DoAvailable; procedure DoSpeechStarted; procedure DoSpeechFinished; property Available: Boolean read FAvailable write FAvailable; {$ENDREGION 'Internal Declarations'} end; implementation { TgoTextToSpeechBase } procedure TgoTextToSpeechBase.DoAvailable; begin if Assigned(FOnAvailable) then begin { Fire event from main thread. Use Queue instead of Synchronize to avoid blocking. } TThread.Queue(nil, procedure begin FOnAvailable(Self); end); end; end; procedure TgoTextToSpeechBase.DoSpeechFinished; begin if Assigned(FOnSpeechFinished) then begin TThread.Queue(nil, procedure begin FOnSpeechFinished(Self); end); end; end; procedure TgoTextToSpeechBase.DoSpeechStarted; begin if Assigned(FOnSpeechStarted) then begin TThread.Queue(nil, procedure begin FOnSpeechStarted(Self); end); end; end; function TgoTextToSpeechBase._GetAvailable: Boolean; begin Result := FAvailable; end; function TgoTextToSpeechBase._GetOnAvailable: TNotifyEvent; begin Result := FOnAvailable; end; function TgoTextToSpeechBase._GetOnSpeechFinished: TNotifyEvent; begin Result := FOnSpeechFinished; end; function TgoTextToSpeechBase._GetOnSpeechStarted: TNotifyEvent; begin Result := FOnSpeechStarted; end; procedure TgoTextToSpeechBase._SetOnAvailable(const AValue: TNotifyEvent); begin FOnAvailable := AValue; if (FAvailable) then DoAvailable; end; procedure TgoTextToSpeechBase._SetOnSpeechFinished(const AValue: TNotifyEvent); begin FOnSpeechFinished := AValue; end; procedure TgoTextToSpeechBase._SetOnSpeechStarted(const AValue: TNotifyEvent); begin FOnSpeechStarted := AValue; end; end.
type matrix = array[1..2,1..2] of int64; const I : matrix = ((1,0),(0,1)); F : matrix = ((0,1),(1,1)); function product(x,y:matrix):matrix; var i,j,k:longint; temp:matrix; begin for i:=1 to 2 do for j:=1 to 2 do temp[i][j]:=0; for i:=1 to 2 do for j:=1 to 2 do for k:=1 to 2 do temp[i][j]:=(temp[i][j]+x[i][k]*y[k][j]) mod 1000000; exit(temp); end; function power(x:matrix; n:longint):matrix; var temp:matrix; begin if n=0 then exit(I); temp := power(x,n div 2); temp := product(temp,temp); if n mod 2=1 then temp:=product(temp,x); exit(temp); end; var n:longint; begin readln(n); writeln((power(F,n)[1][1]+power(F,n)[2][1]) mod 1000000); end.
unit uTools; interface uses TypInfo, Variants, Classes, SysUtils; procedure DumpObject(instance: TObject); function ReadUTF8File(const fileName: String): String; function SplitString(const Source: String; Delimeters: array of Char): TStringList; implementation function ReadUTF8File(const fileName: String): String; var fs : TFileStream; src: UTF8String; data: WideString; begin fs := TFileStream.Create(fileName, fmOpenRead); try SetLength(src, fs.Size); fs.Read((PUTF8String(src))^, fs.Size); data := UTF8Decode(src); if ord(data[1]) = 65279 then Result := Copy(data, 2, Length(data)) else Result := data; finally fs.Free; end; end; procedure DumpObject(instance: TObject); var cnt : Integer; Size: Integer; List : PPropList; PropInfo: PPropInfo; i : Integer; begin cnt := GetPropList(instance.ClassInfo, tkAny, nil); writeln('Properties count: ', cnt); Size := cnt * SizeOf(Pointer); GetMem(List, Size); try cnt := GetPropList(instance.ClassInfo, tkAny, List); for i := 0 to cnt-1 do begin PropInfo := List^[i]; writeln(PropInfo^.Name, ' : ', VarToStr(GetPropValue(Instance, PropInfo^.Name))); end; finally FreeMem(List); end; end; function SplitString(const Source: String; Delimeters: array of Char): TStringList; var i : Integer; currVal: String; begin Result := TStringList.Create; currVal := Source; for i:=Low(Delimeters) to High(Delimeters) do currVal := StringReplace(currVal, Delimeters[i], #13#10, [rfReplaceAll]); Result.Text := currVal; end; end.
unit TNT_3D; interface uses TNT_Timer, TNT_Scene, TNT_Camera, TNT_Console; type TNT3D = class private Timer: TTime; public FPS: Single; Tris: Cardinal; constructor Create; procedure Resize(Width, Height: Cardinal); procedure Render; destructor Destroy; override; end; var TNT: TNT3D; Scene: TScene; Camera: TCamera; Console: TConsole; implementation uses OpenGL12, SysUtils, TNT_Font; constructor TNT3D.Create; begin inherited Create; Console := TConsole.Create(NB_LINES, PROMPT, LOG_NAME); Scene := TScene.Create; Camera := TCamera.Create(0,0,0, 0,0,0); Font := TFont.Create('font.tex'); Timer := TTime.Create; end; procedure TNT3D.Render; begin Scene.Render(Timer.Delta); glFlush; FPS := Timer.Refresh; end; procedure TNT3D.Resize(Width, Height: Cardinal); begin glViewPort(0, 0, Width, Height); glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(45, Width/Height, 1, 3000); Console.Log('OpenGL display resized to '+IntToStr(Width)+'x'+IntToStr(Height)); end; destructor TNT3D.Destroy; begin Timer.Free; Camera.Free; Scene.Free; Font.Free; Console.Free; inherited Destroy; end; end.
unit uEstadoDto; interface type TEstadoDto = class private FID: Integer; FUF: String; FNome: String; public property ID: Integer read FID write FID; property UF: String read FUF write FUF; property Nome: String read FNome write FNome; end; implementation end.
{$A+,B-,D-,E-,F-,I-,L-,N-,O-,R-,S-,V+} Unit CompMark; { COMPMARK.PAS - Adaptive data compression using "Splay" tree with Markov model. This algorithm was originally implemented in Pascal on the IBM PC by Kim Kokkonen [72457,2131], TurboPower Software, 8-16-88. His documentation follows: "Based on an article by Douglas W. Jones, 'Application of Splay Trees to Data Compression', in Communications of the ACM, August 1988, page 996. "This is a method somewhat similar to Huffman encoding (SQZ), but which is locally adaptive. It therefore requires only a single pass over the uncompressed file, and does not require storage of a code tree with the compressed file. It is characterized by code simplicity and low data overhead. Compression efficiency is not as good as recent ARC implementations, especially for large files. However, for small files, the efficiency of SPLAY approaches that of ARC's squashing technique." I have re-implemented the algorithm in assembler with some changes: 1. My intended use for this unit is to compress a relatively small data buffer as one might wish to do before transmitting it over a communications channel or storing it on disk. Consequently, this unit compresses and decompresses an in-memory buffer rather than a file. InitCompress initially balances the Splay tree[s] in the work area. The work area retains any tree adaptations done during compression or expansion until InitCompress is called again. Therefore, If you wish to make each buffer independently expandable, you must call InitCompress before each call to CompressData. ExpandData will detect what you have done and automatically call InitCompress where necessary. 2. I run-length-encode the input before compressing it with the Splay tree algorithm. This improves the compression ratio where the input contains long runs of duplicate characters. 3. Kim's original implementation used a unique trailer character to mark the end of data. I store the pre-compressed data length as the first word in the compressed data buffer and do not use a unique trailer character. This permits the uncompressed length to be determined by inspection and, because the ExpandBuffer routine stops when the output length is achieved, transmission errors will be less likely to blow out a buffer on the receiving end. The "Bits" parameter from InitCompress is also stored as the third byte in the buffer. 4. I have implemented the "Markov modeling" technique outlined in the Jones ACM reference. You may (indirectly) indicate the number of states in the InitCompress procedure. The work area size requirements are outlined in the comments on that proc. InitCompress(0) should reproduce the compression behavior of Kim's original SPLAY.PAS. The work area is passed as a parameter to the assembler primatives so they may be fully re-entrant. 5. I have added objects for management of compressed sequential record files on disk (see below). Cautions: 1. CompressData and ExpandData both read/write their input/output under the constraints of the 8086 segmented archetecture and I do not normalize the input/output pointers before starting. Therefore, you should call these routines with normalized pointers, and expect invalid output if the input/output length exceeds 64k minus Ofs(Dest). 2. The compressed output data may actually be longer than the input data if the input already has high "entropy". Compression typically increases the data entropy. Multiple compressions, therefore, are usually a waste of time. 3. As indicated in the ACM reference, this compression technique does not perform as well as LZW and its variations on large text files. It should be considered only where working storage is very scarce and/or the data to be compressed is expected to contain considerable redundency at the character level. The reference indicates that this algorithm can do especially well with image files. This program is contributed to the public domain. Please report bugs to the author: Edwin T. Floyd [76067,747] #9 Adams Park Ct. Columbus, GA 31909 404-576-3305 (work) 404-322-0076 (home) History -------- 12-27-89 Added compressed sequential file objects 12-07-89 Added 'cld' to compmark.asm, added auto-init detection logic 10-15-89 Initial Upload } Interface Uses DOS; Type { High-level objects for compressed sequential file support. } CompFileBase = Object { Used by objects below - Don't instantiate this object } CompBuff : Pointer; { Pointer to I/O buffer } CompTree : Pointer; { Pointer to compression/expansion work area } CompTrLen : LongInt;{ Length of compression/expansion work area } CompTotal : LongInt;{ Total size of uncompressed data in file } CompPosn : Word; { Current position in I/O buffer } CompBufSize : Word; { I/O buffer size } CompFile : File; { Physical file } CompName : PathStr; { File name } CompOpen : Boolean; { True if file is open } CompBits : Byte; { Current bits value } Constructor Init; { Dummy constructor, aborts program } Destructor Done; Virtual; { Close file and release buffer and work area } End; CompFileIn = Object(CompFileBase) { Compressed sequential input file } CompBytes : Word; { Number of bytes currently in buffer } Constructor Init(Name : PathStr; BufSize : Word); { Name specifies an existing compressed sequential file. BufSize specifies the size of I/O buffer to obtain from the heap. File is initially positioned to the first record. } Procedure GetRecord(Var Rec; Len : Word); { Uncompress the current record into Rec for a maximum length of Len bytes and update the file position to the next record. } Function RecLength : Word; { Returns the uncompressed length in bytes of the current record (this is the length of the record to be returned by the next GetRecord). } Function Eof : Boolean; { Returns TRUE after the last record has been retrieved by GetRecord. } Procedure Rewind; { Call this at any time to restart at the first record. } End; CompFileOut = Object(CompFileBase) { Compressed sequential output file } CompFlushed : Boolean; { True if output file doesn't need flushing } Constructor Init(Name : PathStr; BufSize : Word); { Name specifies the compressed sequential file to be created. BufSize specifies the size of buffer to obtain from the heap. After Init, the file is empty and ready to receive the first record. As a rule, BufSize should be AT LEAST 1.25 * SizeOf(Largest_Rec) + 5. To specify the 'Bits' value to be used for compression, call InitCompress immediately before the call to this constructor, otherwise Bits=0. } Destructor Done; Virtual; { Flush any remaining records in the buffer to the file, close the the file and release the buffer. } Procedure PutRecord(Var Rec; Len : Word); { Compress Rec for Len bytes and write to the file. } Procedure Flush; { Flush any records in the buffer to the file, close the file, re-open, and position to end of file. } End; CompFileAppend = Object(CompFileOut) { Append to existing compressed sequential file } Constructor Init(Name : PathStr; BufSize : Word); { Name and BufSize as above. After this Init, if the file already exists, it is positioned at the end of file ready to receive the next record. If the file doesn't exist, a new file is created, as for CompFileOut. Specify the 'Bits' value as above; bits may be different from the value originally specified. } End; { Low-level routines for buffer compression/expansion. } Procedure InitCompress(Bits : Byte); { Allocate compression/expansion work area and initialize. "Bits" refers to the number of bits in the current plain-text byte that determine the "state" of the Markov model to use for the next byte. "Bits" may be any value from 0 to 8. The size of the work area is determined by the number of states that may be specified by the indicated number of bits (plus 16 bytes). Each state is a Splay tree which occupies 1.5K of memory, so e.g, Bits=0 => determines 1 tree, or 1536+16 for a work area size of 1552 bytes. Bits=2 determines 4 trees or 4*1536+16 for a 6160 byte work area. Bits=8 determines 256 trees for a size of 393232 bytes. In general, the larger the number of states, the better the compression. If InitCompress is not called, CompressData will call it with Bits = 0, and ExpandData will call it with the same "Bits" setting used on the compressed buffer. InitCompress allocates its work area with HugeGetMem from the public domain TPALLOC unit by Brian Foley of TurboPower Software. } Function WorkAreaSize(Bits : Byte) : LongInt; { This function returns the length in bytes of the work area that would be allocated by InitCompress with the indicated Bits setting. } Function CompressData(Var Source; Count : Word; Var Dest) : Word; { Compress Count bytes from Source and place the compressed data in Dest. The length of the compressed data is returned as the function result. } Function ExpandData(Var Source; Var Dest) : Word; { Expand compressed data from Source and place the expanded data in Dest. The length of the expanded data is returned as the function result. } Function ExpandedLength(Var Source) : Word; { Inspect the compressed data in Source and return the length it will have when expanded. } Procedure ExpandDataLimited(Var Source; Var Dest; Len : Word); { Expand compressed data from Source and place the expanded data in Dest. Truncate the expanded data to no more than Len bytes. } Implementation Uses TpAlloc; Const MagicNumber = $4295E8F6; { This number marks the beginning of a compressed sequential file. } ReadMode = $40; { Deny None, Read access } WriteMode = $42; { Deny None, Read/Write access } Type BigArray = Array[0..65534] Of Byte; BufHeader = Record BufLength : Word; { Length of un-compressed data } BufBits : Byte; { 'Bits' value used to compress this buffer } BufData : Byte; { Beginning of compressed data } End; Var CompWork : Pointer; { Pointer to compression work area } WorkSize : LongInt; { Work area size } InitBits : Byte; { 'Bits' value for current work area } {$F-} Procedure InitSplay(Var Work; Bits : Word); External; { NEAR call } Function CompressBuffer(Var Work; Var Source; Count : Word; Var Dest) : Word; External; { NEAR call } Procedure ExpandBuffer(Var Work; Var Source; Var Dest; Count : Word); External; { NEAR call } {$L COMPMARK.OBJ } Function WorkAreaSize(Bits : Byte) : LongInt; Begin If Bits > 8 Then Bits := 8; WorkAreaSize := (LongInt(1) Shl Bits) * 1536 + 16; End; Procedure InitCompress(Bits : Byte); Begin Bits := Bits And $7F; If Bits > 8 Then Bits := 8; If Bits <> (InitBits And $7F) Then Begin HugeFreeMem(CompWork, WorkSize); WorkSize := WorkAreaSize(Bits); HugeGetMem(CompWork, WorkSize); If CompWork = Nil Then Begin WriteLn('InitCompress is unable to allocate ', WorkSize, ' bytes of workarea'); Halt(1); End; InitBits := Bits; End; InitSplay(CompWork^, Bits); InitBits := InitBits Or $80; End; Function CompressData(Var Source; Count : Word; Var Dest) : Word; Var DestBuf : BufHeader Absolute Dest; Begin If (InitBits And $7F) > 8 Then InitCompress(0); With DestBuf Do Begin BufLength := Count; BufBits := InitBits; InitBits := InitBits And $7F; If Count > 0 Then CompressData := CompressBuffer(CompWork^, Source, Count, BufData) + 3 Else CompressData := 3; End; End; Function ExpandData(Var Source; Var Dest) : Word; Var SourceBuf : BufHeader Absolute Source; Begin With SourceBuf Do Begin If ((BufBits And $7F) <> (InitBits And $7F)) Or ((BufBits And $80) <> 0) Then InitCompress(BufBits); If BufLength > 0 Then ExpandBuffer(CompWork^, BufData, Dest, BufLength); InitBits := InitBits And $7F; ExpandData := BufLength; End; End; Procedure ExpandDataLimited(Var Source; Var Dest; Len : Word); Var SourceBuf : BufHeader Absolute Source; Begin With SourceBuf Do Begin If ((BufBits And $7F) <> (InitBits And $7F)) Or ((BufBits And $80) <> 0) Then InitCompress(BufBits); If Len > BufLength Then Len := BufLength; If Len > 0 Then ExpandBuffer(CompWork^, BufData, Dest, Len); InitBits := InitBits And $7F; End; End; Function ExpandedLength(Var Source) : Word; Var SourceBuf : BufHeader Absolute Source; Begin ExpandedLength := SourceBuf.BufLength; End; Constructor CompFileBase.Init; Begin WriteLn('Use CompFileIn or CompFileOut'); Halt(1); End; Destructor CompFileBase.Done; Begin If CompOpen Then Begin Close(CompFile); CompOpen := False; End; If CompBufSize > 0 Then Begin FreeMem(CompBuff, CompBufSize); CompBufSize := 0; End; If CompTrLen > 0 Then Begin HugeFreeMem(CompTree, CompTrLen); CompTree := Nil; CompTrLen := 0; CompBits := 255; End; End; Constructor CompFileIn.Init(Name : PathStr; BufSize : Word); Var Magic : LongInt; OldMode : Byte; Begin CompOpen := False; CompBufSize := 0; CompBytes := 0; CompTree := Nil; CompTrLen := 0; CompBits := 255; CompPosn := 0; CompName := FExpand(Name); {$I-} OldMode := FileMode; FileMode := ReadMode; Assign(CompFile, CompName); Reset(CompFile, 1); FileMode := OldMode; {$I+} If IoResult = 0 Then Begin CompBufSize := BufSize; GetMem(CompBuff, CompBufSize); CompOpen := True; BlockRead(CompFile, Magic, SizeOf(Magic)); BlockRead(CompFile, CompTotal, SizeOf(CompTotal)); BlockRead(CompFile, CompBuff^, CompBufSize, CompBytes); If (Magic <> MagicNumber) Or ((CompBytes > 0) And (Word(CompBuff^) + 2 > CompBytes)) Then Begin WriteLn('Invalid compressed file format: ', CompName); Halt(1); End; End; End; Procedure CompFileIn.GetRecord(Var Rec; Len : Word); Var SaveWork : Pointer; SaveLen : LongInt; WorkLen : Word; SaveBits : Byte; Begin SaveWork := CompWork; SaveLen := WorkSize; SaveBits := InitBits; CompWork := CompTree; WorkSize := CompTrLen; InitBits := CompBits; If CompBytes > 0 Then Begin ExpandDataLimited(BigArray(CompBuff^)[CompPosn+2], Rec, Len); Move(BigArray(CompBuff^)[CompPosn], WorkLen, 2); CompPosn := CompPosn + WorkLen + 2; Move(BigArray(CompBuff^)[CompPosn], WorkLen, 2); If (CompPosn >= CompBytes) Or (WorkLen + CompPosn + 2 > CompBytes) Then Begin If CompPosn < CompBytes Then Begin If CompPosn > 0 Then Begin CompBytes := CompBytes - CompPosn; Move(BigArray(CompBuff^)[CompPosn], CompBuff^, CompBytes); End; End Else CompBytes := 0; CompPosn := 0; If FilePos(CompFile) < FileSize(CompFile) Then Begin BlockRead(CompFile, BigArray(CompBuff^)[CompBytes], CompBufSize - CompBytes, WorkLen); CompBytes := CompBytes + WorkLen; End; If (CompBytes > 0) And (Word(CompBuff^) + 2 > CompBytes) Then Begin WriteLn('Invalid file format or buffer too short: ', CompName); WriteLn('Expecting ', Word(CompBuff^) + 2, ' bytes'); WriteLn('Buffer holds ', CompBytes, ' bytes'); WriteLn(WorkLen, ' bytes from last file read'); WriteLn('File position is: ', FilePos(CompFile)); Halt(1); End; End; End; CompTree := CompWork; CompTrLen := WorkSize; CompBits := InitBits; CompWork := SaveWork; WorkSize := SaveLen; InitBits := SaveBits; End; Function CompFileIn.RecLength : Word; Begin If CompBytes > 0 Then RecLength := ExpandedLength(BigArray(CompBuff^)[CompPosn+2]) Else RecLength := 0; End; Function CompFileIn.Eof : Boolean; Begin Eof := CompBytes = 0; End; Procedure CompFileIn.Rewind; Begin If CompOpen Then Begin Seek(CompFile, SizeOf(LongInt)); BlockRead(CompFile, CompTotal, SizeOf(CompTotal)); BlockRead(CompFile, CompBuff^, CompBufSize, CompBytes); CompPosn := 0; End; End; Constructor CompFileOut.Init(Name : PathStr; BufSize : Word); Var Magic : LongInt; OldMode : Byte; Begin CompBufSize := BufSize; CompName := FExpand(Name); OldMode := FileMode; FileMode := WriteMode; Assign(CompFile, CompName); ReWrite(CompFile, 1); FileMode := OldMode; Magic := MagicNumber; BlockWrite(CompFile, Magic, SizeOf(Magic)); CompTotal := 0; BlockWrite(CompFile, CompTotal, SizeOf(CompTotal)); CompOpen := True; GetMem(CompBuff, CompBufSize); CompPosn := 0; CompFlushed := True; If (InitBits And $80) <> 0 Then Begin CompTree := CompWork; CompTrLen := WorkSize; CompBits := InitBits; CompWork := Nil; WorkSize := 0; InitBits := 255; End Else Begin CompTree := Nil; CompTrLen := 0; CompBits := 255; End; End; Destructor CompFileOut.Done; Begin If CompPosn > 0 Then BlockWrite(CompFile, CompBuff^, CompPosn); CompPosn := 0; Seek(CompFile, SizeOf(LongInt)); BlockWrite(CompFile, CompTotal, SizeOf(CompTotal)); CompFileBase.Done; End; Procedure CompFileOut.PutRecord(Var Rec; Len : Word); Var WorkLen, CompLen : Word; SaveWork : Pointer; SaveLen : LongInt; SaveBits : Byte; Begin SaveWork := CompWork; SaveLen := WorkSize; SaveBits := InitBits; CompWork := CompTree; WorkSize := CompTrLen; InitBits := CompBits; WorkLen := CompBufSize - CompPosn; If (Len + 5 > WorkLen) Or (Len + 5 > WorkLen - (Len Shr 2)) Then Begin BlockWrite(CompFile, CompBuff^, CompPosn); CompPosn := 0; WorkLen := CompBufSize; End; CompLen := CompressData(Rec, Len, BigArray(CompBuff^)[CompPosn+2]); If CompLen > WorkLen Then Begin WriteLn('Fatal error - Buffer overflow'); Close(CompFile); Halt(1); End; Inc(CompTotal, Len); Move(CompLen, BigArray(CompBuff^)[CompPosn], 2); CompPosn := CompPosn + CompLen + 2; CompFlushed := False; CompTree := CompWork; CompTrLen := WorkSize; CompBits := InitBits; CompWork := SaveWork; WorkSize := SaveLen; InitBits := SaveBits; End; Procedure CompFileOut.Flush; Var OldMode : Byte; Begin If Not CompFlushed Then Begin If CompPosn > 0 Then BlockWrite(CompFile, CompBuff^, CompPosn); CompPosn := 0; Seek(CompFile, SizeOf(LongInt)); BlockWrite(CompFile, CompTotal, SizeOf(CompTotal)); Close(CompFile); OldMode := FileMode; FileMode := WriteMode; Reset(CompFile, 1); FileMode := OldMode; Seek(CompFile, FileSize(CompFile)); CompFlushed := True; End; End; Constructor CompFileAppend.Init(Name : PathStr; BufSize : Word); Var Magic : LongInt; OldMode : Byte; Begin CompName := FExpand(Name); {$I-} OldMode := FileMode; FileMode := WriteMode; Assign(CompFile, CompName); Reset(CompFile, 1); {$I+} If IoResult = 0 Then Begin BlockRead(CompFile, Magic, SizeOf(Magic)); If Magic <> MagicNumber Then Begin WriteLn('Invalid compressed file format: ', CompName); Halt(1); End; BlockRead(CompFile, CompTotal, SizeOf(CompTotal)); Seek(CompFile, FileSize(CompFile)); End Else Begin ReWrite(CompFile, 1); Magic := MagicNumber; BlockWrite(CompFile, Magic, SizeOf(Magic)); CompTotal := 0; BlockWrite(CompFile, CompTotal, SizeOf(CompTotal)); End; FileMode := OldMode; CompOpen := True; CompBufSize := BufSize; GetMem(CompBuff, CompBufSize); CompPosn := 0; CompFlushed := True; If (InitBits And $80) <> 0 Then Begin CompTree := CompWork; CompTrLen := WorkSize; CompBits := InitBits; CompWork := Nil; WorkSize := 0; InitBits := 255; End Else Begin CompTree := Nil; CompTrLen := 0; CompBits := 255; End; End; Begin CompWork := Nil; WorkSize := 0; InitBits := 255; End.
unit Relatorio_NovaImpressao; interface uses Windows, SysUtils, Messages, Classes, Graphics, Controls, StdCtrls, ExtCtrls, Forms, QuickRpt, QRPrntr, QRCtrls, DB, DBClient, QRPDFFilt, CJVQRBarCode; type TTipoBand = (tHeaderUnico, tHeaderPagina, tDetalhe, tSubDetalhe, tRodape); TTipoShape = (tsLinha, tsRetangulo); TDesenho = class(TObject) private fComponenteParent: TWinControl; fRelatorioParent: TWinControl; procedure RedimensionarParent(); procedure VerificaParent; public property ComponenteParent: TWinControl read fComponenteParent write fComponenteParent; property RelatorioParent: TWinControl read fRelatorioParent write fRelatorioParent; procedure AdicionarCampoDBLabel(NomeField: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); procedure AdicionarCampoLabel(Texto: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); procedure AdicionarIncrementoAlturaBand(NomeBand: String; IncrementoAltura: Integer); procedure AdicionarShape(TipoShape: String; Linha, Coluna, Comprimento, Altura: Integer); procedure ConfigurarCampoLabel(var Componente: TQRCustomLabel; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); constructor Create(ARelatorioParent, AComponenteParent: TWinControl); destructor Destroy; override; end; // TFonte = class(TObject) // private // fCor: TColor; // fSublinhado: Boolean; // fNegrito: Boolean; // fNome: String; // fItalico: Boolean; // fTamanho: Integer; // public // property Nome: String read fNome write fNome; // property Tamanho: Integer read fTamanho write fTamanho; // property Negrito: Boolean read fNegrito write fNegrito; // property Italico: Boolean read fItalico write fItalico; // property Sublinhado: Boolean read fSublinhado write fSublinhado; // property Cor: TColor read fCor write fCor; // end; TRelatorio = class(TObject) private public end; TSubDetalhamento = class(TObject) private fDataSet: TDataSet; fCabecalho: TDesenho; fBandCabecalho: TQRBand; fNomeDetalhamento: String; fDetalhe: TDesenho; fBandDetalhe: TQRSubDetail; fRodape: TDesenho; fBandRodape: TQRBand; fRelatorioParent: TWinControl; procedure SetDataSet(const Value: TDataSet); property BandDetalhe: TQRSubDetail read fBandDetalhe; property BandCabecalho: TQRBand read fBandCabecalho; property BandRodape: TQRBand read fBandRodape; public procedure Cores(CorCabecalho, CorDetalhe, CorRodape: TColor); constructor Create(AOwner: TComponent; ANomeDetalhamento: String); destructor Destroy; override; property RelatorioParent: TWinControl read fRelatorioParent write fRelatorioParent; property DataSet: TDataSet read fDataSet write SetDataSet; property NomeDetalhamento: String read fNomeDetalhamento; property Detalhe: TDesenho read fDetalhe; property Cabecalho: TDesenho read fCabecalho; property Rodape: TDesenho read fRodape; end; TRelatorioNovaImpressao = class(TQuickRep) Cabecalho01: TQRBand; Cabecalho02: TQRBand; Cabecalho03: TQRBand; CabecalhoGeral: TQRBand; Detalhe01: TQRSubDetail; Detalhe02: TQRSubDetail; Detalhe03: TQRSubDetail; Principal: TQRBand; QRPDFFilter1: TQRPDFFilter; Rodape01: TQRBand; Rodape02: TQRBand; Rodape03: TQRBand; SeparadorPrincipal: TQRChildBand; procedure QRBandCabecalhoGeralBeforePrint(Sender: TQRCustomBand; var PrintBand: Boolean); private public constructor Create(AOwner: TComponent); override; procedure MontarRelatorio(); procedure Preview(); end; implementation uses StrUtils; {$R *.DFM} { TDesenho } constructor TDesenho.Create(ARelatorioParent, AComponenteParent: TWinControl); begin fRelatorioParent := ARelatorioParent; fComponenteParent := AComponenteParent; end; destructor TDesenho.Destroy; begin fComponenteParent := nil; fRelatorioParent := nil; inherited; end; procedure TDesenho.ConfigurarCampoLabel(var Componente: TQRCustomLabel; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); begin VerificaParent(); Componente.Parent := ComponenteParent; Componente.Left := Coluna; Componente.Top := Linha; Componente.Font.Size := TamanhoFonte; Componente.Width := TamanhoMaxTexto; Componente.AutoSize := False; if (TamanhoMaxTexto = 0) then Componente.AutoSize := True; RedimensionarParent(); end; procedure TDesenho.AdicionarCampoLabel(Texto: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); var Componente: TQRCustomLabel; begin VerificaParent(); Componente := TQRLabel.Create(RelatorioParent); TQRLabel(Componente).Transparent := True; TQRLabel(Componente).Caption := Texto; ConfigurarCampoLabel(Componente, Linha, Coluna, TamanhoMaxTexto, TamanhoFonte); end; procedure TDesenho.AdicionarCampoDBLabel(NomeField: String; Linha, Coluna, TamanhoMaxTexto, TamanhoFonte: Integer); var Componente: TQRCustomLabel; begin VerificaParent(); Componente := TQRDBText.Create(RelatorioParent); TQRDBText(Componente).Transparent := True; if (ComponenteParent.ClassType = TQRSubDetail) then TQRDBText(Componente).DataSet := TQRSubDetail(ComponenteParent).DataSet else if (ComponenteParent.ClassType = TQRBand) or (ComponenteParent.ClassType = TQRChildBand) then TQRDBText(Componente).DataSet := TQuickRep(RelatorioParent).DataSet else raise Exception.CreateFmt('Não identificado Parent para adicionar campo DBLabel %S', [NomeField]); TQRDBText(Componente).DataField := NomeField; ConfigurarCampoLabel(Componente, Linha, Coluna, TamanhoMaxTexto, TamanhoFonte); end; procedure TDesenho.AdicionarShape(TipoShape: String; Linha, Coluna, Comprimento, Altura: Integer); var Componente: TQRShape; begin VerificaParent(); Componente := TQRShape.Create(RelatorioParent); case AnsiIndexStr(UpperCase(TipoShape), ['LINHA', 'RETANGULO', 'OPCAO3']) of 0: Componente.Shape := qrsHorLine; 1: Componente.Shape := qrsRectangle; 2: Componente.Shape := qrsHorLine; end; Componente.Pen.Style := psDot; { linha tracejada } Componente.Parent := ComponenteParent; Componente.Left := Coluna; Componente.Top := Linha; Componente.Width := Comprimento; Componente.Height := Altura; if (Comprimento = 0) then Componente.Width := ComponenteParent.Width - Coluna; if (Altura <= 0) then raise Exception.Create('Obrigatório Informar Altura'); RedimensionarParent(); end; procedure TDesenho.RedimensionarParent(); var TamanhoOcupadoComponente: Integer; begin VerificaParent(); TamanhoOcupadoComponente := ComponenteParent.Top + ComponenteParent.Height; if (ComponenteParent.Parent.Height < TamanhoOcupadoComponente) then ComponenteParent.Parent.Height := TamanhoOcupadoComponente; { Result := TWinControl(FindComponent(NomeComponente)); } end; procedure TDesenho.AdicionarIncrementoAlturaBand(NomeBand: String; IncrementoAltura: Integer); begin VerificaParent(); TQRCustomBand(ComponenteParent).Height := TQRCustomBand(ComponenteParent).Height + IncrementoAltura; end; procedure TDesenho.VerificaParent(); begin if (RelatorioParent = nil) then raise Exception.Create('Relatório Parent não informado'); if (ComponenteParent = nil) then raise Exception.Create('Componente Parent não informado'); end; { TSubDetalhamento } procedure TSubDetalhamento.Cores(CorCabecalho, CorDetalhe, CorRodape: TColor); begin fBandCabecalho.Color := CorCabecalho; fBandDetalhe.Color := CorDetalhe; fBandRodape.Color := CorRodape; end; constructor TSubDetalhamento.Create(AOwner: TComponent; ANomeDetalhamento: String); begin fNomeDetalhamento := ANomeDetalhamento; fBandCabecalho := TQRBand.Create(AOwner); fBandDetalhe := TQRSubDetail.Create(AOwner); fBandRodape := TQRBand.Create(AOwner); fBandCabecalho.Name := 'Cabecalho' + fNomeDetalhamento; fBandDetalhe.Name := 'Detalhe' + fNomeDetalhamento; fBandRodape.Name := 'Rodape' + fNomeDetalhamento; fBandCabecalho.Parent := TWinControl(AOwner); fBandDetalhe.Parent := TWinControl(AOwner); fBandRodape.Parent := TWinControl(AOwner); fBandCabecalho.BandType := rbGroupHeader; fBandRodape.BandType := rbGroupFooter; fBandDetalhe.HeaderBand := fBandCabecalho; fBandDetalhe.FooterBand := fBandRodape; fBandCabecalho.Height := 0; fBandDetalhe.Height := 0; fBandRodape.Height := 0; fCabecalho := TDesenho.Create(TQuickRep(AOwner), fBandCabecalho); fDetalhe := TDesenho.Create(TQuickRep(AOwner), fBandDetalhe); fRodape := TDesenho.Create(TQuickRep(AOwner), fBandRodape); end; destructor TSubDetalhamento.Destroy; begin FreeAndNil(fCabecalho); FreeAndNil(fDetalhe); FreeAndNil(fRodape); fDataSet := nil; fBandCabecalho := nil; fBandDetalhe := nil; fBandRodape := nil; inherited; end; procedure TSubDetalhamento.SetDataSet(const Value: TDataSet); begin fDataSet := Value; fBandDetalhe.DataSet := fDataSet; end; { TRelatorioNovaImpressao } constructor TRelatorioNovaImpressao.Create(AOwner: TComponent); var I: Integer; begin inherited; { podera ser removido codigo abaixo } for I := 0 to ComponentCount - 1 do if (TComponent(Components[I]).ClassType = TQRBand) or (TComponent(Components[I]).ClassType = TQRSubDetail) or (TComponent(Components[I]).ClassType = TQRChildBand) then begin TQRCustomBand(Components[I]).Visible := False; TQRCustomBand(Components[I]).Height := 0; TQRCustomBand(Components[I]).TransparentBand := False; end; end; procedure TRelatorioNovaImpressao.Preview; var I: Integer; begin for I := 0 to ComponentCount - 1 do if (Components[I].ClassType = TQRSubDetail) then TQRSubDetail(Components[I]).PrintIfEmpty := False; Self.PrevInitialZoom := qrZoom100; Self.PreviewInitialState := wsMaximized; Self.PrevShowThumbs := False; Self.PrevShowSearch := False; Self.PreviewModal; end; procedure TRelatorioNovaImpressao.QRBandCabecalhoGeralBeforePrint(Sender: TQRCustomBand; var PrintBand: Boolean); begin // PrintBand := (Self.PageNumber > 1); end; procedure TRelatorioNovaImpressao.MontarRelatorio(); const _CabecalhoGeral = 'CabecalhoGeral'; _BaseRelatorio = 'Principal'; _RodapeGeral = 'QRBandRodape'; var ItensPedido, Ordem, Bloqueio: TSubDetalhamento; begin // AdicionarCampoLabel('Total Itens: ' + IntToStr(Self.DataSet.RecordCount), 1, 300, 0, 12, _CabecalhoGeral); // AdicionarCampoLabel('texto fixo em toda pagina ', 1, 100, 0, 12, _CabecalhoGeral); // // AdicionarCampoLabel('texto fixo em todo rodape ', 1, 100, 0, 12, _RodapeGeral); // // AdicionarCampoLabel('texto corpo', 1, 300, 0, 12, _BaseRelatorio); // AdicionarCampoLabel('texto corpo 2', 30, 300, 0, 12, _BaseRelatorio); // AdicionarCampoDBLabel('numero', 1, 50, 50, 12, _BaseRelatorio); // AdicionarCampoDBLabel('emissao', 1, 150, 0, 12, _BaseRelatorio); // // AdicionarShape('retangulo', 1, 1, 0, 18, _BaseRelatorio); // AdicionarShape('linha', 50, 0, 0, 5, _BaseRelatorio); // AdicionarIncrementoAlturaBand(_BaseRelatorio, 50); // // AdicionarShape('linha', 1, 0, 0, 18, 'SeparadorPrincipal'); ItensPedido := TSubDetalhamento.Create(Self, 'ItensPedido'); ItensPedido.Cores($005F9EF5, $009BC2F9, $00D1E3FC); ItensPedido.DataSet := Detalhe01.DataSet; ItensPedido.Cabecalho.AdicionarCampoLabel('numero-->', 1, 50, 0, 10); ItensPedido.Detalhe.AdicionarCampoDBLabel('NUMERO', 1, 50, 0, 10); ItensPedido.Detalhe.AdicionarCampoDBLabel('PRODUTO', 1, 200, 0, 10); ItensPedido.Detalhe.AdicionarCampoLabel('texto fixo itens', 10, 300, 0, 10); ItensPedido.Rodape.AdicionarCampoLabel('numero<--', 1, 50, 0, 10); FreeAndNil(ItensPedido); Ordem := TSubDetalhamento.Create(Self, 'Ordem'); Ordem.Cores($00D0EB76, $00E3F3AB, $00BEE340); Ordem.DataSet := Detalhe02.DataSet; Ordem.Cabecalho.AdicionarCampoLabel('ordem-->', 1, 50, 0, 10); Ordem.Detalhe.AdicionarCampoDBLabel('NUMERO', 1, 1, 0, 10); Ordem.Detalhe.AdicionarCampoDBLabel('ORDEM', 1, 50, 0, 10); Ordem.Detalhe.AdicionarCampoDBLabel('VCTO', 1, 100, 0, 10); Ordem.Detalhe.AdicionarCampoDBLabel('VALOR', 1, 250, 0, 10); Ordem.Detalhe.AdicionarCampoLabel('texto fixo ordem', 1, 400, 0, 10); Ordem.Rodape.AdicionarCampoLabel('ordem<--', 1, 50, 0, 10); FreeAndNil(Ordem); Bloqueio := TSubDetalhamento.Create(Self, 'Bloqueio'); Bloqueio.Cores($00FFAC59, $00FFD8B0, $00FFC891); Bloqueio.DataSet := Detalhe03.DataSet; Bloqueio.Cabecalho.AdicionarCampoLabel('bloqueio-->', 1, 50, 0, 10); Bloqueio.Detalhe.AdicionarCampoDBLabel('PEDIDO', 1, 1, 0, 10); Bloqueio.Detalhe.AdicionarCampoDBLabel('MOTIVO', 1, 50, 0, 10); Bloqueio.Detalhe.AdicionarCampoDBLabel('AUTORIZADO', 1, 100, 0, 10); Bloqueio.Detalhe.AdicionarCampoLabel('texto fixo bloqueio', 1, 400, 0, 10); Bloqueio.Rodape.AdicionarCampoLabel('bloqueio<--', 1, 50, 0, 10); FreeAndNil(Bloqueio); end; end.
unit UI.Principal; interface uses Gerenciador.TorreHanoi, System.UITypes, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Vcl.ComCtrls, Vcl.ImgList; type TForm2 = class(TForm) Panel1: TPanel; PnlOrigem: TPanel; PnlAuxiliar: TPanel; PnlDestino: TPanel; StatusBar1: TStatusBar; ImageList1: TImageList; GroupBox1: TGroupBox; BitBtn1: TBitBtn; BitBtn2: TBitBtn; ButtonedEdit1: TButtonedEdit; BitBtn3: TBitBtn; procedure BitBtn1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BitBtn2Click(Sender: TObject); procedure ButtonedEdit1RightButtonClick(Sender: TObject); procedure BitBtn3Click(Sender: TObject); private { Private declarations } public { Public declarations } TorreHanoi: TTorreHanoi; // declaração do objeto que ira processar o algoritmo da torre de hanói end; var Form2: TForm2; implementation {$R *.dfm} procedure TForm2.BitBtn1Click(Sender: TObject); begin // Esse metodo desenha os discos TorreHanoi.DesenharDiscos( StrToInt( ButtonedEdit1.Text ) ); end; procedure TForm2.BitBtn2Click(Sender: TObject); begin // verifica se os discos ja estão crados if ( TorreHanoi.VerificarSeOsDiscosForamCriados ) then TorreHanoi.Executar() // Executa o algoritmo da torre de hanói else MessageDlg( 'É necessário criar os discos', mtInformation, [mbOk], 0 ); end; procedure TForm2.BitBtn3Click(Sender: TObject); begin if ( MessageDlg( 'Deseja realmente sair?', mtConfirmation, [mbYes, mbNo], 0 ) = mrYes ) then Close(); end; procedure TForm2.ButtonedEdit1RightButtonClick(Sender: TObject); var QuantidadeDiscos: string; begin if ( InputQuery( 'Torre de Hanói', 'Informe a quantidade de discos', QuantidadeDiscos)) then ButtonedEdit1.Text:= QuantidadeDiscos; end; procedure TForm2.FormCreate(Sender: TObject); begin // Cria o objeto responsável por processar o algoritmo da torre de hanói TorreHanoi:= TTorreHanoi.Create( PnlOrigem, PnlAuxiliar, PnlDestino ); end; procedure TForm2.FormDestroy(Sender: TObject); begin // destroi o objeto criado para processar o algoritmo da torre de hanói FreeAndNil( TorreHanoi ) end; end.
unit Server.Models.Cadastros.FaseContato; interface uses System.Classes, DB, System.SysUtils, Generics.Collections, /// orm dbcbr.mapping.attributes, dbcbr.types.mapping, ormbr.types.lazy, ormbr.types.nullable, dbcbr.mapping.register, Server.Models.Base.TabelaBase; type [Entity] [Table('FASE_CONTATO','')] [PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')] TFaseContato = class(TTabelaBase) private fNOME: String; fEXIGE_OBSERVACAO: String; function Getid: Integer; procedure Setid(const Value: Integer); procedure GetNOME(const Value: String); public constructor create; destructor destroy; override; { Public declarations } [Restrictions([NotNull, Unique])] [Column('CODIGO', ftInteger)] [Dictionary('CODIGO','','','','',taCenter)] property id: Integer read Getid write Setid; [Column('NOME', ftString, 50)] [Dictionary('NOME','Mensagem de validação','','','',taLeftJustify)] property NOME: String read fNOME write GetNOME; [Column('EXIGE_OBSERVACAO', ftString, 1)] [Dictionary('EXIGE_OBSERVACAO','Mensagem de validação','','','',taLeftJustify)] property EXIGE_OBSERVACAO:String read fEXIGE_OBSERVACAO write fEXIGE_OBSERVACAO; end; implementation { TFaseContato } uses Infotec.Utils; constructor TFaseContato.create; begin end; destructor TFaseContato.destroy; begin inherited; end; function TFaseContato.Getid: Integer; begin Result := fid; end; procedure TFaseContato.GetNOME(const Value: String); begin fNOME := TInfotecUtils.RemoverEspasDuplas(Value); end; procedure TFaseContato.Setid(const Value: Integer); begin fid := Value; end; initialization TRegisterClass.RegisterEntity(TFaseContato); end.
unit uFormulario; { Exemplo de Façade com Delphi Criado por André Luis Celestino: www.andrecelestino.com } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, StdCtrls, Buttons, Grids, DBGrids; type { Client } TfFormulario = class(TForm) ClientDataSetClientes: TClientDataSet; ClientDataSetClientesCodigo: TIntegerField; ClientDataSetClientesCliente: TStringField; ClientDataSetClientesFidelidade: TSmallintField; BitBtnCalcularValorDaVenda: TBitBtn; ClientDataSetProdutos: TClientDataSet; ClientDataSetProdutosCodigo: TIntegerField; ClientDataSetProdutosProduto: TStringField; ClientDataSetProdutosPreco: TFloatField; DBGridClientes: TDBGrid; LabelCliente: TLabel; DBGridProdutos: TDBGrid; LabelProduto: TLabel; DataSourceClientes: TDataSource; DataSourceProdutos: TDataSource; Memo: TMemo; LabelHistorico: TLabel; procedure BitBtnCalcularValorDaVendaClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ClientDataSetClientesFidelidadeGetText(Sender: TField; var Text: String; DisplayText: Boolean); end; var fFormulario: TfFormulario; implementation uses System.UITypes, uFacade; {$R *.dfm} procedure TfFormulario.BitBtnCalcularValorDaVendaClick(Sender: TObject); var Fidelidade: smallint; Preco: real; Facade: TFacade; begin MessageDlg('Neste momento, o Façade será instanciado para:' + sLineBreak + ' - Consultar a cotação do dólar no WebService;' + sLineBreak + ' - Calcular o preço em Reais (R$);' + sLineBreak + ' - Aplicar desconto conforme Fidelidade e margem de venda;' + sLineBreak + ' - Registrar a operação no arquivo "Histórico.txt".', mtInformation, [mbOK], 0); Fidelidade := ClientDataSetClientes.FieldByName('Fidelidade').AsInteger; Preco := ClientDataSetProdutos.FieldByName('Preco').AsFloat; // cria uma instância do Façade Facade := TFacade.Create; try // chama o método do Façade que, por sua vez, // executa as operações de todos os Subsystems Facade.CalcularValorDeVenda(Fidelidade, Preco); // carrega o log da operação (gerado por um dos Subsystems) Memo.Lines.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'Historico.txt'); // navega para a última linha do Memo Memo.Lines.Add(EmptyStr); Perform(EM_SCROLL, SB_LINEDOWN, 0); finally // libera o objeto da memória FreeAndNil(Facade); end; end; procedure TfFormulario.FormCreate(Sender: TObject); var CaminhoAplicacao: string; begin // obtém o caminho do aplicação CaminhoAplicacao := ExtractFilePath(ParamStr(0)); // exclui o arquivo de histórico existente DeleteFile(CaminhoAplicacao + 'Historico.txt'); // carrega os dados de clientes e produtos a partir de arquivos XML ClientDataSetClientes.LoadFromFile(CaminhoAplicacao + 'Clientes.xml'); ClientDataSetProdutos.LoadFromFile(CaminhoAplicacao + 'Produtos.xml'); end; procedure TfFormulario.ClientDataSetClientesFidelidadeGetText( Sender: TField; var Text: String; DisplayText: Boolean); begin // exibe a descrição da fidelidade conforme o código case Sender.AsInteger of 0: Text := 'Nenhum'; 1: Text := 'Bronze'; 2: Text := 'Prata'; 3: Text := 'Ouro'; end; end; end.
unit CatCLUtils; { Catarinka - Command-line parameters related functions Copyright (c) 2003-2014 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.SysUtils; {$ELSE} SysUtils; {$ENDIF} function GetCmdLine: string; function GetCmdParam(const param: string; const def_value: string = ''): string; function GetCmdParamQuoted(const param: string; const def_value: string = ''): string; function HasCmdParam(const param: string): boolean; implementation uses CatStrings; function GetCmdLine: string; var i: integer; begin result := emptystr; if ParamCount > 0 then for i := 1 to ParamCount do result := result + ' ' + (ParamStr(i)); end; // Example: hascmdparam('-test') or ('-test:anystr') returns true function HasCmdParam(const param: string): boolean; var i: integer; curparam: string; begin result := false; if ParamCount = 0 then exit; for i := 1 to ParamCount do begin curparam := lowercase(ParamStr(i)); if pos(':', curparam) <> 0 then curparam := before(curparam, ':'); if curparam = lowercase(param) then result := true; end; end; // if paramstr is: name:somestring // eg: getCmdParam('name') will return "somestring" function GetCmdParam(const param: string; const def_value: string = ''): string; var i: integer; params: string; begin result := emptystr; if ParamCount = 0 then exit; for i := 1 to ParamCount do params := params + ' ' + (ParamStr(i)); params := params + ' '; result := after(params, param + ':'); result := before(result, ' '); if result = emptystr then result := def_value; end; function GetCmdParamQuoted(const param: string; const def_value: string = ''): string; var i: integer; params: string; const quote = '"'; begin result := emptystr; if ParamCount = 0 then exit; for i := 1 to ParamCount do params := params + ' ' + (ParamStr(i)); params := params + ' '; result := after(params, param + ':'); if beginswith(result, quote) then begin result := after(result, quote); result := before(result, quote); end else result := before(result, ' '); if result = emptystr then result := def_value; end; // ------------------------------------------------------------------------// end.
unit RRManagerMapViewFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RRManagerBaseGUI, ToolWin, ComCtrls, OleCtrls, RRManagerObjects, ActnList, ImgList, Menus, RRManagerCommon, OleServer, RRManagerBaseObjects; type // TfrmMapView = class(TFrame) TfrmMapView = class(TBaseFrame) tlbrMapEdit: TToolBar; actnLst: TActionList; actnAgglomerateSelection: TAction; actnClearSlelection: TAction; ToolButton1: TToolButton; ToolButton2: TToolButton; imgLst: TImageList; tlbtnSelectedStructures: TToolButton; pmnStructures: TPopupMenu; actnStructures: TAction; ToolButton3: TToolButton; pmnStructuresFoundByName: TPopupMenu; pmnNotFoundStructures: TPopupMenu; actStructuresFoundByName: TAction; actnNotFoundStructures: TAction; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; actnZoomSelected: TAction; ToolButton7: TToolButton; procedure actnAgglomerateSelectionExecute(Sender: TObject); procedure actnClearSlelectionExecute(Sender: TObject); procedure actnStructuresUpdate(Sender: TObject); procedure actStructuresFoundByNameUpdate(Sender: TObject); procedure actnNotFoundStructuresUpdate(Sender: TObject); procedure actnZoomSelectedExecute(Sender: TObject); procedure mgmFundMaponSelectionChanged(ASender: TObject; const Map: IDispatch); private { Private declarations } FLayerName, FFieldLayerName: string; //FLayer, FFieldLayer: IMapLayer3; FNGRID: integer; FSelectedStructure: TOldStructure; FLoadSelectedStructAction: TBaseAction; function GetMapObject(AUIN: string; PreserveSelection: boolean): boolean; function GetMapNamedObject(AName: string; PreserveSelection: boolean): boolean; function GetBufferedObjectsMap: boolean; function GetStructure: TOldStructure; procedure MenuItemClick(Sender: TObject); protected procedure FillControls(ABaseObject: TBaseObject); override; procedure ClearControls; override; procedure FillParentControls; override; public { Public declarations } property Structure: TOldStructure read GetStructure; property SelectedStructure: TOldStructure read FSelectedStructure; constructor Create(AOwner: TComponent); override; end; implementation uses RRManagerLoaderCommands, RRManagerPersistentObjects, RRManagerDataPosters, RRManagerEditCommands, Facade; {$R *.dfm} type TLoadSelectedStructure = class(TStructureBaseLoadAction) private FLastUIN: integer; public function Execute(AFilter: string): boolean; override; function Execute(AUIN: integer): boolean; overload; constructor Create(AOwner: TComponent); override; end; TEditSelectedStructure = class(TStructureBaseEditAction) public function Execute(ABaseObject: TBaseObject): boolean; overload; override; function Execute: boolean; overload; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; // не работает - компонент глючит // Shape удаляется один, а строка в таблице - другая, // не соответствующая ему TDeleteSelectedStructure = class(TStructureBaseDeleteAction) public function Execute(ABaseObject: TBaseObject): boolean; overload; override; function Execute: boolean; overload; override; function Update: boolean; override; constructor Create(AOwner: TComponent); override; end; function FindMenuItem(ATag: integer; AMenu: TMenu): TMenuItem; var i: integer; begin Result := nil; for i := 0 to AMenu.Items.Count - 1 do if AMenu.Items[i].Tag = ATag then begin Result := AMenu.Items[i]; break; end; end; function AddMenuItem(AMenu: TMenu; ACaption: string; AImageIndex, ATag: integer; AChacked: boolean; AOnClick: TNotifyEvent): TMenuItem; begin Result := TMenuItem.Create(AMenu); Result.Caption := ACaption; Result.Tag := ATag; Result.Checked := true; Result.OnClick := AOnClick; Result.ImageIndex := AImageIndex; AMenu.Items.Add(Result); end; { TfrmMapView } procedure TfrmMapView.ClearControls; begin inherited; actnClearSlelection.Execute; end; constructor TfrmMapView.Create(AOwner: TComponent); var actn: TBaseAction; begin inherited; FLayerName := 'struct'; FFieldLayerName := 'месторождения'; actn := TLoadSelectedStructure.Create(actnLst); actn.ActionList := actnLst; FLoadSelectedStructAction := actn; { actn := TDeleteSelectedStructure.Create(actnLst); actn.ActionList := actnLst; AddToolButton(tlbrMapEdit, actn);} actn := TEditSelectedStructure.Create(actnLst); actn.ActionList := actnLst; AddToolButton(tlbrMapEdit, actn) end; procedure TfrmMapView.FillControls(ABaseObject: TBaseObject); var bObjectFound: boolean; begin inherited; if Structure.PetrolRegions.Count > 0 then FNGRID := Structure.PetrolRegions.Items[0].ID; bObjectFound := GetMapObject(IntToStr(Structure.ID), actnAgglomerateSelection.Checked); if bObjectFound then begin { if not mgmFundMap.isBusy and actnZoomSelected.Checked then begin mgmFundMap.zoomSelected; if Assigned(mgmFundMap.Selection) then mgmFundMap.Selection.clear; end; } if (actnAgglomerateSelection.Checked and not Assigned(FindMenuItem(Structure.ID, pmnStructures))) then AddMenuItem(pmnStructures, Structure.Name, Structure.StructureTypeID + 1, Structure.ID, true, MenuItemClick) end else begin bObjectFound := GetMapNamedObject(Structure.Name, actnAgglomerateSelection.Checked); if bObjectFound then begin { if not mgmFundMap.isBusy and actnZoomSelected.Checked then begin mgmFundMap.zoomSelected; if Assigned(mgmFundMap.Selection) then mgmFundMap.Selection.clear; end; } if (actnAgglomerateSelection.Checked and not Assigned(FindMenuItem(Structure.ID, pmnStructuresFoundByName))) then AddMenuItem(pmnStructuresFoundByName, Structure.Name, Structure.StructureTypeID + 1, Structure.ID, true, MenuItemClick) end else begin // отзумить на НГР { if not mgmFundMap.isBusy and actnZoomSelected.Checked then begin if Assigned(mgmFundMap.Selection) then mgmFundMap.Selection.clear; mgmFundMap.zoomGotoLocation('НГР_uin', IntToStr(FNgrID), 2000); end;} if (actnAgglomerateSelection.Checked and not Assigned(FindMenuItem(Structure.ID, pmnNotFoundStructures))) then AddMenuItem(pmnNotFoundStructures, Structure.Name, Structure.StructureTypeID + 1, Structure.ID, true, MenuItemClick) end; end; end; procedure TfrmMapView.FillParentControls; begin inherited; end; function TfrmMapView.GetMapObject(AUIN: string; PreserveSelection: boolean): boolean; {var mObj: IMapObject2; sel: ISelection;} begin Result := false; {if not mgmFundMap.isBusy then begin if not Assigned(FLayer) then FLayer := mgmFundMap.GetMapLayer(FLayerName); if not Assigned(FFieldLayer) then FFieldLayer := mgmFundMap.GetMapLayer(FFieldLayerName); if Assigned(FLayer) then begin FLayer.setVisibility(true); mObj := FLayer.getMapObject(AUIN); if Assigned(mObj) then begin Result := true; sel := mgmFundMap.getSelection; if not PreserveSelection then sel.clear; sel.addObject(mObj, true); end; end; end;} end; function TfrmMapView.GetStructure: TOldStructure; begin Result := EditingObject as TOldStructure; FSelectedStructure := Result; end; procedure TfrmMapView.actnAgglomerateSelectionExecute(Sender: TObject); begin actnAgglomerateSelection.Checked := not actnAgglomerateSelection.Checked; end; procedure TfrmMapView.actnClearSlelectionExecute(Sender: TObject); //var sel: ISelection; begin {if not mgmFundMap.isBusy then begin sel := mgmFundMap.getSelection; sel.clear; if not mgmFundMap.isBusy and actnZoomSelected.Checked then pmnStructures.Items.Clear; pmnStructuresFoundByName.Items.Clear; pmnNotFoundStructures.Items.Clear; end;} end; procedure TfrmMapView.MenuItemClick(Sender: TObject); var mni: TMenuItem; begin mni := Sender as TMenuItem; mni.Checked := not mni.Checked; GetBufferedObjectsMap; { if not mgmFundMap.isBusy and actnZoomSelected.Checked then mgmFundMap.zoomSelected; } end; function TfrmMapView.GetBufferedObjectsMap: boolean; {var i: integer; sel: ISelection;} begin Result := false; { sel := mgmFundMap.getSelection; sel.Clear; for i := 0 to pmnStructures.Items.Count - 1 do if pmnStructures.Items[i].Checked then GetMapObject(IntToStr(pmnStructures.Items[i].Tag), true); for i := 0 to pmnStructuresFoundByName.Items.Count - 1 do if pmnStructuresFoundByName.Items[i].Checked then GetMapNamedObject(pmnStructuresFoundByName.Items[i].Caption, true); } end; procedure TfrmMapView.actnStructuresUpdate(Sender: TObject); begin actnStructures.Enabled := actnAgglomerateSelection.Checked and (pmnStructures.Items.Count > 0); end; function TfrmMapView.GetMapNamedObject(AName: string; PreserveSelection: boolean): boolean; {var mObjs: ICollection; mObj: OleVariant; sel: OleVariant; i: integer; sName: string;} begin { Result := false; if not mgmFundMap.isBusy then begin if not Assigned(FLayer) then FLayer := mgmFundMap.GetMapLayer(FLayerName); if not Assigned(FFieldLayer) then FFieldLayer := mgmFundMap.GetMapLayer(FFieldLayerName); if Assigned(FLayer) then begin FLayer.setVisibility(true); mObjs := FLayer.getMapObjects; for i := 0 to mObjs.size - 1 do begin mObj := mObjs.item(i); sName := trim(AnsiUpperCase(mObj.getName)); AName := trim(AnsiUpperCase(AName)); // вычищаем ое, ая и скобки AName := trim(StringReplace(AName, '(ОЕ)', '', [])); AName := trim(StringReplace(AName, '(-ОЕ)', '', [])); if (pos(sName, AName) = 1) or (pos(AName, sName) = 1) then begin Result := true; sel := mgmFundMap.getSelection; if not PreserveSelection then sel.clear; sel.addObject(mObj, true); break; end; end; end; end;} end; procedure TfrmMapView.actStructuresFoundByNameUpdate(Sender: TObject); begin actStructuresFoundByName.Enabled := actnAgglomerateSelection.Checked and (pmnStructuresFoundByName.Items.Count > 0); end; procedure TfrmMapView.actnNotFoundStructuresUpdate(Sender: TObject); begin actnNotFoundStructures.Enabled := actnAgglomerateSelection.Checked and (pmnNotFoundStructures.Items.Count > 0); end; procedure TfrmMapView.actnZoomSelectedExecute(Sender: TObject); begin actnZoomSelected.Checked := not actnZoomSelected.Checked; {if not mgmFundMap.isBusy and actnZoomSelected.Checked then mgmFundMap.zoomSelected else mgmFundMap.zoomOut;} end; procedure TfrmMapView.mgmFundMaponSelectionChanged(ASender: TObject; const Map: IDispatch); {var Sel: OleVariant; SelObjs: OleVariant; SelItem: OleVariant; i, iKey: integer;} begin // { FSelectedStructure := nil; sel := mgmFundMap.getSelection; if not Assigned(FLayer) then FLayer := mgmFundMap.GetMapLayer(FLayerName); if not Assigned(FFieldLayer) then FFieldLayer := mgmFundMap.GetMapLayer(FFieldLayerName); SelObjs := Sel.getMapObjects(FLayer); if SelObjs.Count = 0 then SelObjs := Sel.getMapObjects(FFieldLayer); for i := 0 to SelObjs.Count - 1 do begin SelItem := SelObjs.Item(i); iKey := SelItem.Key; if iKey > 0 then begin (FLoadSelectedStructAction as TLoadSelectedStructure).Execute(iKey); end; end;} end; { TLoadSelectedStructure } constructor TLoadSelectedStructure.Create(AOwner: TComponent); begin inherited; Visible := false; Enabled := false; end; function TLoadSelectedStructure.Execute(AFilter: string): boolean; var dp: TDataPoster; cls: TDataPosterClass; begin with ActionList.Owner as TfrmMapView do begin FSelectedStructure := (TMainFacade.GetInstance as TMainFacade).AllStructures.ItemsByUIN[FLastUIN] as TOldStructure; if not Assigned(FSelectedStructure) then begin Result := false; LastCollection := (TMainFacade.GetInstance as TMainFacade).AllStructures; LastCollection.NeedsUpdate := (AFilter <> LastFilter) or (FLastUIN = 0); LastFilter := AFilter; if LastCollection.NeedsUpdate then begin dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[TStructureDataPoster] as TDataPoster; dp.ClearFirst := false; Result := inherited Execute(AFilter); FSelectedStructure := (TMainFacade.GetInstance as TMainFacade).AllStructures.ItemsByUIN[FLastUIN] as TOldStructure; dp.ClearFirst := true; if Assigned(FSelectedStructure) then begin cls := TStructureDataPoster; case FSelectedStructure.StructureTypeID of // Выявленные 1: cls := TDiscoveredStructureDataPoster; // подгтовленные 2: cls := TPreparedStructureDataPoster; // в бурении 3: cls := TDrilledStructureDataPoster; // месторождения 4: cls := TFieldDataPoster; end; if Assigned(cls) then begin // берем постер dp := (TMainFacade.GetInstance as TMainFacade).AllPosters.Posters[cls]; // инициализируем коллекцию dp.LastGotObject := FSelectedStructure; // инициализируем коллекцию dp.GetFromDB(FSelectedStructure.ID); FSelectedStructure.NeedsUpdate := false; end; end; end; end; end; end; function TLoadSelectedStructure.Execute(AUIN: integer): boolean; begin FLastUIN := AUIN; Result := Execute('Structure_ID = ' + IntToStr(AUIN)); end; { TEditSelectedStructure } constructor TEditSelectedStructure.Create(AOwner: TComponent); begin inherited; Caption := 'Редактировать структуру'; ImageIndex := 2; Visible := true; Enabled := true; end; function TEditSelectedStructure.Execute: boolean; begin Result := Execute((ActionList.Owner as TfrmMapView).SelectedStructure); end; function TEditSelectedStructure.Execute(ABaseObject: TBaseObject): boolean; begin Result := inherited Execute(ABaseObject); end; function TEditSelectedStructure.Update: boolean; begin inherited Update; Result := Assigned((ActionList.Owner as TfrmMapView).SelectedStructure); Enabled := Result; end; { TDeleteSelectedStructure } constructor TDeleteSelectedStructure.Create(AOwner: TComponent); begin inherited; Caption := 'Удалить структуру'; ImageIndex := 11; Visible := true; Enabled := true; end; function TDeleteSelectedStructure.Execute: boolean; begin Result := Execute((ActionList.Owner as TfrmMapView).SelectedStructure); end; function TDeleteSelectedStructure.Execute( ABaseObject: TBaseObject): boolean; { var iUIN, iCurRecord: integer; frm: TfrmMapView; ShapeFiles: TShapeFiles; sName: OleVariant; procedure CopyFiles(AFileName: string); var sr: TSearchRec; sTimeStamp: string; fs, ss: TFileStream; begin sTimeStamp := FormatDateTime('yyyy_m_d_hh_mm', Now); if FindFirst('\\srv3\fund$\' + AFileName + '.*', faAnyFile, Sr) = 0 then begin sTimeStamp :='\\srv3\fund$\ModifiedShapes\' + sTimeStamp + '\'; repeat CreateDir(sTimeStamp); fs := TFileStream.Create(sTimeStamp + ExtractFileName(sr.Name), fmCreate or fmOpenWrite); ss := TFileStream.Create('D:\Work\NewClient\Struct\' + sr.Name, fmOpenRead); fs.CopyFrom(ss, ss.Size); fs.Free; SS.Free; until FindNext(sr) <> 0; FindClose(sr); end end;} {procedure MoveFiles(AShapeFiles: TShapeFiles); var NewSHP: TShapeFiles; i: integer; k: OleVariant; begin NewSHP := TShapeFiles.Create(nil); NewSHP.OpenShape('D:\Work\NewClient\Struct\' + 'struct_.shp', shpCreate, shpPolygon); // добавляем поля for i := 0 to AShapeFiles.ShapeFields.Count - 1 do begin k := i; NewSHP.ShapeFields.CreateField(AShapeFiles.ShapeFields[k].FieldName, AShapeFiles.ShapeFields[k].FieldType, AShapeFiles.ShapeFields[k].FieldSize, AShapeFiles.ShapeFields[k].FieldDecimal); end; NewSHP.AppendFieldDefs; for i := 0 to AShapeFiles.RecordCount - 1 do begin NewSHP.CreateShape; end; end; } begin (* iUIN := ABaseObject.ID; // Result := inherited Execute(ABaseObject); Result := true; if Result then begin frm := (ActionList.Owner as TfrmMapView); ShapeFiles := TShapeFiles.Create(nil); ShapeFiles.OpenShape('D:\Work\NewClient\Struct\struct.shp', shpOpen, shpPolygon); ShapeFiles.FindFirst('ID', '=', varAsType(iUIN, varInteger)); While not ShapeFiles.NoMatch do begin // копируем ShapeFile в другое место CopyFiles('struct'); // удаляем ShapeFiles.MoveTo(ShapeFiles.CurrentRecord - 2); ShowMessage(IntToStr(ShapeFiles.CurrentRecord)); sName := 'ID'; ShowMessage(varAsType(ShapeFiles.ShapeFields[sName].Value, varOleStr)); sName := 'ID'; ShowMessage(varAsType(ShapeFiles.ShapeFields[sName].Value, varOleStr)); iCurRecord := ShapeFiles.CurrentRecord; ShapeFiles.OpenShape('D:\Work\NewClient\Struct\struct.shp', shpEdit, shpPolygon); ShapeFiles.Pack; ShapeFiles.OpenShape('D:\Work\NewClient\Struct\struct.shp', shpOpen, shpPolygon); ShapeFiles.FindNext; if not ShapeFiles.NoMatch then ShapeFiles.OpenShape('D:\Work\NewClient\Struct\struct.shp', shpEdit, shpPolygon); end; // переместить файлы ShapeFiles.Free; end; *) end; function TDeleteSelectedStructure.Update: boolean; begin Result := Assigned((ActionList.Owner as TfrmMapView).SelectedStructure); Enabled := Result; end; end.
unit uTempItem; interface type TTempItem = class private FCelsius: double; FFahrenheit: double; public constructor Create( C, F : double ); published property Celsius: double read FCelsius write FCelsius; property Fahrenheit: double read FFahrenheit write FFahrenheit; end; implementation { TTempItem } constructor TTempItem.Create(C, F: double); begin inherited Create; self.Celsius := C; self.Fahrenheit := F; end; end.
{******************************************************************} { } { Borland Delphi Runtime Library } { Public Definitions of HID USAGES } { } { Portions created by Microsoft are } { Copyright (c) 1996, 1997 Microsoft Corporation } { All Rights Reserved. } { } { The original file is: hidusage.h, released March 1999. } { The original Pascal code is: HidUsage.pas, released 31 Jan 2000. } { The initial developer of the Pascal code is Robert Marquardt } { (robert_marquardt att gmx dott de) } { } { Portions created by Robert Marquardt are } { Copyright (c) 1999, 2000 Robert Marquardt. } { } { Contributor(s): Marcel van Brakel (brakelm att chello dott nl) } { Francois KREBS (fkrebs att free dott fr) } { } { Obtained through: } { Joint Endeavour of Delphi Innovators (Project JEDI) } { } { You may retrieve the latest version of this file at the Project } { JEDI home page, located at http://delphi-jedi.org } { } { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/NPL/NPL-1_1Final.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } { } {******************************************************************} unit HidUsage; interface {$WEAKPACKAGEUNIT} uses Windows; const // // Usage Pages // HID_USAGE_PAGE_UNDEFINED = $00; HID_USAGE_PAGE_GENERIC = $01; HID_USAGE_PAGE_SIMULATION = $02; HID_USAGE_PAGE_VR = $03; HID_USAGE_PAGE_SPORT = $04; HID_USAGE_PAGE_GAME = $05; HID_USAGE_PAGE_GENERIC_GAME_CONTROLS = $06; HID_USAGE_PAGE_KEYBOARD = $07; HID_USAGE_PAGE_LED = $08; HID_USAGE_PAGE_BUTTON = $09; HID_USAGE_PAGE_ORDINAL = $0A; HID_USAGE_PAGE_TELEPHONY = $0B; HID_USAGE_PAGE_CONSUMER = $0C; HID_USAGE_PAGE_DIGITIZER = $0D; HID_USAGE_PAGE_PHYSICAL_INPUT_DEVICE = $0F; HID_USAGE_PAGE_UNICODE = $10; HID_USAGE_PAGE_ALPHANUMERIC = $14; HID_USAGE_PAGE_MEDICAL_INSTRUMENT = $40; HID_USAGE_PAGE_USB_MONITOR = $80; HID_USAGE_PAGE_MONITOR_ENUMERATED_VALUES = $81; HID_USAGE_PAGE_VESA_VIRTUAL_CONTROLS = $82; HID_USAGE_PAGE_RESERVED = $83; HID_USAGE_PAGE_POWER_DEVICE = $84; HID_USAGE_PAGE_BATTERY_SYSTEM = $85; HID_USAGE_PAGE_BARCODE_SCANNER = $8C; HID_USAGE_PAGE_WEIGHING_DEVICE = $8D; HID_USAGE_PAGE_MAGNETIC_STRIPE_READER = $8E; // // Usages from Generic Desktop Page (0x01) // HID_USAGE_UNDEFINED = $00; HID_USAGE_GENERIC_POINTER = $01; HID_USAGE_GENERIC_MOUSE = $02; HID_USAGE_GENERIC_RESERVED1 = $03; HID_USAGE_GENERIC_JOYSTICK = $04; HID_USAGE_GENERIC_GAMEPAD = $05; HID_USAGE_GENERIC_KEYBOARD = $06; HID_USAGE_GENERIC_KEYPAD = $07; HID_USAGE_GENERIC_MULTIAXIS = $08; HID_USAGE_GENERIC_X = $30; HID_USAGE_GENERIC_Y = $31; HID_USAGE_GENERIC_Z = $32; HID_USAGE_GENERIC_RX = $33; HID_USAGE_GENERIC_RY = $34; HID_USAGE_GENERIC_RZ = $35; HID_USAGE_GENERIC_SLIDER = $36; HID_USAGE_GENERIC_DIAL = $37; HID_USAGE_GENERIC_WHEEL = $38; HID_USAGE_GENERIC_HATSWITCH = $39; HID_USAGE_GENERIC_COUNTED_BUFFER = $3A; HID_USAGE_GENERIC_BYTE_COUNT = $3B; HID_USAGE_GENERIC_MOTION_WAKEUP = $3C; HID_USAGE_GENERIC_START = $3D; HID_USAGE_GENERIC_SELECT = $3E; HID_USAGE_GENERIC_RESERVED2 = $3F; HID_USAGE_GENERIC_VX = $40; HID_USAGE_GENERIC_VY = $41; HID_USAGE_GENERIC_VZ = $42; HID_USAGE_GENERIC_VBRX = $43; HID_USAGE_GENERIC_VBRY = $44; HID_USAGE_GENERIC_VBRZ = $45; HID_USAGE_GENERIC_VNO = $46; HID_USAGE_FEATURE_NOTIFICATION = $47; HID_USAGE_GENERIC_SYSTEM_CTL = $80; HID_USAGE_GENERIC_SYSCTL_POWER = $81; HID_USAGE_GENERIC_SYSCTL_SLEEP = $82; HID_USAGE_GENERIC_SYSCTL_WAKE = $83; HID_USAGE_GENERIC_SYSCTL_CONTEXT_MENU = $84; HID_USAGE_GENERIC_SYSCTL_MAIN_MENU = $85; HID_USAGE_GENERIC_SYSCTL_APP_MENU = $86; HID_USAGE_GENERIC_SYSCTL_HELP_MENU = $87; HID_USAGE_GENERIC_SYSCTL_MENU_EXIT = $88; HID_USAGE_GENERIC_SYSCTL_MENU_SELECT = $89; HID_USAGE_GENERIC_SYSCTL_MENU_RIGHT = $8A; HID_USAGE_GENERIC_SYSCTL_MENU_LEFT = $8B; HID_USAGE_GENERIC_SYSCTL_MENU_UP = $8C; HID_USAGE_GENERIC_SYSCTL_MENU_DOWN = $8D; HID_USAGE_GENERIC_SYSCTL_COLD_RESTART = $8E; HID_USAGE_GENERIC_SYSCTL_WARM_RESTART = $8F; HID_USAGE_GENERIC_SYSCTL_DPAD_UP = $90; HID_USAGE_GENERIC_SYSCTL_DPAD_DOWN = $91; HID_USAGE_GENERIC_SYSCTL_DPAD_RIGHT = $92; HID_USAGE_GENERIC_SYSCTL_DPAD_LEFT = $93; HID_USAGE_GENERIC_SYSCTL_DOCK = $A0; HID_USAGE_GENERIC_SYSCTL_UNDOCK = $A1; HID_USAGE_GENERIC_SYSCTL_SETUP = $A2; HID_USAGE_GENERIC_SYSCTL_BREAK = $A3; HID_USAGE_GENERIC_SYSCTL_DEBUGGER_BREAK = $A4; HID_USAGE_GENERIC_SYSCTL_APP_BREAK = $A5; HID_USAGE_GENERIC_SYSCTL_APP_DEBUGGER_BREAK = $A6; HID_USAGE_GENERIC_SYSCTL_SYSTEM_SPEAKER_MUTE = $A7; HID_USAGE_GENERIC_SYSCTL_SYSTEM_HIBERNATE = $A8; HID_USAGE_GENERIC_SYSCTL_DISPLAY_INVERT = $B0; HID_USAGE_GENERIC_SYSCTL_DISPLAY_INTERNAL = $B1; HID_USAGE_GENERIC_SYSCTL_DISPLAY_EXTERNAL = $B2; HID_USAGE_GENERIC_SYSCTL_DISPLAY_BOTH = $B3; HID_USAGE_GENERIC_SYSCTL_DISPLAY_DUAL = $B4; HID_USAGE_GENERIC_SYSCTL_DISPLAY_TOGGLE_INT_EXT = $B5; HID_USAGE_GENERIC_SYSCTL_DISPLAY_SWAP = $B6; HID_USAGE_GENERIC_SYSCTL_DISPLAY_LCD_AUTOSCALE = $B7; // // Usages from Simulation Controls Page (0x02) // HID_USAGE_SIMULATION_UNDEFINED = $00; HID_USAGE_SIMULATION_FLIGHT = $01; HID_USAGE_SIMULATION_AUTOMOBILE = $02; HID_USAGE_SIMULATION_TANK = $03; HID_USAGE_SIMULATION_SPACESHIP = $04; HID_USAGE_SIMULATION_SUBMARINE = $05; HID_USAGE_SIMULATION_SAILING = $06; HID_USAGE_SIMULATION_MOTORCYCLE = $07; HID_USAGE_SIMULATION_SPORTS = $08; HID_USAGE_SIMULATION_AIRPLANE = $09; HID_USAGE_SIMULATION_HELICOPTER = $0A; HID_USAGE_SIMULATION_MAGIC_CARPET = $0B; HID_USAGE_SIMULATION_BICYCLE = $0C; HID_USAGE_SIMULATION_FLIGHT_CONTROL_STICK = $20; HID_USAGE_SIMULATION_FLIGHT_STICK = $21; HID_USAGE_SIMULATION_CYCLIC_CONTROL = $22; HID_USAGE_SIMULATION_CYCLIC_TRIM = $23; HID_USAGE_SIMULATION_FLIGHT_YOKE = $24; HID_USAGE_SIMULATION_TRACK_CONTROL = $25; HID_USAGE_SIMULATION_AILERON = $B0; HID_USAGE_SIMULATION_AILERON_TRIM = $B1; HID_USAGE_SIMULATION_ANTITORQUE_CONTROL = $B2; HID_USAGE_SIMULATION_AUTOPILOT_ENABLE = $B3; HID_USAGE_SIMULATION_CHAFF_RELEASE = $B4; HID_USAGE_SIMULATION_COLLECTIVE_CONTROL = $B5; HID_USAGE_SIMULATION_DIVE_BREAK = $B6; HID_USAGE_SIMULATION_ELECTRONIC_COUNTERMEASURES = $B7; HID_USAGE_SIMULATION_ELEVATOR = $B8; HID_USAGE_SIMULATION_ELEVATOR_TRIM = $B9; HID_USAGE_SIMULATION_RUDDER = $BA; HID_USAGE_SIMULATION_THROTTLE = $BB; HID_USAGE_SIMULATION_FLIGHT_COMMUNICATIONS = $BC; HID_USAGE_SIMULATION_FLARE_RELEASE = $BD; HID_USAGE_SIMULATION_LANDING_GEAR = $BE; HID_USAGE_SIMULATION_TOE_BRAKE = $BF; HID_USAGE_SIMULATION_TRIGGER = $C0; HID_USAGE_SIMULATION_WEAPONS_ARM = $C1; HID_USAGE_SIMULATION_WEAPONS_SELECT = $C2; HID_USAGE_SIMULATION_WING_FLAPS = $C3; HID_USAGE_SIMULATION_ACCELERATOR = $C4; HID_USAGE_SIMULATION_BRAKE = $C5; HID_USAGE_SIMULATION_CLUTCH = $C6; HID_USAGE_SIMULATION_SHIFTER = $C7; HID_USAGE_SIMULATION_STEERING = $C8; HID_USAGE_SIMULATION_TURRET_DIRECTION = $C9; HID_USAGE_SIMULATION_BARREL_ELEVATION = $CA; HID_USAGE_SIMULATION_DIVE_PLANE = $CB; HID_USAGE_SIMULATION_BALLAST = $CC; HID_USAGE_SIMULATION_BICYCLE_CRANK = $CD; HID_USAGE_SIMULATION_HANDLE_BARS = $CE; HID_USAGE_SIMULATION_FRONT_BRAKE = $CF; HID_USAGE_SIMULATION_REAR_BRAKE = $D0; // // Virtual Reality Controls Page (0x03) // HID_USAGE_VR_UNDEFINED = $00; HID_USAGE_VR_BELT = $01; HID_USAGE_VR_BODY_SUIT = $02; HID_USAGE_VR_FLEXOR = $03; HID_USAGE_VR_GLOVE = $04; HID_USAGE_VR_HEAD_TRACKER = $05; HID_USAGE_VR_HEAD_MOUNTED_DISPLAY = $06; HID_USAGE_VR_HAND_TRACKER = $07; HID_USAGE_VR_OCULOMETER = $08; HID_USAGE_VR_VEST = $09; HID_USAGE_VR_ANIMATRONIC_DEVICE = $0A; HID_USAGE_VR_STEREO_ENABLE = $20; HID_USAGE_VR_DISPLAY_ENABLE = $21; // // Sport Controls Page (0x04) // HID_USAGE_SPORT_UNDEFINED = $00; HID_USAGE_SPORT_BASEBALL_BAT = $01; HID_USAGE_SPORT_GOLF_CLUB = $02; HID_USAGE_SPORT_ROWING_MACHINE = $03; HID_USAGE_SPORT_TREADMILL = $04; HID_USAGE_SPORT_OAR = $30; HID_USAGE_SPORT_SLOPE = $31; HID_USAGE_SPORT_RATE = $32; HID_USAGE_SPORT_STICK_SPEED = $33; HID_USAGE_SPORT_STICK_FACE_ANGLE = $34; HID_USAGE_SPORT_STICK_HEEL_TOE = $35; HID_USAGE_SPORT_STICK_FOLLOW_THROUGH = $36; HID_USAGE_SPORT_STICK_TEMPO = $37; HID_USAGE_SPORT_STICK_TYPE = $38; HID_USAGE_SPORT_STICK_HEIGHT = $39; HID_USAGE_SPORT_PUTTER = $50; HID_USAGE_SPORT_IRON_1 = $51; HID_USAGE_SPORT_IRON_2 = $52; HID_USAGE_SPORT_IRON_3 = $53; HID_USAGE_SPORT_IRON_4 = $54; HID_USAGE_SPORT_IRON_5 = $55; HID_USAGE_SPORT_IRON_6 = $56; HID_USAGE_SPORT_IRON_7 = $57; HID_USAGE_SPORT_IRON_8 = $58; HID_USAGE_SPORT_IRON_9 = $59; HID_USAGE_SPORT_IRON_10 = $5A; HID_USAGE_SPORT_IRON_11 = $5B; HID_USAGE_SPORT_SAND_WEDGE = $5C; HID_USAGE_SPORT_LOFT_WEDGE = $5D; HID_USAGE_SPORT_POWER_WEDGE = $5E; HID_USAGE_SPORT_WOOD_1 = $5F; HID_USAGE_SPORT_WOOD_3 = $60; HID_USAGE_SPORT_WOOD_5 = $61; HID_USAGE_SPORT_WOOD_7 = $62; HID_USAGE_SPORT_WOOD_9 = $63; // // Game Controls Page (0x05) // HID_USAGE_GAME_UNDEFINED = $00; HID_USAGE_GAME_3D_GAME_CONTROLLER = $01; HID_USAGE_GAME_PINBALL_DEVICE = $02; HID_USAGE_GAME_GUN_DEVICE = $03; HID_USAGE_GAME_POINT_OF_VIEW = $20; HID_USAGE_GAME_TURN_RIGHT_LEFT = $21; HID_USAGE_GAME_PITCH_FORWARD_BACKWARD = $22; HID_USAGE_GAME_ROLL_RIGHT_LEFT = $23; HID_USAGE_GAME_MOVE_RIGHT_LEFT = $24; HID_USAGE_GAME_MOVE_FORWARD_BACKWARD = $25; HID_USAGE_GAME_MOVE_UP_DOWN = $26; HID_USAGE_GAME_LEAN_RIGHT_LEFT = $27; HID_USAGE_GAME_LEAN_FORWARD_BACKWARD = $28; HID_USAGE_GAME_HEIGHT_OF_POV = $29; HID_USAGE_GAME_FLIPPER = $2A; HID_USAGE_GAME_SECONDARY_FLIPPER = $2B; HID_USAGE_GAME_BUMP = $2C; HID_USAGE_GAME_NEW_GAME = $2D; HID_USAGE_GAME_SHOOT_BALL = $2E; HID_USAGE_GAME_PLAYER = $2F; HID_USAGE_GAME_GUN_BOLT = $30; HID_USAGE_GAME_GUN_CLIP = $31; HID_USAGE_GAME_GUN_SELECTOR = $32; HID_USAGE_GAME_GUN_SINGLE_SHOT = $33; HID_USAGE_GAME_GUN_BURST = $34; HID_USAGE_GAME_GUN_AUTOMATIC = $35; HID_USAGE_GAME_GUN_SAFETY = $36; HID_USAGE_GAME_GAMEPAD_FIRE_JUMP = $37; HID_USAGE_GAME_GAMEPAD_TRIGGER = $39; // // Generic Device Controls Page (0x06) // HID_USAGE_GENERIC_GAME_UNDEFINED = $00; HID_USAGE_GENERIC_GAME_BATTERY_STRENGTH = $20; HID_USAGE_GENERIC_GAME_WIRELESS_CHANNEL = $21; HID_USAGE_GENERIC_GAME_WIRELESS_ID = $22; // // Keyboard/Keypad Page (0x07) // // Error "keys" HID_USAGE_KEYBOARD_NOEVENT = $00; HID_USAGE_KEYBOARD_ROLLOVER = $01; HID_USAGE_KEYBOARD_POSTFAIL = $02; HID_USAGE_KEYBOARD_UNDEFINED = $03; // Letters HID_USAGE_KEYBOARD_aA = $04; HID_USAGE_KEYBOARD_bB = $05; HID_USAGE_KEYBOARD_cC = $06; HID_USAGE_KEYBOARD_dD = $07; HID_USAGE_KEYBOARD_eE = $08; HID_USAGE_KEYBOARD_fF = $09; HID_USAGE_KEYBOARD_gG = $0A; HID_USAGE_KEYBOARD_hH = $0B; HID_USAGE_KEYBOARD_iI = $0C; HID_USAGE_KEYBOARD_jJ = $0D; HID_USAGE_KEYBOARD_kK = $0E; HID_USAGE_KEYBOARD_lL = $0F; HID_USAGE_KEYBOARD_mM = $10; HID_USAGE_KEYBOARD_nN = $11; HID_USAGE_KEYBOARD_oO = $12; HID_USAGE_KEYBOARD_pP = $13; HID_USAGE_KEYBOARD_qQ = $14; HID_USAGE_KEYBOARD_rR = $15; HID_USAGE_KEYBOARD_sS = $16; HID_USAGE_KEYBOARD_tT = $17; HID_USAGE_KEYBOARD_uU = $18; HID_USAGE_KEYBOARD_vV = $19; HID_USAGE_KEYBOARD_wW = $1A; HID_USAGE_KEYBOARD_xX = $1B; HID_USAGE_KEYBOARD_yY = $1C; HID_USAGE_KEYBOARD_zZ = $1D; // Numbers HID_USAGE_KEYBOARD_ONE = $1E; // or ! HID_USAGE_KEYBOARD_TWO = $1F; // or @ HID_USAGE_KEYBOARD_THREE = $20; // or # HID_USAGE_KEYBOARD_FOUR = $21; // or $ HID_USAGE_KEYBOARD_FIVE = $22; // or % HID_USAGE_KEYBOARD_SIX = $23; // or ^ HID_USAGE_KEYBOARD_SEVEN = $24; // or & HID_USAGE_KEYBOARD_EIGHT = $25; // or * HID_USAGE_KEYBOARD_NINE = $26; // or ( HID_USAGE_KEYBOARD_ZERO = $27; // or ) HID_USAGE_KEYBOARD_ENTER = $28; // RETURN is another key HID_USAGE_KEYBOARD_ESCAPE = $29; HID_USAGE_KEYBOARD_BACKSPACE = $2A; // Delete left char HID_USAGE_KEYBOARD_TAB = $2B; HID_USAGE_KEYBOARD_SPACE = $2C; HID_USAGE_KEYBOARD_MINUS = $2D; // or _ HID_USAGE_KEYBOARD_EQUAL = $2E; // or + HID_USAGE_KEYBOARD_LSQBRACKET = $2F; // or { HID_USAGE_KEYBOARD_RSQBRACKET = $30; // or } HID_USAGE_KEYBOARD_BACKSLASH = $31; // or | HID_USAGE_KEYBOARD_HASHMARK2 = $32; // or ~ Non US Key HID_USAGE_KEYBOARD_SEMICOLON = $33; HID_USAGE_KEYBOARD_APOSTROPH = $34; // or : HID_USAGE_KEYBOARD_GRAVEACCENT = $35; // or Tilde HID_USAGE_KEYBOARD_COMMA = $36; // or < HID_USAGE_KEYBOARD_DOT = $37; // or > HID_USAGE_KEYBOARD_SLASH = $38; // or ? HID_USAGE_KEYBOARD_CAPS_LOCK = $39; // Function keys HID_USAGE_KEYBOARD_F1 = $3A; HID_USAGE_KEYBOARD_F2 = $3B; HID_USAGE_KEYBOARD_F3 = $3C; HID_USAGE_KEYBOARD_F4 = $3D; HID_USAGE_KEYBOARD_F5 = $3E; HID_USAGE_KEYBOARD_F6 = $3F; HID_USAGE_KEYBOARD_F7 = $40; HID_USAGE_KEYBOARD_F8 = $41; HID_USAGE_KEYBOARD_F9 = $42; HID_USAGE_KEYBOARD_F10 = $43; HID_USAGE_KEYBOARD_F11 = $44; HID_USAGE_KEYBOARD_F12 = $45; HID_USAGE_KEYBOARD_PRINT_SCREEN = $46; HID_USAGE_KEYBOARD_SCROLL_LOCK = $47; HID_USAGE_KEYBOARD_PAUSE = $48; HID_USAGE_KEYBOARD_INSERT = $49; HID_USAGE_KEYBOARD_HOME = $4A; HID_USAGE_KEYBOARD_PAGEUP = $4B; HID_USAGE_KEYBOARD_DELETE = $4C; HID_USAGE_KEYBOARD_END = $4D; HID_USAGE_KEYBOARD_PAGEDOWN = $4E; HID_USAGE_KEYBOARD_RIGHT = $4F; HID_USAGE_KEYBOARD_LEFT = $50; HID_USAGE_KEYBOARD_DOWN = $51; HID_USAGE_KEYBOARD_UP = $52; HID_USAGE_KEYPAD_NUM_LOCK = $53; HID_USAGE_KEYPAD_SLASH = $54; HID_USAGE_KEYPAD_STAR = $55; HID_USAGE_KEYPAD_MINUS = $56; HID_USAGE_KEYPAD_PLUS = $57; HID_USAGE_KEYPAD_ENTER = $58; HID_USAGE_KEYPAD_ONE = $59; HID_USAGE_KEYPAD_TWO = $5A; HID_USAGE_KEYPAD_THREE = $5B; HID_USAGE_KEYPAD_FOUR = $5C; HID_USAGE_KEYPAD_FIVE = $5D; HID_USAGE_KEYPAD_SIX = $5E; HID_USAGE_KEYPAD_SEVEN = $5F; HID_USAGE_KEYPAD_EIGHT = $60; HID_USAGE_KEYPAD_NINE = $61; HID_USAGE_KEYPAD_ZERO = $62; HID_USAGE_KEYPAD_DOT = $63; HID_USAGE_KEYBOARD_BACKSLASH2 = $64; // or | Non US key HID_USAGE_KEYBOARD_APPLICATION = $65; // Keys not for Windows HID_USAGE_KEYBOARD_POWER = $66; HID_USAGE_KEYPAD_EQUAL2 = $67; // Keys not for Windows HID_USAGE_KEYBOARD_F13 = $68; HID_USAGE_KEYBOARD_F14 = $69; HID_USAGE_KEYBOARD_F15 = $6A; HID_USAGE_KEYBOARD_F16 = $6B; HID_USAGE_KEYBOARD_F17 = $6C; HID_USAGE_KEYBOARD_F18 = $6D; HID_USAGE_KEYBOARD_F19 = $6E; HID_USAGE_KEYBOARD_F20 = $6F; HID_USAGE_KEYBOARD_F21 = $70; HID_USAGE_KEYBOARD_F22 = $71; HID_USAGE_KEYBOARD_F23 = $72; HID_USAGE_KEYBOARD_F24 = $73; HID_USAGE_KEYBOARD_EXECUTE = $74; HID_USAGE_KEYBOARD_HELP = $75; HID_USAGE_KEYBOARD_MENU = $76; HID_USAGE_KEYBOARD_SELECT = $77; HID_USAGE_KEYBOARD_STOP = $78; HID_USAGE_KEYBOARD_AGAIN = $79; HID_USAGE_KEYBOARD_UNDO = $7A; HID_USAGE_KEYBOARD_CUT = $7B; HID_USAGE_KEYBOARD_COPY = $7C; HID_USAGE_KEYBOARD_PASTE = $7D; HID_USAGE_KEYBOARD_FIND = $7E; HID_USAGE_KEYBOARD_MUTE = $7F; HID_USAGE_KEYBOARD_VOLUME_UP = $80; HID_USAGE_KEYBOARD_VOLUME_DOWN = $81; HID_USAGE_KEYBOARD_LOCKCAPS = $82; HID_USAGE_KEYBOARD_LOCKNUM = $83; HID_USAGE_KEYBOARD_LOCKSCROLL = $84; HID_USAGE_KEYPAD_COMMA = $85; HID_USAGE_KEYPAD_EQUALSIGN = $86; HID_USAGE_KEYBOARD_INATL1 = $87; HID_USAGE_KEYBOARD_INATL2 = $88; HID_USAGE_KEYBOARD_INATL3 = $89; HID_USAGE_KEYBOARD_INATL4 = $8A; HID_USAGE_KEYBOARD_INATL5 = $8B; HID_USAGE_KEYBOARD_INATL6 = $8C; HID_USAGE_KEYBOARD_INATL7 = $8D; HID_USAGE_KEYBOARD_INATL8 = $8E; HID_USAGE_KEYBOARD_INATL9 = $8F; HID_USAGE_KEYBOARD_LANG1 = $90; HID_USAGE_KEYBOARD_LANG2 = $91; HID_USAGE_KEYBOARD_LANG3 = $92; HID_USAGE_KEYBOARD_LANG4 = $93; HID_USAGE_KEYBOARD_LANG5 = $94; HID_USAGE_KEYBOARD_LANG6 = $95; HID_USAGE_KEYBOARD_LANG7 = $96; HID_USAGE_KEYBOARD_LANG8 = $97; HID_USAGE_KEYBOARD_LANG9 = $98; HID_USAGE_KEYBOARD_ALTERASE = $99; HID_USAGE_KEYBOARD_SYSREQ = $9A; HID_USAGE_KEYBOARD_CANCEL = $9B; HID_USAGE_KEYBOARD_CLEAR = $9C; HID_USAGE_KEYBOARD_PRIOR = $9D; HID_USAGE_KEYBOARD_RETURN = $9E; HID_USAGE_KEYBOARD_SEPARATOR = $9F; HID_USAGE_KEYBOARD_OUT = $A0; HID_USAGE_KEYBOARD_OPER = $A1; HID_USAGE_KEYBOARD_CLEAR_AGAIN = $A2; HID_USAGE_KEYBOARD_CRSEL = $A3; HID_USAGE_KEYBOARD_EXSEL = $A4; HID_USAGE_KEYPAD_HUNDREDS = $B0; HID_USAGE_KEYPAD_THOUSANDS = $B1; HID_USAGE_KEYPAD_THOUSANDS_SEP = $B2; HID_USAGE_KEYPAD_DECIMAL_SEP = $B3; HID_USAGE_KEYPAD_CURR_UNIT = $B4; HID_USAGE_KEYPAD_CURR_SUBUNIT = $B5; HID_USAGE_KEYPAD_LROUNDBRACKET = $B6; HID_USAGE_KEYPAD_RROUNDBRACKET = $B7; HID_USAGE_KEYPAD_LCURLYBRACKET = $B8; HID_USAGE_KEYPAD_RCURLYBRACKET = $B9; HID_USAGE_KEYPAD_TABULATOR = $BA; HID_USAGE_KEYPAD_BACKSPACE = $BB; HID_USAGE_KEYPAD_A = $BC; HID_USAGE_KEYPAD_B = $BD; HID_USAGE_KEYPAD_C = $BE; HID_USAGE_KEYPAD_D = $BF; HID_USAGE_KEYPAD_E = $C0; HID_USAGE_KEYPAD_F = $C1; HID_USAGE_KEYPAD_XOR = $C2; HID_USAGE_KEYPAD_CIRCUMFLEX = $C3; HID_USAGE_KEYPAD_PERCENT = $C4; HID_USAGE_KEYPAD_BIGGER_THAN = $C5; HID_USAGE_KEYPAD_LESS_THAN = $C6; HID_USAGE_KEYPAD_BINARY_AND = $C7; HID_USAGE_KEYPAD_LOGICAL_AND = $C8; HID_USAGE_KEYPAD_BINARY_OR = $C9; HID_USAGE_KEYPAD_LOGICAL_OR = $CA; HID_USAGE_KEYPAD_COLON = $CB; HID_USAGE_KEYPAD_HASHMARK = $CC; HID_USAGE_KEYPAD_SPACE = $CD; HID_USAGE_KEYPAD_AT = $CE; HID_USAGE_KEYPAD_EXCLAMATION = $CF; HID_USAGE_KEYPAD_MEM_STORE = $D0; HID_USAGE_KEYPAD_MEM_RECALL = $D1; HID_USAGE_KEYPAD_MEM_CLEAR = $D2; HID_USAGE_KEYPAD_MEM_ADD = $D3; HID_USAGE_KEYPAD_MEM_SUBTRACT = $D4; HID_USAGE_KEYPAD_MEM_MULTIPLY = $D5; HID_USAGE_KEYPAD_MEM_DIVIDE = $D6; HID_USAGE_KEYPAD_PLUS_MINUS = $D7; HID_USAGE_KEYPAD_CLEAR = $D8; HID_USAGE_KEYPAD_CLEAR_ENTRY = $D9; HID_USAGE_KEYPAD_BINARY = $DA; HID_USAGE_KEYPAD_OCTAL = $DB; HID_USAGE_KEYPAD_DECIMAL = $DC; HID_USAGE_KEYPAD_HEXADECIMAL = $DD; HID_USAGE_KEYPAD_RESERVED1 = $DE; HID_USAGE_KEYPAD_RESERVED2 = $DF; HID_USAGE_KEYBOARD_LCTRL = $E0; HID_USAGE_KEYBOARD_LSHFT = $E1; HID_USAGE_KEYBOARD_LALT = $E2; HID_USAGE_KEYBOARD_LGUI = $E3; HID_USAGE_KEYBOARD_RCTRL = $E4; HID_USAGE_KEYBOARD_RSHFT = $E5; HID_USAGE_KEYBOARD_RALT = $E6; HID_USAGE_KEYBOARD_RGUI = $E7; // and hundreds more... // (rom) $E8 to $FFFF are reserved in "USB HID Usage Tables 1.11" (Hut1_11.pdf) // // LED Page (0x08) // HID_USAGE_LED_UNDEFINED = $00; HID_USAGE_LED_NUM_LOCK = $01; HID_USAGE_LED_CAPS_LOCK = $02; HID_USAGE_LED_SCROLL_LOCK = $03; HID_USAGE_LED_COMPOSE = $04; HID_USAGE_LED_KANA = $05; HID_USAGE_LED_POWER = $06; HID_USAGE_LED_SHIFT = $07; HID_USAGE_LED_DO_NOT_DISTURB = $08; HID_USAGE_LED_MUTE = $09; HID_USAGE_LED_TONE_ENABLE = $0A; HID_USAGE_LED_HIGH_CUT_FILTER = $0B; HID_USAGE_LED_LOW_CUT_FILTER = $0C; HID_USAGE_LED_EQUALIZER_ENABLE = $0D; HID_USAGE_LED_SOUND_FIELD_ON = $0E; HID_USAGE_LED_SURROUND_FIELD_ON = $0F; HID_USAGE_LED_REPEAT = $10; HID_USAGE_LED_STEREO = $11; HID_USAGE_LED_SAMPLING_RATE_DETECT = $12; HID_USAGE_LED_SPINNING = $13; HID_USAGE_LED_CAV = $14; HID_USAGE_LED_CLV = $15; HID_USAGE_LED_RECORDING_FORMAT_DET = $16; HID_USAGE_LED_OFF_HOOK = $17; HID_USAGE_LED_RING = $18; HID_USAGE_LED_MESSAGE_WAITING = $19; HID_USAGE_LED_DATA_MODE = $1A; HID_USAGE_LED_BATTERY_OPERATION = $1B; HID_USAGE_LED_BATTERY_OK = $1C; HID_USAGE_LED_BATTERY_LOW = $1D; HID_USAGE_LED_SPEAKER = $1E; HID_USAGE_LED_HEAD_SET = $1F; HID_USAGE_LED_HOLD = $20; HID_USAGE_LED_MICROPHONE = $21; HID_USAGE_LED_COVERAGE = $22; HID_USAGE_LED_NIGHT_MODE = $23; HID_USAGE_LED_SEND_CALLS = $24; HID_USAGE_LED_CALL_PICKUP = $25; HID_USAGE_LED_CONFERENCE = $26; HID_USAGE_LED_STAND_BY = $27; HID_USAGE_LED_CAMERA_ON = $28; HID_USAGE_LED_CAMERA_OFF = $29; HID_USAGE_LED_ON_LINE = $2A; HID_USAGE_LED_OFF_LINE = $2B; HID_USAGE_LED_BUSY = $2C; HID_USAGE_LED_READY = $2D; HID_USAGE_LED_PAPER_OUT = $2E; HID_USAGE_LED_PAPER_JAM = $2F; HID_USAGE_LED_REMOTE = $30; HID_USAGE_LED_FORWARD = $31; HID_USAGE_LED_REVERSE = $32; HID_USAGE_LED_STOP = $33; HID_USAGE_LED_REWIND = $34; HID_USAGE_LED_FAST_FORWARD = $35; HID_USAGE_LED_PLAY = $36; HID_USAGE_LED_PAUSE = $37; HID_USAGE_LED_RECORD = $38; HID_USAGE_LED_ERROR = $39; HID_USAGE_LED_SELECTED_INDICATOR = $3A; HID_USAGE_LED_IN_USE_INDICATOR = $3B; HID_USAGE_LED_MULTI_MODE_INDICATOR = $3C; HID_USAGE_LED_INDICATOR_ON = $3D; HID_USAGE_LED_INDICATOR_FLASH = $3E; HID_USAGE_LED_INDICATOR_SLOW_BLINK = $3F; HID_USAGE_LED_INDICATOR_FAST_BLINK = $40; HID_USAGE_LED_INDICATOR_OFF = $41; HID_USAGE_LED_FLASH_ON_TIME = $42; HID_USAGE_LED_SLOW_BLINK_ON_TIME = $43; HID_USAGE_LED_SLOW_BLINK_OFF_TIME = $44; HID_USAGE_LED_FAST_BLINK_ON_TIME = $45; HID_USAGE_LED_FAST_BLINK_OFF_TIME = $46; HID_USAGE_LED_INDICATOR_COLOR = $47; HID_USAGE_LED_RED = $48; HID_USAGE_LED_GREEN = $49; HID_USAGE_LED_AMBER = $4A; HID_USAGE_LED_GENERIC_INDICATOR = $4B; HID_USAGE_LED_SYSTEM_SUSPEND = $4C; HID_USAGE_LED_EXTERNAL_POWER = $4D; // (rom) $4E to $FFFF are reserved in "USB HID Usage Tables 1.11" (Hut1_11.pdf) // // Button Page (0x09) // // There is no need to label these usages. // HID_USAGE_BUTTON_NO_BUTTON = $00; // (rom) Usage 1..65535 is the button number // // Ordinal Page (0x0A) // // There is no need to label these usages. // HID_USAGE_ORDINAL_RESERVED = $00; // (rom) Usage 1..65535 is the ordinal number // // Telephony Device Page (0x0B) // HID_USAGE_TELEPHONY_UNDEFINED = $00; HID_USAGE_TELEPHONY_PHONE = $01; HID_USAGE_TELEPHONY_ANSWERING_MACHINE = $02; HID_USAGE_TELEPHONY_MESSAGE_CONTROLS = $03; HID_USAGE_TELEPHONY_HANDSET = $04; HID_USAGE_TELEPHONY_HEADSET = $05; HID_USAGE_TELEPHONY_KEYPAD = $06; HID_USAGE_TELEPHONY_PROGRAMMABLE_BUTTON = $07; HID_USAGE_TELEPHONY_HOOK_SWITCH = $20; HID_USAGE_TELEPHONY_FLASH = $21; HID_USAGE_TELEPHONY_FEATURE = $22; HID_USAGE_TELEPHONY_HOLD = $23; HID_USAGE_TELEPHONY_REDIAL = $24; HID_USAGE_TELEPHONY_TRANSFER = $25; HID_USAGE_TELEPHONY_DROP = $26; HID_USAGE_TELEPHONY_PARK = $27; HID_USAGE_TELEPHONY_FORWARD_CALLS = $28; HID_USAGE_TELEPHONY_ALTERNATE_FUNCTION = $29; HID_USAGE_TELEPHONY_LINE = $2A; HID_USAGE_TELEPHONY_SPEAKER_PHONE = $2B; HID_USAGE_TELEPHONY_CONFERENCE = $2C; HID_USAGE_TELEPHONY_RING_ENABLE = $2D; HID_USAGE_TELEPHONY_RING_SELECT = $2E; HID_USAGE_TELEPHONY_PHONE_MUTE = $2F; HID_USAGE_TELEPHONY_CALLER_ID = $30; HID_USAGE_TELEPHONY_SEND = $31; HID_USAGE_TELEPHONY_SPEED_DIAL = $50; HID_USAGE_TELEPHONY_STORE_NUMBER = $51; HID_USAGE_TELEPHONY_RECALL_NUMBER = $52; HID_USAGE_TELEPHONY_PHONE_DIRECTORY = $53; HID_USAGE_TELEPHONY_VOICE_MAIL = $70; HID_USAGE_TELEPHONY_SCREEN_CALLS = $71; HID_USAGE_TELEPHONY_DO_NOT_DISTURB = $72; HID_USAGE_TELEPHONY_MESSAGE = $73; HID_USAGE_TELEPHONY_ANSWER_ON_OFF = $74; HID_USAGE_TELEPHONY_INSIDE_DIAL_TONE = $90; HID_USAGE_TELEPHONY_OUTSIDE_DIAL_TONE = $91; HID_USAGE_TELEPHONY_INSIDE_RING_TONE = $92; HID_USAGE_TELEPHONY_OUTSIDE_RING_TONE = $93; HID_USAGE_TELEPHONY_PRIORITY_RING_TONE = $94; HID_USAGE_TELEPHONY_INSIDE_RINGBACK = $95; HID_USAGE_TELEPHONY_PRIORITY_RINGBACK = $96; HID_USAGE_TELEPHONY_LINE_BUSY_TONE = $97; HID_USAGE_TELEPHONY_REORDER_TONE = $98; HID_USAGE_TELEPHONY_CALL_WAITING_TONE = $99; HID_USAGE_TELEPHONY_CONFIRMATION_TONE_1 = $9A; HID_USAGE_TELEPHONY_CONFIRMATION_TONE_2 = $9B; HID_USAGE_TELEPHONY_TONES_OFF = $9C; HID_USAGE_TELEPHONY_OUTSIDE_RINGBACK = $9D; HID_USAGE_TELEPHONY_RINGER = $9E; HID_USAGE_TELEPHONY_KEY_0 = $B0; HID_USAGE_TELEPHONY_KEY_1 = $B1; HID_USAGE_TELEPHONY_KEY_2 = $B2; HID_USAGE_TELEPHONY_KEY_3 = $B3; HID_USAGE_TELEPHONY_KEY_4 = $B4; HID_USAGE_TELEPHONY_KEY_5 = $B5; HID_USAGE_TELEPHONY_KEY_6 = $B6; HID_USAGE_TELEPHONY_KEY_7 = $B7; HID_USAGE_TELEPHONY_KEY_8 = $B8; HID_USAGE_TELEPHONY_KEY_9 = $B9; HID_USAGE_TELEPHONY_KEY_STAR = $BA; HID_USAGE_TELEPHONY_KEY_POUND = $BB; HID_USAGE_TELEPHONY_KEY_A = $BC; HID_USAGE_TELEPHONY_KEY_B = $BD; HID_USAGE_TELEPHONY_KEY_C = $BE; HID_USAGE_TELEPHONY_KEY_D = $BF; // (rom) $C0 to $FFFF are reserved in "USB HID Usage Tables 1.11" (Hut1_11.pdf) // // Consumer Page (0x0C) // HID_USAGE_CONSUMER_UNDEFINED = $000; HID_USAGE_CONSUMER_CONSUMER_CONTROL = $001; HID_USAGE_CONSUMER_NUMERIC_KEY_PAD = $002; HID_USAGE_CONSUMER_PROGRAMMABLE_BUTTONS = $003; HID_USAGE_CONSUMER_MICROPHONE = $004; HID_USAGE_CONSUMER_HEADPHONE = $005; HID_USAGE_CONSUMER_GRAPHIC_EQUALIZER = $006; HID_USAGE_CONSUMER_PLUS_10 = $020; HID_USAGE_CONSUMER_PLUS_100 = $021; HID_USAGE_CONSUMER_AM_PM = $022; HID_USAGE_CONSUMER_POWER = $030; HID_USAGE_CONSUMER_RESET = $031; HID_USAGE_CONSUMER_SLEEP = $032; HID_USAGE_CONSUMER_SLEEP_AFTER = $033; HID_USAGE_CONSUMER_SLEEP_MODE = $034; HID_USAGE_CONSUMER_ILLUMINATION = $035; HID_USAGE_CONSUMER_FUNCTION_BUTTONS = $036; HID_USAGE_CONSUMER_MENU = $040; HID_USAGE_CONSUMER_MENU_PICK = $041; HID_USAGE_CONSUMER_MENU_UP = $042; HID_USAGE_CONSUMER_MENU_DOWN = $043; HID_USAGE_CONSUMER_MENU_LEFT = $044; HID_USAGE_CONSUMER_MENU_RIGHT = $045; HID_USAGE_CONSUMER_MENU_ESCAPE = $046; HID_USAGE_CONSUMER_MENU_VALUE_INCREASE = $047; HID_USAGE_CONSUMER_MENU_VALUE_DECREASE = $048; HID_USAGE_CONSUMER_DATA_ON_SCREEN = $060; HID_USAGE_CONSUMER_CLOSED_CAPTION = $061; HID_USAGE_CONSUMER_CLOSED_CAPTION_SELECT = $062; HID_USAGE_CONSUMER_VCR_TV = $063; HID_USAGE_CONSUMER_BROADCAST_MODE = $064; HID_USAGE_CONSUMER_SNAPSHOT = $065; HID_USAGE_CONSUMER_STILL = $066; HID_USAGE_CONSUMER_SELECTION = $080; HID_USAGE_CONSUMER_ASSIGN_SELECTION = $081; HID_USAGE_CONSUMER_MODE_STEP = $082; HID_USAGE_CONSUMER_RECALL_LAST = $083; HID_USAGE_CONSUMER_ENTER_CHANNEL = $084; HID_USAGE_CONSUMER_ORDER_MOVIE = $085; HID_USAGE_CONSUMER_CHANNEL = $086; HID_USAGE_CONSUMER_MEDIA_SELECTION = $087; HID_USAGE_CONSUMER_MEDIA_SELECT_COMPUTER = $088; HID_USAGE_CONSUMER_MEDIA_SELECT_TV = $089; HID_USAGE_CONSUMER_MEDIA_SELECT_WWW = $08A; HID_USAGE_CONSUMER_MEDIA_SELECT_DVD = $08B; HID_USAGE_CONSUMER_MEDIA_SELECT_TELEPHONE = $08C; HID_USAGE_CONSUMER_MEDIA_SELECT_PROGRAM_GUIDE = $08D; HID_USAGE_CONSUMER_MEDIA_SELECT_VIDEO_PHONE = $08E; HID_USAGE_CONSUMER_MEDIA_SELECT_GAMES = $08F; HID_USAGE_CONSUMER_MEDIA_SELECT_MESSAGES = $090; HID_USAGE_CONSUMER_MEDIA_SELECT_CD = $091; HID_USAGE_CONSUMER_MEDIA_SELECT_VCR = $092; HID_USAGE_CONSUMER_MEDIA_SELECT_TUNER = $093; HID_USAGE_CONSUMER_QUIT = $094; HID_USAGE_CONSUMER_HELP = $095; HID_USAGE_CONSUMER_MEDIA_SELECT_TAPE = $096; HID_USAGE_CONSUMER_MEDIA_SELECT_CABLE = $097; HID_USAGE_CONSUMER_MEDIA_SELECT_SATELLITE = $098; HID_USAGE_CONSUMER_MEDIA_SELECT_SECURITY = $099; HID_USAGE_CONSUMER_MEDIA_SELECT_HOME = $09A; HID_USAGE_CONSUMER_MEDIA_SELECT_CALL = $09B; HID_USAGE_CONSUMER_CHANNEL_INCREMENT = $09C; HID_USAGE_CONSUMER_CHANNEL_DECREMENT = $09D; HID_USAGE_CONSUMER_MEDIA_SELECT_SAP = $09E; HID_USAGE_CONSUMER_RESERVED = $09F; HID_USAGE_CONSUMER_VCR_PLUS = $0A0; HID_USAGE_CONSUMER_ONCE = $0A1; HID_USAGE_CONSUMER_DAILY = $0A2; HID_USAGE_CONSUMER_WEEKLY = $0A3; HID_USAGE_CONSUMER_MONTHLY = $0A4; HID_USAGE_CONSUMER_PLAY = $0B0; HID_USAGE_CONSUMER_PAUSE = $0B1; HID_USAGE_CONSUMER_RECORD = $0B2; HID_USAGE_CONSUMER_FAST_FORWARD = $0B3; HID_USAGE_CONSUMER_REWIND = $0B4; HID_USAGE_CONSUMER_SCAN_NEXT_TRACK = $0B5; HID_USAGE_CONSUMER_SCAN_PREV_TRACK = $0B6; HID_USAGE_CONSUMER_STOP = $0B7; HID_USAGE_CONSUMER_EJECT = $0B8; HID_USAGE_CONSUMER_RANDOM_PLAY = $0B9; HID_USAGE_CONSUMER_SELECT_DISC = $0BA; HID_USAGE_CONSUMER_ENTER_DISC = $0BB; HID_USAGE_CONSUMER_REPEAT = $0BC; HID_USAGE_CONSUMER_TRACKING = $0BD; HID_USAGE_CONSUMER_TRACK_NORMAL = $0BE; HID_USAGE_CONSUMER_SLOW_TRACKING = $0BF; HID_USAGE_CONSUMER_FRAME_FORWARD = $0C0; HID_USAGE_CONSUMER_FRAME_BACK = $0C1; HID_USAGE_CONSUMER_MARK = $0C2; HID_USAGE_CONSUMER_CLEAR_MARK = $0C3; HID_USAGE_CONSUMER_REPEAT_FROM_MARK = $0C4; HID_USAGE_CONSUMER_RETURN_TO_MARK = $0C5; HID_USAGE_CONSUMER_SEARCH_MARK_FORWARD = $0C6; HID_USAGE_CONSUMER_SEARCK_MARK_BACKWARDS = $0C7; HID_USAGE_CONSUMER_COUNTER_RESET = $0C8; HID_USAGE_CONSUMER_SHOW_COUNTER = $0C9; HID_USAGE_CONSUMER_TRACKING_INCREMENT = $0CA; HID_USAGE_CONSUMER_TRACKING_DECREMENT = $0CB; HID_USAGE_CONSUMER_STOP_EJECT = $0CC; HID_USAGE_CONSUMER_PLAY_PAUSE = $0CD; HID_USAGE_CONSUMER_PLAY_SKIP = $0CE; HID_USAGE_CONSUMER_VOLUME = $0E0; HID_USAGE_CONSUMER_BALANCE = $0E1; HID_USAGE_CONSUMER_MUTE = $0E2; HID_USAGE_CONSUMER_BASS = $0E3; HID_USAGE_CONSUMER_TREBLE = $0E4; HID_USAGE_CONSUMER_BASS_BOOST = $0E5; HID_USAGE_CONSUMER_SURROUND_MODE = $0E6; HID_USAGE_CONSUMER_LOUDNESS = $0E7; HID_USAGE_CONSUMER_MPX = $0E8; HID_USAGE_CONSUMER_VOLUME_INCREMENT = $0E9; HID_USAGE_CONSUMER_VOLUME_DECREMENT = $0EA; HID_USAGE_CONSUMER_SPEED_SELECT = $0F0; HID_USAGE_CONSUMER_PLAYBACK_SPEED = $0F1; HID_USAGE_CONSUMER_STANDARD_PLAY = $0F2; HID_USAGE_CONSUMER_LONG_PLAY = $0F3; HID_USAGE_CONSUMER_EXTENDED_PLAY = $0F4; HID_USAGE_CONSUMER_SLOW = $0F5; HID_USAGE_CONSUMER_FAN_ENABLE = $100; HID_USAGE_CONSUMER_FAN_SPEED = $101; HID_USAGE_CONSUMER_LIGHT_ENABLE = $102; HID_USAGE_CONSUMER_LIGHT_ILLUMINATION_LEVEL = $103; HID_USAGE_CONSUMER_CLIMATE_CONTROL_ENABLE = $104; HID_USAGE_CONSUMER_ROOM_TEMPERATURE = $105; HID_USAGE_CONSUMER_SECURITY_ENABLE = $106; HID_USAGE_CONSUMER_FIRE_ALARM = $107; HID_USAGE_CONSUMER_POLICE_ALARM = $108; HID_USAGE_CONSUMER_PROXIMITY = $109; HID_USAGE_CONSUMER_MOTION = $10A; HID_USAGE_CONSUMER_DURESS_ALARM = $10B; HID_USAGE_CONSUMER_HOLDUP_ALARM = $10C; HID_USAGE_CONSUMER_MEDICAL_ALARM = $10D; HID_USAGE_CONSUMER_BALANCE_RIGHT = $150; HID_USAGE_CONSUMER_BALANCE_LEFT = $151; HID_USAGE_CONSUMER_BASS_INCREMENT = $152; HID_USAGE_CONSUMER_BASS_DECREMENT = $153; HID_USAGE_CONSUMER_TREBLE_INCREMENT = $154; HID_USAGE_CONSUMER_TREBLE_DECREMENT = $155; HID_USAGE_CONSUMER_SPEAKER_SYSTEM = $160; HID_USAGE_CONSUMER_CHANNEL_LEFT = $161; HID_USAGE_CONSUMER_CHANNEL_RIGHT = $162; HID_USAGE_CONSUMER_CHANNEL_CENTER = $163; HID_USAGE_CONSUMER_CHANNEL_FRONT = $164; HID_USAGE_CONSUMER_CHANNEL_CENTER_FRONT = $165; HID_USAGE_CONSUMER_CHANNEL_SIDE = $166; HID_USAGE_CONSUMER_CHANNEL_SURROUND = $167; HID_USAGE_CONSUMER_CHANNEL_LOW_FREQ_ENH = $168; HID_USAGE_CONSUMER_CHANNEL_TOP = $169; HID_USAGE_CONSUMER_CHANNEL_UNKNOWN = $16A; HID_USAGE_CONSUMER_SUB_CHANNEL = $170; HID_USAGE_CONSUMER_SUB_CHANNEL_INCREMENT = $171; HID_USAGE_CONSUMER_SUB_CHANNEL_DECREMENT = $172; HID_USAGE_CONSUMER_ALTERNATE_AUDIO_INCREMENT = $173; HID_USAGE_CONSUMER_ALTERNATE_AUDIO_DECREMENT = $174; HID_USAGE_CONSUMER_APP_LAUNCH_BUTTONS = $180; HID_USAGE_CONSUMER_AL_LAUNCH_BUTTON_CONFIG_TOOL = $181; HID_USAGE_CONSUMER_AL_PROG_BUTTON_CONFIG = $182; HID_USAGE_CONSUMER_AL_CONSUMER_CONTROL_CONFIG = $183; HID_USAGE_CONSUMER_AL_WORD_PROCESSOR = $184; HID_USAGE_CONSUMER_AL_TEXT_EDITOR = $185; HID_USAGE_CONSUMER_AL_SPREADSHEET = $186; HID_USAGE_CONSUMER_AL_GRAPHICS_EDITOR = $187; HID_USAGE_CONSUMER_AL_PRESENTATION_APP = $188; HID_USAGE_CONSUMER_AL_DATABASE_APP = $189; HID_USAGE_CONSUMER_AL_EMAIL_READER = $18A; HID_USAGE_CONSUMER_AL_NEWSREADER = $18B; HID_USAGE_CONSUMER_AL_VOICEMAIL = $18C; HID_USAGE_CONSUMER_AL_CONTACTS_ADDESSBOOK = $18D; HID_USAGE_CONSUMER_AL_CALENDAR_SCHEDULE = $18E; HID_USAGE_CONSUMER_AL_TASK_PROJECT_MANAGER = $18F; HID_USAGE_CONSUMER_AL_LOG_JOURNAL_TIMECARD = $190; HID_USAGE_CONSUMER_AL_CHECKBOOK_FINANCE = $191; HID_USAGE_CONSUMER_AL_CALCULATOR = $192; HID_USAGE_CONSUMER_AL_AV_CAPTURE_PLAYBACK = $193; HID_USAGE_CONSUMER_AL_LOCAL_MACHINE_BROWSER = $194; HID_USAGE_CONSUMER_AL_LAN_WAN_BROWSER = $195; HID_USAGE_CONSUMER_AL_INTERNET_BROWSER = $196; HID_USAGE_CONSUMER_AL_REMOTE_NETWORKING_ISP_CONNECT = $197; HID_USAGE_CONSUMER_AL_NETWORK_CONFERENCE = $198; HID_USAGE_CONSUMER_AL_NETWORK_CHAT = $199; HID_USAGE_CONSUMER_AL_TELEPHONY_DIALER = $19A; HID_USAGE_CONSUMER_AL_LOGON = $19B; HID_USAGE_CONSUMER_AL_LOGOFF = $19C; HID_USAGE_CONSUMER_AL_LOGON_LOGOFF = $19D; HID_USAGE_CONSUMER_AL_TERMINAL_LOCK_SCREENSAVER = $19E; HID_USAGE_CONSUMER_AL_CONTROL_PANEL = $19F; HID_USAGE_CONSUMER_AL_COMMAND_LINE_PROCESSOR_RUN = $1A0; HID_USAGE_CONSUMER_AL_PROCESS_TASK_MANAGER = $1A1; HID_USAGE_CONSUMER_AL_SELECT_TASK_APP = $1A2; HID_USAGE_CONSUMER_AL_NEXT_TASK_APP = $1A3; HID_USAGE_CONSUMER_AL_PREV_TASK_APP = $1A4; HID_USAGE_CONSUMER_AL_PREEMPTIVE_HALT_TASK_APP = $1A5; HID_USAGE_CONSUMER_AL_INTEGRATED_HELP_CENTER = $1A6; HID_USAGE_CONSUMER_AL_DOCUMENTS = $1A7; HID_USAGE_CONSUMER_AL_THESAURUS = $1A8; HID_USAGE_CONSUMER_AL_DICTIONARY = $1A9; HID_USAGE_CONSUMER_AL_DESKTOP = $1AA; HID_USAGE_CONSUMER_AL_SPELL_CHECK = $1AB; HID_USAGE_CONSUMER_AL_GRAMMAR_CHECK = $1AC; HID_USAGE_CONSUMER_AL_WIRELESS_STATUS = $1AD; HID_USAGE_CONSUMER_AL_KEYBOARD_LAYOUT = $1AE; HID_USAGE_CONSUMER_AL_VIRUS_PROTECTION = $1AF; HID_USAGE_CONSUMER_AL_ENCRYPTION = $1B0; HID_USAGE_CONSUMER_AL_SCREENSAVER = $1B1; HID_USAGE_CONSUMER_AL_ALARMS = $1B2; HID_USAGE_CONSUMER_AL_CLOCK = $1B3; HID_USAGE_CONSUMER_AL_FILE_BROWSER = $1B4; HID_USAGE_CONSUMER_AL_POWER_STATUS = $1B5; HID_USAGE_CONSUMER_GENERIC_GUI_APP_CONTROLS = $200; HID_USAGE_CONSUMER_AC_NEW = $201; HID_USAGE_CONSUMER_AC_OPEN = $202; HID_USAGE_CONSUMER_AC_CLOSE = $203; HID_USAGE_CONSUMER_AC_EXIT = $204; HID_USAGE_CONSUMER_AC_MAXIMIZE = $205; HID_USAGE_CONSUMER_AC_MINIMIZE = $206; HID_USAGE_CONSUMER_AC_SAVE = $207; HID_USAGE_CONSUMER_AC_PRINT = $208; HID_USAGE_CONSUMER_AC_PROPERTIES = $209; HID_USAGE_CONSUMER_AC_UNDO = $21A; HID_USAGE_CONSUMER_AC_COPY = $21B; HID_USAGE_CONSUMER_AC_CUT = $21C; HID_USAGE_CONSUMER_AC_PASTE = $21D; HID_USAGE_CONSUMER_AC_SELECT_ALL = $21E; HID_USAGE_CONSUMER_AC_FIND = $21F; HID_USAGE_CONSUMER_AC_FIND_AND_REPLACE = $220; HID_USAGE_CONSUMER_AC_SEARCH = $221; HID_USAGE_CONSUMER_AC_GO_TO = $222; HID_USAGE_CONSUMER_AC_HOME = $223; HID_USAGE_CONSUMER_AC_BACK = $224; HID_USAGE_CONSUMER_AC_FORWARD = $225; HID_USAGE_CONSUMER_AC_STOP = $226; HID_USAGE_CONSUMER_AC_REFRESH = $227; HID_USAGE_CONSUMER_AC_PREV_LINK = $228; HID_USAGE_CONSUMER_AC_NEXT_LINK = $229; HID_USAGE_CONSUMER_AC_BOOKMARKS = $22A; HID_USAGE_CONSUMER_AC_HISTORY = $22B; HID_USAGE_CONSUMER_AC_SUBSCRIPTIONS = $22C; HID_USAGE_CONSUMER_AC_ZOOM_IN = $22D; HID_USAGE_CONSUMER_AC_ZOOM_OUT = $22E; HID_USAGE_CONSUMER_AC_ZOOM = $22F; HID_USAGE_CONSUMER_AC_FULL_SCREEN_VIEW = $230; HID_USAGE_CONSUMER_AC_NORMAL_VIEW = $231; HID_USAGE_CONSUMER_AC_VIEW_TOGGLE = $232; HID_USAGE_CONSUMER_AC_SCROLL_UP = $233; HID_USAGE_CONSUMER_AC_SCROLL_DOWN = $234; HID_USAGE_CONSUMER_AC_SCROLL = $235; HID_USAGE_CONSUMER_AC_PAN_LEFT = $236; HID_USAGE_CONSUMER_AC_PAN_RIGHT = $237; HID_USAGE_CONSUMER_AC_PAN = $238; HID_USAGE_CONSUMER_AC_NEW_WINDOW = $239; HID_USAGE_CONSUMER_AC_TILE_HORIZONTALLY = $23A; HID_USAGE_CONSUMER_AC_TILE_VERTICALLY = $23B; HID_USAGE_CONSUMER_AC_FORMAT = $23C; HID_USAGE_CONSUMER_AC_EDIT = $23D; HID_USAGE_CONSUMER_AC_BOLD = $23E; HID_USAGE_CONSUMER_AC_ITALICS = $23F; HID_USAGE_CONSUMER_AC_UNDERLINE = $240; HID_USAGE_CONSUMER_AC_STRIKETHROUGH = $241; HID_USAGE_CONSUMER_AC_SUBSCRIPT = $242; HID_USAGE_CONSUMER_AC_SUPERSCRIPT = $243; HID_USAGE_CONSUMER_AC_ALL_CAPS = $244; HID_USAGE_CONSUMER_AC_ROTATE = $245; HID_USAGE_CONSUMER_AC_RESIZE = $246; HID_USAGE_CONSUMER_AC_FLIP_HORIZONTAL = $247; HID_USAGE_CONSUMER_AC_FLIP_VERTICAL = $248; HID_USAGE_CONSUMER_AC_MIRROR_HORIZONTAL = $249; HID_USAGE_CONSUMER_AC_MIRROR_VERTICAL = $24A; HID_USAGE_CONSUMER_AC_FONT_SELECT = $24B; HID_USAGE_CONSUMER_AC_FONT_COLOR = $24C; HID_USAGE_CONSUMER_AC_FONT_SIZE = $24D; HID_USAGE_CONSUMER_AC_JUSTIFY_LEFT = $24E; HID_USAGE_CONSUMER_AC_JUSTIFY_CENTER_H = $24F; HID_USAGE_CONSUMER_AC_JUSTIFY_RIGHT = $250; HID_USAGE_CONSUMER_AC_JUSTIFY_BLOCK_H = $251; HID_USAGE_CONSUMER_AC_JUSTIFY_TOP = $252; HID_USAGE_CONSUMER_AC_JUSTIFY_CENTER_V = $253; HID_USAGE_CONSUMER_AC_JUSTIFY_BOTTOM = $254; HID_USAGE_CONSUMER_AC_JUSTIFY_BLOCK_V = $255; HID_USAGE_CONSUMER_AC_INDENT_DECREASE = $256; HID_USAGE_CONSUMER_AC_INDENT_INCREASE = $257; HID_USAGE_CONSUMER_AC_NUMBERED_LIST = $258; HID_USAGE_CONSUMER_AC_RESTART_NUMBERING = $259; HID_USAGE_CONSUMER_AC_BULLETED_LIST = $25A; HID_USAGE_CONSUMER_AC_PROMOTE = $25B; HID_USAGE_CONSUMER_AC_DEMOTE = $25C; HID_USAGE_CONSUMER_AC_YES = $25D; HID_USAGE_CONSUMER_AC_NO = $25E; HID_USAGE_CONSUMER_AC_CANCEL = $25F; HID_USAGE_CONSUMER_AC_CATALOG = $260; HID_USAGE_CONSUMER_AC_BUY_CHECKOUT = $261; HID_USAGE_CONSUMER_AC_ADD_TO_CART = $262; HID_USAGE_CONSUMER_AC_EXPAND = $263; HID_USAGE_CONSUMER_AC_EXPAND_ALL = $264; HID_USAGE_CONSUMER_AC_COLLAPSE = $265; HID_USAGE_CONSUMER_AC_COLLAPSE_ALL = $266; HID_USAGE_CONSUMER_AC_PRINT_PREVIEW = $267; HID_USAGE_CONSUMER_AC_PASTE_SPECIAL = $268; HID_USAGE_CONSUMER_AC_INSERT_MODE = $269; HID_USAGE_CONSUMER_AC_DELETE = $26A; HID_USAGE_CONSUMER_AC_LOCK = $26B; HID_USAGE_CONSUMER_AC_UNLOCK = $26C; HID_USAGE_CONSUMER_AC_PROTECT = $26D; HID_USAGE_CONSUMER_AC_UNPROTECT = $26E; HID_USAGE_CONSUMER_AC_ATTACH_COMMENT = $26F; HID_USAGE_CONSUMER_AC_DELETE_COMMENT = $270; HID_USAGE_CONSUMER_AC_VIEW_COMMENT = $271; HID_USAGE_CONSUMER_AC_SELECT_WORD = $272; HID_USAGE_CONSUMER_AC_SELECT_SENTENCE = $273; HID_USAGE_CONSUMER_AC_SELECT_PARAGRAPH = $274; HID_USAGE_CONSUMER_AC_SELECT_COLUMN = $275; HID_USAGE_CONSUMER_AC_SELECT_ROW = $276; HID_USAGE_CONSUMER_AC_SELECT_TABLE = $277; HID_USAGE_CONSUMER_AC_SELECT_OBJECT = $278; HID_USAGE_CONSUMER_AC_REDO_REPEAT = $279; HID_USAGE_CONSUMER_AC_SORT = $27A; HID_USAGE_CONSUMER_AC_SORT_ASCENDING = $27B; HID_USAGE_CONSUMER_AC_SORT_DESCENDING = $27C; HID_USAGE_CONSUMER_AC_FILTER = $27D; HID_USAGE_CONSUMER_AC_SET_CLOCK = $27E; HID_USAGE_CONSUMER_AC_VIEW_CLOCK = $27F; HID_USAGE_CONSUMER_AC_SELECT_TIME_ZONE = $280; HID_USAGE_CONSUMER_AC_EDIT_TIME_ZONES = $281; HID_USAGE_CONSUMER_AC_SET_ALARM = $282; HID_USAGE_CONSUMER_AC_CLEAR_ALARM = $283; HID_USAGE_CONSUMER_AC_SNOOZE_ALARM = $284; HID_USAGE_CONSUMER_AC_RESET_ALARM = $285; HID_USAGE_CONSUMER_AC_SYNCHRONIZE = $286; HID_USAGE_CONSUMER_AC_SEND_RECEIVE = $287; HID_USAGE_CONSUMER_AC_SEND_TO = $288; HID_USAGE_CONSUMER_AC_REPLY = $289; HID_USAGE_CONSUMER_AC_REPLY_ALL = $28A; HID_USAGE_CONSUMER_AC_FORWARD_MSG = $28B; HID_USAGE_CONSUMER_AC_SEND = $28C; HID_USAGE_CONSUMER_AC_ATTACH_FILE = $28D; HID_USAGE_CONSUMER_AC_UPLOAD = $28E; HID_USAGE_CONSUMER_AC_DOWNLOAD = $28F; HID_USAGE_CONSUMER_AC_SET_BORDERS = $290; HID_USAGE_CONSUMER_AC_INSERT_ROW = $291; HID_USAGE_CONSUMER_AC_INSERT_COLUMN = $292; HID_USAGE_CONSUMER_AC_INSERT_FILE = $293; HID_USAGE_CONSUMER_AC_INSERT_PICTURE = $294; HID_USAGE_CONSUMER_AC_INSERT_OBJECT = $295; HID_USAGE_CONSUMER_AC_INSERT_SYMBOL = $296; HID_USAGE_CONSUMER_AC_SAVE_AND_CLOSE = $297; HID_USAGE_CONSUMER_AC_RENAME = $298; HID_USAGE_CONSUMER_AC_MERGE = $299; HID_USAGE_CONSUMER_AC_SPLIT = $29A; HID_USAGE_CONSUMER_AC_DISTRIBUTE_HORIZONTALLY = $29B; HID_USAGE_CONSUMER_AC_DISTRIBUTE_VERTICALLY = $29C; // (rom) $29D to $FFFF are reserved in "USB HID Usage Tables 1.11" (Hut1_11.pdf) // // Digitizer Page (0x0D) // HID_USAGE_DIGITIZER_UNDEFINED = $00; HID_USAGE_DIGITIZER_DIGITIZER = $01; HID_USAGE_DIGITIZER_PEN = $02; HID_USAGE_DIGITIZER_LIGHT_PEN = $03; HID_USAGE_DIGITIZER_TOUCH_SCREEN = $04; HID_USAGE_DIGITIZER_TOUCH_PAD = $05; HID_USAGE_DIGITIZER_WHITE_BOARD = $06; HID_USAGE_DIGITIZER_COORDINATE_MEASURING_MACHINE = $07; HID_USAGE_DIGITIZER_3D_DIGITIZER = $08; HID_USAGE_DIGITIZER_STEREO_PLOTTER = $09; HID_USAGE_DIGITIZER_ARTICULATED_ARM = $0A; HID_USAGE_DIGITIZER_ARMATURE = $0B; HID_USAGE_DIGITIZER_MULTIPLE_POINT_DIGITIZER = $0C; HID_USAGE_DIGITIZER_FREE_SPACE_WAND = $0D; HID_USAGE_DIGITIZER_STYLUS = $20; HID_USAGE_DIGITIZER_PUCK = $21; HID_USAGE_DIGITIZER_FINGER = $22; HID_USAGE_DIGITIZER_TIP_PRESSURE = $30; HID_USAGE_DIGITIZER_BARREL_PRESSURE = $31; HID_USAGE_DIGITIZER_IN_RANGE = $32; HID_USAGE_DIGITIZER_TOUCH = $33; HID_USAGE_DIGITIZER_UNTOUCH = $34; HID_USAGE_DIGITIZER_TAP = $35; HID_USAGE_DIGITIZER_QUALITY = $36; HID_USAGE_DIGITIZER_DATA_VALID = $37; HID_USAGE_DIGITIZER_TRANSDUCER_INDEX = $38; HID_USAGE_DIGITIZER_TABLET_FUNCTION_KEYS = $39; HID_USAGE_DIGITIZER_PROGRAM_CHANGE_KEYS = $3A; HID_USAGE_DIGITIZER_BATTERY_STRENGTH = $3B; HID_USAGE_DIGITIZER_INVERT = $3C; HID_USAGE_DIGITIZER_X_TILT = $3D; HID_USAGE_DIGITIZER_Y_TILT = $3E; HID_USAGE_DIGITIZER_AZIMUTH = $3F; HID_USAGE_DIGITIZER_ALTITUDE = $40; HID_USAGE_DIGITIZER_TWIST = $41; HID_USAGE_DIGITIZER_TIP_SWITCH = $42; HID_USAGE_DIGITIZER_SECONDARY_TIP_SWITCH = $43; HID_USAGE_DIGITIZER_BARREL_SWITCH = $44; HID_USAGE_DIGITIZER_ERASER = $45; HID_USAGE_DIGITIZER_TABLET_PICK = $46; // (rom) $47 to $FFFF are reserved in "USB HID Usage Tables 1.11" (Hut1_11.pdf) // // Physical Input Page (0x0F) // HID_USAGE_PID_UNDEFINED = $00; HID_USAGE_PID_PHYSICAL_INTERFACE_DEVICE = $01; HID_USAGE_PID_NORMAL = $20; HID_USAGE_PID_SET_EFFECT_REPORT = $21; HID_USAGE_PID_EFFECT_BLOCK_INDEX = $22; HID_USAGE_PID_PARAMETER_BLOCK_OFFSET = $23; HID_USAGE_PID_ROM_FLAG = $24; HID_USAGE_PID_EFFECT_TYPE = $25; HID_USAGE_PID_ET_CONSTANT_FORCE = $26; HID_USAGE_PID_ET_RAMP = $27; HID_USAGE_PID_ET_CUSTOM_FORCE_DATA = $28; HID_USAGE_PID_ET_SQUARE = $30; HID_USAGE_PID_ET_SINE = $31; HID_USAGE_PID_ET_TRIANGLE = $32; HID_USAGE_PID_ET_SAWTOOTH_UP = $33; HID_USAGE_PID_ET_SAWTOOTH_DOWN = $34; HID_USAGE_PID_ET_SPRING = $40; HID_USAGE_PID_ET_DAMPER = $41; HID_USAGE_PID_ET_INERTIA = $42; HID_USAGE_PID_ET_FRICTION = $43; HID_USAGE_PID_DURATION = $50; HID_USAGE_PID_SAMPLE_PERIOD = $51; HID_USAGE_PID_GAIN = $52; HID_USAGE_PID_TRIGGER_BUTTON = $53; HID_USAGE_PID_TRIGGER_REPEAT_INTERVAL = $54; HID_USAGE_PID_AXES_ENABLE = $55; HID_USAGE_PID_DIRECTION_ENABLE = $56; HID_USAGE_PID_DIRECTION = $57; HID_USAGE_PID_TYPE_SPECIFIC_BLOCK_OFFSET = $58; HID_USAGE_PID_BLOCK_TYPE = $59; HID_USAGE_PID_SET_ENVELOPE_REPORT = $5A; HID_USAGE_PID_ATTACK_LEVEL = $5B; HID_USAGE_PID_ATTACK_TIME = $5C; HID_USAGE_PID_FADE_LEVEL = $5D; HID_USAGE_PID_FADE_TIME = $5E; HID_USAGE_PID_SET_CONDITION_REPORT = $5F; HID_USAGE_PID_CP_OFFSET = $60; HID_USAGE_PID_POSITIVE_COEFFICIENT = $61; HID_USAGE_PID_NEGATIVE_COEFFICIENT = $62; HID_USAGE_PID_POSITIVE_SATURATION = $63; HID_USAGE_PID_NEGATIVE_SATURATION = $64; HID_USAGE_PID_DEAD_BAND = $65; HID_USAGE_PID_DOWNLOAD_FORCE_SAMPLE = $66; HID_USAGE_PID_ISOCH_CUSTOM_FORCE_ENABLE = $67; HID_USAGE_PID_CUSTOM_FORCE_DATA_REPORT = $68; HID_USAGE_PID_CUSTOM_FORCE_DATA = $69; HID_USAGE_PID_CUSTOM_FORCE_VENDOR_DEFINED_DATA = $6A; HID_USAGE_PID_SET_CUSTOM_FORCE_REPORT = $6B; HID_USAGE_PID_CUSTOM_FORCE_DATA_OFFSET = $6C; HID_USAGE_PID_SAMPLE_COUNT = $6D; HID_USAGE_PID_SET_PERIODIC_REPORT = $6E; HID_USAGE_PID_OFFSET = $6F; HID_USAGE_PID_MAGNITUDE = $70; HID_USAGE_PID_PHASE = $71; HID_USAGE_PID_PERIOD = $72; HID_USAGE_PID_SET_CONSTANT_FORCE_REPORT = $73; HID_USAGE_PID_SET_RAMP_FORCE_REPORT = $74; HID_USAGE_PID_RAMP_START = $75; HID_USAGE_PID_RAMP_END = $76; HID_USAGE_PID_EFFECT_OPERATION_REPORT = $77; HID_USAGE_PID_EFFECT_OPERATION = $78; HID_USAGE_PID_OP_EFFECT_START = $79; HID_USAGE_PID_OP_EFFECT_START_SOLO = $7A; HID_USAGE_PID_OP_EFFECT_STOP = $7B; HID_USAGE_PID_LOOP_COUNT = $7C; HID_USAGE_PID_DEVICE_GAIN_REPORT = $7D; HID_USAGE_PID_DEVICE_GAIN = $7E; HID_USAGE_PID_PID_POOL_REPORT = $7F; HID_USAGE_PID_RAM_POOL_SIZE = $80; HID_USAGE_PID_ROM_POOL_SIZE = $81; HID_USAGE_PID_ROM_EFFECT_BLOCK_COUNT = $82; HID_USAGE_PID_SIMULTANEOUS_EFFECTS_MAX = $83; HID_USAGE_PID_POOL_ALIGNMENT = $84; HID_USAGE_PID_PID_POOL_MOVE_REPORT = $85; HID_USAGE_PID_MOVE_SOURCE = $86; HID_USAGE_PID_MOVE_DESTINATION = $87; HID_USAGE_PID_MOVE_LENGTH = $88; HID_USAGE_PID_PID_BLOCK_LOAD_REPORT = $89; HID_USAGE_PID_BLOCK_LOAD_STATUS = $8B; HID_USAGE_PID_BLOCK_LOAD_SUCCESS = $8C; HID_USAGE_PID_BLOCK_LOAD_FULL = $8D; HID_USAGE_PID_BLOCK_LOAD_ERROR = $8E; HID_USAGE_PID_BLOCK_HANDLE = $8F; HID_USAGE_PID_PID_BLOCK_FREE_REPORT = $90; HID_USAGE_PID_TYPE_SPECIFIC_BLOCK_HANDLE = $91; HID_USAGE_PID_PID_STATE_REPORT = $92; HID_USAGE_PID_EFFECT_PLAYING = $94; HID_USAGE_PID_PID_DEVICE_CONTROL_REPORT = $95; HID_USAGE_PID_PID_DEVICE_CONTROL = $96; HID_USAGE_PID_DC_ENABLE_ACTUATORS = $97; HID_USAGE_PID_DC_DISABLE_ACTUATORS = $98; HID_USAGE_PID_DC_STOP_ALL_EFFECTS = $99; HID_USAGE_PID_DC_DEVICE_RESET = $9A; HID_USAGE_PID_DC_DEVICE_PAUSE = $9B; HID_USAGE_PID_DC_DEVICE_CONTINUE = $9C; HID_USAGE_PID_DEVICE_PAUSED = $9F; HID_USAGE_PID_ACTUATORS_ENABLED = $A0; HID_USAGE_PID_SAFETY_SWITCH = $A4; HID_USAGE_PID_ACTUATOR_OVERRIDE_SWITCH = $A5; HID_USAGE_PID_ACTUATOR_POWER = $A6; HID_USAGE_PID_START_DELAY = $A7; HID_USAGE_PID_PARAMETER_BLOCK_SIZE = $A8; HID_USAGE_PID_DEVICE_MANAGED_POOL = $A9; HID_USAGE_PID_SHARED_PARAMETER_BLOCKS = $AA; HID_USAGE_PID_CREATE_NEW_EFFECT_REPORT = $AB; HID_USAGE_PID_RAM_POOL_AVAILABLE = $AC; // (rom) $AD to $FFFF are reserved in "Device Class Definition for Physical Interface Devices 1.0" (pid1_01.pdf) // // Unicode Page (0x10) // // (rom) The Unicode Page directly maps to the two-octet form defined in the Unicode Standard // // Alphanumeric Display Page (0x14) // HID_USAGE_ALNUM_DISPLAY_UNDEFINED = $00; HID_USAGE_ALNUM_DISPLAY_ALPHANUMERIC_DISPLAY = $01; HID_USAGE_ALNUM_DISPLAY_DISPLAY_ATTRIBUTES_REPORT = $20; HID_USAGE_ALNUM_DISPLAY_ASCII_CHARSET = $21; HID_USAGE_ALNUM_DISPLAY_DATA_READ_BACK = $22; HID_USAGE_ALNUM_DISPLAY_FONT_READ_BACK = $23; HID_USAGE_ALNUM_DISPLAY_DISPLAY_CONTROL_REPORT = $24; HID_USAGE_ALNUM_DISPLAY_CLEAR_DISPLAY = $25; HID_USAGE_ALNUM_DISPLAY_DISPLAY_ENABLE = $26; HID_USAGE_ALNUM_DISPLAY_SCREEN_SAVER_DELAY = $27; HID_USAGE_ALNUM_DISPLAY_SCREEN_SAVER_ENABLE = $28; HID_USAGE_ALNUM_DISPLAY_VERTICAL_SCROLL = $29; HID_USAGE_ALNUM_DISPLAY_HORIZONTAL_SCROLL = $2A; HID_USAGE_ALNUM_DISPLAY_CHARACTER_REPORT = $2B; HID_USAGE_ALNUM_DISPLAY_DISPLAY_DATA = $2C; HID_USAGE_ALNUM_DISPLAY_DISPLAY_STATUS = $2D; HID_USAGE_ALNUM_DISPLAY_STAT_NOT_READY = $2E; HID_USAGE_ALNUM_DISPLAY_STAT_READY = $2F; HID_USAGE_ALNUM_DISPLAY_ERR_NOT_A_LOADABLE_CHAR = $30; HID_USAGE_ALNUM_DISPLAY_ERR_FONT_DATA_CANNOT_BE_READ = $31; HID_USAGE_ALNUM_DISPLAY_CURSOR_POSITION_REPORT = $32; HID_USAGE_ALNUM_DISPLAY_ROW = $33; HID_USAGE_ALNUM_DISPLAY_COLUMN = $34; HID_USAGE_ALNUM_DISPLAY_ROWS = $35; HID_USAGE_ALNUM_DISPLAY_COLUMNS = $36; HID_USAGE_ALNUM_DISPLAY_CURSOR_PIXEL_POSITIONING = $37; HID_USAGE_ALNUM_DISPLAY_CURSOR_MODE = $38; HID_USAGE_ALNUM_DISPLAY_CURSOR_ENABLE = $39; HID_USAGE_ALNUM_DISPLAY_CURSOR_BLINK = $3A; HID_USAGE_ALNUM_DISPLAY_FONT_REPORT = $3B; HID_USAGE_ALNUM_DISPLAY_FONT_DATA = $3C; HID_USAGE_ALNUM_DISPLAY_CHAR_WIDTH = $3D; HID_USAGE_ALNUM_DISPLAY_CHAR_HEIGHT = $3E; HID_USAGE_ALNUM_DISPLAY_CHAR_SPACING_HORIZONTAL = $3F; HID_USAGE_ALNUM_DISPLAY_CHAR_SPACING_VERTICAL = $40; HID_USAGE_ALNUM_DISPLAY_UNICODE_CHARSET = $41; HID_USAGE_ALNUM_DISPLAY_FONT_7_SEGMENT = $42; HID_USAGE_ALNUM_DISPLAY_7_SEGMENT_DIRECT_MAP = $43; HID_USAGE_ALNUM_DISPLAY_FONT_14_SEGMENT = $44; HID_USAGE_ALNUM_DISPLAY_14_SEGMENT_DIRECT_MAP = $45; HID_USAGE_ALNUM_DISPLAY_DISPLAY_BRIGHTNESS = $46; HID_USAGE_ALNUM_DISPLAY_DISPLAY_CONTRAST = $47; HID_USAGE_ALNUM_DISPLAY_CHAR_ATTRIBUTE = $48; HID_USAGE_ALNUM_DISPLAY_ATTRIBUTE_READBACK = $49; HID_USAGE_ALNUM_DISPLAY_ATTRIBUTE_DATA = $4A; HID_USAGE_ALNUM_DISPLAY_CHAR_ATTR_ENHANCE = $4B; HID_USAGE_ALNUM_DISPLAY_CHAR_ATTR_UNDERLINE = $4C; HID_USAGE_ALNUM_DISPLAY_CHAR_ATTR_BLINK = $4D; // (rom) $4E to $FFFF are reserved in "USB HID Usage Tables 1.11" (Hut1_11.pdf) // // Medical Instrument Page (0x40) // HID_USAGE_MEDICAL_INSTRUMENT_UNDEFINED = $00; HID_USAGE_MEDICAL_INSTRUMENT_MEDICAL_ULTRASOUND = $01; HID_USAGE_MEDICAL_INSTRUMENT_VCR_AQUISITION = $20; HID_USAGE_MEDICAL_INSTRUMENT_FREEZE_THAW = $21; HID_USAGE_MEDICAL_INSTRUMENT_CLIP_STORE = $22; HID_USAGE_MEDICAL_INSTRUMENT_UPDATE = $23; HID_USAGE_MEDICAL_INSTRUMENT_NEXT = $24; HID_USAGE_MEDICAL_INSTRUMENT_SAVE = $25; HID_USAGE_MEDICAL_INSTRUMENT_PRINT = $26; HID_USAGE_MEDICAL_INSTRUMENT_MICROPHONE_ENABLE = $27; HID_USAGE_MEDICAL_INSTRUMENT_CINE = $40; HID_USAGE_MEDICAL_INSTRUMENT_TRANSMIT_POWER = $41; HID_USAGE_MEDICAL_INSTRUMENT_VOLUME = $42; HID_USAGE_MEDICAL_INSTRUMENT_FOCUS = $43; HID_USAGE_MEDICAL_INSTRUMENT_DEPTH = $44; HID_USAGE_MEDICAL_INSTRUMENT_SOFT_STEP_PRIMARY = $60; HID_USAGE_MEDICAL_INSTRUMENT_SOFT_STEP_SECONDARY = $61; HID_USAGE_MEDICAL_INSTRUMENT_DEPTH_GAIN_COMPENSATION = $70; HID_USAGE_MEDICAL_INSTRUMENT_ZOOM_SELECT = $80; HID_USAGE_MEDICAL_INSTRUMENT_ZOOM_ADJUST = $81; HID_USAGE_MEDICAL_INSTRUMENT_SPECTRAL_DOPPLER_MODE_SELECT = $82; HID_USAGE_MEDICAL_INSTRUMENT_SPECTRAL_DOPPLER_ADJUST = $83; HID_USAGE_MEDICAL_INSTRUMENT_COLOR_DOPPLER_MODE_SELECT = $84; HID_USAGE_MEDICAL_INSTRUMENT_COLOR_DOPPLER_ADJUST = $85; HID_USAGE_MEDICAL_INSTRUMENT_MOTION_MODE_SELECT = $86; HID_USAGE_MEDICAL_INSTRUMENT_MOTION_MODE_ADJUST = $87; HID_USAGE_MEDICAL_INSTRUMENT_2D_MODE_SELECT = $88; HID_USAGE_MEDICAL_INSTRUMENT_2D_MODE_ADJUST = $89; HID_USAGE_MEDICAL_INSTRUMENT_SOFT_CONTROL_SELECT = $A0; HID_USAGE_MEDICAL_INSTRUMENT_SOFT_CONTROL_ADJUST = $A1; // (rom) $A2 to $FFFF are reserved in "USB HID Usage Tables 1.11" (Hut1_11.pdf) // // USB Monitor Page (0x80) // HID_USAGE_MONITOR_RESERVED = $00; HID_USAGE_MONITOR_MONITOR_CONTROL = $01; HID_USAGE_MONITOR_EDID_INFORMATION = $02; HID_USAGE_MONITOR_VDIF_INFORMATION = $03; HID_USAGE_MONITOR_VESA_VERSION = $04; // // Monitor Enumerated Values Page (0x81) // HID_USAGE_MONITOR_ENUM_VALUE_NO_VALUE = $00; // (rom) read "usbmon10.pdf" from USB IF for more info // // Monitor VESA Virtual Control Page (0x82) // HID_USAGE_MONITOR_VESA_BRIGHTNESS = $10; HID_USAGE_MONITOR_VESA_CONTRAST = $12; HID_USAGE_MONITOR_VESA_RED_VIDEO_GAIN = $16; HID_USAGE_MONITOR_VESA_GREEN_VIDEO_GAIN = $18; HID_USAGE_MONITOR_VESA_BLUE_VIDEO_GAIN = $1A; HID_USAGE_MONITOR_VESA_FOCUS = $1C; HID_USAGE_MONITOR_VESA_HORIZONTAL_POS = $20; HID_USAGE_MONITOR_VESA_HORIZONTAL_SIZE = $22; HID_USAGE_MONITOR_VESA_HORIZONTAL_PINCUSHION = $24; HID_USAGE_MONITOR_VESA_HORIZONTAL_PINCUSHION_BALANCE = $26; HID_USAGE_MONITOR_VESA_HORIZONTAL_MISCONVERGENCE = $28; HID_USAGE_MONITOR_VESA_HORIZONTAL_LINEARITY = $2A; HID_USAGE_MONITOR_VESA_HORIZONTAL_LINEARITY_BALANCE = $2C; HID_USAGE_MONITOR_VESA_VERTICAL_POS = $30; HID_USAGE_MONITOR_VESA_VERTICAL_SIZE = $32; HID_USAGE_MONITOR_VESA_VERTICAL_PINCUSHION = $34; HID_USAGE_MONITOR_VESA_VERTICAL_PINCUSHION_BALANCE = $36; HID_USAGE_MONITOR_VESA_VERTICAL_MISCONVERGENCE = $38; HID_USAGE_MONITOR_VESA_VERTICAL_LINEARITY = $3A; HID_USAGE_MONITOR_VESA_VERTICAL_LINEARITY_BALANCE = $3C; HID_USAGE_MONITOR_VESA_PARALLELOGRAM_DISTORTION = $40; HID_USAGE_MONITOR_VESA_TRAPEZOIDAL_DISTORTION = $42; HID_USAGE_MONITOR_VESA_TILT = $44; HID_USAGE_MONITOR_VESA_TOP_CORNER_DISTORTION = $46; HID_USAGE_MONITOR_VESA_TOP_CORNER_DISTORTION_BALANCE = $48; HID_USAGE_MONITOR_VESA_BOTTOM_CORNER_DISTORTION = $4A; HID_USAGE_MONITOR_VESA_BOTTOM_CORNER_DISTORTION_BALANCE = $4C; HID_USAGE_MONITOR_VESA_HORIZONTAL_MOIRE = $56; HID_USAGE_MONITOR_VESA_VERTICAL_MOIRE = $58; HID_USAGE_MONITOR_VESA_RED_VIDEO_BLACK_LEVEL = $6C; HID_USAGE_MONITOR_VESA_GREEN_VIDEO_BLACK_LEVEL = $6E; HID_USAGE_MONITOR_VESA_BLUE_VIDEO_BLACK_LEVEL = $70; HID_USAGE_MONITOR_VESA_INPUT_LEVEL_SELECT = $5E; HID_USAGE_MONITOR_VESA_INPUT_SOURCE_SELECT = $60; HID_USAGE_MONITOR_VESA_ON_SCREEN_DISPLAY = $CA; HID_USAGE_MONITOR_VESA_STEREO_MODE = $D4; HID_USAGE_MONITOR_VESA_AUTO_SIZE_CENTER = $A2; HID_USAGE_MONITOR_VESA_POLARITY_HORIZONTAL_SYNC = $A4; HID_USAGE_MONITOR_VESA_POLARITY_VERTICAL_SYNC = $A6; HID_USAGE_MONITOR_VESA_SYNC_TYPE = $A8; HID_USAGE_MONITOR_VESA_SCREEN_ORIENTATION = $AA; HID_USAGE_MONITOR_VESA_HORIZONTAL_FREQUENCY = $AC; HID_USAGE_MONITOR_VESA_VERTICAL_FREQUENCY = $AE; HID_USAGE_MONITOR_VESA_DEGAUSS = $01; HID_USAGE_MONITOR_VESA_SETTINGS = $B0; // // Monitor Reserved Page (0x83) // // // Power Device Page (0x84) // HID_USAGE_POWER_DEVICE_UNDEFINED = $00; HID_USAGE_POWER_DEVICE_INAME = $01; HID_USAGE_POWER_DEVICE_PRESENT_STATUS = $02; HID_USAGE_POWER_DEVICE_CHANGED_STATUS = $03; HID_USAGE_POWER_DEVICE_UPS = $04; HID_USAGE_POWER_DEVICE_POWER_SUPPLY = $05; HID_USAGE_POWER_DEVICE_BATTERY_SYSTEM = $10; HID_USAGE_POWER_DEVICE_BATTERY_SYSTEM_ID = $11; HID_USAGE_POWER_DEVICE_BATTERY = $12; HID_USAGE_POWER_DEVICE_BATTERY_ID = $13; HID_USAGE_POWER_DEVICE_CHARGER = $14; HID_USAGE_POWER_DEVICE_CHARGER_ID = $15; HID_USAGE_POWER_DEVICE_POWER_CONVERTER = $16; HID_USAGE_POWER_DEVICE_POWER_CONVERTER_ID = $17; HID_USAGE_POWER_DEVICE_OUTLET_SYSTEM = $18; HID_USAGE_POWER_DEVICE_OUTLET_SYSTEM_ID = $19; HID_USAGE_POWER_DEVICE_INPUT = $1A; HID_USAGE_POWER_DEVICE_INPUT_ID = $1B; HID_USAGE_POWER_DEVICE_OUTPUT = $1C; HID_USAGE_POWER_DEVICE_OUTPUT_ID = $1D; HID_USAGE_POWER_DEVICE_FLOW = $1E; HID_USAGE_POWER_DEVICE_FLOW_ID = $1F; HID_USAGE_POWER_DEVICE_OUTLET = $20; HID_USAGE_POWER_DEVICE_OUTLET_ID = $21; HID_USAGE_POWER_DEVICE_GANG = $22; HID_USAGE_POWER_DEVICE_GANG_ID = $23; HID_USAGE_POWER_DEVICE_POWER_SUMMARY = $24; HID_USAGE_POWER_DEVICE_POWER_SUMMARY_ID = $25; HID_USAGE_POWER_DEVICE_VOLTAGE = $30; HID_USAGE_POWER_DEVICE_CURRENT = $31; HID_USAGE_POWER_DEVICE_FREQUENCY = $32; HID_USAGE_POWER_DEVICE_APPARENT_POWER = $33; HID_USAGE_POWER_DEVICE_ACTIVE_POWER = $34; HID_USAGE_POWER_DEVICE_PERCENT_LOAD = $35; HID_USAGE_POWER_DEVICE_TEMPERATURE = $36; HID_USAGE_POWER_DEVICE_HUMIDITY = $37; HID_USAGE_POWER_DEVICE_BAD_COUNT = $38; HID_USAGE_POWER_DEVICE_CONFIG_VOLTAGE = $40; HID_USAGE_POWER_DEVICE_CONFIG_CURRENT = $41; HID_USAGE_POWER_DEVICE_CONFIG_FREQUENCY = $42; HID_USAGE_POWER_DEVICE_CONFIG_APPARENT_POWER = $43; HID_USAGE_POWER_DEVICE_CONFIG_ACTIVE_POWER = $44; HID_USAGE_POWER_DEVICE_CONFIG_PERCENT_LOAD = $45; HID_USAGE_POWER_DEVICE_CONFIG_TEMPERATURE = $46; HID_USAGE_POWER_DEVICE_CONFIG_HUMIDITY = $47; HID_USAGE_POWER_DEVICE_SWITCH_ON_CONTROL = $50; HID_USAGE_POWER_DEVICE_SWITCH_OFF_CONTROL = $51; HID_USAGE_POWER_DEVICE_TOGGLE_CONTROL = $52; HID_USAGE_POWER_DEVICE_LOW_VOLTAGE_TRANSFER = $53; HID_USAGE_POWER_DEVICE_HIGH_VOLTAGE_TRANSFER = $54; HID_USAGE_POWER_DEVICE_DELAY_BEFORE_REBOOT = $55; HID_USAGE_POWER_DEVICE_DELAY_BEFORE_STARTUP = $56; HID_USAGE_POWER_DEVICE_DELAY_BEFORE_SHUTDOWN = $57; HID_USAGE_POWER_DEVICE_TEST = $58; HID_USAGE_POWER_DEVICE_MODULE_RESET = $59; HID_USAGE_POWER_DEVICE_AUDIBLE_ALARM_CONTROL = $5A; HID_USAGE_POWER_DEVICE_PRESENT = $60; HID_USAGE_POWER_DEVICE_GOOD = $61; HID_USAGE_POWER_DEVICE_INTERNAL_FAILURE = $62; HID_USAGE_POWER_DEVICE_VOLTAGE_OUT_OF_RANGE = $63; HID_USAGE_POWER_DEVICE_FREQUENCY_OUT_OF_RANGE = $64; HID_USAGE_POWER_DEVICE_OVERLOAD = $65; HID_USAGE_POWER_DEVICE_OVERCHARGED = $66; HID_USAGE_POWER_DEVICE_OVERTEMPERATURE = $67; HID_USAGE_POWER_DEVICE_SHUTDOWN_REQUESTED = $68; HID_USAGE_POWER_DEVICE_SHUTDOWN_IMMINENT = $69; HID_USAGE_POWER_DEVICE_SWITCH_ON_OFF = $6B; HID_USAGE_POWER_DEVICE_SWITCHABLE = $6C; HID_USAGE_POWER_DEVICE_USED = $6D; HID_USAGE_POWER_DEVICE_BOOST = $6E; HID_USAGE_POWER_DEVICE_BUCK = $6F; HID_USAGE_POWER_DEVICE_INITIALIZED = $70; HID_USAGE_POWER_DEVICE_TESTED = $71; HID_USAGE_POWER_DEVICE_AWAITING_POWER = $72; HID_USAGE_POWER_DEVICE_COMMUNICATION_LOST = $73; HID_USAGE_POWER_DEVICE_IMANUFACTURER = $FD; HID_USAGE_POWER_DEVICE_IPRODUCT = $FE; HID_USAGE_POWER_DEVICE_ISERIALNUMBER = $FF; // // Battery System Page (0x85) // HID_USAGE_BATTERY_SYSTEM_UNDEFINED = $00; HID_USAGE_BATTERY_SYSTEM_SMB_BATTERY_MODE = $01; HID_USAGE_BATTERY_SYSTEM_SMB_BATTERY_STATUS = $02; HID_USAGE_BATTERY_SYSTEM_SMB_ALARM_WARNING = $03; HID_USAGE_BATTERY_SYSTEM_SMB_CHARGER_MODE = $04; HID_USAGE_BATTERY_SYSTEM_SMB_CHARGER_STATUS = $05; HID_USAGE_BATTERY_SYSTEM_SMB_CHARGER_SPEC_INFO = $06; HID_USAGE_BATTERY_SYSTEM_SMB_SELECTOR_STATE = $07; HID_USAGE_BATTERY_SYSTEM_SMB_SELECTOR_PRESETS = $08; HID_USAGE_BATTERY_SYSTEM_SMB_SELECTOR_INFO = $09; HID_USAGE_BATTERY_SYSTEM_OPTIONAL_MFG_FUNCTION_1 = $10; HID_USAGE_BATTERY_SYSTEM_OPTIONAL_MFG_FUNCTION_2 = $11; HID_USAGE_BATTERY_SYSTEM_OPTIONAL_MFG_FUNCTION_3 = $12; HID_USAGE_BATTERY_SYSTEM_OPTIONAL_MFG_FUNCTION_4 = $13; HID_USAGE_BATTERY_SYSTEM_OPTIONAL_MFG_FUNCTION_5 = $14; HID_USAGE_BATTERY_SYSTEM_CONNECTION_TO_SMBUS = $15; HID_USAGE_BATTERY_SYSTEM_OUTPUT_CONNECTION = $16; HID_USAGE_BATTERY_SYSTEM_CHARGER_CONNECTION = $17; HID_USAGE_BATTERY_SYSTEM_BATTERY_INSERTION = $18; HID_USAGE_BATTERY_SYSTEM_USE_NEXT = $19; HID_USAGE_BATTERY_SYSTEM_OK_TO_USE = $1A; HID_USAGE_BATTERY_SYSTEM_BATTERY_SUPPORTED = $1B; HID_USAGE_BATTERY_SYSTEM_SELECTOR_REVISION = $1C; HID_USAGE_BATTERY_SYSTEM_CHARGING_INDICATOR = $1D; HID_USAGE_BATTERY_SYSTEM_MANUFACTURER_ACCESS = $28; HID_USAGE_BATTERY_SYSTEM_REMAINING_CAPACITY_LIMIT = $29; HID_USAGE_BATTERY_SYSTEM_REMAINING_TIME_LIMIT = $2A; HID_USAGE_BATTERY_SYSTEM_AT_RATE = $2B; HID_USAGE_BATTERY_SYSTEM_CAPACITY_MODE = $2C; HID_USAGE_BATTERY_SYSTEM_BROADCAST_TO_CHARGER = $2D; HID_USAGE_BATTERY_SYSTEM_PRIMARY_BATTERY = $2E; HID_USAGE_BATTERY_SYSTEM_CHARGE_CONTROLLER = $2F; HID_USAGE_BATTERY_SYSTEM_TERMINATE_CHARGE = $40; HID_USAGE_BATTERY_SYSTEM_TERMINATE_DISCHARGE = $41; HID_USAGE_BATTERY_SYSTEM_BELOW_REMAINING_CAPACITY_LIMIT = $42; HID_USAGE_BATTERY_SYSTEM_REMAINING_TIME_LIMIT_EXPIRED = $43; HID_USAGE_BATTERY_SYSTEM_CHARGING = $44; HID_USAGE_BATTERY_SYSTEM_DISCHARGING = $45; HID_USAGE_BATTERY_SYSTEM_FULLY_CHARGED = $46; HID_USAGE_BATTERY_SYSTEM_FULLY_DISCHARGED = $47; HID_USAGE_BATTERY_SYSTEM_CONDITIONING_FLAG = $48; HID_USAGE_BATTERY_SYSTEM_AT_RATE_OK = $49; HID_USAGE_BATTERY_SYSTEM_SMB_ERROR_CODE = $4A; HID_USAGE_BATTERY_SYSTEM_NEED_REPLACEMENT = $4B; HID_USAGE_BATTERY_SYSTEM_AT_RATE_TIME_TO_FULL = $60; HID_USAGE_BATTERY_SYSTEM_AT_RATE_TIME_TO_EMPTY = $61; HID_USAGE_BATTERY_SYSTEM_AVERAGE_CURRENT = $62; HID_USAGE_BATTERY_SYSTEM_MAX_ERROR = $63; HID_USAGE_BATTERY_SYSTEM_RELATIVE_STATE_OF_CHARGE = $64; HID_USAGE_BATTERY_SYSTEM_ABSOLUTE_STATE_OF_CHARGE = $65; HID_USAGE_BATTERY_SYSTEM_REMAINING_CAPACITY = $66; HID_USAGE_BATTERY_SYSTEM_FULL_CHARGE_CAPACITY = $67; HID_USAGE_BATTERY_SYSTEM_RUN_TIME_TO_EMPTY = $68; HID_USAGE_BATTERY_SYSTEM_AVERAGE_TIME_TO_EMPTY = $69; HID_USAGE_BATTERY_SYSTEM_AVERAGE_TIME_TO_FULL = $6A; HID_USAGE_BATTERY_SYSTEM_CYCLE_COUNT = $6B; HID_USAGE_BATTERY_SYSTEM_BATT_PACK_MODEL_LEVEL = $80; HID_USAGE_BATTERY_SYSTEM_INTERNAL_CHARGE_CONTROLLER = $81; HID_USAGE_BATTERY_SYSTEM_PRIMARY_BATTERY_SUPPORT = $82; HID_USAGE_BATTERY_SYSTEM_DESIGN_CAPACITY = $83; HID_USAGE_BATTERY_SYSTEM_SPECIFICATION_INFO = $84; HID_USAGE_BATTERY_SYSTEM_MANUFACTURER_DATE = $85; HID_USAGE_BATTERY_SYSTEM_SERIAL_NUMBER = $86; HID_USAGE_BATTERY_SYSTEM_I_MANUFACTURER_NAME = $87; HID_USAGE_BATTERY_SYSTEM_I_DEVICE_NAME = $88; HID_USAGE_BATTERY_SYSTEM_I_DEVICE_CHEMISTERY = $89; HID_USAGE_BATTERY_SYSTEM_MANUFACTURER_DATA = $8A; HID_USAGE_BATTERY_SYSTEM_RECHARGABLE = $8B; HID_USAGE_BATTERY_SYSTEM_WARNING_CAPACITY_LIMIT = $8c; HID_USAGE_BATTERY_SYSTEM_CAPACITY_GRANULARITY_1 = $8d; HID_USAGE_BATTERY_SYSTEM_CAPACITY_GRANULARITY_2 = $8E; HID_USAGE_BATTERY_SYSTEM_I_OEM_INFORMATION = $8F; HID_USAGE_BATTERY_SYSTEM_INHIBIT_CHARGE = $C0; HID_USAGE_BATTERY_SYSTEM_ENABLE_POLLING = $C1; HID_USAGE_BATTERY_SYSTEM_RESET_TO_ZERO = $C2; HID_USAGE_BATTERY_SYSTEM_AC_PRESENT = $D0; HID_USAGE_BATTERY_SYSTEM_BATTERY_PRESENT = $D1; HID_USAGE_BATTERY_SYSTEM_POWER_FAIL = $D2; HID_USAGE_BATTERY_SYSTEM_ALARM_INHIBITED = $D3; HID_USAGE_BATTERY_SYSTEM_THERMISTOR_UNDER_RANGE = $D4; HID_USAGE_BATTERY_SYSTEM_THERMISTOR_HOT = $D5; HID_USAGE_BATTERY_SYSTEM_THERMISTOR_COLD = $D6; HID_USAGE_BATTERY_SYSTEM_THERMISTOR_OVER_RANGE = $D7; HID_USAGE_BATTERY_SYSTEM_VOLTAGE_OUT_OF_RANGE = $D8; HID_USAGE_BATTERY_SYSTEM_CURRENT_OUT_OF_RANGE = $D9; HID_USAGE_BATTERY_SYSTEM_CURRENT_NOT_REGULATED = $DA; HID_USAGE_BATTERY_SYSTEM_VOLTAGE_NOT_REGULATED = $DB; HID_USAGE_BATTERY_SYSTEM_MASTER_MODE = $DC; HID_USAGE_BATTERY_SYSTEM_CHARGER_SELECTOR_SUPPORT = $F0; HID_USAGE_BATTERY_SYSTEM_CHARGER_SPEC = $F1; HID_USAGE_BATTERY_SYSTEM_LEVEL_2 = $F2; HID_USAGE_BATTERY_SYSTEM_LEVEL_3 = $F3; // (rom) $F4 to $FF are reserved in "Usage Tables for HID Power Devices 1.0" (pdcv10.pdf) // // Barcode Scanner Page (0x8C) // HID_USAGE_BARCODE_SCANNER_UNDEFINED = $000; HID_USAGE_BARCODE_SCANNER_BAR_CODE_BADGE_READER = $001; HID_USAGE_BARCODE_SCANNER_BAR_CODE_SCANNER = $002; HID_USAGE_BARCODE_SCANNER_DUMB_BAR_CODE_SCANNER = $003; HID_USAGE_BARCODE_SCANNER_CORDLESS_SCANNER_BASE = $004; HID_USAGE_BARCODE_SCANNER_BAR_CODE_SCANNER_CRADLE = $005; HID_USAGE_BARCODE_SCANNER_ATTRIBUTE_REPORT = $010; HID_USAGE_BARCODE_SCANNER_SETTINGS_REPORT = $011; HID_USAGE_BARCODE_SCANNER_SCANNED_DATA_REPORT = $012; HID_USAGE_BARCODE_SCANNER_RAW_SCANNED_DATA_REPORT = $013; HID_USAGE_BARCODE_SCANNER_TRIGGER_REPORT = $014; HID_USAGE_BARCODE_SCANNER_STATUS_REPORT = $015; HID_USAGE_BARCODE_SCANNER_UPC_EAN_CONTROL_REPORT = $016; HID_USAGE_BARCODE_SCANNER_EAN_2_3_LABEL_CONTROL_REPORT = $017; HID_USAGE_BARCODE_SCANNER_CODE_39_CONTROL_REPORT = $018; HID_USAGE_BARCODE_SCANNER_INTERLEAVED_2_OF_5_CONTROL_REPORT = $019; HID_USAGE_BARCODE_SCANNER_STANDARD_2_OF_5_CONTROL_REPORT = $01A; HID_USAGE_BARCODE_SCANNER_MSI_PLESSEY_CONTROL_REPORT = $01B; HID_USAGE_BARCODE_SCANNER_CODABAR_CONTROL_REPORT = $01C; HID_USAGE_BARCODE_SCANNER_CODE_128_CONTROL_REPORT = $01D; HID_USAGE_BARCODE_SCANNER_MISC_1D_CONTROL_REPORT = $01E; HID_USAGE_BARCODE_SCANNER_2D_CONTROL_REPORT = $01F; HID_USAGE_BARCODE_SCANNER_AIMING_POINTER_MODE = $030; HID_USAGE_BARCODE_SCANNER_BAR_CODE_PRESENT_SENSOR = $031; HID_USAGE_BARCODE_SCANNER_CLASS_1A_LASER = $032; HID_USAGE_BARCODE_SCANNER_CLASS_2_LASER = $033; HID_USAGE_BARCODE_SCANNER_HEATER_PRESENT = $034; HID_USAGE_BARCODE_SCANNER_CONTACT_SCANNER = $035; HID_USAGE_BARCODE_SCANNER_ELECTRONIC_ARTICLE_SURVEILLANCE_NOTIFICATION = $036; HID_USAGE_BARCODE_SCANNER_CONSTANT_ARTICLE_SURVEILLANCE_NOTIFICATION = $037; HID_USAGE_BARCODE_SCANNER_ERROR_INDICATION = $038; HID_USAGE_BARCODE_SCANNER_FIXED_BEEPER = $039; HID_USAGE_BARCODE_SCANNER_GOOD_DECODE_INDICATION = $03A; HID_USAGE_BARCODE_SCANNER_HANDS_FREE_SCANNING = $03B; HID_USAGE_BARCODE_SCANNER_INTRINSICALLY_SAFE = $03C; HID_USAGE_BARCODE_SCANNER_KLASSE_EINS_LASER = $03D; HID_USAGE_BARCODE_SCANNER_LONG_RANGE_SCANNER = $03E; HID_USAGE_BARCODE_SCANNER_MIRROR_SPEED_CONTROL = $03F; HID_USAGE_BARCODE_SCANNER_NOT_ON_FILE_INDICATION = $040; HID_USAGE_BARCODE_SCANNER_PROGRAMMABLE_BEEPER = $041; HID_USAGE_BARCODE_SCANNER_TRIGGERLESS = $042; HID_USAGE_BARCODE_SCANNER_WAND = $043; HID_USAGE_BARCODE_SCANNER_WATER_RESISTANT = $044; HID_USAGE_BARCODE_SCANNER_MULTI_RANGE_SCANNER = $045; HID_USAGE_BARCODE_SCANNER_PROXIMITIY_SENSOR = $046; HID_USAGE_BARCODE_SCANNER_FRAGMENT_DECODING = $04D; HID_USAGE_BARCODE_SCANNER_SCANNER_READ_CONFIDENCE = $04E; HID_USAGE_BARCODE_SCANNER_DATA_PREFIX = $04F; HID_USAGE_BARCODE_SCANNER_PREFIX_AIMI = $050; HID_USAGE_BARCODE_SCANNER_PREFIX_NODE = $051; HID_USAGE_BARCODE_SCANNER_PREFIX_PROPRIETARY = $052; HID_USAGE_BARCODE_SCANNER_ACTIVE_TIME = $055; HID_USAGE_BARCODE_SCANNER_AIMING_LASER_PATTERN = $056; HID_USAGE_BARCODE_SCANNER_BAR_CODE_PRESENT = $057; HID_USAGE_BARCODE_SCANNER_BEEPER_STATE = $058; HID_USAGE_BARCODE_SCANNER_LASER_ON_TIME = $059; HID_USAGE_BARCODE_SCANNER_LASER_STATE = $05A; HID_USAGE_BARCODE_SCANNER_LOCKOUT_TIME = $05B; HID_USAGE_BARCODE_SCANNER_MOTOR_STATE = $05C; HID_USAGE_BARCODE_SCANNER_MOTOR_TIMEOUT = $05D; HID_USAGE_BARCODE_SCANNER_POWER_ON_RESET_SCANNER = $05E; HID_USAGE_BARCODE_SCANNER_PREVENT_READ_OF_BARCODES = $05F; HID_USAGE_BARCODE_SCANNER_INITIATE_BARCODE_READ = $060; HID_USAGE_BARCODE_SCANNER_TRIGGER_STATE = $061; HID_USAGE_BARCODE_SCANNER_TRIGGER_MODE = $062; HID_USAGE_BARCODE_SCANNER_TM_BLINKING_LASER_ON = $063; HID_USAGE_BARCODE_SCANNER_TM_CONTINUOUS_LASER_ON = $064; HID_USAGE_BARCODE_SCANNER_TM_LASER_ON_WHILE_PULLED = $065; HID_USAGE_BARCODE_SCANNER_TM_LASER_STAYS_ON_AFTER_TRIGGER_RELEASE = $066; HID_USAGE_BARCODE_SCANNER_COMMIT_PARAMETERS_TO_NVM = $06D; HID_USAGE_BARCODE_SCANNER_PARAMETER_SCANNING = $06E; HID_USAGE_BARCODE_SCANNER_PARAMETERS_CHANGED = $06F; HID_USAGE_BARCODE_SCANNER_SET_PARAMETER_DEFAULT_VALUES = $070; HID_USAGE_BARCODE_SCANNER_SCANNER_IN_CRADLE = $075; HID_USAGE_BARCODE_SCANNER_SCANNER_IN_RANGE = $076; HID_USAGE_BARCODE_SCANNER_AIM_DURATION = $07A; HID_USAGE_BARCODE_SCANNER_GOOD_READ_LAMP_DURATION = $07B; HID_USAGE_BARCODE_SCANNER_GOOD_READ_LAMP_INTENSITY = $07C; HID_USAGE_BARCODE_SCANNER_GOOD_READ_LED = $07D; HID_USAGE_BARCODE_SCANNER_GOOD_READ_TONE_FREQUENCY = $07E; HID_USAGE_BARCODE_SCANNER_GOOD_READ_TONE_LENGTH = $07F; HID_USAGE_BARCODE_SCANNER_GOOD_READ_TONE_VOLUME = $080; HID_USAGE_BARCODE_SCANNER_NO_READ_MESSAGE = $082; HID_USAGE_BARCODE_SCANNER_NOT_ON_FILE_VOLUME = $083; HID_USAGE_BARCODE_SCANNER_POWERUP_BEEP = $084; HID_USAGE_BARCODE_SCANNER_SOUND_ERROR_BEEP = $085; HID_USAGE_BARCODE_SCANNER_SOUND_GOOD_READ_BEEP = $086; HID_USAGE_BARCODE_SCANNER_SOUND_NOT_ON_FILE_BEEP = $087; HID_USAGE_BARCODE_SCANNER_GOOD_READ_WHEN_TO_WRITE = $088; HID_USAGE_BARCODE_SCANNER_GRWTI_AFTER_DECODE = $089; HID_USAGE_BARCODE_SCANNER_GRWTI_BEEP_LAMP_AFTER_TRANSMIT = $08a; HID_USAGE_BARCODE_SCANNER_GRWTI_NO_BEEP_LAMP_USE_AT_ALL = $08B; HID_USAGE_BARCODE_SCANNER_BOOKLAND_EAN = $091; HID_USAGE_BARCODE_SCANNER_CONVERT_EAN_8_TO_13_TYPE = $092; HID_USAGE_BARCODE_SCANNER_CONVERT_UPC_A_TO_EAN_13 = $093; HID_USAGE_BARCODE_SCANNER_CONVERT_UPC_E_TO_A = $094; HID_USAGE_BARCODE_SCANNER_EAN_13 = $095; HID_USAGE_BARCODE_SCANNER_EAN_8 = $096; HID_USAGE_BARCODE_SCANNER_EAN_99_128_MANDATORY = $097; HID_USAGE_BARCODE_SCANNER_EAN_99_P5_128_OPTIONAL = $098; HID_USAGE_BARCODE_SCANNER_UPC_EAN = $09A; HID_USAGE_BARCODE_SCANNER_UPC_EAN_COUPON_CODE = $09B; HID_USAGE_BARCODE_SCANNER_UPC_EAN_PERIODICALS = $09C; HID_USAGE_BARCODE_SCANNER_UPC_A = $09D; HID_USAGE_BARCODE_SCANNER_UPC_A_WITH_128_MANDATORY = $09E; HID_USAGE_BARCODE_SCANNER_UPC_A_WITH_128_OPTIONAL = $09F; HID_USAGE_BARCODE_SCANNER_UPC_A_WITH_P5_OPTIONAL = $0A0; HID_USAGE_BARCODE_SCANNER_UPC_E = $0A1; HID_USAGE_BARCODE_SCANNER_UPC_E1 = $0A2; HID_USAGE_BARCODE_SCANNER_PERIODICAL = $0A9; HID_USAGE_BARCODE_SCANNER_PERIODICAL_AUTODISCRIMINATE_2 = $0AA; HID_USAGE_BARCODE_SCANNER_PERIODICAL_ONLY_DECODE_WITH_2 = $0AB; HID_USAGE_BARCODE_SCANNER_PERIODICAL_IGNORE_2 = $0AC; HID_USAGE_BARCODE_SCANNER_PERIODICAL_AUTODISCRIMINATE_5 = $0AD; HID_USAGE_BARCODE_SCANNER_PERIODICAL_ONLY_DECODE_WITH_5 = $0AE; HID_USAGE_BARCODE_SCANNER_PERIODICAL_IGNORE_5 = $0AF; HID_USAGE_BARCODE_SCANNER_CHECK = $0B0; HID_USAGE_BARCODE_SCANNER_CHECK_DISABLE_PRICE = $0B1; HID_USAGE_BARCODE_SCANNER_CHECK_ENABLE_4_DIGIT_PRICE = $0B2; HID_USAGE_BARCODE_SCANNER_CHECK_ENABLE_5_DIGIT_PRICE = $0B3; HID_USAGE_BARCODE_SCANNER_CHECK_ENABLE_EUROPEAN_4_DIGIT_PRICE = $0B4; HID_USAGE_BARCODE_SCANNER_CHECK_ENABLE_EUROPEAN_5_DIGIT_PRICE = $0B5; HID_USAGE_BARCODE_SCANNER_EAN_TWO_LABEL = $0B7; HID_USAGE_BARCODE_SCANNER_EAN_THREE_LABEL = $0B8; HID_USAGE_BARCODE_SCANNER_EAN_8_FLAG_DIGIT_1 = $0B9; HID_USAGE_BARCODE_SCANNER_EAN_8_FLAG_DIGIT_2 = $0BA; HID_USAGE_BARCODE_SCANNER_EAN_8_FLAG_DIGIT_3 = $0BB; HID_USAGE_BARCODE_SCANNER_EAN_13_FLAG_DIGIT_1 = $0BC; HID_USAGE_BARCODE_SCANNER_EAN_13_FLAG_DIGIT_2 = $0BD; HID_USAGE_BARCODE_SCANNER_EAN_13_FLAG_DIGIT_3 = $0BE; HID_USAGE_BARCODE_SCANNER_ADD_EAN_2_3_LABEL_DEFINITION = $0BF; HID_USAGE_BARCODE_SCANNER_CLEAR_ALL_EAN_2_3_LABEL_DEFINITIONS = $0C0; HID_USAGE_BARCODE_SCANNER_CODABAR = $0C3; HID_USAGE_BARCODE_SCANNER_CODE_128 = $0C4; HID_USAGE_BARCODE_SCANNER_CODE_39 = $0C7; HID_USAGE_BARCODE_SCANNER_CODE_93 = $0C8; HID_USAGE_BARCODE_SCANNER_FULL_ASCII_CONVERSION = $0C9; HID_USAGE_BARCODE_SCANNER_INTERLEAVED_2_OF_5 = $0CA; HID_USAGE_BARCODE_SCANNER_ITALIAN_PHARMACY_CODE = $0CB; HID_USAGE_BARCODE_SCANNER_MSI_PLESSEY = $0CC; HID_USAGE_BARCODE_SCANNER_STANDARD_2_OF_5_IATA = $0CD; HID_USAGE_BARCODE_SCANNER_STANDARD_2_OF_5 = $0CE; HID_USAGE_BARCODE_SCANNER_TRANSMIT_START_STOP = $0D3; HID_USAGE_BARCODE_SCANNER_TRI_OPTIC = $0D4; HID_USAGE_BARCODE_SCANNER_UCC_EAN_128 = $0D5; HID_USAGE_BARCODE_SCANNER_CHECK_DIGIT = $0D6; HID_USAGE_BARCODE_SCANNER_CD_DISABLE = $0D7; HID_USAGE_BARCODE_SCANNER_CD_ENABLE_INTERLEAVED_2_OF_5_OPCC = $0D8; HID_USAGE_BARCODE_SCANNER_CD_ENABLE_INTERLEAVED_2_OF_5_USS = $0D9; HID_USAGE_BARCODE_SCANNER_CD_ENABLE_STANDARD_2_OF_5_OPCC = $0DA; HID_USAGE_BARCODE_SCANNER_CD_ENABLE_STANDARD_2_OF_5_USS = $0DB; HID_USAGE_BARCODE_SCANNER_CD_ENABLE_ONE_MSI_PLESSEY = $0DC; HID_USAGE_BARCODE_SCANNER_CD_ENABLE_TWO_MSI_PLESSEY = $0DD; HID_USAGE_BARCODE_SCANNER_CD_CODABAR_ENABLE = $0DE; HID_USAGE_BARCODE_SCANNER_CD_CODE_39_ENABLE = $0DF; HID_USAGE_BARCODE_SCANNER_TRANSMIT_CHECK_DIGIT = $0F0; HID_USAGE_BARCODE_SCANNER_DISABLE_CHECK_DIGIT_TRANSMIT = $0F1; HID_USAGE_BARCODE_SCANNER_ENABLE_CHECK_DIGIT_TRANSMIT = $0F2; HID_USAGE_BARCODE_SCANNER_SYMBOLOGY_IDENTIFIER_1 = $0FB; HID_USAGE_BARCODE_SCANNER_SYMBOLOGY_IDENTIFIER_2 = $0FC; HID_USAGE_BARCODE_SCANNER_SYMBOLOGY_IDENTIFIER_3 = $0FD; HID_USAGE_BARCODE_SCANNER_DECODED_DATA = $0FE; HID_USAGE_BARCODE_SCANNER_DECODED_DATA_CONTINUED = $0FF; HID_USAGE_BARCODE_SCANNER_BAR_SPACE_DATA = $100; HID_USAGE_BARCODE_SCANNER_SCANNER_DATA_ACCURACY = $101; HID_USAGE_BARCODE_SCANNER_RAW_DATA_POLARITY = $102; HID_USAGE_BARCODE_SCANNER_POLARITY_INVERTED_BAR_CODE = $103; HID_USAGE_BARCODE_SCANNER_POLARITY_NORMAL_BAR_CODE = $104; HID_USAGE_BARCODE_SCANNER_MINIMUM_LENGTH_TO_DECODE = $106; HID_USAGE_BARCODE_SCANNER_MAXIMUM_LENGTH_TO_DECODE = $107; HID_USAGE_BARCODE_SCANNER_FIRST_DISCRETE_LENGTH_TO_DECODE = $108; HID_USAGE_BARCODE_SCANNER_SECOND_DISCRETE_LENGTH_TO_DECODE = $109; HID_USAGE_BARCODE_SCANNER_DATA_LENGTH_METHOD = $10A; HID_USAGE_BARCODE_SCANNER_DLM_READ_ANY = $10B; HID_USAGE_BARCODE_SCANNER_DLM_CHECK_IN_RANGE = $10C; HID_USAGE_BARCODE_SCANNER_DLM_CHECK_FOR_DISCRETE = $10D; HID_USAGE_BARCODE_SCANNER_AZTEC_CODE = $110; HID_USAGE_BARCODE_SCANNER_BC412 = $111; HID_USAGE_BARCODE_SCANNER_CHANNEL_CODE = $112; HID_USAGE_BARCODE_SCANNER_CODE_16 = $113; HID_USAGE_BARCODE_SCANNER_CODE_32 = $114; HID_USAGE_BARCODE_SCANNER_CODE_49 = $115; HID_USAGE_BARCODE_SCANNER_CODE_ONE = $116; HID_USAGE_BARCODE_SCANNER_COLORCODE = $117; HID_USAGE_BARCODE_SCANNER_DATA_MATRIX = $118; HID_USAGE_BARCODE_SCANNER_MAXICODE = $119; HID_USAGE_BARCODE_SCANNER_MICROPDF = $11A; HID_USAGE_BARCODE_SCANNER_PDF_417 = $11B; HID_USAGE_BARCODE_SCANNER_POSICODE = $11C; HID_USAGE_BARCODE_SCANNER_QR_CODE = $11D; HID_USAGE_BARCODE_SCANNER_SUPERCODE = $11E; HID_USAGE_BARCODE_SCANNER_ULTRACODE = $11F; HID_USAGE_BARCODE_SCANNER_USD_5 = $120; HID_USAGE_BARCODE_SCANNER_VERICODE = $121; // (rom) $122 to $FFFF are reserved in "HID Point of Sale Usage Tables 1.02" (pos1_02.pdf) // // Weighing Device Page (0x8D) // HID_USAGE_SCALE_UNDEFINED = $00; HID_USAGE_SCALE_WEIGHING_DEVICE = $01; HID_USAGE_SCALE_SCALE_DEVICE_CLASS = $20; HID_USAGE_SCALE_SCALE_CLASS_I_METRIC_CLASS = $21; HID_USAGE_SCALE_SCALE_CLASS_I_METRIC = $22; HID_USAGE_SCALE_SCALE_CLASS_II_METRIC = $23; HID_USAGE_SCALE_SCALE_CLASS_III_METRIC = $24; HID_USAGE_SCALE_SCALE_CLASS_IIIL_METRIC = $25; HID_USAGE_SCALE_SCALE_CLASS_IV_METRIC = $26; HID_USAGE_SCALE_SCALE_CLASS_III_ENGLISH = $27; HID_USAGE_SCALE_SCALE_CLASS_IIIL_ENGLISH = $28; HID_USAGE_SCALE_SCALE_CLASS_IV_ENGLISH = $29; HID_USAGE_SCALE_SCALE_CLASS_GENERIC = $2A; HID_USAGE_SCALE_SCALE_ATTRIBUTE_REPORT = $30; HID_USAGE_SCALE_SCALE_CONTROL_REPORT = $31; HID_USAGE_SCALE_SCALE_DATA_REPORT = $32; HID_USAGE_SCALE_SCALE_STATUS_REPORT = $33; HID_USAGE_SCALE_SCALE_WEIGHT_LIMIT_REPORT = $34; HID_USAGE_SCALE_SCALE_STATISTICS_REPORT = $35; HID_USAGE_SCALE_DATA_WEIGHT = $40; HID_USAGE_SCALE_DATA_SCALING = $41; HID_USAGE_SCALE_WEIGHT_UNIT_CLASS = $50; HID_USAGE_SCALE_WEIGHT_UNIT_MILLIGRAM = $51; HID_USAGE_SCALE_WEIGHT_UNIT_GRAM = $52; HID_USAGE_SCALE_WEIGHT_UNIT_KILOGRAM = $53; HID_USAGE_SCALE_WEIGHT_UNIT_CARATS = $54; HID_USAGE_SCALE_WEIGHT_UNIT_TAELS = $55; HID_USAGE_SCALE_WEIGHT_UNIT_GRAINS = $56; HID_USAGE_SCALE_WEIGHT_UNIT_PENNYWEIGHTS = $57; HID_USAGE_SCALE_WEIGHT_UNIT_METRIC_TON = $58; HID_USAGE_SCALE_WEIGHT_UNIT_AVOIR_TON = $59; HID_USAGE_SCALE_WEIGHT_UNIT_TROY_OUNCE = $5A; HID_USAGE_SCALE_WEIGHT_UNIT_OUNCE = $5B; HID_USAGE_SCALE_WEIGHT_UNIT_POUND = $5C; HID_USAGE_SCALE_CALIBRATION_COUNT = $60; HID_USAGE_SCALE_RE_ZERO_COUNT = $61; HID_USAGE_SCALE_SCALE_STATUS_CLASS = $70; HID_USAGE_SCALE_SCS_FAULT = $71; HID_USAGE_SCALE_SCS_STABLE_AT_CENTER_OF_ZERO = $72; HID_USAGE_SCALE_SCS_IN_MOTION = $73; HID_USAGE_SCALE_SCS_WEIGHT_STABLE = $74; HID_USAGE_SCALE_SCS_UNDER_ZERO = $75; HID_USAGE_SCALE_SCS_OVER_WEIGHT_LIMIT = $76; HID_USAGE_SCALE_SCS_REQUIRES_CALIBRATION = $77; HID_USAGE_SCALE_SCS_REQUIRES_REZEROING = $78; HID_USAGE_SCALE_ZERO_SCALE = $80; HID_USAGE_SCALE_ENFORCED_ZERO_RETURN = $81; // (rom) $82 to $FFFF are reserved in "HID Point of Sale Usage Tables 1.02" (pos1_02.pdf) // // Magnetic Stripe Reader Page (0x8E) // HID_USAGE_MSR_UNDEFINED = $00; HID_USAGE_MSR_MSR_DEVICE_READ_ONLY = $01; HID_USAGE_MSR_TRACK_1_LENGTH = $11; HID_USAGE_MSR_TRACK_2_LENGTH = $12; HID_USAGE_MSR_TRACK_3_LENGTH = $13; HID_USAGE_MSR_TRACK_JIS_LENGTH = $14; HID_USAGE_MSR_TRACK_DATA = $20; HID_USAGE_MSR_TRACK_1_DATA = $21; HID_USAGE_MSR_TRACK_2_DATA = $22; HID_USAGE_MSR_TRACK_3_DATA = $23; HID_USAGE_MSR_TRACK_JIS_DATA = $24; // (rom) $25 to $FFFF are reserved in ""HID Point of Sale Usage Tables 1.02" (pos1_02.pdf) implementation end.
unit tabManagerPanel; interface uses classes, Vcl.Controls,Vcl.ExtCtrls, Forms, System.SysUtils, Windows, vkvariable, AtTabs, Winapi.Messages, System.Math, FrameTab; type // TFrameClass = class of TFrame; TTabManagerPanel = class(TPanel) private FFrameTabs: TATTabs; bInit: Boolean; function CreateFrameDoc(AFrameDocClass: TTabFrameClass): TTabFrame; procedure MyOnTabMove(Sender: TObject; NFrom, NTo: Integer); procedure MyOnTabClose(Sender: TObject; ATabIndex: Integer; var ACanClose, ACanContinue: Boolean); procedure MyOnTabClick(Sender: TObject); procedure SetVisible(AFrame: TTabFrame); public constructor create(aOwner: TComponent);override; procedure ShowTab(const AFrameDocClassName: String; AParams:TVkVariableCollection = nil); // procedure ShowDocument(AFrameDocClass: TDocFrameClass); end; implementation { TDocManagerPanel } var glId: Integer = 0; constructor TTabManagerPanel.create(aOwner: TComponent); begin inherited create(aOwner); Caption := ''; Align := alClient; FFrameTabs := TAtTabs(aOwner.FindComponent('MainTabs')); if not Assigned(FFrameTabs) then begin FFrameTabs := TATTabs.Create(AOwner); FFrameTabs.parent := TWinControl(AOwner); FFrameTabs.Align := alTop; end; FFrameTabs.OnTabMove := MyOnTabMove; FFrameTabs.OnTabClose := MyOnTabClose; FFrameTabs.OnTabClick := MyOnTabClick; end; procedure TTabManagerPanel.MyOnTabClick(Sender: TObject); var frm1: TTabFrame; i: Integer; begin if not bInit then begin frm1 := TTabFrame(FFrameTabs.GetTabData(FFrameTabs.TabIndex).TabObject); if Assigned(frm1) then if not frm1.Visible then SetVisible(frm1); end; end; procedure TTabManagerPanel.ShowTab(const AFrameDocClassName: String; AParams:TVkVariableCollection); var _FrameDocClass : TTabFrameClass; docFrame : TTabFrame; i: Integer; //control: TWinControl; begin _FrameDocClass := TTabFrameClass(FindClass(AFrameDocClassName)); for I := 0 to FFrameTabs.Tabs.Count-1 do begin docFrame := TTabFrame(FFrameTabs.GetTabData(i).TabObject); if Assigned(docFrame) then begin if (docFrame.ClassType = _FrameDocClass) and (docFrame.IsEqualParams(AParams)) then begin SetVisible(docFrame); exit; end; end; end; docFrame := CreateFrameDoc(_FrameDocClass); docFrame.CheckParams(AParams); //control := docFrame.getActiveControl; FFrameTabs.AddTab(FFrameTabs.TabCount,docFrame.GetCaption, docFrame); {if (Assigned(control) and control.visible and control.Enabled) then try // PostMessage(WM_SETFOCUS,control.Handle,0,0); TForm(Owner).ActiveControl := control; except end;} // if (Assigned(AParams)) then // docFrame.checkParams(AParams); end; {*procedure TDocManagerPanel.ShowDocument(AFrameDocClass: TDocFrameClass); begin // FPrepare := bPrepare; try Inc(glId); //inherited Create(AOwner); //if name='' then // name := 'FmCustomUibDoc' + IntToStr(glId) //else // name := name + IntToStr(glId); //FDmMain := MainDm; //FFrameDocClass := AFrameDocClass; var docFrame := CreateFrameDoc(AFrameDocClass); TForm(Owner).ActiveControl := docFrame.DBGridEhVkDoc; doc finally // FPrepare := False; end; end;} function TTabManagerPanel.CreateFrameDoc(AFrameDocClass: TTabFrameClass): TTabFrame; // var _dmDoc: TDocDm; begin // _dmDoc := AFrameDocClass.GetDmDoc; //.Create(FDmMain); Result := AFrameDocClass.Create(self, nil); Result.Name := Result.Name+'_'+IntToStr(GetTickCount); Result.Parent := self; Result.Align := alClient; Result.ParentForm := TForm(self.Owner); Result.InitActionManager(Result.ParentForm); //FFrameDoc.Prepare := FPrepare; //Caption := FFrameDoc.GetCaption; end; procedure TTabManagerPanel.MyOnTabMove(Sender: TObject; NFrom, NTo: Integer); var _DocFrame: TTabFrame; begin if (NTo>-1) and not bInit then begin _DocFrame := TTabFrame(FFrameTabs.GetTabData(NTo).TabObject); SetVisible(_DocFrame); end; end; procedure TTabManagerPanel.SetVisible(AFrame: TTabFrame); var frm: TTabFrame; i: Integer; begin for I := 0 to FFrameTabs.TabCount-1 do begin frm := TTabFrame(FFrameTabs.GetTabData(i).TabObject); if Assigned(frm) then begin frm.Visible := frm = AFrame; if frm.Visible then begin //StatusBar1.Panels[0].Text := frm.GetFileName; //--- frm.SynEdit1.CaretX :=1; // frm.SynEdit1.CaretY :=1; // TForm(Owner).ActiveControl := frm.GetActiveControl; if FFrameTabs.TabIndex <> i then FFrameTabs.TabIndex := i; PostMessage(WM_SETFOCUS,frm.GetActiveControl.Handle,0,0); end; end; end; end; procedure TTabManagerPanel.MyOnTabClose(Sender: TObject; ATabIndex: Integer; var ACanClose, ACanContinue: Boolean); var frm: TTabFrame; NewIndex: Integer; begin frm := TTabFrame(FFrameTabs.GetTabData(ATabIndex).TabObject); if Assigned(frm) then begin frm.Visible := False; frm.Free; if FFrameTabs.TabCount>1 then begin NewIndex := ifThen(ATabIndex > 0, ATabIndex-1,1); frm := TTabFrame(FFrameTabs.GetTabData(NewIndex).TabObject); end; end; end; end.
program Begin16; var x1,x2,a : integer; begin writeln('Enter first coordinate point: '); readln(x1); writeln('Enter second coordinate point: '); readln(x2); a:=abs(x1-x2); writeln('Distance points: ',a); end.
unit ServerMethods; interface uses System.SysUtils, System.Classes, System.Json, Datasnap.DSServer, Datasnap.DSAuth, System.IOUtils, System.Hash; type {$METHODINFO ON} TMetodos = class(TDataModule) private { Var privates } public { Public example declarations } function EchoString(Value: string): string; function ReverseString(Value: string): string; { } function sIniciarSesion(pAuthorization, pUser, pContrasena: String): String; { Examples } function Datos(pAuthorization, pValue, pParams: String): TJSONArray; function UpdateDatos(pAuthorization, pTable: String; LJsonObjet: TJSONObject): Boolean; function CancelDatos(pAuthorization, pValue: String): Boolean; function AcceptDatos(pAuthorization, pTable: String; LJsonObjet: TJSONObject): Boolean; { Web properties } end; {$METHODINFO OFF} implementation {$R *.dfm} uses System.StrUtils, uAutorizacion, USesion; function TMetodos.AcceptDatos(pAuthorization, pTable: String; LJsonObjet: TJSONObject): Boolean; var i: Integer; CadenaFields: String; CadenaValues: String; begin Result := False; CadenaFields := ''; CadenaValues := ''; try try if true then begin if true then begin if LJsonObjet.Count > 0 then begin for i := 0 to LJsonObjet.Count - 1 do begin CadenaFields := CadenaFields + LJsonObjet.Pairs[i] .JsonString.Value; CadenaValues := CadenaValues + QuotedStr(LJsonObjet.Pairs[i].JsonValue.Value); if i <> LJsonObjet.Count - 1 then begin CadenaFields := CadenaFields + ','; CadenaValues := CadenaValues + ','; end; end; { sqlQuery.Close; sqlQuery.SQL.Clear; sqlQuery.SQL.Add('INSERT INTO ' + pTable + '(' + CadenaFields + ')' + 'values(' + CadenaValues + ')'); sqlQuery.ExecSQL; ConfirmarConexion; if sqlQuery.RowsAffected > 0 then Result := True; } end; end; end; except on E: Exception do end; finally end; end; function TMetodos.CancelDatos(pAuthorization, pValue: String): Boolean; begin Result := False; try if true then begin if true then begin try { sqlQuery.Close; sqlQuery.SQL.Clear; sqlQuery.SQL.Add(pValue); sqlQuery.ExecSQL; ConfirmarConexion; if sqlQuery.RowsAffected > 0 then Result := True; } except on E: Exception do end; end; end; finally end; end; function TMetodos.Datos(pAuthorization, pValue, pParams: String): TJSONArray; var i: Integer; FJsonObject: TJSONObject; begin try if true then begin if true then begin Result := TJSONArray.Create; try { sqlQuery.Close; sqlQuery.SQL.Clear; sqlQuery.SQL.Add('Select * from ' + pValue + ' where 1=1 ' + pParams); sqlQuery.Open; sqlQuery.First; while not sqlQuery.Eof do begin FJsonObject := TJSONObject.Create; for i := 0 to sqlQuery.FieldCount - 1 do begin FJsonObject.AddPair(sqlQuery.Fields[i].FullName, sqlQuery.Fields[i].AsString); end; Result.AddElement(FJsonObject); sqlQuery.Next; end; } except on E: Exception do begin Result.Add(E.Message); end; end; end; end; finally end; end; function TMetodos.EchoString(Value: string): string; begin Result := GenerarToken; end; function TMetodos.sIniciarSesion(pAuthorization, pUser, pContrasena: String): String; begin if IniciarSesion(pAuthorization, pUser, pContrasena) then begin Result := AsignarContrasena(pUser); end; end; function TMetodos.ReverseString(Value: string): string; begin Result := EncriptarContrasena(Value); end; function TMetodos.UpdateDatos(pAuthorization, pTable: String; LJsonObjet: TJSONObject): Boolean; var i: Integer; Cadena: String; Llave: String; Valor: String; begin Result := False; Cadena := ''; try try if true then begin if true then begin if LJsonObjet.Count > 0 then begin for i := 0 to LJsonObjet.Count - 1 do begin if LJsonObjet.Pairs[i].JsonString.Value = 'key' then Llave := LJsonObjet.Pairs[i].JsonValue.Value else if LJsonObjet.Pairs[i].JsonString.Value = 'value' then Valor := LJsonObjet.Pairs[i].JsonValue.Value else begin Cadena := Cadena + LJsonObjet.Pairs[i].JsonString.Value + '=' + LJsonObjet.Pairs[i].JsonValue.Value; if i <> LJsonObjet.Count - 1 then Cadena := Cadena + ','; end; end; { sqlQuery.Close; sqlQuery.SQL.Clear; sqlQuery.SQL.Add('UPDATE ' + pTable + ' SET ' + Cadena + ' WHERE ' + Llave + '=' + Valor); sqlQuery.ExecSQL; ConfirmarConexion; if sqlQuery.RowsAffected > 0 then Result := True; } end; end; end; except on E: Exception do end; finally end; end; end.
unit wordpress_nggallery_model; {$mode objfpc}{$H+} interface uses database_lib, fpTemplate, Classes, SysUtils; type { TWPNGGallery } TWPNGGallery = class(TSimpleModel) private FBaseURL: string; FPath: string; procedure ngTagController(Sender: TObject; const TagString: string; TagParams: TStringList; Out ReplaceText: string); public constructor Create(const DefaultTableName: string = ''); destructor Destroy; override; property Path: string read FPath write FPath; property BaseURL: string read FBaseURL write FBaseURL; function Render(const Content: string): string; end; var WPNGGallery: TWPNGGallery; implementation uses common, fastplaz_handler, logutil_lib, theme_controller; { TWPNGGallery } procedure TWPNGGallery.ngTagController(Sender: TObject; const TagString: string; TagParams: TStringList; out ReplaceText: string); var tags: TStrings; id, src: string; begin tags := Explode(TagString, ' '); if tags.Count = 0 then begin FreeAndNil(tags); Exit; end; case tags[0] of 'singlepic': begin id := tags.Values['id']; AddJoin('ngg_gallery', 'gid', 'galleryid', ['path']); FindFirst([AppData.tablePrefix + '_ngg_pictures.pid=' + id], '', 'filename,alttext'); if Data.RecordCount > 0 then begin src := BaseURL + FPath + '/' + Value['path'].AsString + '/' + Value['filename'].AsString; ReplaceText := '<div><img src="' + src + '"'; if tags.Values['w'] <> '' then ReplaceText := ReplaceText + ' width="' + tags.Values['w']; if tags.Values['h'] <> '' then ReplaceText := ReplaceText + ' height="' + tags.Values['h']; if tags.Values['float'] <> '' then ReplaceText := ReplaceText + ' class="ngg-singlepic float_' + tags.Values['float'] + '"'; ReplaceText := ReplaceText + ' alt="' + Value['alttext'].AsString + '"'; ReplaceText := ReplaceText + ' title="' + Value['alttext'].AsString + '"'; ReplaceText := ReplaceText + '></div>'; end; end; end; end; constructor TWPNGGallery.Create(const DefaultTableName: string); begin inherited Create('ngg_pictures'); Path := Config.GetValue('wordpress/path', ''); BaseURL := Config.GetValue('wordpress/base_url', ''); if BaseURL = '' then begin BaseURL := 'http://' + GetEnvironmentVariable('SERVER_NAME'); end; end; destructor TWPNGGallery.Destroy; begin inherited Destroy; end; function TWPNGGallery.Render(const Content: string): string; var template: TFPTemplate; begin Result := Content; template := TFPTemplate.Create; template.Template := Content; template.AllowTagParams := True; template.StartDelimiter := '['; template.EndDelimiter := ']'; template.ParamValueSeparator := '='; template.OnReplaceTag := @ngTagController; Result := template.GetContent; FreeAndNil(template); end; initialization //WPNGGallery:= TWPNGGallery.Create; finalization //FreeAndNil( WPNGGallery); end.
{***************************************************************************} {***************************************************************************} { } { Command Line Parser } { Copyright (C) 2021 Wuping Xin } { } { Based on VSoft.CommandLine } { Copyright (C) 2014 Vincent Parrett } { vincent@finalbuilder.com } { http://www.finalbuilder.com } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit CmdLineParserTests.TestObject; interface uses DUnitX.TestFramework, CmdLineParser; type TExampleEnum = (enOne, enTwo, enThree); TExampleSet = set of TExampleEnum; [TestFixture] TCmdLineParserTests = class public {$REGION 'Setup and Teardown'} [Setup] procedure Setup; [TearDown] procedure TearDown; {$ENDREGION} [Test] procedure Can_Parse_ColonEqualNameValueSeparator; [Test] procedure Can_Parse_Enum_Parameter; [Test] procedure Can_Parse_EqualNameValueSeparator; [Test] procedure Can_Parse_Multiple_Anonymous_Parameters; [Test] procedure Can_Parse_Quoted_Value; [Test] procedure Can_Parse_Set_Parameter; [Test] procedure Can_Parse_Anonymous_Parameter; [Test] procedure Can_Register_Anonymous_Parameter; [Test] procedure Test_Single_Option; [Test] procedure Will_Generate_Error_For_Extra_Unamed_Parameter; [Test] procedure Will_Generate_Error_For_Invalid_Enum; [Test] procedure Will_Generate_Error_For_Invalid_Set; [Test] procedure Will_Generate_Error_For_Missing_Value; [Test] procedure Will_Generate_Error_For_Unknown_Option; [Test] procedure Will_Raise_For_Missing_Param_File; [Test] procedure Will_Raise_On_Registering_Duplicate_Options; [Test] procedure Will_Raise_On_Registering_Anonymous_Option; [Test] procedure Can_Parse_Command_Options; end; implementation uses System.Classes; procedure TCmdLineParserTests.Can_Parse_ColonEqualNameValueSeparator; var LTestStr: String; begin TOptionsRegistry.RegisterOption<string>('test', 't', procedure(const aValue: String) begin LTestStr := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('--test:=hello'); try TOptionsRegistry.NameValueSeparator := ':='; TOptionsRegistry.Parse(LCmdline); finally LCmdline.Free; end; Assert.AreEqual('hello', LTestStr); end; procedure TCmdLineParserTests.Can_Parse_Enum_Parameter; var LTestEnum: TExampleEnum; begin TOptionsRegistry.RegisterOption<TExampleEnum>('test', 't', procedure(const aValue: TExampleEnum) begin LTestEnum := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('--test:enTwo'); try TOptionsRegistry.NameValueSeparator := ':'; var LParseResult := TOptionsRegistry.Parse(LCmdline); Assert.IsFalse(LParseResult.HasErrors); Assert.AreEqual<TExampleEnum>(TExampleEnum.enTwo, LTestEnum); finally LCmdline.Free; end end; procedure TCmdLineParserTests.Can_Parse_EqualNameValueSeparator; var LTestStr: String; begin TOptionsRegistry.RegisterOption<string>('test', 't', procedure(const aValue: String) begin LTestStr := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('--test=hello'); try TOptionsRegistry.NameValueSeparator := '='; TOptionsRegistry.Parse(LCmdline); finally LCmdline.Free; end; Assert.AreEqual('hello', LTestStr); end; procedure TCmdLineParserTests.Can_Parse_Multiple_Anonymous_Parameters; var LFileName_1, LFileName_2: String; LTestBool: Boolean; begin TOptionsRegistry.RegisterAnonymousOption<string> ('the file we want to process', procedure(const aValue: String) begin LFileName_1 := aValue; end); TOptionsRegistry.RegisterAnonymousOption<string> ('the second file we want to process', procedure(const aValue: String) begin LFileName_2 := aValue; end); var LOption := TOptionsRegistry.RegisterOption<Boolean>('test', 't', procedure(const aValue: Boolean) begin LTestBool := aValue; end); LOption.RequiresValue:= False; var LCmdline := TStringList.Create; LCmdline.Add('c:\file1.txt'); LCmdline.Add('--test'); LCmdline.Add('c:\file2.txt'); try var LParseResult := TOptionsRegistry.Parse(LCmdline); Assert.IsFalse(LParseResult.HasErrors); Assert.AreEqual('c:\file1.txt', LFileName_1); Assert.AreEqual('c:\file2.txt', LFileName_2); finally LCmdline.Free; end end; procedure TCmdLineParserTests.Can_Parse_Quoted_Value; var LTestStr_1, LTestStr_2: String; begin TOptionsRegistry.RegisterOption<string>('test', 't', procedure(const aValue: String) begin LTestStr_1 := aValue; end); TOptionsRegistry.RegisterOption<string>('test2', 't2', procedure(const aValue: String) begin LTestStr_2 := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('--test:"hello world"'); LCmdline.Add('--test2:''hello world'''); try TOptionsRegistry.NameValueSeparator := ':'; TOptionsRegistry.Parse(LCmdline); finally LCmdline.Free; end; Assert.AreEqual('hello world', LTestStr_1); Assert.AreEqual('hello world', LTestStr_2); end; procedure TCmdLineParserTests.Can_Parse_Set_Parameter; var LTestSet: TExampleSet; begin TOptionsRegistry.RegisterOption<TExampleSet>('test', 't', procedure(const aValue: TExampleSet) begin LTestSet := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('--test:[enOne,enThree]'); try var LParseResult := TOptionsRegistry.Parse(LCmdline); Assert.IsFalse(LParseResult.HasErrors); Assert.AreEqual<TExampleSet>(LTestSet, [enOne, enThree]); finally LCmdline.Free; end end; procedure TCmdLineParserTests.Can_Parse_Anonymous_Parameter; var LTestStr: String; begin TOptionsRegistry.RegisterAnonymousOption<string> ('the file we want to process', procedure(const aValue: String) begin LTestStr := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('c:\test.txt'); try TOptionsRegistry.Parse(LCmdline); finally LCmdline.Free; end; Assert.AreEqual('c:\test.txt', LTestStr); end; procedure TCmdLineParserTests.Can_Parse_Command_Options; var LTestEnum: TExampleEnum; LTestBool: Boolean; begin TOptionsRegistry .RegisterCommand('test','t','Test Command', 'Test [Options]','Test Usage') .RegisterOption<TExampleEnum>('verbose', 'v', procedure(const aValue: TExampleEnum) begin LTestEnum := aValue; end); // Global options that go with the default command. TOptionsRegistry.RegisterOption<Boolean>('autosave', 'as', procedure(const aValue: Boolean) begin LTestBool := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('-as:true'); // Appear the first time, it goes by the global check. LCmdline.Add('test'); // The registered command, current command now swap to it from default command. LCmdline.Add('-v:enTwo'); // The command has no option named "as" registered. So the search will look up the global options. LCmdline.Add('-as:false'); // Appear the second time, it goes by current command check first, if fails, then global check. try TOptionsRegistry.NameValueSeparator := ':'; var LParseResult := TOptionsRegistry.Parse(LCmdline); WriteLn(LParseResult.ErrorText); Assert.IsFalse(LParseResult.HasErrors); // LTestBool was first set to True, then the second time it was set to False. This is // because -as appeared twice in the command line. Assert.IsFalse(LTestBool); Assert.AreEqual<TExampleEnum>(enTwo, LTestEnum); finally LCmdline.Free; end end; procedure TCmdLineParserTests.Can_Register_Anonymous_Parameter; begin var LOption := TOptionsRegistry.RegisterAnonymousOption<string>('the file we want to process', procedure(const value: String) begin end); Assert.IsTrue(LOption.IsAnonymous); end; procedure TCmdLineParserTests.Setup; begin TOptionsRegistry.Clear; end; procedure TCmdLineParserTests.TearDown; begin TOptionsRegistry.Clear; end; procedure TCmdLineParserTests.Test_Single_Option; var TTestBool: Boolean; begin var LOption := TOptionsRegistry.RegisterOption<Boolean>('test', 't', procedure(const aValue: Boolean) begin TTestBool := aValue; end); LOption.RequiresValue := False; var LCmdline := TStringList.Create; LCmdline.Add('--test'); try TOptionsRegistry.Parse(LCmdline); finally LCmdline.Free; end; Assert.IsTrue(TTestBool); end; procedure TCmdLineParserTests.Will_Generate_Error_For_Extra_Unamed_Parameter; var LFileName, LTestStr: String; begin TOptionsRegistry.RegisterAnonymousOption<string> ('the file we want to process', procedure(const aValue: String) begin LFileName := aValue; end); TOptionsRegistry.RegisterOption<string>('test', 't', procedure(const aValue: String) begin LTestStr := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('c:\file1.txt'); LCmdline.Add('--test:hello'); LCmdline.Add('c:\file2.txt'); try var LParseResult := TOptionsRegistry.Parse(LCmdline); WriteLn(LParseResult.ErrorText); Assert.IsTrue(LParseResult.HasErrors); Assert.AreEqual('c:\file1.txt', LFileName); Assert.AreEqual('hello', LTestStr) finally LCmdline.Free; end end; procedure TCmdLineParserTests.Will_Generate_Error_For_Invalid_Enum; var LTestEnum: TExampleEnum; begin TOptionsRegistry.RegisterOption<TExampleEnum>('test', 't', procedure(const aValue: TExampleEnum) begin LTestEnum := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('--test:enbBlah'); try var LParseResult := TOptionsRegistry.Parse(LCmdline); WriteLn(LParseResult.ErrorText); Assert.IsTrue(LParseResult.HasErrors); finally LCmdline.Free; end; end; procedure TCmdLineParserTests.Will_Generate_Error_For_Invalid_Set; var LTestSet: TExampleSet; begin TOptionsRegistry.RegisterOption<TExampleSet>('test', 't', procedure(const aValue: TExampleSet) begin LTestSet := aValue; end); var LCmdline := TStringList.Create; LCmdline.Add('--test:[enOne,enFoo]'); try var LParseResult := TOptionsRegistry.Parse(LCmdline); WriteLn(LParseResult.ErrorText); Assert.IsTrue(LParseResult.HasErrors); finally LCmdline.Free; end; end; procedure TCmdLineParserTests.Will_Generate_Error_For_Missing_Value; var LTestBool: Boolean; begin var LOption := TOptionsRegistry.RegisterOption<Boolean>('test', 't', procedure(const aValue: Boolean) begin LTestBool := aValue; end); LOption.RequiresValue := True; var LCmdline := TStringList.Create; LCmdline.Add('--test'); try var LParseResult := TOptionsRegistry.Parse(LCmdline); WriteLn(LParseResult.ErrorText); Assert.IsTrue(LParseResult.HasErrors); finally LCmdline.Free; end; end; procedure TCmdLineParserTests.Will_Generate_Error_For_Unknown_Option; begin var LCmdline := TStringList.Create; LCmdline.Add('--blah'); try var LParseResult := TOptionsRegistry.Parse(LCmdline); WriteLn(LParseResult.ErrorText); Assert.IsTrue(LParseResult.HasErrors); finally LCmdline.Free; end; end; procedure TCmdLineParserTests.Will_Raise_For_Missing_Param_File; begin var LOption := TOptionsRegistry.RegisterOption<Boolean>('options', 'o', nil); LOption.IsOptionFile := True; // Set IsOptionFile True var LCmdline := TStringList.Create; LCmdline.Add('--options:"x:\blah blah.txt"'); try var LParseResult := TOptionsRegistry.Parse(LCmdline); WriteLn(LParseResult.ErrorText); Assert.IsTrue(LParseResult.HasErrors); finally LCmdline.Free; end; end; procedure TCmdLineParserTests.Will_Raise_On_Registering_Duplicate_Options; var LTestBool: Boolean; begin // same long names Assert.WillRaise( procedure begin TOptionsRegistry.RegisterOption<Boolean>('test', 't', procedure(const aValue: Boolean) begin LTestBool := aValue; end); TOptionsRegistry.RegisterOption<Boolean>('test', 't', procedure(const aValue: Boolean) begin LTestBool := aValue; end); end); // same short names Assert.WillRaise( procedure begin TOptionsRegistry.RegisterOption<Boolean>('test', 't', procedure(const aValue: Boolean) begin LTestBool := aValue; end); TOptionsRegistry.RegisterOption<Boolean>('t', 'blah', procedure(const aValue: Boolean) begin LTestBool := aValue; end); end); end; procedure TCmdLineParserTests.Will_Raise_On_Registering_Anonymous_Option; begin // same long names Assert.WillRaise( procedure begin TOptionsRegistry.RegisterOption<Boolean>('', 't', procedure(const aValue: Boolean) begin // end); end); end; initialization TDUnitX.RegisterTestFixture(TCmdLineParserTests); end.
// My own search, written 131210 while replacing TXN // Small parts remain from SearchBuf {@mode delphi} unit BetterFindUnit; interface function MyFind(buf: AnsiString; searchString: AnsiString; aStart,endchar: Longint; findBackwards, ignoreCase, wholeWords: Boolean) : Longint; implementation // Stolen from strutils.pp const { Default word delimiters are any character except the core alphanumerics. } WordDelimiters: set of Char = [#0..#255] - ['a'..'z','A'..'Z','1'..'9','0']; type TEqualFunction = function (const a,b : char) : boolean; function EqualWithCase (const a,b : char) : boolean; begin EqualWithCase := (a = b); end; function EqualWithoutCase (const a,b : char) : boolean; begin EqualWithoutCase := (LowerCase(a) = LowerCase(b)); end; function MyFind(buf: AnsiString; searchString: AnsiString; aStart,endchar: Longint; findBackwards, ignoreCase, wholeWords: Boolean) : Longint; var found: Boolean; s, c: Longint; equal: TEqualFunction; function IsWholeWord (wordstart, wordend: Longint): Boolean; begin // Check start IsWholeWord := ((wordstart = 1) or (buf[wordstart-1] in worddelimiters)) and // Check end ((wordend = Length(buf)) or (buf[wordend+1] in worddelimiters)); end; begin if not ignoreCase then equal := EqualWithCase else equal := EqualWithoutCase; if not findBackwards then begin if endchar = 0 then endchar := Length(buf); for c := aStart to endchar-Length(searchString)+1 do begin found := true; for s := 1 to Length(searchString) do begin if not equal(buf[c + s - 1], searchString[s]) then begin found := false; Break; end; end; if found = true then begin if not wholeWords then begin MyFind := c; // WriteLn('Found "', Copy(buf, c, Length(searchString)), '" at ', c); Exit(MyFind); end else if IsWholeWord(c, c+Length(searchString)-1) then begin MyFind := c; // WriteLn('Found whole word "', Copy(buf, c, Length(searchString)), '" at ', c); Exit(MyFind); end; end; end; end else begin // bw if endchar = 0 then endchar := 1; for c := aStart-Length(searchString) downto endchar do begin found := true; for s := 1 to Length(searchString) do begin if not equal(buf[c + s - 1], searchString[s]) then begin found := false; Break; end; end; if found = true then begin if not wholeWords then begin MyFind := c; // WriteLn('Found "', Copy(buf, c, Length(searchString)), '" at ', c); Exit(MyFind); end else if IsWholeWord(c, c+Length(searchString)-1) then begin MyFind := c; // WriteLn('Found whole word "', Copy(buf, c, Length(searchString)), '" at ', c); Exit(MyFind); end; end; end; end; MyFind := -1; WriteLn('Did not find "', searchString, '"'); end; end.
unit UDicionario; interface uses Classes; type TCustomDicionario = class(TComponent) private FValores: TStringList; FSignificados: TStringList; procedure AdicionaAtributosA; procedure AdicionaAtributosB; procedure AdicionaAtributosC; procedure AdicionaAtributosDEFGH; procedure AdicionaAtributosIJKLM; procedure AdicionaAtributosNOPQ; procedure AdicionaAtributosRSTU; procedure AdicionaAtributosVWXYZ; procedure AdicionaTabelas; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Inicializa; virtual; published property Significados: TStringList read FSignificados write FSignificados; property Valores: TStringList read FValores write FValores; procedure Adiciona(const Valor, Significado: string); function Significado(const Valor: string): string; function Valor(const Significado: string): string; end; TDicionario = class(TCustomDicionario) public procedure Inicializa; override; end; var Dicionario: TDicionario; implementation uses SysUtils, UStringFunctions; { TDicionario } procedure TDicionario.Inicializa; begin inherited; AdicionaAtributosA; AdicionaAtributosB; AdicionaAtributosC; AdicionaAtributosDEFGH; AdicionaAtributosIJKLM; AdicionaAtributosNOPQ; AdicionaAtributosRSTU; AdicionaAtributosVWXYZ; AdicionaTabelas; end; { TCustomDicionario } procedure TCustomDicionario.AdicionaAtributosA; begin Self.Adiciona('AbeAutLanIcmIpi', 'LancaAutomaticamenteIPIICMSNotaFiscal'); Self.Adiciona('AbeFecAtuPer', 'AbertoFechadoAtual'); Self.Adiciona('AcrAgeNocOco', 'AcrescimoAgenteNocivoOcorrencia'); Self.Adiciona('AcrEscSimpPre', 'AlterarAliquotaSimplesCalculoApuracao'); Self.Adiciona('AcrPerRecBruPre', 'AcrescimoReceitaBrutaPreferenciaEscrita'); Self.Adiciona('AdmFunClu', 'AdministradoraFundosClubes'); Self.Adiciona('AgeRegInf', 'AgenteReguladoInformante'); Self.Adiciona('AgpCslIrpMatPreEsc', 'AgrupaCSLLIRPJMatriz'); Self.Adiciona('AgrLanImpCntMat', 'AgrupaLancamentosImportacaoNaContaDaMatriz'); Self.Adiciona('AgrLanPad', 'AgrupaLancamentoPadrao'); Self.Adiciona('AgrPisCofMatPreEsc', 'AgrupaPISCOFINSMatriz'); Self.Adiciona('AgrSerSubSerStgPreEsc', 'AgrupaSerieSubSeriePreferenciaEscrita'); Self.Adiciona('AliBseCslVar', 'AliquotaBaseCSLLVariavelPreferenciaEscrita'); Self.Adiciona('AliCof', 'AliquotaCofins'); Self.Adiciona('ALICOF', 'AliquotaCOFINS'); Self.Adiciona('AliCofEntEtq', 'AliquotaCOFINSEntradaEstoque'); Self.Adiciona('AliCofEtq', 'AliquotaCOFINSSaidaEstoque'); Self.Adiciona('AliCofFaiVlrSplNac', 'AliquotaCOFINSFaixaValorSimplesNacional2009'); Self.Adiciona('ALICOFIMPFED', 'AliquotaCOFINSImpostoFederal'); Self.Adiciona('AliCppFaiVlrSplNac', 'AliquotaCPPFaixaValorSimplesNacional2009'); Self.Adiciona('AliCreOutPreEsc', 'AliquotaCreditoOutorgadoPreferenciaEscrita'); Self.Adiciona('AliCslFaiVlrSplNac', 'AliquotaCSLLFaixaValorSimplesNacional2009'); Self.Adiciona('ALICSLIMPFED', 'AliquotaCSLImpostoFederal'); Self.Adiciona('AliEmpTri', 'Aliquota'); Self.Adiciona('AliFai001FaiVlrFatRSeSplNac', 'AliquotaFaixa001FaixaValorFatorRSimplesNacional2009'); Self.Adiciona('AliFai002FaiVlrFatRSeSplNac', 'AliquotaFaixa002FaixaValorFatorRSimplesNacional2009'); Self.Adiciona('AliFai003FaiVlrFatRSeSplNac', 'AliquotaFaixa003FaixaValorFatorRSimplesNacional2009'); Self.Adiciona('AliFai004FaiVlrFatRSeSplNac', 'AliquotaFaixa004FaixaValorFatorRSimplesNacional2009'); Self.Adiciona('AliFai005FaiVlrFatRSeSplNac', 'AliquotaFaixa005FaixaValorFatorRSimplesNacional2009'); Self.Adiciona('AliFai006FaiVlrFatRSeSplNac', 'AliquotaFaixa006FaixaValorFatorRSimplesNacional2009'); Self.Adiciona('AliFai007FaiVlrFatRSeSplNac', 'AliquotaFaixa007FaixaValorFatorRSimplesNacional2009'); Self.Adiciona('AliFai008FaiVlrFatRSeSplNac', 'AliquotaFaixa008FaixaValorFatorRSimplesNacional2009'); Self.Adiciona('AliFun', 'AliquotaFunrural'); Self.Adiciona('ALIICM', 'AliquotaIcms'); Self.Adiciona('AliIcmOri', 'AliquotaIcmsOrigem'); Self.Adiciona('AliIcmDpiMovCodFis', 'AliquotaICMSDPI'); Self.Adiciona('AliIcmFaiVlrSplNac', 'AliquotaICMSFaixaValorSimplesNacional2009'); Self.Adiciona('AliInfAdiMajSplNac', 'AliquotaInformacaoAdicionalMajorado'); Self.Adiciona('AliInfAdiSplNac', 'AliquotaInformacaoAdicional'); Self.Adiciona('AliInsAutFpa', 'AliquotaINSSAutonomoFPAS'); Self.Adiciona('AliInsFolPagFpa', 'AliquotaINSSFolhaPagamentoFPAS'); Self.Adiciona('AliInsProLabFpa', 'AliquotaINSSProLaboreFPAS'); Self.Adiciona('AliIntPreEsc', 'AliquotaInternaProtege'); Self.Adiciona('AliIntSai', 'AliquotaInternaICMS'); Self.Adiciona('AliIpi', 'AliquotaIpi'); Self.Adiciona('AliIpiFaiVlrSplNac', 'AliquotaIPIFaixaValorSimplesNacional2009'); Self.Adiciona('AliIrpFaiVlrSplNac', 'AliquotaIRPJFaixaValorSimplesNacional2009'); Self.Adiciona('ALIIRPIMPSFED', 'AliquotaIRPJImpostoFederal'); Self.Adiciona('AliIssEmpEsc', 'AliquotaISSEmpresaEscrita'); Self.Adiciona('AliIssFaiVlrSplNac', 'AliquotaISSFaixaValorSimplesNacional2009'); Self.Adiciona('AliPadSerValTri', 'AliquotaPadrao'); Self.Adiciona('AliPis', 'AliquotaPis'); Self.Adiciona('ALIPIS', 'AliquotaPIS'); Self.Adiciona('AliPisEntEtq', 'AliquotaPISEntradaEstoque'); Self.Adiciona('AliPisEtq', 'AliquotaPISSaidaEstoque'); Self.Adiciona('ALIPISIMPFED', 'AliquotaPISImpostoFederal'); Self.Adiciona('AliPisPasFaiVlrSplNac', 'AliquotaPISFaixaValorSimplesNacional2009'); Self.Adiciona('AliPtgPreEsc', 'AliquotaProtege'); Self.Adiciona('AliSggApuSplNac', 'AliquotaSegregacaoApuracaoSimplesNacional'); Self.Adiciona('AliSggMajApuSplNac', 'AliquotaSegregacaoApuracaoMajoradoSimplesNacional'); Self.Adiciona('AliTotFaiVlrSplNac', 'AliquotaTotalFaixaValorSimplesNacional2009'); Self.Adiciona('AliTri', 'AliquotaImposto'); Self.Adiciona('ALITRIAPUIMP','AliquotaApuracaoImposto'); Self.Adiciona('AliTriZee', 'AliquotaTributacaoLeituraZ'); Self.Adiciona('AlqConIndOutEnt', 'AliquotaContribuinteIndividualOutraEntidade'); Self.Adiciona('AlqCslLlrEmpCtb', 'AliquotaCSLL'); Self.Adiciona('AlqForTri', 'AliquotaFormulaTributacao'); Self.Adiciona('AlqInsCbtInd', 'AliquotaINSSContribuinteIndividual'); Self.Adiciona('AlqIrpLlrEmpCtb', 'AliquotaIRPJ'); Self.Adiciona('AlqIss', 'AliquotaIssGerenciadorContabil'); Self.Adiciona('AlqISSCbtInd', 'AliquotaISSContribuinteIndividual'); Self.Adiciona('AlqSpdPisCof511', 'AliquotaSpedPisCofins'); Self.Adiciona('AnaSinCnt', 'AnaliticaSintetica'); Self.Adiciona('AndEmp', 'Andar'); Self.Adiciona('AneClaFis', 'AnexoClassificacaoFiscal'); Self.Adiciona('AneOpePre', 'AnexoOperacaoPrestacao'); Self.Adiciona('AnoAceMovPre', 'AnoAcessoMovimento'); Self.Adiciona('AnoCalParGuiEst', 'AnoCalculoParcelaGuiaEstadual'); Self.Adiciona('AnoExeCnt', 'AnoExercicio'); Self.Adiciona('AprDadConFreNotAco', 'AproveitaDadosConhecimentoFreteNasNotasFiscais'); Self.Adiciona('ApuCslImuIse', 'ApuracaoCsllImuneIsenta'); Self.Adiciona('ApuIrpImuIse', 'ApuracaoIrpjImuneIsenta'); Self.Adiciona('ApuProSubTriCodAjuApuIcm', 'ApuracaoPropriaSubstituicaoTributariaCodigoAjusteApuracaoICMS'); Self.Adiciona('AquAtiFixPreConPat', 'CodigoHistoricoAquisicaoAtivoFixo'); Self.Adiciona('AquAtiFixPreHis', 'HistoricoAquisicaoAtivoFixo'); Self.Adiciona('AreCom', 'AreaLivreComercio'); Self.Adiciona('AssScoRspEmp', 'ResponsavelAssinatura'); Self.Adiciona('AtiExt', 'AtivosExterior'); Self.Adiciona('AtiInaPes', 'AtivoInativoPessoa'); Self.Adiciona('AtuEmiDes', 'AtualizarEmitenteDestinatarioImportacaoDANFE'); Self.Adiciona('AtvRur', 'AtividadeRural'); Self.Adiciona('AusFCont', 'AusenteFCont'); Self.Adiciona('AUTGNR','AutenticacaoGNRE'); end; procedure TCustomDicionario.AdicionaAtributosB; begin Self.Adiciona('BaiEct', 'BairroEscritorio'); Self.Adiciona('BaiEmp', 'Bairro'); Self.Adiciona('BaiFazObr', 'BairroCentroDeCustoLivroCaixa'); Self.Adiciona('BaiFor', 'BairroFornecedor'); Self.Adiciona('BaiHisPreConPat', 'CodigoHistoricoBaixa'); Self.Adiciona('BaiLot', 'BairroLotacao'); Self.Adiciona('BaiPes', 'BairroPessoa'); Self.Adiciona('BaiRspTcm', 'BairroResponsavelTCM'); Self.Adiciona('BaiScoRsp', 'BairroSocioResponsavel'); Self.Adiciona('BalPatCnt', 'AusenteBalanco'); Self.Adiciona('BaRemIRRCbtInd', 'BaseIRRFContribuinteIndividual'); Self.Adiciona('BASCALCOF', 'BaseCalculoCOFINS'); Self.Adiciona('BasCalIcmDpiMovCodFis', 'BaseCalculoICMSDPI'); Self.Adiciona('BasCalInfAdiMajSplNac', 'BaseCalculoInformacaoAdicionalMajorado'); Self.Adiciona('BasCalInfAdiSplNac', 'BaseCalculoInformacaoAdicional'); Self.Adiciona('BasCalMovIcm', 'BaseCalculoICMS'); Self.Adiciona('BasCalMovSplNac', 'BaseCalculoMovimentoSimplesNacional'); Self.Adiciona('BASCALPIS', 'BaseCalculoPIS'); Self.Adiciona('BASCALRED', 'BaseCalculoReduzida'); Self.Adiciona('BASCALTRIAPUIMP', 'BaseDeCalculoApuracaoImposto'); Self.Adiciona('BasCalTriZee', 'BaseCalculoTributacaoLeituraZ'); Self.Adiciona('BASCLCREDISSMOV','BaseCalculoReduzidaMovimentacaoISS'); Self.Adiciona('BasInsOutVinCbt', 'BaseINSSOutrosVinculosContribuinteIndividual'); Self.Adiciona('BasSalBasFaiSal', 'BaseSalarioComBaseFaixaSalarial'); Self.Adiciona('BasSldCnt', 'MesBaseSaldo'); Self.Adiciona('BenFomProMic', 'BeneficioFomentarProduzirMicroProduzir'); Self.Adiciona('BENINCATIIMO', 'BensIncorporadosAoAtivoImobilizado'); Self.Adiciona('BLQALTLANCESCFIS', 'BloqueiaAlteracaoLancamentoEscritaFiscal'); Self.Adiciona('BLQALTLANFOLPGT', 'BloqueiaAlteracaoLancamentoFolhaPagamento'); Self.Adiciona('BLQALTLANGERCNT', 'BloqueiaAlteracaoLancamentoGerenciadorContabil'); Self.Adiciona('BLQALTLANLIVCXA', 'BloqueiaAlteracaoLancamentoLivroCaixa'); Self.Adiciona('BlqLanDocFisConPagEnt', 'BloqueiaLancamentoDocumentoFiscalSemContasPagar'); Self.Adiciona('BlqLanDocFisConRecSai', 'BloqueiaLancamentoDocumentoFiscalSemContasReceber'); Self.Adiciona('BloMesAnoEmpAreAtu', 'BloqueioMesAno'); Self.Adiciona('BSECLCICMMOVINV','BaseCalculoICMSMovimentacaoInventario'); Self.Adiciona('BSECLCIRD','BaseCalculoImpostoRendaMovimentacaoInventario'); Self.Adiciona('BSECLCIRDETQ','BaseImpostoRendaEstoque'); Self.Adiciona('BSECOFIMPFED', 'BaseCOFINSImpostoFederal'); Self.Adiciona('BSECOFIMPFED','BaseCOFINSImpostoFederal'); Self.Adiciona('BSECSLIMPFED', 'BaseCLSImpostoFederal'); Self.Adiciona('BSECSLIMPFED','BaseCLSImpostoFederal'); Self.Adiciona('BSEIRPIMPSFED', 'BaseIRPJImpostoFederal'); Self.Adiciona('BSEIRPIMPSFED','BaseIRPJImpostoFederal'); Self.Adiciona('BSEPISIMPFED', 'BasePISImpostoFederal'); Self.Adiciona('BSEPISIMPFED','BasePISImpostoFederal'); end; procedure TCustomDicionario.AdicionaAtributosC; begin Self.Adiciona('CaiPosEmp', 'CaixaPostal'); Self.Adiciona('CalAviPre','CalculaAvisoDiferenciado'); Self.Adiciona('CalDsrPreFol','CalcularDSR'); Self.Adiciona('CalHrsExtInt','CalculoHorasExtrasIntervalo'); Self.Adiciona('CalIrrMenDez','CalculaIRRFMenorDezReais'); Self.Adiciona('CalProAdiNot', 'CalcularProrrogacaoAdicionalNoturno'); Self.Adiciona('CalSalFam','CalculoSalarioFamilia'); Self.Adiciona('CamDet', 'CampoDetalhamento'); Self.Adiciona('CanMov', 'NotaFiscalCancelada'); Self.Adiciona('CapInf', 'CapacitacaoInformatica'); Self.Adiciona('CapSocEmp', 'CapitalSocial'); Self.Adiciona('CapVolClaFis', 'CapacidadeVolumetricaClassificacaoFiscal'); Self.Adiciona('CapVolEtq', 'CapacidadeVolumetricaProdutoEstoque'); Self.Adiciona('CarEmp', 'TermoCartorio'); Self.Adiciona('CarFolEmp', 'FolhaCartorio'); Self.Adiciona('CarLivEmp', 'LivroCartorio'); Self.Adiciona('CatEstAnp', 'CategoriaEstabelecimentoAnp'); Self.Adiciona('CdtRodCbtInd', 'CondutorRodoviarioContribuinteIndividual'); Self.Adiciona('CenLanEmiDesMat', 'CentralizarLancamentoMatriz'); Self.Adiciona('CepCaiPosEmp', 'CepCaixaPostal'); Self.Adiciona('CepCid', 'CepCidade'); Self.Adiciona('CepEct', 'CEPEscritorio'); Self.Adiciona('CepEmp', 'Cep'); Self.Adiciona('CepFazObr', 'CEPCentroDeCustoLivroCaixa'); Self.Adiciona('CepFor', 'CepFornecedor'); Self.Adiciona('CepLot', 'CEPLotacao'); Self.Adiciona('CepPes', 'CEPPessoa'); Self.Adiciona('CepRspTcm', 'CEPResponsavelTCM'); Self.Adiciona('CepScoRsp', 'CepSocioResponsavel'); Self.Adiciona('ChaAceNotFisEle', 'ChaveAcessoNotaFiscalEletronica'); Self.Adiciona('ChvAceImp', 'ValidaUfChaveAcessoNfe'); Self.Adiciona('ChcEmb', 'NumeroConhecimentoEmbarque'); Self.Adiciona('CifFobFreMov', 'CifFobFreteMovimentacao'); Self.Adiciona('ClaCodOpe', 'ClassificacaoCodigoOperacaoAnp'); Self.Adiciona('ClaSerVal', 'ClassificacaoSerieValida'); Self.Adiciona('CmpLanPre', 'CampoLancamento'); Self.Adiciona('CnpBen', 'CNPJBeneficiario'); Self.Adiciona('CnpCpfAdq', 'CNPJCPFAdiquirente'); Self.Adiciona('CNPITVVOLVENCMB','CNPJInterventor'); Self.Adiciona('CnpSucCreDec', 'CNPJSucedidoCreditosDecorrentes'); Self.Adiciona('CnpUndGes','CNPJUnidadeGestora'); Self.Adiciona('CntAnaZer', 'ContaAnaliticaZerada'); Self.Adiciona('CntCxa', 'ContaCaixa'); Self.Adiciona('CntDFC', 'ContaDFC'); Self.Adiciona('CntDFCDsp', 'ContaDFCDisponivel'); Self.Adiciona('CntLcx', 'ContaLivroCaixa'); Self.Adiciona('CntLcxDes', 'ContaLivroCaixaDesconto'); Self.Adiciona('CntLcxJur', 'ContaLivroCaixaJuros'); Self.Adiciona('CntLcxMlt', 'ContaLivroCaixaMulta'); Self.Adiciona('CntLcxPad', 'ContaLivroCaixaPadrao'); Self.Adiciona('CntLcxTit', 'ContaLivroCaixaTitulo'); Self.Adiciona('CntNaoDetLcx', 'ContaNaoDedutiveLivroCaixa'); Self.Adiciona('CntResCnt', 'ContaResultado'); Self.Adiciona('CntSemHirCpt', 'ContaSemHierarquiaCompleta'); Self.Adiciona('CodAcePgd', 'CodigoAcessoPGDAS'); Self.Adiciona('CodAdi', 'CodigoAdicaoItemAtivoFixo'); Self.Adiciona('CODAGE','CodigoAgencia'); Self.Adiciona('CodAgeNoc', 'CodigoAgenteNocivo'); Self.Adiciona('CodAgeQui', 'CodigoAgenteQuimico'); Self.Adiciona('CodAgeRis', 'CodigoAgenteRisco'); Self.Adiciona('CodAju', 'CodigoAjuste'); Self.Adiciona('CodAjuApu', 'CodigoAjusteApuracao'); Self.Adiciona('CodAjuApuIcm', 'CodigoAjusteApuracaoICMS'); Self.Adiciona('CodAjuApuIcmEFD', 'CodigoAjusteApuracaoICMSEFD'); Self.Adiciona('CodAjuApuIpi', 'CodigoAjusteApuracaoIPIEFD'); Self.Adiciona('CodAli', 'CodigoAliquota'); Self.Adiciona('CodAliUniMedPro', 'CodigoAliquotaUnidadeMedidaProduto'); Self.Adiciona('CodAliUniMedProPisCof', 'CodigoAliquotaUnidadeMedidaProdutoPisCofins'); Self.Adiciona('CodAmb', 'CodigoAmbiente'); Self.Adiciona('CodAnaMatBio', 'CodigoAnaliseMaterialBiologico'); Self.Adiciona('CodAno', 'CodigoAnotacaoCTPS'); Self.Adiciona('CodAnp', 'CodigoAnp'); Self.Adiciona('CodAnxSupSpl', 'CodigoAnexoSuperSimples'); Self.Adiciona('CodAreAtu', 'CodigoAreaAtuacao'); Self.Adiciona('CodAso', 'CodigoASO'); Self.Adiciona('CodAtv', 'CodigoAtividadeLALUR'); Self.Adiciona('CodAtvEcoTer', 'CodigoDeAtividadeEconomicaDoTerceiro'); Self.Adiciona('CodAtvSggSupSpl', 'CodigoAtividadeSegregacaoSuperSimples'); Self.Adiciona('CodBarPrdCom', 'CodigoBarrasProduto'); Self.Adiciona('CodBasCalCre', 'CodigoBaseCalculoCredito'); Self.Adiciona('CodBco','CodigoBanco'); Self.Adiciona('CODBENINCATIIMO', 'CodigoBensIncorrentesAtivoImobilizado'); Self.Adiciona('CodCadEmpIns', 'CodigoCadastralInstituicaoSPED'); Self.Adiciona('CodCarFisQuiPrd', 'CodigoDaCaracteristicaFisicoQuimicoDoProduto'); Self.Adiciona('CodCat', 'CodigoCategoria'); Self.Adiciona('CodCbo', 'CodigoCBO'); Self.Adiciona('CodCenCus', 'CodigoCentroCusto'); Self.Adiciona('CODCENCUSSUBCNTANA', 'CodigoCentroCustosSubcontaContabilAnalitica'); Self.Adiciona('CODCENCUSSUBCNTANAAUX', 'CodigoCentroCustosSubcontaContabilAnaliticaAuxiliar'); Self.Adiciona('CodCenCusK155', 'CodigoCentroCustoK155'); Self.Adiciona('CodCenCusOutOpe', 'CodigoCentroCustosOutrasOperacoes'); Self.Adiciona('CodCenCusSpdEcf', 'CodigoCentroCustoSpedEcf'); Self.Adiciona('CodCfgCtb', 'CodigoConfiguracaoContabil'); Self.Adiciona('CodCfgCtbAnt', 'CodigoConfiguracaoContabilAnterior'); Self.Adiciona('CodCfgCtbNov', 'CodigoConfiguracaoContabilNova'); Self.Adiciona('CodCid', 'CodigoCidade'); Self.Adiciona('CodCidEnqMun', 'CodigoCidadeEnquadramentoMunicipal'); Self.Adiciona('CodCidOri', 'CodigoCidadeOrigem'); Self.Adiciona('CodClaAtv', 'CodigoClassificacaoAtividades'); Self.Adiciona('CodClaFis', 'CodigoClassificacaoFiscal'); Self.Adiciona('CodClaFpa', 'CodigoClassificacaoFPAS'); Self.Adiciona('CodClaSerCsm', 'CodigoClassificacaoServicoConsumo'); Self.Adiciona('CodClaSerCsmLfe', 'CodigoClassificacaoServicoConsumoLFE'); Self.Adiciona('CodClsAtvCnaDoi', 'CodigoClassificacaoAtividadesCNAEDois'); Self.Adiciona('CodCstPis', 'CodigoCstPis'); Self.Adiciona('CodCstCof', 'CodigoCstCofins'); Self.Adiciona('CODCNTBLI200', 'CodigoContaBlocoI200'); Self.Adiciona('CODCNTBLI300', 'CodigoContaBlocoI300'); Self.Adiciona('CodCntConLanSpg', 'CodigoContaConfirmacaoLancamentoSopag'); Self.Adiciona('CodCntCtbPtb', 'CodigoContaContrapartidaParteB'); Self.Adiciona('CodCntEcfSpdFis', 'CodigoContaCupom'); Self.Adiciona('CodCntEntSpdFis', 'CodigoContaEntrada'); Self.Adiciona('CodCntLlr', 'CodigoContaLalur'); Self.Adiciona('CodCntOutOpe', 'CodigoContaOutrasOperacoes'); Self.Adiciona('CodCntPrdSpdFis', 'CodigoContaProduto'); Self.Adiciona('CodCntPrvLanSpg', 'CodigoContaProvisaoLancamentoSopag'); Self.Adiciona('CodCntPtb', 'CodigoContaParteB'); Self.Adiciona('CodCntRef', 'CodigoContaReferencial'); Self.Adiciona('CodCntSaiSpdFis', 'CodigoContaSaida'); Self.Adiciona('CodCntSpdFis', 'ContaContabilItemAtivoFixo'); Self.Adiciona('CODCNTSPDPISCOF', 'CodigoContaSpedPisCofins'); Self.Adiciona('CodCntSup', 'CodigoContaSuperior'); Self.Adiciona('CODCOM', 'CodigoComplemento'); Self.Adiciona('CodConCor', 'CodigoContaCorrente'); Self.Adiciona('CodCrg', 'CodigoCargo'); Self.Adiciona('CodCrs', 'CodigoCurso'); Self.Adiciona('CodDep', 'CodigoDepartamento'); Self.Adiciona('CodDesRenTit', 'CodigoDestinoRenegociacaoTitulo'); Self.Adiciona('CODGRPANP', 'CodigoGrupoCombustivel'); Self.Adiciona('CODDET', 'CodigoDetalhamento'); Self.Adiciona('CodDisAtz', 'CodigoDispositivoAutorizado'); Self.Adiciona('CodDivAtv', 'CodigoDivisaoAtividades'); Self.Adiciona('CodDivAtvCnaDoi', 'CodigoDivisaoAtividadesCNAEDois'); Self.Adiciona('CodDoc', 'CodigoDocumento'); Self.Adiciona('CodDocInf', 'CodigoDocumentoInformado'); Self.Adiciona('CodEct', 'CodigoEscritorio'); Self.Adiciona('CodEmiCupFis', 'CodigoEmissorCupomFiscal'); Self.Adiciona('CodEmiDes', 'CodigoEmitenteDestinatario'); Self.Adiciona('CodEmp', 'CodigoEmpresa'); Self.Adiciona('CodEmpCli', 'CodigoEmpresaCliente'); Self.Adiciona('CodEmpCtb', 'CodigoEmpresaContabil'); Self.Adiciona('CodEmpDes', 'CodigoDestinatarioNotaFiscal'); Self.Adiciona('CodEmpDie', 'CodigoEmpresaDief'); Self.Adiciona('CodEmpEmi', 'CodigoEmitenteNotaFiscal'); Self.Adiciona('CodEmpEmiDes', 'CodigoEmitenteDestinatarioE313'); Self.Adiciona('CodEmpEsc', 'CodigoEmpresaEscrita'); Self.Adiciona('CodEmpExc', 'CodigoEmpresaExcexao'); Self.Adiciona('CodEmpFol', 'CodigoEmpresaFolha'); Self.Adiciona('CodEmpGerCtb', 'CodigoEmpresaGerenciadorContabil'); Self.Adiciona('CodEmpInt','CodigoEmpresaIntegracao'); Self.Adiciona('CodEmpIntCtb','CodigoEmpresaIntegracaoContabil'); Self.Adiciona('CodEmpIntLcx','CodigoEmpresaIntegracaoLivroCaixa'); Self.Adiciona('CodEmpMat','CodigoEmpresaMatrizContabil'); Self.Adiciona('CodEmpOri', 'CodigoEmpresaOrigem'); Self.Adiciona('CodEmpPrt', 'CodigoEmpresaPortador'); Self.Adiciona('CodEmpRef', 'CodigoEmpresaReferencia'); Self.Adiciona('CodEmpTrs', 'CodigoEmpresaTransferencia'); Self.Adiciona('CodEsp', 'CodigoEspecie'); Self.Adiciona('CodEspClaFis', 'CodigoEspecificacaoClassificacaoFiscal'); Self.Adiciona('CodEspDocBol', 'CodigoEspecieDocumento'); Self.Adiciona('CodEspEnt', 'EspecieSerieValidaEntradaImportacaoSintegra'); Self.Adiciona('CodEspRecEst', 'CodigoEspecieRecolhimentoEstadual'); Self.Adiciona('CodEspSai', 'EspecieSerieValidaSaidaImportacaoSintegra'); Self.Adiciona('CodEstCid', 'CodigoEstadual'); Self.Adiciona('CodEve', 'CodigoEvento'); Self.Adiciona('CodEveAdiNot', 'CodigoEventoAdicionalNoturno'); Self.Adiciona('CodEveAdiNotOutFol', 'CodigoEventoAdicionalNoturnoOutraFolha'); Self.Adiciona('CodEveFal', 'CodigoEventoFaltas'); Self.Adiciona('CodEveFalOutFol', 'CodigoEventoFaltasOutraFolha'); Self.Adiciona('CodEveHorTrb', 'CodigoEventoHorasTrabalhadas'); Self.Adiciona('CodEveHorTrbOutFol', 'CodigoEventoHorasTrabalhadasOutraFolha'); Self.Adiciona('CODEXPAPUICM', 'CodigoExpressoesApuracaoICMSSPEDFiscalDF'); Self.Adiciona('CodFazObr', 'CodigoCentroDeCustoLivroCaixa'); Self.Adiciona('CodFedCid', 'CodigoFederal'); Self.Adiciona('CodFis', 'CodigoFiscal'); Self.Adiciona('CodFisCmb', 'CodigoFiscalCombustivel'); Self.Adiciona('CodFisDenEst', 'CodigoFiscalDentroEstado'); Self.Adiciona('CodFisDocFis', 'CodigoFiscalDocumentoFiscal'); Self.Adiciona('CodFisExc', 'CodigoFiscalExcecao'); Self.Adiciona('CodFisExcSpdFis', 'CodigoFiscalExcecaoSpedFiscal'); Self.Adiciona('CodFisForEst', 'CodigoFiscalForaEstado'); Self.Adiciona('CodFisSer', 'CodigoFiscalServico'); Self.Adiciona('CodFisSubTri', 'CodigoFiscalSubstituicaoTributaria'); Self.Adiciona('CodFisTriNor', 'CodigoFiscalTributacaoNormal'); Self.Adiciona('CodFisTrs', 'CodigoFiscalTransferencia'); Self.Adiciona('CodFor', 'CodigoFornecedor'); Self.Adiciona('CodForTri', 'CodigoFormulaTributacao'); Self.Adiciona('CodFpa', 'CodigoFPAS'); Self.Adiciona('CodFrlCtb', 'CodigoFormulaContabil'); Self.Adiciona('CodGPS', 'CodigoGPS'); Self.Adiciona('CodGroPrd', 'CodigoGeneroProduto'); Self.Adiciona('CodGrpAce', 'CodigoGrupoAcesso'); Self.Adiciona('CodGrpAtiFix', 'CodigoGrupoAtivoFixo'); Self.Adiciona('CodGrpAtv', 'CodigoGrupoAtividades'); Self.Adiciona('CodGrpAtvCnaDoi', 'CodigoGrupoAtividadesCNAEDois'); Self.Adiciona('CodGrpBas', 'CodigoGrupoBase'); Self.Adiciona('CodGrpCBO', 'CodigoGrupoCBO'); Self.Adiciona('CodGrpCntLcx', 'CodigoGrupoContaLivroCaixa'); Self.Adiciona('CodGrpEpi', 'CodigoGrupoEPI'); Self.Adiciona('CodGrpHis', 'CodigoGrupoHistorico'); Self.Adiciona('CodGrpNatJur', 'CodigoGrupoNaturezaJuridica'); Self.Adiciona('CodGrpOgc', 'CodigoGrupoObrigacao'); Self.Adiciona('CodIstBolCob', 'CodigoBoleto'); Self.Adiciona('CodHis', 'CodigoHistorico'); Self.Adiciona('CodHisAdi', 'CodigoHistoricoAdiantamento'); Self.Adiciona('CodHisAfa', 'CodigoHistoricoAfastamento'); Self.Adiciona('CodHisAut', 'CodigoHistoricoAutonomo'); Self.Adiciona('CodHisFer', 'CodigoHistoricoFerias'); Self.Adiciona('CodHisIteMovCtb', 'CodigoHistoricoItemMovimentacaoContabil'); Self.Adiciona('CodHisLanPadCre', 'CodigoHistoricoLancamentoPadraoCredito'); Self.Adiciona('CodHisLanPadDeb', 'CodigoHistoricoLancamentoPadraoDebito'); Self.Adiciona('CodHisLlr', 'CodigoHistoricoLALUR'); Self.Adiciona('CodHisMen', 'CodigoHistoricoMensal'); Self.Adiciona('CodHisPpr', 'CodigoHistoricoPpr'); Self.Adiciona('CodHisPriDecTer', 'CodigoHistoricoPrimeiraDecimoTerceiro'); Self.Adiciona('CodHisPro', 'CodigoHistoricoProLabore'); Self.Adiciona('CodHisRes', 'CodigoHistoricoRescisao'); Self.Adiciona('CodHisSegDecTer', 'CodigoHistoricoSegundaDecimoTerceiro'); Self.Adiciona('CodIdePro', 'CodigoIdentificacaoProducao'); Self.Adiciona('CodIdeVar', 'CodigoVara'); Self.Adiciona('Codigo', 'CodigoEventoMigracao'); Self.Adiciona('CodImp', 'CodigoImposto'); Self.Adiciona('CodImpEst', 'CodigoImpostoEstadual'); Self.Adiciona('CODINCCONSIN', 'CodigoIncidenciaContSind'); Self.Adiciona('CODINCFGT', 'CodigoIncidenciaFGTS'); Self.Adiciona('CODINCINS', 'CodigoIncidenciaInss'); Self.Adiciona('CODINCIRR', 'CodigoIncidenciaIRRF'); Self.Adiciona('CodIncTrb', 'CodigoIndicadorIncidenciaTributaria'); Self.Adiciona('CodIncTri', 'CodigoIncidenciaTributaria'); Self.Adiciona('CodIncTriEso', 'CodigoIncidenciaTributariaeSocial'); Self.Adiciona('CodIndMoe', 'CodigoIndexadorMoeda'); Self.Adiciona('IndMovDifAli', 'IndicadorMovimentoDiferencialAliquota'); Self.Adiciona('CodInfAdiApu', 'CodigoInformacaoAdicionalApuracaoEFD'); Self.Adiciona('CodInsAnp', 'CodigoInstalacaoAnp'); Self.Adiciona('CodInsAnp1', 'CodigoInstalacaoAnp1'); Self.Adiciona('CodInsAnp2', 'CodigoInstalacaoAnp2'); Self.Adiciona('CodInsSub', 'CodigoInsumoSubstituido'); Self.Adiciona('CodInt', 'CodigoIntervalo'); Self.Adiciona('CodIteDes', 'CodigoItemDestino'); Self.Adiciona('CodIteEpi', 'CodigoItemEPI'); Self.Adiciona('CodIteEtq', 'CodigoItemEstoque'); Self.Adiciona('CodIteIns', 'CodigoItemInsumo'); Self.Adiciona('CodIteOri', 'CodigoItemOrigem'); Self.Adiciona('CodItePro', 'CodigoItemProducao'); Self.Adiciona('CodLanPad', 'CodigoLancamentoPadrao'); Self.Adiciona('CodLanPadDes', 'CodigoLancamentoPadraoDesconto'); Self.Adiciona('CodLanPadHon13', 'CodigoLancamentoPadraoHonorario13'); Self.Adiciona('CodLanPadHonCom', 'CodigoLancamentoPadraoHonorarioComplementar'); Self.Adiciona('CodLanPadHonNor', 'CodigoLancamentoPadraoHonorarioNormal'); Self.Adiciona('CodLanPadJur', 'CodigoLancamentoPadraoJuros'); Self.Adiciona('CodLanPadMul', 'CodigoLancamentoPadraoMulta'); Self.Adiciona('CodLanPadTit', 'CodigoLancamentoPadraoTitulo'); Self.Adiciona('CodLanPta', 'CodigoLancamentoParteA'); Self.Adiciona('CodLayPto', 'CodigoLayoutPonto'); Self.Adiciona('CodLimEnq', 'CodigoLimiteEnquadramento'); Self.Adiciona('CodLivElePai', 'CodigoLivroEletronico'); Self.Adiciona('CodLocBem', 'CodigoLocalizacaoBem'); Self.Adiciona('CodLot', 'CodigoLote'); Self.Adiciona('CodMac', 'CodigoMacro'); Self.Adiciona('CodMar', 'CodigoMarca'); Self.Adiciona('CodMarEmiCupFis', 'CodigoMarcaEmissorCupomFiscal'); Self.Adiciona('CodMatBio', 'CodigoMaterialBiologico'); Self.Adiciona('CodMerSujReaIcmPerFixSai', 'CodigoMercadoriasSujeitasReaIcmsPercentualFixoSobreSaidas'); Self.Adiciona('CodMetUtiAfeCar', 'CodigoDoMetodoUtilizadoParaAfericaoDaCaracteristica'); Self.Adiciona('CodMod', 'CodigoModelo'); Self.Adiciona('CodModCnt', 'CodigoModeloConta'); Self.Adiciona('CodModDocFis', 'CodigoModeloDocumentoFiscal'); Self.Adiciona('CodDocArrEst', 'CodigoDocumentoArrecadacaoEstadual'); Self.Adiciona('CodModUtiMov', 'CodigoDoModalUtilizadoNaMovimentacao'); Self.Adiciona('CodMotAbn', 'CodigoMotivoAbono'); Self.Adiciona('CodMotCarCor', 'CodigoMotivoCartaCorrecao'); Self.Adiciona('CodMotInv', 'CodigoMotivoInventario'); Self.Adiciona('CodMotFlg', 'CodigoMotivoFolga'); Self.Adiciona('CodMotSusExiSup', 'CodigoMotivoSuspensaoExigibilidadeSuspensa'); Self.Adiciona('CodMqnCta', 'CodigoMaquinaColetora'); Self.Adiciona('CodMscCnt', 'CodigoMascaraConta'); Self.Adiciona('CodMsg', 'CodigoMensagem'); Self.Adiciona('CodMunAnp', 'CodigoDoMunicipioAnp'); Self.Adiciona('CodNacPai', 'CodigoNacionalidade'); Self.Adiciona('CodNaoRgtPto', 'CodigoNaoRegistraPonto'); Self.Adiciona('CodNatCnt', 'NaturezaContaItemAtivoFixo'); Self.Adiciona('CodNatCntRef', 'CodigoNaturezaContaReferencial'); Self.Adiciona('CodNatJur', 'CodigoNaturezaJuridica'); Self.Adiciona('CodNatRecApuImp', 'CodigoNaturezaReceitaTributo'); Self.Adiciona('CodNatRecSpd', 'CodigoNaturezaReceita'); Self.Adiciona('CodNatRecSpdFis', 'CodigoNaturezaReceitaSpedFiscal'); Self.Adiciona('CodNiv','CodigoNivel'); Self.Adiciona('CodNiv1','CodigoNivel1'); Self.Adiciona('CodNorCnt', 'CodigoNormal'); Self.Adiciona('CODNORSUBCNT', 'CodigoNormalSubconta'); Self.Adiciona('CODNORSUBCNTAUX', 'CodigoNormalSubcontaAuxiliar'); Self.Adiciona('CodObrIcmRecEfd', 'CodigoObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('CodObrRec', 'CodigoObrigacaoRecolher'); Self.Adiciona('CodOco', 'CodigoOcorrencia'); Self.Adiciona('CodOcoAgeNoc', 'CodigoOcorrenciaAgenteNocivo'); Self.Adiciona('CodOcoAjuIcmEFD', 'CodigoOcorrenciaAjusteEFD'); Self.Adiciona('CodOcuPro', 'CodigoOcupacaoProfissional'); Self.Adiciona('CodOgc', 'CodigoObrigacao'); Self.Adiciona('CodOpcSpl', 'CodigoOpcaoSimples'); Self.Adiciona('CodOpeAnp', 'CodigoOperacaoAnp'); Self.Adiciona('CodOpeDie', 'CodigoOperacaoDie'); Self.Adiciona('CodOpePlaSau', 'CodigoOperadorPlanoSaude'); Self.Adiciona('CodOpePre', 'CodigoOperacaoPrestacao'); Self.Adiciona('CodOptImpSplNac', 'CodigoOpcaoImpostoSimplesNacional'); Self.Adiciona('CodOrgReg', 'CodigoOrgaoRegistro'); Self.Adiciona('CodOri', 'CodigoOrigem'); Self.Adiciona('CodOriCre', 'CodigoOrigemCredito'); Self.Adiciona('CodOriCtbSpg', 'CodigoOrigemContabilizacaoSopag'); Self.Adiciona('CodOriLan', 'CodigoOrigemLancamento'); Self.Adiciona('CodOriMer', 'CodigoOrigemMercadoria'); Self.Adiciona('CodOriRenTit', 'CodigoOrigemRenegociacaoTitulo'); Self.Adiciona('CodOutEnt', 'CodigoOutraEntidade'); Self.Adiciona('CodOutVlrFis', 'CodigoOutrosValoresFiscaisPreferenciaEscrita'); Self.Adiciona('CodPai', 'CodigoPais'); Self.Adiciona('CodPaiAnp', 'CodigoDoPaisAnp'); Self.Adiciona('CodPar', 'CodigoParticipante'); Self.Adiciona('CodParCnt', 'CodigoParametroConta'); Self.Adiciona('CodParCntSpd', 'CodigoParametroContaSped'); Self.Adiciona('CodParMul', 'CodigoPartidaMultipla'); Self.Adiciona('CodPerOgc', 'CodigoPeriodoObrigacao'); Self.Adiciona('CodPes', 'CodigoPessoa'); Self.Adiciona('CodPesCbtInd', 'CodigoPessoaContribuinteIndividual'); Self.Adiciona('CodPesMedRsp', 'CodigoPessoaMedicoResponsavel'); Self.Adiciona('CodPesRspExa', 'CodigoPessoaResponsavelExame'); Self.Adiciona('CodPesRspMonBio', 'CodigoPessoaResponsavelMonitoracaoBiologica'); Self.Adiciona('CodPesTom', 'CodigoPessoaTomador'); Self.Adiciona('CodPosPrd', 'CodigoPosseProduto'); Self.Adiciona('CODPRDANP','CodigoCombustivel'); Self.Adiciona('CodPrdCom', 'CodigoProduto'); Self.Adiciona('CodPrdComDos', 'CodigoProdutoComercialDOS'); Self.Adiciona('CodPrdOpeAnp', 'CodigoDoProdutoOperado'); Self.Adiciona('CodPrdOpeRes', 'CodigoDoProdutoOperacaoResultante'); Self.Adiciona('CodPrdSer', 'CodigoProdutoServico'); Self.Adiciona('CodPreGer', 'CodigoPreferenciaGeral'); Self.Adiciona('CodPrePon', 'CodigoPreferenciaPonto'); Self.Adiciona('CODPRO', 'CodigoProcesso'); Self.Adiciona('CODPROREF', 'CodigoProcessoReferenciado'); Self.Adiciona('CODPROREF', 'CodigoProcessoReferenciado'); Self.Adiciona('CodProSer', 'CodigoProdutoServico'); Self.Adiciona('CodProSer', 'CodigoProdutosServicos');//Utilizado no cadastro Formulas de Tributacao Self.Adiciona('CodPrt', 'CodigoPortador'); Self.Adiciona('CodPrtBxa', 'CodigoPortadorBaixa'); Self.Adiciona('CodQuaPesJur', 'CodigoQualificacaoPessoaJuridica'); Self.Adiciona('CodRamAti', 'RamoAtividade'); Self.Adiciona('CodRatLcx', 'CodigoRateioLcx'); Self.Adiciona('CodRatLcx', 'CodigoRateioLcx'); Self.Adiciona('CodRatPlaLcx', '_CodigoRateioPlanoLcx'); Self.Adiciona('CodRatPlaLcx', 'CodigoRateioPlanoLcx'); Self.Adiciona('CodRec', 'CodigoReceita'); Self.Adiciona('CodRecDct', 'CodigoReceitaDCTF'); Self.Adiciona('CodRecObrIcmRecEfd', 'CodigoReceitaObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('CodRecRetFon', 'CodigoRecolhimentoRetidoFonte'); Self.Adiciona('CodRecSfp', 'CodigoRecolhimentoSefip'); Self.Adiciona('CodRedAtiCnt', 'CodigoContaAtivo'); Self.Adiciona('CodRedCnt', 'CodigoReduzido'); Self.Adiciona('CodRedCntMod', 'CodigoReduzidoModelo'); Self.Adiciona('CodRedCntSup', 'CodigoReduzidoSuperior'); Self.Adiciona('CodRedCntAdi','CodigoReduzidoContaLiquidoAdiantamento'); Self.Adiciona('CodRedCntAfa','CodigoReduzidoContaLiquidoAfastamento'); Self.Adiciona('CodRedCntAnt', 'CodigoReduzidoAnterior'); Self.Adiciona('CodRedCntAut','CodigoReduzidoContaLiquidoAutonomo'); Self.Adiciona('CodRedCntBxaPad', 'CodigoContaBaixaPadrao'); Self.Adiciona('CodRedCntCre', 'CodigoContaCredito'); Self.Adiciona('CodRedCntDeb', 'CodigoContaDebito'); Self.Adiciona('CodRedCntDes','CodigoContaDesconto'); Self.Adiciona('CodRedCntFer','CodigoReduzidoContaLiquidoFerias'); Self.Adiciona('CodRedCntIteMovCtb','CodigoReduzidoContaItemMovimentacaoContabil'); Self.Adiciona('CodRedCntJur','CodigoContaJuros'); Self.Adiciona('CodRedCntMen','CodigoReduzidoContaLiquidoMensal'); Self.Adiciona('CodRedCntMul','CodigoContaMulta'); Self.Adiciona('CodRedCntNov', 'CodigoReduzidoNovo'); Self.Adiciona('CodRedCntPpr','CodigoReduzidoContaLiquidoPpr'); Self.Adiciona('CodRedCntPriDecTer','CodigoReduzidoContaLiquidoPrimeiraDecimoTerceiro'); Self.Adiciona('CodRedCntPro','CodigoReduzidoContaLiquidoProLabore'); Self.Adiciona('CodRedCntRec','CodigoContaReceita'); Self.Adiciona('CodRedCntRef','CodigoReduzidoContaReferencial'); Self.Adiciona('CodRedCntRes','CodigoReduzidoContaLiquidoRescisao'); Self.Adiciona('CodRedCntSegDecTer','CodigoReduzidoContaLiquidoSegundaDecimoTerceiro'); Self.Adiciona('CodRedIteCtbSpg', 'CodigoReduzidoItemContabilizacaoSopag'); Self.Adiciona('CodRedPreLcx', 'CodigoContaCaixa'); Self.Adiciona('CODREDSUBCNT', 'CodigoReduzidoSubcontaAnalitica'); Self.Adiciona('CODREDSUBCNTAUX', 'CodigoReduzidoSubcontaAnalitaAuxiliar'); Self.Adiciona('CodRenTit', 'CodigoRenegociacaoTitulo'); Self.Adiciona('CodReqOcuPro', 'CodigoRequisitoOcupacaoProfissional'); Self.Adiciona('CodResASO', 'CodigoResultadoASO'); Self.Adiciona('CodRgmPrv', 'CodigoRegimePrevidenciario'); Self.Adiciona('CodRspAdmCad', 'CodigoInstituicaoResponsavelAdministracaoSPED'); Self.Adiciona('CodRspTcm', 'CodigoResponsavelTCM'); Self.Adiciona('CodRspTcm', 'CodigoResponsavelTCM'); Self.Adiciona('CodSal', 'CodigoSala'); Self.Adiciona('CodScd', 'CodigoSociedadeContaParticipacao'); Self.Adiciona('CodScdOst', 'CodigoSociedadeContaParticipacaoOstensiva'); Self.Adiciona('CodScoRsp', 'CodigoSocioResponsavel'); Self.Adiciona('CodScp', 'CodigoSociedadeContaParticipacaoECF'); Self.Adiciona('CodSec', 'CodigoSecao'); Self.Adiciona('CodSecAtv', 'CodigoSecaoAtividades'); Self.Adiciona('CodSecAtvCnaDoi', 'CodigoSecaoAtividadesCNAEDois'); Self.Adiciona('CodSeqOutVlrFis', 'CodigoSequenciaOutrosValoresFiscais'); Self.Adiciona('CodSerAco', 'CodigoDoSericoAcordado'); Self.Adiciona('CodSerLei', 'CodigoServicoLei'); Self.Adiciona('CodSerNotFisOpeCom', 'CodigoDaSerieDaNotaFiscalDaOperacaoComercial'); Self.Adiciona('CodSerPre', 'CodigoServicoPrestado'); Self.Adiciona('CodSerPreFol', 'CodigoServicoPrestadoFolha'); Self.Adiciona('CodSggPreSerSupSpl', 'CodigoSegregacaoPrestacaoServicoSimplesNacionalPreferenciaEscrita'); Self.Adiciona('CodSggSupSpl', 'CodigoSegregacaoSuperSimples'); Self.Adiciona('CodSiaDfm','CodigoSiaDfm'); Self.Adiciona('CodSir','CodigoSirene'); Self.Adiciona('CodSitBem', 'CodigoSituacaoBem'); Self.Adiciona('CodSitEpg', 'CodigoSituacaoEmpregado'); Self.Adiciona('CodSitEpgLicRem', 'CodigoSituacaoLicencaRemunerada'); Self.Adiciona('CodSitEsp', 'CodigoSituacaoEspecial'); Self.Adiciona('CodSitEspEnt', 'CodigoSituacaoEspecialEntrada'); Self.Adiciona('CodSitEspSai', 'CodigoSituacaoEspecialSaida'); Self.Adiciona('CodSitTrbImp', 'CodigoSituacaoTributaria'); Self.Adiciona('CODSITTRIAPUIMP', 'CodigoSituacaoTributariaTributo'); Self.Adiciona('CodSpdEcfPai', 'CodigoPaisSped'); Self.Adiciona('CodSpdPisCof511', 'CodigoSpedFiscalPisCofins511'); Self.Adiciona('CodSpg', 'CodigoSopag'); Self.Adiciona('CodSubClaAtv', 'CodigoSubClassificacaoAtividades'); Self.Adiciona('CodSubClsAtvCnaDoi', 'CodigoSubClassificacaoAtividadesCNAEDois'); Self.Adiciona('CodSubGrp', 'CodigoSubGrupo'); Self.Adiciona('CodSubGrpEpi', 'CodigoSubGrupoEPI'); Self.Adiciona('CODTABDIM010', 'CodigoTabelaDinamicaM010'); Self.Adiciona('CODTABDIM300', 'CodigoTabelaDinamicaM300'); Self.Adiciona('CodTabDIM350', 'CodigoTabelaDinamicaM350'); Self.Adiciona('CODTABDIN500', 'CodigoTabelaDinamicaN500'); Self.Adiciona('CODTABDIN600', 'CodigoTabelaDinamicaN600'); Self.Adiciona('CODTABDIN610', 'CodigoTabelaDinamicaN610'); Self.Adiciona('CODTABDIN620', 'CodigoTabelaDinamicaN620'); Self.Adiciona('CODTABDIN630', 'CodigoTabelaDinamicaN630'); Self.Adiciona('CODTABDIN650', 'CodigoTabelaDinamicaN650'); Self.Adiciona('CODTABDIN660', 'CodigoTabelaDinamicaN660'); Self.Adiciona('CODTABDIN670', 'CodigoTabelaDinamicaN670'); Self.Adiciona('CodTabDINL210', 'CodigoTabelaDinamicaL210'); Self.Adiciona('CODTABDIP200', 'CodigoTabelaDinamicaP200'); Self.Adiciona('CODTABDIP300', 'CodigoTabelaDinamicaP300'); Self.Adiciona('CODTABDIP400', 'CodigoTabelaDinamicaP400'); Self.Adiciona('CODTABDIP500', 'CodigoTabelaDinamicaP500'); Self.Adiciona('CODTABDIT120', 'CodigoTabelaDinamicaT120'); Self.Adiciona('CODTABDIT150', 'CodigoTabelaDinamicaT150'); Self.Adiciona('CODTABDIT170', 'CodigoTabelaDinamicaT170'); Self.Adiciona('CODTABDIT181', 'CodigoTabelaDinamicaT181'); Self.Adiciona('CODTABDIU180', 'CodigoTabelaDinamicaU180'); Self.Adiciona('CODTABDIU182', 'CodigoTabelaDinamicaU182'); Self.Adiciona('CODTBL', 'CodigoTabela'); Self.Adiciona('CODTBL', 'CodigoTabela'); Self.Adiciona('CodTcmCid', 'CodigoTCM'); Self.Adiciona('CodTcmUndGes', 'CodigoTCMUnidadeGestora'); Self.Adiciona('CodTcmUndOrc', 'CodigoTCMUnidadeOrcamentaria'); Self.Adiciona('CodTec', 'CodigoTecnica'); Self.Adiciona('CodTerFpaOutEnt', 'CodigoTerceiros'); Self.Adiciona('CodTipAdi', 'CodigoTipoAdicaoItemAtivoFixo'); Self.Adiciona('CodTipAqu', 'CodigoTipoAquisicao'); Self.Adiciona('CodTipAso', 'CodigoTipoASO'); Self.Adiciona('CodTipBai', 'CodigoTipoBaixaCiap'); Self.Adiciona('CodTipBem', 'CodigoTipoBem'); Self.Adiciona('CodTipCre', 'CodigoTipoCredito'); Self.Adiciona('CodTipCreDec', 'CodigoTipoCreditosDecorrentes'); Self.Adiciona('CodTipDeb', 'CodigoTipoDebito'); Self.Adiciona('CodTipDoc', 'CodigoTipoDocumento'); Self.Adiciona('CodTipDRF', 'CodigoTipoDIRF'); Self.Adiciona('CodTipEnq', 'CodigoTipoEnquadramento'); Self.Adiciona('CodTipEnqEst', 'CodigoTipoEnquadramentoEstadual'); Self.Adiciona('CodTipEnqFed', 'CodigoTipoEnquadramentoFedral'); Self.Adiciona('CodTipEnqMun', 'CodigoTipoEnquadramentoMunicipal'); Self.Adiciona('CodTipExa', 'CodigoTipoExame'); Self.Adiciona('CodTipFol', 'CodigoTipoFolha'); Self.Adiciona('CodTipInc', 'CodigoTipoIncidencia'); Self.Adiciona('CodTipLiv', 'CodigoTipoLivro'); Self.Adiciona('CodTipLog', 'CodigoTipoLogradouro'); Self.Adiciona('CODTIPLOT', 'TipoLotacao'); Self.Adiciona('CodTipOcoGerCtb', 'CodigoTipoOcorrencia'); Self.Adiciona('CodTipOpe', 'CodigoTipoOperacao'); Self.Adiciona('CodTipRis', 'CodigoTipoRisco'); Self.Adiciona('CodTipTri', 'CodigoTipoImposto'); Self.Adiciona('CodTipUndGes', 'CodigoTipoUnidadeGestora'); Self.Adiciona('CodTipUtiCreFisIcm', 'CodigoTipoUtilizacaoCreditosFiscaisIcms'); Self.Adiciona('CodTrb', 'CodigoTRB'); Self.Adiciona('CodTrbAdiExc', 'CodigoTributoAdicaoExclusao'); Self.Adiciona('codtrbptb', 'CodigoTributoParteB'); Self.Adiciona('CodTri', 'CodigoTributo'); Self.Adiciona('CodTriFed', 'CodigoTributoFederal'); Self.Adiciona('CodUndFed', 'CodigoUnidadeFederacao'); Self.Adiciona('CodUndFedCrcCtb', 'CodigoUnidadeFederacaoCRCContador'); Self.Adiciona('CodUndFedEnqEst', 'CodigoUFEnquadramentoFederal'); Self.Adiciona('CodUndFedExpCrm', 'CodigoUnidadeFederacaoExpedicaoCRM'); Self.Adiciona('CodUndFedPos', 'CodigoUnidadeFederacaoCaixaPostal'); Self.Adiciona('CodUndFedRegRspTcm', 'CodigoUnidadeFederativaRegistroResponsavelTCM'); Self.Adiciona('CodUndGes', 'CodigoUnidadeGestora'); Self.Adiciona('CodUndMedCar', 'CodigoDaUnidadeDeMedidaDaCaracteristica'); Self.Adiciona('CodUndOrc', 'CodigoUnidadeOrcamentaria'); Self.Adiciona('CodUndOrcRsp', 'CodigoUnidadeOrcamentariaResponsavel'); Self.Adiciona('CodUniFedChvAce', 'CodigoUnidadeFederacaoChaveAcesso'); Self.Adiciona('CodUniMed','CodigoUnidadeMedida'); Self.Adiciona('CodUsuSpg', 'CodigoUsuarioSopag'); Self.Adiciona('CodVeiUtiMod', 'CodigoDoVeiculoUtilizadoNoModal'); Self.Adiciona('CodVlrManDemRes', 'CodigoValorManual'); Self.Adiciona('COFOPEIMPMOV','ValorCofinsOperacaoImportacao'); Self.Adiciona('ComCenCusEmp', 'CodigoEmpresaCompartilhamentoCentrosNegocios'); Self.Adiciona('ComCntEmp', 'CodigoEmpresaCompartilhamentoContas'); Self.Adiciona('ComCntLcxEmp', 'CodigoEmpresaCompartilhamentoContasLivroCaixa'); Self.Adiciona('ComEle', 'ComercioEletronico'); Self.Adiciona('ComEmp', 'Complemento'); Self.Adiciona('ComEndEct', 'ComplementoEnderecoEscritorio'); Self.Adiciona('ComEndFazObr', 'ComplementoEnderecoCentroDeCustoLivroCaixa'); Self.Adiciona('ComExp', 'ComercialExportadora'); Self.Adiciona('ComFor', 'ComplementoFornecedor'); Self.Adiciona('ComHisEmp', 'CodigoEmpresaCompartilhamentoHistoricos'); Self.Adiciona('ComLan', 'ComplementoLancamento'); Self.Adiciona('ComLanPadEmp', 'CodigoEmpresaCompartilhamentoLancamentosPadrao'); Self.Adiciona('ComMsg', 'ComplementoMensagem'); Self.Adiciona('ComRatEmp', 'CodigoEmpresaCompartilhamentoRateios'); Self.Adiciona('ConDesIndMsPreEsc', 'GerarRegistroTipo88doSINTEGRA'); Self.Adiciona('ConEmiGuiFol', 'ControlaEmissaoGuiasFolha'); Self.Adiciona('ConHrsAdiNot', 'ConverterHoraAdicionalNoturno'); Self.Adiciona('ConInsSalMatEmpFol','ConvenioInssSalarioMaternidade'); Self.Adiciona('ConLan', 'LancamentoConciliado'); Self.Adiciona('ConOpeFimMovECf', 'ContadorOperacaoFimMovimentacaoEmissorCupomFiscal'); Self.Adiciona('ConOpeIniMovEcf','ContadorOperacaoInicioMovimentacaoEmissorDocumentoFiscal'); Self.Adiciona('ConOpeMovEcf','ContadorOperacaoMovimentacaoEmissorCupomFiscal'); Self.Adiciona('ConPagMov','CondicaoPagamentoNotaFiscal'); Self.Adiciona('ConRedZeeMovEcf','ContadorReducaoZMovimentacaoEmissorCupomFiscal'); Self.Adiciona('ConReiMovEcf','ContadorReinicioMovimentacaoEmissorCupomFiscal'); Self.Adiciona('CooMovEcf','ContadorOrdemOperacaoMovimentacaoEmissorCupomFiscal'); Self.Adiciona('CopPerAnt', 'CopiaPeriodoAnterior'); Self.Adiciona('CorAtiHis', 'CodigoHistoricoCorrecaoAtivo'); Self.Adiciona('CorMonDepAcuHis', 'CodigoHistoricoCorrecaoDepreciacaoAcumulada'); Self.Adiciona('CorPasPreConPat', 'CodigoHistoricoCorrecaoPassivo'); Self.Adiciona('CpfCtb', 'CpfContador'); Self.Adiciona('CPFITVVOLVENCMB','CPFInterventor'); Self.Adiciona('CpfPdtRurPreEsc', 'CPFdeProdutorRuralPrefereciasEscrita'); Self.Adiciona('CpfPrdRur', 'CPFProdutorRural'); Self.Adiciona('CpfPrdRur', 'CPFProdutorRural'); Self.Adiciona('CpfRepLeg', 'CpfRepresentanteLegal'); Self.Adiciona('CpfRspTcm', 'CPFResponsavelTCM'); Self.Adiciona('CplHisLcx', 'ComplementoLivroCaixa'); Self.Adiciona('CrcCtb', 'CrcContador'); Self.Adiciona('CrcEct', 'CRCEscritorio'); Self.Adiciona('CRCFazObr', 'CRCCentroDeCustoLivroCaixa'); Self.Adiciona('CreEntApuIpi', 'ValorCreditosApuracaoIPI'); Self.Adiciona('CreImpRec', 'creditoImpostoARecolher'); Self.Adiciona('CreOutImpEst', 'CreditoOutorgadoImpostoEstoque'); Self.Adiciona('CreOutTriZee', 'CreditoOutorgadoTributacaoLeituraZ'); Self.Adiciona('CreSldCnt', 'ValorCreditoSaldo'); Self.Adiciona('CreSobEntApuIcm', 'CreditoSobreEntradaApuracaoICMS'); Self.Adiciona('CrmMedRsp', 'CrmMedicoResponsavel'); Self.Adiciona('CSTCOF', 'CSTCOFINS'); Self.Adiciona('CstCofDocFis', 'CstCofinsDocumentoFiscal'); Self.Adiciona('CstCofSaiRegD205', 'CstCofinsSaidaRegistrod205'); Self.Adiciona('CstIcm', 'CSTICMS'); Self.Adiciona('CstOut', 'CodigoSituacaoTributaria'); Self.Adiciona('CSTPIS', 'CSTPIS'); Self.Adiciona('CstPisDocFis', 'CstPisDocumentoFiscal'); Self.Adiciona('CstPisSaiRegD201', 'CstPisSaidaRegistroD201'); Self.Adiciona('CstSplNac', 'CodigoSituacaoTributariaSimplesNacional'); Self.Adiciona('CtlConPorCnpCpfMatFil', 'ControleContabilidadeCNPJCPF'); Self.Adiciona('CtrCtbGerIteAtiFix', 'TipoControleItemAtivoFixo'); Self.Adiciona('CtrDsrFerTol','ControlarDSRFeriadoTolerancia'); Self.Adiciona('CtrFqc','ControlarFrequencia'); Self.Adiciona('CtrMeiFal','ControlarMeiaFalta'); Self.Adiciona('CtrMeiFalPer','ControlarMeiaFaltaPercentual'); Self.Adiciona('CtrPatIaf', 'ControlePatrimonioItemAtivoFixo'); Self.Adiciona('CtrSalFamDocDpd','ControlarSalarioFamiliaConformeDocumentacaoDependentes'); Self.Adiciona('CupFisIntCtbPreEsc', 'IntegracaoContabilCupomFiscal'); Self.Adiciona('CupFisIrpPreEsc', 'IntegracaoContabilCupomFiscal'); Self.Adiciona('CupFisOpePreEsc', 'CodigoOperacaoCupomFiscalMatoGrosso'); Self.Adiciona('CusOrcUndImbVen', 'CustosOrcadosNaUnidadeImobiliariaVendida'); Self.Adiciona('CodIdeVar', 'CodigoVara'); Self.Adiciona('AUTGNR','AutenticacaoGNRE'); Self.Adiciona('ALITRIAPUIMP','AliquotaApuracaoImposto'); Self.Adiciona('ALICOF', 'AliquotaCOFINS'); Self.Adiciona('AliCofEntEtq', 'AliquotaCOFINSEntradaEstoque'); Self.Adiciona('AliCofEtq', 'AliquotaCOFINSSaidaEstoque'); Self.Adiciona('ALIPIS', 'AliquotaPIS'); Self.Adiciona('AliPisEntEtq', 'AliquotaPISEntradaEstoque'); Self.Adiciona('AliPisEtq', 'AliquotaPISSaidaEstoque'); Self.Adiciona('BaiFazObr', 'BairroCentroDeCustoLivroCaixa'); Self.Adiciona('BaiFor', 'BairroFornecedor'); Self.Adiciona('BASCALCOF', 'BaseCalculoCOFINS'); Self.Adiciona('BASCALPIS', 'BaseCalculoPIS'); Self.Adiciona('BASCALRED', 'BaseCalculoReduzida'); Self.Adiciona('BASCALTRIAPUIMP', 'BaseDeCalculoApuracaoImposto'); Self.Adiciona('BasSalBasFaiSal', 'BaseSalarioComBaseFaixaSalarial'); Self.Adiciona('BENINCATIIMO', 'BensIncorporadosAoAtivoImobilizado'); Self.Adiciona('BlqLanDocFisConPagEnt', 'BloqueiaLancamentoDocumentoFiscalSemContasPagar'); Self.Adiciona('BlqLanDocFisConRecSai', 'BloqueiaLancamentoDocumentoFiscalSemContasReceber'); Self.Adiciona('VLRBASCRE', 'BaseCalculoCredito'); Self.Adiciona('BSECOFIMPFED','BaseCOFINSImpostoFederal'); Self.Adiciona('BSECLCICMMOVINV','BaseCalculoICMSMovimentacaoInventario'); Self.Adiciona('BSECLCIRD','BaseCalculoImpostoRendaMovimentacaoInventario'); Self.Adiciona('BASCLCREDISSMOV','BaseCalculoReduzidaMovimentacaoISS'); Self.Adiciona('BSECSLIMPFED','BaseCLSImpostoFederal'); Self.Adiciona('BSEIRPIMPSFED','BaseIRPJImpostoFederal'); Self.Adiciona('BSEPISIMPFED','BasePISImpostoFederal'); Self.Adiciona('BSECLCIRDETQ','BaseImpostoRendaEstoque'); Self.Adiciona('VlrBasRedPerComAli','BaseCalculoReduzidaPercentualComplementoAliquota'); Self.Adiciona('CepFazObr', 'CEPCentroDeCustoLivroCaixa'); Self.Adiciona('CepFor', 'CepFornecedor'); Self.Adiciona('CNPITVVOLVENCMB','CNPJInterventor'); Self.Adiciona('CnpUndGes','CNPJUnidadeGestora'); Self.Adiciona('CODAGE','CodigoAgencia'); Self.Adiciona('CodBco','CodigoBanco'); Self.Adiciona('CODBENINCATIIMO', 'CodigoBensIncorrentesAtivoImobilizado'); Self.Adiciona('CodFazObr', 'CodigoCentroDeCustoLivroCaixa'); Self.Adiciona('CodDesRenTit', 'CodigoDestinoRenegociacaoTitulo'); Self.Adiciona('CODGRPANP', 'CodigoGrupoCombustivel'); Self.Adiciona('CodGrpCntLcx', 'CodigoGrupoContaLivroCaixa'); Self.Adiciona('CodOriRenTit', 'CodigoOrigemRenegociacaoTitulo'); Self.Adiciona('CODPRDANP','CodigoCombustivel'); Self.Adiciona('CODPROREF', 'CodigoProcessoReferenciado'); Self.Adiciona('CODPRO', 'CodigoProcesso'); Self.Adiciona('CODPROLOT', 'CodigoProcessoRelativo'); Self.Adiciona('CodRatLcx', 'CodigoRateioLcx'); Self.Adiciona('CodProSer', 'CodigoProdutoServico'); Self.Adiciona('CodRatPlaLcx', '_CodigoRateioPlanoLcx'); Self.Adiciona('CodRatPlaLcx', 'CodigoRateioPlanoLcx'); Self.Adiciona('CodRec', 'CodigoReceita'); Self.Adiciona('CodRecSfp', 'CodigoRecolhimentoSefip'); Self.Adiciona('CodScd', 'CodigoSociedadeContaParticipacao'); Self.Adiciona('CODSITTRIAPUIMP', 'CodigoSituacaoTributariaTributo'); Self.Adiciona('CodUndFedCrcCtb', 'CodigoUnidadeFederacaoCRCContador'); Self.Adiciona('CodUndFedRegRspTcm', 'CodigoUnidadeFederativaRegistroResponsavelTCM'); Self.Adiciona('COFOPEIMPMOV','ValorCofinsOperacaoImportacao'); Self.Adiciona('ComEndFazObr', 'ComplementoEnderecoCentroDeCustoLivroCaixa'); Self.Adiciona('CPFITVVOLVENCMB','CPFInterventor'); Self.Adiciona('CreImpRec', 'creditoImpostoARecolher'); Self.Adiciona('CSTCOF', 'CSTCOFINS'); Self.Adiciona('CSTPIS', 'CSTPIS'); Self.Adiciona('CtlConPorCnpCpfMatFil', 'ControleContabilidadeCNPJCPF'); Self.Adiciona('CvtMovMen', 'MovimentacaoConvertida'); end; procedure TCustomDicionario.AdicionaAtributosDEFGH; begin Self.Adiciona('DddEstAso', 'DddEstabelecimento'); Self.Adiciona('DscAmb', 'DescricaoAmbiente'); Self.Adiciona('DSCCOM', 'DescricaoComplemento'); Self.Adiciona('DSCCOMPAJUAPU', 'DescricaoComplementarAjusteApuracao'); Self.Adiciona('DSCCOMAJUAPU', 'DescricaoComplementarAjusteApuracaoE316E312'); Self.Adiciona('DSCCOMDOCOPE', 'DescricaoComplementarDocumentoOperacao'); Self.Adiciona('DSCCODOUTVLRFIS', 'DescricaoOutrosValoresFiscais'); Self.Adiciona('DSCEXPAPUICM', 'DescricaoExpressoesApuracaoICMSSPEDFiscalDF'); Self.Adiciona('DSCDET', 'DescricaoDetalhamento'); Self.Adiciona('DscTipDeb', 'DescricaoTipoDebito'); Self.Adiciona('DtaIni', 'DataInicial'); Self.Adiciona('DTAINICOM', 'DataInicialDetalhamemento'); Self.Adiciona('DTAINIDET', 'DataInicialDetalhamemento'); Self.Adiciona('DTATERCOM', 'DataFinalComplemento'); Self.Adiciona('DTAEXAAMB', 'DataAvaliacaoAmbiente'); Self.Adiciona('DTAEXACLIPER', 'DataExameComplementar'); Self.Adiciona('DTAEXACLIAUD', 'DataExameAudiometrico'); Self.Adiciona('DTAVENEXACLIAUD', 'DataVencimentoExameAudiometrico'); Self.Adiciona('DTAVENEXAAMB', 'DataVencimentoAvaliacaoAmbiente'); Self.Adiciona('DTAVENEXACLIPER', 'DataVencimentoExameComplementar'); Self.Adiciona('DtaASO', 'DataASO'); Self.Adiciona('DTATERDET', 'DataFinalDetalhamento'); Self.Adiciona('DARCENMAT', 'AcumulaDARFMatrizFilialFolhaPagamento'); Self.Adiciona('DDDCid', 'DDDCidade'); Self.Adiciona('DtaEmiCtbSpg', 'DataEmissaoContabilizacaoSopag'); Self.Adiciona('DtaEmiImpFed', 'DataEmissaoImpostoFederal'); Self.Adiciona('DtaEntImpFed', 'DataEntradaImpostoFederal'); Self.Adiciona('DtaEtqFin', 'DataEstoqueFinal'); Self.Adiciona('DtaPgtCtbSpg', 'DataPagamentoContabilizacaoSopag'); Self.Adiciona('DtaPgtSpg', 'DataPagamentoSopag'); Self.Adiciona('DtaPrd', 'DataProducao'); Self.Adiciona('DtaIniUtlIte', 'DataInicioUtilizacaoItem'); Self.Adiciona('DtaIniTabDin', 'DataInicioTabelaDinamica'); Self.Adiciona('DtaFimTabDin', 'DataFimTabelaDinamica'); Self.Adiciona('DtaFin', 'DataFinal'); Self.Adiciona('DtaFinUtlite', 'DataFimUtilizacaoItem'); Self.Adiciona('DebEspApuIcm', 'DebitosEspeciais'); Self.Adiciona('DebEspSubTrbApuIcm', 'ValorDebitoEspecialSubstituicaoTributaria'); Self.Adiciona('DebSaiApuIpi', 'ValorDebitosApuracaoIPI'); Self.Adiciona('DebSobSaiApuIcm', 'DebitoSobreSaidaApuracaoICMS'); Self.Adiciona('DebSldCnt', 'ValorDebitoSaldo'); Self.Adiciona('Dec29179De19Jun08', 'Decreto29179De19Junho2008'); Self.Adiciona('DedApuIcm', 'ValorTotalDeducao'); Self.Adiciona('DedApuIpi', 'ValorDeducoesApuracaoIPI'); Self.Adiciona('DecModAliRatEmp', 'DecisaoModificandoRat'); Self.Adiciona('DecSusAltAliFapAplCbt', 'DecisaoSuspendendoAlterandoFap'); Self.Adiciona('DedConCbtInd', 'DeducaoContribuinteIndividual'); Self.Adiciona('DedFalPrgFrs', 'DeduzFaltasProgramacaoFerias'); Self.Adiciona('DedPisConPreEsc', 'DeducaoPISCOFINSPreferenciaEscrita'); Self.Adiciona('DEMCODFISAUSEFDCTBPRDALQBAS', 'DemonstrarCFOPausenteDaEFDContribuicoesEmProdutosAliquotaBasica'); Self.Adiciona('DEMDOCFISNAOGERCRDAPUREFDCTR', 'DemonstrarDocFiscalNaoGeradorDeCREDITONaApuracaoEFDContribuicoes'); Self.Adiciona('DEMDOCFISNAOGERDEBAPUREFDCTR', 'DemonstrarDocFiscalNaoGeradorDeDEBITONaApuracaoEFDContribuicoes'); Self.Adiciona('DepExiSupSplNacTri', 'DepositoExigibilidadeSuspensa'); Self.Adiciona('DepExiSupApuSplNac', 'DepositoExigibilidadeSuspensaApuracao'); Self.Adiciona('DepPreConPat', 'CodigoHistoricoDepreciacao'); Self.Adiciona('DepPreHis', 'HistoricoDepreciacao'); Self.Adiciona('DesAbn', 'DescontarAbono'); Self.Adiciona('DesAss', 'DescontarAssiduidade'); Self.Adiciona('DesFer', 'DescontarFerias'); Self.Adiciona('DesFlgMotFlg', 'DescontoFolgaMotivoFolga'); Self.Adiciona('DesFolEmp', 'DesoneraFolhaEmpresa'); Self.Adiciona('DesISSCbtInd', 'DescontaISSContribuinteIndividual'); Self.Adiciona('DesMovPagRec', 'DescontoMovimentacaoPagarReceber'); Self.Adiciona('DesPrd', 'DescricaoProdutoAliquotaUnidadeMedida'); Self.Adiciona('DesRenTit', 'DescontoRenegociacaoTitulo'); Self.Adiciona('DesResUndVen', 'DescricaoResumidaUnidadeVendida'); Self.Adiciona('DgtTriFed', 'DigitoVerificadorTributoFederal'); Self.Adiciona('DtaRef', 'DataReferencia'); Self.Adiciona('DtaResDiaTrb', 'ContaDataRescisaoDiaDeTrabalho'); Self.Adiciona('DiaAviDocFis', 'DiasAvisoVencimentoDocumentoFiscal'); Self.Adiciona('DiaFecFolPreFol','DiaFechamentoFolha'); Self.Adiciona('DiaLanPadFix', 'DiaLancamentoPadraoFixo'); Self.Adiciona('DiaVctEmpGerCtb', 'DiaVencimento'); Self.Adiciona('DiaVctOgc', 'DiaVencimentoObrigacao'); Self.Adiciona('DifAliCodFis', 'DiferencialAliquotaCodigoFiscal'); Self.Adiciona('DifAliOutDebOutVlrFis', 'DiferencialAliquotaOutrosDebitos'); Self.Adiciona('DifConFco', 'DiferencaContabilidadeFCont'); Self.Adiciona('DigVerConCor', 'DigitoVerificadorContaCorrente'); Self.Adiciona('DoaEle', 'DoacoesEleitorais'); Self.Adiciona('DocAtzDocFis', 'DocumentoAutorizacaoDocumentoFiscal'); Self.Adiciona('DocExiRet', 'DocumentoExigeRetorno'); Self.Adiciona('DocLan', 'DocumentoLancamento'); Self.Adiciona('DscAdiIaf', 'DescricaoAdicaoItemAtivoFixo'); Self.Adiciona('DscAgeRis', 'DescricaoAgenteRisco'); Self.Adiciona('DscAgeQui', 'DescricaoAgenteQuimico'); Self.Adiciona('DscAjuApuIpi', 'DescricaoAjusteApuracaoIPI'); Self.Adiciona('DscAltCnt', 'DescricaoAlternativaConta'); Self.Adiciona('DscAltVlrMan', 'DescricaoAlternativaValorManual'); Self.Adiciona('DscAnaMatBio', 'DescricaoAnaliseMaterialBiologico'); Self.Adiciona('DscAno', 'DescricaoAnotacaoCTPS'); Self.Adiciona('DscAbn', 'DescricaoAbono'); Self.Adiciona('DscAtvAgeRis', 'DescricaoAtividadeAgenteRisco'); Self.Adiciona('DscAtvExeOcuPro', 'DescricaoAtividadeExercidaOcupacaoProfissional'); Self.Adiciona('DscAtvSggSupSpl', 'DescricaoAtividadeSegregacaoSuperSimples'); Self.Adiciona('DscHisLlr', 'DescricaoHistoricoLALUR'); Self.Adiciona('DscBasCalCre', 'DescricaoBaseCalculoCredito'); Self.Adiciona('DscCenCus', 'DescricaoCentroDeCusto'); Self.Adiciona('DscCenNeg', 'DescricaoCentroNegocio'); Self.Adiciona('DscCerAprIteEpi', 'DescricaoCertificadoAprovacaoItemEPI'); Self.Adiciona('DscCfgCtb', 'DescricaoConfiguracaoContabil'); Self.Adiciona('DscClaFis', 'DescricaoClassificacaoFiscal'); Self.Adiciona('DscClaSerCsm', 'DescricaoClassificacaoServicoConsumo'); Self.Adiciona('DscCnt', 'DescricaoConta'); Self.Adiciona('DscCntLlr', 'DescricaoContaLalur'); Self.Adiciona('DscCntPtb', 'DescricaoContaParteB'); Self.Adiciona('DscCntRef', 'DescricaoContaReferencial'); Self.Adiciona('DscCodAjuApuIcmEFD', 'DescricaoCodigoAjusteApuracaoICMSEFD'); Self.Adiciona('DscCodAjuApuIpi', 'DescricaoCodigoAjusteApuracaoIPIEFD'); Self.Adiciona('DscCodFis', 'DescricaoCodigoFiscal'); Self.Adiciona('DscCodFisExc', 'DescricaoCodigoFiscalExcecao'); Self.Adiciona('DscCodOcoAjuIcmEFD', 'DescricaoCodigoOcorrenciaAjusteEFD'); Self.Adiciona('DscComAjuBenIncApuIcmEFD', 'DescricaoComplementarAjusteBeneficioIncentivoApuracaoICMSEFD'); Self.Adiciona('DscComAjuDocFis', 'DescricaoComplementarAjusteDocumentoFiscal'); Self.Adiciona('DscComInfAdiAjuApuIcm', 'DescricaoComplementarInformacaoAdicionalApuracaoICMS'); Self.Adiciona('DscComInfAdiApuVlrDec', 'DescricaoComplementarInformacaoAdicionalApuracaoValorDeclaratorioEFD'); Self.Adiciona('DscComObrIcmRecEfd', 'DescricaoComplementarObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('DscComOutObrDocFisEFD', 'DescricaoComplementarOutrasObrigacoesDocumentoFiscal'); Self.Adiciona('DscCrg', 'DescricaoCargo'); Self.Adiciona('DscCrs', 'DescricaoCurso'); Self.Adiciona('DscCtvGenIndMoe', 'DescricaoCentavoGeneroIndexadorMoeda'); Self.Adiciona('DscCtvPluIndMoe', 'DescricaoCentavoPluralIndexadorMoeda'); Self.Adiciona('DscCtvSinIndMoe', 'DescricaoCentavoSingularIndexadorMoeda'); Self.Adiciona('DscDep', 'DescricaoDepartamento'); Self.Adiciona('Descricao', 'DescricaoEventoMigracao'); Self.Adiciona('DscDoc', 'DescricaoDocumento'); Self.Adiciona('DSCLOT', 'DescricaoLotacao'); Self.Adiciona('DscDocOutOpe', 'DescricaoDocumentoOutrasOperacoes'); Self.Adiciona('DscEmiCupFis', 'DescricaoEmissorCupomFiscal'); Self.Adiciona('DscPro', 'DescricaoProcesso'); Self.Adiciona('DscPosPrd', 'DescricaoPosseProduto'); Self.Adiciona('DscEsp', 'DescricaoEspecie'); Self.Adiciona('DscEspDocBol', 'DescricaoEspecieDocumento'); Self.Adiciona('DscEspRecEst', 'DescricaoEspecieRecolhimentoEstadual'); Self.Adiciona('DscEttDmt', 'DescricaoEstrutura'); Self.Adiciona('DscFpa', 'DescricaoFPAS'); Self.Adiciona('DscFonPgt', 'DescricaoFontePagadora'); Self.Adiciona('DSCGROPRD', 'DescricaoGeneroProduto'); Self.Adiciona('DscGrpHis', 'DescricaoGrupoHistorico'); Self.Adiciona('DscGrpOgc', 'DescricaoGrupoObrigacao'); Self.Adiciona('DscIstBolCob', 'DescricaoBoleto'); Self.Adiciona('DscHis','DescricaoHistorico'); Self.Adiciona('DscIaf', 'DescricaoItemAtivoFixo'); Self.Adiciona('DscInfAdiApu', 'DescricaoCodigoInformacaoAdicionalApuracaoEFD'); Self.Adiciona('DscInfComObs', 'DescricaoInformacaoComplementarObservacao'); Self.Adiciona('DscIteEpi', 'DescricaoItemEPI'); Self.Adiciona('DscIteSpg', 'DescricaoItemSopag'); Self.Adiciona('DscIncTri', 'DescricaoIncidenciaTributaria'); Self.Adiciona('DscLanPad', 'DescricaoLancamentoPadrao'); Self.Adiciona('DscLanPta', 'DescricaoLancamentoParteA'); Self.Adiciona('DscLayPto', 'DescricaoLayoutPonto'); Self.Adiciona('DscLcr', 'DescricaoLucro'); Self.Adiciona('DscLocBem', 'DescricaoLocalizacaoBem'); Self.Adiciona('DscMac', 'DescricaoMacro'); Self.Adiciona('DscMar', 'DescricaoMarca'); Self.Adiciona('DscMarEmiCupFis', 'DescricaoMarcaEmissorCupomFiscal'); Self.Adiciona('DscModCnt', 'DescricaoModeloConta'); Self.Adiciona('DscMoeGenIndMoe', 'DescricaoMoedaGeneroIndexadorMoeda'); Self.Adiciona('DscMoePluIndMoe', 'DescricaoMoedaPluralIndexadorMoeda'); Self.Adiciona('DscMoeSinIndMoe', 'DescricaoMoedaSingularIndexadorMoeda'); Self.Adiciona('DscMotCarCor', 'DescricaoMotivoCartaCorrecao'); Self.Adiciona('DscMotFlg', 'DescricaoMotivoFolga'); Self.Adiciona('DscMqnCta', 'DescricaoMaquinaColetora'); Self.Adiciona('DscMsg', 'DescricaoMensagem'); Self.Adiciona('DscModDocFis', 'DescricaoModeloDocumentoFiscal'); Self.Adiciona('DscNacPai', 'DescricaoNacionalidade'); Self.Adiciona('DscNaoRgtPto', 'DescricaoNaoRegistraPonto'); Self.Adiciona('DscNatRecSpd', 'DescricaoNaturezaReceita'); Self.Adiciona('DscNiv', 'DescricaoNivel'); Self.Adiciona('DscObsEsc', 'DescricaoObservacaoEscritaFiscal'); Self.Adiciona('DscOpeDie', 'DescricaoOperacaoDie'); Self.Adiciona('DscOcuPro', 'DescricaoOcupacaoProfissional'); Self.Adiciona('DscOgc', 'DescricaoObrigacao'); Self.Adiciona('DscOpcSpl', 'DescricaoOpcaoSimples'); Self.Adiciona('DscOpePlaSau', 'DescricaoOperadorPlanoSaude'); Self.Adiciona('DscOutValFis', 'DescricaoOutrosValoresFiscais'); Self.Adiciona('DscOrgReg', 'DescricaOrgaoRegistro'); Self.Adiciona('DscOriMer', 'DescricaoOrigemMercadoria'); Self.Adiciona('DscPai', 'DescricaoPais'); Self.Adiciona('DscParCnt', 'DescricaoParametroConta'); Self.Adiciona('DscPrdCom', 'DescricaoProduto'); Self.Adiciona('DscPrePon', 'DescricaoPreferenciaPonto'); Self.Adiciona('DscPrj', 'DescricaoPrejuizo'); Self.Adiciona('DscQuaPesJur', 'DescricaoQualificacaoPessoaJuridica'); Self.Adiciona('DscRamAti', 'DescricaoRamoAtividade'); Self.Adiciona('DscRecRetFon', 'DescricaoRecolhimentoRetidoFonte'); Self.Adiciona('DSCRESAJU', 'DescricaoResumidaAjuste'); Self.Adiciona('DscResObrIcmRecEfd', 'DescricaoResumidaObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('DscResGrpEtt', 'DescricaoResultadoGrupo'); Self.Adiciona('DscResProAjuApu', 'DescricaoResumidaProcessoAjusteApuracao'); Self.Adiciona('DscResProInfAdiAjuApuIcm', 'DescricaoResumidaInformacaoAdicionalApuracaoICMS'); Self.Adiciona('DscRgmPrv', 'DescricaoRegimePrevidenciario'); Self.Adiciona('DscSal', 'DescricaoSala'); Self.Adiciona('DscSec', 'DescricaoSecao'); Self.Adiciona('DscSerLei', 'DescricaoServicoLei'); Self.Adiciona('DscSerPre', 'DescricaoServicoPrestado'); Self.Adiciona('DscSggPreSerSupSpl', 'DescricaoSegregacaoPrestacaoServicoSuperSimples'); Self.Adiciona('DscSir', 'DescricaoSirene'); Self.Adiciona('DscSubGrpEtt', 'DescricaoSubGrupo'); Self.Adiciona('DscSitBem', 'DescricaoSituacaoBem'); Self.Adiciona('DscSitEpg', 'DescricaoSituacaoEmpregado'); Self.Adiciona('DscSitEsp', 'DescricaoSituacaoEspecial'); Self.Adiciona('DscSitTrbImp', 'DescricaoSituacaoTributaria'); Self.Adiciona('DscSpdPisCof511', 'DescricaoSpedFiscalPisCofins511'); Self.Adiciona('DscTabDinL210', 'DescricaoTabelaDinamicaL210'); Self.Adiciona('DscTabDim350', 'DescricaoTabelaDinamicaM350'); Self.Adiciona('DSCTABDIN500', 'DescricaoTabelaDinamicaN500'); Self.Adiciona('DSCTABDIN600', 'DescricaoTabelaDinamicaN600'); Self.Adiciona('DSCTABDIN610', 'DescricaoTabelaDinamicaN610'); Self.Adiciona('DSCTABDIN620', 'DescricaoTabelaDinamicaN620'); Self.Adiciona('DSCTABDIN630', 'DescricaoTabelaDinamicaN630'); Self.Adiciona('DSCTABDIN650', 'DescricaoTabelaDinamicaN650'); Self.Adiciona('DSCTABDIN660', 'DescricaoTabelaDinamicaN660'); Self.Adiciona('DSCTABDIN670', 'DescricaoTabelaDinamicaN670'); Self.Adiciona('DSCTABDIP200', 'DescricaoTabelaDinamicaP200'); Self.Adiciona('DSCTABDIP300', 'DescricaoTabelaDinamicaP300'); Self.Adiciona('DSCTABDIP400', 'DescricaoTabelaDinamicaP400'); Self.Adiciona('DSCTABDIP500', 'DescricaoTabelaDinamicaP500'); Self.Adiciona('DSCTABDIM010', 'DescricaoTabelaDinamicaM010'); Self.Adiciona('DSCTABDIM300', 'DescricaoTabelaDinamicaM300'); Self.Adiciona('DSCTABDIT120', 'DescricaoTabelaDinamicaT120'); Self.Adiciona('DSCTABDIT150', 'DescricaoTabelaDinamicaT150'); Self.Adiciona('DSCTABDIT170', 'DescricaoTabelaDinamicaT170'); Self.Adiciona('DSCTABDIT181', 'DescricaoTabelaDinamicaT181'); Self.Adiciona('DSCTABDIU180', 'DescricaoTabelaDinamicaU180'); Self.Adiciona('DSCTABDIU182', 'DescricaoTabelaDinamicaU182'); Self.Adiciona('DscSpdEcfPai', 'DescricaoSpedECFPais'); Self.Adiciona('DscTec', 'DescricaoTecnica'); Self.Adiciona('DscTipAqu', 'DescricaoTipoAquisicao'); Self.Adiciona('DscTipBai', 'DescricaoTipoBaixaCiap'); Self.Adiciona('DscTipCre', 'DescricaoTipoCredito'); Self.Adiciona('DscTipBem', 'DescricaoTipoBem'); Self.Adiciona('DscTipExa', 'DescricaoTipoExame'); Self.Adiciona('DscTipUtiCreFisIcm', 'DescricaoTipoUtilizacaoCreditosFiscaisIcms'); Self.Adiciona('DscTitGrpEtt', 'DescricaoTituloGrupo'); Self.Adiciona('DscTipOcoGerCtb', 'DescricaoTipoOcorrencia'); Self.Adiciona('DscTrb', 'DescricaoTributacao'); Self.Adiciona('DscTriFed', 'DescricaoTributoFederal'); Self.Adiciona('DscUndGes', 'DescricaoUnidadeGestora'); Self.Adiciona('DscUndOrc', 'DescricaoUnidadeOrcamentaria'); Self.Adiciona('DscUniMed', 'DescricaoUnidadeMedida'); Self.Adiciona('DscVlrMan', 'DescricaoValorManual'); Self.Adiciona('DsdReqOcuPro', 'DescricaoRequisitoOcupacaoProfissional'); Self.Adiciona('DtaAbeSpg', 'DataAberturaSopag'); Self.Adiciona('DtaAdmConInd', 'DataAdmissaoContribuinteIndividual'); Self.Adiciona('DtaAdmScoEmp', 'DataAdmissaoSocio'); Self.Adiciona('DtaAdiIaf', 'DataAdicaoItemAtivoFixo'); Self.Adiciona('DtaAprIteEpi', 'DataAprovacaoItemEPI'); Self.Adiciona('DtaValIteEpi', 'DataValidacaoItemEPI'); Self.Adiciona('DtaVncSpg', 'DataVencimentoSopag'); Self.Adiciona('DtaAnoProFrs', 'DataAnotacaoProgramacaoFerias'); Self.Adiciona('DtaAqsIaf', 'DataAquisicaoItemAtivoFixo'); Self.Adiciona('DtaAltQdrSco', 'DataAlteracaoQuadroSocietario'); Self.Adiciona('DtaAvbEpt', 'DataAverbacaoDeclaracaoExportacao'); Self.Adiciona('DtaBaiCia', 'DataBaixaCiapItemAtivoFixo'); Self.Adiciona('DtaBasItePatLiq', 'DataBaseItemPatrimonioLiquido'); Self.Adiciona('DtaBloMesAnoEmpAreAtu', 'DataBloqueioMesAno'); Self.Adiciona('DtaChc', 'DataConhecimentoEmbarque'); Self.Adiciona('DtaConIns', 'DataConsumoInsumo'); Self.Adiciona('DtaConSitEmp', 'DataSituacaoEmpresa'); Self.Adiciona('DtaCreCOF','DataDebitoCreditoCOFINS'); Self.Adiciona('DtaCrePIS','DataDebitoCreditoPIS'); Self.Adiciona('DtaDcl', 'DataDeclaracao'); Self.Adiciona('DtaDesCbtInd', 'DataDesligamentoContribuinteIndividual'); Self.Adiciona('DtaDesScoEmp', 'DataDesligamentoSocio'); Self.Adiciona('DtaDetVlrManDemRes', 'DataDetalhamentoValorManual'); Self.Adiciona('DtaDgtLan', 'DataDigitacaoLancamento'); Self.Adiciona('DtaDigLanLcx', 'DataDigitacaoLancamentoLivroCaixa'); Self.Adiciona('DtaDigEcf', 'DataDigitacaoEmissorCupomFiscal'); Self.Adiciona('DtaDigMov', 'DataDigitacaoNotaFiscal'); Self.Adiciona('DtaDoc', 'DataDocumento'); Self.Adiciona('DtaEmiDocFis', 'DataEmissaoDocumentoFiscal'); Self.Adiciona('DtaEmiEcf', 'DataEmissaoEmissorCupomFiscal'); Self.Adiciona('DtaEmiMov', 'DataEmissaoNotaFiscal'); Self.Adiciona('DtaDocInfComNotRef', 'DataEmissaoNotaFiscalReferenciada'); Self.Adiciona('DtaEmiMovPagRec', 'DataEmissaoMovimentacaoPagarReceber'); Self.Adiciona('DtaEntSai', 'DataEntradaSaida'); Self.Adiciona('DtaEntSaiMov', 'DataEntradaSaidaNotaFiscal'); Self.Adiciona('DtaEntSaiMovExt', 'DataEntradaSaidaNotaFiscalExtemporanea'); Self.Adiciona('DtaEmiMovExt', 'DataEmissaoNotaFiscalExtemporanea'); Self.Adiciona('DtaEveCreDec', 'DataEventoCreditosDecorrentes'); self.Adiciona('DtaEveLicMed', 'DataEventoLicencaMedica'); Self.Adiciona('DtaFatAntApuSplNac', 'DataFaturamentoAnteriorApuracaoSimplesNacional'); Self.Adiciona('DtaExeMov', 'DataExercicioMovimentacao'); Self.Adiciona('DtaFimSitTrbImp', 'DataFimSituacaoTributaria'); Self.Adiciona('DtaFimQdrSco', 'DataFimQuadroSocietario'); Self.Adiciona('DtaFimApu', 'DataFinalApuracao'); Self.Adiciona('DtaFimPerApu', 'DataFimPeriodoApuracao'); Self.Adiciona('DtaFin', 'DataFinal'); Self.Adiciona('DtaFinAboPrgFrs', 'DataFinalAbonoProgramacaoFerias'); Self.Adiciona('DtaFinApuIcm', 'DataFinalApuracaoICMS'); Self.Adiciona('DtaFinApuIcmSubTrb', 'DataFimApuracaoSubstituicaoTributaria'); Self.Adiciona('DtaFinApuIpi', 'DataFimApuracaoIPI'); Self.Adiciona('DtaFinApuSplNac', 'DataFinalApuracaoSimplesNacional'); Self.Adiciona('DtaFinAquItePrgFrs', 'DataFinalAquisicaoItemProgramacaoFerias'); Self.Adiciona('DtaFinAquPrgFrs', 'DataFinalAquisicaoProgramacaoFerias'); Self.Adiciona('DtaFinAtiScd', 'DataFinalSociedade'); Self.Adiciona('DtaFinConVlrIpi', 'DataFinalConsolidacaoValorIPI'); Self.Adiciona('DtaFinConPrgFrs', 'DataFinalConcessaoProgramacaoFerias'); Self.Adiciona('DtaFinEnqLimEnqEmp', 'DataFinalEnquadramento'); Self.Adiciona('DtaFinExeLlrEmpCtb', 'DataFimExercicioLALUR'); Self.Adiciona('DtaFinFaiVlrFatRseSplNac', 'DataFinalFaixaValorSimplesNacional2009'); Self.Adiciona('DtaFinFaiVlrFatRSeSplNac', 'DataFinalFaixaValorFatorRSimplesNacional2009'); Self.Adiciona('DtaFinGozPrgFrs', 'DataFinalGozoProgramacaoFerias'); Self.Adiciona('DtaFinInfAdiApu', 'DataTerminoCodigoInformacaoAdicionalApuracaoEFD'); Self.Adiciona('DtaFinLicRem', 'DataFinalLicencaRemunerada'); Self.Adiciona('DtaFinLimEnq', 'DataFinalLimiteEnquadramento'); Self.Adiciona('DtaFinMon', 'DataFinalMonitoracao'); Self.Adiciona('DtaFinMovInv', 'DataFinalInventario'); Self.Adiciona('DtaFinTblNatRec', 'DataFimNaturezaReceita'); Self.Adiciona('DtaFinPer', 'DataTerminoPeriodo'); Self.Adiciona('DtaFinPro', 'DataFinalProducao'); Self.Adiciona('DtaFinQuaPesJur', 'DataFinalQualificacaoPessoaJuridica'); Self.Adiciona('DtaFinVal', 'DataFinalValidade'); Self.Adiciona('DtaFinRsp', 'DataTerminoResponsabilidade'); Self.Adiciona('DtaFimSpdPisCof511', 'DataFimSpedPisCofins'); Self.Adiciona('DtaFimPerComali', 'DataFimPercentualComplementoAliquota'); Self.Adiciona('DtaImpSisVlrIni', 'DataImplantacaoSistema'); Self.Adiciona('DtaIncAlt', 'DataInclusaoAlteracao'); Self.Adiciona('DtaIni', 'DataInicio'); Self.Adiciona('DtaIniAboPrgFrs', 'DataInicioAbonoProgramacaoFerias'); Self.Adiciona('DtaIniApuIcm', 'DataInicialApuracaoICMS'); Self.Adiciona('DtaIniApuIcmSubTrb', 'DataInicioApuracaoSubstituicaoTributaria'); Self.Adiciona('DtaIniApuIpi', 'DataInicioApuracaoIPI'); Self.Adiciona('DtaIniApu', 'DataInicioApuracao'); Self.Adiciona('DtaIniApuSplNac', 'DataInicioApuracaoSimplesNacional'); Self.Adiciona('DtaIniAqu', 'DataInicioAquisicao'); Self.Adiciona('DtaIniAquPrgFrs', 'DataInicioAquisicaoProgramacaoFerias'); Self.Adiciona('DtaIniAtvEmp', 'DataInicioAtividades'); Self.Adiciona('DtaIniAtiScd', 'DataInicioSociedade'); Self.Adiciona('DtaIniBcoHrs', 'DataInicioBancoHoras'); Self.Adiciona('DtaIniCodAjuApuIcmEFD', 'DataInicioCodigoAjusteApuracaoICMSEFD'); Self.Adiciona('DtaIniCodAjuApuIpi', 'DataInicioCodigoAjusteApuracaoIPIEFD'); Self.Adiciona('DtaIniCodOcoAjuIcmEFD', 'DataInicioCodigoOcorrenciaAjusteEFD'); Self.Adiciona('DtaIniConPrgFrs', 'DataInicioConcessaoProgramacaoFerias'); Self.Adiciona('DtaIniConVlrIpi', 'DataInicialConsolidacaoValorIPI'); Self.Adiciona('DtaIniEnqLimEnqEmp', 'DataInicialEnquadramento'); Self.Adiciona('DtaIniEtqDia', 'DataInicioEstoqueDia'); Self.Adiciona('DtaIniExeLlrEmpCtb', 'DataInicioExercicioLALUR'); Self.Adiciona('DtaIniFaiVlrFatRseSplNac', 'DataInicialFaixaValorSimplesNacional2009'); Self.Adiciona('DtaIniFaiVlrFatRSeSplNac', 'DataInicialFaixaValorFatorRSimplesNacional2009'); Self.Adiciona('DtaIniFatGerMovMen', 'DataInicioFatoGerador'); Self.Adiciona('DtaFinFatGerMovMen', 'DataFinalFatoGerador'); Self.Adiciona('DtaIniInfAdiApu', 'DataInicioCodigoInformacaoAdicionalApuracaoEFD'); Self.Adiciona('DtaIniInt', 'DataInicioIntegracao'); Self.Adiciona('DtaIniGozPrgFrs', 'DataInicioGozoProgramacaoFerias'); Self.Adiciona('DtaIniLicRem', 'DataInicialLicencaRemunerada'); Self.Adiciona('DtaIniLimEnq', 'DataInicialLimiteEnquadramento'); Self.Adiciona('DtaIniMon', 'DataInicialMonitoracao'); Self.Adiciona('DtaIniMovInv', 'DataInicialInventario'); Self.Adiciona('DtaIniPer', 'DataInicioPeriodo'); Self.Adiciona('DtaIniPerAnt', 'DataInicioPeriodoAnterior'); Self.Adiciona('DtaIniPerNov', 'DataInicioPeriodoNovo'); Self.Adiciona('DtaIniPro', 'DataInicioProducao'); Self.Adiciona('DtaIniQuaPesJur', 'DataInicialQualificacaoPessoaJuridica'); Self.Adiciona('DtaIniTblNatRec', 'DataInicioNaturezaReceita'); Self.Adiciona('DtaIniRsp', 'DataInicioResponsabilidade'); Self.Adiciona('DtaIniSalMin', 'DataInicioSalarioMinimo'); Self.Adiciona('DtaIniSitTrbImp', 'DataInicioSituacaoTributaria'); Self.Adiciona('DtaIniSpdPisCof511', 'DataInicioSpedPisCofins'); Self.Adiciona('DtaIniTipUtiCreFisIcm', 'DataInicioTipoUtilizacaoCreditosFiscaisIcms'); Self.Adiciona('DtaIniVal', 'DataInicioValidade'); Self.Adiciona('DtaIniPerComAli', 'DataInicioPercentualComplementoAliquota'); Self.Adiciona('DtaLan', 'DataLancamento'); Self.Adiciona('DtaLimAdiExcCom', 'DataLimiteAdicaoExclusaoCompensacao'); Self.Adiciona('DtaLanEfd', 'DataLancamentoEFD'); Self.Adiciona('DtaLanAjuApuIpi', 'DataLancamentoAjusteApuracaoIPI'); Self.Adiciona('DtaLanAjuBenIncApuIcmEFD', 'DataLancamentoAjusteBeneficioIncentivoApuracaoICMSEFD'); Self.Adiciona('DtaLanInfAdiApuVlrDec', 'DataLancamentoInformacaoAdicionalApuracaoValorDeclaratorioEFD'); Self.Adiciona('DtaLanLcx', 'DataLancamentoLivroCaixa'); Self.Adiciona('DtaLanOutVlrFis', 'DataLancamentoOutrosValoresFiscais'); Self.Adiciona('DtaLanSerPreFol', 'DataLancamentoServicoPrestado'); Self.Adiciona('DtaLeiOcuPro', 'DataLeiOcupacaoProfissional'); Self.Adiciona('DtaMovCtb', 'DataMovimentacaoContabil'); Self.Adiciona('DtaMovDie', 'DataMovimentacaoDief'); Self.Adiciona('DtaMovIte', 'DataMovimentacaoItem'); Self.Adiciona('DtaNasCbtInd', 'DataNascimentoContribuinteIndividual'); Self.Adiciona('DtaObsEsc', 'DataObservacaoNotaFiscal'); Self.Adiciona('DtaOpcFGTCtbTIInd', 'DataOpcaoFGTSContribuinteIndividual'); Self.Adiciona('DtaOpe', 'DataOperacao'); Self.Adiciona('DtaOpeCom', 'DataDaOperacaoComercial'); Self.Adiciona('DtaOpeOutOpe', 'DataOperacaoOutrasOperacaoes'); Self.Adiciona('DtaPagMovPagRec', 'DataPagamentoMovimentacaoPagarReceber'); Self.Adiciona('DtaPagSerPreFol', 'DataPagamentoServicoPrestado'); Self.Adiciona('DtaPgtMov', 'DataPagamentoMovimentacao'); Self.Adiciona('DtaReaParHon', 'DataReajusteParametroHonorario'); Self.Adiciona('DtaRegCarEmp', 'DataRegistroCartorio'); Self.Adiciona('DtaRegEmpOrg', 'DataRegistroOrgao'); Self.Adiciona('DtaRegEpt', 'DataRegistroExportacao'); Self.Adiciona('DtaRegJunComEmp', 'DataRegistroJuntaComercial'); Self.Adiciona('DtaRenTit', 'DataRenegociacaoTitulo'); Self.Adiciona('DtaTerAtvEmp', 'DataTerminoAtividades'); Self.Adiciona('DtaTerCodAjuApuIcmEFD', 'DataTerminoCodigoAjusteApuracaoICMSEFD'); Self.Adiciona('DtaTerCodAjuApuIpi', 'DataTerminoCodigoAjusteApuracaoIPIEFD'); Self.Adiciona('DtaTerCodOcoAjuIcmEFD', 'DataTerminoCodigoOcorrenciaAjusteEFD'); Self.Adiciona('DtaTerTipUtiCreFisIcm', 'DataTerminoTipoUtilizacaoCreditosFiscaisIcms'); Self.Adiciona('DtaTri', 'DataImposto'); Self.Adiciona('DtaValDocFis', 'DataValidadeDocumentoFiscal'); Self.Adiciona('DtaVen', 'DataVencimento'); Self.Adiciona('DtaVenCreIaf', 'DataVencimentoCreditoItemAtivoFixo'); Self.Adiciona('DtaVenMovPgrRec', 'DataVencimentoMovimentacaoPagarReceber'); Self.Adiciona('DtaVenObrIcmRecEfd', 'DataVencimentoObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('DebImpRec', 'debitoImpostoARecolher'); Self.Adiciona('DESCOM', 'DescricaoComplementar'); Self.Adiciona('DesDecJud', 'DescricaoDecisaoJudicial'); Self.Adiciona('DscCntLcx', 'DescricaoContaLivroCaixa'); Self.Adiciona('DscCntLcxPad', 'DescricaoLivroCaixaPadrao'); Self.Adiciona('DscFazObr', 'descricaoCentroDeCustoLivroCaixa'); Self.Adiciona('DscGrpAce', 'DescricaoGrupoAcesso'); Self.Adiciona('DscGrpCntLcx', 'descricaoGrupoContaLcx'); Self.Adiciona('DSCGRPPRDANP', 'DescricaoGrupoCombustivel'); Self.Adiciona('DSCPRDANP','DescricaoCombustivel'); Self.Adiciona('DscRatLcx', 'descricaoRateioLcx'); Self.Adiciona('DOCOPEIMPMOV','TipoDocumentoImportacao'); Self.Adiciona('DTAAPLLACBOMCMB','DataAplicacao'); Self.Adiciona('DtaCad', 'DataCadastro'); Self.Adiciona('DtaDecAdm', 'DataDecisaoAdministrativa'); Self.Adiciona('DTAEMIGNR','DataEmissaoGNRE'); Self.Adiciona('DTAFECMOVCMB','DataFechamentoMovimentacao'); Self.Adiciona('DTANSCRSP','DataNascimentoSocioResponsavel'); Self.Adiciona('DTAINIAPUIMP','DataInicioApuracaoImposto'); Self.Adiciona('DTAFINAPUIMP','DataFinalApuracaoImposto'); Self.Adiciona('DTAPAGGNR','DataPagamentoGNRE'); Self.Adiciona('DTARECBRU', 'DataOperacaoReceiraBruta'); Self.Adiciona('DtaRecTriFed', 'DataReceitaTributoFederal'); Self.Adiciona('DtaRet', 'DataRetencao'); Self.Adiciona('DtaSaiEtq', 'DataSaidaEstoque'); Self.Adiciona('DtaSenJud', 'DataSentencaJudicial'); Self.Adiciona('DTAVENGNR','DataVencimentoGNRE'); Self.Adiciona('DRFGERIMPFED', 'GeraDRFImpostoFederal'); Self.Adiciona('DurSir', 'DuracaoSirene'); Self.Adiciona('FrmTrb', 'FormaTributacaoFCONT'); Self.Adiciona('DTADEC', 'DataDecisao'); Self.Adiciona('EdiBatEpg','EditarRegistrosPontoEmpregado'); Self.Adiciona('EfeLogPre', 'EfetuaLog'); Self.Adiciona('EfeLogPreGer', 'EfetuaLogGeral'); Self.Adiciona('EmaComPes', 'EmailComercialPessoa'); Self.Adiciona('EmaEct', 'EmailEscritorio'); Self.Adiciona('EmaEmp', 'Email'); Self.Adiciona('EmaRspTcm', 'EmailResponsavelTCM'); Self.Adiciona('EmaScoRsp', 'EmailSocioResponsavel'); Self.Adiciona('EmaResPes', 'EmailResidencialPessoa'); Self.Adiciona('EmiAviFalIntMovPreEsc', 'EmiteAvisoIntegracaoContabilNotaFiscalPreferenciaEscrita'); Self.Adiciona('EmpCenGrpEco', 'EmpresaCentralizadoraGrupoEconomico'); Self.Adiciona('EmpCtb', 'EmpresaContabil'); Self.Adiciona('EmpDefMscCnt', 'MascaraDefinidaEmpresa'); Self.Adiciona('EmpEnq', 'EmpresaEnquadradaArtigo48'); Self.Adiciona('EmpGerEscFisDig', 'GeraEscrituracaFiscalDigital'); Self.Adiciona('EmpGerEfdPisCof', 'GeraEscrituracaFiscalDigitalPisCofins'); Self.Adiciona('EmpHab', 'EmpresaHabilitadaRepes'); Self.Adiciona('EmpSelPre', 'MantemEmpresaSelecionada'); Self.Adiciona('EmpExcCrePreEsl', 'EmpresaDedicaExclusivamenteAtividadeCrechePreEscolaPreferenciasEscrita'); Self.Adiciona('EncExePreCtb', 'CodigoHistoricoEncerramentoExercicio'); Self.Adiciona('EmpIntPrt', 'EmpresaIntegraPortal'); Self.Adiciona('EndIp', 'EnderecoIp'); Self.Adiciona('EntEtqDia', 'EntradaEstoqueDia'); Self.Adiciona('EspAltSerVal', 'EspecieAlternativa'); Self.Adiciona('EspOpeAnp', 'EspecificacaoCodigoOperacaoAnp'); Self.Adiciona('EstCivCbtInd', 'EstadoCivilContribuinteIndividual'); Self.Adiciona('EstCreApuIcm', 'EstornoCreditoApuracaoICMS'); Self.Adiciona('EstCreApuIpi', 'ValorEstornoCreditosApuracaoIPI'); Self.Adiciona('EstDebApuIcm', 'EstornoDebitoApuracaoICMS'); Self.Adiciona('EstDebApuIpi', 'ValorEstornoDebitosApuracaoIPI'); Self.Adiciona('EstIniEtqDia', 'EstoqueInicialEstoqueDia'); Self.Adiciona('ExcIcmRetApuCpsFat', 'ExcluiIcmsRetidoApuracaoComprasFaturamento'); Self.Adiciona('ExbNivZer', 'ExibeNiveisZerados'); Self.Adiciona('ExbSldPre', 'ExibicaoSaldos'); Self.Adiciona('ExiAtvNaoAbr', 'ExistenciaAtividadeNaoAbrangida'); Self.Adiciona('ExpExc', 'ExposicaoExcessiva'); Self.Adiciona('FaiFimFaiVlrFatRseSplNac', 'FaixaFinalFaixaValorSimplesNacional2009'); Self.Adiciona('FaiIniFaiVlrFatRseSplNac', 'FaixaInicialFaixaValorSimplesNacional2009'); Self.Adiciona('FaiFimFaiVlrFatRSeSplNac', 'FaixaFinalFaixaValorFatorRSimplesNacional2009'); Self.Adiciona('FaiIniFaiVlrFatRSeSplNac', 'FaixaInicialFaixaValorFatorRSimplesNacional2009'); Self.Adiciona('FatMar', 'FatorMarca'); Self.Adiciona('FatQtd20C', 'FatorQuantidade20C'); Self.Adiciona('FatUndMedEtq', 'FatorUnidadeMedida'); Self.Adiciona('FecPrgPre', 'PerguntaFecharPrograma'); Self.Adiciona('FinCodOpe', 'FinalidadeCodigoOperacaoAnp'); Self.Adiciona('FinExi', 'ExistenciaFINOR'); Self.Adiciona('FocApoLanPre', 'FocoAposLancamento'); Self.Adiciona('ForAgrPreFol','FormaAgrupamento'); Self.Adiciona('ForApuEstMen','FormaApuracaoEstimativaMensal'); Self.Adiciona('ForCalHorExePre','FormaCalculoHorasExtrasPreferencia'); Self.Adiciona('ForCtbPreFol','FormaContabilizar'); Self.Adiciona('ForCtbPreEsc','FormaContabilizacao'); Self.Adiciona('FORDOA','FormaDoacao'); Self.Adiciona('ForPagCbtInd', 'FormaPagamentoContribuinteIndividual'); Self.Adiciona('ForTrbLuc', 'FormaTributacaoLucro'); Self.Adiciona('ForTrbPer', 'FormaTributacaoPeriodo'); Self.Adiciona('FrmImpPrd','FormaImportacaoProduto'); Self.Adiciona('FrmIntPonPrt', 'FormaIntegracaoPontoPortal'); Self.Adiciona('FrmDtaLanCtbPre', 'FormatoDataLancamentoContabil'); Self.Adiciona('FrmLanPad', 'FormaLancamentoPadrao'); Self.Adiciona('FrmLanPre', 'FormaLancamento'); Self.Adiciona('FunIte', 'FuncaoItemAtivoFixo'); Self.Adiciona('GerAutBatEpg','GerarAutomaticamenteRegistrosPontoEmpregado'); Self.Adiciona('GerComCtbEmpEscInt','TipoComplementoContabil'); Self.Adiciona('GerConOpeIniPreEsc', 'GerarContadorOperacaoInicio'); Self.Adiciona('GerCodFisDif', 'GerarCodigoFiscalDif'); Self.Adiciona('GerCodFisDie', 'GerarCodigoFiscalDief'); Self.Adiciona('GerIcmRetCst60OutIcm', 'GerarIcmsRetidoCST60ParaOutrasICMS'); Self.Adiciona('GerVlrContISSOutICM', 'GerarValorContabilISSParaOutrasICMS'); Self.Adiciona('GerVlrNaoIncPatSfp', 'GerarValorNaoIncidenciaPatronalSefip'); Self.Adiciona('GerPrdSinPreEsc', 'GerarProdutosSINTEGRAPreferenciaEscrita'); Self.Adiciona('GerProRel', 'GeraProtocolo'); Self.Adiciona('GerVlrNaoTrbImpSin', 'GerarValorNaoTributadoImportacaSintegra'); Self.Adiciona('GraInsCbtInd', 'GrauInstrucaoContribuinteIndividual'); Self.Adiciona('GrpSeqLan', 'GrupoSequenciaLancamento'); Self.Adiciona('GrpSeqLanLcx', 'GrupoSequenciaLancamentoLivroCaixa'); Self.Adiciona('GrpSeqMovPgrRec', 'GrupoSequenciaMovimentacaoPagarReceber'); Self.Adiciona('GrpClaSerCsm', 'GrupoClassificacaoServicoConsumo'); Self.Adiciona('EmaFazObr', 'EmailCentroDeCustoLivroCaixa'); Self.Adiciona('EmaFor', 'EmailFornecedor'); Self.Adiciona('ENTLITMOVCMB','VolumeEntradaDia'); Self.Adiciona('ENTLITMOVTANCMB','VolumeEntradaDiaTanque'); Self.Adiciona('ETQABEMOVCMB','EstoqueInicioDia'); Self.Adiciona('ETQABEMOVTANCMB','EstoqueInicioDiaTanque'); Self.Adiciona('ETQFINMOVCMB','EstoqueFimDia'); Self.Adiciona('ETQFINMOVTANCMB','EstoqueFimDiaTanque'); Self.Adiciona('FABBOMCMB','Fabricante'); Self.Adiciona('FaxScoRsp', 'FaxSocioResponsavel'); Self.Adiciona('GANLITMOVCMB','ValordoGanho'); Self.Adiciona('GANLITMOVTANCMB','ValordoGanhoTanque'); Self.Adiciona('GerDocFisSpdPisCof', 'GerarDocumentoFiscalSpedPisCofins'); Self.Adiciona('GERDOCFISNAOGERCRDARQEFDCNT', 'GerarDocFiscalNaoGeradorDeCreditoNoArquivoEFDContribuicoes'); Self.Adiciona('HabTGCBox', 'HabilitadoTGCBox'); Self.Adiciona('HasEcfAnt', 'HashECFAnterior'); Self.Adiciona('HisPagPreLcx', 'CodigoHistoricoPagamento'); Self.Adiciona('HisRecPreLcx', 'CodigoHistoricoRecebimento'); Self.Adiciona('HisLanPtb', 'HistoricoLancamentoParteB'); Self.Adiciona('HisLanEla', 'HistoricoLancamentoElacs'); Self.Adiciona('HorIniInt', 'HorarioInicialIntervalo'); Self.Adiciona('HorTerInt', 'HorarioTerminoIntervalo'); Self.Adiciona('HrsSir', 'HoraSirene'); end; procedure TCustomDicionario.AdicionaAtributosIJKLM; begin Self.Adiciona('IndAprAvuInv', 'IndicadorApresentacaoAvulsaInventario'); Self.Adiciona('IndAprEscCtb', 'IndicadorApresentacaoEscrituracaoContabil'); Self.Adiciona('IndDocConArq', 'IndicadorDocumentoContidoNoArquivo'); Self.Adiciona('IndEntDad', 'IndicadorEntradaDados'); Self.Adiciona('IndExiAnuRegInv', 'IndicadorExigibilidadeAnualRegistroInventario'); Self.Adiciona('IndExiEscIcm', 'IndicadorExigibilidadeEscrituracaoICMS'); Self.Adiciona('IndExiEscIss', 'IndicadorExigibilidadeEscrituracaoISS'); Self.Adiciona('IndExiLivMovCom', 'IndicadorExigibilidadeLivroMovimentacaoCombustiveis'); Self.Adiciona('IndExiRegImpDoc', 'IndicadorExigibilidadeRegistroImpressaoDocumentos'); Self.Adiciona('IndExiRegUtiDoc', 'IndicadorExigibilidadeRegistroUtilizacaoDocumentos'); Self.Adiciona('IndExiRegVei', 'IndicadorExigibilidadeRegistroVeiculos'); Self.Adiciona('IndOpe', 'IndicadorOperacao'); Self.Adiciona('IndOpeAntTriIcmEnt', 'IndicadorOperacoesAntecipacaoTributariaICMSEntradas'); Self.Adiciona('IndOpeRetTriIcm', 'IndicadorOperacoesRetencaoTributariaICMS'); Self.Adiciona('IndOpeRetTriIss', 'IndicadorOperacoesRetencaoTributariaISS'); Self.Adiciona('IndOpeSjtIcm', 'IndicadorOperacoesSujeitaICMS'); Self.Adiciona('IndOpeSjtIpi', 'IndicadorOperacoesSujeitaIPI'); Self.Adiciona('IndOpeSjtIss', 'IndicadorOperacoesSujeitaISS'); Self.Adiciona('IndSitCntRefIni', 'IndicadorSituacaoContaReferencialInicial'); Self.Adiciona('IndSitCntRefFin', 'IndicadorSituacaoContaReferencialFinal'); Self.Adiciona('IndSldIni', 'IndicadorSaldoInicial'); Self.Adiciona('sldinicntperapu', 'SaldoInicialContaPeriodoApuracao'); Self.Adiciona('IndSldFin', 'IndicadorSaldoFinal'); Self.Adiciona('INDSLDFIS', 'IndicadorSaldoFiscal'); Self.Adiciona('INDSLDSOC', 'IndicadorSaldoSocietario'); Self.Adiciona('IndLanPtb', 'IndicadorLancamentoParteB'); Self.Adiciona('TipLanPta', 'TipoLancamentoParteA'); Self.Adiciona('IndEscAti', 'IndicadorEscrituracaoAtivo'); Self.Adiciona('INFCOMBLI100', 'InformacaoComplementarBlocoI100'); Self.Adiciona('INFCOMBLI200', 'InformacaoComplementarBlocoI200'); Self.Adiciona('INFCOMBLI300', 'InformacaoComplementarBlocoI300'); Self.Adiciona('IcmEstImpEst', 'PercentualICMSEstadual'); Self.Adiciona('IcmEstParGuiEst', 'IcmsEstimativaParcelaGuiaEstadual'); Self.Adiciona('IcmEppPriParGuiEst', 'IcmsEppPrimeiraParcelaGuiaEstadual'); Self.Adiciona('IcmEppSegParGuiEst', 'IcmsEppSegundaParcelaGuiaEstadual'); Self.Adiciona('IcmEppTerParGuiEst', 'IcmsEppTerceiraParcelaGuiaEstadual'); Self.Adiciona('IcmMicPriParGuiEst', 'IcmsMicroPrimeiraParcelaGuiaEstadual'); Self.Adiciona('IcmMicSegParGuiEst', 'IcmsMicroSegundaParcelaGuiaEstadual'); Self.Adiciona('IcmMicTerParGuiEst', 'IcmsMicroTerceiraParcelaGuiaEstadual'); Self.Adiciona('IcmNorPriParGuiEst', 'IcmsNormalPrimeiraParcelaGuiaEstadual'); Self.Adiciona('IcmNorSegParGuiEst', 'IcmsNormalSegundaParcelaGuiaEstadual'); Self.Adiciona('IcmPriDecParGuiEst', 'IcmsPrimeiroDecendioGuiaEstadual'); Self.Adiciona('IcmSegDecParGuiEst', 'IcmsSegundoDecendioGuiaEstadual'); Self.Adiciona('IcmTerDecParGuiEst', 'IcmsTerceiroDecendioGuiaEstadual'); Self.Adiciona('IdeEct', 'IdentidadeEscritorio'); Self.Adiciona('IdeTerEnvOpe', 'IdentificacaoDoTerceiroEnvolvidoNaOperacao'); Self.Adiciona('IdeNomEmp', 'IdentificacaoNomeEmpreendimento'); Self.Adiciona('IdeScoRsp', 'IdentidadeSocioResponsavel'); Self.Adiciona('ImpDtaHrsPreGer', 'ImprimeDataHora'); Self.Adiciona('ImpEmiDesPorInsEmpPreEsc', 'ImportacaoEmitenteDestinatarioInscricao'); Self.Adiciona('ImpNomLic', 'ImprimirNomeLicenca'); Self.Adiciona('ImpRecApuIcm', 'ValorICMSRecolherApuracaoICMS'); Self.Adiciona('ImpRecApuIpi', 'ValorImpostoRecolherApuracaoIPI'); Self.Adiciona('ImpPrdRgmEsp', 'ImportarProdutoRegimeEspecial'); Self.Adiciona('IncCiaCodFis', 'IncidenciaCiapCodigoFiscal'); Self.Adiciona('IncParDecTerPrgFrs', 'IncluiParcelaDecimoTerceiroProgramacaoFerias'); Self.Adiciona('IncCiaSegColCodFis', 'IncidenciaCiapSegundaColunaCodigoFiscal'); Self.Adiciona('IncFomProMic', 'IncidenciaFomentarProduzirMicroproduzir'); Self.Adiciona('IncFomProTotSai', 'IncidenciaFomentarProdutoTotalSaida'); Self.Adiciona('IncOutValFis', 'IncidenciaOutrosValoresFiscais'); Self.Adiciona('IncIns', 'IncidenciaINSS'); Self.Adiciona('IncIrr', 'IncidenciaIRRF'); Self.Adiciona('IncFgt', 'IncidenciaFGTS'); Self.Adiciona('IncConSin', 'IncidenciaContSindical'); Self.Adiciona('INDALQCSL', 'IndiceAliquotaCSLL'); Self.Adiciona('IndCon', 'IndicadorConteudo'); Self.Adiciona('IndCrgFre', 'IndicadorCargaTransportada'); Self.Adiciona('IndDoc', 'IndicadorTipoDocumento'); Self.Adiciona('IndDesSpd', 'IndicadorDescentralizacao'); Self.Adiciona('IndDifAlqAntInt', 'IndicadorDiferencialAliquotaAntecipacaoInterestadual'); Self.Adiciona('INDDIFSLD', 'IndicadorDiferencaSaldos'); Self.Adiciona('IndEmiMov', 'IndicadorEmitenteMovimentacao'); Self.Adiciona('IndEmiInfComNotRef', 'IndicadorEmitenteMovimentacaoReferenciada'); Self.Adiciona('IndMetAvaEtq', 'IndicadorMetodoAvaliacaoEstoque'); Self.Adiciona('IndOpeOutOpe', 'IndicadorOperacaoOutrasOperacoes'); Self.Adiciona('IndOriCre', 'IndicadorOrigemCredito'); Self.Adiciona('IndOriCreOutOpe', 'IndicadorOrigemCreditoOutrasOperacoes'); Self.Adiciona('IndOriDocAjuApuIpi', 'IndicadorOrigemDocumentoApuracaoIPI'); Self.Adiciona('IndOriPro', 'IndicadorOrigemProcesso'); Self.Adiciona('IndOriProAjuApu', 'IndicadorOrigemProcessoAjusteApuracao'); Self.Adiciona('IndOriProIndAjuApuIcm', 'IndicadorOrigemProcessoInformacaoAdicionalApuracaoICMS'); Self.Adiciona('IndOriProObrIcmRecEfd', 'IndicadorOrigemProcessoObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('IndOrgPub', 'IndicadorOrgaoPublico'); Self.Adiciona('IndProMovInv', 'IndicadorPropriedadeInventario'); Self.Adiciona('IndNatDir', 'IndicadorNaturezaDirigente'); Self.Adiciona('IndNumPar', 'IndicadorNumeroParcelas'); Self.Adiciona('IndRecCom', 'IndicadorRecolhimentoComunicacao'); Self.Adiciona('IndRegApu', 'IndicadorRegimeApuracao'); Self.Adiciona('IndRelLanPta', 'IndicadorRelacionamentoLancamentoParteA'); Self.Adiciona('IndSinSldFinCnt', 'IndicadorSinalSaldoFinalConta'); Self.Adiciona('IndTipAju', 'IndicadorTipoAjuste'); Self.Adiciona('IndRst', 'IndicacaoResultados'); Self.Adiciona('IndTipCnt', 'IndicadorTipoConta'); Self.Adiciona('IndTipEtq', 'IndicadorTipoEstoque'); Self.Adiciona('IndTipVlr', 'IndicadorTipoValor'); Self.Adiciona('IndTipUndImoVen', 'IndicadorTipoUnidadeImobiliariaVendida'); Self.Adiciona('IndTotCntRef', 'IndicadorTotalContaReferencial'); Self.Adiciona('IndTotLan', 'IndicadorTotalLancamentos'); Self.Adiciona('IndOriDed', 'IndicadorOrigemDeducao'); Self.Adiciona('IndNatDed', 'IndicadorNaturezaDeducao'); Self.Adiciona('IndNatEspEmp', 'IndicadorNaturezaEspcificaEmpreendimento'); Self.Adiciona('IndQlfSco', 'IndicadorQualificacaoSocio'); Self.Adiciona('IndQlfRepLeg', 'IndicadorQualificacaoRepresentanteLegal'); Self.Adiciona('IncOutValFis', 'IncidenciaOutrosValoresFiscais'); Self.Adiciona('IniEscMesAno', 'InicioEscrituracaoMesAno'); Self.Adiciona('InoTec', 'InovacaoTecnologica'); Self.Adiciona('InsAmb', 'InscricacaoAmbiente'); Self.Adiciona('InsCedCre', 'InscricaoCedenteCredito'); Self.Adiciona('InsDir', 'InscricaoDirigente'); Self.Adiciona('InsEmi', 'InscricaoEmitente'); Self.Adiciona('InsEct', 'InscricaoEscritorio'); Self.Adiciona('InsEmp', 'Inscricao'); Self.Adiciona('InsEmpDie', 'CnpjAdministradora'); Self.Adiciona('InsEmpEmiDes', 'InscricaoEmitenteDestinatario'); Self.Adiciona('InsEmpRspTcm', 'InscricaoEmpresaResponsavelTCM'); Self.Adiciona('InsEstEmp', 'InscricaoEstadual'); Self.Adiciona('InsEstFazObr', 'InscricaoEstadualCentroDeCustoLivroCaixa'); Self.Adiciona('InsEstFor', 'InscricaoEstadualFornecedor'); Self.Adiciona('InsEstInsSub', 'InscricaoEstadualSubstituto'); Self.Adiciona('InsFedAdq', 'InscricaoFederalAdquirente'); Self.Adiciona('InsFonPag', 'InscricaoFontePagadora'); Self.Adiciona('InsFor', 'InscricaoFornecedor'); Self.Adiciona('InsMunCbtInd', 'InscricaoMunicipalContribuinteIndividual'); Self.Adiciona('InsMunEmp', 'InscricaoMunicipal'); Self.Adiciona('InsPes', 'InscricaoPessoa'); Self.Adiciona('InsOpePlaSau', 'InscricaoOperadorPlanoSaude'); Self.Adiciona('InsRecOutVinCbt', 'ValorINSSOutrosVinculosContribuinteIndividual'); Self.Adiciona('InsRsp', 'InscricaoResponsavel'); Self.Adiciona('InsSco', 'InscricaoSocio'); Self.Adiciona('InsScoRsp', 'CPFSocioResponsavel'); Self.Adiciona('InsSitEsp', 'InscricaoSituacaoEspecial'); Self.Adiciona('InsSuf', 'InscricaoSUFRAMA'); Self.Adiciona('INTCONEXAAMB', 'IntensidadeConcentracaoAvaliacaoAmbiente'); Self.Adiciona('InsLot', 'InscricacaoLotacao'); Self.Adiciona('InsConLot', 'InscricaoContratante'); Self.Adiciona('InsProCno', 'InscricaoProprietarioCNO'); Self.Adiciona('InfCom', 'InformacaoComplementar'); Self.Adiciona('InfComScd', 'InformacaoComplementarSociedade'); Self.Adiciona('IntCtb', 'IntegraComContabilidade'); Self.Adiciona('IntExa', 'InterpretacaoExame'); Self.Adiciona('InvTipLanLcx', 'InverteTipoLancamentoLivroCaixa'); Self.Adiciona('InvTipLanMovLcx', 'InverteTipoLancamentoMovimentacaoLivroCaixa'); Self.Adiciona('IntMatPer', 'IntegraComMatriz'); Self.Adiciona('IpiEtq', 'PercentualIPI'); Self.Adiciona('IscEstMovInv', 'InscricaoEstadualInventario'); Self.Adiciona('IstNorPrdRurPreEsc', 'IN67304ProdutorAgropecuarioPreferenciaEscrita'); Self.Adiciona('IseIrrCbt', 'IsencaoIRRFContribuinteIndividual'); Self.Adiciona('ItgPtoElePreGer', 'IntegracaoPontoEletronico'); Self.Adiciona('IvaImpEst', 'IVAEstoque'); Self.Adiciona('JunComEmp', 'InscricaoJuntaComercial'); Self.Adiciona('JurMovPagRec', 'JurosMovimentacaoPagarReceber'); Self.Adiciona('JurRenTit', 'JurosRenegociacaoTitulo'); Self.Adiciona('LanCheMorTraLanSai', 'LancarChequeMoradiaLancamentoSaida'); Self.Adiciona('LanConPatEmp', 'LancaControlePatrimonial'); Self.Adiciona('LanCtbLcxEmpEscInt', 'TipoIntegracaoFiscal'); Self.Adiciona('LanDesEmp', 'LancaDestiantario'); Self.Adiciona('LanDifAlqPreEsc', 'LancaDiferencialAliquotaPreferenciaEscrita'); Self.Adiciona('LanEmpTri', 'LancaTributo'); Self.Adiciona('LanGerEmp', 'LancamentoGerencial'); Self.Adiciona('LanImoIveIteAtiFix', 'LancaItemAtivoFixoInventario'); Self.Adiciona('lanInvPreEsc','LancaInventarioPreferenciaEscrita'); Self.Adiciona('LanIteAtiFixPre', 'LancaItemAtivoFixo'); Self.Adiciona('LanMerMovPre', 'LancaMercadoria'); Self.Adiciona('LanPreCusPrdValUni', 'LancaPrecoCustoProdutoValorUnitario'); Self.Adiciona('LanProAut', 'LancaProtegeAutomaticamente'); Self.Adiciona('LanRetImpFed', 'LancaRetencaoImpostoFederal'); Self.Adiciona('LanSitEspEntSai', 'LancaSituacaoEspecial'); Self.Adiciona('LanVlrUniTotPre', 'LancaValorUnitarioTotal'); Self.Adiciona('LcrExePreCtb', 'CodigoLucroExercicio'); Self.Adiciona('LimCamPre', 'LimpaCampos'); Self.Adiciona('LgrEmp', 'Logradouro'); Self.Adiciona('LgrFor', 'LogradouroFornecedor'); Self.Adiciona('LgrScoRsp', 'LogradouroSocioResponsavel'); Self.Adiciona('LocAmb', 'LocalAmbiente'); Self.Adiciona('LocCopBco', 'LocalCopiaBanco'); Self.Adiciona('LogEct', 'LogradouroEscritorio'); Self.Adiciona('LogPes', 'LogradouroPessoa'); Self.Adiciona('LogRspTcm', 'LogradouroResponsavelTCM'); Self.Adiciona('LOGLOT', 'LogradouroLotacao'); Self.Adiciona('LucExp', 'LucroExploracao'); Self.Adiciona('MacBasCalIcmNorForTri', 'MacroBaseCalculoIcmsNormalFormulaTributacao'); Self.Adiciona('MacBasCalIcmRetForTri', 'MacroBaseCalculoIcmsRetidoFormulaTributacao'); Self.Adiciona('MacBasRedForTri', 'MacroBaseReducaoFormulaTributacao'); Self.Adiciona('MacIcmRetForTri', 'MacroIcmsRetidoFormulaTributacao'); Self.Adiciona('MacNaoTriForTri', 'MacroNaoTributadoFormulaTributacao'); Self.Adiciona('MacVlrBseCalIpiNor', 'MacroValorBaseCalculoIpiNormal'); Self.Adiciona('MacVlrBseRedIpi', 'MacroValorBaseReducaoIpi'); Self.Adiciona('MacVlrIseIpi', 'MacroValorIsentaIpi'); Self.Adiciona('MacVlrIseForTri', 'MacroValorIsentaFormulaTributacao'); Self.Adiciona('MacVlrNaoTriIpi', 'MacroValorNaoTributadoIpi'); Self.Adiciona('MacVlrOutIpi', 'MacroValorOutroIpi'); Self.Adiciona('MacVlrOutForTri', 'MacroValorOutroFormulaTributacao'); Self.Adiciona('ManCabDocPreEsc', 'ManterCabecalhoDocumentoEntradasSaidas'); Self.Adiciona('MatEmp', 'CodigoEmpresaMatriz'); Self.Adiciona('MatEpgCtt', 'MatriculaEmpregado'); Self.Adiciona('MasEspPrd', 'MassaEspecificaDoProduto'); Self.Adiciona('MesAnoAdeSupSpl', 'MesAnoAdesaoSuperSimples'); Self.Adiciona('MesAnoAqu', 'MesAnoAquisicao'); Self.Adiciona('MesAnoExeMov', 'MesAnoExercicioNotaFiscal'); Self.Adiciona('MesAnoExeMovNotFisCmp', 'MesAnoExercicioMovimentacaoNotaFiscalComplementar'); Self.Adiciona('MesAnoMov', 'MesAnoMovimentacao'); Self.Adiciona('MesAnoExeMovGerCtb', 'MesAnoExercicioMovimentacaoGerenciadorContabil'); Self.Adiciona('MesAnoExeCreDec', 'MesAnoExercicioCreditosDecorrentes'); Self.Adiciona('MesAnoFatGerMovMen', 'MesAnoFatoGerador'); Self.Adiciona('MesAnoIncMovMen', 'MesAnoIncidenciaMovimentacaoMensal'); Self.Adiciona('MesAnoLot', 'MesAnoLote'); Self.Adiciona('MesAnoObrIcmRecEfd', 'MesAnoReferenciaObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('MesAnoOpeCrtDes', 'DataLancamentoOperacaoCartaoCreditoDebito'); Self.Adiciona('MesAnoOpeVlrAgr', 'DataLancamentoOperacaoValoresAgregados'); Self.Adiciona('MesAnoOutOpe', 'MesAnoOutrasOperacoesPisCofins'); Self.Adiciona('MesAnoExeMovTrs', 'MesAnoExercicioMovimentacaoTransferencia'); Self.Adiciona('MesAnoIniDec', 'MesAnoInicioDecisao'); Self.Adiciona('MesAnoFimDec', 'MesAnoFimDecisao'); Self.Adiciona('MesPagFolMenPreFol','MesPagamentoFolhaMensal'); Self.Adiciona('MesRef', 'MesReferencia'); Self.Adiciona('METCONSUB', 'MetodoControleSubconta'); Self.Adiciona('ModEttDmt','ModeloEstruturaDemonstracao'); Self.Adiciona('ModDep', 'ModoDepreciacao'); Self.Adiciona('ModCnx', 'ModoConexao'); Self.Adiciona('MotCanMov','MotivoCancelamentoNotaFiscal'); Self.Adiciona('MscCalMscCntMod', 'MascaraCalculoModeloConta'); Self.Adiciona('MscEdiMscCntMod', 'MascaraEdicaoModeloConta'); Self.Adiciona('MulMovPagRec', 'MultaMovimentacaoPagarReceber'); Self.Adiciona('MscCalMscCnt', 'MascaraCalculoConta'); Self.Adiciona('MscEdiMscCnt', 'MascaraEdicaoConta'); Self.Adiciona('MsgCom', 'MensagemComunicacao'); Self.Adiciona('MulRenTit', 'MultaRenegociacaoTitulo'); Self.Adiciona('IndGerReg', 'IndicadorGeracaoRegistro'); Self.Adiciona('IndNatRec', 'IndicadorNaturezaReceita'); Self.Adiciona('IndNatRet', 'IndicacaoNaturezaRetencao'); Self.Adiciona('IndNatEveCreDec', 'IndicadorNaturezaEventoCreditosDecorrentes'); Self.Adiciona('IndDec', 'IndicadorDeclarante'); Self.Adiciona('InsFazObr', 'inscricaoCentroDeCustoLivroCaixa'); Self.Adiciona('IdeFazObr', 'IdentidadeCentroDeCustoLivroCaixa'); Self.Adiciona('IndDep', 'IndicativoDepositoMontanteIntegral'); Self.Adiciona('IndAutPro', 'AutorAcao'); Self.Adiciona('IndAltCap', 'IndicadorAlteracaoCapital'); Self.Adiciona('VlrLanEla', 'ValorLancamentoElacs'); Self.Adiciona('vlrlanptb', 'ValorLancamentoParteB'); Self.Adiciona('VlrLanEla', 'ValorLancamentoElacs'); Self.Adiciona('indvlrlanpta', 'IndicadorValorLancamentoParteA'); Self.Adiciona('indvlrlanptb', 'IndicadorValorLancamentoParteB'); Self.Adiciona('IndDecPro', 'IndicativoDecisao'); Self.Adiciona('InsEmpScd', 'InscricaoSociedade'); Self.Adiciona('LogFazObr', 'LogradouroCentroDeCustoLivroCaixa'); Self.Adiciona('MatRspBem', 'MatriculaResponsavelBem'); Self.Adiciona('MESANOBASGNR','MesAnoBaseGNRE'); Self.Adiciona('MesAnoExeConRetFon', 'MesAnoExercicioContribuicaoRetidaNaFonte'); Self.Adiciona('MesAnoExeDedDiv', 'MesAnoExercicioDeducoesDiversas'); Self.Adiciona('MESANORECBRU','MesAnoReceitaBrutaPisCofins'); Self.Adiciona('MODBOMCMB','Modelo'); Self.Adiciona('MODDOCARR','CodigoModeloDocumento'); Self.Adiciona('MOTITVVOLVENCMB','MotivoIntervencao'); Self.Adiciona('ValCRC', 'ValidadeCRC'); end; procedure TCustomDicionario.AdicionaAtributosNOPQ; begin Self.Adiciona('NatCnt', 'NaturezaConta'); Self.Adiciona('NatCodAjuApuIpi', 'NaturezaTipoAjusteApuracaoIPI'); Self.Adiciona('NatBseCalOutOpe', 'NaturezaBaseCalculoOutrasOperacoes'); Self.Adiciona('NatEpt', 'NaturezaExportacao'); Self.Adiciona('NatFrt', 'NaturezaDoFrete'); Self.Adiciona('NatIteBasEtt', 'NaturezaItemEstrutura'); Self.Adiciona('NatIteMovMen', 'NaturezaItemMovimentacaoMensal'); Self.Adiciona('NatLan', 'NaturezaLancamento'); Self.Adiciona('NatLanLcx', 'NaturezaLancamentoLivroCaixa'); Self.Adiciona('NatLanLcx', 'NaturezaLancamentoLivroCaixa'); Self.Adiciona('Natureza', 'NaturezaEventoMigracao'); Self.Adiciona('NatLanIteCtbSpg', 'NaturezaLancamentoItemContabilizacaoSopag'); Self.Adiciona('NatLanIteMovCtb', 'NaturezaLancamentoItemMovimentacaoContabil'); Self.Adiciona('NatOpeDie', 'NaturezaOperacaoDie'); Self.Adiciona('NatNivCenNeg', 'NaturezaNivelCentroNegocio'); Self.Adiciona('NatPes', 'NaturalidadePessoa'); Self.Adiciona('NfeApuCpsFatPreEsc', 'NFdeEntradasComunicacaoCompoeApuracaoCompraFaturamento'); Self.Adiciona('NcmDes', 'NcmDesonerado'); Self.Adiciona('NcmPrd', 'NCM'); Self.Adiciona('NcmSpdPisCof511', 'NcmSpedPisCofins'); Self.Adiciona('NivCenNeg', 'NivelCentroNegocio'); Self.Adiciona('NivCenNeg1', 'NivelCentroNegocios1'); Self.Adiciona('NivCnt', 'NivelConta'); Self.Adiciona('NivGrpEtt', 'NivelGrupo'); Self.Adiciona('NivIteBasEtt', 'NivelItem'); Self.Adiciona('NomAdq', 'NomeAdquirente'); Self.Adiciona('NomAdmDie', 'NomeAdministradora'); Self.Adiciona('NomBco', 'NomeBanco'); Self.Adiciona('NomCid', 'NomeCidade'); Self.Adiciona('NomDir', 'NomeDirigente'); Self.Adiciona('NomEct', 'NomeEscritorio'); Self.Adiciona('NomEmpRef', 'NomeEmpresaReferencia'); Self.Adiciona('NomEstUndFed', 'NomeUnidadeFederacao'); Self.Adiciona('NomFanEmp', 'NomeFantasia'); Self.Adiciona('NomFor', 'NomeFornecedor'); Self.Adiciona('NomForTri', 'NomeFormulaTributacao'); Self.Adiciona('NomFun', 'NomeFuncionario'); Self.Adiciona('NomInsAnp1', 'NomeInstalacaoAnp1'); Self.Adiciona('NomRspBem', 'NomeResponsavelBem'); Self.Adiciona('NomRspTcm', 'NomeResponsavelTCM'); Self.Adiciona('NomScoRsp', 'NomeSocioResponsavel'); Self.Adiciona('NomSco', 'NomeSocio'); Self.Adiciona('NomScp', 'NomeSociedadeContaParticipacao'); Self.Adiciona('NotFisLei4159','EmpresaIncluidaProgramaNotaLegal'); Self.Adiciona('ModEmiCupFis', 'ModeloEmissorCupomFiscal'); Self.Adiciona('NosNumPgrRec', 'NossoNumeroMovimentacaoPagarReceber'); Self.Adiciona('NumCasDecQtdPrdPre', 'NumeroCasasDecimaisQuantidade'); Self.Adiciona('NumCasDecVlrPrdPre', 'NumeroCasasDecimaisValor'); Self.Adiciona('NumCerAprIteEpi', 'NumeroCertificadoAprovacaoItemEPI'); Self.Adiciona('NumConPes', 'NumeroConselhoPessoa'); Self.Adiciona('NumDcl', 'NumeroDeclaracao'); Self.Adiciona('NumDecImp', 'NumeroDaDeclaracaoDeImportacao'); Self.Adiciona('NumDoc', 'NumeroDocumento'); Self.Adiciona('NumDocAjuApuIpi', 'NumeroDocumentoAjusteApuracaoIPI'); Self.Adiciona('NumDocArrEstInfAdiAjuApuIcm', 'NumeroDocumentoArrecadacaoEstadualInformacaoAdicionalApuracaoICMS'); Self.Adiciona('NumDocAdi','NumeroDocumentoAdicaoItemAtivoFixo'); Self.Adiciona('NumDocBaiCia', 'NumeroDocumentoBaixaItemAtivoFixo'); Self.Adiciona('NumDocCan', 'NumeroDocumentoCancelado'); Self.Adiciona('NumDocCreCOF','NumeroDocumentoDebitoCreditoCOFINS'); Self.Adiciona('NumDocCrePIS','NumeroDocumentoDebitoCreditoPIS'); Self.Adiciona('NumDocFin', 'NumeroDocumentoFinal'); Self.Adiciona('NumDocFis', 'NumeroDocumentoFiscal'); Self.Adiciona('NumDocIaf','NumeroDocumentoEntradaItemAtivoFixo'); Self.Adiciona('NumDocIni', 'NumeroDocumentoInicial'); Self.Adiciona('NumDocUtiBaiCre', 'NumeroDocumentoUtilizadoBaixaCredito'); Self.Adiciona('NUMDOCIMPFED', 'NumeroDocumentoImpostoFederal'); Self.Adiciona('NumEprEmp', 'NumeroEmpregados'); Self.Adiciona('NumFabRep', 'NumeroFabricacaoREP'); Self.Adiciona('NumFolEmp', 'NumeroFolha'); Self.Adiciona('NumFor', 'NumeroFornecedor'); Self.Adiciona('NumEmp', 'Numero'); Self.Adiciona('NumFinDocFis', 'NumeroFinalDocumentoFiscal'); Self.Adiciona('NumIniDocFis', 'NumeroInicialDocumentoFiscal'); Self.Adiciona('NumInsEmpOrg', 'NumeroInscricao'); Self.Adiciona('NumLeiOcuPro', 'NumeroLeiOcupacaoProfissional'); Self.Adiciona('NumLicImp', 'NumeroDaLicensaDeImportacao'); Self.Adiciona('NumLivEmp', 'NumeroLivro'); Self.Adiciona('NumLogEct', 'NumeroEscritorio'); Self.Adiciona('NumLogRspTcm', 'NumeroLogradouroResponsavelTCM'); Self.Adiciona('NumLotIteEpi', 'NumeroLoteItemEPI'); Self.Adiciona('NumLot', 'NumeroLotacao'); Self.Adiciona('NumMov', 'NumeroInicialNotaFiscal'); Self.Adiciona('NumDocInfComNotRef', 'NumeroNotaFiscalReferenciada'); Self.Adiciona('NumNotFisOpeCom', 'NumeroDaNotaFiscalDaOperacaoComercial'); Self.Adiciona('NumOrdIteMovEcf', 'NumeroOrdemItemMovimentacaoEmissorCupoFiscal'); Self.Adiciona('NumParMovPagRec', 'NumeroParcelaMovimentacaoPagarReceber'); Self.Adiciona('NumPes', 'NumeroPessoa'); Self.Adiciona('NumPro', 'NumeroProcesso'); Self.Adiciona('NumProAjuApu', 'NumeroProcessoAjusteApuracao'); Self.Adiciona('NumProInfAdiAjuApuIcm', 'NumeroProcessoInformacaoAdicionalApuracaoICMS'); Self.Adiciona('NumProDocAtoCon', 'NumeroProcessoDocumentoOuAtoConcessorio'); Self.Adiciona('NumProExiSupSplNacTri', 'NumeroProcessoExigibilidadeSuspensa'); Self.Adiciona('NumProExiSupApuSplNac', 'NumeroProcessoExigibilidadeSuspensaApuracao'); Self.Adiciona('NumProObrIcmRecEfd', 'NumeroProcessoObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('NumRcbSerPreFol', 'NumeroReciboServicoPrestado'); Self.Adiciona('NumRegAgeNacSau', 'NumeroRegistroAgenciaNacionalSaude'); Self.Adiciona('NumRegEpt', 'NumeroRegistroExportacao'); Self.Adiciona('NumRegRspTcm', 'NumeroRegistroResponsavelTCM'); Self.Adiciona('NumParRenTit', 'NumeroParcelaRenegociacaoTitulo'); Self.Adiciona('NumScoRsp', 'NumeroSocioResponsavel'); Self.Adiciona('NumSerEmiCupFis', 'NumeroSerieEmissorCupomFiscal'); Self.Adiciona('NumTanMovAmzCmb', 'NumeroTanqueArmazenamentoCombustivel'); Self.Adiciona('NumTerMov', 'NumeroFinalNotaFiscal'); Self.Adiciona('NumTitMovPgrRec', 'NumeroTituloMovimentacaoPagarReceber'); Self.Adiciona('NumViaSerVal', 'NumeroViaEntregeAAgenfa'); Self.Adiciona('ObgCenNegPre', 'ObrigaCentroNegocios'); Self.Adiciona('ObsAgeRis', 'ObservacaoAgenteRisco'); Self.Adiciona('ObsCbtInd', 'ObservacaoContribuinteIndividual'); Self.Adiciona('ObsCOF','ObservacaoDebitoCreditoCOFINS'); Self.Adiciona('ObsCrePIS','ObservacaoDebitoCreditoPIS'); Self.Adiciona('ObsEcf', 'ObservacaoMovimentacaoEmissorCupomFiscal'); Self.Adiciona('ObsFrsPrgFrs', 'ObservacaoFeriasProgramacaoFerias'); Self.Adiciona('ObsMov', 'ObservacaoNotaFiscal'); Self.Adiciona('ObsMovInv', 'ObservacaoInventario'); Self.Adiciona('ObsMovIteEtq', 'ObservacaoItemEstoque'); Self.Adiciona('ObsPrgFrs', 'ObservacaoProgramacaoFerias'); Self.Adiciona('ObsScoRsp', 'ObservacaoSocioResponsavel'); Self.Adiciona('OpeExt', 'OperacoesExterior'); Self.Adiciona('OpeIncFomPrz', 'OperacaoIncentivadaFomentar'); Self.Adiciona('OpeIteBasEtt', 'OperacaoItemEstrutura'); Self.Adiciona('OpeVin', 'OperacoesPessoaVinculada'); Self.Adiciona('OptExtRtt', 'OptanteExtincaoRtt'); Self.Adiciona('OrdExa', 'OrdemExame'); Self.Adiciona('OriLan', 'OrigemLancamento'); Self.Adiciona('OriLanMov', 'OrigemLancamentoNotaFiscal'); Self.Adiciona('OriLanMovECF', 'OrigemLancamentoMovimentacaoEmissorCupomFiscal'); Self.Adiciona('OriLanOutVlrFis', 'OrigemLancamentoOutrosValoresFiscais'); Self.Adiciona('OrgExpEct', 'OrgaoExpedidorEscritorio'); Self.Adiciona('OrgExpScoRsp', 'OrgaoExpedidorSocioResponsavel'); Self.Adiciona('OutCreApuIcm', 'OutrosCreditosApuracaoICMS'); Self.Adiciona('OutCreApuIpi', 'ValorOutrosCreditosApuracaoIPI'); Self.Adiciona('OutDebApuIcm', 'OutrosDebitosApuracaoICMS'); Self.Adiciona('OutDebApuIpi', 'ValorOutrosDebitosApuracaoIPI'); Self.Adiciona('OutValFis', 'OutrosValoresFiscais'); Self.Adiciona('ParFerMun', 'ParametroFeriadoMunicipal'); Self.Adiciona('PRCPISBLI100', 'PercentualPisBlocoI100'); Self.Adiciona('PRCCOFBLI100', 'PercentualCofinsBlocoI100'); Self.Adiciona('PrcParCapTot', 'PercentualParticipacaoCapitalTotal'); Self.Adiciona('PrcParCapVol', 'PercentualParticipacaoCapitalVolante'); Self.Adiciona('PagDifDecTerMesNov','PagaDiferencaDecimoTerceiroMesNovembro'); Self.Adiciona('ParCol', 'ParticipacaoColigadas'); Self.Adiciona('ParConEmp', 'ParticipacoesConsorciosEmpresas'); Self.Adiciona('ParExt', 'ParticipacoesExterior'); Self.Adiciona('PerApu', 'PeriodoApuracao'); Self.Adiciona('PerApuCre', 'PeriodoApuracaoCredito'); Self.Adiciona('PerApuCreDec', 'PeriodoApuracaoCreditosDecorrentes'); Self.Adiciona('PerApuIrpCsl', 'PeriodoApuracaoIRPJCSLL'); Self.Adiciona('ParTipCodFis', 'ParametroTipoCodigoFiscal'); Self.Adiciona('PerCofIteMovEcf', 'PercentualCofinsItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('PerCreOutIteMovEcf', 'PercentualCreditoOutorgadoItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('PerCreDecCis', 'PercentualCreditosDecorrentesCisao'); Self.Adiciona('PerFixSaiEst', 'PercentualFixoSobreSaidaEstadual'); Self.Adiciona('PerFixSaiInt', 'PercentualFixoSobreSaidaInterestadual'); Self.Adiciona('PerIcmIteMovEcf', 'PercentualICMSItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('PerIpiIteMovEcf', 'PercentualIPIItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('PerIvaIteMovEcf', 'PercentualIVAItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('PrcIcmSubMovIteEtq', 'PercentualICMSSubstituicaoTributaria'); Self.Adiciona('PrcIcmFcpUndFedDes', 'PercentualIcmsFcpUFDestino'); Self.Adiciona('PrcIntUndDes', 'AliquotaInternaUFDestino'); Self.Adiciona('PrcIntUfs', 'AliquotaInterestadualUFs'); Self.Adiciona('PrcProPar', 'PercentualProvisorioPartilha'); Self.Adiciona('PerLucEtq', 'PercentualLucroEstoque'); Self.Adiciona('PerMulCntRec', 'PercentualMultaContasReceber'); Self.Adiciona('PerPisIteMovEcf', 'PercentualPisItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('PerPrtCapScoEmp', 'PercentualParticipacaoCapitalSocial'); Self.Adiciona('PerRedIteMovEcf', 'PercentualReducaoItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('PerVenProEmpTri', 'PercentualVendaProduto'); Self.Adiciona('PerVenSerEmpTri', 'PercentualVendaServico'); Self.Adiciona('PesBrtFre', 'PesoBrutoCargaTransportada'); Self.Adiciona('PesLiqFre', 'PesoLiquidoCargaTransportada'); Self.Adiciona('PISPASCbtInd', 'PISPASEPContribuinteIndividual'); Self.Adiciona('PISPASScoRsp', 'PISPASEPSocioResponsavel'); Self.Adiciona('PISPASMedRsp', 'PISPASEPMedicoResponsavel'); Self.Adiciona('PgtExt', 'PagamentosExterior'); Self.Adiciona('PgtRem', 'PagamentosRemessas'); Self.Adiciona('PlcIteAti', 'PlacaItemAtivoFixo'); Self.Adiciona('PolAma', 'PoloAmazonia'); Self.Adiciona('PorCom', 'PortaComunicacao'); Self.Adiciona('PorIp', 'PortaIP'); Self.Adiciona('PosAno', 'PosicaoAno'); Self.Adiciona('PosCodEmp', 'PosicaoCodigoEmpresa'); Self.Adiciona('PosCodMqnCta', 'PosicaoCodigoMaquinaColetora'); Self.Adiciona('PosDia', 'PosicaoDia'); Self.Adiciona('PosHrs', 'PosicaoHora'); Self.Adiciona('PosMatEpg', 'PosicaoMatriculaEmpregado'); Self.Adiciona('PosMes', 'PosicaoMes'); Self.Adiciona('PosMin', 'PosicaoMinuto'); Self.Adiciona('PrcAliSerValTri', 'PercentualSerieValida'); Self.Adiciona('PrcBasInsCbtInd', 'PercentualBaseINSSContribuinteIndividual'); Self.Adiciona('PrcBasIrrCbtInd', 'PercentualBaseIRRFContribuinteIndividual'); Self.Adiciona('PrcCreOutMovIteEtq', 'PercentualCreditoOutorgadoItemEstoque'); Self.Adiciona('PrcCofDocFis', 'PercentualCofinsDocumentoFiscal'); Self.Adiciona('PrcCofMovIteEtq', 'PercentualCOFINSItemEstoque'); Self.Adiciona('PrcCofOutOpe', 'PercentualCOFINSOutrasOperacoes'); Self.Adiciona('PrcCusMovInv', 'PrecoCustoInventario'); Self.Adiciona('PrcDstEmpGerCtb', 'PercentualDesconto'); Self.Adiciona('PrcIcmMovIteEtq', 'PercentualICMSItemEstoque'); Self.Adiciona('PrcIcmSubMovIteEtq', 'PercentualICMSSubstituicaoTributaria'); Self.Adiciona('PrcInsEmpAut', 'PercentualINSSAutonomo'); Self.Adiciona('PrcInsEmpProLab', 'PercentualINSSProLabore'); Self.Adiciona('PrcInsEmpSeg', 'PercentualINSSSegurado'); Self.Adiciona('PrcIpiMovIteEtq', 'PercentualIPIItemEstoque'); Self.Adiciona('PrcIvaMovIteEtq', 'PercentualIVAItemEstoque'); Self.Adiciona('PrcLucMovInv', 'PercentualLucroInventario'); Self.Adiciona('PrcPisDocFis', 'PercentualPisDocumentoFiscal'); Self.Adiciona('PrcPisMovIteEtq', 'PercentualPISItemEstoque'); Self.Adiciona('PrcPisOutOpe', 'PercentualPISOutrasOperacoes'); Self.Adiciona('PrcRecTotRec', 'PercentualReceitaTotalRecebida'); Self.Adiciona('PrcRed', 'PercentualReducao'); Self.Adiciona('PrdRedMovIteEst', 'PercentualReducaoItemEstoque'); Self.Adiciona('PrcSegAtvRurEmpCtb', 'PercentualSegregacao'); Self.Adiciona('PrdStgPreEsc', 'MercadoriaPorCodigoReferencia'); Self.Adiciona('PRETOTJURMUL', 'ParametrizacaoIntegracaoPagarReceber'); Self.Adiciona('PreCusEtq', 'PrecoCustoEstoque'); Self.Adiciona('ProDecTerSalMes','ProvisaoDecimoTerceiroSalarioMes'); Self.Adiciona('ProDecTerSalAcm','ProvisaoDecimoTerceiroSalarioAcumulado'); Self.Adiciona('ProEmpTri', 'ProcessoEmpresaTributo'); Self.Adiciona('ProFerMes', 'ProvisaoFeriasMes'); Self.Adiciona('ProFerAcm', 'ProvisaoFeriasAcumulada'); Self.Adiciona('ProFgtDecTerSal', 'ProvisaoFgtsDecimoTerceiroSalario'); Self.Adiciona('ProFgtDecTerSalMes', 'ProvisaoFgtsDecimoTerceiroSalarioMes'); Self.Adiciona('ProFgtFerMes', 'ProvisaoFgtsFeriasMes'); Self.Adiciona('ProFgtFerAcm', 'ProvisaoFgtsFeriasAcumuladas'); Self.Adiciona('ProInsDecTerSal', 'ProvisaoInssDecimoTerceiroSalario'); Self.Adiciona('ProInsDecTerSalMes','ProvisaoInssDecimoTerceiroSalarioMes'); Self.Adiciona('ProInsFerMes', 'ProvisaoInssFeriasMes'); Self.Adiciona('ProInsFerAcm', 'ProvisaoInssFeriasAcumuladas'); Self.Adiciona('ProLabScoEmp', 'ProLabore'); Self.Adiciona('ProRea', 'CodigoProcedimentoRealizado'); Self.Adiciona('ProTerFerAcm', 'ProvisaoTercoFeriasAcumuladas'); Self.Adiciona('ProTerFerMes', 'ProvisaoTercoFeriasMes'); Self.Adiciona('PtcApeUm', 'PertenceApendiceI'); Self.Adiciona('QtdAnoAviPre', 'PartirDeQuantosAnosCalculaAviso'); Self.Adiciona('PlcVei', 'PlacaVeiculo'); Self.Adiciona('QlfSco', 'QualificacaoSocio'); Self.Adiciona('QlfDir', 'QualificacaoDirigente'); Self.Adiciona('QtdDepImpRenCbtInd', 'QuantidadeDependentesIRContribuinteIndividual'); Self.Adiciona('QtdDiaPttEmpGerCtb', 'QuantidadeDiasProtesto'); Self.Adiciona('QtdDgtCarCodBar', 'QuantidadeDigitoCartaoCodigoBarra'); Self.Adiciona('QtdEtq', 'QuantidadeEstoque'); Self.Adiciona('QtdIaf', 'QuantidadeItemAtivoFixo'); Self.Adiciona('QtdItePro', 'QuantidadeItemProducao'); Self.Adiciona('QtdItePer', 'QuantidadeItemPerda'); Self.Adiciona('QtdIteMovEcf', 'QuantidadeItemMovimentacaoEmissorDocumentoFiscal'); Self.Adiciona('QtdLtrMovAmzCmb', 'QuantidadeLitrosArmazenamentoCombustivel'); Self.Adiciona('QtdMesBcoHrs', 'QuantidadeMesBancoHoras'); Self.Adiciona('QtdMovInv', 'QuantidadeInventario'); Self.Adiciona('QtdMovIss', 'QuantidadeServico'); Self.Adiciona('QtdMovIte', 'QuantidadeMovimentadaItem'); Self.Adiciona('QtdMovIteEtq', 'QuantidadeProduto'); Self.Adiciona('QtdOgc', 'QuantidadeObrigacao'); Self.Adiciona('QtdScp', 'QuantidadeSCP'); Self.Adiciona('QtdVagOcuProI', 'QuantidadeVagaOcupacaoProfissional'); Self.Adiciona('QtdVolFre', 'QuantidadeVolumeCargaTransportada'); Self.Adiciona('QuaOrgReg', 'QualificacaoOrgaoRegistro'); Self.Adiciona('QuaPesJur', 'QualificacaoPessoaJuridica'); Self.Adiciona('QtdPrdOpeUniMed', 'QuantidadeDoProdutoOperadoUnidadeMedidaAnp'); Self.Adiciona('QtdPrdOpeQuiGra', 'QuantidadeDoProdutoOperadoQuilograma'); Self.Adiciona('QtdPro', 'QuantidadeProducao'); Self.Adiciona('QuaTipExa', 'QualificacaoTipoExame'); Self.Adiciona('NatAca', 'NaturezaAcao'); Self.Adiciona('NatBemIaf', 'NaturezaBemItemAtivoFixo'); Self.Adiciona('MESANOBLI100', 'MesAnoBlocoI100'); Self.Adiciona('NATBASCALCRE', 'NaturezaBaseCalculoCredito'); Self.Adiciona('NOMITVVOLVENCMB','NomedoInterventor'); Self.Adiciona('NotExpCodFis', 'NotasExplicativasCodigoFiscal'); Self.Adiciona('NUMCMP', 'NumeroCampo'); Self.Adiciona('NUMBIC','NumeroBico'); Self.Adiciona('NUMCNVGNR','NumeroConvenioGNRE'); Self.Adiciona('NunCtr', 'NumeroContrato'); Self.Adiciona('NUMCTRPATITEATIFIX','NumeroControlePatrimonial'); Self.Adiciona('NUMPRO', 'NumeroProcesso'); Self.Adiciona('NUMDOCGNR','NumeroDocumentoGNRE'); Self.Adiciona('NUMDRAOPEIMPMOV','NumeroDrawback'); Self.Adiciona('NUMITVVOLVENCMB','NumeroIntervencao'); Self.Adiciona('NumLogFazObr', 'NumeroLogradouroCentroDeCustoLivroCaixa'); Self.Adiciona('NUMOPEIMPMOV','NumeroDocumentoImportacao'); Self.Adiciona('NUMTAN','NumeroTanque'); Self.Adiciona('OrgExpFazObr', 'OrgaoExpedidorCentroDeCustoLivroCaixa'); Self.Adiciona('ORIBEMINC', 'OrigemDoBemIncorporado'); Self.Adiciona('ORIPRO', 'OrigemProcesso'); Self.Adiciona('OriSitEpg', 'OrigemSituacaoEmpregado'); Self.Adiciona('ORIPRO', 'OrigemProcesso'); Self.Adiciona('PAREXCBASCRE', 'ParcelaAExcluirDaBaseDeCalculo'); Self.Adiciona('PARCRECOFTRIMERINT', 'ParcelaCreditoCOFINSTributadaMercadoInterno'); Self.Adiciona('PARCRECOFNAOTRIMERINT', 'ParcelaCreditoCOFINSNaoTributadaMercadoInterno'); Self.Adiciona('PARCRECOFEXP', 'ParcelaCreditoCOFINSExportacao'); Self.Adiciona('PARCREPISTRIMERINT', 'ParcelaCreditoPISTributadaMercadoInterno'); Self.Adiciona('PARCREPISNAOTRIMERINT', 'ParcelaCreditoPISNaoTributadaMercadoInterno'); Self.Adiciona('PARCREPISEXP', 'ParcelaCreditoPISExportacao'); Self.Adiciona('PERLITMOVCMB','ValordaPerda'); Self.Adiciona('PERLITMOVTANCMB','ValordaPerdaTanque'); Self.Adiciona('PISOPEIMPMOV','ValorPisOperacaoImportacao'); Self.Adiciona('PmtRegPtoSitEpg','PermiteRegistroPontoSituacaoEmpregado'); Self.Adiciona('PrcRatPlaLcx', 'percentualRateioPlanoLcx'); Self.Adiciona('PrjExePreCtb','CodigoPrejuizoExercicio'); end; procedure TCustomDicionario.AdicionaAtributosRSTU; begin Self.Adiciona('RazSocScd', 'RazaoSocialSociedade'); Self.Adiciona('RecEmpTri', 'RecolheTributo'); Self.Adiciona('RecExt', 'RedimentosExterior'); Self.Adiciona('RecGlp', 'RecipienteDeGlp'); Self.Adiciona('RecIcmEmpParGuiEst', 'IcmsEmpresaNormalGuiaEstadual'); Self.Adiciona('RecIcmEppParGuiEst', 'IcmsEppGuiaEstadual'); Self.Adiciona('RecIssEmpNorParGuiEst', 'IssEmpresaNormalGuiaEstadual'); Self.Adiciona('RecIcmMicEmpParGuiEst', 'IcmsMicroEmpresaGuiaEstadual'); Self.Adiciona('RecIssMicEmpParGuiEst', 'IssMicroEmpresaGuiaEstadual'); Self.Adiciona('RecIssEppParGuiEst', 'IssEppGuiaEstadual'); Self.Adiciona('RedIseImp', 'ReducaoIsencaoImposto'); Self.Adiciona('RefParHon', 'ReferenciaParametroHonorario'); Self.Adiciona('RefParPrd', 'ReferenciaParametrizacaoProduto'); Self.Adiciona('RefPrdCom', 'ReferenciaProduto'); Self.Adiciona('RazSocEmp', 'RazaoSocial'); Self.Adiciona('RazSocEmpRspTcm', 'RazaoSocialEmpresaResponsavelTCM'); Self.Adiciona('ReaConSerVal', 'RealizaControleDeDocumentoFiscal'); Self.Adiciona('ReaConConIcm', 'RealizaControleConvenioICMS'); Self.Adiciona('RedIcmImpEst', 'ReducaoICMSEstoque'); Self.Adiciona('ReaImpDan', 'RealizarImportacaoDanfSiteFazenda'); Self.Adiciona('RefCnt', 'Referencia'); Self.Adiciona('RefDecTer', 'ReferenciaDecimoTerceiro'); Self.Adiciona('RefEveSal', 'ReferenciaEventoSalario'); Self.Adiciona('RefIteMovMen', 'ReferenciaItemMovimentacaoMensal'); Self.Adiciona('RefNatRecSpd', 'ReferenciaNaturezaReceita'); Self.Adiciona('RefSerPreFol', 'ReferenciaServicoPrestado'); Self.Adiciona('RegGerAutOutVlrFis', 'RegistroGeradoAutomaticamenteOutrosValoresFiscais'); Self.Adiciona('RefInfComObs', 'ReferenciaInformacaoComplementarObservacao'); Self.Adiciona('RegTriDifPreEsc', 'RegimeTributarioDiferenciado'); Self.Adiciona('RenSer', 'RendimentosServicos'); Self.Adiciona('ResExaCliPer', 'ResultadoExameComplementar'); Self.Adiciona('RgmEsp', 'RegimeEspecialSituacao08'); Self.Adiciona('ResApuImp', 'ResumoApuracaoImposto'); Self.Adiciona('RetCofPreEsc', 'AliquotaRentencaoCOFINSPreferenciaEscrita'); Self.Adiciona('RetCslPreEsc', 'AliquotaRentencaoCSLLPreferenciaEscrita'); Self.Adiciona('RetImpCrfPreEsc', 'AliquotaCertificadoRegularidadeFGTSCRF'); Self.Adiciona('ALQCREOUT', 'AliquotaDoCreditoOutorgado'); Self.Adiciona('RetImpFedSerVal', 'RetencaoImpostosFederais'); Self.Adiciona('RetIrpPreEsc', 'AliquotaRentencaoIRPJPreferenciaEscrita'); Self.Adiciona('RetPisPreEsc', 'AliquotaRentencaoPISPreferenciaEscrita'); Self.Adiciona('RESOREDIREXACLIPER', 'ResultadoOrelhaDireita'); Self.Adiciona('RESOREESQEXACLIPER', 'ResultadoOrelhaEsquerda'); Self.Adiciona('ESTOREESQEXACLIPER','EstadoOrelhaEsquerda'); Self.Adiciona('ESTOREDIREXACLIPER','EstadoOrelhaDireita'); Self.Adiciona('TIPADINOT', 'TipoAdicionalNoturno'); Self.Adiciona('TIPAGROREESQEXACLIPER','TipoAgravamentoOrelhaEsquerda'); Self.Adiciona('TIPAGROREDIREXACLIPER','TipoAgravamentoOrelhaDireira'); Self.Adiciona('TIPBEN', 'TipoBeneficio'); Self.Adiciona('RgmIns', 'EhRegimeINSS'); Self.Adiciona('RoyPag', 'RoyaltiesPagos'); Self.Adiciona('RoyRec', 'RoyaltiesRecebidos'); Self.Adiciona('RmlScoRsp', 'RamalSocioResponsavel'); Self.Adiciona('RESIMPREC','ResumoImpostoARecolher'); Self.Adiciona('SAILITMOVCMB','VolumeTotalSaida'); Self.Adiciona('SAILITMOVTANCMB','VolumeTotalSaidaTanque'); Self.Adiciona('SecJud', 'SecaoJudiciaria'); Self.Adiciona('SenRep', 'SenhaREP'); Self.Adiciona('SeqCerAprIteEpi','SequenciaAprovacaoItemEPI'); Self.Adiciona('SEQAPUIMP','SequenciaApuracaoImposto'); Self.Adiciona('SEQBICBOMCMB','SequenciaBicoBomba'); Self.Adiciona('SEQBOMCMB','SequenciaBomba'); Self.Adiciona('SeqConCon','SequenciaConsolidacaoContribuicao'); Self.Adiciona('SeqConPreSobRecBru','SequenciaContribuicaoPrevidenciariaSobreReceitaBruta'); Self.Adiciona('SeqConZee', 'SequenciaContabilizacaoLeituraZ'); Self.Adiciona('SeqCreDec', 'SequenciaCreditosDecorrentes'); Self.Adiciona('SeqDedDiv', 'SequenciaDeducoesDiversas'); Self.Adiciona('SeqDetConPre', 'SequenciaDetalhamentoContribuicaoPrevidenciaria'); Self.Adiciona('SEQGNR','SequenciaGNRE'); Self.Adiciona('SEQGROPRD', 'SequenciaGeneroProduto'); Self.Adiciona('SeqGroSer', 'SequenciaGeneroServicoPrestado'); Self.Adiciona('SEQIMPREC','SequenciaImpostoARecolher'); Self.Adiciona('SEQLACBOMCMB','SequenciaLacreBomba'); Self.Adiciona('SeqLanPadFix', 'SequenciaLancamentoPadraoFixo'); Self.Adiciona('SEQMOVCMB','SequenciaMovimentacaoCombustivel'); Self.Adiciona('SeqMovInv','SequenciaMovimentacaoInventario'); Self.Adiciona('SeqMovLcx', 'SequenciaMovimentacaoLivroCaixa'); Self.Adiciona('SeqMovNotFisCmp', 'SequenciaMovimentacaoNotaFiscalComplementar'); Self.Adiciona('SEQMOVTANCMB','SequenciaTanque'); Self.Adiciona('SEQMOVD420','SequenciaMovimentacaoD420'); Self.Adiciona('SeqMsgCom', 'SequenciaMensagemComunicacao'); Self.Adiciona('SEQOPEIMPMOV','SequenciaOperacaoImportacao'); Self.Adiciona('SEQPARPRDCODFIS','SequenciaParametrizacaoProdutoCodigoFiscal'); Self.Adiciona('SEQPRDANP','SequenciaProdutoANP'); Self.Adiciona('SeqProRef','SequenciaProcessoReferenciado'); Self.Adiciona('SeqPerComAli','SequenciaPercentualComplementoAliquota'); Self.Adiciona('SeqRecBru', 'SequenciaReceitaBrutaPisCofins'); Self.Adiciona('SEQTRIAPUIMP','SequenciaTributoApuracaoImposto'); Self.Adiciona('SEQVOLVENCMB','SequenciaVolVenda'); Self.Adiciona('SERBOMCMB','NumeroSerie'); Self.Adiciona('SerPadEnt', 'ServicoPadraoEntrada'); Self.Adiciona('SerPadSai', 'ServicoPadraoSaida'); Self.Adiciona('SerPagSerPreFol', 'ServicoPagoServicoPrestado'); Self.Adiciona('SitBco', 'SiteBanco'); Self.Adiciona('SitFazObr', 'SiteCentroDeCustoLivroCaixa'); Self.Adiciona('StsGrpCntLcx', 'statusGrupoContaLcx'); Self.Adiciona('StsLanPad', 'StatusLancamentoPadrao'); Self.Adiciona('StsMotCarCor', 'StatusMotivoCartaCorrecao'); Self.Adiciona('StsParCnt', 'StatusParametroConta'); Self.Adiciona('StsOcuPro', 'StatusOcupacaoProfissional'); Self.Adiciona('StsRspBem', 'StatusResponsavelBem'); Self.Adiciona('StsSitBem', 'StatusSituacaoBem'); Self.Adiciona('StsScoRsp', 'StatusSocioResponsavel'); Self.Adiciona('StsSpg', 'StatusSopag'); Self.Adiciona('SldRemPerAnt', 'SaldoRemanescentePeriodoAnterior'); Self.Adiciona('SaiEtqDia', 'SaidaEstoqueDia'); Self.Adiciona('SalConEmp', 'Sala'); Self.Adiciona('SalCreFisEfd', 'SaldoCreditoFiscalEFD'); Self.Adiciona('SalCreFisPerAntEfd', 'SaldoCreditoFiscalPeriodoAnteriorEFD'); Self.Adiciona('SalCtbCtbInd', 'SalarioContribuinteIndividual'); Self.Adiciona('SelMesAnoLanNotFisPreEsc', 'SelecionaMesAnoLancamentoNotasFiscais'); Self.Adiciona('SeqAjuApuIpi', 'SequenciaAjusteApuracaoIPI'); Self.Adiciona('SeqAjuBenIncApuIcmEFD', 'SequenciaAjusteBeneficioIncentivoApuracaoICMSEFD'); Self.Adiciona('SeqAjuConPrev', 'SequenciaAjusteContribuicaoPrevidenciaria'); Self.Adiciona('SeqApuIcmEfd', 'SequenciaApuracaoICMS'); Self.Adiciona('SeqApuIcmSubTrb', 'SequenciaApuracaoICMSSubstituicaoTributaria'); Self.Adiciona('SeqApuIpiEfd', 'SequenciaApuracaoIPI'); Self.Adiciona('SeqApuSplNac', 'SequenciaApuracaoSimplesNacional'); Self.Adiciona('SeqSpdPisCof1100', 'SequenciaSpedPisCofinsRegistro1100'); Self.Adiciona('SeqSpdPisCof1101', 'SequenciaSpedPisCofinsRegistro1101'); Self.Adiciona('SeqSpdPisCof1500', 'SequenciaSpedPisCofinsRegistro1500'); Self.Adiciona('SeqSpdPisCof1501', 'SequenciaSpedPisCofinsRegistro1501'); Self.Adiciona('SeqSpdPisCof511', 'SequenciaSpedFiscalPisCofins511'); Self.Adiciona('SeqSpdEcfQ100', 'SequenciaSpedEcfQ100'); Self.Adiciona('SeqSpdEcfY570', 'SequenciaSPEDECFY570'); Self.Adiciona('SeqSpg', 'SequenciaSopag'); Self.Adiciona('SeqSubGrpEtt', 'SequenciaSubGrupoEstruturaDemonstracao'); Self.Adiciona('SeqClaSerCsm', 'SequenciaClassificacaoServicoConsumo'); Self.Adiciona('SeqCodAjuApuIcmEFD', 'SequenciaCodigoAjusteApuracaoICMSEFD'); Self.Adiciona('SeqCodAjuApuIpi', 'SequenciaCodigoAjusteApuracaoIPIEFD'); Self.Adiciona('SeqCodOcoAjuIcmEFD', 'SequenciaCodigoOcorrenciaAjusteEFD'); Self.Adiciona('SeqConVlrIpi', 'SequenciaConsolidacaoValorIPI'); Self.Adiciona('SeqCreCOF','SequenciaDebitoCreditoCOFINS'); Self.Adiciona('SeqCrePIS','SequenciaDebitoCreditoPIS'); Self.Adiciona('SeqCusIncUndImo', 'SequenciaCustoIncorridoDaUnidadeImobiliaria'); Self.Adiciona('SeqCusOrcUndImoVen', 'SequenciaCustoOrcadoUnidadeVendida'); Self.Adiciona('SeqEttDmt', 'SequenciaEstrutura'); Self.Adiciona('SeqUndImoVen', 'SequenciaUnidadeImobiliariaVendida'); Self.Adiciona('SeqFaiVlrSplNac', 'SequenciaFaixaValorSimplesNacional2009'); Self.Adiciona('SeqFaiVlrFatRSeSplNac', 'SequenciaFaixaValorFatorRSimplesNacional2009'); Self.Adiciona('SeqFatAntApuSplNac', 'SequenciaFaturamentoAnteriorApuracaoSimplesNacional'); Self.Adiciona('SeqGerLan', 'SequenciaGeralLancamento'); Self.Adiciona('SeqGrpEtt', 'SequenciaGrupo'); Self.Adiciona('SeqHisIte', 'SequenciaHistoricoItem'); Self.Adiciona('SeqInfAdiAjuApuIcm', 'SequenciaInformacaoAdicionalApuracaoICMS'); Self.Adiciona('SeqInfAdiSplnac', 'SequenciaInformacaoAdicionalApuracaoSimplesNacional'); Self.Adiciona('SeqInfAdiAjuApuIcmIdeDocFis', 'SequenciaInformacaoAdicionalApuracaoICMSDocumentoFiscal'); Self.Adiciona('SeqInfAdiApu', 'SequenciaCodigoInformacaoAdicionalApuracaoEFD'); Self.Adiciona('SeqInfAdiApuVlrDec', 'SequenciaInformacaoAdicionalApuracaoValorDeclaratorioEFD'); Self.Adiciona('SeqInfComObs', 'SequenciaInformacaoComplementarObservacao'); Self.Adiciona('SeqIteBasEtt', 'SequenciaItem'); Self.Adiciona('SeqIteCtbSpg', 'SequenciaItemContabilizacaoSopag'); Self.Adiciona('SeqIteMovCbt', 'SequenciaItemMovimentacaoContabilMovimentacao'); Self.Adiciona('SeqIteMovEcf', 'SequenciaItemMovimentacaoCupomFiscal'); Self.Adiciona('SeqIteMovMen', 'SequenciaItemMovimentacaoMensal'); Self.Adiciona('SeqIteSpg', 'SequenciaItemSopag'); Self.Adiciona('SeqLanLcx', 'SequenciaLancamentoLivroCaixa'); Self.Adiciona('SeqLanMonBio', 'SequenciaLancamentoMonitoracaoBiologica'); Self.Adiciona('SeqMatMovCtb', 'SequenciaMatrizMovimentacaoContabil'); Self.Adiciona('SeqMerSujReaIcmPerFixSai', 'SequenciaMercadoriasSujeitasReaIcmsPercentualFixoSobreSaidas'); Self.Adiciona('SeqMov', 'SequenciaMovimentacao'); Self.Adiciona('SeqMovCbt', 'SequenciaMovimentacaoContabilMovimentacao'); Self.Adiciona('SeqMovCtb', 'SequenciaMovimentacaoContabilItemMovimentacao'); Self.Adiciona('SeqMovConFre', 'SequenciaMovimentacaoConhecimentoFrete'); Self.Adiciona('SeqMovCtbLan', 'SequenciaMovimentacaoContabil'); Self.Adiciona('SeqMovDifAli', 'SequenciaMovimentacaoDiferencialAliquota'); Self.Adiciona('SeqMovEcf', 'SequenciaMovimentacaoEmissorCupomFiscal'); Self.Adiciona('SeqMovEcfRef', 'SequenciaMovimentacaoEmissorCupomFiscalReferenciado'); Self.Adiciona('SeqMovGerCtb', 'SequenciaMovimentacaoGerenciadorContabil'); Self.Adiciona('SeqMovIcm', 'SequenciaMovimentacaoICMS'); Self.Adiciona('SeqMovInfCom', 'SequenciaMovimentacaoInformacaoComplementar'); Self.Adiciona('SeqMovIpi', 'SequenciaMovimentacaoIPI'); Self.Adiciona('SeqMovIsimp', 'SequenciaMovimentacaoISimp'); Self.Adiciona('SeqMovIss', 'SequenciaMovimentacaoISS'); Self.Adiciona('SeqMovIteEstMovIcm', 'SequenciaMovimentacaoItemEstoqueICMS'); Self.Adiciona('SeqMovIteEtq', 'SequenciaMovimentacaoItemEstoque'); Self.Adiciona('SeqMovMen', 'SequenciaMovimentacaoMensal'); Self.Adiciona('SeqMovPgrRec', 'SequenciaMovimentacaoPagarReceber'); Self.Adiciona('SeqMovResMovDia', 'SequenciaMovimentacaoResumoMovimentacaoDiaria'); Self.Adiciona('SeqMovTrs', 'SequenciaMovimentacaoTransferencia'); Self.Adiciona('SeqNorRef', 'SequenciaNormasReferenciadas'); Self.Adiciona('SeqObrIcmRecEfd', 'SequenciaObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('SeqOpeCrtDes', 'SequenciaOperacaoCartaoCreditoDebito'); Self.Adiciona('SeqOpeISimp', 'SequenciaCodigoOperacaoAnp'); Self.Adiciona('SeqOpeVlrAgr', 'SequenciaOperacaoValoresAgregados'); Self.Adiciona('SeqOutObrConFreEFD', 'SequenciaOutrasObrigacoesConhecimentoFreteSPEDFiscal'); Self.Adiciona('SeqOutObrDocFisEFD', 'SequenciaOutrasObrigacoesTributariasDocumentoFiscal'); Self.Adiciona('SeqOutOpe', 'SequenciaOutrasOperacoesPisCofins'); Self.Adiciona('SeqParCntSpd', 'SequenciaParametroContaSped'); Self.Adiciona('SeqParSitTrbImp', 'SequenciaParametroSituacaoTributariaImposto'); Self.Adiciona('SeqRegApuConPre', 'SequenciaRegimeApuracaocontribuicaoTributaria'); Self.Adiciona('SeqRegInfExpEfd', 'SequenciaRegistroInformacoesExportacao'); Self.Adiciona('SeqSerValTri', 'SequenciaTributacaoSerieValida'); Self.Adiciona('SeqSitTrbCof', 'SequenciaSituacaoTributariaCOFINS'); Self.Adiciona('SeqSitTrbCofEnt','SequenciaSituacaoTributariaCOFINSEntrada'); Self.Adiciona('SeqSitTrbCofSai','SequenciaSituacaoTributariaCOFINSSaida'); Self.Adiciona('SeqSitTrbImp', 'SequenciaSituacaoTributariaImposto'); Self.Adiciona('SeqSitTrbImpEnt', 'SequenciaSituacaoTributariaIPIEntrada'); Self.Adiciona('SeqSitTrbImpSai', 'SequenciaSituacaoTributariaIPISaida'); Self.Adiciona('SeqSitTrbIpi', 'SequenciaSituacaoTributariaIPI'); Self.Adiciona('SeqSitTrbPis', 'SequenciaSituacaoTributariaPIS'); Self.Adiciona('SeqSitTrbpisEnt','SequenciaSituacaoTributariaPISEntrada'); Self.Adiciona('SeqSitTrbPisSai','SequenciaSituacaoTributariaPISSaida'); Self.Adiciona('SeqSitTrtCof', 'SequenciaSituacaoTributariaCOFINSOutrasOperacoes'); Self.Adiciona('SeqSitTrtPis', 'SequenciaSituacaoTributariaPISOutrasOperacoes'); Self.Adiciona('SeqSggApuSplNac', 'SequenciaSegregacaoApuracaoSimplesNacional'); Self.Adiciona('SeqMovSplNac', 'SequenciaMovimentoSimplesNacional'); Self.Adiciona('SeqMovSplNacTri', 'SequenciaMovimentoSimplesNacionalTributos'); Self.Adiciona('SeqNatRecSpd', 'SequenciaNaturezaReceita'); Self.Adiciona('SeqOutObrDocFisEFD', 'SequenciaOutrasObrigacoesTributariasDocumentoFiscal'); Self.Adiciona('SeqTblSplNac', 'SequenciaTabelaSimplesNacional2009'); Self.Adiciona('SeqCtbSpg', 'SequenciaContabilizacaoSopag'); Self.Adiciona('SeqCtrCreFisIcmEfd', 'SequenciaControleCreditoFiscalIcmsEFD'); Self.Adiciona('SeqTipUtiCreFisIcm', 'SequenciaTipoUtilizacaoCreditosFiscaisIcms'); Self.Adiciona('SeqTriZee', 'SequenciaTributacaoLeituraZ'); Self.Adiciona('SeqUtiCreFisIcmEfd', 'SequenciaUtilizacaoCreditosFiscaisIcms'); Self.Adiciona('SeqImpFed', 'SequenciaImpostoFederal'); Self.Adiciona('SerAltSerVal', 'SerieAlternativa'); Self.Adiciona('SerDoc', 'SerieDocumento'); Self.Adiciona('SerSerVal', 'SerieValida'); Self.Adiciona('SerSerValEnt', 'SerieValidaEntradaImportacaoSintegra'); Self.Adiciona('SerSerValSai', 'SerieValidaSaidaImportacaoSintegra'); Self.Adiciona('SitEmp', 'Site'); Self.Adiciona('SitEct', 'SiteEscritorio'); Self.Adiciona('SitIctFis', 'SituacaoIncentivoFiscalItemEstoque'); Self.Adiciona('SitIctFisEtq', 'SituacaoIncentivoFiscalEstoque'); Self.Adiciona('SitDocFisMov', 'SituacaoDocumentoFiscal'); Self.Adiciona('SitTitMovPgrRec', 'SituacaoTituloMovimentacaoPagarReceber'); Self.Adiciona('SldCreIcmRetOutAntApuIcm', 'SaldoCredorPeriodoAnteriorSubstituicaoTributariaApuracaoICMS'); Self.Adiciona('SldCrePerAntApuIcm', 'SaldoCredorPeriodoAnteriorApuracaoICMS'); Self.Adiciona('SldCrePerAntApuIpi', 'ValorSaldoCredorAnteriorApuracaoIPI'); Self.Adiciona('SldCreTraApuIcm', 'SaldoCredorTransportarApuracaoICMS'); Self.Adiciona('SldCreTraApuIpi', 'ValorSaldoCredorTransportarApuracaoIPI'); Self.Adiciona('SldDebAntVlrIni', 'SaldoDebitoAnteriorValorInicial'); Self.Adiciona('SldDevApuIcm', 'ValorSaldoDevedorApuracaoICMS'); Self.Adiciona('SldDevApuIpi', 'ValorSaldoDevedorApuracaoIPI'); Self.Adiciona('SocPar', 'SocioParticipacao'); Self.Adiciona('SomIpiBasIcm', 'SomaIpiBaseIcms'); Self.Adiciona('SomIpiBasPisCof', 'SomaIpiBasePisCofins'); Self.Adiciona('SomFreBasIcm', 'SomaFreteBaseIcms'); Self.Adiciona('SomFreBasPisCof', 'SomaFreteBasePisCofins'); Self.Adiciona('SomSegBasIcm', 'SomaSeguroBaseIcms'); Self.Adiciona('SomSegBasPisCof', 'SomaSeguroBasePisCofins'); Self.Adiciona('SrmDtaHrs', 'SincronismoDataHora'); Self.Adiciona('StsAtiInaPrd', 'StatusProduto'); Self.Adiciona('StsCfgCtb', 'StatusConfiguracaoContabil'); Self.Adiciona('StsCnt', 'StatusConta'); Self.Adiciona('StsComHis', 'HistoricoCompartilhado'); Self.Adiciona('StsDocFis', 'StatusDocumentoFiscal'); Self.Adiciona('StsEmp', 'StatusEmpresa'); Self.Adiciona('StsEmpEmi', 'StatusEmpresaEmitente'); Self.Adiciona('StsFor', 'StatusFornecedor'); Self.Adiciona('StsGrpHis', 'StatusGrupoHistorico'); Self.Adiciona('StsHis', 'StatusHistorico'); Self.Adiciona('StsIaf', 'StatusItemAtivoFixo'); Self.Adiciona('StsTri', 'StatusImposto'); Self.Adiciona('StsIndMoe', 'StatusIndexadorMoeda'); Self.Adiciona('StsLimEnq', 'StatusLimiteEnquadramento'); Self.Adiciona('StsLocBem', 'StatusLocalizacaoBem'); Self.Adiciona('StsOrgReg', 'StatusOrgaoRegistro'); Self.Adiciona('StsOriMer', 'SituacaoOrigemMercadoria'); Self.Adiciona('StsScoRsp', 'StatusSocioResponsavel'); Self.Adiciona('StsTipAqu', 'StatusTipoAquisicao'); Self.Adiciona('StsTrb', 'SituacaoTributacao'); Self.Adiciona('StsVlrMan', 'StatusValorManual'); Self.Adiciona('SubSerDoc', 'SubSerieDocumento'); Self.Adiciona('SubSerVal', 'SubSerie'); Self.Adiciona('SujAliCsl', 'SujeitoAliquotaCSLL'); Self.Adiciona('SEQCOM', 'SequenciaComplemento'); Self.Adiciona('SEQDET', 'SequenciaDetalhamento'); Self.Adiciona('SEQBLI100', 'SequenciaBlocoI100'); Self.Adiciona('SEQBLI200', 'SequenciaBlocoI200'); Self.Adiciona('SEQBLI300', 'SequenciaBlocoI300'); Self.Adiciona('SEQSITTRTPISCOF', 'SequenciaSituacaoTributariaPisCofins'); Self.Adiciona('SPDFISDFLEI5005', 'SpedFiscalDistritoFederalLei5005'); Self.Adiciona('TamAno', 'TamanhoAno'); Self.Adiciona('TamCodEmp', 'TamanhoCodigoEmpresa'); Self.Adiciona('TamCodMqnCta', 'TamanhoCodigoMaquinaColetora'); Self.Adiciona('TamDia', 'TamanhoDia'); Self.Adiciona('TamHrs', 'TamanhoHora'); Self.Adiciona('TamMatEpg', 'TamanhoMatriculaEmpregado'); Self.Adiciona('TamMes', 'TamanhoMes'); Self.Adiciona('TamMin', 'TamanhoMinuto'); Self.Adiciona('TelEstAso', 'TelefoneEstabelecimento'); Self.Adiciona('TelFazObr', 'TelefoneCentroDeCustoLivroCaixa'); Self.Adiciona('TelFor', 'TelefoneFornecedor'); Self.Adiciona('TelRspTcm', 'TelefoneResponsavelTCM'); Self.Adiciona('TelScoRsp', 'TelefoneSocioResponsavel'); Self.Adiciona('TerEscMesAno', 'TerminoEscrituracaoMesAno'); Self.Adiciona('TipAno', 'TipoAnotacaoCTPS'); Self.Adiciona('TipApuDesFol', 'TipoApuracaoDesoneracaoFolha'); Self.Adiciona('TipBemSpdAtiFix', 'TipoBemSpedAtivoFixo'); Self.Adiciona('TipCntLcx', 'TipoContaLivroCaixa'); Self.Adiciona('TipCntLcxPad', 'TipoContaLivroCaixaPadrao'); Self.Adiciona('TipCodOpe', 'TipoCodigoOperacaoAnp'); Self.Adiciona('TevDirFer', 'TeveDireitoFerias'); Self.Adiciona('TipCntLcx', 'naturezaLancamentoLcx'); Self.Adiciona('TipCodFis', 'TipoCodigoFiscal'); Self.Adiciona('TipExaMedBio', 'TipoExameMedicoBiologico'); Self.Adiciona('TipInsAmb', 'TipoInscricaoAmbiente'); Self.Adiciona('TIPINSLOT', 'TipoInscricaoLotacao'); Self.Adiciona('TIPINSCONLOT', 'TipoInscricaoContratante'); Self.Adiciona('TIPINSPROCNO', 'TipoInscricaoProprietarioCNO'); Self.Adiciona('TipInsFazObr', 'tipoInscricaoCentroDeCustoLivroCaixa'); Self.Adiciona('TipInsFor', 'TipoInscricaoFornecedor'); Self.Adiciona('TIPMEDBOMCMB','IdentificadorMedicao'); Self.Adiciona('TIPMOVECF','TipoMovimentacaoEmissorCupomFiscal'); Self.Adiciona('TIPMOT','TipoMotivo'); Self.Adiciona('TipMotFlg','TipoMotivoFolga'); Self.Adiciona('TipMsgCom', 'TipoMensagemComunicacao'); Self.Adiciona('TIPRATLCX', 'tipoDoRateioLcx'); Self.Adiciona('TipTom', 'TipoTomador'); Self.Adiciona('TIPTRIAPUIMP', 'TipoTributoApuracaoImposto'); Self.Adiciona('TIPPRO', 'TipoProcesso'); Self.Adiciona('TARGYNPREESC', 'TareGoiania'); Self.Adiciona('TarPreEsc', 'Tare129603'); Self.Adiciona('TelEct', 'TelefoneEscritorio'); Self.Adiciona('TerColGrpEtt', 'TerceiraColuna'); Self.Adiciona('TipAssCom', 'TipoAssinanteComunicacao'); Self.Adiciona('TipAtvEtq', 'TipoAtividadeEstoque'); Self.Adiciona('TipAtvIteMovEcf', 'TipoAtividadeItemMovimentacaoEcf'); Self.Adiciona('TipAtvMovIteEtq', 'TipoAtividadeMovimentacaoItemEstoque'); Self.Adiciona('TipAtvPisCof', 'TipoAtividadeProdutoPisCofinsItemEstoque'); Self.Adiciona('TipAtvPisCofEtq', 'TipoAtividadeProdutoPisCofinsEstoque'); Self.Adiciona('TipCalEmpTri', 'TipoCalculoTributo'); Self.Adiciona('TipCalPrgFrs', 'TipoCalculoProgramacaoFerias'); Self.Adiciona('TipCalLlrEmpCtb', 'TipoCalculoLALUR'); Self.Adiciona('TipCalEmpTri', 'TipoCalculoTributo'); Self.Adiciona('TipCalTriFed', 'TipoCalculoTributoFederal'); Self.Adiciona('TipChc', 'TipoConhecimentoEmbarque'); Self.Adiciona('TipClaSerCsm', 'TipoClassificacaoServicoConsumo'); Self.Adiciona('TipCnt', 'TipoConta'); Self.Adiciona('TipCntMovPgrRec', 'TipoContaMovimentacaoPagarReceber'); Self.Adiciona('TipCRCFazObr', 'TipoCRCCentroDeCustoLivroCaixa'); Self.Adiciona('TipCrcEct', 'TipoCRCEscritorio'); Self.Adiciona('TipCtbSpg', 'TipoContabilizacaoSopag'); Self.Adiciona('TipCteMov', 'TipoConhecimentoFreteEletronico'); Self.Adiciona('TipEscEmpCtb', 'TipoEscrituracao'); Self.Adiciona('TipEttDmt', 'TipoEstrutura'); Self.Adiciona('TipFreMov', 'TipoFrete'); Self.Adiciona('TipFreEtq', 'TipoFreteEstoque'); Self.Adiciona('TipFrsPrgFrs', 'TipoFeriasProgramacaoFerias'); Self.Adiciona('TipInsEct', 'TipoInscricaoEscritorio'); Self.Adiciona('TipInsScoRsp', 'TipoInscricaoSocioResponsavel'); Self.Adiciona('TipInsEmp', 'TipoInscricao'); Self.Adiciona('TipInsPes', 'TipoInscricaoPessoa'); Self.Adiciona('TipInsScoRsp', 'TipoInscricaoSocioResponsavel'); Self.Adiciona('TipIntEmpGerCtb', 'TipoIntegracao'); Self.Adiciona('TipLanCodFisLanPadTri', 'TipoLancamentoCodigoFiscalLancamentoPadraoTributacao'); Self.Adiciona('TipLanPta', 'TipoLancamentoParteA'); Self.Adiciona('TipLanFCont', 'TipoLancamentoFCont'); Self.Adiciona('TipLanIteBasEtt', 'TipoLancamentoItem'); Self.Adiciona('TipLanMovEcf', 'TipoLancamentoMovimentacaoEmissorCupomFiscal'); Self.Adiciona('TipLanPad', 'TipoLancamentoPadrao'); Self.Adiciona('TipLanPadFol', 'TipoLancamentoPadraoFolha'); Self.Adiciona('TipLanSerValLanPadTri', 'TipoLancamentoSerieValidaLancamentoPadraoTributacao'); Self.Adiciona('TipLanSpg', 'TipoLancamentoSopag'); Self.Adiciona('TipMarSec', 'TipoMarcaSecao'); Self.Adiciona('TipNotCtbImpStg', 'RealizaContabilizacaoCodigoContabilExistenteParaEmitenteDestinatario'); Self.Adiciona('TipOutVlrFis','TipoOutrosValoresFiscais'); Self.Adiciona('TipOpeDie', 'TipoOperacaoDie'); Self.Adiciona('TipParHon', 'TipoParametroHonorario'); Self.Adiciona('TipPes', 'TipoPessoa'); Self.Adiciona('TipPesCbtInd', 'TipoPessoaContribuinteIndividual'); Self.Adiciona('TipPesJur', 'TipoPessoaJuridica'); Self.Adiciona('TipPesMedRsp', 'TipoPessoaMedicoResponsavel'); Self.Adiciona('TipPesRspExa', 'TipoPessoaResponsavelExame'); Self.Adiciona('TipPesRspMonBio', 'TipoPessoaResponsavelMonitoracaoBiologica'); Self.Adiciona('TipPrdMovIteEtq', 'TipoItemEstoque'); Self.Adiciona('TipPrdRamAtv', 'TipoProdutoRamoAtividade'); Self.Adiciona('TipPtd', 'TipoPartida'); Self.Adiciona('TipRsp', 'TipoResponsabilidade'); Self.Adiciona('TipScoRsp', 'TipoSocioResponsavel'); Self.Adiciona('TipSec', 'TipoSecao'); Self.Adiciona('TipSerMovIss', 'TipoServico'); Self.Adiciona('TipSerDmsMovIss', 'TipoServicoDMS'); Self.Adiciona('TipSerVal', 'TipoSerie'); Self.Adiciona('TipSerValEnt', 'TipoSerieValidaEntradaImportacaoSintegra'); Self.Adiciona('TipSerValSai', 'TipoSerieValidaSaidaImportacaoSintegra'); Self.Adiciona('TipSitEpg', 'TipoSituacaoEmpregado'); Self.Adiciona('TipSitEsp', 'TipoSituacaoEspecial'); Self.Adiciona('TipUndOrcRsp', 'TipoUnidadeOrcamentariaResponsavel'); Self.Adiciona('TipVndCodFisLanPadTri', 'TipoVendaCodigoFiscalLancamentoPadraoTributacao'); Self.Adiciona('TipVndSerValLanPadTri', 'TipoVendaSerieValidaLancamentoPadraoTributacao'); Self.Adiciona('TipIncIns', 'TipoIncidenciaINSS'); Self.Adiciona('TmpMsg', 'TemporizadorMensagem'); Self.Adiciona('TotCreAprMesEfd', 'TotalCreditoApropriadoMesEFD'); Self.Adiciona('TotCreRecTraEfd', 'TotalCreditoRecebidoTransferenciaEFD'); Self.Adiciona('TotCreUti', 'TotalCreditoUtilizado'); Self.Adiciona('TotCreUtiPerEfd', 'TotalCreditoUtilizadoPeriodoEFD'); Self.Adiciona('GrpTot', 'GrupoTotalizador'); Self.Adiciona('TotParApr', 'TotalParcelasApropriarItemAtivoFixo'); Self.Adiciona('TxaDepIaf', 'TaxaDepreciacaoItemAtivoFixo'); Self.Adiciona('TxtBalNotExp', 'TextoBalanco'); Self.Adiciona('TxtBalPre', 'TextoParecerConselhoFiscal'); Self.Adiciona('TxtParConAdm', 'TextoParecerConselhoAdministrativo'); Self.Adiciona('TxtOfiCir', 'TextoOficioCircular'); Self.Adiciona('TxtNorRef', 'TextoNormasReferenciadas'); Self.Adiciona('UltSeqRep', 'UltimaSequenciaREP'); Self.Adiciona('UsuDefAnaSin', 'UsuarioDefineAnaliticaSintetica'); Self.Adiciona('UndEstClaFis', 'UnidadeEstatisticaClassificacaoFiscal'); Self.Adiciona('UniMed','UnidadeMedida'); Self.Adiciona('UniMedEtq','CodigoUnidadeMedidaEstoque'); Self.Adiciona('UniMedSerPre', 'UnidadeMedidaServico'); Self.Adiciona('UTIBENINC', 'UtilizacaoDosBensIncorporados'); Self.Adiciona('UTLEPC', 'UtilizacaoEPC'); Self.Adiciona('UFVei', 'UFVeiculo'); Self.Adiciona('UtiCodAjuApuIcm', 'UtilizacaoCodigoAjusteApuracaoICMS'); end; procedure TCustomDicionario.AdicionaAtributosVWXYZ; begin Self.Adiciona('VlrBaiImo', 'ValorBaixaImobilizado'); Self.Adiciona('VLRBASCRE', 'BaseCalculoCredito'); Self.Adiciona('VLRBSEPISBLI100', 'ValorBasePisBlocoI100'); Self.Adiciona('VLRBSECOFBLI100', 'ValorBaseCofinsBlocoI100'); Self.Adiciona('VLRCOFBLI100', 'ValorCofinsBlocoI100'); Self.Adiciona('VlrCntRefIni', 'ValorContaReferencialInicial'); Self.Adiciona('VlrCntRefFin', 'ValorContaReferencialFinal'); Self.Adiciona('VlrFcpDes', 'ValorFundoCombatePobreza'); Self.Adiciona('VlrCslImpFed', 'ValorCSLLImpostoFederal'); Self.Adiciona('VlrCslRet', 'ValorCSLLRetido'); Self.Adiciona('VlrCntRec', 'ValorContasReceber'); Self.Adiciona('VlrCntRecAnt', 'ValorContasReceberAnterior'); Self.Adiciona('VlrCntPag', 'ValorContasPagar'); Self.Adiciona('VlrCntPagAnt', 'ValorContasPagarAnterior'); Self.Adiciona('VlrCmpMer', 'ValorCompraMercadorias'); Self.Adiciona('VlrCmpAti', 'ValorCompraAtivo'); Self.Adiciona('VlrConConZee', 'ValorContabilContabilizacaoLeituraZ'); Self.Adiciona('VlrCrePer', 'ValorCreditoPeriodo'); Self.Adiciona('VlrCreExtApuAnt', 'ValorCreditoExtemporaneoApuradoAnterior'); Self.Adiciona('VlrTOTCreApu', 'ValorTotalCreditoApurado'); Self.Adiciona('VlrCreDesAnt', 'ValorCreditoDescontoAnterior'); Self.Adiciona('VlrCreResAnt', 'ValorCreditoRessarcimentoAnterior'); Self.Adiciona('VlrCreComIntAnt', 'ValorCreditoCompensacaoIntermediariaAnterior'); Self.Adiciona('VlrSldCreDis', 'ValorSaldoCreditoDisponivel'); Self.Adiciona('VlrCreDes', 'ValorCreditoDescontado'); Self.Adiciona('VlrCreRes', 'ValorCreditoRessarcimento'); Self.Adiciona('VlrCreComInt', 'ValorCreditoCompensacaoIntermediaria'); Self.Adiciona('VlrCreTra', 'ValorCreditoTransferido'); Self.Adiciona('VlrCreOutFor', 'ValorCreditoOutrasFormas'); Self.Adiciona('VlrSldCre', 'ValorSaldoCredito'); Self.Adiciona('VlrSldCreAntDifAli', 'ValorSaldoCredorDiferencialAliquota'); Self.Adiciona('VlrSldCreTra', 'ValorSaldoCredorTransportar'); Self.Adiciona('VlrDedDifAli', 'ValorDeducaoDiferencialAliquota'); Self.Adiciona('VlrSldDevAntDifAli', 'ValorSaldoDevedorAnteriorDiferencialAliquota'); Self.Adiciona('VLRCxa', 'ValorCaixa'); Self.Adiciona('VLRCxaAnt', 'ValorCaixaAnterior'); Self.Adiciona('VlrDebEspDifAli', 'ValorDebitoEspontaneoDiferencialAliquota'); Self.Adiciona('VlrDebPer', 'ValorDebitoPeriodo'); Self.Adiciona('VLRDIFSLD', 'ValorDiferencaSaldos'); Self.Adiciona('VlrDoa', 'ValorDoacao'); Self.Adiciona('VlrDoaCri', 'ValorDoacaoCrianca'); Self.Adiciona('VlrDoaIdo', 'ValorDoacaoIdoso'); Self.Adiciona('VLRDEDGERBLI100', 'ValorDeducaoGeralBlocoI100'); Self.Adiciona('VLRDEDESPBLI100', 'ValorDeducaoEspecificoBlocoI100'); Self.Adiciona('VLRDETBLI200', 'ValorDetalhado'); Self.Adiciona('VLRDETRECBLI300', 'ValorDetalhamentoRecolherBlocoI300'); Self.Adiciona('VLRPISBLI100', 'ValorPisBlocoI100'); Self.Adiciona('VlrRec', 'ValorReceitas'); Self.Adiciona('VlrRec', 'ValorRecolhido'); Self.Adiciona('VLRRECBLI100', 'ValorReceitaBlocoI100'); Self.Adiciona('VlrRemTrb', 'ValorRemuneracaoTrabalhador'); Self.Adiciona('VlrLucDiv', 'ValorLucrosDividendos'); Self.Adiciona('VlrJurCap', 'ValorJurosCapital'); Self.Adiciona('VlrDemRen', 'ValorDemaisRendimentos'); Self.Adiciona('VlrIrrRet', 'ValorIRRetido'); Self.Adiciona('VlrIncIni', 'ValorIncentivoInicio'); Self.Adiciona('VlrIncFin', 'ValorIncentivoFim'); Self.Adiciona('VlrRndBrt', 'ValorRendimentoBruto'); Self.Adiciona('VelMqnCta', 'VelocidadeMaquinaColetora'); Self.Adiciona('VenExp', 'VendasExportadora'); Self.Adiciona('VLRNOTIMPFED', 'ValorNotaImpostoFederal'); Self.Adiciona('VlrL210', 'ValorN210'); Self.Adiciona('VLRN500', 'ValorN500'); Self.Adiciona('VLRN600', 'ValorN600'); Self.Adiciona('VLRN610', 'ValorN610'); Self.Adiciona('VLRN620', 'ValorN620'); Self.Adiciona('VLRN630', 'ValorN630'); Self.Adiciona('VLRN650', 'ValorN650'); Self.Adiciona('VLRN660', 'ValorN660'); Self.Adiciona('VLRN670', 'ValorN670'); Self.Adiciona('VLRP200', 'ValorP200'); Self.Adiciona('VLRP300', 'ValorP300'); Self.Adiciona('VLRP400', 'ValorP400'); Self.Adiciona('VLRP500', 'ValorP500'); Self.Adiciona('VLRY540', 'ValorY540'); Self.Adiciona('VLRT120', 'ValorT120'); Self.Adiciona('VLRT150', 'ValorT150'); Self.Adiciona('VLRT170', 'ValorT170'); Self.Adiciona('VLRT181', 'ValorT181'); Self.Adiciona('VLRU180', 'ValorU180'); Self.Adiciona('VLRU182', 'ValorU182'); Self.Adiciona('VctFatMesAtl', 'VencimentoMesEmissao'); Self.Adiciona('VarExiSupSplNacTri', 'VaraExigibilidadeSuspensa'); Self.Adiciona('VarExiSupApuSplNac', 'VaraExigibilidadeSuspensaApuracao'); Self.Adiciona('VerRep', 'VersaoREP'); Self.Adiciona('VidUti', 'VidaUtilItemAtivoFixo'); Self.Adiciona('VisImpPreGer', 'VisualizaImpressao'); Self.Adiciona('VisOgcCtb', 'VisualizaAgendaObrigacoes'); Self.Adiciona('VlrAcrIssIteMovEcf', 'ValorAcrescimoIssItemMovimentacaoCupomFiscal'); Self.Adiciona('VlrAcrIteMovEcf', 'ValorAcrescimoItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrAcuSggApuSplNac', 'ValorAcumuladoSegregacaoApuracaoSimplesNacional'); Self.Adiciona('VlrAcuSggMajApuSplNac', 'ValorAcumuladoSegregacaoMajoradoApuracaoSimplesNacional'); Self.Adiciona('VlrAdiIaf', 'ValorAdicaoItemAtivoFixo'); Self.Adiciona('VlrAgeNocMovMen', 'ValorAgenteNocivoMovimentacaoMensal'); Self.Adiciona('VLRAJU', 'ValorAjuste'); Self.Adiciona('VlrAjuApu', 'ValorAjusteApuracao'); Self.Adiciona('VlrAjuApuIpi', 'ValorAjusteApuracaoIPI'); Self.Adiciona('VlrAjuBenIncApuIcmEFD', 'ValorAjusteBeneficioIncentivoApuracaoICMSEFD'); Self.Adiciona('VlrAjuCreApuIcm', 'ValorAjusteCreditoDocumentoFiscal'); Self.Adiciona('VlrAjuDebApuIcm', 'ValorAjusteDebitoDocumentoFiscal'); Self.Adiciona('VlrAjuDifAli', 'ValorAjusteOperacao'); Self.Adiciona('VlrAjuOpeIte', 'ValorAjusteOperacaoDocumentoFiscal'); Self.Adiciona('VlrAli', 'AliquotaContribuicaoPrevidenciaria'); Self.Adiciona('VlrAliRed', 'ValorAliquotaReduzida'); Self.Adiciona('VlrAliCof', 'ValorAliquotaCofins'); Self.Adiciona('VlrAliIcmOutObrDocFisEFD', 'ValorAliquotaICMSObrigacoesTributariasDocumentoFiscal'); Self.Adiciona('VlrAliMovIcm', 'ValorAliquotaICMS'); Self.Adiciona('VlrAliMovIpi', 'ValorAliquotaIPI'); Self.Adiciona('VlrAliMovIss', 'ValorAliquotaISSQN'); Self.Adiciona('VlrAliPis', 'ValorAliquotaPis'); Self.Adiciona('VlrAplFin', 'ValorAplicacaoFinanceira'); Self.Adiciona('VlrAplFinAnt', 'ValorAplicacaoFinanceiraAnterior'); Self.Adiciona('VlrAquImo', 'ValorAquisicaoImobilizado'); Self.Adiciona('VlrAqsIaf', 'ValorAquisicaoItemAtivoFixo'); Self.Adiciona('VlrAquMaq', 'ValorAquisicaoMaquina'); Self.Adiciona('VlrBasCal', 'ValorBaseCalculo'); Self.Adiciona('VlrBasCalCof', 'ValorBaseCofins'); Self.Adiciona('VlrBasCalCre', 'ValorBaseCalculoCredito'); Self.Adiciona('VlrBasCalIpiConVlrIpi', 'ValorBaseCalculoIPIConsolidacaoValorIPI'); Self.Adiciona('VlrBasCalIcmOutObrDocFisEFD', 'ValorBaseCalculoICMSObrigacoesTributariasDocumentoFiscal'); Self.Adiciona('VlrBasCalMovIpi', 'ValorBaseCalculoIPI'); Self.Adiciona('VlrBasCalMovIss', 'ValorBaseCalculoISSQN'); Self.Adiciona('VlrBasCalOpe', 'ValorBaseCalculoOperacao'); Self.Adiciona('VlrBasCalPis', 'ValorBasePis'); Self.Adiciona('VlrBseCofDocFis', 'ValorBaseCofinsDocumentoFiscal'); Self.Adiciona('VlrBasCofMovIteEtq', 'ValorBaseCofinsMovimentacaoItemEstoque'); Self.Adiciona('VlrBasCofIteMovEcf', 'ValorBaseCofinsItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrBseCofOutOpe', 'ValorBaseCOFINSOutrasOperacoes'); Self.Adiciona('VlrBasCreCOF','ValorDebitoCreditoCOFINS'); Self.Adiciona('VlrBasIaf', 'ValorBaseItemAtivoFixo'); Self.Adiciona('VlrBasIcm', 'ValorBaseIcms'); Self.Adiciona('VlrBasIcmMovIteEtq', 'ValorBaseIcmsMovimentacaoItemEstoque'); Self.Adiciona('VlrBasIcmNorSubTriMov', 'ValorBaseICMSNormal'); Self.Adiciona('VlrBasIcmRetMov', 'ValorBaseICMSRetido'); Self.Adiciona('VlrBasIcmUndFedDes', 'ValorBaseIcmsUFDestino'); Self.Adiciona('VlrBasIpiMovIteEtq', 'ValorBaseIpiMovimentacaoItemEstoque'); Self.Adiciona('VlrBasItePatLiq', 'ValorBaseItemPatrimonioLiquido'); Self.Adiciona('VlrBsePisDocFis', 'ValorBasePisDocumentoFiscal'); Self.Adiciona('VlrBasPisIteMovEcf', 'ValorBasePisItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrBasPisMovIteEtq', 'ValorBasePisMovimentacaoItemEstoque'); Self.Adiciona('VlrBsePisOutOpe', 'ValorBasePisOutrasOperacoes'); Self.Adiciona('VlrBasRedMov', 'ValorBaseReduzidaICMS'); Self.Adiciona('VlrBasRedIpiConVlrIpi', 'ValorBaseReduzidaIPIConsolidacaoValorIPI'); Self.Adiciona('VlrBasRedIpiMov', 'ValorBaseReduzidaIPI'); Self.Adiciona('VlrBasSubStr', 'ValorBaseSubstituicaoTributaria'); Self.Adiciona('VlrCanIssIteMovEcf', 'ValorCancelamentoISSItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrCanIteMovEcf', 'ValorCancelamentoItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrCap', 'ValorCapital'); Self.Adiciona('VlrCapAnt', 'ValorCapitalAnterior'); Self.Adiciona('VlrCof', 'ValorCofins'); Self.Adiciona('VlrConPre', 'ValorContribuicaoPrevidenciaria'); Self.Adiciona('VlrConPreSobRec', 'ValorContribuicaoPrevidenciariaSobreReceitaBruta'); Self.Adiciona('VlrConPreSobRem', 'ValorContribuicaoPrevidenciariaSobreRemuneracao'); Self.Adiciona('VlrCre', 'ValorCredito'); Self.Adiciona('VlrCreCsl', 'ValorCreditoCsll'); Self.Adiciona('VlrCreApuImpCmp', 'ValorCreditoApuracaoImpostoComplemento'); Self.Adiciona('VlrCreIcmIaf', 'ValorCreditoIcmsItemAtivoFixo'); Self.Adiciona('VlrCreIniIcmImpVlrIni', 'ValorCreditoInicialIcmsImpostoValorInicial'); Self.Adiciona('VlrCreIniIpiImpValIni', 'ValorCreditoInicialIpiImpostoValorInicial'); Self.Adiciona('VlrCofDocFis', 'ValorCofinsDocumentoFiscal'); Self.Adiciona('VlrCofImpFed', 'ValorCOFINSImpostoFederal'); Self.Adiciona('VlrCofIteMovEcf', 'ValorCofinsItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrCofMovIteEtq', 'ValorCOFINSItemEstoque'); Self.Adiciona('VlrCofOutOpe', 'ValorCOFINSOutrasOperacoes'); Self.Adiciona('VlrCreOutMovIcm', 'ValorCreditoOutorgado'); Self.Adiciona('VlrCrePIS','ValorDebitoCreditoPIS'); Self.Adiciona('VLRCRECOF', 'ValorCreditoCOFINS'); Self.Adiciona('VlrCreDecPis', 'ValorCreditosDecorrentesPIS'); Self.Adiciona('VlrCreDecCof', 'ValorCreditosDecorrentesCOFINS'); Self.Adiciona('VlrCrePisDesPerAntEsc', 'ValorCreditoPisDescontadoPeriodoAnteriorEscrituracao'); Self.Adiciona('VlrCrePisDesPerEsc', 'ValorCreditoPisDescontarPeriodoEscrituracao'); Self.Adiciona('VlrCreCofDesPerAntEsc', 'ValorCreditoCofinsDescontadoPeriodoAnteriorEscrituracao'); Self.Adiciona('VlrCreCofDesPerEsc', 'ValorCreditoCofinsDescontarPeriodoEscrituracao'); Self.Adiciona('VlrCtbCodFis', 'ValorContabilCodigoFiscal'); Self.Adiciona('VlrCtbIteMovCtb', 'ValorContabilItemMovimentacaoContabil'); Self.Adiciona('VlrCtbMovCtb', 'ValorContabilMovimentacaoContabil'); Self.Adiciona('VlrCtbSpg', 'ValorContabilizacaoSopag'); Self.Adiciona('VlrCusAcuMesAntEsc', 'ValorCustoAcumuladoMesAnteriorEscrituracao'); Self.Adiciona('VlrCusMesEsc', 'ValorCustoMesEscrituracao'); Self.Adiciona('VlrCusOrc', 'ValorCustoOrcado'); Self.Adiciona('VlrCusSemDirCreAtvImo', 'ValorCustoSemDireitoCreditoAtividadeImobiliaria'); Self.Adiciona('VlrDeb', 'ValorDebito'); Self.Adiciona('VlrDebApuImpCmp', 'ValorDebitoApuracaoImpostoComplemento'); Self.Adiciona('VlrDepAmoIncPer', 'ValorDeprAmortIncorridosNoPeriodo'); Self.Adiciona('VlrDes', 'ValorDescontos'); Self.Adiciona('VlrDedCof', 'ValorDeducaoCofins'); Self.Adiciona('VlrDedPis', 'ValorDeducaoPis'); Self.Adiciona('VlrDesAceMovIteEtq', 'ValorDespesasAcessorias'); Self.Adiciona('VlrDesIssIteMovEcf', 'ValorDescontoISSItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrDesIteMovEcf', 'ValorDescontoItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrDesMovIss', 'ValorDescontoMovimentoServico'); Self.Adiciona('VlrDesMovIteEtq', 'ValorDescontoItemEstoque'); Self.Adiciona('VlrDet', 'ValorDetalhamento'); Self.Adiciona('VlrDetVlrManDemRes', 'ValorDetalhamentoValorManual'); Self.Adiciona('VlrDevSubTrbApuIcm', 'ValorDevolucaoSubstituicaoTributaria'); Self.Adiciona('VlrDstEmpGerCtb', 'ValorDesconto'); Self.Adiciona('VlrEncCar', 'ValorEncontradoDaCaracteristica'); Self.Adiciona('VlrEnt', 'ValorEntrada'); Self.Adiciona('VlrEstIcm', 'ValorEstornoCompICMS'); Self.Adiciona('VlrEstIss', 'ValorEstornoCompISS'); Self.Adiciona('VlrExcRecBru', 'ValorExclusaoReceitaBruta'); Self.Adiciona('VlrExe', 'ValorExecucao'); Self.Adiciona('VlrEtq', 'ValorEstoque'); Self.Adiciona('VlrEtqAnt', 'ValorEstoqueAnterior'); Self.Adiciona('VlrFatAntApuSplNac', 'ValorFaturamentoAnteriorApuracaoSimplesNacional'); Self.Adiciona('VlrFatBruSplNac', 'ValorFaturamentoBrutoSimplesNacional'); Self.Adiciona('VlrFat12UltMesSplNac', 'ValorFaturamento12UltimosMesesSimplesNacional'); Self.Adiciona('VlrFatAcuSplNac', 'ValorFaturamentoAcumuladoSimplesNacional'); Self.Adiciona('VlrFatIcm', 'ValorFaturamentoCompICMS'); Self.Adiciona('VlrFatIss', 'ValorFaturamentoCompISS'); Self.Adiciona('VlrFinLimEnq', 'ValorFinalLimiteEnquadramento'); Self.Adiciona('VlrFixIcmSggApuSplNac', 'ValorFixoICMSSegregacaoApuracaoSimplesNacional'); Self.Adiciona('VlrFixIcmApuSplNac', 'ValorFixoICMSApuracaoSimplesNacional'); Self.Adiciona('VlrFixIssSggApuSplNac', 'ValorFixoISSSegregacaoApuracaoSimplesNacional'); Self.Adiciona('VlrFixIssApuSplNac', 'ValorFixoISSApuracaoSimplesNacional'); Self.Adiciona('VlrFol', 'ValorFolha'); Self.Adiciona('VlrIcmDes', 'ValorICMSDestinatario'); Self.Adiciona('VlrIcmRem', 'ValorICMSRemetente'); Self.Adiciona('VlrIcmFcp', 'ValorIcmsFcp'); Self.Adiciona('VlrIcmIntUndFedDes', 'ValorIcmsInterestadualUFDestino'); Self.Adiciona('VlrIcmIntUndFedRem', 'ValorIcmsInterestadualUFRemetente'); Self.Adiciona('VlrFolTot', 'ValorTotalFolha'); Self.Adiciona('VlrFolPgt12UltMesSplNac', 'ValorFolhaPagamento12UltimosMesesSimplesNacional'); Self.Adiciona('VlrFolPgtApuSplNac', 'ValorFolhaPagamentoApuracaoSimplesNacional'); Self.Adiciona('VlrFre', 'ValorFrete'); Self.Adiciona('VlrFreMovIteEtq', 'ValorFreteMovimentacaoItemEstoque'); Self.Adiciona('VlrGerIteMovEcf', 'TotalGeralItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrGerIteMovEcf', 'TotalGeralItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrImpIcmDpiMovCodFis', 'ValorICMSDPI'); Self.Adiciona('VlrImpIteMovEcf', 'ValorImpostoItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrImpTriZee', 'ValorImpostoTributacaoLeituraZ'); Self.Adiciona('VlrIcmMovIteEtq', 'ValorICMSMovimentacaoItemEstoque'); Self.Adiciona('VlrIcmNorSubTrbOutObrDocFisEFD', 'ValorICMSNormalSubstituicaoTributaria'); Self.Adiciona('VlrIcmRetComVlrCtb','ValorIcmsRetidoCompoeValorContabil'); Self.Adiciona('VlrIcmRetMov', 'ValorICMSRetido'); Self.Adiciona('VlrIcmSubTriMovIteEtq', 'ValorICMSSubstituicaoTributaria'); Self.Adiciona('VlrIcmRetSubTrbApuIcm', 'ValorICMSRetidoSubstituicaoTributaria'); Self.Adiciona('VlrInfAdiApuVlrDec', 'ValorInformacaoAdicionalApuracaoValorDeclaratorioEFD'); Self.Adiciona('VlrIniLimEnq', 'ValorInicialLimiteEnquadramento'); Self.Adiciona('VlrIpiConVlrIpi', 'ValorIPIConsolidacaoValorIPI'); Self.Adiciona('VlrIpiIteMovEcf', 'ValorIPIItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrIpiMovIteEtq', 'ValorIpiItemEstoque'); Self.Adiciona('VlrIpiProCom', 'ValorIPIProduto'); Self.Adiciona('VlrIrrMov', 'ValorIRRFServicoNotaFiscal'); Self.Adiciona('VlrIrpImpFed', 'ValorIRImpostoFederal'); Self.Adiciona('VlrIrpRet', 'ValorIRRetido'); Self.Adiciona('VlrIseIcmMov', 'ValorIsentasICMS'); Self.Adiciona('VlrIseIpiConVlrIpi', 'ValorIsentoIPIConsolidacaoValorIPI'); Self.Adiciona('VlrIseIpiMov', 'ValorIsentasIPI'); Self.Adiciona('VlrIssComMov', 'ValorISSQNComplementarNotaFiscal'); Self.Adiciona('VlrIssRetMov', 'ValorISSQNRetidoNotaFiscal'); Self.Adiciona('VlrIteCtbSpg', 'ValorItemContabilizacaoSopag'); Self.Adiciona('VlrIteSpg', 'ValorItemSopag'); Self.Adiciona('VlrLan', 'ValorLancamento'); Self.Adiciona('VlrLanCenNeg', 'ValorLancamentoCentroNegocios'); Self.Adiciona('VlrLanLcx', 'ValorLancamentoLivroCaixa'); Self.Adiciona('vlrlanpta', 'ValorLancamentoParteA'); Self.Adiciona('VlrLiqSerPreFol', 'ValorLiquidoServicoPrestado'); Self.Adiciona('VlrLot', 'ValorLote'); Self.Adiciona('VlrMulCntRec', 'ValorMultaContasReceber'); Self.Adiciona('VLRCUM','ValorCumulativo'); Self.Adiciona('VlrCtbMovLcx','ValorContabilMovimentacaoLivroCaixa'); Self.Adiciona('VLRFINVOLVENCMB','ValorLeituraFinal'); Self.Adiciona('VLRINIVOLVENCMB','ValorLeituraInicial'); Self.Adiciona('VOLAFEVOLVENCMB','ValorAferidoBomba'); Self.Adiciona('VLRBASCALISS','ValorBaseCalculoIss'); Self.Adiciona('VlrBasDir', 'ValorBaseDIRF'); Self.Adiciona('VlrBasFgt', 'ValorBaseFGTS'); Self.Adiciona('VlrBasIns', 'ValorBaseINSS'); Self.Adiciona('VlrBasInsEmpSerPreFol', 'ValorBaseInsSEmpresaServicoPrestado'); Self.Adiciona('VlrBasInsSerPreFol', 'ValorBaseInsSServicoPrestado'); Self.Adiciona('VlrBasIrr', 'ValorBaseIRRF'); Self.Adiciona('VlrBasIrrSerPreFol', 'ValorBaseIrrFServicoPrestado'); Self.Adiciona('VlrBasRai', 'ValorBaseRAIS'); Self.Adiciona('VlrBasSal', 'ValorBaseSalario'); Self.Adiciona('VlrBasSalFam', 'ValorBaseSalarioFamilia'); Self.Adiciona('VlrBasSalInt', 'ValorBaseSalarioIntegral'); Self.Adiciona('VlrBseCalRet', 'ValorBaseCalculoRetencao'); Self.Adiciona('VlrBxaMovPgrRec', 'ValorBaixaMovimentacaoPagarReceber'); Self.Adiciona('VLRCOMAPUIMP','ValorComprasApuracaoImposto'); Self.Adiciona('VlrDocRenTit', 'ValorDocumentoRenegociacaoTitulo'); Self.Adiciona('VLRGNR','ValorGNRE'); Self.Adiciona('VlrInsEmpMovMen', 'ValorINSSEmpresaMovimentacaoMensal'); Self.Adiciona('VLRICMMOVINV','ValorICMSMovimentacaoInventario'); Self.Adiciona('VLRIMPTRIAPUIMP','ValorDoImpostoApuracaoImposto'); Self.Adiciona('VlrInsEmpSerPreFol', 'ValorINSSEmpresaServicoPrestado'); Self.Adiciona('VlrInsSerPreFol', 'ValorINSSServicoPrestado'); Self.Adiciona('VlrIrrSerPreFol', 'ValorIRRFServicoPrestado'); Self.Adiciona('VLRISEISS','ValorIsentoIss'); Self.Adiciona('VLRISS','ValorIss'); Self.Adiciona('VLRICMCOM','ValorICMSComplementar'); Self.Adiciona('VLRISSRET','ValorIssRetido'); Self.Adiciona('VlrIssSerPreFol', 'ValorIssServicoPrestado'); Self.Adiciona('VlrNaoCumExp', 'ValorNaoCumulativoExportacao'); Self.Adiciona('VlrNaoCumNaoTriMecInt', 'ValorNaoCumulativoNaoTributadaMercadoInterno'); Self.Adiciona('VlrNaoCumTriMerInt', 'ValorNaoCumulativoTributadaMercadoInterno'); Self.Adiciona('VLRNAOTRBISS','ValorNaoTributadoIss'); Self.Adiciona('VlrSai','ValorSaida'); Self.Adiciona('VlrSalMin','ValorSalarioMinimo'); Self.Adiciona('VLRVENAPUIMP','ValorVendasApuracaoImposto'); Self.Adiciona('VlrMatAplMov', 'ValorMateriaisAplicacosNotaFiscal'); Self.Adiciona('VlrMovIcm', 'ValorICMS'); Self.Adiciona('VlrMovIss', 'ValorISSQN'); Self.Adiciona('VlrMovIteEtq', 'ValorItem'); Self.Adiciona('VlrMovIpi', 'ValorIPI'); Self.Adiciona('VlrNaoTrbIcmMov', 'ValorNaoTributadasICMS'); Self.Adiciona('VlrNaoTrbIpiConVlrIpi', 'ValorNaoTributadoIPIConsolidacaoValorIPI'); Self.Adiciona('VlrNaoTrbIpiMov', 'ValorNaoTributadasIPI'); Self.Adiciona('VlrNotMov', 'ValorNotaFiscal'); Self.Adiciona('VlrNaoTriIssMov', 'ValorNaoTributadoServicoNotaFiscal'); Self.Adiciona('VlrObrIcmRecEfd', 'ValorObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('VlrObrRec', 'ValorObrigacaoRecolher'); Self.Adiciona('VlrOpe', 'ValorOperacao'); Self.Adiciona('VlrOpeAqu', 'ValorOperacaoAquisicao'); Self.Adiciona('VlrOpeCrtCreDes', 'ValorLancamentoCredito'); Self.Adiciona('VlrOpeOutOpe', 'ValorOperacaoOutrasOperacoes'); Self.Adiciona('VlrOpeVlrAgr', 'ValorAgregado'); Self.Adiciona('VlrOpeSemIof', 'ValorOperacaoSemIof'); Self.Adiciona('VlrOpeCrtDebDes', 'ValorLancamentoDebito'); Self.Adiciona('VlrOpr', 'ValorOperacoes'); Self.Adiciona('VlrOutCreSubTrbApuIcm', 'ValorOutrosCreditosSubstituicaoTributaria'); Self.Adiciona('VlrOutDebDifAli', 'ValorOutrosDebitosDiferencialAliquota'); Self.Adiciona('VlrOutDebSubTrbApuIcm', 'ValorOutrosDebitosSubstituicaoTributaria'); Self.Adiciona('VlrOutDesAce', 'ValorOutrasDespesasAcessorias'); Self.Adiciona('VlrOutEntMovMen', 'ValorOutrasEntidadesMovimentacaoMensal'); Self.Adiciona('VlrOutIcmMov', 'ValorOutrasICMS'); Self.Adiciona('VlrOutIpiConVlrIpi', 'ValorOutrasIPIConsolidacaoValorIPI'); Self.Adiciona('VlrOutIpiMov', 'ValorOutrasIPI'); Self.Adiciona('VlrOutOutObrDocFisEFD', 'ValorOutrasObrigacoesTributariasDocumentoFiscal'); Self.Adiciona('VlrOutVlrFis', 'ValorOutrosValoresFiscais'); Self.Adiciona('VlrPagSerPreFol', 'ValorPagoServicoPrestado'); Self.Adiciona('VlrParIse', 'ValorParcelaIsenta'); Self.Adiciona('VlrParMovPgrRec', 'ValorParcelaMovimentacaoPagarReceber'); Self.Adiciona('VlrParRecIse', 'ValorParcelaRecolherIsento'); Self.Adiciona('VlrParRecRed', 'ValorParcelaRecolherReducao'); Self.Adiciona('VlrPerIteBasEtt', 'PercentualItem'); Self.Adiciona('VlrPis', 'ValorPis'); Self.Adiciona('VlrPisDocFis', 'ValorPisDocumentoFiscal'); Self.Adiciona('VlrPisImpFed', 'ValorPISImpostoFederal'); Self.Adiciona('VlrPisIteMovEcf', 'ValorPisItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrPisMovIteEtq', 'ValorPISItemEstoque'); Self.Adiciona('VlrPisOutOpe', 'ValorPisOutrasOperacoes'); Self.Adiciona('VlrRecAcu', 'ValorRecebidoAcumulado'); Self.Adiciona('VlrRecBruCorAtv', 'ValorReceitaBrutaCorrespondenteAtividade'); Self.Adiciona('VlrRecBruTotPesJur', 'ValorReceitaBrutaTotalPessoaJuridica'); Self.Adiciona('VlrRecSggApuSplNac', 'ValorReceitaSegregada'); Self.Adiciona('VlrRecSggInfAdiSplNac', 'ValorReceitaSegregadaInformacaoAdicional'); Self.Adiciona('VlrRecSggInfAdiMajSplNac', 'ValorReceitaSegregadaInformacaoAdicionalMajorado'); Self.Adiciona('VlrRecSggMajApuSplNac', 'ValorReceitaSegregadaMajorado'); Self.Adiciona('VlrRemCbtInd', 'ValorRemuneracaoContribuinteIndividual'); Self.Adiciona('VlrResSubTrbApuIcm', 'ValorRessarsimentoSubstituicaoTributaria'); Self.Adiciona('VlrRetCof', 'ValorRetencaoCofins'); Self.Adiciona('VlrRetPis', 'ValorRetencaoPis'); Self.Adiciona('VlrSldIni', 'ValorSaldoInicial'); Self.Adiciona('VlrSldFin', 'ValorSaldoFinal'); Self.Adiciona('VLRSLDFIS', 'ValorSaldoFiscal'); Self.Adiciona('VLRSLDSOC', 'ValorSaldoSocietario'); Self.Adiciona('vlrsldfimperapu', 'ValorSaldoFinalPeriodoApuracao'); Self.Adiciona('VlrSeg', 'ValorSeguro'); Self.Adiciona('VlrSegAciMovMen', 'ValorSeguroAcidenteMovimentacaoMensal'); Self.Adiciona('VlrSegMovIteEtq', 'ValorSeguroMovimentacaoItemEstoque'); Self.Adiciona('VlrSegMovIteEtq', 'ValorSeguroMovimentacaoItemEstoque'); Self.Adiciona('VlrSer', 'ValorServicosPrestados'); Self.Adiciona('VlrSubEmpTriMov', 'ValorSubEmpreiteiraNotaFiscal'); Self.Adiciona('VlrSplNac', 'ValorSimplesNacional'); Self.Adiciona('VlrTerSerPreFol', 'ValorTerceirosServicoPrestado'); Self.Adiciona('VlrTotAti', 'ValorTotalAtivo'); Self.Adiciona('VlrTotAju', 'ValorTotalAjustes'); Self.Adiciona('VlrTotAjuAcr', 'ValorTotalAjusteAcrescimo'); Self.Adiciona('VlrTotAjuCreApuIcm', 'ValorTotalAjusteCredito'); Self.Adiciona('VlrTotAjuCreSubTrbApuIcm', 'ValorTotalAjusteCreditoDocumentoFiscalSubstituicaoTributaria'); Self.Adiciona('VlrTotAjuDebApuIcm', 'ValorTotalAjusteDebito'); Self.Adiciona('VlrTotAjuDebSubTrbApuIcm', 'ValorTotalAjusteDebitoDocumentoFiscalSubstituicaoTributaria'); Self.Adiciona('VlrTotAjuDifAlqAntInt', 'ValorTotalAjustesDiferencialAliquotaAntecipacaoInterestadual'); Self.Adiciona('VlrTotAjuRed', 'ValorTotalAjusteReducao'); Self.Adiciona('VlrTotCreApuAnt', 'ValorTotalCreditoApuradoAnterior'); Self.Adiciona('VlrTotCntRef', 'ValorTotalContaReferencial'); Self.Adiciona('VlrTotConPreRec', 'ValortotalContribuicaoPrevidenciariaARecolher'); Self.Adiciona('VlrTotDec', 'ValorTotalDeclarar'); Self.Adiciona('VlrTotDecIcmDifAlqAntInt', 'ValorTotalDeclararICMSDiferencialAliquotaAntecipacaoInterestadual'); Self.Adiciona('VlrTotCreDifAli', 'ValorTotalCreditosDiferencialAliquota'); Self.Adiciona('VlrTotCreFcp', 'ValorTotalCreditosFundoCombatePobreza'); Self.Adiciona('VlrOutCreDifAli', 'ValorOutrosCreditosDiferencialAliquota'); Self.Adiciona('VlrTotDebDifAli', 'ValorTotalDebitosDiferencialAliquota'); Self.Adiciona('VlrTotDebFcp', 'ValorTotalDebitosFundoCombatePobreza'); Self.Adiciona('VlrTotDedSubTrbApuIcm', 'ValorTotalDeducoesSubstituicaoTributaria'); Self.Adiciona('VlrTotDifAlqAntInt', 'ValorTotalDiferencialAliquotaAntecipacaoInterestadual'); Self.Adiciona('VlrTotEveIteMovMen', 'ValorTotalEventoItemMovimentacaoMensal'); Self.Adiciona('VlrTotForCon', 'ValorTotalFornecidoConsumido'); Self.Adiciona('VlrTotIteMovEcf', 'ValorTotalItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VlrTotLan', 'ValorTotalLancamentos'); Self.Adiciona('VlrTotMovIss', 'ValorTotalMovimentoServico'); Self.Adiciona('VlrTotMovIteEtq', 'ValorTotalItemEstoque'); Self.Adiciona('VlrTotNotFis', 'ValorTotalNotasFiscais'); Self.Adiciona('VlrTotRec', 'ValorTotalRecebido'); Self.Adiciona('VLRTOTRECBRU','ValorTotalReceitaBruta'); Self.Adiciona('VlrTotRenTit', 'ValorTotalRenegociacaoTitulo'); Self.Adiciona('VlrTotRet', 'ValorTotalRetencao'); Self.Adiciona('VlrTotSpg', 'ValorTotalSopag'); Self.Adiciona('VlrTotSubTriCom', 'ValorTotalSubstituicaoTributariaCombustiveis'); Self.Adiciona('VlrTotSubTriInt', 'ValorTotalSubstituicaoTributariaInterestaduais'); Self.Adiciona('VlrTotSubTriNotFis', 'ValorTotalSubstituicaoTributariaNotasFiscais'); Self.Adiciona('VLRTOTTRA', 'ValorTotalTransferido'); Self.Adiciona('VlrTotUndVen', 'ValorTotalUnidadeVendida'); Self.Adiciona('VlrUniMovIss', 'ValorUnitarioMovimentoServico'); Self.Adiciona('VlrUntIteMovEcf', 'ValorUnitarioItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('VisCodCnt', 'VisualizaCodigoConta'); Self.Adiciona('VisEcf', 'VisualizaEcf'); Self.Adiciona('VisPrd', 'VisualizaProduto'); Self.Adiciona('VisSitEsp', 'VisualizaSituacaoEspecial'); Self.Adiciona('Vra', 'Vara'); Self.Adiciona('ZerCreSldCnt', 'ValorCreditoZeramento'); Self.Adiciona('ZerDebSldCnt', 'ValorDebitoZeramento'); Self.Adiciona('ZonExp', 'ZonaExportacao'); end; procedure TCustomDicionario.AdicionaTabelas; begin Self.Adiciona('TBLADIITEATIFIX', 'TAdicaoItemAtivoFixo'); Self.Adiciona('TBLAJUBENINCAPUICMEFD', 'TAjusteBeneficioIncentivoApuracaoICMSEFD'); Self.Adiciona('TBLAJUAPUIPI', 'TAjusteApuracaoIPI'); Self.Adiciona('TBLAJUCONPREAPURECBRUP210', 'TAjusteContribuicaoPrevidenciariaApuradaSobreReceitaBrutaP210'); Self.Adiciona('TBLALIUNIMEDPRO', 'TAliquotaUnidadeMedidaProduto'); Self.Adiciona('TBLAGERIS', 'TAgenteRisco'); Self.Adiciona('TBLAGEQUI', 'TAgenteQuimico'); Self.Adiciona('TBLAMB', 'TAmbientes'); Self.Adiciona('TBLANAMATBIO', 'TAnaliseMaterialBiologico'); Self.Adiciona('TBLANO', 'TAnotacaoCTPS'); Self.Adiciona('TBLATVSGGSUPSPL', 'TAtividadeSegregacaoSimplesNacional'); Self.Adiciona('TBLBENINCATIIMO', 'TBensAtivoImobilizado'); Self.Adiciona('TBLBENINCATIIMOF130', 'TBensAtivoImobilizadoF130'); Self.Adiciona('TBLBLOMESANOEMPAREATU', 'TFechamentoMovimentacaoMensal'); Self.Adiciona('TBLCENCUSSPDFIS', 'TCentroDeCustosItemAtivoFixoSpedFiscal'); Self.Adiciona('TBLCENNEGCTB', 'TCentroNegocio'); Self.Adiciona('TBLCNTMOD', 'TContaModelo'); Self.Adiciona('TBLCNTLLR', 'TContaLalur'); Self.Adiciona('TBLCODAJUAPUICMEFD', 'TCodigoAjusteApuracaoICMSEFD'); Self.Adiciona('TBLCODAJUAPUIPI', 'TCodigoAjusteApuracaoIPIEFD'); Self.Adiciona('TBLCODBASCALCRE', 'TCodigoBaseCalculoCredito'); Self.Adiciona('TBLISTBOLCOB', 'TBoletoCobranca'); Self.Adiciona('TBLCODTIPCRE', 'TCodigoTipoCredito'); Self.Adiciona('TBLTIPDEB', 'TCodigoTipoDebito'); Self.Adiciona('TBLCLASERCSM', 'TClassificacaoServicoConsumo'); Self.Adiciona('TBLCLAFIS', 'TClassificacaoFiscal'); Self.Adiciona('TBLAPUE300E310', 'TSpedfiscalRegistroE300'); Self.Adiciona('TBLAPUE311', 'TSpedfiscalRegistroE311'); Self.Adiciona('TBLAPUE312', 'TSpedfiscalRegistroE312'); Self.Adiciona('TBLAPUE313', 'TSpedfiscalRegistroE313'); Self.Adiciona('TBLAPUE316', 'TSpedfiscalRegistroE316'); Self.Adiciona('TBLAPUICMEFD', 'TApuracaoICMS'); Self.Adiciona('TBLAPUICMSUBTBR', 'TApuracaoICMSSubstituicaoTributaria'); Self.Adiciona('TBLAPUIMP', 'TApuracaoDeImposto'); Self.Adiciona('TBLAPUIPIEFD', 'TApuracaoIPI'); Self.Adiciona('TBLAPUSPLNAC', 'TApuracaoSimplesNacional'); Self.Adiciona('TBLCBTIND', 'TContribuinteIndividual'); Self.Adiciona('TBLCERAPRITEEPI', 'TCertificadoAprovacaoItemEPI'); Self.Adiciona('TBLPARAPUSPLNAC', 'TParametrizacaoApuracaoSimplesNacional'); Self.Adiciona('TBLPARINTEVE', 'TCentralDeEventosMigracao'); Self.Adiciona('TBLCFGCTB', 'TConfiguracaoContabil'); Self.Adiciona('TBLCID', 'TCidade'); Self.Adiciona('TBLCNTTRASLDINI', 'TContaTransferenciaSaldoInicial'); Self.Adiciona('TBLCODFIS', 'TCodigoFiscal'); Self.Adiciona('TBLCODFISEXC', 'TCodigoFiscalExcecao'); Self.Adiciona('TBLCODFISLANPADTRI', 'TCodigoFiscalLancamentoPadraoTributacao'); Self.Adiciona('TBLCODGPS', 'TCodigoGPS'); Self.Adiciona('TBLRECSFP', 'TRecolhimentoSefip'); Self.Adiciona('TBLCOMALI', 'TComplementoAliquota'); Self.Adiciona('TBLPERCOMALI', 'TPercentualComplementoAliquota'); Self.Adiciona('TBLPOSPRD', 'TPosseProduto'); Self.Adiciona('TBLCOMSVCINTPRT', 'TComunicacaoServicoIntegracaoPortal'); Self.Adiciona('TBLCODOCOAJUICMEFD', 'TCodigoOcorrenciaAjusteEFD'); Self.Adiciona('TBLCODOPEDIE', 'TCodigoOperacaoDIE'); Self.Adiciona('TBLCODOPEISIMP', 'TCodigoOperacaoISimp'); Self.Adiciona('TBLCOF', 'TMovimentacaoDebitoCreditoCOFINS'); Self.Adiciona('TBLCONCONPREP200', 'TConsolidacaoContribuicaoPrevidenciariaP200'); Self.Adiciona('TBLCONPRESOBRECBRU', 'TContribuicaoPrevidenciariaSobreReceitaBruta'); Self.Adiciona('TBLCONRETFONPISCOF', 'TContribuicaoRetidaNaFontePisCofins'); Self.Adiciona('TBLCONRETFONPISCOFPAR', 'TParametrosContribuicaoRetidaNaFontePisCofins'); Self.Adiciona('TBLCONVLRIPI', 'TConsolidacaoValorIPI'); Self.Adiciona('TBLCONZEE', 'TContabilizacaoLeituraZ'); Self.Adiciona('TBLCREDECINCFUSCIS', 'TCreditosDecorrentesdeFusao'); Self.Adiciona('TBLCREPIS', 'TMovimentacaoDebitoCreditoPIS'); Self.Adiciona('TBLCRG', 'TCargo'); Self.Adiciona('TBLCRS', 'TCurso'); Self.Adiciona('TBLCTRCREFISICMEFD', 'TControleCreditosFiscaisIcmsEFD'); Self.Adiciona('TBLCTBSPG', 'TContabilizacaoSopag'); Self.Adiciona('TBLESP', 'TEspecie'); Self.Adiciona('TBLESPDOCBOL', 'TEspecieDocumento'); Self.Adiciona('TBLESPRECEST', 'TCodigoRecolhimentoDAR'); Self.Adiciona('TBLCUSINCUNDVEN', 'TF200CustoIncorridoDaUnidadeImobiliaria'); Self.Adiciona('TBLCUSORCUNDIMOVEN', 'TF200CustoOrcadoUnidadeVendida'); Self.Adiciona('TBLDEP', 'TDepartamento'); Self.Adiciona('TBLDEPPAT', 'TDepartamentoPatrimonial'); Self.Adiciona('TBLDESTDA0030', 'TDeSTDARegistro0030'); Self.Adiciona('TBLDESTDAG020', 'TDeSTDARegistroG020'); Self.Adiciona('TBLDESTDAG600', 'TDeSTDARegistroG600'); Self.Adiciona('TBLDESTDAG605', 'TDeSTDARegistroG605'); Self.Adiciona('TBLDESTDAG610', 'TDeSTDARegistroG610'); Self.Adiciona('TBLDESTDAG615', 'TDeSTDARegistroG615'); Self.Adiciona('TBLDESTDAG620', 'TDeSTDARegistroG620'); Self.Adiciona('TBLDESTDAG625', 'TDeSTDARegistroG625'); Self.Adiciona('TBLDOC', 'TDocumento'); Self.Adiciona('TBLDOCFIS', 'TDocumentoFiscal'); Self.Adiciona('TBLD410DOCINF', 'TD410DocumentosInformados'); Self.Adiciona('TBLD411DOCCAN', 'TD411DocumentoCancelado'); Self.Adiciona('TBLD420COMDOCINF', 'TD420ComplementoDocumentoInformado'); Self.Adiciona('TBLDEDDIV', 'TDeducoesDiversas'); Self.Adiciona('TBLDETAPUCONPRE', 'TDetalhamentoApuracaoContribuicaoPrevidenciaria'); Self.Adiciona('TBLDETVLRMANDEMRES', 'TValorDetalhamentoValorManualDemostrativoResultado'); Self.Adiciona('TBLDIEANV', 'TDiefAnexov'); Self.Adiciona('TBLPER', 'TPeriodoContabil'); Self.Adiciona('TBLECT', 'TEscritorioContabil'); Self.Adiciona('TBLEMICUPFIS', 'TEmissorCupomFiscal'); Self.Adiciona('TBLEMP', 'TEmpresa'); Self.Adiciona('TBLEMPCTB', 'TEmpresaContabilidade'); Self.Adiciona('TBLEMPEMI', 'TEmpresaEmitente'); Self.Adiciona('TBLEMPEMICNT', 'TEmpresaEmitentePlanoConta'); Self.Adiciona('TBLEMPDET', 'TEmpresaDetalhe'); Self.Adiciona('TBLEMPDES', 'TEmpresaDestinatario'); Self.Adiciona('TBLEMPDESCNT', 'TEmpresaDestinatarioPlanoConta'); Self.Adiciona('TBLEMPESC', 'TEmpresaEscrita'); Self.Adiciona('TBLEMPESCINT', 'TEmpresaEscritaIntegracao'); Self.Adiciona('TBLEMPFOL', 'TEmpresaFolha'); Self.Adiciona('TBLEMPGERCTB', 'TEmpresaGerenciadorContabil'); Self.Adiciona('TBLEMPGERCTBCNT', 'TEmpresaGerenciadorContabilConta'); Self.Adiciona('TBLEMPGERCTBPARHON', 'TEmpresaGerenciadorContabilParametroHonorario'); Self.Adiciona('TBLEMPORGREG', 'TEmpresaOrgaoRegistro'); Self.Adiciona('TBLEMPREF', 'TEmpresaReferencia'); Self.Adiciona('TBLEMPTRI', 'TTributoEmpresa'); Self.Adiciona('TBLETQ', 'TEstoque'); Self.Adiciona('TBLETQDIA', 'TEstoqueDia'); Self.Adiciona('TBLETQIMPEST', 'TEstoqueImpostoEstadual'); Self.Adiciona('TBLETTDMT', 'TEstruturaDemonstracao'); Self.Adiciona('TBLETTDMTMOD', 'TEstruturaDemonstracaoModelo'); Self.Adiciona('TBLFATANTAPUSPLNAC', 'TFaturamentoAnteriorApuracaoSimplesNacional'); Self.Adiciona('TBLFOR', 'TFornecedor'); Self.Adiciona('TBLFORTRI', 'TFormulaTributacao'); Self.Adiciona('TBLFPA', 'TFPAS'); Self.Adiciona('TBLGROPRD', 'TGeneroProduto'); Self.Adiciona('TBLGRPACE', 'TGrupoAcesso'); Self.Adiciona('TBLGRPETT', 'TGrupoEstruturaDemonstracao'); Self.Adiciona('TBLGRPHIS', 'TGrupoHistorico'); Self.Adiciona('TBLGRPOGC', 'TGrupoObrigacao'); Self.Adiciona('TBLHISCTB', 'THistorico'); Self.Adiciona('TBLHISLLR', 'THistoricoLALUR'); Self.Adiciona('TBLINDMOE', 'TMoedaIndexador'); Self.Adiciona('TBLINFADIAJUAPUICM', 'TInformacaoAdicionalAjusteApuracaoICMS'); Self.Adiciona('TBLINFADIAPUSPLNAC', 'TInformacaoAdicionalApuracaoSimplesNacional'); Self.Adiciona('TBLINFADIAPU', 'TCodigoInformacaoAdicionalApuracaoEFD'); Self.Adiciona('TBLINFADIAPUVLRDEC', 'TInformacaoAdicionalApuracaoValorDeclaratorioEFD'); Self.Adiciona('TBLINFCOMOBS', 'TInformacaoComplementarObservacao'); Self.Adiciona('TBLINSSUB', 'TInscricaoSubstituto'); Self.Adiciona('TBLIMPEST', 'TImpostoEstadual'); Self.Adiciona('TBLIMPREC', 'TImpostoARecolher'); Self.Adiciona('TBLINT', 'TIntervaloHorarioTrabalho'); Self.Adiciona('TBLITEATIFIX', 'TItemAtivoFixo'); Self.Adiciona('TBLITEBASETT', 'TItemBaseEstruturaDemonstracao'); Self.Adiciona('TBLITECTBSPG', 'TItemContabilizacaoSopag'); Self.Adiciona('TBLITEEPI', 'TItemEPI'); Self.Adiciona('TBLITEMOVCTB', 'TItemMovimentacaoContabil'); Self.Adiciona('TBLITEMOVECF', 'TItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('TBLITEMOVMEN', 'TItemMovimentacaoMensal'); Self.Adiciona('TBLITEPRGFRS', 'TItemProgramacaoFerias'); Self.Adiciona('TBLITEPATLIQ', 'TItemPatrimonioLiquido'); Self.Adiciona('TBLITESPG', 'TItemSopag'); Self.Adiciona('TBLLAN', 'TLancamento'); Self.Adiciona('TBLLANCENNEG', 'TLancamentoCentroNegocios'); Self.Adiciona('TBLLANLCX', 'TLancamentoLivroCaixa'); Self.Adiciona('TBLLANMONBIO', 'TLancamentoMonitoracaoBiologica'); Self.Adiciona('TBLLANPADCTB', 'TLancamentoPadrao'); Self.Adiciona('TBLLANPADCTBFIX', 'TLancamentoPadraoFixo'); Self.Adiciona('TBLLANPADTRI', 'TLancamentoPadraoTributacao'); Self.Adiciona('TBLLAYPTO', 'TLayoutPonto'); Self.Adiciona('TBLLIMENQEMP', 'TEnquadramentoFiscal'); Self.Adiciona('TBLLIMENQEMPRECTRIFED', 'TCodigoReceitaEmpresa'); Self.Adiciona('TBLLIMENQ', 'TLimiteEnquadramento'); Self.Adiciona('TBLLOCBEM', 'TLocalizacaoItem'); Self.Adiciona('TBLLOT', 'TLote'); Self.Adiciona('TBLMAC', 'TMacro'); Self.Adiciona('TBLMAREMICUPFIS', 'TMarcaEmissorCupomFiscal'); Self.Adiciona('TBLMARSEC', 'TMarcaSecao'); Self.Adiciona('TBLMEDRSP', 'TMedicoResponsavel'); Self.Adiciona('TBLMERSUJREAICMPERFIXSAI', 'TMercadoriasSujeitasReaIcmsPercentualFixoSobreSaidas'); Self.Adiciona('TBLMODCNT', 'TModeloConta'); Self.Adiciona('TBLMODDOCFIS', 'TModeloDocumentoFiscal'); Self.Adiciona('TBLMOTABN', 'TMotivoAbono'); Self.Adiciona('TBLMOTCARCOR', 'TEspecificacaoCartaCorrecao'); Self.Adiciona('TBLMOV', 'TMovimentacaoDocumentoFiscal'); Self.Adiciona('TBLMOVCODFIS', 'TMovimentacaoCodigoFiscal'); Self.Adiciona('TBLMOVCTB', 'TMovimentacaoContabil'); Self.Adiciona('TBLMOVECF', 'TMovimentacaoEmissorCupomFiscal'); Self.Adiciona('TBLMOVECFREF', 'TMovimentacaoEmissorCupomFiscalReferenciado'); Self.Adiciona('TBLMOVE311', 'TMovimentacaoSpedfiscalRegistroE311'); Self.Adiciona('TBLMOVE312', 'TMovimentacaoSpedfiscalRegistroE312'); Self.Adiciona('TBLMOVE313', 'TMovimentacaoSpedfiscalRegistroE313'); Self.Adiciona('TBLMOVISIMP', 'TRegistroDaMovimentacaoISimp'); Self.Adiciona('TBLMOVLCX', 'TMovimentacaoLivroCaixa'); Self.Adiciona('TBLMOVMEN', 'TMovimentacaoMensal'); Self.Adiciona('TBLITEMOVECF', 'TItemMovimentacaoEmissorCupomFiscal'); Self.Adiciona('TBLMOTFLG', 'TMotivoFolga'); Self.Adiciona('TBLMOTNAORGTPTO', 'TMotivoNaoRegistraPonto'); Self.Adiciona('TBLMOVICM', 'TMovimentacaoICMS'); Self.Adiciona('TBLMOVINFCOMECFREF', 'TCupomFiscalReferenciado'); Self.Adiciona('TBLMOVINFCOMGNRREF', 'TDocumentoArrecadacaoReferenciado'); Self.Adiciona('TBLMOVINFCOMNOTREF', 'TNotaFiscalReferenciada'); Self.Adiciona('TBLMOVINV', 'TMovimentacaoInventario'); Self.Adiciona('TBLMOVIPI', 'TMovimentacaoIPI'); Self.Adiciona('TBLMOVISS','TMovimentacaoISSQN'); Self.Adiciona('TBLMOVITEETQ', 'TMovimentacaoProduto'); Self.Adiciona('TBLMOVITEETQMOVAMZCMB', 'TMovimentacaoArmazenamentoCombustivel'); Self.Adiciona('TBLMOVPGRREC', 'TMovimentacaoPagarReceber'); Self.Adiciona('TBLMOVPGRRECLAN', 'TMovimentacaoPagarReceberLancamento'); Self.Adiciona('TBLMOVSPLNAC', 'TMovimentacaoSimplesNacional'); Self.Adiciona('TBLMOVSPLNACTRI', 'TMovimentacaoSimplesNacionalTributo'); Self.Adiciona('TBLMQNCTA', 'TColetor'); Self.Adiciona('TBLMSCCNT', 'TMascaraConta'); Self.Adiciona('TBLMSG', 'TMensagem'); Self.Adiciona('TBLNATRECSPD', 'TNaturezaReceita'); Self.Adiciona('TBLNIVCTB', 'TNivelCentroNegocio'); Self.Adiciona('TBLNORREF', 'TNormasReferenciadas'); Self.Adiciona('TBLOBRICMRECOPEPROEFD', 'TObrigacaoIcmsRecolherOperacaoPropriaEFD'); Self.Adiciona('TBLOBSESC', 'TObservacaoEscritaFiscal'); Self.Adiciona('TBLOCOAGENOC', 'TOcorrenciaAgenteNocivo'); Self.Adiciona('TBLOGC', 'TObrigacao'); Self.Adiciona('TBLOPCSPL', 'TOpcaoSimples'); Self.Adiciona('TBLOPECRTDES', 'TOperacoesCartaoCreditoDebito'); Self.Adiciona('TBLOPEPLASAU', 'TOperadorPlanoSaudeDIRF'); Self.Adiciona('TBLOPEVLRAGR', 'TOperacoesValoresAgregados'); Self.Adiciona('TBLORGREG', 'TOrgaoRegistro'); Self.Adiciona('TBLORIMER', 'TOrigemMercadoria'); Self.Adiciona('TBLORITRI', 'TOrigemTributacao'); Self.Adiciona('TBLOUTOBRCONFREEFD', 'TOutrasObrigacoesConhecimentoFreteSPEDFiscal'); Self.Adiciona('TBLOUTOBRDOCFISEFD', 'TOutrasObrigacoesTributariasAjustesInformacoesDocumentoFiscal'); Self.Adiciona('TBLOUTOPEPISCOF', 'TOutrasOperacoesSpedPisCofins'); Self.Adiciona('TBLOUTVLRFIS', 'TOutrosValoresFiscais'); Self.Adiciona('TBLCODOUTVLRFIS', 'TCodigoOutrosValoresFiscais'); Self.Adiciona('TBLPAI', 'TPais'); Self.Adiciona('TBLPARCNT', 'TParametroConta'); Self.Adiciona('TBLPARCNTSPD', 'TParametroContaSped'); Self.Adiciona('TBLPARIMPREGF200', 'TF200ParametrizacaoImportacao'); Self.Adiciona('TBLPARGUIEST', 'TParametroDar'); Self.Adiciona('TBLPARPRD', 'TParametrizacaoProduto'); Self.Adiciona('TBLPARCODOPE', 'TParametrizacaoCFOPCodigoOperacao'); Self.Adiciona('TBLPARCREOUTPRD', 'TParametrizacaoCreditoOutorgadoProduto'); Self.Adiciona('TBLPARSITTRBIMP', 'TParametroSituacaoTributariaImposto'); Self.Adiciona('TBLPARSPDECF0010', 'TParametroSPEDECF0010'); Self.Adiciona('TBLPARSPDECF0020', 'TParametroSPEDECF0020'); Self.Adiciona('TBLPARSPDECF0035', 'TParametroSPEDECF0035'); Self.Adiciona('TBLPES', 'TPessoa'); Self.Adiciona('TBLPRDCOM', 'TProdutoComercial'); Self.Adiciona('TBLPRDCOMRAMATV', 'TProdutoComercialRamoAtividade'); Self.Adiciona('TBLPRDPAD', 'TProdutoPadrao'); Self.Adiciona('TBLPREPON', 'TPreferenciaEmpregado'); Self.Adiciona('TBLPLACNT', 'TConta'); Self.Adiciona('TBLPLACNTREF', 'TContaReferencial'); Self.Adiciona('TBLPRE', 'TPreferencia'); Self.Adiciona('TBLPREBALPAT', 'TPreferenciaBalancoPatrimonial'); Self.Adiciona('TBLPRECONPAT', 'TPreferenciaControlePatrimonial'); Self.Adiciona('TBLPRGFRS', 'TProgramacaoFerias'); Self.Adiciona('TBLPROREF', 'TProcessoReferenciado'); Self.Adiciona('TBLPROREFF130', 'TProcessoReferenciadoF130'); Self.Adiciona('TBLPROREFP199', 'TProcessoReferenciadoP199'); Self.Adiciona('TBLPROREFADM', 'TProcessoReferenciadoAdministrativo'); Self.Adiciona('TBLPROREFJUD', 'TProcessoReferenciadoJudicial'); Self.Adiciona('TBLPRTCNTGERCTB', 'TPortadorContaGerenciadorContabil'); Self.Adiciona('TBLTEC', 'TTecnicaAvaliacao'); Self.Adiciona('TBLTIPBEM', 'TTipoBem'); Self.Adiciona('TBLTIPDOCAQU', 'TTipoDocumentoAquisicao'); Self.Adiciona('TBLTIPEXA', 'TTipoExameMedico'); Self.Adiciona('TBLTIPOCOGERCTB', 'TTipoOcorrencia'); Self.Adiciona('TBLTIPUTICREFISICM', 'TCodigoTipoUtilizacaoCreditoEFD'); Self.Adiciona('TBLUTICREFISICMEFD', 'TUtilizacaoCreditosFiscaisIcmsEFD'); Self.Adiciona('TBLPARPRDCODFIS','TParametrizacaoProdutoCodigoFiscal'); Self.Adiciona('TBLPLACNTSPDFIS','TPlanoContasItemAtivoFixoSpedFiscal'); Self.Adiciona('TBLPRECONPATGER', 'TPreferenciaControlePatrimonialGeral'); Self.Adiciona('TBLPRECTB', 'TPreferenciaContabil'); Self.Adiciona('TBLPREESC', 'TPreferenciaEscrita'); Self.Adiciona('TBLPREFOL', 'TPreferenciaFolha'); Self.Adiciona('TBLPREFOLCNT', 'TPreferenciaFolhaConta'); Self.Adiciona('TBLPREGER', 'TPreferenciaGeral'); Self.Adiciona('TBLPREGERCTBINTCTB', 'TPreferenciaGerenciadorIntegracaoContabilidade'); Self.Adiciona('TBLPREGERCTBINTLCX', 'TPreferenciaGerenciadorIntegracaoLivroCaixa'); Self.Adiciona('TBLPREGERCTBINTESC', 'TPreferenciaGerenciadorIntegracaoEscrita'); Self.Adiciona('TBLPRELCX', 'TPreferenciaLivroCaixa'); Self.Adiciona('TBLPRELCXGER', 'TPreferenciaLivroCaixaGeral'); Self.Adiciona('TBLQUAPESJUR', 'TCodigoQualificacaoPessoaJuridica'); Self.Adiciona('TBLRAMATI', 'TRamoAtividade'); Self.Adiciona('TBLRATPLALCX', 'TPlanoRateioLcx'); Self.Adiciona('TBLREGINFEXPEFD', 'TRegistroInformacoesExportacaoEFD'); Self.Adiciona('TBLREQOCUPRO', 'TRequisito'); Self.Adiciona('TBLREGAPUCONPRE', 'TRegimeApuracaoContribuicaoPrevidenciaria'); Self.Adiciona('TBLRGMPRV', 'TRegimePrevidenciario'); Self.Adiciona('TBLRSPBEM', 'TResponsavelItemBem'); Self.Adiciona('TBLRSPTCM', 'TResponsavelTCM'); Self.Adiciona('TBLSALMIN', 'TSalarioMinimo'); Self.Adiciona('TBLSALPAT', 'TSalaPatrimonial'); Self.Adiciona('TBLSIR', 'TSirene'); Self.Adiciona('TBLSCORSP', 'TSocioResponsavel'); Self.Adiciona('TBLSCORSPEMP', 'TSocioResponsavelEmpresa'); Self.Adiciona('TBLSGGAPUSPLNAC', 'TSegregacaoApuracaoSimplesNacional'); Self.Adiciona('TBLSGGPRESERSUPSPL', 'TSegregacaoPrestacaoServicoSuperSimples'); Self.Adiciona('TBLSERLEI116', 'TServicoLei116'); Self.Adiciona('TBLSEC', 'TSecao'); Self.Adiciona('TBLSERPRE', 'TServicoPrestado'); Self.Adiciona('TBLSERPREFOL', 'TServicoPrestadoFolha'); Self.Adiciona('TBLSERVAL', 'TSerieDocumentoFiscal'); Self.Adiciona('TBLSERVALLANPADTRI', 'TSerieValidaLancamentoPadraoTributacao'); Self.Adiciona('TBLSERVALTRI', 'TTributacaoSerieDocumentoFiscal'); Self.Adiciona('TBLSITBEM', 'TSituacaoItemBem'); Self.Adiciona('TBLSITEPG', 'TSituacaoEmpregado'); Self.Adiciona('TBLSITESP', 'TSituacaoEspecial'); Self.Adiciona('TBLSITTRBIMP', 'TSituacaoTributariaImposto'); Self.Adiciona('TBLSLDCNTCTB', 'TSaldoConta'); Self.Adiciona('TBLSPDECFE010', 'TSpedEcfRegistroE010'); Self.Adiciona('TBLSPDECFE020', 'TSpedEcfRegistroE020'); Self.Adiciona('TBLSPDECFE030', 'TSpedEcfRegistroE030'); Self.Adiciona('TBLSPDECFK030', 'TSpedEcfRegistroK030'); Self.Adiciona('TBLSPDECFU030', 'TSpedEcfRegistroU030'); Self.Adiciona('TBLSPDECFU150', 'TSpedEcfRegistroU150'); Self.Adiciona('TBLSPDECFU180', 'TSpedEcfRegistroU180'); Self.Adiciona('TBLSPDECFU182', 'TSpedEcfRegistroU182'); Self.Adiciona('TBLSPDECFE155', 'TSpedEcfRegistroE155'); Self.Adiciona('TBLSPDECFE355', 'TSpedEcfRegistroE355'); Self.Adiciona('TBLSPDECFJ050', 'TSpedEcfRegistroJ050'); Self.Adiciona('TBLSPDECFJ051', 'TSpedEcfRegistroJ051'); Self.Adiciona('TBLSPDECFJ100', 'TSpedEcfRegistroJ100'); Self.Adiciona('TBLSPDECFK155', 'TSpedEcfRegistroK155'); Self.Adiciona('TBLSPDECFK156', 'TSpedEcfRegistroK156'); Self.Adiciona('TBLSPDECFK355', 'TSpedEcfRegistroK355'); Self.Adiciona('TBLSPDECFK356', 'TSpedEcfRegistroK356'); Self.Adiciona('TBLSPDECFL030', 'TSpedEcfRegistroL030'); Self.Adiciona('TBLSPDECFL100', 'TSpedECFRegistroL100'); Self.Adiciona('TBLSPDECFL200', 'TSpedEcfRegistroL200'); Self.Adiciona('TBLSPDECFL210', 'TSpedEcfRegistroL210'); Self.Adiciona('TBLSPDECFL300', 'TSpedEcfRegistroL300'); Self.Adiciona('TBLSPDECFCODRECRETFON', 'TSpedEcfRecolhimentoRetidoFonte'); Self.Adiciona('TBLSPDECFP030', 'TSpedEcfRegistroP030'); Self.Adiciona('TBLSPDECFP100', 'TSpedEcfRegistroP100'); Self.Adiciona('TBLSPDECFP200', 'TSpedEcfRegistroP200'); Self.Adiciona('TBLSPDECFP300', 'TSpedEcfRegistroP300'); Self.Adiciona('TBLSPDECFP400', 'TSpedEcfRegistroP400'); Self.Adiciona('TBLSPDECFP500', 'TSpedEcfRegistroP500'); Self.Adiciona('TBLSPDECFM010', 'TSpedEcfRegistroM010'); Self.Adiciona('TBLSPDECFM030', 'TSpedEcfRegistroM030'); Self.Adiciona('TBLSPDECFM300', 'TSpedEcfRegistroM300'); Self.Adiciona('TBLSPDECFM305', 'TSpedEcfRegistroM305'); Self.Adiciona('TBLSPDECFM350', 'TSpedEcfRegistroM350'); Self.Adiciona('TBLSPDECFM300CNTPAR', 'TDinamicaLalur300'); Self.Adiciona('TBLSPDECFM350CNTPAR', 'TDinamicaLalur350'); Self.Adiciona('TBLSPDECFM355', 'TSpedEcfRegistroM355'); Self.Adiciona('TBLSPDECFM410', 'TSpedEcfRegistroM410'); Self.Adiciona('TBLSPDECFM500', 'TSpedEcfRegistroM500'); Self.Adiciona('TBLSPDECFN030', 'TSpedEcfRegistroN030'); Self.Adiciona('TBLSPDECFN500', 'TSpedEcfRegistroN500'); Self.Adiciona('TBLSPDECFN600', 'TSpedEcfRegistroN600'); Self.Adiciona('TBLSPDECFN610', 'TSpedEcfRegistroN610'); Self.Adiciona('TBLSPDECFN620', 'TSpedEcfRegistroN620'); Self.Adiciona('TBLSPDECFN630', 'TSpedEcfRegistroN630'); Self.Adiciona('TBLSPDECFN650', 'TSpedEcfRegistroN650'); Self.Adiciona('TBLSPDECFN660', 'TSpedEcfRegistroN660'); Self.Adiciona('TBLSPDECFN670', 'TSpedEcfRegistroN670'); Self.Adiciona('TBLSPDECFP150', 'TSpedEcfRegistroP150'); Self.Adiciona('TBLSPDECFQ100', 'TSpedEcfRegistroQ100'); Self.Adiciona('TBLSPDECFT030', 'TSpedEcfRegistroT030'); Self.Adiciona('TBLSPDECFT120', 'TSpedEcfRegistroT120'); Self.Adiciona('TBLSPDECFT150', 'TSpedEcfRegistroT150'); Self.Adiciona('TBLSPDECFT170', 'TSpedEcfRegistroT170'); Self.Adiciona('TBLSPDECFT181', 'TSpedEcfRegistroT181'); Self.Adiciona('TBLSPDECFU100', 'TSpedEcfRegistroU100'); Self.Adiciona('TBLSPDECFY540', 'TSpedEcfRegistroY540'); Self.Adiciona('TBLSPDECFTABDIM010', 'TSPEDECFTabelaDinamicaM010'); Self.Adiciona('TBLSPDECFTABDIM100', 'TSPEDECFTabelaDinamicaM100'); Self.Adiciona('TBLSPDECFTABDIM300', 'TSPEDECFTabelaDinamicaM300'); Self.Adiciona('TBLSPDECFTABDIM350', 'TSpedEcfTabelaDinamicaM350'); Self.Adiciona('TBLSPDECFTABDINL210', 'TSpedEcfTabelaDinamicaL210'); Self.Adiciona('TBLSPDECFTABDIN500', 'TSPEDECFTabelaDinamicaN500'); Self.Adiciona('TBLSPDECFTABDIN600', 'TSpedEcfTabelaDinamicaN600'); Self.Adiciona('TBLSPDECFTABDIN610', 'TSpedEcfTabelaDinamicaN610'); Self.Adiciona('TBLSPDECFTABDIN620', 'TSpedEcfTabelaDinamicaN620'); Self.Adiciona('TBLSPDECFTABDIN630', 'TSPEDECFTabelaDinamicaN630'); Self.Adiciona('TBLSPDECFTABDIN650', 'TSPEDECFTabelaDinamicaN650'); Self.Adiciona('TBLSPDECFTABDIN660', 'TSPEDECFTabelaDinamicaN660'); Self.Adiciona('TBLSPDECFTABDIN670', 'TSPEDECFTabelaDinamicaN670'); Self.Adiciona('TBLSPDECFTABDIP200', 'TSpedEcfTabelaDinamicaP200'); Self.Adiciona('TBLSPDECFTABDIP300', 'TSpedEcfTabelaDinamicaP300'); Self.Adiciona('TBLSPDECFTABDIP400', 'TSpedEcfTabelaDinamicaP400'); Self.Adiciona('TBLSPDECFTABDIP500', 'TSpedEcfTabelaDinamicaP500'); Self.Adiciona('TBLSPDECFTABDIT120', 'TSpedEcfTabelaDinamicaT120'); Self.Adiciona('TBLSPDECFTABDIT150', 'TSpedEcfTabelaDinamicaT150'); Self.Adiciona('TBLSPDECFTABDIT170', 'TSpedEcfTabelaDinamicaT170'); Self.Adiciona('TBLSPDECFTABDIT181', 'TSpedEcfTabelaDinamicaT181'); Self.Adiciona('TBLSPDECFTABDIU180', 'TSpedEcfTabelaDinamicaU180'); Self.Adiciona('TBLSPDECFTABDIU182', 'TSpedEcfTabelaDinamicaU182'); Self.Adiciona('TBLSPDPISCOF511', 'TSpedFiscalPisCofins511'); Self.Adiciona('TBLSPDECFPAI', 'TSpedEcfPais'); Self.Adiciona('TBLSPDECFY570', 'TSPEDECFRegistroY570'); Self.Adiciona('TBLSPDECFY600', 'TSPEDECFRegistroY600'); Self.Adiciona('TBLSPDECFY611', 'TSPEDECFRegistroY611'); Self.Adiciona('TBLSPDECFY580', 'TSpedEcfRegistroY580'); Self.Adiciona('TBLSPDECFY665', 'TSpedEcfRegistroY665'); Self.Adiciona('TBLSPDECFY671', 'TSpedEcfRegistroY671'); Self.Adiciona('TBLSPDECFY672', 'TSPEDECFRegistroY672'); Self.Adiciona('TBLSPDPISCOF1100', 'TSpedPisCofinsRegistro1100'); Self.Adiciona('TBLSPDPISCOF1101', 'TSpedPisCofinsRegistro1101'); Self.Adiciona('TBLSPDPISCOF1102', 'TSpedPisCofinsRegistro1102'); Self.Adiciona('TBLSPDPISCOF1500', 'TSpedPisCofinsRegistro1500'); Self.Adiciona('TBLSPDPISCOF1501', 'TSpedPisCofinsRegistro1501'); Self.Adiciona('TBLSPDPISCOF1502', 'TSpedPisCofinsRegistro1502'); Self.Adiciona('TBLSPDFIS205', 'TInformacoesRegistro0205SPEDFiscal'); Self.Adiciona('TBLSPDFIS210', 'TSPEDFiscalRegistro0210'); Self.Adiciona('TBLMOVC101', 'TSpedfiscalRegistroC101'); Self.Adiciona('TBLMOVD101', 'TSpedfiscalRegistroD101'); Self.Adiciona('TBLSPDFISK200', 'TSPEDFiscalRegistroK200'); Self.Adiciona('TBLSPDFISK220', 'TSPEDFiscalRegistroK220'); Self.Adiciona('TBLSPDFISK230', 'TSPEDFiscalRegistroK230'); Self.Adiciona('TBLSPDFISK235', 'TSPEDFiscalRegistroK235'); Self.Adiciona('TBLSPDFISK250', 'TSPEDFiscalRegistroK250'); Self.Adiciona('TBLSPDFISK255', 'TSPEDFiscalRegistroK255'); Self.Adiciona('TBLSPG', 'TSopag'); Self.Adiciona('TBLSUBGRPETT', 'TSubGrupoEstruturaDemonstracao'); Self.Adiciona('TBLTRB', 'TTributacao'); Self.Adiciona('TBLTRI', 'TTributo'); Self.Adiciona('TBLTRIAPUIMP', 'TTributoApuracaoImposto'); Self.Adiciona('TBLTRIFED', 'TTributoFederal'); Self.Adiciona('TBLTRIFED', 'TCodigoReceitaFederal'); Self.Adiciona('TBLTRIZEE', 'TTributacaoLeituraZ'); Self.Adiciona('TBLUNDFED', 'TUnidadeFederacao'); Self.Adiciona('TBLUNDIMOVEN', 'TF200UnidadeImobiliariaVendida'); Self.Adiciona('TBLUNDORC', 'TUnidadeOrcamentaria'); Self.Adiciona('TBLUNDGES', 'TUnidadeGestora'); Self.Adiciona('TBLUNDORCRSP', 'TUnidadeOrcamentariaResponsavel'); Self.Adiciona('TBLVLRINI', 'TImplantacaoFiscal'); Self.Adiciona('TBLVLRMANDEMRES', 'TValorManual'); Self.Adiciona('TBLUNIMED', 'TUnidadeMedida'); Self.Adiciona('TBLCNTLCX', 'TContaLcx'); Self.Adiciona('TBLCNTLCXPAD', 'TContasPadraoLivroCaixa'); Self.Adiciona('TBLGRPCNTLCX', 'TGrupoContaLcx'); Self.Adiciona('TBLFAZOBR', 'TCentroDeCustoLivroCaixa'); Self.Adiciona('TBLRATPLALCX', 'TPlanoRateioLcx'); Self.Adiciona('TBLRATLCX', 'TRateioLcx'); Self.Adiciona('TBLGRPPRDANP', 'TGrupoCombustivelANP'); Self.Adiciona('TBLPRDANP','TCodigoCombustivelANP'); Self.Adiciona('TBLBCO', 'TBanco'); Self.Adiciona('TBLBOMCMB','TBomba'); Self.Adiciona('TBLLACBOMCMB','TLacreBomba'); Self.Adiciona('TBLBICBOMCMB','TBicoBomba'); Self.Adiciona('TBLMOVCMB','TMovimentacaoDiariaCombustivel'); Self.Adiciona('TBLMOVTANCMB','TMovimentacaoDiariaTanqueCombustivel'); Self.Adiciona('TBLVOLVENCMB','TVolumedeVendas'); Self.Adiciona('TBLPARCSTNFE', 'TParametrizacaoSituacaoTributariaNFE'); Self.Adiciona('TBLPAUPRDCOMRAMATV', 'TPautaProduto'); Self.Adiciona('TBLOPEIMPMOV', 'TOperacaoImportacao'); Self.Adiciona('TBLMOVINFCOM', 'TInformacaoComplementarNotaFiscal'); Self.Adiciona('TBLGNR', 'TGNRE'); Self.Adiciona('TBLRECBRUMENPISCOF', 'TReceitaBrutaMensalRateioCreditosPisCofins'); Self.Adiciona('TBLRENTIT', 'TRenegociacaoTitulo'); Self.Adiciona('TBLRETIMPFED', 'TRetencaoImpostoFederal'); Self.Adiciona('TBLPROEMP', 'TProcessoEmpresa'); Self.Adiciona('TBLSERVAL', 'TSerieValida'); Self.Adiciona('TBLSPDPISCOFBLI100', 'TSpedPisCofinsBlocoI100'); Self.Adiciona('TBLSPDPISCOFBLI199', 'TSpedPisCofinsBlocoI199'); Self.Adiciona('TBLSPDPISCOFBLI200', 'TSpedPisCofinsBlocoI200'); Self.Adiciona('TBLSPDPISCOFBLI299', 'TSpedPisCofinsBlocoI299'); Self.Adiciona('TBLEVEPRO', 'TEventoProcesso'); Self.Adiciona('TBLSPDPISCOFBLI300', 'TSpedPisCofinsBlocoI300'); Self.Adiciona('TBLSPDPISCOFBLI399', 'TSpedPisCofinsBlocoI399'); Self.Adiciona('TBLSPDPISCOFBLICOM', 'TSpedPisCofinsBlocoIComplemento'); Self.Adiciona('TBLSPDPISCOFBLIDET', 'TSpedPisCofinsBlocoIDetalhamento'); Self.Adiciona('TBLASO', 'TAtestadoSaudeOcupacional'); Self.Adiciona('TBLLOTEMP', 'TLotacao'); Self.Adiciona('TBLEVEINCTRI', 'TIncidenciaTributariaEvento'); Self.Adiciona('TBLINCTRI', 'TIncidenciaTributaria'); Self.Adiciona('TBLEXAAMB', 'TAvaliacaoDeAmbiente'); Self.Adiciona('TBLEXAMEDCLI', 'TExameComplementar'); Self.Adiciona('TBLEXACLIAUD', 'TExameAudiometrico'); Self.Adiciona('TBLEXPAPUICM', 'TExpressoesApuracaoICMSSPEDFiscalDF'); Self.Adiciona('TBLLOGESO', 'TLogeSocial'); Self.Adiciona('TBLSCDCNTPAR', 'TSociedadeContaParticipacao'); Self.Adiciona('TBLSCPOST', 'TSociedadeContaParticipacaoOstensiva'); end; { TCustomDicionario } procedure TCustomDicionario.Adiciona(const Valor, Significado: string); begin // Adicionando normal Self.Valores.Add(Format('%s=%s', [Valor, Significado])); // Adicionando o inverso para conseguir via dupla de consulta Self.Significados.Add(Format('%s=%s', [Significado, Valor])); end; constructor TCustomDicionario.Create(AOwner: TComponent); begin inherited; FValores := TStringList.Create; FValores.Sorted := False; FSignificados := TStringList.Create; FSignificados.Sorted := False; Self.Inicializa; end; destructor TCustomDicionario.Destroy; begin FValores.Free; inherited; end; procedure TCustomDicionario.Inicializa; begin end; function TCustomDicionario.Significado(const Valor: string): string; begin Result := Self.Valores.Values[Valor]; if TStringFunctions.IsEmpty(Result) then Result := Valor; end; function TCustomDicionario.Valor(const Significado: string): string; begin Result := Self.Significados.Values[Significado]; if TStringFunctions.IsEmpty(Result) then Result := Significado; end; initialization Dicionario := TDicionario.Create(nil); finalization Dicionario.Free; end.
unit controller.auth.dto; {$mode delphi} interface uses Classes, SysUtils; type { TAuthResponse } (* data transfer object sent back from the authentication endpoint *) TAuthResponse = record public const PROP_TOKEN = 'token'; PROP_EXPIRES = 'expires'; strict private FExp: String; FToken: String; public //guid identifier property Token : String read FToken write FToken; //expiration time in ISO8601 (utc) property Expires : String read FExp write FExp; function ToJSON : String; procedure FromJSON(Const AJSON : String); end; { TAuthRequest } (* data transfer object to request authentication *) TAuthRequest = record public const PROP_USER = 'userKey'; PROP_PARCEL = 'parcelIdentity'; strict private FKey, FParcel : String; public property UserKey : String read FKey write FKey; property ParcelID : String read FParcel write FParcel; function ToJSON : String; procedure FromJSON(Const AJSON : String); end; { TLookupRequest } (* data transfer object to request details for lookup using a token *) TLookupRequest = record public const PROP_TOKEN = 'token'; strict private FToken : String; public property Token : String read FToken write FToken; function ToJSON : String; procedure FromJSON(Const AJSON : String); end; //for now validate request only requires a token TValidateRequest = TLookupRequest; implementation uses fpjson, jsonparser; { TLookupRequest } function TLookupRequest.ToJSON: String; var LObj: TJSONObject; begin LObj := TJSONObject.Create; try LObj.Add(PROP_TOKEN, TJSONString.Create(FToken)); Result := LObj.AsJSON; finally LObj.Free; end; end; procedure TLookupRequest.FromJSON(const AJSON: String); var LObj: TJSONData; begin LObj := GetJSON(AJSON); if not Assigned(LObj) then raise Exception.Create('TLookupRequest::FromJSON::invalid json [' + AJSON + ']'); if not (LObj.JSONType = jtObject) then begin LObj.Free; raise Exception.Create('TLookupRequest::FromJSON::json is not valid object [' + AJSON + ']'); end; try FToken := TJSONObject(LObj).Get(PROP_TOKEN); finally LObj.Free; end; end; { TAuthRequest } function TAuthRequest.ToJSON: String; var LObj: TJSONObject; begin LObj := TJSONObject.Create; try LObj.Add(PROP_USER, TJSONString.Create(FKey)); LObj.Add(PROP_PARCEL, TJSONString.Create(FParcel)); Result := LObj.AsJSON; finally LObj.Free; end; end; procedure TAuthRequest.FromJSON(const AJSON: String); var LObj: TJSONData; begin LObj := GetJSON(AJSON); if not Assigned(LObj) then raise Exception.Create('TAuthRequest::FromJSON::invalid json [' + AJSON + ']'); if not (LObj.JSONType = jtObject) then begin LObj.Free; raise Exception.Create('TAuthRequest::FromJSON::json is not valid object [' + AJSON + ']'); end; try FKey := TJSONObject(LObj).Get(PROP_USER); FParcel := TJSONObject(LObj).Get(PROP_PARCEL); finally LObj.Free; end; end; { TAuthResponse } function TAuthResponse.ToJSON: String; var LObj: TJSONObject; begin LObj := TJSONObject.Create; try LObj.Add(PROP_TOKEN, TJSONString.Create(FToken)); LObj.Add(PROP_EXPIRES, TJSONString.Create(FExp)); Result := LObj.AsJSON; finally LObj.Free; end; end; procedure TAuthResponse.FromJSON(const AJSON: String); var LObj: TJSONData; begin LObj := GetJSON(AJSON); if not Assigned(LObj) then raise Exception.Create('TToken::FromJSON::invalid json [' + AJSON + ']'); if not (LObj.JSONType = jtObject) then begin LObj.Free; raise Exception.Create('TToken::FromJSON::json is not valid object [' + AJSON + ']'); end; try FExp := TJSONObject(LObj).Get(PROP_EXPIRES); FToken := TJSONObject(LObj).Get(PROP_TOKEN); finally LObj.Free; end; end; end.
unit uExportador; {$mode objfpc}{$H+} interface uses DB, BufDataset, Classes, SysUtils, Variants; type { TExportador } TExportador = class(TComponent) private public function ExportarFuncionario: TBufDataSet; function ExportarDependentes: TBufDataSet; procedure Exportar(Arquivo: TStringList); end; implementation { TExportador } function TExportador.ExportarFuncionario: TBufDataSet; begin Result := Nil; end; function TExportador.ExportarDependentes: TBufDataSet; begin Result := Nil; end; procedure TExportador.Exportar(Arquivo: TStringList); var I: integer; lLinha, lFuncionario, lDependente: string; begin for I := 0 to pred(Arquivo.Count) do begin lLinha := Arquivo[I]; if lLinha = '' then begin lFuncionario := ''; lDependente := ''; continue; end; if lFuncionario <> '' then ExportarDependentes; if lFuncionario <> '' and lDependente <> '' then ExportarFuncionario; end; end; end.
unit diagramblock; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, types, DiagramTypes, Graphics, textrender, ComCtrls{$ifdef windows}, gl, glext{$endif}, betterControls; type TDiagramBlock=class; TDiagramBlockSideDescriptor=record block: TDiagramBlock; side: TDiagramBlockSide; sideposition: integer; //0 is center, -1 is one pixel to the left, 1 is one pixel to the rigth end; TDBCustomDrawEvent=procedure(Sender: TDiagramBlock; const ARect: TRect; beforePaint: boolean; var DefaultDraw: Boolean) of object; TDiagramBlock=class private fx,fy: integer; fwidth: integer; fheight: integer; fname: string; fcaption: string; fOnDoubleClickHeader: TNotifyEvent; fOnDoubleClickBody: TNotifyEvent; fOnRenderHeader: TDBCustomDrawEvent; fOnRenderBody: TDBCustomDrawEvent; data: TStringList; captionheight: integer; config: TDiagramConfig; fOnDestroy: TNotifyEvent; useCustomBackgroundColor: boolean; customBackgroundColor: tcolor; useCustomTextColor: boolean; CustomTextColor: Tcolor; fAutoSide: boolean; fAutoSideDistance: integer; fAutoSize: boolean; preferedWidth, preferedHeight: integer; hasChanged: boolean; cachedBlock: TBitmap; //Cache the block image and only update when changes happen {$ifdef windows} ftexture: glint; {$endif} fBlockId: integer; fShowHeader: boolean; fDragbody: boolean; fOnDrag: TNotifyEvent; fOnDragStart: TNotifyEvent; fOnDragEnd: TNotifyEvent; fTag: qword; function getBackgroundColor: TColor; procedure setBackgroundColor(c: TColor); function getTextColor: TColor; procedure setTextColor(c: TColor); function getCanvas: TCanvas; function getOwner: TCustomControl; procedure setCaption(c: string); procedure setWidth(w: integer); procedure setHeight(h: integer); procedure DataChange(sender: TObject); procedure setx(newx: integer); procedure sety(newy: integer); function getRect: trect; procedure setRect(r: trect); procedure createBlock(graphConfig: TDiagramConfig); public function getData: TStrings; procedure setData(s: TStrings); procedure dblClick(xpos,ypos: integer); function IsAtBorder(xpos, ypos: integer; out side: TDiagramBlockSide): boolean; function IsInsideHeader(xpos,ypos: integer):boolean; function IsInsideBody(xpos,ypos: integer):boolean; function IsInside(xpos,ypos: integer):boolean; function OverlapsWith(otherBlock: TDiagramBlock): boolean; procedure resize(xpos, ypos: integer; side: TDiagramBlockSide); function getConnectPosition(side: TDiagramBlockSide; position: integer=0): tpoint; function getClosestSideDescriptor(xpos,ypos: integer): TDiagramBlockSideDescriptor; procedure setAutoSize(state: boolean); procedure DoAutoSize; function IntersectsWithLine(startpoint, endpoint: tpoint; out intersectpoint: tpoint): boolean; procedure saveToStream(f: TStream); procedure loadFromStream(f: TStream); procedure render; property OnDestroy: TNotifyEvent read fOnDestroy write fOnDestroy; property BlockRect: TRect read getRect write setRect; property BlockID: integer read fBlockId write fBlockId; //used for saving/loading. set by diagram constructor create(graphConfig: TDiagramConfig); constructor createFromStream(graphConfig: TDiagramConfig; f: TStream); destructor destroy; override; published property Owner: TCustomControl read getOwner; property Canvas: TCanvas read getCanvas; property X: integer read fx write setX; property Y: integer read fy write setY; property Width: integer read fwidth write setWidth; property Height: integer read fheight write setHeight; property Caption: string read fcaption write setCaption; property Strings: TStrings read getData write setData; property BackgroundColor: TColor read getBackgroundColor write setBackgroundColor; property TextColor: TColor read getTextColor write setTextColor; property Name: string read fname write fname; property AutoSize: boolean read fAutoSize write setAutoSize; property AutoSide: boolean read fAutoSide write fAutoSide; property AutoSideDistance: integer read fAutoSideDistance write fAutoSideDistance; property ShowHeader: boolean read fShowHeader write fShowHeader default true; property DragBody: boolean read fDragbody write fDragBody; property OnDoubleClickHeader: TNotifyEvent read fOnDoubleClickHeader write fOnDoubleClickHeader; property OnDoubleClickBody: TNotifyEvent read fOnDoubleClickBody write fOnDoubleClickBody; property OnRenderHeader: TDBCustomDrawEvent read fOnRenderHeader write fOnRenderHeader; property OnRenderBody: TDBCustomDrawEvent read fOnRenderBody write fOnRenderBody; property OnDrag: TNotifyEvent read fOnDrag write fOnDrag; property OnDragStart: TNotifyEvent read fOnDragStart write fOnDragStart; property OnDragEnd: TNotifyEvent read fOnDragEnd write fOnDragEnd; property Tag: Qword read fTag write fTag; end; implementation uses math; //http://www.delphipages.com/tip/test_if_2_lines_cross_and_find_intersection-10800.html function LinesCross(LineAP1, LineAP2, LineBP1, LineBP2 : TPoint) : boolean; Var diffLA, diffLB : TPoint; CompareA, CompareB : integer; begin Result := False; diffLA := LineAP2.Subtract(LineAP1); //Subtract(LineAP2, LineAP1); diffLB := LineBP2.Subtract(LineBP1); //Subtract(LineBP2, LineBP1); CompareA := diffLA.X*LineAP1.Y - diffLA.Y*LineAP1.X; CompareB := diffLB.X*LineBP1.Y - diffLB.Y*LineBP1.X; if ( ((diffLA.X*LineBP1.Y - diffLA.Y*LineBP1.X) < CompareA) xor ((diffLA.X*LineBP2.Y - diffLA.Y*LineBP2.X) < CompareA) ) and ( ((diffLB.X*LineAP1.Y - diffLB.Y*LineAP1.X) < CompareB) xor ((diffLB.X*LineAP2.Y - diffLB.Y*LineAP2.X) < CompareB) ) then Result := True; end; function LineIntersect(LineAP1, LineAP2, LineBP1, LineBP2 : TPoint) : TPointF; Var LDetLineA, LDetLineB, LDetDivInv : Real; LDiffLA, LDiffLB : TPoint; begin LDetLineA := LineAP1.X*LineAP2.Y - LineAP1.Y*LineAP2.X; LDetLineB := LineBP1.X*LineBP2.Y - LineBP1.Y*LineBP2.X; LDiffLA := LineAP1.Subtract(LineAP2); // Subtract(LineAP1, LineAP2); LDiffLB := LineBP1.Subtract(LineBP2); // Subtract(LineBP1, LineBP2); LDetDivInv := 1 / ((LDiffLA.X*LDiffLB.Y) - (LDiffLA.Y*LDiffLB.X)); Result.X := ((LDetLineA*LDiffLB.X) - (LDiffLA.X*LDetLineB)) * LDetDivInv; Result.Y := ((LDetLineA*LDiffLB.Y) - (LDiffLA.Y*LDetLineB)) * LDetDivInv; end; function TDiagramBlock.IntersectsWithLine(startpoint, endpoint: tpoint; out intersectpoint: tpoint): boolean; var r: trect; ip: TPointF; best: record distance: single; point: tpointf; end; distance: single; startpointf: tpointf; begin //check from where to where it goes and pick a r:=getRect; startpointf.x:=startpoint.x; startpointf.y:=startpoint.y; best.distance:=0; result:=false; if LinesCross(startpoint,endpoint,point(r.left,r.top),point(r.right,r.top)) then //top begin ip:=LineIntersect(startpoint,endpoint,point(r.left,r.top),point(r.right,r.top)); best.distance:=ip.distance(startpointf); best.point:=ip; result:=true; end; if LinesCross(startpoint,endpoint,point(r.right,r.top),point(r.right,r.bottom)) then //right begin ip:=LineIntersect(startpoint,endpoint,point(r.right,r.top),point(r.right,r.bottom)); distance:=ip.Distance(startpointf); if (result=false) or (distance<best.distance) then begin best.distance:=distance; best.point:=ip; end; result:=true; end; if LinesCross(startpoint,endpoint,point(r.left,r.bottom),point(r.right,r.bottom)) then //bottom begin ip:=LineIntersect(startpoint,endpoint,point(r.left,r.bottom),point(r.right,r.bottom)); distance:=ip.Distance(startpointf); if (result=false) or (distance<best.distance) then begin best.distance:=distance; best.point:=ip; end; result:=true; end; if LinesCross(startpoint,endpoint,point(r.left,r.top),point(r.left,r.bottom)) then //left begin ip:=LineIntersect(startpoint,endpoint,point(r.left,r.top),point(r.left,r.bottom)); distance:=ip.Distance(startpointf); if (result=false) or (distance<best.distance) then begin best.distance:=distance; best.point:=ip; end; result:=true; end; if result then begin intersectpoint.x:=trunc(best.point.x); intersectpoint.y:=trunc(best.point.y); end; end; procedure TDiagramBlock.setx(newx: integer); begin if newx<=-width+2 then newx:=-width+2; fx:=newx; end; procedure TDiagramBlock.sety(newy: integer); begin if newy<=-captionheight+2 then newy:=-captionheight+2; fy:=newy; end; function TDiagramBlock.getBackgroundColor: TColor; begin if useCustomBackgroundColor then result:=customBackgroundColor else result:=config.BlockBackground; end; procedure TDiagramBlock.setBackgroundColor(c: TColor); begin customBackgroundColor:=c; useCustomBackgroundColor:=true; hasChanged:=true; end; function TDiagramBlock.getTextColor: TColor; begin if useCustomTextColor then result:=CustomTextColor else result:=config.blockTextColorNoMarkup; end; procedure TDiagramBlock.setTextColor(c: TColor); begin CustomTextColor:=c; useCustomTextColor:=true; end; function TDiagramBlock.getOwner: TCustomControl; begin result:=config.owner; end; function TDiagramBlock.getCanvas: TCanvas; begin result:=config.canvas; end; procedure TDiagramBlock.setCaption(c: string); begin fcaption:=c; hasChanged:=true; if fAutoSize then DoAutoSize; end; procedure TDiagramBlock.setWidth(w: integer); begin fwidth:=w; hasChanged:=true; end; procedure TDiagramBlock.setHeight(h: integer); begin fheight:=h; hasChanged:=true; end; procedure TDiagramBlock.DataChange(sender: TObject); begin hasChanged:=true; if fAutoSize then DoAutoSize; end; procedure TDiagramBlock.setAutoSize(state: boolean); begin fAutoSize:=state; if state then begin hasChanged:=true; DoAutoSize; end; end; procedure TDiagramBlock.DoAutoSize; begin if fAutoSize=false then exit; render; width:=preferedwidth+10; height:=preferedheight; end; procedure TDiagramBlock.saveToStream(f: TStream); begin f.WriteAnsiString('BLK'); f.WriteAnsiString(fname); f.WriteAnsiString(fcaption); f.WriteAnsiString(data.Text); f.WriteQWord(tag); f.WriteDWord(fBlockID); f.WriteDWord(fx); f.WriteDWord(fy); f.WriteDWord(fwidth); f.WriteDWord(fheight); f.WriteByte(ifthen(useCustomBackgroundColor, 1,0)); if useCustomBackgroundColor then f.WriteDWord(customBackgroundColor); f.WriteByte(ifthen(useCustomTextColor, 1,0)); if useCustomTextColor then f.WriteDWord(CustomTextColor); f.WriteByte(ifthen(ShowHeader, 1,0)); f.WriteByte(ifthen(DragBody, 1,0)); f.WriteByte(ifthen(AutoSize, 1,0)); f.WriteByte(ifthen(AutoSide, 1,0)); f.WriteWord(fAutoSideDistance); end; procedure TDiagramBlock.loadFromStream(f: TStream); begin if f.ReadAnsiString<>'BLK' then raise exception.create('Block read error'); fname:=f.ReadAnsiString; fcaption:=f.ReadAnsiString; data.text:=f.ReadAnsiString; tag:=f.ReadQWord; fBlockId:=f.ReadDWord; fx:=f.ReadDWord; fy:=f.ReadDWord; fwidth:=f.ReadDWord; fheight:=f.ReadDWord; useCustomBackgroundColor:=f.readbyte=1; if useCustomBackgroundColor then customBackgroundColor:=f.ReadDWord; useCustomTextColor:=f.readByte=1; if useCustomTextColor then CustomTextColor:=f.ReadDWord; ShowHeader:=f.readbyte=1; DragBody:=f.readbyte=1; AutoSize:=f.readbyte=1; autoside:=f.readbyte=1; fAutoSideDistance:=f.readWord; end; procedure TDiagramBlock.render; var c: TCanvas; oldbgc: TColor; oldfontcolor: TColor; renderOriginal: boolean; cr,tr: TRect; pp: PByte; begin //render the block at the given location //if config.canvas=nil then exit; cr.Left:=0; cr.Top:=0; cr.Width:=0; cr.height:=0; tr.left:=0; tr.top:=0; tr.width:=0; tr.height:=0; if hasChanged {$ifdef windows} or (config.UseOpenGL and (ftexture=0)) {$endif} then begin //render if cachedBlock=nil then begin cachedblock:=tbitmap.Create; cachedblock.width:=width; cachedblock.height:=height; cachedblock.PixelFormat:=pf32bit; end; if cachedblock.width<>width then cachedblock.width:=width; if cachedblock.height<>height then cachedblock.height:=height; c:=cachedblock.Canvas; cachedblock.Canvas.brush.Assign(config.canvas.brush); cachedblock.Canvas.pen.Assign(config.canvas.pen); cachedblock.Canvas.font.Assign(config.canvas.font); oldbgc:=c.brush.color; c.brush.color:=BackgroundColor; c.FillRect(0,0,width,height); c.Rectangle(0,0,width,height); if fShowHeader then begin if (captionheight=0) then captionheight:=c.GetTextHeight('XxYyJjQq')+4; c.Rectangle(0,0,width,captionheight); end else captionheight:=0; oldfontcolor:=c.font.color; c.font.color:=TextColor; if fShowHeader then begin renderOriginal:=true; if assigned(fOnRenderHeader) then fOnRenderHeader(self,rect(0,0,width-1,captionheight),true, renderOriginal); if renderOriginal then begin cr:=renderFormattedText(c, rect(0,0,width-1,captionheight),1,0,caption); if assigned(fOnRenderHeader) then fOnRenderHeader(self,rect(0,0,width-1,captionheight),false, renderOriginal); end; end; renderOriginal:=true; if assigned(fOnRenderBody) then fOnRenderBody(self,rect(0,0,width-1,captionheight),true, renderOriginal); if renderOriginal then begin tr:=renderFormattedText(c, rect(0,captionheight,width-1,height-2),1,captionheight,data.text); if assigned(fOnRenderBody) then fOnRenderBody(self,rect(0,0,width-1,captionheight),false, renderOriginal); end; preferedwidth:=cr.Width; if preferedwidth<tr.Width then preferedwidth:=tr.Width; preferedheight:=captionheight+tr.height; c.font.color:=oldfontcolor; c.brush.color:=oldbgc; haschanged:=false; {$ifdef windows} if config.UseOpenGL and (width>0) and (height>0) then begin if ftexture=0 then glGenTextures(1, @ftexture); glBindTexture(GL_TEXTURE_2D, ftexture); glActiveTexture(GL_TEXTURE0); pp:=cachedBlock.RawImage.Data; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, cachedBlock.Width, cachedBlock.height, 0, GL_BGRA, GL_UNSIGNED_BYTE, pp); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); end; {$endif} end; //draw the cached block {$ifdef windows} if config.UseOpenGL then begin if ftexture=0 then begin haschanged:=true; exit; //should never happen end; //render a quad with this texture glBindTexture(GL_TEXTURE_2D, ftexture); glActiveTexture(GL_TEXTURE0); glColor3f(1,1,1); glScalef(config.zoom, config.zoom,1); glTranslatef(-config.scrollx,-config.scrolly,0); glBegin(GL_QUADS); // Each set of 4 vertices form a quad glTexCoord2f(0,0); glVertex2f(x,y); glTexCoord2f(0,1); glVertex2f(x,y+height); glTexCoord2f(1,1); glVertex2f(x+width,y+height); glTexCoord2f(1,0); glVertex2f(x+width,y); glEnd(); glLoadIdentity(); end else {$endif} begin config.canvas.StretchDraw(rect(trunc((x-config.scrollx)*config.zoom),trunc((y-config.scrolly)*config.zoom),ceil(((x-config.scrollx)+width)*config.zoom),ceil(((y-config.scrolly)+Height)*config.zoom)),cachedblock); //config.canvas.Draw(x-config.scrollx,y-config.scrolly,cachedBlock); end; end; function TDiagramBlock.getData: TStrings; begin result:=data; end; procedure TDiagramBlock.setData(s: TStrings); begin data.clear; data.Assign(s); hasChanged:=true; end; procedure TDiagramBlock.dblClick(xpos,ypos: integer); begin if assigned(fOnDoubleClickBody) and IsInsideBody(xpos,ypos) then fOnDoubleClickBody(self) else if assigned(fOnDoubleClickHeader) and IsInsideHeader(xpos,ypos) then fOnDoubleClickHeader(self); end; function TDiagramBlock.getRect: trect; begin result.Left:=x; result.top:=y; result.Right:=x+width; result.Bottom:=y+height; end; procedure TDiagramBlock.setRect(r: trect); begin x:=r.left; y:=r.top; width:=r.width; height:=r.height; end; function TDiagramBlock.OverlapsWith(otherBlock: TDiagramBlock): boolean; var r1,r2: Trect; begin r1:=blockrect; r2:=otherblock.blockrect; result:=r1.IntersectsWith(r2); end; function TDiagramBlock.IsInsideHeader(xpos,ypos: integer):boolean; var headerrect: trect; begin headerrect:=rect(x,y,x+width,y+captionheight); result:=PtInRect(headerrect,point(xpos,ypos)); end; function TDiagramBlock.IsInsideBody(xpos,ypos: integer):boolean; var bodyrect: trect; begin bodyrect:=rect(x,y+captionheight,x+width,y+height); result:=PtInRect(bodyrect,point(xpos,ypos)); end; function TDiagramBlock.IsInside(xpos,ypos: integer):boolean; var r: trect; begin r:=rect(x,y,x+width,y+height); result:=PtInRect(r,point(xpos,ypos)); end; function TDiagramBlock.IsAtBorder(xpos, ypos: integer; out side: TDiagramBlockSide): boolean; var borderthickness: integer; begin result:=false; borderthickness:=3; if PtInRect(rect(x-borderthickness,y-borderthickness,x+width+borderthickness,y+height+borderthickness),point(xpos,ypos))=false then exit; //not even within the range //still here so it's within the region if PtInRect(rect(x-borderthickness,y-borderthickness, x+borderthickness,y+borderthickness),point(xpos,ypos)) then begin side:=dbsTopLeft; exit(true); end; if PtInRect(rect(x+width-borderthickness,y-borderthickness, x+width+borderthickness,y+borderthickness),point(xpos,ypos)) then begin side:=dbsTopRight; exit(true); end; if PtInRect(rect(x-borderthickness,y+height-borderthickness, x+borderthickness,y+height+borderthickness),point(xpos,ypos)) then begin side:=dbsBottomLeft; exit(true); end; if PtInRect(rect(x+width-borderthickness,y+height-borderthickness, x+width+borderthickness,y+height+borderthickness),point(xpos,ypos)) then begin side:=dbsBottomRight; exit(true); end; if PtInRect(rect(x,y-borderthickness, x+width,y+borderthickness),point(xpos,ypos)) then begin side:=dbsTop; exit(true); end; if PtInRect(rect(x+width-borderthickness,y, x+width+borderthickness,y+height),point(xpos,ypos)) then begin side:=dbsRight; exit(true); end; if PtInRect(rect(x,y+height-borderthickness, x+width,y+height+borderthickness),point(xpos,ypos)) then begin side:=dbsBottom; exit(true); end; if PtInRect(rect(x-borderthickness,y, x+borderthickness,y+height),point(xpos,ypos)) then begin side:=dbsLeft; exit(true); end; end; function TDiagramBlock.getClosestSideDescriptor(xpos,ypos: integer): TDiagramBlockSideDescriptor; var r: TDiagramBlockSideDescriptor; cx,cy: integer; p: tpoint; closestpointdistance: ValReal; distance: ValReal; begin r.block:=self; r.sideposition:=0; cx:=x+width div 2; cy:=y+height div 2; //calculate the side and position closest to the given x/ypos if ypos<y then begin //top if xpos<x then begin //topleft r.side:=dbsTopLeft; end else if xpos>x+width then begin //topright r.side:=dbsTopRight; end else begin //top r.side:=dbsTop; r.sideposition:=xpos-cx; end; end else if ypos>y+height then begin //bottom if xpos<x then begin //bottomleft r.side:=dbsBottomLeft; end else if xpos>x+width then begin //bottomright r.side:=dbsBottomRight; end else begin //bottom r.side:=dbsBottom; r.sideposition:=xpos-cx; end; end else begin //left/right if xpos<x then begin //left r.side:=dbsLeft; r.sideposition:=ypos-cy; end else if xpos>x+width then begin //right r.side:=dbsRight; r.sideposition:=ypos-cy; end else begin //inside //calculate which side is closest //top p:=point(xpos,ypos); closestpointdistance:=point(xpos,y).Distance(p); r.side:=dbsTop; r.sideposition:=xpos-cx; //topright distance:=point(x+width,y).Distance(p); if distance<closestpointdistance then begin closestpointdistance:=distance; r.side:=dbsTopRight; r.sideposition:=0; end; //right distance:=point(x+width,ypos).Distance(p); if distance<closestpointdistance then begin closestpointdistance:=distance; r.side:=dbsRight; r.sideposition:=ypos-cy; end; //bottomright distance:=point(x+width,y+height).Distance(p); if distance<closestpointdistance then begin closestpointdistance:=distance; r.side:=dbsBottomRight; r.sideposition:=0; end; //bottom distance:=point(xpos,y+height).Distance(p); if distance<closestpointdistance then begin closestpointdistance:=distance; r.side:=dbsBottom; r.sideposition:=xpos-cx; end; //bottomleft distance:=point(x,y+height).Distance(p); if distance<closestpointdistance then begin closestpointdistance:=distance; r.side:=dbsBottomRight; r.sideposition:=0; end; //left distance:=point(x,ypos).Distance(p); if distance<closestpointdistance then begin closestpointdistance:=distance; r.side:=dbsLeft; r.sideposition:=ypos-cy; end; //topleft distance:=point(x,y).Distance(p); if distance<closestpointdistance then begin closestpointdistance:=distance; r.side:=dbsTopLeft; r.sideposition:=0; end; end; end; result:=r; end; function TDiagramBlock.getConnectPosition(side: TDiagramBlockSide; position: integer=0): tpoint; //returns the canvas x,y position of the specified side's center, offset by the given position up to the max length of the side var hc,vc: integer; begin result.x:=0; result.y:=0; case side of dbsTopLeft: exit(point(x,y)); dbsTop: begin hc:=width div 2; if (abs(position)>hc) then begin if position>0 then position:=hc else position:=-hc; end; exit(point(x+hc+position,y)); end; dbsTopRight: exit(point(x+width,y)); dbsRight: begin vc:=height div 2; if (abs(position)>vc) then begin if position>0 then position:=vc else position:=-vc; end; exit(point(x+width,y+vc+position)); end; dbsBottomRight: exit(point(x+width,y+height)); dbsBottom: begin hc:=width div 2; if (abs(position)>hc) then begin if position>0 then position:=hc else position:=-hc; end; exit(point(x+hc+position,y+height)); end; dbsBottomLeft: exit(point(x,y+height)); dbsLeft: begin vc:=height div 2; if (abs(position)>vc) then begin if position>0 then position:=vc else position:=-vc; end; exit(point(x,y+vc+position)); end; end; end; procedure TDiagramBlock.resize(xpos, ypos: integer; side: TDiagramBlockSide); var d: integer; procedure resizeLeft; begin if xpos>=(x+width-1) then xpos:=x+width-1; d:=xpos-x; width:=width-d; x:=xpos; end; procedure resizeTop; begin if ypos>=(y+height-captionheight-1) then ypos:=y+height-captionheight-1; d:=ypos-y; height:=height-d; y:=ypos; end; procedure resizeRight; begin width:=xpos-x; if width<1 then width:=1; end; procedure resizeBottom; begin height:=ypos-y; if height<captionheight then height:=captionheight; end; begin case side of dbsTopLeft: begin resizeLeft; resizeTop; end; dbsTop: resizeTop; dbsTopRight: begin resizeTop; resizeRight; end; dbsRight: resizeRight; dbsBottomRight: begin resizeBottom; resizeRight; end; dbsBottom: resizeBottom; dbsBottomLeft: begin resizeBottom; resizeLeft; end; dbsLeft: resizeLeft; end; end; procedure TDiagramBlock.createBlock(graphConfig: TDiagramConfig); begin fShowHeader:=true; data:=TStringList.create; data.OnChange:=@DataChange; config:=GraphConfig; x:=0; y:=0; width:=100; height:=100; end; constructor TDiagramBlock.create(graphConfig: TDiagramConfig); begin createBlock(graphConfig); end; constructor TDiagramBlock.createFromStream(graphConfig: TDiagramConfig; f: TStream); begin createBlock(graphConfig); loadFromStream(f); end; destructor TDiagramBlock.destroy; begin if assigned(OnDestroy) then OnDestroy(self); //owner.NotifyBlockDestroy(self); if data<>nil then freeandnil(data); if cachedblock<>nil then freeandnil(cachedblock); inherited destroy; end; end.
unit DBCfile; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs; type PCardinal = array of Cardinal; PInteger = array of Integer; PArray = array of Char; PDBCFile = ^TDBCFile; TDBCFile = class public recordSize: Cardinal; recordCount: Cardinal; fieldCount: Cardinal; stringSize: Cardinal; fieldsOffset: PCardinal; data: PChar; stringTable: PChar; offset: PChar; IsLocalized: boolean; constructor Create; destructor Destroy; override; function Load(filename: WideString): boolean; procedure setRecord(id: Cardinal); function GetNumRows(): Cardinal; function GetCols(): Cardinal; function GetOffset(id: Cardinal): Cardinal; function IsLoaded(): boolean; function getFloat(field: Cardinal): Single; function getUInt(field: Cardinal): Cardinal; function getUInt8(field: Cardinal): Byte; function getPChar(field: Cardinal): pchar; function getString(field: Cardinal): WideString; end; TDBCFileStruct = record filename : WideString; fmt : WideString; end; const FT_NA='x'; //not used or unknown, 4 byte size FT_NA_BYTE='X'; //not used or unknown, byte FT_STRING='s'; //char* FT_FLOAT='f'; //float FT_INT='i'; //uint32 FT_BYTE='b'; //uint8 FT_SORT='d'; //sorted by this field, field is not included FT_IND='n'; //the same,but parsed to data FT_LOGIC='l'; //Logical (boolean) DBCFileStruct : array[0..245] of TDBCFileStruct = ( (filename: 'Achievement.dbc'; fmt: 'iiiissssssssssssssssissssssssssssssssiiiiiissssssssssssssssiii'), (filename: 'Achievement_Category.dbc'; fmt: 'iissssssssssssssssii'), (filename: 'Achievement_Criteria.dbc'; fmt: 'iiiiiiiiissssssssssssssssiiiiii'), (filename: 'AnimationData.dbc'; fmt: 'isiiiiii'), (filename: 'AreaGroup.dbc'; fmt: 'iiiiiiii'), (filename: 'AreaPOI.dbc'; fmt: 'iiiiiiiiiiiifffiiissssssssssssssssissssssssssssssssiii'), (filename: 'AreaTable.dbc'; fmt: 'iiiiiiiiiiissssssssssssssssiiiiiiffi'), (filename: 'AreaTrigger.dbc'; fmt: 'iiffffffff'), (filename: 'AttackAnimKits.dbc'; fmt: 'iiiii'), (filename: 'AttackAnimTypes.dbc'; fmt: 'is'), (filename: 'AuctionHouse.dbc'; fmt: 'iiiissssssssssssssssi'), (filename: 'BankBagSlotPrices.dbc'; fmt: 'ii'), (filename: 'BannedAddOns.dbc'; fmt: 'iiiiiiiiiii'), (filename: 'BarberShopStyle.dbc'; fmt: 'iissssssssssssssssissssssssssssssssifiii'), (filename: 'BattlemasterList.dbc'; fmt: 'iiiiiiiiiiissssssssssssssssiiiii'), (filename: 'CameraShakes.dbc'; fmt: 'iiifffff'), (filename: 'Cfg_Categories.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiii'), (filename: 'Cfg_Configs.dbc'; fmt: 'iiii'), (filename: 'CharacterFacialHairStyles.dbc'; fmt: 'iiiiiiii'), (filename: 'CharBaseInfo.dbc'; fmt: 'bb'), (filename: 'CharHairGeosets.dbc'; fmt: 'iiiiii'), (filename: 'CharHairTextures.dbc'; fmt: 'iiiiiiii'), (filename: 'CharSections.dbc'; fmt: 'iiiisssiii'), (filename: 'CharStartOutfit.dbc'; fmt: 'ibbbbiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'CharTitles.dbc'; fmt: 'iissssssssssssssssissssssssssssssssii'), (filename: 'CharVariations.dbc'; fmt: ''), (filename: 'ChatChannels.dbc'; fmt: 'iisssssssssssssssssissssssssssssssssi'), (filename: 'ChatProfanity.dbc'; fmt: 'isi'), (filename: 'ChrClasses.dbc'; fmt: 'iiiissssssssssssssssissssssssssssssssissssssssssssssssiiiiii'), (filename: 'ChrRaces.dbc'; fmt: 'iiiiiisfiiiisissssssssssssssssissssssssssssssssissssssssssssssssisssi'), (filename: 'CinematicCamera.dbc'; fmt: 'isiffff'), (filename: 'CinematicSequences.dbc'; fmt: 'iiiiiiiiii'), (filename: 'CreatureDisplayInfo.dbc'; fmt: 'iiiifisssiiiiiii'), (filename: 'CreatureDisplayInfoExtra.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiis'), (filename: 'CreatureFamily.dbc'; fmt: 'ififiiiiiissssssssssssssssis'), (filename: 'CreatureModelData.dbc'; fmt: 'iisiisiffffiiiifffffffffffff'), (filename: 'CreatureMovementInfo.dbc'; fmt: 'ii'), (filename: 'CreatureSoundData.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'CreatureSpellData.dbc'; fmt: 'iiiiiiiii'), (filename: 'CreatureType.dbc'; fmt: 'issssssssssssssssii'), (filename: 'CurrencyCategory.dbc'; fmt: 'iissssssssssssssssi'), (filename: 'CurrencyTypes.dbc'; fmt: 'iiii'), (filename: 'DanceMoves.dbc'; fmt: 'iiisisssssssssssssssssii'), (filename: 'DeathThudLookups.dbc'; fmt: 'iiiii'), (filename: 'DeclinedWord.dbc'; fmt: 'is'), (filename: 'DeclinedWordCases.dbc'; fmt: 'iiis'), (filename: 'DestructibleModelData.dbc'; fmt: 'iiiiiiiiiiiiiiiiiii'), (filename: 'DungeonEncounter.dbc'; fmt: 'iiiiissssssssssssssssii'), (filename: 'DungeonMap.dbc'; fmt: 'iiiffffi'), (filename: 'DungeonMapChunk.dbc'; fmt: 'iiiif'), (filename: 'DurabilityCosts.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'DurabilityQuality.dbc'; fmt: 'if'), (filename: 'Emotes.dbc'; fmt: 'isiiiii'), (filename: 'EmotesText.dbc'; fmt: 'isiiiiiiiiiiiiiiiii'), (filename: 'EmotesTextData.dbc'; fmt: 'issssssssssssssssi'), (filename: 'EmotesTextSound.dbc'; fmt: 'iiiii'), (filename: 'EnvironmentalDamage.dbc'; fmt: 'iii'), (filename: 'Exhaustion.dbc'; fmt: 'iifffssssssssssssssssif'), (filename: 'Faction.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiissssssssssssssssissssssssssssssssi'), (filename: 'FactionGroup.dbc'; fmt: 'iisssssssssssssssssi'), (filename: 'FactionTemplate.dbc'; fmt: 'iiiiiiiiiiiiii'), (filename: 'FileData.dbc'; fmt: 'isi'), (filename: 'FootprintTextures.dbc'; fmt: 'is'), (filename: 'FootstepTerrainLookup.dbc'; fmt: 'iiiii'), (filename: 'GameObjectArtKit.dbc'; fmt: 'iiiissss'), (filename: 'GameObjectDisplayInfo.dbc'; fmt: 'isiiiiiiiiiifffffff'), (filename: 'GameTables.dbc'; fmt: 'sii'), (filename: 'GameTips.dbc'; fmt: 'issssssssssssssssi'), (filename: 'GemProperties.dbc'; fmt: 'iiiii'), (filename: 'GlyphProperties.dbc'; fmt: 'iiii'), (filename: 'GlyphSlot.dbc'; fmt: 'iii'), (filename: 'GMSurveyAnswers.dbc'; fmt: 'iiissssssssssssssssi'), (filename: 'GMSurveyCurrentSurvey.dbc'; fmt: 'ii'), (filename: 'GMSurveyQuestions.dbc'; fmt: 'issssssssssssssssi'), (filename: 'GMSurveySurveys.dbc'; fmt: 'iiiiiiiiiii'), (filename: 'GMTicketCategory.dbc'; fmt: 'issssssssssssssssi'), (filename: 'GroundEffectDoodad.dbc'; fmt: 'iis'), (filename: 'GroundEffectTexture.dbc'; fmt: 'iiiiiiiiiii'), (filename: 'gtBarberShopCostBase.dbc'; fmt: 'f'), (filename: 'gtChanceToMeleeCrit.dbc'; fmt: 'f'), (filename: 'gtChanceToMeleeCritBase.dbc'; fmt: 'f'), (filename: 'gtChanceToSpellCrit.dbc'; fmt: 'f'), (filename: 'gtChanceToSpellCritBase.dbc'; fmt: 'f'), (filename: 'gtCombatRatings.dbc'; fmt: 'f'), (filename: 'gtNPCManaCostScaler.dbc'; fmt: 'f'), (filename: 'gtOCTClassCombatRatingScalar.dbc'; fmt: 'if'), (filename: 'gtOCTRegenHP.dbc'; fmt: 'f'), (filename: 'gtOCTRegenMP.dbc'; fmt: 'f'), (filename: 'gtRegenHPPerSpt.dbc'; fmt: 'f'), (filename: 'gtRegenMPPerSpt.dbc'; fmt: 'f'), (filename: 'HelmetGeosetVisData.dbc'; fmt: 'iiiiiiii'), (filename: 'HolidayDescriptions.dbc'; fmt: 'issssssssssssssssi'), (filename: 'HolidayNames.dbc'; fmt: 'issssssssssssssssi'), (filename: 'Holidays.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiisiii'), (filename: 'Item.dbc'; fmt: 'iiiiiiii'), (filename: 'ItemBagFamily.dbc'; fmt: 'issssssssssssssssi'), (filename: 'ItemClass.dbc'; fmt: 'iiissssssssssssssssi'), (filename: 'ItemCondExtCosts.dbc'; fmt: 'iiii'), (filename: 'ItemDisplayInfo.dbc'; fmt: 'issssssiiiiiiiissssssssii'), (filename: 'ItemExtendedCost.dbc'; fmt: 'iiiiiiiiiiiiiiii'), (filename: 'ItemGroupSounds.dbc'; fmt: 'iiiii'), (filename: 'ItemLimitCategory.dbc'; fmt: 'issssssssssssssssiii'), (filename: 'ItemPetFood.dbc'; fmt: 'issssssssssssssssi'), (filename: 'ItemPurchaseGroup.dbc'; fmt: 'iiiissssssssssssssssiiiiii'), (filename: 'ItemRandomProperties.dbc'; fmt: 'isiiiiissssssssssssssssi'), (filename: 'ItemRandomSuffix.dbc'; fmt: 'issssssssssssssssisiiiiiiiiii'), (filename: 'ItemSet.dbc'; fmt: 'issssssssssssssssiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'ItemSubClass.dbc'; fmt: 'iiiiiiiiiissssssssssssssssissssssssssssssssi'), (filename: 'ItemSubClassMask.dbc'; fmt: 'iissssssssssssssssi'), (filename: 'ItemVisualEffects.dbc'; fmt: 'is'), (filename: 'ItemVisuals.dbc'; fmt: 'iiiiii'), (filename: 'Languages.dbc'; fmt: 'issssssssssssssssi'), (filename: 'LanguageWords.dbc'; fmt: 'iis'), (filename: 'LFGDungeonExpansion.dbc'; fmt: 'iiiiiiii'), (filename: 'LFGDungeonGroup.dbc'; fmt: 'issssssssssssssssiiii'), (filename: 'LFGDungeons.dbc'; fmt: 'issssssssssssssssiiiiiiiiiiiiiiissssssssssssssssi'), (filename: 'Light.dbc'; fmt: 'iifffffiiiiiiii'), (filename: 'LightFloatBand.dbc'; fmt: 'iiiiffffffffffffffffffffffffffffff'), (filename: 'LightIntBand.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'LightParams.dbc'; fmt: 'iiiifffff'), (filename: 'LightSkybox.dbc'; fmt: 'isi'), (filename: 'LiquidMaterial.dbc'; fmt: 'iii'), (filename: 'LiquidType.dbc'; fmt: 'isiiiiiffffifiiiiiiiiiiiffffiiiifffffffffffii'), (filename: 'LoadingScreens.dbc'; fmt: 'isss'), (filename: 'LoadingScreenTaxiSplines.dbc'; fmt: 'iifffffffifffffffii'), (filename: 'Lock.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'LockType.dbc'; fmt: 'issssssssssssssssissssssssssssssssissssssssssssssssis'), (filename: 'MailTemplate.dbc'; fmt: 'issssssssssssssssissssssssssssssssi'), (filename: 'Map.dbc'; fmt: 'isiisssssssssssssssssiissssssssssssssssissssssssssssssssiififfiiii'), (filename: 'MapDifficulty.dbc'; fmt: 'iiissssssssssssssssiiii'), (filename: 'Material.dbc'; fmt: 'iiiii'), (filename: 'Movie.dbc'; fmt: 'isi'), (filename: 'MovieFileData.dbc'; fmt: 'ii'), (filename: 'MovieVariation.dbc'; fmt: 'iii'), (filename: 'NameGen.dbc'; fmt: 'isii'), (filename: 'NamesProfanity.dbc'; fmt: 'isi'), (filename: 'NamesReserved.dbc'; fmt: 'isi'), (filename: 'NPCSounds.dbc'; fmt: 'iiiii'), (filename: 'ObjectEffect.dbc'; fmt: 'isiiiiiififi'), (filename: 'ObjectEffectGroup.dbc'; fmt: 'is'), (filename: 'ObjectEffectModifier.dbc'; fmt: 'iiiiffff'), (filename: 'ObjectEffectPackage.dbc'; fmt: 'is'), (filename: 'ObjectEffectPackageElem.dbc'; fmt: 'iiii'), (filename: 'OverrideSpellData.dbc'; fmt: 'iiiiiiiiiiii'), (filename: 'Package.dbc'; fmt: 'iiissssssssssssssssi'), (filename: 'PageTextMaterial.dbc'; fmt: 'is'), (filename: 'PaperDollItemFrame.dbc'; fmt: 'ssi'), (filename: 'ParticleColor.dbc'; fmt: 'ibbbbbbbbb'), (filename: 'PetitionType.dbc'; fmt: 'isi'), (filename: 'PetPersonality.dbc'; fmt: 'issssssssssssssssiiiffff'), (filename: 'PowerDisplay.dbc'; fmt: 'iiiiii'), (filename: 'PvpDifficulty.dbc'; fmt: 'iiiiii'), (filename: 'QuestFactionReward.dbc'; fmt: 'iiiiiiiiiii'), (filename: 'QuestInfo.dbc'; fmt: 'issssssssssssssssi'), (filename: 'QuestSort.dbc'; fmt: 'issssssssssssssssi'), (filename: 'QuestXP.dbc'; fmt: 'iiiiiiiiiii'), (filename: 'RandPropPoints.dbc'; fmt: 'iiiiiiiiiiiiiiii'), (filename: 'Resistances.dbc'; fmt: 'iiissssssssssssssssi'), (filename: 'ScalingStatDistribution.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiii'), (filename: 'ScalingStatValues.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'ScreenEffect.dbc'; fmt: 'isiiiiiiii'), (filename: 'ServerMessages.dbc'; fmt: 'issssssssssssssssi'), (filename: 'SheatheSoundLookups.dbc'; fmt: 'iiiiiii'), (filename: 'SkillCostsData.dbc'; fmt: 'iiiii'), (filename: 'SkillLine.dbc'; fmt: 'iiissssssssssssssssissssssssssssssssiissssssssssssssssii'), (filename: 'SkillLineAbility.dbc'; fmt: 'iiiiiiiiiiiiii'), (filename: 'SkillLineCategory.dbc'; fmt: 'issssssssssssssssii'), (filename: 'SkillRaceClassInfo.dbc'; fmt: 'iiiiiiii'), (filename: 'SkillTiers.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'SoundAmbience.dbc'; fmt: 'iii'), (filename: 'SoundEmitters.dbc'; fmt: 'iffffffiis'), (filename: 'SoundEntries.dbc'; fmt: 'iisssssssssssiiiiiiiiiisfiffii'), (filename: 'SoundEntriesAdvanced.dbc'; fmt: 'iifiiiiiiiiifffiiiiffffs'), (filename: 'SoundFilter.dbc'; fmt: 'is'), (filename: 'SoundFilterElem.dbc'; fmt: 'iiiifffffffff'), (filename: 'SoundProviderPreferences.dbc'; fmt: 'isiifffiifififffifffffff'), (filename: 'SoundSamplePreferences.dbc'; fmt: 'iiiiiifffffffffff'), (filename: 'SoundWaterType.dbc'; fmt: 'iiii'), (filename: 'SpamMessages.dbc'; fmt: 'is'), (filename: 'Spell.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiifiiiiiiiiiiiiiiiiiiiiiiiiiiiiifffiiiiiiiiiiiiiiiiiiiiifffiiiiiiiiiiiiiiifffiiiiiiiiiiiiiissssssssssssssssissssssssssssssssiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiifffiiiiiiiiiiiiiii'), (filename: 'SpellCastTimes.dbc'; fmt: 'iiii'), (filename: 'SpellCategory.dbc'; fmt: 'ii'), (filename: 'SpellChainEffects.dbc'; fmt: 'iiiiiiisiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'SpellDescriptionVariables.dbc'; fmt: 'is'), (filename: 'SpellDifficulty.dbc'; fmt: 'iiiii'), (filename: 'SpellDispelType.dbc'; fmt: 'issssssssssssssssiiis'), (filename: 'SpellDuration.dbc'; fmt: 'iiii'), (filename: 'SpellEffectCameraShakes.dbc'; fmt: 'iiii'), (filename: 'SpellFocusObject.dbc'; fmt: 'issssssssssssssssi'), (filename: 'SpellIcon.dbc'; fmt: 'is'), (filename: 'SpellItemEnchantment.dbc'; fmt: 'iiiiiiiiiiiiiissssssssssssssssiiiiiiii'), (filename: 'SpellItemEnchantmentCondition.dbc'; fmt: 'ibbbbbiiiiibbbbbbbbbbiiiiibbbbb'), (filename: 'SpellMechanic.dbc'; fmt: 'issssssssssssssssi'), (filename: 'SpellMissile.dbc'; fmt: 'iiffffffffffffi'), (filename: 'SpellMissileMotion.dbc'; fmt: 'issii'), (filename: 'SpellRadius.dbc'; fmt: 'ifif'), (filename: 'SpellRange.dbc'; fmt: 'iffffissssssssssssssssissssssssssssssssi'), (filename: 'SpellRuneCost.dbc'; fmt: 'iiiii'), (filename: 'SpellShapeshiftForm.dbc'; fmt: 'iissssssssssssssssiiiiiiiiiiiiiiiii'), (filename: 'SpellVisual.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii'), (filename: 'SpellVisualEffectName.dbc'; fmt: 'issffff'), (filename: 'SpellVisualKit.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiiffffffffffffffii'), (filename: 'SpellVisualKitAreaModel.dbc'; fmt: 'iii'), (filename: 'SpellVisualKitModelAttach.dbc'; fmt: 'iiiiiiiiii'), (filename: 'SpellVisualPrecastTransitions.dbc'; fmt: 'iss'), (filename: 'StableSlotPrices.dbc'; fmt: 'ii'), (filename: 'Startup_Strings.dbc'; fmt: 'isssssssssssssssssi'), (filename: 'Stationery.dbc'; fmt: 'iisi'), (filename: 'StringLookups.dbc'; fmt: 'is'), (filename: 'SummonProperties.dbc'; fmt: 'iiiiii'), (filename: 'Talent.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiii'), (filename: 'TalentTab.dbc'; fmt: 'issssssssssssssssiiiiiis'), (filename: 'TaxiNodes.dbc'; fmt: 'iifffssssssssssssssssiii'), (filename: 'TaxiPath.dbc'; fmt: 'iiii'), (filename: 'TaxiPathNode.dbc'; fmt: 'iiiifffiiii'), (filename: 'TeamContributionPoints.dbc'; fmt: 'if'), (filename: 'TerrainType.dbc'; fmt: 'isiiii'), (filename: 'TerrainTypeSounds.dbc'; fmt: 'i'), (filename: 'TotemCategory.dbc'; fmt: 'issssssssssssssssiii'), (filename: 'TransportAnimation.dbc'; fmt: 'iiifffi'), (filename: 'TransportPhysics.dbc'; fmt: 'iffffffffff'), (filename: 'TransportRotation.dbc'; fmt: 'iiiffff'), (filename: 'UISoundLookups.dbc'; fmt: 'iis'), (filename: 'UnitBlood.dbc'; fmt: 'iiiiissssi'), (filename: 'UnitBloodLevels.dbc'; fmt: 'iiii'), (filename: 'Vehicle.dbc'; fmt: 'iiffffiiiiiiiifffffffffffffffiiiififiiii'), (filename: 'VehicleSeat.dbc'; fmt: 'iiiffffffffffiiiiiiiffffffiiifffiiiiiiiffiiiiiiiiiiiiiiiii'), (filename: 'VehicleUIIndicator.dbc'; fmt: 'ii'), (filename: 'VehicleUIIndSeat.dbc'; fmt: 'iiiff'), (filename: 'VideoHardware.dbc'; fmt: 'iiiiiiiiiiiiiiiiiissiii'), (filename: 'VocalUISounds.dbc'; fmt: 'iiiiiii'), (filename: 'WeaponImpactSounds.dbc'; fmt: 'iiiiiiiiiiiiiiiiiiiiiii'), (filename: 'WeaponSwingSounds2.dbc'; fmt: 'iiii'), (filename: 'Weather.dbc'; fmt: 'iiiffffs'), (filename: 'WMOAreaTable.dbc'; fmt: 'iiiiiiiiiiissssssssssssssssi'), (filename: 'WorldChunkSounds.dbc'; fmt: 'iiiiiiiii'), (filename: 'WorldMapArea.dbc'; fmt: 'iiisffffiii'), (filename: 'WorldMapContinent.dbc'; fmt: 'iiiiiifffffffi'), (filename: 'WorldMapOverlay.dbc'; fmt: 'iiiiiiiisiiiiiiii'), (filename: 'WorldMapTransforms.dbc'; fmt: 'iiffffiffi'), (filename: 'WorldSafeLocs.dbc'; fmt: 'iifffssssssssssssssssi'), (filename: 'WorldStateUI.dbc'; fmt: 'iiiisssssssssssssssssissssssssssssssssiiiissssssssssssssssiiiii'), (filename: 'WorldStateZoneSounds.dbc'; fmt: 'iiiiiiii'), (filename: 'WowError_Strings.dbc'; fmt: 'isssssssssssssssssi'), (filename: 'ZoneIntroMusicTable.dbc'; fmt: 'isiii'), (filename: 'ZoneMusic.dbc'; fmt: 'isiiiiii') ); implementation uses MyDataModule; procedure assert(Expr: boolean); begin if not Expr then raise Exception.Create('Incorrect field number'); end; { TDBCFile } constructor TDBCFile.Create; begin data := NIL; fieldsOffset := NIL; IsLocalized := true; end; destructor TDBCFile.Destroy; begin if Assigned(data) then FreeMem(data); if Assigned(fieldsOffset) then SetLength(fieldsOffset,0); inherited; end; function TDBCFile.GetCols: Cardinal; begin Result := fieldCount; end; function TDBCFile.GetNumRows: Cardinal; begin Result := recordCount; end; function TDBCFile.GetOffset(id: Cardinal): Cardinal; begin if (fieldsOffset <> nil) and (id<fieldCount) then Result := fieldsOffset[id] else Result := 0; end; procedure TDBCFile.setRecord(id: Cardinal); begin offset := pchar(Cardinal(data) + id * recordSize); end; function TDBCFile.IsLoaded: boolean; begin Result := data <> nil; end; function SwapEndian(Value: integer): integer; register; overload; asm bswap eax end; function SwapEndian(Value: smallint): smallint; register; overload; asm xchg al, ah end; function TDBCFile.Load(filename: WideString): boolean; var header, i: Cardinal; f: Integer; fmt: PArray; tmp: String; begin if Assigned(data) then begin FreeMem(data); data := nil; end; f := FileOpen(filename, fmOpenRead); if f = -1 then begin Result := false; Exit; end; FileRead(f, header, 4); if header <> $43424457 then begin Result := false; Exit; end; for i:= 0 to High(DBCFileStruct) do begin if DBCFileStruct[i].filename = ExtractFileName(filename) then begin tmp := DBCFileStruct[i].fmt; SetLength(fmt, Length(tmp)); CopyMemory(@fmt[low(fmt)], @tmp[1], sizeof(fmt)); break; end; end; if fmt = nil then begin ShowMessage('Fatal Error - Couldn''t read DBC Format for file '+filename+#10#13#10#13+tmp); Result := false; Exit; end; FileRead(F, recordCount, 4); SwapEndian(recordCount); FileRead(F, fieldCount, 4); SwapEndian(fieldCount); FileRead(F, recordSize, 4); SwapEndian(recordSize); FileRead(F, stringSize, 4); SwapEndian(stringSize); SetLength(fieldsOffset, fieldCount+1); //ShowMessage('RC:'+IntToStr(recordCount)+' FC:'+IntToStr(fieldCount)+' RS:'+IntToStr(recordSize)+' FOS:'+IntToStr(High(fmt))); fieldsOffset[0] := 0; for i := 1 to fieldCount do begin fieldsOffset[i] := fieldsOffset[i-1]; if (fmt[i-1] = 'b') OR (fmt[i-1] = 'X') then inc(fieldsOffset[i],1) else inc(fieldsOffset[i],4); end; data := PChar(AllocMem(recordSize*recordCount + stringSize + 1)); stringTable := pointer( Cardinal(data) + recordSize*recordCount); FileRead(F, data^, recordSize*recordCount+stringSize); FileClose(F); Result := True; end; { TRecord } function TDBCFile.getFloat(field: Cardinal): Single; begin assert(field < fieldCount); CopyMemory(@Result, offset + GetOffset(field), SizeOf(Result)); end; function TDBCFile.getPChar(field: Cardinal): PChar; var stringOffset : Cardinal; fieldid: Cardinal; i: Cardinal; begin if dmMain.DBCLocale < 16 then begin if IsLocalized then fieldid := field + dmMain.DBCLocale else fieldid := field; assert(fieldid < fieldCount); stringOffset := getUInt(fieldid); assert(stringOffset < stringSize); Result := stringTable + stringOffset; end else begin // Autodetect DBC Locale for I := 0 to 15 do begin fieldid := field + I; assert(fieldid < fieldCount); stringOffset := getUInt(fieldid); assert(stringOffset < stringSize); Result := stringTable + stringOffset; if Result<>'' then begin dmMain.DBCLocale := I; Exit; end; end; end; end; function TDBCFile.getString(field: Cardinal): WideString; var s: WideString; begin s := getPChar(field); Result := UTF8ToString(@Pointer(s)); end; function TDBCFile.getUInt(field: Cardinal): Cardinal; begin assert(field < fieldCount); //ShowMessage('Field: ' + IntToStr(field) + ' Data: ' + (offset + GetOffset(field))); CopyMemory(@Result, offset + GetOffset(field), sizeof(Result)); end; function TDBCFile.getUInt8(field: Cardinal): Byte; begin assert(field < fieldCount); CopyMemory(@Result, offset + GetOffset(field), SizeOf(Result)); end; end.
unit uCnvDictionary; interface {$IFNDEF VER130} {$IF CompilerVersion >= 21.0} {$DEFINE HAS_GENERICS} {$IFEND} {$ENDIF} uses {$IFDEF HAS_GENERICS}System.Generics.Collections{$ELSE}HashTrie{$ENDIF}, Windows; type (* AValue can be primitive wrapper(use if (AValue is TPrimitiveWrapper) then to check) then you can access value: TStringWrapper(AValue).Value TIntegerWrapper(AValue).Value etc. *) TCnvStringDictionaryEnumerateCallback = procedure(const AKey: string; const AValue: TObject) of object; TCnvIntegerDictionaryEnumerateCallback = procedure(const AKey: Integer; const AValue: TObject) of object; (* Associative array with string key implementation *) TCnvStringDictionary = class private FDic: {$IFDEF HAS_GENERICS}TDictionary<string, TObject>{$ELSE}TStringHashTrie{$ENDIF}; FUserEnumerateCallback: TCnvStringDictionaryEnumerateCallback; {$IFNDEF HAS_GENERICS} procedure EnumerateCallback(UserData: Pointer; Value: PChar; Data: TObject; var Done: Boolean); {$ENDIF} public constructor Create(AAutoFreeObjects: Boolean = false); destructor Destroy; override; procedure AddOrSetValue(const AKey: string; const AValue: TObject); overload; procedure AddOrSetValue(const AKey: string; const AValue: string); overload; procedure AddOrSetValue(const AKey: string; const AValue: Integer); overload; procedure AddOrSetValue(const AKey: string; const AValue: Int64); overload; procedure AddOrSetValue(const AKey: string; const AValue: Double); overload; procedure AddOrSetValue(const AKey: string; const AValue: Boolean); overload; procedure AddOrSetValueDate(const AKey: string; const AValue: TDateTime); procedure Remove(const AKey: string); function TryGetValue(const AKey: string; out AValue: TObject): Boolean; overload; function TryGetValue(const AKey: string; out AValue: string): Boolean; overload; function TryGetValue(const AKey: string; out AValue: Integer): Boolean; overload; function TryGetValue(const AKey: string; out AValue: Int64): Boolean; overload; function TryGetValue(const AKey: string; out AValue: Double): Boolean; overload; function TryGetValue(const AKey: string; out AValue: Boolean): Boolean; overload; function TryGetValueDate(const AKey: string; out AValue: TDateTime): Boolean; function ContainsKey(const AKey: string): Boolean; procedure Clear; procedure Foreach(ACallback: TCnvStringDictionaryEnumerateCallback); end; (* Associative array with integer key implementation *) TCnvIntegerDictionary = class private FDic: {$IFDEF HAS_GENERICS}TDictionary<Integer, TObject>{$ELSE}TIntegerHashTrie{$ENDIF}; FUserEnumerateCallback: TCnvIntegerDictionaryEnumerateCallback; {$IFNDEF HAS_GENERICS} procedure EnumerateCallback(UserData: Pointer; Value: Integer; Data: TObject; var Done: Boolean); {$ENDIF} public constructor Create(AAutoFreeObjects: Boolean = false); destructor Destroy; override; procedure AddOrSetValue(const AKey: Integer; const AValue: TObject); overload; procedure AddOrSetValue(const AKey: Integer; const AValue: string); overload; procedure AddOrSetValue(const AKey: Integer; const AValue: Integer); overload; procedure AddOrSetValue(const AKey: Integer; const AValue: Int64); overload; procedure AddOrSetValue(const AKey: Integer; const AValue: Double); overload; procedure AddOrSetValue(const AKey: Integer; const AValue: Boolean); overload; procedure AddOrSetValueDate(const AKey: Integer; const AValue: TDateTime); procedure Remove(const AKey: Integer); function TryGetValue(const AKey: Integer; out AValue: TObject): Boolean; overload; function TryGetValue(const AKey: Integer; out AValue: string): Boolean; overload; function TryGetValue(const AKey: Integer; out AValue: Integer): Boolean; overload; function TryGetValue(const AKey: Integer; out AValue: Int64): Boolean; overload; function TryGetValue(const AKey: Integer; out AValue: Double): Boolean; overload; function TryGetValue(const AKey: Integer; out AValue: Boolean): Boolean; overload; function TryGetValueDate(const AKey: Integer; out AValue: TDateTime): Boolean; function ContainsKey(const AKey: Integer): Boolean; procedure Clear; procedure Foreach(ACallback: TCnvIntegerDictionaryEnumerateCallback); end; (* wrapper classes to support primitives(assigned to TObject) *) TPrimitiveWrapper = class end; TStringWrapper = class(TPrimitiveWrapper) private FValue: string; public constructor Create(AValue: string); property Value: string read FValue write FValue; end; TIntegerWrapper = class(TPrimitiveWrapper) private FValue: Integer; public constructor Create(AValue: Integer); property Value: Integer read FValue write FValue; end; TInt64Wrapper = class(TPrimitiveWrapper) private FValue: Int64; public constructor Create(AValue: Int64); property Value: Int64 read FValue write FValue; end; TDoubleWrapper = class(TPrimitiveWrapper) private FValue: Extended; public constructor Create(AValue: Extended); property Value: Extended read FValue write FValue; end; TBooleanWrapper = class(TPrimitiveWrapper) private FValue: Boolean; public constructor Create(AValue: Boolean); property Value: Boolean read FValue write FValue; end; TDateTimeWrapper = class(TPrimitiveWrapper) private FValue: TDateTime; public constructor Create(AValue: TDateTime); property Value: TDateTime read FValue write FValue; end; implementation { TCnvStringDictionary } constructor TCnvStringDictionary.Create(AAutoFreeObjects: Boolean); {$IFDEF HAS_GENERICS} var ownerships: TDictionaryOwnerships; {$ENDIF} begin {$IFDEF HAS_GENERICS} if AAutoFreeObjects then ownerships := [doOwnsValues] else ownerships := []; FDic := TObjectDictionary<string, TObject>.Create(ownerships); {$ELSE} FDic := TStringHashTrie.Create; FDic.AutoFreeObjects := AAutoFreeObjects; {$ENDIF} end; destructor TCnvStringDictionary.Destroy; begin FDic.Free; inherited; end; {$IFNDEF HAS_GENERICS} procedure TCnvStringDictionary.EnumerateCallback(UserData: Pointer; Value: PChar; Data: TObject; var Done: Boolean); begin FUserEnumerateCallback(Value, Data); end; {$ENDIF} procedure TCnvStringDictionary.Foreach(ACallback: TCnvStringDictionaryEnumerateCallback); {$IFDEF HAS_GENERICS} var key: string; {$ENDIF} begin FUserEnumerateCallback := ACallback; {$IFDEF HAS_GENERICS} for key in FDic.Keys do FUserEnumerateCallback(key, FDic.Items[key]); {$ELSE} FDic.Traverse(nil, EnumerateCallback); {$ENDIF} end; procedure TCnvStringDictionary.AddOrSetValue(const AKey: string; const AValue: TObject); begin {$IFDEF HAS_GENERICS} FDic.AddOrSetValue(AKey, AValue); {$ELSE} FDic.Add(AKey, AValue); {$ENDIF} end; procedure TCnvStringDictionary.AddOrSetValue(const AKey: string; const AValue: Integer); begin AddOrSetValue(AKey, TIntegerWrapper.Create(AValue)); end; procedure TCnvStringDictionary.AddOrSetValue(const AKey, AValue: string); begin AddOrSetValue(AKey, TStringWrapper.Create(AValue)); end; procedure TCnvStringDictionary.AddOrSetValue(const AKey: string; const AValue: Boolean); begin AddOrSetValue(AKey, TBooleanWrapper.Create(AValue)); end; procedure TCnvStringDictionary.AddOrSetValueDate(const AKey: string; const AValue: TDateTime); begin AddOrSetValue(AKey, TDateTimeWrapper.Create(AValue)); end; procedure TCnvStringDictionary.AddOrSetValue(const AKey: string; const AValue: Int64); begin AddOrSetValue(AKey, TInt64Wrapper.Create(AValue)); end; procedure TCnvStringDictionary.AddOrSetValue(const AKey: string; const AValue: Double); begin AddOrSetValue(AKey, TDoubleWrapper.Create(AValue)); end; procedure TCnvStringDictionary.Clear; begin FDic.Clear; end; function TCnvStringDictionary.ContainsKey(const AKey: string): Boolean; {$IFNDEF HAS_GENERICS} var stub: TObject; {$ENDIF} begin {$IFDEF HAS_GENERICS} Result := FDic.ContainsKey(AKey); {$ELSE} Result := FDic.Find(AKey, stub); {$ENDIF} end; procedure TCnvStringDictionary.Remove(const AKey: string); begin {$IFDEF HAS_GENERICS} FDic.Remove(AKey); {$ELSE} FDic.Delete(AKey); {$ENDIF} end; function TCnvStringDictionary.TryGetValue(const AKey: string; out AValue: TObject): Boolean; begin {$IFDEF HAS_GENERICS} Result := FDic.TryGetValue(AKey, AValue); {$ELSE} Result := FDic.Find(AKey, AValue); {$ENDIF} end; function TCnvStringDictionary.TryGetValue(const AKey: string; out AValue: Integer): Boolean; var wrap: TIntegerWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvStringDictionary.TryGetValue(const AKey: string; out AValue: string): Boolean; var wrap: TStringWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvStringDictionary.TryGetValue(const AKey: string; out AValue: Int64): Boolean; var wrap: TInt64Wrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvStringDictionary.TryGetValue(const AKey: string; out AValue: Double): Boolean; var wrap: TDoubleWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvStringDictionary.TryGetValue(const AKey: string; out AValue: Boolean): Boolean; var wrap: TBooleanWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvStringDictionary.TryGetValueDate(const AKey: string; out AValue: TDateTime): Boolean; var wrap: TDateTimeWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; { TCnvIntegerDictionary } procedure TCnvIntegerDictionary.AddOrSetValue(const AKey: Integer; const AValue: TObject); begin {$IFDEF HAS_GENERICS} FDic.AddOrSetValue(AKey, AValue); {$ELSE} FDic.Add(AKey, AValue); {$ENDIF} end; procedure TCnvIntegerDictionary.AddOrSetValue(const AKey, AValue: Integer); begin AddOrSetValue(AKey, TIntegerWrapper.Create(AValue)); end; procedure TCnvIntegerDictionary.AddOrSetValue(const AKey: Integer; const AValue: string); begin AddOrSetValue(AKey, TStringWrapper.Create(AValue)); end; procedure TCnvIntegerDictionary.AddOrSetValue(const AKey: Integer; const AValue: Boolean); begin AddOrSetValue(AKey, TBooleanWrapper.Create(AValue)); end; procedure TCnvIntegerDictionary.AddOrSetValueDate(const AKey: Integer; const AValue: TDateTime); begin AddOrSetValue(AKey, TDateTimeWrapper.Create(AValue)); end; procedure TCnvIntegerDictionary.AddOrSetValue(const AKey: Integer; const AValue: Int64); begin AddOrSetValue(AKey, TInt64Wrapper.Create(AValue)); end; procedure TCnvIntegerDictionary.AddOrSetValue(const AKey: Integer; const AValue: Double); begin AddOrSetValue(AKey, TDoubleWrapper.Create(AValue)); end; procedure TCnvIntegerDictionary.Clear; begin FDic.Clear; end; function TCnvIntegerDictionary.ContainsKey(const AKey: Integer): Boolean; {$IFNDEF HAS_GENERICS} var stub: TObject; {$ENDIF} begin {$IFDEF HAS_GENERICS} Result := FDic.ContainsKey(AKey); {$ELSE} Result := FDic.Find(AKey, stub); {$ENDIF} end; constructor TCnvIntegerDictionary.Create(AAutoFreeObjects: Boolean); {$IFDEF HAS_GENERICS} var ownerships: TDictionaryOwnerships; {$ENDIF} begin {$IFDEF HAS_GENERICS} if AAutoFreeObjects then ownerships := [doOwnsValues] else ownerships := []; FDic := TObjectDictionary<Integer, TObject>.Create(ownerships); {$ELSE} FDic := TIntegerHashTrie.Create; FDic.AutoFreeObjects := AAutoFreeObjects; {$ENDIF} end; destructor TCnvIntegerDictionary.Destroy; begin FDic.Free; inherited; end; {$IFNDEF HAS_GENERICS} procedure TCnvIntegerDictionary.EnumerateCallback(UserData: Pointer; Value: Integer; Data: TObject; var Done: Boolean); begin FUserEnumerateCallback(Value, Data); end; {$ENDIF} procedure TCnvIntegerDictionary.Foreach( ACallback: TCnvIntegerDictionaryEnumerateCallback); {$IFDEF HAS_GENERICS} var key: Integer; {$ENDIF} begin FUserEnumerateCallback := ACallback; {$IFDEF HAS_GENERICS} for key in FDic.Keys do FUserEnumerateCallback(key, FDic.Items[key]); {$ELSE} FDic.Traverse(nil, EnumerateCallback); {$ENDIF} end; procedure TCnvIntegerDictionary.Remove(const AKey: Integer); begin {$IFDEF HAS_GENERICS} FDic.Remove(AKey); {$ELSE} FDic.Delete(AKey); {$ENDIF} end; function TCnvIntegerDictionary.TryGetValue(const AKey: Integer; out AValue: TObject): Boolean; begin {$IFDEF HAS_GENERICS} Result := FDic.TryGetValue(AKey, AValue); {$ELSE} Result := FDic.Find(AKey, AValue); {$ENDIF} end; function TCnvIntegerDictionary.TryGetValue(const AKey: Integer; out AValue: Integer): Boolean; var wrap: TIntegerWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvIntegerDictionary.TryGetValue(const AKey: Integer; out AValue: string): Boolean; var wrap: TStringWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvIntegerDictionary.TryGetValue(const AKey: Integer; out AValue: Int64): Boolean; var wrap: TInt64Wrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvIntegerDictionary.TryGetValue(const AKey: Integer; out AValue: Double): Boolean; var wrap: TDoubleWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvIntegerDictionary.TryGetValue(const AKey: Integer; out AValue: Boolean): Boolean; var wrap: TBooleanWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; function TCnvIntegerDictionary.TryGetValueDate(const AKey: Integer; out AValue: TDateTime): Boolean; var wrap: TDateTimeWrapper; begin Result := TryGetValue(AKey, TObject(wrap)) and (wrap <> nil); if Result then AValue := wrap.Value; end; { TStringWrapper } constructor TStringWrapper.Create(AValue: string); begin FValue := AValue; end; { TIntegerWrapper } constructor TIntegerWrapper.Create(AValue: Integer); begin FValue := AValue; end; { TInt64Wrapper } constructor TInt64Wrapper.Create(AValue: Int64); begin FValue := AValue; end; { TDoubleWrapper } constructor TDoubleWrapper.Create(AValue: Extended); begin FValue := AValue; end; { TBooleanWrapper } constructor TBooleanWrapper.Create(AValue: Boolean); begin FValue := AValue; end; { TDateTimeWrapper } constructor TDateTimeWrapper.Create(AValue: TDateTime); begin FValue := AValue; end; end.
unit MqttDbServer; interface {$I mormot.defines.inc} uses sysutils, classes, variants, contnrs, mormot.core.base, mormot.core.os, mormot.core.data, mormot.core.text, mormot.core.log, mormot.core.json, mormot.rest.sqlite3, mormot.db.raw.sqlite3, mormot.rest.server, mormot.rest.core, mormot.orm.core, MqttService; type TSQLRecordTimeStamped = class(TOrm) private fCreatedAt: TCreateTime; fModifiedAt: TModTime; published property CreatedAt: TCreateTime read fCreatedAt write fCreatedAt; property ModifiedAt: TModTime read fModifiedAt write fModifiedAt; end; TSQLMessage = class(TSQLRecordTimeStamped) private fTitle,fBody:RawByteString; public published property Title: RawByteString read fTitle write fTitle; property Body: RawByteString read fBody write fBody; end; TMQTTHttpServer = class(TSQLRestServerDB) protected fmqttserver:TMQTTServer; function OnBeforeIrData(Ctxt: TRestServerUriContext): boolean; procedure OnAfterExecProc(Ctxt: TRestServerUriContext); public constructor MyCreate(aModel:TOrmModel;mqttserver:TMQTTServer;const aDBFileName: TFileName); published procedure getclients(Ctxt: TRestServerUriContext); procedure getclientcount(Ctxt: TRestServerUriContext); procedure getblackip(Ctxt: TRestServerUriContext); end; function CreateMyModel: TOrmModel; implementation function CreateMyModel: TOrmModel; begin result := TOrmModel.Create([TSQLMessage],'root'); Result.SetCustomCollationForAll(oftUtf8Text,'NOCASE'); end; { TMQTTHttpServer } procedure TMQTTHttpServer.getblackip(Ctxt: TRestServerUriContext); var i:integer; //sstr:ShortString; begin fmqttserver.BlackBook.Safe.Lock; try //sstr := PPShortString(PPAnsiChar(fmqttserver.BlackBook)^ + vmtClassName)^^; Ctxt.Returns(fmqttserver.BlackBook); finally fmqttserver.BlackBook.Safe.Unlock; end; end; procedure TMQTTHttpServer.getclientcount(Ctxt: TRestServerUriContext); begin fmqttserver.Lock; try Ctxt.Returns(Int32ToUtf8(fmqttserver.ConnectionCount)); finally fmqttserver.Unlock; end; end; procedure TMQTTHttpServer.getclients(Ctxt: TRestServerUriContext); begin fmqttserver.Lock; try Ctxt.Returns(ObjArrayToJson(fmqttserver.Connection,[woDontStoreDefault,woEnumSetsAsText])); finally fmqttserver.Unlock; end; end; constructor TMQTTHttpServer.MyCreate(aModel:TOrmModel;mqttserver:TMQTTServer;const aDBFileName: TFileName); begin inherited Create(aModel,aDBFileName,false); fmqttserver := mqttserver; // OnBeforeURI := {$ifdef FPC}@{$endif}OnBeforeIrData; // OnAfterURI := {$ifdef FPC}@{$endif}OnAfterExecProc; // ServiceDefine(TServiceCalculator,[ICalculator],sicShared); end; procedure TMQTTHttpServer.OnAfterExecProc(Ctxt: TRestServerUriContext); begin // end; function TMQTTHttpServer.OnBeforeIrData(Ctxt: TRestServerUriContext): boolean; begin Result := (fmqttserver<>nil); end; end.
unit ThreadTestCase; interface uses TestFramework, Classes, Windows, ZmqIntf; type TMyZMQThread = class(TInterfacedObject) private FThread: IZMQThread; tvar: Boolean; protected procedure DoExecute(AThread: TObject); public constructor Create(lArgs: Pointer; const ctx: IZMQContext); destructor Destroy; override; property Thread: IZMQThread read FThread; end; TThreadTestCase = class( TTestCase ) private context: IZMQContext; tvar: Boolean; tmpS: WideString; public myThr: TMyZMQThread; procedure SetUp; override; procedure TearDown; override; procedure DetachedTestMeth( args: Pointer; const context: IZMQContext ); procedure AttachedTestMeth( args: Pointer; const context: IZMQContext; const pipe: PZMQSocket ); procedure AttachedPipeTestMeth( args: Pointer; const context: IZMQContext; const pipe: PZMQSocket ); procedure InheritedThreadTerminate( Sender: TObject ); published procedure CreateAttachedTest; procedure CreateDetachedTest; procedure CreateInheritedAttachedTest; procedure CreateInheritedDetachedTest; procedure AttachedPipeTest; end; implementation uses Sysutils ; var ehandle: THandle; { TMyZMQThread } constructor TMyZMQThread.Create(lArgs: Pointer; const ctx: IZMQContext); begin FThread := ZMQ.CreateThread(lArgs, ctx); FThread.OnExecute := DoExecute; end; destructor TMyZMQThread.Destroy; begin FThread := nil; inherited; end; procedure TMyZMQThread.doExecute; begin // custom code. tvar := true; SetEvent( ehandle ); end; { TThreadTestCase } procedure TThreadTestCase.SetUp; begin inherited; ehandle := CreateEvent( nil, true, false, nil ); context := ZMQ.CreateContext; tvar := false; end; procedure TThreadTestCase.TearDown; begin inherited; context := nil; CloseHandle( ehandle ); end; procedure TThreadTestCase.AttachedTestMeth( args: Pointer; const context: IZMQContext; const pipe: PZMQSocket ); begin tvar := true; SetEvent( ehandle ); end; procedure TThreadTestCase.CreateAttachedTest; var thr: IZMQThread; begin thr := ZMQ.CreateAttached( AttachedTestMeth, context, nil ); thr.FreeOnTerminate := true; thr.Resume; WaitForSingleObject( ehandle, INFINITE ); CheckEquals( true, tvar, 'tvar didn''t set' ); end; procedure TThreadTestCase.DetachedTestMeth( args: Pointer; const context: IZMQContext ); begin tvar := true; context.Socket( TZMQSocketType( Args^ ) ); Dispose( args ); SetEvent( ehandle ); end; procedure TThreadTestCase.CreateDetachedTest; var thr: IZMQThread; sockettype: ^TZMQSocketType; begin New( sockettype ); sockettype^ := stDealer; thr := ZMQ.CreateDetached( DetachedTestMeth, sockettype ); thr.FreeOnTerminate := true; thr.Resume; WaitForSingleObject( ehandle, INFINITE ); CheckEquals( true, tvar, 'tvar didn''t set' ); end; procedure TThreadTestCase.InheritedThreadTerminate( Sender: TObject ); begin // this executes in the main thread. tvar := myThr.tvar; end; procedure TThreadTestCase.CreateInheritedAttachedTest; begin mythr := TMyZMQThread.Create( nil, context ); mythr.Thread.OnTerminate := InheritedThreadTerminate; mythr.Thread.Resume; WaitForSingleObject( ehandle, INFINITE ); sleep(10); mythr.Free; CheckEquals( true, tvar, 'tvar didn''t set' ); end; procedure TThreadTestCase.CreateInheritedDetachedTest; begin mythr := TMyZMQThread.Create( nil, nil ); mythr.Thread.OnTerminate := InheritedThreadTerminate; mythr.Thread.Resume; WaitForSingleObject( ehandle, INFINITE ); mythr.Free; CheckEquals( true, tvar, 'tvar didn''t set' ); end; procedure TThreadTestCase.AttachedPipeTestMeth(args: Pointer; const context: IZMQContext; const pipe: PZMQSocket ); begin pipe.RecvString( tmpS ); SetEvent( ehandle ); end; procedure TThreadTestCase.AttachedPipeTest; var thr: IZMQThread; begin thr := ZMQ.CreateAttached( AttachedPipeTestMeth, context, nil ); thr.FreeOnTerminate := true; thr.Resume; thr.pipe.SendString( 'hello pipe' ); WaitForSingleObject( ehandle, INFINITE ); CheckEquals( 'hello pipe', tmpS, 'pipe error' ); end; initialization RegisterTest(TThreadTestCase.Suite); end.
unit CommonIDObjectComboFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, BaseObjects, CommonIDObjectListForm; type TfrmIDObjectCombo = class(TFrame) cmbxName: TComboBox; btnShowAdditional: TButton; lblName: TStaticText; procedure cmbxNameChange(Sender: TObject); procedure btnShowAdditionalClick(Sender: TObject); private { Private declarations } FLoadedList: TIDObjects; FIsEditable: Boolean; FEditorForm: TfrmIDObjectList; FEditorFormClass: TfrmIDObjectListFormClass; FMultipleSelect: Boolean; FSelectedObjects: TIDObjects; procedure SetLoadedList(const Value: TIDObjects); procedure CreateForm; procedure SetMultipleSelect(const Value: Boolean); function GetCaption: string; procedure SetCaption(const Value: string); function GetSelectedObject: TIDObject; procedure SetSelectedObject(const Value: TIDObject); procedure SetSelectedObjects(const Value: TIDObjects); protected procedure ReloadList; virtual; procedure SetEnabled(Value: Boolean); override; public { Public declarations } property LoadedList: TIDObjects read FLoadedList write SetLoadedList; property IsEditable: Boolean read FIsEditable write FIsEditable; property Caption: string read GetCaption write SetCaption; property MultipleSelect: Boolean read FMultipleSelect write SetMultipleSelect; property SelectedObjects: TIDObjects read FSelectedObjects write SetSelectedObjects; property SelectedObject: TIDObject read GetSelectedObject write SetSelectedObject; procedure Clear; property EditorFormClass: TfrmIDObjectListFormClass read FEditorFormClass write FEditorFormClass; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation {$R *.dfm} { TfrmIDObjectCombo } constructor TfrmIDObjectCombo.Create(AOwner: TComponent); begin inherited; FEditorFormClass := TfrmIDObjectList; FSelectedObjects := TIDObjects.Create; FSelectedObjects.OwnsObjects := False; IsEditable := true; end; procedure TfrmIDObjectCombo.CreateForm; begin if not Assigned(FEditorForm) then FEditorForm := EditorFormClass.Create(Self); FEditorForm.IDObjects := LoadedList; FEditorForm.MultiSelect := MultipleSelect; FEditorForm.SelectedObjects := SelectedObjects; FEditorForm.IsEditable := IsEditable; FEditorForm.ModalResult := mrOk; end; destructor TfrmIDObjectCombo.Destroy; begin FSelectedObjects.Free; inherited; end; function TfrmIDObjectCombo.GetCaption: string; begin Result := lblName.Caption; end; function TfrmIDObjectCombo.GetSelectedObject: TIDObject; begin if SelectedObjects.Count > 0 then Result := SelectedObjects.Items[0] else Result := nil; end; procedure TfrmIDObjectCombo.SetCaption(const Value: string); begin lblName.Caption := Value; end; procedure TfrmIDObjectCombo.SetLoadedList(const Value: TIDObjects); begin FLoadedList := Value; ReloadList; end; procedure TfrmIDObjectCombo.SetMultipleSelect(const Value: Boolean); begin FMultipleSelect := Value; if FMultipleSelect then cmbxName.Style := csSimple else cmbxName.Style := csDropDownList; end; procedure TfrmIDObjectCombo.SetSelectedObject(const Value: TIDObject); begin SelectedObjects.Clear; SelectedObjects.Add(Value, false, False); cmbxName.ItemIndex := cmbxName.Items.IndexOfObject(SelectedObjects.Items[0]); end; procedure TfrmIDObjectCombo.cmbxNameChange(Sender: TObject); begin if cmbxName.ItemIndex > -1 then SelectedObject := TIDObject(cmbxName.Items.Objects[cmbxName.ItemIndex]); end; procedure TfrmIDObjectCombo.Clear; begin cmbxName.ItemIndex := -1; SelectedObjects.Clear; end; procedure TfrmIDObjectCombo.btnShowAdditionalClick(Sender: TObject); begin CreateForm; if FEditorForm.ShowModal <> mrNone then begin ReloadList; SelectedObjects := FEditorForm.SelectedObjects; end; end; procedure TfrmIDObjectCombo.ReloadList; var i: integer; begin cmbxName.Items.Clear; for i := 0 to LoadedList.Count - 1 do cmbxName.AddItem(LoadedList.Items[i].List, LoadedList.Items[i]); end; procedure TfrmIDObjectCombo.SetSelectedObjects(const Value: TIDObjects); begin FSelectedObjects.Clear; FSelectedObjects.AddObjects(Value, False, false); ReloadList; if MultipleSelect then cmbxName.Text := FSelectedObjects.List else cmbxName.ItemIndex := cmbxName.Items.IndexOfObject(SelectedObject); end; procedure TfrmIDObjectCombo.SetEnabled(Value: Boolean); begin inherited; cmbxName.Enabled := Value; btnShowAdditional.Enabled := Value; end; end.
unit TCPStreamServerFrmImp; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdContext, StdCtrls, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdSync, Unit_Indy_Classes, Unit_Indy_Functions, Vcl.Imaging.jpeg, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.Buttons, Vcl.Samples.Spin, Vcl.CheckLst, IdStack; type TTCPStreamServerFrm = class(TForm) TCPServer: TIdTCPServer; StatusBar1: TStatusBar; Panel1: TPanel; SpeedButton1: TSpeedButton; Label1: TLabel; EdtPort: TSpinEdit; GroupBox1: TGroupBox; MemoLogs: TMemo; GroupBox2: TGroupBox; MemoMsgs: TMemo; ClbIPs: TCheckListBox; procedure FormCreate(Sender: TObject); procedure ClientConnected; procedure ClientDisconnected; procedure TCPServerExecute(AContext: TIdContext); procedure TCPServerConnect(AContext: TIdContext); procedure TCPServerDisconnect(AContext: TIdContext); procedure FormDestroy(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); private procedure ShowCannotGetBufferErrorMessage; procedure ShowCannotSendBufferErrorMessage; procedure StreamReceived; procedure WMSysCommand(var Msg: TMessage); message WM_SYSCOMMAND; procedure ActiveServer(doConnect : Boolean = True); { Private declarations } public { Public declarations } end; var TCPStreamServerFrm: TTCPStreamServerFrm; //MyErrorMessage: string; implementation {$R *.dfm} uses Unit_DelphiCompilerversionDLG; const ID_INFOCOMPILER = WM_USER + 1; ID_NEWLINE = WM_USER + 4; procedure TTCPStreamServerFrm.ActiveServer(doConnect : Boolean); var i : Integer; begin StatusBar1.Panels[3].Text := EmptyStr; try try if doConnect and TCPServer.Active then raise Exception.Create('The server is running.'); TCPServer.Bindings.Clear; if doConnect then begin for i := 0 to ClbIPs.Items.Count - 1 do begin if ClbIPs.Checked[i] then TCPServer.Bindings.Add.IP := ClbIPs.Items[i]; end; end; TCPServer.Bindings.Add.Port := EdtPort.Value; TCPServer.Active := doConnect; except on e : exception do begin MemoLogs.Lines.Add(e.Message) end; end; finally if TCPServer.Active then StatusBar1.Panels[3].Text := 'Running'; end; end; procedure TTCPStreamServerFrm.ClientConnected; begin MemoLogs.Lines.Add('A Client connected'); end; procedure TTCPStreamServerFrm.ClientDisconnected; begin MemoLogs.Lines.Add('A Client disconnected'); end; procedure TTCPStreamServerFrm.FormCreate(Sender: TObject); var SysMenu: THandle; begin SysMenu := GetSystemMenu(Handle, False); InsertMenu(SysMenu, Word(-1), MF_SEPARATOR, ID_NEWLINE, ''); InsertMenu(SysMenu, Word(-1), MF_BYPOSITION, ID_INFOCOMPILER, 'Program build information.'); with ClbIPs do begin Clear; Items := GStack.LocalAddresses; If Items.Strings[0] <> '127.0.0.1' then Items.Insert(0, '127.0.0.1'); Checked[0] := true; end; ActiveServer(True); end; procedure TTCPStreamServerFrm.FormDestroy(Sender: TObject); begin TCPServer.Active := False; end; procedure TTCPStreamServerFrm.TCPServerConnect(AContext: TIdContext); begin TIdNotify.NotifyMethod(ClientConnected); end; procedure TTCPStreamServerFrm.TCPServerDisconnect(AContext: TIdContext); begin TIdNotify.NotifyMethod(ClientDisconnected); end; procedure TTCPStreamServerFrm.TCPServerExecute(AContext: TIdContext); var FStreamR : TStringStream; FStreamS : TStringStream; lSlResponse : TStrings; begin FStreamR := TStringStream.Create; FStreamS := TStringStream.Create; lSlResponse := TStringList.Create; try MemoLogs.Lines.Add('Server starting .... '); AContext.Connection.IOHandler.ReadTimeout := 9000; if (ReceiveStream(AContext, TStream(FStreamR)) = False) then begin TIdNotify.NotifyMethod(ShowCannotGetBufferErrorMessage); Exit; end; FStreamR.Position := 0; MemoMsgs.Lines.Clear; MemoMsgs.Lines.LoadFromStream(FStreamR); TIdNotify.NotifyMethod(StreamReceived); MemoLogs.Lines.Add('Stream Size: ' + IntToStr(FStreamR.Size)); //Response lSlResponse.Add('TCPStreamServerResponse'); lSlResponse.Add(Format('Time: %s', [FormatDateTime('DD/MM/YYYY HH:NN:SS.ZZZ', now)])); lSlResponse.Add(Format('Count: %s', [IntToStr(MemoMsgs.Lines.Count)])); lSlResponse.SaveToStream(FStreamS); FStreamS.Position := 0; if (SendStream(AContext, TStream(FStreamS)) = False) then begin TIdNotify.NotifyMethod(ShowCannotSendBufferErrorMessage); Exit; end; MemoLogs.Lines.Add('Stream sent'); MemoLogs.Lines.Add('Server done .... '); finally FreeAndNil(lSlResponse); FreeAndNil(FStreamR); FreeAndNil(FStreamS); end; end; procedure TTCPStreamServerFrm.StreamReceived; begin MemoLogs.Lines.Add('Stream received'); end; procedure TTCPStreamServerFrm.WMSysCommand(var Msg: TMessage); begin case Msg.wParam of ID_INFOCOMPILER : OKRightDlgDelphi.Show; end; inherited; end; procedure TTCPStreamServerFrm.ShowCannotGetBufferErrorMessage; begin MemoLogs.Lines.Add('Cannot get stream from client, Unknown error occured'); end; procedure TTCPStreamServerFrm.ShowCannotSendBufferErrorMessage; begin MemoLogs.Lines.Add('Cannot send stream to client, Unknown error occured'); end; procedure TTCPStreamServerFrm.SpeedButton1Click(Sender: TObject); begin ActiveServer(not TCPServer.Active); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Button3: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; spolu, pocet : Integer; riadky : TStrings; implementation {$R *.lfm} { TForm1 } procedure TForm1.Button1Click(Sender: TObject); var znamka : integer; begin while true do begin if not TryStrToInt(InputBox('Znamky', 'Zadajte dalsiu znamku alebo -1 pre ukoncenie', ''), znamka) Then begin Memo1.Lines.Add('chyba'); exit; end; if znamka = -1 then break; pocet := pocet + 1; spolu := spolu + znamka; riadky.Add(IntToStr(znamka)); end; end; procedure TForm1.Button2Click(Sender: TObject); var i : integer; begin for i := 0 to riadky.Count - 1 do Memo1.Lines.Add(riadky.Strings[i]); end; procedure TForm1.Button3Click(Sender: TObject); begin Memo1.Lines.Add('Priemerna znamka je: ' + FloatToStr(spolu / pocet)); end; procedure TForm1.FormCreate(Sender: TObject); begin riadky := TStringList.Create; end; end.
unit DIPXRcv; (***************************************************************************** Prozessprogrammierung SS08 Aufgabe: Muehle Beinhaltet die IPX-Empfaenger-Task, die Nachrichten per IPX empfaengt und diese an die zustaendigen Tasks weiterleitet. Autor: Alexander Bertram (B_TInf 2616) *****************************************************************************) interface procedure IPXReceiverTask; implementation uses RTKernel, RTIPX, Types, DIPX, Tools, DispMB, BoardMB, Board, DTypes, Semas; {F+} procedure IPXReceiverTask; (***************************************************************************** Beschreibung: IPX-Empfaenger-Task In: - Out: - *****************************************************************************) var PMessage: PDisplayMessage; BoardMessage: TBoardMessage; begin Debug('Wurde erzeugt'); { IPX-Kanal oeffnen } Debug('Oeffne Kanal'); DIPX.OpenChannel(cIPXReceiveBuffers); Debug('Kanal geoeffnet'); while true do begin { Auf Nachrichten warten } Debug('Warte auf Nachrichten vom Prozessrechner'); DIPX.Get(IPXMailbox, PMessage); Debug('Nachricht empfangen'); { Nachricht analysieren und wetierleiten } Debug('Analysiere Nachricht'); case PMessage^.Kind of { Initialisierungsnachricht } dmkInit: begin BoardMessage.Kind := bmkInit; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Spielerfarben } dmkPlayerColors: begin Debug('Spielerfarben empfangen'); BoardMessage.Kind := bmkPlayerColors; BoardMessage.Colors := PMessage^.Colors; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Aktueller Spieler } dmkCurrentPlayer: begin Debug('Aktuellen Spieler empfangen'); BoardMessage.Kind := bmkCurrentPlayer; BoardMessage.Player := PMessage^.Player; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Zugmoeglichkeiten } dmkMovePossibilities: begin Debug('Zugmoeglichkeiten empfangen'); with BoardMessage do begin Kind := bmkTokenMovePossibilities; TokenMovePossibilities := PMessage^.Possibilities; end; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Spielfeld } dmkField: begin Debug('Spielfeld empfangen'); with BoardMessage do begin Kind := bmkField; Field := PMessage^.Field; end; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Zugdaten } dmkTokenMove: begin Debug('Zugdaten empfangen'); with BoardMessage do begin Kind := bmkTokenMove; TokenMoveData := PMessage^.TokenMoveData; end; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Spielerphase } dmkPlayerStage: begin Debug('Spielerphase empfangen'); BoardMessage.Kind := bmkPlayerStage; BoardMessage.PlayerStage := PMessage^.Stage; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Programmende } dmkExit: begin {$IFDEF DEBUG} LoggerMessage.Kind := lomkExit; LoggerMB.Put(Logger.Mailbox, LoggerMessage); {$ELSE} Signal(ExitSemaphore); {$ENDIF} end; { Spielende } dmkGameOver: begin BoardMessage.Kind := bmkGameOver; BoardMB.Put(Board.Mailbox, BoardMessage); end; end; Debug('Nachricht analysiert'); { IPX-Buffer freigeben } Debug('Gebe IPX-Buffer frei'); DIPX.FreeBuffer(PMessage); Debug('IPX-Buffer freigegeben'); { Taskwechsel } RTKernel.Delay(0); end; Debug('Werde zerstoert'); end; end.
program SPS; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, CustApp, Citys, SysData, SearchKernel, DatabaseIO, SysDAT { you can add units after this }; type { TConsoleServer } TConsoleServer = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure WriteHelp; virtual; end; { TConsoleServer } { 关于输入的格式: 如果只有一天的数据,则为"ExeName 1day %八位数日期% %第一天数据库路径% %写出数据库路径%" 如果只有两天的数据,则为"ExeName 2day %八位数日期% %第一天数据库路径% %第二天数据库路径% %写出数据库路径%" } procedure TConsoleServer.DoRun; var Days,tgr:string; id,day,i:integer; cmdline:string; EcptJump:boolean; begin OpenLog; //打开日志文件 Days:=ParamStr(1); //载入多少天的数据 day:=-1; if Days='1day' then day:=1; if Days='2day' then day:=2; ResetData; DataDate:=StrToInt(ParamStr(2)); //取数据日期 //取几天的数据库的文件路径 Day1DB:=ParamStr(3); Day2DB:=ParamStr(4); cmdline:=''; for i:=0 to 5 do cmdline:=cmdline+ParamStr(i)+' '; AddLog('Start up command line is : '+cmdline); Case day of 1:begin Day1DBText:=Day1DB; OutputDB:=Day2DB; //只有一天时,第四个参数为输出的数据库名字 TotalTime:=day*24*2; LoadDBFromText(Day1DBText,1); //读入数据 AddLog('Load database 1 over.'); for id:=1 to RouterNumber do begin EcptJump:=true; tgr:=GetTWCodeByID(id); AddLog('Now calculating target to '+tgr); try DPSearch(tgr); AddLog('Calculation of target to '+tgr+' over. Now writing database.'); EcptJump:=false; except on E:Exception do AddLog('Exception happened. Details : '+E.ClassName+':'+E.Message); end; if EcptJump then continue; try WriteDataToSQLite(tgr); AddLog('Write database over.'); except on E:Exception do AddLog('Exception happened. Details : '+E.ClassName+':'+E.Message); end; end; AddLog('Calculation over. Now terminate.'); end; 2:begin Day1DBText:=Day1DB; LoadDBFromText(Day1DBText,1); //读入数据 AddLog('Load database 1 over.'); Day2DBText:=Day2DB; LoadDBFromText(Day2DBText,1*2*24+1); //读入数据 AddLog('Load database 2 over.'); OutputDB:=ParamStr(5); //只有两天时,第五个参数为输出的数据库名字 TotalTime:=day*24*2; for id:=1 to RouterNumber do begin EcptJump:=false; tgr:=GetTWCodeByID(id); AddLog('Now calculating target to '+tgr); try DPSearch(tgr); AddLog('Calculation of target to '+tgr+' over. Now writing database.'); EcptJump:=false; except on E:Exception do AddLog('Exception happened. Details : '+E.ClassName+':'+E.Message); end; if EcptJump then continue; try WriteDataToSQLite(tgr); AddLog('Write database over.'); except on E:Exception do AddLog('Exception happened. Details : '+E.ClassName+':'+E.Message); end; end; AddLog('Calculation over. Now terminate.'); end; -1:begin AddLog('Start up command line error. Now terminate.') end; end; CloseLog; Terminate; end; constructor TConsoleServer.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException:=True; end; destructor TConsoleServer.Destroy; begin inherited Destroy; end; procedure TConsoleServer.WriteHelp; begin end; var Application: TConsoleServer; {$IFDEF WINDOWS}{$R SPS.rc}{$ENDIF} begin Application:=TConsoleServer.Create(nil); Application.Title:='ShortestPathSearch'; AOwner:=Application.Owner; Application.Run; Application.Free; end.
unit URawDataInterface; interface uses classes, sysutils; type TRawDataInterface = class; TArrayOfByte = Array of byte; TRawDataInterface = class private { Private declarations } READ_INDEX : INTEGER; buff : TArrayOfByte; packet : TArrayOfByte; public { Public declarations } procedure LoadFromStream(Stream : TStream; Var Buffer : TArrayOfByte); procedure ReadData(Count : Integer; Var Buffer : TArrayOfByte); constructor create; destructor destroy; end; implementation destructor TRawDataInterface.destroy; begin {} setlength(buff, 0); setlength(packet, 0); READ_INDEX := 0; end; constructor TRawDataInterface.create; begin {} setlength(buff, 20*1024*1024); // 20 MB setlength(packet, 1*1024*1024); // 1 MB READ_INDEX := 0; end; procedure TRawDataInterface.ReadData(Count : Integer; Var Buffer : TArrayOfByte); var arr : TArrayOfByte; p : pointer; i : integer; begin arr := packet; p := packet; FillChar(p^, Count + 1, 0); // ZeroMemory for i := 1 to count do begin arr[ i - 1 ] := buff[ READ_INDEX ]; READ_INDEX := READ_INDEX + 1; end; Buffer := packet; end; procedure TRawDataInterface.LoadFromStream(Stream : TStream; Var Buffer : TArrayOfByte); const rsize=2048; type TArrayOfByte = Array of byte; var j, x : integer; index : integer; BuffByte : Array [1..rsize] of byte; begin index := 0; for J := 1 to (Stream.Size div rsize) do begin Stream.Read(BuffByte[1], rsize); for x := 1 to rsize do begin buff[index] := ord(inttohex(BuffByte[x], 2)[1]); index := index + 1; buff[index] :=ord(inttohex(BuffByte[x], 2)[2]); index := index + 1; end; end; Stream.Read(BuffByte[1], Stream.Size mod rsize); for x := 1 to rsize do begin buff[index] := ord(inttohex(BuffByte[x], 2)[1]); index := index + 1; buff[index] := ord(inttohex(BuffByte[x], 2)[2]); index := index + 1; end; Buffer := buff; end; end.
unit uLight; interface uses uVect, uColour, uSource; type Light = class(Source) private position: Vect; color: Colour; public constructor Create; overload; constructor Create(p: Vect; c: Colour); overload; function getLightPosition: Vect; override; function getLightColor: Colour; override; end; implementation { Light } constructor Light.Create; begin position := Vect.Create(0,0,0); color := Colour.Create(1,1,1,0); end; constructor Light.Create(p: Vect; c: Colour); begin position := p; color := c; end; function Light.getLightColor: Colour; begin Result := color; end; function Light.getLightPosition: Vect; begin Result := position; end; end.
unit uSimpleInterception; interface uses Spring.Interception; type TInterceptor = class(TInterfacedObject, IInterceptor) procedure Intercept(const invocation: IInvocation); end; TClassToIntercept = class procedure InterceptedMethod; virtual; end; procedure DoIt; implementation uses System.SysUtils ; procedure DoIt; var Generator: TProxyGenerator; Interceptor: IInterceptor; InterceptedClass: TClassToIntercept; begin Generator := TProxyGenerator.Create; try Interceptor := TInterceptor.Create; InterceptedClass := Generator.CreateClassProxy<TClassToIntercept>([Interceptor]); InterceptedClass.InterceptedMethod; finally Generator.Free; end; end; { TInterceptorClass } procedure TInterceptor.Intercept(const Invocation: IInvocation); begin WriteLn('Before Method call named: ', Invocation.Method.Name); try //Invocation. Invocation.Proceed; except on E: Exception do begin WriteLn('Method threw an exception: ' + E.Message); end; end; WriteLn('After Method Call named: ', Invocation.Method.Name); end; procedure TClassToIntercept.InterceptedMethod; begin WriteLn('Calling InterceptedMethod'); end; end.
unit Domain.Entity.Cliente; interface uses System.Classes, Domain.ValuesObject.Email, Dialogs, SysUtils, EF.Mapping.Base, EF.Core.Types, EF.Mapping.Atributes, Domain.Entity.Contato, Domain.Entity.Veiculo,Domain.Entity.ClienteTabelaPreco, System.Generics.Collections, Domain.Consts, Domain.Entity.ClienteEmpresa, EF.Core.List, Domain.Entity.Endereco; type [View('vwClientes')] TvwCliente = class( TEntityBase ) private FNome: TString; published property Nome: TString read FNome write FNome; end; [Table('Clientes')] TCliente = class( TEntityBase ) private FCPFCNPJ: TString; FRenda: TFloat; FIdade: TInteger; FNome: TString; FRG: TString; FDataNascimento: TDate; FAtivo: TString; FNomeFantasia: TString; FApelido: TString; FSituacao: TString; FTipo: TString; FEstadoCivil: TString; FObservacao: TString; FCalcRenda: TFloat; FEmail:TEmail; FContados: Collection<TContato>; FVeiculo: TVeiculo; FClienteTabelaPreco: TClienteTabelaPreco; FClienteEmpresa: TClienteEmpresa; FEndereco: TEndereco; public constructor Create;override; procedure Validate; override; published [Column('Nome', varchar50,false)] [LengthMin(10)] property Nome: TString read FNome write FNome; [Column('NomeFantasia',varchar50,false)] property NomeFantasia: TString read FNomeFantasia write FNomeFantasia; [Column('CPFCNPJ', varchar15,true)] [LengthMin(11)] [NoSpecialChar] property CPFCNPJ: TString read FCPFCNPJ write FCPFCNPJ; [Column('Renda', float,true)] property Renda:TFloat read FRenda write FRenda; [Column('Idade',int,true)] property Idade: TInteger read FIdade write FIdade; [Column('RG',varchar10,true)] [LengthMin(6)] property RG: TString read FRG write FRG; [Column('DataNascimento','Date',true)] property DataNascimento:TDate read FDataNascimento write FDataNascimento; [Column('Ativo',Char1 ,true)] property Ativo: TString read FAtivo write FAtivo; [Column('Situacao',varchar20,true)] [Items(ItemsSituacaoCliente)] [Default('L')] property Situacao:TString read FSituacao write FSituacao; [Column('Tipo',varchar20,true)] [Items( ItemsTipoPessoa )] property Tipo: TString read FTipo write FTipo; [Column('EstadoCivil',varchar20,true)] property EstadoCivil: TString read FEstadoCivil write FEstadoCivil; [Column('Observacao',varchar500,true)] property Observacao:TString read FObservacao write FObservacao; property Email:TEmail read FEmail write FEmail; [NotMapped] property Contatos: Collection<TContato> read FContados write FContados; [NotMapped] property Veiculo: TVeiculo read FVeiculo write FVeiculo; [NotMapped] property ClienteTabelaPreco: TClienteTabelaPreco read FClienteTabelaPreco write FClienteTabelaPreco; [NotMapped] property ClienteEmpresa: TClienteEmpresa read FClienteEmpresa write FClienteEmpresa; [NotMapped] [Reference('CLIENTES.ID = ENDERECO.ClienteId')] property Endereco: TEndereco read FEndereco write FEndereco; class function New(const aCPFCNPJ: TString;const aRenda: TFloat;const aIdade: TInteger; const aNome, aRG: TString;const aDataNascimento: TDate;const aAtivo, aNomeFantasia, aSituacao, aTipo, aEstadoCivil, aObservacao: TString):TCliente; end; implementation constructor TCliente.Create; begin inherited; FEmail := TEmail.Create; FVeiculo := TVeiculo.Create; FClienteTabelaPreco := TClienteTabelaPreco.Create; FClienteEmpresa := TClienteEmpresa.Create; FContados := Collection<TContato>.create; Endereco := TEndereco.Create; end; class function TCliente.New(const aCPFCNPJ: TString;const aRenda: TFloat;const aIdade: TInteger; const aNome, aRG: TString;const aDataNascimento: TDate;const aAtivo, aNomeFantasia, aSituacao, aTipo, aEstadoCivil, aObservacao: TString): TCliente; var C: TCliente; begin C:= TCliente.Create; with C do begin CPFCNPJ:= aCPFCNPJ; Renda:= aRenda; Idade:= aIdade; Nome:= aNome; RG:=aRG; DataNascimento:= aDataNascimento; Ativo:= aAtivo; NomeFantasia:= aNomeFantasia; Situacao:= aSituacao; Tipo:= aTipo; EstadoCivil:= aEstadoCivil; Observacao:= aObservacao; end; result:= C; end; procedure TCliente.Validate; begin inherited; Email.Validate; end; initialization RegisterClass(TCliente); finalization UnRegisterClass(TCliente); end.
{ Program PIC_PROG [options] * * Program data into a PIC microcontroller using the PICPRG PIC programmer. } program pic_prog; %include 'sys.ins.pas'; %include 'util.ins.pas'; %include 'string.ins.pas'; %include 'file.ins.pas'; %include 'stuff.ins.pas'; %include 'picprg.ins.pas'; const dblclick = 0.300; {max time for button double click, seconds} max_msg_args = 2; {max arguments we can pass to a message} var fnam_in: {HEX input file name} %include '(cog)lib/string_treename.ins.pas'; iname_set: boolean; {TRUE if the input file name already set} erase: boolean; {erase target only, don't program} verify: boolean; {verify only, don't program} run: boolean; {-RUN command line option issued} bend: boolean; {-BEND command line option} wait: boolean; {-WAIT command line option} loop: boolean; {-LOOP command line option} quit: boolean; {deliberately exiting program, but no error} noprog: boolean; {don't program the chip} vdd1: boolean; {single Vdd level specified on command line} vdd1lev: real; {the Vdd level specified on the command line} runvdd: real; {Vdd volts for -RUN} ntarg: sys_int_machine_t; {number of targets operated on} name: {PIC name selected by user} %include '(cog)lib/string32.ins.pas'; pr: picprg_t; {PICPRG library state} tinfo: picprg_tinfo_t; {configuration info about the target chip} ihn: ihex_in_t; {HEX file reading state} d18: boolean; {-D18 command line option was given} noverify: boolean; {perform no verify passes} vhonly: boolean; {verify addresses in HEX file only} ii, jj: sys_int_machine_t; {scratch integers and loop counters} r: real; {scratch floating point value} timer: sys_timer_t; {stopwatch timer} clock1: sys_clock_t; {scratch system clock value} tdat_p: picprg_tdat_p_t; {pointer to target data info} verflags: picprg_verflags_t; {set of option flags for verification} progflags: picprg_progflags_t; {set of options flags for programming} opts: {all command line options separate by spaces} %include '(cog)lib/string256.ins.pas'; opt: {upcased command line option} %include '(cog)lib/string_treename.ins.pas'; parm: {command line option parameter} %include '(cog)lib/string_treename.ins.pas'; pick: sys_int_machine_t; {number of token picked from list} msg_parm: {references arguments passed to a message} array[1..max_msg_args] of sys_parm_msg_t; stat: sys_err_t; {completion status code} label next_opt, done_opt, err_parm, err_conflict, parm_bad, done_opts, loop_loop, done_wait, leave, abort, abort2, leave_all; begin sys_timer_init (timer); {initialize the stopwatch} sys_timer_start (timer); {start the stopwatch} string_cmline_init; {init for reading the command line} string_append_token (opts, string_v('-HEX')); {1} string_append_token (opts, string_v('-SIO')); {2} string_append_token (opts, string_v('-PIC')); {3} string_append_token (opts, string_v('-ERASE')); {4} string_append_token (opts, string_v('-V')); {5} string_append_token (opts, string_v('-RUN')); {6} string_append_token (opts, string_v('-WAIT')); {7} string_append_token (opts, string_v('-LOOP')); {8} string_append_token (opts, string_v('-BEND')); {9} string_append_token (opts, string_v('-NPROG')); {10} string_append_token (opts, string_v('-D18')); {11} string_append_token (opts, string_v('-VDD')); {12} string_append_token (opts, string_v('-N')); {13} string_append_token (opts, string_v('-NOVERIFY')); {14} string_append_token (opts, string_v('-QV')); {15} string_append_token (opts, string_v('-LVP')); {16} { * Initialize our state before reading the command line options. } picprg_init (pr); {select defaults for opening PICPRG library} iname_set := false; {no input file name specified} erase := false; {init to not just erase target} verify := false; {init to not just verify} run := false; {init to no -RUN command line option} wait := false; {init to no -WAIT command line option} loop := false; {init to no -LOOP command line option} noprog := false; {init to no -NPROG command line option} runvdd := 0.0; d18 := false; {init to not double PIC 18 EEPROM offsets} quit := false; ntarg := 0; {init number of target systems operated on} vdd1 := false; {no single Vdd level specified} noverify := false; {init to verify the programmed memory} vhonly := false; {init to verify all memory not just HEX file adr} sys_envvar_get ( {init programmer name from environment variable} string_v('PICPRG_NAME'), {environment variable name} parm, {returned environment variable value} stat); if not sys_error(stat) then begin {envvar exists and got its value ?} string_copy (parm, pr.prgname); {initialize target programmer name} end; { * Back here each new command line option. } next_opt: string_cmline_token (opt, stat); {get next command line option name} if string_eos(stat) then goto done_opts; {exhausted command line ?} sys_error_abort (stat, 'string', 'cmline_opt_err', nil, 0); if (opt.len >= 1) and (opt.str[1] <> '-') then begin {implicit pathname token ?} if erase then goto err_conflict; {can't have file name with -ERASE} if not iname_set then begin {input file name not set yet ?} string_copy (opt, fnam_in); {set input file name} iname_set := true; {input file name is now set} goto next_opt; end; goto err_conflict; end; string_upcase (opt); {make upper case for matching list} string_tkpick (opt, opts, pick); {pick command line option name from list} case pick of {do routine for specific option} { * -HEX filename } 1: begin if iname_set then goto err_conflict; {input file name already set ?} if erase then goto err_conflict; {can't have file name with -ERASE} string_cmline_token (fnam_in, stat); iname_set := true; end; { * -SIO n } 2: begin string_cmline_token_int (pr.sio, stat); pr.devconn := picprg_devconn_sio_k; end; { * -PIC name } 3: begin string_cmline_token (name, stat); string_upcase (name); end; { * -ERASE } 4: begin if iname_set then goto err_conflict; {can't have ERASE with input file name} erase := true; noprog := true; end; { * -V } 5: begin verify := true; end; { * -RUN vdd } 6: begin string_cmline_token_fpm (runvdd, stat); {get Vdd voltage to run at} if sys_error(stat) then goto err_parm; if (runvdd < 0.0) or (runvdd > 6.0) then begin {Vdd level out of range ?} sys_message_bomb ('picprg', 'vdd_outofrange', nil, 0); end; runvdd := max(runvdd, 0.024); {minimum level instead of zero special case} run := true; bend := bend or loop; end; { * -WAIT } 7: begin wait := true; end; { * -LOOP } 8: begin loop := true; wait := true; bend := bend or run; end; { * -BEND } 9: begin bend := true; end; { * -NPROG } 10: begin noprog := true; end; { * -D18 } 11: begin d18 := true; end; { * -VDD v } 12: begin string_cmline_token_fpm (vdd1lev, stat); {get Vdd level to operate at} if sys_error(stat) then goto err_parm; vdd1 := true; {indicate to use single Vdd level} end; { * -N name } 13: begin string_cmline_token (pr.prgname, stat); {get programmer name} if sys_error(stat) then goto err_parm; end; { * -NOVERIFY } 14: begin noverify := true; end; { * -QV } 15: begin vhonly := true; end; { * -LVP } 16: begin pr.hvpenab := false; {disallow high voltage program mode entry} end; { * Unrecognized command line option. } otherwise string_cmline_opt_bad; {unrecognized command line option} end; {end of command line option case statement} done_opt: {done handling this command line option} err_parm: {jump here on error with parameter} string_cmline_parm_check (stat, opt); {check for bad command line option parameter} goto next_opt; {back for next command line option} err_conflict: {this option conflicts with a previous opt} sys_msg_parm_vstr (msg_parm[1], opt); sys_message_bomb ('string', 'cmline_opt_conflict', msg_parm, 1); parm_bad: {jump here on got illegal parameter} string_cmline_reuse; {re-read last command line token next time} string_cmline_token (parm, stat); {re-read the token for the bad parameter} sys_msg_parm_vstr (msg_parm[1], parm); sys_msg_parm_vstr (msg_parm[2], opt); sys_message_bomb ('string', 'cmline_parm_bad', msg_parm, 2); done_opts: {done with all the command line options} { * All done reading the command line. } (* pr.flags := pr.flags + [picprg_flag_showin_k, picprg_flag_showout_k]; *) picprg_open (pr, stat); {open the PICPRG programmer library} sys_error_abort (stat, 'picprg', 'open', nil, 0); { * Get the firmware info and check the version. } picprg_fw_show1 (pr, pr.fwinfo, stat); {show version and organization to user} sys_error_abort (stat, '', '', nil, 0); picprg_fw_check (pr, pr.fwinfo, stat); {check firmware version for compatibility} sys_error_abort (stat, '', '', nil, 0); { * Verify that all requested command line options are supported by this * programmer and firmware. } if vdd1 then begin {fixed Vdd level specified ?} if (vdd1lev < pr.fwinfo.vddmin) or (vdd1lev > pr.fwinfo.vddmax) then begin sys_msg_parm_real (msg_parm[1], pr.fwinfo.vddmin); sys_msg_parm_real (msg_parm[2], pr.fwinfo.vddmax); sys_message_bomb ('picprg', 'unsup_vdd', msg_parm, 2); end; end; if run then begin {-RUN specified ?} if not pr.fwinfo.cmd[48] then begin {RUN command not available ?} sys_message_bomb ('picprg', 'unsup_run', nil, 0); end; if (runvdd < pr.fwinfo.vddmin) or (runvdd > pr.fwinfo.vddmax) then begin sys_msg_parm_real (msg_parm[1], pr.fwinfo.vddmin); sys_msg_parm_real (msg_parm[2], pr.fwinfo.vddmax); sys_message_bomb ('picprg', 'unsup_vdd', msg_parm, 2); end; end; if wait then begin {-WAIT specified ?} if (not pr.fwinfo.cmd[47]) or {APPLED command not available ?} (not pr.fwinfo.cmd[46]) {GETBUTT command not available ?} then begin sys_message_bomb ('picprg', 'unsup_wait', nil, 0); end; end; if bend then begin {-BEND specified ?} if (not pr.fwinfo.cmd[46]) then begin {GETBUTT command not available ?} sys_message_bomb ('picprg', 'unsup_bend', nil, 0); end; end; { * Wait for user confirmation if -WAIT specified on the command line. } loop_loop: {loop back to here on -LOOP} if not wait then goto done_wait; {-WAIT not specified ?} sys_timer_init (timer); {reset the stopwatch} picprg_cmdw_getbutt (pr, ii, stat); {get current number of button presses} if sys_error_check (stat, '', '', nil, 0) then goto abort; picprg_cmdw_appled (pr, 15, 1.0, 15, 1.0, stat); {light App LED brightly} if sys_error_check (stat, '', '', nil, 0) then goto abort; repeat {back here until button is pressed} picprg_cmdw_getbutt (pr, jj, stat); {check number of button presses again} clock1 := sys_clock; {save time right at this button result} if sys_error_check (stat, '', '', nil, 0) then goto abort; jj := (jj - ii) & 255; {make number of new button presses} until jj <> 0; {back if button not pressed} picprg_cmdw_appled (pr, 0, 1.0, 0, 1.0, stat); {turn off App LED to confirm} if sys_error_check (stat, '', '', nil, 0) then goto abort; if loop then begin writeln; {blank line to separate from previous target} end; repeat {loop short time looking for double click} picprg_cmdw_getbutt (pr, jj, stat); {check number of button presses again} if sys_error_check (stat, '', '', nil, 0) then goto abort; jj := (jj - ii) & 255; {make number of new button presses} if jj <> 1 then begin {found double click ?} quit := true; {indicate exiting program but no error} goto abort; end; r := sys_clock_to_fp2 ( {make seconds since first button press} sys_clock_sub (sys_clock, clock1)); until r >= dblclick; {back until double click time expired} sys_timer_start (timer); {start the stopwatch for this target} done_wait: {done waiting for user confirmation} { * Configure to the specific target chip. } picprg_config (pr, name, stat); {configure the library to the target chip} if sys_error_check (stat, '', '', nil, 0) then goto abort; picprg_tinfo (pr, tinfo, stat); {get detailed info about the target chip} if sys_error_check (stat, '', '', nil, 0) then goto abort; sys_msg_parm_vstr (msg_parm[1], tinfo.name); sys_msg_parm_int (msg_parm[2], tinfo.rev); sys_message_parms ('picprg', 'target_type', msg_parm, 2); {show target name} if not ( {nothing more to do ?} erase or {erase the chip ?} iname_set) {program the chip ?} then goto leave; picprg_tdat_alloc (pr, tdat_p, stat); {allocate and init target data} if sys_error_check (stat, '', '', nil, 0) then goto abort; if vdd1 then begin {operate at a single Vdd level ?} picprg_tdat_vdd1 (tdat_p^, vdd1lev); end; { * Erase the chip if -ERASE was specified. } if erase then begin {erase the chip ?} picprg_tdat_vddlev (tdat_p^, picprg_vdd_norm_k, r, stat); sys_message ('picprg', 'erasing'); picprg_erase (pr, stat); {erase the target chip} if sys_error_check (stat, '', '', nil, 0) then goto abort; goto leave; end; { * Read the HEX file data and save it. } if d18 then begin {EEPROM addresses are doubled in HEX file} tdat_p^.eedouble := true; end; ihex_in_open_fnam (fnam_in, '.hex .HEX'(0), ihn, stat); {open the HEX input file} if sys_error_check (stat, '', '', nil, 0) then goto abort; string_copy (ihn.conn_p^.tnam, fnam_in); {save full treename of HEX file} picprg_tdat_hex_read (tdat_p^, ihn, stat); {read HEX file and save target data} if sys_error_check (stat, '', '', nil, 0) then goto abort; ihex_in_close (ihn, stat); {close the HEX file} if sys_error_check (stat, '', '', nil, 0) then goto abort; if ihn.ndat = 0 then begin {no data bytes in the HEX file ?} sys_msg_parm_vstr (msg_parm[1], fnam_in); sys_message_bomb ('picprg', 'hex_nodat', msg_parm, 1); end; { * Verify and don't write to the target if -V was specified. } if noprog then goto leave; {not supposed to program or verify the chip ?} if verify then begin {verify only without writing to target ?} verflags := [ {set fixed verify options} picprg_verflag_stdout_k, {show progress on standard output} picprg_verflag_prog_k, {verify program memory} picprg_verflag_data_k, {verify data EEPROM} picprg_verflag_other_k, {verify "other" locations} picprg_verflag_config_k]; {verify config words} if vhonly then begin verflags := verflags + [picprg_verflag_hex_k]; {verify only data in HEX file} end; if not picprg_tdat_verify (tdat_p^, verflags, stat) then begin {verify failed ?} sys_error_print (stat, '', '', nil, 0); goto abort; end; goto leave; end; {end of verify only case} { * Perform the programming operation. } progflags := [picprg_progflag_stdout_k]; {init to fixed options} if noverify then begin {no verify at all ?} progflags := progflags + [picprg_progflag_nover_k]; end; if vhonly then begin {verify only locations specified in HEX file ?} progflags := progflags + [picprg_progflag_verhex_k]; end; picprg_tdat_prog (tdat_p^, progflags, stat); {program the target} if sys_error_check (stat, '', '', nil, 0) then goto abort; { * Common point for exiting the program with the PICPRG library open * and no error. } leave: {clean up and close connection to this target} ntarg := ntarg + 1; {count one more target system operated on} picprg_cmdw_appled (pr, 0, 1.0, 0, 1.0, stat); {make sure App LED, if any, is off} discard( sys_stat_match (picprg_subsys_k, picprg_stat_cmdnimp_k, stat) ); if sys_error_check (stat, '', '', nil, 0) then goto abort; if run then begin {run the target at specified Vdd level} picprg_cmdw_run (pr, runvdd, stat); {set up to power and run the target} if sys_error_check (stat, '', '', nil, 0) then goto abort; end else begin {do not try to run the target} picprg_off (pr, stat); {disengage from the target system} if sys_error_check (stat, '', '', nil, 0) then goto abort2; end ; sys_timer_stop (timer); {stop the stopwatch} r := sys_timer_sec (timer); {get total elapsed seconds} sys_msg_parm_real (msg_parm[1], r); sys_message_parms ('picprg', 'no_errors', msg_parm, 1); if bend then begin {wait until user button pressed ?} picprg_cmdw_getbutt (pr, ii, stat); {get current number of button presses} if sys_error_check (stat, '', '', nil, 0) then goto abort; repeat {wait until button pressed} picprg_cmdw_getbutt (pr, jj, stat); {check number of button presses again} if sys_error_check (stat, '', '', nil, 0) then goto abort; jj := (jj - ii) & 255; {make number of new button presses} until jj <> 0; {back if button not pressed} picprg_off (pr, stat); {disengage from the target system} if sys_error_check (stat, '', '', nil, 0) then goto abort2; end; if loop then goto loop_loop; {back to do another target ?} picprg_close (pr, stat); {close the PICPRG library} sys_error_abort (stat, 'picprg', 'close', nil, 0); goto leave_all; { * Exit point with the PICPRG library open. QUIT set indicates that * the program is being aborted deliberately and that should not be * considered an error. * * If jumping here due to error, then the error message must already have been * written. } abort: picprg_off (pr, stat); {disengage from the target system} sys_error_abort (stat, '', '', nil, 0); { * Programmer has already disengaged from the target to the exent possible. } abort2: picprg_close (pr, stat); {close the PICPRG library} sys_error_abort (stat, 'picprg', 'close', nil, 0); if not quit then begin {aborting program on error ?} sys_bomb; {exit the program with error status} end; if loop then begin {could have done multiple target systems ?} sys_msg_parm_int (msg_parm[1], ntarg); sys_message_parms ('picprg', 'num_targets', msg_parm, 1); end; leave_all: end.
{ Copyright 2020 Ideas Awakened Inc. Part of the "iaLib" shared code library for Delphi For more detail, see: https://github.com/ideasawakened/iaLib Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module History 1.0 2020-June-24 Darian Miller: Unit created } unit iaVCL.SynEdit.StyleHook; interface uses Winapi.Messages, Vcl.Controls, Vcl.Forms, Vcl.Graphics, Vcl.Styles, Vcl.Themes, SynEdit; type // Interposer - add this unit after SynEdit in the uses statement so this class will be used rather than the original TSynEdit = class(SynEdit.TSynEdit) protected procedure CMStyleChanged(var Message:TMessage); message CM_STYLECHANGED; procedure Loaded(); override; procedure UpdateCustomStyle(); end; implementation procedure TSynEdit.CMStyleChanged(var Message:TMessage); begin UpdateCustomStyle(); Invalidate(); end; procedure TSynEdit.Loaded(); begin inherited; UpdateCustomStyle(); end; procedure TSynEdit.UpdateCustomStyle(); var vActiveStyle:TCustomStyleServices; begin vActiveStyle := TStyleManager.ActiveStyle; Color := vActiveStyle.GetStyleColor(scEdit); Font.Color := vActiveStyle.GetStyleFontColor(sfEditBoxTextNormal); RightEdgeColor := vActiveStyle.GetStyleColor(scSplitter); ScrollHintColor := vActiveStyle.GetSystemColor(clInfoBk); ActiveLineColor := clNone; Gutter.Color := vActiveStyle.GetStyleColor(scPanel); Gutter.Font.Color := vActiveStyle.GetStyleFontColor(sfPanelTextNormal); Gutter.GradientStartColor := vActiveStyle.GetStyleColor(scToolBarGradientBase); Gutter.GradientEndColor := vActiveStyle.GetStyleColor(scToolBarGradientEnd); Gutter.BorderColor := vActiveStyle.GetStyleColor(scSplitter); // Optional items: I tend to prefer the default selected text colors rather than theme colors // SelectedColor.Background := vActiveStyle.GetSystemColor(clHighlight); // SelectedColor.Foreground := vActiveStyle.GetSystemColor(clHighlightText); end; initialization // handles styling of the scroll bars TStyleManager.Engine.RegisterStyleHook(TSynEdit, TScrollBoxStyleHook); finalization TStyleManager.Engine.UnRegisterStyleHook(TSynEdit, TScrollBoxStyleHook); end.
unit FunctionsUnit; interface uses Windows, Messages, Classes, SysUtils, DeCAL; const MathLibrary = 'MyMath.dll'; type TParamsArray = array of Extended; TFunction = class private name: String; pcount: Integer; function Exec(params: TParamsArray): Extended; virtual; abstract; public constructor Create; virtual; property ParamCount: Integer read pcount; end; TStandartFunctionOne = class (TFunction) function Exec(params: TParamsArray): Extended; override; end; TStandartFunctionTwo = class (TFunction) constructor Create; override; function Exec(params: TParamsArray): Extended; override; end; TFunctionsList = class private functions: DMap; public constructor Create; destructor Destroy; override; procedure Load(folder: String = 'Functions'); function Call(fname: String; params: TParamsArray): Extended; function getFunctionNames(): TStringList; end; TFunctionClass = class of TFunction; EFunctionsError = class (Exception); function ExecFunction(FName: string; x,y: Extended): Extended; var FunctionsList: TFunctionsList; implementation function ExecFunction(FName: string; x,y: Extended): Extended; var Func: function (x,y: Extended): Extended; hLib: HWND; begin hLib:=LoadLibrary(PChar(MathLibrary)); fname := AnsiUpperCase(fname); if HLib <> 0 then begin Func:=GetProcAddress(hLib, PChar(FName)); if @Func <> nil then try Result:=Func(x,y); except on EZeroDivide do raise EFunctionsError.Create('Деление на ноль'); on E: Exception do raise; end else raise EFunctionsError.Create('В библиотеке нет функции ' +Copy(FName, 2, Length(FName)-1)); end else raise EFunctionsError.CreateFmt('Не найдено библиотеки математических функций (%s)', [MathLibrary]); FreeLibrary(hLib); FreeLibrary(hLib); end; { TFunction } constructor TFunction.Create; begin pcount := 1; end; //------------------------------------------------------------------------------ { TStandartFunctionOne } function TStandartFunctionOne.Exec(params: TParamsArray): Extended; var x: Extended; begin x := params[0]; try Result := ExecFunction('m'+self.name, x, 0); except on E: Exception do raise EFunctionsError.CreateFmt('Ошибка во время выполнения функции "%s".'#13#10' %s' , [name, E.Message]); end; end; { TStandartFunctionTwo } constructor TStandartFunctionTwo.Create; begin inherited; pcount := 2; end; function TStandartFunctionTwo.Exec(params: TParamsArray): Extended; var x, y: Extended; begin x := params[0]; y := params[1]; try Result := ExecFunction('m'+self.name, x, y); except on E: Exception do raise EFunctionsError.CreateFmt('Ошибка во время выполнения функции "%s".'#13#10' %s' , [name, E.Message]); end; end; { TFunctionsList } function TFunctionsList.Call(fname: String; params: TParamsArray): Extended; var fc: TFunctionClass; func: TFunction; iter : DIterator; begin iter := functions.locate([fname]); if not AtEnd(iter) then begin fc := TFunctionClass(getClass(iter)); func := fc.Create; func.name := fname; if func.ParamCount <> Length(params) then raise EFunctionsError.CreateFmt('У функции "%s" %d параметр(а)', [fname, func.ParamCount]); Result := func.Exec(params); end else raise EFunctionsError.CreateFmt('Не найдена функция "%s"', [fname]); end; constructor TFunctionsList.Create; begin functions := DMap.Create; functions.putPair(['SIN', TStandartFunctionOne]); functions.putPair(['SINC', TStandartFunctionOne]); functions.putPair(['SINH', TStandartFunctionOne]); functions.putPair(['ARCSIN', TStandartFunctionOne]); functions.putPair(['ARCSINH', TStandartFunctionOne]); functions.putPair(['COS', TStandartFunctionOne]); functions.putPair(['ARCCOS', TStandartFunctionOne]); functions.putPair(['COSH', TStandartFunctionOne]); functions.putPair(['ARCCOSH', TStandartFunctionOne]); functions.putPair(['TG', TStandartFunctionOne]); functions.putPair(['ARCTG', TStandartFunctionOne]); functions.putPair(['TGH', TStandartFunctionOne]); functions.putPair(['ARCTGH', TStandartFunctionOne]); functions.putPair(['CTG', TStandartFunctionOne]); functions.putPair(['CTGH', TStandartFunctionOne]); functions.putPair(['ARCCTGH', TStandartFunctionOne]); functions.putPair(['ARCCTG', TStandartFunctionOne]); functions.putPair(['NOT', TStandartFunctionOne]); functions.putPair(['SQRT', TStandartFunctionOne]); functions.putPair(['SQR', TStandartFunctionOne]); functions.putPair(['SGN', TStandartFunctionOne]); functions.putPair(['FRAC', TStandartFunctionOne]); functions.putPair(['EXP', TStandartFunctionOne]); functions.putPair(['ABS', TStandartFunctionOne]); functions.putPair(['TRUNC', TStandartFunctionOne]); functions.putPair(['INT', TStandartFunctionOne]); functions.putPair(['PRED', TStandartFunctionOne]); functions.putPair(['SUCC', TStandartFunctionOne]); functions.putPair(['ROUND', TStandartFunctionOne]); functions.putPair(['XOR', TStandartFunctionTwo]); functions.putPair(['OR', TStandartFunctionTwo]); functions.putPair(['AND', TStandartFunctionTwo]); functions.putPair(['MOD', TStandartFunctionTwo]); functions.putPair(['DIV', TStandartFunctionTwo]); functions.putPair(['POWER', TStandartFunctionTwo]); functions.putPair(['SHL', TStandartFunctionTwo]); functions.putPair(['SHR', TStandartFunctionTwo]); functions.putPair(['LN', TStandartFunctionOne]); functions.putPair(['LOG', TStandartFunctionTwo]); functions.putPair(['FACT', TStandartFunctionTwo]); end; destructor TFunctionsList.Destroy; begin functions.Free(); inherited; end; function TFunctionsList.getFunctionNames: TStringList; var iter: DIterator; begin Result := TStringList.Create(); iter := functions.start(); SetToKey(iter); while not atEnd(iter) do begin Result.Add(getString(iter)); advance(iter); end; end; procedure TFunctionsList.Load(folder: String); begin end; initialization FunctionsList := TFunctionsList.Create; FunctionsList.Load(); finalization FunctionsList.Free(); end.
unit ChildMeter; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TFormChildMeter = class(TForm) MeterPic: TImage; Label1: TLabel; edMeter: TEdit; Label2: TLabel; edSection: TEdit; Label3: TLabel; edTrip: TEdit; Label4: TLabel; edPrevRead: TEdit; Label5: TLabel; edRead: TEdit; Label6: TLabel; edComment: TEdit; Label7: TLabel; edAvgkw: TEdit; Label8: TLabel; edKW: TEdit; Label9: TLabel; edDiff: TEdit; procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); private { Private declarations } procedure MakeNoDataScreen; public { Public declarations } procedure ShowMeter(MeterNumber : string;RcvFileDate : TDateTime); function CalcKW(prevRead,cRead,prevDate : string;cDate : TDatetime) : string; end; var FormChildMeter: TFormChildMeter; implementation uses MeterData,jpeg; {$R *.DFM} procedure TFormChildMeter.MakeNoDataScreen; begin edMeter.Text := '>> Not Found <<'; edSection.Clear; edTrip.Clear; edPrevRead.Clear; edRead.Clear; edComment.Clear; edAvgkw.Clear; edKw.Clear; edDiff.Clear; end; function TFormChildMeter.CalcKW(prevRead,cRead,prevDate : string;cDate : TDatetime) : string; var syy,smm,sdd : string; prevDT : TDateTime; diffMeter : integer; numDay : integer; begin if (prevRead='') or (cRead='') then begin result := 'N/A'; end else begin syy := '25'+copy(prevDate,1,2); smm := copy(prevDate,3,2); sdd := copy(prevDate,5,2); prevDT := encodedate(StrToInt(syy)-543,StrToInt(smm),StrToInt(sdd)); diffMeter := StrToInt(cRead)-StrToInt(prevRead); numDay := trunc(cDate-prevDT); result := IntToStr(trunc(diffMeter*1000/(numDay*24))); end; end; procedure TFormChildMeter.FormActivate(Sender: TObject); begin dm.tbMeter.open; end; procedure TFormChildMeter.ShowMeter; begin self.Caption := MeterNumber; if not dm.tbMeter.Find(MeterNumber,true,false) then begin MakenoDataScreen; end else begin with dm.tbMeter do begin edMeter.Text := MeterNumber; edSection.Text := StringGet('m_section'); edtrip.Text := StringGet('m_trip'); edPrevRead.Text := StringGet('m_prev_rd'); edRead.Text := StringGet('e_last_rd'); edComment.Text := StringGet('e_hh_cmt'); edAvgKw.Text := StringGet('m_avg_kwhr'); edKw.Text := CalcKw(StringGet('m_prev_rd'), StringGet('e_last_rd'), StringGet('m_prev_dte'), rcvFileDate); if fileExists('pic\'+MeterNumber+'.jpg') then MeterPic.Picture.LoadFromFile('pic\'+MeterNumber+'.jpg'); end; end; end; procedure TFormChildMeter.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFormChildMeter.FormCreate(Sender: TObject); begin MeterPic.Picture.RegisterFileFormat('jpg', 'JPEG', TJPEGImage); end; end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) } unit AsyncExTypes; (* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2004 - 2006 Martin Offenwanger * * Mail: coder@dsplayer.de * * Web: http://www.dsplayer.de * * * * This Program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2, 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 GNU Make; see the file COPYING. If not, write to * * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * * http://www.gnu.org/copyleft/gpl.html * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *) { @author(Martin Offenwanger: coder@dsplayer.de) @created(Apr 22, 2004) @lastmod(Apr 02, 2005) } interface uses ActiveX; const AsyncExFileName = 'AsyncEx.ax'; AsyncExFilterID = 'AsyncEx'; AsyncExPinID = 'StreamOut'; CLSID_AsyncEx: TGUID = '{3E0FA044-926C-42d9-BA12-EF16E980913B}'; IID_AsyncExControl: TGUID = '{3E0FA056-926C-43d9-BA18-EF16E980913B}'; IID_AsyncExCallBack: TGUID = '{3E0FB667-956C-43d9-BA18-EF16E980913B}'; PinID = 'StreamOut'; FilterID = 'AsyncEx'; type IAsyncExCallBack = interface(IUnknown) ['{3E0FB667-956C-43d9-BA18-EF16E980913B}'] function AsyncExFilterState(Buffering: LongBool; PreBuffering: LongBool; Connecting: LongBool; Playing: LongBool; BufferState: integer): HRESULT; stdcall; function AsyncExICYNotice(IcyItemName: PChar; ICYItem: PChar): HRESULT; stdcall; function AsyncExMetaData(Title: PChar; URL: PChar): HRESULT; stdcall; function AsyncExSockError(ErrString: PChar): HRESULT; stdcall; end; IAsyncExControl = interface(IUnknown) ['{3E0FA056-926C-43d9-BA18-EF16E980913B}'] function SetLoadFromStream(Stream: IStream; Length: int64): HRESULT; stdcall; function SetConnectToIp(Host: PChar; Port: PChar; Location: PChar; AgentName:pchar): HRESULT; stdcall; function SetConnectToURL(URL: PChar; AgentName:pchar): HRESULT; stdcall; function SetBuffersize(BufferSize: integer): HRESULT; stdcall; function GetBuffersize(out BufferSize: integer): HRESULT; stdcall; function SetRipStream(Ripstream: LongBool; Path: PwideChar; Filename: PwideChar): HRESULT; stdcall; function GetRipStream(out Ripstream: LongBool; out FileO: PwideChar): HRESULT; stdcall; function SetCallBack(CallBack: IAsyncExCallBack): HRESULT; stdcall; function FreeCallback(): HRESULT; stdcall; function ExitAllLoops(): HRESULT; stdcall; end; implementation end.
unit editingwindow; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ExtDlgs, IniFiles; type { TFrmEditingWindow } TFrmEditingWindow = class(TForm) bClose: TButton; bSave: TButton; bSearchIcon: TButton; BtnSearchExecFile: TButton; cbFileType: TComboBox; eCategories: TEdit; eIconPath: TEdit; eExecPath: TEdit; eName: TEdit; GroupBox1: TGroupBox; ImgIcon: TImage; LblCategories: TLabel; LblIconPath: TLabel; LblExec: TLabel; LblName: TLabel; odOpenExecFile: TOpenDialog; opdOpenIconFile: TOpenPictureDialog; procedure bCloseClick(Sender: TObject); procedure bSaveClick(Sender: TObject); procedure BtnSearchExecFileClick(Sender: TObject); procedure bSearchIconClick(Sender: TObject); private public end; var FrmEditingWindow: TFrmEditingWindow; implementation {$R *.lfm} { TFrmEditingWindow } procedure TFrmEditingWindow.bCloseClick(Sender: TObject); begin eName.Clear; eExecPath.Clear; eIconPath.Clear; eCategories.Clear; Close; end; procedure TFrmEditingWindow.bSaveClick(Sender: TObject); const C_DF_SECTION = 'Desktop Entry'; var ini: TIniFile; pathToFile: String; begin pathToFile := GetUserDir + '/.local/share/applications/' + eName.Text + '.desktop'; ini := TIniFile.Create(pathToFile); try ini.WriteString(C_DF_SECTION,'Name',eName.Text); ini.WriteString(C_DF_SECTION,'Exec',eExecPath.Text); ini.WriteString(C_DF_SECTION,'Icon',eIconPath.Text); ini.WriteString(C_DF_SECTION,'Type',cbFileType.Text); ini.WriteString(C_DF_SECTION,'Categories',eCategories.Text); ShowMessage('Die Datei: ' + eName.Text + '.desktop wurde erfolgreich angelegt.') finally ini.Free; end; end; procedure TFrmEditingWindow.BtnSearchExecFileClick(Sender: TObject); begin if odOpenExecFile.Execute then begin eName.Text:=ExtractFileName(odOpenExecFile.FileName); eExecPath.Text:=odOpenExecFile.FileName; end; end; procedure TFrmEditingWindow.bSearchIconClick(Sender: TObject); begin if opdOpenIconFile.Execute then begin eIconPath.Text:=opdOpenIconFile.FileName; ImgIcon.Picture.LoadFromFile(opdOpenIconFile.FileName); end; end; end.
unit LuaTreeNodes; {$mode delphi} interface uses Classes, SysUtils, ComCtrls, lua, lualib, lauxlib; implementation uses luaclass, luahandler, LuaObject; function treenodes_clear(L: Plua_State): integer; cdecl; var treenodes: TTreeNodes; i: integer; begin result:=0; treenodes:=luaclass_getClassObject(L); {$ifdef cpu32} //free the allocated memory if there was any for i:=0 to treenodes.count-1 do begin if treenodes[i].Data<>nil then freemem(treenodes[i].data) end; {$endif} treenodes.Clear; end; function treenodes_getItem(L: PLua_State): integer; cdecl; var treenodes: Ttreenodes; index: integer; begin result:=0; treenodes:=luaclass_getClassObject(L); if lua_gettop(L)>=1 then begin index:=lua_tointeger(L,-1); luaclass_newClass(L, treenodes.Item[index]); result:=1; end; end; function treenodes_getCount(L: PLua_State): integer; cdecl; var treenodes: Ttreenodes; begin treenodes:=luaclass_getClassObject(L); lua_pushvariant(L, treenodes.Count); result:=1; end; function treenodes_add(L: PLua_State): integer; cdecl; var treenodes: Ttreenodes; paramcount: integer; s: string; begin treenodes:=luaclass_getClassObject(L); paramcount:=lua_gettop(L); if paramcount>=1 then s:=Lua_ToString(L, 1) else s:=''; luaclass_newClass(L, treenodes.add(nil, s)); result:=1; end; function treenodes_insertBehind(L: PLua_State): integer; cdecl; var treenodes: Ttreenodes; treenode: ttreenode; paramcount: integer; s: string; begin treenodes:=luaclass_getClassObject(L); paramcount:=lua_gettop(L); if paramcount>=1 then treenode:=lua_ToCEUserData(L, 1) else treenode:=nil; if paramcount>=2 then s:=Lua_ToString(L, 2) else s:=''; luaclass_newClass(L, treenodes.InsertBehind(treenode, s)); result:=1; end; function treenodes_insert(L: PLua_State): integer; cdecl; var treenodes: Ttreenodes; treenode: ttreenode; paramcount: integer; s: string; begin treenodes:=luaclass_getClassObject(L); paramcount:=lua_gettop(L); if paramcount>=1 then treenode:=lua_ToCEUserData(L, 1) else treenode:=nil; if paramcount>=2 then s:=Lua_ToString(L, 2) else s:=''; luaclass_newClass(L, treenodes.insert(treenode, s)); result:=1; end; procedure treenodes_addMetaData(L: PLua_state; metatable: integer; userdata: integer ); begin object_addMetaData(L, metatable, userdata); luaclass_addClassFunctionToTable(L, metatable, userdata, 'clear', treenodes_clear); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getCount', treenodes_getCount); luaclass_addClassFunctionToTable(L, metatable, userdata, 'getItem', treenodes_getItem); luaclass_addClassFunctionToTable(L, metatable, userdata, 'add', treenodes_add); luaclass_addClassFunctionToTable(L, metatable, userdata, 'insert', treenodes_insert); luaclass_addClassFunctionToTable(L, metatable, userdata, 'insertBehind', treenodes_insertBehind); luaclass_addPropertyToTable(L, metatable, userdata, 'Count', treenodes_getCount, nil); luaclass_addArrayPropertyToTable(L, metatable, userdata, 'Item', treenodes_getItem); luaclass_setDefaultArrayProperty(L, metatable, userdata, treenodes_getItem, nil); end; initialization luaclass_register(TTreeNodes, treenodes_addMetaData); end.
unit uRest; interface uses System.SysUtils, REST.Client; type TRest = class private FRESTClient: TRESTClient; FRESTRequest: TRESTRequest; FRESTResponse: TRESTResponse; public constructor Create; destructor Destroy; override; function Execute(Const pBaseUrl: string; Const pResource: string; Const ResourceSuffix: string): string; property RESTClient: TRESTClient read FRESTClient; property RESTRequest: TRESTRequest read FRESTRequest; property RESTResponse: TRESTResponse read FRESTResponse; end; implementation { TRest } constructor TRest.Create; begin Self.FRESTClient := TRESTClient.Create(EmptyStr); Self.FRESTRequest := TRESTRequest.Create(nil); Self.FRESTResponse := TRESTResponse.Create(nil); Self.RESTRequest.Client := Self.FRESTClient; Self.RESTRequest.Response := Self.FRESTResponse; end; destructor TRest.Destroy; begin Self.FRESTResponse.Free; Self.FRESTRequest.Free; Self.FRESTClient.Free; inherited; end; function TRest.Execute(const pBaseUrl, pResource, ResourceSuffix: string): string; begin try Self.FRESTClient.BaseURL := pBaseUrl; Self.FRESTRequest.Resource := pResource; Self.FRESTRequest.ResourceSuffix := ResourceSuffix; Self.FRESTRequest.Execute; Result := Self.FRESTResponse.JSONValue.ToJSON; Except Result := EmptyStr; end; end; end.
unit PACCPointerHashMap; {$i PACC.inc} interface uses PACCTypes; type TPACCPointerHashMapData=pointer; PPACCPointerHashMapEntity=^TPACCPointerHashMapEntity; TPACCPointerHashMapEntity=record Key:pointer; Value:TPACCPointerHashMapData; end; TPACCPointerHashMapEntities=array of TPACCPointerHashMapEntity; TPACCPointerHashMapEntityIndices=array of longint; TPACCPointerHashMap=class private function FindCell(const Key:pointer):TPACCUInt32; procedure Resize; protected function GetValue(const Key:pointer):TPACCPointerHashMapData; procedure SetValue(const Key:pointer;const Value:TPACCPointerHashMapData); public Parent:TPACCPointerHashMap; RealSize:longint; LogSize:longint; Size:longint; Entities:TPACCPointerHashMapEntities; EntityToCellIndex:TPACCPointerHashMapEntityIndices; CellToEntityIndex:TPACCPointerHashMapEntityIndices; constructor Create; destructor Destroy; override; procedure Clear; function Add(const Key:pointer;const Value:TPACCPointerHashMapData):PPACCPointerHashMapEntity; function Get(const Key:pointer;const CreateIfNotExist:boolean=false):PPACCPointerHashMapEntity; function Delete(const Key:pointer;const DoParent:boolean=false):boolean; property Values[const Key:pointer]:TPACCPointerHashMapData read GetValue write SetValue; default; end; implementation const CELL_EMPTY=-1; CELL_DELETED=-2; ENT_EMPTY=-1; ENT_DELETED=-2; function HashPointer(const p:pointer):TPACCUInt32; begin result:=(TPACCPtrUInt(p)*$5052acdb0){$ifdef cpu64} xor ((TPACCPtrUInt(p) shr 32)*$57559429){$endif}; if result=0 then begin result:=$ffffffff; end; end; constructor TPACCPointerHashMap.Create; begin inherited Create; Parent:=nil; RealSize:=0; LogSize:=0; Size:=0; Entities:=nil; EntityToCellIndex:=nil; CellToEntityIndex:=nil; Resize; end; destructor TPACCPointerHashMap.Destroy; var Counter:longint; begin Clear; for Counter:=0 to length(Entities)-1 do begin Entities[Counter].Key:=nil; end; SetLength(Entities,0); SetLength(EntityToCellIndex,0); SetLength(CellToEntityIndex,0); inherited Destroy; end; procedure TPACCPointerHashMap.Clear; var Counter:longint; begin for Counter:=0 to length(Entities)-1 do begin Entities[Counter].Key:=nil; end; RealSize:=0; LogSize:=0; Size:=0; SetLength(Entities,0); SetLength(EntityToCellIndex,0); SetLength(CellToEntityIndex,0); Resize; end; function TPACCPointerHashMap.FindCell(const Key:pointer):TPACCUInt32; var HashCode,Mask,Step:TPACCUInt32; Entity:longint; begin HashCode:=HashPointer(Key); Mask:=(2 shl LogSize)-1; Step:=((HashCode shl 1)+1) and Mask; if LogSize<>0 then begin result:=HashCode shr (32-LogSize); end else begin result:=0; end; repeat Entity:=CellToEntityIndex[result]; if (Entity=ENT_EMPTY) or ((Entity<>ENT_DELETED) and (Entities[Entity].Key=Key)) then begin exit; end; result:=(result+Step) and Mask; until false; end; procedure TPACCPointerHashMap.Resize; var NewLogSize,NewSize,Cell,Entity,Counter:longint; OldEntities:TPACCPointerHashMapEntities; OldCellToEntityIndex:TPACCPointerHashMapEntityIndices; OldEntityToCellIndex:TPACCPointerHashMapEntityIndices; begin NewLogSize:=0; NewSize:=RealSize; while NewSize<>0 do begin NewSize:=NewSize shr 1; inc(NewLogSize); end; if NewLogSize<1 then begin NewLogSize:=1; end; Size:=0; RealSize:=0; LogSize:=NewLogSize; OldEntities:=Entities; OldCellToEntityIndex:=CellToEntityIndex; OldEntityToCellIndex:=EntityToCellIndex; Entities:=nil; CellToEntityIndex:=nil; EntityToCellIndex:=nil; SetLength(Entities,2 shl LogSize); SetLength(CellToEntityIndex,2 shl LogSize); SetLength(EntityToCellIndex,2 shl LogSize); for Counter:=0 to length(CellToEntityIndex)-1 do begin CellToEntityIndex[Counter]:=ENT_EMPTY; end; for Counter:=0 to length(EntityToCellIndex)-1 do begin EntityToCellIndex[Counter]:=CELL_EMPTY; end; for Counter:=0 to length(OldEntityToCellIndex)-1 do begin Cell:=OldEntityToCellIndex[Counter]; if Cell>=0 then begin Entity:=OldCellToEntityIndex[Cell]; if Entity>=0 then begin Add(OldEntities[Counter].Key,OldEntities[Counter].Value); end; end; end; for Counter:=0 to length(OldEntities)-1 do begin OldEntities[Counter].Key:=nil; end; SetLength(OldEntities,0); SetLength(OldCellToEntityIndex,0); SetLength(OldEntityToCellIndex,0); end; function TPACCPointerHashMap.Add(const Key:pointer;const Value:TPACCPointerHashMapData):PPACCPointerHashMapEntity; var Entity:longint; Cell:TPACCUInt32; begin result:=nil; while RealSize>=(1 shl LogSize) do begin Resize; end; Cell:=FindCell(Key); Entity:=CellToEntityIndex[Cell]; if Entity>=0 then begin result:=@Entities[Entity]; result^.Key:=Key; result^.Value:=Value; exit; end; Entity:=Size; inc(Size); if Entity<(2 shl LogSize) then begin CellToEntityIndex[Cell]:=Entity; EntityToCellIndex[Entity]:=Cell; inc(RealSize); result:=@Entities[Entity]; result^.Key:=Key; result^.Value:=Value; end; end; function TPACCPointerHashMap.Get(const Key:pointer;const CreateIfNotExist:boolean=false):PPACCPointerHashMapEntity; var Entity:longint; Cell:TPACCUInt32; begin result:=nil; Cell:=FindCell(Key); Entity:=CellToEntityIndex[Cell]; if Entity>=0 then begin result:=@Entities[Entity]; end else if CreateIfNotExist then begin result:=Add(Key,nil); end; if assigned(Parent) and not assigned(result) then begin result:=Parent.Get(Key,CreateIfNotExist); end; end; function TPACCPointerHashMap.Delete(const Key:pointer;const DoParent:boolean=false):boolean; var Entity:longint; Cell:TPACCUInt32; begin result:=false; Cell:=FindCell(Key); Entity:=CellToEntityIndex[Cell]; if Entity>=0 then begin Entities[Entity].Key:=nil; Entities[Entity].Value:=nil; EntityToCellIndex[Entity]:=CELL_DELETED; CellToEntityIndex[Cell]:=ENT_DELETED; result:=true; end else if DoParent and assigned(Parent) then begin result:=Parent.Delete(Key); end; end; function TPACCPointerHashMap.GetValue(const Key:pointer):TPACCPointerHashMapData; var Entity:longint; Cell:TPACCUInt32; begin Cell:=FindCell(Key); Entity:=CellToEntityIndex[Cell]; if Entity>=0 then begin result:=Entities[Entity].Value; end else if assigned(Parent) then begin result:=Parent.GetValue(Key); end else begin result:=nil; end; end; procedure TPACCPointerHashMap.SetValue(const Key:pointer;const Value:TPACCPointerHashMapData); begin Add(Key,Value); end; end.
{ 单元名称: uJxdFileShareManage 单元作者: 江晓德(Terry) 邮 箱: jxd524@163.com jxd524@gmail.com 说 明: 开始时间: 2011-04-08 修改时间: 2011-09-12 (最后修改时间) 类说明 : 管理本地文件的共享,记录文件的HASH,验证文件用到的HASH, 验证文件HASH的分段大小为 SegmentSize * 32 默认情况,HASH检验分段大小为: 8.0M (256K * 32) 大部分情况下是不需要用到分段HASH检验的。提供分段HASH检验功能 Hash计算使用函数: HashFun_BKDR 内存使用动态申请的,如想优化,可做不定长内存分配处理 配置保存方案 文件版本号 共享数量(Integer), 多个以下结构 begin 文件名称(word + string) 文件大小(Int64) 文件分段大小(Integer) Hash检验分段大小(Integer) 文件Hash( 16 ) 验证分段数量(4) 分段1HASH 分段2HASH ... end; } unit uJxdFileShareManage; interface uses Windows, Classes, SysUtils, uJxdHashCalc, uSysSub, uJxdDataStream, uJxdFileSegmentStream, uJxdDataStruct; const CtCalcHashSegmentCount = 32; // * SegmentSize 为一个大分段的HASH验证大小使用的分段数量 type PFileShareInfo = ^TFileShareInfo; TFileShareInfo = record FShareID: Cardinal; FShareTag: string; FFileName: string; FFileSize: Int64; FSegmentSize: Integer; FFileHash, FWebHash: TxdHash; FHashCheckSegmentSize: Integer; //Hash分段的检验大小 FHashCheckSegmentCount: Integer; //HASH检验数量 FHashCheckTable: array[0..0] of TxdHash; //HASH检验表 end; TOnFileShareInfo = procedure(Sender: TObject; const Ap: PFileShareInfo) of object; {$M+} TxdFileShareManage = class public constructor Create; destructor Destroy; override; //添加一个本地的文件来共享, 不对文件进行判断 function AddLocalFileToShare(const AFileName: string; const AShareTag: string = ''; const ASegmentSize: Integer = 0): Boolean; overload; function AddLocalFileToShare(const AStream: TxdFileSegmentStream; const AShareTag: string): Boolean; overload; procedure LockShareManage; inline; procedure UnLockShareManage; inline; {查找共享信息,非线程安全} procedure LoopShareFileInfo(ALoop: TOnLoopNode); //遍历共享表中所有内容 function FindShareInfoByFileHash(const AHash: TxdHash; const ADel: Boolean = False): PFileShareInfo; function FindShareInfoByWebHash(const AHash: TxdHash; const ADel: Boolean = False): PFileShareInfo; private FCurFindWebHash: TxdHash; FCurFindWebHashDel: Boolean; FFindShareInfo: PFileShareInfo; FCloseingManage: Boolean; FCalcLock: TRTLCriticalSection; FShareLock: TRTLCriticalSection; FCalcingHash: Boolean; FCalcHashList: TList; FShareFileList: THashArrayEx; procedure ActiveShareManage; procedure UnActiveShareManage; procedure LoadFromFile; procedure SaveToFile; protected function GetFileShareMem(const ACheckHashSegmentCount: Integer): PFileShareInfo; procedure FreeFileShareMem(Ap: PFileShareInfo); procedure DoAddShareFileInfo(const Ap: PFileShareInfo); procedure DoFreeShareFileInfo(Ap: PFileShareInfo); procedure DoNotifyAddShareSuccess(const Ap: PFileShareInfo); //通知添加到列表成功 procedure DoNotifyExistsFile(const Ap: PFileShareInfo); //通知已存在的共享文件 procedure DoNotifyEmptyHashFile(const Ap: PFileShareInfo); //计算不出HASH的共享文件 procedure DoLoopSaveShareInfoToFile(const AParamNode: Pointer; Sender: TObject; const AID: Cardinal; pData: Pointer; var ADel: Boolean; var AFindNext: Boolean); procedure DoLoopToFreeAllShareInfo(Sender: TObject; const AID: Cardinal; pData: Pointer; var ADel: Boolean; var AFindNext: Boolean); procedure DoLoopToFindInfoByWebHash(Sender: TObject; const AID: Cardinal; pData: Pointer; var ADel: Boolean; var AFindNext: Boolean); procedure DoThreadCalcFileHash; procedure CalcHashCheckTable(stream: TxdP2SPFileStreamBasic; const Ap: PFileShareInfo); procedure WaitThreadExit; private FFileName: string; FActive: Boolean; FHashTableCount: Integer; FMaxShareFileCount: Integer; FCurThreadCount: Integer; FMinShareFileSize: Integer; FCurCalcHashFileName: string; FOnFileShareInfo: TOnFileShareInfo; procedure SetMaxShareFileCount(const Value: Integer); procedure SetFileName(const Value: string); procedure SetActive(const Value: Boolean); procedure SetHashTableCount(const Value: Integer); procedure SetMinShareFileSize(const Value: Integer); function GetCurShareFileCount: Integer; function GetCurCalcHashCount: Integer; function GetShareFileList: THashArrayEx; published property CurThreadCount: Integer read FCurThreadCount; property CurShareFileCount: Integer read GetCurShareFileCount; property CurCalcHashCount: Integer read GetCurCalcHashCount; property CurCalcHashFileName: string read FCurCalcHashFileName; property ShareFileList: THashArrayEx read GetShareFileList; property Active: Boolean read FActive write SetActive; property MinShareFileSize: Integer read FMinShareFileSize write SetMinShareFileSize; property FileName: string read FFileName write SetFileName; property HashTableCount: Integer read FHashTableCount write SetHashTableCount; property MaxShareFileCount: Integer read FMaxShareFileCount write SetMaxShareFileCount; property OnFileShareInfo: TOnFileShareInfo read FOnFileShareInfo write FOnFileShareInfo; end; {$M-} function HashToID(const AHash: TxdHash): Cardinal; implementation uses uJxdThread, uHashFun; const CtConfigVersion = 100; CtFileShareInfoSize = SizeOf(TFileShareInfo); function HashToID(const AHash: TxdHash): Cardinal; begin // Result := AHash.A + AHash.B + AHash.C + AHash.D; Result := HashFun_BKDR( @AHash.v, CtHashSize ); end; { TxdFileShareManage } procedure TxdFileShareManage.ActiveShareManage; begin try FCurThreadCount := 0; FCalcHashList := TList.Create; FShareFileList := THashArrayEx.Create; FShareFileList.MaxHashNodeCount := MaxShareFileCount; FShareFileList.HashTableCount := HashTableCount; FShareFileList.Active := True; LoadFromFile; FActive := True; except UnActiveShareManage; end; end; function TxdFileShareManage.AddLocalFileToShare(const AFileName: string; const AShareTag: string; const ASegmentSize: Integer): Boolean; var p: PFileShareInfo; nCheckHashSegmentCount: Integer; nSegSize: Integer; nCalcHashSegmentSize: Cardinal; nFileSize: Int64; begin Result := False; nFileSize := GetFileSizeEx(AFileName); if nFileSize <= MinShareFileSize then Exit; if ASegmentSize <= 0 then nSegSize := CtSegmentDefaultSize else nSegSize := ASegmentSize; nCalcHashSegmentSize := nSegSize * CtCalcHashSegmentCount; if nCalcHashSegmentSize > nFileSize then nCalcHashSegmentSize := nFileSize; nCheckHashSegmentCount := (nFileSize + nCalcHashSegmentSize - 1) div nCalcHashSegmentSize; p := GetFileShareMem( nCheckHashSegmentCount ); p^.FShareTag := AShareTag; p^.FFileName := AFileName; p^.FFileSize := nFileSize; p^.FSegmentSize := nSegSize; p^.FHashCheckSegmentSize := nCalcHashSegmentSize; p^.FHashCheckSegmentCount := nCheckHashSegmentCount; if p^.FShareTag = '' then p^.FShareTag := ExtractFileName( p^.FFileName ); EnterCriticalSection( FCalcLock ); try FCalcHashList.Add( p ); finally LeaveCriticalSection( FCalcLock ); end; if not FCalcingHash then RunningByThread( DoThreadCalcFileHash ); end; function TxdFileShareManage.AddLocalFileToShare(const AStream: TxdFileSegmentStream; const AShareTag: string): Boolean; var p: PFileShareInfo; nCheckHashSegmentCount: Integer; nSegSize: Integer; nCalcHashSegmentSize: Cardinal; nFileSize: Int64; begin Result := Assigned(AStream) and Assigned(AStream.SegmentTable); if not Result then Exit; nFileSize := AStream.SegmentTable.FileSize; if nFileSize <= MinShareFileSize then begin Result := False; Exit; end; if AStream.SegmentTable.SegmentSize <= 0 then nSegSize := CtSegmentDefaultSize else nSegSize := AStream.SegmentTable.SegmentSize; nCalcHashSegmentSize := nSegSize * CtCalcHashSegmentCount; if nCalcHashSegmentSize > nFileSize then nCalcHashSegmentSize := nFileSize; nCheckHashSegmentCount := (nFileSize + nCalcHashSegmentSize - 1) div nCalcHashSegmentSize; p := GetFileShareMem( nCheckHashSegmentCount ); p^.FShareTag := AShareTag; p^.FFileName := AStream.RenameFileName; if p^.FFileName = '' then p^.FFileName := AStream.FileName; p^.FFileSize := nFileSize; p^.FSegmentSize := nSegSize; p^.FHashCheckSegmentSize := nCalcHashSegmentSize; p^.FHashCheckSegmentCount := nCheckHashSegmentCount; p^.FFileHash := AStream.FileHash; p^.FWebHash := AStream.WebHash; p^.FShareID := HashToID(p^.FFileHash); EnterCriticalSection( FCalcLock ); try FCalcHashList.Add( p ); finally LeaveCriticalSection( FCalcLock ); end; if not FCalcingHash then RunningByThread( DoThreadCalcFileHash ); end; procedure TxdFileShareManage.CalcHashCheckTable(stream: TxdP2SPFileStreamBasic; const Ap: PFileShareInfo); var i: Integer; nSize: Integer; buf: PByte; begin GetMem( buf, Ap^.FHashCheckSegmentSize ); try for i := 0 to Ap^.FHashCheckSegmentCount - 1 do begin if HashCompare(CtEmptyHash, Ap^.FHashCheckTable[i]) then begin if i = Ap^.FHashCheckSegmentCount - 1 then nSize := Ap^.FFileSize - i * Ap^.FHashCheckSegmentSize else nSize := Ap^.FHashCheckSegmentSize; Stream.ReadBuffer( i * Ap^.FHashCheckSegmentSize, nSize, buf ); Ap^.FHashCheckTable[i] := HashBuffer( buf, nSize ); end; if not Active then Break; end; finally FreeMem( buf, Ap^.FHashCheckSegmentSize ); end; end; constructor TxdFileShareManage.Create; begin FFileName := ''; FCurCalcHashFileName := ''; FActive := False; FHashTableCount := 547; FMaxShareFileCount := 10000; FMinShareFileSize := 100; FCalcingHash := False; FCloseingManage := False; InitializeCriticalSection( FCalcLock ); InitializeCriticalSection( FShareLock ); end; destructor TxdFileShareManage.Destroy; begin Active := False; DeleteCriticalSection( FCalcLock ); DeleteCriticalSection( FShareLock ); inherited; end; procedure TxdFileShareManage.DoAddShareFileInfo(const Ap: PFileShareInfo); var pNode: PHashNode; bFind, bValidFile: Boolean; pF: PFileShareInfo; begin bFind := False; bValidFile := False; LockShareManage; try if not Active then begin //当程序要退出时,先将信息保存到列表中,此时只有文件名称跟分段大小有效。下次启动时再去计算 FShareFileList.Add( Ap^.FShareID, Ap ); end else begin if HashCompare(Ap^.FFileHash, CtEmptyHash) then begin //计算不出HASH的文件断定它无效 bValidFile := True; end else begin pNode := FShareFileList.FindBegin( Ap^.FShareID ); while Assigned(pNode) do begin pF := pNode^.NodeData; if HashCompare(Ap^.FFileHash, pF^.FFileHash) then begin bFind := True; Break; end; pNode := FShareFileList.FindNext( pNode ); end; if not bFind then begin FShareFileList.Add( Ap^.FShareID, Ap ); DoNotifyAddShareSuccess( Ap ); end; end; end; finally FShareFileList.FindEnd; UnLockShareManage; end; if bValidFile then begin DoNotifyEmptyHashFile(Ap); DoFreeShareFileInfo( Ap ); end else if bFind then begin //已经存在的节点 DoNotifyExistsFile( Ap ); DoFreeShareFileInfo( Ap ); end; end; procedure TxdFileShareManage.DoFreeShareFileInfo(Ap: PFileShareInfo); begin // FreeAndNil( Ap^.FSegmentTable ); // ReleaseFileSegmentStream( Ap^.FStream ); FreeFileShareMem( Ap ); end; procedure TxdFileShareManage.DoLoopSaveShareInfoToFile(const AParamNode: Pointer; Sender: TObject; const AID: Cardinal; pData: Pointer; var ADel, AFindNext: Boolean); var f: TxdStreamHandle; p: PFileShareInfo; i: Integer; begin p := PFileShareInfo(pData); f := TxdStreamHandle(AParamNode); with f do begin { FShareID: Cardinal; FShareTag: string; FFileName: string; FFileSize: Int64; FSegmentSize: Integer; FFileHash, FWebHash: TMD4Digest; FHashCheckSegmentSize: Integer; FHashCheckSegmentCount: Integer; FHashCheckTable: array[0..0] of TMD4Digest; end;} WriteStringEx(p^.FShareTag); WriteStringEx(p^.FFileName); WriteInt64(p^.FFileSize); WriteInteger(p^.FSegmentSize); WriteLong(p^.FFileHash, CtHashSize); WriteLong(p^.FWebHash, CtHashSize); for i := 0 to p^.FHashCheckSegmentCount - 1 do WriteLong(p^.FHashCheckTable[i], CtHashSize); end; end; procedure TxdFileShareManage.DoLoopToFindInfoByWebHash(Sender: TObject; const AID: Cardinal; pData: Pointer; var ADel, AFindNext: Boolean); var p: PFileShareInfo; begin p := pData; AFindNext := not HashCompare( p^.FWebHash, FCurFindWebHash ); if not AFindNext then begin FFindShareInfo := p; ADel := FCurFindWebHashDel; end; end; procedure TxdFileShareManage.DoLoopToFreeAllShareInfo(Sender: TObject; const AID: Cardinal; pData: Pointer; var ADel, AFindNext: Boolean); var p: PFileShareInfo; begin ADel := True; AFindNext := True; p := pData; DoFreeShareFileInfo( p ); end; procedure TxdFileShareManage.DoNotifyAddShareSuccess(const Ap: PFileShareInfo); begin OutputDebugString( '成功添加一个共享信息' ); if Assigned(FOnFileShareInfo) then FOnFileShareInfo(Self, Ap); end; procedure TxdFileShareManage.DoNotifyEmptyHashFile(const Ap: PFileShareInfo); begin OutputDebugString( '计算不出HASH的共享文件' ); end; procedure TxdFileShareManage.DoNotifyExistsFile(const Ap: PFileShareInfo); begin OutputDebugString( '已存在的共享文件' ); end; procedure TxdFileShareManage.DoThreadCalcFileHash; var p: PFileShareInfo; i: Integer; Stream: TxdLocalFileStream; begin FCalcingHash := True; FCurCalcHashFileName := ''; InterlockedIncrement( FCurThreadCount ); try Sleep(100); while FCalcHashList.Count > 0 do begin EnterCriticalSection( FCalcLock ); try p := FCalcHashList[ FCalcHashList.Count - 1 ]; FCalcHashList.Delete( FCalcHashList.Count - 1 ); finally LeaveCriticalSection( FCalcLock ); end; FCurCalcHashFileName := p^.FFileName; //计算本地文件的HASH信息 Stream := TxdLocalFileStream.Create( p^.FFileName, CtEmptyHash, p^.FSegmentSize ); try if Active and IsEmptyHash(P^.FFileHash) then CalcFileHash( Stream, p^.FFileHash, @FCloseingManage ); if Active and IsEmptyHash(p^.FWebHash) then CalcFileWebHash( Stream, p^.FWebHash, @FCloseingManage ); p^.FShareID := HashToID(p^.FFileHash); if Active then begin if p^.FHashCheckSegmentCount = 1 then begin p^.FHashCheckTable[0] := p^.FFileHash; end else begin //计算分段检验HASH信息 CalcHashCheckTable( Stream, p ); end; end; DoAddShareFileInfo( p ); finally Stream.Free; end; //结束 if not Active then begin EnterCriticalSection( FCalcLock ); try for i := FCalcHashList.Count - 1 downto 0 do begin p := FCalcHashList[i]; FCalcHashList.Delete( i ); p^.FShareID := 0; DoAddShareFileInfo( p ); end; finally LeaveCriticalSection( FCalcLock ); end; Break; end; end; finally InterlockedDecrement( FCurThreadCount ); FCalcingHash := False; FCurCalcHashFileName := ''; end; end; function TxdFileShareManage.FindShareInfoByFileHash(const AHash: TxdHash; const ADel: Boolean): PFileShareInfo; var pNode: PHashNode; nID: Cardinal; p: PFileShareInfo; begin Result := nil; nID := HashToID(AHash); try pNode := FShareFileList.FindBegin( nID ); while Assigned(pNode) do begin p := pNode^.NodeData; if HashCompare(AHash, p^.FFileHash) then begin Result := p; if ADel then FShareFileList.FindDelete( pNode ); Break; end; pNode := FShareFileList.FindNext( pNode ); end; finally FShareFileList.FindEnd; end; end; function TxdFileShareManage.FindShareInfoByWebHash(const AHash: TxdHash; const ADel: Boolean): PFileShareInfo; begin // EnterCriticalSection( FShareLock ); try FCurFindWebHash := AHash; FCurFindWebHashDel := ADel; FFindShareInfo := nil; FShareFileList.Loop( DoLoopToFindInfoByWebHash ); Result := FFindShareInfo; finally // LeaveCriticalSection( FShareLock ); end; end; procedure TxdFileShareManage.FreeFileShareMem(Ap: PFileShareInfo); begin if Assigned(Ap) then FreeMem( Ap ); end; function TxdFileShareManage.GetCurCalcHashCount: Integer; begin if Assigned(FCalcHashList) then Result := FCalcHashList.Count else Result := 0; end; function TxdFileShareManage.GetCurShareFileCount: Integer; begin if Assigned(FShareFileList) then Result := FShareFileList.Count else Result := 0; end; function TxdFileShareManage.GetFileShareMem(const ACheckHashSegmentCount: Integer): PFileShareInfo; begin if ACheckHashSegmentCount >= 1 then begin GetMem( Pointer(Result), CtFileShareInfoSize + (ACheckHashSegmentCount - 1) * CtHashSize ); FillChar( Result^, CtFileShareInfoSize + (ACheckHashSegmentCount - 1) * CtHashSize, 0 ); end else Result := nil; end; function TxdFileShareManage.GetShareFileList: THashArrayEx; begin Result := FShareFileList; end; procedure TxdFileShareManage.LoadFromFile; var f: TxdFileStream; p: PFileShareInfo; nCheckHashSegmentCount: Integer; nSegSize: Integer; nCalcHashSegmentSize: Cardinal; nFileSize: Int64; i, j, nCount: Integer; bCalcHash: Boolean; strFileName, strTag: string; begin if FileExists(FFileName) then begin f := TxdFileStream.Create(FFileName, fmOpenRead); try if CtConfigVersion <> f.ReadInteger then begin OutputDebugString( '共享文件版本号出错' ); Exit; end; nCount := f.ReadInteger; for i := 0 to nCount - 1 do begin { WriteStringEx(p^.FShareTag); WriteStringEx(p^.FFileName); WriteInt64(p^.FFileSize); WriteInteger(p^.FSegmentSize); WriteLong(p^.FFileHash, CMD4Size); WriteLong(p^.FWebHash, CMD4Size); for i := 0 to p^.FHashCheckSegmentCount - 1 do WriteLong(p^.FHashCheckTable[i], CMD4Size); end;} strTag := f.ReadStringEx; strFileName := f.ReadStringEx; nFileSize := f.ReadInt64; nSegSize := f.ReadInteger; if nSegSize <= 0 then nSegSize := CtSegmentDefaultSize; if FileExists(strFileName) and (nFileSize <> GetFileSizeEx(strFileName)) then begin nFileSize := GetFileSizeEx(strFileName); if nFileSize <= MinShareFileSize then Continue; nSegSize := CtSegmentDefaultSize; end; nCalcHashSegmentSize := nSegSize * CtCalcHashSegmentCount; if nCalcHashSegmentSize > nFileSize then nCalcHashSegmentSize := nFileSize; nCheckHashSegmentCount := (nFileSize + nCalcHashSegmentSize - 1) div nCalcHashSegmentSize; p := GetFileShareMem( nCheckHashSegmentCount ); p^.FShareTag := strTag; p^.FFileName := strFileName; p^.FFileSize := nFileSize; p^.FSegmentSize := nSegSize; p^.FHashCheckSegmentSize := nCalcHashSegmentSize; p^.FHashCheckSegmentCount := nCheckHashSegmentCount; f.ReadLong( p^.FFileHash, CtHashSize ); f.ReadLong( p^.FWebHash, CtHashSize ); bCalcHash := HashCompare(p^.FFileHash, CtEmptyHash); for j := 0 to p^.FHashCheckSegmentCount - 1 do begin f.ReadLong(p^.FHashCheckTable[j], CtHashSize); if not bCalcHash then bCalcHash := HashCompare(p^.FHashCheckTable[j], CtEmptyHash); end; if not FileExists(strFileName) then begin FreeFileShareMem( p ); Continue; end; if bCalcHash then FCalcHashList.Add(p) else begin p^.FShareID := HashToID(p^.FFileHash); FShareFileList.Add( p^.FShareID, p ); DoNotifyAddShareSuccess( p ); end; end; finally f.Free; end; if FCalcHashList.Count <> 0 then RunningByThread( DoThreadCalcFileHash ); end; end; procedure TxdFileShareManage.LockShareManage; begin EnterCriticalSection( FShareLock ); end; procedure TxdFileShareManage.LoopShareFileInfo(ALoop: TOnLoopNode); begin FShareFileList.Loop(ALoop); end; procedure TxdFileShareManage.SaveToFile; var f: TxdFileStream; begin f := TxdFileStream.Create( FFileName, fmCreate ); try f.WriteInteger( CtConfigVersion ); f.WriteInteger( FShareFileList.Count ); FShareFileList.Loop( DoLoopSaveShareInfoToFile, Pointer(f) ); finally f.Free; end; end; procedure TxdFileShareManage.SetActive(const Value: Boolean); begin if FActive <> Value then begin if Value then ActiveShareManage else UnActiveShareManage; end; end; procedure TxdFileShareManage.SetFileName(const Value: string); var strPath: string; begin strPath := ExtractFilePath(Value); if not DirectoryExists(strPath) then if not ForceDirectories(strPath) then Exit; FFileName := Value; end; procedure TxdFileShareManage.SetHashTableCount(const Value: Integer); begin if not Active then FHashTableCount := Value; end; procedure TxdFileShareManage.SetMaxShareFileCount(const Value: Integer); begin if not Active then FMaxShareFileCount := Value; end; procedure TxdFileShareManage.SetMinShareFileSize(const Value: Integer); begin if (FMinShareFileSize <> Value) and (Value >= 0) then FMinShareFileSize := Value; end; procedure TxdFileShareManage.UnActiveShareManage; begin FCloseingManage := True; FActive := False; WaitThreadExit; SaveToFile; FShareFileList.Loop( DoLoopToFreeAllShareInfo ); FreeAndNil(FCalcHashList); FreeAndNil( FShareFileList ); end; procedure TxdFileShareManage.UnLockShareManage; begin LeaveCriticalSection( FShareLock ); end; procedure TxdFileShareManage.WaitThreadExit; var nMaxWaitCount: Integer; begin nMaxWaitCount := 1000000; while (FCurThreadCount > 0) and (nMaxWaitCount > 0) do begin Sleep(10); Dec( nMaxWaitCount ); end; end; end.
unit Main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdSocketHandle, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, ComCtrls, Themes, SynEdit, SynEditHighlighter, SynHighlighterSQL, ExtCtrls, StdCtrls, StrUtils, DateUtils, ActnList, ToolWin, ImgList, ActnMan, ActnCtrls, PlatformDefaultStyleActnCtrls,Generics.Collections, LQMessage,LQSearch, Math; type TfrmMain = class(TForm) UDPServer: TIdUDPServer; SynSQLSyn1: TSynSQLSyn; pnlQuery: TPanel; lvQueries: TListView; ActionList1: TActionList; ImageList1: TImageList; ActionToolBar1: TActionToolBar; ActionManager1: TActionManager; actnClear: TAction; actnListen: TAction; Panel1: TPanel; SynEdit: TSynEdit; Panel2: TPanel; lvResult: TListView; memMessage: TMemo; Splitter1: TSplitter; actnSearch: TAction; pnlSearch: TPanel; edtSearch: TEdit; lblResults: TLabel; tc1: TTabControl; procedure FormCreate(Sender: TObject); procedure actnClearExecute(Sender: TObject); procedure actnListenExecute(Sender: TObject); procedure lvQueriesChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure UDPServerUDPRead(AThread: TIdUDPListenerThread; AData: TBytes; ABinding: TIdSocketHandle); procedure FormDestroy(Sender: TObject); procedure lvQueriesData(Sender: TObject; Item: TListItem); procedure actnSearchExecute(Sender: TObject); procedure SearchListViewItems(str: string); procedure edtSearchChange(Sender: TObject); procedure CreateNewTab(app: string); procedure tc1Change(Sender: TObject); private FAutoInc: Integer; FMessageList : TList<TLiveQueryEntry>; FSearchResult: TList<TLiveQueryEntry>; FFiltered : Boolean; FSearchTerm: string; FSearchObj : TLiveQuerySearch; procedure ResultSetToListView(json: string); procedure UpdateSearchLabel; procedure DataProviderUpdated; public function FindOrCreateGroup(AppName : string): Integer; function FindGroupByCaption(const S: string): Integer; procedure GenerateRandomData; end; var frmMain: TfrmMain; implementation {$R *.dfm} uses superobject; procedure TfrmMain.actnClearExecute(Sender: TObject); begin SynEdit.Clear; memMessage.Visible := False; lvResult.Visible := False; FMessageList.Clear; FSearchResult.Clear; DataProviderUpdated; end; procedure TfrmMain.actnListenExecute(Sender: TObject); begin // end; procedure TfrmMain.actnSearchExecute(Sender: TObject); begin pnlSearch.Visible := actnSearch.Checked; if pnlSearch.Visible then edtSearch.SetFocus; end; procedure TfrmMain.CreateNewTab(app: string); var i: Integer; begin for i := 0 to tc1.Tabs.Count - 1 do begin if tc1.Tabs[i] = app then Exit; end; with tc1.Tabs do begin Append(app); end; end; procedure TfrmMain.DataProviderUpdated; begin if FFiltered then lvQueries.Items.Count := FSearchResult.Count else lvQueries.Items.Count := FMessageList.Count; lvQueries.Invalidate; end; procedure TfrmMain.edtSearchChange(Sender: TObject); begin FSearchTerm := edtSearch.Text; if FSearchTerm = '' then begin FFiltered := False; lblResults.Caption := 'Search above'; tc1.TabIndex := 0; end else begin //SearchListViewItems(FSearchTerm); FFiltered := True; FSearchResult := FSearchObj.SearchListItems(FMessageList,FSearchTerm,False); UpdateSearchLabel; end; DataProviderUpdated; // lvQueries.Items.Count := FSearchResult.Count; // lvQueries.Invalidate; end; procedure TfrmMain.GenerateRandomData; var i : Integer; msg : TLiveQueryMessage; data: TLiveQueryEntry; begin for i := 1 to 10 do begin msg.Query := RandomFrom(['hello', 'world', 'test']); msg.Error := RandomRange(1, 10) > 5; msg.TextMessage := RandomFrom(['hello', 'world', 'test']); msg.Rows := RandomFrom(['[]', '[{id:1, name:"Test"}]']); msg.RemoteAddr := RandomFrom(['::1', '127.0.0.1', 'google.com', '80.78.66.66']); data.ID := i; data.TimeStamp := Now; data.Msg := msg; FMessageList.Add(data); end; DataProviderUpdated; end; function TfrmMain.FindGroupByCaption(const S: string): Integer; begin Result := -1; for Result := 0 to lvQueries.Groups.Count -1 do if lvQueries.Groups[Result].Header = S then Exit; with lvQueries.Groups.Add do begin Header := S; Result := GroupID; end; end; function TfrmMain.FindOrCreateGroup(AppName: string): Integer; var i : Integer; begin //iteron grupet; nese ekzisotn kthen GroupID; //ne te kundert krijon grup te ri me emrin qe vjen; for i := 0 to lvQueries.Groups.Count - 1 do begin if lvQueries.Groups[i].Header = AppName then begin Exit(lvQueries.Groups[i].GroupID); end; end; with lvQueries.Groups.Add do begin Header := AppName; Result := GroupID; end; end; procedure TfrmMain.FormCreate(Sender: TObject); begin DoubleBuffered := True; SynEdit.DoubleBuffered := True; FMessageList := TList<TLiveQueryEntry>.Create; FSearchResult := TList<TLiveQueryEntry>.Create; FSearchObj := TLiveQuerySearch.Create; FAutoInc := 0; GenerateRandomData; lvQueries.Columns[0].Width := 80; lvQueries.Columns[1].Width := 165; end; procedure TfrmMain.FormDestroy(Sender: TObject); begin FMessageList.Free; FSearchResult.Free; FSearchObj.Destroy; end; procedure TfrmMain.lvQueriesChange(Sender: TObject; Item: TListItem; Change: TItemChange); var Entry: TLiveQueryEntry; begin if Assigned(lvQueries.Selected) and (lvQueries.Selected.SubItems.Text <> '') then begin Entry := FMessageList[Item.Index]; SynEdit.Text := Entry.Msg.Query; memMessage.Text := Entry.Msg.TextMessage; ResultSetToListView(Entry.Msg.Rows); memMessage.Visible := lvResult.Items.Count = 0; lvResult.Visible := not memMessage.Visible; end else begin SynEdit.Text := ''; memMessage.Text := ''; memMessage.Visible := False; lvResult.Visible := False; end; end; procedure TfrmMain.lvQueriesData(Sender: TObject; Item: TListItem); var Entry: TLiveQueryEntry; begin if not FFiltered then Entry := FMessageList[Item.Index] else Entry := FSearchResult[Item.Index]; Item.Caption := FormatDateTime('hh:mm:ss', Entry.TimeStamp); //Item.GroupID := FindOrCreateGroup(Entry.Msg.App); CreateNewTab(Entry.Msg.RemoteAddr); Item.SubItems.Add(Entry.Msg.Query); if Entry.Msg.Error then Item.ImageIndex := 3 else Item.ImageIndex := 4; end; procedure TfrmMain.ResultSetToListView(json: string); var Obj: ISuperObject; Item: TSuperAvlEntry; I: Integer; listItem: TListItem; Col: TListColumn; begin Obj := SO(json); try lvResult.Items.BeginUpdate; lvResult.Items.Clear; lvResult.Columns.Clear; if Obj.AsArray.Length = 0 then Exit; with lvResult.Columns.Add do begin Caption := ''; Width := 30; end; for Item in Obj.AsArray[0].AsObject do begin Col := lvResult.Columns.Add; Col.Width := -1; Col.Width := -2; Col.Caption := Item.Name; end; for I := 0 to Obj.AsArray.Length - 1 do begin listItem := lvResult.Items.Add; listItem.Caption := IntToStr(listItem.Index + 1); for Item in Obj.AsArray[I].AsObject do listItem.SubItems.Add(Item.Value.AsString); end; // ignore first column, which is the row number for I := 1 to lvResult.Columns.Count - 1 do if lvResult.Columns[i].Width < 100 then lvResult.Columns[i].Width := 100; finally lvResult.Items.EndUpdate; lvResult.Refresh; end; end; procedure TfrmMain.SearchListViewItems(str: string); var rec: TLiveQueryEntry; begin FSearchResult.Clear; FFiltered := True; for rec in FMessageList do begin if (str <> '') and (Pos(str, rec.Msg.Query) > 0) then begin FSearchResult.Add(rec); end; end; end; procedure TfrmMain.tc1Change(Sender: TObject); var group : string; begin group := tc1.Tabs[tc1.TabIndex]; FFiltered := True; if tc1.TabIndex = 0 then FFiltered := False else FSearchResult := FSearchObj.SearchListItems(FMessageList,group,true); DataProviderUpdated; end; procedure TfrmMain.UDPServerUDPRead(AThread: TIdUDPListenerThread; AData: TBytes; ABinding: TIdSocketHandle); var Msg: AnsiString; Obj: ISuperObject; Rec: TLiveQueryEntry; begin if not actnListen.Checked then Exit; SetString(Msg, PAnsiChar(@AData[0]), Length(AData)); Obj := SO(Msg); FlashWindow(Application.Handle, True); Rec.TimeStamp := Now; Rec.ID := FAutoInc; Inc(FAutoInc); Rec.Msg.Query := Obj.AsObject.S['query']; Rec.Msg.Error := Obj.AsObject.B['error']; Rec.Msg.TextMessage := Obj.AsObject.S['message']; Rec.Msg.Rows := Obj.AsObject.S['rows']; Rec.Msg.RemoteAddr := Obj.AsObject.S['remote_address']; // Entries te reja dalin ne fillim FMessageList.Insert(0, Rec); // Nese rekordet jane te filtruara i shtojme vetem nese bejne match // ndryshe shtohen pa kriter if FFiltered then begin if Pos(FSearchTerm, rec.Msg.Query) > 0 then begin FSearchResult.Insert(0, Rec); lvQueries.Items.Count := FSearchResult.Count; end; UpdateSearchLabel; end else begin lvQueries.Items.Count := FMessageList.Count; end; lvQueries.Invalidate; end; procedure TfrmMain.UpdateSearchLabel; begin lblResults.Caption := Format('Showing %d/%d records', [FSearchResult.Count, FMessageList.Count]); end; end.
{Projet: Démonstrateur d'accŐs directe clavier Date de rédaction: Mercredi le 28 novembre 2001 Nom du programmeur: Sylvain Maltais Groupe: Les Chevaliers de Malte - Développeur Pascal Configuration requise: Souris avec port PS/2 Courriel: gladir@hotmail.com Site INTERNET: http://gladir.multimania.com/ Description ═══════════ Ce programme effectue une démonstration de l'enfoncement des touches «Ctrl+Alt+Barre d'espacement» simultanément en accédant directement par le contrôleur clavier sans utiliser les interruptions ou les variables de BIOS. } Program RawKeyboard; Uses DOS; Const { Code brute du clavier } rqkEsc=1; { Escape} rqkCtrl=$1D; { Ctrl} rqkAlt=$38; { Alt} rqkSpaceBar=$39; { Barre d'espacement } Var {Variable de traitement clavier } Key:Array[0..127]of Boolean; { Tampon représenter chacune des touches possibles } AnyPressed:Boolean; { Indique si au moins une touche est enfoncée } {Variable de sauvegarde} OldInt09:Pointer; { Sauvegarde l'adresse de l'ancienne interruption 09h } { Nouvelle interruption clavier ů utiliser } Procedure NewInt09;Interrupt;Assembler;ASM STI XOR CH,CH MOV DX,060h IN AL,DX MOV CL,AL AND CL,07Fh MOV BX,Offset Key ADD BX,CX MOV SI,BX {$IFOPT G+} SHR AL,7 {$ELSE} ROL AL,1 AND AL,1 {$ENDIF} XOR AL,1 MOV [SI],AL MOV AnyPressed,AL MOV DX,061h IN AL,DX MOV CL,AL OR AL,080h OUT DX,AL MOV AL,CL OUT DX,AL MOV AX,020h MOV DX,AX OUT DX,AX CLI END; { Cette procédure initialise notre interruption 09h } Procedure InitInt09;Begin GetIntVec($09,OldInt09); SetIntVec($09,@NewInt09); FillChar(Key,SizeOf(Key),0); End; { Cette procédure remet l'ancienne interruption 09h } Procedure RestoreInt09;Begin SetIntVec($09,OldInt09); End; { Programme principal } BEGIN InitInt09; WriteLn('Presse ESC pour quitter...'); Repeat If Key[rqkCtrl]and Key[rqkAlt]and Key[rqkSpaceBar]Then WriteLn('Ctrl+Alt+Barre d''espacement enfoncé'); Until Key[rqkEsc]; RestoreInt09; END.
unit Logic; interface const StatPath = 'stats.txt'; DictPath = 'dict.dat'; Type StrMat = array of array of string; Tstr = string[20]; SetOfProbNumbers = set of 0 .. 49; PTNode = ^TNode; TNode = record // Стоит ли делать тип списка публичным???? Да Key: char; Word: string; NextKey, NextLvL: PTNode; end; TWord = record Word: String; Add_pos: byte; x: byte; y: byte; path: string; end; procedure ClearMatrix(var Mat: StrMat); procedure GetPosByTag(tag, size: integer; out i, j: byte); procedure InitData; procedure ReadDict; procedure rmDIct(tmp: PTNode); function IsWordInDict(str: string): boolean; function SelectWord(diff: byte): TWord; procedure AddPosibleTurn(str: string; Add_pos, x, y: byte; path: string); procedure AddTurn(str: string; whoChr: char); procedure SaveGame(path: string); procedure LoadGame(path: string); procedure WriteResult(winner, points, title: string); var PosibleWord: array of TWord; Dict: PTNode; TurnsArr: array of string; implementation uses System.SysUtils, BoardUnit; Const LenFL = 10; Type FileLine = array [1 .. LenFL] of string[20]; procedure ClearMatrix(var Mat: StrMat); var i, j: byte; begin for i := 0 to High(Mat) do for j := 0 to High(Mat) do Mat[i, j] := ''; end; procedure GetPosByTag(tag, size: integer; out i, j: byte); begin i := tag div size; j := tag mod size; end; function isWordInTurns(str: string): boolean; var i: Word; begin i := 0; while i <= High(TurnsArr) do begin if copy(TurnsArr[i], 0, high(TurnsArr[i]) - 2) = str then begin result := true; exit; end; inc(i); end; result := false; end; procedure AddWordToDict(str: string); var tmp: PTNode; i: byte; begin tmp := Dict; for i := 1 to Length(str) do begin if tmp^.NextLvL = nil then begin new(tmp^.NextLvL); // inc(count); tmp^.NextLvL^.Key := str[i]; tmp^.NextLvL^.Word := ''; tmp^.NextLvL^.NextKey := nil; tmp^.NextLvL^.NextLvL := nil; end; tmp := tmp^.NextLvL; while tmp^.Key <> str[i] do begin if tmp^.NextKey = nil then begin new(tmp^.NextKey); tmp^.NextKey^.Key := str[i]; tmp^.NextKey^.Word := ''; tmp^.NextKey^.NextKey := nil; tmp^.NextKey^.NextLvL := nil; end; tmp := tmp^.NextKey; end; end; tmp^.Word := str; end; function IsWordInDict(str: string): boolean; var i: byte; tmp: PTNode; begin tmp := Dict; for i := 1 to Length(str) do begin if tmp^.NextLvL = nil then begin result := false; exit; end else tmp := tmp^.NextLvL; while str[i] <> tmp^.Key do begin if tmp^.NextKey = nil then begin result := false; exit; end; tmp := tmp^.NextKey; end; end; if str = tmp^.Word then begin result := true; tmp^.Word := ''; end else result := false; end; procedure rmDIct(tmp: PTNode); begin if tmp^.NextLvL <> nil then rmDIct(tmp^.NextLvL); if tmp^.NextKey <> nil then rmDIct(tmp^.NextKey); Dispose(tmp); end; procedure InitData; begin Randomize; new(Dict); Dict.Key := ' '; // ??? Dict.Word := ''; Dict.NextKey := nil; Dict.NextLvL := nil; setLength(PosibleWord, 0); setLength(TurnsArr, 0); end; { function rmWord(str: string; Node: PTNode): boolean; begin if str = '' then exit; if Node^.NextLvL^.NextLvL^=nil and Node^.NextLvL^.NextKey = nil then while Node^.Key <> str[1] do Node := Node^.NextKey; if (Node^.NextLvL = nil) and (Node^.NextKey = nil) then begin Dispose(Node); result := true; exit end; while Node^.Key <> str[1] do Node := Node^.NextKey; end; } procedure ReadDict; var DictFile: TextFile; str: string; begin if not FileExists(DictPath) then exit; assign(DictFile, DictPath); reset(DictFile); while not EOF(DictFile) do begin readln(DictFile, str); if not isWordInTurns(str) then AddWordToDict(str); end; closeFile(DictFile); end; procedure AddTurn(str: string; whoChr: char); overload; var n: byte; begin n := Length(TurnsArr); setLength(TurnsArr, n + 1); TurnsArr[n] := str + '-' + whoChr; end; procedure AddTurn(str: string); overload; var n: byte; begin n := Length(TurnsArr); setLength(TurnsArr, n + 1); TurnsArr[n] := str; end; procedure WriteResult(winner, points, title: string); var saveFile: TextFile; begin assign(saveFile, StatPath); if not FileExists(StatPath) then begin rewrite(saveFile); writeln('СТАТИСТИКА ИГР'); close(saveFile); end; Append(saveFile); writeln(saveFile, DateToStr(Date) + ' ' + TimeToStr(Time) + '>' + title + '-' + winner + ' ' + points); close(saveFile); end; procedure SaveGame(path: string); var saveFile: file of FileLine; tmp: FileLine; i, j: byte; begin assign(saveFile, path); rewrite(saveFile); reset(saveFile); tmp[1] := inttostr(BoardFORM.BoardSize); tmp[2] := inttostr(BoardFORM.Difficult); write(saveFile, tmp); for j := 1 to BoardFORM.BoardSize do // Помни что массива для 5 на 5, 7*7 begin for i := 1 to BoardFORM.BoardSize do tmp[i] := BoardFORM.ValsOfCells[j, i]; for i := i to LenFL do tmp[i] := '0'; write(saveFile, tmp); end; i := 1; while (i <= Length(TurnsArr)) do begin tmp[(i - 1) mod LenFL + 1] := TurnsArr[i - 1]; if i mod (LenFL) = 0 then write(saveFile, tmp); inc(i); end; tmp[(i - 1) mod LenFL + 1] := 'END';; if i mod (LenFL) <> 0 then write(saveFile, tmp); close(saveFile); end; procedure LoadGame(path: string); var loadFile: file of FileLine; tmp: FileLine; i, j: byte; begin if not FileExists(path) then exit; assign(loadFile, path); reset(loadFile); read(loadFile, tmp); BoardFORM.BoardSize := strtoint(tmp[1]); BoardFORM.Difficult := strtoint(tmp[2]); setLength(BoardFORM.ValsOfCells, BoardFORM.BoardSize + 2, BoardFORM.BoardSize + 2); // Logic.ClearMatrix(BoardFORM.ValsOfCells); for i := 1 to BoardFORM.BoardSize do begin read(loadFile, tmp); for j := 1 to BoardFORM.BoardSize do BoardFORM.ValsOfCells[i, j] := tmp[j]; end; i := 1; read(loadFile, tmp); setLength(TurnsArr, 0); while tmp[i] <> 'END' do begin AddTurn(tmp[i]); if (i mod 10) = 0 then begin i := i mod 10; read(loadFile, tmp); end; inc(i); end; close(loadFile); end; procedure AddPosibleTurn(str: string; Add_pos, x, y: byte; path: string); var n: byte; begin n := Length(PosibleWord); setLength(PosibleWord, n + 1); PosibleWord[n].Word := str; PosibleWord[n].Add_pos := Add_pos; PosibleWord[n].x := x; PosibleWord[n].y := y; PosibleWord[n].path := path; end; function SelectWord(diff: byte): TWord; var i: Word; begin result := PosibleWord[0]; case diff of 0: for i := 0 to High(PosibleWord) do if Length(PosibleWord[i].Word) <= Length(result.Word) then result := PosibleWord[i]; 1: result := PosibleWord[random(high(PosibleWord))]; 2: for i := 0 to High(PosibleWord) do if Length(PosibleWord[i].Word) >= Length(result.Word) then result := PosibleWord[i]; end; end; end.
Program pr4ejer2; const CapacBloque = 64; PorcCarga = 0.9; { Uso las constantes que usaron ellos en el ejemplo } TAMANOLONGINT = 4; N = 1; { Cantidad de bytes que va leyendo } type docente = record { A pesar de que el archivo sea sin tipo, uso esto para almacenar temporalmente a la data que me llega } apellido: string; nombre: string; fecha: longint; end; dBloque = record cantRegs: word; contenido: array[0..CapacBloque] of byte; end; aDocentes = record arch: file; { ACA ESTA EL ARCHIVO SIN TIPO, es FILE y nada mas } espLibres: file of word; bloque: dBloques; iBloque: word; espLibreBloque; end; procedure agregar(var ad: aDocentes; dc: docente); var tamReg, aux: byte; libres: word; disponibles: integer; i: integer; begin tamRg := length(dc.apellido) + length(dc.nombre) + 6; { Es longitud + 6 ya que necesitamos guardar: tamaño del apellido + apellido, tamaño del nombre + nombre, y fecha que ocupa 4 bytes. } with ad do begin seek(espLibres, 0); repeat read(espLibres, libres); disponibles := libres - round((1-PorcCarga) * CapacBloque); until eof(espLibres) or (disponibles >= tagReg); if (tamReg > disponibles) then begin { Entra a este if solo si no hay espacio en ningun bloque, si no hay lo tenemos que agregar al final } bloque.cantRegs := 0; { incializamos la cantidad de registros del bloque que vamos a agregar, el agregado del bloque se hace mas adelante } libres := CapacBloque; iBloque := 0; { El iBloque lo empece en 0 porque dBloque.contenido va de 0..CapacBloque, pero si va de 1..CapacBloque+1, entonces iBloque := 1 } seek(arch, filesize(arch)); end else begin { Si entra aca quiere decir que encontramos un bloque con suficiente espacio como para almacenar nuestro registro } seek(arch, filepos(espLibres)-1); blockread(arch, bloque.cantRegs, 4); { Lee un word = 4 bytes } for i:= 0 to CapacBloque do blockread(arch, bloque.contenido[i], N); { Va leyendo de a un byte } read(arch, bloque); iBloque := CapacBloque - libres + 1; { actualizamos el indice del bloque donde vamos a agregar nuestro registro, lo ponemos en el comienzo del mismo } seek(arch, filepos(espLibres)-1); seek(espLibres, filepos(espLibres)-1); { Nos posicionamos para luego poder actualizar } end; aux := length(dc.apellido); move(dc.apellido, bloque.contenido[iBloque], aux); { Mandamos el dc.apellido al bloque, el move primero escribe la longitud del string y despues escribe el string, entonces si el apellido es PAN, el bloque.contenido = [ [3], [P], [A], [N] ] } Inc(iBloque, aux+1); { nos movemos dentro del bloque para poder escribir lo siguiente } aux := length(dc.nombre); move(dc.nombre, bloque.contenido[iBloque], aux); { lo mismo que el apellido pero para el nombre } Inc(iBloque, aux+1); { nos movemos dentro del bloque para poder escribir lo siguiente } move(dc.fecha, bloque.contenido[iBloque], TAMANOLONGINT); { Del long int ya sabemos que su tamaño es 4, asique no necesitamos calcular su length } Inc(iBloque, aux+1); { nos movemos dentro del bloque para poder escribir lo siguiente } Dec(libres, tamReg); { Actualizamos la cantidad de libres en el bloque actual } blockwrite(arch, bloque.cantRegs, 4); for i:=0 to (CapacBloque-libres) do blockwrite(arch, bloque.contenido[i], N) write(espLibres, libres); end; end; procedure primero(var ad: aDocentes; var dc: docente); var tamReg, lApellido, lNombre: byte; begin with ad do begin seek(arch, 0); seek(espLibre, 0); iBloque := 0; read(espLibres, espLibreBloque); blockread(arch, bloque.cantRegs, 4); for i:=0 to (CapacBloque-espLibreBloque) do blockread(arch, bloque.contenido[i], N); lApellido := bloque.contenido[0]; { tamaño del apellido } lNombre := bloque.contenido[lApellido+1]; tamReg := lApellido + lNombre + 6; { bloque.contenido[iBloque+aux+1] = tamaño del nombre } move(bloque.contenido[iBloque], dc.apellido, lApellido); Inc(iBloque, lApellido+1); move(bloque.contenido[iBloque], dc.nombre, lNombre); Inc(iBloque, lNombre+1); move(bloque.contenido[iBloque], dc.fecha, TAMANOLONGINT); Inc(iBloque, TAMANOLONGINT+1); end; end; procedure siguiente(var ad: aDocentes; var dc: docente); var tamReg, lApellido, lNombre: byte; begin with ad do begin { Primero analizamos si nos quedan mas registros en el bloque actual } if(iBloque>CapacBloque-espLibreBloque) then begin { Quiere decir que ya no hay mas registros en el bloque actual } blockread(arch, bloque.cantRegs, 4); { Leemos la cantidad de registros } read(espLibre, espLibreBloque) for i:=0 to (CapacBloque-espLibreBloque) do blockread(arch, bloque.contenido[i], N); iBloque := 0; end; { Ahora analizamos si nos quedan registros en el bloque para poder leerlos } if(iBloque < CapacBloque - espLibreBloque) then begin lApellido := bloque.contenido[iBloque]; { tamaño del apellido } lNombre := bloque.contenido[iBloque+lApellido+1]; tamReg := lApellido + lNombre + 6; { bloque.contenido[iBloque+aux+1] = tamaño del nombre } move(bloque.contenido[iBloque], dc.apellido, lApellido); Inc(iBloque, lApellido+1); move(bloque.contenido[iBloque], dc.nombre, lNombre); Inc(iBloque, lNombre+1); move(bloque.contenido[iBloque], dc.fecha, TAMANOLONGINT); Inc(iBloque, TAMANOLONGINT+1); end else dc.apellido := 'fin'; end; end; procedure obtener(var ad: aDocentes; var dc: docente; var resultado: boolean); var doc: docente; begin with ad do begin primero(ad, doc); while((doc.apellido <> 'fin')and((dc.nombre <>.docnombre)and(dc.apellido <> doc.apellido)and(dc.fecha <> doc.fecha))) do siguiente(ad, doc); if((doc.nombre = dc.nombre) and (doc.apellido = dc.apellido) and (doc.fecha = dc.fecha)) then resultado := true; else resultado := false; end; end; procedure eliminar(var ad: aDocentes; dc: docente; var: resultado: boolean); var restObt: boolean; resto: word; tamReg: byte; begin Obtener(ad, dc, resObt); { Devuele true dentro de resObt si ad.arch contiene a dc } if(resObt) then begin with ad do begin resto := CapacBloque - espLibreBloque - iBloque + 1; { Aca se calcula la cantidad de "bytes" que quedan en el bloque.contenido } tamReg := length(dc.nombre) + length(dc.apellido) + 2 + TAMANOLONGINT; if(resto > 0) then { Esto se hace solo si quedan elementos despues del registro que queremos eliminar } move(bloque.contenido[iBloque], bloque.contenido[iBloque - tamReg], resto); { Movemos lo que queda hacia atras, para ocupar el espacio del registro que estamos eliminando } dec(bloque.cantRegs); inc(espLibreBloque, tamReg); seek(arch, filepos(arch)-1); blockwrite(arch, bloque.cantRegs, 4); for i:=0 to (CapacBloque - espLibreBloque) do blockwrite(arch, bloque.contenido[i], N); seek(espLibre, filepos(arch)-1); write(espLibre, espLibreBloque); resultado := true end; end else resultado := false; { No lo encontro } end;
unit Lbsqlist; interface Uses SysUtils,StdCtrls,Classes,Buttons,Controls,ExtCtrls,Menus, Messages,SQLList,SQLCtrls,DBTables; Type TLabelSQLListBox=class(TSQLControl) protected BackUp:Integer; procedure WriteCaption(s:string); Function ReadCaption:String; procedure WriteDSN(s:string); Function ReadDSN:String; procedure WriteTable(s:string); Function ReadTable:String; procedure WriteID(s:string); Function ReadID:String; procedure WriteInfo(s:string); Function ReadInfo:String; procedure WriteWhere(s:string); Function ReadWhere:String; procedure WritePC(s:boolean); Function ReadPC:boolean; procedure WriteOnChange(s:TNotifyEvent); Function ReadOnChange:TNotifyEvent; procedure LBOnKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure LBOnEnter(Sender: TObject); procedure WriteOnItemChange(s:TNotifyEvent); Function ReadOnItemChange:TNotifyEvent; public Data:longint; Lbl:TLabel; SQLListBox:TSQLListBox; constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure WMSize(var Msg:TMessage); message WM_SIZE; function GetHeight:integer; procedure Value(sl:TStringList); override; procedure SetValue(var q:TQuery); override; procedure SetActive(l:longint); function GetData:longint; published property Caption:String read ReadCaption write WriteCaption; property Table:String read ReadTable write WriteTable; property DatabaseName:String read ReadDSN write WriteDSN; property IDField:String read ReadID write WriteID; property InfoField:String read ReadInfo write WriteInfo; property Where:String read ReadWhere write WriteWhere; property ParentColor:boolean read ReadPC write WritePC; property OnChange:TNotifyEvent read ReadOnChange write WriteOnChange; property OnItemChange:TNotifyEvent read ReadOnItemChange write WriteOnItemChange; property Align; property DragCursor; property DragMode; property Enabled; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; end; procedure Register; implementation Uses WinTypes; function TLabelSQLListBox.GetHeight:integer; begin GetHeight:=Height end; destructor TLabelSQLListBox.Destroy; begin Lbl.Free; SQLListBox.Free; inherited Destroy; end; constructor TLabelSQLListBox.Create(AOwner:TComponent); begin inherited create(AOwner); Lbl:=TLabel.Create(self); SQLListBox:=TSQLListBox.Create(self); Lbl.Parent:=self; SQLListBox.Parent:=self; Lbl.Left:=0; Lbl.Top:=0; SQLListBox.Left:=0; end; procedure TLabelSQLListBox.Value(sl:TStringList); var i:integer; begin if Assigned(fValueEvent) then fValueEvent(self,sl) else if (not Visible) or (SQLListBox.GetData=0) then sl.Add('NULL') else sl.Add(IntToStr(SQLListBox.GetData)); end; procedure TLabelSQLListbox.SetValue(var q:TQuery); begin if Assigned(fSetValueEvent) then fSetValueEvent(self,q) else SQLListbox.SetActive(q.FieldByName(fFieldName).AsInteger); end; procedure TLabelSQLListBox.WMSize(var Msg:TMessage); begin Lbl.Height:=-Lbl.Font.Height+3; Lbl.Width:=Msg.LParamLo; SQLListBox.Top:=Lbl.Height; SQLListBox.Height:=Msg.LParamHi-SQLListBox.Top; SQLListBox.Width:=Msg.LParamLo; Height:=Msg.LParamHi; Width:=Msg.LParamLo; end; procedure TLabelSQLListBox.WriteCaption(s:String); begin Lbl.Caption:=s end; function TLabelSQLListBox.ReadCaption:String; begin ReadCaption:=Lbl.Caption end; procedure TLabelSQLListBox.WriteDSN(s:String); begin SQLListBox.DatabaseName:=s end; function TLabelSQLListBox.ReadDSN:String; begin ReadDSN:=SQLListBox.DatabaseName end; procedure TLabelSQLListBox.WriteTable(s:String); begin SQLListBox.Table:=s end; function TLabelSQLListBox.ReadTable:String; begin ReadTable:=SQLListBox.Table end; procedure TLabelSQLListBox.WriteID(s:String); begin SQLListBox.IDField:=s end; function TLabelSQLListBox.ReadID:String; begin ReadID:=SQLListBox.IDField end; procedure TLabelSQLListBox.WriteInfo(s:String); begin SQLListBox.InfoField:=s end; function TLabelSQLListBox.ReadInfo:String; begin ReadInfo:=SQLListBox.InfoField end; procedure TLabelSQLListBox.WriteWhere(s:String); begin SQLListBox.Where:=s end; function TLabelSQLListBox.ReadWhere:String; begin ReadWhere:=SQLListBox.Where end; procedure TLabelSQLListBox.WritePC(s:boolean); begin SQLListBox.ParentColor:=s end; function TLabelSQLListBox.ReadPC:boolean; begin ReadPC:=SQLListBox.ParentColor end; procedure TLabelSQLListBox.WriteOnChange(s:TNotifyEvent); begin SQLListBox.OnClick:=s end; function TLabelSQLListBox.ReadOnChange:TNotifyEvent; begin ReadOnChange:=SQLListBox.OnClick end; procedure Register; begin RegisterComponents('MyOwn',[TLabelSQLListBox]) end; procedure TLabelSQLListBox.LBOnKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=VK_ESCAPE then SQLListBox.ItemIndex:=BackUp end; procedure TLabelSQLListBox.LBOnEnter(Sender: TObject); begin SQLListBox.SetFocus; BackUp:=SQLListBox.ItemIndex end; procedure TLabelSQLListBox.SetActive(l:longint); begin SQLListbox.SetActive(l) end; function TLabelSQLListBox.GetData:longint; begin GetData:=SQLListbox.GetData end; procedure TLabelSQLListBox.WriteOnItemChange(s:TNotifyEvent); begin SQLListBox.OnItemChange:=s end; Function TLabelSQLListBox.ReadOnItemChange:TNotifyEvent; begin ReadOnItemChange:=SQLListBox.OnItemChange; end; end.
unit VectorOnSelfTestCase; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; type { TVectorOnSelfTestCase } TVectorOnSelfTestCase = class(TVectorBaseTestCase) published procedure TestCompare; // these two test ensure we have data to play procedure TestCompareFalse; // with and tests the compare function. procedure TestpAddVector; procedure TestpAddSingle; procedure TestpSubVector; procedure TestpSubSingle; procedure TestpMulVector; procedure TestpMulSingle; procedure TestpDivVector; procedure TestpDivSingle; procedure TestpInvert; procedure TestpNegate; procedure TestpAbs; procedure TestpDivideBy2; procedure TestpCrossProduct; procedure TestpNormalize; procedure TestpMulAdd; procedure TestpMulDiv; procedure TestpClampVector; procedure TestpClampSingle; end; implementation {%region%====[ TVectorOnSelfTestCase ]=========================================} procedure TVectorOnSelfTestCase.TestCompare; begin AssertTrue('Test Values do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestCompareFalse; begin AssertFalse('Test Values should not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt2)); end; procedure TVectorOnSelfTestCase.TestpAddVector; begin nt1.pAdd(nt2); vt1.pAdd(vt2); AssertTrue('Vector pAdds Vectors do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpAddSingle; begin nt1.pAdd(Fs1); vt1.pAdd(Fs1); AssertTrue('Vector pAdd Singles do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpSubVector; begin nt1.pSub(nt2); vt1.pSub(vt2); AssertTrue('Vector pSub Vectors do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpSubSingle; begin nt1.pSub(Fs1); vt1.pSub(Fs1); AssertTrue('Vector pSub singles do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpMulVector; begin nt1.pMul(nt2); vt1.pMul(vt2); AssertTrue('Vector pMul Vectors do not match'+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpMulSingle; begin nt1.pMul(Fs1); vt1.pMul(Fs1); AssertTrue('Vector pMul singles do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpDivVector; begin nt1.pDiv(nt2); vt1.pDiv(vt2); AssertTrue('Vector pDiv Vectors do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpDivSingle; begin nt1.pDiv(Fs1); vt1.pDiv(Fs1); AssertTrue('Vector pDiv singles do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpInvert; begin nt1.pInvert; vt1.pInvert; AssertTrue('Vector pInverts do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpNegate; begin nt1.pNegate; vt1.pNegate; AssertTrue('Vector pNegates do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpAbs; begin nt1.pAbs; vt1.pAbs; AssertTrue('Vector pAbs do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpDivideBy2; begin nt1.pDivideBy2; vt1.pDivideBy2; AssertTrue('Vector pAbs do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpCrossProduct; begin nt1.pCrossProduct(nt2); vt1.pCrossProduct(vt2); AssertTrue('Vector pCrossProducts do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpNormalize; begin nt1.pNormalize; vt1.pNormalize; AssertTrue('Vector pNormalizes do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1, 1e-5)); end; procedure TVectorOnSelfTestCase.TestpMulAdd; begin nt1.pMulAdd(nt2, nt1); vt1.pMulAdd(vt2, vt1); AssertTrue('Vector pMulAdds do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpMulDiv; begin nt1.pMulDiv(nt2, nt1); vt1.pMulDiv(vt2, vt1); AssertTrue('Vector pMulDivs do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpClampVector; begin nt3 := nt1.DivideBy2; vt3.V := nt3.V; nt1.pClamp(nt2,nt3); vt1.pClamp(vt2,vt3); AssertTrue('Vector pClamp vectors do not match : '+nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; procedure TVectorOnSelfTestCase.TestpClampSingle; begin nt1.pClamp(fs2,fs1); vt1.pClamp(fs2,fs1); AssertTrue('Vector pClampSingle do not match : '+ nt1.ToString+' --> '+vt1.ToString, Compare(nt1,vt1)); end; {%endregion%} initialization RegisterTest(REPORT_GROUP_VECTOR4F, TVectorOnSelfTestCase); end.
Program ex1function; procedure Maior(a, b : integer); begin if (a > b) then writeln('O maior numero é : ', a) else if (b > a) then writeln('O maior numero é : ', b) else writeln('Os valores são iguais'); end; var c, d : integer; Begin write('Insira um número: '); read(c); write('Insira um número: '); read(d); Maior(c, d); End.
unit uJxdGpTrackBar; interface uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, GDIPAPI, GDIPOBJ, uJxdGpBasic, uJxdGpStyle, uJxdGpCommon; type TxdTrackBar = class(TxdGpCommon) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; protected FBufferBmp: TGPBitmap; //缓存图像 procedure Resize; override; procedure DoObjectChanged(Sender: TObject); override; function DoIsDrawSubItem(const Ap: PDrawInfo): Boolean; override; procedure DoSubItemMouseDown(const Ap: PDrawInfo); override; procedure DoSubItemMouseUp(const Ap: PDrawInfo); override; procedure DoControlStateChanged(const AOldState, ANewState: TxdGpUIState; const ACurPt: TPoint); override; procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE; private FSliderInfo, FOverItem: PDrawInfo; //滑块信息指针 FBuildingDrawInfo: Boolean; //是否进行生成绘制信息 FMouseDownPt: TPoint; FPrePosPiexl: Double; FChangeStyle: TxdChangedStyle; procedure ReBuildDrawInfo; //生成绘制信息 procedure FindSliderItem; //查找滑块信息 procedure ReCalcSliderInfo; //计算滑块的位置和大小 procedure DoNotifyPosChanged; private {自动生成属性信息} FTrackBarStyle: TxdScrollStyle; FShowSliderItem: Boolean; FPosition: Integer; FMax: Integer; FMin: Integer; FAllowChangedByMouse: Boolean; FOnPosChanged: TOnChangedNotify; procedure SetTrackBarStyle(const Value: TxdScrollStyle); procedure SetShowSliderItem(const Value: Boolean); procedure SetPosition(const Value: Integer); procedure SetMax(const Value: Integer); published property TrackBarStyle: TxdScrollStyle read FTrackBarStyle write SetTrackBarStyle; property ShowSliderItem: Boolean read FShowSliderItem write SetShowSliderItem; property AllowChangedByMouse: Boolean read FAllowChangedByMouse write FAllowChangedByMouse; property Min: Integer read FMin; property Max: Integer read FMax write SetMax; property Position: Integer read FPosition write SetPosition; property OnPosChanged: TOnChangedNotify read FOnPosChanged write FOnPosChanged; end; implementation const CtClickID_SliderButton = 0; //滑块按钮 CtClickID_Other = 1; //其它地方 CtLayoutBk = 0; CtLayoutOver = 1; CtLayoutSlider = 2; CtMinPerSlipPiexl = 2; //最小滚动像素点 { TxdTrackBar } constructor TxdTrackBar.Create(AOwner: TComponent); begin inherited; FBufferBmp := nil; FShowSliderItem := True; FMin := 0; FMax := 100; FPosition := 30; Width := 300; Height := 16; FTrackBarStyle := ssVerical; FBuildingDrawInfo := False; ImageDrawMethod.OnChange := nil; ImageDrawMethod.DrawStyle := dsDrawByInfo; FAllowChangedByMouse := True; ImageDrawMethod.OnChange := DoObjectChanged; end; destructor TxdTrackBar.Destroy; begin FreeAndNil( FBufferBmp ); inherited; end; procedure TxdTrackBar.DoControlStateChanged(const AOldState, ANewState: TxdGpUIState; const ACurPt: TPoint); begin inherited; if ANewState = uiDown then FMouseDownPt := ACurPt else FMouseDownPt := Point(0, 0); end; function TxdTrackBar.DoIsDrawSubItem(const Ap: PDrawInfo): Boolean; begin Result := True; if not ShowSliderItem and (Ap = FSliderInfo) then Result := False; end; procedure TxdTrackBar.DoNotifyPosChanged; begin if Assigned(FOnPosChanged) then FOnPosChanged( Self, FChangeStyle ); FChangeStyle := csNull; end; procedure TxdTrackBar.DoObjectChanged(Sender: TObject); begin if not ((Sender is TDrawMethod) or (Sender is TImageInfo)) then begin Inherited; Exit; end; if not FBuildingDrawInfo then begin FBuildingDrawInfo := True; try ReBuildDrawInfo; ReCalcSliderInfo; finally FBuildingDrawInfo := False; end; end; inherited; end; procedure TxdTrackBar.DoSubItemMouseDown(const Ap: PDrawInfo); var pt: TPoint; begin inherited; case Ap^.FClickID of CtClickID_Other: begin if AllowChangedByMouse then begin GetCursorPos(pt); pt := ScreenToClient(pt); FChangeStyle := csMouse; if FTrackBarStyle = ssVerical then Position := Round(pt.X / FPrePosPiexl) else Position := Round((Height - pt.Y) / FPrePosPiexl); end; end; end; end; procedure TxdTrackBar.DoSubItemMouseUp(const Ap: PDrawInfo); begin inherited; end; procedure TxdTrackBar.FindSliderItem; var i: Integer; p: PDrawInfo; begin FOverItem := nil; for i := 0 to ImageDrawMethod.CurDrawInfoCount - 1 do begin p := ImageDrawMethod.GetDrawInfo( i ); if Assigned(p) and (p^.FLayoutIndex = CtLayoutOver) then begin FOverItem := p; Break; end; end; FSliderInfo := nil; if not FShowSliderItem then Exit; for i := 0 to ImageDrawMethod.CurDrawInfoCount - 1 do begin p := ImageDrawMethod.GetDrawInfo( i ); if Assigned(p) and (p^.FClickID = CtClickID_SliderButton) then begin FSliderInfo := p; Break; end; end; end; procedure TxdTrackBar.ReBuildDrawInfo; var nBmpW, nBmpH: Integer; info: TDrawInfo; bmp: TGPBitmap; G: TGPGraphics; destPt: array[0..2] of TGPPoint; begin ImageDrawMethod.ClearDrawInfo; if not Assigned(ImageInfo.Image) or (ImageInfo.ImageCount < 2) then Exit; nBmpW := ImageInfo.Image.GetWidth; nBmpH := ImageInfo.Image.GetHeight; if FTrackBarStyle = ssVerical then begin //水平方式 if nBmpH > nBmpW then begin //将垂直图片修改成水平方式 bmp := TGPBitmap.Create( nBmpH, nBmpW, ImageInfo.Image.GetPixelFormat ); G := TGPGraphics.Create( bmp ); destPt[0] := MakePoint(0, Integer(bmp.GetHeight) ); destPt[1] := MakePoint(0, 0); destPt[2] := MakePoint( Integer(bmp.GetWidth), Integer(bmp.GetHeight) ); G.DrawImage( ImageInfo.Image, PGpPoint(@destPt), 3, 0, 0, nBmpW, nBmpH, UnitPixel ); FreeAndNil( FBufferBmp ); G.Free; FBufferBmp := bmp; ImageInfo.OnChange := nil; ImageInfo.Image := FBufferBmp; ImageInfo.OnChange := DoObjectChanged; end; nBmpW := Integer(ImageInfo.Image.GetWidth) div ImageInfo.ImageCount; nBmpH := ImageInfo.Image.GetHeight; // Height := nBmpH; //最低层背景 info.FText := ''; info.FClickID := CtClickID_Other; info.FLayoutIndex := CtLayoutBk; info.FDrawStyle := dsStretchByVH; info.FDestRect := MakeRect(0, 0, Width, nBmpH); info.FNormalSrcRect := MakeRect(0, 0, nBmpW, nBmpH); info.FActiveSrcRect := info.FNormalSrcRect; info.FDownSrcRect := info.FNormalSrcRect; ImageDrawMethod.AddDrawInfo( @info ); //已复盖部分 info.FClickID := CtClickID_Other; info.FLayoutIndex := CtLayoutOver; info.FDestRect := MakeRect(0, 0, Width, nBmpH); info.FNormalSrcRect := MakeRect(nBmpW, 0, nBmpW, nBmpH); info.FActiveSrcRect := info.FNormalSrcRect; info.FDownSrcRect := info.FNormalSrcRect; ImageDrawMethod.AddDrawInfo( @info ); if ImageInfo.ImageCount > 2 then begin //滑块 info.FClickID := CtClickID_SliderButton; info.FLayoutIndex := CtLayoutSlider; info.FDrawStyle := dsPaste; info.FDestRect := MakeRect(0, 0, nBmpW, nBmpH); info.FNormalSrcRect := MakeRect(nBmpW * 2, 0, nBmpW, nBmpH); if ImageInfo.ImageCount > 3 then info.FActiveSrcRect := MakeRect(nBmpW * 3, 0, nBmpW, nBmpH) else info.FActiveSrcRect := info.FNormalSrcRect; if ImageInfo.ImageCount > 4 then info.FDownSrcRect := MakeRect(nBmpW * 4, 0, nBmpW, nBmpH) else info.FDownSrcRect := info.FActiveSrcRect; ImageDrawMethod.AddDrawInfo( @info ); end else if ShowSliderItem then begin //滑块 info.FClickID := CtClickID_SliderButton; info.FLayoutIndex := CtLayoutSlider; info.FDrawStyle := dsStretchByVH; info.FDestRect := MakeRect(0, 0, nBmpW, nBmpH); info.FNormalSrcRect := MakeRect(0, 0, 0, 0); info.FActiveSrcRect := info.FNormalSrcRect; info.FDownSrcRect := info.FActiveSrcRect; ImageDrawMethod.AddDrawInfo( @info ); end; end else begin //垂直方式 if nBmpH < nBmpW then begin //将水平图片修改成垂直方式 bmp := TGPBitmap.Create( nBmpH, nBmpW, ImageInfo.Image.GetPixelFormat ); G := TGPGraphics.Create( bmp ); destPt[0] := MakePoint( Integer(bmp.GetWidth), 0 ); destPt[1] := MakePoint( Integer(bmp.GetWidth), Integer(bmp.GetHeight) ); destPt[2] := MakePoint( 0, 0 ); G.DrawImage( ImageInfo.Image, PGpPoint(@destPt), 3, 0, 0, nBmpW, nBmpH, UnitPixel ); FreeAndNil( FBufferBmp ); G.Free; FBufferBmp := bmp; ImageInfo.OnChange := nil; ImageInfo.Image := FBufferBmp; ImageInfo.OnChange := DoObjectChanged; end; nBmpW := ImageInfo.Image.GetWidth; nBmpH := Integer(ImageInfo.Image.GetHeight) div ImageInfo.ImageCount; Width := nBmpW; //最低层背景 info.FText := ''; info.FClickID := CtClickID_Other; info.FLayoutIndex := CtLayoutBk; info.FDrawStyle := dsStretchByVH; info.FDestRect := MakeRect(0, 0, nBmpW, Height); info.FNormalSrcRect := MakeRect(0, 0, nBmpW, nBmpH); info.FActiveSrcRect := info.FNormalSrcRect; info.FDownSrcRect := info.FNormalSrcRect; ImageDrawMethod.AddDrawInfo( @info ); //已复盖部分 info.FClickID := CtClickID_Other; info.FLayoutIndex := CtLayoutOver; info.FDestRect := MakeRect(0, 0, nBmpW, nBmpH); info.FNormalSrcRect := MakeRect(0, nBmpH, nBmpW, nBmpH); info.FActiveSrcRect := info.FNormalSrcRect; info.FDownSrcRect := info.FNormalSrcRect; ImageDrawMethod.AddDrawInfo( @info ); if ImageInfo.ImageCount > 2 then begin //滑块 info.FClickID := CtClickID_SliderButton; info.FLayoutIndex := CtLayoutSlider; info.FDrawStyle := dsPaste; info.FDestRect := MakeRect(0, 0, nBmpW, nBmpH); info.FNormalSrcRect := MakeRect(0, nBmpH * 2, nBmpW, nBmpH); if ImageInfo.ImageCount > 3 then info.FActiveSrcRect := MakeRect(0, nBmpH * 3, nBmpW, nBmpH) else info.FActiveSrcRect := info.FNormalSrcRect; if ImageInfo.ImageCount > 4 then info.FDownSrcRect := MakeRect(0, nBmpH * 4, nBmpW, nBmpH) else info.FDownSrcRect := info.FActiveSrcRect; ImageDrawMethod.AddDrawInfo( @info ); end else if ShowSliderItem then begin //滑块 info.FClickID := CtClickID_SliderButton; info.FLayoutIndex := CtLayoutSlider; info.FDrawStyle := dsPaste; info.FDestRect := MakeRect(0, 0, nBmpW, nBmpH); info.FNormalSrcRect := MakeRect(0, 0, 0, 0); info.FActiveSrcRect := info.FNormalSrcRect; info.FDownSrcRect := info.FActiveSrcRect; ImageDrawMethod.AddDrawInfo( @info ); end; end; FindSliderItem; end; procedure TxdTrackBar.ReCalcSliderInfo; begin if not Assigned(FOverItem) then Exit; if FTrackBarStyle = ssVerical then begin FPrePosPiexl := Width / Max; FOverItem^.FDestRect.Width := Round(FPrePosPiexl * Position); if Assigned(FSliderInfo) then begin FSliderInfo^.FDestRect.X := FOverItem^.FDestRect.Width - FSliderInfo^.FDestRect.Width div 2; if FSliderInfo^.FDestRect.X < 0 then FSliderInfo^.FDestRect.X := 0; if FSliderInfo^.FDestRect.X + FSliderInfo^.FDestRect.Width > Width then FSliderInfo^.FDestRect.X := Width - FSliderInfo^.FDestRect.Width; end; end else begin FPrePosPiexl := Height / Max; FOverItem^.FDestRect.Height := Round(FPrePosPiexl * Position); FOverItem^.FDestRect.Y := Height - FOverItem^.FDestRect.Height; if Assigned(FSliderInfo) then begin FSliderInfo^.FDestRect.Y := Height - FOverItem^.FDestRect.Height - FSliderInfo^.FDestRect.Height div 2; if FSliderInfo^.FDestRect.Y < 0 then FSliderInfo^.FDestRect.Y := 0; if FSliderInfo^.FDestRect.Y + FSliderInfo^.FDestRect.Height > Height then FSliderInfo^.FDestRect.Y := Height - FSliderInfo^.FDestRect.Height; end; end; end; procedure TxdTrackBar.Resize; begin inherited; ReBuildDrawInfo; ReCalcSliderInfo; end; procedure TxdTrackBar.SetMax(const Value: Integer); begin if (FMax <> Value) and (Value > FPosition) then begin FMax := Value; ReBuildDrawInfo; ReCalcSliderInfo; end; end; procedure TxdTrackBar.SetPosition(const Value: Integer); var R1, R2: TGPRect; begin if (FPosition <> Value) and (Value >= 0) and (Value <= FMax) then begin FPosition := Value; if Assigned(FSliderInfo) then R1 := FSliderInfo^.FDestRect; ReBuildDrawInfo; ReCalcSliderInfo; if Assigned(FSliderInfo) then begin R2 := FSliderInfo^.FDestRect; case FTrackBarStyle of ssVerical: begin if R1.X > R2.X then begin R1.Width := R1.X + R1.Width - R2.X + 1; R1.X := R2.X; end else R1.Width := R2.X + R2.Width - R1.X; end; ssHorizontal: begin if R1.Y > R2.Y then begin R1.Height := R1.Y + R1.Height - R2.Y + 1; R1.Y := R2.Y; end else R1.Height := R2.Y + R2.Height - R1.Y; end; end; InvalidateRect( R1 ); end; DoNotifyPosChanged; end; FChangeStyle := csNull; end; procedure TxdTrackBar.SetShowSliderItem(const Value: Boolean); begin if FShowSliderItem <> Value then begin FShowSliderItem := Value; FindSliderItem; end; end; procedure TxdTrackBar.SetTrackBarStyle(const Value: TxdScrollStyle); var nTemp: Integer; begin if FTrackBarStyle <> Value then begin FTrackBarStyle := Value; if FTrackBarStyle = ssVerical then begin if (csDesigning in ComponentState) and (Height > Width) then begin nTemp := Height; Height := Width; Width := nTemp; end; end else begin if (csDesigning in ComponentState) and (Height < Width) then begin nTemp := Height; Height := Width; Width := nTemp; end; end; ReBuildDrawInfo; ReCalcSliderInfo; end; end; procedure TxdTrackBar.WMMouseMove(var Message: TWMMouseMove); var nLen, nPos: Integer; p: PDrawInfo; begin inherited; if not AllowChangedByMouse then Exit; p := CurActiveSubItem; if Assigned(p) then begin if GetCurControlState = uiDown then begin case p^.FClickID of CtClickID_SliderButton: begin if FTrackBarStyle = ssVerical then nLen := Message.XPos - FMouseDownPt.X else nLen := FMouseDownPt.Y - Message.YPos; if abs(nLen) < Round(FPrePosPiexl) then Exit; nPos := Round( nLen / FPrePosPiexl ); if abs(nPos) > 0 then begin FMouseDownPt.X := Message.XPos; FMouseDownPt.Y := Message.YPos; FChangeStyle := csMouse; Position := Position + nPos; end; end; end; end; end; end; end.
{ Copyright 2019 Ideas Awakened Inc. Part of the "iaLib" shared code library for Delphi For more detail, see: https://github.com/ideasawakened/iaLib Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Module History 1.5 2023-Apr-23 Darian Miller: Add optional output capture for console applications 1.4 2023-Apr-20 Darian Miller: Removed API - no current plans of supporting other Operating Systems, but do have plans on more features for MS Windows 1.3 2023-Apr-20 Darian Miller: WaitForInputIdleMaxMS no longer used unless waiting for process completion as there's no need to slow down the StartProcess completion 1.2 2023-Apr-19 Darian Miller: Added ShowWindowState+ProcessCreationFlags 1.1 2019-Dec-26 Darian Miller: ASL-2.0 applied, complete refactor 1.0 2019-Dec-26 Darian Miller: Unit created using Delphi Dabbler's Public Domain code. } unit iaRTL.ProcessExecutor.Windows; interface uses System.Classes, System.SysUtils, WinAPI.Windows; type TReadPipeResult = (APIFailure, Success, BrokenPipe); TiaPipeHandles = record OurRead:THandle; ChildWrite:THandle; end; TiaCapture = record StdOutput:TiaPipeHandles; StdError:TiaPipeHandles; end; TiaLaunchContext = record CommandLine:string; StartupInfo:TStartupInfo; ProcessInfo:TProcessInformation; ExitCode:DWord; ErrorCode:DWord; ErrorMessage:string; IPC:TiaCapture; OutputCaptured:Boolean; procedure Finalize; end; TOnCaptureProc = reference to procedure(const Value:string); TiaWindowsProcessExecutor = class private const defWaitForCompletion = False; defWaitForInputIdleMaxMS = 750; defInheritHandles = False; defInheritParentEnvironmentVariables = True; private fContext:TiaLaunchContext; fEnvironmentVariables:TStringList; fInheritHandles:Boolean; fInheritParentEnvironmentVariables:Boolean; fProcessCreationFlags:DWord; fShowWindowState:Word; fWaitForInputIdleMaxMS:Integer; fOnStandardOutputCapture:TOnCaptureProc; fOnStandardErrorCapture:TOnCaptureProc; fCaptureEncoding:TEncoding; protected procedure CaptureSystemError(const aExtendedDescription:string); function CreateEnvironmentVariables(var aCustomList:TStringList):PChar; function DoCreateProcess(const aWorkingFolder:string; const aEnvironmentVarPtr:PChar):Boolean; function GetExitCode:Boolean; function TryReadFromPipes:TReadPipeResult; function SetupRedirectedIO(const CurrentProcess:THandle):Boolean; function WaitForProcessCompletion:Boolean; procedure WaitForProcessStabilization; public constructor Create; destructor Destroy; override; /// <summary> /// Executes the given command line and optionally waits for the program started by the /// command line to exit. If not waiting for the process to complete this returns True if /// the process was started, false otherwise. /// </summary> /// <remarks> /// WaitForCompletion is ignored if waiting on output capture /// </remarks> function LaunchProcess(const aCommandLine:string; const aWaitForCompletionFlag:Boolean = defWaitForCompletion; const aWorkingFolder:string = ''):Boolean; overload; /// <summary> /// Context of the child application process for inspection/logging purposes /// </summary> property Context:TiaLaunchContext read fContext; /// <summary> /// The initial window state can be customized to one of the SW_xxx values used by ShowWindow calls. /// For list of valid values, see: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow /// </summary> /// <remarks> /// You may want to set to SW_HIDE when waiting for console apps to complete to prevent the console window from appearing /// </remarks> property ShowWindowState:Word read fShowWindowState write fShowWindowState; /// <summary> /// Optionally used to set environment variables available to the launched process (in the style of Name=Value, non-duplicate/sorted list) /// </summary> property EnvironmentVariables:TStringList read fEnvironmentVariables write fEnvironmentVariables; /// <summary> /// Can customize the use of parent environment variables /// </summary> /// <remarks> /// Current default is True /// </remarks> property InheritParentEnvironmentVariables:Boolean read fInheritParentEnvironmentVariables write fInheritParentEnvironmentVariables; /// <summary> /// Can optionally capture the hStdOutput content of a child process /// </summary> property OnStandardOutputCapture:TOnCaptureProc read fOnStandardOutputCapture write fOnStandardOutputCapture; /// <summary> /// Can optionally capture the hStdError content of a child process /// </summary> property OnStandardErrorCapture:TOnCaptureProc read fOnStandardErrorCapture write fOnStandardErrorCapture; /// <summary> /// If capturing output of a child process, can optionally customize the TEncoding.ANSI default /// </summary> property CaptureEncoding:TEncoding read fCaptureEncoding write fCaptureEncoding; /// <summary> /// This is the dwCreationFlags parameter to CreateProcess which control the priority class and the creation of the process /// For list of valid values, see: https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags /// </summary> /// <remarks> /// The CREATE_UNICODE_ENVIRONMENT flag is automatically added if custom environment variables are used /// The CREATE_NEW_CONSOLE flag is automatically added if capturing output /// </remarks> property ProcessCreationFlags:DWord read fProcessCreationFlags write fProcessCreationFlags; /// <summary> /// Delay passed to WaitForInputIdle after launching a new process, granting the process time to startup and become idle /// </summary> /// <remarks> /// Value not used unless waiting for process completion. /// Current default is 750ms /// </remarks> property WaitForInputIdleMaxMS:Integer read fWaitForInputIdleMaxMS write fWaitForInputIdleMaxMS; /// <summary> /// By default, passing TRUE as the value of the bInheritHandles parameter causes all inheritable handles to be inherited by the new process. /// If the parameter is FALSE, the handles are not inherited. Note that inherited handles have the same value and access rights as the original handles. /// This can be problematic for applications which create processes from multiple threads simultaneously yet desire each process to inherit different handles. /// Applications can use the UpdateProcThreadAttributeList function with the PROC_THREAD_ATTRIBUTE_HANDLE_LIST parameter to provide a list of handles to be inherited by a particular process. /// </summary> /// <remarks> /// Current default is False /// The bInheritHandles parameter is automatically set to true if capturing output of a Console process /// </remarks> property InheritHandles:Boolean read fInheritHandles write fInheritHandles; end; /// <summary> /// Executes the given command line and waits for the program started by the /// command line to exit. Returns true if the program returns a zero exit code and /// false if the program doesn't start or returns a non-zero error code. /// </summary> function ExecAndWait(const aCommandLine:string; const aWorkingFolder:string = ''):Boolean; /// <summary> /// Executes the given command line and waits for it to complete while redirecting the output to the provided events (and the console window is hidden) /// By default, the captured text is assumed to be ANSI. If your launched applications outputs Unicode to StdOut then pass in TEncoding.Unicode; /// By default, your CommandLine will be prefixed with 'CMD /C ' which is required for commands like "dir *.txt" (The COMSPEC environment variable used to determine CMD) /// </summary> function ExecAndCaptureOutuput(const aCommandLine:string; const aOnStandardOutput:TOnCaptureProc; const aOnStandardError:TOnCaptureProc; const aCaptureEncoding:TEncoding = nil; const aAddCommandPrefix:Boolean = True; const aWorkingFolder:string = ''):Boolean; /// <summary> /// Executes the given command line and does not wait for it to finish runing before returning /// </summary> function StartProcess(const aCommandLine:string; const aWorkingFolder:string = ''):Boolean; implementation uses iaRTL.EnvironmentVariables.Windows, iaWin.Utils; function ExecAndWait(const aCommandLine:string; const aWorkingFolder:string = ''):Boolean; var ProcessExecutor:TiaWindowsProcessExecutor; begin ProcessExecutor := TiaWindowsProcessExecutor.Create; try Result := ProcessExecutor.LaunchProcess(aCommandLine, { WaitForCompletion= } True, aWorkingFolder); finally ProcessExecutor.Free; end; end; function StartProcess(const aCommandLine:string; const aWorkingFolder:string = ''):Boolean; var ProcessExecutor:TiaWindowsProcessExecutor; begin ProcessExecutor := TiaWindowsProcessExecutor.Create; try Result := ProcessExecutor.LaunchProcess(aCommandLine, { WaitForCompletion = } False, aWorkingFolder); finally ProcessExecutor.Free; end; end; function ExecAndCaptureOutuput(const aCommandLine:string; const aOnStandardOutput:TOnCaptureProc; const aOnStandardError:TOnCaptureProc; const aCaptureEncoding:TEncoding=nil; const aAddCommandPrefix:Boolean=True; const aWorkingFolder:string = ''):Boolean; var ProcessExecutor:TiaWindowsProcessExecutor; CmdLine:String; begin ProcessExecutor := TiaWindowsProcessExecutor.Create; try ProcessExecutor.ShowWindowState := SW_HIDE; ProcessExecutor.OnStandardOutputCapture := aOnStandardOutput; ProcessExecutor.OnStandardErrorCapture := aOnStandardError; if Assigned(aCaptureEncoding) then begin ProcessExecutor.CaptureEncoding := aCaptureEncoding; end; if aAddCommandPrefix then begin CmdLine := GetEnvironmentVariable('COMSPEC') + ' /C ' + aCommandLine; end else begin CmdLine := aCommandLine; end; Result := ProcessExecutor.LaunchProcess(CmdLine, { WaitForCompletion= } True, aWorkingFolder); finally ProcessExecutor.Free; end; end; constructor TiaWindowsProcessExecutor.Create; begin inherited; fEnvironmentVariables := TStringList.Create; fEnvironmentVariables.Sorted := True; fEnvironmentVariables.Duplicates := TDuplicates.dupIgnore; fInheritParentEnvironmentVariables := defInheritParentEnvironmentVariables; fInheritHandles := defInheritHandles; // Process creation flags default of 0: The process inherits both the error mode of the caller and the parent's console // And the environment block for the new process is assumed to contain ANSI characters fProcessCreationFlags := 0; fShowWindowState := SW_SHOWDEFAULT; fWaitForInputIdleMaxMS := defWaitForInputIdleMaxMS; fCaptureEncoding := TEncoding.ANSI; end; destructor TiaWindowsProcessExecutor.Destroy; begin fEnvironmentVariables.Free; inherited; end; function TiaWindowsProcessExecutor.LaunchProcess(const aCommandLine:string; const aWaitForCompletionFlag:Boolean = defWaitForCompletion; const aWorkingFolder:string = ''):Boolean; var EnvironmentListForChildProcess:TStringList; EnvironmentVars:PChar; begin Result := False; fContext := Default(TiaLaunchContext); fContext.StartupInfo.cb := SizeOf(fContext.StartupInfo); fContext.CommandLine := aCommandLine; if ShowWindowState <> SW_SHOWDEFAULT then begin fContext.StartupInfo.dwFlags := fContext.StartupInfo.dwFlags or STARTF_USESHOWWINDOW; fContext.StartupInfo.wShowWindow := ShowWindowState; // SW_HIDE, SW_SHOWNORMAL... end; EnvironmentVars := CreateEnvironmentVariables(EnvironmentListForChildProcess); try if Assigned(OnStandardOutputCapture) or Assigned(OnStandardErrorCapture) then begin if not SetupRedirectedIO(GetCurrentProcess) then Exit(False); fContext.OutputCaptured := True; end; if DoCreateProcess(aWorkingFolder, EnvironmentVars) then begin try if fContext.OutputCaptured then begin // These are no longer used in this parent process // "You need to make sure that no handles to the write end of the // output pipe are maintained in this process or else the pipe will // not close when the child process exits and the ReadFile will hang." TiaWinUtils.CloseHandle(fContext.IPC.StdOutput.ChildWrite); TiaWinUtils.CloseHandle(fContext.IPC.StdError.ChildWrite); end; if aWaitForCompletionFlag or fContext.OutputCaptured then begin WaitForProcessStabilization; if WaitForProcessCompletion and GetExitCode then begin if fContext.ExitCode = 0 then begin Result := True; end else begin fContext.ErrorCode := fContext.ExitCode; fContext.ErrorMessage := 'Child process completed with ExitCode ' + fContext.ExitCode.ToString; end; end; end else begin Result := True; end; finally fContext.Finalize; end; end; finally EnvironmentListForChildProcess.Free; end; end; // Note: When adding custom environment variables, the parent's variables are not inherited by CreateProcess which may, or may not, be desired. Use InheritParentEnvironmentVariables to decide. function TiaWindowsProcessExecutor.CreateEnvironmentVariables(var aCustomList:TStringList):PChar; begin aCustomList := nil; if EnvironmentVariables.Count > 0 then begin ProcessCreationFlags := ProcessCreationFlags or CREATE_UNICODE_ENVIRONMENT; // by default, environment assumes ANSI, since we're using Unicode strings (assuming D2009+), need to tell Windows to expect Unicdoe characters if InheritParentEnvironmentVariables then begin aCustomList := TStringList.Create; aCustomList.Sorted := True; // list must be sorted aCustomList.Duplicates := TDuplicates.dupIgnore; // and the list should only contain unique names aCustomList.Assign(EnvironmentVariables); // our custom list takes priority GetEnvironmentVariables(aCustomList); // then add any other unique variables from parent (duplicates ignored) Result := CreateEnvironmentBlock(aCustomList); end else begin Result := CreateEnvironmentBlock(EnvironmentVariables); // will only use our custom list, no parent variables inherited end; end else begin if InheritParentEnvironmentVariables then begin Result := nil; // if a custom list is not provided, then CreateProcess automatically inherits environment from parent end else begin // A special case - we aren't specifying a list of custom environment variables, but we don't want the parent's environment either ProcessCreationFlags := ProcessCreationFlags or CREATE_UNICODE_ENVIRONMENT; aCustomList := TStringList.Create; // empty list Result := CreateEnvironmentBlock(aCustomList); end; end; end; // https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createpipe // https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-sethandleinformation function TiaWindowsProcessExecutor.SetupRedirectedIO(const CurrentProcess:THandle):Boolean; function SetupPipe(var PipeHandles:TiaPipeHandles; sa:TSecurityAttributes; const Description:string):Boolean; begin // Create a pair of handles - one for reading from the pipe and another for writing to the pipe. // Final param is the size of the buffer for the pipe, in bytes. // The size is only a suggestion; the system uses the value to calculate an appropriate buffering mechanism. // If this parameter is zero, the system uses the default buffer size. if CreatePipe(PipeHandles.OurRead, PipeHandles.ChildWrite, @sa, 0) then begin if SetHandleInformation(PipeHandles.OurRead, HANDLE_FLAG_INHERIT, 0) then // Other examples call DuplicateHandle on a temp handle used in CreatePipe, with Inherited property set to False begin Result := True; end else begin CaptureSystemError(Description + ' SetHandleInformation on read handle failed'); Result := False; end; end else begin CaptureSystemError(Description + ' CreatePipe failed'); Result := False; end; end; var PipeSA:TSecurityAttributes; begin Result := True; PipeSA := Default(TSecurityAttributes); PipeSA.nLength := SizeOf(TSecurityAttributes); PipeSA.lpSecurityDescriptor := nil; PipeSA.bInheritHandle := True; if Assigned(OnStandardOutputCapture) then begin if not SetupPipe(fContext.IPC.StdOutput, PipeSA, 'hStdOutput') then Exit(False); fContext.StartupInfo.hStdOutput := fContext.IPC.StdOutput.ChildWrite; end else begin fContext.StartupInfo.hStdOutput := GetStdHandle(STD_OUTPUT_HANDLE); end; if Assigned(fOnStandardErrorCapture) then begin if not SetupPipe(fContext.IPC.StdError, PipeSA, 'hStdError') then Exit(False); fContext.StartupInfo.hStdError := fContext.IPC.StdError.ChildWrite; end else begin fContext.StartupInfo.hStdError := GetStdHandle(STD_ERROR_HANDLE); end; fContext.StartupInfo.dwFlags := fContext.StartupInfo.dwFlags or STARTF_USESTDHANDLES; // *** When capturing, STARTF_USESTDHANDLES must be set AND the bInheritHandles parameter to CreateProcess must be set True fContext.StartupInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); // If this flag is not specified when a console process is created, both processes are attached to the same console, // and there is no guarantee that the correct process will receive the input intended for it ProcessCreationFlags := ProcessCreationFlags or CREATE_NEW_CONSOLE; end; // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw function TiaWindowsProcessExecutor.DoCreateProcess(const aWorkingFolder:string; const aEnvironmentVarPtr:PChar):Boolean; var CurrentDirectoryPtr:PChar; ShouldInheritHandles:Boolean; CmdLine:string; begin if aWorkingFolder = '' then begin CurrentDirectoryPtr := nil; end else begin CurrentDirectoryPtr := PChar(aWorkingFolder); end; ShouldInheritHandles := InheritHandles or fContext.OutputCaptured; // *** When capturing, STARTF_USESTDHANDLES must be set AND the bInheritHandles parameter to CreateProcess must be set True // see: http://edn.embarcadero.com/article/38693 // The Unicode version of this function, CreateProcessW, can modify the contents of this string. // Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). // If this parameter is a constant string, the function may cause an access violation // also: https://stackoverflow.com/questions/6705532/access-violation-in-function-createprocess-in-delphi-2009 CmdLine := fContext.CommandLine; UniqueString(CmdLine); Result := CreateProcess(nil, PChar(CmdLine), nil, nil, ShouldInheritHandles, ProcessCreationFlags, aEnvironmentVarPtr, CurrentDirectoryPtr, fContext.StartupInfo, fContext.ProcessInfo); if not Result then begin CaptureSystemError('CreateProcess failed'); end; end; // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-waitforinputidle?redirectedfrom=MSDN // ex: https://www.tek-tips.com/viewthread.cfm?qid=1443661 procedure TiaWindowsProcessExecutor.WaitForProcessStabilization; begin // If immediately inspecting a newly launched child process, should give it time to stabilize if WaitForInputIdleMaxMS > 0 then begin { MS: WaitForInputIdle can be useful for synchronizing a parent process and a newly created child process. When a parent process creates a child process, the CreateProcess function returns without waiting for the child process to finish its initialization. Before trying to communicate with the child process, the parent process can use the WaitForInputIdle function to determine when the child's initialization has been completed. For example, the parent process should use the WaitForInputIdle function before trying to find a window associated with the child process. Note: can be used at any time, not just during application startup. However, WaitForInputIdle waits only once for a process to become idle; subsequent calls return immediately, whether the process is idle or busy. Note: If this process is a console application or does not have a message queue, WaitForInputIdle returns immediately. } WaitForInputIdle(fContext.ProcessInfo.hProcess, WaitForInputIdleMaxMS); end; end; // NOTE: neither method handles windows messages - if called by main thread, it will be blocked while waiting // https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject function TiaWindowsProcessExecutor.WaitForProcessCompletion:Boolean; var WaitResult:DWord; PipeResult:TReadPipeResult; BrokenPipe:Boolean; begin if fContext.OutputCaptured then // Poll pipes while waiting for process to exit begin BrokenPipe := False; repeat WaitResult := WaitForSingleObject(fContext.ProcessInfo.hProcess, 200); if (WaitResult = WAIT_TIMEOUT) and (not BrokenPipe) then begin PipeResult := TryReadFromPipes; if PipeResult = TReadPipeResult.APIFailure then begin Exit(False); end else if PipeResult = TReadPipeResult.BrokenPipe then begin BrokenPipe := True; WaitResult := WAIT_OBJECT_0; //usually caught by WaitForSingleObject, but pipe is down so process is finished end; end; until WaitResult <> WAIT_TIMEOUT; if WaitResult = WAIT_OBJECT_0 then begin if not BrokenPipe then // try to read any remaining data left in the buffer begin Result := TryReadFromPipes <> TReadPipeResult.APIFailure; end else // process complete + no data left in buffer to read begin Result := True; end; end else begin Result := False; CaptureSystemError('Polling WaitForProcessCompletion failed'); end; end else // Simply wait for process to exit begin if WaitForSingleObject(fContext.ProcessInfo.hProcess, INFINITE) = WAIT_OBJECT_0 then begin Result := True; end else begin Result := False; CaptureSystemError('WaitForProcessCompletion failed'); end; end; end; // https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-peeknamedpipe // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfile function TiaWindowsProcessExecutor.TryReadFromPipes:TReadPipeResult; function PeekRead(const hOurRead:THandle; const EventToCall:TOnCaptureProc):TReadPipeResult; var BytesAvailable:DWord; BytesRead:DWord; PipeData:TBytes; begin Result := TReadPipeResult.BrokenPipe; if PeekNamedPipe(hOurRead, nil, 0, nil, @BytesAvailable, nil) then begin if BytesAvailable = 0 then Exit(TReadPipeResult.Success); SetLength(PipeData, BytesAvailable); if ReadFile(hOurRead, PipeData[0], BytesAvailable, BytesRead, nil) then begin Result := TReadPipeResult.Success; if BytesRead < BytesAvailable then begin SetLength(PipeData, BytesRead); end; if Assigned(EventToCall) then begin EventToCall(CaptureEncoding.GetString(PipeData)); end; end else begin Result := TReadPipeResult.APIFailure; CaptureSystemError('ReadFile after PeekNamedPipe failed'); end; end else if GetLastError <> ERROR_BROKEN_PIPE then begin Result := TReadPipeResult.APIFailure; CaptureSystemError('PeekNamedPipe failed'); end; end; begin Result := TReadPipeResult.Success; if Assigned(OnStandardOutputCapture) then begin Result := PeekRead(fContext.IPC.StdOutput.OurRead, OnStandardOutputCapture); end; if (Result = TReadPipeResult.Success) and Assigned(OnStandardErrorCapture) then begin Result := PeekRead(fContext.IPC.StdError.OurRead, OnStandardErrorCapture); end; end; // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodeprocess function TiaWindowsProcessExecutor.GetExitCode:Boolean; begin Result := GetExitCodeProcess(fContext.ProcessInfo.hProcess, fContext.ExitCode); if not Result then begin CaptureSystemError('GetExitCode failed'); end; end; // https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror procedure TiaWindowsProcessExecutor.CaptureSystemError(const aExtendedDescription:string); begin fContext.ErrorCode := GetLastError; fContext.ErrorMessage := '[' + aExtendedDescription + '] ' + SysErrorMessage(fContext.ErrorCode); end; procedure TiaLaunchContext.Finalize; begin TiaWinUtils.CloseHandle(ProcessInfo.hProcess); TiaWinUtils.CloseHandle(ProcessInfo.hThread); if OutputCaptured then begin TiaWinUtils.CloseHandle(IPC.StdOutput.OurRead); TiaWinUtils.CloseHandle(IPC.StdOutput.ChildWrite); TiaWinUtils.CloseHandle(IPC.StdError.OurRead); TiaWinUtils.CloseHandle(IPC.StdError.ChildWrite); end; end; // reminder // WaitForInputIdle shouldn't use INFINITE // https://stackoverflow.com/questions/46221282/c-builder-10-2-thread-blocks-waitforinputidle // may block for 25 days :) // https://stackoverflow.com/questions/10711070/can-process-waitforinputidle-return-false end.
{******************************************************************************* Title: T2Ti ERP Fenix Description: Service relacionado à tabela [COLABORADOR] The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (alberteije@gmail.com) @version 1.0.0 *******************************************************************************} unit ColaboradorService; interface uses Colaborador, Usuario, Pessoa, Cargo, Setor, System.SysUtils, System.Generics.Collections, ServiceBase, MVCFramework.DataSet.Utils; type TColaboradorService = class(TServiceBase) private class procedure AnexarObjetosVinculados(AListaColaborador: TObjectList<TColaborador>); overload; class procedure AnexarObjetosVinculados(AColaborador: TColaborador); overload; class procedure InserirObjetosFilhos(AColaborador: TColaborador); class procedure ExcluirObjetosFilhos(AColaborador: TColaborador); public class function ConsultarLista: TObjectList<TColaborador>; class function ConsultarListaFiltroValor(ACampo: string; AValor: string): TObjectList<TColaborador>; class function ConsultarObjeto(AId: Integer): TColaborador; class procedure Inserir(AColaborador: TColaborador); class function Alterar(AColaborador: TColaborador): Integer; class function Excluir(AColaborador: TColaborador): Integer; end; var sql: string; implementation { TColaboradorService } class procedure TColaboradorService.AnexarObjetosVinculados(AColaborador: TColaborador); begin // Usuario sql := 'SELECT * FROM USUARIO WHERE ID_COLABORADOR = ' + AColaborador.Id.ToString; AColaborador.Usuario := GetQuery(sql).AsObject<TUsuario>; // Pessoa sql := 'SELECT * FROM PESSOA WHERE ID = ' + AColaborador.IdPessoa.ToString; AColaborador.Pessoa := GetQuery(sql).AsObject<TPessoa>; // Cargo sql := 'SELECT * FROM CARGO WHERE ID = ' + AColaborador.IdCargo.ToString; AColaborador.Cargo := GetQuery(sql).AsObject<TCargo>; // Setor sql := 'SELECT * FROM SETOR WHERE ID = ' + AColaborador.IdSetor.ToString; AColaborador.Setor := GetQuery(sql).AsObject<TSetor>; end; class procedure TColaboradorService.AnexarObjetosVinculados(AListaColaborador: TObjectList<TColaborador>); var Colaborador: TColaborador; begin for Colaborador in AListaColaborador do begin AnexarObjetosVinculados(Colaborador); end; end; class function TColaboradorService.ConsultarLista: TObjectList<TColaborador>; begin sql := 'SELECT * FROM COLABORADOR ORDER BY ID'; try Result := GetQuery(sql).AsObjectList<TColaborador>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TColaboradorService.ConsultarListaFiltroValor(ACampo, AValor: string): TObjectList<TColaborador>; begin sql := 'SELECT * FROM COLABORADOR where ' + ACampo + ' like "%' + AValor + '%"'; try Result := GetQuery(sql).AsObjectList<TColaborador>; AnexarObjetosVinculados(Result); finally Query.Close; Query.Free; end; end; class function TColaboradorService.ConsultarObjeto(AId: Integer): TColaborador; begin sql := 'SELECT * FROM COLABORADOR WHERE ID = ' + IntToStr(AId); try GetQuery(sql); if not Query.Eof then begin Result := Query.AsObject<TColaborador>; AnexarObjetosVinculados(Result); end else Result := nil; finally Query.Close; Query.Free; end; end; class procedure TColaboradorService.Inserir(AColaborador: TColaborador); begin AColaborador.ValidarInsercao; AColaborador.Id := InserirBase(AColaborador, 'COLABORADOR'); InserirObjetosFilhos(AColaborador); end; class function TColaboradorService.Alterar(AColaborador: TColaborador): Integer; begin AColaborador.ValidarAlteracao; Result := AlterarBase(AColaborador, 'COLABORADOR'); ExcluirObjetosFilhos(AColaborador); InserirObjetosFilhos(AColaborador); end; class procedure TColaboradorService.InserirObjetosFilhos(AColaborador: TColaborador); begin // Usuario AColaborador.Usuario.IdColaborador := AColaborador.Id; InserirBase(AColaborador.Usuario, 'USUARIO'); end; class function TColaboradorService.Excluir(AColaborador: TColaborador): Integer; begin AColaborador.ValidarExclusao; ExcluirObjetosFilhos(AColaborador); Result := ExcluirBase(AColaborador.Id, 'COLABORADOR'); end; class procedure TColaboradorService.ExcluirObjetosFilhos(AColaborador: TColaborador); begin ExcluirFilho(AColaborador.Id, 'USUARIO', 'ID_COLABORADOR'); end; end.
unit SDLTimer; interface uses Timer, SDL; type TSDLTimer = class(TTimer) private protected function GetElapsedTime: Cardinal; override; function GetFramesPerSecond: Byte; override; procedure SetLockedFramesPerSecond(const Value: Byte); override; public procedure Initialise; override; published end; implementation { TSDLTimer } function TSDLTimer.GetElapsedTime: Cardinal; begin FLastTime := FElapsedTime; FElapsedTime := SDL_GetTicks - FStartTime; // Calculate Elapsed Time FElapsedTime :=(FLastTime + ElapsedTime) shr 1; // Average it out for smoother movement result := FElapsedTime; end; function TSDLTimer.GetFramesPerSecond: Byte; begin end; procedure TSDLTimer.Initialise; begin FStartTime := SDL_GetTicks; end; procedure TSDLTimer.SetLockedFramesPerSecond(const Value: Byte); begin FLockedFramesPerSecond := Value; end; end.
unit State; interface uses Registrator, BaseObjects, Classes; type // причины ликвидации TAbandonReason = class (TRegisteredIDObject) public constructor Create (ACollection: TIDObjects); override; end; TAbandonReasons = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TAbandonReason; public property Items[Index: Integer]: TAbandonReason read GetItems; Constructor Create; override; end; // причины ликвидации скважины TAbandonReasonWell = class (TAbandonReason) private FDtLiquidation: TDateTime; protected procedure AssignTo(Dest: TPersistent); override; public // дата ликвидации property DtLiquidation: TDateTime read FDtLiquidation write FDtLiquidation; constructor Create (ACollection: TIDObjects); override; end; TAbandonReasonWells = class (TAbandonReasons) private function GetItems(Index: Integer): TAbandonReasonWell; public property Items[Index: Integer]: TAbandonReasonWell read GetItems; Constructor Create; override; end; // cостояние скважины TState = class (TRegisteredIDObject) public constructor Create (ACollection: TIDObjects); override; end; TStates = class (TRegisteredIDObjects) private function GetItems(Index: Integer): TState; public property Items[Index: Integer]: TState read GetItems; Constructor Create; override; end; implementation uses Facade, StatePoster; { TWellState } constructor TState.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Состояние скважины'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TStateDataPoster]; end; { TWellStates } constructor TStates.Create; begin inherited; FObjectClass := TState; Poster := TMainFacade.GetInstance.DataPosterByClassType[TStateDataPoster]; end; function TStates.GetItems(Index: Integer): TState; begin Result := inherited Items[Index] as TState; end; { TAbandonReasons } constructor TAbandonReasons.Create; begin inherited; FObjectClass := TAbandonReason; Poster := TMainFacade.GetInstance.DataPosterByClassType[TAbandonReasonDataPoster]; end; function TAbandonReasons.GetItems(Index: Integer): TAbandonReason; begin Result := inherited Items[Index] as TAbandonReason; end; { TAbandonReason } constructor TAbandonReason.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Причина ликвидации'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TAbandonReasonDataPoster]; end; { TAbandonReasonWells } constructor TAbandonReasonWells.Create; begin inherited; FObjectClass := TAbandonReasonWell; Poster := TMainFacade.GetInstance.DataPosterByClassType[TAbandonReasonWellDataPoster]; end; function TAbandonReasonWells.GetItems(Index: Integer): TAbandonReasonWell; begin Result := inherited Items[Index] as TAbandonReasonWell; end; { TAbandonReasonWell } procedure TAbandonReasonWell.AssignTo(Dest: TPersistent); var o: TAbandonReasonWell; begin inherited; o := Dest as TAbandonReasonWell; o.DtLiquidation := DtLiquidation; end; constructor TAbandonReasonWell.Create(ACollection: TIDObjects); begin inherited; ClassIDString := 'Причина ликвидации скважины'; FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TAbandonReasonWellDataPoster]; end; end.
unit DuringTime; interface uses Windows, Messages, SysUtils, Classes, Controls, Graphics, Dialogs,ComCtrls; type TDuringOfTime = (WholeNote, HalfNote, QuarterNote, Quavers, SixteenthNote, DemiSemiQuavers); TDuringTime = class(TCustomControl) private fDuringOfTime:TDuringOfTime; fTime:Cardinal; DOTUpDown:TUpDown; TimeUpDown:TUpDown; fOnDOTClick:TNotifyEvent; fOnTimeClick:TNotifyEvent; Function Create_UpDown(ALeft:Integer):TUpDown; Procedure Set_DuringOfTime(Value:TDuringOfTime); Procedure Set_Time(Value:Cardinal); Procedure DrawNote; Procedure DuringOfTimeUDClick(Sender: TObject;Button: TUDBtnType); Procedure TimeUDClick(Sender: TObject;Button: TUDBtnType); protected Procedure Paint; override; Procedure Resize; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published Property Color; Property DuringOfTime:TDuringOfTime Read fDuringOfTime Write Set_DuringOfTime; Property Time:Cardinal Read fTime Write Set_Time; Property OnDuringOfTimeClick:TNotifyEvent Read fOnDOTClick Write fOnDOTClick; Property OnTimeClick:TNotifyEvent Read fOnTimeClick Write fOnTimeClick; Property OnClick; Property OnDblClick; Property OnMouseDown; Property OnMouseUp; Property OnMouseMove; end; procedure Register; implementation procedure Register; begin RegisterComponents('MUSIC_PRO', [TDuringTime]); end; constructor TDuringTime.Create(AOwner:TComponent); begin inherited Create(AOwner); fDuringOfTime:=WholeNote; fTime:=8; Color:=$00C08000; DOTUpDown:=Create_UpDown(80); DOTUpDown.OnClick:=DuringOfTimeUDClick; TimeUpDown:=Create_UpDown(156); TimeUpDown.OnClick:=TimeUDClick; end; destructor TDuringTime.Destroy; begin DOTUpDown.Free; TimeUpDown.Free; inherited; end; Function TDuringTime.Create_UpDown(ALeft:Integer):TUpDown; Begin Result:=TUpDown.Create(Self); With Result Do Begin Parent:=Self; Height:=30; Top:=6; Left:=ALeft; Width:=12; End; End; Procedure TDuringTime.Set_DuringOfTime(Value:TDuringOfTime); begin fDuringOfTime:=Value; Invalidate; end; Procedure TDuringTime.Set_Time(Value:Cardinal); begin fTime:=Value; Invalidate; end; Procedure TDuringTime.DuringOfTimeUDClick(Sender: TObject;Button: TUDBtnType); begin If Button=btNext Then Begin If fDuringOfTime>=DemiSemiQuavers Then Exit; Inc(fDuringOfTime); End; If Button=btPrev Then Begin If fDuringOfTime<=WholeNote Then Exit; Dec(fDuringOfTime); End; If Assigned(fOnDOTClick) Then fOnDOTClick(Self); Invalidate; end; Procedure TDuringTime.TimeUDClick(Sender: TObject;Button: TUDBtnType); begin If Button=btNext Then Begin If fTime<=2 Then Exit; Dec(fTime); End; If Button=btPrev Then Begin If fTime>=8 Then Exit; Inc(fTime); End; If Assigned(fOnTimeClick) Then fOnTimeClick(Self); Invalidate; end; Procedure TDuringTime.Paint; Var UpperCorner,LowerCorner:Array [0..2] Of TPoint; TopText:Integer; Str:String; Rect:TRect; begin inherited; With Canvas Do Begin Pen.Width:=4; UpperCorner[0]:=Point(Width,0); UpperCorner[1]:=Point(0,0); UpperCorner[2]:=Point(0,Height); LowerCorner[0]:=Point(0,Height); LowerCorner[1]:=Point(Width,Height); LowerCorner[2]:=Point(Width,0); Brush.Color:=ClWhite; Pen.Color:=ClWhite; Polyline(UpperCorner); Brush.Color:=$005F5F5F; Pen.Color:=$005F5F5F; Polyline(LowerCorner); Str:='RYTHME'; TopText:=(Height-TextHeight(Str)) Div 2; Brush.Style:=BsClear; Font.Color:=ClWhite; TextOut(8,TopText,Str); Pen.Width:=1; Brush.Color:=ClBlack; Pen.Color:=ClBlack; DrawNote; Brush.Style:=BsClear; With Rect Do Begin Left:=4; Right:=94; Top:=4; Bottom:=37; Rectangle(Rect); End; Str:='TEMPS : '+IntTostr(fTime); TopText:=(Height-TextHeight(Str)) Div 2; Font.Color:=ClWhite; TextOut(100,TopText,Str); With Rect Do Begin Left:=97; Right:=170; Top:=4; Bottom:=37; Rectangle(Rect); End; End; end; Procedure TDuringTime.DrawNote; Const NoteToInt: Array[TDuringOfTime] of Integer =(0,1,2,3,4,5); Var IndexStrap:Integer; Begin With Canvas Do Begin If Not (fDuringOfTime In [WholeNote,HalfNote]) Then Brush.Style:=BsSolid Else Brush.Style:=BsClear; If fDuringOfTime=WholeNote Then Begin Ellipse(65,17,75,24); MoveTo(63,20); LineTo(77,20); End Else Begin Ellipse(65,25,75,31); MoveTo(74,28); LineTo(74,10); If NoteToInt[fDuringOfTime]>=3 Then For IndexStrap:=0 To (NoteToInt[fDuringOfTime]-3) Do Begin MoveTo(74,10+IndexStrap*4); LineTo(78,14+IndexStrap*4); MoveTo(78,14+IndexStrap*4); LineTo(78,18+IndexStrap*4); End; End; End; End; Procedure TDuringTime.Resize; begin inherited; Height:=40; Width:=174; end; end.
{***************************************************************************} { } { Модуль: Матрицы } { Описание: Операции с матрицами } { Автор: Зверинцев Дмитрий } { } {***************************************************************************} unit Matrixes; interface uses SysUtils,Vectors,Complex; type PMatrix = ^_Matrix; _Matrix=record private Matr:array of array of TNumber; cols,rows:integer; function getelement(i, j: integer): TNumber; procedure setelement(i, j: integer; const Value: TNumber); procedure CheckMainDiag(); function Minor(i,j:integer):TNumber; function Algebraic():PMatrix; procedure SwapRows(from_row,to_row:integer); procedure SwapCols(from_col,to_col:integer); public procedure CopyTo(B:PMatrix); procedure SetMatrix(row,col:integer); class operator Add(const A,B:_Matrix):PMatrix;overload; class operator Add(const A:_Matrix;const B:TNumber):PMatrix;overload; class operator Add(const B:TNumber;const A:_Matrix):PMatrix;overload; class operator Multiply(const A,B:_Matrix):PMatrix;overload; class operator Multiply(const k:TNumber;const B:_Matrix):PMatrix;overload; class operator Multiply(const B:_MAtrix;const k:TNumber):PMatrix;overload; class operator Subtract(const A,B:_Matrix):PMatrix;overload; class operator Subtract(const A:_Matrix;const B:TNumber):PMatrix;overload; class operator Subtract(const B:TNumber;const A:_Matrix):PMatrix;overload; class operator Divide(const A,B:_Matrix):PMatrix;overload; class operator Divide(const A:_Matrix;const B:double):PMatrix;overload; class operator Divide(const B:double;const A:_MAtrix):PMatrix;overload; function Gauss():PVector; function Rank():TNumber; function Transpose():PMatrix; class function Inverse(const A:PMatrix):PMatrix;static; function Getdet(): TNumber; function ToString(const sett:TFormat):AnsiString; property RowsCount:Integer read rows; property ColsCount:Integer read cols; property Element[i,j:integer]:TNumber read getelement write setelement;default; end; resourcestring InvalidLength='Матрицы должны иметь однинаковый размер.'; NoInverse='Для данной матрицы обратной не существует.'; NoMul='Умножение невозможно.'; implementation //////////////////////////////{ TMatrix }////////////////////////////////////// procedure _Matrix.CopyTo(B:PMatrix); var i,j:integer; begin B.SetMatrix(rows,cols); for i:=0 to rows-1 do for j:=0 to cols-1 do B.Matr[i,j]:=self.Matr[i,j]; end; function _MAtrix.Gauss():PVector; var i,j,k,co:integer; T:PMatrix; fre,mde,res:TNumber; swaprec:array of integer; function FindMax(row:integer):boolean; var j,k,x:integer; value:double; begin value:=0.0;x:=0; for k:= 0 to T.cols-2 do if(absval(T.Matr[row,k])>e)then begin value:=absval(T.Matr[row,k]); x:=k; for j:=k to T.cols-2 do if (absval(T.Matr[row,j])>value) then begin value:=absval(T.Matr[row,j]); x:=j end; break end else value:=0.0; if (absval(value)>e) then begin if (row<>x)then begin T.SwapCols(x,row); setlength(swaprec,length(swaprec)+2); swaprec[high(swaprec)]:=x; swaprec[high(swaprec)-1]:=row; end; result:=true; end else result:=false end; begin New(T); self.CopyTo(T); New(result); result.VectorLength:=cols-1; mde:=0;co:=1; // Прямой ход while(co < T.rows)do begin k:=1; for i:=co to T.rows-1 do begin FindMax(co-1); mde:=T.Matr[co-1,co-1]; fre:=T.Matr[i,co-1]; for j:=co-1 to T.cols-1 do begin if (absval(mde)<e) then begin if not FindMax(co-1) then raise Exception.Create('Уравнение не имеет решений.') else begin mde:=T.Matr[co-1,j]; fre:=T.Matr[i,j]; end end; T.Matr[i,j]:=T.Matr[i,j]-((fre/mde)*T.Matr[i-k,j]); end; {for} inc(k); end;{for} inc(co); end; {while} // Обратный ход for i:=T.rows-1 downto 0 do begin res:=0; for j:=i to T.cols-2 do res:=res+T.Matr[i,j]*result^[j]; if (absval(res)<e) and (absval(T.Matr[i,i])<e) and (absval(T.Matr[i,cols-1])>e) then begin dispose(T); raise Exception.Create('Уравнение не имеет решений.'); end else result^[i]:=(T.Matr[i,cols-1]-res)/T.Matr[i,i]; end; dispose(T); if length(swaprec)>0 then begin i:=high(swaprec); repeat res:=result^[swaprec[i]]; result^[swaprec[i]]:=result^[swaprec[i-1]]; result^[swaprec[i-1]]:=res; dec(i,2) until (i<0); end end; {$REGION ' Operations '} // Сумма матриц (векторов) class operator _Matrix.Add(const B:TNumber;const A:_Matrix):PMatrix; var i,j:integer; begin new(result); Result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do begin for j:=0 to A.cols-1 do Result.Matr[i,j]:=A.Matr[i,j]+B; end end; class operator _Matrix.Add(const A:_Matrix;const B:TNumber):PMatrix; var i,j:integer; begin new(result); Result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do begin for j:=0 to A.cols-1 do Result.Matr[i,j]:=A.Matr[i,j]+B; end end; class operator _Matrix.Add(const A,B:_Matrix):PMatrix; var i,j:integer; begin if (A.rows=B.rows)and(B.cols=A.cols)then begin new(result); Result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do begin for j:=0 to B.cols-1 do Result.Matr[i,j]:=A.Matr[i,j]+B.Matr[i,j]; end end else raise Exception.Create(invalidlength); end; //Разность матриц class operator _Matrix.Subtract(const A:_Matrix;const B:TNumber):PMatrix; var i,j:integer; begin new(result); Result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do begin for j:=0 to A.cols-1 do Result.Matr[i,j]:=A.Matr[i,j]-B; end end; class operator _Matrix.Subtract(const B:TNumber;const A:_Matrix):PMatrix; var i,j:integer; begin new(result); Result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do begin for j:=0 to A.cols-1 do Result.Matr[i,j]:=B-A.Matr[i,j]; end end; class operator _Matrix.Subtract(const A,B:_Matrix):PMatrix; var i,j:integer; begin if (A.rows=B.rows)and(B.cols=A.cols)then begin new(result); Result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do begin for j:=0 to B.cols-1 do Result.Matr[i,j]:=A.Matr[i,j]-B.Matr[i,j]; end end else raise Exception.Create(invalidlength); end; // Умножение матриц (Векторное произведение) // Для умножения матриц нужно чтоб кол-во строк А = кол-ву столбцов В class operator _Matrix.Multiply(const A,B:_Matrix):PMatrix; var i,j,k:integer; begin if A.rows=B.cols then begin new(result); result.SetMatrix(A.rows,B.cols); for k:=0 to result.rows-1 do // Строка результирующей матрицы for i:=0 to A.rows-1 do for j:=0 to B.rows-1 do result.Matr[k,i]:=result.Matr[k,i]+(A.Matr[k,j]*B.Matr[j,i]); end else raise Exception.Create(NoMul); end; // Умножение матрицы(вектора) на число class operator _Matrix.Multiply(const k:TNumber;const B:_Matrix):PMatrix; var i,j:integer; begin new(result); result.SetMatrix(B.rows,B.cols); for i:=0 to B.rows-1 do for j:=0 to B.cols-1 do result.Matr[i,j]:=k*B.Matr[i,j]; end; class operator _Matrix.Multiply(const B:_MAtrix;const k:TNumber):PMatrix; var i,j:integer; begin new(result); result.SetMatrix(B.rows,B.cols); for i:=0 to B.rows-1 do for j:=0 to B.cols-1 do result.Matr[i,j]:=k*B.Matr[i,j]; end; // Деление матриц class operator _Matrix.Divide(const A,B:_Matrix):PMatrix; var T:PMatrix;i,j:integer; begin if (A.rows=A.cols)and(B.cols=B.rows)then begin try T:=Inverse(@B); except raise Exception.Create('Деление не возможно.'); Dispose(T);Dispose(result); end; result:=A*T^; Dispose(T) end else if (A.rows=B.rows) and (B.cols=A.cols)then begin new(result); result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do for j:=0 to B.cols-1 do begin if absval(B[i,j])<e then result^[i,j]:=e else result^[i,j]:=A[i,j]/B[i,j] end end else raise Exception.Create(InvalidLength); end; class operator _Matrix.Divide(const A:_Matrix;const B:double):PMatrix; var i,j:integer; begin new(result); Result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do begin for j:=0 to A.cols-1 do if (B < -e) or (B > e) then Result.Matr[i,j] := A.Matr[i,j] / B else Result.Matr[i,j] := NaN end end; class operator _Matrix.Divide(const B:double;const A:_MAtrix):PMatrix; var i,j:integer; begin new(result); Result.SetMatrix(A.rows,A.cols); for i:=0 to A.rows-1 do begin for j:=0 to A.cols-1 do if (B < -e) or (B > e) then Result.Matr[i,j] := B / A.Matr[i,j] else Result.Matr[i,j] := NaN end end; {$ENDREGION} function _Matrix.Transpose():PMatrix; var i,j:integer; begin new(result); result.SetMatrix(cols,rows); for i:=0 to rows-1 do for j:=0 to cols-1 do result^.Matr[j,i]:=Matr[i,j]; end; // Процедура Проверки главной диаг на наличие 0 если есть то строки или столбцы меняются местами procedure _Matrix.CheckMainDiag(); var i,j,k,eqnum:integer; row,col:integer; label Verify; begin row:=0;col:=0; // Проверка есть ли на главной диагонали 0 Verify: for i:=row to rows-1 do for j:=col to cols-1 do if (i=j) and (absval(Matr[i,j])<e) then begin eqnum:=i; for k:= col to cols-1 do if(absval(Matr[eqnum,k])>e)then begin SwapCols(eqnum,k); inc(row);inc(col); goto Verify; end; for k:=row to rows-1 do if (absval(Matr[k,eqnum])>e)then begin SwapRows(k,eqnum); inc(row);inc(col); goto Verify; end; {if} end {if} end; function _Matrix.Rank():TNumber; var i,j,co,k:integer; T:PMatrix; mde,fre:TNumber; zero:boolean; {function FindMax(row:integer):boolean; var j,k,x:integer; value:double; begin value:=0.0;x:=0; for k:= 0 to T.cols-2 do if(absval(T.Matr[row,k])>e)then begin value := double(T.Matr[row,k]); x:=k; for j:=k to T.cols-2 do if (absval(T.Matr[row,j])>value) then begin value:=T.Matr[row,j].float; x:=j end; break end else value:=0.0; if abs(value)>e then begin T.SwapCols(x,row); result:=true; end else result:=false end; } begin {result:=0;co:=0; CheckMainDiag(); while(co < T.rows)do begin k:=1; for i:=co to T.rows-1 do begin mde:=T.Matr[co-1,co-1]; fre:=T.Matr[i,co-1]; if (absval(mde)<e)then Zero:=true else Zero:=false; for j:=co-1 to T.cols-1 do begin if Zero then begin if not FindMax(co-1) then raise Exception.Create('Уравнение не имеет решений.') else begin mde:=T.Matr[co-1,j]; fre:=T.Matr[i,j]; Zero:=false; end end; if not zero then T.Matr[i,j]:=T.Matr[i,j]-((fre/mde)*T.Matr[i-k,j]); end; //for inc(k); end; // for inc(co); end; // while CheckMainDiag(); for i:=0 to rows-1 do for j:=0 to cols-1 do if (i=j) and (absval(Matr[i,j])>e) then result:=result+1;} end; // перестановка столбцов procedure _Matrix.SwapCols(from_col,to_col:integer); var i:integer;tmp:Tnumber; begin if (from_col<>to_col) and (from_col<=cols) and (to_col<=cols) then for i:=0 to rows-1 do begin tmp:=Matr[i,to_col]; Matr[i,to_col]:=Matr[i,from_col]; Matr[i,from_col]:=tmp end end; // Перестановка строк procedure _Matrix.SwapRows(from_row,to_row:integer); // параметры индексы var i:integer; tmp:TNumber; begin if (from_row<>to_row) and (from_row<=rows) and (to_row<=rows) then for i:=0 to cols-1 do begin tmp:=Matr[to_row,i]; Matr[to_row,i]:=Matr[from_row,i]; Matr[from_row,i]:=tmp; end end; // Минор матрицы function _Matrix.Minor(i, j: integer):Tnumber; var k,l,n,m:integer; T:PMatrix; begin n:=0;m:=0;result:=0; if ((i<rows) and (j<cols))then if (rows>2)and(cols>2) then begin new(T); T.SetMatrix(rows-1,cols-1); for k:=0 to rows-1 do for l:=0 to cols-1 do if (k<>i)and(l<>j)then if m<=T.cols-1 then begin T.Matr[n,m]:=Matr[k,l]; inc(m); end else begin m:=0; inc(n); T.Matr[n,m]:=Matr[k,l]; inc(m); end; result:=T.Getdet(); Dispose(T) end end; // Алгебраическое дополнение элемента матрицы function _Matrix.Algebraic(): PMatrix; var minorel:TNumber;Ex,i,j:integer; T:PMatrix; begin new(T);new(result); result.SetMatrix(rows,cols); self.CopyTo(T); for i:=0 to rows-1 do for j:=0 to cols-1 do begin minorel:=T.Minor(i,j); Ex:=(i+j); if odd(Ex) then result.Matr[j,i]:=-minorel else result.Matr[j,i]:=minorel; end; Dispose(T); end; // Обратная матрица class function _Matrix.Inverse(const A:PMatrix):PMatrix; var det,k:TNumber; T,Alg:PMatrix; begin if (A.rows=A.cols)then begin new(T);new(alg); A.CopyTo(T); det:=T.Getdet; if absval(det)>e then begin new(result); Alg:=T.Algebraic; k:=1./det; result.SetMatrix(T.rows,T.cols); result:=k*Alg^; Dispose(T);dispose(Alg); end else begin Dispose(T);dispose(Alg); raise Exception.Create(NoInverse); end end else raise Exception.Create(InvalidLength); end; // Определитель function _Matrix.Getdet(): TNumber; var minorel,mds,pds:Tnumber; T:PMatrix;co,s:integer; // Проверка есть ли на главной диагонали 0 если меняются строки то меняется знак результата function CheckDiag():integer; var i,j,k:integer; row,col:integer; label Verify; begin row:=0;col:=0;result:=1; Verify: for i:=row to T.rows-1 do for j:=col to T.cols-1 do if (i=j) and (absval(T.Matr[i,j])<e) then begin for k:= col to T.cols-1 do if(absval(T.Matr[k,i])>e)then begin T.SwapRows(k,i); inc(row);inc(col); result:=-result; goto Verify; end; end {if} end; // Нижний треугольный вид function SetTriangle():TNumber; var i,j,k,co:integer; fre,mde:TNumber; begin mde:=0;result:=1; co:=1; while(co<T.rows-1)do begin k:=1; for i:=co to T.rows-1 do begin mde:=T.Matr[co-1,co-1]; fre:=T.Matr[i,co-1]; for j:=co-1 to T.cols-1 do if absval(mde)<e then T.Matr[i,j]:=0.0 else T.Matr[i,j]:=T.Matr[i,j]-((fre/mde)*T.Matr[i-k,j]); inc(k); end;{for} inc(co); result:=result*mde; end; {while} end; begin if ((rows>=2) and (cols>=2)) and (rows=cols) then begin new(T); self.CopyTo(T); mds:=0;pds:=0;minorel:=1;s:=1; if (rows>2) and (cols>2) then begin s:=CheckDiag(); minorel:=SetTriangle(); end; // Вычисление разности главной и побочной диагоналей co:=rows-1; mds:=T.Matr[co,co]*T.Matr[co-1,co-1]; pds:=T.Matr[co,co-1]*T.Matr[co-1,co]; Result:=(minorel*(mds-pds))*s; Dispose(T); end else raise Exception.Create(InvalidLength); end; // function _Matrix.ToString(const sett:TFormat):AnsiString; var i,j:integer; begin result:=''; for i:=0 to rows-1 do begin for j:=0 to cols-1 do result:=result+Matr[i,j].ToString(sett)+','; Delete(result,length(result),1); result:=result+#13#10; end end; procedure _MAtrix.SetMatrix(row,col:integer); begin if (row>=0)and(col>=0)then SetLength(Matr,row,col); rows:=row; cols:=col end; function _Matrix.getelement(i, j: integer): Tnumber; begin Result:=self.Matr[i,j]; end; procedure _Matrix.setelement(i, j: integer; const Value: TNumber); begin self.Matr[i,j]:=Value; end; end.
unit TIFF; // ----------------------------------- // TIFF file format handling component // ----------------------------------- // 17.04.03 interface uses SysUtils, Classes, Dialogs ; type TTiffHeader = packed record ByteOrder : Word ; Signature : Word ; IFDOffset : Cardinal ; end ; TTiffIFDEntry = packed record Tag : Word ; FieldType : Word ; Count : Cardinal ; Offset : Cardinal ; end ; TRational = packed record Numerator : Cardinal ; Denominator : Cardinal ; end ; TTIFF = class(TComponent) private { Private declarations } FileHandle : Integer ; // TIFF file handle FFrameWidth : Integer ; // Image width FFrameHeight : Integer ; // Image height FPixelDepth : Integer ; // No. of bits per pixel FNumFrames : Integer ; // No. of images in file FXResolution : Double ; FYResolution : Double ; FResolutionUnit : Integer ; FDescription : String ; // Description of TIFF image IFDCount : Word ; TIFFHeader : TTiffHeader ; // TIFF file header SamplesPerPixel : Word ; BitsPerSample : Word ; RowsPerStrip : Cardinal ; MinSampleValue : Cardinal ; MaxSampleValue : Cardinal ; UICSTKFormat : Boolean ; NumBytesPerFrame : Integer ; FIFDPointerList : Array[0..10000] of Integer ; procedure ClearIFD ; Procedure ReadIFDFromFile( FileHandle : Integer ; IFDPointer : Cardinal ; var IFD : Array of TTiffIFDEntry ; var NumIFDEntries : Integer ; var NextIFDPointer : Integer ) ; procedure AddIFDEntry( Tag : Word ; FieldType : Word ; NumValues : Cardinal ; Value : Cardinal ) ; function GetIFDEntry( IFD : Array of TTIFFIFDEntry ; NumEntries : Integer ; Tag : Integer ; var NumValues : Integer ; var Value : Integer ) : Boolean ; function ReadRationalField( FileHandle : Integer ; // Open TIFF file handle FileOffset : Integer // Offset to start reading from ) : Double ; // Return as double function ReadASCIIField( FileHandle : Integer ; // Open TIFF file handle FileOffset : Integer ; // Offset to start reading from NumChars : Integer // No. of characters to read ) : String ; protected { Protected declarations } public { Public declarations } Constructor Create(AOwner : TComponent) ; override ; Destructor Destroy ; override ; Function OpenFile( FileName : String ) : Boolean ; Procedure CloseFile ; Function LoadFrame( FrameNum : Integer ; PImageBuf : Pointer ) : Boolean ; published { Published declarations } Property FrameWidth : Integer Read FFrameWidth ; Property FrameHeight : Integer Read FFrameHeight ; Property PixelDepth : Integer Read FPixelDepth ; Property NumFrames : Integer Read FNumFrames ; Property ResolutionUnit : Integer Read FResolutionUnit ; Property XResolution : Double Read FXResolution ; Property YResolution : Double Read FYResolution ; end; procedure Register; implementation type TLongArray = Array[0..60000] of Cardinal ; const LittleEndian = $4949 ; BigEndian = $4d4d ; Signature = $42 ; // Field types ByteField = 1 ; ASCIIField = 2 ; ShortField = 3 ; LongField = 4 ; RationalField = 5 ; SignedByteField = 6 ; UndefinedField = 7 ; SignedShortField = 8 ; SignedLongField = 9 ; SignedRationalField = 10 ; FloatField = 11 ; DoubleField = 12 ; // Tag definitions NewSubfileTypeTag = 254 ; SubfileTypeTag = 255 ; FullResolutionImage = 1 ; ReducedResolutionImage = 2 ; MultiPageImage = 3 ; ImageWidthTag = 256 ; ImageLengthTag = 257 ; BitsPerSampleTag = 258 ; CompressionTag = 259 ; NoCompression = 1 ; CCCITCompression = 2 ; Group3Fax = 3 ; Group4Fax = 4 ; LZW = 5 ; JPEG = 6 ; PackBits = 32773 ; PhotometricInterpretationTag = 262 ; WhiteIsZero = 0 ; BlackIsZero = 1 ; RGB = 2 ; RGBPalette = 3 ; TransparencyMask = 4 ; CMYK = 5 ; YCbCr = 6 ; CIELab = 7 ; ThresholdingTag = 263 ; CellWidthTag = 264 ; CellLengthTag = 265 ; FillOrderTag = 266 ; DocumentNameTag = 269 ; ImageDescriptionTag = 270 ; MakeTag = 271 ; ModelTag = 272 ; StripOffsetsTag = 273 ; OrientationTag = 274 ; SamplesPerPixelTag = 277 ; RowsPerStripTag = 278 ; StripByteCountsTag = 279 ; MinSampleValueTag = 280 ; MaxSampleValueTag = 281 ; XResolutionTag = 282 ; YResolutionTag = 283 ; PlanarConfigurationTag = 284 ; PageNameTag = 285 ; XPositionTag = 286 ; YPositiontag = 287 ; FreeOffsetsTag = 288 ; FreeByteCountstag = 289 ; GrayResponseUnitTag = 290 ; GrayResponseCurveTag = 291 ; T4OptionsTag = 292 ; T6OptionsTag = 293 ; ResolutionUnitTag = 296 ; NoUnits = 1 ; InchUnits = 2 ; CentimeterUnits = 3 ; PageNumberTag = 297 ; TransferFunctionTag = 301 ; // Universal Imaging MetaMorph tags UIC1Tag = 33628 ; UIC2Tag = 33629 ; UIC3Tag = 33630 ; UIC4Tag = 33631 ; procedure Register; begin RegisterComponents('Samples', [TTIFF]); end; constructor TTIFF.Create(AOwner : TComponent) ; { -------------------------------------------------- Initialise component's internal objects and fields -------------------------------------------------- } begin inherited Create(AOwner) ; FileHandle := -1 ; FFrameWidth := 0 ; FFrameHeight := 0 ; FPixelDepth := 0 ; FNumFrames := 0 ; FResolutionUnit := 1 ; FXResolution := 1.0 ; FYResolution := 1.0 ; FDescription := '' ; end ; destructor TTIFF.Destroy ; { ------------------------------------ Tidy up when component is destroyed ----------------------------------- } begin // Close open TIFF file if FileHandle >= 0 then FileClose( FileHandle ) ; { Call inherited destructor } inherited Destroy ; end ; procedure TTiff.ClearIFD ; // -------------------------- // Clear Image file directory // -------------------------- begin IFDCount := 0 ; end ; procedure TTiff.AddIFDEntry( Tag : Word ; // Type of IFD entry FieldType : Word ; // Type of data in field NumValues : Cardinal ; // Number of values Value : Cardinal ) ; // Value (or file offset of value) // ------------------------------------------ // Add a single valued IFD entry to IFD table // ------------------------------------------ begin { IFD[IFDCount].Tag := Tag ; IFD[IFDCount].FieldType := FieldType ; IFD[IFDCount].Count := NumValues ; IFD[IFDCount].Offset := Value ; if IFDCount < High(IFD) then Inc(IFDCount) ;} end ; function TTIFF.GetIFDEntry( IFD : Array of TTIFFIFDEntry ; NumEntries : Integer ; Tag : Integer ; var NumValues : Integer ; var Value : Integer ) : Boolean ; // ---------------------------------- // Find and return value of IFD entry // ---------------------------------- var i : Integer ; begin i := 0 ; while (i < NumEntries) and (IFD[i].Tag <> Tag) do Inc(i) ; if IFD[i].Tag = Tag then begin NumValues := IFD[i].Count ; Value := IFD[i].Offset ; Result := True ; end else begin NumValues := 0 ; Value := 0 ; Result := False ; end ; end ; function TTIFF.ReadRationalField( FileHandle : Integer ; // Open TIFF file handle FileOffset : Integer // Offset to start reading from ) : Double ; // Return as double // ---------------------------------------- // Read`rational field entry from TIFF file // ---------------------------------------- var Numerator, Denominator : Integer ; Value : Double ; begin FileSeek( FileHandle, FileOffset, 0 ) ; FileRead( FileHandle, Numerator, SizeOf(Numerator) ) ; FileRead( FileHandle, Denominator, SizeOf(Denominator) ) ; Value := Numerator ; if Denominator <> 0 then Value := Value / Denominator else Value := 0.0 ; Result := Value ; end ; function TTIFF.ReadASCIIField( FileHandle : Integer ; // Open TIFF file handle FileOffset : Integer ; // Offset to start reading from NumChars : Integer // No. of characters to read ) : String ; // ---------------------------------------- // Read`ASCII field entry from TIFF file // ---------------------------------------- var i : Integer ; Ch : Char ; begin Result := '' ; if NumChars <= 0 then Exit ; FileSeek( FileHandle, FileOffset, 0 ) ; for i := 1 to NumChars do begin FileRead( FileHandle, Ch, 1 ) ; if Ch <> #0 then Result := Result + Ch ; end ; end ; procedure TTiff.ReadIFDFromFile( FileHandle : Integer ; // TIFF File handle (IN) IFDPointer : Cardinal ; // File pointer to start of IFD (IN) var IFD : Array of TTiffIFDEntry ; // IFD (OUT) var NumIFDEntries : Integer ; // No. of entries in IDF (OUT) var NextIFDPointer : Integer ) ; // ----------------------------------- // Read image file directory from file // ----------------------------------- var IFDCount : SmallInt ; i : Integer ; IFDEntry : TTiffIFDEntry ; Done : Boolean ; begin // Move file pointer to start of IFD FileSeek(FileHandle,IFDPointer,0) ; // Read number of entries in IFD FileRead(FileHandle, IFDCount, SizeOf(IFDCount) ) ; Done := False ; NumIFDEntries := 0 ; while not Done do begin // Read IFD entry if FileRead(FileHandle, IFDEntry, SizeOf(TTiffIFDEntry)) = SizeOf(TTiffIFDEntry) then begin IFD[NumIFDEntries] := IFDEntry ; Inc(NumIFDEntries) ; Dec(IFDCount) ; if IFDCount = 0 then Done := True ; end else begin MessageDlg( 'TIFF: Error reading IFD', mtWarning, [mbOK], 0 ) ; Done := True ; end ; end ; NextIFDPointer := 1 ; FileRead(FileHandle, NextIFDPointer, SizeOf(NextIFDPointer) ) ; end ; function TTiff.OpenFile( FileName : string // Name of TIFF file to be read (IN) ) : Boolean ; // Returns TRUE if successful // --------------- // Open TIFF file // --------------- var i,NumEntries : Integer ; NumValues : Integer ; FileOffset : Integer ; IFDPointer : Integer ; // Pointer to image file directory NextIFDPointer : Integer ; NumIFDEntries : Word ; // No.of entries in an IFD TIFFHeader : TTIFFHeader ; // TIFF file header structure IFD : Array[0..100] of TTiffIFDEntry ; Done : Boolean ; Value : Double ; begin Result := False ; if FileHandle >= 0 then begin MessageDlg( 'TIFF: A file is aready open ', mtWarning, [mbOK], 0 ) ; Exit ; end ; // Open file FileHandle := FileOpen( FileName, fmOpenRead ) ; if FileHandle < 0 then begin MessageDlg( 'TIFF: Unable to open ' + FileName, mtWarning, [mbOK], 0 ) ; Exit ; end ; // Read TIFF file header FileSeek(FileHandle,0,0) ; if FileRead(FileHandle, TIFFHeader, SizeOf(TIFFHeader)) <> SizeOf(TIFFHeader) then begin ; MessageDlg( 'TIFF: Unable to read file header of' + FileName, mtWarning, [mbOK], 0 ) ; FileClose( FileHandle ) ; FileHandle := -1 ; Exit ; end ; // Only little-endian (Intel CPUs) byte ordering supported at present if TIFFHeader.ByteOrder <> LittleEndian then begin MessageDlg( 'TIFF: Macintosh byte ordering not supported!', mtWarning, [mbOK], 0 ) ; FileClose( FileHandle ) ; FileHandle := -1 ; Exit ; end ; // A .stk file ending indicates that this is a Universal Imaging // stack file which has to be processed specially if LowerCase(ExtractFileExt(FileName)) = '.stk' then UICSTKFormat := True else UICSTKFormat := False ; IFDPointer := TIFFHeader.IFDOffset ; FNumFrames := 0 ; Done := False ; while not Done do begin // Read`image file directory FIFDPointerList[FNumFrames] := IFDPointer ; ReadIFDFromFile( FileHandle, IFDPointer, IFD, NumEntries, NextIFDPointer ) ; // Get image characteristics GetIFDEntry( IFD, NumEntries, ImageWidthTag, NumValues, FFrameWidth ) ; GetIFDEntry( IFD, NumEntries, ImageLengthTag, NumValues, FFrameHeight ) ; GetIFDEntry( IFD, NumEntries, BitsPerSampleTag, NumValues, FPixelDepth ) ; NumBytesPerFrame := FFrameWidth*FFrameHeight* (((FPixelDepth-1) div 8) + 1) ; // Get spatial resolution information FResolutionUnit := 1 ; GetIFDEntry( IFD, NumEntries, ResolutionUnitTag, NumValues, FResolutionUnit ) ; GetIFDEntry( IFD, NumEntries, XResolutionTag, NumValues, FileOffset ) ; if NumValues > 0 then begin Value := ReadRationalField(FileHandle,FileOffset) ; if Value <> 0.0 then FXResolution := 1.0 / Value ; end ; GetIFDEntry( IFD, NumEntries, YResolutionTag, NumValues, FileOffset ) ; if NumValues > 0 then begin Value := ReadRationalField(FileHandle,FileOffset) ; if Value <> 0.0 then FYResolution := 1.0 / Value ; end ; // Read image description field FDescription := '' ; GetIFDEntry( IFD, NumEntries, ImageDescriptionTag, NumValues, FileOffset ) ; if NumValues > 0 then FDescription := ReadASCIIField(FileHandle,FileOffset,NumValues) ; // If this is Universal Imaging STK format file get number of frames if UICSTKFormat then begin GetIFDEntry( IFD, NumEntries, UIC1Tag, NumValues, FileOffset ) ; if NumValues > 0 then FNumFrames := NumValues ; GetIFDEntry( IFD, NumEntries, UIC2Tag, NumValues, FileOffset ) ; if NumValues > 0 then FNumFrames := NumValues ; end else Inc(FNumFrames) ; // Null pointer indicates last IFD if NextIFDPointer > 0 then IFDPointer := NextIFDPointer else Done := True ; // Only one IFD in UIC format if UICSTKFormat then begin for i := 1 to FNumFrames-1 do FIFDPointerList[i] := FIFDPointerList[0] ; end ; end ; Result := True ; end ; procedure TTiff.CloseFile ; // --------------- // Close TIFF file // --------------- begin FNumFrames := 0 ; if FileHandle >= 0 then begin FileClose(FileHandle) ; FileHandle := -1 ; end ; end ; Function TTIFF.LoadFrame( FrameNum : Integer ; // Frame # to load PImageBuf : Pointer // Pointer to buffer to receive image ) : Boolean ; // Returns TRUE if frame available // -------------------------------------- // Load frame # <FrameNum> from TIFF file // -------------------------------------- var NumEntries : Integer ; NumValues,nc : Integer ; IFDPointer : Integer ; // Pointer to image file directory NextIFDPointer : Integer ; NumIFDEntries : Word ; // No.of entries in an IFD OK : Boolean ; Strip : Integer ; StripOffsets : Array[0..1000] of Cardinal ; StripByteCounts : Array[0..1000] of Cardinal ; IFD : Array[0..100] of TTiffIFDEntry ; NumStrips : Integer ; FilePointer : Integer ; RowsPerStrip : Integer ; FrameOffset : Integer ; PBuf : Pointer ; begin Result := False ; if (NumFrames <= 0) or (FrameNum <= 0) or (FrameNum > NumFrames) then Exit ; // Read IFD IFDPointer := FIFDPointerList[FrameNum-1] ; ReadIFDFromFile( FileHandle, IFDPointer, IFD, NumEntries, NextIFDPointer ) ; // Get pointers to image strips OK := GetIFDEntry( IFD, NumEntries, StripOffsetsTag, NumStrips, FilePointer ) ; if OK then begin FileSeek( FileHandle, FilePointer, 0 ) ; FileRead( FileHandle, StripOffsets, NumStrips*4 ) ; end else Exit ; // Get number of bytes in each image strip OK := GetIFDEntry( IFD, NumEntries, StripByteCountsTag, NumStrips, FilePointer ) ; if OK then begin FileSeek( FileHandle, FilePointer, 0 ) ; FileRead( FileHandle, StripByteCounts, NumStrips*4 ) ; end else Exit ; // Get number of image rows in each strip OK := GetIFDEntry( IFD, NumEntries, RowsPerStripTag, NumValues, RowsPerStrip ) ; // Read image if UICSTKFormat then begin // Read frame from UIC metamorph stack format file FrameOffset := FrameNum*( StripOffsets[NumStrips-1] + StripByteCounts[NumStrips-1] - StripOffsets[0] ) + StripOffsets[0] ; FileSeek( FileHandle, FrameOffset, 0 ) ; FileRead( FileHandle, PByteArray(PImageBuf)^, NumBytesPerFrame ) ; end else begin // Read frame from standard multi-page TIFF file PBuf := PImageBuf ; for Strip := 0 to NumStrips-1 do begin FileSeek( FileHandle, StripOffsets[Strip], 0 ) ; RowsPerStrip := FileRead( FileHandle, PByteArray(PBuf)^, StripByteCounts[Strip] ) ; PBuf := Ptr(Integer(PBuf) + StripByteCounts[Strip]) ; end ; end ; Result := True ; end ; end.
unit RRManagerLayerEditForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, ImgList, ActnList, ClientDicts, BaseDicts {$IFDEF VER150} , Variants {$ENDIF} ; type TfrmEditLayer = class(TDictEditForm) Label1: TLabel; edtLayerName: TEdit; gbxContainment: TGroupBox; sbtnRight: TSpeedButton; sbtnLeft: TSpeedButton; sbtnFullLeft: TSpeedButton; lbxContainedStratons: TListBox; pnlLeft: TPanel; Label2: TLabel; lbxAllStratons: TListBox; edtSearch: TEdit; pnlButtons: TPanel; btnOK: TButton; btnCancel: TButton; actnEditStratum: TActionList; MoveRight: TAction; MoveLeft: TAction; MoveAllLeft: TAction; imgList: TImageList; procedure FormCreate(Sender: TObject); procedure MoveRightExecute(Sender: TObject); procedure MoveRightUpdate(Sender: TObject); procedure MoveLeftExecute(Sender: TObject); procedure MoveLeftUpdate(Sender: TObject); procedure MoveAllLeftExecute(Sender: TObject); procedure edtSearchChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure lbxAllStratonsDblClick(Sender: TObject); procedure lbxContainedStratonsDblClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure SetDict(const Value: TDict); override; public { Public declarations } procedure ClearControls; override; procedure SaveValues; override; procedure AdditionalSave; override; end; var frmEditLayer: TfrmEditLayer; implementation uses Facade; {$R *.DFM} { TfrmEditLayer } procedure TfrmEditLayer.AdditionalSave; begin inherited; FDict.SetRefer(lbxContainedStratons.Items); end; procedure TfrmEditLayer.ClearControls; begin edtLayerName.Clear; lbxContainedStratons.Clear; end; procedure TfrmEditLayer.SaveValues; begin inherited; FDict.Columns[1].Value := edtLayerName.Text; end; procedure TfrmEditLayer.SetDict(const Value: TDict); begin FDict := Value; ClearControls; end; procedure TfrmEditLayer.FormCreate(Sender: TObject); begin (TMainFacade.GetInstance as TMainFacade).AllDicts.MakeList(lbxAllStratons.Items, (TMainFacade.GetInstance as TMainFacade).AllDicts.DictContentByName('TBL_STRATIGRAPHY_NAME_DICT')); lbxAllStratons.Sorted := true; end; procedure TfrmEditLayer.MoveRightExecute(Sender: TObject); begin with lbxAllStratons do begin lbxContainedStratons.ItemIndex := lbxContainedStratons.Items.IndexOfObject(Items.Objects[ItemIndex]); if lbxContainedStratons.ItemIndex = -1 then lbxContainedStratons.ItemIndex := lbxContainedStratons.Items.AddObject(Items[ItemIndex], Items.Objects[ItemIndex]); lbxContainedStratons.Sorted := true; end; end; procedure TfrmEditLayer.MoveRightUpdate(Sender: TObject); begin MoveRight.Enabled := lbxAllStratons.ItemIndex > -1; end; procedure TfrmEditLayer.MoveLeftExecute(Sender: TObject); begin lbxContainedStratons.Items.Delete(lbxContainedStratons.ItemIndex); end; procedure TfrmEditLayer.MoveLeftUpdate(Sender: TObject); begin MoveLeft.Enabled := lbxContainedStratons.ItemIndex > -1; end; procedure TfrmEditLayer.MoveAllLeftExecute(Sender: TObject); begin lbxContainedStratons.Clear; end; procedure TfrmEditLayer.edtSearchChange(Sender: TObject); var i: integer; begin for i := 0 to lbxAllStratons.Items.Count - 1 do if pos(edtSearch.Text, lbxAllStratons.Items[i]) > 0 then begin lbxAllStratons.ItemIndex := i; break; end; end; procedure TfrmEditLayer.FormShow(Sender: TObject); var v: variant; begin edtLayerName.Text := Dict.Columns[1].Value; // загружаем зависимые v := Dict.Reference('TBL_STRATIGRAPHY_LAYER', 'STRATON_ID'); if not varIsEmpty(v) then (TMainFacade.GetInstance as TMainFacade).AllDicts.MakeList(lbxContainedStratons.Items, (TMainFacade.GetInstance as TMainFacade).AllDicts.DictContentByName('TBL_STRATIGRAPHY_NAME_DICT'), v, 0); end; procedure TfrmEditLayer.lbxAllStratonsDblClick(Sender: TObject); begin MoveRightExecute(Sender); end; procedure TfrmEditLayer.lbxContainedStratonsDblClick(Sender: TObject); begin MoveLeftExecute(Sender); end; end.
unit FrmBase; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uDefine; type TBaseForm = class(TForm) private { Private declarations } protected FParHandle: THandle; {* جلت¾؟ٍ *} procedure InfoBox(AText: string); procedure ErrorBox(AText: string); function AskBox(AText: string): Boolean; procedure CreateParams(var Params: TCreateParams); override; public { Public declarations } constructor Create(AOwner: TComponent; AHandle: THandle = 0); reintroduce; end; var BaseForm: TBaseForm; implementation {$R *.dfm} { TBaseForm } function TBaseForm.AskBox(AText: string): Boolean; begin if MessageBox(Handle, PChar(AText), CAsk, MB_ICONQUESTION + MB_YESNO) = mrYes then Result := True else Result := False; end; constructor TBaseForm.Create(AOwner: TComponent; AHandle: THandle); begin FParHandle := AHandle; inherited Create(AOwner); end; procedure TBaseForm.CreateParams(var Params: TCreateParams); begin inherited; Params.WndParent := FParHandle; end; procedure TBaseForm.ErrorBox(AText: string); begin MessageBox(Handle, PChar(AText), CError, MB_ICONERROR); end; procedure TBaseForm.InfoBox(AText: string); begin MessageBox(Handle, PChar(AText), CHint, MB_ICONINFORMATION); end; end.
{ /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * HproseHttpClient.pas * * * * hprose indy http client unit for delphi. * * * * LastModified: Dec 9, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ } unit HproseHttpClient; interface uses Classes, HproseCommon, HproseClient, IdHeaderList, SysUtils{$IFDEF FPC}, LResources{$ENDIF}; type THproseHttpClient = class(THproseClient) private FHttpPool: IList; FUserName: string; FPassword: string; FHeaders: IMap; FProxyHost: string; FProxyPort: Integer; FProxyUser: string; FProxyPass: string; FUserAgent: string; FKeepAlive: Boolean; FKeepAliveTimeout: Integer; FConnectionTimeout: Integer; protected function SendAndReceive(const Data: TBytes; const Context: TClientContext): TBytes; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published {:Before HTTP operation you may define any non-standard headers for HTTP request, except of: 'Expect: 100-continue', 'Content-Length', 'Content-Type', 'Connection', 'Authorization', 'Proxy-Authorization' and 'Host' headers.} property Headers: IMap read FHeaders; {:If @true (default value is @false), keepalives in HTTP protocol 1.1 is enabled.} property KeepAlive: Boolean read FKeepAlive write FKeepAlive; {:Define timeout for keepalives in seconds! Default value is 300.} property KeepAliveTimeout: integer read FKeepAliveTimeout write FKeepAliveTimeout; {:Address of proxy server (IP address or domain name).} property ProxyHost: string read FProxyHost Write FProxyHost; {:Port number for proxy connection. Default value is 8080.} property ProxyPort: Integer read FProxyPort Write FProxyPort; {:Username for connect to proxy server.} property ProxyUser: string read FProxyUser Write FProxyUser; {:Password for connect to proxy server.} property ProxyPass: string read FProxyPass Write FProxyPass; {:Here you can specify custom User-Agent indentification. By default is used: 'Hprose Http Client for Delphi (Indy10)'} property UserAgent: string read FUserAgent Write FUserAgent; {:UserName for user authorization.} property UserName: string read FUserName write FUserName; {:Password for user authorization.} property Password: string read FPassword write FPassword; {:Define timeout for ConnectionTimeout in milliseconds! Default value is 10000.} property ConnectionTimeout: Integer read FConnectionTimeout write FConnectionTimeout; end; procedure Register; implementation uses IdHttp, IdGlobalProtocols, IdCookieManager; var CookieManager: TIdCookieManager = nil; { THproseHttpClient } constructor THproseHttpClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FHttpPool := TArrayList.Create(10); FHeaders := TCaseInsensitiveHashMap.Create; FUserName := ''; FPassword := ''; FKeepAlive := True; FKeepAliveTimeout := 300; FProxyHost := ''; FProxyPort := 8080; FProxyUser := ''; FProxyPass := ''; FUserAgent := 'Hprose Http Client for Delphi (Indy10)'; FConnectionTimeout := 10000; end; destructor THproseHttpClient.Destroy; var I: Integer; IdHttp: TIdHttp; begin FHttpPool.Lock; try for I := FHttpPool.Count - 1 downto 0 do begin IdHttp := TIdHttp(VarToObj(FHttpPool.Delete(I))); FreeAndNil(IdHttp); end; finally FHttpPool.Unlock; end; inherited; end; function THproseHttpClient.SendAndReceive(const Data: TBytes; const Context: TClientContext): TBytes; var IdHttp: TIdHttp; OutStream, InStream: TBytesStream; Header, HttpHeader: IMap; CustomHeaders, RawHeaders: TIdHeaderList; I: Integer; Key: string; begin FHttpPool.Lock; try if FHttpPool.Count > 0 then IdHttp := TIdHttp(VarToObj(FHttpPool.Delete(FHttpPool.Count - 1))) else begin IdHttp := TIdHttp.Create(nil); IdHttp.AllowCookies := True; IdHttp.CookieManager := CookieManager; IdHttp.HTTPOptions := IdHttp.HTTPOptions + [hoKeepOrigProtocol]; IdHttp.ProtocolVersion := pv1_1; end; finally FHttpPool.Unlock; end; IdHttp.ConnectTimeout := FConnectionTimeout; IdHttp.ReadTimeout := Context.Settings.Timeout; IdHttp.Request.UserAgent := FUserAgent; if FProxyHost <> '' then begin IdHttp.ProxyParams.ProxyServer := FProxyHost; IdHttp.ProxyParams.ProxyPort := FProxyPort; IdHttp.ProxyParams.ProxyUsername := FProxyUser; IdHttp.ProxyParams.ProxyPassword := FProxyPass; end; CustomHeaders := IdHttp.Request.CustomHeaders; if KeepAlive then begin IdHttp.Request.Connection := 'keep-alive'; CustomHeaders.Values['Keep-Alive'] := IntToStr(FKeepAliveTimeout); end else IdHttp.Request.Connection := 'close'; if FUserName <> '' then begin IdHttp.Request.BasicAuthentication := True; IdHttp.Request.UserName := FUserName; IdHttp.Request.Password := FPassword; end; IdHttp.Request.ContentType := 'application/hprose'; Header := TCaseInsensitiveHashMap.Create; Header.PutAll(FHeaders); HttpHeader := VarToMap(Context['httpHeader']); if (Assigned(HttpHeader)) then Header.PutAll(HttpHeader) else HttpHeader := TCaseInsensitiveHashMap.Create; for I := 0 to Header.Count - 1 do CustomHeaders.Values[Header.Keys[I]] := Header.Values[I]; OutStream := TBytesStream.Create(Data); InStream := TBytesStream.Create; try IdHttp.Post(URI, OutStream, InStream); HttpHeader.Clear(); RawHeaders := IdHttp.Response.RawHeaders; for I := 0 to RawHeaders.Count - 1 do begin Key := RawHeaders.Names[I]; HttpHeader.Put(Key, RawHeaders.Values[Key]); end; Context['httpHeader'] := HttpHeader; Result := InStream.Bytes; SetLength(Result, InStream.Size); finally OutStream.Free; InStream.Free; end; IdHttp.Request.Clear; IdHttp.Request.CustomHeaders.Clear; IdHttp.Response.Clear; FHttpPool.Lock; try FHttpPool.Add(ObjToVar(IdHttp)); finally FHttpPool.Unlock; end; end; procedure Register; begin RegisterComponents('Hprose', [THproseHttpClient]); end; initialization CookieManager := TIdCookieManager.Create(nil); {$IFDEF FPC} {$I Hprose.lrs} {$ENDIF} finalization FreeAndNil(CookieManager); end.
{==============================================================================| | Project : Bauglir Internet Library | |==============================================================================| | Content: Generic connection and server | |==============================================================================| | Copyright (c)2011-2012, Bronislav Klucka | | All rights reserved. | | Source code is licenced under original 4-clause BSD licence: | | http://licence.bauglir.com/bsd4.php | | | | | | Project download homepage: | | http://code.google.com/p/bauglir-websocket/ | | Project homepage: | | http://www.webnt.eu/index.php | | WebSocket RFC: | | http://tools.ietf.org/html/rfc6455 | | | | | |==============================================================================| | Requirements: Ararat Synapse (http://www.ararat.cz/synapse/) | |==============================================================================} { 2.0.4 1/ change: send generic frame SendData public on WSConnection 2/ pascal bugfix: closing connection issues (e.g. infinite sleep) 3/ add: server CloseAllConnections 4/ change: default client version 13 (RFC) 5/ pascal change: CanReceiveOrSend public 6/ pascal bugfix: events missing on erratic traffic 7/ add: make Handschake public property @todo * move writing to separate thread * test for simultaneous i/o operations http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 http://tools.ietf.org/html/rfc6455 http://dev.w3.org/html5/websockets/#refsFILEAPI } unit WebSocket2; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$H+} interface uses {$IFDEF UNIX} cthreads, {$ENDIF} Classes, SysUtils, blcksock, CustomServer2, syncobjs; const {:Constants section defining what kind of data are sent from one pont to another} {:Continuation frame } wsCodeContinuation = $0; {:Text frame } wsCodeText = $1; {:Binary frame } wsCodeBinary = $2; {:Close frame } wsCodeClose = $8; {:Ping frame } wsCodePing = $9; {:Frame frame } wsCodePong = $A; {:Constants section defining close codes} {:Normal valid closure, connection purpose was fulfilled} wsCloseNormal = 1000; {:Endpoint is going away (like server shutdown) } wsCloseShutdown = 1001; {:Protocol error } wsCloseErrorProtocol = 1002; {:Unknown frame data type or data type application cannot handle } wsCloseErrorData = 1003; {:Reserved } wsCloseReserved1 = 1004; {:Close received by peer but without any close code. This close code MUST NOT be sent by application. } wsCloseNoStatus = 1005; {:Abnotmal connection shutdown close code. This close code MUST NOT be sent by application. } wsCloseErrorClose = 1006; {:Received text data are not valid UTF-8. } wsCloseErrorUTF8 = 1007; {:Endpoint is terminating the connection because it has received a message that violates its policy. Generic error. } wsCloseErrorPolicy = 1008; {:Too large message received } wsCloseTooLargeMessage = 1009; {:Client is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake } wsCloseClientExtensionError= 1010; {:Server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request } wsCloseErrorServerRequest = 1011; {:Connection was closed due to a failure to perform a TLS handshake. This close code MUST NOT be sent by application. } wsCloseErrorTLS = 1015; type TWebSocketCustomConnection = class; {:Event procedural type to hook OnOpen events on connection } TWebSocketConnectionEvent = procedure (aSender: TWebSocketCustomConnection) of object; {:Event procedural type to hook OnPing, OnPong events on connection TWebSocketConnectionPingPongEvent = procedure (aSender: TWebSocketCustomConnection; aData: string) of object; } {:Event procedural type to hook OnClose event on connection } TWebSocketConnectionClose = procedure (aSender: TWebSocketCustomConnection; aCloseCode: integer; aCloseReason: string; aClosedByPeer: boolean) of object; {:Event procedural type to hook OnRead on OnWrite event on connection } TWebSocketConnectionData = procedure (aSender: TWebSocketCustomConnection; aFinal, aRes1, aRes2, aRes3: boolean; aCode: integer; aData: TMemoryStream) of object; {:Event procedural type to hook OnReadFull } TWebSocketConnectionDataFull = procedure (aSender: TWebSocketCustomConnection; aCode: integer; aData: TMemoryStream) of object; {:abstract(WebSocket connection) class is parent class for server and client connection } TWebSocketCustomConnection = class(TCustomConnection) private protected fOnRead: TWebSocketConnectionData; fOnReadFull: TWebSocketConnectionDataFull; fOnWrite: TWebSocketConnectionData; fOnClose: TWebSocketConnectionClose; fOnOpen: TWebSocketConnectionEvent; //fOnPing: TWebSocketConnectionPingPongEvent; //fOnPong: TWebSocketConnectionPingPongEvent; fCookie: string; fVersion: integer; fProtocol: string; fResourceName: string; fOrigin: string; fExtension: string; fPort: string; fHost: string; fHeaders: TStringList; fClosedByMe: boolean; fClosedByPeer: boolean; fMasking: boolean; fRequireMasking: boolean; fHandshake: boolean; fCloseCode: integer; fCloseReason: string; fClosingByPeer: boolean; fReadFinal: boolean; fReadRes1: boolean; fReadRes2: boolean; fReadRes3: boolean; fReadCode: integer; fReadStream: TMemoryStream; fWriteFinal: boolean; fWriteRes1: boolean; fWriteRes2: boolean; fWriteRes3: boolean; fWriteCode: integer; fWriteStream: TMemoryStream; fSendCriticalSection: syncobjs.TCriticalSection; fFullDataProcess: boolean; fFullDataStream: TMemoryStream; function GetClosed: boolean; function GetClosing: boolean; procedure ExecuteConnection; override; function ReadData(var aFinal, aRes1, aRes2, aRes3: boolean; var aCode: integer; aData: TMemoryStream): integer; virtual; function ValidConnection: boolean; procedure DoSyncClose; procedure DoSyncOpen; //procedure DoSyncPing; //procedure DoSyncPong; procedure DoSyncRead; procedure DoSyncReadFull; procedure DoSyncWrite; procedure SyncClose; procedure SyncOpen; //procedure SyncPing; //procedure SyncPong; procedure SyncRead; procedure SyncReadFull; procedure SyncWrite; {:Overload this function to process connection close (not at socket level, but as an actual WebSocket frame) aCloseCode represents close code (see wsClose constants) aCloseReason represents textual information transfered with frame (there is no specified format or meaning) aClosedByPeer whether connection has been closed by this connection object or by peer endpoint } procedure ProcessClose(aCloseCode: integer; aCloseReason: string; aClosedByPeer: boolean); virtual; {:Overload this function to process data as soon as they are read before other Process<data> function is called this function should be used by extensions to modify incomming data before the are process based on code } procedure ProcessData(var aFinal: boolean; var aRes1: boolean; var aRes2: boolean; var aRes3: boolean; var aCode: integer; aData: TMemoryStream); virtual; {:Overload this function to process ping frame) aData represents textual information transfered with frame (there is no specified format or meaning) } procedure ProcessPing(aData: string); virtual; {:Overload this function to process pong frame) aData represents textual information transfered with frame (there is no specified format or meaning) } procedure ProcessPong(aData: string); virtual; {:Overload this function to process binary frame) aFinal whether frame is final frame or continuing aRes1 whether 1st extension bit is set up aRes2 whether 2nd extension bit is set up aRes3 whether 3rd extension bit is set up aData data stream second version is for contuniation frames } procedure ProcessStream(aFinal, aRes1, aRes2, aRes3: boolean; aData: TMemoryStream); virtual; procedure ProcessStreamContinuation(aFinal, aRes1, aRes2, aRes3: boolean; aData: TMemoryStream); virtual; procedure ProcessStreamFull(aData: TMemoryStream); virtual; {:Overload this function to process text frame) aFinal whether frame is final frame or continuing aRes1 whether 1st extension bit is set up aRes2 whether 2nd extension bit is set up aRes3 whether 3rd extension bit is set up aData textual data second version is for contuniation frames } procedure ProcessText(aFinal, aRes1, aRes2, aRes3: boolean; aData: string); virtual; procedure ProcessTextContinuation(aFinal, aRes1, aRes2, aRes3: boolean; aData: string); virtual; procedure ProcessTextFull(aData: string); virtual; published public constructor Create(aSocket: TTCPCustomConnectionSocket); override; destructor Destroy; override; {: Whether connection is in active state (not closed, closing, socket, exists, i/o threads not terminated..) } function CanReceiveOrSend: boolean; {:Procedure to close connection aCloseCode represents close code (see wsClose constants) aCloseReason represents textual information transfered with frame (there is no specified format or meaning) the string can only be 123 bytes length } procedure Close(aCode: integer; aCloseReason: string); virtual; abstract; {:Send binary frame aData data stream aFinal whether frame is final frame or continuing aRes1 1st extension bit aRes2 2nd extension bit aRes3 3rd extension bit } procedure SendBinary(aData: TStream; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); {:Send binary continuation frame aData data stream aFinal whether frame is final frame or continuing aRes1 1st extension bit aRes2 2nd extension bit aRes3 3rd extension bit } procedure SendBinaryContinuation(aData: TStream; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); {:Send generic frame aFinal whether frame is final frame or continuing aRes1 1st extension bit aRes2 2nd extension bit aRes3 3rd extension bit aCode frame code aData data stream or string } function SendData(aFinal, aRes1, aRes2, aRes3: boolean; aCode: integer; aData: TStream): integer; overload; virtual; function SendData(aFinal, aRes1, aRes2, aRes3: boolean; aCode: integer; aData: string): integer; overload; virtual; {:Send textual frame aData data string (MUST be UTF-8) aFinal whether frame is final frame or continuing aRes1 1st extension bit aRes2 2nd extension bit aRes3 3rd extension bit } procedure SendText(aData: string; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); virtual; {:Send textual continuation frame aData data string (MUST be UTF-8) aFinal whether frame is final frame or continuing aRes1 1st extension bit aRes2 2nd extension bit aRes3 3rd extension bit } procedure SendTextContinuation(aData: string; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); {:Send Ping aData ping informations } procedure Ping(aData: string); {:Send Pong aData pong informations } procedure Pong(aData: string); {:Temination procedure This method should be called instead of Terminate to terminate thread, it internally calls Terminate, but can be overloaded, and can be used for data clean up } procedure TerminateThread; override; {: Whether connection has been closed (either socket has been closed or thread has been terminated or WebSocket has been closed by this and peer connection) } property Closed: boolean read GetClosed; {: Whether WebSocket has been closed by this and peer connection } property Closing: boolean read GetClosing; {: WebSocket connection cookies Property is regular unparsed Cookie header string e.g. cookie1=value1;cookie2=value2 empty string represents that no cookies are present } property Cookie: string read fCookie; {: WebSocket connection extensions Property is regular unparsed Sec-WebSocket-Extensions header string e.g. foo, bar; baz=2 On both client and server connection this value represents the extension(s) selected by server to be used as a result of extension negotioation value - represents that no extension was negotiated and no header will be sent to client it is the default value } property Extension: string read fExtension; {:Whether to register for full data processing (callink @link(ProcessFullText), @link(ProcessFullStream) @link(OnFullRead) those methods/events are called if FullDataProcess is @true and whole message is read (after final frame) } property FullDataProcess: boolean read fFullDataProcess write fFullDataProcess; {: Whether WebSocket handshake was succecfull (and connection is afer WS handshake) } property Handshake: boolean read fHandshake; {: WebSocket connection host Property is regular unparsed Host header string e.g. server.example.com } property Host: string read fHost; {: WebSocket connection origin Property is regular unparsed Sec-WebSocket-Origin header string e.g. http://example.com } property Origin: string read fOrigin; {: WebSocket connection protocol Property is regular unparsed Sec-WebSocket-Protocol header string e.g. chat, superchat On both client and server connection this value represents the protocol(s) selected by server to be used as a result of protocol negotioation value - represents that no protocol was negotiated and no header will be sent to client it is the default value } property Protocol: string read fProtocol; {: Connection port } property Port: string read fPort; {: Connection resource e.g. /path1/path2/path3/file.ext } property ResourceName: string read fResourceName; {: WebSocket version (either 7 or 8 or 13)} property Version: integer read fVersion; {: WebSocket Close frame event } property OnClose: TWebSocketConnectionClose read fOnClose write fOnClose; {: WebSocket connection successfully } property OnOpen: TWebSocketConnectionEvent read fOnOpen write fOnOpen; { : WebSocket ping property OnPing: TWebSocketConnectionPingPongEvent read fOnPing write fOnPing; } { : WebSocket pong property OnPong: TWebSocketConnectionPingPongEvent read fOnPong write fOnPong; } {: WebSocket frame read } property OnRead: TWebSocketConnectionData read fOnRead write fOnRead; {: WebSocket read full data} property OnReadFull: TWebSocketConnectionDataFull read fOnReadFull write fOnReadFull; {: WebSocket frame written } property OnWrite: TWebSocketConnectionData read fOnWrite write fOnWrite; end; {: Class of WebSocket connections } TWebSocketCustomConnections = class of TWebSocketCustomConnection; {: WebSocket server connection automatically created by server on incoming connection } TWebSocketServerConnection = class(TWebSocketCustomConnection) public constructor Create(aSocket: TTCPCustomConnectionSocket); override; procedure Close(aCode: integer; aCloseReason: string); override; procedure TerminateThread; override; {: List of all headers keys are lowercased header name e.g host, connection, sec-websocket-key } property Header: TStringList read fHeaders; end; {: Class of WebSocket server connections } TWebSocketServerConnections = class of TWebSocketServerConnection; {: WebSocket client connection, this object shoud be created to establish client to server connection } TWebSocketClientConnection = class(TWebSocketCustomConnection) protected function BeforeExecuteConnection: boolean; override; public {: construstor to create connection, parameters has the same meaning as corresponging connection properties (see 2 differences below) and should be formated according to headers values aProtocol and aExtension in constructor represents protocol(s) and extension(s) client is trying to negotiate, obejst properties then represents protocol(s) and extension(s) the server is supporting (the negotiation result) Version must be >= 8 } constructor Create(aHost, aPort, aResourceName: string; aOrigin: string = '-'; aProtocol: string = '-'; aExtension: string = '-'; aCookie: string = '-'; aVersion: integer = 13); reintroduce; virtual; procedure Close(aCode: integer; aCloseReason: string); override; procedure Execute; override; end; TWebSocketServer = class; {:Event procedural type to hook OnReceiveConnection events on server every time new server connection is about to be created (client is connecting to server) this event is called properties are representing connection properties as defined in @link(TWebSocketServerConnection) Protocol and Extension represents corresponding headers sent by client, as their out value server must define what kind of protocol(s) and extension(s) server is supporting, if event is not implemented, both values are considered as - (no value at all) HttpResult represents the HTTP result to be send in response, if connection is about to be accepted, the value MUST BE 101, any other value meand that the client will be informed about the result (using the HTTP code meaning) and connection will be closed, if event is not implemented 101 is used as a default value } TWebSocketServerReceiveConnection = procedure ( Server: TWebSocketServer; Socket: TTCPCustomConnectionSocket; Header: TStringList; ResourceName, Host, Port, Origin, Cookie: string; HttpResult: integer; Protocol, Extensions: string ) of object; TWebSocketServer = class(TCustomServer) protected {CreateServerConnection sync variables} fncSocket: TTCPCustomConnectionSocket; fncResourceName: string; fncHost: string; fncPort: string; fncOrigin: string; fncProtocol: string; fncExtensions: string; fncCookie: string; fncHeaders: string; fncResultHttp: integer; fOnReceiveConnection: TWebSocketServerReceiveConnection; protected function CreateServerConnection(aSocket: TTCPCustomConnectionSocket): TCustomConnection; override; procedure DoSyncReceiveConnection; procedure SyncReceiveConnection; property Terminated; {:This function defines what kind of TWebSocketServerConnection implementation should be used as a connection object. The servers default return value is TWebSocketServerConnection. If new connection class based on TWebSocketServerConnection is implemented, new server should be implemented as well with this method overloaded properties are representing connection properties as defined in @link(TWebSocketServerConnection) Protocol and Extension represents corresponding headers sent by client, as their out value server must define what kind of protocol(s) and extension(s) server is supporting, if event is not implemented, both values are cosidered as - (no value at all) HttpResult represents the HTTP result to be send in response, if connection is about to be accepted, the value MUST BE 101, any other value meand that the client will be informed about the result (using the HTTP code meaning) and connection will be closed, if event is not implemented 101 is used as a default value } function GetWebSocketConnectionClass( Socket: TTCPCustomConnectionSocket; Header: TStringList; ResourceName, Host, Port, Origin, Cookie: string; out HttpResult: integer; var Protocol, Extensions: string ): TWebSocketServerConnections; virtual; public {: WebSocket connection received } property OnReceiveConnection: TWebSocketServerReceiveConnection read fOnReceiveConnection write fOnReceiveConnection; {: close all connections for parameters see connection Close method } procedure CloseAllConnections(aCloseCode: integer; aReason: string); {:Temination procedure This method should be called instead of Terminate to terminate thread, it internally calls Terminate, but can be overloaded, and can be used for data clean up } procedure TerminateThread; override; {: Method to send binary data to all connected clients see @link(TWebSocketServerConnection.SendBinary) for parameters description } procedure BroadcastBinary(aData: TStream; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); {: Method to send text data to all connected clients see @link(TWebSocketServerConnection.SendText) for parameters description } procedure BroadcastText(aData: string; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); end; function httpCode(code: integer): string; implementation uses Math, synautil, synacode, synsock {$IFDEF Win32}, Windows{$ENDIF Win32}, BClasses, synachar; {$IFDEF Win32} {$O-} {$ENDIF Win32} function httpCode(code: integer): string; begin case (code) of 100: result := 'Continue'; 101: result := 'Switching Protocols'; 200: result := 'OK'; 201: result := 'Created'; 202: result := 'Accepted'; 203: result := 'Non-Authoritative Information'; 204: result := 'No Content'; 205: result := 'Reset Content'; 206: result := 'Partial Content'; 300: result := 'Multiple Choices'; 301: result := 'Moved Permanently'; 302: result := 'Found'; 303: result := 'See Other'; 304: result := 'Not Modified'; 305: result := 'Use Proxy'; 307: result := 'Temporary Redirect'; 400: result := 'Bad Request'; 401: result := 'Unauthorized'; 402: result := 'Payment Required'; 403: result := 'Forbidden'; 404: result := 'Not Found'; 405: result := 'Method Not Allowed'; 406: result := 'Not Acceptable'; 407: result := 'Proxy Authentication Required'; 408: result := 'Request Time-out'; 409: result := 'Conflict'; 410: result := 'Gone'; 411: result := 'Length Required'; 412: result := 'Precondition Failed'; 413: result := 'Request Entity Too Large'; 414: result := 'Request-URI Too Large'; 415: result := 'Unsupported Media Type'; 416: result := 'Requested range not satisfiable'; 417: result := 'Expectation Failed'; 500: result := 'Internal Server Error'; 501: result := 'Not Implemented'; 502: result := 'Bad Gateway'; 503: result := 'Service Unavailable'; 504: result := 'Gateway Time-out'; else result := 'unknown code: $code'; end; end; function ReadHttpHeaders(aSocket: TTCPCustomConnectionSocket; var aGet: string; aHeaders: TStrings): boolean; var s, name: string; begin aGet := ''; aHeaders.Clear; result := true; repeat aSocket.MaxLineLength := 1024 * 1024; // not to attack memory on server s := aSocket.RecvString(30 * 1000); // not to hang up connection if (aSocket.LastError <> 0) then begin result := false; break; end; if (s = '') then break; if (aGet = '') then aGet := s else begin name := LowerCase(trim(SeparateLeft(s, ':'))); if (aHeaders.Values[name] = '') then aHeaders.Values[name] := trim(SeparateRight(s, ':')) else aHeaders.Values[name] := aHeaders.Values[name] + ',' + trim(SeparateRight(s, ':')); end; until {IsTerminated} false; aSocket.MaxLineLength := 0; end; procedure ODS(aStr: string); overload; begin {$IFDEF Win32} OutputDebugString(pChar(FormatDateTime('yyyy-mm-dd hh:nn:ss', now) + ': ' + aStr)); {$ENDIF Win32} end; procedure ODS(aStr: string; aData: array of const); overload; begin {$IFDEF Win32} ODS(Format(aStr, aData)); {$ENDIF Win32} end; { TWebSocketServer } procedure TWebSocketServer.BroadcastBinary(aData: TStream; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); var i: integer; begin LockTermination; for i := 0 to fConnections.Count - 1 do begin if (not TWebSocketServerConnection(fConnections[i]).IsTerminated) then TWebSocketServerConnection(fConnections[i]).SendBinary(aData, aFinal, aRes1, aRes2, aRes3); end; UnLockTermination; end; procedure TWebSocketServer.BroadcastText(aData: string; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); var i: integer; begin LockTermination; for i := 0 to fConnections.Count - 1 do begin if (not TWebSocketServerConnection(fConnections[i]).IsTerminated) then TWebSocketServerConnection(fConnections[i]).SendText(aData, aFinal, aRes1, aRes2, aRes3); end; UnLockTermination; end; procedure TWebSocketServer.CloseAllConnections(aCloseCode: integer; aReason: string); var i: integer; begin LockTermination; //for i := 0 to fConnections.Count - 1 do for i := fConnections.Count - 1 downto 0 do begin if (not TWebSocketServerConnection(fConnections[i]).IsTerminated) then TWebSocketServerConnection(fConnections[i]).Close(aCloseCode, aReason);// SendBinary(aData, aFinal, aRes1, aRes2, aRes3); end; UnLockTermination; end; function TWebSocketServer.CreateServerConnection(aSocket: TTCPCustomConnectionSocket): TCustomConnection; var headers, hrs: TStringList; get: string; s{, resName, host, port}, key, version{, origin, protocol, extensions, cookie}: string; iversion, vv: integer; res: boolean; r : TWebSocketServerConnections; begin fncSocket := aSocket; result := inherited CreateServerConnection(aSocket); headers := TStringList.Create; try res := ReadHttpHeaders(aSocket, get, headers); if (res) then begin res := false; try //CHECK HTTP GET if ((Pos('GET ', Uppercase(get)) <> 0) and (Pos(' HTTP/1.1', Uppercase(get)) <> 0)) then begin fncResourceName := SeparateRight(get, ' '); fncResourceName := SeparateLeft(fncResourceName, ' '); end else exit; fncResourceName := trim(fncResourceName); //CHECK HOST AND PORT s := headers.Values['host']; if (s <> '') then begin fncHost := trim(s); fncPort := SeparateRight(fncHost, ':'); fncHost := SeparateLeft(fncHost, ':'); end; fncHost := trim(fncHost); fncPort := trim(fncPort); if (fncHost = '') then exit; //if (fncPort <> '') and (fncPort <> self.port) then exit; { if (self.host <> '0.0.0.0') and (self.Host <> '127.0.0.1') and (self.host <> 'localhost') and (fncHost <> self.host) then exit; } //WEBSOCKET KEY s := headers.Values['sec-websocket-key']; if (s <> '') then begin if (Length(DecodeBase64(s)) = 16) then begin key := s; end; end; if (key = '') then exit; key := trim(key); //WEBSOCKET VERSION s := headers.Values['sec-websocket-version']; if (s <> '') then begin vv := StrToIntDef(s, -1); if ((vv >= 7) and (vv <= 13)) then begin version := s; end; end; if (version = '') then exit; version := trim(version); iversion := StrToIntDef(version, 13); if (LowerCase(headers.Values['upgrade']) <> LowerCase('websocket')) or (pos('upgrade', LowerCase(headers.Values['connection'])) = 0) then exit; //COOKIES fncProtocol := '-'; fncExtensions := '-'; fncCookie := '-'; fncOrigin := '-'; if (iversion < 13) then begin if (headers.IndexOfName('sec-websocket-origin') > -1) then fncOrigin := trim(headers.Values['sec-websocket-origin']); end else begin if (headers.IndexOfName('origin') > -1) then fncOrigin := trim(headers.Values['origin']); end; if (headers.IndexOfName('sec-websocket-protocol') > -1) then fncProtocol := trim(headers.Values['sec-websocket-protocol']); if (headers.IndexOfName('sec-websocket-extensions') > -1) then fncExtensions := trim(headers.Values['sec-websocket-extensions']); if (headers.IndexOfName('cookie') > -1) then fncCookie := trim(headers.Values['cookie']); fncHeaders := trim(headers.text); res := true; finally if (res) then begin fncResultHttp := 101; hrs := TStringList.Create; hrs.Assign(headers); r := GetWebSocketConnectionClass( fncSocket, hrs, fncResourceName, fncHost, fncPort, fncOrigin, fncCookie, fncResultHttp, fncProtocol, fncExtensions ); if (assigned(r)) then begin DoSyncReceiveConnection; if (fncResultHttp <> 101) then //HTTP ERROR FALLBACK begin aSocket.SendString(Format('HTTP/1.1 %d %s'+#13#10, [fncResultHttp, httpCode(fncResultHttp)])); aSocket.SendString(Format('%d %s'+#13#10#13#10, [fncResultHttp, httpCode(fncResultHttp)])); end else begin key := EncodeBase64(SHA1(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')); s := 'HTTP/1.1 101 Switching Protocols' + #13#10; s := s + 'Upgrade: websocket' + #13#10; s := s + 'Connection: Upgrade' + #13#10; s := s + 'Sec-WebSocket-Accept: ' + key + #13#10; if (fncProtocol <> '-') then begin s := s + 'Sec-WebSocket-Protocol: ' + fncProtocol + #13#10; end; // Commenting this out fixed errors. // if (fncExtensions <> '-') then // begin // s := s + 'Sec-WebSocket-Extensions: ' + fncExtensions + #13#10; // end; s := s + #13#10; aSocket.SendString(s); if (aSocket.LastError = 0) then begin result := r.Create(aSocket); TWebSocketCustomConnection(result).fCookie := fncCookie; TWebSocketCustomConnection(result).fVersion := StrToInt(version); TWebSocketCustomConnection(result).fProtocol := fncProtocol; TWebSocketCustomConnection(result).fResourceName := fncResourceName; TWebSocketCustomConnection(result).fOrigin := fncOrigin; TWebSocketCustomConnection(result).fExtension := fncExtensions; TWebSocketCustomConnection(result).fPort := fncPort; TWebSocketCustomConnection(result).fHost := fncHost; TWebSocketCustomConnection(result).fHeaders.Assign(headers); TWebSocketCustomConnection(result).fHandshake := true; end; end; end; hrs.Free; end; end; end; finally headers.Free; end; end; procedure TWebSocketServer.DoSyncReceiveConnection; begin if (assigned(fOnReceiveConnection)) then Synchronize(SyncReceiveConnection) end; function TWebSocketServer.GetWebSocketConnectionClass( Socket: TTCPCustomConnectionSocket; Header: TStringList; ResourceName, Host, Port, Origin, Cookie: string; out HttpResult: integer; var Protocol, Extensions: string ): TWebSocketServerConnections; begin result := TWebSocketServerConnection; end; procedure TWebSocketServer.SyncReceiveConnection; var h: TStringList; begin if (assigned(fOnReceiveConnection)) then begin h := TStringList.Create; h.Text := fncHeaders; fOnReceiveConnection( self, fncSocket, h, fncResourceName, fncHost, fncPort, fncOrigin, fncCookie, fncResultHttp, fncProtocol, fncExtensions ); h.Free; end; end; procedure TWebSocketServer.TerminateThread; begin if (terminated) then exit; fOnReceiveConnection := nil; inherited; end; { TWebSocketCustomConnection } function TWebSocketCustomConnection.CanReceiveOrSend: boolean; begin result := ValidConnection and not (fClosedByMe or fClosedByPeer) and fHandshake; end; constructor TWebSocketCustomConnection.Create(aSocket: TTCPCustomConnectionSocket); begin fHeaders := TStringList.Create; fCookie := ''; fVersion := 0; fProtocol := '-'; fResourceName := ''; fOrigin := ''; fExtension := '-'; fPort := ''; fHost := ''; fClosedByMe := false; fClosedByPeer := false; fMasking := false; fClosingByPeer := false; fRequireMasking := false; fReadFinal := false; fReadRes1 := false; fReadRes2 := false; fReadRes3 := false; fReadCode := 0; fReadStream := TMemoryStream.Create; fWriteFinal := false; fWriteRes1 := false; fWriteRes2 := false; fWriteRes3 := false; fWriteCode := 0; fWriteStream := TMemoryStream.Create; fFullDataProcess := false; fFullDataStream := TMemoryStream.Create; fSendCriticalSection := syncobjs.TCriticalSection.Create; fHandshake := false; inherited; end; destructor TWebSocketCustomConnection.Destroy; begin fSendCriticalSection.Free; fFullDataStream.Free; fWriteStream.Free; fReadStream.Free; fHeaders.Free; inherited; end; procedure TWebSocketCustomConnection.DoSyncClose; begin if (assigned(fOnClose)) then Synchronize(SyncClose); end; procedure TWebSocketCustomConnection.DoSyncOpen; begin if (assigned(fOnOpen)) then Synchronize(SyncOpen); end; { procedure TWebSocketCustomConnection.DoSyncPing; begin end; procedure TWebSocketCustomConnection.DoSyncPong; begin end; } procedure TWebSocketCustomConnection.DoSyncRead; begin fReadStream.Position := 0; if (assigned(fOnRead)) then Synchronize(SyncRead); end; procedure TWebSocketCustomConnection.DoSyncReadFull; begin fFullDataStream.Position := 0; if (assigned(fOnReadFull)) then Synchronize(SyncReadFull); end; procedure TWebSocketCustomConnection.DoSyncWrite; begin if (assigned(fOnWrite)) then Synchronize(SyncWrite); end; procedure TWebSocketCustomConnection.ExecuteConnection; var result: integer; //Data: string; closeCode: integer; closeResult: string; s: string; lastDataCode, lastDataCode2: integer; //Data: TStringStream; begin DoSyncOpen; try //while(not IsTerminated) or fClosed do lastDataCode := -1; lastDataCode2 := -1; while CanReceiveOrSend do begin //OutputDebugString(pChar(Format('execute %d', [fIndex]))); result := ReadData(fReadFinal, fReadRes1, fReadRes2, fReadRes3, fReadCode, fReadStream); if (CanReceiveOrSend) then begin if (result = 0) then // no socket error occured begin fReadStream.Position := 0; ProcessData(fReadFinal, fReadRes1, fReadRes2, fReadRes3, fReadCode, fReadStream); fReadStream.Position := 0; if (fReadCode in [wsCodeText, wsCodeBinary]) and fFullDataProcess then begin fFullDataStream.Size := 0; fFullDataStream.Position := 0; end; if (fReadCode in [wsCodeContinuation, wsCodeText, wsCodeBinary]) and fFullDataProcess then begin fReadStream.Position := 0; fFullDataStream.CopyFrom(fReadStream, fReadStream.Size); fReadStream.Position := 0; end; //if (fReadFinal) then //final frame begin case fReadCode of wsCodeContinuation: begin if (lastDataCode = wsCodeText) then begin s := ReadStrFromStream(fReadStream, fReadStream.size); ProcessTextContinuation(fReadFinal, fReadRes1, fReadRes2, fReadRes3, s); DoSyncRead; end else if (lastDataCode = wsCodeBinary) then begin ProcessStreamContinuation(fReadFinal, fReadRes1, fReadRes2, fReadRes3, fReadStream); DoSyncRead; end else Close(wsCloseErrorProtocol, 'Unknown continuaton'); if (fReadFinal) then lastDataCode := -1; end; wsCodeText: begin // text, binary frame s := ReadStrFromStream(fReadStream, fReadStream.size); ProcessText(fReadFinal, fReadRes1, fReadRes2, fReadRes3, s); DoSyncRead; if (not fReadFinal) then lastDataCode := wsCodeText else lastDataCode := -1; lastDataCode2 := wsCodeText; end; wsCodeBinary: begin // text, binary frame ProcessStream(fReadFinal, fReadRes1, fReadRes2, fReadRes3, fReadStream); DoSyncRead; if (not fReadFinal) then lastDataCode := wsCodeBinary else lastDataCode := -1; lastDataCode2 := wsCodeBinary; end; wsCodeClose: begin //connection close closeCode := wsCloseNoStatus; closeResult := ReadStrFromStream(fReadStream, fReadStream.size); if (length(closeResult) > 1) then begin closeCode := ord(closeResult[1])*256 + ord(closeResult[2]); delete(closeResult, 1, 2); end; fClosedByPeer := true; //OutputDebugString(pChar(Format('closing1 %d', [fIndex]))); ProcessClose(closeCode, closeResult, true); //OutputDebugString(pChar(Format('closing2 %d', [fIndex]))); TerminateThread; //OutputDebugString(pChar(Format('closing3 %d', [fIndex]))); fSendCriticalSection.Enter; end; wsCodePing: begin // ping ProcessPing(ReadStrFromStream(fReadStream, fReadStream.size)); DoSyncRead; end; wsCodePong: begin // pong ProcessPong(ReadStrFromStream(fReadStream, fReadStream.size)); DoSyncRead; end else begin //ERROR Close(wsCloseErrorData, Format('Unknown data type: %d', [fReadCode])); end; end; end; if (fReadCode in [wsCodeContinuation, wsCodeText, wsCodeBinary]) and fFullDataProcess and fReadFinal then begin fFullDataStream.Position := 0; if (lastDataCode2 = wsCodeText) then begin s := ReadStrFromStream(fFullDataStream, fFullDataStream.size); ProcessTextFull(s); end else if (lastDataCode2 = wsCodeBinary) then ProcessStreamFull(fFullDataStream); SyncReadFull; end; end else TerminateThread; end; end; finally {$IFDEF UNIX} sleep(2000); {$ENDIF UNIX} end; while not terminated do sleep(500); //OutputDebugString(pChar(Format('terminating %d', [fIndex]))); fSendCriticalSection.Enter; end; function TWebSocketCustomConnection.GetClosed: boolean; begin result := not CanReceiveOrSend; end; function TWebSocketCustomConnection.GetClosing: boolean; begin result := (fClosedByMe or fClosedByPeer); end; procedure TWebSocketCustomConnection.Ping(aData: string); begin if (CanReceiveOrSend) then begin SendData(true, false, false, false, wsCodePing, aData); end; end; procedure TWebSocketCustomConnection.Pong(aData: string); begin if (CanReceiveOrSend) then begin SendData(true, false, false, false, wsCodePong, aData); end; end; procedure TWebSocketCustomConnection.ProcessClose(aCloseCode: integer; aCloseReason: string; aClosedByPeer: boolean); begin fCloseCode := aCloseCode; fCloseReason := aCloseReason; fClosingByPeer := aClosedByPeer; DoSyncClose; end; procedure TWebSocketCustomConnection.ProcessData(var aFinal, aRes1, aRes2, aRes3: boolean; var aCode: integer; aData: TMemoryStream); begin end; procedure TWebSocketCustomConnection.ProcessPing(aData: string); begin Pong(aData); end; procedure TWebSocketCustomConnection.ProcessPong(aData: string); begin end; procedure TWebSocketCustomConnection.ProcessStream(aFinal, aRes1, aRes2, aRes3: boolean; aData: TMemoryStream); begin end; procedure TWebSocketCustomConnection.ProcessStreamContinuation(aFinal, aRes1, aRes2, aRes3: boolean; aData: TMemoryStream); begin end; procedure TWebSocketCustomConnection.ProcessStreamFull( aData: TMemoryStream); begin end; procedure TWebSocketCustomConnection.ProcessText(aFinal, aRes1, aRes2, aRes3: boolean; aData: string); begin end; procedure TWebSocketCustomConnection.ProcessTextContinuation(aFinal, aRes1, aRes2, aRes3: boolean; aData: string); begin end; procedure TWebSocketCustomConnection.ProcessTextFull(aData: string); begin end; function GetByte(aSocket: TTCPCustomConnectionSocket; var aByte: Byte; var aTimeout: integer): integer; begin aByte := aSocket.RecvByte(aTimeout); result := aSocket.LastError; end; function hexToStr(aDec: integer; aLength: integer): string; var tmp: string; i: integer; begin tmp := IntToHex(aDec, aLength); result := ''; for i := 1 to (Length(tmp)+1) div 2 do begin result := result + ansichar(StrToInt('$'+Copy(tmp, i * 2 - 1, 2))); end; end; function StrToHexstr2(str: string): string; var i: integer; begin result := ''; for i := 1 to Length(str) do result := result + IntToHex(ord(str[i]), 2) + ' '; end; function TWebSocketCustomConnection.ReadData(var aFinal, aRes1, aRes2, aRes3: boolean; var aCode: integer; aData: TMemoryStream): integer; var timeout: integer; b: byte; mask: boolean; len, i: int64; mBytes: array[0..3] of byte; ms: TMemoryStream; begin result := 0; len := 0; //aCode := 0; repeat timeout := 10 * 1000; if CanReceiveOrSend then begin //OutputDebugString(pChar(Format('%d', [Index]))); if (fSocket.CanReadEx(1000)) then begin if CanReceiveOrSend then begin b := fSocket.RecvByte(1000); if (fSocket.LastError = 0) then begin try try // BASIC INFORMATIONS aFinal := (b and $80) = $80; aRes1 := (b and $40) = $40; aRes2 := (b and $20) = $20; aRes3 := (b and $10) = $10; aCode := b and $F; // MASK AND LENGTH mask := false; result := GetByte(fSocket, b, timeout); if (result = 0) then begin mask := (b and $80) = $80; len := (b and $7F); if (len = 126) then begin result := GetByte(fSocket, b, timeout); if (result = 0) then begin len := b * $100; // 00 00 result := GetByte(fSocket, b, timeout); if (result = 0) then begin len := len + b; end; end; end else if (len = 127) then //00 00 00 00 00 00 00 00 begin //TODO nesting og get byte should be different result := GetByte(fSocket, b, timeout); if (result = 0) then begin len := b * $100000000000000; if (result = 0) then begin result := GetByte(fSocket, b, timeout); len := len + b * $1000000000000; end; if (result = 0) then begin result := GetByte(fSocket, b, timeout); len := len + b * $10000000000; end; if (result = 0) then begin result := GetByte(fSocket, b, timeout); len := len + b * $100000000; end; if (result = 0) then begin result := GetByte(fSocket, b, timeout); len := len + b * $1000000; end; if (result = 0) then begin result := GetByte(fSocket, b, timeout); len := len + b * $10000; end; if (result = 0) then begin result := GetByte(fSocket, b, timeout); len := len + b * $100; end; if (result = 0) then begin result := GetByte(fSocket, b, timeout); len := len + b; end; end; end; end; if (result = 0) and (fRequireMasking) and (not mask) then begin // TODO some protocol error raise Exception.Create('mask'); end; // MASKING KEY if (mask) and (result = 0) then begin result := GetByte(fSocket, mBytes[0], timeout); if (result = 0) then result := GetByte(fSocket, mBytes[1], timeout); if (result = 0) then result := GetByte(fSocket, mBytes[2], timeout); if (result = 0) then result := GetByte(fSocket, mBytes[3], timeout); end; // READ DATA if (result = 0) then begin aData.Clear; ms := TMemoryStream.Create; try timeout := 1000 * 60 * 60 * 2; //(len div (1024 * 1024)) * 1000 * 60; if (mask) then fSocket.RecvStreamSize(ms, timeout, len) else fSocket.RecvStreamSize(aData, timeout, len); ms.Position := 0; aData.Position := 0; result := fSocket.LastError; if (result = 0) then begin if (mask) then begin i := 0; while i < len do begin ms.ReadBuffer(b, sizeOf(b)); b := b xor mBytes[i mod 4]; aData.WriteBuffer(b, SizeOf(b)); inc(i); end; end; end; finally ms.free; end; aData.Position := 0; break; end; except result := -1; end; finally end; end else begin result := -1; end; end else begin result := -1; end; end else begin // if (fSocket.CanRead(0)) then // ODS(StrToHexstr2(fSocket.RecvBufferStr(10, 1000))); if (fSocket.LastError <> WSAETIMEDOUT) and (fSocket.LastError <> 0) then begin //if (fSocket.LastError = WS then result := -1; end; end; end else begin result := -1; end; if (result <> 0) then begin if (not Terminated) then begin if (fSocket.LastError = WSAECONNRESET) then begin result := 0; aCode := wsCodeClose; aFinal := true; aRes1 := false; aRes2 := false; aRes3 := false; aData.Size := 0; WriteStrToStream(aData, ansichar(wsCloseErrorClose div 256) + ansichar(wsCloseErrorClose mod 256)); aData.Position := 0; end else begin if (not fClosedByMe) then begin Close(wsCloseErrorProtocol, ''); TerminateThread; end; end; end; break; end until false; end; function TWebSocketCustomConnection.SendData(aFinal, aRes1, aRes2, aRes3: boolean; aCode: integer; aData: TStream): integer; var b: byte; s: ansistring; mBytes: array[0..3] of byte; ms: TMemoryStream; i, len: int64; begin result := 0; if (CanReceiveOrSend) or ((aCode = wsCodeClose) and (not fClosedByPeer)) then begin fSendCriticalSection.Enter; try s := ''; // BASIC INFORMATIONS b := IfThen(aFinal, 1, 0) * $80; b := b + IfThen(aRes1, 1, 0) * $40; b := b + IfThen(aRes2, 1, 0) * $20; b := b + IfThen(aRes3, 1, 0) * $10; b := b + aCode; s := s + ansichar(b); // MASK AND LENGTH b := IfThen(fMasking, 1, 0) * $80; if (aData.Size < 126) then b := b + aData.Size else if (aData.Size < 65536) then b := b + 126 else b := b + 127; s := s + ansichar(b); if (aData.Size >= 126) then begin if (aData.Size < 65536) then begin s := s + hexToStr(aData.Size, 4); end else begin s := s + hexToStr(aData.Size, 16); end; end; // MASKING KEY if (fMasking) then begin mBytes[0] := Random(256); mBytes[1] := Random(256); mBytes[2] := Random(256); mBytes[3] := Random(256); s := s + ansichar(mBytes[0]); s := s + ansichar(mBytes[1]); s := s + ansichar(mBytes[2]); s := s + ansichar(mBytes[3]); end; fSocket.SendString(s); result := fSocket.LastError; if (result = 0) then begin aData.Position := 0; ms := TMemoryStream.Create; try if (not fMasking) then begin fSocket.SendStreamRaw(aData); end else begin i := 0; len := aData.Size; while i < len do begin aData.ReadBuffer(b, sizeOf(b)); b := b xor mBytes[i mod 4]; ms.WriteBuffer(b, SizeOf(b)); inc(i); end; ms.Position := 0; fSocket.SendStreamRaw(ms); end; result := fSocket.LastError; if (result = 0) then begin fWriteFinal := aFinal; fWriteRes1 := aRes1; fWriteRes2 := aRes2; fWriteRes3 := aRes3; fWriteCode := aCode; aData.Position := 0; fWriteStream.Clear; fWriteStream.LoadFromStream(aData); DoSyncWrite; end; finally ms.Free; end; end; finally if (aCode <> wsCodeClose) then while not fSocket.CanWrite(10) do sleep(10); fSendCriticalSection.Leave; end; end; end; function TWebSocketCustomConnection.SendData(aFinal, aRes1, aRes2, aRes3: boolean; aCode: integer; aData: string): integer; var ms : TMemoryStream; begin ms := TMemoryStream.Create; try WriteStrToStream(ms, aData); result := SendData(aFinal, aRes1, aRes2, aRes3, aCode, ms); finally ms.Free; end; end; procedure TWebSocketCustomConnection.SendBinary(aData: TStream; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); begin SendData(aFinal, aRes1, aRes2, aRes3, wsCodeBinary, aData); end; procedure TWebSocketCustomConnection.SendBinaryContinuation(aData: TStream; aFinal, aRes1, aRes2, aRes3: boolean); begin SendData(aFinal, aRes1, aRes2, aRes3, wsCodeContinuation, aData); end; procedure TWebSocketCustomConnection.SendText(aData: string; aFinal: boolean = true; aRes1: boolean = false; aRes2: boolean = false; aRes3: boolean = false); begin SendData(aFinal, aRes1, aRes2, aRes3, wsCodeText, aData); end; procedure TWebSocketCustomConnection.SendTextContinuation(aData: string; aFinal, aRes1, aRes2, aRes3: boolean); begin SendData(aFinal, aRes1, aRes2, aRes3, wsCodeContinuation, aData); end; { procedure TWebSocketCustomConnection.SendStream(aFinal, aRes1, aRes2, aRes3: boolean; aData: TStream); begin if (CanReceiveOrSend) then begin SendData(aFinal, aRes1, aRes2, aRes3, wsCodeBinary, aData); end; end; } { procedure TWebSocketCustomConnection.SendStream(aData: TStream); begin //SendStream(aFinal, false, false, false, aData); end; } { procedure TWebSocketCustomConnection.SendText(aFinal, aRes1, aRes2, aRes3: boolean; aData: string); //var tmp: string; begin if (CanReceiveOrSend) then begin SendData(aFinal, false, false, false, wsCodeText, aData); end; end; } { procedure TWebSocketCustomConnection.SendText(aData: string); begin //SendText(true, false, false, false, aData); //SendData(true, false, false end; } procedure TWebSocketCustomConnection.SyncClose; begin if (assigned(fOnClose)) then fOnClose(self, fCloseCode, fCloseReason, fClosingByPeer); end; procedure TWebSocketCustomConnection.SyncOpen; begin if (assigned(fOnOpen)) then fOnOpen(self); end; { procedure TWebSocketCustomConnection.SyncPing; begin end; procedure TWebSocketCustomConnection.SyncPong; begin end; } procedure TWebSocketCustomConnection.SyncRead; begin fReadStream.Position := 0; if (assigned(fOnRead)) then fOnRead(self, fReadFinal, fReadRes1, fReadRes2, fReadRes3, fReadCode, fReadStream); end; procedure TWebSocketCustomConnection.SyncReadFull; begin fFullDataStream.Position := 0; if (assigned(fOnReadFull)) then fOnReadFull(self, fReadCode, fFullDataStream); end; procedure TWebSocketCustomConnection.SyncWrite; begin fWriteStream.Position := 0; if (assigned(fOnWrite)) then fOnWrite(self, fWriteFinal, fWriteRes1, fWriteRes2, fWriteRes3, fWriteCode, fWriteStream); end; procedure TWebSocketCustomConnection.TerminateThread; begin if (Terminated) then exit; if (not Closed) then DoSyncClose; Socket.OnSyncStatus := nil; Socket.OnStatus := nil; fOnRead := nil; fOnReadFull := nil; fOnWrite := nil; fOnClose := nil; fOnOpen := nil; { if not Closing then begin SendData(true, false, false, false, wsCodeClose, '1001'); end; } inherited; end; function TWebSocketCustomConnection.ValidConnection: boolean; begin result := (not IsTerminated) and (Socket.Socket <> INVALID_SOCKET); end; { TWebSocketServerConnection } procedure TWebSocketServerConnection.Close(aCode: integer; aCloseReason: string); begin if (Socket.Socket <> INVALID_SOCKET) and (not fClosedByMe) then begin fClosedByMe := true; if (not fClosedByPeer) then begin SendData(true, false, false, false, wsCodeClose, hexToStr(aCode, 4) + copy(aCloseReason, 1, 123)); //Sleep(2000); ProcessClose(aCode, aCloseReason, false); end; TerminateThread; end; end; constructor TWebSocketServerConnection.Create(aSocket: TTCPCustomConnectionSocket); begin inherited; fRequireMasking := true; end; procedure TWebSocketServerConnection.TerminateThread; begin if (Terminated) then exit; //if (not TWebSocketServer(fParent).Terminated) and (not fClosedByMe) then DoSyncClose; fOnClose := nil; inherited; end; { TWebSocketClientConnection } function TWebSocketClientConnection.BeforeExecuteConnection: boolean; var key, s, get: string; i: integer; headers: TStringList; begin Result := not IsTerminated; if (Result) then begin s := Format('GET %s HTTP/1.1' + #13#10, [fResourceName]); s := s + Format('Upgrade: websocket' + #13#10, []); s := s + Format('Connection: Upgrade' + #13#10, []); s := s + Format('Host: %s:%s' + #13#10, [fHost, fPort]); for I := 1 to 16 do key := key + ansichar(Random(85) + 32); key := EncodeBase64(key); s := s + Format('Sec-WebSocket-Key: %s' + #13#10, [(key)]); s := s + Format('Sec-WebSocket-Version: %d' + #13#10, [fVersion]); //TODO extensions if (fProtocol <> '-') then s := s + Format('Sec-WebSocket-Protocol: %s' + #13#10, [fProtocol]); if (fOrigin <> '-') then begin if (fVersion < 13) then s := s + Format('Sec-WebSocket-Origin: %s' + #13#10, [fOrigin]) else s := s + Format('Origin: %s' + #13#10, [fOrigin]); end; if (fCookie <> '-') then s := s + Format('Cookie: %s' + #13#10, [(fCookie)]); if (fExtension <> '-') then s := s + Format('Sec-WebSocket-Extensions: %s' + #13#10, [fExtension]); s := s + #13#10; fSocket.SendString(s); Result := (not IsTerminated) and (fSocket.LastError = 0); if (result) then begin headers := TStringList.Create; try result := ReadHttpHeaders(fSocket, get, headers); if (result) then result := pos(LowerCase('HTTP/1.1 101'), LowerCase(get)) = 1; if (result) then result := (LowerCase(headers.Values['upgrade']) = LowerCase('websocket')) and (LowerCase(headers.Values['connection']) = 'upgrade'); fProtocol := '-'; fExtension := '-'; if (headers.IndexOfName('sec-websocket-protocol') > -1) then fProtocol := trim(headers.Values['sec-websocket-protocol']); if (headers.IndexOfName('sec-websocket-extensions') > -1) then fExtension := trim(headers.Values['sec-websocket-extensions']); if (result) then result := (headers.Values['sec-websocket-accept'] = EncodeBase64(SHA1(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); finally headers.Free; end; end; end; if (result) then fHandshake := true; end; procedure TWebSocketClientConnection.Close(aCode: integer; aCloseReason: string); begin if ValidConnection and (not fClosedByMe) then begin fClosedByMe := true; if (not fClosedByPeer) then begin SendData(true, false, false, false, wsCodeClose, hexToStr(aCode, 4) + copy(aCloseReason, 1, 123)); //Sleep(2000); ProcessClose(aCode, aCloseReason, false); end; TerminateThread; end; end; constructor TWebSocketClientConnection.Create(aHost, aPort, aResourceName, aOrigin, aProtocol: string; aExtension: string; aCookie: string; aVersion: integer); begin fSocket := TTCPCustomConnectionSocket.Create; inherited Create(fSocket); fOrigin := aOrigin; fHost := aHost; fPort := aPort; fResourceName := aResourceName; fProtocol := aProtocol; fVersion := aVersion; fMasking := true; fCookie := aCookie; fExtension := aExtension; end; { procedure TWebSocketClientConnection.DoConnect; begin if (assigned(fOnConnect)) then Synchronize(SyncConnect); end; procedure TWebSocketClientConnection.DoDisconnect; begin if (assigned(fOnDisConnect)) then Synchronize(SyncDisconnect); end; } procedure TWebSocketClientConnection.Execute; begin if (not IsTerminated) and (fVersion >= 8) then begin fSocket.Connect(fHost, fPort); if (SSL) then fSocket.SSLDoConnect; if (fSocket.LastError = 0) then begin //DoConnect; inherited Execute; //DoDisconnect; end else TerminateThread; end; end; { procedure TWebSocketClientConnection.SyncConnect; begin fOnConnect(self); end; procedure TWebSocketClientConnection.SyncDisconnect; begin fOnDisConnect(self); end; } initialization Randomize; { GET / HTTP/1.1 Upgrade: websocket Connection: Upgrade Host: 81.0.231.149:81 Sec-WebSocket-Origin: http://html5.bauglir.dev Sec-WebSocket-Key: Q9ceXTuzjdF2o23CRYvnuA== Sec-WebSocket-Version: 8 GET / HTTP/1.1 Host: 81.0.231.149:81 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: sk,cs;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Accept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7 Connection: keep-alive, Upgrade Sec-WebSocket-Version: 7 Sec-WebSocket-Origin: http://html5.bauglir.dev Sec-WebSocket-Key: HgBKcPfdBSzjCYxGnWCO3g== Pragma: no-cache Cache-Control: no-cache Upgrade: websocket Cookie: __utma=72544661.1949147240.1313811966.1313811966.1313811966.1; __utmb=72544661.3.10.1313811966; __utmc=72544661; __utmz=72544661.1313811966.1.1.utmcsr=localhost|utmccn=(referral)|utmcmd=referral|utmcct=/websocket/index.php 1300} end.
unit uthrCancelarFechamento; interface uses System.Classes, clAgentes, clEntregador, clEntrega, clExtrato, clLancamentos, clAbastecimentos, clRestricoes, clPlanilhaCredito, clUtil, udm, Dialogs, Windows, Forms, SysUtils, Messages, Controls, System.DateUtils; type thrCancelarFechamento = class(TThread) private { Private declarations } agente: TAgente; entregador: TEntregador; entrega: TEntrega; extrato: TExtrato; lancamento: TLancamentos; restricao: TRestricoes; abastecimento: TAbastecimentos; planilha: TPlanilhaCredito; protected procedure Execute; override; procedure IniciaProcesso; procedure AtualizaProgress; procedure TerminaProcesso; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure thrCancelarFechamento.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } { thrCancelarFechamento } uses ufrmExtrato, uGlobais; procedure thrCancelarFechamento.Execute; var Contador, LinhasTotal, iCodigo: Integer; begin agente := TAgente.Create(); entregador := TEntregador.Create(); entrega := TEntrega.Create(); extrato := TExtrato.Create(); lancamento := TLancamentos.Create(); restricao := TRestricoes.Create(); abastecimento := TAbastecimentos.Create(); planilha := TPlanilhaCredito.Create(); try Contador := 1; LinhasTotal := dm.tbExtrato.RecordCount; Synchronize(IniciaProcesso); dm.tbExtrato.First; while not(dm.tbExtrato.Eof) do begin iCodigo := dm.tbExtratoCOD_ENTREGADOR.AsInteger; // Cancela fechamento das entregas if not(entrega.Fechar(dm.tbExtratoDAT_INICIO.AsString, dm.tbExtratoDAT_TERMINO.AsString, dm.tbExtratoDAT_PAGO.AsString, dm.tbExtratoNUM_EXTRATO.AsString, dm.tbExtratoCOD_AGENTE.AsString, dm.tbExtratoCOD_ENTREGADOR.AsString, 'BAIXA', 'CANCELAR', 0)) then begin MessageDlg('Erro Cancelamento de Fechamento: ENTREGAS; Agente: ' + dm.tbExtratoCOD_AGENTE.AsString + ' / Entregador: ' + dm.tbExtratoCOD_ENTREGADOR.AsString, mtWarning, [mbOK], 0); Self.Terminate; end; // Cancela fechameto dos abastecimentos if not(TUtil.Empty(dm.tbExtratoDAT_INICIO_ABASTECIMENTO.AsString)) then begin if not(abastecimento.Fechar(dm.tbExtratoDAT_INICIO_ABASTECIMENTO. AsString, dm.tbExtratoDAT_FINAL_ABASTECIMENTO.AsString, dm.tbExtratoCOD_ENTREGADOR.AsString, dm.tbExtratoNUM_EXTRATO.AsString, 'CANCELAR')) then begin MessageDlg('Erro Cancelamento Fechamento: ENTREGAS; Agente: ' + dm.tbExtratoCOD_AGENTE.AsString + ' / Entregador: ' + dm.tbExtratoCOD_ENTREGADOR.AsString, mtWarning, [mbOK], 0); Self.Terminate; end; end; // Retorna valores das restrições if dm.tbExtratoVAL_RESTRICAO.Value < 0 then begin if restricao.getObject(dm.tbExtratoCOD_ENTREGADOR.AsString, 'ENTREGADOR') then begin restricao.Valor := restricao.Valor + ABS(dm.tbExtratoVAL_RESTRICAO.Value); restricao.Pago := restricao.Pago + dm.tbExtratoVAL_RESTRICAO.Value; restricao.Debitar := ABS(dm.tbExtratoVAL_RESTRICAO.Value); if not(restricao.Update) then begin MessageDlg('Erro Cancelamento do Fechamento: RESTRIÇÃO; Agente: ' + dm.tbExtratoCOD_AGENTE.AsString + ' / Entregador: ' + dm.tbExtratoCOD_ENTREGADOR.AsString, mtWarning, [mbOK], 0); Self.Terminate; end; end else begin if restricao.getObject(dm.tbExtratoCOD_AGENTE.AsString, 'AGENTE') then begin restricao.Valor := restricao.Valor + ABS(dm.tbExtratoVAL_RESTRICAO.Value); restricao.Pago := restricao.Pago + dm.tbExtratoVAL_RESTRICAO.Value; restricao.Debitar := ABS(dm.tbExtratoVAL_RESTRICAO.Value); if not(restricao.Update) then begin MessageDlg('Erro Cancelamento Fechamento: RESTRIÇÃO; Agente: ' + dm.tbExtratoCOD_AGENTE.AsString + ' / Entregador: ' + dm.tbExtratoCOD_ENTREGADOR.AsString, mtWarning, [mbOK], 0); Self.Terminate; end; end; end; end; // Cancela fechamento de lançamentos de débitos e créditos if entregador.getObject(dm.tbExtratoCOD_ENTREGADOR.AsString, 'CODIGO') then begin iCodigo := entregador.Cadastro; end; if not(lancamento.Fechar(dm.tbExtratoDAT_INICIO.AsString, dm.tbExtratoDAT_TERMINO.AsString, dm.tbExtratoDAT_PAGO.AsString, dm.tbExtratoNUM_EXTRATO.AsString, IntToStr(iCodigo), 'CANCELAR')) then begin MessageDlg('Erro Cancelamento Fechamento: LANÇAMENTO; Agente: ' + dm.tbExtratoCOD_AGENTE.AsString + ' / Entregador: ' + dm.tbExtratoCOD_ENTREGADOR.AsString, mtWarning, [mbOK], 0); Self.Terminate; end; // Excluir planilha de crédito planilha.extrato := dm.tbExtratoNUM_EXTRATO.AsString; if not(planilha.Delete('EXTRATO')) then begin MessageDlg('Erro Cancelamento Fechamento: PLANILHA: Agente: ' + dm.tbExtratoCOD_AGENTE.AsString + ' / Entregador: ' + dm.tbExtratoCOD_ENTREGADOR.AsString, mtWarning, [mbOK], 0); Self.Terminate; end; // Excluir registro do extrato extrato.CodigoAgente := dm.tbExtratoCOD_AGENTE.Value; extrato.CodigoEntregador := dm.tbExtratoCOD_ENTREGADOR.Value; extrato.DataBase := dm.tbExtratoDAT_TERMINO.Value; if not(extrato.Delete('BASE1')) then begin MessageDlg('Erro Fechamento: EXTRATO; Agente: ' + dm.tbExtratoCOD_AGENTE.AsString + ' / Entregador: ' + dm.tbExtratoCOD_ENTREGADOR.AsString, mtWarning, [mbOK], 0); Self.Terminate; end; dPosicao := (Contador / LinhasTotal) * 100; Inc(Contador); if not(Self.Terminated) then begin Synchronize(AtualizaProgress); end else begin agente.Free; entregador.Free; entrega.Free; extrato.Free; lancamento.Free; restricao.Free; abastecimento.Free; planilha.Free; Abort; end; dm.tbExtrato.Next; end; finally Synchronize(TerminaProcesso); agente.Free; entregador.Free; entrega.Free; extrato.Free; lancamento.Free; restricao.Free; abastecimento.Free; planilha.Free; end; end; procedure thrCancelarFechamento.AtualizaProgress; begin frmExtrato.cxProgressBar.Visible := True; frmExtrato.cxProgressBar.Position := Round(dPosicao); frmExtrato.cxProgressBar.Properties.Text := IntToStr(Round(dPosicao)) + '%'; frmExtrato.cxProgressBar.Refresh; end; procedure thrCancelarFechamento.TerminaProcesso; begin frmExtrato.cxGrid1DBTableView1.OptionsView.NoDataToDisplayInfoText := '<Nenhuma Informação Disponível>'; frmExtrato.cxProgressBar.Visible := False; frmExtrato.cxProgressBar.Properties.Text := ''; frmExtrato.cxProgressBar.Position := 0; frmExtrato.cxProgressBar.Clear; frmExtrato.dsExtrato.Enabled := True; frmExtrato.actFechamentoExportarResumo.Enabled := False; frmExtrato.actFechamentoExportarEntregas.Enabled := False; frmExtrato.actExtratoCalcular.Enabled := True; frmExtrato.actFechamentoFechar.Enabled := False; frmExtrato.actFechamentoCancelarFechamento.Enabled := False; dm.tbExtrato.Close; frmExtrato.dsExtrato.Enabled := True; Application.MessageBox('Cancelamento concluído.', 'Cancelando Fechamento do Extrato', MB_OK + MB_ICONINFORMATION); end; procedure thrCancelarFechamento.IniciaProcesso; begin frmExtrato.dsExtrato.Enabled := False; frmExtrato.cxGrid1DBTableView1.OptionsView.NoDataToDisplayInfoText := '<Cancelando o Fechamento do Extrato. Aguarde...>'; frmExtrato.actFechamentoExportarResumo.Enabled := False; frmExtrato.actFechamentoExportarEntregas.Enabled := False; frmExtrato.actExtratoCalcular.Enabled := False; frmExtrato.actFechamentoFechar.Enabled := False; frmExtrato.actFechamentoCancelarFechamento.Enabled := False; frmExtrato.cxProgressBar.Clear; end; end.
Program Colors; uses crt; const cN=10; cM=10; type tInfo=Integer; pEdge = ^tEdge; tEdge = record Start: tInfo; //вершина Final: tInfo; //конец Next:pEdge; //переход к следующему ребру end; //в нулевом будем хранить текущее количество отмеченных вершин tTop=1..cN; tColor=0..cM; tPointer = array[tTop] of tColor; var input, output: text; firstEdge, lastEdge: pEdge; //указатели на начальное и конечное ребро данного графа N,M,k:Integer; bool:boolean; Pointer:tPointer; i: integer; function isEmpty(first: pEdge):boolean; //определение существования элементов в списке. begin isEmpty:= (first = nil); end; Procedure add (S,F{вершины ребра}:tInfo; var efirst,elast{первый и последний элементы списка, реализующего граф}:pEdge); //добавление элементов в список. var old: pEdge{временная переменная}; //стандартное добавление в конец списка. begin old:= elast; new(elast); elast^.Start:= S; elast^.Final:= F; elast^.next:= nil; if isEmpty(efirst) then efirst:= elast //пустой - первый элемент = последнему else old^.next:= elast; //иначе - добавляем в конец end; Procedure print(p:pEdge); //Печать списка. begin while p<>nil do //Перебор элементов списка. begin writeln(p^.Start,' ',p^.Final); //какое ребро, вершины p:=p^.next; end; writeln(); end; Procedure gettext(var fi,la:pEdge{первый и последний элементы списка(ребра)}); var Info1,Info2:tInfo; //вершины begin while not EOF(input) do //Считываем из файла текст. И сразу заполняем символьный список. begin readln(input,Info1,Info2); add(Info1,Info2,fi,la); //ребра,первый и последний элементы списка end; end; Procedure destroy(var fi:pEdge); //сборка мусора. var c:pEdge; begin while not isEmpty(fi)do //DISPOSE begin c:=fi; fi:=fi^.next; Dispose(c); end; end; function Right(ra:tPointer;Edge:pEdge;var p:integer):boolean; var b: boolean; begin b:=true; while (Edge<>nil) and b do begin if Edge^.Start=p then if ra[p]=ra[Edge^.Final] then b:=false; if Edge^.Final=p then if ra[p]= ra[Edge^.Start] then b:=false; Edge:=Edge^.Next; end; Right:=b; end; Procedure PrintPoint(ras:tPointer); begin for i:=1 to N do writeln('вершина: ', i,' раскрашена в цвет: ',ras[i]); end; Procedure Push(var ra:tPointer; var p:integer); begin inc(p); ra[p]:=1; end; Procedure Ret(var ra:tPointer; var exist:boolean;var p:integer); begin if ra[p]>=M then begin ra[p]:=0; dec(p); end else{<M} inc(ra[p]); if p<1 then exist:=false; end; Procedure Backtracking(firstEdge:pEdge; var found:boolean; var k:integer; var r: tPointer); var exists:boolean; p:integer; begin found:=false; exists:=true; {не закончились раскраски длины < N} r[1]:=1; p:=1; while exists do //? begin if Right(r,firstEdge,p) then if p=N{полная} then begin found:=true; PrintPoint(r); inc(k); r[p]:=0; dec(p); end else {начало добавления в новую вершину} Push(r,p) else {не правильная} Ret(r, exists,p) {=Следующая(r,exists)} end; end; begin clrscr; Assign(input, 'IN_GRAF.txt'); //Работа с файлами. Assign(output,'output.txt'); reset(input); rewrite(output); readln(input,N); //считываем количество вершин. readln(input,M); gettext(firstEdge,lastEdge); //считываем граф и заполняем список writeln(); writeln('Раскраска. Перебор с возвратом'); writeln(); writeln(' Граф содержит ',N,' вершин'); //печатаем, что прочитали до этого. print(firstEdge); writeln(); for i:=1 to N do Pointer[i]:=0; k:=0; Backtracking(firstEdge,bool,k,Pointer); //поиск правильных раскрасок if bool then writeln('количество раскрасок: ',k) else writeln('нет правильных раскрасок'); destroy(firstEdge); close(input); close(output); end.
(* @abstract(Contient une bibliothèque de classes mathématique optimisée pour les vecteurs utilisant l'accélération SIMD (SSE, SSE3, SS4, AVX, AVX2) @br Elles peuvent être utilisées dans les graphiques 2D / 3D et tout autre application nécessitant des calculs mathématique avec des vecteurs.) Types de vecteurs supportés :@br @unorderedlist( @item(Vecteur 2D Integer, Single et Double) @item(Vecteur 3D Byte, Integer, and Single) @item(Vecteur 4D Byte, Integer, Single) @item(Matrice 2D Single) @item(Matrice 4D Single Matrix (@TODO Integer ????)) @item(Quaternion) @item(Plan Homogène) ) Contient également des fonctions identique au script GLSL / HLSL ------------------------------------------------------------------------------------------------------------- @created(2017-11-25) @author(J.Delauney (BeanzMaster)) @author(Peter Dyson (Dicepd)) Historique : @br @unorderedList( @item(Last Update : 13/03/2018 ) @item(25/11/2017 : Creation ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes) : @br Remarquez, ici, nous devons redéfinir le mode d'arrondi FPC comme identique à notre code SSE. @br   Dans FPC, la 'fonction Round' utilise l'algorithme 'd'arrondissement bancaire'. @br   Il ne fait pas un "RoundUp" ou "RoundDown" si le paramètre d'entré est exactement x.50. Exemples : @br @code(Round(2.5) Resultat = 2) @br @code(Round(3.5) Resultat = 4) Pour plus d'informations voir : https://www.freepascal.org/docs-html/rtl/system/round.html @br @bold(Alignement des données sur la limite de 16 bits) : @br Sous x64, pour utiliser les fonctions vectorielle, vous aurez besoin d'ajouter des commandes de préprocesseur pour obtenir des données alignées appropriées. Normalement, ce n'est pas nécessaire sous x86. Mais c'est recommandé pour plus de sécurité. Dans l'en-tête des unité ajoutez : @br @longcode(# Unit MyUnit; {$mode objfpc}{$H+} {$ALIGN 16} {$CODEALIGN CONSTMIN=16} {$CODEALIGN LOCALMIN=16} {$CODEALIGN VARMIN=16} #) @OrderedList( @item(Pour les constantes : @br Vous devez d'entourer votre variable comme ceci : @br @longcode(# Const {$CODEALIGN CONSTMIN=16} cMyVector : TBZVector = (X:0.5;Y:0.5;Z:0.5;W:1.0); {$CODEALIGN CONSTMIN=4} #)) @item(Pour des Variables ou champs à l'intérieur d'une classe : @br Vous devez d'entourer votre variable comme ceci : @br @longcode(# Type TMyClass = Class private {$CODEALIGN RECORMIN=16} FVec : TBZVector; FMatrix : TBZMatrix; {$CODEALIGN RECORMIN=4} FFactor : Single; public property Vec : TBZVector read FVec write FVec end; #)) @item(Pour des variables dans des fonctions ou procédures : @br Vous devez d'entourer votre variable comme ceci : @longcode(# function MyFunc(A,B,C:Single):Single; var {$CODEALIGN VARMIN=16} MyTempVec : TBZVector {$CODEALIGN VARMIN=4} begin //... end; #)) ) ------------------------------------------------------------------------------------------------------------- Quelques liens de référence : @br @unorderedList( @item(http://forum.lazarus.freepascal.org/index.php/topic,32741.0.html) @item(http://agner.org/optimize/) @item(http://www.songho.ca/misc/sse/sse.html) @item(https://godbolt.org); @item(http://softpixel.com/~cwright/programming/simd/sse.php) @item(https://www.gamasutra.com/view/feature/132636/designing_fast_crossplatform_simd_.php?page=3) @item(https://butterflyofdream.wordpress.com/2016/07/05/converting-rotation-matrices-of-left-handed-coordinate-system/) @item(http://shybovycha.tumblr.com/post/122400740651/speeding-up-algorithms-with-sse) @item(https://www.scratchapixel.com/index.php) @item(http://mark.masmcode.com) @item(https://www.cs.uaf.edu/courses/cs441/notes/sse-avx/) @item(http://www.euclideanspace.com) @item(https://www.3dgep.com/category/math/) ) Quelques liens en français (in french) : @br @unorderedList( @item(http://villemin.gerard.free.fr/Wwwgvmm/Nombre.htm) @item(https://ljk.imag.fr/membres/Bernard.Ycart/mel/) @item(https://www.gladir.com/CODER/ASM8086/) ) Autres articles, papiers intéressant sur certains points :@br @unorderedList( @item(https://conkerjo.wordpress.com/2009/06/13/spatial-hashing-implementation-for-fast-2d-collisions/) @item(https://realhet.wordpress.com/2016/11/02/fast-sse-3x3-median-filter-for-rgb24-images/) @item(http://www.jagregory.com/abrash-black-book/) @item(http://x86asm.net/articles/fixed-point-arithmetic-and-tricks/) @item(http://lolengine.net/blog/2011/3/20/understanding-fast-float-integer-conversions) @item(http://chrishecker.com/Miscellaneous_Technical_Articles) @item(http://catlikecoding.com/unity/tutorials/rendering/part-1/) ) Vous trouverez d'autres article dans le dossier @bold(DocRefs) @br ------------------------------------------------------------------------------------------------------------- @bold(Dependances) : BZMath, BZArrayClasses ------------------------------------------------------------------------------------------------------------- @bold(Credits :)@br @unorderedList( @item(FPC/Lazarus) @item(GLScene) @item(Tous les auteurs des liens et articles) ) ------------------------------------------------------------------------------------------------------------- @bold(LICENCE) : MPL / GPL ------------------------------------------------------------------------------------------------------------- *) Unit BZVectorMath; //============================================================================== {$mode objfpc}{$H+} {$i ..\bzscene_options.inc} {.$INLINE ON} //----------------------- DATA ALIGNMENT --------------------------------------- {$ALIGN 16} {$CODEALIGN CONSTMIN=16} {$CODEALIGN LOCALMIN=16} {$CODEALIGN VARMIN=16} //------------------------------------------------------------------------------ {$MODESWITCH ADVANCEDRECORDS} //============================================================================== Interface Uses Classes, Sysutils, BZArrayClasses; //============================================================================== Const { Constante pour la normalisation d'un composant de couleur en byte vers un npmbre flottant } cColorFloatRatio : Single = 1/255; {%region%----[ SSE States Flags Const ]----------------------------------------} Type { Mode d'arrondissement du SIMD } sse_Rounding_Mode = (rmNearestSSE, rmFloorSSE, rmCeilSSE, rmDefaultSSE); Const { SIMD mxcsr register bits } {@exclude} sse_FlagInvalidOp = %0000000000000001; {@exclude} sse_FlagDenorm = %0000000000000010; {@exclude} sse_FlagDivZero = %0000000000000100; {@exclude} sse_FlagOverflow = %0000000000001000; {@exclude} sse_FlagUnderflow = %0000000000010000; {@exclude} sse_FlagPrecision = %0000000000100000; {@exclude} sse_FlagDenormZero= %0000000001000000; {@exclude} sse_MaskInvalidOp = %0000000010000000; {@exclude} sse_MaskDenorm = %0000000100000000; {@exclude} sse_MaskDivZero = %0000001000000000; {@exclude} sse_MaskOverflow = %0000010000000000; {@exclude} sse_MaskUnderflow = %0000100000000000; {@exclude} sse_MaskPrecision = %0001000000000000; {@exclude} sse_MaskNegRound = %0010000000000000; {@exclude} sse_MaskPosRound = %0100000000000000; {@exclude} sse_MaskZeroFlush = %1000000000000000; {@exclude} //masque pour enlever les anciens bits d'arrondi pour définir de nouveaux bits sse_no_round_bits_mask= $ffffffff-sse_MaskNegRound-sse_MaskPosRound; { Valeur par défaut du registre mxcsr après le démarrage du PC @ br     Paramétrage par défaut du registre mxscr; désactivation de toutes les exceptions } mxcsr_default : dword =sse_MaskInvalidOp or sse_MaskDenorm or sse_MaskDivZero or sse_MaskOverflow or sse_MaskUnderflow or sse_MaskPrecision or $00000000;// ; //sse_MaskPosRound; // {@exclude} mxcsr_default_TEST : dword =sse_MaskInvalidOp and sse_MaskDenorm or sse_MaskDivZero or sse_MaskOverflow or sse_MaskUnderflow or sse_MaskPrecision or $00000000 and sse_MaskZeroFlush; //sse_MaskPosRound; { Table de conversion du nom du mode d'arrondissement vers bits d'arrondi } sse_Rounding_Flags: array [sse_Rounding_Mode] of longint = (0,sse_MaskNegRound,sse_MaskPosRound,0); sse_align=16; //< Constant d'alignement des données SIMD en bits sse_align_mask=sse_align-1; //< Mask pour l'alignement des données {%endregion%} {%region%----[ Vectors ]-------------------------------------------------------} type { Tableau aligné pour les vecteur 2D Single } TBZVector2fType = packed array[0..1] of Single; { Tableau aligné pour les vecteur 2D Double } TBZVector2dType = packed array[0..1] of Double; { Tableau aligné pour les vecteur 2D Integer } TBZVector2iType = packed array[0..1] of Integer; { Tableau aligné pour les vecteur 3D Single } TBZVector3fType = packed array[0..2] of Single; { Tableau aligné pour les vecteur 3D Integer } TBZVector3iType = packed Array[0..2] of Longint; { Tableau aligné pour les vecteur 3D Byte } TBZVector3bType = packed Array[0..2] of Byte; { Tableau aligné pour les vecteur 4D Single } TBZVector4fType = packed array[0..3] of Single; { Tableau aligné pour les vecteur 4D Integer } TBZVector4iType = packed array[0..3] of Longint; { Tableau aligné pour les vecteur 4D Byte } TBZVector4bType = packed Array[0..3] of Byte; { Référence pour le mélange des composants d'un vecteur (swizzle/shuffle) 2D } TBZVector2SwizzleRef = (swDefaultSwizzle2, swXX, swYY, swXY, swYX); { Référence pour le mélange des composants d'un vecteur (swizzle/shuffle) 3D } TBZVector3SwizzleRef = (swDefaultSwizzle3, swXXX, swYYY, swZZZ, swXYZ, swXZY, swZYX, swZXY, swYXZ, swYZX, swRRR, swGGG, swBBB, swRGB, swRBG, swBGR, swBRG, swGRB, swGBR); { Référence pour le mélange des composants d'un vecteur (swizzle/shuffle) 4D } TBZVector4SwizzleRef = (swDefaultSwizzle4, swXXXX, swYYYY, swZZZZ, swWWWW, swXYZW, swXZYW, swZYXW, swZXYW, swYXZW, swYZXW, swWXYZ, swWXZY, swWZYX, swWZXY, swWYXZ, swWYZX, swRRRR, swGGGG, swBBBB, swAAAA, swRGBA, swRBGA, swBGRA, swBRGA, swGRBA, swGBRA, swARGB, swARBG, swABGR, swABRG, swAGRB, swAGBR); { Définition d'un Vecteur 2D de type Integer } TBZVector2i = record { Initialisation des valeurs X et Y } procedure Create(aX, aY:Integer); overload; { Retourne une chaine de caractères formaté représentant le vecteur : '(x, y)' } function ToString : String; { Ajoute deux vecteurs TBZVector2i} class operator +(Constref A, B: TBZVector2i): TBZVector2i;overload; { Soustrait deux vecteurs TBZVector2i} class operator -(constref A, B: TBZVector2i): TBZVector2i; overload; { Multiplie deux vecteurs TBZVector2i} class operator *(constref A, B: TBZVector2i): TBZVector2i; overload; { Divise deux vecteurs TBZVector2i} class operator Div(constref A, B: TBZVector2i): TBZVector2i; overload; { Divise un vecteurs TBZVector2i avec une variable de type Integer} class operator Div(constref A: TBZVector2i; Constref B:Integer): TBZVector2i; overload; { Ajoute un vecteurs TBZVector2i avec une variable de type Integer} class operator +(Constref A: TBZVector2i; constref B:Integer): TBZVector2i;overload; { Ajoute une variable de type Single a un vecteurs TBZVector2i} class operator +(Constref A: TBZVector2i; constref B:Single): TBZVector2i; overload; { Soustrait une variable de type Integer a un vecteurs TBZVector2i} class operator -(constref A: TBZVector2i; constref B:Integer): TBZVector2i; overload; { Soustrait une variable de type Single a un vecteurs TBZVector2i } class operator -(constref A: TBZVector2i; constref B:Single): TBZVector2i; overload; { Multiplie un vecteur TBZVector2i avec une variable de type Integer } //class operator *(constref A: TBZVector2i; constref B:Integer): TBZVector2i; overload; { Multiplie un vecteurs TBZVector2i avec une variable de type Single} class operator *(constref A: TBZVector2i; constref B:Single): TBZVector2i; overload; { Divise un vecteurs TBZVector2i avec une variable de type Single } class operator /(constref A: TBZVector2i; constref B:Single): TBZVector2i; overload; { Inverse le signe des composantes du vecteur } class operator -(constref A: TBZVector2i): TBZVector2i; overload; { Compare si deux variables de type TBZVector2i sont égales. Retourne @True si la condition est vérifiée. Chaque composant du vecteur est vérifié} class operator =(constref A, B: TBZVector2i): Boolean; overload; { Compare si deux variables de type TBZVector2i ne sont pas égales. Retourne @True si la condition est vérifiée. Chaque composant du vecteur est vérifié} class operator <>(constref A, B: TBZVector2i): Boolean; overload; { Retourne le reste de chaque composante de la division de deux vecteur } class operator mod(constref A, B : TBZVector2i): TBZVector2i; overload; { Retourne le minimum de chaque composants entre le vecteur courrant et un autre TBZVector2i } function Min(constref B: TBZVector2i): TBZVector2i; overload; { Retourne le minimum de chaque composants entre vecteur courrant et une valeur de type Integer } function Min(constref B: Integer): TBZVector2i; overload; { Retourne le maximum de chaque composants entre vecteur courrant et une valeur de type TBZVector2i } function Max(constref B: TBZVector2i): TBZVector2i; overload; { Retourne le maximum de chaque composants entre le vecteur courrant et une valeur de type Integer } function Max(constref B: Integer): TBZVector2i; overload; { S'assure que chaque composant du vecteur courrant soit compris en les valeur définit par les valeurs de type TBZVector2i "AMin" et "AMax" } function Clamp(constref AMin, AMax: TBZVector2i): TBZVector2i;overload; { S'assure que chaque composant du vecteur courrant soit compris en les valeur de type Integer "AMin" et "AMax" } function Clamp(constref AMin, AMax: Integer): TBZVector2i;overload; { Multiplie le vecteur courrant par un autre TBZVector2i et ajoute un deuxieme TBZVector2i au résultat } function MulAdd(constref A,B:TBZVector2i): TBZVector2i; { Multiplie le vecteur courrant par un autre TBZVector2i et divise le resultat par un deuxieme TBZVector2i } function MulDiv(constref A,B:TBZVector2i): TBZVector2i; { Retourne la longueur du vecteur } function Length:Single; { Retourne la longueur carré du vecteur } function LengthSquare:Single; { Retourne la distance entre le vecteur courrant et un autre TBZVector2i } function Distance(constref A:TBZVector2i):Single; { Retourne la distance carré entre le vecteur courrant et un autre TBZVector2i } function DistanceSquare(constref A:TBZVector2i):Single; { Retourne le produit scalaire du vecteur courrent avec un autre TBZVector2i } function DotProduct(A:TBZVector2i):Single; { Retourne l'angle en "Degré" entre le vecteur courrant et un autre TBZVector2i relatif a un autre TBZVector2i décrivant le centre de rotation } function AngleBetween(Constref A, ACenterPoint : TBZVector2i): Single; { Retourne le cosinus de l'angle entre le vecteur courrant et un autre TBZVector2i } function AngleCosine(constref A: TBZVector2i): Single; { Retourne la valeur absolue de chaque composant du vecteur courrant } function Abs:TBZVector2i;overload; { Accès aux valeurs du vecteur } case Byte of 0: (V: TBZVector2iType); //< Acces via tableau 1: (X, Y : Integer); //< Acces par défaut 2: (Width, Height : Integer); //< Propriétés de convenance pour la manipulation de taille end; { Pointeur vers un TBZVector2i } PBZVector2i = ^TBZVector2i; { Définition d'un vecteur 2D de type Single } { TBZVector2f } TBZVector2f = record { Initialisation des valeurs X et Y } procedure Create(aX,aY: single); { Retourne une chaine de caractères formaté représentant le vecteur : '(x, y)' } function ToString : String; { Ajoute deux vecteurs de type TBZVector2f } class operator +(constref A, B: TBZVector2f): TBZVector2f; overload; { Ajoute un vecteur de type TBZVector2f à un vecteur de type TBZVector2i } class operator +(constref A: TBZVector2f; constref B: TBZVector2i): TBZVector2f; overload; { Soustrait deux vecteurs de type TBZVector2f } class operator -(constref A, B: TBZVector2f): TBZVector2f; overload; { Soustrait un vecteur de type TBZVector2f à un vecteur de type TBZVector2i } class operator -(constref A: TBZVector2f; constref B: TBZVector2i): TBZVector2f; overload; { Multiplie deux vecteurs de type TBZVector2f } class operator *(constref A, B: TBZVector2f): TBZVector2f; overload; { Multiplie un vecteur de type TBZVector2f avec un vecteur de type TBZVector2i } class operator *(constref A:TBZVector2f; Constref B: TBZVector2i): TBZVector2f; overload; { Divise deux vecteurs de type TBZVector2f } class operator /(constref A, B: TBZVector2f): TBZVector2f; overload; { Ajoute chaque composant du vecteur de type TBZVector2f avec une valeur de type Single } class operator +(constref A: TBZVector2f; constref B:Single): TBZVector2f; overload; { Soustrait chaque composant du vecteur de type TBZVector2f avec une valeur de type Single } class operator -(constref A: TBZVector2f; constref B:Single): TBZVector2f; overload; { Multiplie chaque composant du vecteur de type TBZVector2f par une valeur de type Single } class operator *(constref A: TBZVector2f; constref B:Single): TBZVector2f; overload; { Divise chaque composant du vecteur de type TBZVector2f une valeur de type Single } class operator /(constref A: TBZVector2f; constref B:Single): TBZVector2f; overload; { Divise un vecteur de type TBZVector2f avec un vecteur de type TBZVector2i } class operator /(constref A: TBZVector2f; constref B: TBZVector2i): TBZVector2f; overload; { Inverse le signe des composants du vecteur } class operator -(constref A: TBZVector2f): TBZVector2f; overload; { Compare si deux variables de type TBZVector2f sont égales. Retourne @True si la condition est vérifiée. Chaque composant du vecteur est vérifié} class operator =(constref A, B: TBZVector2f): Boolean; { Compare si deux variables de type TBZVector2f ne sont pas égales. Retourne @True si la condition est vérifiée. Chaque composant du vecteur est vérifié} class operator <>(constref A, B: TBZVector2f): Boolean; //class operator mod(const a,b:TBZVector2f): TBZVector2f; { Retourne le minimum de chaque composant entre le vecteur courrant et un autre TBZVector2f } function Min(constref B: TBZVector2f): TBZVector2f; overload; { Retourne le minimum de chaque composant entre vecteur courrant et un valeur de type Single } function Min(constref B: Single): TBZVector2f; overload; { Retourne le maximum de chaque composant entre le vecteur courrant et un autre TBZVector2f } function Max(constref B: TBZVector2f): TBZVector2f; overload; { Retourne le maximum de chaque composant entre vecteur courrant et un valeur de type Single } function Max(constref B: Single): TBZVector2f; overload; { S'assure que chaque composant du vecteur courrant soit compris en les valeur définit par les valeurs de type TBZVector2f "AMin" et "AMax" } function Clamp(constref AMin, AMax: TBZVector2f): TBZVector2f;overload; { S'assure que chaque composant du vecteur courrant soit compris en les valeur de type Single "AMin" et "AMax" } function Clamp(constref AMin, AMax: Single): TBZVector2f;overload; { Multiplie le vecteur courrant par un autre TBZVector2f et ajoute un deuxieme TBZVector2f au résultat } function MulAdd(constref A,B:TBZVector2f): TBZVector2f; { Multiplie le vecteur courrant par un autre TBZVector2f et soustrait un deuxieme TBZVector2f au résultat } function MulSub(constref A,B:TBZVector2f): TBZVector2f; { Multiplie le vecteur courrant par un autre TBZVector2f et divise le résultat par un deuxieme TBZVector2f } function MulDiv(constref A,B:TBZVector2f): TBZVector2f; { Retourne la longueur du vecteur } function Length:Single; { Retourne la longueur carré du vecteur } function LengthSquare:Single; { Retourne la distance (Cartésienne) entre le vecteur courrant et un autre TBZVector2f } function Distance(constref A:TBZVector2f):Single; { Retourne la distance (Cartésienne) carré entre le vecteur courrant et un autre TBZVector2f } function DistanceSquare(constref A:TBZVector2f):Single; { Retourne la distance de Manhattan. @br @bold(Note) : La distance de Manahattan est la distance de "marche" entre deux points. @br Aucun déplacement angulaire n'est autorisé. (applicable uniquement pour des mouvements horizontaux et verticaux)} function ManhattanDistance(constref A : TBZVector2f) : Single; { Retourne la distance de Chebyshev. Similaire à ManhattanDistance. @br Sauf que le mouvement diagonal est autorisé. @br @bold(Note) : Cette fonction est aussi appelée "distance de l'échiquier" car elle correspond au nombre de mouvements qu'une pièce du roi doit effectuer pour se déplacer entre deux points.} function ChebyshevDistance(constref A : TBZVector2f) : Single; function MinkovskiDistance(constref A : TBZVector2f): Single; { Retourne le barycentre pondéré. @br cf : https://fr.wikibooks.org/wiki/Manuel_de_géométrie_vectorielle/Coordonnées_du_barycentre } function BaryCenter(constRef B : TBZVector2f; const WeightA : Single = 1.0; Const WeightB : Single = 1.0) : TBZVector2f; function Center(ConstRef B : TBZVector2f) : TBZVector2f; { Retourne le vecteur courrant normalisé } function Normalize : TBZVector2f; //---------------------------------------------------------------------------------------------------------------- // NOTE : Le produit en croix d'un vecteur 2D n'existe pas. // Nous substituons cette opération en deux fonctions afin de pouvoir simuler le produit en croix d'un vecteur 3D { Retourne la composante Z (Magnitude) d'un produit en croix d'un vecteur 3D. Nous supposons ici que la valeur "Z" est egale à 0 } function Perp(A : TBZVector2f) : Single; { Retourne le produit en croix du vecteur Equivalent au produit en croix d'un vecteur 3D. (Pour simuler le calcul et obtenir un résultat, on "suppose" que la valeur "Z" est égale à 1) Pour obtenir la valeur de "Z" (magnitude) du produit en croix d'un vecteur 3D il faut utiliser la fonction Perp } function CrossProduct(A : TBZVector2f): TBZVector2f; //---------------------------------------------------------------------------------------------------------------- { Retourne le produit scalaire du vecteur courrant avec un autre TBZVector2f } function DotProduct(A:TBZVector2f):Single; { Retourne l'angle en "Degré" entre le vecteur courrant et un autre TBZVector2f relatif a un autre TBZVector2f décrivant le centre de rotation } function AngleBetween(Constref A, ACenterPoint : TBZVector2f): Single; { Retourne l'angle en "Degré" entre le vecteur courrant et un autre TBZVector2f. Note le centre de rotation se trouve à la position (0,0) } function AngleBetweenPointsInDeg(C : TBZVector2f):Single; { Retourne le cosinus de l'angle entre le vecteur courrant et un autre TBZVector2f } function AngleCosine(constref A: TBZVector2f): Single; { Retourne le point après rotation du vecteur de "anAngle" en degré par rapport au centre de rotation "aCenterPoint } function Rotate(anAngle : Single; aCenterPoint : TBZVector2f) : TBZVector2f; // function Reflect(I, NRef : TVector2f):TVector2f // function Edge(ConstRef A, B : TBZVector2f):Single; // @TODO : a passer dans TBZVector2fHelper ??? { Retourne la valeur absolue de chaque composant du vecteur courrant } function Abs:TBZvector2f;overload; { Retourne la valeur arrondit de chaque composant du vecteur courrant dans un vecteur de type TBZVector2i } function Round: TBZVector2i; overload; { Retourne la valeur tronqué de chaque composant du vecteur courrant dans un vecteur de type TBZVector2i } function Trunc: TBZVector2i; overload; { Retourne la valeur arrondit tendant vers le négatif de chaque composant du vecteur courrant dans un vecteur de type TBZVector2i } function Floor: TBZVector2i; overload; { Retourne la valeur arrondit tendant vers le positif de chaque composant du vecteur courrant dans un vecteur de type TBZVector2i } function Ceil : TBZVector2i; overload; { Retourne la partie fractionnaire de chaque composant du vecteur courrant } function Fract : TBZVector2f; overload; { Retourne le dividende de chaque composant du vecteur courrant avec comme diviseur un autre vecteur de type TBZVector2f } function Modf(constref A : TBZVector2f): TBZVector2f; { Retourne le dividende de chaque composant du vecteur courrant avec comme diviseur un autre vecteur de type TBZVector2i ( TODO : Overload modf ou fmod ???) } function fMod(Constref A : TBZVector2f): TBZVector2i; { Retourne la racine carré de chaque composant du vecteur courrant } function Sqrt : TBZVector2f; overload; { Retourne la racine carré inverse de chaque composant du vecteur courrant } function InvSqrt : TBZVector2f; overload; { Accès aux valeurs du vecteur } case Byte of 0: (V: TBZVector2fType); //< Acces via tableau 1: (X, Y : Single); //< Acces par défaut 2: (Width, Height : Single); //< Propriétés de convenance pour la manipulation de taille End; { Définition de convenance pour la représentation d'un point 2D en virgule flottante } TBZFloatPoint = TBZVector2f; { Définition d'un vecteur 2D de type Double } TBZVector2d = record { Initialisation des valeurs X et Y } procedure Create(aX,aY: Double); { Retourne une chaine de caractères formaté représentant le vecteur : '(x, y)' } function ToString : String; { Ajoute deux vecteurs de type TBZVector2d } class operator +(constref A, B: TBZVector2d): TBZVector2d; overload; { Ajoute un vecteur de type TBZVector2d à un vecteur de type TBZVector2i } class operator +(constref A: TBZVector2d; constref B: TBZVector2i): TBZVector2d; overload; { Soustrait deux vecteurs de type TBZVector2f } class operator -(constref A, B: TBZVector2d): TBZVector2d; overload; { Soustrait un vecteur de type TBZVector2d à un vecteur de type TBZVector2i } class operator -(constref A: TBZVector2d; constref B: TBZVector2i): TBZVector2d; overload; { Multiplie deux vecteurs de type TBZVector2d } class operator *(constref A, B: TBZVector2d): TBZVector2d; overload; { Multiplie un vecteur de type TBZVector2d avec un vecteur de type TBZVector2i } class operator *(constref A:TBZVector2d; Constref B: TBZVector2i): TBZVector2d; overload; { Divise deux vecteurs de type TBZVector2d } class operator /(constref A, B: TBZVector2d): TBZVector2d; overload; { Ajoute chaque composant du vecteur de type TBZVector2d avec une valeur de type Double } class operator +(constref A: TBZVector2d; constref B:Double): TBZVector2d; overload; { Soustrait chaque composant du vecteur de type TBZVector2d avec une valeur de type Double } class operator -(constref A: TBZVector2d; constref B:Double): TBZVector2d; overload; { Multiplie chaque composant du vecteur de type TBZVector2d par une valeur de type Double } class operator *(constref A: TBZVector2d; constref B:Double): TBZVector2d; overload; { Divise chaque composant du vecteur de type TBZVector2d par une valeur de type Double } class operator /(constref A: TBZVector2d; constref B:Double): TBZVector2d; overload; { Divise un vecteur de type TBZVector2d avec un vecteur de type TBZVector2i } class operator /(constref A: TBZVector2d; constref B: TBZVector2i): TBZVector2d; overload; { Inverse le signe des composants du vecteur } class operator -(constref A: TBZVector2d): TBZVector2d; overload; { Compare si deux variables de type TBZVector2d sont égales. Retourne @True si la condition est vérifiée. @br Chaque composant du vecteur est vérifié } class operator =(constref A, B: TBZVector2d): Boolean; { Compare si deux variables de type TBZVector2d ne sont pas égales. Retourne @True si la condition est vérifiée. @br Chaque composant du vecteur est vérifié } class operator <>(constref A, B: TBZVector2d): Boolean; //class operator mod(const a,b:TBZVector2d): TBZVector2d; { Retourne le minimum de chaque composant entre le vecteur courrant et un autre TBZVector2d } function Min(constref B: TBZVector2d): TBZVector2d; overload; { Retourne le minimum de chaque composant entre vecteur courrant et un valeur de type Double } function Min(constref B: Double): TBZVector2d; overload; { Retourne le maximum de chaque composant entre le vecteur courrant et un autre TBZVector2d } function Max(constref B: TBZVector2d): TBZVector2d; overload; { Retourne le maximum de chaque composant entre vecteur courrant et un valeur de type Double } function Max(constref B: Double): TBZVector2d; overload; { S'assure que chaque composant du vecteur courrant soit compris en les valeur définit par les valeurs de type TBZVector2d "AMin" et "AMax" } function Clamp(constref AMin, AMax: TBZVector2d): TBZVector2d;overload; { S'assure que chaque composant du vecteur courrant soit compris en les valeur de type Double "AMin" et "AMax" } function Clamp(constref AMin, AMax: Double): TBZVector2d;overload; { Multiplie le vecteur courrant par un autre TBZVector2d et ajoute un deuxieme TBZVector2d au résultat } function MulAdd(constref A,B:TBZVector2d): TBZVector2d; { Multiplie le vecteur courrant par un autre TBZVector2d et soustrait un deuxieme TBZVector2d au résultat } function MulSub(constref A,B:TBZVector2d): TBZVector2d; { Multiplie le vecteur courrant par un autre TBZVector2d et divise le résultat par un deuxieme TBZVector2d } function MulDiv(constref A,B:TBZVector2d): TBZVector2d; { Retourne la longueur du vecteur } function Length:Double; { Retourne la longueur carré du vecteur } function LengthSquare:Double; { Retourne la distance entre le vecteur courrant et un autre TBZVector2d } function Distance(constref A:TBZVector2d):Double; { Retourne la distance carré entre le vecteur courrant et un autre TBZVector2d } function DistanceSquare(constref A:TBZVector2d):Double; { Retourne le vecteur courrant normalisé } function Normalize : TBZVector2d; { Retourne le produit scalaire du vecteur courrant avec un autre TBZVector2d } function DotProduct(A:TBZVector2d):Double; { Retourne l'angle en "Degré" entre le vecteur courrant et un autre TBZVector2d relatif a un autre TBZVector2d décrivant le centre de rotation } function AngleBetween(Constref A, ACenterPoint : TBZVector2d): Double; { Retourne l'angle en "Degré" entre le vecteur courrant et un autre TBZVector2f. Note le centre de rotation se trouve à la position (0,0) } //function AngleBetweenPointsInDeg(C : TBZVector2f):Single; { Retourne le cosinus de l'angle entre le vecteur courrant et un autre TBZVector2d } function AngleCosine(constref A: TBZVector2d): Double; // function Reflect(I, NRef : TVector2f):TVector2f // function Edge(ConstRef A, B : TBZVector2d):Single; // @TODO : a passer dans TBZVector2dHelper ??? { Retourne la valeur absolue de chaque composant du vecteur courrant } function Abs:TBZVector2d;overload; { Retourne la valeur arrondie de chaque composant du vecteur courrant dans un vecteur de type TBZVector2i } function Round: TBZVector2i; overload; { Retourne la valeur tronquée de chaque composant du vecteur courrant dans un vecteur de type TBZVector2i } function Trunc: TBZVector2i; overload; { Retourne la valeur arrondie tendant vers le négatif de chaque composant du vecteur courrant dans un vecteur de type TBZVector2i } function Floor: TBZVector2i; overload; { Retourne la valeur arrondie tendant vers le positif de chaque composant du vecteur courrant dans un vecteur de type TBZVector2i } function Ceil : TBZVector2i; overload; { Retourne la partie fractionnaire de chaque composant du vecteur courrant } function Fract : TBZVector2d; overload; { Retourne le dividende de chque composant du vecteur courrant avec comme diviseur un autre vecteur de type TBZVector2d } function Modf(constref A : TBZVector2d): TBZVector2d; { Retourne le dividende de chque composant du vecteur courrant avec comme diviseur un autre vecteur de type TBZVector2i ( TODO : Overload modf ou fmod ???) } function fMod(Constref A : TBZVector2d): TBZVector2i; { Retourne la racine carré de chaque composant du vecteur courrant } function Sqrt : TBZVector2d; overload; { Retourne la racine carré inverse de chaque composant du vecteur courrant } function InvSqrt : TBZVector2d; overload; { Accès aux valeurs du vecteur } case Byte of 0: (V: TBZVector2dType); //< Acces via tableau 1: (X, Y : Double); //< Acces par défaut 2: (Width, Height : Double); //< Propriétés de convenance pour la manipulation de taille End; { Représentation d'un nombre complex } { TBZComplexVector } TBZComplexVector = record { Creation d'un nombre complex } procedure Create(ARealPart, AnImaginaryPart : Double); { Creation d'un nombre complex depuis un TBZVector2d ou X est la partie Reelle et Y la partie Imaginaire } procedure Create(AValue : TBZVector2d); { Retourne une chaine de caractères formaté représentant le vecteur : '(RealPart, ImaginaryPart)' } function ToString : String; { Ajoute deux nombre complex } class operator +(constref A, B: TBZComplexVector): TBZComplexVector; overload; { Soustrait deux nombre complex } class operator -(constref A, B: TBZComplexVector): TBZComplexVector; overload; { Multiplie deux nombre complex } class operator *(constref A, B: TBZComplexVector): TBZComplexVector; overload; { Multiplie le nombre complex avec une valeur de type Single (Mise à l'echelle/Scale)} class operator *(constref A : TBZComplexVector; constref B : Single): TBZComplexVector; overload; { Divise deux nombre complex } class operator /(constref A, B: TBZComplexVector): TBZComplexVector; overload; { Compare si deux nombre complex sont égales. Retourne @True si la condition est vérifiée. @br Chaque composant du vecteur est vérifié } class operator =(constref A, B: TBZComplexVector): Boolean; { Compare si deux nombre complex ne sont pas égales. Retourne @True si la condition est vérifiée. @br Chaque composant du vecteur est vérifié } class operator <>(constref A, B: TBZComplexVector): Boolean; { Negation de la partie Reel } function Conjugate : TBZComplexVector; { Retourne la longueur (magnitude) du nombre complex } function Length : Double; { Retourne la phase du nombre complex (Z) (en radian, dans l'interval [-pi, pi]) } function Phase : Double; { Retourne le cosinus du nombre complexe } function Cosinus : TBZComplexVector; { Retourne le sinus du nombre complexe } function Sinus : TBZComplexVector; { Retourne le polynome de "Degree" du nombre complexe } function Polynome(Degree : Integer) : TBZComplexVector; Case Byte of 0: (V: TBZVector2dType); //< Acces via tableau 1: (RealPart, ImaginaryPart : Double); //< Acces par défaut 2: (AsVector2D : TBZVector2D); //< Comme une TBZVector2D end; { Définition d'un vecteur 3D de type Byte. } TBZVector3b = Record public { Initialisation des valeurs X, Y et Z} procedure Create(const aX, aY, aZ: Byte); { Retourne une chaine de caractères formaté représentant le vecteur : '(x, y, z)' } function ToString : String; { Ajoute deux vecteurs de type TBZVector3b } class operator +(constref A, B: TBZVector3b): TBZVector3b; overload; { Soustrait deux vecteurs de type TBZVector3b } class operator -(constref A, B: TBZVector3b): TBZVector3b; overload; { Multiplie deux vecteurs de type TBZVector3b } class operator *(constref A, B: TBZVector3b): TBZVector3b; overload; { Divise deux vecteurs de type TBZVector3b } class operator Div(constref A, B: TBZVector3b): TBZVector3b; overload; { Ajoute chaque composant du vecteur de type TBZVector2d avec une valeur de type Byte } class operator +(constref A: TBZVector3b; constref B:Byte): TBZVector3b; overload; { Soustrait chaque composant du vecteur de type TBZVector2d avec une valeur de type Byte } class operator -(constref A: TBZVector3b; constref B:Byte): TBZVector3b; overload; { Multiplie chaque composant du vecteur de type TBZVector2d avec une valeur de type Byte } class operator *(constref A: TBZVector3b; constref B:Byte): TBZVector3b; overload; { Multiplie chaque composant du vecteur de type TBZVector2d avec une valeur de type Single } class operator *(constref A: TBZVector3b; constref B:Single): TBZVector3b; overload; { Divise chaque composant du vecteur de type TBZVector2d avec une valeur de type Byte } class operator Div(constref A: TBZVector3b; constref B:Byte): TBZVector3b; overload; { Compare si deux variables de type TBZVector3b sont égales. Retourne @True si la condition est vérifiée. @br Chaque composant du vecteur est vérifié } class operator =(constref A, B: TBZVector3b): Boolean; { Compare si deux variables de type TBZVector3b ne sont pas égales. Retourne @True si la condition est vérifiée. @br Chaque composant du vecteur est vérifié } class operator <>(constref A, B: TBZVector3b): Boolean; { Opérateur logique ET (AND) entre deux TBZVector3b } class operator And(constref A, B: TBZVector3b): TBZVector3b; overload; { Opérateur logique OU (OR) entre deux TBZVector3b } class operator Or(constref A, B: TBZVector3b): TBZVector3b; overload; { Opérateur logique OU EXCLUSIF (XOR) entre deux TBZVector3b } class operator Xor(constref A, B: TBZVector3b): TBZVector3b; overload; { Opérateur logique ET (AND) entre un TBZVector3b et une valeur de type Byte } class operator And(constref A: TBZVector3b; constref B:Byte): TBZVector3b; overload; { Opérateur logique OR (OR) entre un TBZVector3b et une valeur de type Byte } class operator or(constref A: TBZVector3b; constref B:Byte): TBZVector3b; overload; { Opérateur logique OU EXCLUSIF (XOR) entre un TBZVector3b et une valeur de type Byte } class operator Xor(constref A: TBZVector3b; constref B:Byte): TBZVector3b; overload; { Mélange les composants (swizzle)en fonction du paramètre de type TBZVector3SwizzleRef } function Swizzle(Const ASwizzle : TBZVector3SwizzleRef): TBZVector3b; { Acces aux propriétés } Case Byte of 0 : (V:TBZVector3bType); //< Acces via un tableau 1 : (X, Y, Z:Byte); //< Acces par défaut 2 : (Red, Green, Blue:Byte); //< Acces comme une couleur au format RGB end; { Définition de convenace d'un vecteur 3D de type Integer non étendu. Juste pour les accès aux valeurs. Pour les manipulations, en lieu et place utilisez plutôt un vecteur de type TBZVector4i } TBZVector3i = record { Acces aux propriétés } case Byte of 0: (V: TBZVector3iType); //< Acces via tableau 1: (X, Y, Z : Integer); //< Acces par défaut 2: (Red, Green, Blue : Integer); //< Acces comme une couleur au format RGB end; { Définition de convenace d'un vecteur 3D de type Single non étendu. Juste pour les accès aux valeurs. Pour les manipulations, en lieu et place utilisez plutôt un vecteur de type TBZVector4f } TBZVector3f = record public { Retourne une chaine de caractères formaté représentant le vecteur : '(x, y, z)' } function ToString : String; { Acces aux propriétés } case Byte of 0: (V: TBZVector3fType); //< Acces via tableau 1: (X, Y, Z: Single); //< Acces par défaut 2: (Red, Green, Blue: Single); //< Acces comme une couleur au format RGB End; { Définition de convenance pratique pour décrire un vecteur affine de type TBZVector3f } TBZAffineVector = TBZVector3f; PBZAffineVector = ^TBZAffineVector; //< Pointeur vers TBZAffineVector { Définition d'un vecteur 4D de type Byte. } TBZVector4b = Record public { Initialisation des valeurs X, Y, Z et W @br Par défaut la valeur W est mise à 255 } procedure Create(Const aX,aY,aZ: Byte; const aW : Byte = 255); overload; { Creation depuis un TBZVector3b et W @br Par défaut la valeur W est mise à 255 } procedure Create(Const aValue : TBZVector3b; const aW : Byte = 255); overload; { Retourne une chaine de caractères formaté représentant le vecteur : '(x, y, z, w)' } function ToString : String; { Ajoute deux TBZVector4b } class operator +(constref A, B: TBZVector4b): TBZVector4b; overload; { Soustrait deux TBZVector4b } class operator -(constref A, B: TBZVector4b): TBZVector4b; overload; { Multiplie deux TBZVector4b } class operator *(constref A, B: TBZVector4b): TBZVector4b; overload; { Divise deux TBZVector4b } class operator Div(constref A, B: TBZVector4b): TBZVector4b; overload; { Ajoute à chaque composant une variable de type Byte } class operator +(constref A: TBZVector4b; constref B:Byte): TBZVector4b; overload; { Soustrait à chaque composant une variable de type Byte } class operator -(constref A: TBZVector4b; constref B:Byte): TBZVector4b; overload; { Multiplie chaque composant par variable de type Byte } class operator *(constref A: TBZVector4b; constref B:Byte): TBZVector4b; overload; { Multiplie chaque composant par variable de type Single. Les valeurs sont arrondis et leur interval vérifié } class operator *(constref A: TBZVector4b; constref B:Single): TBZVector4b; overload; { Divise chaque composant par variable de type Byte } class operator Div(constref A: TBZVector4b; constref B:Byte): TBZVector4b; overload; { Retourne @True si le vecteur A est égale au vecteur B } class operator =(constref A, B: TBZVector4b): Boolean; { Retourne @True si le vecteur A n'est pas égale au vecteur B } class operator <>(constref A, B: TBZVector4b): Boolean; { Opérateur logique ET (AND) entre deux TBZVector4b } class operator And(constref A, B: TBZVector4b): TBZVector4b; overload; { Opérateur logique OU (OR) entre deux TBZVector4b } class operator Or(constref A, B: TBZVector4b): TBZVector4b; overload; { Opérateur logique OU EXCLUSIF (XOR) entre deux TBZVector4b } class operator Xor(constref A, B: TBZVector4b): TBZVector4b; overload; { Opérateur logique ET (AND) entre un TBZVector4b et une variable de type Byte } class operator And(constref A: TBZVector4b; constref B:Byte): TBZVector4b; overload; { Opérateur logique OU (OR) entre un TBZVector4b et une variable de type Byte } class operator or(constref A: TBZVector4b; constref B:Byte): TBZVector4b; overload; { Opérateur logique OU EXCLUSIF (XOR) entre un TBZVector4b et une variable de type Byte } class operator Xor(constref A: TBZVector4b; constref B:Byte): TBZVector4b; overload; { Division rapide par 2} function DivideBy2 : TBZVector4b; { Retourne le minimum de chaque composant entre le vecteur courrant et un autre TBZVector4b } function Min(Constref B : TBZVector4b):TBZVector4b; overload; { Retourne le minimum de chaque composant entre le vecteur courrant et un valeur de type Byte } function Min(Constref B : Byte):TBZVector4b; overload; { Retourne le maximum de chaque composant entre le vecteur courrant et un autre TBZVector4b } function Max(Constref B : TBZVector4b):TBZVector4b; overload; { Retourne le maximum de chaque composant entre le vecteur courrant et un valeur de type Byte } function Max(Constref B : Byte):TBZVector4b; overload; { S'assure que chaque composant du vecteur courrant soit compris en les valeur définit par les valeurs de type TBZVector4b "AMin" et "AMax" } function Clamp(Constref AMin, AMax : TBZVector4b):TBZVector4b; overload; { S'assure que chaque composant du vecteur courrant soit compris en les valeur de type Byte "AMin" et "AMax" } function Clamp(Constref AMin, AMax : Byte):TBZVector4b; overload; { Multiplie le vecteur courrant par un autre TBZVector2d et ajoute un deuxieme TBZVector4b au résultat } function MulAdd(Constref B, C : TBZVector4b):TBZVector4b; { Multiplie le vecteur courrant par un autre TBZVector2d et divise le resultat par un deuxieme TBZVector4b au résultat } function MulDiv(Constref B, C : TBZVector4b):TBZVector4b; { Mélange (Shuffle) les composants par rapport à l'odre des paramètres } function Shuffle(const x,y,z,w : Byte):TBZVector4b; { Mélange (Swizzle) les composants en fonction du masque de type TBZVector4SwizzleRef } function Swizzle(const ASwizzle: TBZVector4SwizzleRef ): TBZVector4b; { Retourne la combinaison = Self + (V2 * F2) } function Combine(constref V2: TBZVector4b; constref F1: Single): TBZVector4b; { Retourne la combinaison = (Self * F1) + (V2 * F2) } function Combine2(constref V2: TBZVector4b; const F1, F2: Single): TBZVector4b; { Retourne la combinaison = (Self * F1) + (V2 * F2) + (V3 * F3) } function Combine3(constref V2, V3: TBZVector4b; const F1, F2, F3: Single): TBZVector4b; { Retourne la valeurs minimum dans les composants XYZ } function MinXYZComponent : Byte; { Retourne la valeurs maximale dans les composants XYZ } function MaxXYZComponent : Byte; { Acces aux propriétés } Case Integer of 0 : (V:TBZVector4bType); //< Acces via tableau 1 : (X, Y, Z, W:Byte); //< Acces par défaut 2 : (Red, Green, Blue, Alpha:Byte); //< Acces comme une couleur au format RGBA 3 : (AsVector3b : TBZVector3b); //< Acces comme un TBZVector3b 4 : (AsInteger : Integer); //< Acces comme valeur 32 bit Integer end; { Définition d'un vecteur 4D de type Integer. } TBZVector4i = Record public { Initialisation des valeurs X, Y, Z et W } procedure Create(Const aX,aY,aZ: Longint; const aW : Longint = 0); overload; { Creation d'un vecteur TBZVector4i à partir d'un TBZVector3i et W } procedure Create(Const aValue : TBZVector3i; const aW : Longint = 0); overload; { Creation d'un vecteur TBZVector4i à partir d'un TBZVector3b et W } procedure Create(Const aValue : TBZVector3b; const aW : Longint = 0); overload; //procedure Create(Const aX,aY,aZ: Longint); overload; @TODO ADD as Affine creation //procedure Create(Const aValue : TBZVector3i); overload; //procedure Create(Const aValue : TBZVector3b); overload; { Retourne une chaine de caractères formaté représentant le vecteur : '(x, y, z, w)' } function ToString : String; { Ajoute deux TBZVector4i } class operator +(constref A, B: TBZVector4i): TBZVector4i; overload; { Soustrait deux TBZVector4i } class operator -(constref A, B: TBZVector4i): TBZVector4i; overload; { Multiplie deux TBZVector4i } class operator *(constref A, B: TBZVector4i): TBZVector4i; overload; { Divise deux TBZVector4i } class operator Div(constref A, B: TBZVector4i): TBZVector4i; overload; { Ajoute à chaque composant une variable de type Longint } class operator +(constref A: TBZVector4i; constref B:Longint): TBZVector4i; overload; { Soustrait à chaque composant une variable de type Longint } class operator -(constref A: TBZVector4i; constref B:Longint): TBZVector4i; overload; { Multiplie chaque composant par une variable de type Longint } class operator *(constref A: TBZVector4i; constref B:Longint): TBZVector4i; overload; { Multiplie chaque composant par une variable de type Single et arrondie les valeurs } class operator *(constref A: TBZVector4i; constref B:Single): TBZVector4i; overload; { Divise chaque composant par une variable de type Longint } class operator Div(constref A: TBZVector4i; constref B:Longint): TBZVector4i; overload; { Negation } class operator -(constref A: TBZVector4i): TBZVector4i; overload; { Retourne @True si le vecteur A est égale au vecteur B } class operator =(constref A, B: TBZVector4i): Boolean; { Retourne @True si deux TBZVector4f ne sont pas égale } class operator <>(constref A, B: TBZVector4i): Boolean; (* class operator And(constref A, B: TBZVector4i): TBZVector4i; overload; class operator Or(constref A, B: TBZVector4i): TBZVector4i; overload; class operator Xor(constref A, B: TBZVector4i): TBZVector4i; overload; class operator And(constref A: TBZVector4i; constref B:LongInt): TBZVector4i; overload; class operator or(constref A: TBZVector4i; constref B:LongInt): TBZVector4i; overload; class operator Xor(constref A: TBZVector4i; constref B:LongInt): TBZVector4i; overload; *) { Division rapide par 2 } function DivideBy2 : TBZVector4i; { Retourne les valeur absolue de chaque composant } function Abs: TBZVector4i; { Retourne la valeur minimum de chaque composant du vecteur par rapport à un autre TBZVector4i } function Min(Constref B : TBZVector4i):TBZVector4i; overload; { Retourne la valeur minimum de chaque composant du vecteur par rapport à une valeur de type Longint } function Min(Constref B : LongInt):TBZVector4i; overload; { Retourne la valeur maximum de chaque composant du vecteur par rapport à un autre TBZVector4i } function Max(Constref B : TBZVector4i):TBZVector4i; overload; { Retourne la valeur maximum de chaque composant du vecteur par rapport à une valeur de type Longint } function Max(Constref B : LongInt):TBZVector4i; overload; { S'assure que les valeurs de chaque composants se trouve dans l'interval des valeurs de type TBZVector4i AMin et AMax } function Clamp(Constref AMin, AMax : TBZVector4i):TBZVector4i; overload; { S'assure que les valeurs de chaque composants se trouve dans l'interval des valeurs de type Longint AMin et AMax } function Clamp(Constref AMin, AMax : LongInt):TBZVector4i; overload; { Multiplie le vecteur avec un autre TBZVector4i (B) et ajoute un deuxieme vecteur (C) } function MulAdd(Constref B, C : TBZVector4i):TBZVector4i; { Multiplie le vecteur avec un autre TBZVector4f (B) et soustrait un deuxieme vecteur (C) } //function MulSub(Constref B, C : TBZVector4i):TBZVector4i; { Multiplie le vecteur avec un autre TBZVector4i (B) et divise avec deuxieme vecteur (C) } function MulDiv(Constref B, C : TBZVector4i):TBZVector4i; { Mélange (Shuffle) les composants par rapport à l'odre des paramètres } function Shuffle(const x,y,z,w : Byte):TBZVector4i; { Mélange (Swizzle) les composants en fonction du masque de type TBZVector4SwizzleRef } function Swizzle(const ASwizzle: TBZVector4SwizzleRef ): TBZVector4i; { Retourne la combinaison = Self + (V2 * F2) } function Combine(constref V2: TBZVector4i; constref F1: Single): TBZVector4i; { Retourne la combinaison = (Self * F1) + (V2 * F2) } function Combine2(constref V2: TBZVector4i; const F1, F2: Single): TBZVector4i; { Retourne la combinaison = (Self * F1) + (V2 * F2) + (V3 * F3) } function Combine3(constref V2, V3: TBZVector4i; const F1, F2, F3: Single): TBZVector4i; { Retourne la valeur minimum dans les composants XYZ } function MinXYZComponent : LongInt; { Retourne la valeur maximale dans les composants XYZ } function MaxXYZComponent : LongInt; { Acces aux propriétés } case Byte of 0 : (V: TBZVector4iType); //< Acces par tableau 1 : (X,Y,Z,W: longint); //< Acces par défaut 2 : (Red, Green, Blue, Alpha : Longint); //< Acces comme une couleur dans l'ordre RGBA 3 : (AsVector3i : TBZVector3i); //< Acces comme un TBZVector3i 4 : (ST,UV : TBZVector2i); //< Acces comme un coordonnées de Texture 5 : (Left, Top, Right, Bottom: Longint); //< Acces comme un rectangle 6 : (TopLeft,BottomRight : TBZVector2i); //< Acces comme les coins haut-gauche et bas-droit d'un rectangle end; { Définition d'un vecteur 4D de type Single. } TBZVector4f = record public { Création d'un vecteur homogène à partir d'une variable de type Single. @br La valeur W est mise à 0.0 par défaut } procedure Create(Const AValue: single); overload; { Création d'un vecteur homogène à partir de valeurs de type Single. @br La valeur W est mise à 0.0 par défaut } procedure Create(Const aX,aY,aZ: single; const aW : Single = 0); overload; { Création d'un vecteur homogène à partir d'un TBZVector3f. @br La valeur W est mise à 0.0 par défaut } procedure Create(Const anAffineVector: TBZVector3f; const aW : Single = 0); overload; { Création d'un vecteur comme une Point à partir d'une variable de type Single. @br La valeur W est mise à 1.0 par défaut } procedure CreatePoint(Const AValue: single); overload; { Création d'un vecteur comme une Point à partir de valeurs de type Single. @br La valeur W est mise à 1.0 par défaut } procedure CreatePoint(Const aX,aY,aZ: single); overload; { Création d'un vecteur comme une Point à partir d'un TBZVector3f. @br La valeur W est mise à 1.0 par défaut } procedure CreatePoint(Const anAffineVector: TBZVector3f); overload; { Retourne une chaine de caractères formaté représentant le vecteur : '(x, y, z, w)' } function ToString : String; { Ajoute deux TBZVector4f } class operator +(constref A, B: TBZVector4f): TBZVector4f; overload; { Soustrait deux TBZVector4f } class operator -(constref A, B: TBZVector4f): TBZVector4f; overload; { Multiplie deux TBZVector4f } class operator *(constref A, B: TBZVector4f): TBZVector4f; overload; { Divise deux TBZVector4f } class operator /(constref A, B: TBZVector4f): TBZVector4f; overload; { Ajoute à chaque composant une variable de type Single } class operator +(constref A: TBZVector4f; constref B:Single): TBZVector4f; overload; { Soustrait à chaque composant une variable de type Single } class operator -(constref A: TBZVector4f; constref B:Single): TBZVector4f; overload; { Multiplie chaque composant par une variable de type Single } class operator *(constref A: TBZVector4f; constref B:Single): TBZVector4f; overload; { Divise chaque composant par une variable de type Single } class operator /(constref A: TBZVector4f; constref B:Single): TBZVector4f; overload; { Retourne la valeur négative } class operator -(constref A: TBZVector4f): TBZVector4f; overload; { Retourne @True si le vecteur A est égale au vecteur B } class operator =(constref A, B: TBZVector4f): Boolean; { Retourne @True si le vecteur A est plus grand ou égale que le vecteur B } class operator >=(constref A, B: TBZVector4f): Boolean; { Retourne @True si le vecteur A est plus petit ou égale que le vecteur B } class operator <=(constref A, B: TBZVector4f): Boolean; { Retourne @True si le vecteur A est plus grand que le vecteur B } class operator >(constref A, B: TBZVector4f): Boolean; { Retourne @True si le vecteur A est plus petit que le vecteur B } class operator <(constref A, B: TBZVector4f): Boolean; { Retourne @True si deux TBZVector4f ne sont pas égale } class operator <>(constref A, B: TBZVector4f): Boolean; class operator xor (constref A, B: TBZVector4f) : TBZVector4f; { Mélange (Shuffle) les composants par rapport à l'odre des paramètres } function Shuffle(const x,y,z,w : Byte): TBZVector4f; { Mélange (Swizzle) les composants en fonction du masque de type TBZVector4SwizzleRef } function Swizzle(const ASwizzle: TBZVector4SwizzleRef ): TBZVector4f; { Retourne la valeur minimum dans les composants XYZ } function MinXYZComponent : Single; { Retourne la valeur maximale dans les composants XYZ } function MaxXYZComponent : Single; { Retourne les valeurs absolue de chaque composant } function Abs:TBZVector4f;overload; { Negation } function Negate:TBZVector4f; { Division rapide par deux } function DivideBy2:TBZVector4f; { Retourne la longueur du vecteur } function Length:Single; { Retourne la longueur du vecteur au carré } function LengthSquare:Single; { Retourne la distance entre le vecteur et un autre TBZVector4f } function Distance(constref A: TBZVector4f):Single; { Retourne la distance au carré entre le vecteur et un autre TBZVector4f } function DistanceSquare(constref A: TBZVector4f):Single; { Calcules Abs(v1[x]-v2[x])+Abs(v1[y]-v2[y])+..., aussi connu sous le nom de "Norm1". } function Spacing(constref A: TBZVector4f):Single; { Retourne le produit scalaire du vecteur avec un autre TBZVector4f } function DotProduct(constref A: TBZVector4f):Single; { Retourne le produit en croix du vecteur avec un autre TBZVector4f } function CrossProduct(constref A: TBZVector4f): TBZVector4f; { Normalise le vecteur } function Normalize: TBZVector4f; { Retourne la normal du vecteur } function Norm:Single; { Retourne la valeur minimum de chaque composant du vecteur par rapport à un autre TBZVector4f } function Min(constref B: TBZVector4f): TBZVector4f; overload; { Retourne la valeur minimum de chaque composant du vecteur par rapport à une valeur de type Single } function Min(constref B: Single): TBZVector4f; overload; { Retourne la valeur maximum de chaque composant du vecteur par rapport à un autre TBZVector4f } function Max(constref B: TBZVector4f): TBZVector4f; overload; { Retourne la valeur maximum de chaque composant du vecteur par rapport à une valeur de type Single } function Max(constref B: Single): TBZVector4f; overload; { S'assure que les valeurs de chaque composants se trouve dans l'interval des valeurs de type TBZVector4f AMin et AMax } function Clamp(Constref AMin, AMax: TBZVector4f): TBZVector4f; overload; { S'assure que les valeurs de chaque composants se trouve dans l'interval des valeurs de type Single AMin et AMax } function Clamp(constref AMin, AMax: Single): TBZVector4f; overload; { Multiplie le vecteur avec un autre TBZVector4f (B) et ajoute un deuxieme vecteur (C) } function MulAdd(Constref B, C: TBZVector4f): TBZVector4f; { Multiplie le vecteur avec un autre TBZVector4f (B) et soustrait un deuxieme vecteur (C) } function MulSub(Constref B, C: TBZVector4f): TBZVector4f; { Multiplie le vecteur avec un autre TBZVector4f (B) et divise avec deuxieme vecteur (C) } function MulDiv(Constref B, C: TBZVector4f): TBZVector4f; { Retourne la valeur interpolée linéarie à un moment T (compris entre 0 et 1.0) entre le vecteur et un autre vecteur } function Lerp(Constref B: TBZVector4f; Constref T:Single): TBZVector4f; { Retourne l'angle Cosine entre le vecteur et un autre TBZVector4f } function AngleCosine(constref A : TBZVector4f): Single; { Retourne l'angle entre le vecteur et un autre TBZVector4f, relatif à un centre de rotation TBZVector4f } function AngleBetween(Constref A, ACenterPoint : TBZVector4f): Single; { Retourne la combinaison = Self + (V2 * F2) } function Combine(constref V2: TBZVector4f; constref F1: Single): TBZVector4f; { Retourne la combinaison = (Self * F1) + (V2 * F2) } function Combine2(constref V2: TBZVector4f; const F1, F2: Single): TBZVector4f; { Retourne la combinaison = (Self * F1) + (V2 * F2) + (V3 * F3) } function Combine3(constref V2, V3: TBZVector4f; const F1, F2, F3: Single): TBZVector4f; { Retourne les valeurs arrondi dans un TBZVector4i } function Round: TBZVector4i; { Retourne les valeurs tronqué dans un TBZVector4i } function Trunc: TBZVector4i; { Retourne les valeurs arrondi vers l'infini négatif dans un TBZVector4i } function Floor: TBZVector4i; overload; { Retourne les valeurs arrondi vers l'infini positif dans un TBZVector4i } function Ceil : TBZVector4i; overload; { Retourne la partie fractionnaire de chaque composant } function Fract : TBZVector4f; overload; { Retourne la racine carré de chaque composant } function Sqrt : TBZVector4f; overload; { Retourne la racine carré inverse de chaque composant } function InvSqrt : TBZVector4f; overload; { Acces aux propriétés } case Byte of 0: (V: TBZVector4fType); //< Acces par tableau 1: (X, Y, Z, W: Single); //< Acces par défaut 2: (Red, Green, Blue, Alpha: Single); //< Acces comme une couleur dans l'ordre RGBA 3: (AsVector3f : TBZVector3f); //< Acces comme un TBZVector3f 4: (ST, UV : TBZVector2f); //< Acces comme un coordonnées de Texture 5: (Left, Top, Right, Bottom: Single); //< Acces comme un rectangle 6: (TopLeft,BottomRight : TBZVector2f); //< Acces comme les coins haut-gauche et bas-droit d'un rectangle end; { Définition de convenance pratique pour décrire un vecteur homogène de type TBZVector4f } TBZVector = TBZVector4f; { Pointeur vers TBZVector } PBZVector = ^TBZVector; TBZClipRect = TBZVector; //< TODO : Rendre Independant ou extraire TBZFloatRect de l'unité BZGraphic {%endregion%} {%region%----[ Plane ]---------------------------------------------------------} Const {@groupbegin Constantes de representation de la "moitié du plan l'espace" (half space) } cPlaneFront = 0; cPlaneBack = 1; cPlanePlanar = 2; cPlaneClipped = 3; cPlaneCulled = 4; cPlaneVisible = 5; {@groupend} type { Description du plan dans l'espace. @br La Position des point par rapport à l'axe normal d'un plan. @br     La définition positive est relative à la direction normale du vecteur } TBZHmgPlaneHalfSpace = ( phsIsOnNegativeSide, //< est sur la face negative phsIsOnPositiveSide, //< est sur la face positive phsIsOnPlane, //< est sur le plan phsIsClipped, //< est dans le plan phsIsAway //< est en dehors du plan ); { @abstract(Définition d'un plan homogène.) Une équation plane est défini par son équation A.x + B.y + C.z + D, un plan peut être mappé sur les     Coordonnées d'espace homogènes, et c'est ce que nous faisons ici. @br     Le plan est normalisé et contient donc une unité normale dans ABC (XYZ) et la distance de l'origine du plan.     @bold(AVERTISSEMENT) : la méthode Create(Point, Normal) autorisera les vecteurs non-unitaires mais fondamentalement @bold(NE LE FAITES PAS). @br     Un vecteur non-unitaire calculera la mauvaise distance au plan.     C’est un moyen rapide de créer un plan quand on a un point et une Normale sans encore un autre appel à la méthode sqrt.     Plus d'informations : @br @unorderedlist( @item(https://en.wikipedia.org/wiki/Plane_(geometry) ) @item(http://www.songho.ca/math/plane/plane.html) @item(https://brilliant.org/wiki/3d-coordinate-geometry-equation-of-a-plane/ ) @item(http://tutorial.math.lamar.edu/Classes/CalcII/EqnsOfPlanes.aspx ) ) } TBZHmgPlane = record private procedure CalcNormal(constref p1, p2, p3 : TBZVector); public { Création d'un plan homogène. @br Autorise les vecteurs non unitaires mais essentiellement @bold(NE PAS LE FAIRE). @Br       Un vecteur non unitaire calculera la mauvaise distance au plan.} procedure Create(constref point, normal : TBZVector); overload; { Création et calcule des paramètres du plan définis par trois points. } procedure Create(constref p1, p2, p3 : TBZVector); overload; { Normalise le plan } procedure Normalize; { Retourne le plan normalisé } function Normalized : TBZHmgPlane; { Retourne la distance absolue entre le plan et un point } function AbsDistance(constref point : TBZVector) : Single; { Retourne la distance entre le plan et un point } function Distance(constref point : TBZVector) : Single; overload; { Retourne la distance entre le plan et une sphere de centre "Center" et de rayon "Radius" } function Distance(constref Center : TBZVector; constref Radius:Single) : Single; overload; { Calcul et retourne le vecteur perpendiculaire au plan. @br Le plan courrant est supposé être de longueur unitaire, pour pouvoir soustraire tout composant parallèle à lui même } function Perpendicular(constref P : TBZVector) : TBZVector; { Reflète le vecteur V par rapport le plan (on suppose que le plan est normalisé) } function Reflect(constref V: TBZVector): TBZVector; { Retourne @True si un point est dans la moitié de l'espace } function IsInHalfSpace(constref point: TBZVector) : Boolean; { Return the position for a point relative to the normal axis of the plane. @param( : TBZVector) @return(TBZHmgPlaneHalfSpace) } //function GetHalfSpacePosition(constref point: TBZVector) : TBZHmgPlaneHalfSpace; { Computes point to plane projection. Plane and direction have to be normalized } //function PointOrthoProjection(const point: TAffineVector; const plane : THmgPlane; var inter : TAffineVector; bothface : Boolean = True) : Boolean; //function PointProjection(const point, direction : TAffineVector; const plane : THmgPlane; var inter : TAffineVector; bothface : Boolean = True) : Boolean; { Computes segment / plane intersection return false if there isn't an intersection} // function SegmentIntersect(const ptA, ptB : TAffineVector; const plane : THmgPlane; var inter : TAffineVector) : Boolean; { Access aux propriétés } case Byte of 0: (V: TBZVector4fType); //< Doit être compatible avec le type TBZVector4f 1: (A, B, C, D: Single); //< Paramètres du plan 2: (AsNormal3: TBZAffineVector); //< Accès super rapide à la Normale en tant que vecteur affine. 3: (AsVector: TBZVector); //< Accès comme un TBZVector4f 4: (X, Y, Z, W: Single); //< Acces légal pour que le code existant fonctionne end; {%endregion%} {%region%----[ Matrix ]--------------------------------------------------------} { Type d'action de transformation d'une matrice } TBZMatrixTransType = (ttScaleX, ttScaleY, ttScaleZ, ttShearXY, ttShearXZ, ttShearYZ, ttRotateX, ttRotateY, ttRotateZ, ttTranslateX, ttTranslateY, ttTranslateZ, ttPerspectiveX, ttPerspectiveY, ttPerspectiveZ, ttPerspectiveW); { TBZMatrixTransformations : Est utilisé pour décrire une séquence de transformation en suivant l'odre définis tel que : [Sx][Sy][Sz][ShearXY][ShearXZ][ShearZY][Rx][Ry][Rz][Tx][Ty][Tz][P(x,y,z,w)] Constants are declared for easier access (see MatrixDecompose below) } TBZMatrixTransformations = array [TBZMatrixTransType] of Single; {%region%----[ TBZMatrix4f ]---------------------------------------------------} { @abstract(Définition d'un matrice 4D de type Single @br Les éléments de la matrice sont dans l'ordre des lignes principales (Row-major) )     Plus d'informations :@br @unorderedlist( @item(http://www.euclideanspace.com/maths/algebra/matrix/index.htm) @item(http://www.euclideanspace.com/maths/differential/other/matrixcalculus/index.htm) @item(http://www.fastgraph.com/makegames/3drotation/) ) } TBZMatrix4f = record private function GetComponent(const ARow, AColumn: Integer): Single; inline; procedure SetComponent(const ARow, AColumn: Integer; const Value: Single); inline; function GetRow(const AIndex: Integer): TBZVector; inline; procedure SetRow(const AIndex: Integer; const Value: TBZVector); inline; function GetDeterminant: Single; function MatrixDetInternal(const a1, a2, a3, b1, b2, b3, c1, c2, c3: Single): Single; procedure Transpose_Scale_M33(constref src : TBZMatrix4f; Constref ascale : Single); public { Création d'une matrice homogène identitaire } procedure CreateIdentityMatrix; { Création d'une matrice d'hommotéthie depuis un TBZAffineVector } procedure CreateScaleMatrix(const v : TBZAffineVector); overload; { Création d'une matrice d'hommotéthie depuis un TBZVector } procedure CreateScaleMatrix(const v : TBZVector); overload; { Creation d'une matrice de translation depuis un TBZAffineVector } procedure CreateTranslationMatrix(const V : TBZAffineVector); overload; { Creation d'une matrice de translation depuis un TBZVector } procedure CreateTranslationMatrix(const V : TBZVector); overload; { Creation d'une matrice d'hommotéthie + de translation. @br L'hommotéthie est appliqué avant la translation. } procedure CreateScaleAndTranslationMatrix(const aScale, Offset : TBZVector); overload; { Création d'une matrice de rotation de type "Main droite" autours de l'axe des X depuis Sin et Cos } procedure CreateRotationMatrixX(const sine, cosine: Single); overload; { Création d'une matrice de rotation de type "Main droite" autours de l'axe des X depuis un Angle (en radian) } procedure CreateRotationMatrixX(const angle: Single); overload; { Création d'une matrice de rotation de type "Main droite" autours de l'axe des Y depuis Sin et Cos } procedure CreateRotationMatrixY(const sine, cosine: Single); overload; { Création d'une matrice de rotation de type "Main droite" autours de l'axe des X depuis un Angle (en radian) } procedure CreateRotationMatrixY(const angle: Single); overload; { Création d'une matrice de rotation de type "Main droite" autours de l'axe des Z depuis Sin et Cos } procedure CreateRotationMatrixZ(const sine, cosine: Single); overload; { Création d'une matrice de rotation de type "Main droite" autours de l'axe des Z depuis un Angle (en radian) } procedure CreateRotationMatrixZ(const angle: Single); overload; { Creatin d'une matrice de rotation le long de l'axe donné de type TBZAffineVector "anAxis" par Angle (en radians). } procedure CreateRotationMatrix(const anAxis : TBZAffineVector; angle : Single); overload; { Creatin d'une matrice de rotation le long de l'axe donné de type TBZVector "anAxis" par Angle (en radians). } procedure CreateRotationMatrix(const anAxis : TBZVector; angle : Single); overload; { Creatin d'une matrice de rotation depuis les angles d'euler Yaw, Pitch et Roll } procedure CreateRotationMatrixYawPitchRoll(yawAngle, pitchAngle, rollAngle : Single); { Creation d'un matrice "regarder (Look at) de type "Main droite") } procedure CreateLookAtMatrix(const eye, center, normUp: TBZVector); { Creation d'une matrice de "vue" depuis les plan d'un "Frustum"(Left, Right, Bottom, Top, ZNear, ZFar) } procedure CreateMatrixFromFrustumPlane(Left, Right, Bottom, Top, ZNear, ZFar: Single); // Par defaut le plan utiliser est le plan defini par les point LeftTop et BottomRight avec les valeur en z les plus grandes // procedure CreateMatrixFromFrustum(vFrustum : TBZFrustum); { Creation d'une matrice de "Perspective" } procedure CreatePerspectiveMatrix(FOV, Aspect, ZNear, ZFar: Single); { Creation d'une matrice de vue othogonale à partir des paramètre du Frustum } procedure CreateOrthoMatrix(Left, Right, Bottom, Top, ZNear, ZFar: Single); { Creation d'une matrice de sélection } procedure CreatePickMatrix(x, y, deltax, deltay: Single; const viewport: TBZVector4i); { Creation d'une matrice de projection parallele. @br Les points transformés seront projetés sur le plan le long de la direction spécifiée. } procedure CreateParallelProjectionMatrix(const plane : TBZHmgPlane; const dir : TBZVector); { Creation d'une matrice de projection "Ombre" (shadow). @br L'ombre sera projetésur le plan définit par "planePoint" et "planeNormal", depuis la position de la lumière "lightPos".} procedure CreateShadowMatrix(const planePoint, planeNormal, lightPos : TBZVector); { Creation d'une matrice de reflection pour le plan donné. @br La matrice de réflexion permet la mise en œuvre de planes réflecteurs (miroirs) } procedure CreateReflectionMatrix(const planePoint, planeNormal : TBZVector); { Retourne une chaine de caractères formaté représentant la matrice : @br "("x, y, z, w")" @br "("x, y, z, w")" @br "("x, y, z, w")" @br "("x, y, z, w")" } function ToString : String; { Ajoute deux matrices } class operator +(constref A, B: TBZMatrix4f): TBZMatrix4f; overload; { Ajoute à chaque composant de la matrice une variable de type Single } class operator +(constref A: TBZMatrix4f; constref B: Single): TBZMatrix4f; overload; { Soustrait deux matrices } class operator -(constref A, B: TBZMatrix4f): TBZMatrix4f; overload; { Soustrait à chaque composant de la matrice une variable de type Single } class operator -(constref A: TBZMatrix4f; constref B: Single): TBZMatrix4f; overload; { Multiplie deux matrices } class operator *(constref A, B: TBZMatrix4f): TBZMatrix4f; overload; { Multiplie chaque composant de la matrice par une variable de type Single } class operator *(constref A: TBZMatrix4f; constref B: Single): TBZMatrix4f; overload; { Transforme un vecteur homogene en le multipliant par la matrice } class operator *(constref A: TBZMatrix4f; constref B: TBZVector): TBZVector; overload; { Transforme un vecteur homogene en le multipliant par la matrice } class operator *(constref A: TBZVector; constref B: TBZMatrix4f): TBZVector; overload; { Divise chaque composant de la matrice par une variable de type Single } class operator /(constref A: TBZMatrix4f; constref B: Single): TBZMatrix4f; overload; { Negation de chaque composant de la matrice } class operator -(constref A: TBZMatrix4f): TBZMatrix4f; overload; //class operator =(constref A, B: TBZMatrix4): Boolean;overload; //class operator <>(constref A, B: TBZMatrix4): Boolean;overload; { Transpose la matrice } function Transpose: TBZMatrix4f; { Retourne la matrice inverse } function Invert : TBZMatrix4f; { Normalise la matrice et supprime les composant de translation. @br Le résultat est une matrice orthonormal (la direction Y direction est preservé, puis Z) } function Normalize : TBZMatrix4f; { Adjugate and Determinant functionality.@br Is used in the computation of the inverse of a matrix@br So far has only been used in Invert and eliminated from assembler algo might not need to do this just keep it for pascal do what it says on the tin anyway as it has combined. } { Fonctionnalité adjuvante et déterminante. @Br       Est utilisé dans le calcul de la matrice inverse. @br       Jusqu'à présent, a seulement été utilisé dans "Invert" } procedure Adjoint; { Trouve la matrice inverse enpréservant l'angle .@br La préservation de l'angle peut permettre le calcul de la matrice inverse des matrices combiner de la translation, de la rotation, de la mise à l'échelle isotrope. @br Les autres matrices ne seront pas correctement inversées par cette fonction. } procedure AnglePreservingMatrixInvert(constref mat : TBZMatrix4f); { Décompose une matrice de transformation non dégénérée en la séquence de transformations qui l'a produite. @Br       Auteur original : Spencer W. Thomas, Université du Michigan. @br       Le coefficient de chaque transformation est retourné dans l'élément correspondant du vecteur Translation. @br Retourne @true en cas de success, si non @false la matrice est singulière. } function Decompose(var Tran: TBZMatrixTransformations): Boolean; { Ajoute un vecteur de translation à la matrice } function Translate( constref v : TBZVector):TBZMatrix4f; { Multiplication par composants (Component-wise multiplication) } function Multiply(constref M2: TBZMatrix4f):TBZMatrix4f; // function getCoFactor : single; { Acces aux lignes de la matrice par vecteur } property Rows[const AIndex: Integer]: TBZVector read GetRow write SetRow; { Acces aux composants de la matrice } property Components[const ARow, AColumn: Integer]: Single read GetComponent write SetComponent; default; { Retourne le déterminant de la matrice } property Determinant: Single read GetDeterminant; { Access aux propriétés } case Byte of 0: (M: array [0..3, 0..3] of Single); //< Acces par tableau 2D 1: (V: array [0..3] of TBZVector); //< Acces via tableau de TBZVector 2: (VX : Array[0..1] of array[0..7] of Single); //< acces pour l'AVX 3: (X,Y,Z,W : TBZVector); //< Acces aux lignes 4: (m11, m12, m13, m14: Single; //< Acces par défaut m21, m22, m23, m24: Single; m31, m32, m33, m34: Single; m41, m42, m43, m44: Single); End; { Définition de convenance pratique pour décrire une matrice de type TBZMatrix4f } TBZMatrix = TBZMatrix4f; { Pointeur vers TBZMatrix } PBZMatrix = ^TBZMatrix; {%endregion%} {%endregion%} {%region%----[ TBZEulerAngles ]------------------------------------------------} { Ordre de rotation des angles d'Euler. @br Ici, nous utilisons les conventions d'angles de Tait-Bryan pour la définition des axes de rotation. @br (x-y-z, y-z-x, z-x-y, x-z-y, z-y-x, y-x-z). } TBZEulerOrder = (eulXYZ, eulXZY, eulYXZ, eulYZX, eulZXY, eulZYX); { @abstract(Descrition d'angles d'Euler) Les angles d'Euler sont trois angles pour décrire l'orientation d'un corps rigide par rapport à un repère fixe. @br     Ils peuvent également représenter l'orientation d'un référentiel mobile en physique. Ou l'orientation d'une base générale en algèbre linéaire tridimensionnelle. Est utilisé par le type TBZQuaternion. @bold(A RETENIR) : @unorderedlist( @item(X = Roll = Bank = Tilt) @item(Y = Yaw = Heading = Azimuth) @item(Z = Pitch = Attitude = Elevation) ) Source : https://en.wikipedia.org/wiki/Euler_angles Plus d'informations :@br @unorderedlist( @item(https://en.wikipedia.org/wiki/Euler%27s_rotation_theorem) @item(http://ressources.univ-lemans.fr/AccesLibre/UM/Pedago/physique/02/meca/angleeuler.html) @item(https://en.wikipedia.org/wiki/Orientation_(geometry)) @item(https://en.wikipedia.org/wiki/Inertial_navigation_system) @item(http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm) @item(http://www.starlino.com/imu_guide.html) ) } TBZEulerAngles = record public { Creation des angles d'Euler depuis les angles XYZ (en degré) } procedure Create(X,Y,Z:Single); // Roll, Yaw, Pitch { CCreation des angles d'Euler depuis les angles définie dans un TBZVector (en degré) } procedure Create(Const Angles: TBZVector); { Convertis les angles d'Euler en angle et en un axe selon l'ordre de rotation. @br Ordre des angles de rotation par défaut YZX (TBZEulerOrder) } procedure ConvertToAngleAxis(Out Angle : Single; Out Axis : TBZVector;Const EulerOrder : TBZEulerOrder = eulYZX); { Convertis les angles d'Euler vers une matrice de rotation suivant l'ordre de rotation. @br Ordre des angles de rotation par défaut YZX (TBZEulerOrder) } function ConvertToRotationMatrix(Const EulerOrder:TBZEulerOrder = eulYZX): TBZMatrix; { Acces aux propriétés } Case Byte of 0 : ( V : TBZVector3fType ); //< Accès via tableau 1 : ( X, Y, Z : Single ); //< Acces par défaut 2 : ( Roll, Yaw, Pitch : Single ); //< Acces par angle 3 : ( Bank, Heading, Attitude : Single ); //< Acces par angle "avionique" 4 : ( Tilt, Azimuth, Elevation : Single ); //< Acces par angle "topographie" end; {%endregion%} {%region%----[ Quaternion ]----------------------------------------------------} { @abstract(Description et manipulation de quaternions) Les quaternions sont un système numérique qui étend les nombres complexes     et sont appliqués à la mécanique dans l'espace tridimensionnel. @br     Une des caractéristiques des quaternions est que la multiplication de deux quaternions n'est pas commutative. Plus informations :@br @unorderedlist( @item(https://en.wikipedia.org/wiki/Quaternion) @item(http://developerblog.myo.com/quaternions/) @item(http://www.chrobotics.com/library/understanding-quaternions) @item(https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation) @item(http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/) @item(http://mathworld.wolfram.com/Quaternion.html) ) } TBZQuaternion = record public { Creation d'un quaternion } procedure Create(x,y,z: Single; Real : Single);overload; { Creation d'un quaternion } procedure Create(const Imag: array of Single; Real : Single); overload; { Création d'un quaternion unitaire depuis deux vecteurs de type TBZAffineVector } procedure Create(const V1, V2: TBZAffineVector); overload; { Creation d'un quaternion unitaire à partir de deux vecteurs unitaires ou de deux points ou sur une sphère unitaire } procedure Create(const V1, V2: TBZVector); overload; { Creation d'un quaternion unitaire à partir d'une matrice. @br @bold(Note) : La matrice doit-être une matrice de rotation ! } procedure Create(const mat : TBZMatrix); overload; { Création d'un quaternion depuis un angle (en degré) et un axe de type TBZAffineVector } procedure Create(const angle : Single; const axis : TBZAffineVector); overload; //procedure Create(const angle : Single; const axis : TBZVector); overload; { Création d'un quaternion depuis les angles d'Euler. ( Ordre standard des angles d'Euler = YZX ) } procedure Create(const Yaw, Pitch, Roll : Single); overload; { Création d'un quaternion depuis les angles d'Euler dans un ordre arbitraire TBZEulerOrder (angles en degré) } procedure Create(const x, y, z: Single; eulerOrder : TBZEulerOrder); overload; { Création d'un quaternion depuis les angles d'Euler TBZEulerAngles dans un ordre arbitraire TBZEulerOrder (angles en degré) } procedure Create(const EulerAngles : TBZEulerAngles; eulerOrder : TBZEulerOrder); overload; { Retourne le produite de deux quaternion. @br "quatrenion_Left * quaternion_Right" est la concaténation d'une rotation de A suivie de la rotation B @br @bold(Note) : L'ordre inversé est important A * B car B * A donne de mauvais résultats ! } class operator *(constref A, B: TBZQuaternion): TBZQuaternion; { Retourne @True si le quaternion A est égale au quaternion B } class operator =(constref A, B: TBZQuaternion): Boolean; { Retourne @True si le quaternion A n'est pas égale au quaternion B } class operator <>(constref A, B: TBZQuaternion): Boolean; { Retourne une chaine de caractères formaté représentant le quaternion : "("x, y, z, w")" } function ToString : String; (*PD : CONVERTS A UNIT QUATERNION INTO TWO POINTS ON A UNIT SPHERE PD THIS IS A NONSENSE FUNCTION. IT DOES NOT DO THIS. IT MAKES ASSUMTIONS THERE IS NO Z COMPONENT IN THE CALCS. IT TRIES TO USE IMAGINARY PART AS A VECTOR WHICH YOU CANNOT DO WITH A QUAT, IT IS A 4D OBJECT WHICH MUST USE OTHER METHODS TO TRANSFORM 3D OBJECTS. IT HOLDS NO POSITION INFO. CONVERTIR UN QUATERNION UNITAIRE EN DEUX POINTS SUR UNE SPHÈRE UNITAIRE N'A PAS DE SENS ET ON NE DOIT PAS LE FAIRE. IL N'Y A PAS DE COMPOSANT Z DANS LES CALCULS ET ON NE PEUX PAS TENTER D'UTILISER UNE PARTIE IMAGINAIRE.      EN TANT QUE VECTEUR ON NE PEUX PAS FAIRE AVEC UN QUATERNION. C'EST UN OBJET 4D QUI DOIT UTILISER D'AUTRES MÉTHODES POUR TRANSFORMER DES OBJETS 3D. IL NE CONTIENT AUCUNE INFORMATION DE POSITION. THIS FUNCTION IS USE FOR "ARCBALL" GIZMO. CAN BE REMOVE FROM HERE. IT CAN TAKE PLACE IN THE "GIZMOARCBALL OBJECT" PROCEDURE CONVERTTOPOINTS(VAR ARCFROM, ARCTO: TBZAFFINEVECTOR); //OVERLOAD; PROCEDURE CONVERTTOPOINTS(VAR ARCFROM, ARCTO: TBZVECTOR); //OVERLOAD; *) { Convertis le quaternion en une matrice de rotation (possibilité au quaternion d'être non-unitaire). @br On suppose que la matrice sera utilisé pour multiplié la colonne du vecteur sur la gauche : @br vnew = mat * vold. @br Fonctionne correctement pour les coordonées "Main droite".} function ConvertToMatrix : TBZMatrix; { Convertis le quaternion vers l'ordre de rotation définis par TBZEulerOrder } function ConvertToEuler(Const EulerOrder : TBZEulerOrder) : TBZEulerAngles; { Convertis le quaternion vers un angle (en degré) et un axe de type TBZAffineVector } procedure ConvertToAngleAxis(out angle : Single; out axis : TBZAffineVector); { Retourne le quaternion "conjuguer" (conjugate) } function Conjugate : TBZQuaternion; { Retourne la magnitude du quaternion } function Magnitude : Single; { Normalise le quaternion } procedure Normalize; { Applique la rotation au vecteur V de type TBZVector autours l'axe local. } function Transform(constref V: TBZVector): TBZVector; { Redimensionne le quaternion. @br Si le facteur de mise à l'échelle Un facteur d'échelle est appliqué à un quaternion puis la rotation mettra à l'échelle les vecteurs lors de leur transformation. @br On suppose que le quaternion est déja normalisé. } procedure Scale(ScaleVal: single); { Retourne le produit de deux quaternion : quaternion_Right * quaternion_Left. @br Pour combiner les rotations, utilisez Muliply(qSecond, qFirst), ce qui aura pour effet de faire une rotation par qFirst puis qSecond. @br @bold(Note) : l'ordre de la multiplication est importante ! } function MultiplyAsSecond(const qFirst : TBZQuaternion): TBZQuaternion; { Interpolation linéaire sphérique de quaternions unitaires avec des tours (spins). @br @bold(Note) : @br - la valeur de début QStart correspond au quaternion courrant Self. @br - t est une valeur comprise entre 0.0 et 1.0 @br - Spin est le nombre de rotation supplémentaire à effectuer. } function Slerp(const QEnd: TBZQuaternion; Spin: Integer; t: Single): TBZQuaternion; overload; { Interpolation linéaire sphérique de quaternions unitaires. @br @bold(Note) : @br - la valeur de début QStart correspond au quaternion courrant Self. @br - t est une valeur comprise entre 0.0 et 1.0 @br } function Slerp(const QEnd: TBZQuaternion; const t : Single) : TBZQuaternion; overload; { Acces aux propriétés } case Byte of 0: (V: TBZVector4fType); //< Acces via tableau 1: (X, Y, Z, W: Single); //< Acces par défaut 2: (AsVector4f : TBZVector4f); //< Acces comme un TBZVector 3: (ImagePart : TBZVector3f; RealPart : Single); //< Acces comme un nombre complexe End; {%endregion%} {%region%----[ Helpers ]-------------------------------------------------------} {%region%----[ TBZVector2iHelper ]---------------------------------------------} {Assistant pour le type TBZVector2i } TBZVector2iHelper = record helper for TBZVector2i private function GetYX : TBZVector2i; public { Retourne le vecteur courrant normalisé } function Normalize : TBZVector2f; { Acces comme un TBZVector2f } function AsVector2f : TBZVector2f; { Retourne les valeurs dans l'ordre YX } property YX : TBZVector2i read GetYX; end; {%endregion%} {%region%----[ TBZVector2fHelper ]---------------------------------------------} { Assistant pour le type TBZVector2f } TBZVector2fHelper = record helper for TBZVector2f private // Swizling access function GetXY : TBZVector2f; function GetYX : TBZVector2f; function GetXX : TBZVector2f; function GetYY : TBZVector2f; function GetXXY : TBZVector4f; function GetYYX : TBZVector4f; function GetXYY : TBZVector4f; function GetYXX : TBZVector4f; function GetXYX : TBZVector4f; function GetYXY : TBZVector4f; function GetXXX : TBZVector4f; function GetYYY : TBZVector4f; public { @abstract(Implémente une fonction d'étape renvoyant une pour chaque composant de Self qui est       supérieur ou égal au composant correspondant dans la référence du Vecteur B, et zéro si non) Plus d'informations : @br @unorderedlist( @item(http://developer.download.nvidia.com/cg/step.html) @item(https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/step.xhtml )) } function Step(ConstRef B : TBZVector2f):TBZVector2f; { @abstract(Retourne une normale telle quelle si le vecteur de position dans l'espace occulaire d'un sommet pointe dans la direction opposée d'une normale géométrique, sinon renvoie la version inversée de la normale.) Le vecteur courrant représente le vecteur de la normale pertubée. @br Le vecteur A représente un vecteur d'incidence (généralement un vecteur de direction de l'œil vers un sommet) @br Le vecteur B représente le vecteur normal géométrique (pour certaines facettes, la normale péturbée est identique). Plus d'informations : @br @unorderedlist( @item(http://developer.download.nvidia.com/cg/faceforward.html) @item(https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/faceforward.xhtml )) } //function FaceForward(constref A, B: TBZVector2f): TBZVector2f; { @abstract(Renvoie le plus petit entier non inférieur à un scalaire ou à chaque composante vectorielle.)       Retourne la valeur de la saturation dans la plage [0,1] comme suit: @br @orderedlist( @item(Retourne 0 si le vecteur courrant est plus petit que 0) @item(Retourne 1 si le vecteur courrant est plus grand que 1) @item(Dans les autres cas retourne les valeurs courrantes.)) Plus d'informations : http://developer.download.nvidia.com/cg/saturate.html ) } function Saturate : TBZVector2f; { @abstract(Interpolation douce entre deux valeurs basé sur le troisième paramètre.) @unorderedlist( @item(Retourne 0 si Self < A < B ou que Self > A > A) @item(Retourne 1 si Self < B < A ou que Self > B > A) @item(La valeur interpolée retournée est comprise dans l'intervalle 0.0 et 1.0 pour le domaina [A,B].)) Si A = Self alors, la pente de Self.smoothstep(a, b) et b.smoothstep(a, b) est nulle.@br Plus d'information : @br @unorderedlist( @item(http://developer.download.nvidia.com/cg/smoothstep.html) @item(https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/smoothstep.xhtml )) } function SmoothStep(ConstRef A,B : TBZVector2f): TBZVector2f; { @abstract(Retourne la valeur de l'interpolation linéaire du vecteur courrant et de B en fonction du poid T. @br Si T est une valeur en dehors de l'interval [0.0, 1.0], il sera actuellement extrapolé. ) Plus d'informations : @br @unorderedlist( @item(http://developer.download.nvidia.com/cg/lerp.html) @item(https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/mix.xhtml) )} function Lerp(Constref B: TBZVector2f; Constref T:Single): TBZVector2f; { Accès rapide aux propriétés de "Swizzling" comme dans HLSL et GLSL } {@groupbegin} property XY : TBZVector2f read GetXY; property YX : TBZVector2f read GetYX; property XX : TBZVector2f read GetXX; property YY : TBZVector2f read GetYY; property XXY : TBZVector4f read GetXXY; property YYX : TBZVector4f read GetYYX; property XYY : TBZVector4f read GetXYY; property YXX : TBZVector4f read GetYXX; property XYX : TBZVector4f read GetXYX; property YXY : TBZVector4f read GetYXY; property XXX : TBZVector4f read GetXXX; property YYY : TBZVector4f read GetYYY; {@groupend} end; {%endregion%} {%region%----[ TBZVector4fHelper ]---------------------------------------------} { Assistant pour le type TBZVector eg : TBZVector4f } TBZVectorHelper = record helper for TBZVector private // Swizling access function GetXY : TBZVector2f; procedure SetXY(Const Value: TBZVector2f); function GetYX : TBZVector2f; function GetXZ : TBZVector2f; function GetZX : TBZVector2f; function GetYZ : TBZVector2f; function GetZY : TBZVector2f; function GetXX : TBZVector2f; function GetYY : TBZVector2f; function GetZZ : TBZVector2f; function GetXYZ : TBZVector4f; function GetXZY : TBZVector4f; function GetYXZ : TBZVector4f; function GetYZX : TBZVector4f; function GetZXY : TBZVector4f; function GetZYX : TBZVector4f; function GetXXX : TBZVector4f; function GetYYY : TBZVector4f; function GetZZZ : TBZVector4f; function GetYYX : TBZVector4f; function GetXYY : TBZVector4f; function GetYXY : TBZVector4f; public { @abstract(Effectue une rotation du point selon un axe arbitraire et d'un angle (en radians)) Le système de coordonnées utilisé ets "Main droite".@br Les rotations positives sont dans le sens inverse des aiguilles d'une montre avec l'axe positif vers vous. @br Les rotations positives sont vues dans le sens horaire depuis l'origine le long de l'axe positif : @br @unorderedlist( @item(Orientation de l'axe pour visualiser les positifs dans le quadrant supérieur droit [sous forme d'axes de graphique] ) @item(Avec + Z pointé vers vous (vers l'écran), +X est à droite, +Y est vers le haut) @item(Avec + Y pointant vers vous, +Z est à droite, +X est vers le haut) @item(Avec + X pointant vers vous +Y est à gauche +Z est vers le haut)) } function Rotate(constref axis : TBZVector; angle : Single):TBZVector; { Effectue une rotation matricielle du point autours l'axe des X et d'un angle "Alpha" (en radians) } function RotateWithMatrixAroundX(alpha : Single) : TBZVector; { Effectue une rotation matricielle du point autours l'axe des Y et d'un angle "Alpha" (en radians) } function RotateWithMatrixAroundY(alpha : Single) : TBZVector; { Effectue une rotation matricielle du point autours l'axe des Z et d'un angle "Alpha" (en radians) } function RotateWithMatrixAroundZ(alpha : Single) : TBZVector; { @abstract(Effectue une rotation du point autours l'axe des X et d'un angle "Alpha" (en radians)) Avec +X pointant vers vous, +Y est à gauche, +Z est vers le haut. @br Une rotation positive autour de x, Y devient négatif. } function RotateAroundX(alpha : Single) : TBZVector; { @abstract(Effectue une rotation du point autours l'axe des Y et d'un angle "Alpha" (en radians)) Avec +Y pointant vers vous, +Z est à droite, +X est vers le haut. @br Une rotation positive autour de y, Z devient négatif. } function RotateAroundY(alpha : Single) : TBZVector; { @abstract(Effectue une rotation du point autours l'axe des Y et d'un angle "Alpha" (en radians)) Avec +Z pointant vers vous, +X est à droite, +Y est vers le haut. @br Une rotation positive autour de z, X devient négatif. } function RotateAroundZ(alpha : Single) : TBZVector; { @abstract(Projection du point sur la ligne définie par "Origin" et "Direction".) Effectue un produit scalaire : DotProduct((p - origine), direction) qui, si la direction est normalisée, calcule la distance entre l'origine et la projection deu point sur la ligne (origine, direction). } function PointProject(constref origin, direction : TBZVector4f) : Single; // Returns true if line intersect ABCD quad. Quad have to be flat and convex //function IsLineIntersectQuad(const direction, ptA, ptB, ptC, ptD : TBZVector) : Boolean; // Computes closest point on a segment (a segment is a limited line). //function PointSegmentClosestPoint(segmentStart, segmentStop : TBZVector) : TBZVector; { Computes algebraic distance between segment and line (a segment is a limited line).} //function PointSegmentDistance(const point, segmentStart, segmentStop : TAffineVector) : single; { Computes closest point on a line.} //function PointLineClosestPoint(const linePoint, lineDirection : TBZVector) : TBZVector; { Computes algebraic distance between point and line.} //function PointLineDistance(const linePoint, lineDirection : TBZVector) : Single; { @abstract(Modifie la position du vecteur (caméra) pour le déplacer autour de sa cible. @br       Cette méthode permet de mettre en œuvre rapidement les commandes d'une caméra. @br @bold(Note) : Angle deltas est en degré.) @bold(Astuce) :@br Les coordonnées du parent vecteur (caméra) doivent être une "identité". @br Faire du vecteur de la camera un enfant d'un objet, et en déplacant simplement la cible, permet de changer l'angle de vue. (style FPS) } function MoveAround(constref AMovingObjectUp, ATargetPosition: TBZVector; pitchDelta, turnDelta: Single): TBZVector; { @abstract(Translation du point depuis le centre "Center" a une distance "ADistance") Si "AFromCenterSpot" est à : @br @unorderedlist( @item( @true : la distance, est la distance que le point doit garder du centre) @item( @false : la distance, est la distance que le point doit se déplacer de sa position actuelle par rapport au centre. ) ) } function ShiftObjectFromCenter(Constref ACenter: TBZVector; const ADistance: Single; const AFromCenterSpot: Boolean): TBZVector; { Retourne la moyenne de quatre point représentant un plan } function AverageNormal4(constref up, left, down, right: TBZVector): TBZVector; { @abstract(Implémente une fonction d'étape renvoyant une pour chaque composant de Self qui est       supérieur ou égal au composant correspondant dans la référence du Vecteur B, et zéro si non) Plus d'informations : @br @unorderedlist( @item(http://developer.download.nvidia.com/cg/step.html) @item(https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/step.xhtml )) } function Step(ConstRef B : TBZVector4f):TBZVector4f; { @abstract(Retourne une normale telle quelle si le vecteur de position dans l'espace occulaire d'un sommet pointe dans la direction opposée d'une normale géométrique, sinon renvoie la version inversée de la normale.) Le vecteur courrant représente le vecteur de la normale pertubée. @br Le vecteur A représente un vecteur d'incidence (généralement un vecteur de direction de l'œil vers un sommet) @br Le vecteur B représente le vecteur normal géométrique (pour certaines facettes, la normale péturbée est identique). Plus d'informations : @br @unorderedlist( @item(http://developer.download.nvidia.com/cg/faceforward.html) @item(https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/faceforward.xhtml )) } function FaceForward(constref A, B: TBZVector4f): TBZVector4f; { @abstract(Renvoie le plus petit entier non inférieur à un scalaire ou à chaque composante vectorielle.)      Retourne la valeur de la saturation dans la plage [0,1] comme suit: @br @orderedlist( @item(Retourne 0 si le vecteur courrant est plus petit que 0) @item(Retourne 1 si le vecteur courrant est plus grand que 1) @item(Dans les autres cas retourne les valeurs courrantes.)) Plus d'informations : http://developer.download.nvidia.com/cg/saturate.html ) } function Saturate : TBZVector4f; { @abstract(Interpolation douce entre deux valeurs basé sur le troisième paramètre.) @unorderedlist( @item(Retourne 0 si Self < A < B ou que Self > A > A) @item(Retourne 1 si Self < B < A ou que Self > B > A) @item(La valeur interpolée retournée est comprise dans l'intervalle 0.0 et 1.0 pour le domaina [A,B].)) Si A = Self alors, la pente de Self.smoothstep(a, b) et b.smoothstep(a, b) est nulle.@br Plus d'information : @br @unorderedlist( @item(http://developer.download.nvidia.com/cg/smoothstep.html) @item(https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/smoothstep.xhtml )) } function SmoothStep(ConstRef A,B : TBZVector4f): TBZVector4f; { @name : @param(N : TBZVector4f) @return(TBZVector4f ) } function Reflect(ConstRef N: TBZVector4f): TBZVector4f; // Project3dVectorOnToPlane.cs ////taken from http://answers.unity3d.com/questions/1097270/project-a-vector3-onto-a-plane-orthographically.html ////You simply project your vector onto the normal and subtract the result from your original vector. That will give you the projected vector on the plane. If you want to project a point to a plane you first need to calculate the relative vector from a point on that plane. // // Vector3 planeOrigin; // Vector3 planeNormal; // Vector3 point; // // Vector3 v = point - planeOrigin; // Vector3 d = Vector3.Project(v, planeNormal.normalized); // Vector3 projectedPoint = point - d; { Accès rapide aux propriétés de "Swizzling" comme dans HLSL et GLSL } {@groupbegin} property XY : TBZVector2f read GetXY Write SetXY; property YX : TBZVector2f read GetYX; property XZ : TBZVector2f read GetXZ; property ZX : TBZVector2f read GetZX; property YZ : TBZVector2f read GetYZ; property ZY : TBZVector2f read GetZY; property XX : TBZVector2f read GetXX; property YY : TBZVector2f read GetYY; property ZZ : TBZVector2f read GetZZ; property XYZ : TBZVector4f read GetXYZ; property XZY : TBZVector4f read GetXZY; property YXZ : TBZVector4f read GetYXZ; property YZX : TBZVector4f read GetYZX; property ZXY : TBZVector4f read GetZXY; property ZYX : TBZVector4f read GetZYX; property XXX : TBZVector4f read GetXXX; property YYY : TBZVector4f read GetYYY; property ZZZ : TBZVector4f read GetZZZ; property YYX : TBZVector4f read GetYYX; property XYY : TBZVector4f read GetXYY; property YXY : TBZVector4f read GetYXY; {@groupend} end; {%endregion%} {%region%----[ TBZMatrixHelper ]-----------------------------------------------} { Assistant pour le type TBZMatrix eg : TBZMatrix4f } TBZMatrixHelper = record helper for TBZMatrix public // Create rotation matrix from "Euler angles" (Tait–Bryan angles) Yaw = Y, Pitch = Z, Roll = X (angles in deg) { @name : @param( : ) @param( : ) } // procedure CreateRotationMatrix(angleX, angleY, aangleZ : Single;Const EulerOrder:TBZEulerOrder = eulYZX);overload; // Self is ViewProjMatrix //function Project(Const objectVector: TBZVector; const viewport: TVector4i; out WindowVector: TBZVector): Boolean; //function UnProject(Const WindowVector: TBZVector; const viewport: TVector4i; out objectVector: TBZVector): Boolean; // coordinate system manipulation functions { Retourne la matrice de rotation d'une rotation sur l'axe des Y de angle ( en radian) dans le système de coordonnées définie } function Turn(angle : Single) : TBZMatrix; overload; { Retourne la matrice de rotation d'une rotation sur l'axe des Y en fonction de la direction de l'axe représenté par "MasterUp" de angle ( en radian) dans le système de coordonnées définie } function Turn(constref MasterUp : TBZVector; Angle : Single) : TBZMatrix; overload; { Retourne la matrice de rotation d'une rotation sur l'axe des X de angle ( en radian) dans le système de coordonnées définie } function Pitch(Angle: Single): TBZMatrix; overload; { Retourne la matrice de rotation d'une rotation sur l'axe X en fonction de la direction de l'axe représenté par "MasterRight" de angle ( en radian) dans le système de coordonnées définie } function Pitch(constref MasterRight: TBZVector; Angle: Single): TBZMatrix; overload; { Retourne la matrice de rotation d'une rotation sur l'axe des Z de angle ( en radian) dans le système de coordonnées définie } function Roll(Angle: Single): TBZMatrix; overload; { Retourne la matrice de rotation d'une rotation sur l'axe Z en fonction de la direction de l'axe représenté par "MasterDirection" de angle ( en radian) dans le système de coordonnées définie } function Roll(constref MasterDirection: TBZVector; Angle: Single): TBZMatrix; overload; { @name :Convert matrix to Eulers Angles according Euler Order @br @bold(Note :) Assume matrix is a rotation matrix. @param( : ) @param( : ) @return(TBZ ) } //function ConvertToEulerAngles(Const EulerOrder : TBZEulerOrder):TBZEulerAngles; end; {%endregion%} {%endregion%} {%region%----[ Vectors Const ]-------------------------------------------------} Const { Vecteurs 2D standard } {@groupbegin} NullVector2f : TBZVector2f = (x:0;y:0); OneVector2f : TBZVector2f = (x:1;y:1); NullVector2d : TBZVector2d = (x:0;y:0); OneVector2d : TBZVector2d = (x:1;y:1); NullVector2i : TBZVector2i = (x:0;y:0); OneVector2i : TBZVector2i = (x:1;y:1); {@groupend} { Vecteurs affines 3D standard } {@groupbegin} XVector : TBZAffineVector = (X:1; Y:0; Z:0); YVector : TBZAffineVector = (X:0; Y:1; Z:0); ZVector : TBZAffineVector = (X:0; Y:0; Z:1); XYVector : TBZAffineVector = (X:1; Y:1; Z:0); XZVector : TBZAffineVector = (X:1; Y:0; Z:1); YZVector : TBZAffineVector = (X:0; Y:1; Z:1); XYZVector : TBZAffineVector = (X:1; Y:1; Z:1); NullVector : TBZAffineVector = (X:0; Y:0; Z:0); {@groupend} { Vecteurs homogènes 4D standard } {@groupbegin} XHmgVector : TBZVector = (X:1; Y:0; Z:0; W:0); YHmgVector : TBZVector = (X:0; Y:1; Z:0; W:0); ZHmgVector : TBZVector = (X:0; Y:0; Z:1; W:0); WHmgVector : TBZVector = (X:0; Y:0; Z:0; W:1); NullHmgVector : TBZVector = (X: 0; Y: 0; Z: 0; W: 0); XYHmgVector : TBZVector = (X: 1; Y: 1; Z: 0; W: 0); YZHmgVector : TBZVector = (X: 0; Y: 1; Z: 1; W: 0); XZHmgVector : TBZVector = (X: 1; Y: 0; Z: 1; W: 0); XYZHmgVector : TBZVector = (X: 1; Y: 1; Z: 1; W: 0); XYZWHmgVector : TBZVector = (X: 1; Y: 1; Z: 1; W: 1); {@groupend} { Points standard homogènes 4D} {@groupbegin} XHmgPoint : TBZVector = (X:1; Y:0; Z:0; W:1); YHmgPoint : TBZVector = (X:0; Y:1; Z:0; W:1); ZHmgPoint : TBZVector = (X:0; Y:0; Z:1; W:1); WHmgPoint : TBZVector = (X:0; Y:0; Z:0; W:1); NullHmgPoint : TBZVector = (X:0; Y:0; Z:0; W:1); {@groupend} { Vecteur homogène unitaire négatif } NegativeUnitVector : TBZVector = (X:-1; Y:-1; Z:-1; W:-1); { Constantes de vecteur utiles } {@groupbegin} cNullVector2f : TBZVector2f = (x:0;y:0); cHalfOneVector2f : TBZVector2f = (X:0.5; Y:0.5); cNullVector4f : TBZVector = (x:0;y:0;z:0;w:0); cNullVector4i : TBZVector4i = (x:0;y:0;z:0;w:0); cOneVector4f : TBZVector = (x:1;y:1;z:1;w:1); cOneMinusVector4f : TBZVector = (x:-1;y:-1;z:-1;w:-1); cNegateVector4f_PNPN : TBZVector = (x:1;y:-1;z:1;w:-1); cWOneVector4f : TBZVector = (x:0;y:0;z:0;w:1); cWOneSSEVector4f : TBZVector = (X:0; Y:0; Z:0; W:1); cHalfOneVector4f : TBZVector = (X:0.5; Y:0.5; Z:0.5; W:0.5); // 00800000h,00800000h,00800000h,00800000h {@groupend} {%endregion%} {%region%----[ Matrix Const ]--------------------------------------------------} Const { Matrice homogène d'identité } IdentityHmgMatrix : TBZMatrix = (V:((X:1; Y:0; Z:0; W:0), (X:0; Y:1; Z:0; W:0), (X:0; Y:0; Z:1; W:0), (X:0; Y:0; Z:0; W:1))); { Matrice homogène vide } EmptyHmgMatrix : TBZMatrix = (V:((X:0; Y:0; Z:0; W:0), (X:0; Y:0; Z:0; W:0), (X:0; Y:0; Z:0; W:0), (X:0; Y:0; Z:0; W:0))); {%endregion%} {%region%----[ Quaternion Const ]----------------------------------------------} Const { Quaternion d'identité } IdentityQuaternion: TBZQuaternion = (ImagePart:(X:0; Y:0; Z:0); RealPart: 1); {%endregion%} {%region%----[ SSE Register States and utils funcs ]---------------------------} // Retourne le mode actuel d'arrondissement SIMD function sse_GetRoundMode: sse_Rounding_Mode; // Définit le mode actuel d'arrondissement SIMD procedure sse_SetRoundMode(Round_Mode: sse_Rounding_Mode); {%endregion%} {%region%----[ Vectors Arrays ]------------------------------------------------} Type { Liste dynamique 2D contenant des TBZVector2f } TBZVector2f2DMap = class(specialize TBZArrayMap2DFloat<TBZVector2f>); { Liste dynamique 2D contenant des TBZVector4f } TBZVector4f2DMap = class(specialize TBZArrayMap2DFloat<TBZVector4f>); { Liste dynamique 1D contenant des TBZVector2i } TBZVector2iList = class(specialize TBZArrayInt<TBZVector2i>); { Liste dynamique 1D contenant des TBZVector2f } { TBZVector2fList } TBZVector2fList = class(specialize TBZArrayFloat<TBZVector2f>) protected function CompareValue(Const elem1, elem2) : Integer; override; end; { Liste dynamique 1D contenant des TBZVector3B } TBZVector3bList = class(specialize TBZArrayByte<TBZVector3b>); //TBZVector3iList = class(specialize TBZArrayInt<TBZVector3i>); //TBZVector3fList = class(specialize TBZArrayFloat<TBZVector3f>); { Liste dynamique 1D contenant des TBZVector4b } TBZVector4bList = class(specialize TBZArrayByte<TBZVector4b>); { Liste dynamique 1D contenant des TBZVector4i } TBZVector4iList = class(specialize TBZArrayInt<TBZVector4i>); { Liste dynamique 1D contenant des TBZVector4f } TBZVector4fList = class(specialize TBZArrayFloat<TBZVector4f>); { Type de convenance pour un tableau 1D conteant des TBZVector2f } TBZArrayOfFloatPoints = TBZVector2fList; { Type de convenance pour un tableau 1D conteant des TBZVector2i } TBZArrayOfPoints = TBZVector2iList; // //---- Must be outside here ------------------------ // TBZVectorList = class(TBZVector4fList); // TBZTexCoordList = class(TBZVector2fList); // TBZColorVectorList = class(TBZVector4fList); //Class(TBZColorVectorList) // TBZIndiceList = class(TBZIntegerList); {%endregion%} Implementation Uses Math, BZMath; //, BZLogger; //, BZUtils; {%region%----[ Internal Types and Const ]---------------------------------------} Const { SSE rounding modes (bits in MXCSR register) } cSSE_ROUND_MASK : DWord = $00009FFF; // never risk a stray bit being set in MXCSR reserved cSSE_ROUND_MASK_NEAREST : DWord = $00000000; cSSE_ROUND_MASK_TRUNC : DWord = $00006000; // cSSE_ROUND_MASK_DOWN = $00002000; // cSSE_ROUND_MASK_UP = $00004000; // cNullVector2i : TBZVector2i = (x:0;y:0); {$IFDEF USE_ASM} cSSE_MASK_ABS : array [0..3] of UInt32 = ($7FFFFFFF, $7FFFFFFF, $7FFFFFFF, $7FFFFFFF); cSSE_MASK_NEGATE : array [0..3] of UInt32 = ($80000000, $80000000, $80000000, $80000000); cSSE_MASK_ONE : array [0..3] of UInt32 = ($00000001, $00000001, $00000001, $00000001); cSSE_SIGN_MASK_NPPP : array [0..3] of UInt32 = ($80000000, $00000000, $00000000, $00000000); cSSE_SIGN_MASK_PPPN : array [0..3] of UInt32 = ($00000000, $00000000, $00000000, $80000000); cSSE_SIGN_MASK_NPNP : array [0..3] of UInt32 = ($80000000, $00000000, $80000000, $00000000); cSSE_SIGN_MASK_PNPN : array [0..3] of UInt32 = ($00000000, $80000000, $00000000, $80000000); cSSE_SIGN_MASK_PNNP : array [0..3] of UInt32 = ($00000000, $80000000, $80000000, $00000000); cSSE_MASK_NO_W : array [0..3] of UInt32 = ($FFFFFFFF, $FFFFFFFF, $FFFFFFFF, $00000000); cSSE_MASK_ONLY_W : array [0..3] of UInt32 = ($00000000, $00000000, $00000000, $FFFFFFFF); //cSSE_MASK_NO_XYZ : array [0..3] of UInt32 = ($00000000, $00000000, $00000000, $FFFFFFFF); cSSE_OPERATOR_EQUAL = 0; cSSE_OPERATOR_LESS = 1; cSSE_OPERATOR_LESS_OR_EQUAL = 2; cSSE_OPERATOR_ORDERED = 3; cSSE_OPERATOR_NOT_EQUAL = 4; cSSE_OPERATOR_NOT_LESS = 5; cSSE_OPERATOR_NOT_LESS_OR_EQUAL = 6; cSSE_OPERATOR_NOT_ORDERED = 7; {$ENDIF} const { cEulerOrderRef : Tableau représentant les différents ordre des angles d'Euler } cEulerOrderRef : array [Low(TBZEulerOrder)..High(TBZEulerOrder)] of array [1..3] of Byte = ( (0, 1, 2), (0, 2, 1), (1, 0, 2), // eulXYZ, eulXZY, eulYXZ, (1, 2, 0), (2, 0, 1), (2, 1, 0) ); // eulYZX, eulZXY, eulZYX // ---- Used by ASM Round & Trunc functions ------------------------------------ //var // _bakMXCSR, _tmpMXCSR : DWord; //------------------------------------------------------------------------------ {%endregion%} Var _oldMXCSR: DWord; // FLAGS SSE //-----[ INTERNAL FUNCTIONS ]--------------------------------------------------- function AffineVectorMake(const x, y, z : Single) : TBZAffineVector; inline; begin Result.X:=x; Result.Y:=y; Result.Z:=z; end; { TBZVector2fList } function TBZVector2fList.CompareValue(const elem1, elem2) : Integer; var {$CODEALIGN VARMIN=16} i1 : TBZVector2f absolute elem1; i2 : TBZVector2f absolute elem2; {$CODEALIGN VARMIN=4} begin if (i1.y = i2.y) then begin if (i1.x = i2.x) then Result := 0 else if (i1.x < i2.x) then Result := -1 else Result := 1; end else if (i1.y < i2.y) then Result := -1 else Result := 1; end; //-----[ FUNCTIONS For TBZVector3f ]------------------------------------------- function TBZVector3f.ToString : String; begin Result := '(X: '+FloattoStrF(Self.X,fffixed,5,5)+ ' ,Y: '+FloattoStrF(Self.Y,fffixed,5,5)+ ' ,Z: '+FloattoStrF(Self.Z,fffixed,5,5); end; //-----[ INCLUDE IMPLEMENTATION ]----------------------------------------------- {$ifdef USE_ASM} {$ifdef CPU64} {$ifdef UNIX} {$IFDEF USE_ASM_AVX} {$I vectormath_vector2i_native_imp.inc} {.$I vectormath_vector2i_unix64_avx_imp.inc} {$I vectormath_vector2f_native_imp.inc} {$I vectormath_vector2f_unix64_avx_imp.inc} {$I vectormath_vector2d_native_imp.inc} {$I vectormath_complex_native_imp.inc} {$I vectormath_vector3b_native_imp.inc} {$I vectormath_vector4b_native_imp.inc} {$I vectormath_vector4f_native_imp.inc} {$I vectormath_vector4f_unix64_avx_imp.inc} {$I vectormath_vector4i_native_imp.inc} {$I vectormath_vector4i_unix64_avx_imp.inc} {$I vectormath_quaternion_native_imp.inc} {$I vectormath_quaternion_unix64_avx_imp.inc} {$I vectormath_matrix4f_native_imp.inc} {$I vectormath_matrix4f_unix64_avx_imp.inc} {$I vectormath_matrixhelper_native_imp.inc} {$I vectormath_vectorhelper_native_imp.inc} {$I vectormath_vectorhelper_unix64_avx_imp.inc} {$I vectormath_hmgplane_native_imp.inc} {$I vectormath_hmgplane_unix64_avx_imp.inc} {$ELSE} {$I vectormath_vector2i_native_imp.inc} {$I vectormath_vector2i_unix64_sse_imp.inc} {$I vectormath_vector2f_native_imp.inc} {$I vectormath_vector2f_unix64_sse_imp.inc} {$I vectormath_vector2d_native_imp.inc} {$I vectormath_vector2d_unix64_sse_imp.inc} {$I vectormath_complex_native_imp.inc} {$I vectormath_complex_unix64_sse_imp.inc} {$I vectormath_vector3b_native_imp.inc} {$I vectormath_vector4b_native_imp.inc} {$I vectormath_vector4i_native_imp.inc} {$I vectormath_vector4i_unix64_sse_imp.inc} {$I vectormath_vector4f_native_imp.inc} {$I vectormath_vector4f_unix64_sse_imp.inc} {$I vectormath_quaternion_native_imp.inc} {$I vectormath_quaternion_unix64_sse_imp.inc} {$I vectormath_matrix4f_native_imp.inc} {$I vectormath_matrix4f_unix64_sse_imp.inc} {$I vectormath_matrixhelper_native_imp.inc} {$I vectormath_vector2fhelper_native_imp.inc} {$I vectormath_vector2fhelper_unix64_sse_imp.inc} {$I vectormath_vectorhelper_native_imp.inc} {$I vectormath_vectorhelper_unix64_sse_imp.inc} {$I vectormath_hmgplane_native_imp.inc} {$I vectormath_hmgplane_unix64_sse_imp.inc} {$ENDIF} {$else} // win64 {$IFDEF USE_ASM_AVX} {$I vectormath_vector2i_native_imp.inc} {$I vectormath_vector2i_win64_avx_imp.inc} {$I vectormath_vector2f_native_imp.inc} {$I vectormath_vector2f_win64_avx_imp.inc} {$I vectormath_vector2f_win64_avx_imp.inc} {$I vectormath_vector2d_native_imp.inc} {$I vectormath_complex_native_imp.inc} {$I vectormath_vector3b_native_imp.inc} {$I vectormath_vector4b_native_imp.inc} {$I vectormath_vector4f_native_imp.inc} {$I vectormath_vector4f_win64_avx_imp.inc} {$I vectormath_vector4i_native_imp.inc} {$I vectormath_vector4i_win64_avx_imp.inc} {$I vectormath_quaternion_native_imp.inc} {$I vectormath_quaternion_win64_avx_imp.inc} {$I vectormath_matrix4f_native_imp.inc} {$I vectormath_matrix4f_win64_avx_imp.inc} {$I vectormath_matrixhelper_native_imp.inc} {$I vectormath_vectorhelper_native_imp.inc} {$I vectormath_vectorhelper_win64_avx_imp.inc} {$I vectormath_hmgplane_native_imp.inc} {$I vectormath_hmgplane_win64_avx_imp.inc} {$ELSE} {$I vectormath_vector2i_native_imp.inc} {$I vectormath_vector2i_win64_sse_imp.inc} {$I vectormath_vector2f_native_imp.inc} {$I vectormath_vector2f_win64_sse_imp.inc} {$I vectormath_vector2d_native_imp.inc} {$I vectormath_vector2d_win64_sse_imp.inc} {$I vectormath_complex_native_imp.inc} {$I vectormath_complex_win64_sse_imp.inc} {$I vectormath_vector3b_native_imp.inc} {.$I vectormath_vector3i_native_imp.inc} {.$I vectormath_vector3f_native_imp.inc} {$I vectormath_vector4b_native_imp.inc} {$I vectormath_vector4i_native_imp.inc} {$I vectormath_vector4i_win64_sse_imp.inc} {$I vectormath_vector4f_native_imp.inc} {$I vectormath_vector4f_win64_sse_imp.inc} {$I vectormath_quaternion_native_imp.inc} {$I vectormath_quaternion_win64_sse_imp.inc} {$I vectormath_matrix4f_native_imp.inc} {$I vectormath_matrix4f_win64_sse_imp.inc} {$I vectormath_hmgplane_native_imp.inc} {$I vectormath_hmgplane_win64_sse_imp.inc} {$I vectormath_vector2fhelper_native_imp.inc} {$I vectormath_vector2fhelper_win64_sse_imp.inc} {$I vectormath_vectorhelper_native_imp.inc} {$I vectormath_vectorhelper_win64_sse_imp.inc} {$I vectormath_matrixhelper_native_imp.inc} {.$I vectormath_matrixhelper_win64_sse_imp.inc} {$ENDIF} {$endif} //unix {$else} // CPU32 {$IFDEF USE_ASM_AVX} {$I vectormath_vector2f_native_imp.inc} {$I vectormath_vector2f_intel32_avx_imp.inc} {$I vectormath_vector2d_native_imp.inc} {$I vectormath_complex_native_imp.inc} {$I vectormath_vector3b_native_imp.inc} {$I vectormath_vector4b_native_imp.inc} {$I vectormath_vector4f_native_imp.inc} {$I vectormath_vector4f_intel32_avx_imp.inc} {$I vectormath_vectorhelper_native_imp.inc} {$I vectormath_vectorhelper_intel32_avx_imp.inc} {$I vectormath_hmgplane_native_imp.inc} {$I vectormath_hmgplane_intel32_avx_imp.inc} {$I vectormath_matrix4f_native_imp.inc} {$I vectormath_matrix4f_intel32_avx_imp.inc} {$I vectormath_matrixhelper_native_imp.inc} {$I vectormath_quaternion_native_imp.inc} {$I vectormath_quaternion_intel32_avx_imp.inc} {$ELSE} {$I vectormath_vector2f_native_imp.inc} {$I vectormath_vector2f_intel32_sse_imp.inc} {$I vectormath_vector2d_native_imp.inc} {$I vectormath_complex_native_imp.inc} {$I vectormath_vector3b_native_imp.inc} {$I vectormath_vector4b_native_imp.inc} {$I vectormath_vector4f_native_imp.inc} {$I vectormath_vector4f_intel32_sse_imp.inc} {$I vectormath_vector4i_native_imp.inc} {$I vectormath_vector4i_intel32_sse_imp.inc} {$I vectormath_vectorhelper_native_imp.inc} {$I vectormath_vectorhelper_intel32_sse_imp.inc} {$I vectormath_hmgplane_native_imp.inc} {$I vectormath_hmgplane_intel32_sse_imp.inc} {$I vectormath_matrix4f_native_imp.inc} {$I vectormath_matrix4f_intel32_sse_imp.inc} {$I vectormath_matrixhelper_native_imp.inc} {$I vectormath_quaternion_native_imp.inc} {$I vectormath_quaternion_intel32_sse_imp.inc} {$ENDIF} {$endif} {$else} // pascal {$I vectormath_vector2i_native_imp.inc} {$I vectormath_vector2f_native_imp.inc} {$I vectormath_vector2d_native_imp.inc} {$I vectormath_complex_native_imp.inc} {$I vectormath_vector3b_native_imp.inc} {.$I vectormath_vector3i_native_imp.inc} {.$I vectormath_vector3f_native_imp.inc} {$I vectormath_vector4b_native_imp.inc} {$I vectormath_vector4i_native_imp.inc} {$I vectormath_vector4f_native_imp.inc} {$I vectormath_quaternion_native_imp.inc} {$I vectormath_matrix4f_native_imp.inc} {$I vectormath_matrixhelper_native_imp.inc} {$I vectormath_hmgplane_native_imp.inc} {$I vectormath_vector2fhelper_native_imp.inc} {$I vectormath_vectorhelper_native_imp.inc} {$endif} {%region%----[ SSE Register States and utils Funcs ]----------------------------} function get_mxcsr:dword; var _flags:dword; begin asm stmxcsr _flags end; get_mxcsr:=_flags; end; procedure set_mxcsr(flags:dword); var _flags:dword; begin _flags:=flags; asm ldmxcsr _flags end; end; function sse_GetRoundMode: sse_Rounding_Mode; begin Result := sse_Rounding_Mode((get_MXCSR and (sse_MaskNegRound or sse_MaskPosRound)) shr 13); end; procedure sse_SetRoundMode(Round_Mode: sse_Rounding_Mode); begin set_mxcsr ((get_mxcsr and sse_no_round_bits_mask) {%H-}or sse_Rounding_Flags[Round_Mode] ); end; {%endregion%} //============================================================================== var _oldFPURoundingMode : TFPURoundingMode; initialization { Nous devons définir le mode d'arrondi de FPC sur le même mode que notre code SSE     Dans FPC, la fonction Round utilise l'algorithme 'd'arrondissement du banquier'.     En gros, il ne fait pas de d'arrondissement supérieur ou inférieur si la valeur fractionnel est exactement égale à x.50     Exemple : Round(2.5) = 2 et Round(3.5) = 4 Pour plus infos voir : https://www.freepascal.org/docs-html/rtl/system/round.html } // Store Default FPC "Rounding Mode" _oldFPURoundingMode := GetRoundMode; Math.SetRoundMode(rmNearest); // Store MXCSR SSE Flags _oldMXCSR := get_mxcsr; set_mxcsr (mxcsr_default); finalization // Restore MXCSR SSE Flags to default value set_mxcsr(_oldMXCSR); // Restore Default FPC "Rounding Mode" Math.SetRoundMode(_oldFPURoundingMode); End.
unit VisibleDSA.AlgoVisualizer; interface uses System.Classes, System.SysUtils, System.Types, System.Math, Winapi.Windows, FMX.Graphics, FMX.Forms, VisibleDSA.AlgoVisHelper, VisibleDSA.GameData; type TAlgoVisualizer = class(TObject) public const D: TArr2D_int = [[-1, 0], [0, 1], [1, 0], [0, -1]]; private _width: integer; _height: integer; _data: TGameData; procedure __setData; procedure __desktopCenter(form: TForm); public constructor Create(form: TForm); destructor Destroy; override; procedure Paint(canvas: TCanvas); procedure Run; end; implementation uses VisibleDSA.AlgoForm; { TAlgoVisualizer } constructor TAlgoVisualizer.Create(form: TForm); var blockSide: integer; begin blockSide := 80; _data := TGameData.Create; _width := blockSide * _data.M; _height := blockSide * _data.N; form.ClientWidth := _width; form.ClientHeight := _height; form.Caption := 'Move the Box Solver --- ' + Format('W: %d, H: %d', [_Width, _Height]); __desktopCenter(form); AllocConsole; end; destructor TAlgoVisualizer.Destroy; begin FreeAndNil(_data); FreeConsole; inherited Destroy; end; procedure TAlgoVisualizer.Paint(canvas: TCanvas); //var // w, h: integer; // i, j: integer; // str: UString; // stm: TResourceStream; begin // w := _width div _data.M; // h := _height div _data.N; // // for i := 0 to _data.N - 1 do // begin // for j := 0 to _data.M - 1 do // begin // if _data.Mines[i, j] then // str := TGameData.PNG_MINE // else // str := TGameData.PNG_BLOCK; // // stm := TResourceStream.Create(HINSTANCE, str, RT_RCDATA); // TAlgoVisHelper.DrawImageFormResourceStream(canvas, stm, j * w, i * h, w, h); // end; // end; end; procedure TAlgoVisualizer.Run; begin _data.PrintStarterBoard; end; procedure TAlgoVisualizer.__setData; begin // if finished or (_runningStatus >= 5) then // begin // TAlgoVisHelper.Pause(0); // AlgoForm.PaintBox.Repaint; // _runningStatus := 0; // end // else // begin // _runningStatus := _runningStatus + 1; // end; end; procedure TAlgoVisualizer.__desktopCenter(form: TForm); var top, left: Double; begin top := (Screen.Height div 2) - (form.ClientHeight div 2); left := (Screen.Width div 2) - (form.ClientWidth div 2); form.top := Trunc(top); form.left := Trunc(left); 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/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: MTSync.pas, released on 2000-09-22. The Initial Developer of the Original Code is Erwin Molendijk. Portions created by Erwin Molendijk are Copyright (C) 2002 Erwin Molendijk. All Rights Reserved. Contributor(s): ______________________________________. You may retrieve the latest version of this file at the Project JEDI home page, located at http://www.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id: JvMTSync.pas 12833 2010-09-05 13:25:12Z obones $ unit JvMTSync; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} SysUtils, Classes, SyncObjs, {$IFDEF MSWINDOWS} Windows, {$ENDIF MSWINDOWS} {$IFDEF HAS_UNIT_LIBC} Libc, {$ENDIF HAS_UNIT_LIBC} JvMTConsts; type TMTSynchroObject = class(TSynchroObject) private FHandle: THandle; FLastError: Integer; FName: string; protected function CreateHandle: THandle; virtual; abstract; public constructor Create(Name: string = ''); destructor Destroy; override; procedure Acquire; override; procedure Release; override; procedure Signal; procedure Wait; function WaitFor(Timeout: LongWord): Boolean; {$IFDEF RTL220_UP}reintroduce;{$ENDIF RTL220_UP} virtual; property Handle: THandle read FHandle; property LastError: Integer read FLastError; property Name: string read FName; end; TMTSimpleEvent = class(TMTSynchroObject) protected function CreateHandle: THandle; override; public procedure Release; override; procedure SetEvent; procedure ResetEvent; end; TMTSemaphore = class(TMTSynchroObject) private FInitialCount: Integer; FMaximumCount: Integer; protected function CreateHandle: THandle; override; public constructor Create(InitialCount, MaximumCount: Integer; Name: string = ''); procedure Release; override; end; TMTMutex = class(TMTSemaphore) public constructor Create(Name: string = ''); procedure Enter; procedure Leave; end; TMTCriticalSection = class(TMTMutex) private FOwnerThread: TObject; FSelfCount: Integer; public procedure Release; override; function WaitFor(Timeout: LongWord): Boolean; override; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvMTSync.pas $'; Revision: '$Revision: 12833 $'; Date: '$Date: 2010-09-05 15:25:12 +0200 (dim. 05 sept. 2010) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses JvResources, JvMTThreading; //=== { TMTSemaphore } ======================================================= constructor TMTSynchroObject.Create(Name: string); begin inherited Create; if Name = '' then FName := ClassName else FName := Name; FHandle := CreateHandle; end; destructor TMTSynchroObject.Destroy; begin CloseHandle(FHandle); inherited Destroy; end; procedure TMTSynchroObject.Acquire; var OldName: string; begin // first wait for 500 ms if not WaitFor(500) then begin // still not succeeded: change the name of the thread and wait again if CurrentMTThread <> nil then begin OldName := CurrentMTThread.Name; CurrentMTThread.Name := OldName + '.' + FName + '.Wait'; end; try WaitFor(INFINITE); // this time, wait forever (ETerminate can be raised though) finally if CurrentMTThread <> nil then CurrentMTThread.Name := OldName; end; end; end; procedure TMTSynchroObject.Release; begin // ReleaseSemaphore(FHandle, 1, nil); end; procedure TMTSynchroObject.Signal; begin Release; end; procedure TMTSynchroObject.Wait; begin Acquire; end; { WaitFor() Wait for the semaphore to become signalled or the for the timeout time to pass. If the Thread is terminated before or during the waiting, an EMTTerminateError exception will be raised. The exception will only be raised if the semaphore was not signalled during the wait. This will ensure that the caller can take appropriate measures to return the semaphore to the appropriate state before terminating the thread. } function TMTSynchroObject.WaitFor(Timeout: LongWord): Boolean; var HandleArray: array [0..1] of THandle; begin Result := False; if CurrentMTThread <> nil then begin {MT thread} // don't wait if we are already terminated // because we don't want to take the risk of getting the // semaphore in that case. CurrentMTThread.CheckTerminate; // setup the handle array. // the semphore has priority over the terminate signal // because if we get the semaphore we must not raise an EMTTerminateError HandleArray[0] := FHandle; HandleArray[1] := CurrentMTThread.TerminateSignal; // perform the wait case WaitForMultipleObjects(2, @HandleArray[0], False, Timeout) of WAIT_FAILED: begin FLastError := GetLastError; raise EMTThreadError.CreateResFmt(@RsESemaphoreFailure, [FLastError]); end; WAIT_TIMEOUT: Result := False; WAIT_OBJECT_0: Result := True; WAIT_OBJECT_0 + 1: CurrentMTThread.CheckTerminate; // do raise EMTTerminateError WAIT_ABANDONED: raise EMTTerminateError.CreateRes(@RsESemaphoreAbandoned); WAIT_ABANDONED + 1: raise EMTTerminateError.CreateRes(@RsEThreadAbandoned); end; end else begin {main VCL thread} // perform the wait without checking the TerminateSignal since the // main VCL thread does not have such a signal case WaitForSingleObject(FHandle, Timeout) of WAIT_OBJECT_0: Result := True; WAIT_ABANDONED: raise EMTTerminateError.CreateRes(@RsESemaphoreAbandoned); WAIT_TIMEOUT: Result := False; WAIT_FAILED: begin FLastError := GetLastError; raise EMTThreadError.CreateRes(@RsESemaphoreFailure); end; end; end; end; //=== { TMTSemaphore } ======================================================= constructor TMTSemaphore.Create(InitialCount, MaximumCount: Integer; Name: string); begin FInitialCount := InitialCount; FMaximumCount := MaximumCount; inherited Create(Name); end; function TMTSemaphore.CreateHandle: THandle; begin Result := CreateSemaphore(nil, FInitialCount, FMaximumCount, ''); end; procedure TMTSemaphore.Release; begin ReleaseSemaphore(FHandle, 1, nil); end; //=== { TMTMutex } =========================================================== constructor TMTMutex.Create(Name: string = ''); begin inherited Create(1, 1); end; procedure TMTMutex.Enter; begin Acquire; end; procedure TMTMutex.Leave; begin Release; end; //=== { TMTCriticalSection } ================================================= procedure TMTCriticalSection.Release; begin Dec(FSelfCount); if FSelfCount = 0 then begin FOwnerThread := nil; inherited Release; end; end; function TMTCriticalSection.WaitFor(Timeout: LongWord): Boolean; begin if CurrentMTThread <> FOwnerThread then begin Result := inherited WaitFor(Timeout); if Result then begin FOwnerThread := CurrentMTThread; FSelfCount := 1; end; end else begin Result := True; Inc(FSelfCount); end; end; //=== { TMTSimpleEvent } ===================================================== function TMTSimpleEvent.CreateHandle: THandle; begin Result := CreateEvent(nil, True, False, ''); end; procedure TMTSimpleEvent.Release; begin SetEvent; end; procedure TMTSimpleEvent.ResetEvent; begin Windows.ResetEvent(FHandle); end; procedure TMTSimpleEvent.SetEvent; begin Windows.SetEvent(FHandle); end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit caTimer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, MMSystem; type TcaTimer = class; //--------------------------------------------------------------------------- // TcaTimerThread //--------------------------------------------------------------------------- TcaTimerThread = class(TThread) private FTimer: TcaTimer; protected procedure DoExecute; public constructor CreateTimerThread(Timer: TcaTimer); procedure Execute; override; end; //--------------------------------------------------------------------------- // TcaTimer //--------------------------------------------------------------------------- TcaTimer = class(TComponent) private FInterval: Integer; FPriority: TThreadPriority; FOnTimer: TNotifyEvent; FContinue: Boolean; FRunning: Boolean; FEnabled: Boolean; procedure SetEnabled(Value: Boolean ); protected procedure StartTimer; procedure StopTimer; property Continue: Boolean read FContinue write FContinue; public constructor Create(Owner: TComponent); override; procedure On; procedure Off; published property Enabled: Boolean read FEnabled write SetEnabled; property Interval: Integer read FInterval write FInterval; property ThreadPriority: TThreadPriority read FPriority write FPriority default tpNormal; property OnTimer: TNotifyEvent read FOnTimer write FOnTimer; end; procedure Register; implementation procedure Register; begin RegisterComponents('System', [TcaTimer]); end; //----------------------------------------------------------------------------- // TcaTimerThread //----------------------------------------------------------------------------- constructor TcaTimerThread.CreateTimerThread(Timer: TcaTimer); begin inherited Create(True); FTimer := Timer; FreeOnTerminate := True; end; procedure TcaTimerThread.Execute; var SleepTime, Last: Integer; begin while FTimer.Continue do begin Last := timeGetTime; Synchronize(DoExecute); SleepTime := FTimer.FInterval - (timeGetTime - Last); if SleepTime < 10 then SleepTime := 10; Sleep(SleepTime); end; end; procedure TcaTimerThread.DoExecute; begin if Assigned(FTimer.OnTimer) then FTimer.OnTimer(FTimer); end; //----------------------------------------------------------------------------- // TcaTimer //----------------------------------------------------------------------------- constructor TcaTimer.Create(Owner: TComponent); begin inherited; FPriority := tpNormal; end; procedure TcaTimer.SetEnabled(Value: Boolean); begin if Value <> FEnabled then begin FEnabled := Value; if FEnabled then StartTimer else StopTimer; end; end; procedure TcaTimer.StartTimer; begin if FRunning then Exit; FContinue := True; if not (csDesigning in ComponentState) then begin with TcaTimerThread.CreateTimerThread(Self) do begin Priority := FPriority; Resume; end; end; FRunning := True; end; procedure TcaTimer.StopTimer; begin FContinue := False; FRunning := False; end; procedure TcaTimer.On; begin StartTimer; end; procedure TcaTimer.Off; begin StopTimer; end; end.
//Copyright by Victor Derevyanko, dvpublic0@gmail.com //http://derevyanko.blogspot.com/2010/10/blog-post.html //http://code.google.com/p/dvsrc/ //{$Id$} unit FastFilter; interface uses Windows, SysUtils, DB, ExtCtrls, ComCtrls, Classes, StrUtils, StdCtrls, Graphics; type TFastFilter = class public //search text entries in fields of srcDs class function OnFilterRecord(const filterText: String; srcDs: TDataSet): Boolean; overload; //all fields class function OnFilterRecord(const filterText: String; srcDs: TDataSet; srcFields: array of String): Boolean; overload; //only selected fields class procedure OnTimer(const filterText: String; srcDs: TDataSet; timerFilter: TTimer); class procedure OnFilterChange(const filterText: String; srcDs: TDataSet; timerFilter: TTimer); class function OnPressKeyInFilter(const srcKey: Dword; srcDs: TDataSet; const filterText: String; timerFilter: TTimer): Boolean; class procedure InitializeFilter(edFilter: TEdit; timerFilter: TTimer); //helper function to make appearance of all filter edit boxes same private class function pos_case_insensitive(const subStrUpperCased, srcS: string): Boolean; //первый аргумент предполагается в UpperCase end; //common implementation of the filter for TEdit TFastFilterCommon = class public constructor Create(const edFilter: TEdit; srcDs: TDataSet); overload; constructor Create(const edFilter: TEdit; srcDs: TDataSet; srcFields: array of String); overload; destructor Destroy; override; private procedure initialize(const edFilter: TEdit; srcDs: TDataSet); procedure on_filter_change(Sender: TObject); procedure on_timer(Sender: TObject); procedure on_filter_record(DataSet: TDataSet; var Accept: Boolean); procedure on_filter_keydown(Sender: TObject; var Key: Word; Shift: TShiftState); private m_Edit: TEdit; m_Ds: TDataSet; m_Timer: TTimer; m_Fields: array of String; end; implementation const COLOR_FILTER_BOX = clMoneyGreen; //all filters can be highlighted by same color DEFAULT_STRING_FIELD_SIZE = 200; DEFAULT_FILTER_TIMER_DELAY_MS = 1000; DEFAULT_FILTER_TOOLTIP = 'Use Ctrl+Enter to execute filter manually'; class procedure TFastFilter.OnTimer(const filterText: String; srcDs: TDataSet; timerFilter: TTimer); begin //executes filter by timer and turns timer off timerFilter.Enabled := false; if filterText <> '' then begin srcDs.Filtered := false; srcDs.Filtered := true; end else begin srcDs.Filtered := false; end; end; class function TFastFilter.OnFilterRecord(const filterText: String; srcDs: TDataSet): Boolean; var text: String; i: Integer; begin //record is accepted if at least one field contains specified text text := AnsiUpperCase(filterText); Result := false; for i := 0 to srcDs.FieldCount-1 do begin if pos_case_insensitive(text, srcDs.Fields[i].DisplayText) then begin Result := true; break; end; end; end; class function TFastFilter.OnFilterRecord(const filterText: String; srcDs: TDataSet; srcFields: array of String): Boolean; var text: String; i: Integer; begin //record is approved if at least one of selected fields contains specified text text := AnsiUpperCase(filterText); Result := false; for i := Low(srcFields) to High(srcFields) do begin if pos_case_insensitive(text, srcDs.FieldByName(srcFields[i]).DisplayText) then begin Result := true; break; end; end; end; class procedure TFastFilter.OnFilterChange(const filterText: String; srcDs: TDataSet; timerFilter: TTimer); begin //execute timer after any modification of filter string //if user won't press key during timer interfal then filtration will be executed automatically timerFilter.Enabled := false; timerFilter.Enabled := true; if filterText = '' then begin srcDs.Filtered := false; end; end; class function TFastFilter.OnPressKeyInFilter(const srcKey: Dword; srcDs: TDataSet; const filterText: String; timerFilter: TTimer): Boolean; begin //allows user to change dataset position directly from filter edit box using Up and Down keys Result := true; if srcKey = VK_UP then srcDs.Prior else if srcKey = VK_DOWN then srcDs.Next else if (srcKey = VK_RETURN) then OnTimer(filterText, srcDs, timerFilter) else Result := false; end; class function TFastFilter.pos_case_insensitive(const subStrUpperCased, srcS: string): Boolean; begin if Length(subStrUpperCased) > Length(srcS) then Result := false else Result := AnsiPos(subStrUpperCased, AnsiUpperCase(srcS)) <> 0; //!TODO: до тех пор, пока нет нормальной реализации ansi_posiex //первый аргумент рассматриваем как уже приведенный к upper case //все функции OnFilterRecordXXX приводят его перед вызовом pos_case_insensitive end; class procedure TFastFilter.InitializeFilter(edFilter: TEdit; timerFilter: TTimer); begin //helper function to make all filter edit boxes "same" edFilter.Color := COLOR_FILTER_BOX; timerFilter.Interval := DEFAULT_FILTER_TIMER_DELAY_MS; edFilter.Hint := DEFAULT_FILTER_TOOLTIP; edFilter.ShowHint := true; end; /////////////////////////////////////////////////////////////////////////////// // simple implementation of the filter for TEdit constructor TFastFilterCommon.Create(const edFilter: TEdit; srcDs: TDataSet); begin initialize(edFilter, srcDs); end; constructor TFastFilterCommon.Create(const edFilter: TEdit; srcDs: TDataSet; srcFields: array of String); var i: Integer; begin initialize(edFilter, srcDs); SetLength(m_Fields, Length(srcFields)); for i := 0 to Length(srcFields)-1 do m_Fields[i] := srcFields[i]; end; procedure TFastFilterCommon.initialize(const edFilter: TEdit; srcDs: TDataSet); begin m_Edit := edFilter; m_Edit.ShowHint := true; m_Edit.Hint := DEFAULT_FILTER_TOOLTIP; m_Ds := srcDs; m_Timer := TTimer.Create(edFilter.Parent); m_Timer.Interval := DEFAULT_FILTER_TIMER_DELAY_MS; m_Timer.Enabled := false; assert(not assigned(m_Edit.OnChange)); m_Edit.OnChange := on_filter_change; assert(not assigned(m_Ds.OnFilterRecord)); m_Ds.OnFilterRecord := on_filter_record; assert(not assigned(m_Edit.OnKeyDown)); m_Edit.OnKeyDown := on_filter_keydown; m_Timer.OnTimer := on_timer; end; destructor TFastFilterCommon.Destroy; begin m_Timer.Free; inherited; end; procedure TFastFilterCommon.on_filter_change(Sender: TObject); begin TFastFilter.OnFilterChange(m_Edit.Text, m_Ds, m_Timer) end; procedure TFastFilterCommon.on_filter_keydown(Sender: TObject; var Key: Word; Shift: TShiftState); begin TFastFilter.OnPressKeyInFilter(Key, m_Ds, m_Edit.Text, m_Timer); end; procedure TFastFilterCommon.on_filter_record(DataSet: TDataSet; var Accept: Boolean); var list: TStringList; i: Integer; begin list := TStringList.Create; try ExtractStrings([' '], [], PChar(m_Edit.Text), list); for i := 0 to list.Count - 1 do begin if Length(m_Fields) = 0 then Accept := TFastFilter.OnFilterRecord(Trim(list[i]), m_Ds) else Accept := TFastFilter.OnFilterRecord(Trim(list[i]), m_Ds, m_Fields); if Accept then break; end; finally list.Free; end; end; procedure TFastFilterCommon.on_timer(Sender: TObject); begin TFastFilter.OnTimer(m_Edit.Text, m_Ds, m_Timer); end; end.
namespace Sugar.TestFramework; interface type SugarTestException = public class({$IF NOUGAT}Foundation.NSException{$ELSE}Exception{$ENDIF}) public constructor (aMessage: String); {$IF NOUGAT} property Message: String read reason; {$ENDIF} end; implementation constructor SugarTestException(aMessage: String); begin {$IF NOUGAT} result := inherited initWithName('SugarTestException') reason(aMessage) userInfo(nil); {$ELSE} inherited constructor(aMessage); {$ENDIF} end; end.
unit CepUtils; interface uses SysUtils, Variants, Classes, MyStrUtils, URLUtils; type TEndereco = class private FCep: string; FLogradouro: string; FBairro: string; FCidade: string; FUf: string; FCodigoIbge: string; procedure SetCep(Avalue: string); procedure GetCep(const Value: string); public constructor Create; overload; constructor Create(cep: String); overload; procedure BuscarCep; published property Cep: string read FCep write SetCep; property Logradouro: string read FLogradouro write FLogradouro; property Bairro: string read FBairro write FBairro; property Cidade: string read FCidade write FCidade; property Uf: string read FUf write FUf; property CodigoIbge: string read FCodigoIbge write FCodigoIbge; end; function FormataCep(cep: string): string; implementation uses IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP; function FormataCep(cep: string): string; begin Result := ''; cep := SomenteNumeros(cep); if cep <> '' then Result := Format('%s.%s-%s',[Copy(cep, 1,2), Copy(cep, 3,3), Copy(cep,6,3)]) end; { TEndereco } constructor TEndereco.Create; begin FCep := ''; FLogradouro := ''; FBairro := ''; FCidade := ''; FUf := ''; FCodigoIbge := ''; end; procedure TEndereco.BuscarCep; function BuscaViaCep: string; var stmResponse : TStringStream; lURL : String; begin try stmResponse := TStringStream.Create(''); lURL := Format('http://viacep.com.br/ws/%s/xml/', [FCep]); with TIdHTTP.Create(nil) do begin AllowCookies := True; ProxyParams.BasicAuthentication := False; ProxyParams.ProxyPort := 0; Request.ContentLength := -1; Request.ContentRangeEnd := 0; Request.ContentRangeStart := 0; Request.ContentRangeInstanceLength := 0; Request.Accept := 'text/html, */*'; Request.BasicAuthentication := False; Request.ContentEncoding := 'ISO-8859-1'; Request.AcceptCharSet := 'ISO-8859-1'; Response.ContentEncoding := 'ISO-8859-1'; Request.UserAgent := 'Mozilla/3.0 (compatible; Indy Library)'; HTTPOptions := [hoForceEncodeParams]; Get(lURL, stmResponse); end; stmResponse.Position := 0; Result := StreamToString(stmResponse); finally FreeAndNil(stmResponse); end; end; var stmResponse : TStringStream; lURL, response : String; begin response := URLDecode(BuscaViaCep); if (ExtractStr(response, '<erro>', '</erro>') = 'true') then raise exception.create('CEP não encontrado'); FLogradouro := ExtractStr(response, '<logradouro>', '</logradouro>'); FBairro := ExtractStr(response, '<bairro>', '</bairro>'); FCidade := ExtractStr(response, '<localidade>', '</localidade>'); FUf := ExtractStr(response, '<uf>', '</uf>'); FCodigoIbge := ExtractStr(response, '<ibge>', '</ibge>'); end; constructor TEndereco.Create(cep: String); begin Create; FCep := SomenteNumeros(cep); BuscarCep; end; procedure TEndereco.GetCep(const Value: string); begin FCep := Value; end; procedure TEndereco.SetCep(AValue: string); begin FCep := SomenteNumeros(AValue); end; end.
unit math; interface type bit = 0..1; arbittype = array[1..8] of bit; arbittype2= array[1..4]of bit; var arbit:arbittype; function PowO{rdinal}(x,y:longint):longint; function pow(x,y:real):real;{X^Y} procedure BitofByte(val:byte); function ByteOfBitSet(a:arbittype):byte; function Conc2Bytes(v1,v2:byte):byte; implementation {$I-} uses crt; var ifnine:bit; counter,b:byte; sum:integer; par:^arbittype; (********************************************) function powo(x,y:longint):longint; begin powo:=round(exp(y*ln(x))); end; (********************************************) function pow(x,y:real):real; begin pow:=exp(y*ln(x)) end; (********************************************) procedure bitofbyte(val:byte){:parbit}; begin sum:=0; {arbit9[9]:=0;} for counter:=8 downto 1 do begin if counter=8 then ifnine:=0 else ifnine:=arbit[counter+1]; sum:=sum+ifnine{arbit9[counter+1]}*powo(2,counter); arbit[counter]:=trunc( (val-sum)/powo(2,counter-1) ); end; {for counter:=1 to 8 do {bitofbyte^[9-counter]:=arbit9[counter]} end; (********************************************) function byteofbitset(a:arbittype):byte; begin b:=0; for counter:=1 to 8 do b:=b+a[counter]*powo(2,8-counter); byteofbitset:=b end; (********************************************) function Conc2Bytes(v1,v2:byte):byte; var ar1,ar2:arbittype; begin bitofbyte(v1); for counter:=1 to 4 do ar1[5-counter]:=arbit[counter]; bitofbyte(v2); for counter:=1 to 4 do ar2[5-counter]:=arbit[counter]; new(par); for counter:=1 to 4 do par^[counter]:=ar1[counter]; for counter:=1 to 4 do par^[counter+4]:=ar2[counter]; Conc2Bytes:=byteofbitset(par^); {i:=0; for counter:=1 to sizeof(par^) do if par^[counter]=1 then begin i:=i+1; end; {dispose(par);} end; BEGIN END.
{******************************************************************************* 作者: dmzn@163.com 2013-12-04 描述: 模块业务对象 *******************************************************************************} unit UWorkerHardware; {$I Link.Inc} interface uses Windows, Classes, Controls, DB, SysUtils, UBusinessWorker, UBusinessPacker, UBusinessConst, UMgrDBConn, UMgrParam, ZnMD5, ULibFun, UFormCtrl, USysLoger, USysDB, UMITConst; type THardwareDBWorker = class(TBusinessWorkerBase) protected FErrNum: Integer; //错误码 FDBConn: PDBWorker; //数据通道 FDataIn,FDataOut: PBWDataBase; //入参出参 FDataOutNeedUnPack: Boolean; //需要解包 procedure GetInOutData(var nIn,nOut: PBWDataBase); virtual; abstract; //出入参数 function VerifyParamIn(var nData: string): Boolean; virtual; //验证入参 function DoDBWork(var nData: string): Boolean; virtual; abstract; function DoAfterDBWork(var nData: string; nResult: Boolean): Boolean; virtual; //数据业务 public function DoWork(var nData: string): Boolean; override; //执行业务 procedure WriteLog(const nEvent: string); //记录日志 end; THardwareCommander = class(THardwareDBWorker) private FListA,FListB,FListC: TStrings; //list FIn: TWorkerBusinessCommand; FOut: TWorkerBusinessCommand; protected procedure GetInOutData(var nIn,nOut: PBWDataBase); override; function DoDBWork(var nData: string): Boolean; override; //base funciton function ExecuteSQL(var nData: string): Boolean; //执行SQL语句 function TruckProbe_IsTunnelOK(var nData: string): Boolean; function TruckProbe_TunnelOC(var nData: string): Boolean; //车辆检测控制器业务 function RemotePrint(var nData: string): Boolean; //远程打印服务 public constructor Create; override; destructor destroy; override; //new free function GetFlagStr(const nFlag: Integer): string; override; class function FunctionName: string; override; //base function class function CallMe(const nCmd: Integer; const nData,nExt: string; const nOut: PWorkerBusinessCommand): Boolean; //local call end; implementation uses UTaskMonitor, UMgrRemotePrint, UMgrTruckProbeOPC; //Date: 2012-3-13 //Parm: 如参数护具 //Desc: 获取连接数据库所需的资源 function THardwareDBWorker.DoWork(var nData: string): Boolean; begin Result := False; FDBConn := nil; with gParamManager.ActiveParam^ do try FDBConn := gDBConnManager.GetConnection(FDB.FID, FErrNum); if not Assigned(FDBConn) then begin nData := '连接数据库失败(DBConn Is Null).'; Exit; end; if not FDBConn.FConn.Connected then FDBConn.FConn.Connected := True; //conn db FDataOutNeedUnPack := True; GetInOutData(FDataIn, FDataOut); FPacker.UnPackIn(nData, FDataIn); with FDataIn.FVia do begin FUser := gSysParam.FAppFlag; FIP := gSysParam.FLocalIP; FMAC := gSysParam.FLocalMAC; FTime := FWorkTime; FKpLong := FWorkTimeInit; end; {$IFDEF DEBUG} WriteLog('Fun: '+FunctionName+' InData:'+ FPacker.PackIn(FDataIn, False)); {$ENDIF} if not VerifyParamIn(nData) then Exit; //invalid input parameter FPacker.InitData(FDataOut, False, True, False); //init exclude base FDataOut^ := FDataIn^; Result := DoDBWork(nData); //execute worker if Result then begin if FDataOutNeedUnPack then FPacker.UnPackOut(nData, FDataOut); //xxxxx Result := DoAfterDBWork(nData, True); if not Result then Exit; with FDataOut.FVia do FKpLong := GetTickCount - FWorkTimeInit; nData := FPacker.PackOut(FDataOut); {$IFDEF DEBUG} WriteLog('Fun: '+FunctionName+' OutData:'+ FPacker.PackOut(FDataOut, False)); {$ENDIF} end else DoAfterDBWork(nData, False); finally gDBConnManager.ReleaseConnection(FDBConn); end; end; //Date: 2012-3-22 //Parm: 输出数据;结果 //Desc: 数据业务执行完毕后的收尾操作 function THardwareDBWorker.DoAfterDBWork(var nData: string; nResult: Boolean): Boolean; begin Result := True; end; //Date: 2012-3-18 //Parm: 入参数据 //Desc: 验证入参数据是否有效 function THardwareDBWorker.VerifyParamIn(var nData: string): Boolean; begin Result := True; end; //Desc: 记录nEvent日志 procedure THardwareDBWorker.WriteLog(const nEvent: string); begin gSysLoger.AddLog(THardwareDBWorker, FunctionName, nEvent); end; //------------------------------------------------------------------------------ class function THardwareCommander.FunctionName: string; begin Result := sBus_HardwareCommand; end; constructor THardwareCommander.Create; begin FListA := TStringList.Create; FListB := TStringList.Create; FListC := TStringList.Create; inherited; end; destructor THardwareCommander.destroy; begin FreeAndNil(FListA); FreeAndNil(FListB); FreeAndNil(FListC); inherited; end; function THardwareCommander.GetFlagStr(const nFlag: Integer): string; begin Result := inherited GetFlagStr(nFlag); case nFlag of cWorker_GetPackerName : Result := sBus_BusinessCommand; end; end; procedure THardwareCommander.GetInOutData(var nIn,nOut: PBWDataBase); begin nIn := @FIn; nOut := @FOut; FDataOutNeedUnPack := False; end; //Date: 2012-3-22 //Parm: 输入数据 //Desc: 执行nData业务指令 function THardwareCommander.DoDBWork(var nData: string): Boolean; begin with FOut.FBase do begin FResult := True; FErrCode := 'S.00'; FErrDesc := '业务执行成功.'; end; case FIn.FCommand of cBC_RemoteExecSQL : Result := ExecuteSQL(nData); cBC_RemotePrint : Result := RemotePrint(nData); cBC_IsTunnelOK : Result := TruckProbe_IsTunnelOK(nData); cBC_TunnelOC : Result := TruckProbe_TunnelOC(nData); else begin Result := False; nData := '无效的业务代码(Invalid Command).'; end; end; end; //Desc: 执行SQL语句 function THardwareCommander.ExecuteSQL(var nData: string): Boolean; var nInt: Integer; begin Result := True; nInt := gDBConnManager.WorkerExec(FDBConn, PackerDecodeStr(FIn.FData)); FOut.FData := IntToStr(nInt); end; //Desc: 执行远程打印 function THardwareCommander.RemotePrint(var nData: string): Boolean; begin Result := True; if Length(Trim(FIn.FExtParam)) < 1 then Exit; gRemotePrinter.PrintBill(FIn.FData + #9 + Trim(FIn.FExtParam)); end; //Date: 2014-10-01 //Parm: 通道号[FIn.FData] //Desc: 获取指定通道的光栅状态 function THardwareCommander.TruckProbe_IsTunnelOK(var nData: string): Boolean; begin Result := True; if not Assigned(gProberOPCManager) then begin FOut.FData := sFlag_Yes; Exit; end; if gProberOPCManager.IsTunnelOK(FIn.FData) then FOut.FData := sFlag_Yes else FOut.FData := sFlag_No; nData := Format('IsTunnelOK -> %s:%s', [FIn.FData, FOut.FData]); WriteLog(nData); end; //Date: 2014-10-01 //Parm: 通道号[FIn.FData];开合[FIn.FExtParam] //Desc: 开合指定通道 function THardwareCommander.TruckProbe_TunnelOC(var nData: string): Boolean; begin Result := True; if not Assigned(gProberOPCManager) then Exit; if FIn.FExtParam = sFlag_Yes then gProberOPCManager.OpenTunnel(FIn.FData) else gProberOPCManager.CloseTunnel(FIn.FData); nData := Format('TunnelOC -> %s:%s', [FIn.FData, FIn.FExtParam]); WriteLog(nData); end; //Date: 2014-09-15 //Parm: 命令;数据;参数;输出 //Desc: 本地调用业务对象 class function THardwareCommander.CallMe(const nCmd: Integer; const nData, nExt: string; const nOut: PWorkerBusinessCommand): Boolean; var nStr: string; nIn: TWorkerBusinessCommand; nPacker: TBusinessPackerBase; nWorker: TBusinessWorkerBase; begin nPacker := nil; nWorker := nil; try nIn.FCommand := nCmd; nIn.FData := nData; nIn.FExtParam := nExt; nPacker := gBusinessPackerManager.LockPacker(sBus_BusinessCommand); nPacker.InitData(@nIn, True, False); //init nStr := nPacker.PackIn(@nIn); nWorker := gBusinessWorkerManager.LockWorker(FunctionName); //get worker Result := nWorker.WorkActive(nStr); if Result then nPacker.UnPackOut(nStr, nOut) else nOut.FData := nStr; finally gBusinessPackerManager.RelasePacker(nPacker); gBusinessWorkerManager.RelaseWorker(nWorker); end; end; initialization gBusinessWorkerManager.RegisteWorker(THardwareCommander, sPlug_ModuleHD); end.
unit vEdit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VirtualTrees, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, System.ImageList, Vcl.ImgList, System.Generics.Collections, API_MVC_VCL, API_ORM_BindVCL, eExtLink, eMediaFile, eVideoFile, eVideoMovie; type TSectionRootNode = class public Caption: string; end; TViewEdit = class(TViewVCLBase) vstLibrary: TVirtualStringTree; vstSearchResults: TVirtualStringTree; btnOK: TButton; btnCancel: TButton; vstFiles: TVirtualStringTree; btnSearch: TButton; bcVideoReleaseTypeID: TComboBox; procedure FormShow(Sender: TObject); procedure vstLibraryGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure vstSearchResultsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure vstSearchResultsInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure vstSearchResultsMeasureItem(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; var NodeHeight: Integer); procedure vstSearchResultsDrawText(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; const Text: string; const CellRect: TRect; var DefaultDraw: Boolean); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure vstLibraryFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); procedure vstFilesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); procedure btnSearchClick(Sender: TObject); procedure vstSearchResultsClick(Sender: TObject); private { Private declarations } FAudioRootNode: TSectionRootNode; FBind: TORMBind; FMediaFileList: TMediaFileList; FSelectedSearchResArr: TExtMovieSearchArr; FSearchResPicDic: TObjectDictionary<Integer, TImage>; FVideoRootNode: TSectionRootNode; function GetAudioNode: PVirtualNode; function GetSelectedMovie: TMovie; function GetSelectedSearchResult: TExtMovieSearchResult; function GetVideoNode: PVirtualNode; procedure CreateAudioNodeIfNotExist; procedure CreateVideoNodeIfNotExist; procedure RenderFile(aMediaFile: TMediaFile); public { Public declarations } procedure RenderMediaFile(aMediaFile: TMediaFile); procedure RenderSearchRes(aExtMovieSearchArr: TExtMovieSearchArr); procedure RenderSearchResPic(aPicData: TBytes; const aSearchResID: Integer); procedure RenderVideoReleaseTypes(aVideoReleaseTypeList: TVideoReleaseTypeList); property SelectedMovie: TMovie read GetSelectedMovie; property SelectedSearchResArr: TExtMovieSearchArr read FSelectedSearchResArr; property SelectedSearchResult: TExtMovieSearchResult read GetSelectedSearchResult; end; var ViewEdit: TViewEdit; implementation {$R *.dfm} uses API_VCL_UIExt, API_Types, eAudioArtist, Vcl.Imaging.jpeg; procedure TViewEdit.CreateAudioNodeIfNotExist; begin if FAudioRootNode = nil then begin FAudioRootNode := TSectionRootNode.Create; FAudioRootNode.Caption := 'audio'; vstLibrary.AddChild(nil, FAudioRootNode); end end; procedure TViewEdit.CreateVideoNodeIfNotExist; begin if FVideoRootNode = nil then begin FVideoRootNode := TSectionRootNode.Create; FVideoRootNode.Caption := 'video'; vstLibrary.AddChild(nil, FVideoRootNode); end end; function TViewEdit.GetAudioNode: PVirtualNode; begin Result := vstLibrary.FindNode<TSectionRootNode>(FAudioRootNode); end; procedure TViewEdit.RenderVideoReleaseTypes(aVideoReleaseTypeList: TVideoReleaseTypeList); begin FBind.BindComboBoxItems(bcVideoReleaseTypeID, aVideoReleaseTypeList.AsEntityArray, 'ID', 'Name'); end; function TViewEdit.GetSelectedSearchResult: TExtMovieSearchResult; begin Result := vstSearchResults.GetNodeData<TExtMovieSearchResult>(vstSearchResults.FocusedNode); end; function TViewEdit.GetSelectedMovie: TMovie; begin Result := vstLibrary.GetNodeData<TMovie>(vstLibrary.FocusedNode); end; procedure TViewEdit.RenderFile(aMediaFile: TMediaFile); var VirtualNode: PVirtualNode; begin VirtualNode := vstFiles.AddChild(nil); VirtualNode.SetData<TMediaFile>(aMediaFile); end; function TViewEdit.GetVideoNode: PVirtualNode; begin Result := vstLibrary.FindNode<TSectionRootNode>(FVideoRootNode); end; procedure TViewEdit.RenderSearchResPic(aPicData: TBytes; const aSearchResID: Integer); var Image: TImage; JPEGPicture: TJPEGImage; PicStream: TMemoryStream; begin PicStream := TStreamEngine.CreateStreamFromBytes(aPicData); JPEGPicture := TJPEGImage.Create; try JPEGPicture.LoadFromStream(PicStream); JPEGPicture.DIBNeeded; Image := TImage.Create(nil); Image.Picture.Assign(JPEGPicture); vstSearchResults.BeginUpdate; FSearchResPicDic.AddOrSetValue(aSearchResID, Image); vstSearchResults.EndUpdate; finally PicStream.Free; JPEGPicture.Free; end; end; procedure TViewEdit.RenderSearchRes(aExtMovieSearchArr: TExtMovieSearchArr); var MovieSearchResult: TExtMovieSearchResult; VirtualNode: PVirtualNode; begin vstSearchResults.NodeDataSize := SizeOf(TExtMovieSearchResult); for MovieSearchResult in aExtMovieSearchArr do begin VirtualNode := vstSearchResults.AddChild(nil); VirtualNode.SetData<TExtMovieSearchResult>(MovieSearchResult); vstSearchResults.MultiLine[VirtualNode] := True; end; FSelectedSearchResArr := aExtMovieSearchArr; //FSearchResPicDic.Clear; SendMessage('GetSearchResultPics'); end; procedure TViewEdit.RenderMediaFile(aMediaFile: TMediaFile); var VirtualNode: PVirtualNode; begin FMediaFileList.Add(aMediaFile); if aMediaFile.Movie <> nil then begin CreateVideoNodeIfNotExist; VirtualNode := vstLibrary.AddChild(GetVideoNode, aMediaFile.Movie); FBind.BindEntity(aMediaFile.VideoFile, 'Video'); vstLibrary.Expanded[GetVideoNode] := True; end; if aMediaFile.Artist <> nil then begin CreateAudioNodeIfNotExist; VirtualNode := vstLibrary.AddChild(GetAudioNode, aMediaFile.Artist); vstLibrary.Expanded[GetAudioNode] := True; end; end; procedure TViewEdit.vstFilesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var MediaFile: TMediaFile; begin inherited; MediaFile := Sender.GetNodeData<TMediaFile>(Node); if MediaFile <> nil then CellText := MediaFile.Source.FullPath; end; procedure TViewEdit.vstLibraryFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex); var Level: Integer; MediaFile: TMediaFile; Movie: TMovie; begin inherited; Level := Sender.GetNodeLevel(Node); if Level = 1 then begin vstFiles.Clear; Movie := Sender.GetNodeData<TMovie>(Node); for MediaFile in FMediaFileList do if MediaFile.Movie = Movie then RenderFile(MediaFile); end; end; procedure TViewEdit.vstLibraryGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var Artist: TArtist; Level: Integer; Movie: TMovie; SectionRootNode: TSectionRootNode; begin inherited; Level := Sender.GetNodeLevel(Node); case Level of 0: begin SectionRootNode := Sender.GetNodeData<TSectionRootNode>(Node); CellText := SectionRootNode.Caption; end; 1: begin if Node.Parent = GetVideoNode then begin Movie := Sender.GetNodeData<TMovie>(Node); CellText := Movie.Title; end; if Node.Parent = GetAudioNode then begin Artist := Sender.GetNodeData<TArtist>(Node); CellText := Artist.Name; end; end; end; end; procedure TViewEdit.vstSearchResultsClick(Sender: TObject); begin inherited; SendMessage('AssignKPSource'); end; procedure TViewEdit.vstSearchResultsDrawText(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; const Text: string; const CellRect: TRect; var DefaultDraw: Boolean); var Image: TImage; MovieSearchResult: TExtMovieSearchResult; begin inherited; if Column = 0 then begin MovieSearchResult := Node.GetData<TExtMovieSearchResult>; DefaultDraw := False; if FSearchResPicDic.TryGetValue(MovieSearchResult.ID, Image) then TargetCanvas.Draw(0, 0, Image.Picture.Graphic); end; end; procedure TViewEdit.vstSearchResultsGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: string); var MovieSearchResult: TExtMovieSearchResult; begin inherited; if Column = 0 then CellText := 'CoverPic' else if Column = 1 then begin MovieSearchResult := Node.GetData<TExtMovieSearchResult>; CellText := MovieSearchResult.Title; if MovieSearchResult.TitleOrign <> '' then CellText := CellText + #13#10 + MovieSearchResult.TitleOrign; if MovieSearchResult.Year > 0 then CellText := CellText + #13#10 + MovieSearchResult.Year.ToString; end; end; procedure TViewEdit.vstSearchResultsInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); begin inherited; Include(InitialStates, ivsMultiline); end; procedure TViewEdit.vstSearchResultsMeasureItem(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; var NodeHeight: Integer); begin inherited; if Sender.MultiLine[Node] then begin TargetCanvas.Font := Sender.Font; NodeHeight := 75; end; end; procedure TViewEdit.btnSearchClick(Sender: TObject); begin inherited; SendMessage('GetSearchResults'); end; procedure TViewEdit.FormCreate(Sender: TObject); begin inherited; FBind := TORMBind.Create(Self); FMediaFileList := TMediaFileList.Create(False); FSearchResPicDic := TObjectDictionary<Integer, TImage>.Create([doOwnsValues]); end; procedure TViewEdit.FormDestroy(Sender: TObject); begin inherited; FBind.Free; FMediaFileList.Free; FSearchResPicDic.Free; if Assigned(FVideoRootNode) then FVideoRootNode.Free; if Assigned(FAudioRootNode) then FAudioRootNode.Free; end; procedure TViewEdit.FormShow(Sender: TObject); begin inherited; SendMessage('PullFiles'); end; end.
{ Copyright (c) 2018, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } unit RGB_test; interface uses SysUtils, RGB, {$IFDEF FPC} fpcunit, testregistry {$ELSE} TestFramework {$ENDIF}; type TRGBTest = class sealed(TTestCase) strict private _RGB: IRGB; public procedure SetUp; override; published procedure RedIs100; procedure GreenIs110; procedure BlueIs120; end; implementation procedure TRGBTest.RedIs100; begin CheckEquals(100, _RGB.Red); end; procedure TRGBTest.GreenIs110; begin CheckEquals(110, _RGB.Green); end; procedure TRGBTest.BlueIs120; begin CheckEquals(120, _RGB.Blue); end; procedure TRGBTest.SetUp; begin inherited; _RGB := TRGB.New(100, 110, 120); end; initialization RegisterTest(TRGBTest {$IFNDEF FPC}.Suite {$ENDIF}); end.
unit WinshoeMessage; interface uses Classes , EncodeWinshoe , Winshoes; Const WinshoeMessageHeaderNames: array [0..6] of String = ('From' , 'Organization' , 'References' , 'Reply-To' , 'Subject' , 'To' // 5 , 'Message-ID' // 6 ); Type TOnGetAttachmentStream = procedure(pstrm: TStream) of object; TOnGetInLineImageStream = procedure(pstrm: TStream) of object; // Satvinder Basra 2/12/1999 Added to deal with inline images // The structure for TWinshoeMessage changes a bit. // However, some properties will be kept for backward compatibility. // ADDED: // // property TMessageParts: contains all the different part of a MIME message (excluding attachments) // // // carry on commenting once you finish. // CHANGES: // // When using TWinshoeMessage for POP3, the TEXT property will be empty. This is substituted with // the MessageParts property /////////////////////////////////////////// TMessagePart = class(TCollectionItem) private fslstText:TStrings; // the actual text of the corresponding message part fsContentTransfer, fsContentType: string; // identifies the content-type encoding of the message public property ContentType: string read fsContentType write fsContentType; property ContentTransfer: string read fsContentTransfer write fsContentTransfer; property Text: TStrings read fslstText write fslstText; constructor Create(Collection: TCollection); override ; destructor Destroy; override; end ; TMessageParts = class(TCollection) private function GetItem(Index: Integer): TMessagePart; procedure SetItem(Index: Integer; const Value:TMessagePart); public function Add: TMessagePart; procedure AddMessagePart(const psContentType,psContentTransfer:string; slstText:TStrings); property Items[Index: Integer]: TMessagePart read GetItem write SetItem; end ; //////////////////////////////////////////// TAttachment = class(TCollectionItem) private fslstHeaders: TStrings; fsFilename, fsStoredPathname: String; fOnGetAttachmentStream: TOnGetAttachmentStream; // procedure SetStoredPathname(const Value: String); public property Filename: string read fsFilename write fsFilename; property Headers: TStrings read fslstHeaders; property OnGetAttachmentStream: TOnGetAttachmentStream read fOnGetAttachmentStream write fOnGetAttachmentStream; property StoredPathname: String read fsStoredPathname write SetStoredPathname; // // SaveToFile // This method will save the attachment to the specified filename. function SaveToFile( strFileName: string):boolean; constructor Create(Collection: TCollection); override; destructor Destroy; override; end; TAttachments = class(TCollection) private function GetItem(Index: Integer): TAttachment; procedure SetItem(Index: Integer; const Value: TAttachment); public function Add: TAttachment; procedure AddAttachment(const psPathname: string); property Items[Index: Integer]: TAttachment read GetItem write SetItem; default; end; // Satvinder Basra 2/12/1999 Added to deal with inline images TInLineImage = class(TCollectionItem) private fslstHeaders: TStrings; fsFilename, fsStoredPathname: String; fOnGetInLineImageStream: TOnGetInLineImageStream; // procedure SetStoredPathname(const Value: String); public property Filename: string read fsFilename write fsFilename; property Headers: TStrings read fslstHeaders; property OnGetInLineImageStream: TOnGetInLineImageStream read fOnGetInLineImageStream write fOnGetInLineImageStream; property StoredPathname: String read fsStoredPathname write SetStoredPathname; // // SaveToFile // This method will save the attachment to the specified filename. function SaveToFile( strFileName: string):boolean; constructor Create(Collection: TCollection); override; destructor Destroy; override; end; TInLineImages = class(TCollection) private function GetItem(Index: Integer): TInLineImage; procedure SetItem(Index: Integer; const Value: TInLineImage); public function Add: TInLineImage; procedure AddInLineImage(const psPathname: string); property Items[Index: Integer]: TInLineImage read GetItem write SetItem; default; end; TWinshoeMessage = class(TComponent) private fbExtractAttachments, fbUseNowForDate: Boolean; fiMsgNo: Integer; fsContentType: string; FsDefaultDomain: string; fAttachments: TAttachments; fInLineImages : TInLineImages; // Satvinder Basra 2/12/1999 Added to deal with inline images // added for MessageParts fMessageParts: TMessageParts; fbNoDecode:boolean; FslstToo, FslstCCList, FslstBCCList, fslstHeaders, fslstText, fslstNewsgroups: TStrings; // procedure SetBCCList(Value: TStrings); procedure SetCCList(Value: TStrings); procedure SetText(slst: TStrings); procedure SetHeaders(Value: TStrings); procedure SetNewsgroups(Value: TStrings); //function GetNewsgroups: TStrings; //function GetCCList: TStrings; procedure SetToo(Value: TStrings); //function GetToo:TStrings; protected procedure SetHeaderDate(const Value: TDateTime); procedure SetHeaderString(const piIndex: Integer; const Value: String); function GetHeaderDate: TDateTime; function GetHeaderString(const piIndex: Integer): string; public procedure Clear; virtual; procedure ClearBody; procedure ClearHeader; constructor Create(AOwner: TComponent); override; destructor Destroy; override; class procedure FromArpa(const sFull: string; var sAddr, sReal: string); {Given a Full address, this will seperate the Address from the Descriptive and return in the 2nd and 3rd parameters. If no Real exists, Real will be the same as Addr} class function ExtractAddr(const sFull: string): string; {Returns just the address from a full address} class function ExtractReal(const sFull: string): string; {Returns just the descriptive portion of a full address} {TODO Fix to use Streaming - also will allow to make changes and remain compatible} procedure LoadFromFile(const sFileName: String); procedure SaveToFile(const sFileName: String); procedure SetDynamicHeaders; class function StrInternetToDateTime(s1: string): TDateTime; {Attempts to convert a text internet representation of a date to a TDatetime. Is about 85% successful} class function ToArpa(const sAddress, sReal: string): string; {Given an address and a descriptive portion, a full address is returned} class procedure ValidateAddr(const psAddr, psField: String); // property Attachments: TAttachments read fAttachments; property InLineImages: TInLineImages read fInLineImages; // Satvinder Basra 2/12/1999 Added to deal with inline images property MessageParts: TMessageParts read fMessageParts ; published // NOTE: There is no GetBCCList since when a message is sent // The Bcc list does not show. property BCCList: TStrings read FslstBCCList write SetBCCList; property CCList: TStrings read fslstCCList write SetCCList; {}property DefaultDomain: String read FsDefaultDomain write FsDefaultDomain; // Contains the default domain to be used for adressees who do not have one property ExtractAttachments: Boolean read fbExtractAttachments write fbExtractAttachments default True; property Headers: TStrings read FslstHeaders write SetHeaders; property MsgNo: Integer read fiMsgNo write fiMsgNo; property Text: TStrings read fslstText write SetText; property UseNowForDate: Boolean read fbUseNowForDate write fbUseNowForDate default True; // Linked to Headers property ContentType: string read fsContentType write fsContentType; property Date: TDateTime read GetHeaderDate write SetHeaderDate; property Newsgroups: TStrings read fslstNewsgroups write SetNewsgroups; // property From: string index 0 read GetHeaderString write SetHeaderString; property Organization: string index 1 read GetHeaderString write SetHeaderString; property MsgID: string index 6 read GetHeaderString write SetHeaderString; property References: string index 2 read GetHeaderString write SetHeaderString; property ReplyTo: string index 3 read GetHeaderString write SetHeaderString; property Subject: string index 4 read GetHeaderString write SetHeaderString; property Too: TStrings read fslstToo write SetToo; property NoDecode: boolean read fbNoDecode write fbNoDEcode default False; end; TWinshoeMessageClient = class(TWinshoeClient) private fsXProgram: String; protected public procedure ReceiveHeader(pMsg: TWinshoeMessage; const psDelim: string); virtual; procedure ReceiveBody(pMsg: TWinshoeMessage); virtual; procedure Send(pMsg: TWinshoeMessage); virtual; procedure WriteHeader(const psHeader, psValue: String); procedure WriteMessage(pslst: TStrings); published property XProgram: string read fsXProgram write fsXProgram; end; //Procs procedure Register; const MultiPartBoundary = '=_NextPart_2rfksadvnqw3nerasdf'; MultiPartAlternativeBoundary = '=_NextPart_2altrfksadvnqw3nerasdf'; MultiPartRelatedBoundary = '=_NextPart_2relrfksadvnqw3nerasdf'; implementation Uses GlobalWinshoe, StringsWinshoe, SystemWinshoe, SysUtils, Windows; procedure Register; begin RegisterComponents('Winshoes Misc', [TWinshoeMessage]); end; procedure TWinshoeMessageClient.WriteHeader(const psHeader, psValue: String); begin if length(psValue) > 0 then WriteLn(psHeader + ': ' + psValue); end; procedure TWinshoeMessage.SetNewsgroups; begin fslstNewsgroups.Assign(Value); end; procedure TWinshoeMessage.SetCCList; begin fslstCCList.Assign(Value); end; procedure TWinshoeMessage.SetBCCList; begin FslstBCCList.Assign(Value); end; class procedure TWinshoeMessage.ValidateAddr; begin if Length(ExtractAddr(psAddr)) = 0 then raise Exception.Create(psField + ' not specified.'); end; class function TWinshoeMessage.ToArpa; begin if (length(sReal) > 0) and (Uppercase(sAddress) <> sReal) then Result := sReal + ' <' + sAddress + '>' else Result := sAddress; end; class function TWinshoeMessage.ExtractReal; begin FromArpa(sFull, sVoid, Result); end; class function TWinshoeMessage.ExtractAddr; begin FromArpa(sFull, Result, sVoid); end; procedure TWinshoeMessage.SetText; begin FslstText.Assign(slst); end; procedure TWinshoeMessage.SetHeaders; begin FslstHeaders.Assign(Value); end; class procedure TWinshoeMessage.FromArpa(const sFull: string; var sAddr, sReal: string); var iPos: Integer; begin sAddr := ''; sReal := ''; if Copy(sFull, Length(sFull) , 1) = '>' then begin iPos := Pos('<', sFull); if iPos > 0 then begin sAddr := Trim(Copy(sFull, iPos + 1, Length(sFull) - iPos - 1)); sReal := Trim(Copy(sFull, 1, iPos - 1)); end; end else if Copy(sFull, Length(sFull), 1) = ')' then begin iPos := Pos('(', sFull); if iPos > 0 then begin sReal := Trim(Copy(sFull, iPos + 1, Length(sFull) - iPos - 1)); sAddr := Trim(Copy(sFull, 1, iPos - 1)); end; end else begin sAddr := sFull; end; while length(sReal) > 1 do begin if (sReal[1] = '"') and (sReal[Length(sReal)] = '"') then sReal := Copy(sReal, 2, Length(sReal) - 2) else if (sReal[1] = '''') and (sReal[Length(sReal)] = '''') then sReal := Copy(sReal, 2, Length(sReal) - 2) else break; end; if Length(sReal) = 0 then sReal := sAddr; end; class function TWinshoeMessage.StrInternetToDateTime(s1: string): TDateTime; var i1: Integer; wDt, wMo, wYr, wHo, wMin, wSec: Word; begin result := 0.0; s1 := Trim(s1); if length(s1) = 0 then exit; try if StrToDay(Copy(s1, 1, 3)) > 0 then Delete(s1, 1, 5); if IsNumeric(s1[2]) then begin wDt := StrToIntDef(Copy(s1, 1, 2), 1); i1 := 4; end else begin wDt := StrToIntDef(Copy(s1, 1, 1), 1); i1 := 3; end; wMo := StrToMonth(Copy(s1, i1, 3)); if wMo = 0 then wMo := 1; if (i1 + 6 > Length(s1)) or (s1[i1 + 6] = ' ') then wYr := StrToIntDef(Copy(s1, i1 + 4, 2), 1900) else wYr := StrToIntDef(Copy(s1, i1 + 4, 4), 1900); if wYr < 80 then Inc(wYr, 2000) else if wYr < 100 then Inc(wYr, 1900); Result := EncodeDate(wYr, wMo, wDt); i1 := Pos(':',s1); // added this if i1 > 0 then begin wHo := StrToInt(Copy(s1,i1-2,2)); wMin := StrToInt(Copy(s1,i1+1,2)); wSec := StrToInt(Copy(s1,i1+4,2)); result := result + EncodeTime(wHo,wMin,wSec,0); end; except Result := 0.0; end; end; constructor TWinshoeMessage.Create; begin inherited; fbExtractAttachments := True; fbUseNowForDate := True; fsContentType := 'text/plain'; fAttachments := TAttachments.Create(TAttachment); fInLineImages := TInLineImages.create(TInLineImage); // Satvinder Basra 2/12/1999 Added to deal with inline images // fMessageParts := TMessageParts.Create(TMessagePart); fslstBCCList := TStringList.Create; fslstCCList := TStringList.Create; fslstHeaders := TStringList.Create; fslstText := TStringList.Create; fslstNewsgroups := TStringList.Create; fslstToo := TStringList.Create ; fbNoDecode := false ; end; procedure TWinshoeMessageClient.Send; var i: integer; encd: TWinshoeEncoder; begin if pMsg.Attachments.Count > 0 then begin if (pMsg.InLineImages.Count >0) and (pMsg.Attachments.Count >0) then begin WriteLn('This is a multi-part message in MIME format.'); WriteLn(''); WriteLn('--' + MultiPartRelatedBoundary); WriteLn('Content-Type: multipart/related; '); WriteLn(' boundary="' + MultiPartAlternativeBoundary +'"'); WriteLn(' type: multipart/alternative; '); WriteLn(''); WriteLn('--' + MultiPartAlternativeBoundary); WriteLn('Content-Type: multipart/alternative; '); WriteLn(' boundary="' + MultiPartBoundary +'"'); WriteLn(''); end else begin if (pMsg.InLineImages.Count >0) or (pMsg.Attachments.Count >0) then begin WriteLn('This is a multi-part message in MIME format.'); WriteLn(''); WriteLn('--' + MultiPartAlternativeBoundary); WriteLn('Content-Type: multipart/alternative; '); WriteLn(' boundary="' + MultiPartBoundary +'"'); WriteLn(''); end; end; WriteLn(''); if pMsg.MessageParts.Count > 0 then // Alternative part begin with pMsg.MessageParts do begin for i := 0 to Pred(Count) do begin WriteLn('--' + MultiPartBoundary); WriteLn('Content-Type: ' + Items[i].ContentType ) ; WriteLn('Content-Transfer-Encoding: ' + Items[i].ContentTransfer); WriteLn(''); WriteMessage(Items[i].Text ); WriteLn(''); end; end; WriteLn('--' + MultiPartBoundary + '--'); end else // No alternative part begin WriteLn('--' + MultiPartBoundary); WriteLn('Content-Type: ' + pMsg.ContentType+ ';'); WriteLn(' charset="iso-8859-1"'); WriteLn('Content-Transfer-Encoding: 7bit'); WriteLn(''); WriteMessage(pMsg.Text); WriteLn(''); WriteLn('--' + MultiPartBoundary + '--'); end; // Now the InLineImages with pMsg.InLineImages do begin encd := TWinshoeEncoder.Create; try for i := 0 to Pred(Count) do begin WriteLn(''); if pMsg.Attachments.Count > 0 then WriteLn('--' + MultiPartAlternativeBoundary) else WriteLn('--' + MultiPartRelatedBoundary); WriteLn('Content-Type: image/' + Copy(ExtractFileExt(Items[i].Filename),2,length(Items[i].Filename)) + ';'); WriteLn(' name="' + Items[i].Filename + '"'); WriteLn('Content-Transfer-Encoding: base64'); WriteLn('Content-ID: <'+ Items[i].Filename +'>'); WriteLn(''); encd.EncodeFile(Self, Items[i].StoredPathname); end; if (pMsg.InLineImages.Count >0) then if pMsg.Attachments.Count > 0 then WriteLn('--' + MultiPartAlternativeBoundary + '--') else WriteLn('--' + MultiPartRelatedBoundary + '--'); finally encd.free; end; end ; // Now the attachments with pMsg.Attachments do begin encd := TWinshoeEncoder.Create; try for i := 0 to Pred(Count) do begin WriteLn(''); if pMsg.InLineImages.Count > 0 then WriteLn('--' + MultiPartRelatedBoundary) else WriteLn('--' + MultiPartAlternativeBoundary); WriteLn('Content-Type: application/octet-stream;'); WriteLn(' name="' + Items[i].Filename + '"'); WriteLn('Content-Transfer-Encoding: base64'); WriteLn('Content-Disposition: attachment;'); WriteLn(' filename="' + Items[i].Filename + '"'); WriteLn(''); encd.EncodeFile(Self, Items[i].StoredPathname); end; if pMsg.InLineImages.Count > 0 then WriteLn('--' + MultiPartRelatedBoundary + '--') else WriteLn('--' + MultiPartAlternativeBoundary + '--'); finally encd.free; end; WriteLn(''); end ; end else // No attachments begin // need to check for inline images if (pMsg.InLineImages.Count >0) then begin WriteLn('This is a multi-part message in MIME format.'); WriteLn(''); WriteLn('--' + MultiPartAlternativeBoundary); WriteLn('Content-Type: multipart/alternative; '); WriteLn(' boundary="' + MultiPartBoundary +'"'); WriteLn(''); WriteLn(''); if pMsg.MessageParts.Count > 0 then // Alternative part begin with pMsg.MessageParts do begin for i := 0 to Pred(Count) do begin WriteLn('--' + MultiPartBoundary); WriteLn('Content-Type: ' + Items[i].ContentType ) ; WriteLn('Content-Transfer-Encoding: ' + Items[i].ContentTransfer); WriteLn(''); WriteMessage(Items[i].Text ); WriteLn(''); end; end; WriteLn('--' + MultiPartBoundary + '--'); end else // No alternative part begin WriteLn('--' + MultiPartBoundary); WriteLn('Content-Type: ' + pMsg.ContentType+ ';'); WriteLn(' charset="iso-8859-1"'); WriteLn('Content-Transfer-Encoding: 7bit'); WriteLn(''); WriteMessage(pMsg.Text); WriteLn(''); WriteLn('--' + MultiPartBoundary + '--'); end; // Now the InLineImages with pMsg.InLineImages do begin encd := TWinshoeEncoder.Create; try for i := 0 to Pred(Count) do begin WriteLn(''); WriteLn('--' + MultiPartAlternativeBoundary); WriteLn('Content-Type: image/' + Copy(ExtractFileExt(Items[i].Filename),2,length(Items[i].Filename)) + ';'); WriteLn(' name="' + Items[i].Filename + '"'); WriteLn('Content-Transfer-Encoding: base64'); WriteLn('Content-ID: <'+ Items[i].Filename +'>'); WriteLn(''); encd.EncodeFile(Self, Items[i].StoredPathname); end; WriteLn('--' + MultiPartAlternativeBoundary + '--'); finally encd.free; end; end; end else begin if pMsg.MessageParts.Count > 0 then // Has alternative begin WriteLn('This is a multi-part message in MIME format.'); WriteLn(''); with pMsg.MessageParts do begin for i := 0 to Pred(Count) do begin WriteLn('--' + MultiPartBoundary); WriteLn('Content-Type: ' + Items[i].ContentType ) ; WriteLn('Content-Transfer-Encoding: ' + Items[i].ContentTransfer); WriteLn(''); WriteMessage(Items[i].Text ); WriteLn(''); end; end; WriteLn('--' + MultiPartBoundary + '--'); end else WriteMessage(pMsg.Text); // No attachments or alternative parts (message parts) end; end; end; destructor TWinshoeMessage.Destroy; begin fMessageParts.Free ; fAttachments.Free; fInLineImages.Free; // Satvinder Basra 2/12/1999 Added to deal with inline images FslstBCCList.Free; FslstCCList.Free; FslstHeaders.Free; FslstText.Free; fslstNewsgroups.Free; fslstToo.Free; inherited Destroy; end; procedure TWinshoeMessage.Clear; begin ClearHeader; ClearBody; end; procedure TWinshoeMessage.ClearBody; begin MessageParts.Clear; Attachments.Clear; InLineImages.Clear; // Satvinder Basra 2/12/1999 Added to deal with inline images Text.Clear; end; procedure TWinshoeMessage.ClearHeader; begin BCCList.Clear; CCList.Clear; DefaultDomain := ''; Date := 0 ; From := ''; Headers.Clear; MsgNo := 0 ; Newsgroups.Clear; Organization := ''; References := ''; ReplyTo := ''; Subject := ''; Too.Clear; end; procedure TWinshoeMessageClient.WriteMessage(pslst: TStrings); {Writes a message to a socket, guaranteeing a terminating EOL , and changes leading '.'} var i: integer; s: string; begin for i := 0 to Pred(pslst.Count) do begin s := pslst[i]; if Copy(s, 1, 1) = '.' then s := '.' + s; WriteLn(s); end; end; function TWinshoeMessage.GetHeaderDate: TDateTime; begin result := StrInternetToDateTime(Headers.Values['Date']); end; function TWinshoeMessage.GetHeaderString(const piIndex: Integer): string; begin result := Headers.Values[WinshoeMessageHeaderNames[piIndex]]; end; procedure TWinshoeMessage.SetHeaderDate(const Value: TDateTime); var TheDate:TDateTime ; strOldFormat, strDate: String; wDay, wMonth, wYear:WORD; begin // This code doesn't work with non-english systems. //Headers.Values['Date'] := FormatDateTime('ddd, dd mmm yyyy hh:nn:ss ' //+ DateTimeToGmtOffSetStr(OffsetFromUTC, False), Value); if fbUseNowForDate then TheDate := Now else TheDate := Value ; // Replace with this: strOldFormat := ShortDateFormat ; ShortDateFormat := 'DD.MM.YYYY'; // Date case DayOfWeek(TheDate) of 1: strDate := 'Sun, '; 2: strDate := 'Mon, '; 3: strDate := 'Tue, '; 4: strDate := 'Wed, '; 5: strDate := 'Thu, '; 6: strDate := 'Fri, '; 7: strDate := 'Sat, '; end; DecodeDate(TheDate, wYear, wMonth, wDay); strDate := strDate + IntToStr(wDay) + #32; case wMonth of 1: strDate := strDate + 'Jan '; 2: strDate := strDate + 'Feb '; 3: strDate := strDate + 'Mar '; 4: strDate := strDate + 'Apr '; 5: strDate := strDate + 'May '; 6: strDate := strDate + 'Jun '; 7: strDate := strDate + 'Jul '; 8: strDate := strDate + 'Aug '; 9: strDate := strDate + 'Sep '; 10: strDate := strDate + 'Oct '; 11: strDate := strDate + 'Nov '; 12: strDate := strDate + 'Dec '; end; strDate := strDate + IntToStr(wYear) + #32 + TimeToStr(TheDate); Headers.Values['Date'] := strDate + DateTimeToGmtOffSetStr(OffsetFromUTC,False); ShortDateFormat := strOldFormat ; end; procedure TWinshoeMessage.SetHeaderString(const piIndex: Integer; const Value: String); begin Headers.Values[WinshoeMessageHeaderNames[piIndex]] := Value; end; procedure TWinshoeMessage.SaveToFile; begin with TFileStream.Create(sFileName, fmCreate) do try WriteComponent (Self); finally Free; end; end; procedure TWinshoeMessage.LoadFromFile; begin with TFileStream.Create(sFileName, fmOpenRead) do try ReadComponent(Self); finally Free; end; end; procedure TWinshoeMessage.SetDynamicHeaders; var useBoundary : string; begin Date := Now; // Satvinder Basra 2/12/1999 Added to deal with inline images if (InLineImages.Count >0) and (Attachments.Count >0) then useBoundary := MultiPartRelatedBoundary else if (InLineImages.Count >0) or (Attachments.Count >0) then useBoundary := MultiPartAlternativeBoundary else useBoundary := MultiPartBoundary; if Attachments.Count > 0 then begin // Has attachments Headers.Values['MIME-Version'] := '1.0'; Headers.Values['Content-Type'] := 'multipart/mixed; boundary="' + useBoundary {MultiPartBoundary} + '"'; end else begin if InLineImages.Count > 0 then begin // Has InLineImages Headers.Values['MIME-Version'] := '1.0'; Headers.Values['Content-Type'] := 'multipart/related; '+ 'type="multipart/alternative"; ' + 'boundary="' + useBoundary {MultiPartBoundary} + '"'; end else begin if MessageParts.Count > 0 then begin Headers.Values['MIME-Version'] := '1.0'; Headers.Values['Content-Type'] := 'multipart/alternative; boundary="' + useBoundary{MultiPartBoundary} + '"'; end else begin Headers.Values['MIME-Version'] := ''; Headers.Values['Content-Type'] := fsContentType + ' boundary="' + useBoundary{MultiPartBoundary} + '"'; end; end; end; if Newsgroups.Count > 0 then Headers.Values['Newsgroups'] := Newsgroups.CommaText; end; function TAttachments.Add: TAttachment; begin result := TAttachment(inherited Add); end; procedure TAttachments.AddAttachment(const psPathname: string); begin with Add do begin Filename := ExtractFileName(psPathname); StoredPathname := psPathname; end; end; function TAttachments.GetItem(Index: Integer): TAttachment; begin result := TAttachment(inherited GetItem(Index)); end; procedure TAttachments.SetItem(Index: Integer; const Value: TAttachment); begin inherited SetItem(Index, Value); end; procedure TWinshoeMessageClient.ReceiveBody(pMsg: TWinshoeMessage); var intStart, intEnd, i: integer; intPos : integer ; sOldBoundary, sTemp, s, sBoundary: string; lstBoundary : TStringList; slst : TStringList; MsgPart : TMessagePart; Att : TAttachment; Img : TInLineImage; strmOut: TFileStream; bBoundary, boolBoundaryFound: boolean ; function ExtractBoundary : string; var b: string; begin Result := ''; intPos := Pos('=',s); b := Trim(Copy(s,intPos+1,Length(s)-intPos+1)); if pos(';',b) <> 0 then b:= Fetch(b,';'); if b[length(b)]='"' then intEnd := Length(b)-1; if b[1]='"' then intStart := 1 else intStart := 0; b := Trim( Copy(b, intStart+1, IntEnd-1)); Result := b; end; {ExtractBoundary} procedure ExtractInLineImages; var b : integer; begin with pMsg do begin if (ExtractAttachments) and (Pos('multipart/alternative',slst.Values['Content-Type'])=0) then begin strmOut := nil ; try Img := InLineImages.Add ; with Img do begin Headers.Assign(slst); FileName := Pluck(slst.Values['Content-Type'], 'name="', '"', True ); if FileName = '' then FileName := Pluck(slst.Values['Content-Disposition'], 'filename="', '"', True ); if slst.Values[slst.Values['Content-ID']] <> '' then slst.Values[slst.Values['Content-ID']] := FileName; if MsgPart.fslstText.indexof( Pluck(slst.Values['Content-ID'], '<','>',True)) >-1 then begin MsgPart.fslstText[MsgPart.fslstText.indexof( Pluck(slst.Values['Content-ID'], '<','>',True))] := Pluck(slst.Values['Content-ID'], '<','>',True); end; for b := 0 to MsgPart.fslstText.Count-1 do begin {Satvinder Basra 13/12/99 - fix problem with images with spaces in name} if Pos(' ',FileName)> 0 then MsgPart.text[b] := StringReplace( MsgPart.text[b], Pluck(slst.Values['Content-ID'], '<','>',True), '"'+FileName+'"',[rfReplaceAll,rfIgnoreCase]) else MsgPart.text[b] := StringReplace( MsgPart.text[b], Pluck(slst.Values['Content-ID'], '<','>',True), FileName,[rfReplaceAll,rfIgnoreCase]); MsgPart.text[b] := StringReplace( MsgPart.text[b], 'CID:', '', [rfReplaceAll,rfIgnoreCase]); MsgPart.text[b] := StringReplace( MsgPart.text[b], '""'+FileName+'""', '"'+FileName+'"', [rfReplaceAll,rfIgnoreCase]); end; for b := 0 to pMsg.Text.Count-1 do begin {Satvinder Basra 13/12/99 - fix problem with images with spaces in name} if Pos(' ',FileName)> 0 then pMsg.text[b] := StringReplace( pMsg.Text[b], Pluck(slst.Values['Content-ID'], '<','>',True), '"'+FileName+'"',[rfReplaceAll,rfIgnoreCase]) else pMsg.text[b] := StringReplace( pMsg.Text[b], Pluck(slst.Values['Content-ID'], '<','>',True), FileName,[rfReplaceAll,rfIgnoreCase]); pMsg.text[b] := StringReplace( pMsg.Text[b], 'CID:', '', [rfReplaceAll,rfIgnoreCase]); pMsg.text[b] := StringReplace( pMsg.Text[b], '""'+FileName+'""', '"'+FileName+'"', [rfReplaceAll,rfIgnoreCase]); end; if assigned ( OnGetInLineImageStream ) then OnGetInLineImageStream(strmOut); end ; if strmOut = nil then begin Img.StoredPathName := MakeTempFilename ; strmOut := TFileStream.Create(Img.StoredPathName, fmCreate ); end ; if CompareText(slst.Values['Content-Transfer-Encoding'], 'base64' ) = 0 then begin boolBoundaryFound := False ; while true do begin s := ReadLn ; if Length ( s ) = 0 then // some clients don't leave break // a space at then end before boundary else if (s = sBoundary) or (s = sBoundary + '--') then // Some clients don't leave a blank line begin boolBoundaryFound := True ; break ; end ; s := TWinshoeDecoder.DecodeLine(s); strmOut.WriteBuffer(s[1], Length(s)); end ; if not boolBoundaryFound then i := Capture (nil, [sBoundary, sBoundary + '--']) else i := 0 ; end else i := Capture(strmOut, [sBoundary, sBoundary + '--']); finally strmOut.Free ; end ; end else // don't save attachment i := Capture(nil, [sBoundary,sBoundary + '--']) ; end end; {ExtractInLineImages} procedure ExtractAttachedFiles; begin with pMsg do begin if (ExtractAttachments) and (Pos('multipart/alternative',slst.Values['Content-Type'])=0) then begin strmOut := nil ; try Att := Attachments.Add ; with Att do begin Headers.Assign(slst); FileName := Pluck(slst.Values['Content-Type'], 'name="', '"', True ); if FileName = '' then FileName := Pluck(slst.Values['Content-Disposition'], 'filename="', '"', True ); if assigned ( OnGetAttachmentStream ) then OnGetAttachmentStream(strmOut); end ; if strmOut = nil then begin Att.StoredPathName := MakeTempFilename ; strmOut := TFileStream.Create(Att.StoredPathName, fmCreate ); end; if CompareText(slst.Values['Content-Transfer-Encoding'], 'base64' ) = 0 then begin boolBoundaryFound := False ; while true do begin s := ReadLn ; if Length ( s ) = 0 then // some clients don't leave break // a space at then end before boundary else if (s = sBoundary) or (s = sBoundary + '--') then // Some clients don't leave a blank line begin boolBoundaryFound := True ; break ; end ; s := TWinshoeDecoder.DecodeLine(s); strmOut.WriteBuffer(s[1], Length(s)); end ; if not boolBoundaryFound then i := Capture (nil, [sBoundary, sBoundary + '--']) else i := 0 ; end else i := Capture(strmOut, [sBoundary, sBoundary + '--']); finally strmOut.Free ; end ; end else // don't save attachment i := Capture(nil, [sBoundary,sBoundary + '--']) ; end; end; {ExtractAttachedFiles} begin bBoundary := FALSE; if pMsg.fbNoDecode then // Don't decode the message, just capture it raw Capture(pMsg.fslstText,['.']) else begin lstBoundary := TStringList.Create ; try sOldBoundary := '' ; OnCaptureLine := nil; with pMsg do begin s := Headers.Values['Content-Type']; // Get the header content-type if CompareText(Fetch(s,'/'),'multipart') = 0 then // If this is a multipart message begin // now it could be mixed or alternative // We have to distinguish if it is alternative, since we have to change the boundary. // If there is an attachment, it will be multipart/mixed s := Headers.Values['Content-Type']; // See if boundary is found intPos := Pos('boundary',LowerCase(s)); // some put boundary in caps s := Trim ( Copy ( s, intPos, Length ( s ) - intPos + 1 )) ; if (CompareText(Copy(s,1,8), 'boundary') = 0 ) then begin // According to the RFC, the boundary should be put in the content type as: // boundary="simple boundary", that is boundary an = sign and then the boundary. // However, I found some boundary with spaces on each between the = sign. This is why // the following fixes this problem. // Get the actual boundary intPos := Pos ('=', s) ; sBoundary := Trim(Copy(s,intPos+1,Length(s)-intPos + 1 )); // See if there is a ';' the boundary if Pos(';',s) <> 0 then s := Fetch(s,';'); if s[Length(s)]='"' then // in case boundary is enclosed in quotes ("). intEnd := Length(s) -11 else intEnd := Length(s) - 9; if s[10] = '"' then intStart := 1 else intStart := 0 ; // Set the boundary sBoundary := '--' + Trim(Copy(s,intStart + 10,intEnd)); s := ReadLn ; repeat if bBoundary then s := sBoundary; if s = sBoundary then // new part of messsage begin slst := TStringList.Create ; try CaptureHeader ( slst, ''); if slst.Count > 0 then begin s := slst.Values['Content-Type']; // Set flag if alternative if (Pos('multipart/alternative',s)>0) or (Pos('multipart/related',s)>0) then begin {Satvinder Basra 13/12/99 - fix problem with not decoding emails} { with images text and attachments} lstBoundary.Add(sBoundary); sOldBoundary := sBoundary ; // Save boundary bBoundary := FALSE; if Pos('boundary',s) >0 then begin s:= Copy(s,Pos('boundary',s), length(s)); sBoundary := '--'+ExtractBoundary; bBoundary := TRUE; Continue; end else begin if (Pos('multipart/alternative',s)>0) then begin CompareText(Trim(Fetch(s,';')),'multipart/alternative'); end; if (Pos('multipart/related',s)>0) then begin CompareText(Trim(Fetch(s,';')),'multipart/related') end; // Get alternative boundary sBoundary := '--' + Copy(Trim(s),11,Length(s)-12); end; end; s := slst.Values['Content-Type']; s := Trim(Fetch(s,'/')); if (CompareText(s, 'text') = 0) and // Maybe this won't work with all. // Temp Change. For allowing inline images etc... // if (Pos('multipart',s)=0) and (Pos('attachment',slst.Values['Content-Disposition'])=0) then // if it is a body part begin // Create the message part MsgPart := MessageParts.Add ; MsgPart.fsContentType := slst.Values ['Content-Type']; MsgPart.fsContentTransfer := slst.Values['Content-Transfer-Encoding']; // Get the message if LowerCase(MsgPart.fsContentTransfer) = 'quoted-printable' then i := CaptureQuotedPrintable(MsgPart.fslstText, [sBoundary, sBoundary + '--']) else i := Capture(MsgPart.fslstText, [sBoundary, sBoundary + '--']); bBoundary := FALSE; // for back compatibility assign to text fslstText.AddStrings ( MsgPart.fslstText ) ; // remove this in future versions end else // It is an attachment begin // Get rid of alternative saving // if (Pluck(slst.Values['Content-Disposition'], 'filename="','"',True) <> '') // and (ExtractAttachments) then if (Pluck(slst.Values['Content-ID'], '<','>',True) <> '') then begin ExtractInLineImages; bBoundary := FALSE; end else begin ExtractAttachedFiles; bBoundary := FALSE; end; {} end; if i = 1 then s := sBoundary ; // else //Took this out. BUG // s := ''// 24 OCT. 1999 Wasn't decoding atts. with this properly. end ; finally slst.Free ; end end else if s = '.' then break else begin {Satvinder Basra 13/12/99 - reset boundary to previous in list} if (lstBoundary.Count > 0) and (bBoundary = FALSE) then begin sBoundary := lstBoundary.strings[Pred(lstBoundary.Count)]; lstBoundary.Delete(Pred(lstBoundary.Count)); bBoundary := TRUE; end; // if sOldBoundary <> '' then // restore boundary // sBoundary := sOldBoundary ; s := ReadLn ; end ; until false ; end else // Boundary error raise EWinshoeException.Create('Boundary error'); end else // this is not a multipart message or content-type not set begin // Create a message part and finish. s := Headers.Values['Content-Type']; // if CompareText(Fetch(s,'/'),'text') <> 0 then if (CompareText(Fetch(s,'/'),'text') <> 0) and (s<>'') then begin sTemp :=Pluck(Headers.Values['Content-Disposition'], 'filename="','"',True); if (sTemp<>'') and (ExtractAttachments) then begin strmOut := nil ; try Att := Attachments.Add ; with Att do begin FileName := sTemp; if assigned ( OnGetAttachmentStream ) then OnGetAttachmentStream(strmOut); end ; if strmOut = nil then begin Att.StoredPathName := MakeTempFilename ; strmOut := TFileStream.Create(Att.StoredPathName, fmCreate ); end ; if CompareText(Headers.Values['Content-Transfer-Encoding'], 'base64' ) = 0 then begin while true do begin s := ReadLn ; if (Length ( s ) = 0) or (s='.') then // some clients don't leave break; // a space at then end before boundary s := TWinshoeDecoder.DecodeLine(s); strmOut.WriteBuffer(s[1], Length(s)); end ; end else Capture(strmOut, [sBoundary, sBoundary + '--']); finally strmOut.Free; end ; end end else begin MsgPart := MessageParts.Add ; MsgPart.fsContentType := Headers.Values['Content-Type']; MsgPart.fsContentTransfer := Headers.Values['Content-Transfer-Encoding']; // Get the text if LowerCase(MsgPart.fsContentTransfer) = 'quoted-printable' then CaptureQuotedPrintable(MsgPart.fslstText, ['.']) else Capture(MsgPart.fslstText, ['.']); // For back compatibilty assign the text to the Text property aswell fslstText.Assign ( MsgPart.fslstText ) ; // This line will be removed in future versions end ; {if} end; {if} end ; {with} finally lstBoundary.Free; end; end ; {if} end; {ReceiveBody} procedure TWinshoeMessageClient.ReceiveHeader; var s: string; begin with pMsg do begin Clear; CaptureHeader(Headers, psDelim); ParseCommaString(Too, Headers.Values['To']); ParseCommaString(CCList, Headers.Values['Cc']); ParseCommaString(Newsgroups, Headers.Values['Newsgroups']); s := Headers.Values['Title']; if length(s) > 0 then begin Headers.Values['Subject'] := Headers.Values['Title']; Headers.Values['Title'] := ''; end; end; end; procedure TWinshoeMessage.SetToo(Value: TStrings); begin FslstToo.Assign(Value); end ; { TAttachment } constructor TAttachment.Create; begin inherited; fslstHeaders := TStringList.Create; end; destructor TAttachment.Destroy; begin fslstHeaders.Free; inherited; end; function TAttachment.SaveToFile(strFileName: string): boolean; begin // What it really does is copy the file from the // temp location where the attachment has been saved // to the location specified in the parameter. if strFileName [ Length ( strFileName ) ] = '\' then strFileName := Copy ( strFileName, 1, Length ( strFileName ) - 1 ); Result := CopyFile ( PChar ( fsStoredPathname ) , PChar(strFileName), False); end; procedure TAttachment.SetStoredPathname(const Value: String); begin fsStoredPathname := Value; end; { TMessagePart } constructor TMessagePart.Create(Collection: TCollection); begin inherited ; fslstText := TStringList.Create; end; destructor TMessagePart.Destroy; begin fslstText.Free ; inherited; end; { TMessageParts } function TMessageParts.Add: TMessagePart; begin result := TMessagePart(inherited Add); end; function TMessageParts.GetItem(Index: Integer): TMessagePart; begin result := TMessagePart(inherited GetItem(Index)); end; procedure TMessageParts.AddMessagePart(const psContentType, psContentTransfer: string; slstText: TStrings); begin with Add do begin ContentType := psContentType; if psContentTransfer = '' then ContentTransfer := 'quoted-printable' else ContentTransfer := psContentTransfer ; Text.Assign(slstText) ; end ; end; procedure TMessageParts.SetItem(Index: Integer; const Value: TMessagePart); begin inherited SetItem(Index,Value); end; { TInLineImages } function TInLineImages.Add: TInLineImage; begin result := TInLineImage(inherited Add); end; procedure TInLineImages.AddInLineImage(const psPathname: string); begin with Add do begin Filename := ExtractFileName(psPathname); StoredPathname := psPathname; end; end; function TInLineImages.GetItem(Index: Integer): TInLineImage; begin result := TInLineImage(inherited GetItem(Index)); end; procedure TInLineImages.SetItem(Index: Integer; const Value: TInLineImage); begin inherited SetItem(Index, Value); end; { TInLineImage } constructor TInLineImage.Create; begin inherited; fslstHeaders := TStringList.Create; end; destructor TInLineImage.Destroy; begin fslstHeaders.Free; inherited; end; function TInLineImage.SaveToFile(strFileName: string): boolean; begin // What it really does is copy the file from the // temp location where the attachment has been saved // to the location specified in the parameter. if strFileName [ Length ( strFileName ) ] = '\' then strFileName := Copy ( strFileName, 1, Length ( strFileName ) - 1 ); Result := CopyFile ( PChar ( fsStoredPathname ) , PChar(strFileName), False); end; procedure TInLineImage.SetStoredPathname(const Value: String); begin fsStoredPathname := Value; end; end.
{------------------------------------ 功能说明:实现IDBAccess接口 创建日期:2010/04/26 作者:wzw 版权:wzw -------------------------------------} unit DBAccess; interface uses SysUtils, DB, DBClient, Provider, ADODB, DBIntf, SvcInfoIntf; type TDBOperation = class(TInterfacedObject, IDBAccess, ISvcInfo) private FConnection: TADOConnection; protected {IDBOperation} procedure BeginTrans; procedure CommitTrans; procedure RollbackTrans; procedure QuerySQL(Cds: TClientDataSet; const SQLStr: String); procedure ExecuteSQL(const SQLStr: String); procedure ApplyUpdate(const TableName: String; Cds: TClientDataSet); {ISvcInfo} function GetModuleName: String; function GetTitle: String; function GetVersion: String; function GetComments: String; public constructor Create; destructor Destroy; override; end; implementation uses SysSvc, SysFactory, ActiveX; { TDBOperation } function TDBOperation.GetComments: String; begin Result := '用于数据库操作'; end; function TDBOperation.GetModuleName: String; begin Result := ExtractFileName(SysUtils.GetModuleName(HInstance)); end; function TDBOperation.GetTitle: String; begin Result := '数据库操作接口(IDBAccess)'; end; function TDBOperation.GetVersion: String; begin Result := '20100426.001'; end; procedure TDBOperation.BeginTrans; begin FConnection.BeginTrans; end; procedure TDBOperation.CommitTrans; begin FConnection.CommitTrans; end; procedure TDBOperation.RollbackTrans; begin FConnection.RollbackTrans; end; procedure TDBOperation.ExecuteSQL(const SQLStr: String); var TmpQry: TADOQuery; begin TmpQry := TADOQuery.Create(nil); try TmpQry.Connection := FConnection; TmpQry.SQL.Text := SQLStr; TmpQry.ExecSQL; finally tmpQry.Free; end; end; procedure TDBOperation.QuerySQL(Cds: TClientDataSet; const SQLStr: String); var Provider: TDataSetProvider; TmpQry: TADOQuery; begin TmpQry := TADOQuery.Create(nil); Provider := TDataSetProvider.Create(nil); try TmpQry.Connection := FConnection; Provider.DataSet := TmpQry; TmpQry.SQL.Text := SQLStr; TmpQry.Open; Cds.Data := Provider.Data; finally tmpQry.Free; Provider.Free; end; end; procedure TDBOperation.ApplyUpdate(const TableName: String; Cds: TClientDataSet); const SQL = 'select * from %s where 1<>1'; var Provider: TDataSetProvider; TmpQry: TADOQuery; SQLStr: String; ECount: Integer; begin if Cds.State in [dsEdit, dsInsert] then cds.Post; if Cds.ChangeCount = 0 then exit; TmpQry := TADOQuery.Create(nil); Provider := TDataSetProvider.Create(nil); try SQLStr := Format(SQL, [TableName]); Provider.ResolveToDataSet := False; Provider.UpdateMode := upWhereAll;//upWhereKeyOnly; Provider.Options := [poAllowMultiRecordUpdates]; TmpQry.Connection := FConnection; Provider.DataSet := TmpQry; TmpQry.SQL.Text := SQLStr; TmpQry.Open; Provider.ApplyUpdates(Cds.Delta, -1, ECount); Cds.MergeChangeLog; finally tmpQry.Free; Provider.Free; end; end; constructor TDBOperation.Create; var Obj: TObject; DBConn: IDBConnection; begin DBConn := SysService as IDBConnection; if not DBConn.Connected then DBConn.Connected := True; Obj := DBConn.GetDBConnection; if Obj is TADOConnection then FConnection := TADOConnection(Obj); end; destructor TDBOperation.Destroy; begin inherited; end; function CreateDBOperation(param: Integer): TObject; begin CoInitialize(nil); Result := TDBOperation.Create; CoUnInitialize; end; initialization TIntfFactory.Create(IDBAccess, @CreateDBOperation); finalization end.
unit tg; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpJSON, jsonparser, SyncObjs, regexpr, fgl, gqueue, fphttpclient, Math, LazLogger, flqueue; //The API will not allow more than ~30 messages to different users per second //Also note that your bot will not be able to send more than 20 messages per minute to the same group. //If you're sending bulk notifications to multiple users, the API will not allow more than 30 messages per second or so. //error_code type TTelegramUpdateObj = class; TTelegramMessageObj = class; TTelegramMessageEntityObj = class; TTelegramUpdateObjList = specialize TFPGObjectList<TTelegramMessageEntityObj>; { TTelegramObj } TTelegramObj = class private fJSON: TJSONObject; public constructor Create(JSONObject: TJSONObject); virtual; class function CreateFromJSONObject(JSONObject: TJSONObject): TTelegramObj; end; TTelegramObjClass = class of TTelegramObj; { TTelegramUpdateObj } TTelegramUpdateObj = class(TTelegramObj) private fUpdateId: Integer; fMessage: TTelegramMessageObj; public constructor Create(JSONObject: TJSONObject); override; property UpdateId: Integer read fUpdateId; property Message: TTelegramMessageObj read fMessage; end; { TTelegramMessageObj } TTelegramMessageObj = class(TTelegramObj) private fMessageId: Integer; fChatId: Integer; fText: string; fEntities: TTelegramUpdateObjList; public constructor Create(JSONObject: TJSONObject); override; destructor Destroy; override; property MessageId: Integer read fMessageId; property ChatId: Integer read fChatId; property Text: string read fText; property Entities: TTelegramUpdateObjList read fEntities; end; { TTelegramMessageEntityObj } TTelegramMessageEntityObj = class(TTelegramObj) private fTypeEntity: string; fOffset: Integer; fLength: Integer; public constructor Create(JSONObject: TJSONObject); override; property TypeEntity: string read fTypeEntity; property Offset: Integer read fOffset; property Length: Integer read fLength; end; { TTGQueueRequestsThread } TTGQueneProcessorThread = class(TThread) private fToken: string; fQueue: TFLQueue; protected procedure Execute; override; public constructor Create(const aToken: string; aPower : NativeInt = 10); destructor Destroy; override; procedure AddUpdateObj(UpdateObj: TTelegramUpdateObj); end; { TTGLongPollThread } TTGLongPollThread = class(TThread) private fToken: string; fQueneProcessor: TTGQueneProcessorThread; protected function StreamToJSONObject(Stream: TMemoryStream): TJSONObject; function GetUpdates(HTTPClient: TFPHTTPClient; aOffset: Integer): Integer; procedure Execute; override; public constructor Create(const aToken: string); destructor Destroy; override; end; const TELEGRAM_REQUEST_GETUPDATES = 'getUpdates'; implementation { TTelegramObj } constructor TTelegramObj.Create(JSONObject: TJSONObject); begin fJSON := JSONObject.Clone as TJSONObject; end; class function TTelegramObj.CreateFromJSONObject(JSONObject: TJSONObject): TTelegramObj; begin try if Assigned(JSONObject) then Result := Self.Create(JSONObject) else Result := nil; except Result := nil; end; end; { TTelegramUpdateObj } constructor TTelegramUpdateObj.Create(JSONObject: TJSONObject); begin inherited Create(JSONObject); fUpdateId := fJSON.Integers['update_id']; // объекты - не нашли?! - nil fMessage := TTelegramMessageObj.CreateFromJSONObject(fJSON.Find('message', jtObject) as TJSONObject) as TTelegramMessageObj; end; { TTelegramMessageObj } constructor TTelegramMessageObj.Create(JSONObject: TJSONObject); var lJSONArray: TJSONArray; lJSONEnum: TJSONEnum; begin inherited Create(JSONObject); fMessageId := fJSON.Integers['message_id']; fChatId := fJSON.Objects['chat'].Integers['id']; // простые типы - не нашли?! - дефолтное значение fText := fJSON.Get('text', ''); fEntities := TTelegramUpdateObjList.Create; lJSONArray := fJSON.Find('entities', jtArray) as TJSONArray; if Assigned(lJSONArray) then for lJSONEnum in lJSONArray do fEntities.Add(TTelegramMessageEntityObj.CreateFromJSONObject(lJSONEnum.Value as TJSONObject) as TTelegramMessageEntityObj); end; destructor TTelegramMessageObj.Destroy; begin fEntities.Free; inherited Destroy; end; { TTelegramMessageEntityObj } constructor TTelegramMessageEntityObj.Create(JSONObject: TJSONObject); begin inherited Create(JSONObject); fTypeEntity := fJSON.Strings['type']; fOffset := fJSON.Integers['offset']; fLength := fJSON.Integers['length']; end; { TTGQueneProcessorThread } procedure TTGQueneProcessorThread.Execute; var lUpdateObj: TTelegramUpdateObj; lMessageEntityObj: TTelegramMessageEntityObj; lHTTPClient: TFPHTTPClient; lCommand: string; begin lHTTPClient := TFPHTTPClient.Create(nil); try while not Terminated do while fQueue.length <> 0 do begin lUpdateObj := fQueue.pop as TTelegramUpdateObj; if Assigned(lUpdateObj.Message) then for lMessageEntityObj in lUpdateObj.Message.Entities do if (lMessageEntityObj.TypeEntity = 'bot_command') and (lMessageEntityObj.Offset = 0) then begin lCommand := Copy(lUpdateObj.Message.Text, lMessageEntityObj.Offset, lMessageEntityObj.Length); if lCommand = '/help' or lCommand = '/start' then begin lHTTPClient.Get('https://api.telegram.org/bot' + fToken + '/sendMessage?chat_id=' + IntToStr(lUpdateObj.Message.ChatId) + '&parse_mode=Markdown&text=' + EncodeURLElement( '*Привет!' + #$F0#$9F#$98#$81 + 'Я умеею показывать расписание.*') ); end; end; end; finally lHTTPClient.Free; end; end; constructor TTGQueneProcessorThread.Create(const aToken: string; aPower : NativeInt); begin FreeOnTerminate := False; inherited Create(False); fToken := aToken; fQueue := TFLQueue.Create(10); end; destructor TTGQueneProcessorThread.Destroy; begin fQueue.Free; inherited Destroy; end; procedure TTGQueneProcessorThread.AddUpdateObj(UpdateObj: TTelegramUpdateObj); begin fQueue.push(UpdateObj); end; { TTGLongPollThread } function TTGLongPollThread.StreamToJSONObject(Stream: TMemoryStream): TJSONObject; var lParser: TJSONParser; lJSON: TJSONObject; begin Result := nil; if Stream.Size > 0 then begin Stream.Position := 0; lParser := TJSONParser.Create(Stream); try try lJSON := lParser.Parse as TJSONObject; if lJSON.Booleans['ok'] then Result := lJSON; except end; finally lParser.Free; end; end; end; function TTGLongPollThread.GetUpdates(HTTPClient: TFPHTTPClient; aOffset: Integer): Integer; var lData: TMemoryStream; lJSON: TJSONObject; lJSONArray: TJSONArray; lJSONEnum: TJSONEnum; lUpdateObj: TTelegramUpdateObj; begin Result := 0; lData := TMemoryStream.Create; try if aOffset > 0 then HTTPClient.Get('https://api.telegram.org/bot' + fToken + '/getUpdates?offset=' + IntToStr(aOffset) + '&timeout=30', lData) else HTTPClient.Get('https://api.telegram.org/bot' + fToken + '/getUpdates?timeout=30', lData); lJSON := StreamToJSONObject(lData); if Assigned(lJSON) then try lJSONArray := lJSON.Find('result', jtArray) as TJSONArray; if Assigned(lJSONArray) then for lJSONEnum in lJSONArray do begin lUpdateObj := TTelegramUpdateObj.CreateFromJSONObject(lJSONEnum.Value as TJSONObject) as TTelegramUpdateObj; fQueneProcessor.AddUpdateObj(lUpdateObj); Result := Max(Result, lUpdateObj.UpdateId); end; except end; lData.Clear; finally lData.Free; end; end; procedure TTGLongPollThread.Execute; var lOffset: Integer; lHTTPClient: TFPHTTPClient; begin lHTTPClient := TFPHTTPClient.Create(nil); try while not Terminated do begin lOffset := GetUpdates(lHTTPClient, lOffset); // next! if lOffset > 0 then lOffset := lOffset + 1; end; finally lHTTPClient.Free; end; end; constructor TTGLongPollThread.Create(const aToken: string); begin FreeOnTerminate := False; inherited Create(False); fToken := aToken; fQueneProcessor := TTGQueneProcessorThread.Create(fToken, 10); end; destructor TTGLongPollThread.Destroy; begin fQueneProcessor.Terminate; fQueneProcessor.WaitFor; fQueneProcessor.Free; inherited Destroy; end; end.
{---------------------------------------------------------------------- DEVIUM Content Management System Copyright (C) 2004 by DEIV Development Team. http://www.deiv.com/ $Header: /devium/Devium\040CMS\0402/Source/Common/DeviumLib.pas,v 1.5 2004/05/14 09:38:10 paladin Exp $ ------------------------------------------------------------------------} unit DeviumLib; interface uses DBClient, Classes, Windows; procedure OpenDataSet(DataSet: TClientDataSet; const Prefix, Path: String); function TransLiterStr(const Value: String): String; function LowerCaseRus(const S: string): string; procedure ApplyUpdates(DM: TDataModule); function CanApplyUpdates(DM: TDataModule): Boolean; procedure Close(DM: TDataModule); procedure Open(DM: TDataModule; const DataBasePrefix, DataPath: String); procedure SoapConnectionAfterExecute(const MethodName: String; SOAPResponse: TStream); procedure DeleteDataFiles(DM: TDataModule); function UnixPathToDosPath(const Path: string): string; function DosPathToUnixPath(const Path: string): string; // files function ForceDeleteDir(const AName: String): Boolean; function ForceDeleteDirOrFile(const AName: String): Boolean; // Unix timestamp // введена из-за проблем с часовыми поясами function DateTimeToUnixPHP(const AValue: TDateTime): Int64; function UnixToDateTimePHP(const AValue: Int64): TDateTime; implementation uses StrUtils, XMLDoc, ZLIBEX, EncdDecd, SysUtils, DateUtils; function DateTimeToUnixPHP(const AValue: TDateTime): Int64; var lpUniversalTime, lpLocalTime: TSystemTime; lpFileTime, lpFileTimeUTC: TFileTime; begin DateTimeToSystemTime(AValue, lpLocalTime); SystemTimeToFileTime(lpLocalTime, lpFileTime); LocalFileTimeToFileTime(lpFileTime, lpFileTimeUTC); FileTimeToSystemTime(lpFileTimeUTC, lpUniversalTime); Result := DateTimeToUnix(SystemTimeToDateTime(lpUniversalTime)); end; function UnixToDateTimePHP(const AValue: Int64): TDateTime; var lpTimeZoneInformation: TIME_ZONE_INFORMATION; lpUniversalTime, lpLocalTime: TSystemTime; begin GetTimeZoneInformation(lpTimeZoneInformation); DateTimeToSystemTime(UnixToDateTime(AValue), lpUniversalTime); SystemTimeToTzSpecificLocalTime(@lpTimeZoneInformation, lpUniversalTime,lpLocalTime); Result := SystemTimeToDateTime(lpLocalTime); end; function ForceDeleteDir(const AName: String): Boolean; var sr: TSearchRec; Name, FullPath: String; begin Name := IncludeTrailingPathDelimiter(AName); if FindFirst(Name + '*.*', faAnyFile, sr) = 0 then begin repeat if ((sr.Name <> '.') and (sr.Name <> '..')) then begin FullPath := Name + sr.Name; if ((sr.Attr and faDirectory) = faDirectory) then ForceDeleteDir(FullPath) else DeleteFile(FullPath); end; until FindNext(sr) <> 0; FindClose(sr); end; Result := RemoveDir(Name) end; function ForceDeleteDirOrFile(const AName: String): Boolean; begin if FileExists(AName) then Result := DeleteFile(AName) else Result := ForceDeleteDir(AName) end; procedure DeleteDataFiles(DM: TDataModule); var DataSet: TClientDataSet; i: Integer; begin for i := 0 to DM.ComponentCount - 1 do begin if (DM.Components[i] is TClientDataSet) then begin DataSet := TClientDataSet(DM.Components[i]); if Assigned(DataSet.RemoteServer) then DeleteFile(DataSet.FileName); end; end; end; function TranslateChar(const Str: string; FromChar, ToChar: Char): string; var I: Integer; begin Result := Str; for I := 1 to Length(Result) do if Result[I] = FromChar then Result[I] := ToChar else if Result[I] = '?' then Break; end; function UnixPathToDosPath(const Path: string): string; begin Result := TranslateChar(Path, '/', '\'); end; function DosPathToUnixPath(const Path: string): string; begin Result := TranslateChar(Path, '\', '/'); end; procedure SoapConnectionAfterExecute(const MethodName: String; SOAPResponse: TStream); var s: String; XMLDocument: TXMLDocument; begin if MethodName = 'AS_ApplyUpdates' then Exit; XMLDocument := TXMLDocument.Create(nil); try SOAPResponse.Position := 0; XMLDocument.LoadFromStream(SOAPResponse); while not XMLDocument.IsEmptyDoc do ; s := XMLDocument.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes[0].Text; s := DecodeString(s); s := ZDecompressStr(s); s := EncodeString(s); XMLDocument.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes[0].Text := s; SOAPResponse.Size := 0; XMLDocument.SaveToStream(SOAPResponse); finally XMLDocument.Free; end; end; procedure Open(DM: TDataModule; const DataBasePrefix, DataPath: String); var DataSet: TClientDataSet; i: Integer; begin for i := 0 to DM.ComponentCount - 1 do begin if (DM.Components[i] is TClientDataSet) then begin DataSet := TClientDataSet(DM.Components[i]); if Assigned(DataSet.RemoteServer) then OpenDataSet(DataSet, DataBasePrefix, DataPath) end; end; end; procedure Close(DM: TDataModule); var i: Integer; begin for i := 0 to DM.ComponentCount - 1 do begin if (DM.Components[i] is TClientDataSet) then TClientDataSet(DM.Components[i]).Close; end; end; function CanApplyUpdates(DM: TDataModule): Boolean; var DataSet: TClientDataSet; i: Integer; begin Result := False; for i := 0 to DM.ComponentCount - 1 do begin if (DM.Components[i] is TClientDataSet) then begin DataSet := TClientDataSet(DM.Components[i]); if Assigned(DataSet.RemoteServer) then Result := Result or (DataSet.ChangeCount > 0); end; end; end; procedure ApplyUpdates(DM: TDataModule); var DataSet: TClientDataSet; i: Integer; begin for i := 0 to DM.ComponentCount - 1 do begin if (DM.Components[i] is TClientDataSet) then begin DataSet := TClientDataSet(DM.Components[i]); if Assigned(DataSet.RemoteServer) and (DataSet.ChangeCount > 0) then DataSet.ApplyUpdates(-1); end; end; end; procedure OpenDataSet(DataSet: TClientDataSet; const Prefix, Path: String); begin DataSet.ProviderName := Prefix + DataSet.ProviderName; DataSet.FileName := Path + DataSet.ProviderName + '.xml'; DataSet.Open; DataSet.SaveToFile(); end; function LowerCaseRus(const S: string): string; var Ch: Char; L: Integer; Source, Dest: PChar; begin L := Length(S); SetLength(Result, L); Source := Pointer(S); Dest := Pointer(Result); while L <> 0 do begin Ch := Source^; if (Ch >= 'А') and (Ch <= 'Я') then Inc(Ch, 32); Dest^ := Ch; Inc(Source); Inc(Dest); Dec(L); end; Result := LowerCase(Result); end; function TransLiterStr(const Value: String): String; var i:Integer; S: String; begin Result := ''; S := LowerCaseRus(AnsiReplaceText(Value, ' ', '_')); for i:=1 to Length(S) do case S[i] Of 'а':Result := Result +'a'; 'б':Result := Result +'b'; 'в':Result := Result +'v'; 'г':Result := Result +'g'; 'д':Result := Result +'d'; 'е':Result := Result +'e'; 'ё':Result := Result +'yo'; 'ж':Result := Result +'zh'; 'з':Result := Result +'z'; 'и':Result := Result +'i'; 'й':Result := Result +'y'; 'к':Result := Result +'k'; 'л':Result := Result +'l'; 'м':Result := Result +'m'; 'н':Result := Result +'n'; 'о':Result := Result +'o'; 'п':Result := Result +'p'; 'р':Result := Result +'r'; 'с':Result := Result +'s'; 'т':Result := Result +'t'; 'у':Result := Result +'u'; 'ф':Result := Result +'f'; 'х':Result := Result +'h'; 'ц':Result := Result +'c'; 'ч':Result := Result +'ch'; 'ш':Result := Result +'sh'; 'щ':Result := Result +'sch'; 'ы':Result := Result +'i'; 'э':Result := Result +'e'; 'ю':Result := Result +'yu'; 'я':Result := Result +'ya'; else Result := Result + S[i]; end; //[a-z_0-9-]+ s := Result; Result := ''; for i:=1 to Length(S) do case S[i] Of 'a'..'z', '0'..'9', '_', '-': Result := Result + S[i]; end; end; end.
unit CRPetrolRegionsReportFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PetrolRegionsEditorForm, StdCtrls, ExtCtrls, CommonFrame, CommonParentChildTreeFrame, Mask, ToolEdit; type TfrmPetrolRegionsReport = class(TfrmPetrolRegionsEditor) gbxSettings: TGroupBox; chbxAreaTotals: TCheckBox; chbxNGRTotals: TCheckBox; chbxNGOTotals: TCheckBox; chbxOverallTotal: TCheckBox; chbxSaveFiles: TCheckBox; edtReportPath: TDirectoryEdit; procedure chbxSaveFilesClick(Sender: TObject); private function GetAreaTotals: boolean; function GetNGOTotals: boolean; function GetNGRTotals: boolean; function GetOverallTotal: boolean; function GetSaveResult: boolean; function GetSavingPath: string; { Private declarations } public { Public declarations } property AreaTotals: boolean read GetAreaTotals; property NGRTotals: boolean read GetNGRTotals; property NGOTotals: boolean read GetNGOTotals; property OverallTotal: boolean read GetOverallTotal; property SaveResult: boolean read GetSaveResult; property SavingPath: string read GetSavingPath; constructor Create(AOwner: TComponent); override; end; var frmPetrolRegionsReport: TfrmPetrolRegionsReport; implementation {$R *.dfm} { TfrmPetrolRegionsReport } function TfrmPetrolRegionsReport.GetAreaTotals: boolean; begin Result := chbxAreaTotals.Checked; end; function TfrmPetrolRegionsReport.GetNGOTotals: boolean; begin Result := chbxNGOTotals.Checked; end; function TfrmPetrolRegionsReport.GetNGRTotals: boolean; begin Result := chbxNGRTotals.Checked; end; function TfrmPetrolRegionsReport.GetOverallTotal: boolean; begin Result := chbxOverallTotal.Checked; end; function TfrmPetrolRegionsReport.GetSaveResult: boolean; begin result := chbxSaveFiles.Checked; end; function TfrmPetrolRegionsReport.GetSavingPath: string; begin Result := edtReportPath.Text; end; procedure TfrmPetrolRegionsReport.chbxSaveFilesClick(Sender: TObject); begin inherited; edtReportPath.Enabled := chbxSaveFiles.Checked; end; constructor TfrmPetrolRegionsReport.Create(AOwner: TComponent); begin inherited; edtReportPath.Enabled := chbxSaveFiles.Checked; end; end.
unit uDebugLock; interface uses Classes, Windows, SysUtils; type TDebugLockItem = packed record ThreadId: Cardinal; Msg: string; MsgLast: string; LastTick: Cardinal; end; PDebugLockItem = ^TDebugLockItem; TDebugLock = class FLock: TRTLCriticalSection; FList: TList; private procedure Lock; procedure Unlock; procedure Clean; public constructor Create; destructor Destroy; override; public procedure AddDebug(ThreadId: Cardinal); procedure RemoveDebug(ThreadId: Cardinal); public procedure Debug(Msg: string); function TrackDebug: string; end; var DebugLock: TDebugLock; implementation { TDebugLock } procedure TDebugLock.AddDebug(ThreadId: Cardinal); var DebugLockItem: PDebugLockItem; begin New(DebugLockItem); DebugLockItem^.ThreadId := ThreadId; DebugLockItem^.Msg := ''; DebugLockItem^.MsgLast := ''; DebugLockItem^.LastTick := GetTickCount; Lock; try FList.Add(DebugLockItem); finally Unlock; end; end; procedure TDebugLock.Clean; var I: Integer; begin Lock; try for I := 0 to FList.Count - 1 do begin Dispose(PDebugLockItem(FList.Items[I])); end; FList.Clear; finally Unlock; end; end; constructor TDebugLock.Create; begin inherited Create; InitializeCriticalSection(FLock); FList := TList.Create; end; procedure TDebugLock.Debug(Msg: string); var ThreadId: Cardinal; I: Integer; Index: Integer; DebugLockItem: PDebugLockItem; begin ThreadId := GetCurrentThreadId; Index := -1; Lock; try for I := 0 to FList.Count - 1 do begin if PDebugLockItem(FList.Items[I])^.ThreadId = ThreadId then begin Index := I; Break; end; end; finally Unlock; end; if Index > -1 then begin PDebugLockItem(FList.Items[I])^.Msg := PDebugLockItem(FList.Items[I])^.MsgLast; PDebugLockItem(FList.Items[I])^.MsgLast := Msg; PDebugLockItem(FList.Items[I])^.LastTick := GetTickCount; end else begin { New(DebugLockItem); DebugLockItem^.ThreadId := ThreadId; DebugLockItem^.Msg := ''; DebugLockItem^.MsgLast := Msg; DebugLockItem^.LastTick := GetTickCount; Lock; try FList.Add(DebugLockItem); finally Unlock; end; } end; end; destructor TDebugLock.Destroy; begin Clean; FList.Free; DeleteCriticalSection(FLock); inherited Destroy; end; procedure TDebugLock.Lock; begin EnterCriticalSection(FLock); end; procedure TDebugLock.RemoveDebug(ThreadId: Cardinal); var I: Integer; DebugLockItem: PDebugLockItem; begin DebugLockItem := nil; Lock; try for I := 0 to FList.Count - 1 do begin if PDebugLockItem(FList.Items[I])^.ThreadId = ThreadId then begin DebugLockItem := FList.Items[I]; FList.Delete(I); Break; end; end; finally Unlock; end; if DebugLockItem <> nil then begin Dispose(DebugLockItem); end; end; function TDebugLock.TrackDebug: string; var I: Integer; DebugLockItem: PDebugLockItem; begin Result := '--TDebugLock.TrackDebug--' + #13#10; Lock; try for I := 0 to FList.Count - 1 do begin DebugLockItem := FList.Items[I]; Result := Result + Format('ThreadId: %u, Msg: %s -> LastMsg: %s, LastTick: %dms' , [DebugLockItem^.ThreadId, DebugLockItem^.Msg, DebugLockItem^.MsgLast, GetTickCount - DebugLockItem^.LastTick]) + #13#10; end; finally Unlock; end; end; procedure TDebugLock.Unlock; begin LeaveCriticalSection(FLock); end; initialization DebugLock := TDebugLock.Create; finalization DebugLock.Free; end.
unit LNetHTTPDataProvider; {$mode objfpc}{$H+} interface uses Forms, Classes, SysUtils, IpHtml, IpMsg, IpUtils, lnetcomponents, Graphics, lhttp, lnet; type TIpHTTPDataProvider = class; TGettingURLCB = procedure(AProvider: TIpHTTPDataProvider; AURL: String) of object; { TIpHTTPDataProvider } TIpHTTPDataProvider = class(TIpAbstractHtmlDataProvider) private fLastType: String; fCachedStreams: TStringList; fCachedEmbeddedObjects: TStringList; procedure AddObjectToCache(ACache: TStringList; AURL: String; AStream: TStream); procedure ClearCache; procedure ClearCachedObjects; function GetCachedURL(AURL: String): TStream; function GetCachedObject(AURL: String): TStream; procedure HttpError(const msg: string; aSocket: TLSocket); function HttpInput(ASocket: TLHTTPClientSocket; ABuffer: pchar; ASize: LongInt): LongInt; procedure HttpInputDone(ASocket: TLHTTPClientSocket); procedure HttpProcessHeader(ASocket: TLHTTPClientSocket); procedure HttpCanWrite(ASocket: TLHTTPClientSocket; var OutputEof: TWriteBlockStatus); procedure HttpDisconnect(aSocket: TLSocket); function GetURL(const AURL: String; JustHeader: Boolean = False): TStream; function GetHostAndURI(const fURL: String; var AHost: String; var AURI: String): Boolean; protected function DoGetHtmlStream(const URL: string; PostData: TIpFormDataEntity) : TStream; override; function DoCheckURL(const URL: string; var ContentType: string): Boolean; override; procedure DoLeave(Html: TIpHtml); override; procedure DoReference(const URL: string); override; procedure DoGetImage(Sender: TIpHtmlNode; const URL: string; var Picture: TPicture); override; function DoGetStream(const URL: string): TStream; override; function CanHandle(const URL: string): Boolean; override; function BuildURL(const OldURL, NewURL: string): string; override; public constructor Create(AOwner: TComponent); destructor Destroy; override; end; TLHttpClientEx = class(TLHTTPClientComponent) //TLHttpClientEx = class(TLHTTPClient) private Stream: TStream; Waiting: Boolean; HeaderOnly: Boolean; end; implementation uses FPImage, {$IF FPC_FULLVERSION>=20602} //fpreadgif exists since at least this version FPReadgif, {$ENDIF} FPReadbmp, FPReadxpm, FPReadJPEG, FPReadpng, FPWritebmp, IntFGraphics; { TIpHTTPDataProvider } procedure TIpHTTPDataProvider.AddObjectToCache ( ACache: TStringList; AURL: String; AStream: TStream ) ; var TmpStream: TStream; begin TmpStream := TMemoryStream.Create; AStream.Position := 0; TmpStream.CopyFrom(AStream, AStream.Size); ACache.AddObject(AURL, TmpStream); AStream.Position := 0; end; procedure TIpHTTPDataProvider.ClearCache; var i: Integer; begin for i := 0 to fCachedStreams.Count-1 do if fCachedStreams.Objects[i] <> nil then fCachedStreams.Objects[i].Free; fCachedStreams.Clear; end; procedure TIpHTTPDataProvider.ClearCachedObjects; var i: Integer; begin for i := 0 to fCachedStreams.Count-1 do if fCachedEmbeddedObjects.Objects[i] <> nil then fCachedEmbeddedObjects.Objects[i].Free; fCachedEmbeddedObjects.Clear; end; function TIpHTTPDataProvider.GetCachedURL ( AURL: String ) : TStream; var i: Integer; begin Result := nil; if Trim(AURL) = '' then Exit; for i := 0 to fCachedStreams.Count-1 do if fCachedStreams.Strings[i] = AURL then begin if fCachedStreams.Objects[i] = nil then break; Result := TMemoryStream.Create; TStream(fCachedStreams.Objects[i]).Position := 0; Result.CopyFrom(TStream(fCachedStreams.Objects[i]), TStream(fCachedStreams.Objects[i]).Size); Result.Position := 0; break; end; //WriteLn(AURL,' in cache = ', Result <> nil); if Result = nil then Result := GetCachedObject(AURL); end; function TIpHTTPDataProvider.GetCachedObject ( AURL: String ) : TStream; var i: Integer; begin Result := nil; if Trim(AURL) = '' then Exit; for i := 0 to fCachedEmbeddedObjects.Count-1 do if fCachedEmbeddedObjects.Strings[i] = AURL then begin if fCachedEmbeddedObjects.Objects[i] = nil then break; Result := TMemoryStream.Create; TStream(fCachedEmbeddedObjects.Objects[i]).Position := 0; Result.CopyFrom(TStream(fCachedEmbeddedObjects.Objects[i]), TStream(fCachedEmbeddedObjects.Objects[i]).Size); Result.Position := 0; break; end; //WriteLn(AURL,' in cached objects = ', Result <> nil); end; procedure TIpHTTPDataProvider.HttpError(const msg: string; aSocket: TLSocket); begin TLHttpClientEx(ASocket.Creator).Waiting := False; //writeLn('Error occured: ', msg); end; function TIpHTTPDataProvider.HttpInput(ASocket: TLHTTPClientSocket; ABuffer: pchar; ASize: LongInt): LongInt; begin //WriteLN(ASocket.Creator.ClassName); if TLHttpClientEx(ASocket.Creator).Stream = nil then TLHttpClientEx(ASocket.Creator).Stream := TMemoryStream.Create; Result := TLHttpClientEx(ASocket.Creator).Stream.Write(ABuffer^, ASize); end; procedure TIpHTTPDataProvider.HttpInputDone(ASocket: TLHTTPClientSocket); begin TLHttpClientEx(ASocket.Creator).Waiting := False; aSocket.Disconnect; //WriteLn('InputDone'); end; procedure TIpHTTPDataProvider.HttpProcessHeader(ASocket: TLHTTPClientSocket); var i: TLHTTPParameter; begin //WriteLn('Process Header'); //for i := Low(TLHTTPParameterArray) to High(TLHTTPParameterArray) do // if ASocket.Parameters[i] <> '' then // WriteLn(ASocket.Parameters[i]); //WriteLn(ASocket.Parameters[hpContentType]); fLastType := ASocket.Parameters[hpContentType]; if TLHttpClientEx(ASocket.Creator).HeaderOnly then TLHttpClientEx(ASocket.Creator).Waiting := False; end; procedure TIpHTTPDataProvider.HttpCanWrite(ASocket: TLHTTPClientSocket; var OutputEof: TWriteBlockStatus); begin //WriteLn('OnCanWrite'); end; procedure TIpHTTPDataProvider.HttpDisconnect(aSocket: TLSocket); begin TLHttpClientEx(ASocket.Creator).Waiting := False; //WriteLn('Disconnected'); end; function TIpHTTPDataProvider.GetURL(const AURL: String; JustHeader: Boolean = False): TStream; var fHost, fURI: String; fHttpClient: TLHttpClientEx; begin Result := nil; if JustHeader = False then Result := GetCachedURL(AURL); //WriteLN('Getting: ', AURL); if Result = nil then begin if not GetHostAndURI(AURL, fHost, fURI) then Exit(nil); //WriteLn('Result := True'); fHttpClient := TLHttpClientEx.Create(Owner); fHttpClient.OnInput := @HttpInput; fHttpClient.OnError := @HttpError; fHttpClient.OnDoneInput := @HttpInputDone; fHttpClient.OnProcessHeaders := @HttpProcessHeader; fHttpClient.OnCanWrite := @HttpCanWrite; fHttpClient.OnDisconnect := @HttpDisconnect; fHttpClient.Host := fHost; fHttpClient.Port := 80; fHttpClient.HeaderOnly := JustHeader; if JustHeader then fHttpClient.Method := hmHead else fHttpClient.Method := hmGet; fHttpClient.URI := fURI; fHttpClient.SendRequest; //WriteLn('Sending Request'); fHttpClient.Waiting := True; {while fHttpClient.Waiting = True do begin fHttpClient.CallAction; Sleep(1); end;} while fHttpClient.Waiting do begin //WriteLn('InFirstLoop'); Application.HandleMessage; if csDestroying in ComponentState then Exit; end; //WriteLn('LeftLoop'); Result:= fHttpClient.Stream; if Result <> nil then Result.Position := 0; //fDataStream.SaveToFile('temp.txt'); //Application.Terminate; fHttpClient.Free; end; end; function TIpHTTPDataProvider.GetHostAndURI(const fURL: String; var AHost: String; var AURI: String): Boolean; var fPos: Integer; begin fPos := Pos('://', fUrl); if fPos = 0 then Exit(False); Result := True; AHost := Copy(fURL, fPos+3, Length(fURL)); fPos := Pos('/', AHost); if fPos = 0 then begin AURI:='/'; Exit(True); end; AURI := Copy(AHost, fPos, Length(AHost)); AHost := Copy(AHost, 1, fPos-1); //WriteLn('Got Host: ',AHost); //WriteLn('Got URI : ',AURI); end; function TIpHTTPDataProvider.DoGetHtmlStream(const URL: string; PostData: TIpFormDataEntity): TStream; begin Result := GetCachedURL(URL); if Result = nil then begin Result := GetURL(URL); if Result <> nil then AddObjectToCache(fCachedStreams, URL, Result); end; end; function TIpHTTPDataProvider.DoCheckURL(const URL: string; var ContentType: string): Boolean; var TmpStream: TStream; begin //WriteLn('Want content type: "', ContentType,'" for Url:',URL); Result := True; //TmpStream := GetCachedURL(URL); //if TmpStream = nil then //begin TmpStream := GetURL(URL, True); // if TmpStream <> nil then // AddObjectToCache(fCachedStreams, URL, TmpStream); //end; if TmpStream <> nil then FreeAndNil(TmpStream); ContentType := fLastType;//}'text/html'; end; procedure TIpHTTPDataProvider.DoLeave(Html: TIpHtml); begin ClearCache; end; procedure TIpHTTPDataProvider.DoReference(const URL: string); begin end; procedure TIpHTTPDataProvider.DoGetImage(Sender: TIpHtmlNode; const URL: string; var Picture: TPicture); var Stream: TStream; FileExt: String; begin //DebugLn('Getting Image ',(Url)); Picture := nil; FileExt := ExtractFileExt(URL); Picture := TPicture.Create; try Stream := GetCachedObject(URL); if Stream = nil then begin Stream := GetURL(URL); if Stream <> nil then AddObjectToCache(fCachedEmbeddedObjects, URL, Stream); end; if Assigned(Stream) then begin Stream.Position := 0; Picture.LoadFromStreamWithFileExt(Stream, FileExt); end else Picture.Graphic := TBitmap.Create; except try Picture.Free; finally Picture := TPicture.Create; Picture.Graphic := TBitmap.Create; end; end; Stream.Free; end; function TIpHTTPDataProvider.DoGetStream ( const URL: string ) : TStream; begin Result := GetCachedObject(URL); if Result = nil then begin Result := GetURL(URL); if Result <> nil then AddObjectToCache(fCachedEmbeddedObjects, URL, Result); end; end; function TIpHTTPDataProvider.CanHandle(const URL: string): Boolean; begin //WriteLn('Can Handle: ', URL); Result := True; end; function TIpHTTPDataProvider.BuildURL(const OldURL, NewURL: string): string; begin Result := Iputils.BuildURL(OldURL, NewURL); end; constructor TIpHTTPDataProvider.Create(AOwner: TComponent); begin inherited Create(AOwner); fCachedEmbeddedObjects := TStringList.Create; fCachedStreams := TStringList.Create; end; destructor TIpHTTPDataProvider.Destroy; begin ClearCache; ClearCachedObjects; fCachedStreams.Free; fCachedEmbeddedObjects.Free; inherited Destroy; end; end.
unit uInNomineSkills; interface uses SysUtils, uInNomineSystem; function GetAllSkills: TSkills; implementation function GetAllSkills: TSkills; var i: integer; begin for i := 0 to NUMBER_OF_SKILLS - 1 do Result[i] := TSkill.Create; Result[0].description := SKILLS_NAMES[0]; // acrobatics Result[0].attributes := [agility]; Result[0].defaultPenalty := -3; Result[0].needsSpecification := False; Result[1].description := SKILLS_NAMES[1]; // artistry Result[1].attributes := [perception]; Result[1].defaultPenalty := -2; Result[1].needsSpecification := False; Result[2].description := SKILLS_NAMES[2]; // chemistry Result[2].attributes := [intelligence]; Result[2].defaultPenalty := -5; Result[2].needsSpecification := False; Result[3].description := SKILLS_NAMES[3]; // climbing Result[3].attributes := [agility]; Result[3].defaultPenalty := -2; Result[3].needsSpecification := False; Result[4].description := SKILLS_NAMES[4]; // computer operation Result[4].attributes := [intelligence]; Result[4].defaultPenalty := -4; Result[4].needsSpecification := False; Result[5].description := SKILLS_NAMES[5]; // detect lies Result[5].attributes := [perception]; Result[5].defaultPenalty := -2; Result[5].needsSpecification := False; Result[6].description := SKILLS_NAMES[6]; // dodge Result[6].attributes := [agility]; Result[6].defaultPenalty := -1; Result[6].needsSpecification := False; Result[7].description := SKILLS_NAMES[7]; // driving Result[7].attributes := [perception]; Result[7].defaultPenalty := -2; Result[7].needsSpecification := True; Result[8].description := SKILLS_NAMES[8]; // eletronics Result[8].attributes := [intelligence, precision]; Result[8].defaultPenalty := -5; Result[8].needsSpecification := False; Result[9].description := SKILLS_NAMES[9]; //emote Result[9].attributes := [perception]; Result[9].defaultPenalty := -1; Result[9].needsSpecification := False; Result[10].description := SKILLS_NAMES[10]; // engineering Result[10].attributes := [precision]; Result[10].defaultPenalty := -4; Result[10].needsSpecification := False; Result[11].description := SKILLS_NAMES[11]; // escape Result[11].attributes := [agility, precision]; Result[11].defaultPenalty := -3; Result[11].needsSpecification := False; Result[12].description := SKILLS_NAMES[12]; // fast-talk Result[12].attributes := [will]; Result[12].defaultPenalty := -1; Result[12].needsSpecification := False; Result[13].description := SKILLS_NAMES[13]; // fighting Result[13].attributes := [strength, will]; Result[13].defaultPenalty := -1; Result[13].needsSpecification := True; Result[14].description := SKILLS_NAMES[14]; // knowledge Result[14].attributes := [intelligence]; Result[14].defaultPenalty := -4; Result[14].needsSpecification := True; Result[15].description := SKILLS_NAMES[15]; // languages Result[15].attributes := [intelligence]; Result[15].defaultPenalty := -4; Result[15].needsSpecification := True; Result[16].description := SKILLS_NAMES[16]; // large weapon Result[16].attributes := [strength]; Result[16].defaultPenalty := -3; Result[16].needsSpecification := True; Result[17].description := SKILLS_NAMES[17]; // lockpicking Result[17].attributes := [precision]; Result[17].defaultPenalty := -3; Result[17].needsSpecification := False; Result[18].description := SKILLS_NAMES[18]; // lying Result[18].attributes := [intelligence, perception]; Result[18].defaultPenalty := -2; Result[18].needsSpecification := False; Result[19].description := SKILLS_NAMES[19]; // medicine Result[19].attributes := [precision]; Result[19].defaultPenalty := -4; Result[19].needsSpecification := False; Result[20].description := SKILLS_NAMES[20]; // move silently Result[20].attributes := [agility]; Result[20].defaultPenalty := -1; Result[20].needsSpecification := False; Result[21].description := SKILLS_NAMES[21]; // ranged weapon Result[21].attributes := [precision]; Result[21].defaultPenalty := -2; Result[21].needsSpecification := True; Result[22].description := SKILLS_NAMES[22]; // running Result[22].attributes := [strength, agility]; Result[22].defaultPenalty := -1; Result[22].needsSpecification := False; Result[23].description := SKILLS_NAMES[23]; // savoir-faire Result[23].attributes := [intelligence, precision]; Result[23].defaultPenalty := -4; Result[23].needsSpecification := False; Result[24].description := SKILLS_NAMES[24]; // seduction Result[24].attributes := [will]; Result[24].defaultPenalty := -1; Result[24].needsSpecification := False; Result[25].description := SKILLS_NAMES[25]; // singing Result[25].attributes := [perception]; Result[25].defaultPenalty := -2; Result[25].needsSpecification := False; Result[26].description := SKILLS_NAMES[26]; // small weapon Result[26].attributes := [precision]; Result[26].defaultPenalty := -2; Result[26].needsSpecification := True; Result[27].description := SKILLS_NAMES[27]; // survival Result[27].attributes := [will, perception]; Result[27].defaultPenalty := -4; Result[27].needsSpecification := True; Result[28].description := SKILLS_NAMES[28]; // swimming Result[28].attributes := [agility]; Result[28].defaultPenalty := -2; Result[28].needsSpecification := False; Result[29].description := SKILLS_NAMES[29]; // tactics Result[29].attributes := [intelligence]; Result[29].defaultPenalty := -2; Result[29].needsSpecification := False; Result[30].description := SKILLS_NAMES[30]; // throwing Result[30].attributes := [agility, precision]; Result[30].defaultPenalty := -3; Result[30].needsSpecification := False; Result[31].description := SKILLS_NAMES[31]; // tracking Result[31].attributes := [perception]; Result[31].defaultPenalty := -2; Result[31].needsSpecification := False; end; end.
// Copyright (c) Maxim Puchkin, Stanislav Mihalkovich (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) ///Модуль реализует воспроизведение речи (text-to-speech) на английском и русском. ///Также реализовано распознавание речи (speech recognition) русского и английского языков. ///Используется платформа Microsoft Speech Platform 11. unit SpeechABC; {$reference 'Microsoft.Speech.dll'} {Для корректной работы должны быть скачаны и установлены языки - для синтеза речи, и для распознавания. 1. Скачать и установить Runtime - https://www.microsoft.com/en-us/download/details.aspx?id=27225 2. Необязательно – скачать и установить SDK - это, наверное, не нужно https://www.microsoft.com/en-us/download/details.aspx?id=27226 3. Скачать дополнительные языки - рекомендуются британский и английский, русский https://www.microsoft.com/en-us/download/details.aspx?id=27224 Там список. Из них те, что TTS - голоса, SR - распознавалки. Качать en-GB, en-US и ru-RU - их надо устанавливать. 4. В папке с этой программой должна быть Microsoft.Speech.dll, если её нет, то искать в папке, в которую установился SDK. } interface uses Microsoft.Speech; uses Microsoft.Speech.Synthesis; uses Microsoft.Speech.Recognition; uses System.Globalization; /// Языки для воспроизведения и распознавания. Британский и американский английский синтезатором не различаются type Languages = (Russian, English, American); /// Статус генератора речи type SpeakerState = (Ready, Speaking, Paused); /// Класс для воспроизведения речи type Speaker = class private synth : Microsoft.Speech.Synthesis.SpeechSynthesizer; Lang : Languages; AudioVol : integer := 99; currRuIndex, currEngIndex : integer; procedure SetLang(newLang : Languages); function GetLang : Languages; procedure SetVolume(Volume : integer); function GetVolume : integer; function GetRussianVoices : System.Collections.Generic.List<InstalledVoice>; function GetEnglishVoices : System.Collections.Generic.List<InstalledVoice>; function GetState : SpeakerState; public /// Язык воспроизведения речи – русский или английский property Language : Languages write SetLang; /// Громкость воспроизведения (от 0 до 100) property Volume : integer read GetVolume write SetVolume; /// Состояние воспроизведения речи property State : SpeakerState read GetState; /// Проговорить фразу. Язык и голос используются ранее заданные procedure Speak(Phrase : string); /// Проговорить фразу. Язык и голос используются ранее заданные. /// Не блокирует выполнение - программа продолжится не дожидаясь окончания фразы. procedure SpeakAsync(Phrase : string); /// Конструктор объекта воспроизведения речи с заданным языком constructor Create(Language : Languages := Languages.Russian); /// Конструктор с проговариванием указанной фразы. Язык выбирается автоматически constructor Create(Phrase : string); /// Выбор англоговорящего голоса по индексу (индексация от 0) procedure SelectEnglishVoice(VoiceIndex :integer := 0); /// Выбор русскоговорящего голоса по индексу (индексация от 0) procedure SelectRussianVoice(VoiceIndex :integer := 0); /// Выбор голоса по номеру для текущего языка(индексация от 0) procedure SelectVoice(VoiceIndex : integer); /// Количество установленных голосов для текущего языка function VoicesCount : integer; end; type RecognizerStates = (NotReady, Inited, Recognizing, Wait); type StringArray = array of string; /// Класс объектов для распознавания речи type Recognizer = class PhrasesArr : array of string; State : RecognizerStates; Recogn : Microsoft.Speech.Recognition.SpeechRecognitionEngine; LanguageDefined : boolean; Lang : Languages; function GetState : RecognizerStates; procedure SetPhrases(Phrases : array of string); /// Автоматическое распознавание языка фраз function DetectLanguage(Phrases : array of string) : Languages; procedure SetLang(Language : Languages); procedure SpeechRecognized(sender : object; e : Microsoft.Speech.Recognition.SpeechRecognizedEventArgs); procedure SpeechRecognitionRejected(sender : object; e : Microsoft.Speech.Recognition.SpeechRecognitionRejectedEventArgs); procedure RecognizeCompleted(sender : object; e : RecognizeCompletedEventArgs); function Init : boolean; public /// Обработчик события распознавания OnRecognized : procedure(Phrase : string); /// Обработчик ошибки распознавания OnError : procedure(Phrase : string); /// Язык распознавателя. Можно не указывать, тогда определяется по фразам для распознавания property Language : Languages write SetLang; /// Создание распознавателя с указанием языка constructor Create(Language : Languages := Languages.Russian); /// Создание распознавателя с указанием вариантов для распознавания. Язык выводится автоматически constructor Create(Phrases : array of string); /// Фразы для распознавания в виде массива строк. Результатом распознавания будет одна из этих фраз property Phrases : array of string write SetPhrases; //function Recognize : boolean; /// Старт распознавания. Объект должен быть корректно настроен - заданы фразы и указан обработчик procedure Start; /// Остановка распознавания procedure Stop; end; /// Информация об установленных "говорилках" и "голосах" procedure SpeechInfo; /// Озвучивание одной фразы. Язык выбирается автоматически procedure Say(Phrase : string); /// Воспроизведение одной фразы, не блокирующее procedure SayAsync(Phrase : string); /// Озвучивание одной фразы на русском procedure SayAsyncRus(Phrase : string); /// Озвучивание одной фразы на английском procedure SayAsyncEng(Phrase : string); //------------------------------------------------------------------------------ implementation /// Вывод вспомогательной информации и справки procedure SpeechInfo; begin /// Проверить наличие устройств воспроизведения и записи звука - не сделано /// Проверить установленные компоненты для воспроизведения и записи звука /// Проверить наличие голосов для распознавания и воспроизведения звука try begin var synth := new SpeechSynthesizer(); var iv := synth.GetInstalledVoices(CultureInfo.GetCultureInfoByIetfLanguageTag('ru-RU')); Writeln('Для корректной работы убедитесь, что у вас в системе установлено устройство воспроизведения звука и микрофон.'); var UnitReady := true; if iv.Count > 0 then begin WriteLn('Установлены русскоговорящие голоса:'); foreach var v in iv do writeln(' ', v.VoiceInfo.Name); end else begin UnitReady := false; WriteLn('Не установлен русскоговорящий голос!'); Write('Вам необходимо скачать и установить русскоговорящие голоса для синтеза речи. '); Write('Скачать можно со страницы https://www.microsoft.com/en-us/download/details.aspx?id=27224. '); Write('Русскоговорящие – голоса со строкой TTS_ru-RU в названии. Открыть страницу скачивания? [Y/N]'); if UpCase(ReadChar)='Y' then System.Diagnostics.Process.Start('https://www.microsoft.com/en-us/download/details.aspx?id=27224'); end; var ivUS := synth.GetInstalledVoices(CultureInfo.GetCultureInfoByIetfLanguageTag('en-US')); var ivGB := synth.GetInstalledVoices(CultureInfo.GetCultureInfoByIetfLanguageTag('en-GB')); var ivGB_US := ivUS.Concat(ivGB); if ivGB_US.Count > 0 then begin WriteLn('Установлены англоговорящие голоса:'); foreach var v in ivGB_US do writeln(' ', v.VoiceInfo.Name); end else begin UnitReady := false; WriteLn('Не установлен англоговорящий голос!'); Write('Вам необходимо скачать и установить англоговорящие голоса для синтеза речи. '); Write('Скачать можно со страницы https://www.microsoft.com/en-us/download/details.aspx?id=27224. '); Write('Англоговорящие – голоса со строкой TTS_en в названии. Открыть страницу скачивания? [Y/N]'); if UpCase(ReadChar)='Y' then System.Diagnostics.Process.Start('https://www.microsoft.com/en-us/download/details.aspx?id=27224'); end; // Проверяем установленные голоса для распознавания var RecognizerInfo := SpeechRecognitionEngine.InstalledRecognizers() .Where(ri -> (ri.Culture.Name = 'ru-RU')); if RecognizerInfo.Count > 0 then begin WriteLn('Установлены модули распознавания русского языка:'); foreach var v in RecognizerInfo do writeln(' ', v.Name); end else begin UnitReady := false; WriteLn('Не установлен модуль распознавания русской речи!'); Write('Вам необходимо скачать и установить распознаватели русской речи. '); Write('Скачать можно со страницы https://www.microsoft.com/en-us/download/details.aspx?id=27224. '); Write('Для английского языка – со строкой SR_ru-RU в названии. Открыть страницу скачивания? [Y/N]'); if UpCase(ReadChar)='Y' then System.Diagnostics.Process.Start('https://www.microsoft.com/en-us/download/details.aspx?id=27224'); end; RecognizerInfo := SpeechRecognitionEngine.InstalledRecognizers() .Where(ri -> (ri.Culture.Name = 'en-US')or(ri.Culture.Name = 'en-GB')); if RecognizerInfo.Count > 0 then begin WriteLn('Установлены модули распознавания английского языка:'); foreach var v in RecognizerInfo do writeln(' ', v.Name); end else begin UnitReady := false; WriteLn('Не установлен модуль распознавания английской речи!'); Write('Вам необходимо скачать и установить распознаватели английской речи. '); Write('Скачать можно со страницы https://www.microsoft.com/en-us/download/details.aspx?id=27224. '); Write('Для английского языка – со строкой SR_en-GB или SR_en-US в названии. Открыть страницу скачивания? [Y/N]'); if UpCase(ReadChar)='Y' then System.Diagnostics.Process.Start('https://www.microsoft.com/en-us/download/details.aspx?id=27224'); end; if UnitReady then WriteLn('Голоса и распознаватели обнаружены, модуль готов к работе.'); end except writeln('При получении информации возникла ошибка - проверьте корректность установки Microsoft Speech Platform.'); end; end; /// Автоматическое определения языка строки - английского или руского, по преобладанию букв соответствующего алфавита function DetectLanguage(Phrase : string) : Languages; begin var RussianLetters := 0; foreach var ch in phrase do begin var code := OrdUnicode(UpCase(ch)); if (code >= OrdUnicode('А')) and (code <= OrdUnicode('Я')) then inc(RussianLetters) else if (code >= OrdUnicode('A')) and (code <= OrdUnicode('Z')) then dec(RussianLetters); if Abs(RussianLetters)>=100 then begin if RussianLetters>=0 then Result := Languages.Russian else Result := Languages.English; exit; end; end; if RussianLetters>=0 then Result := Languages.Russian else Result := Languages.English; end; //------------------------------------------------------------------------------ constructor Speaker.Create(Language : Languages); begin synth := new SpeechSynthesizer; synth.SetOutputToDefaultAudioDevice; currRuIndex := 0; currEngIndex := 0; if Language=Languages.American then Language := Languages.English; SetLang(Language); end; constructor Speaker.Create(Phrase : string); begin synth := new SpeechSynthesizer; synth.SetOutputToDefaultAudioDevice; currRuIndex := 0; currEngIndex := 0; if Lang=Languages.American then Lang := Languages.English; SetLang(DetectLanguage(Phrase)); Speak(Phrase); end; function Speaker.GetRussianVoices : System.Collections.Generic.List<InstalledVoice>; begin Result := new System.Collections.Generic.List<InstalledVoice>(synth.GetInstalledVoices(CultureInfo.GetCultureInfoByIetfLanguageTag('ru-RU'))); end; function Speaker.GetEnglishVoices : System.Collections.Generic.List<InstalledVoice>; begin var ivUS := synth.GetInstalledVoices(CultureInfo.GetCultureInfoByIetfLanguageTag('en-US')); var ivGB := synth.GetInstalledVoices(CultureInfo.GetCultureInfoByIetfLanguageTag('en-GB')); var iv := ivUS.Concat(ivGB); Result := new System.Collections.Generic.List<InstalledVoice>(iv); end; function Speaker.GetState : SpeakerState; begin case synth.State of Microsoft.Speech.Synthesis.SynthesizerState.Ready : Result := SpeakerState.Ready; Microsoft.Speech.Synthesis.SynthesizerState.Paused : Result := SpeakerState.Paused; Microsoft.Speech.Synthesis.SynthesizerState.Speaking : Result := SpeakerState.Speaking; end; end; procedure Speaker.SetLang(newLang : Languages); begin if newLang=Languages.American then newLang := Languages.English; if newLang = lang then exit; if newLang = Languages.Russian then SelectRussianVoice(currRuIndex) else SelectEnglishVoice(currEngIndex); end; function Speaker.GetLang : Languages; begin Result := Lang; end; procedure Speaker.SetVolume(Volume : integer); begin AudioVol := min(100, max(0,Volume)); if synth <> nil then synth.Volume := AudioVol; end; function Speaker.GetVolume : integer; begin Result := AudioVol; end; procedure Speaker.Speak(Phrase : string); begin synth.Speak(Phrase); end; procedure Speaker.SpeakAsync(Phrase : string); begin var t := new System.Threading.Thread(() -> synth.Speak(Phrase)); t.Start(); end; procedure Speaker.SelectEnglishVoice(VoiceIndex :integer); begin var EngVC := GetEnglishVoices; var VoicesCount := EngVC.Count; if VoicesCount = 0 then raise new Exception('Ошибка! Не установлены англоговорящие голоса.'); currEngIndex := min(VoicesCount-1,max(0,VoiceIndex)); synth.SelectVoice(EngVC.ElementAt(currEngIndex).VoiceInfo.Name); Lang := Languages.English; end; procedure Speaker.SelectRussianVoice(VoiceIndex :integer); begin var RusVC := GetRussianVoices; var VoicesCount := GetRussianVoices.Count; if VoicesCount = 0 then raise new Exception('Ошибка! Не установлены русскоговорящие голоса.'); currRuIndex := min(VoicesCount-1,max(0,VoiceIndex)); synth.SelectVoice(RusVC.ElementAt(currRuIndex).VoiceInfo.Name); Lang := Languages.Russian; end; procedure Speaker.SelectVoice(VoiceIndex : integer); begin if Lang = Languages.American then Lang := Languages.English; var Voices : System.Collections.Generic.List<InstalledVoice>; if Lang = Languages.English then Voices := GetEnglishVoices else Voices := GetRussianVoices; VoiceIndex := max(0,min(Voices.Count-1,VoiceIndex)); synth.SelectVoice(Voices.ElementAt(VoiceIndex).VoiceInfo.Name); end; function Speaker.VoicesCount : integer; begin if Lang = Languages.Russian then Result := GetRussianVoices.Count else Result := GetEnglishVoices.Count; end; //------------------------------------------------------------------------------ constructor Recognizer.Create(Language : Languages); begin recogn := nil; lang := Language; languageDefined := true; State := RecognizerStates.NotReady; end; constructor Recognizer.Create(Phrases : array of string); begin recogn := nil; languageDefined := false; State := RecognizerStates.NotReady; SetPhrases(Phrases); end; /// Инициализация распознавателя function Recognizer.Init : boolean; begin if PhrasesArr.Length = 0 then begin Result := false; exit; end; if not LanguageDefined then Lang := DetectLanguage(PhrasesArr); LanguageDefined := true; var recognLanguage := 'ru-RU'; // Варианты: en-GB, en-US, ru-RU case Lang of Languages.American : recognLanguage := 'en-US'; Languages.English : recognLanguage := 'en-GB'; end; var RecognizerInfo := SpeechRecognitionEngine.InstalledRecognizers.Where(ri -> ri.Culture.Name = recognLanguage).FirstOrDefault(); if Recogn <> nil then begin if State = RecognizerStates.Recognizing then begin Recogn.RecognizeAsyncCancel; State := RecognizerStates.NotReady; end; Recogn.UnloadAllGrammars; end else begin Recogn := new Microsoft.Speech.Recognition.SpeechRecognitionEngine(RecognizerInfo.Id); Recogn.SpeechRecognized += SpeechRecognized; Recogn.SpeechRecognitionRejected += SpeechRecognitionRejected; Recogn.RecognizeCompleted += RecognizeCompleted; end; var Choises := new Microsoft.Speech.Recognition.Choices(); Choises.Add(PhrasesArr.ToArray); var gb := new Microsoft.Speech.Recognition.GrammarBuilder(); gb.Culture := RecognizerInfo.Culture; gb.Append(Choises); var gr := new Microsoft.Speech.Recognition.Grammar(gb); Recogn.LoadGrammar(gr); Recogn.RequestRecognizerUpdate(); try Recogn.SetInputToDefaultAudioDevice(); except Writeln('Не могу найти устройство записи звука (микрофон не подключен)'); end; state := RecognizerStates.Inited; end; function Recognizer.GetState : RecognizerStates; begin Result := State; end; procedure Recognizer.SetPhrases(Phrases : array of string); begin PhrasesArr := Copy(Phrases); Init; end; function Recognizer.DetectLanguage(Phrases : array of string) : Languages; begin var RussianLetters := 0; foreach var s in phrases do foreach var ch in s do begin var code := OrdUnicode(UpCase(ch)); if (code >= OrdUnicode('А')) and (code <= OrdUnicode('Я')) then inc(RussianLetters) else if (code >= OrdUnicode('A')) and (code <= OrdUnicode('Z')) then dec(RussianLetters); if Abs(RussianLetters)>=100 then begin if RussianLetters>=0 then Result := Languages.Russian else Result := Languages.English; exit; end; end; if RussianLetters>=0 then Result := Languages.Russian else Result := Languages.English; end; procedure Recognizer.SetLang(Language : Languages); begin Lang := Language; LanguageDefined := true; State := RecognizerStates.NotReady; end; procedure Recognizer.SpeechRecognized(sender : object; e : Microsoft.Speech.Recognition.SpeechRecognizedEventArgs); begin if (OnRecognized <> nil) and (e <> nil) then try var tx := e.Result.Text; OnRecognized.Invoke(tx); except on Exception do writeln('Exception captured'); end; end; procedure Recognizer.SpeechRecognitionRejected(sender : object; e : Microsoft.Speech.Recognition.SpeechRecognitionRejectedEventArgs); begin try begin var tx := e.Result.Text; if OnError <> nil then OnError(tx); end except on Exception do writeln('In rejected exception captured'); end; end; procedure Recognizer.RecognizeCompleted(sender : object; e : RecognizeCompletedEventArgs); begin // Not implemented yet end; procedure Recognizer.Start; begin if (State = RecognizerStates.Inited) or (State = RecognizerStates.Wait) then begin if OnRecognized = nil then begin // Здесь надо исключение выбрасывать exit; end; try Recogn.RecognizeAsync(Microsoft.Speech.Recognition.RecognizeMode.Multiple); State := RecognizerStates.Recognizing; except begin // здесь исключение должно быть State := RecognizerStates.NotReady; end; end; end; end; procedure Recognizer.Stop; begin if State = RecognizerStates.Recognizing then begin Recogn.RecognizeAsyncCancel; State := RecognizerStates.Wait; end; end; //------------------------------------------------------------------------------ procedure Say(Phrase : string); begin Speaker.Create(Phrase); end; procedure SayAsync(Phrase : string); begin var sp := Speaker.Create(DetectLanguage(Phrase)); sp.SpeakAsync(Phrase); end; procedure SayAsyncRus(Phrase : string); begin var sp := new Speaker(Languages.Russian); sp.SpeakAsync(Phrase); end; procedure SayAsyncEng(Phrase : string); begin var sp := new Speaker(Languages.English); sp.SpeakAsync(Phrase); end; end.
unit frmrindes; {$mode objfpc}{$H+} interface uses {$IFDEF MSWINDOWS} Windows, windirs, {$ENDIF} {$IFDEF UNIX} Unix, {$ENDIF} Classes, SysUtils, FileUtil, LR_Class, LR_DBSet, DateTimePicker, rxdbgrid, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons, ActnList, StdCtrls, DBGrids, DbCtrls, frmlistabase, db, ZDataset, zcontroladorgrilla, datGeneral, frmeditarrindes, lr_e_pdf, LSConfig, LCLIntf; type { TfmRindes } TfmRindes = class(TfmListaBase) bbExportarExcelRindes: TBitBtn; bbExportarResumen: TBitBtn; bbExportarExcel: TBitBtn; cbIncluirSinTallas: TCheckBox; cbMostrarResumen: TCheckBox; dbgResumen: TRxDBGrid; dbtDscResumen: TDBText; dsRindes: TDataSource; dsResumen: TDataSource; dtFecha: TDateTimePicker; frDBdsResumenRindes: TfrDBDataSet; frResumenRindes: TfrReport; frResumenRindes1: TfrReport; Label1: TLabel; paResumen: TPanel; sdGuardarPDF: TSaveDialog; sdCarpetaRindes: TSelectDirectoryDialog; zcgResumen: TZControladorGrilla; zqResumencapt_nro_ejemp_comerciales: TLargeintField; zqResumencapt_nro_ejemp_no_comerciales: TLargeintField; zqResumencapt_porc_ejemp_no_comerciales: TFloatField; zqResumenfecha: TDateField; zqResumenhora: TTimeField; zqResumenidmarea: TLongintField; zqResumenmoda_captura: TLargeintField; zqResumenpeso_bycatch: TFloatField; zqResumenpeso_mayor_55: TFloatField; zqResumenpeso_vieira: TFloatField; zqResumenret_nro_ejemp_comerciales: TLargeintField; zqResumenret_nro_ejemp_no_comerciales: TLargeintField; zqResumenret_porc_ejemp_no_comerciales: TFloatField; zqResumenrinde_comercial: TFloatField; zqResumenrinde_total: TFloatField; zqRindes: TZQuery; zqResumen: TZQuery; zqRindesbanda: TStringField; zqRindescomentarios: TStringField; zqRindesDscResumen: TStringField; zqRindesfecha: TDateField; zqRindeshora: TTimeField; zqRindesidmarea: TLongintField; zqRindesidmuestras_rinde: TLongintField; zqRindeslance_banda: TBytesField; zqRindesnrolance: TLongintField; zqRindespeso_comercial: TFloatField; zqRindespeso_fauna_acomp: TFloatField; zqRindespeso_no_comercial: TFloatField; zqRindespeso_total: TFloatField; zqRindesrinde_comercial: TFloatField; zqRindesrinde_total: TFloatField; procedure bbExportarResumenClick(Sender: TObject); procedure cbIncluirSinTallasChange(Sender: TObject); procedure cbMostrarResumenChange(Sender: TObject); procedure dtFechaChange(Sender: TObject); procedure dtFechaCheckBoxChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure zqResumenAfterOpen(DataSet: TDataSet); procedure zqResumenBeforeOpen(DataSet: TDataSet); procedure zqRindesAfterOpen(DataSet: TDataSet); procedure zqRindesAfterScroll(DataSet: TDataSet); procedure zqRindesBeforeOpen(DataSet: TDataSet); procedure zqRindesCalcFields(DataSet: TDataSet); private { private declarations } public { public declarations } end; var fmRindes: TfmRindes; implementation {$R *.lfm} { TfmRindes } procedure TfmRindes.zqRindesBeforeOpen(DataSet: TDataSet); begin zqRindes.ParamByName('idmarea').Value:=dmGeneral.IdMareaActiva; if dtFecha.Checked then zqRindes.ParamByName('fecha').AsDateTime:=dtFecha.Date else zqRindes.ParamByName('fecha').AsString:=''; end; procedure TfmRindes.zqRindesCalcFields(DataSet: TDataSet); begin zqRindesDscResumen.Value:=' del día '+FormatDateTime('dd/mm/yyyy', zqRindesfecha.Value); end; procedure TfmRindes.dtFechaCheckBoxChange(Sender: TObject); begin if dtFecha.Checked then dtFecha.Date:=Date else dtFecha.Date:=NullDate; zcgLista.Buscar; end; procedure TfmRindes.FormCreate(Sender: TObject); var bool_conf: Boolean; begin bool_conf := dmGeneral.LeerBooleanConfig('RindesIncluirSinTallas', False); cbIncluirSinTallas.Checked := bool_conf; end; procedure TfmRindes.FormShow(Sender: TObject); begin dtFecha.Date:=Date; inherited; end; procedure TfmRindes.zqResumenAfterOpen(DataSet: TDataSet); begin bbExportarResumen.Enabled:=zqResumen.RecordCount>0; end; procedure TfmRindes.zqResumenBeforeOpen(DataSet: TDataSet); begin zqResumen.ParamByName('idmarea').Value:=dmGeneral.IdMareaActiva; zqResumen.ParamByName('fecha').Value:=zqRindesfecha.Value; // zqResumen.ParamByName('IncluirSinTallas').AsInteger:= cbIncluirSinTallas.Checked?1:0 if cbIncluirSinTallas.Checked then zqResumen.ParamByName('IncluirSinTallas').AsInteger:=1 else zqResumen.ParamByName('IncluirSinTallas').AsInteger:=0; end; procedure TfmRindes.zqRindesAfterOpen(DataSet: TDataSet); begin if cbMostrarResumen.Checked then zcgResumen.Buscar; // zqResumen.Close; // zqResumen.Open; end; procedure TfmRindes.zqRindesAfterScroll(DataSet: TDataSet); begin zqResumen.ParamByName('fecha').Value:=zqRindesfecha.Value; if cbMostrarResumen.Checked then zcgResumen.Buscar; end; procedure TfmRindes.dtFechaChange(Sender: TObject); begin zcgLista.Buscar; end; procedure TfmRindes.bbExportarResumenClick(Sender: TObject); var archivo_destino: string; destino:String; begin destino:=dmGeneral.LeerStringConfig('destino_pdf_rindes', ''); // LSLoadConfig(['destino_pdf_rindes'],[destino],[@destino]); {$IFDEF MSWINDOWS} if (destino='') or (not DirectoryExistsUTF8(destino)) then destino:=GetWindowsSpecialDir(CSIDL_PERSONAL); {$ENDIF} sdCarpetaRindes.InitialDir := destino; if sdCarpetaRindes.Execute then begin archivo_destino:=IncludeTrailingPathDelimiter(sdCarpetaRindes.FileName)+'Rindes '+FormatDateTime('yyyy-mm-dd', zqResumenfecha.AsDateTime)+'.pdf'; if (not FileExistsUTF8(archivo_destino)) or (MessageDlg('El archivo '+archivo_destino+' ya existe. ¿Desea reemplazarlo?', mtConfirmation, [mbYes, mbNo],0) = mrYes) then begin dmGeneral.GuardarStringConfig('destino_pdf_rindes',IncludeTrailingPathDelimiter(sdCarpetaRindes.FileName)); // LSSaveConfig(['destino_pdf_rindes'],[IncludeTrailingPathDelimiter(sdCarpetaRindes.FileName)]); frResumenRindes.PrepareReport; //frResumenRindes.ShowReport; frResumenRindes.ExportTo(TfrTNPDFExportFilter, archivo_destino); if MessageDlg('El informe ha sido guardado en la carpeta indicada. ¿Desea visualizarlo?', mtConfirmation, [mbYes, mbNo],0) = mrYes then begin OpenDocument(archivo_destino); end; end; end; end; procedure TfmRindes.cbIncluirSinTallasChange(Sender: TObject); begin // Guardo la selección de planillas a guardar dmGeneral.GuardarBooleanConfig('RindesIncluirSinTallas', cbIncluirSinTallas.Checked); if cbMostrarResumen.Checked then zcgResumen.Buscar; end; procedure TfmRindes.cbMostrarResumenChange(Sender: TObject); begin zqResumen.Close; if cbMostrarResumen.Checked then zcgResumen.Buscar; end; end.
unit uCefUtilType; interface uses System.SysUtils, System.Types, System.Math, // uCefUtilConst; type TCefUISpeed = Byte; TCefControllerBase = class public Cursor: TPoint; Speed: TCefUISpeed; constructor Create; function Pause: Integer; end; function SpeedToPause(A: TCefUISpeed): Integer; const SPEED_DEF: TCefUISpeed = High(TCefUISpeed) div 2; implementation function SpeedToPause(A: TCefUISpeed): Integer; begin Result := Round(Power(A / (High(TCefUISpeed) * 100), -1)); end; { TCefControllerBase } constructor TCefControllerBase.Create; begin Cursor := TPoint.Create(0, 0); Speed := SPEED_DEF; end; function TCefControllerBase.Pause: Integer; begin Result := SpeedToPause(Speed) end; end.
{$REGION 'documentation'} { Copyright (c) 2018, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } { RGB convert interfaces @created(21/03/2018) @author Vencejo Software <www.vencejosoft.com> } {$ENDREGION} unit RGBConvert; interface uses Graphics, RGB; type {$REGION 'documentation'} { @abstract(Generic RGB representation convert interface) @member( ToValue Convert RGB object to generic value @param(RGB RGB representation) @return(Generic value) ) @member( FromValue Convert generic value to RGB object @param(Value Generic value) @return(@link(IRGB RGB object)) ) } {$ENDREGION} IRGBConvert<T> = interface ['{D35A61F2-5D07-41BC-9953-C04B280F5501}'] function ToValue(const RGB: IRGB): T; function FromValue(const Value: T): IRGB; end; {$REGION 'documentation'} { @abstract(Convert RGB to TColor and viceversa interface) } {$ENDREGION} IRGBTColor = interface(IRGBConvert<TColor>) ['{13805C76-7EF2-4094-8B4F-F9B9117300E9}'] end; {$REGION 'documentation'} { @abstract(Implementation of @link(IRGBTColor)) @member(ToValue @seealso(IRGBTColor.ToValue)) @member(FromValue @seealso(IRGBTColor.FromValue)) @member(New Create a new @classname as interface) } {$ENDREGION} TRGBTColor = class sealed(TInterfacedObject, IRGBTColor) public function ToValue(const RGB: IRGB): TColor; function FromValue(const Color: TColor): IRGB; class function New: IRGBTColor; end; implementation function TRGBTColor.FromValue(const Color: TColor): IRGB; var SysColor: Longint; begin SysColor := Graphics.ColorToRGB(Color); Result := TRGB.New(Byte(SysColor), Byte(SysColor shr 8), Byte(SysColor shr 16)); end; function TRGBTColor.ToValue(const RGB: IRGB): TColor; begin Result := (RGB.Blue shl 16) or (RGB.Green shl 8) or RGB.Red; end; class function TRGBTColor.New: IRGBTColor; begin Result := TRGBTColor.Create; end; end.