text
stringlengths
14
6.51M
object FormViewOptions: TFormViewOptions Left = 253 Top = 152 BorderStyle = bsDialog Caption = 'Universal Viewer settings' ClientHeight = 395 ClientWidth = 570 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poScreenCenter ShowHint = True OnCreate = FormCreate OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object Label2: TLabel Left = 64 Top = 196 Width = 44 Height = 13 Caption = 'Internet:' end object btnOk: TButton Left = 392 Top = 364 Width = 81 Height = 23 Caption = 'OK' Default = True ModalResult = 1 TabOrder = 1 end object btnCancel: TButton Left = 480 Top = 364 Width = 81 Height = 23 Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 2 end object PageControl1: TPageControl Left = 8 Top = 8 Width = 553 Height = 349 ActivePage = tabFile TabOrder = 0 object tabIntf: TTabSheet Caption = 'Interface' object boxIntf: TGroupBox Left = 8 Top = 4 Width = 449 Height = 285 Caption = 'Interface' TabOrder = 0 object labLang: TLabel Left = 8 Top = 20 Width = 51 Height = 13 Caption = 'Language:' FocusControl = edLang end object labIcon: TLabel Left = 8 Top = 44 Width = 30 Height = 13 Caption = 'Icons:' FocusControl = edIcon end object edLang: TComboBox Left = 88 Top = 16 Width = 153 Height = 21 Style = csDropDownList DropDownCount = 10 ItemHeight = 13 TabOrder = 0 OnChange = edLangChange end object chkShell: TCheckBox Left = 8 Top = 188 Width = 400 Height = 17 Caption = 'Explorer context menu item' TabOrder = 9 end object chkToolbar: TCheckBox Left = 8 Top = 116 Width = 400 Height = 17 Caption = 'Show toolbar' TabOrder = 5 end object chkBorder: TCheckBox Left = 8 Top = 148 Width = 400 Height = 17 Caption = 'Show border' TabOrder = 7 end object chkSingleInst: TCheckBox Left = 8 Top = 204 Width = 400 Height = 17 Caption = 'Run single instance only' TabOrder = 10 end object chkMenu: TCheckBox Left = 8 Top = 84 Width = 400 Height = 17 Caption = 'Show menu' TabOrder = 3 end object chkStatusBar: TCheckBox Left = 8 Top = 164 Width = 400 Height = 17 Caption = 'Show status bar' TabOrder = 8 end object chkNav: TCheckBox Left = 8 Top = 68 Width = 400 Height = 17 Caption = 'Show navigation panel' TabOrder = 2 end object chkMenuIcons: TCheckBox Left = 8 Top = 100 Width = 400 Height = 17 Caption = 'Show icons in menu' TabOrder = 4 end object edIcon: TComboBox Left = 88 Top = 40 Width = 153 Height = 21 Style = csDropDownList DropDownCount = 10 ItemHeight = 13 TabOrder = 1 OnChange = edIconChange end object Panel1: TPanel Left = 248 Top = 32 Width = 129 Height = 33 TabOrder = 11 Visible = False object Image1: TImage Left = 1 Top = 1 Width = 127 Height = 31 Align = alClient end end object chkShowCfm: TCheckBox Left = 8 Top = 228 Width = 433 Height = 17 Caption = 'Show confirmation' TabOrder = 12 end object chkShowConv: TCheckBox Left = 8 Top = 244 Width = 433 Height = 17 Caption = 'Show converter msg' TabOrder = 13 end object chkToolbarFS: TCheckBox Left = 24 Top = 132 Width = 400 Height = 17 Caption = 'Allow toolbar in full-screen' TabOrder = 6 end object chkRen: TCheckBox Left = 8 Top = 260 Width = 433 Height = 17 Caption = 'Suggest rename' TabOrder = 14 end end end object tabFile: TTabSheet Caption = 'File types' ImageIndex = 5 object boxExt: TGroupBox Left = 8 Top = 4 Width = 369 Height = 149 Caption = 'File extensions' TabOrder = 0 object labConv: TLabel Left = 8 Top = 90 Width = 39 Height = 13 Caption = 'labConv' FocusControl = edConv end object labText: TLabel Left = 8 Top = 18 Width = 36 Height = 13 Caption = 'labText' FocusControl = edText end object edText: TEdit Left = 120 Top = 16 Width = 233 Height = 21 TabOrder = 0 end object edImages: TEdit Left = 120 Top = 40 Width = 233 Height = 21 TabOrder = 2 end object edInet: TEdit Left = 120 Top = 64 Width = 233 Height = 21 TabOrder = 4 end object edConv: TEdit Left = 120 Top = 88 Width = 233 Height = 21 TabOrder = 5 end object chkImages: TCheckBox Left = 8 Top = 42 Width = 112 Height = 17 Caption = 'chkImages' TabOrder = 1 end object chkInet: TCheckBox Left = 8 Top = 66 Width = 112 Height = 17 Caption = 'chkInet' TabOrder = 3 end object edIgnore: TEdit Left = 120 Top = 112 Width = 233 Height = 21 TabOrder = 7 end object chkIgnore: TCheckBox Left = 8 Top = 114 Width = 112 Height = 17 Caption = 'Ignore:' TabOrder = 6 end end object btnTextOptions: TButton Left = 8 Top = 248 Width = 185 Height = 21 Caption = 'Auto-detection...' TabOrder = 1 OnClick = btnTextOptionsClick end object btnImageOptions: TButton Left = 8 Top = 274 Width = 185 Height = 21 Caption = 'Libraries...' TabOrder = 2 OnClick = btnImageOptionsClick end end object tabText: TTabSheet Caption = 'Text' ImageIndex = 3 object boxText: TGroupBox Left = 276 Top = 4 Width = 262 Height = 197 Caption = 'Text' TabOrder = 1 object labTextFixedWidth: TLabel Left = 64 Top = 126 Width = 115 Height = 13 Caption = 'Binary mode fixed width' FocusControl = edTextWidth end object labTabSize: TLabel Left = 64 Top = 170 Width = 39 Height = 13 Caption = 'Tab size' FocusControl = edTextTabSize end object labTextLength: TLabel Left = 64 Top = 148 Width = 90 Height = 13 Caption = 'Maximal line length' FocusControl = edTextLength end object edTextWidth: TSpinEdit Left = 8 Top = 124 Width = 49 Height = 22 AutoSize = False Increment = 10 MaxValue = 2000 MinValue = 10 TabOrder = 6 Value = 10 OnKeyDown = edHTextKeyDown end object chkTextWidthFit: TCheckBox Left = 8 Top = 104 Width = 250 Height = 17 Caption = 'Binary mode fit width' TabOrder = 5 OnClick = chkTextWidthFitClick end object chkTextAutoCopy: TCheckBox Left = 8 Top = 88 Width = 250 Height = 17 Caption = 'Auto-copy to clipboard' TabOrder = 4 end object edTextTabSize: TSpinEdit Left = 8 Top = 168 Width = 49 Height = 22 AutoSize = False MaxValue = 20 MinValue = 1 TabOrder = 8 Value = 1 OnKeyDown = edHTextKeyDown end object edTextLength: TSpinEdit Left = 8 Top = 146 Width = 49 Height = 22 AutoSize = False Increment = 50 MaxValue = 10000 MinValue = 10 TabOrder = 7 Value = 10 OnKeyDown = edHTextKeyDown end object chkTextWrap: TCheckBox Left = 8 Top = 40 Width = 250 Height = 17 Caption = 'Wrap' TabOrder = 1 end object chkTextNonPrint: TCheckBox Left = 8 Top = 72 Width = 250 Height = 17 Caption = 'Non-print' TabOrder = 3 end object btnGutterOptions: TButton Left = 8 Top = 16 Width = 201 Height = 21 Caption = 'Gutter && line numbers' TabOrder = 0 OnClick = btnGutterOptionsClick end object chkTextURLs: TCheckBox Left = 8 Top = 56 Width = 249 Height = 17 Caption = 'Hilight URLs' TabOrder = 2 end end object boxTextFont: TGroupBox Left = 8 Top = 4 Width = 262 Height = 105 Caption = 'Font' TabOrder = 0 object labTextFont1: TLabel Left = 8 Top = 19 Width = 26 Height = 13 Caption = 'Font:' FocusControl = btnTextFont end object labTextFontShow: TLabel Left = 96 Top = 19 Width = 22 Height = 13 Caption = 'Font' end object labTextColors: TLabel Left = 8 Top = 40 Width = 34 Height = 13 Caption = 'Colors:' FocusControl = btnTextColor end object labTextFontShowOEM: TLabel Left = 96 Top = 81 Width = 22 Height = 13 Caption = 'Font' end object btnTextFont: TButton Left = 64 Top = 16 Width = 25 Height = 21 Caption = '...' TabOrder = 0 OnClick = btnTextFontClick end object btnTextColor: TButton Left = 64 Top = 38 Width = 25 Height = 21 Caption = '...' TabOrder = 1 OnClick = btnTextColorClick end object btnTextColorHexBack: TButton Left = 88 Top = 38 Width = 25 Height = 21 Caption = '...' TabOrder = 2 OnClick = btnTextColorHexBackClick end object btnTextColorHex1: TButton Left = 112 Top = 38 Width = 25 Height = 21 Caption = '...' TabOrder = 3 OnClick = btnTextColorHex1Click end object btnTextColorHex2: TButton Left = 136 Top = 38 Width = 25 Height = 21 Caption = '...' TabOrder = 4 OnClick = btnTextColorHex2Click end object btnTextColorGutter: TButton Left = 160 Top = 38 Width = 25 Height = 21 Caption = '...' TabOrder = 5 OnClick = btnTextColorGutterClick end object chkTextOemSpecial: TCheckBox Left = 8 Top = 60 Width = 241 Height = 17 Caption = 'Use special OEM font' TabOrder = 7 OnClick = chkTextOemSpecialClick end object btnTextFontOEM: TButton Left = 64 Top = 78 Width = 25 Height = 21 Caption = '...' TabOrder = 8 OnClick = btnTextFontOEMClick end object btnTextColorURL: TButton Left = 184 Top = 38 Width = 25 Height = 21 Hint = 'URL' Caption = '...' TabOrder = 6 OnClick = btnTextColorURLClick end object btnTextColorHi: TButton Left = 208 Top = 38 Width = 25 Height = 21 Hint = 'Highlight' Caption = '...' TabOrder = 9 OnClick = btnTextColorHiClick end end object boxTextSearch: TGroupBox Left = 8 Top = 188 Width = 262 Height = 97 Caption = 'Search' TabOrder = 3 object labSearchIndent: TLabel Left = 56 Top = 70 Width = 135 Height = 13 Caption = 'Search result: lines from top' FocusControl = edSearchIndent end object edSearchIndent: TSpinEdit Left = 8 Top = 68 Width = 41 Height = 22 AutoSize = False MaxLength = 100 MaxValue = 0 MinValue = 0 TabOrder = 3 Value = 0 OnKeyDown = edHTextKeyDown end object chkSearchSel: TCheckBox Left = 8 Top = 16 Width = 250 Height = 17 Caption = 'Suggest selection' TabOrder = 0 end object chkSearchNoMsg: TCheckBox Left = 8 Top = 32 Width = 250 Height = 17 Caption = 'No error msg' TabOrder = 1 end object chkSearchNoCfm: TCheckBox Left = 8 Top = 48 Width = 250 Height = 17 Caption = 'No next cfm' TabOrder = 2 end end object boxTextReload: TGroupBox Left = 8 Top = 112 Width = 262 Height = 73 Caption = 'Auto-reload' TabOrder = 2 object chkTextReload: TCheckBox Left = 8 Top = 16 Width = 250 Height = 17 Caption = 'Auto-reload' TabOrder = 0 OnClick = chkTextReloadClick end object chkTextReloadBeep: TCheckBox Left = 8 Top = 32 Width = 250 Height = 17 Caption = 'Beep' TabOrder = 1 end object chkTextReloadTail: TCheckBox Left = 8 Top = 48 Width = 250 Height = 17 Caption = 'Follow tail' TabOrder = 2 end end end object tabMedia: TTabSheet Caption = 'Multimedia' ImageIndex = 4 object boxImage: TGroupBox Left = 8 Top = 4 Width = 265 Height = 209 Caption = 'Image' TabOrder = 0 object labColorImage: TLabel Left = 8 Top = 20 Width = 34 Height = 13 Caption = 'Colors:' FocusControl = btnMediaColor end object chkImageResample: TCheckBox Left = 8 Top = 144 Width = 254 Height = 17 Caption = 'Resample image' TabOrder = 9 end object chkImageTransp: TCheckBox Left = 8 Top = 160 Width = 254 Height = 17 Caption = 'Show transparency' TabOrder = 10 end object btnMediaColor: TButton Left = 80 Top = 17 Width = 33 Height = 21 Caption = '...' TabOrder = 0 OnClick = btnMediaColorClick end object btnMediaColorLabel: TButton Left = 112 Top = 17 Width = 33 Height = 21 Caption = '...' TabOrder = 1 OnClick = btnMediaColorLabelClick end object btnMediaColorLabelErr: TButton Left = 144 Top = 17 Width = 33 Height = 21 Caption = '...' TabOrder = 2 OnClick = btnMediaColorLabelErrClick end object chkImageFit: TCheckBox Left = 8 Top = 40 Width = 254 Height = 17 Caption = 'Fit image' TabOrder = 3 end object chkImageFitBig: TCheckBox Left = 8 Top = 56 Width = 254 Height = 17 Caption = 'Fit only big' TabOrder = 4 end object chkImageCenter: TCheckBox Left = 8 Top = 104 Width = 254 Height = 17 Caption = 'Center' TabOrder = 7 end object chkImageFitWindow: TCheckBox Left = 8 Top = 120 Width = 254 Height = 17 Caption = 'Fit window' TabOrder = 8 end object chkImageLabel: TCheckBox Left = 8 Top = 184 Width = 254 Height = 17 Caption = 'Show info line' TabOrder = 11 end object chkImageFitWidth: TCheckBox Left = 8 Top = 72 Width = 254 Height = 17 Caption = 'Fit only width' TabOrder = 5 end object chkImageFitHeight: TCheckBox Left = 8 Top = 88 Width = 254 Height = 17 Caption = 'Fit only height' TabOrder = 6 end end object boxInternet: TGroupBox Left = 280 Top = 8 Width = 257 Height = 53 Caption = 'Internet' TabOrder = 1 object chkWebOffline: TCheckBox Left = 8 Top = 20 Width = 246 Height = 17 Caption = 'Offline mode' TabOrder = 0 end end end object tabShortcuts: TTabSheet Caption = 'Shortcuts' ImageIndex = 1 object labShortcut: TLabel Left = 328 Top = 8 Width = 45 Height = 13 Caption = 'Shortcut:' FocusControl = HotKey1_ end object ListKeys: TListView Left = 8 Top = 8 Width = 305 Height = 261 Columns = < item Caption = 'Command' Width = 165 end item Caption = 'Shortcut' Width = 115 end> ColumnClick = False GridLines = True HideSelection = False ReadOnly = True RowSelect = True TabOrder = 0 ViewStyle = vsReport OnSelectItem = ListKeysSelectItem end object HotKey1_: THotKey Left = 376 Top = 36 Width = 145 Height = 19 Enabled = False HotKey = 0 Modifiers = [] TabOrder = 1 Visible = False end object btnKeyOk: TButton Left = 328 Top = 48 Width = 89 Height = 21 Caption = 'OK' Enabled = False TabOrder = 3 OnClick = btnKeyOkClick end object btnKeyReset: TButton Left = 328 Top = 72 Width = 89 Height = 21 Caption = 'Reset' Enabled = False TabOrder = 4 OnClick = btnKeyResetClick end object HotKey1: TecHotKey Left = 328 Top = 24 Width = 137 Height = 21 TabStop = False HotKey = 0 TabOrder = 2 end end object tabHistory: TTabSheet Caption = 'History' ImageIndex = 6 object boxHistory: TGroupBox Left = 8 Top = 4 Width = 305 Height = 157 Caption = 'History' TabOrder = 0 object chkSaveFolder: TCheckBox Left = 8 Top = 128 Width = 289 Height = 17 Caption = 'Save last working folder' TabOrder = 6 end object chkSavePosition: TCheckBox Left = 8 Top = 112 Width = 289 Height = 17 Caption = 'Save window position' TabOrder = 5 end object chkSaveRecents: TCheckBox Left = 8 Top = 16 Width = 289 Height = 17 Caption = 'Save recent files list' TabOrder = 0 end object chkSaveSearch: TCheckBox Left = 8 Top = 72 Width = 289 Height = 17 Caption = 'Save search history' TabOrder = 3 end object btnClearRecent: TButton Left = 24 Top = 50 Width = 89 Height = 21 Caption = 'Clear' TabOrder = 2 OnClick = btnClearRecentClick end object btnClearSearch: TButton Left = 24 Top = 89 Width = 89 Height = 21 Caption = 'Clear' TabOrder = 4 OnClick = btnClearSearchClick end object chkSaveFile: TCheckBox Left = 24 Top = 32 Width = 270 Height = 17 Caption = 'Reopen last used file' TabOrder = 1 end end end object tabMisc: TTabSheet Caption = 'Misc' ImageIndex = 2 object boxMisc: TGroupBox Left = 8 Top = 4 Width = 305 Height = 133 Caption = 'Misc' TabOrder = 0 object labViewerTitle: TLabel Left = 8 Top = 44 Width = 63 Height = 13 Caption = 'Window title:' FocusControl = edViewerTitle end object labViewerMode: TLabel Left = 8 Top = 20 Width = 65 Height = 13 Caption = 'Startup view:' FocusControl = edViewerMode end object labFileSort: TLabel Left = 8 Top = 68 Width = 47 Height = 13 Caption = 'Files sort:' FocusControl = edFileSort end object chkResolveLinks: TCheckBox Left = 8 Top = 104 Width = 289 Height = 17 Caption = 'Resolve .lnk' TabOrder = 4 end object chkShowHidden: TCheckBox Left = 8 Top = 88 Width = 289 Height = 17 Caption = 'Show hidden files' TabOrder = 3 end object edViewerTitle: TComboBox Left = 144 Top = 40 Width = 153 Height = 22 Style = csOwnerDrawFixed ItemHeight = 16 ItemIndex = 0 TabOrder = 1 Text = 'Display full pathname' Items.Strings = ( 'Display full pathname' 'Display filename only') end object edViewerMode: TComboBox Left = 144 Top = 16 Width = 153 Height = 22 Style = csOwnerDrawFixed DropDownCount = 10 ItemHeight = 16 ItemIndex = 0 TabOrder = 0 Text = 'Auto detect' Items.Strings = ( 'Auto detect' 'Text' 'Binary' 'Hex' 'Image/Multimedia' 'Internet' 'Unicode' 'Plugins' 'RTF/UTF-8') end object edFileSort: TComboBox Left = 144 Top = 64 Width = 153 Height = 22 Style = csOwnerDrawFixed ItemHeight = 16 ItemIndex = 0 TabOrder = 2 Text = 'File name' Items.Strings = ( 'File name' 'File name (desc.)' 'Extension' 'Extension (desc.)') end end object boxPrint: TGroupBox Left = 320 Top = 4 Width = 217 Height = 57 Caption = 'Print' TabOrder = 2 object labFontFooter: TLabel Left = 8 Top = 15 Width = 59 Height = 13 Caption = 'Footer font:' FocusControl = btnFontFooter end object labFooterFontShow: TLabel Left = 64 Top = 32 Width = 22 Height = 13 Caption = 'Font' end object btnFontFooter: TButton Left = 24 Top = 30 Width = 33 Height = 21 Caption = '...' TabOrder = 0 OnClick = btnFontFooterClick end end object boxHMisc: TGroupBox Left = 8 Top = 140 Width = 305 Height = 141 Caption = 'Use custom height' TabOrder = 1 object chkHText: TCheckBox Left = 8 Top = 16 Width = 130 Height = 17 Caption = 'Text' TabOrder = 0 OnClick = chkHTextClick end object edHText: TSpinEdit Left = 144 Top = 12 Width = 50 Height = 22 Increment = 20 MaxValue = 2000 MinValue = 40 TabOrder = 1 Value = 40 OnKeyDown = edHTextKeyDown end object chkHImage: TCheckBox Left = 8 Top = 40 Width = 130 Height = 17 Caption = 'Image' TabOrder = 2 OnClick = chkHTextClick end object edHImage: TSpinEdit Left = 144 Top = 36 Width = 50 Height = 22 Increment = 20 MaxValue = 2000 MinValue = 40 TabOrder = 3 Value = 40 OnKeyDown = edHTextKeyDown end object chkHWeb: TCheckBox Left = 8 Top = 64 Width = 130 Height = 17 Caption = 'Web' TabOrder = 4 OnClick = chkHTextClick end object edHWeb: TSpinEdit Left = 144 Top = 60 Width = 50 Height = 22 Increment = 20 MaxValue = 2000 MinValue = 40 TabOrder = 5 Value = 40 OnKeyDown = edHTextKeyDown end object chkHRtf: TCheckBox Left = 8 Top = 112 Width = 130 Height = 17 Caption = '&RTF/UTF-8:' TabOrder = 8 OnClick = chkHTextClick end object edHRtf: TSpinEdit Left = 144 Top = 108 Width = 50 Height = 22 Increment = 20 MaxValue = 2000 MinValue = 40 TabOrder = 9 Value = 40 OnKeyDown = edHTextKeyDown end object chkHPlug: TCheckBox Left = 8 Top = 88 Width = 130 Height = 17 Caption = 'Plugins:' TabOrder = 6 OnClick = chkHTextClick end object edHPlug: TSpinEdit Left = 144 Top = 84 Width = 50 Height = 22 Increment = 20 MaxValue = 2000 MinValue = 40 TabOrder = 7 Value = 40 OnKeyDown = edHTextKeyDown end end end end object FontDialog1: TFontDialog Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Shell Dlg' Font.Style = [] Left = 424 Top = 12 end object ColorDialog1: TColorDialog Left = 472 Top = 12 end object FontDialog2: TFontDialog Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Shell Dlg' Font.Style = [] Device = fdPrinter Options = [fdEffects, fdWysiwyg] Left = 448 Top = 12 end object SaveDialog1: TSaveDialog DefaultExt = '.bmp' FileName = '(Template).bmp' Filter = '*.bmp|*.bmp' InitialDir = 'C:\' Options = [ofOverwritePrompt, ofHideReadOnly, ofPathMustExist, ofEnableSizing] Left = 504 Top = 8 end object Timer1: TTimer Enabled = False Interval = 100 OnTimer = Timer1Timer Left = 320 Top = 360 end end
Program Aufgabe10; {$codepage utf8} Var Auswahl: Integer; Begin Repeat WriteLn(); WriteLn(); WriteLn(); WriteLn('Weißes Haus Velten - Menü'); WriteLn('1 - Döner Teller (groß)'); WriteLn('2 - Döner Teller (normal)'); WriteLn('3 - Kids Menü'); WriteLn('4 - Chili Cheeseburger Menü'); WriteLn('5 - Chili Hamburger Menü'); WriteLn('6 - Family Menü'); WriteLn('7 - Beenden'); WriteLn(); Write('Bitte triff eine Auswahl: '); Read(Auswahl); Case Auswahl Of 1: WriteLn('Döner Teller (groß) mit doppelt Fleisch, Pommes frites und Salat: 8,50€'); 2: WriteLn('Döner Teller (normal) mit Pommes frites und Salat: 7,80€'); 3: WriteLn('Kids Menü - 4 Nuggets - Pommes frites - Capri-Sonne - Überraschung: 5,00€'); 4: WriteLn('Chili Cheeseburger Menü - 1 Chili Cheeseburger - 1 Pommes frites - 1 Softgetränk 0,33l: 6,80€'); 5: WriteLn('Chili Hamburger Menü - 1 Chili Hamburger - 1 Pommes frites - 1 Softgetränk 0,33l: 6,50€'); 6: Begin WriteLn('Family Menü - 1 Dönerteller mit Salat und Pommes frites - 2 Hamburger'); WriteLn(' - Chicken Nuggets (6 Stück) - 1 Pommes frites - 2 Softgetränke 0,33l - 2 Capri-Sonnen: 28,50€'); End; 7: WriteLn('Bye!'); End; Until Auswahl = 7; End.
(* * This code was generated by the TaskGen tool from file * "CommonOptionsTask.xml" * Version: 18.0.0.0 * Runtime Version: v2.0.50727 * Changes to this file may cause incorrect behavior and will be * overwritten when the code is regenerated. *) unit CommonOptionStrs; interface const sTaskName = 'commonoptions'; // PathsAndDefines sDefines = 'Defines'; sIncludePath = 'IncludePath'; sFinalOutputDir = 'FinalOutputDir'; sIntermediateOutputDir = 'IntermediateOutputDir'; // MiscInternalOptions sShowGeneralMessages = 'ShowGeneralMessages'; // CommonPackageOpts sPackageImports = 'PackageImports'; sAllPackageLibs = 'AllPackageLibs'; sPackageLibs = 'PackageLibs'; sDesignOnlyPackage = 'DesignOnlyPackage'; sRuntimeOnlyPackage = 'RuntimeOnlyPackage'; // DelphiInternalOptions sGenPackage = 'GenPackage'; sGenDll = 'GenDll'; sUsePackages = 'UsePackages'; sHasTypeLib = 'HasTypeLib'; sAutoGenImportAssembly = 'AutoGenImportAssembly'; sAutoRegisterTLB = 'AutoRegisterTLB'; sImageDebugInfo = 'ImageDebugInfo'; sDebugSourcePath = 'DebugSourcePath'; // OutputFilenameModifiers sOutputExt = 'OutputExt'; sOutputName = 'OutputName'; sDllPrefixDefined = 'DllPrefixDefined'; sDllPrefix = 'DllPrefix'; sDllVersion = 'DllVersion'; sDllSuffix = 'DllSuffix'; // C++InternalOptions sMultithreaded = 'Multithreaded'; sDynamicRTL = 'DynamicRTL'; sUsingDelphiRTL = 'UsingDelphiRTL'; sLinkCodeGuard = 'LinkCodeGuard'; sRunBCCOutOfProcess = 'RunBCCOutOfProcess'; // WindowsVersionInformation sVerInfo_IncludeVerInfo = 'VerInfo_IncludeVerInfo'; sVerInfo_MajorVer = 'VerInfo_MajorVer'; sVerInfo_MinorVer = 'VerInfo_MinorVer'; sVerInfo_Release = 'VerInfo_Release'; sVerInfo_Build = 'VerInfo_Build'; sVerInfo_Debug = 'VerInfo_Debug'; sVerInfo_PreRelease = 'VerInfo_PreRelease'; sVerInfo_Special = 'VerInfo_Special'; sVerInfo_Private = 'VerInfo_Private'; sVerInfo_DLL = 'VerInfo_DLL'; sVerInfo_Locale = 'VerInfo_Locale'; sVerInfo_CodePage = 'VerInfo_CodePage'; sVerInfo_CompanyName = 'VerInfo_CompanyName'; sVerInfo_FileDescription = 'VerInfo_FileDescription'; sVerInfo_FileVersion = 'VerInfo_FileVersion'; sVerInfo_InternalName = 'VerInfo_InternalName'; sVerInfo_LegalCopyright = 'VerInfo_LegalCopyright'; sVerInfo_LegalTrademarks = 'VerInfo_LegalTrademarks'; sVerInfo_OriginalFilename = 'VerInfo_OriginalFilename'; sVerInfo_ProductName = 'VerInfo_ProductName'; sVerInfo_ProductVersion = 'VerInfo_ProductVersion'; sVerInfo_Comments = 'VerInfo_Comments'; sVerInfo_Keys = 'VerInfo_Keys'; sVerInfo_AutoGenVersion = 'VerInfo_AutoGenVersion'; sVerInfo_AutoIncVersion = 'VerInfo_AutoIncVersion'; sVerInfo_BundleId = 'VerInfo_BundleId'; sVerInfo_UIDeviceFamily = 'VerInfo_UIDeviceFamily'; sIcon_MainIcon = 'Icon_MainIcon'; sIcns_MainIcns = 'Icns_MainIcns'; sManifest_File = 'Manifest_File'; sVCL_Custom_Styles = 'VCL_Custom_Styles'; // DebuggerProjectOptions sDebugger_RunParams = 'Debugger_RunParams'; sDebugger_RemoteRunParams = 'Debugger_RemoteRunParams'; sDebugger_HostApplication = 'Debugger_HostApplication'; sDebugger_RemotePath = 'Debugger_RemotePath'; sDebugger_RemoteHost = 'Debugger_RemoteHost'; sDebugger_EnvVars = 'Debugger_EnvVars'; sDebugger_SymTabs = 'Debugger_SymTabs'; sDebugger_Launcher = 'Debugger_Launcher'; sDebugger_RemoteLauncher = 'Debugger_RemoteLauncher'; sDebugger_IncludeSystemVars = 'Debugger_IncludeSystemVars'; sDebugger_UseLauncher = 'Debugger_UseLauncher'; sDebugger_UseRemoteLauncher = 'Debugger_UseRemoteLauncher'; sDebugger_CWD = 'Debugger_CWD'; sDebugger_RemoteCWD = 'Debugger_RemoteCWD'; sDebugger_RemoteDebug = 'Debugger_RemoteDebug'; sDebugger_DebugSourcePath = 'Debugger_DebugSourcePath'; sDebugger_LoadAllSymbols = 'Debugger_LoadAllSymbols'; sDebugger_LoadUnspecifiedSymbols = 'Debugger_LoadUnspecifiedSymbols'; sDebugger_SymbolSourcePath = 'Debugger_SymbolSourcePath'; // BuildEvents sPreBuildEvent = 'PreBuildEvent'; sPreBuildEventCancelOnError = 'PreBuildEventCancelOnError'; sPreLinkEvent = 'PreLinkEvent'; sPreLinkEventCancelOnError = 'PreLinkEventCancelOnError'; sPostBuildEvent = 'PostBuildEvent'; sPostBuildEventExecuteWhen = 'PostBuildEventExecuteWhen'; sPostBuildEventExecuteWhen_Always = 'Always'; sPostBuildEventExecuteWhen_TargetOutOfDate = 'TargetOutOfDate'; sPostBuildEventCancelOnError = 'PostBuildEventCancelOnError'; // ProvisionFiles sPF_Debug = 'PF_Debug'; sPF_AdHoc = 'PF_AdHoc'; sPF_AppStore = 'PF_AppStore'; sPF_Sandbox = 'PF_Sandbox'; // ProvisionDeveloperIdentity sPF_DevDebug = 'PF_DevDebug'; sPF_DevAdHoc = 'PF_DevAdHoc'; sPF_DevAppStore = 'PF_DevAppStore'; sPF_DevSandbox = 'PF_DevSandbox'; // ProvisionDeveloperProgramIdentity sPF_DevTeamIdDebug = 'PF_DevTeamIdDebug'; sPF_DevTeamIdAdHoc = 'PF_DevTeamIdAdHoc'; sPF_DevTeamIdAppStore = 'PF_DevTeamIdAppStore'; sPF_DevTeamIdSandbox = 'PF_DevTeamIdSandbox'; // EntitlementList sEL_ReadOnlyMovies = 'EL_ReadOnlyMovies'; sEL_ReadWriteMovies = 'EL_ReadWriteMovies'; sEL_ReadOnlyMusic = 'EL_ReadOnlyMusic'; sEL_ReadWriteMusic = 'EL_ReadWriteMusic'; sEL_ReadOnlyPictures = 'EL_ReadOnlyPictures'; sEL_ReadWritePictures = 'EL_ReadWritePictures'; sEL_CaptureCamera = 'EL_CaptureCamera'; sEL_RecordingMicrophone = 'EL_RecordingMicrophone'; sEL_USBDevices = 'EL_USBDevices'; sEL_ReadWriteDownloads = 'EL_ReadWriteDownloads'; sEL_ReadOnlyFileDialog = 'EL_ReadOnlyFileDialog'; sEL_ReadWriteFileDialog = 'EL_ReadWriteFileDialog'; sEL_ChildProcessInheritance = 'EL_ChildProcessInheritance'; sEL_OutgoingNetwork = 'EL_OutgoingNetwork'; sEL_IncomingNetwork = 'EL_IncomingNetwork'; sEL_ReadWriteAddressBook = 'EL_ReadWriteAddressBook'; sEL_ReadWriteCalendars = 'EL_ReadWriteCalendars'; sEL_Location = 'EL_Location'; sEL_Printing = 'EL_Printing'; // iOSArtwork siPhone_AppIcon57 = 'iPhone_AppIcon57'; siPhone_AppIcon114 = 'iPhone_AppIcon114'; siPhone_Launch320 = 'iPhone_Launch320'; siPhone_Launch640 = 'iPhone_Launch640'; siPhone_Launch640x1136 = 'iPhone_Launch640x1136'; siPhone_Spotlight29 = 'iPhone_Spotlight29'; siPhone_Spotlight58 = 'iPhone_Spotlight58'; siOS_AppStore512 = 'iOS_AppStore512'; siOS_AppStore1024 = 'iOS_AppStore1024'; siPad_AppIcon72 = 'iPad_AppIcon72'; siPad_AppIcon144 = 'iPad_AppIcon144'; siPad_Launch768 = 'iPad_Launch768'; siPad_Launch1024 = 'iPad_Launch1024'; siPad_Launch1536 = 'iPad_Launch1536'; siPad_Launch2048 = 'iPad_Launch2048'; siPad_SpotLight50 = 'iPad_SpotLight50'; siPad_SpotLight100 = 'iPad_SpotLight100'; siPad_Setting29 = 'iPad_Setting29'; siPad_Setting58 = 'iPad_Setting58'; // BuildType sBT_BuildType = 'BT_BuildType'; // Orientation sOrientationPortrait = 'OrientationPortrait'; sOrientationPortraitUpsideDown = 'OrientationPortraitUpsideDown'; sOrientationLandscapeLeft = 'OrientationLandscapeLeft'; sOrientationLandscapeRight = 'OrientationLandscapeRight'; implementation end.
unit ufTarefa3; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, DataSnap.DBClient, uProjetos, System.Math; type TfTarefa3 = class(TForm) pnMain: TPanel; lbValoresProjeto: TLabel; grProjetos: TDBGrid; btTotal: TButton; edTotal: TEdit; btTotalDivisoes: TButton; edTotalDiv: TEdit; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure btTotalClick(Sender: TObject); procedure btTotalDivisoesClick(Sender: TObject); private cdsProjetos: TClientDataSet; dsProjetos: TDataSource; Projetos: TProjetos; function CalcularValorTotalProjetos: Currency; function CalcularTotalDivisoes: Currency; procedure InicializarProjetos; procedure InicializarEstrutura; { Private declarations } public { Public declarations } end; var fTarefa3: TfTarefa3; implementation {$R *.dfm} { TfTarefa3 } procedure TfTarefa3.btTotalClick(Sender: TObject); begin edTotal.Text := FormatCurr('R$ 0.00', CalcularValorTotalProjetos); end; procedure TfTarefa3.btTotalDivisoesClick(Sender: TObject); begin edTotalDiv.Text := FormatCurr('R$ 0.00', CalcularTotalDivisoes); end; function TfTarefa3.CalcularTotalDivisoes: Currency; var ValorTotalDiv: Real; ValorAnterior: Currency; begin ValorTotalDiv := 0.0; cdsProjetos.DisableControls; try cdsProjetos.First; ValorAnterior := cdsProjetos.FieldByName('Valor').AsCurrency; cdsProjetos.Next; while not cdsProjetos.Eof do begin ValorTotalDiv := ValorTotalDiv + (cdsProjetos.FieldByName('Valor').AsCurrency / ValorAnterior); ValorAnterior := cdsProjetos.FieldByName('Valor').AsCurrency; cdsProjetos.Next; end; finally Result := RoundTo(ValorTotalDiv, -2); cdsProjetos.EnableControls; end; end; function TfTarefa3.CalcularValorTotalProjetos: Currency; var ValorTotal: Currency; begin ValorTotal := 0.0; cdsProjetos.DisableControls; try cdsProjetos.First; while not cdsProjetos.Eof do begin ValorTotal := ValorTotal + cdsProjetos.FieldByName('Valor').AsCurrency; cdsProjetos.Next; end; finally Result := ValorTotal; cdsProjetos.EnableControls; end; end; procedure TfTarefa3.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; Release; fTarefa3 := nil; end; procedure TfTarefa3.FormCreate(Sender: TObject); begin InicializarEstrutura; InicializarProjetos; end; procedure TfTarefa3.FormDestroy(Sender: TObject); begin Projetos.Free; end; procedure TfTarefa3.InicializarEstrutura; begin Projetos := TProjetos.Create; cdsProjetos := TClientDataSet.Create(Self); cdsProjetos.FieldDefs.Add('IdProjeto', ftInteger); cdsProjetos.FieldDefs.Add('NomeProjeto', ftString, 50); cdsProjetos.FieldDefs.Add('Valor', ftCurrency); cdsProjetos.CreateDataSet; dsProjetos := TDataSource.Create(Self); dsProjetos.DataSet := cdsProjetos; grProjetos.DataSource := dsProjetos; end; procedure TfTarefa3.InicializarProjetos; var I: Integer; begin Projetos.GerarItensAleatorios(10, 100); for I:=0 to Projetos.Items.Count-1 do begin cdsProjetos.Append; cdsProjetos.FieldByName('IdProjeto').AsInteger := Projetos.Items[I].Id; cdsProjetos.FieldByName('NomeProjeto').AsString := Projetos.Items[I].Nome; cdsProjetos.FieldByName('Valor').AsCurrency := Projetos.Items[I].Valor; cdsProjetos.Post; end; end; end.
unit ce_writableComponent; {$I ce_defines.inc} interface uses Classes, SysUtils, ce_common, typinfo, fpjson, jsonparser, fpjsonrtti; type (** * The ancestor of classes which can be saved or reloaded to/from a file. * It's used each time some options or data have to * persist from a cession to another, independently from the centralized * system provided by the ICESessionOptionObserver/Subject mechanism. * * The descendants overrides customLoadFromFile and customSaveToFile * to save/load to/from a specific format. *) TCustomWritableComponent = class(TComponent) protected fFilename: string; fHasLoaded: boolean; fHasSaved: boolean; procedure setFilename(const aValue: string); virtual; procedure beforeLoad; virtual; procedure beforeSave; virtual; procedure afterLoad; virtual; procedure afterSave; virtual; procedure customLoadFromFile(const aFilename: string); virtual; abstract; procedure customSaveToFile(const aFilename: string); virtual; abstract; public procedure saveToFile(const aFilename: string); virtual; procedure loadFromFile(const aFilename: string); virtual; // property Filename: string read fFilename write setFilename; property hasLoaded: boolean read fHasLoaded; property hasSaved: boolean read fHasSaved; end; (** * The ancestor of classes which can be saved or reloaded to/from * a LFM text file. * By default, reading errors are skipped and no exception is raised. *) TWritableLfmTextComponent = class(TCustomWritableComponent) protected procedure customLoadFromFile(const aFilename: string); override; procedure customSaveToFile(const aFilename: string); override; procedure readerPropNoFound(Reader: TReader; Instance: TPersistent; var PropName: string; IsPath: boolean; var Handled, Skip: Boolean); virtual; procedure readerError(Reader: TReader; const Message: string; var Handled: Boolean); virtual; end; (** * The ancestor of classes which can be saved or reloaded to/from * a JSON file. * By default, reading errors are skipped and no exception is raised. *) TWritableJsonComponent = class(TCustomWritableComponent) protected procedure propertyError(Sender : TObject; AObject : TObject; Info : PPropInfo; AValue : TJSONData; Error : Exception; Var doContinue : Boolean); virtual; procedure restoreProperty(Sender : TObject; AObject : TObject; Info : PPropInfo; AValue : TJSONData; Var Handled : Boolean); virtual; procedure customLoadFromFile(const aFilename: string); override; procedure customSaveToFile(const aFilename: string); override; end; implementation {$REGION TCustomWritableComponent ----------------------------------------------} procedure TCustomWritableComponent.beforeSave; begin end; procedure TCustomWritableComponent.beforeLoad; begin end; procedure TCustomWritableComponent.afterLoad; begin end; procedure TCustomWritableComponent.afterSave; begin end; procedure TCustomWritableComponent.setFilename(const aValue: string); begin fFilename := aValue; end; procedure TCustomWritableComponent.saveToFile(const aFilename: string); begin fHasSaved := true; beforeSave; try customSaveToFile(aFilename); except fHasSaved := false; end; setFilename(aFilename); afterSave; end; procedure TCustomWritableComponent.loadFromFile(const aFilename: string); begin fHasLoaded := true; beforeLoad; setFilename(aFilename); customLoadFromFile(aFilename); afterLoad; end; {$ENDREGION} {$REGION TWritableLfmTextComponent ---------------------------------------------} procedure TWritableLfmTextComponent.customSaveToFile(const aFilename: string); begin saveCompToTxtFile(self, aFilename); end; procedure TWritableLfmTextComponent.customLoadFromFile(const aFilename: string); begin loadCompFromTxtFile(self, aFilename, @readerPropNoFound, @readerError); end; procedure TWritableLfmTextComponent.readerPropNoFound(Reader: TReader; Instance: TPersistent; var PropName: string; IsPath: boolean; var Handled, Skip: Boolean); begin Handled := true; Skip := true; end; procedure TWritableLfmTextComponent.readerError(Reader: TReader; const Message: string; var Handled: Boolean); begin Handled := true; fHasLoaded := false; end; {$ENDREGION} {$REGION TWritableJsonComponent ------------------------------------------------} procedure TWritableJsonComponent.propertyError(Sender : TObject; AObject : TObject; Info : PPropInfo; AValue : TJSONData; Error : Exception; Var doContinue : Boolean); begin doContinue := true; end; procedure TWritableJsonComponent.restoreProperty(Sender : TObject; AObject : TObject; Info : PPropInfo; AValue : TJSONData; Var Handled : Boolean); begin Handled := true; end; procedure TWritableJsonComponent.customSaveToFile(const aFilename: string); var file_str: TMemoryStream; json_str: TJSONStreamer; json_dat: TJSONStringType; begin file_str := TMemoryStream.Create; json_str := TJSONStreamer.Create(nil); try json_dat := json_str.ObjectToJSONString(self); file_str.Write(json_dat[1], length(json_dat)); file_str.SaveToFile(aFilename); finally file_str.Free; json_str.Free; end; end; procedure TWritableJsonComponent.customLoadFromFile(const aFilename: string); var file_str: TMemoryStream; json_str: TJSONDeStreamer; json_dat: TJSONStringType; begin file_str := TMemoryStream.Create; json_str := TJSONDeStreamer.Create(nil); try json_str.OnPropertyError:= @propertyError; json_str.OnRestoreProperty := @restoreProperty; file_str.LoadFromFile(aFilename); setLength(json_dat, file_str.Size); file_str.Read(json_dat[1], length(json_dat)); json_str.JSONToObject(json_dat, self); finally file_str.Free; json_str.Free; end; end; {$ENDREGION} initialization registerClasses([TCustomWritableComponent, TWritableLfmTextComponent, TWritableJsonComponent]); end.
unit DeviceLicenseUnit; interface uses SysUtils, BaseExampleUnit, EnumsUnit; type TDeviceLicense = class(TBaseExample) public function Execute(DeviceId: String; DeviceType: TDeviceType): boolean; end; implementation function TDeviceLicense.Execute(DeviceId: String; DeviceType: TDeviceType): boolean; var ErrorString: String; begin Result := Route4MeManager.User.DeviceLicense(DeviceId, DeviceType, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin if Result then WriteLn('DeviceLicense successfully, device is licensed') else WriteLn('DeviceLicense successfully, device is not licensed'); WriteLn(''); end else WriteLn(Format('DeviceLicense error: "%s"', [ErrorString])); end; end.
object fmAlign: TfmAlign Left = 459 Top = 281 ActiveControl = lstTokens AutoScroll = False BorderIcons = [biSystemMenu] Caption = 'Align Lines' ClientHeight = 273 ClientWidth = 265 Color = clBtnFace Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = True Position = poScreenCenter Scaled = False DesignSize = ( 265 273) PixelsPerInch = 96 TextHeight = 14 object lblToken: TLabel Left = 8 Top = 8 Width = 84 Height = 14 Caption = '&Align on token:' FocusControl = lstTokens end object btnOK: TButton Left = 104 Top = 240 Width = 75 Height = 25 Anchors = [akRight, akBottom] Caption = '&OK' Default = True ModalResult = 1 TabOrder = 3 end object btnCancel: TButton Left = 184 Top = 240 Width = 75 Height = 25 Anchors = [akRight, akBottom] Cancel = True Caption = 'Cancel' ModalResult = 2 TabOrder = 4 end object lstTokens: TListBox Left = 8 Top = 24 Width = 249 Height = 177 Anchors = [akLeft, akTop, akRight, akBottom] ItemHeight = 14 TabOrder = 0 OnDblClick = lstTokensDblClick end object cbxMode: TComboBox Left = 8 Top = 208 Width = 248 Height = 22 Style = csDropDownList Anchors = [akLeft, akRight, akBottom] ItemHeight = 14 ItemIndex = 0 TabOrder = 1 Text = 'Align at rightmost token' Items.Strings = ( 'Align at rightmost token' 'Align at first token') end object btnConfig: TButton Left = 8 Top = 240 Width = 89 Height = 25 Anchors = [akLeft, akBottom] Caption = 'Configure ...' TabOrder = 2 OnClick = btnConfigClick end end
unit InfoCANCELTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoCANCELRecord = record PTable: String[2]; PDays: Integer; PPr_PCT: String[168]; PSr_PCT: String[168]; PModCount: SmallInt; End; TInfoCANCELClass2 = class public PTable: String[2]; PDays: Integer; PPr_PCT: String[168]; PSr_PCT: String[168]; PModCount: SmallInt; End; // function CtoRInfoCANCEL(AClass:TInfoCANCELClass):TInfoCANCELRecord; // procedure RtoCInfoCANCEL(ARecord:TInfoCANCELRecord;AClass:TInfoCANCELClass); TInfoCANCELBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoCANCELRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoCANCEL = (InfoCANCELPrimaryKey); TInfoCANCELTable = class( TDBISAMTableAU ) private FDFTable: TStringField; FDFDays: TIntegerField; FDFPr_PCT: TStringField; FDFSr_PCT: TStringField; FDFModCount: TSmallIntField; procedure SetPTable(const Value: String); function GetPTable:String; procedure SetPDays(const Value: Integer); function GetPDays:Integer; procedure SetPPr_PCT(const Value: String); function GetPPr_PCT:String; procedure SetPSr_PCT(const Value: String); function GetPSr_PCT:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoCANCEL); function GetEnumIndex: TEIInfoCANCEL; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoCANCELRecord; procedure StoreDataBuffer(ABuffer:TInfoCANCELRecord); property DFTable: TStringField read FDFTable; property DFDays: TIntegerField read FDFDays; property DFPr_PCT: TStringField read FDFPr_PCT; property DFSr_PCT: TStringField read FDFSr_PCT; property DFModCount: TSmallIntField read FDFModCount; property PTable: String read GetPTable write SetPTable; property PDays: Integer read GetPDays write SetPDays; property PPr_PCT: String read GetPPr_PCT write SetPPr_PCT; property PSr_PCT: String read GetPSr_PCT write SetPSr_PCT; property PModCount: SmallInt read GetPModCount write SetPModCount; published property Active write SetActive; property EnumIndex: TEIInfoCANCEL read GetEnumIndex write SetEnumIndex; end; { TInfoCANCELTable } TInfoCANCELQuery = class( TDBISAMQueryAU ) private FDFTable: TStringField; FDFDays: TIntegerField; FDFPr_PCT: TStringField; FDFSr_PCT: TStringField; FDFModCount: TSmallIntField; procedure SetPTable(const Value: String); function GetPTable:String; procedure SetPDays(const Value: Integer); function GetPDays:Integer; procedure SetPPr_PCT(const Value: String); function GetPPr_PCT:String; procedure SetPSr_PCT(const Value: String); function GetPSr_PCT:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; reintroduce; procedure SetActive(Value: Boolean); override; public function GetDataBuffer:TInfoCANCELRecord; procedure StoreDataBuffer(ABuffer:TInfoCANCELRecord); property DFTable: TStringField read FDFTable; property DFDays: TIntegerField read FDFDays; property DFPr_PCT: TStringField read FDFPr_PCT; property DFSr_PCT: TStringField read FDFSr_PCT; property DFModCount: TSmallIntField read FDFModCount; property PTable: String read GetPTable write SetPTable; property PDays: Integer read GetPDays write SetPDays; property PPr_PCT: String read GetPPr_PCT write SetPPr_PCT; property PSr_PCT: String read GetPSr_PCT write SetPSr_PCT; property PModCount: SmallInt read GetPModCount write SetPModCount; published property Active write SetActive; end; { TInfoCANCELTable } procedure Register; implementation function TInfoCANCELTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoCANCELTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoCANCELTable.GenerateNewFieldName } function TInfoCANCELTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoCANCELTable.CreateField } procedure TInfoCANCELTable.CreateFields; begin FDFTable := CreateField( 'Table' ) as TStringField; FDFDays := CreateField( 'Days' ) as TIntegerField; FDFPr_PCT := CreateField( 'Pr_PCT' ) as TStringField; FDFSr_PCT := CreateField( 'Sr_PCT' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; end; { TInfoCANCELTable.CreateFields } procedure TInfoCANCELTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoCANCELTable.SetActive } procedure TInfoCANCELTable.SetPTable(const Value: String); begin DFTable.Value := Value; end; function TInfoCANCELTable.GetPTable:String; begin result := DFTable.Value; end; procedure TInfoCANCELTable.SetPDays(const Value: Integer); begin DFDays.Value := Value; end; function TInfoCANCELTable.GetPDays:Integer; begin result := DFDays.Value; end; procedure TInfoCANCELTable.SetPPr_PCT(const Value: String); begin DFPr_PCT.Value := Value; end; function TInfoCANCELTable.GetPPr_PCT:String; begin result := DFPr_PCT.Value; end; procedure TInfoCANCELTable.SetPSr_PCT(const Value: String); begin DFSr_PCT.Value := Value; end; function TInfoCANCELTable.GetPSr_PCT:String; begin result := DFSr_PCT.Value; end; procedure TInfoCANCELTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoCANCELTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoCANCELTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Table, String, 2, N'); Add('Days, Integer, 0, N'); Add('Pr_PCT, String, 168, N'); Add('Sr_PCT, String, 168, N'); Add('ModCount, SmallInt, 0, N'); end; end; procedure TInfoCANCELTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Table;Days, Y, Y, N, N'); end; end; procedure TInfoCANCELTable.SetEnumIndex(Value: TEIInfoCANCEL); begin case Value of InfoCANCELPrimaryKey : IndexName := ''; end; end; function TInfoCANCELTable.GetDataBuffer:TInfoCANCELRecord; var buf: TInfoCANCELRecord; begin fillchar(buf, sizeof(buf), 0); buf.PTable := DFTable.Value; buf.PDays := DFDays.Value; buf.PPr_PCT := DFPr_PCT.Value; buf.PSr_PCT := DFSr_PCT.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoCANCELTable.StoreDataBuffer(ABuffer:TInfoCANCELRecord); begin DFTable.Value := ABuffer.PTable; DFDays.Value := ABuffer.PDays; DFPr_PCT.Value := ABuffer.PPr_PCT; DFSr_PCT.Value := ABuffer.PSr_PCT; DFModCount.Value := ABuffer.PModCount; end; function TInfoCANCELTable.GetEnumIndex: TEIInfoCANCEL; var iname : string; begin result := InfoCANCELPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoCANCELPrimaryKey; end; function TInfoCANCELQuery.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoCANCELQuery.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoCANCELQuery.GenerateNewFieldName } function TInfoCANCELQuery.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoCANCELQuery.CreateField } procedure TInfoCANCELQuery.CreateFields; begin FDFTable := CreateField( 'Table' ) as TStringField; FDFDays := CreateField( 'Days' ) as TIntegerField; FDFPr_PCT := CreateField( 'Pr_PCT' ) as TStringField; FDFSr_PCT := CreateField( 'Sr_PCT' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; end; { TInfoCANCELQuery.CreateFields } procedure TInfoCANCELQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoCANCELQuery.SetActive } procedure TInfoCANCELQuery.SetPTable(const Value: String); begin DFTable.Value := Value; end; function TInfoCANCELQuery.GetPTable:String; begin result := DFTable.Value; end; procedure TInfoCANCELQuery.SetPDays(const Value: Integer); begin DFDays.Value := Value; end; function TInfoCANCELQuery.GetPDays:Integer; begin result := DFDays.Value; end; procedure TInfoCANCELQuery.SetPPr_PCT(const Value: String); begin DFPr_PCT.Value := Value; end; function TInfoCANCELQuery.GetPPr_PCT:String; begin result := DFPr_PCT.Value; end; procedure TInfoCANCELQuery.SetPSr_PCT(const Value: String); begin DFSr_PCT.Value := Value; end; function TInfoCANCELQuery.GetPSr_PCT:String; begin result := DFSr_PCT.Value; end; procedure TInfoCANCELQuery.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoCANCELQuery.GetPModCount:SmallInt; begin result := DFModCount.Value; end; function TInfoCANCELQuery.GetDataBuffer:TInfoCANCELRecord; var buf: TInfoCANCELRecord; begin fillchar(buf, sizeof(buf), 0); buf.PTable := DFTable.Value; buf.PDays := DFDays.Value; buf.PPr_PCT := DFPr_PCT.Value; buf.PSr_PCT := DFSr_PCT.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoCANCELQuery.StoreDataBuffer(ABuffer:TInfoCANCELRecord); begin DFTable.Value := ABuffer.PTable; DFDays.Value := ABuffer.PDays; DFPr_PCT.Value := ABuffer.PPr_PCT; DFSr_PCT.Value := ABuffer.PSr_PCT; DFModCount.Value := ABuffer.PModCount; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoCANCELTable, TInfoCANCELQuery, TInfoCANCELBuffer ] ); end; { Register } function TInfoCANCELBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('TABLE','DAYS','PR_PCT','SR_PCT','MODCOUNT' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 5) and (flist[x] <> s) do inc(x); if x <= 5 then result := x else result := 0; end; function TInfoCANCELBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftInteger; 3 : result := ftString; 4 : result := ftString; 5 : result := ftSmallInt; end; end; function TInfoCANCELBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PTable; 2 : result := @Data.PDays; 3 : result := @Data.PPr_PCT; 4 : result := @Data.PSr_PCT; 5 : result := @Data.PModCount; end; end; end.
namespace Sugar.Test; interface uses Sugar, RemObjects.Elements.EUnit; type EncodingTest = public class (Test) public method GetBytes; method GetBytes2; method GetChars; method GetString; method GetEncoding; end; implementation method EncodingTest.GetBytes; begin Assert.AreEqual(Encoding.UTF8.GetBytes("Hello©"), [72, 101, 108, 108, 111, 194, 169]); Assert.AreEqual(Encoding.UTF16LE.GetBytes("Hello"), [72, 0, 101, 0, 108, 0, 108, 0, 111, 0]); Assert.AreEqual(Encoding.UTF16BE.GetBytes("Hello"), [0, 72, 0, 101, 0, 108, 0, 108, 0, 111]); Assert.AreEqual(Encoding.ASCII.GetBytes("Hello"), [72, 101, 108, 108, 111]); Assert.AreEqual(Encoding.GetEncoding("Windows-1251").GetBytes("æж"), [63, 230]); var Value: String := nil; Assert.Throws(->Encoding.UTF8.GetBytes(Value)); end; method EncodingTest.GetBytes2; begin Assert.AreEqual(Encoding.UTF8.GetBytes(['H', 'e', 'l', 'l', 'o', '©']), [72, 101, 108, 108, 111, 194, 169]); Assert.AreEqual(Encoding.UTF16LE.GetBytes(['H', 'e', 'l', 'l', 'o']), [72, 0, 101, 0, 108, 0, 108, 0, 111, 0]); Assert.AreEqual(Encoding.UTF16BE.GetBytes(['H', 'e', 'l', 'l', 'o']), [0, 72, 0, 101, 0, 108, 0, 108, 0, 111]); Assert.AreEqual(Encoding.ASCII.GetBytes(['H', 'e', 'l', 'l', 'o']), [72, 101, 108, 108, 111]); Assert.AreEqual(Encoding.GetEncoding("Windows-1251").GetBytes(['æ', 'ж']), [63, 230]); Assert.AreEqual(Encoding.UTF8.GetBytes(['H', 'e', 'l', 'l', 'o', '©'], 2, 3), [108, 108, 111]); Assert.Throws(->Encoding.UTF8.GetBytes(['a', 'b'], 5, 1)); Assert.Throws(->Encoding.UTF8.GetBytes(['a', 'b'], 1, 5)); Assert.Throws(->Encoding.UTF8.GetBytes(['a', 'b'], -1, 1)); Assert.Throws(->Encoding.UTF8.GetBytes(['a', 'b'], 1, -1)); var Value: array of Char := nil; Assert.Throws(->Encoding.UTF8.GetBytes(Value, 1, 1)); Assert.Throws(->Encoding.UTF8.GetBytes(Value)); end; method EncodingTest.GetChars; begin Assert.AreEqual(Encoding.UTF8.GetChars([72, 101, 108, 108, 111, 194, 169]), ['H', 'e', 'l', 'l', 'o', '©']); Assert.AreEqual(Encoding.UTF16LE.GetChars([72, 0, 101, 0, 108, 0, 108, 0, 111, 0]), ['H', 'e', 'l', 'l', 'o']); Assert.AreEqual(Encoding.UTF16BE.GetChars([0, 72, 0, 101, 0, 108, 0, 108, 0, 111]), ['H', 'e', 'l', 'l', 'o']); Assert.AreEqual(Encoding.ASCII.GetChars([72, 101, 108, 108, 111]), ['H', 'e', 'l', 'l', 'o']); Assert.AreEqual(Encoding.GetEncoding("Windows-1251").GetChars([230]), ['ж']); Assert.AreEqual(Encoding.UTF8.GetChars([72, 101, 108, 108, 111, 194, 169], 2, 3), ['l', 'l', 'o']); var Value: array of Byte := nil; Assert.Throws(->Encoding.ASCII.GetChars(Value)); Assert.Throws(->Encoding.ASCII.GetChars(Value, 5, 1)); Assert.Throws(->Encoding.ASCII.GetChars([1, 2], 5, 1)); Assert.Throws(->Encoding.ASCII.GetChars([1, 2], 1, 5)); Assert.Throws(->Encoding.ASCII.GetChars([1, 2], -1, 1)); Assert.Throws(->Encoding.ASCII.GetChars([1, 2], 1, -1)); end; method EncodingTest.GetString; begin Assert.AreEqual(Encoding.UTF8.GetString([72, 101, 108, 108, 111, 194, 169]), "Hello©"); Assert.AreEqual(Encoding.UTF16LE.GetString([72, 0, 101, 0, 108, 0, 108, 0, 111, 0]), "Hello"); Assert.AreEqual(Encoding.UTF16BE.GetString([0, 72, 0, 101, 0, 108, 0, 108, 0, 111]), "Hello"); Assert.AreEqual(Encoding.ASCII.GetString([72, 101, 108, 108, 111]), "Hello"); Assert.AreEqual(Encoding.GetEncoding("Windows-1251").GetString([168, 230]), "Ёж"); Assert.AreEqual(Encoding.UTF8.GetString([72, 101, 108, 108, 111, 194, 169], 2, 3), "llo"); Assert.AreEqual(Encoding.UTF8.GetString([]), ""); var Value: array of Byte := nil; Assert.Throws(->Encoding.UTF8.GetString(Value)); Assert.Throws(->Encoding.UTF8.GetString(Value, 1, 1)); Assert.Throws(->Encoding.UTF8.GetString([1, 2], 5, 1)); Assert.Throws(->Encoding.UTF8.GetString([1, 2], 1, 5)); Assert.Throws(->Encoding.UTF8.GetString([1, 2], -1, 1)); Assert.Throws(->Encoding.UTF8.GetString([1, 2], 1, -1)); end; method EncodingTest.GetEncoding; begin Assert.IsNotNil(Encoding.ASCII); Assert.IsNotNil(Encoding.UTF8); Assert.IsNotNil(Encoding.UTF16LE); Assert.IsNotNil(Encoding.UTF16BE); Assert.IsNotNil(Encoding.GetEncoding("Windows-1251")); Assert.Throws(->Encoding.GetEncoding(nil)); Assert.Throws(->Encoding.GetEncoding("")); Assert.Throws(->Encoding.GetEncoding("Something completely different")); end; end.
{ Dado o registro abaixo, Nome Sexo Idade Altura Faça um algoritmo que leia N registros e determine: a) altura da pessoa mais alta; b) nome, sexo e idade da pessoa mais nova; c) média de idade dos "baixinhos", altura <= 1,58 cm; d) quantidades de mulheres com idade superior ou igual a 20. } Program Exercicio9; Type reg_pessoa = record nome: string; sexo: char; idade: integer; altura:real; end; vet_pessoas = array[1..100] of reg_pessoa; var pessoas:vet_pessoas; n:integer; procedure verificarQuantidade(var qtd:integer); begin repeat write('Digite a quantidade de pessoas entre 1 e 100: '); readln(n); until (qtd >0) and (qtd <= 100); end; Procedure cadastrarPessoas(var vet: vet_pessoas; n:integer); var sexo: char; i: integer; begin for i := 1 to n do begin write('Nome da pessoa ', i, ': '); readln(vet[i].nome); write('Idade da pessoa ', i, ': '); readln(vet[i].idade); write('Altura da pessoa ', i, ': '); readln(vet[i].altura); repeat write('Sexo da pessoa ', i, '(Digite m ou f): '); readln(sexo); ClrScr; until(sexo = 'm') or (sexo = 'f'); vet[i].sexo := sexo; end; clrscr; end; function getMaiorAltura(pessoas:vet_pessoas;n:integer):real; var altura:real; i:integer; begin altura:=0; for i := 1 to n do begin if(pessoas[i].altura > altura) then altura:= pessoas[i].altura; end; getMaiorAltura:= altura; end; function getMenorIdade(pessoas:vet_pessoas;n:integer):integer; var idade:integer; i:integer; begin idade:=999; for i := 1 to n do begin if(pessoas[i].idade < idade) then idade:= pessoas[i].idade; end; getMenorIdade:= idade; end; procedure imprimirPessoasMaisAltas(pessoas:vet_pessoas;n:integer; altura:real); var i:integer; begin writeln('Pessoas mais altas igual à: ', altura:2:2); for i := 1 to n do begin if(pessoas[i].altura >= altura) then begin writeln('-> ', pessoas[i].nome, ' do sexo: ', pessoas[i].sexo, ', idade: ', pessoas[i].idade, ' e altura de: ', pessoas[i].altura:2:2); end; end; end; procedure imprimirPessoasMaisNovas(pessoas:vet_pessoas;n:integer; idade:integer); var i:integer; begin writeln('Pessoas mais novas igual à: ', idade); for i := 1 to n do begin if(pessoas[i].idade <= idade) then begin writeln('-> ', pessoas[i].nome, ' do sexo: ', pessoas[i].sexo, ', idade: ', pessoas[i].idade, ' e altura de: ', pessoas[i].altura:2:2); end; end; end; procedure imprimirPessoasPorSexoEIdade(pessoas:vet_pessoas;n:integer;sexo:char; idade:integer); var i:integer; begin writeln('Pessoas do sexo: ', sexo, ' com idade >= ', idade); for i := 1 to n do begin if((pessoas[i].idade >= idade) and (pessoas[i].sexo = sexo)) then begin writeln('-> ', pessoas[i].nome, ' do sexo: ', pessoas[i].sexo, ', idade: ', pessoas[i].idade, ' e altura de: ', pessoas[i].altura:2:2); end; end; end; procedure imprimirMediaDeIdadeDeBaixinhos(pessoas:vet_pessoas;n:integer); var i:integer; somaIdades:integer; somaBaixinhos:integer; begin somaIdades:=0; somaBaixinhos:=0; for i := 1 to n do begin if(pessoas[i].altura <= 1.58) then begin somaIdades:= somaIdades + pessoas[i].idade; somaBaixinhos := somaBaixinhos +1; //writeln('-> ', pessoas[i].nome, ' do sexo: ', pessoas[i].sexo, ', idade: ', pessoas[i].idade, ' e altura de: ', pessoas[i].altura:2:2); end; end; writeln('A média de idade de baixinhos é de: ',(somaIdades/somaBaixinhos):2:2); end; Begin verificarQuantidade(n); cadastrarPessoas(pessoas, n); imprimirPessoasMaisAltas(pessoas, n, getMaiorAltura(pessoas,n)); imprimirPessoasMaisNovas(pessoas, n, getMenorIdade(pessoas,n)); imprimirMediaDeIdadeDeBaixinhos(pessoas, n); imprimirPessoasPorSexoEIdade(pessoas,n, 'f', 20); // mostrarMenu(); // writeln(getMaiorAltura(pessoas, n)); // mostrarPessoasMaisAltas(pessoas); End.
unit csUserDefinedExport; { Задание на экспорт, которое выполняется с заданной периодичностью } interface uses csProcessTask, Classes, DT_types; type TcsUserDefinedExport = class(TddProcessTask) // Периодичность, время private f_QueryFile: String; f_TimeToRun: TDateTime; protected procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override; public constructor Create(aOwner: TObject; aUserID: TUserID); override; procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override; property QueryFile: String read f_QueryFile write f_QueryFile; property TimeToRun: TDateTime read f_TimeToRun write f_TimeToRun; end; implementation uses CsTaskTypes, ddServerTask; { ****************************** TddExportTaskItem ******************************* } constructor TcsUserDefinedExport.Create(aOwner: TObject; aUserID: TUserID); begin inherited; TaskType := cs_ttUserDefinedExport; end; procedure TcsUserDefinedExport.LoadFrom(aStream: TStream; aIsPipe: Boolean); var l_Value: Integer; begin inherited; with aStream do begin aStream.Read(f_TimeToRun, SizeOf(TDateTime)); ReadFileFrom(aStream, TaskFolder); end; // with aStream end; procedure TcsUserDefinedExport.SaveTo(aStream: TStream; aIsPipe: Boolean); var l_Value: Integer; begin inherited; with aStream do begin aStream.Write(f_TimeToRun, SizeOf(TDateTime)); WriteFileTo(aStream, f_QueryFile); end; // with aStream end; initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\cs\csUserDefinedExport.pas initialization enter'); {$EndIf} RegisterTaskClass(cs_ttUserDefinedExport, TcsUserDefinedExport, 'Выполнение команды на сервере'); {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\cs\csUserDefinedExport.pas initialization leave'); {$EndIf} end.
unit l3_Base; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "L3" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/L3/l3_Base.pas" // Начат: 05.02.2008 16:57 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Low Level::L3::l3CoreObjects::Tl3_Base // // ! Базовый класс объектов библиотеки L3. Рекомендуется для наследования от него остальных // разрабатываемых объектов. Поддерживает контроль за распределением памяти и освобождением // объектов. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\L3\l3Define.inc} interface uses l3Types, l3CBase, Classes ; type Tl3_Base = class(Tl3CBase) {* ! Базовый класс объектов библиотеки L3. Рекомендуется для наследования от него остальных разрабатываемых объектов. Поддерживает контроль за распределением памяти и освобождением объектов. } protected // property methods function pm_GetHandle: Tl3Handle; virtual; procedure pm_SetHandle(aValue: Tl3Handle); virtual; public // overridden public methods procedure Assign(Source: TPersistent); override; public // public methods function Clone(anOwner: TObject = nil): Pointer; virtual; {* функция для получения копии объекта. } function OCompare(anObject: TObject): Integer; virtual; {* функция сравнения объекта с другим объектом. } public // public properties property Handle: Tl3Handle read pm_GetHandle write pm_SetHandle; {* идентификатор объекта. } end;//Tl3_Base implementation uses l3Base ; // start class Tl3_Base function Tl3_Base.pm_GetHandle: Tl3Handle; //#UC START# *478798730050_47879856035Fget_var* //#UC END# *478798730050_47879856035Fget_var* begin //#UC START# *478798730050_47879856035Fget_impl* Result := 0; //#UC END# *478798730050_47879856035Fget_impl* end;//Tl3_Base.pm_GetHandle procedure Tl3_Base.pm_SetHandle(aValue: Tl3Handle); //#UC START# *478798730050_47879856035Fset_var* //#UC END# *478798730050_47879856035Fset_var* begin //#UC START# *478798730050_47879856035Fset_impl* //#UC END# *478798730050_47879856035Fset_impl* end;//Tl3_Base.pm_SetHandle function Tl3_Base.Clone(anOwner: TObject = nil): Pointer; //#UC START# *478CEE4C0225_47879856035F_var* type Rl3_Base = class of Tl3_Base; //#UC END# *478CEE4C0225_47879856035F_var* begin //#UC START# *478CEE4C0225_47879856035F_impl* Result := Rl3_Base(ClassType).Create(anOwner); Tl3_Base(Result).Assign(Self); //#UC END# *478CEE4C0225_47879856035F_impl* end;//Tl3_Base.Clone function Tl3_Base.OCompare(anObject: TObject): Integer; //#UC START# *478CEE670214_47879856035F_var* //#UC END# *478CEE670214_47879856035F_var* begin //#UC START# *478CEE670214_47879856035F_impl* Assert(false); Result := -1; //#UC END# *478CEE670214_47879856035F_impl* end;//Tl3_Base.OCompare procedure Tl3_Base.Assign(Source: TPersistent); //#UC START# *478CF34E02CE_47879856035F_var* //#UC END# *478CF34E02CE_47879856035F_var* begin //#UC START# *478CF34E02CE_47879856035F_impl* inherited; if (Source Is Tl3_Base) then Handle := Tl3_Base(Source).Handle; //#UC END# *478CF34E02CE_47879856035F_impl* end;//Tl3_Base.Assign end.
unit uConfig; interface uses System.SysUtils, System.IniFiles; type TConfigIni = class private Arquivo: string; procedure CriaArquivoPadrao; function GetChave(Chave: string): string; function GetHost: string; function GetPorta: string; public constructor Create; property Host: string read GetHost; property Porta: string read GetPorta; end; var Config: TConfigIni; const CONFIG_INI_ARQUIVO = 'Config.ini'; CONFIG_INI_SECAO_GERAL = 'Geral'; CONFIG_INI_HOST_NAME = 'Host'; CONFIG_INI_HOST_DEFAULT = 'localhost'; CONFIG_INI_PORTA_NAME = 'Porta'; CONFIG_INI_PORTA_DEFAULT = '25000'; implementation { TConfigIni } constructor TConfigIni.Create; begin Arquivo := Format('%s\%s', [ExtractFilePath(ParamStr(0)), CONFIG_INI_ARQUIVO]); CriaArquivoPadrao; end; procedure TConfigIni.CriaArquivoPadrao; begin if not FileExists(Arquivo) then with TIniFile.Create(Arquivo) do begin try WriteString(CONFIG_INI_SECAO_GERAL, CONFIG_INI_HOST_NAME, CONFIG_INI_HOST_DEFAULT); WriteString(CONFIG_INI_SECAO_GERAL, CONFIG_INI_PORTA_NAME, CONFIG_INI_PORTA_DEFAULT); finally Free; end; end; end; function TConfigIni.GetChave(Chave: string): string; begin with TIniFile.Create(Arquivo) do begin try Result := ReadString(CONFIG_INI_SECAO_GERAL, Chave, ''); finally Free; end; end; end; function TConfigIni.GetHost: string; begin Result := GetChave(CONFIG_INI_HOST_NAME); if (Result = '') then Result := CONFIG_INI_HOST_DEFAULT; end; function TConfigIni.GetPorta: string; begin Result := GetChave(CONFIG_INI_PORTA_NAME); if (Result = '') then Result := CONFIG_INI_PORTA_DEFAULT; end; initialization Config := TConfigIni.Create(); finalization Config.Free(); end.
// AkTools akCOMUtils unit. // Модуль, помогающий работать с COM/OLE. //============================================================================= unit akCOMUtils; interface uses Windows; const // Guid'ы, не определенные в стандартных дельфовых модулях. IID_IOleContainer: TGUID = '{0000011B-0000-0000-C000-000000000046}'; IID_IOleCommandTarget: TGUID = '{b722bccb-4e68-101b-a2bc-00aa00404770}'; CGID_MSHTML: TGUID = '{DE4BA900-59CA-11CF-9592-444553540000}'; // GUID не инициализирован function IsGUIDEmpty(const GUID: TGUID): Boolean; // Очищает GUID procedure EmptyGUID(var GUID: TGUID); // Возвращает строковео представление OleVariant. Если там Null - вернет пустую // строку function OStr(str: OleVariant): String; implementation uses ActiveX, SysUtils; function OStr(str: OleVariant): String; begin if str = Null then Result := '' else Result := str; end; function IsGUIDEmpty(const GUID: TGUID): Boolean; var st: TGUID; begin EmptyGUID(st); Result := CompareMem(@st, @GUID, SizeOf(st)); end; procedure EmptyGUID(var GUID: TGUID); begin ZeroMemory(@GUID, SizeOf(GUID)); end; end.
unit uHardware; interface uses Winapi.Windows, System.SysUtils; function getMacAddress: string; implementation //Rotina baixo nível para capturar mac da placa de rede //Não muda com formatação function getMacAddress: string; var Lib: Cardinal; Func: function(GUID: PGUID): Longint; stdcall; GUID1, GUID2: TGUID; begin Result := ''; Lib := LoadLibrary('rpcrt4.dll'); if Lib <> 0 then begin @Func := GetProcAddress(Lib, 'UuidCreateSequential'); if Assigned(Func) then begin if (Func(@GUID1) = 0) and (Func(@GUID2) = 0) and (GUID1.D4[2] = GUID2.D4[2]) and (GUID1.D4[3] = GUID2.D4[3]) and (GUID1.D4[4] = GUID2.D4[4]) and (GUID1.D4[5] = GUID2.D4[5]) and (GUID1.D4[6] = GUID2.D4[6]) and (GUID1.D4[7] = GUID2.D4[7]) then begin Result := IntToHex(GUID1.D4[2], 2) + '-' + IntToHex(GUID1.D4[3], 2) + '-' + IntToHex(GUID1.D4[4], 2) + '-' + IntToHex(GUID1.D4[5], 2) + '-' + IntToHex(GUID1.D4[6], 2) + '-' + IntToHex(GUID1.D4[7], 2); end; end; end; end; end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2022 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 FB4D.SelfRegistrationFra; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Edit, FMX.Controls.Presentation, FMX.Surfaces, FMX.Consts, FB4D.Interfaces, System.ImageList, FMX.ImgList; type TOnGetAuth = function : IFirebaseAuthentication of object; TOnGetStorage = function : IFirebaseStorage of object; TFraSelfRegistration = class(TFrame) AniIndicator: TAniIndicator; btnCheckEMail: TButton; btnResetPwd: TButton; btnSignIn: TButton; btnSignUp: TButton; edtEMail: TEdit; txtEMail: TText; edtPassword: TEdit; txtPassword: TText; lblStatus: TLabel; btnRegisterDisplayName: TButton; edtDisplayName: TEdit; txtDisplayName: TText; shpProfile: TCircle; btnLoadProfile: TButton; OpenDialog: TOpenDialog; procedure edtEMailChangeTracking(Sender: TObject); procedure btnCheckEMailClick(Sender: TObject); procedure btnSignInClick(Sender: TObject); procedure btnSignUpClick(Sender: TObject); procedure btnResetPwdClick(Sender: TObject); procedure btnRegisterDisplayNameClick(Sender: TObject); procedure btnLoadProfileClick(Sender: TObject); public const cDefaultProfileImgSize = 300; // 300x300 pixels cDefaultStoragePathForProfileImg = 'userProfiles'; private fAuth: IFirebaseAuthentication; fOnUserLogin: TOnUserResponse; fOnGetAuth: TOnGetAuth; fAllowSelfRegistration: boolean; fRequireVerificatedEMail: boolean; fRegisterDisplayName: boolean; fRegisterProfileImg: boolean; fStorage: IFirebaseStorage; fOnGetStorage: TOnGetStorage; fStoragePath: string; fReqInfo: string; fInfo: string; fUser: IFirebaseUser; fTokenRefreshed: boolean; fProfileLoadStream: TMemoryStream; fProfileImgSize: integer; fProfileURL: string; fProfileImg: TBitmap; fDefaultProfileImg: TBitmap; procedure StartTokenReferesh(const LastToken: string); procedure OnFetchProviders(const EMail: string; IsRegistered: boolean; Providers: TStrings); procedure OnFetchProvidersError(const Info, ErrMsg: string); procedure OnResetPwd(const Info: string; Response: IFirebaseResponse); procedure OnUserError(const Info, ErrMsg: string); procedure OnUserResponse(const Info: string; User: IFirebaseUser); procedure OnTokenRefresh(TokenRefreshed: boolean); procedure OnGetUserData(FirebaseUserList: TFirebaseUserList); procedure OnVerificationMailSent(const RequestID: string; Response: IFirebaseResponse); procedure OnChangedProfile(const RequestID: string; Response: IFirebaseResponse); procedure OnProfileImgUpload(Obj: IStorageObject); procedure OnProfileImgError(const RequestID, ErrMsg: string); procedure StartDownloadProfileImg(PhotoURL: string); procedure OnProfileDownload(const DownloadURL: string); function GetProfileImg: TBitmap; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Initialize(Auth: IFirebaseAuthentication; OnUserLogin: TOnUserResponse; const LastRefreshToken: string = ''; const LastEMail: string = ''; AllowSelfRegistration: boolean = true; RequireVerificatedEMail: boolean = false; RegisterDisplayName: boolean = false); procedure InitializeAuthOnDemand(OnGetAuth: TOnGetAuth; OnUserLogin: TOnUserResponse; const LastRefreshToken: string = ''; const LastEMail: string = ''; AllowSelfRegistration: boolean = true; RequireVerificatedEMail: boolean = false; RegisterDisplayName: boolean = false); procedure RequestProfileImg(OnGetStorage: TOnGetStorage; const StoragePath: string = cDefaultStoragePathForProfileImg; ProfileImgSize: integer = cDefaultProfileImgSize); procedure StartEMailEntering; procedure InformDelayedStart(const Msg: string); procedure StopDelayedStart; function GetEMail: string; property ProfileImg: TBitmap read GetProfileImg; property ProfileURL: string read fProfileURL; end; implementation uses REST.Types, FB4D.Helpers; {$R *.fmx} resourcestring rsEnterEMail = 'Enter your e-mail address for sign-in or registration'; rsWait = 'Please wait for Firebase'; rsEnterPassword = 'Enter your password for registration'; rsSetupPassword = 'Setup a new password for future registrations'; rsNotRegisteredEMail = 'The entered e-mail is not registered'; rsPleaseCheckEMail = 'Please check your e-mail inbox to renew your password'; rsLoggedIn = 'Successful logged in'; rsPleaseCheckEMailForVerify = 'Please check your e-mail inbox to confirm your email address'; rsWriteProfileData = 'Your %s will be registrated'; rsUserError = 'Access of user data failed: %s'; rsProfileLoadErr = 'Load of your profile photo is failed: %s'; constructor TFraSelfRegistration.Create(AOwner: TComponent); begin inherited; edtDisplayName.Visible := false; btnRegisterDisplayName.Visible := false; shpProfile.Visible := false; fProfileURL := ''; fProfileImg := nil; fTokenRefreshed := false; fStorage := nil; fDefaultProfileImg := TBitmap.Create; fDefaultProfileImg.Assign(shpProfile.Fill.Bitmap.Bitmap); end; destructor TFraSelfRegistration.Destroy; begin fProfileLoadStream.Free; fDefaultProfileImg.Free; fProfileImg.Free; inherited; end; procedure TFraSelfRegistration.Initialize(Auth: IFirebaseAuthentication; OnUserLogin: TOnUserResponse; const LastRefreshToken, LastEMail: string; AllowSelfRegistration, RequireVerificatedEMail, RegisterDisplayName: boolean); begin fAuth := Auth; fOnUserLogin := OnUserLogin; fOnGetAuth := nil; edtEMail.Text := LastEMail; fAllowSelfRegistration := AllowSelfRegistration; fRequireVerificatedEMail := RequireVerificatedEMail; fRegisterDisplayName := RegisterDisplayName; if LastRefreshToken.IsEmpty then StartEMailEntering else StartTokenReferesh(LastRefreshToken); end; procedure TFraSelfRegistration.InitializeAuthOnDemand(OnGetAuth: TOnGetAuth; OnUserLogin: TOnUserResponse; const LastRefreshToken, LastEMail: string; AllowSelfRegistration, RequireVerificatedEMail, RegisterDisplayName: boolean); begin fAuth := nil; fOnUserLogin := OnUserLogin; fOnGetAuth := OnGetAuth; edtEMail.Text := LastEMail; fAllowSelfRegistration := AllowSelfRegistration; fRequireVerificatedEMail := RequireVerificatedEMail; fRegisterDisplayName := RegisterDisplayName; if LastRefreshToken.IsEmpty then StartEMailEntering else StartTokenReferesh(LastRefreshToken); end; procedure TFraSelfRegistration.RequestProfileImg(OnGetStorage: TOnGetStorage; const StoragePath: string; ProfileImgSize: integer); begin fRegisterProfileImg := true; fOnGetStorage := OnGetStorage; fStoragePath := StoragePath; fProfileImgSize := ProfileImgSize; end; procedure TFraSelfRegistration.StartEMailEntering; begin fInfo := ''; edtEMail.Visible := true; btnCheckEMail.Visible := true; btnCheckEMail.Enabled := TFirebaseHelpers.IsEMailAdress(edtEMail.Text); lblStatus.Text := rsEnterEMail; btnSignIn.Visible := false; btnResetPwd.Visible := false; btnSignUp.Visible := false; edtPassword.Visible := false; edtDisplayName.Visible := false; btnRegisterDisplayName.Visible := false; shpProfile.Visible := false; edtEMail.SetFocus; end; procedure TFraSelfRegistration.edtEMailChangeTracking(Sender: TObject); begin if edtPassword.Visible then begin lblStatus.Text := rsEnterEMail; edtPassword.Visible := false; btnCheckEMail.Visible := true; btnSignUp.Visible := false; btnSignIn.Visible := false; btnResetPwd.Visible := false; end; btnCheckEMail.Enabled := TFirebaseHelpers.IsEMailAdress(edtEMail.Text); end; procedure TFraSelfRegistration.btnCheckEMailClick(Sender: TObject); begin if not assigned(fAuth) and assigned(fOnGetAuth) then fAuth := fOnGetAuth; Assert(assigned(fAuth), 'Auth is not initialized'); fAuth.FetchProvidersForEMail(trim(edtEmail.Text), OnFetchProviders, OnFetchProvidersError); AniIndicator.Enabled := true; AniIndicator.Visible := true; btnCheckEMail.Enabled := false; lblStatus.Text := rsWait; end; procedure TFraSelfRegistration.OnFetchProviders(const EMail: string; IsRegistered: boolean; Providers: TStrings); begin AniIndicator.Enabled := false; AniIndicator.Visible := false; if IsRegistered then begin btnSignUp.Visible := false; btnSignIn.Visible := true; btnSignIn.Enabled := true; btnResetPwd.Visible := true; btnResetPwd.Enabled := true; lblStatus.Text := rsEnterPassword; edtPassword.Text := ''; edtPassword.Visible := true; edtPassword.SetFocus; btnCheckEMail.Visible := false; end else if fAllowSelfRegistration then begin btnSignUp.Visible := true; btnSignUp.Enabled := true; btnSignIn.Visible := false; btnResetPwd.Visible := false; lblStatus.Text := rsSetupPassword; edtPassword.Text := ''; edtPassword.Visible := true; edtPassword.SetFocus; btnCheckEMail.Visible := false; end else begin lblStatus.Text := rsNotRegisteredEMail; edtEMail.SetFocus; end; end; procedure TFraSelfRegistration.OnFetchProvidersError(const Info, ErrMsg: string); begin AniIndicator.Enabled := false; AniIndicator.Visible := false; lblStatus.Text := Info + ': ' + ErrMsg; btnCheckEMail.Enabled := true; end; procedure TFraSelfRegistration.btnSignInClick(Sender: TObject); begin fAuth.SignInWithEmailAndPassword(trim(edtEmail.Text), edtPassword.Text, OnUserResponse, OnUserError); AniIndicator.Enabled := true; AniIndicator.Visible := true; btnSignIn.Enabled := false; btnResetPwd.Enabled := false; lblStatus.Text := rsWait; end; procedure TFraSelfRegistration.btnSignUpClick(Sender: TObject); begin fAuth.SignUpWithEmailAndPassword(trim(edtEmail.Text), edtPassword.Text, OnUserResponse, OnUserError); AniIndicator.Enabled := true; AniIndicator.Visible := true; btnSignUp.Enabled := false; lblStatus.Text := rsWait; end; procedure TFraSelfRegistration.btnResetPwdClick(Sender: TObject); begin fAuth.SendPasswordResetEMail(trim(edtEMail.Text), OnResetPwd, OnUserError); AniIndicator.Enabled := true; AniIndicator.Visible := true; btnSignIn.Enabled := false; btnResetPwd.Enabled := false; lblStatus.Text := rsWait; end; procedure TFraSelfRegistration.OnResetPwd(const Info: string; Response: IFirebaseResponse); begin AniIndicator.Enabled := false; AniIndicator.Visible := false; btnSignIn.Enabled := true; if Response.StatusOk then lblStatus.Text := rsPleaseCheckEMail else lblStatus.Text := Response.ErrorMsgOrStatusText; end; procedure TFraSelfRegistration.StartTokenReferesh(const LastToken: string); begin if not assigned(fAuth) and assigned(fOnGetAuth) then fAuth := fOnGetAuth; Assert(assigned(fAuth), 'Auth is not initialized'); AniIndicator.Enabled := true; AniIndicator.Visible := true; edtEMail.Visible := false; btnCheckEMail.Visible := false; lblStatus.Text := rsWait; btnSignIn.Visible := false; btnResetPwd.Visible := false; btnSignUp.Visible := false; edtPassword.Visible := false; fReqInfo := 'AfterTokenRefresh'; fAuth.RefreshToken(LastToken, OnTokenRefresh, OnUserError); end; procedure TFraSelfRegistration.OnTokenRefresh(TokenRefreshed: boolean); begin fTokenRefreshed := true; if TokenRefreshed then fAuth.GetUserData(OnGetUserData, OnUserError) else StartEMailEntering; end; procedure TFraSelfRegistration.OnGetUserData(FirebaseUserList: TFirebaseUserList); var User: IFirebaseUser; begin if FirebaseUserList.Count = 1 then begin User := FirebaseUserList[0]; if fRequireVerificatedEMail then if User.IsEMailVerified <> tsbTrue then begin fAuth.SendEmailVerification(OnVerificationMailSent, OnUserError); exit; end; OnUserResponse(fReqInfo, User); end else StartEMailEntering; end; procedure TFraSelfRegistration.OnUserError(const Info, ErrMsg: string); begin AniIndicator.Enabled := false; AniIndicator.Visible := false; StartEMailEntering; lblStatus.Text := Format(rsUserError, [ErrMsg]); end; procedure TFraSelfRegistration.OnUserResponse(const Info: string; User: IFirebaseUser); const cReqInfo4Photo = 'GetUserDataForPhoto'; var WaitForDisplayNameOrProfile: boolean; begin if fRequireVerificatedEMail then case User.IsEMailVerified of tsbUnspecified: begin fReqInfo := 'GetUserData'; fAuth.GetUserData(OnGetUserData, OnUserError); exit; end; tsbFalse: begin fAuth.SendEmailVerification(OnVerificationMailSent, OnUserError); exit; end; end; if fRegisterProfileImg and not User.IsPhotoURLAvailable and not SameText(Info, cReqInfo4Photo) then begin fReqInfo := cReqInfo4Photo; fAuth.GetUserData(OnGetUserData, OnUserError); exit; end; AniIndicator.Enabled := false; AniIndicator.Visible := false; edtEMail.Visible := false; edtPassword.Visible := false; btnSignIn.Visible := false; btnSignUp.Visible := false; btnResetPwd.Visible := false; fInfo := Info; if assigned(fUser) and (fUser.UID <> User.UID) then begin fProfileURL := ''; shpProfile.Fill.Bitmap.Bitmap.Assign(fDefaultProfileImg); end; fUser := User; WaitForDisplayNameOrProfile := false; if fRegisterDisplayName and User.IsDisplayNameAvailable and not User.DisplayName.IsEmpty then begin lblStatus.visible := false; edtDisplayName.Visible := true; edtDisplayName.Text := User.DisplayName; btnRegisterDisplayName.Visible := true; end; if fRegisterProfileImg and User.IsPhotoURLAvailable and not User.PhotoURL.IsEmpty and fProfileURL.IsEmpty then begin StartDownloadProfileImg(User.PhotoURL); WaitForDisplayNameOrProfile := true; end else if fRegisterProfileImg and (not User.IsPhotoURLAvailable or User.PhotoURL.IsEmpty) then begin shpProfile.Visible := true; WaitForDisplayNameOrProfile := true; end; if fRegisterDisplayName and (not User.IsDisplayNameAvailable or User.DisplayName.IsEmpty) then begin lblStatus.visible := false; edtDisplayName.Visible := true; edtDisplayName.SetFocus; btnRegisterDisplayName.Visible := true; shpProfile.Visible := fRegisterProfileImg; WaitForDisplayNameOrProfile := true; end; if assigned(fOnUserLogin) and not WaitForDisplayNameOrProfile then begin lblStatus.Text := rsLoggedIn; fOnUserLogin(fInfo, fUser); end; end; function TFraSelfRegistration.GetEMail: string; begin result := trim(edtEmail.Text); end; function TFraSelfRegistration.GetProfileImg: TBitmap; begin if assigned(fProfileImg) then result := fProfileImg else result := fDefaultProfileImg; end; procedure TFraSelfRegistration.OnVerificationMailSent(const RequestID: string; Response: IFirebaseResponse); begin AniIndicator.Enabled := false; AniIndicator.Visible := false; lblStatus.Text := rsPleaseCheckEMailForVerify; btnSignIn.Enabled := true; end; procedure TFraSelfRegistration.btnRegisterDisplayNameClick(Sender: TObject); begin edtDisplayName.Visible := false; btnRegisterDisplayName.Visible := false; lblStatus.Text := Format(rsWriteProfileData, [txtDisplayName.Text]); fAuth.ChangeProfile('', '', edtDisplayName.Text, fProfileURL, OnChangedProfile, OnUserError); end; procedure TFraSelfRegistration.OnChangedProfile(const RequestID: string; Response: IFirebaseResponse); begin fAuth.GetUserData(OnGetUserData, OnUserError); end; procedure TFraSelfRegistration.StartDownloadProfileImg(PhotoURL: string); begin FreeAndNil(fProfileLoadStream); shpProfile.Visible := true; fProfileLoadStream := TMemoryStream.Create; TFirebaseHelpers.SimpleDownload(PhotoURL, fProfileLoadStream, OnProfileDownload, OnProfileImgError); AniIndicator.Enabled := true; AniIndicator.Visible := true; end; procedure TFraSelfRegistration.btnLoadProfileClick(Sender: TObject); var Bmp: TBitmap; Siz: integer; SrcRct, DstRct: TRectF; Ofs: integer; Surf: TBitmapSurface; begin OpenDialog.Filter := TBitmapCodecManager.GetFilterString; if OpenDialog.Execute then begin Bmp := TBitmap.Create; fProfileImg := TBitmap.Create; Surf := TBitmapSurface.Create; FreeAndNil(fProfileLoadStream); fProfileLoadStream := TMemoryStream.Create; try Bmp.LoadFromFile(OpenDialog.FileName); // Crop square image from center if Bmp.Width > Bmp.Height then begin Siz := Bmp.Height; Ofs := (Bmp.Width - Siz) div 2; SrcRct := RectF(Ofs, 0, Ofs + Siz, Siz); end else begin Siz := Bmp.Width; Ofs := (Bmp.Height - Siz) div 2; SrcRct := RectF(0, Ofs, Siz, Ofs + Siz); end; fProfileImg.Width := fProfileImgSize; fProfileImg.Height := fProfileImgSize; DstRct := RectF(0, 0, fProfileImgSize, fProfileImgSize); fProfileImg.Canvas.BeginScene; fProfileImg.Canvas.DrawBitmap(bmp, SrcRct, DstRct, 1); fProfileImg.Canvas.EndScene; shpProfile.Fill.Bitmap.Bitmap.Assign(fProfileImg); fStorage := fOnGetStorage; Surf.Assign(fProfileImg); if not TBitmapCodecManager.SaveToStream(fProfileLoadStream, Surf, SJPGImageExtension) then raise EBitmapSavingFailed.Create(SBitmapSavingFailed); fProfileLoadStream.Position := 0; fStorage.UploadFromStream(fProfileLoadStream, fStoragePath + '/' + fUser.UID, TRESTContentType.ctIMAGE_JPEG, OnProfileImgUpload, OnProfileImgError); btnLoadProfile.Enabled := false; AniIndicator.Enabled := true; AniIndicator.Visible := true; finally Surf.Free; Bmp.Free; end; end; end; procedure TFraSelfRegistration.OnProfileImgUpload(Obj: IStorageObject); begin FreeAndNil(fProfileLoadStream); fProfileURL := Obj.DownloadUrl; fAuth.ChangeProfile('', '', edtDisplayName.Text, fProfileURL, OnChangedProfile, OnUserError); end; procedure TFraSelfRegistration.OnProfileDownload(const DownloadURL: string); begin AniIndicator.Enabled := false; AniIndicator.Visible := false; fProfileURL := DownloadURL; fProfileImg := TBitmap.Create; fProfileImg.LoadFromStream(fProfileLoadStream); shpProfile.Fill.Bitmap.Bitmap.Assign(fProfileImg); FreeAndNil(fProfileLoadStream); if assigned(fOnGetStorage) then fOnGetStorage(); // Side effect disable Bucket edit box if assigned(fOnUserLogin) and fTokenRefreshed then begin lblStatus.Text := rsLoggedIn; TThread.CreateAnonymousThread( procedure begin Sleep(100); TThread.Queue(nil, procedure begin fOnUserLogin(fInfo, fUser); end); end).Start; end else if fRegisterDisplayName then btnRegisterDisplayName.Visible := true; end; procedure TFraSelfRegistration.OnProfileImgError(const RequestID, ErrMsg: string); begin AniIndicator.Enabled := false; AniIndicator.Visible := false; lblStatus.Text := Format(rsProfileLoadErr, [ErrMsg]); FreeAndNil(fProfileLoadStream); end; procedure TFraSelfRegistration.InformDelayedStart(const Msg: string); begin edtDisplayName.Visible := false; btnRegisterDisplayName.Visible := false; shpProfile.Visible := false; AniIndicator.Visible := true; AniIndicator.Enabled := true; lblStatus.visible := true; lblStatus.Text := Msg; {$IFDEF DEBUG} TFirebaseHelpers.Log('FraSelfRegistration.InformDelayedStart: ' + Msg); {$ENDIF} end; procedure TFraSelfRegistration.StopDelayedStart; begin AniIndicator.Visible := false; AniIndicator.Enabled := false; lblStatus.Text := ''; {$IFDEF DEBUG} TFirebaseHelpers.Log('FraSelfRegistration.StopDelayedStart'); {$ENDIF} end; end.
unit AdvCardListEditLinks; interface uses Classes, Spin, Controls, AdvCardList; type { TAdvCardListSpinEditLink } TAdvCardListSpinEditLink = class(TCardListEditLink) private FSpinEdit: TSpinEdit; FMaxValue: integer; FMinValue: integer; FEditorEnabled: boolean; public constructor Create(AOwner: TComponent); override; function CreateControl: TWinControl; override; procedure SetProperties; override; procedure SetSelection(SelStart, SelLength: integer); override; procedure SetFocus; override; procedure ValueToControl(value: variant); override; function ControlToValue: variant; override; published property EditorEnabled: boolean read FEditorEnabled write FEditorEnabled default true; property MinValue: integer read FMinValue write FMinValue default 0; property MaxValue: integer read FMaxValue write FMaxValue default 100; end; procedure Register; implementation procedure Register; begin RegisterComponents('TMS CardList', [TAdvCardListSpinEditLink]); end; { TCardListSpinEditLink } function TAdvCardListSpinEditLink.ControlToValue: variant; begin Result := FSpinEdit.Value; end; constructor TAdvCardListSpinEditLink.Create(AOwner: TComponent); begin inherited; FMinValue := 0; FMaxValue := 100; FEditorEnabled := true; end; function TAdvCardListSpinEditLink.CreateControl: TWinControl; begin FSpinEdit := TSpinEdit.Create(nil); Result := FSpinEdit; end; procedure TAdvCardListSpinEditLink.SetFocus; begin FSpinEdit.SetFocus; end; procedure TAdvCardListSpinEditLink.SetProperties; begin inherited; FSpinEdit.OnKeyDown := ControlKeyDown; FSpinEdit.MaxValue := FMaxValue; FSpinEdit.MinValue := FMinValue; FSpinEdit.EditorEnabled := true; end; procedure TAdvCardListSpinEditLink.SetSelection(SelStart, SelLength: integer); begin FSpinEdit.SelStart := SelStart; FSpinEdit.SelLength := SelLength; end; procedure TAdvCardListSpinEditLink.ValueToControl(value: variant); var str: string; i,e: integer; begin str := value; val(str,i,e); if (e = 0) then FSpinEdit.Value := i else FSpinEdit.Value := 0; end; end.
unit EditWindow; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TEditWin = class(TForm) Panel1: TPanel; Modify: TSpeedButton; Cancel: TSpeedButton; Memo: TMemo; SaveAs: TSpeedButton; SaveDialog: TSaveDialog; procedure ModifyClick(Sender: TObject); procedure CancelClick(Sender: TObject); procedure SaveAsClick(Sender: TObject); private fFileName : string; procedure SetFileName( aFileName : string ); public property FileName : string read fFileName write SetFileName; end; var EditWin: TEditWin; implementation {$R *.DFM} procedure TEditWin.ModifyClick(Sender: TObject); begin Memo.Lines.SaveToFile( fFileName ); ModalResult := mrOk; end; procedure TEditWin.CancelClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TEditWin.SetFileName( aFileName : string ); begin fFileName := aFileName; Caption := 'Editing [' + ExtractFileName(fFileName) + ']'; Memo.Lines.LoadFromFile( fFileName ); end; procedure TEditWin.SaveAsClick(Sender: TObject); begin if (SaveDialog.Execute) and (SaveDialog.FileName <> '') then begin Memo.Lines.SaveToFile( SaveDialog.FileName ); ModalResult := mrOk; end end; end.
unit CliDoc; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ImgList, ActnList, Menus, Db, DBTables, Grids, DBGrids, ComCtrls, DBCtrls, ToolWin, StdCtrls, DBActns, Impre2, JvFormPlacement; type TFCliDoc = class(TForm) MainMenu1: TMainMenu; Ventana1: TMenuItem; Cerrar1: TMenuItem; ActionList1: TActionList; Panel1: TPanel; DBGrid1: TDBGrid; DataSource1: TDataSource; Table1: TTable; CoolBar1: TCoolBar; ToolBar1: TToolBar; Cerrar: TAction; Imprimir: TAction; Ayuda: TAction; ToolButton1: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; Registros1: TMenuItem; Imprimir1: TMenuItem; Ayuda1: TMenuItem; Ayuda2: TMenuItem; Cancelados: TAction; ToolButton6: TToolButton; ToolButton7: TToolButton; ToolButton8: TToolButton; ToolButton9: TToolButton; First1: TDataSetFirst; Prior1: TDataSetPrior; Next1: TDataSetNext; Last1: TDataSetLast; Primero1: TMenuItem; Anterior1: TMenuItem; Siguiente1: TMenuItem; Ultimo1: TMenuItem; Table1Numero: TAutoIncField; Table1Vencto: TDateTimeField; Table1Importe: TFloatField; Table1PesDol: TBooleanField; Table1Coeficiente: TFloatField; Table1Cliente: TStringField; Table1Firmante: TStringField; Table1CodiRec: TStringField; Table1Recibo: TStringField; Table1Saldo: TFloatField; Table1Pago: TDateTimeField; Table1Cancelado: TStringField; Table1CodPago: TStringField; Table1ReciPago: TStringField; Table1Codigo: TStringField; StatusBar1: TStatusBar; Panel2: TPanel; Saldo: TLabel; Total: TLabel; Documentos1: TMenuItem; DocumentosCancelados1: TMenuItem; AnalisisdeCuentaDocumentada1: TMenuItem; Analisis: TAction; Actualiza: TDataSetRefresh; ToolButton5: TToolButton; ToolButton2: TToolButton; JvFormPlacement1: TJvFormStorage; procedure CerrarExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ImprimirExecute(Sender: TObject); procedure AyudaExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure AnalisisExecute(Sender: TObject); procedure CanceladosExecute(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } lEsNegro, lPrim: boolean; Impresora: TImpresora; nSaldoc: double; nPag: integer; sNombre, sCodigo: string; lCancelados: boolean; FechaIni, FechaFin: TDateTime; nVieSal: double; procedure Titulo; public { Public declarations } procedure EnHint(Sender: TObject); procedure SetCli( sCod, sNom: string; lCancel: boolean; nSaldo: double ); end; var FCliDoc: TFCliDoc; implementation uses SelFechas, DetDoc, Main, DMCons; {$R *.DFM} procedure TFCliDoc.CerrarExecute(Sender: TObject); begin Close; end; procedure TFCliDoc.FormCreate(Sender: TObject); begin lEsNegro := false; nVieSal := 0; DCons.TDatos.Open; Table1.Open; Application.OnHint := EnHint; end; procedure TFCliDoc.EnHint(Sender: TObject); begin StatusBar1.SimpleText := Application.Hint; end; procedure TFCliDoc.ImprimirExecute(Sender: TObject); begin if lCancelados then begin with TSelFechasDlg.create( self ) do try Caption := 'Documentos Cancelados'; FecIni.date := date-90; // TDiarioFECHA.value; FecFin.date := date; ShowModal; if ModalResult <> mrOK then exit; FechaIni := FecIni.date; FechaFin := FecFin.date; finally free; end; end; Impresora := TImpresora.create( self ); try With Impresora do begin if Impresora.SetearImp then begin UpdateWindow( Handle ); Abrir; Table1.DisableControls; Table1.First; nSalDoc := 0; if lCancelados then while ( Table1VENCTO.value < FechaIni ) and not ( Table1.eof ) do begin nSalDoc := nSalDoc + Table1IMPORTE.value; Table1.Next; end; lPrim := true; while not Table1.eof do begin Titulo; Imprima( 7, 27, format( '%8.8d', [ Table1NUMERO.value ] )); Imprima( 30, 50, Table1VENCTO.DisplayText ); ImprimaDer( 55, 80, format( '%10.2f', [ Table1IMPORTE.value ] )); ImprimaCen( 82, 92, Table1PESDOL.DisplayText ); ImprimaDer( 95, 115, format( '%6.2f', [ Table1COEFICIENTE.value ] )); ImprimaDer( 122, 147, format( '%10.2f', [ Table1SALDO.value * Table1COEFICIENTE.value ] )); Imprima( 150, 200, Table1FIRMANTE.Value ); nSalDoc := nSalDoc + ( Table1SALDO.value * Table1COEFICIENTE.value ); Table1.Next; end; Titulo; ImprimaDer( 30, 80, 'SALDO a COBRAR'); ImprimaDer( 122, 147, format( '%10.2f', [ nSalDoc ] )); Cerrar; end; end; finally Table1.EnableControls; Impresora.free; end; end; procedure TFCliDoc.Titulo; begin with Impresora do begin if not ( SaltoLinea( 1 )) or ( lPrim ) then begin lPrim := false; Inc( nPag ); ImprimaRaw( 0, DCons.TDatosDENOMINA.value ); ImprimaDer( 160, 200, 'Fecha: ' + DateToStr( date )); SaltoLinea( 1 ); ImprimaDer( 160, 200, 'Página ' + IntToStr( nPag )); SaltoLinea( 1 ); if lCancelados then ImprimaRaw( 50, 'DOCUMENTOS a COBRAR ' ) else begin ImprimaRaw( 50, 'DOCUMENTOS CANCELADOS' ); SaltoLinea( 1 ); ImprimaRaw( 0, 'entre el ' + DateToStr( fechaIni ) + ' y el ' + DateToStr( FechaFin )); end; SaltoLinea( 2 ); ImprimaRaw( 0, 'Cliente : ' + sNombre ); SaltoLinea( 1 ); SaltoLinea( 1 ); Imprima( 7, 27, 'NUMERO' ); Imprima( 30, 50, 'VENCTO.' ); ImprimaDer( 55, 80, 'IMPORTE' ); Imprima( 82, 92, '$/U$S' ); ImprimaDer( 95, 115, 'COEF.' ); ImprimaDer( 122, 147, 'SALDO' ); Imprima( 150, 200, 'FIRMANTE' ); SaltoLinea( 1 ); Imprima( 7, 50, 'SALDO ANTERIOR' ); ImprimaDer( 122, 147, format( '%10.2f', [ nSalDoc ])); SaltoLinea( 1 ); end; end; end; procedure TFCliDoc.AyudaExecute(Sender: TObject); begin Application.HelpCommand( HELP_CONTEXT, 290 ); end; procedure TFCliDoc.FormClose(Sender: TObject; var Action: TCloseAction); begin Application.OnHint := nil; Action := caFree; FCliDoc := nil; end; procedure TFCliDoc.SetCli(sCod, sNom: string; lCancel: boolean; nSaldo: double ); var nSal: double; begin sNombre := sNom; sCodigo := sCod; lCancelados := lCancel; if nSaldo <> 0 then nVieSal := nSaldo; if lCancelados then begin Cancelados.Caption := '&Documentos A Cobrar'; Saldo.Caption := 'SALDO de DOCUMENTOS CANCELADOS'; end else begin Cancelados.Caption := '&Documentos Cancelados'; Saldo.Caption := 'SALDO de DOCUMENTOS a COBRAR del CLIENTE'; end; Table1.DisableControls; if lCancel then begin Caption := 'Documentos Cancelados: ' + sNom; Table1.SetRange( [ 'S', sCod ], [ 'S', sCod ] ); Table1.first; nSal := 0; while not Table1.eof do begin nSal := nSal + ( Table1IMPORTE.value * Table1COEFICIENTE.value ); Table1.next; end; Total.Caption := format( '%12.2m', [ nSal ] ); end else begin Caption := 'Documentos de ' + sNom; Table1.SetRange( [ 'N', sCod ], [ 'N', sCod ] ); Total.Caption := format( '%12.2m', [ nVieSal ] ); end; Table1.EnableControls; end; procedure TFCliDoc.AnalisisExecute(Sender: TObject); begin try Screen.Cursor := crHourGlass; FDetDoc := TFDetDoc.create( self ); FDetDoc.SetFiltro( sCodigo, lEsNegro ); FDetDoc.ShowModal; finally FDetDoc.free; Screen.Cursor := crDefault; end end; procedure TFCliDoc.CanceladosExecute(Sender: TObject); begin lCancelados := not lCancelados; SetCli( sCodigo, sNombre, lCancelados, 0 ); end; procedure TFCliDoc.FormActivate(Sender: TObject); begin Application.OnHint := EnHint; end; procedure TFCliDoc.FormShow(Sender: TObject); begin Screen.Cursor := crDefault; end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2016 * } { *********************************************************** } unit tfUtils; {$I TFL.inc} interface uses tfTypes; const CRC32Table: array[0..255] of UInt32 = ( $00000000, $77073096, $ee0e612c, $990951ba, $076dc419, $706af48f, $e963a535, $9e6495a3, $0edb8832, $79dcb8a4, $e0d5e91e, $97d2d988, $09b64c2b, $7eb17cbd, $e7b82d07, $90bf1d91, $1db71064, $6ab020f2, $f3b97148, $84be41de, $1adad47d, $6ddde4eb, $f4d4b551, $83d385c7, $136c9856, $646ba8c0, $fd62f97a, $8a65c9ec, $14015c4f, $63066cd9, $fa0f3d63, $8d080df5, $3b6e20c8, $4c69105e, $d56041e4, $a2677172, $3c03e4d1, $4b04d447, $d20d85fd, $a50ab56b, $35b5a8fa, $42b2986c, $dbbbc9d6, $acbcf940, $32d86ce3, $45df5c75, $dcd60dcf, $abd13d59, $26d930ac, $51de003a, $c8d75180, $bfd06116, $21b4f4b5, $56b3c423, $cfba9599, $b8bda50f, $2802b89e, $5f058808, $c60cd9b2, $b10be924, $2f6f7c87, $58684c11, $c1611dab, $b6662d3d, $76dc4190, $01db7106, $98d220bc, $efd5102a, $71b18589, $06b6b51f, $9fbfe4a5, $e8b8d433, $7807c9a2, $0f00f934, $9609a88e, $e10e9818, $7f6a0dbb, $086d3d2d, $91646c97, $e6635c01, $6b6b51f4, $1c6c6162, $856530d8, $f262004e, $6c0695ed, $1b01a57b, $8208f4c1, $f50fc457, $65b0d9c6, $12b7e950, $8bbeb8ea, $fcb9887c, $62dd1ddf, $15da2d49, $8cd37cf3, $fbd44c65, $4db26158, $3ab551ce, $a3bc0074, $d4bb30e2, $4adfa541, $3dd895d7, $a4d1c46d, $d3d6f4fb, $4369e96a, $346ed9fc, $ad678846, $da60b8d0, $44042d73, $33031de5, $aa0a4c5f, $dd0d7cc9, $5005713c, $270241aa, $be0b1010, $c90c2086, $5768b525, $206f85b3, $b966d409, $ce61e49f, $5edef90e, $29d9c998, $b0d09822, $c7d7a8b4, $59b33d17, $2eb40d81, $b7bd5c3b, $c0ba6cad, $edb88320, $9abfb3b6, $03b6e20c, $74b1d29a, $ead54739, $9dd277af, $04db2615, $73dc1683, $e3630b12, $94643b84, $0d6d6a3e, $7a6a5aa8, $e40ecf0b, $9309ff9d, $0a00ae27, $7d079eb1, $f00f9344, $8708a3d2, $1e01f268, $6906c2fe, $f762575d, $806567cb, $196c3671, $6e6b06e7, $fed41b76, $89d32be0, $10da7a5a, $67dd4acc, $f9b9df6f, $8ebeeff9, $17b7be43, $60b08ed5, $d6d6a3e8, $a1d1937e, $38d8c2c4, $4fdff252, $d1bb67f1, $a6bc5767, $3fb506dd, $48b2364b, $d80d2bda, $af0a1b4c, $36034af6, $41047a60, $df60efc3, $a867df55, $316e8eef, $4669be79, $cb61b38c, $bc66831a, $256fd2a0, $5268e236, $cc0c7795, $bb0b4703, $220216b9, $5505262f, $c5ba3bbe, $b2bd0b28, $2bb45a92, $5cb36a04, $c2d7ffa7, $b5d0cf31, $2cd99e8b, $5bdeae1d, $9b64c2b0, $ec63f226, $756aa39c, $026d930a, $9c0906a9, $eb0e363f, $72076785, $05005713, $95bf4a82, $e2b87a14, $7bb12bae, $0cb61b38, $92d28e9b, $e5d5be0d, $7cdcefb7, $0bdbdf21, $86d3d2d4, $f1d4e242, $68ddb3f8, $1fda836e, $81be16cd, $f6b9265b, $6fb077e1, $18b74777, $88085ae6, $ff0f6a70, $66063bca, $11010b5c, $8f659eff, $f862ae69, $616bffd3, $166ccf45, $a00ae278, $d70dd2ee, $4e048354, $3903b3c2, $a7672661, $d06016f7, $4969474d, $3e6e77db, $aed16a4a, $d9d65adc, $40df0b66, $37d83bf0, $a9bcae53, $debb9ec5, $47b2cf7f, $30b5ffe9, $bdbdf21c, $cabac28a, $53b39330, $24b4a3a6, $bad03605, $cdd70693, $54de5729, $23d967bf, $b3667a2e, $c4614ab8, $5d681b02, $2a6f2b94, $b40bbe37, $c30c8ea1, $5a05df1b, $2d02ef8d ); type TCRC32 = record class function Init: UInt32; inline; static; class function Update(const Data; DataSize: Cardinal; State: UInt32): UInt32; static; class function Done(State: UInt32): UInt32; inline; static; class function Hash(const Data; DataSize: Cardinal): UInt32; static; end; type TJenkins1 = record class function Init: UInt32; inline; static; class function Update(const Data; DataSize: Cardinal; State: UInt32): UInt32; static; class function Done(State: UInt32): UInt32; inline; static; class function Hash(const Data; DataSize: Cardinal): UInt32; static; end; type TBigEndian = record class function Incr(First, Last: Pointer): Boolean; overload; static; class function Incr(First: Pointer; Count: Cardinal): Boolean; overload; static; class function Incr(First, Last: Pointer; Value: Byte): Boolean; overload; static; class function Incr(First: Pointer; Count: Cardinal; Value: Byte): Boolean; overload; static; class function Decr(First, Last: Pointer): Boolean; overload; static; class function Decr(First: Pointer; Count: Cardinal): Boolean; overload; static; class function Decr(First, Last: Pointer; Value: Byte): Boolean; overload; static; class function Decr(First: Pointer; Count: Cardinal; Value: Byte): Boolean; overload; static; class function Add(A: Pointer; LA: Cardinal; B: Pointer; LB: Cardinal): Boolean; overload; static; class function Sub(A: Pointer; LA: Cardinal; B: Pointer; LB: Cardinal): Boolean; overload; static; class procedure ShiftRight(First, Last: Pointer); overload; static; class procedure ShiftRight(First: Pointer; Count: Cardinal); overload; static; class procedure ShiftRight(First, Last: Pointer; Shift: Cardinal); overload; static; class procedure ShiftRight(First: Pointer; Count, Shift: Cardinal); overload; static; class procedure Reverse(First, Last: Pointer); overload; static; class procedure Reverse(First: Pointer; Count: Cardinal); overload; static; class procedure ReverseCopy(First, Last, Output: Pointer); overload; static; class procedure ReverseCopy(First: Pointer; Count: Cardinal; Output: Pointer); overload; static; end; type TMoveProc = procedure(const Source; var Dest; Count: Cardinal); procedure MoveMem(const Source; var Dest; Count: Cardinal); procedure MoveXor(const Source; var Dest; Count: Cardinal); { type TLittleEndian = record class function Incr(A: Pointer; L: Cardinal): Boolean; overload; static; class function Incr(A: Pointer; L: Cardinal; Value: TLimb): Boolean; overload; static; class function Add(A: Pointer; LA: Cardinal; B: Pointer; LB: Cardinal): Boolean; overload; static; end; } { procedure ReverseCopy(First, Last, Output: Pointer); overload; procedure ReverseCopy(First: Pointer; Count: Cardinal; Output: Pointer); overload; procedure ReverseBytes(First, Last: Pointer); overload; procedure ReverseBytes(First: Pointer; Count: Cardinal); overload; } implementation procedure MoveMem(const Source; var Dest; Count: Cardinal); var S, D: PByte; Cnt1, Cnt2: Cardinal; begin S:= @Source; D:= @Dest; Cnt1:= Count shr 2; Cnt2:= Count and 3; if NativeUInt(D) > NativeUInt(S) then begin if Cnt1 > 0 then begin Inc(PUInt32(S), Cnt1); Inc(PUInt32(D), Cnt1); repeat Dec(PUInt32(S)); Dec(PUInt32(D)); Dec(Cnt1); PUInt32(D)^:= PUInt32(S)^; until Cnt1 = 0; end; while Cnt2 > 0 do begin Dec(S); Dec(D); Dec(Cnt2); D^:= S^; end; end else begin while Cnt1 > 0 do begin PUInt32(D)^:= PUInt32(S)^; Dec(Cnt1); Inc(PUInt32(S)); Inc(PUInt32(D)); end; while Cnt2 > 0 do begin D^:= S^; Dec(Cnt2); Inc(S); Inc(D); end; end; end; procedure MoveXor(const Source; var Dest; Count: Cardinal); var S, D: PByte; Cnt1, Cnt2: Cardinal; begin S:= @Source; D:= @Dest; Cnt1:= Count shr 2; Cnt2:= Count and 3; if NativeUInt(D) > NativeUInt(S) then begin Inc(S, Count); Inc(D, Count); while Cnt2 > 0 do begin Dec(S); Dec(D); Dec(Cnt2); D^:= D^ xor S^; end; while Cnt1 > 0 do begin Dec(PUInt32(S)); Dec(PUInt32(D)); Dec(Cnt1); PUInt32(D)^:= PUInt32(D)^ xor PUInt32(S)^; end; end else begin while Cnt1 > 0 do begin PUInt32(D)^:= PUInt32(D)^ xor PUInt32(S)^; Dec(Cnt1); Inc(PUInt32(S)); Inc(PUInt32(D)); end; while Cnt2 > 0 do begin D^:= D^ xor S^; Dec(Cnt2); Inc(S); Inc(D); end; end; end; { procedure ReverseCopy(First, Last, Output: Pointer); begin while First <> Last do begin Dec(PByte(Last)); PByte(Output)^:= PByte(Last)^; Inc(PByte(Output)); end; end; procedure ReverseCopy(First: Pointer; Count: Cardinal; Output: Pointer); begin ReverseCopy(First, PByte(First) + Count, Output); end; procedure ReverseBytes(First, Last: Pointer); var Tmp: Byte; begin while First <> Last do begin Dec(PByte(Last)); if First = Last then Break; Tmp:= PByte(Last)^; PByte(Last)^:= PByte(First)^; PByte(First)^:= Tmp; Inc(PByte(First)); end; end; procedure ReverseBytes(First: Pointer; Count: Cardinal); begin ReverseBytes(First, PByte(First) + Count); end; } { TCRC32 } class function TCRC32.Init: UInt32; begin Result:= $FFFFFFFF; end; class function TCRC32.Update(const Data; DataSize: Cardinal; State: UInt32): UInt32; var P: PByte; begin P:= @Data; while DataSize > 0 do begin State:= Crc32Table[Byte(State xor P^)] xor UInt32(State shr 8); Dec(DataSize); Inc(P); end; Result:= State; end; class function TCRC32.Done(State: UInt32): UInt32; begin Result:= not State; end; class function TCRC32.Hash(const Data; DataSize: Cardinal): UInt32; var P: PByte; begin P:= @Data; Result:= $FFFFFFFF; while DataSize > 0 do begin Result:= Crc32Table[Byte(Result xor P^)] xor UInt32(Result shr 8); Dec(DataSize); Inc(P); end; Result:= not Result; end; { TJenkinsOne } class function TJenkins1.Init: UInt32; begin Result:= 0; end; class function TJenkins1.Update(const Data; DataSize: Cardinal; State: UInt32): UInt32; var PData: PByte; begin PData:= @Data; while DataSize > 0 do begin State:= State + PData^; State:= State + (State shl 10); State:= State xor (State shr 6); Inc(PData); Dec(DataSize); end; Result:= State; end; class function TJenkins1.Done(State: UInt32): UInt32; begin State:= State + (State shl 3); State:= State xor (State shr 11); State:= State + (State shl 15); Result:= State; end; class function TJenkins1.Hash(const Data; DataSize: Cardinal): UInt32; var PData: PByte; begin Result:= 0; PData:= @Data; while DataSize > 0 do begin Result:= Result + PData^; Result:= Result + (Result shl 10); Result:= Result xor (Result shr 6); Inc(PData); Dec(DataSize); end; Result:= Result + (Result shl 3); Result:= Result xor (Result shr 11); Result:= Result + (Result shl 15); end; (* function JenkinsOneHash(const Data; Len: Cardinal): Integer; var PData: PByte; begin Result:= 0; PData:= @Data; while Len > 0 do begin Result:= Result + PData^; Result:= Result + (Result shl 10); Result:= Result xor (Result shr 6); Inc(PData); Dec(Len); end; Result:= Result + (Result shl 3); Result:= Result xor (Result shr 11); Result:= Result + (Result shl 15); end; *) { TBigEndian } class function TBigEndian.Incr(First, Last: Pointer): Boolean; begin while First <> Last do begin Dec(PByte(Last)); Inc(PByte(Last)^); if PByte(Last)^ <> 0 then begin Result:= False; Exit; end; end; Result:= True; end; class function TBigEndian.Incr(First: Pointer; Count: Cardinal): Boolean; begin Result:= Incr(First, PByte(First) + Count); end; class function TBigEndian.Incr(First, Last: Pointer; Value: Byte): Boolean; var Tmp: Byte; begin while First <> Last do begin Dec(PByte(Last)); Tmp:= PByte(Last)^; PByte(Last)^:= Tmp + Value; if PByte(Last)^ >= Tmp then begin Result:= False; Exit; end; end; Result:= True; end; class function TBigEndian.Incr(First: Pointer; Count: Cardinal; Value: Byte): Boolean; begin Result:= Incr(First, PByte(First) + Count, Value); end; class function TBigEndian.Decr(First, Last: Pointer): Boolean; begin while First <> Last do begin Dec(PByte(Last)); Dec(PByte(Last)^); if PByte(Last)^ <> $FF then begin Result:= False; Exit; end; end; Result:= True; end; class function TBigEndian.Decr(First: Pointer; Count: Cardinal): Boolean; begin Result:= Decr(First, PByte(First) + Count); end; class function TBigEndian.Decr(First, Last: Pointer; Value: Byte): Boolean; var Tmp: Byte; begin while First <> Last do begin Dec(PByte(Last)); Tmp:= PByte(Last)^; PByte(Last)^:= Tmp - Value; if PByte(Last)^ <= Tmp then begin Result:= False; Exit; end; end; Result:= True; end; class function TBigEndian.Decr(First: Pointer; Count: Cardinal; Value: Byte): Boolean; begin Result:= Decr(First, PByte(First) + Count, Value); end; class function TBigEndian.Add(A: Pointer; LA: Cardinal; B: Pointer; LB: Cardinal): Boolean; var CarryOut, CarryIn: Boolean; Tmp: Byte; begin if LB > LA then begin Inc(PByte(B), LB - LA); LB:= LA; end; Inc(PByte(A), LA); Inc(PByte(B), LB); Dec(LA, LB); CarryIn:= False; while LB > 0 do begin Dec(PByte(B)); Dec(PByte(A)); Tmp:= PByte(A)^ + PByte(B)^; CarryOut:= Tmp < PByte(A)^; if CarryIn then begin Inc(Tmp); CarryOut:= CarryOut or (Tmp = 0); end; CarryIn:= CarryOut; PByte(A)^:= Tmp; Dec(LB); end; while (LA > 0) and CarryIn do begin Dec(PByte(A)); Tmp:= PByte(A)^ + 1; CarryIn:= Tmp = 0; PByte(A)^:= Tmp; Dec(LA); end; Result:= CarryIn; end; class function TBigEndian.Sub(A: Pointer; LA: Cardinal; B: Pointer; LB: Cardinal): Boolean; var BorrowOut, BorrowIn: Boolean; Tmp: Byte; begin if LB > LA then begin Inc(PByte(B), LB - LA); LB:= LA; end; Inc(PByte(A), LA); Inc(PByte(B), LB); Dec(LA, LB); BorrowIn:= False; while LB > 0 do begin Dec(PByte(B)); Dec(PByte(A)); Tmp:= PByte(A)^ - PByte(B)^; BorrowOut:= Tmp > PByte(A)^; if BorrowIn then begin BorrowOut:= BorrowOut or (Tmp = 0); Dec(Tmp); end; BorrowIn:= BorrowOut; PByte(A)^:= Tmp; Dec(LB); end; while (LA > 0) and BorrowIn do begin Dec(PByte(A)); Tmp:= PByte(A)^; BorrowIn:= Tmp = 0; PByte(A)^:= Tmp - 1; Dec(LA); end; Result:= BorrowIn; end; class procedure TBigEndian.Reverse(First, Last: Pointer); var Tmp: Byte; begin while First <> Last do begin Dec(PByte(Last)); if First = Last then Break; Tmp:= PByte(Last)^; PByte(Last)^:= PByte(First)^; PByte(First)^:= Tmp; Inc(PByte(First)); end; end; class procedure TBigEndian.Reverse(First: Pointer; Count: Cardinal); begin Reverse(First, PByte(First) + Count); end; class procedure TBigEndian.ReverseCopy(First, Last, Output: Pointer); begin while First <> Last do begin Dec(PByte(Last)); PByte(Output)^:= PByte(Last)^; Inc(PByte(Output)); end; end; class procedure TBigEndian.ReverseCopy(First: Pointer; Count: Cardinal; Output: Pointer); begin ReverseCopy(First, PByte(First) + Count, Output); end; class procedure TBigEndian.ShiftRight(First, Last: Pointer); var Carry, Tmp: Byte; begin if First <> Last then begin Carry:= PByte(First)^; PByte(First)^:= Carry shr 1; Carry:= Carry shl 7; Dec(PByte(Last)); while First <> Last do begin Inc(PByte(First)); Tmp:= PByte(First)^; PByte(First)^:= (Tmp shr 1) or Carry; Carry:= Tmp shl 7; end; end; end; class procedure TBigEndian.ShiftRight(First: Pointer; Count: Cardinal); begin ShiftRight(First, PByte(First) + Count); end; class procedure TBigEndian.ShiftRight(First, Last: Pointer; Shift: Cardinal); begin // todo: while Shift > 0 do begin ShiftRight(First, Last); Dec(Shift); end; end; class procedure TBigEndian.ShiftRight(First: Pointer; Count, Shift: Cardinal); begin // todo: while Shift > 0 do begin ShiftRight(First, PByte(First) + Count); Dec(Shift); end; end; { TLittleEndian class function TLittleEndian.Incr(A: Pointer; L: Cardinal): Boolean; var Tmp: TLimb; begin // !! Assert(Count > 0); Tmp:= PLimb(A)^ + 1; PLimb(A)^:= Tmp; // while we have carry from prev limb .. while (Tmp = 0) do begin Dec(L); Inc(PLimb(A)); if L = 0 then begin Result:= True; Exit; end; Tmp:= PLimb(A)^ + 1; PLimb(A)^:= Tmp; end; Result:= False; end; class function TLittleEndian.Add(A: Pointer; LA: Cardinal; B: Pointer; LB: Cardinal): Boolean; var CarryOut, CarryIn: Boolean; Tmp: TLimb; begin if LB > LA then LB:= LA; Dec(LA, LB); CarryIn:= False; while LB > 0 do begin Tmp:= PLimb(A)^ + PLimb(B)^; CarryOut:= Tmp < PLimb(A)^; Inc(PLimb(B)); if CarryIn then begin Inc(Tmp); CarryOut:= CarryOut or (Tmp = 0); end; CarryIn:= CarryOut; PLimb(A)^:= Tmp; Inc(PLimb(A)); Dec(LB); end; while (LA > 0) and CarryIn do begin Tmp:= PLimb(A)^ + 1; CarryIn:= Tmp = 0; PLimb(A)^:= Tmp; Inc(PLimb(A)); Dec(LA); end; Result:= CarryIn; end; class function TLittleEndian.Incr(A: Pointer; L: Cardinal; Value: TLimb): Boolean; var Tmp: TLimb; begin Tmp:= PLimb(A)^ + Value; PLimb(A)^:= Tmp; if Tmp < Value then repeat Dec(L); Inc(PLimb(A)); if L = 0 then begin Result:= True; Exit; end; Tmp:= PLimb(A)^ + 1; PLimb(A)^:= Tmp; until Tmp <> 0; Result:= False; end; } end.
unit MultipleDepotMultipleDriverTimeWindowTestDataProviderUnit; interface uses SysUtils, BaseOptimizationParametersProviderUnit, AddressUnit, RouteParametersUnit, OptimizationParametersUnit; type TMultipleDepotMultipleDriverTimeWindowTestDataProvider = class(TBaseOptimizationParametersProvider) protected function MakeAddresses(): TArray<TAddress>; override; function MakeRouteParameters(): TRouteParameters; override; /// <summary> /// After response some fields are changed from request. /// </summary> procedure CorrectForResponse(OptimizationParameters: TOptimizationParameters); override; public end; implementation { TMultipleDepotMultipleDriverTimeWindowTestDataProvider } uses DateUtils, EnumsUnit, UtilsUnit; procedure TMultipleDepotMultipleDriverTimeWindowTestDataProvider.CorrectForResponse( OptimizationParameters: TOptimizationParameters); begin inherited; end; function TMultipleDepotMultipleDriverTimeWindowTestDataProvider.MakeAddresses: TArray<TAddress>; var FirstAddress: TAddress; begin Result := TArray<TAddress>.Create(); FirstAddress := TAddress.Create( '455 S 4th St, Louisville, KY 40202', 38.251698, -85.757308, 300); //indicate that this is a departure stop // single depot routes can only have one departure depot FirstAddress.IsDepot := True; //together these two specify the time window of a destination //seconds offset relative to the route start time for the open availability of a destination FirstAddress.TimeWindowStart := 28800; //seconds offset relative to the route end time for the open availability of a destination FirstAddress.TimeWindowEnd := 30477; AddAddress(FirstAddress, Result); AddAddress(TAddress.Create('1604 PARKRIDGE PKWY, Louisville, KY, 40214', 38.141598, -85.793846, 300, 30477, 33406), Result); AddAddress(TAddress.Create('1407 53MCCOY, Louisville, KY, 40215', 38.202496, -85.786514, 300, 33406, 36228), Result); AddAddress(TAddress.Create('4805 BELLEVUE AVE, Louisville, KY, 40215', 38.178844, -85.774864, 300, 36228, 37518), Result); AddAddress(TAddress.Create('730 CECIL AVENUE, Louisville, KY, 40211', 38.248684, -85.821121, 300, 37518, 39550), Result); AddAddress(TAddress.Create('650 SOUTH 29TH ST UNIT 315, Louisville, KY, 40211', 38.251923, -85.800034, 300, 39550, 41348), Result); AddAddress(TAddress.Create('4629 HILLSIDE DRIVE, Louisville, KY, 40216', 38.176067, -85.824638, 300, 41348, 42261), Result); AddAddress(TAddress.Create('4738 BELLEVUE AVE, Louisville, KY, 40215', 38.179806, -85.775558, 300, 42261, 45195), Result); AddAddress(TAddress.Create('318 SO. 39TH STREET, Louisville, KY, 40212', 38.259335, -85.815094, 300, 45195, 46549), Result); AddAddress(TAddress.Create('1324 BLUEGRASS AVE, Louisville, KY, 40215', 38.179253, -85.785118, 300, 46549, 47353), Result); AddAddress(TAddress.Create('7305 ROYAL WOODS DR, Louisville, KY, 40214', 38.162472, -85.792854, 300, 47353, 50924), Result); AddAddress(TAddress.Create('1661 W HILL ST, Louisville, KY, 40210', 38.229584, -85.783966, 300, 50924, 51392), Result); AddAddress(TAddress.Create('3222 KINGSWOOD WAY, Louisville, KY, 40216', 38.210606, -85.822594, 300, 51392, 52451), Result); AddAddress(TAddress.Create('1922 PALATKA RD, Louisville, KY, 40214', 38.153767, -85.796783, 300, 52451, 55631), Result); AddAddress(TAddress.Create('1314 SOUTH 26TH STREET, Louisville, KY, 40210', 38.235847, -85.796852, 300, 55631, 58516), Result); AddAddress(TAddress.Create('2135 MCCLOSKEY AVENUE, Louisville, KY, 40210', 38.218662, -85.789032, 300, 58516, 61080), Result); AddAddress(TAddress.Create('1409 PHYLLIS AVE, Louisville, KY, 40215', 38.206154, -85.781387, 100, 61080, 61504), Result); AddAddress(TAddress.Create('4504 SUNFLOWER AVE, Louisville, KY, 40216', 38.187511, -85.839149, 300, 61504, 62061), Result); AddAddress(TAddress.Create('2512 GREENWOOD AVE, Louisville, KY, 40210', 38.241405, -85.795059, 300, 62061, 65012), Result); AddAddress(TAddress.Create('5500 WILKE FARM AVE, Louisville, KY, 40216', 38.166065, -85.863319, 300, 65012, 67541), Result); AddAddress(TAddress.Create('3640 LENTZ AVE, Louisville, KY, 40215', 38.193283, -85.786201, 300, 67541, 69120), Result); AddAddress(TAddress.Create('1020 BLUEGRASS AVE, Louisville, KY, 40215', 38.17952, -85.780037, 300, 69120, 70572), Result); AddAddress(TAddress.Create('123 NORTH 40TH ST, Louisville, KY, 40212', 38.26498, -85.814156, 300, 70572, 73177), Result); AddAddress(TAddress.Create('7315 ST ANDREWS WOODS CIRCLE UNIT 104, Louisville, KY, 40214', 38.151072, -85.802867, 300, 73177, 75231), Result); AddAddress(TAddress.Create('3210 POPLAR VIEW DR, Louisville, KY, 40216', 38.182594, -85.849937, 300, 75231, 77663), Result); AddAddress(TAddress.Create('4519 LOUANE WAY, Louisville, KY, 40216', 38.1754, -85.811447, 300, 77663, 79796), Result); AddAddress(TAddress.Create('6812 MANSLICK RD, Louisville, KY, 40214', 38.161839, -85.798279, 300, 79796, 80813), Result); AddAddress(TAddress.Create('1524 HUNTOON AVENUE, Louisville, KY, 40215', 38.172031, -85.788353, 300, 80813, 83956), Result); AddAddress(TAddress.Create('1307 LARCHMONT AVE, Louisville, KY, 40215', 38.209663, -85.779816, 300, 83956, 84365), Result); AddAddress(TAddress.Create('434 N 26TH STREET #2, Louisville, KY, 40212', 38.26844, -85.791962, 300, 84365, 85367), Result); AddAddress(TAddress.Create('678 WESTLAWN ST, Louisville, KY, 40211', 38.250397, -85.80629, 300, 85367, 86400), Result); AddAddress(TAddress.Create('2308 W BROADWAY, Louisville, KY, 40211', 38.248882, -85.790421, 300, 86400, 88703), Result); AddAddress(TAddress.Create('2332 WOODLAND AVE, Louisville, KY, 40210', 38.233579, -85.794257, 300, 88703, 89320), Result); AddAddress(TAddress.Create('1706 WEST ST. CATHERINE, Louisville, KY, 40210', 38.239697, -85.783928, 300, 89320, 90054), Result); AddAddress(TAddress.Create('1699 WATHEN LN, Louisville, KY, 40216', 38.216465, -85.792397, 300, 90054, 91150), Result); AddAddress(TAddress.Create('2416 SUNSHINE WAY, Louisville, KY, 40216', 38.186245, -85.831787, 300, 91150, 91915), Result); AddAddress(TAddress.Create('6925 MANSLICK RD, Louisville, KY, 40214', 38.158466, -85.798355, 300, 91915, 93407), Result); AddAddress(TAddress.Create('2707 7TH ST, Louisville, KY, 40215', 38.212438, -85.785082, 300, 93407, 95992), Result); AddAddress(TAddress.Create('2014 KENDALL LN, Louisville, KY, 40216', 38.179394, -85.826668, 300, 95992, 99307), Result); AddAddress(TAddress.Create('612 N 39TH ST, Louisville, KY, 40212', 38.273354, -85.812012, 300, 99307, 102906), Result); AddAddress(TAddress.Create('2215 ROWAN ST, Louisville, KY, 40212', 38.261703, -85.786781, 300, 102906, 106021), Result); AddAddress(TAddress.Create('1826 W. KENTUCKY ST, Louisville, KY, 40210', 38.241611, -85.78653, 300, 106021, 107276), Result); AddAddress(TAddress.Create('1810 GREGG AVE, Louisville, KY, 40210', 38.224716, -85.796211, 300, 107276, 107948), Result); AddAddress(TAddress.Create('4103 BURRRELL DRIVE, Louisville, KY, 40216', 38.191753, -85.825836, 300, 107948, 108414), Result); AddAddress(TAddress.Create('359 SOUTHWESTERN PKWY, Louisville, KY, 40212', 38.259903, -85.823463, 200, 108414, 108685), Result); AddAddress(TAddress.Create('2407 W CHESTNUT ST, Louisville, KY, 40211', 38.252781, -85.792109, 300, 108685, 110109), Result); AddAddress(TAddress.Create('225 S 22ND ST, Louisville, KY, 40212', 38.257616, -85.786658, 300, 110109, 111375), Result); AddAddress(TAddress.Create('1404 MCCOY AVE, Louisville, KY, 40215', 38.202122, -85.786072, 300, 111375, 112120), Result); AddAddress(TAddress.Create('117 FOUNT LANDING CT, Louisville, KY, 40212', 38.270061, -85.799438, 300, 112120, 114095), Result); AddAddress(TAddress.Create('5504 SHOREWOOD DRIVE, Louisville, KY, 40214', 38.145851, -85.7798, 300, 114095, 115743), Result); AddAddress(TAddress.Create('1406 CENTRAL AVE, Louisville, KY, 40208', 38.211025, -85.780251, 300, 115743, 117716), Result); AddAddress(TAddress.Create('901 W WHITNEY AVE, Louisville, KY, 40215', 38.194115, -85.77494, 300, 117716, 119078), Result); AddAddress(TAddress.Create('2109 SCHAFFNER AVE, Louisville, KY, 40210', 38.219699, -85.779363, 300, 119078, 121147), Result); AddAddress(TAddress.Create('2906 DIXIE HWY, Louisville, KY, 40216', 38.209278, -85.798653, 300, 121147, 124281), Result); AddAddress(TAddress.Create('814 WWHITNEY AVE, Louisville, KY, 40215', 38.193596, -85.773521, 300, 124281, 124675), Result); AddAddress(TAddress.Create('1610 ALGONQUIN PWKY, Louisville, KY, 40210', 38.222153, -85.784187, 300, 124675, 127148), Result); AddAddress(TAddress.Create('3524 WHEELER AVE, Louisville, KY, 40215', 38.195293, -85.788643, 300, 127148, 130667), Result); AddAddress(TAddress.Create('5009 NEW CUT RD, Louisville, KY, 40214', 38.165905, -85.779701, 300, 130667, 131980), Result); AddAddress(TAddress.Create('3122 ELLIOTT AVE, Louisville, KY, 40211', 38.251213, -85.804199, 300, 131980, 134402), Result); AddAddress(TAddress.Create('911 GAGEL AVE, Louisville, KY, 40216', 38.173512, -85.807854, 300, 134402, 136787), Result); AddAddress(TAddress.Create('4020 GARLAND AVE #lOOA, Louisville, KY, 40211', 38.246181, -85.818901, 300, 136787, 138073), Result); AddAddress(TAddress.Create('5231 MT HOLYOKE DR, Louisville, KY, 40216', 38.169369, -85.85704, 300, 138073, 141407), Result); AddAddress(TAddress.Create('1339 28TH S #2, Louisville, KY, 40211', 38.235275, -85.800156, 300, 141407, 143561), Result); AddAddress(TAddress.Create('836 S 36TH ST, Louisville, KY, 40211', 38.24651, -85.811234, 300, 143561, 145941), Result); AddAddress(TAddress.Create('2132 DUNCAN STREET, Louisville, KY, 40212', 38.262135, -85.785172, 300, 145941, 148296), Result); AddAddress(TAddress.Create('3529 WHEELER AVE, Louisville, KY, 40215', 38.195057, -85.787949, 300, 148296, 150177), Result); AddAddress(TAddress.Create('2829 DE MEL #11, Louisville, KY, 40214', 38.171662, -85.807271, 300, 150177, 150981), Result); AddAddress(TAddress.Create('1325 EARL AVENUE, Louisville, KY, 40215', 38.204556, -85.781555, 300, 150981, 151854), Result); AddAddress(TAddress.Create('3632 MANSLICK RD #10, Louisville, KY, 40215', 38.193542, -85.801147, 300, 151854, 152613), Result); AddAddress(TAddress.Create('637 S 41ST ST, Louisville, KY, 40211', 38.253632, -85.81897, 300, 152613, 156131), Result); AddAddress(TAddress.Create('3420 VIRGINIA AVENUE, Louisville, KY, 40211', 38.238693, -85.811386, 300, 156131, 157212), Result); AddAddress(TAddress.Create('3501 MALIBU CT APT 6, Louisville, KY, 40216', 38.166481, -85.825928, 300, 157212, 158655), Result); AddAddress(TAddress.Create('4912 DIXIE HWY, Louisville, KY, 40216', 38.170728, -85.826817, 300, 158655, 159145), Result); AddAddress(TAddress.Create('7720 DINGLEDELL RD, Louisville, KY, 40214', 38.162472, -85.792854, 300, 159145, 161831), Result); AddAddress(TAddress.Create('2123 RATCLIFFE AVE, Louisville, KY, 40210', 38.21978, -85.797615, 300, 161831, 163705), Result); AddAddress(TAddress.Create('1321 OAKWOOD AVE, Louisville, KY, 40215', 38.17704, -85.783829, 300, 163705, 164953), Result); AddAddress(TAddress.Create('2223 WEST KENTUCKY STREET, Louisville, KY, 40210', 38.242516, -85.790695, 300, 164953, 166189), Result); AddAddress(TAddress.Create('8025 GLIMMER WAY #3308, Louisville, KY, 40214', 38.131981, -85.77935, 300, 166189, 166640), Result); AddAddress(TAddress.Create('1155 S 28TH ST, Louisville, KY, 40211', 38.238621, -85.799911, 300, 166640, 168147), Result); AddAddress(TAddress.Create('840 IROQUOIS AVE, Louisville, KY, 40214', 38.166355, -85.779396, 300, 168147, 170385), Result); AddAddress(TAddress.Create('5573 BRUCE AVE, Louisville, KY, 40214', 38.145222, -85.779205, 300, 170385, 171096), Result); AddAddress(TAddress.Create('1727 GALLAGHER, Louisville, KY, 40210', 38.239334, -85.784882, 300, 171096, 171951), Result); AddAddress(TAddress.Create('1309 CATALPA ST APT 204, Louisville, KY, 40211', 38.236524, -85.801619, 300, 171951, 172393), Result); AddAddress(TAddress.Create('1330 ALGONQUIN PKWY, Louisville, KY, 40208', 38.219846, -85.777344, 300, 172393, 175337), Result); AddAddress(TAddress.Create('823 SUTCLIFFE, Louisville, KY, 40211', 38.246956, -85.811569, 300, 175337, 176867), Result); AddAddress(TAddress.Create('4405 CHURCHMAN AVENUE #2, Louisville, KY, 40215', 38.177768, -85.792545, 300, 176867, 178051), Result); AddAddress(TAddress.Create('3211 DUMESNIL ST #1, Louisville, KY, 40211', 38.237789, -85.807968, 300, 178051, 179083), Result); AddAddress(TAddress.Create('3904 WEWOKA AVE, Louisville, KY, 40212', 38.270367, -85.813118, 300, 179083, 181543), Result); AddAddress(TAddress.Create('660 SO. 42ND STREET, Louisville, KY, 40211', 38.252865, -85.822624, 300, 181543, 184193), Result); AddAddress(TAddress.Create('3619 LENTZ AVE, Louisville, KY, 40215', 38.193249, -85.785492, 300, 184193, 185853), Result); AddAddress(TAddress.Create('4305 STOLTZ CT, Louisville, KY, 40215', 38.178707, -85.787292, 300, 185853, 187252), Result); end; function TMultipleDepotMultipleDriverTimeWindowTestDataProvider.MakeRouteParameters: TRouteParameters; begin Result := TRouteParameters.Create(); // specify capacitated vehicle routing with time windows and multiple depots, with multiple drivers Result.AlgorithmType := TAlgorithmType.CVRP_TW_MD; Result.StoreRoute := False; // set an arbitrary route name // this value shows up in the website, and all the connected mobile device Result.RouteName := 'Multiple Depot, Multiple Driver, Time Window'; // the route start date in UTC, unix timestamp seconds (Tomorrow) Result.RouteDate := 53583232; //TUtils.ConvertToUnixTimestamp(IncDay(Now, 1)); // the time in UTC when a route is starting (7AM) Result.RouteTime := 60 * 60 * 7; // the maximum duration of a route Result.RouteMaxDuration := 86400 * 3; Result.RT := True; Result.VehicleCapacity := '99'; Result.VehicleMaxDistanceMI := '99999'; Result.Optimize := TOptimize.Time; Result.DistanceUnit := TDistanceUnit.MI; Result.DeviceType := TDeviceType.Web; Result.TravelMode := TTravelMode.Driving; Result.Metric := TMetric.Geodesic; end; end.
(*==========================================================================; * * Copyright (C) 1995-1998 Microsoft Corporation. All Rights Reserved. * * Files: d3dtypes.h d3dcaps.h d3d.h * * DirectX 7.0 Delphi adaptation by Erik Unger * * Modyfied: 19-Feb-2000 * * Download: http://www.delphi-jedi.org/DelphiGraphics/ * E-Mail: Erik.Unger@gmx.at * ***************************************************************************) unit Direct3D; {$MINENUMSIZE 4} {$ALIGN ON} interface uses Windows, DirectDraw; (* TD3DValue is the fundamental Direct3D fractional data type *) type TRefClsID = TGUID; type TD3DValue = Single; TD3DFixed = LongInt; float = TD3DValue; PD3DColor = ^TD3DColor; TD3DColor = DWORD; function D3DVal(val: variant) : float; function D3DDivide(a,b: double) : float; function D3DMultiply(a,b: double) : float; (* * Format of CI colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | alpha | color index | fraction | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ *) // #define CI_GETALPHA(ci) ((ci) >> 24) function CI_GETALPHA(ci: DWORD) : DWORD; // #define CI_GETINDEX(ci) (((ci) >> 8) & 0xffff) function CI_GETINDEX(ci: DWORD) : DWORD; // #define CI_GETFRACTION(ci) ((ci) & 0xff) function CI_GETFRACTION(ci: DWORD) : DWORD; // #define CI_ROUNDINDEX(ci) CI_GETINDEX((ci) + 0x80) function CI_ROUNDINDEX(ci: DWORD) : DWORD; // #define CI_MASKALPHA(ci) ((ci) & 0xffffff) function CI_MASKALPHA(ci: DWORD) : DWORD; // #define CI_MAKE(a, i, f) (((a) << 24) | ((i) << 8) | (f)) function CI_MAKE(a,i,f: DWORD) : DWORD; (* * Format of RGBA colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | alpha | red | green | blue | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ *) // #define RGBA_GETALPHA(rgb) ((rgb) >> 24) function RGBA_GETALPHA(rgb: TD3DColor) : DWORD; // #define RGBA_GETRED(rgb) (((rgb) >> 16) & 0xff) function RGBA_GETRED(rgb: TD3DColor) : DWORD; // #define RGBA_GETGREEN(rgb) (((rgb) >> 8) & 0xff) function RGBA_GETGREEN(rgb: TD3DColor) : DWORD; // #define RGBA_GETBLUE(rgb) ((rgb) & 0xff) function RGBA_GETBLUE(rgb: TD3DColor) : DWORD; // #define RGBA_MAKE(r, g, b, a) ((TD3DColor) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))) function RGBA_MAKE(r, g, b, a: DWORD) : TD3DColor; (* D3DRGB and D3DRGBA may be used as initialisers for D3DCOLORs * The float values must be in the range 0..1 *) // #define D3DRGB(r, g, b) \ // (0xff000000L | (((long)((r) * 255)) << 16) | (((long)((g) * 255)) << 8) | (long)((b) * 255)) function D3DRGB(r, g, b: float) : TD3DColor; // #define D3DRGBA(r, g, b, a) \ // ( (((long)((a) * 255)) << 24) | (((long)((r) * 255)) << 16) \ // | (((long)((g) * 255)) << 8) | (long)((b) * 255) \ // ) function D3DRGBA(r, g, b, a: float) : TD3DColor; (* * Format of RGB colors is * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | ignored | red | green | blue | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ *) // #define RGB_GETRED(rgb) (((rgb) >> 16) & 0xff) function RGB_GETRED(rgb: TD3DColor) : DWORD; // #define RGB_GETGREEN(rgb) (((rgb) >> 8) & 0xff) function RGB_GETGREEN(rgb: TD3DColor) : DWORD; // #define RGB_GETBLUE(rgb) ((rgb) & 0xff) function RGB_GETBLUE(rgb: TD3DColor) : DWORD; // #define RGBA_SETALPHA(rgba, x) (((x) << 24) | ((rgba) & 0x00ffffff)) function RGBA_SETALPHA(rgba: TD3DColor; x: DWORD) : TD3DColor; // #define RGB_MAKE(r, g, b) ((TD3DColor) (((r) << 16) | ((g) << 8) | (b))) function RGB_MAKE(r, g, b: DWORD) : TD3DColor; // #define RGBA_TORGB(rgba) ((TD3DColor) ((rgba) & 0xffffff)) function RGBA_TORGB(rgba: TD3DColor) : TD3DColor; // #define RGB_TORGBA(rgb) ((TD3DColor) ((rgb) | 0xff000000)) function RGB_TORGBA(rgb: TD3DColor) : TD3DColor; (* * Flags for Enumerate functions *) const (* * Stop the enumeration *) D3DENUMRET_CANCEL = DDENUMRET_CANCEL; (* * Continue the enumeration *) D3DENUMRET_OK = DDENUMRET_OK; type TD3DValidateCallback = function (lpUserArg: Pointer; dwOffset: DWORD): HResult; stdcall; TD3DEnumTextureFormatsCallback = function (var lpDdsd: TDDSurfaceDesc; lpContext: Pointer): HResult; stdcall; TD3DEnumPixelFormatsCallback = function (var lpDDPixFmt: TDDPixelFormat; lpContext: Pointer): HResult; stdcall; PD3DMaterialHandle = ^TD3DMaterialHandle; TD3DMaterialHandle = DWORD; PD3DTextureHandle = ^TD3DTextureHandle; TD3DTextureHandle = DWORD; PD3DMatrixHandle = ^TD3DMatrixHandle; TD3DMatrixHandle = DWORD; PD3DColorValue = ^TD3DColorValue; TD3DColorValue = packed record case Integer of 0: ( r: TD3DValue; g: TD3DValue; b: TD3DValue; a: TD3DValue; ); 1: ( dvR: TD3DValue; dvG: TD3DValue; dvB: TD3DValue; dvA: TD3DValue; ); end; PD3DRect = ^TD3DRect; TD3DRect = packed record case Integer of 0: ( x1: LongInt; y1: LongInt; x2: LongInt; y2: LongInt; ); 1: ( lX1: LongInt; lY1: LongInt; lX2: LongInt; lY2: LongInt; ); 2: ( a: array[0..3] of LongInt; ); end; PD3DVector = ^TD3DVector; TD3DVector = packed record case Integer of 0: ( x: TD3DValue; y: TD3DValue; z: TD3DValue; ); 1: ( dvX: TD3DValue; dvY: TD3DValue; dvZ: TD3DValue; ); end; (****************************************************************** * * * D3DVec.inl * * * * Float-valued 3D vector class for Direct3D. * * * * Copyright (c) 1996-1998 Microsoft Corp. All rights reserved. * * * ******************************************************************) // Addition and subtraction function VectorAdd(const v1, v2: TD3DVector) : TD3DVector; function VectorSub(const v1, v2: TD3DVector) : TD3DVector; // Scalar multiplication and division function VectorMulS(const v: TD3DVector; s: TD3DValue) : TD3DVector; function VectorDivS(const v: TD3DVector; s: TD3DValue) : TD3DVector; // Memberwise multiplication and division function VectorMul(const v1, v2: TD3DVector) : TD3DVector; function VectorDiv(const v1, v2: TD3DVector) : TD3DVector; // Vector dominance function VectorSmaller(v1, v2: TD3DVector) : boolean; function VectorSmallerEquel(v1, v2: TD3DVector) : boolean; // Bitwise equality function VectorEquel(v1, v2: TD3DVector) : boolean; // Length-related functions function VectorSquareMagnitude(v: TD3DVector) : TD3DValue; function VectorMagnitude(v: TD3DVector) : TD3DValue; // Returns vector with same direction and unit length function VectorNormalize(const v: TD3DVector) : TD3DVector; // Return min/max component of the input vector function VectorMin(v: TD3DVector) : TD3DValue; function VectorMax(v: TD3DVector) : TD3DValue; // Return memberwise min/max of input vectors function VectorMinimize(const v1, v2: TD3DVector) : TD3DVector; function VectorMaximize(const v1, v2: TD3DVector) : TD3DVector; // Dot and cross product function VectorDotProduct(v1, v2: TD3DVector) : TD3DValue; function VectorCrossProduct(const v1, v2: TD3DVector) : TD3DVector; type (* * Vertex data types supported in an ExecuteBuffer. *) (* * Homogeneous vertices *) PD3DHVertex = ^TD3DHVertex; TD3DHVertex = packed record dwFlags: DWORD; (* Homogeneous clipping flags *) case Integer of 0: ( hx: TD3DValue; hy: TD3DValue; hz: TD3DValue; ); 1: ( dvHX: TD3DValue; dvHY: TD3DValue; dvHZ: TD3DValue; ); end; (* * Transformed/lit vertices *) PD3DTLVertex = ^TD3DTLVertex; TD3DTLVertex = packed record case Integer of 0: ( sx: TD3DValue; (* Screen coordinates *) sy: TD3DValue; sz: TD3DValue; rhw: TD3DValue; (* Reciprocal of homogeneous w *) color: TD3DColor; (* Vertex color *) specular: TD3DColor; (* Specular component of vertex *) tu: TD3DValue; (* Texture coordinates *) tv: TD3DValue; ); 1: ( dvSX: TD3DValue; dvSY: TD3DValue; dvSZ: TD3DValue; dvRHW: TD3DValue; dcColor: TD3DColor; dcSpecular: TD3DColor; dvTU: TD3DValue; dvTV: TD3DValue; ); end; (* * Untransformed/lit vertices *) PD3DLVertex = ^TD3DLVertex; TD3DLVertex = packed record case Integer of 0: ( x: TD3DValue; (* Homogeneous coordinates *) y: TD3DValue; z: TD3DValue; dwReserved: DWORD; color: TD3DColor; (* Vertex color *) specular: TD3DColor; (* Specular component of vertex *) tu: TD3DValue; (* Texture coordinates *) tv: TD3DValue; ); 1: ( dvX: TD3DValue; dvY: TD3DValue; dvZ: TD3DValue; UNIONFILLER1d: DWORD; dcColor: TD3DColor; dcSpecular: TD3DColor; dvTU: TD3DValue; dvTV: TD3DValue; ); end; (* * Untransformed/unlit vertices *) PD3DVertex = ^TD3DVertex; TD3DVertex = packed record case Integer of 0: ( x: TD3DValue; (* Homogeneous coordinates *) y: TD3DValue; z: TD3DValue; nx: TD3DValue; (* Normal *) ny: TD3DValue; nz: TD3DValue; tu: TD3DValue; (* Texture coordinates *) tv: TD3DValue; ); 1: ( dvX: TD3DValue; dvY: TD3DValue; dvZ: TD3DValue; dvNX: TD3DValue; dvNY: TD3DValue; dvNZ: TD3DValue; dvTU: TD3DValue; dvTV: TD3DValue; ); end; (* * Matrix, viewport, and tranformation structures and definitions. *) PD3DMatrix = ^TD3DMatrix; TD3DMatrix = packed record case integer of 0 : (_11, _12, _13, _14: TD3DValue; _21, _22, _23, _24: TD3DValue; _31, _32, _33, _34: TD3DValue; _41, _42, _43, _44: TD3DValue); 1 : (m : array [0..3, 0..3] of TD3DValue); end; PD3DViewport = ^TD3DViewport; TD3DViewport = packed record dwSize: DWORD; dwX: DWORD; dwY: DWORD; (* Top left *) dwWidth: DWORD; dwHeight: DWORD; (* Dimensions *) dvScaleX: TD3DValue; (* Scale homogeneous to screen *) dvScaleY: TD3DValue; (* Scale homogeneous to screen *) dvMaxX: TD3DValue; (* Min/max homogeneous x coord *) dvMaxY: TD3DValue; (* Min/max homogeneous y coord *) dvMinZ: TD3DValue; dvMaxZ: TD3DValue; (* Min/max homogeneous z coord *) end; PD3DViewport2 = ^TD3DViewport2; TD3DViewport2 = packed record dwSize: DWORD; dwX: DWORD; dwY: DWORD; (* Viewport Top left *) dwWidth: DWORD; dwHeight: DWORD; (* Viewport Dimensions *) dvClipX: TD3DValue; (* Top left of clip volume *) dvClipY: TD3DValue; dvClipWidth: TD3DValue; (* Clip Volume Dimensions *) dvClipHeight: TD3DValue; dvMinZ: TD3DValue; (* Min/max of clip Volume *) dvMaxZ: TD3DValue; end; PD3DViewport7 = ^TD3DViewport7; TD3DViewport7 = packed record dwX: DWORD; dwY: DWORD; (* Viewport Top left *) dwWidth: DWORD; dwHeight: DWORD; (* Viewport Dimensions *) dvMinZ: TD3DValue; (* Min/max of clip Volume *) dvMaxZ: TD3DValue; end; (* * Values for clip fields. *) const // Max number of user clipping planes, supported in D3D. D3DMAXUSERCLIPPLANES = 32; // These bits could be ORed together to use with D3DRENDERSTATE_CLIPPLANEENABLE // D3DCLIPPLANE0 = (1 shl 0); D3DCLIPPLANE1 = (1 shl 1); D3DCLIPPLANE2 = (1 shl 2); D3DCLIPPLANE3 = (1 shl 3); D3DCLIPPLANE4 = (1 shl 4); D3DCLIPPLANE5 = (1 shl 5); const D3DCLIP_LEFT = $00000001; D3DCLIP_RIGHT = $00000002; D3DCLIP_TOP = $00000004; D3DCLIP_BOTTOM = $00000008; D3DCLIP_FRONT = $00000010; D3DCLIP_BACK = $00000020; D3DCLIP_GEN0 = $00000040; D3DCLIP_GEN1 = $00000080; D3DCLIP_GEN2 = $00000100; D3DCLIP_GEN3 = $00000200; D3DCLIP_GEN4 = $00000400; D3DCLIP_GEN5 = $00000800; (* * Values for d3d status. *) D3DSTATUS_CLIPUNIONLEFT = D3DCLIP_LEFT; D3DSTATUS_CLIPUNIONRIGHT = D3DCLIP_RIGHT; D3DSTATUS_CLIPUNIONTOP = D3DCLIP_TOP; D3DSTATUS_CLIPUNIONBOTTOM = D3DCLIP_BOTTOM; D3DSTATUS_CLIPUNIONFRONT = D3DCLIP_FRONT; D3DSTATUS_CLIPUNIONBACK = D3DCLIP_BACK; D3DSTATUS_CLIPUNIONGEN0 = D3DCLIP_GEN0; D3DSTATUS_CLIPUNIONGEN1 = D3DCLIP_GEN1; D3DSTATUS_CLIPUNIONGEN2 = D3DCLIP_GEN2; D3DSTATUS_CLIPUNIONGEN3 = D3DCLIP_GEN3; D3DSTATUS_CLIPUNIONGEN4 = D3DCLIP_GEN4; D3DSTATUS_CLIPUNIONGEN5 = D3DCLIP_GEN5; D3DSTATUS_CLIPINTERSECTIONLEFT = $00001000; D3DSTATUS_CLIPINTERSECTIONRIGHT = $00002000; D3DSTATUS_CLIPINTERSECTIONTOP = $00004000; D3DSTATUS_CLIPINTERSECTIONBOTTOM = $00008000; D3DSTATUS_CLIPINTERSECTIONFRONT = $00010000; D3DSTATUS_CLIPINTERSECTIONBACK = $00020000; D3DSTATUS_CLIPINTERSECTIONGEN0 = $00040000; D3DSTATUS_CLIPINTERSECTIONGEN1 = $00080000; D3DSTATUS_CLIPINTERSECTIONGEN2 = $00100000; D3DSTATUS_CLIPINTERSECTIONGEN3 = $00200000; D3DSTATUS_CLIPINTERSECTIONGEN4 = $00400000; D3DSTATUS_CLIPINTERSECTIONGEN5 = $00800000; D3DSTATUS_ZNOTVISIBLE = $01000000; (* Do not use 0x80000000 for any status flags in future as it is reserved *) D3DSTATUS_CLIPUNIONALL = ( D3DSTATUS_CLIPUNIONLEFT or D3DSTATUS_CLIPUNIONRIGHT or D3DSTATUS_CLIPUNIONTOP or D3DSTATUS_CLIPUNIONBOTTOM or D3DSTATUS_CLIPUNIONFRONT or D3DSTATUS_CLIPUNIONBACK or D3DSTATUS_CLIPUNIONGEN0 or D3DSTATUS_CLIPUNIONGEN1 or D3DSTATUS_CLIPUNIONGEN2 or D3DSTATUS_CLIPUNIONGEN3 or D3DSTATUS_CLIPUNIONGEN4 or D3DSTATUS_CLIPUNIONGEN5); D3DSTATUS_CLIPINTERSECTIONALL = ( D3DSTATUS_CLIPINTERSECTIONLEFT or D3DSTATUS_CLIPINTERSECTIONRIGHT or D3DSTATUS_CLIPINTERSECTIONTOP or D3DSTATUS_CLIPINTERSECTIONBOTTOM or D3DSTATUS_CLIPINTERSECTIONFRONT or D3DSTATUS_CLIPINTERSECTIONBACK or D3DSTATUS_CLIPINTERSECTIONGEN0 or D3DSTATUS_CLIPINTERSECTIONGEN1 or D3DSTATUS_CLIPINTERSECTIONGEN2 or D3DSTATUS_CLIPINTERSECTIONGEN3 or D3DSTATUS_CLIPINTERSECTIONGEN4 or D3DSTATUS_CLIPINTERSECTIONGEN5); D3DSTATUS_DEFAULT = ( D3DSTATUS_CLIPINTERSECTIONALL or D3DSTATUS_ZNOTVISIBLE); (* * Options for direct transform calls *) D3DTRANSFORM_CLIPPED = $00000001; D3DTRANSFORM_UNCLIPPED = $00000002; type PD3DTransformData = ^TD3DTransformData; TD3DTransformData = packed record dwSize: DWORD; lpIn: Pointer; (* Input vertices *) dwInSize: DWORD; (* Stride of input vertices *) lpOut: Pointer; (* Output vertices *) dwOutSize: DWORD; (* Stride of output vertices *) lpHOut: ^TD3DHVertex; (* Output homogeneous vertices *) dwClip: DWORD; (* Clipping hint *) dwClipIntersection: DWORD; dwClipUnion: DWORD; (* Union of all clip flags *) drExtent: TD3DRect; (* Extent of transformed vertices *) end; (* * Structure defining position and direction properties for lighting. *) PD3DLightingElement = ^TD3DLightingElement; TD3DLightingElement = packed record dvPosition: TD3DVector; (* Lightable point in model space *) dvNormal: TD3DVector; (* Normalised unit vector *) end; (* * Structure defining material properties for lighting. *) PD3DMaterial = ^TD3DMaterial; TD3DMaterial = packed record dwSize: DWORD; case Integer of 0: ( diffuse: TD3DColorValue; (* Diffuse color RGBA *) ambient: TD3DColorValue; (* Ambient color RGB *) specular: TD3DColorValue; (* Specular 'shininess' *) emissive: TD3DColorValue; (* Emissive color RGB *) power: TD3DValue; (* Sharpness if specular highlight *) hTexture: TD3DTextureHandle; (* Handle to texture map *) dwRampSize: DWORD; ); 1: ( dcvDiffuse: TD3DColorValue; dcvAmbient: TD3DColorValue; dcvSpecular: TD3DColorValue; dcvEmissive: TD3DColorValue; dvPower: TD3DValue; ); end; PD3DMaterial7 = ^TD3DMaterial7; TD3DMaterial7 = packed record case Integer of 0: ( diffuse: TD3DColorValue; (* Diffuse color RGBA *) ambient: TD3DColorValue; (* Ambient color RGB *) specular: TD3DColorValue; (* Specular 'shininess' *) emissive: TD3DColorValue; (* Emissive color RGB *) power: TD3DValue; (* Sharpness if specular highlight *) ); 1: ( dcvDiffuse: TD3DColorValue; dcvAmbient: TD3DColorValue; dcvSpecular: TD3DColorValue; dcvEmissive: TD3DColorValue; dvPower: TD3DValue; ); end; PD3DLightType = ^TD3DLightType; TD3DLightType = ( D3DLIGHT_INVALID_0, D3DLIGHT_POINT, D3DLIGHT_SPOT, D3DLIGHT_DIRECTIONAL, // Note: The following light type (D3DLIGHT_PARALLELPOINT) // is no longer supported from D3D for DX7 onwards. D3DLIGHT_PARALLELPOINT, D3DLIGHT_GLSPOT); (* * Structure defining a light source and its properties. *) PD3DLight = ^TD3DLight; TD3DLight = packed record dwSize: DWORD; dltType: TD3DLightType; (* Type of light source *) dcvColor: TD3DColorValue; (* Color of light *) dvPosition: TD3DVector; (* Position in world space *) dvDirection: TD3DVector; (* Direction in world space *) dvRange: TD3DValue; (* Cutoff range *) dvFalloff: TD3DValue; (* Falloff *) dvAttenuation0: TD3DValue; (* Constant attenuation *) dvAttenuation1: TD3DValue; (* Linear attenuation *) dvAttenuation2: TD3DValue; (* Quadratic attenuation *) dvTheta: TD3DValue; (* Inner angle of spotlight cone *) dvPhi: TD3DValue; (* Outer angle of spotlight cone *) end; PD3DLight7 = ^TD3DLight7; TD3DLight7 = packed record dltType: TD3DLightType; (* Type of light source *) dcvDiffuse: TD3DColorValue; (* Diffuse color of light *) dcvSpecular: TD3DColorValue;(* Specular color of light *) dcvAmbient: TD3DColorValue; (* Ambient color of light *) dvPosition: TD3DVector; (* Position in world space *) dvDirection: TD3DVector; (* Direction in world space *) dvRange: TD3DValue; (* Cutoff range *) dvFalloff: TD3DValue; (* Falloff *) dvAttenuation0: TD3DValue; (* Constant attenuation *) dvAttenuation1: TD3DValue; (* Linear attenuation *) dvAttenuation2: TD3DValue; (* Quadratic attenuation *) dvTheta: TD3DValue; (* Inner angle of spotlight cone *) dvPhi: TD3DValue; (* Outer angle of spotlight cone *) end; (* * Structure defining a light source and its properties. *) (* flags bits *) const D3DLIGHT_ACTIVE = $00000001; D3DLIGHT_NO_SPECULAR = $00000002; D3DLIGHT_ALL = D3DLIGHT_ACTIVE or D3DLIGHT_ACTIVE; (* maximum valid light range *) D3DLIGHT_RANGE_MAX = 1.8439088915e+18; //sqrt(FLT_MAX); type PD3DLight2 = ^TD3DLight2; TD3DLight2 = packed record dwSize: DWORD; dltType: TD3DLightType; (* Type of light source *) dcvColor: TD3DColorValue; (* Color of light *) dvPosition: TD3DVector; (* Position in world space *) dvDirection: TD3DVector; (* Direction in world space *) dvRange: TD3DValue; (* Cutoff range *) dvFalloff: TD3DValue; (* Falloff *) dvAttenuation0: TD3DValue; (* Constant attenuation *) dvAttenuation1: TD3DValue; (* Linear attenuation *) dvAttenuation2: TD3DValue; (* Quadratic attenuation *) dvTheta: TD3DValue; (* Inner angle of spotlight cone *) dvPhi: TD3DValue; (* Outer angle of spotlight cone *) dwFlags: DWORD; end; PD3DLightData = ^TD3DLightData; TD3DLightData = packed record dwSize: DWORD; lpIn: ^TD3DLightingElement; (* Input positions and normals *) dwInSize: DWORD; (* Stride of input elements *) lpOut: ^TD3DTLVertex; (* Output colors *) dwOutSize: DWORD; (* Stride of output colors *) end; (* * Before DX5, these values were in an enum called * TD3DColorModel. This was not correct, since they are * bit flags. A driver can surface either or both flags * in the dcmColorModel member of D3DDEVICEDESC. *) type TD3DColorModel = DWORD; const D3DCOLOR_MONO = 1; D3DCOLOR_RGB = 2; (* * Options for clearing *) const D3DCLEAR_TARGET = $00000001; (* Clear target surface *) D3DCLEAR_ZBUFFER = $00000002; (* Clear target z buffer *) D3DCLEAR_STENCIL = $00000004; (* Clear stencil planes *) (* * Execute buffers are allocated via Direct3D. These buffers may then * be filled by the application with instructions to execute along with * vertex data. *) (* * Supported op codes for execute instructions. *) type PD3DOpcode = ^TD3DOpcode; TD3DOpcode = ( D3DOP_INVALID_0, D3DOP_POINT, D3DOP_LINE, D3DOP_TRIANGLE, D3DOP_MATRIXLOAD, D3DOP_MATRIXMULTIPLY, D3DOP_STATETRANSFORM, D3DOP_STATELIGHT, D3DOP_STATERENDER, D3DOP_PROCESSVERTICES, D3DOP_TEXTURELOAD, D3DOP_EXIT, D3DOP_BRANCHFORWARD, D3DOP_SPAN, D3DOP_SETSTATUS); PD3DInstruction = ^TD3DInstruction; TD3DInstruction = packed record bOpcode: BYTE; (* Instruction opcode *) bSize: BYTE; (* Size of each instruction data unit *) wCount: WORD; (* Count of instruction data units to follow *) end; (* * Structure for texture loads *) PD3DTextureLoad = ^TD3DTextureLoad; TD3DTextureLoad = packed record hDestTexture: TD3DTextureHandle; hSrcTexture: TD3DTextureHandle; end; (* * Structure for picking *) PD3DPickRecord = ^TD3DPickRecord; TD3DPickRecord = packed record bOpcode: BYTE; bPad: BYTE; dwOffset: DWORD; dvZ: TD3DValue; end; (* * The following defines the rendering states which can be set in the * execute buffer. *) PD3DShadeMode = ^TD3DShadeMode; TD3DShadeMode = ( D3DSHADE_INVALID_0, D3DSHADE_FLAT, D3DSHADE_GOURAUD, D3DSHADE_PHONG); PD3DFillMode = ^TD3DFillMode; TD3DFillMode = ( D3DFILL_INVALID_0, D3DFILL_POINT, D3DFILL_WIREFRAME, D3DFILL_SOLID); PD3DLinePattern = ^TD3DLinePattern; TD3DLinePattern = packed record wRepeatFactor: WORD; wLinePattern: WORD; end; PD3DTextureFilter = ^TD3DTextureFilter; TD3DTextureFilter = ( D3DFILTER_INVALID_0, D3DFILTER_NEAREST, D3DFILTER_LINEAR, D3DFILTER_MIPNEAREST, D3DFILTER_MIPLINEAR, D3DFILTER_LINEARMIPNEAREST, D3DFILTER_LINEARMIPLINEAR); PD3DBlend = ^TD3DBlend; TD3DBlend = ( D3DBLEND_INVALID_0, D3DBLEND_ZERO, D3DBLEND_ONE, D3DBLEND_SRCCOLOR, D3DBLEND_INVSRCCOLOR, D3DBLEND_SRCALPHA, D3DBLEND_INVSRCALPHA, D3DBLEND_DESTALPHA, D3DBLEND_INVDESTALPHA, D3DBLEND_DESTCOLOR, D3DBLEND_INVDESTCOLOR, D3DBLEND_SRCALPHASAT, D3DBLEND_BOTHSRCALPHA, D3DBLEND_BOTHINVSRCALPHA); PD3DTextureBlend = ^TD3DTextureBlend; TD3DTextureBlend = ( D3DTBLEND_INVALID_0, D3DTBLEND_DECAL, D3DTBLEND_MODULATE, D3DTBLEND_DECALALPHA, D3DTBLEND_MODULATEALPHA, D3DTBLEND_DECALMASK, D3DTBLEND_MODULATEMASK, D3DTBLEND_COPY, D3DTBLEND_ADD); PD3DTextureAddress = ^TD3DTextureAddress; TD3DTextureAddress = ( D3DTADDRESS_INVALID_0, D3DTADDRESS_WRAP, D3DTADDRESS_MIRROR, D3DTADDRESS_CLAMP, D3DTADDRESS_BORDER); PD3DCull = ^TD3DCull; TD3DCull = ( D3DCULL_INVALID_0, D3DCULL_NONE, D3DCULL_CW, D3DCULL_CCW); PD3DCmpFunc = ^TD3DCmpFunc; TD3DCmpFunc = ( D3DCMP_INVALID_0, D3DCMP_NEVER, D3DCMP_LESS, D3DCMP_EQUAL, D3DCMP_LESSEQUAL, D3DCMP_GREATER, D3DCMP_NOTEQUAL, D3DCMP_GREATEREQUAL, D3DCMP_ALWAYS); PD3DStencilOp = ^TD3DStencilOp; TD3DStencilOp = ( D3DSTENCILOP_INVALID_0, D3DSTENCILOP_KEEP, D3DSTENCILOP_ZERO, D3DSTENCILOP_REPLACE, D3DSTENCILOP_INCRSAT, D3DSTENCILOP_DECRSAT, D3DSTENCILOP_INVERT, D3DSTENCILOP_INCR, D3DSTENCILOP_DECR); PD3DFogMode = ^TD3DFogMode; TD3DFogMode = ( D3DFOG_NONE, D3DFOG_EXP, D3DFOG_EXP2, D3DFOG_LINEAR); PD3DZBufferType = ^TD3DZBufferType; TD3DZBufferType = ( D3DZB_FALSE, D3DZB_TRUE, // Z buffering D3DZB_USEW); // W buffering PD3DAntialiasMode = ^TD3DAntialiasMode; TD3DAntialiasMode = ( D3DANTIALIAS_NONE, D3DANTIALIAS_SORTDEPENDENT, D3DANTIALIAS_SORTINDEPENDENT); // Vertex types supported by Direct3D PD3DVertexType = ^TD3DVertexType; TD3DVertexType = ( D3DVT_INVALID_0, D3DVT_VERTEX, D3DVT_LVERTEX, D3DVT_TLVERTEX); // Primitives supported by draw-primitive API PD3DPrimitiveType = ^TD3DPrimitiveType; TD3DPrimitiveType = ( D3DPT_INVALID_0, D3DPT_POINTLIST, D3DPT_LINELIST, D3DPT_LINESTRIP, D3DPT_TRIANGLELIST, D3DPT_TRIANGLESTRIP, D3DPT_TRIANGLEFAN); (* * Amount to add to a state to generate the override for that state. *) const D3DSTATE_OVERRIDE_BIAS = 256; (* * A state which sets the override flag for the specified state type. *) function D3DSTATE_OVERRIDE(StateType: DWORD) : DWORD; type PD3DTransformStateType = ^TD3DTransformStateType; TD3DTransformStateType = DWORD; const D3DTRANSFORMSTATE_WORLD = 1; D3DTRANSFORMSTATE_VIEW = 2; D3DTRANSFORMSTATE_PROJECTION = 3; D3DTRANSFORMSTATE_WORLD1 = 4; // 2nd matrix to blend D3DTRANSFORMSTATE_WORLD2 = 5; // 3rd matrix to blend D3DTRANSFORMSTATE_WORLD3 = 6; // 4th matrix to blend D3DTRANSFORMSTATE_TEXTURE0 = 16; D3DTRANSFORMSTATE_TEXTURE1 = 17; D3DTRANSFORMSTATE_TEXTURE2 = 18; D3DTRANSFORMSTATE_TEXTURE3 = 19; D3DTRANSFORMSTATE_TEXTURE4 = 20; D3DTRANSFORMSTATE_TEXTURE5 = 21; D3DTRANSFORMSTATE_TEXTURE6 = 22; D3DTRANSFORMSTATE_TEXTURE7 = 23; type PD3DLightStateType = ^TD3DLightStateType; TD3DLightStateType = ( D3DLIGHTSTATE_INVALID_0, D3DLIGHTSTATE_MATERIAL, D3DLIGHTSTATE_AMBIENT, D3DLIGHTSTATE_COLORMODEL, D3DLIGHTSTATE_FOGMODE, D3DLIGHTSTATE_FOGSTART, D3DLIGHTSTATE_FOGEND, D3DLIGHTSTATE_FOGDENSITY, D3DLIGHTSTATE_COLORVERTEX); PD3DRenderStateType = ^TD3DRenderStateType; TD3DRenderStateType = DWORD; const D3DRENDERSTATE_ANTIALIAS = 2; (* D3DANTIALIASMODE *) D3DRENDERSTATE_TEXTUREPERSPECTIVE = 4; (* TRUE for perspective correction *) D3DRENDERSTATE_ZENABLE = 7; (* D3DZBUFFERTYPE (or TRUE/FALSE for legacy) *) D3DRENDERSTATE_FILLMODE = 8; (* D3DFILL_MODE *) D3DRENDERSTATE_SHADEMODE = 9; (* D3DSHADEMODE *) D3DRENDERSTATE_LINEPATTERN = 10; (* D3DLINEPATTERN *) D3DRENDERSTATE_ZWRITEENABLE = 14; (* TRUE to enable z writes *) D3DRENDERSTATE_ALPHATESTENABLE = 15; (* TRUE to enable alpha tests *) D3DRENDERSTATE_LASTPIXEL = 16; (* TRUE for last-pixel on lines *) D3DRENDERSTATE_SRCBLEND = 19; (* D3DBLEND *) D3DRENDERSTATE_DESTBLEND = 20; (* D3DBLEND *) D3DRENDERSTATE_CULLMODE = 22; (* D3DCULL *) D3DRENDERSTATE_ZFUNC = 23; (* D3DCMPFUNC *) D3DRENDERSTATE_ALPHAREF = 24; (* D3DFIXED *) D3DRENDERSTATE_ALPHAFUNC = 25; (* D3DCMPFUNC *) D3DRENDERSTATE_DITHERENABLE = 26; (* TRUE to enable dithering *) D3DRENDERSTATE_ALPHABLENDENABLE = 27; (* TRUE to enable alpha blending *) D3DRENDERSTATE_FOGENABLE = 28; (* TRUE to enable fog blending *) D3DRENDERSTATE_SPECULARENABLE = 29; (* TRUE to enable specular *) D3DRENDERSTATE_ZVISIBLE = 30; (* TRUE to enable z checking *) D3DRENDERSTATE_STIPPLEDALPHA = 33; (* TRUE to enable stippled alpha (RGB device only) *) D3DRENDERSTATE_FOGCOLOR = 34; (* D3DCOLOR *) D3DRENDERSTATE_FOGTABLEMODE = 35; (* D3DFOGMODE *) D3DRENDERSTATE_FOGSTART = 36; (* Fog start (for both vertex and pixel fog) *) D3DRENDERSTATE_FOGEND = 37; (* Fog end *) D3DRENDERSTATE_FOGDENSITY = 38; (* Fog density *) D3DRENDERSTATE_EDGEANTIALIAS = 40; (* TRUE to enable edge antialiasing *) D3DRENDERSTATE_COLORKEYENABLE = 41; (* TRUE to enable source colorkeyed textures *) D3DRENDERSTATE_ZBIAS = 47; (* LONG Z bias *) D3DRENDERSTATE_RANGEFOGENABLE = 48; (* Enables range-based fog *) D3DRENDERSTATE_STENCILENABLE = 52; (* BOOL enable/disable stenciling *) D3DRENDERSTATE_STENCILFAIL = 53; (* D3DSTENCILOP to do if stencil test fails *) D3DRENDERSTATE_STENCILZFAIL = 54; (* D3DSTENCILOP to do if stencil test passes and Z test fails *) D3DRENDERSTATE_STENCILPASS = 55; (* D3DSTENCILOP to do if both stencil and Z tests pass *) D3DRENDERSTATE_STENCILFUNC = 56; (* D3DCMPFUNC fn. Stencil Test passes if ((ref & mask) stencilfn (stencil & mask)) is true *) D3DRENDERSTATE_STENCILREF = 57; (* Reference value used in stencil test *) D3DRENDERSTATE_STENCILMASK = 58; (* Mask value used in stencil test *) D3DRENDERSTATE_STENCILWRITEMASK = 59; (* Write mask applied to values written to stencil buffer *) D3DRENDERSTATE_TEXTUREFACTOR = 60; (* D3DCOLOR used for multi-texture blend *) (* * 128 values [128; 255] are reserved for texture coordinate wrap flags. * These are constructed with the D3DWRAP_U and D3DWRAP_V macros. Using * a flags word preserves forward compatibility with texture coordinates * that are >2D. *) D3DRENDERSTATE_WRAP0 = 128; (* wrap for 1st texture coord. set *) D3DRENDERSTATE_WRAP1 = 129; (* wrap for 2nd texture coord. set *) D3DRENDERSTATE_WRAP2 = 130; (* wrap for 3rd texture coord. set *) D3DRENDERSTATE_WRAP3 = 131; (* wrap for 4th texture coord. set *) D3DRENDERSTATE_WRAP4 = 132; (* wrap for 5th texture coord. set *) D3DRENDERSTATE_WRAP5 = 133; (* wrap for 6th texture coord. set *) D3DRENDERSTATE_WRAP6 = 134; (* wrap for 7th texture coord. set *) D3DRENDERSTATE_WRAP7 = 135; (* wrap for 8th texture coord. set *) D3DRENDERSTATE_CLIPPING = 136; D3DRENDERSTATE_LIGHTING = 137; D3DRENDERSTATE_EXTENTS = 138; D3DRENDERSTATE_AMBIENT = 139; D3DRENDERSTATE_FOGVERTEXMODE = 140; D3DRENDERSTATE_COLORVERTEX = 141; D3DRENDERSTATE_LOCALVIEWER = 142; D3DRENDERSTATE_NORMALIZENORMALS = 143; D3DRENDERSTATE_COLORKEYBLENDENABLE = 144; D3DRENDERSTATE_DIFFUSEMATERIALSOURCE = 145; D3DRENDERSTATE_SPECULARMATERIALSOURCE = 146; D3DRENDERSTATE_AMBIENTMATERIALSOURCE = 147; D3DRENDERSTATE_EMISSIVEMATERIALSOURCE = 148; D3DRENDERSTATE_VERTEXBLEND = 151; D3DRENDERSTATE_CLIPPLANEENABLE = 152; // // retired renderstates - not supported for DX7 interfaces // D3DRENDERSTATE_TEXTUREHANDLE = 1; (* Texture handle for legacy interfaces (Texture;Texture2) *) D3DRENDERSTATE_TEXTUREADDRESS = 3; (* D3DTEXTUREADDRESS *) D3DRENDERSTATE_WRAPU = 5; (* TRUE for wrapping in u *) D3DRENDERSTATE_WRAPV = 6; (* TRUE for wrapping in v *) D3DRENDERSTATE_MONOENABLE = 11; (* TRUE to enable mono rasterization *) D3DRENDERSTATE_ROP2 = 12; (* ROP2 *) D3DRENDERSTATE_PLANEMASK = 13; (* DWORD physical plane mask *) D3DRENDERSTATE_TEXTUREMAG = 17; (* D3DTEXTUREFILTER *) D3DRENDERSTATE_TEXTUREMIN = 18; (* D3DTEXTUREFILTER *) D3DRENDERSTATE_TEXTUREMAPBLEND = 21; (* D3DTEXTUREBLEND *) D3DRENDERSTATE_SUBPIXEL = 31; (* TRUE to enable subpixel correction *) D3DRENDERSTATE_SUBPIXELX = 32; (* TRUE to enable correction in X only *) D3DRENDERSTATE_STIPPLEENABLE = 39; (* TRUE to enable stippling *) D3DRENDERSTATE_BORDERCOLOR = 43; (* Border color for texturing w/border *) D3DRENDERSTATE_TEXTUREADDRESSU = 44; (* Texture addressing mode for U coordinate *) D3DRENDERSTATE_TEXTUREADDRESSV = 45; (* Texture addressing mode for V coordinate *) D3DRENDERSTATE_MIPMAPLODBIAS = 46; (* D3DVALUE Mipmap LOD bias *) D3DRENDERSTATE_ANISOTROPY = 49; (* Max. anisotropy. 1 = no anisotropy *) D3DRENDERSTATE_FLUSHBATCH = 50; (* Explicit flush for DP batching (DX5 Only) *) D3DRENDERSTATE_TRANSLUCENTSORTINDEPENDENT=51; (* BOOL enable sort-independent transparency *) D3DRENDERSTATE_STIPPLEPATTERN00 = 64; (* Stipple pattern 01... *) D3DRENDERSTATE_STIPPLEPATTERN01 = 65; D3DRENDERSTATE_STIPPLEPATTERN02 = 66; D3DRENDERSTATE_STIPPLEPATTERN03 = 67; D3DRENDERSTATE_STIPPLEPATTERN04 = 68; D3DRENDERSTATE_STIPPLEPATTERN05 = 69; D3DRENDERSTATE_STIPPLEPATTERN06 = 70; D3DRENDERSTATE_STIPPLEPATTERN07 = 71; D3DRENDERSTATE_STIPPLEPATTERN08 = 72; D3DRENDERSTATE_STIPPLEPATTERN09 = 73; D3DRENDERSTATE_STIPPLEPATTERN10 = 74; D3DRENDERSTATE_STIPPLEPATTERN11 = 75; D3DRENDERSTATE_STIPPLEPATTERN12 = 76; D3DRENDERSTATE_STIPPLEPATTERN13 = 77; D3DRENDERSTATE_STIPPLEPATTERN14 = 78; D3DRENDERSTATE_STIPPLEPATTERN15 = 79; D3DRENDERSTATE_STIPPLEPATTERN16 = 80; D3DRENDERSTATE_STIPPLEPATTERN17 = 81; D3DRENDERSTATE_STIPPLEPATTERN18 = 82; D3DRENDERSTATE_STIPPLEPATTERN19 = 83; D3DRENDERSTATE_STIPPLEPATTERN20 = 84; D3DRENDERSTATE_STIPPLEPATTERN21 = 85; D3DRENDERSTATE_STIPPLEPATTERN22 = 86; D3DRENDERSTATE_STIPPLEPATTERN23 = 87; D3DRENDERSTATE_STIPPLEPATTERN24 = 88; D3DRENDERSTATE_STIPPLEPATTERN25 = 89; D3DRENDERSTATE_STIPPLEPATTERN26 = 90; D3DRENDERSTATE_STIPPLEPATTERN27 = 91; D3DRENDERSTATE_STIPPLEPATTERN28 = 92; D3DRENDERSTATE_STIPPLEPATTERN29 = 93; D3DRENDERSTATE_STIPPLEPATTERN30 = 94; D3DRENDERSTATE_STIPPLEPATTERN31 = 95; // // retired renderstate names - the values are still used under new naming conventions // D3DRENDERSTATE_FOGTABLESTART = 36; (* Fog table start *) D3DRENDERSTATE_FOGTABLEEND = 37; (* Fog table end *) D3DRENDERSTATE_FOGTABLEDENSITY = 38; (* Fog table density *) type // Values for material source PD3DMateralColorSource = ^TD3DMateralColorSource; TD3DMateralColorSource = ( D3DMCS_MATERIAL, // Color from material is used D3DMCS_COLOR1, // Diffuse vertex color is used D3DMCS_COLOR2 // Specular vertex color is used ); const // For back-compatibility with legacy compilations D3DRENDERSTATE_BLENDENABLE = D3DRENDERSTATE_ALPHABLENDENABLE; // Bias to apply to the texture coordinate set to apply a wrap to. D3DRENDERSTATE_WRAPBIAS = 128; (* Flags to construct the WRAP render states *) D3DWRAP_U = $00000001; D3DWRAP_V = $00000002; (* Flags to construct the WRAP render states for 1D thru 4D texture coordinates *) D3DWRAPCOORD_0 = $00000001; // same as D3DWRAP_U D3DWRAPCOORD_1 = $00000002; // same as D3DWRAP_V D3DWRAPCOORD_2 = $00000004; D3DWRAPCOORD_3 = $00000008; function D3DRENDERSTATE_STIPPLEPATTERN(y: integer) : TD3DRenderStateType; type PD3DState = ^TD3DState; TD3DState = packed record case Integer of 0: ( dtstTransformStateType: TD3DTransformStateType; dwArg: Array [ 0..0 ] of DWORD; ); 1: ( dlstLightStateType: TD3DLightStateType; dvArg: Array [ 0..0 ] of TD3DValue; ); 2: ( drstRenderStateType: TD3DRenderStateType; ); end; (* * Operation used to load matrices * hDstMat = hSrcMat *) PD3DMatrixLoad = ^TD3DMatrixLoad; TD3DMatrixLoad = packed record hDestMatrix: TD3DMatrixHandle; (* Destination matrix *) hSrcMatrix: TD3DMatrixHandle; (* Source matrix *) end; (* * Operation used to multiply matrices * hDstMat = hSrcMat1 * hSrcMat2 *) PD3DMatrixMultiply = ^TD3DMatrixMultiply; TD3DMatrixMultiply = packed record hDestMatrix: TD3DMatrixHandle; (* Destination matrix *) hSrcMatrix1: TD3DMatrixHandle; (* First source matrix *) hSrcMatrix2: TD3DMatrixHandle; (* Second source matrix *) end; (* * Operation used to transform and light vertices. *) PD3DProcessVertices = ^TD3DProcessVertices; TD3DProcessVertices = packed record dwFlags: DWORD; (* Do we transform or light or just copy? *) wStart: WORD; (* Index to first vertex in source *) wDest: WORD; (* Index to first vertex in local buffer *) dwCount: DWORD; (* Number of vertices to be processed *) dwReserved: DWORD; (* Must be zero *) end; const D3DPROCESSVERTICES_TRANSFORMLIGHT = $00000000; D3DPROCESSVERTICES_TRANSFORM = $00000001; D3DPROCESSVERTICES_COPY = $00000002; D3DPROCESSVERTICES_OPMASK = $00000007; D3DPROCESSVERTICES_UPDATEEXTENTS = $00000008; D3DPROCESSVERTICES_NOCOLOR = $00000010; (* * State enumerants for per-stage texture processing. *) type PD3DTextureStageStateType = ^TD3DTextureStageStateType; TD3DTextureStageStateType = DWORD; const D3DTSS_COLOROP = 1; (* D3DTEXTUREOP - per-stage blending controls for color channels *) D3DTSS_COLORARG1 = 2; (* D3DTA_* (texture arg) *) D3DTSS_COLORARG2 = 3; (* D3DTA_* (texture arg) *) D3DTSS_ALPHAOP = 4; (* D3DTEXTUREOP - per-stage blending controls for alpha channel *) D3DTSS_ALPHAARG1 = 5; (* D3DTA_* (texture arg) *) D3DTSS_ALPHAARG2 = 6; (* D3DTA_* (texture arg) *) D3DTSS_BUMPENVMAT00 = 7; (* D3DVALUE (bump mapping matrix) *) D3DTSS_BUMPENVMAT01 = 8; (* D3DVALUE (bump mapping matrix) *) D3DTSS_BUMPENVMAT10 = 9; (* D3DVALUE (bump mapping matrix) *) D3DTSS_BUMPENVMAT11 = 10; (* D3DVALUE (bump mapping matrix) *) D3DTSS_TEXCOORDINDEX = 11; (* identifies which set of texture coordinates index this texture *) D3DTSS_ADDRESS = 12; (* D3DTEXTUREADDRESS for both coordinates *) D3DTSS_ADDRESSU = 13; (* D3DTEXTUREADDRESS for U coordinate *) D3DTSS_ADDRESSV = 14; (* D3DTEXTUREADDRESS for V coordinate *) D3DTSS_BORDERCOLOR = 15; (* D3DCOLOR *) D3DTSS_MAGFILTER = 16; (* D3DTEXTUREMAGFILTER filter to use for magnification *) D3DTSS_MINFILTER = 17; (* D3DTEXTUREMINFILTER filter to use for minification *) D3DTSS_MIPFILTER = 18; (* D3DTEXTUREMIPFILTER filter to use between mipmaps during minification *) D3DTSS_MIPMAPLODBIAS = 19; (* D3DVALUE Mipmap LOD bias *) D3DTSS_MAXMIPLEVEL = 20; (* DWORD 0..(n-1) LOD index of largest map to use (0 == largest) *) D3DTSS_MAXANISOTROPY = 21; (* DWORD maximum anisotropy *) D3DTSS_BUMPENVLSCALE = 22; (* D3DVALUE scale for bump map luminance *) D3DTSS_BUMPENVLOFFSET = 23; (* D3DVALUE offset for bump map luminance *) D3DTSS_TEXTURETRANSFORMFLAGS = 24; (* D3DTEXTURETRANSFORMFLAGS controls texture transform *) // Values, used with D3DTSS_TEXCOORDINDEX, to specify that the vertex data(position // and normal in the camera space) should be taken as texture coordinates // Low 16 bits are used to specify texture coordinate index, to take the WRAP mode from // D3DTSS_TCI_PASSTHRU = $00000000; D3DTSS_TCI_CAMERASPACENORMAL = $00010000; D3DTSS_TCI_CAMERASPACEPOSITION = $00020000; D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR = $00030000; type (* * Enumerations for COLOROP and ALPHAOP texture blending operations set in * texture processing stage controls in D3DRENDERSTATE. *) PD3DTextureOp = ^TD3DTextureOp; TD3DTextureOp = ( D3DTOP_INVALID_0, // Control D3DTOP_DISABLE , // disables stage D3DTOP_SELECTARG1, // the default D3DTOP_SELECTARG2, // Modulate D3DTOP_MODULATE , // multiply args together D3DTOP_MODULATE2X, // multiply and 1 bit D3DTOP_MODULATE4X, // multiply and 2 bits // Add D3DTOP_ADD , // add arguments together D3DTOP_ADDSIGNED , // add with -0.5 bias D3DTOP_ADDSIGNED2X, // as above but left 1 bit D3DTOP_SUBTRACT , // Arg1 - Arg2, with no saturation D3DTOP_ADDSMOOTH , // add 2 args, subtract product // Arg1 + Arg2 - Arg1*Arg2 // = Arg1 + (1-Arg1)*Arg2 // Linear alpha blend: Arg1*(Alpha) + Arg2*(1-Alpha) D3DTOP_BLENDDIFFUSEALPHA , // iterated alpha D3DTOP_BLENDTEXTUREALPHA , // texture alpha D3DTOP_BLENDFACTORALPHA , // alpha from D3DRENDERSTATE_TEXTUREFACTOR // Linear alpha blend with pre-multiplied arg1 input: Arg1 + Arg2*(1-Alpha) D3DTOP_BLENDTEXTUREALPHAPM, // texture alpha D3DTOP_BLENDCURRENTALPHA , // by alpha of current color // Specular mapping D3DTOP_PREMODULATE , // modulate with next texture before use D3DTOP_MODULATEALPHA_ADDCOLOR, // Arg1.RGB + Arg1.A*Arg2.RGB // COLOROP only D3DTOP_MODULATECOLOR_ADDALPHA, // Arg1.RGB*Arg2.RGB + Arg1.A // COLOROP only D3DTOP_MODULATEINVALPHA_ADDCOLOR, // (1-Arg1.A)*Arg2.RGB + Arg1.RGB // COLOROP only D3DTOP_MODULATEINVCOLOR_ADDALPHA, // (1-Arg1.RGB)*Arg2.RGB + Arg1.A // COLOROP only // Bump mapping D3DTOP_BUMPENVMAP , // per pixel env map perturbation D3DTOP_BUMPENVMAPLUMINANCE, // with luminance channel // This can do either diffuse or specular bump mapping with correct input. // Performs the function (Arg1.R*Arg2.R + Arg1.G*Arg2.G + Arg1.B*Arg2.B) // where each component has been scaled and offset to make it signed. // The result is replicated into all four (including alpha) channels. // This is a valid COLOROP only. D3DTOP_DOTPRODUCT3 ); (* * Values for COLORARG1,2 and ALPHAARG1,2 texture blending operations * set in texture processing stage controls in D3DRENDERSTATE. *) const D3DTA_SELECTMASK = $0000000f; // mask for arg selector D3DTA_DIFFUSE = $00000000; // select diffuse color D3DTA_CURRENT = $00000001; // select result of previous stage D3DTA_TEXTURE = $00000002; // select texture color D3DTA_TFACTOR = $00000003; // select RENDERSTATE_TEXTUREFACTOR D3DTA_SPECULAR = $00000004; // select specular color D3DTA_COMPLEMENT = $00000010; // take 1.0 - x D3DTA_ALPHAREPLICATE = $00000020; // replicate alpha to color components (* * IDirect3DTexture2 State Filter Types *) type PD3DTextureMagFilter = ^TD3DTextureMagFilter; TD3DTextureMagFilter = ( D3DTFG_INVALID_0, D3DTFG_POINT , // nearest D3DTFG_LINEAR , // linear interpolation D3DTFG_FLATCUBIC , // cubic D3DTFG_GAUSSIANCUBIC, // different cubic kernel D3DTFG_ANISOTROPIC ); PD3DTextureMinFilter = ^TD3DTextureMinFilter; TD3DTextureMinFilter = ( D3DTFN_INVALID_0, D3DTFN_POINT , // nearest D3DTFN_LINEAR , // linear interpolation D3DTFN_ANISOTROPIC ); PD3DTextureMipFilter = ^TD3DTextureMipFilter; TD3DTextureMipFilter = ( D3DTFP_INVALID_0, D3DTFP_NONE , // mipmapping disabled (use MAG filter) D3DTFP_POINT , // nearest D3DTFP_LINEAR // linear interpolation ); (* * Triangle flags *) (* * Tri strip and fan flags. * START loads all three vertices * EVEN and ODD load just v3 with even or odd culling * START_FLAT contains a count from 0 to 29 that allows the * whole strip or fan to be culled in one hit. * e.g. for a quad len = 1 *) const D3DTRIFLAG_START = $00000000; // #define D3DTRIFLAG_STARTFLAT(len) (len) (* 0 < len < 30 *) function D3DTRIFLAG_STARTFLAT(len: DWORD) : DWORD; const D3DTRIFLAG_ODD = $0000001e; D3DTRIFLAG_EVEN = $0000001f; (* * Triangle edge flags * enable edges for wireframe or antialiasing *) D3DTRIFLAG_EDGEENABLE1 = $00000100; (* v0-v1 edge *) D3DTRIFLAG_EDGEENABLE2 = $00000200; (* v1-v2 edge *) D3DTRIFLAG_EDGEENABLE3 = $00000400; (* v2-v0 edge *) D3DTRIFLAG_EDGEENABLETRIANGLE = ( D3DTRIFLAG_EDGEENABLE1 or D3DTRIFLAG_EDGEENABLE2 or D3DTRIFLAG_EDGEENABLE3); (* * Primitive structures and related defines. Vertex offsets are to types * TD3DVertex, TD3DLVertex, or TD3DTLVertex. *) (* * Triangle list primitive structure *) type PD3DTriangle = ^TD3DTriangle; TD3DTriangle = packed record case Integer of 0: ( v1: WORD; (* Vertex indices *) v2: WORD; v3: WORD; wFlags: WORD; (* Edge (and other) flags *) ); 1: ( wV1: WORD; wV2: WORD; wV3: WORD; ); end; (* * Line strip structure. * The instruction count - 1 defines the number of line segments. *) PD3DLine = ^TD3DLine; TD3DLine = packed record case Integer of 0: ( v1: WORD; (* Vertex indices *) v2: WORD; ); 1: ( wV1: WORD; wV2: WORD; ); end; (* * Span structure * Spans join a list of points with the same y value. * If the y value changes, a new span is started. *) PD3DSpan = ^TD3DSpan; TD3DSpan = packed record wCount: WORD; (* Number of spans *) wFirst: WORD; (* Index to first vertex *) end; (* * Point structure *) PD3DPoint = ^TD3DPoint; TD3DPoint = packed record wCount: WORD; (* number of points *) wFirst: WORD; (* index to first vertex *) end; (* * Forward branch structure. * Mask is logically anded with the driver status mask * if the result equals 'value', the branch is taken. *) PD3DBranch = ^TD3DBranch; TD3DBranch = packed record dwMask: DWORD; (* Bitmask against D3D status *) dwValue: DWORD; bNegate: BOOL; (* TRUE to negate comparison *) dwOffset: DWORD; (* How far to branch forward (0 for exit)*) end; (* * Status used for set status instruction. * The D3D status is initialised on device creation * and is modified by all execute calls. *) PD3DStatus = ^TD3DStatus; TD3DStatus = packed record dwFlags: DWORD; (* Do we set extents or status *) dwStatus: DWORD; (* D3D status *) drExtent: TD3DRect; end; const D3DSETSTATUS_STATUS = $00000001; D3DSETSTATUS_EXTENTS = $00000002; D3DSETSTATUS_ALL = (D3DSETSTATUS_STATUS or D3DSETSTATUS_EXTENTS); type PD3DClipStatus = ^TD3DClipStatus; TD3DClipStatus = packed record dwFlags : DWORD; (* Do we set 2d extents, 3D extents or status *) dwStatus : DWORD; (* Clip status *) minx, maxx : float; (* X extents *) miny, maxy : float; (* Y extents *) minz, maxz : float; (* Z extents *) end; const D3DCLIPSTATUS_STATUS = $00000001; D3DCLIPSTATUS_EXTENTS2 = $00000002; D3DCLIPSTATUS_EXTENTS3 = $00000004; (* * Statistics structure *) type PD3DStats = ^TD3DStats; TD3DStats = packed record dwSize: DWORD; dwTrianglesDrawn: DWORD; dwLinesDrawn: DWORD; dwPointsDrawn: DWORD; dwSpansDrawn: DWORD; dwVerticesProcessed: DWORD; end; (* * Execute options. * When calling using D3DEXECUTE_UNCLIPPED all the primitives * inside the buffer must be contained within the viewport. *) const D3DEXECUTE_CLIPPED = $00000001; D3DEXECUTE_UNCLIPPED = $00000002; type PD3DExecuteData = ^TD3DExecuteData; TD3DExecuteData = packed record dwSize: DWORD; dwVertexOffset: DWORD; dwVertexCount: DWORD; dwInstructionOffset: DWORD; dwInstructionLength: DWORD; dwHVertexOffset: DWORD; dsStatus: TD3DStatus; (* Status after execute *) end; (* * Palette flags. * This are or'ed with the peFlags in the PALETTEENTRYs passed to DirectDraw. *) const D3DPAL_FREE = $00; (* Renderer may use this entry freely *) D3DPAL_READONLY = $40; (* Renderer may not set this entry *) D3DPAL_RESERVED = $80; (* Renderer may not use this entry *) type PD3DVertexBufferDesc = ^TD3DVertexBufferDesc; TD3DVertexBufferDesc = packed record dwSize : DWORD; dwCaps : DWORD; dwFVF : DWORD; dwNumVertices : DWORD; end; const (* These correspond to DDSCAPS_* flags *) D3DVBCAPS_SYSTEMMEMORY = $00000800; D3DVBCAPS_WRITEONLY = $00010000; D3DVBCAPS_OPTIMIZED = $80000000; D3DVBCAPS_DONOTCLIP = $00000001; (* Vertex Operations for ProcessVertices *) D3DVOP_LIGHT = (1 shl 10); D3DVOP_TRANSFORM = (1 shl 0); D3DVOP_CLIP = (1 shl 2); D3DVOP_EXTENTS = (1 shl 3); (* The maximum number of vertices user can pass to any d3d drawing function or to create vertex buffer with *) D3DMAXNUMVERTICES = ((1 shl 16) - 1); (* The maximum number of primitives user can pass to any d3d drawing function. *) D3DMAXNUMPRIMITIVES = ((1 shl 16) - 1); (* Bits for dwFlags in ProcessVertices call *) D3DPV_DONOTCOPYDATA = (1 shl 0); //------------------------------------------------------------------- // Flexible vertex format bits // D3DFVF_RESERVED0 = $001; D3DFVF_POSITION_MASK = $00E; D3DFVF_XYZ = $002; D3DFVF_XYZRHW = $004; D3DFVF_XYZB1 = $006; D3DFVF_XYZB2 = $008; D3DFVF_XYZB3 = $00a; D3DFVF_XYZB4 = $00c; D3DFVF_XYZB5 = $00e; D3DFVF_NORMAL = $010; D3DFVF_RESERVED1 = $020; D3DFVF_DIFFUSE = $040; D3DFVF_SPECULAR = $080; D3DFVF_TEXCOUNT_MASK = $f00; D3DFVF_TEXCOUNT_SHIFT = 8; D3DFVF_TEX0 = $000; D3DFVF_TEX1 = $100; D3DFVF_TEX2 = $200; D3DFVF_TEX3 = $300; D3DFVF_TEX4 = $400; D3DFVF_TEX5 = $500; D3DFVF_TEX6 = $600; D3DFVF_TEX7 = $700; D3DFVF_TEX8 = $800; D3DFVF_RESERVED2 = $f000; // 4 reserved bits D3DFVF_VERTEX = ( D3DFVF_XYZ or D3DFVF_NORMAL or D3DFVF_TEX1 ); D3DFVF_LVERTEX = ( D3DFVF_XYZ or D3DFVF_RESERVED1 or D3DFVF_DIFFUSE or D3DFVF_SPECULAR or D3DFVF_TEX1 ); D3DFVF_TLVERTEX = ( D3DFVF_XYZRHW or D3DFVF_DIFFUSE or D3DFVF_SPECULAR or D3DFVF_TEX1 ); type PD3DDP_PtrStride = ^TD3DDP_PtrStride; TD3DDP_PtrStride = packed record lpvData : pointer; dwStride : DWORD; end; const D3DDP_MAXTEXCOORD = 8; type PD3DDrawPrimitiveStridedData = ^TD3DDrawPrimitiveStridedData; TD3DDrawPrimitiveStridedData = packed record position : TD3DDP_PtrStride; normal : TD3DDP_PtrStride; diffuse : TD3DDP_PtrStride; specular : TD3DDP_PtrStride; textureCoords : array [0..D3DDP_MAXTEXCOORD-1] of TD3DDP_PtrStride; end; //--------------------------------------------------------------------- // ComputeSphereVisibility return values // const D3DVIS_INSIDE_FRUSTUM = 0; D3DVIS_INTERSECT_FRUSTUM = 1; D3DVIS_OUTSIDE_FRUSTUM = 2; D3DVIS_INSIDE_LEFT = 0; D3DVIS_INTERSECT_LEFT = (1 shl 2); D3DVIS_OUTSIDE_LEFT = (2 shl 2); D3DVIS_INSIDE_RIGHT = 0; D3DVIS_INTERSECT_RIGHT = (1 shl 4); D3DVIS_OUTSIDE_RIGHT = (2 shl 4); D3DVIS_INSIDE_TOP = 0; D3DVIS_INTERSECT_TOP = (1 shl 6); D3DVIS_OUTSIDE_TOP = (2 shl 6); D3DVIS_INSIDE_BOTTOM = 0; D3DVIS_INTERSECT_BOTTOM = (1 shl 8); D3DVIS_OUTSIDE_BOTTOM = (2 shl 8); D3DVIS_INSIDE_NEAR = 0; D3DVIS_INTERSECT_NEAR = (1 shl 10); D3DVIS_OUTSIDE_NEAR = (2 shl 10); D3DVIS_INSIDE_FAR = 0; D3DVIS_INTERSECT_FAR = (1 shl 12); D3DVIS_OUTSIDE_FAR = (2 shl 12); D3DVIS_MASK_FRUSTUM = (3 shl 0); D3DVIS_MASK_LEFT = (3 shl 2); D3DVIS_MASK_RIGHT = (3 shl 4); D3DVIS_MASK_TOP = (3 shl 6); D3DVIS_MASK_BOTTOM = (3 shl 8); D3DVIS_MASK_NEAR = (3 shl 10); D3DVIS_MASK_FAR = (3 shl 12); // To be used with GetInfo() D3DDEVINFOID_TEXTUREMANAGER = 1; D3DDEVINFOID_D3DTEXTUREMANAGER = 2; D3DDEVINFOID_TEXTURING = 3; type PD3DStateBlockType = ^TD3DStateBlockType; TD3DStateBlockType = ( D3DSBT_INVALID_0 , D3DSBT_ALL , // capture all state D3DSBT_PIXELSTATE , // capture pixel state D3DSBT_VERTEXSTATE // capture vertex state ); // The D3DVERTEXBLENDFLAGS type is used with D3DRENDERSTATE_VERTEXBLEND state. // PD3DVertexBlendFlags = ^TD3DVertexBlendFlags; TD3DVertexBlendFlags = ( D3DVBLEND_DISABLE , // Disable vertex blending D3DVBLEND_1WEIGHT , // blend between 2 matrices D3DVBLEND_2WEIGHTS, // blend between 3 matrices D3DVBLEND_3WEIGHTS // blend between 4 matrices ); PD3DTextureTransformFlags = ^TD3DTextureTransformFlags; TD3DTextureTransformFlags = ( D3DTTFF_DISABLE , // texture coordinates are passed directly D3DTTFF_COUNT1 , // rasterizer should expect 1-D texture coords D3DTTFF_COUNT2 , // rasterizer should expect 2-D texture coords D3DTTFF_COUNT3 , // rasterizer should expect 3-D texture coords D3DTTFF_COUNT4 // rasterizer should expect 4-D texture coords ); const D3DTTFF_PROJECTED = TD3DTextureTransformFlags(256); // texcoords to be divided by COUNTth element // Macros to set texture coordinate format bits in the FVF id D3DFVF_TEXTUREFORMAT2 = 0; // Two floating point values D3DFVF_TEXTUREFORMAT1 = 3; // One floating point value D3DFVF_TEXTUREFORMAT3 = 1; // Three floating point values D3DFVF_TEXTUREFORMAT4 = 2; // Four floating point values function D3DFVF_TEXCOORDSIZE3(CoordIndex: DWORD) : DWORD; function D3DFVF_TEXCOORDSIZE2(CoordIndex: DWORD) : DWORD; function D3DFVF_TEXCOORDSIZE4(CoordIndex: DWORD) : DWORD; function D3DFVF_TEXCOORDSIZE1(CoordIndex: DWORD) : DWORD; (*==========================================================================; * * * File: d3dcaps.h * Content: Direct3D capabilities include file * ***************************************************************************) (* Description of capabilities of transform *) type PD3DTransformCaps = ^TD3DTransformCaps; TD3DTransformCaps = packed record dwSize: DWORD; dwCaps: DWORD; end; const D3DTRANSFORMCAPS_CLIP = $00000001; (* Will clip whilst transforming *) (* Description of capabilities of lighting *) type PD3DLightingCaps = ^TD3DLightingCaps; TD3DLightingCaps = packed record dwSize: DWORD; dwCaps: DWORD; (* Lighting caps *) dwLightingModel: DWORD; (* Lighting model - RGB or mono *) dwNumLights: DWORD; (* Number of lights that can be handled *) end; const D3DLIGHTINGMODEL_RGB = $00000001; D3DLIGHTINGMODEL_MONO = $00000002; D3DLIGHTCAPS_POINT = $00000001; (* Point lights supported *) D3DLIGHTCAPS_SPOT = $00000002; (* Spot lights supported *) D3DLIGHTCAPS_DIRECTIONAL = $00000004; (* Directional lights supported *) D3DLIGHTCAPS_PARALLELPOINT = $00000008; (* Parallel point lights supported *) D3DLIGHTCAPS_GLSPOT = $00000010; (* GL syle spot lights supported *) (* Description of capabilities for each primitive type *) type PD3DPrimCaps = ^TD3DPrimCaps; TD3DPrimCaps = packed record dwSize: DWORD; dwMiscCaps: DWORD; (* Capability flags *) dwRasterCaps: DWORD; dwZCmpCaps: DWORD; dwSrcBlendCaps: DWORD; dwDestBlendCaps: DWORD; dwAlphaCmpCaps: DWORD; dwShadeCaps: DWORD; dwTextureCaps: DWORD; dwTextureFilterCaps: DWORD; dwTextureBlendCaps: DWORD; dwTextureAddressCaps: DWORD; dwStippleWidth: DWORD; (* maximum width and height of *) dwStippleHeight: DWORD; (* of supported stipple (up to 32x32) *) end; const (* TD3DPrimCaps dwMiscCaps *) D3DPMISCCAPS_MASKPLANES = $00000001; D3DPMISCCAPS_MASKZ = $00000002; D3DPMISCCAPS_LINEPATTERNREP = $00000004; D3DPMISCCAPS_CONFORMANT = $00000008; D3DPMISCCAPS_CULLNONE = $00000010; D3DPMISCCAPS_CULLCW = $00000020; D3DPMISCCAPS_CULLCCW = $00000040; (* TD3DPrimCaps dwRasterCaps *) D3DPRASTERCAPS_DITHER = $00000001; D3DPRASTERCAPS_ROP2 = $00000002; D3DPRASTERCAPS_XOR = $00000004; D3DPRASTERCAPS_PAT = $00000008; D3DPRASTERCAPS_ZTEST = $00000010; D3DPRASTERCAPS_SUBPIXEL = $00000020; D3DPRASTERCAPS_SUBPIXELX = $00000040; D3DPRASTERCAPS_FOGVERTEX = $00000080; D3DPRASTERCAPS_FOGTABLE = $00000100; D3DPRASTERCAPS_STIPPLE = $00000200; D3DPRASTERCAPS_ANTIALIASSORTDEPENDENT = $00000400; D3DPRASTERCAPS_ANTIALIASSORTINDEPENDENT = $00000800; D3DPRASTERCAPS_ANTIALIASEDGES = $00001000; D3DPRASTERCAPS_MIPMAPLODBIAS = $00002000; D3DPRASTERCAPS_ZBIAS = $00004000; D3DPRASTERCAPS_ZBUFFERLESSHSR = $00008000; D3DPRASTERCAPS_FOGRANGE = $00010000; D3DPRASTERCAPS_ANISOTROPY = $00020000; D3DPRASTERCAPS_WBUFFER = $00040000; D3DPRASTERCAPS_TRANSLUCENTSORTINDEPENDENT = $00080000; D3DPRASTERCAPS_WFOG = $00100000; D3DPRASTERCAPS_ZFOG = $00200000; (* TD3DPrimCaps dwZCmpCaps, dwAlphaCmpCaps *) const D3DPCMPCAPS_NEVER = $00000001; D3DPCMPCAPS_LESS = $00000002; D3DPCMPCAPS_EQUAL = $00000004; D3DPCMPCAPS_LESSEQUAL = $00000008; D3DPCMPCAPS_GREATER = $00000010; D3DPCMPCAPS_NOTEQUAL = $00000020; D3DPCMPCAPS_GREATEREQUAL = $00000040; D3DPCMPCAPS_ALWAYS = $00000080; (* TD3DPrimCaps dwSourceBlendCaps, dwDestBlendCaps *) D3DPBLENDCAPS_ZERO = $00000001; D3DPBLENDCAPS_ONE = $00000002; D3DPBLENDCAPS_SRCCOLOR = $00000004; D3DPBLENDCAPS_INVSRCCOLOR = $00000008; D3DPBLENDCAPS_SRCALPHA = $00000010; D3DPBLENDCAPS_INVSRCALPHA = $00000020; D3DPBLENDCAPS_DESTALPHA = $00000040; D3DPBLENDCAPS_INVDESTALPHA = $00000080; D3DPBLENDCAPS_DESTCOLOR = $00000100; D3DPBLENDCAPS_INVDESTCOLOR = $00000200; D3DPBLENDCAPS_SRCALPHASAT = $00000400; D3DPBLENDCAPS_BOTHSRCALPHA = $00000800; D3DPBLENDCAPS_BOTHINVSRCALPHA = $00001000; (* TD3DPrimCaps dwShadeCaps *) D3DPSHADECAPS_COLORFLATMONO = $00000001; D3DPSHADECAPS_COLORFLATRGB = $00000002; D3DPSHADECAPS_COLORGOURAUDMONO = $00000004; D3DPSHADECAPS_COLORGOURAUDRGB = $00000008; D3DPSHADECAPS_COLORPHONGMONO = $00000010; D3DPSHADECAPS_COLORPHONGRGB = $00000020; D3DPSHADECAPS_SPECULARFLATMONO = $00000040; D3DPSHADECAPS_SPECULARFLATRGB = $00000080; D3DPSHADECAPS_SPECULARGOURAUDMONO = $00000100; D3DPSHADECAPS_SPECULARGOURAUDRGB = $00000200; D3DPSHADECAPS_SPECULARPHONGMONO = $00000400; D3DPSHADECAPS_SPECULARPHONGRGB = $00000800; D3DPSHADECAPS_ALPHAFLATBLEND = $00001000; D3DPSHADECAPS_ALPHAFLATSTIPPLED = $00002000; D3DPSHADECAPS_ALPHAGOURAUDBLEND = $00004000; D3DPSHADECAPS_ALPHAGOURAUDSTIPPLED = $00008000; D3DPSHADECAPS_ALPHAPHONGBLEND = $00010000; D3DPSHADECAPS_ALPHAPHONGSTIPPLED = $00020000; D3DPSHADECAPS_FOGFLAT = $00040000; D3DPSHADECAPS_FOGGOURAUD = $00080000; D3DPSHADECAPS_FOGPHONG = $00100000; (* TD3DPrimCaps dwTextureCaps *) (* * Perspective-correct texturing is supported *) D3DPTEXTURECAPS_PERSPECTIVE = $00000001; (* * Power-of-2 texture dimensions are required *) D3DPTEXTURECAPS_POW2 = $00000002; (* * Alpha in texture pixels is supported *) D3DPTEXTURECAPS_ALPHA = $00000004; (* * Color-keyed textures are supported *) D3DPTEXTURECAPS_TRANSPARENCY = $00000008; (* * obsolete, see D3DPTADDRESSCAPS_BORDER *) D3DPTEXTURECAPS_BORDER = $00000010; (* * Only square textures are supported *) D3DPTEXTURECAPS_SQUAREONLY = $00000020; (* * Texture indices are not scaled by the texture size prior * to interpolation. *) D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE = $00000040; (* * Device can draw alpha from texture palettes *) D3DPTEXTURECAPS_ALPHAPALETTE = $00000080; (* * Device can use non-POW2 textures if: * 1) D3DTEXTURE_ADDRESS is set to CLAMP for this texture's stage * 2) D3DRS_WRAP(N) is zero for this texture's coordinates * 3) mip mapping is not enabled (use magnification filter only) *) D3DPTEXTURECAPS_NONPOW2CONDITIONAL = $00000100; // 0x00000200L unused (* * Device can divide transformed texture coordinates by the * COUNTth texture coordinate (can do D3DTTFF_PROJECTED) *) D3DPTEXTURECAPS_PROJECTED = $00000400; (* * Device can do cubemap textures *) D3DPTEXTURECAPS_CUBEMAP = $00000800; D3DPTEXTURECAPS_COLORKEYBLEND = $00001000; (* TD3DPrimCaps dwTextureFilterCaps *) D3DPTFILTERCAPS_NEAREST = $00000001; D3DPTFILTERCAPS_LINEAR = $00000002; D3DPTFILTERCAPS_MIPNEAREST = $00000004; D3DPTFILTERCAPS_MIPLINEAR = $00000008; D3DPTFILTERCAPS_LINEARMIPNEAREST = $00000010; D3DPTFILTERCAPS_LINEARMIPLINEAR = $00000020; (* Device3 Min Filter *) D3DPTFILTERCAPS_MINFPOINT = $00000100; D3DPTFILTERCAPS_MINFLINEAR = $00000200; D3DPTFILTERCAPS_MINFANISOTROPIC = $00000400; (* Device3 Mip Filter *) D3DPTFILTERCAPS_MIPFPOINT = $00010000; D3DPTFILTERCAPS_MIPFLINEAR = $00020000; (* Device3 Mag Filter *) D3DPTFILTERCAPS_MAGFPOINT = $01000000; D3DPTFILTERCAPS_MAGFLINEAR = $02000000; D3DPTFILTERCAPS_MAGFANISOTROPIC = $04000000; D3DPTFILTERCAPS_MAGFAFLATCUBIC = $08000000; D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC = $10000000; (* TD3DPrimCaps dwTextureBlendCaps *) D3DPTBLENDCAPS_DECAL = $00000001; D3DPTBLENDCAPS_MODULATE = $00000002; D3DPTBLENDCAPS_DECALALPHA = $00000004; D3DPTBLENDCAPS_MODULATEALPHA = $00000008; D3DPTBLENDCAPS_DECALMASK = $00000010; D3DPTBLENDCAPS_MODULATEMASK = $00000020; D3DPTBLENDCAPS_COPY = $00000040; D3DPTBLENDCAPS_ADD = $00000080; (* TD3DPrimCaps dwTextureAddressCaps *) D3DPTADDRESSCAPS_WRAP = $00000001; D3DPTADDRESSCAPS_MIRROR = $00000002; D3DPTADDRESSCAPS_CLAMP = $00000004; D3DPTADDRESSCAPS_BORDER = $00000008; D3DPTADDRESSCAPS_INDEPENDENTUV = $00000010; (* D3DDEVICEDESC dwStencilCaps *) D3DSTENCILCAPS_KEEP = $00000001; D3DSTENCILCAPS_ZERO = $00000002; D3DSTENCILCAPS_REPLACE = $00000004; D3DSTENCILCAPS_INCRSAT = $00000008; D3DSTENCILCAPS_DECRSAT = $00000010; D3DSTENCILCAPS_INVERT = $00000020; D3DSTENCILCAPS_INCR = $00000040; D3DSTENCILCAPS_DECR = $00000080; (* D3DDEVICEDESC dwTextureOpCaps *) D3DTEXOPCAPS_DISABLE = $00000001; D3DTEXOPCAPS_SELECTARG1 = $00000002; D3DTEXOPCAPS_SELECTARG2 = $00000004; D3DTEXOPCAPS_MODULATE = $00000008; D3DTEXOPCAPS_MODULATE2X = $00000010; D3DTEXOPCAPS_MODULATE4X = $00000020; D3DTEXOPCAPS_ADD = $00000040; D3DTEXOPCAPS_ADDSIGNED = $00000080; D3DTEXOPCAPS_ADDSIGNED2X = $00000100; D3DTEXOPCAPS_SUBTRACT = $00000200; D3DTEXOPCAPS_ADDSMOOTH = $00000400; D3DTEXOPCAPS_BLENDDIFFUSEALPHA = $00000800; D3DTEXOPCAPS_BLENDTEXTUREALPHA = $00001000; D3DTEXOPCAPS_BLENDFACTORALPHA = $00002000; D3DTEXOPCAPS_BLENDTEXTUREALPHAPM = $00004000; D3DTEXOPCAPS_BLENDCURRENTALPHA = $00008000; D3DTEXOPCAPS_PREMODULATE = $00010000; D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR = $00020000; D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA = $00040000; D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR = $00080000; D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA = $00100000; D3DTEXOPCAPS_BUMPENVMAP = $00200000; D3DTEXOPCAPS_BUMPENVMAPLUMINANCE = $00400000; D3DTEXOPCAPS_DOTPRODUCT3 = $00800000; (* D3DDEVICEDESC dwFVFCaps flags *) D3DFVFCAPS_TEXCOORDCOUNTMASK = $0000ffff; (* mask for texture coordinate count field *) D3DFVFCAPS_DONOTSTRIPELEMENTS = $00080000; (* Device prefers that vertex elements not be stripped *) (* * Description for a device. * This is used to describe a device that is to be created or to query * the current device. *) type PD3DDeviceDesc = ^TD3DDeviceDesc; TD3DDeviceDesc = packed record dwSize: DWORD; (* Size of TD3DDeviceDesc structure *) dwFlags: DWORD; (* Indicates which fields have valid data *) dcmColorModel: TD3DColorModel; (* Color model of device *) dwDevCaps: DWORD; (* Capabilities of device *) dtcTransformCaps: TD3DTransformCaps; (* Capabilities of transform *) bClipping: BOOL; (* Device can do 3D clipping *) dlcLightingCaps: TD3DLightingCaps; (* Capabilities of lighting *) dpcLineCaps: TD3DPrimCaps; dpcTriCaps: TD3DPrimCaps; dwDeviceRenderBitDepth: DWORD; (* One of DDBB_8, 16, etc.. *) dwDeviceZBufferBitDepth: DWORD; (* One of DDBD_16, 32, etc.. *) dwMaxBufferSize: DWORD; (* Maximum execute buffer size *) dwMaxVertexCount: DWORD; (* Maximum vertex count *) // *** New fields for DX5 *** // // Width and height caps are 0 for legacy HALs. dwMinTextureWidth, dwMinTextureHeight : DWORD; dwMaxTextureWidth, dwMaxTextureHeight : DWORD; dwMinStippleWidth, dwMaxStippleWidth : DWORD; dwMinStippleHeight, dwMaxStippleHeight : DWORD; // New fields for DX6 dwMaxTextureRepeat : DWORD; dwMaxTextureAspectRatio : DWORD; dwMaxAnisotropy : DWORD; // Guard band that the rasterizer can accommodate // Screen-space vertices inside this space but outside the viewport // will get clipped properly. dvGuardBandLeft : TD3DValue; dvGuardBandTop : TD3DValue; dvGuardBandRight : TD3DValue; dvGuardBandBottom : TD3DValue; dvExtentsAdjust : TD3DValue; dwStencilCaps : DWORD; dwFVFCaps : DWORD; (* low 4 bits: 0 implies TLVERTEX only, 1..8 imply FVF aware *) dwTextureOpCaps : DWORD; wMaxTextureBlendStages : WORD; wMaxSimultaneousTextures : WORD; end; PD3DDeviceDesc7 = ^TD3DDeviceDesc7; TD3DDeviceDesc7 = packed record dwDevCaps: DWORD; (* Capabilities of device *) dpcLineCaps: TD3DPrimCaps; dpcTriCaps: TD3DPrimCaps; dwDeviceRenderBitDepth: DWORD; (* One of DDBB_8, 16, etc.. *) dwDeviceZBufferBitDepth: DWORD; (* One of DDBD_16, 32, etc.. *) dwMinTextureWidth, dwMinTextureHeight: DWORD; dwMaxTextureWidth, dwMaxTextureHeight: DWORD; dwMaxTextureRepeat: DWORD; dwMaxTextureAspectRatio: DWORD; dwMaxAnisotropy: DWORD; dvGuardBandLeft: TD3DValue; dvGuardBandTop: TD3DValue; dvGuardBandRight: TD3DValue; dvGuardBandBottom: TD3DValue; dvExtentsAdjust: TD3DValue; dwStencilCaps: DWORD; dwFVFCaps: DWORD; dwTextureOpCaps: DWORD; wMaxTextureBlendStages: WORD; wMaxSimultaneousTextures: WORD; dwMaxActiveLights: DWORD; dvMaxVertexW: TD3DValue; deviceGUID: TGUID; wMaxUserClipPlanes: WORD; wMaxVertexBlendMatrices: WORD; dwVertexProcessingCaps: DWORD; dwReserved1: DWORD; dwReserved2: DWORD; dwReserved3: DWORD; dwReserved4: DWORD; end; const D3DDEVICEDESCSIZE = sizeof(TD3DDeviceDesc); D3DDEVICEDESC7SIZE = sizeof(TD3DDeviceDesc7); type TD3DEnumDevicesCallbackA = function (lpGuid: PGUID; // nil for the default device lpDeviceDescription: PAnsiChar; lpDeviceName: PAnsiChar; var lpD3DHWDeviceDesc: TD3DDeviceDesc; var lpD3DHELDeviceDesc: TD3DDeviceDesc; lpContext : pointer) : HResult; stdcall; TD3DEnumDevicesCallback = TD3DEnumDevicesCallbackA; TD3DEnumDevicesCallback7A = function ( lpDeviceDescription: PAnsiChar; lpDeviceName: PAnsiChar; const lpD3DDeviceDesc: TD3DDeviceDesc7; lpContext: Pointer) : HResult; stdcall; TD3DEnumDevicesCallback7 = TD3DEnumDevicesCallback7A; (* TD3DDeviceDesc dwFlags indicating valid fields *) const D3DDD_COLORMODEL = $00000001; (* dcmColorModel is valid *) D3DDD_DEVCAPS = $00000002; (* dwDevCaps is valid *) D3DDD_TRANSFORMCAPS = $00000004; (* dtcTransformCaps is valid *) D3DDD_LIGHTINGCAPS = $00000008; (* dlcLightingCaps is valid *) D3DDD_BCLIPPING = $00000010; (* bClipping is valid *) D3DDD_LINECAPS = $00000020; (* dpcLineCaps is valid *) D3DDD_TRICAPS = $00000040; (* dpcTriCaps is valid *) D3DDD_DEVICERENDERBITDEPTH = $00000080; (* dwDeviceRenderBitDepth is valid *) D3DDD_DEVICEZBUFFERBITDEPTH = $00000100; (* dwDeviceZBufferBitDepth is valid *) D3DDD_MAXBUFFERSIZE = $00000200; (* dwMaxBufferSize is valid *) D3DDD_MAXVERTEXCOUNT = $00000400; (* dwMaxVertexCount is valid *) (* TD3DDeviceDesc dwDevCaps flags *) D3DDEVCAPS_FLOATTLVERTEX = $00000001; (* Device accepts floating point *) (* for post-transform vertex data *) D3DDEVCAPS_SORTINCREASINGZ = $00000002; (* Device needs data sorted for increasing Z*) D3DDEVCAPS_SORTDECREASINGZ = $00000004; (* Device needs data sorted for decreasing Z*) D3DDEVCAPS_SORTEXACT = $00000008; (* Device needs data sorted exactly *) D3DDEVCAPS_EXECUTESYSTEMMEMORY = $00000010; (* Device can use execute buffers from system memory *) D3DDEVCAPS_EXECUTEVIDEOMEMORY = $00000020; (* Device can use execute buffers from video memory *) D3DDEVCAPS_TLVERTEXSYSTEMMEMORY = $00000040; (* Device can use TL buffers from system memory *) D3DDEVCAPS_TLVERTEXVIDEOMEMORY = $00000080; (* Device can use TL buffers from video memory *) D3DDEVCAPS_TEXTURESYSTEMMEMORY = $00000100; (* Device can texture from system memory *) D3DDEVCAPS_TEXTUREVIDEOMEMORY = $00000200; (* Device can texture from device memory *) D3DDEVCAPS_DRAWPRIMTLVERTEX = $00000400; (* Device can draw TLVERTEX primitives *) D3DDEVCAPS_CANRENDERAFTERFLIP = $00000800; (* Device can render without waiting for flip to complete *) D3DDEVCAPS_TEXTURENONLOCALVIDMEM = $00001000; (* Device can texture from nonlocal video memory *) D3DDEVCAPS_DRAWPRIMITIVES2 = $00002000; (* Device can support DrawPrimitives2 *) D3DDEVCAPS_SEPARATETEXTUREMEMORIES = $00004000; (* Device is texturing from separate memory pools *) D3DDEVCAPS_DRAWPRIMITIVES2EX = $00008000; (* Device can support Extended DrawPrimitives2 i.e. DX7 compliant driver*) D3DDEVCAPS_HWTRANSFORMANDLIGHT = $00010000; (* Device can support transformation and lighting in hardware and DRAWPRIMITIVES2EX must be also *) D3DDEVCAPS_CANBLTSYSTONONLOCAL = $00020000; (* Device supports a Tex Blt from system memory to non-local vidmem *) D3DDEVCAPS_HWRASTERIZATION = $00080000; (* Device has HW acceleration for rasterization *) (* * These are the flags in the D3DDEVICEDESC7.dwVertexProcessingCaps field *) (* device can do texgen *) D3DVTXPCAPS_TEXGEN = $00000001; (* device can do IDirect3DDevice7 colormaterialsource ops *) D3DVTXPCAPS_MATERIALSOURCE7 = $00000002; (* device can do vertex fog *) D3DVTXPCAPS_VERTEXFOG = $00000004; (* device can do directional lights *) D3DVTXPCAPS_DIRECTIONALLIGHTS = $00000008; (* device can do positional lights (includes point and spot) *) D3DVTXPCAPS_POSITIONALLIGHTS = $00000010; (* device can do local viewer *) D3DVTXPCAPS_LOCALVIEWER = $00000020; D3DFDS_COLORMODEL = $00000001; (* Match color model *) D3DFDS_GUID = $00000002; (* Match guid *) D3DFDS_HARDWARE = $00000004; (* Match hardware/software *) D3DFDS_TRIANGLES = $00000008; (* Match in triCaps *) D3DFDS_LINES = $00000010; (* Match in lineCaps *) D3DFDS_MISCCAPS = $00000020; (* Match primCaps.dwMiscCaps *) D3DFDS_RASTERCAPS = $00000040; (* Match primCaps.dwRasterCaps *) D3DFDS_ZCMPCAPS = $00000080; (* Match primCaps.dwZCmpCaps *) D3DFDS_ALPHACMPCAPS = $00000100; (* Match primCaps.dwAlphaCmpCaps *) D3DFDS_SRCBLENDCAPS = $00000200; (* Match primCaps.dwSourceBlendCaps *) D3DFDS_DSTBLENDCAPS = $00000400; (* Match primCaps.dwDestBlendCaps *) D3DFDS_SHADECAPS = $00000800; (* Match primCaps.dwShadeCaps *) D3DFDS_TEXTURECAPS = $00001000; (* Match primCaps.dwTextureCaps *) D3DFDS_TEXTUREFILTERCAPS = $00002000; (* Match primCaps.dwTextureFilterCaps *) D3DFDS_TEXTUREBLENDCAPS = $00004000; (* Match primCaps.dwTextureBlendCaps *) D3DFDS_TEXTUREADDRESSCAPS = $00008000; (* Match primCaps.dwTextureBlendCaps *) (* * FindDevice arguments *) type PD3DFindDeviceSearch = ^TD3DFindDeviceSearch; TD3DFindDeviceSearch = packed record dwSize: DWORD; dwFlags: DWORD; bHardware: BOOL; dcmColorModel: TD3DColorModel; guid: TGUID; dwCaps: DWORD; dpcPrimCaps: TD3DPrimCaps; end; PD3DFindDeviceResult = ^TD3DFindDeviceResult; TD3DFindDeviceResult = packed record dwSize: DWORD; guid: TGUID; (* guid which matched *) ddHwDesc: TD3DDeviceDesc; (* hardware TD3DDeviceDesc *) ddSwDesc: TD3DDeviceDesc; (* software TD3DDeviceDesc *) end; (* * Description of execute buffer. *) PD3DExecuteBufferDesc = ^TD3DExecuteBufferDesc; TD3DExecuteBufferDesc = packed record dwSize: DWORD; (* size of this structure *) dwFlags: DWORD; (* flags indicating which fields are valid *) dwCaps: DWORD; (* capabilities of execute buffer *) dwBufferSize: DWORD; (* size of execute buffer data *) lpData: Pointer; (* pointer to actual data *) end; (* D3DEXECUTEBUFFER dwFlags indicating valid fields *) const D3DDEB_BUFSIZE = $00000001; (* buffer size valid *) D3DDEB_CAPS = $00000002; (* caps valid *) D3DDEB_LPDATA = $00000004; (* lpData valid *) (* D3DEXECUTEBUFFER dwCaps *) D3DDEBCAPS_SYSTEMMEMORY = $00000001; (* buffer in system memory *) D3DDEBCAPS_VIDEOMEMORY = $00000002; (* buffer in device memory *) D3DDEBCAPS_MEM = (D3DDEBCAPS_SYSTEMMEMORY or D3DDEBCAPS_VIDEOMEMORY); type PD3DDevInfo_TextureManager = ^TD3DDevInfo_TextureManager; TD3DDevInfo_TextureManager = packed record bThrashing: BOOL; (* indicates if thrashing *) dwApproxBytesDownloaded: DWORD; (* Approximate number of bytes downloaded by texture manager *) dwNumEvicts: DWORD; (* number of textures evicted *) dwNumVidCreates: DWORD; (* number of textures created in video memory *) dwNumTexturesUsed: DWORD; (* number of textures used *) dwNumUsedTexInVid: DWORD; (* number of used textures present in video memory *) dwWorkingSet: DWORD; (* number of textures in video memory *) dwWorkingSetBytes: DWORD; (* number of bytes in video memory *) dwTotalManaged: DWORD; (* total number of managed textures *) dwTotalBytes: DWORD; (* total number of bytes of managed textures *) dwLastPri: DWORD; (* priority of last texture evicted *) end; PD3DDevInfo_Texturing = ^TD3DDevInfo_Texturing; TD3DDevInfo_Texturing = packed record dwNumLoads: DWORD; (* counts Load() API calls *) dwApproxBytesLoaded: DWORD; (* Approximate number bytes loaded via Load() *) dwNumPreLoads: DWORD; (* counts PreLoad() API calls *) dwNumSet: DWORD; (* counts SetTexture() API calls *) dwNumCreates: DWORD; (* counts texture creates *) dwNumDestroys: DWORD; (* counts texture destroys *) dwNumSetPriorities: DWORD; (* counts SetPriority() API calls *) dwNumSetLODs: DWORD; (* counts SetLOD() API calls *) dwNumLocks: DWORD; (* counts number of texture locks *) dwNumGetDCs: DWORD; (* counts number of GetDCs to textures *) end; (*==========================================================================; * * * File: d3d.h * Content: Direct3D include file * ****************************************************************************) function D3DErrorString(Value: HResult) : string; (* * Interface IID's *) const (* * Internal Guid to distinguish requested MMX from MMX being used as an RGB rasterizer *) IID_IDirect3DRampDevice: TGUID = (D1:$F2086B20;D2:$259F;D3:$11CF;D4:($A3,$1A,$00,$AA,$00,$B9,$33,$56)); IID_IDirect3DRGBDevice: TGUID = (D1:$A4665C60;D2:$2673;D3:$11CF;D4:($A3,$1A,$00,$AA,$00,$B9,$33,$56)); IID_IDirect3DHALDevice: TGUID = (D1:$84E63dE0;D2:$46AA;D3:$11CF;D4:($81,$6F,$00,$00,$C0,$20,$15,$6E)); IID_IDirect3DMMXDevice: TGUID = (D1:$881949a1;D2:$d6f3;D3:$11d0;D4:($89,$ab,$00,$a0,$c9,$05,$41,$29)); IID_IDirect3DRefDevice: TGUID = (D1:$50936643;D2:$13e9;D3:$11d1;D4:($89,$aa,$00,$a0,$c9,$05,$41,$29)); IID_IDirect3DNullDevice: TGUID = (D1:$8767df22;D2:$bacc;D3:$11d1;D4:($89,$69,$00,$a0,$c9,$06,$29,$a8)); IID_IDirect3DTnLHalDevice: TGUID = '{f5049e78-4861-11d2-a407-00a0c90629a8}'; type IDirect3D = interface; IDirect3D2 = interface; IDirect3D3 = interface; IDirect3D7 = interface; IDirect3DDevice = interface; IDirect3DDevice2 = interface; IDirect3DDevice3 = interface; IDirect3DDevice7 = interface; IDirect3DExecuteBuffer = interface; IDirect3DLight = interface; IDirect3DMaterial = interface; IDirect3DMaterial2 = interface; IDirect3DMaterial3 = interface; IDirect3DTexture = interface; IDirect3DTexture2 = interface; IDirect3DViewport = interface; IDirect3DViewport2 = interface; IDirect3DViewport3 = interface; IDirect3DVertexBuffer = interface; IDirect3DVertexBuffer7 = interface; (* * Direct3D interfaces *) IDirect3D = interface (IUnknown) ['{3BBA0080-2421-11CF-A31A-00AA00B93356}'] (*** IDirect3D methods ***) function Initialize (lpREFIID: {REFIID} PGUID) : HResult; stdcall; function EnumDevices (lpEnumDevicesCallback: TD3DEnumDevicesCallback; lpUserArg: Pointer) : HResult; stdcall; function CreateLight (var lplpDirect3Dlight: IDirect3DLight; pUnkOuter: IUnknown) : HResult; stdcall; function CreateMaterial (var lplpDirect3DMaterial: IDirect3DMaterial; pUnkOuter: IUnknown) : HResult; stdcall; function CreateViewport (var lplpD3DViewport: IDirect3DViewport; pUnkOuter: IUnknown) : HResult; stdcall; function FindDevice (var lpD3DFDS: TD3DFindDeviceSearch; var lpD3DFDR: TD3DFindDeviceResult) : HResult; stdcall; end; IDirect3D2 = interface (IUnknown) ['{6aae1ec1-662a-11d0-889d-00aa00bbb76a}'] (*** IDirect3D2 methods ***) function EnumDevices(lpEnumDevicesCallback: TD3DEnumDevicesCallback; lpUserArg: pointer) : HResult; stdcall; function CreateLight (var lplpDirect3Dlight: IDirect3DLight; pUnkOuter: IUnknown) : HResult; stdcall; function CreateMaterial (var lplpDirect3DMaterial2: IDirect3DMaterial2; pUnkOuter: IUnknown) : HResult; stdcall; function CreateViewport (var lplpD3DViewport2: IDirect3DViewport2; pUnkOuter: IUnknown) : HResult; stdcall; function FindDevice (var lpD3DFDS: TD3DFindDeviceSearch; var lpD3DFDR: TD3DFindDeviceResult) : HResult; stdcall; function CreateDevice (const rclsid: TRefClsID; lpDDS: IDirectDrawSurface; out lplpD3DDevice2: IDirect3DDevice2) : HResult; stdcall; end; IDirect3D3 = interface (IUnknown) ['{bb223240-e72b-11d0-a9b4-00aa00c0993e}'] (*** IDirect3D3 methods ***) function EnumDevices(lpEnumDevicesCallback: TD3DEnumDevicesCallback; lpUserArg: pointer) : HResult; stdcall; function CreateLight (var lplpDirect3Dlight: IDirect3DLight; pUnkOuter: IUnknown) : HResult; stdcall; function CreateMaterial (var lplpDirect3DMaterial3: IDirect3DMaterial3; pUnkOuter: IUnknown) : HResult; stdcall; function CreateViewport (var lplpD3DViewport3: IDirect3DViewport3; pUnkOuter: IUnknown) : HResult; stdcall; function FindDevice (var lpD3DFDS: TD3DFindDeviceSearch; var lpD3DFDR: TD3DFindDeviceResult) : HResult; stdcall; function CreateDevice (const rclsid: TRefClsID; lpDDS: IDirectDrawSurface4; out lplpD3DDevice: IDirect3DDevice3; pUnkOuter: IUnknown) : HResult; stdcall; function CreateVertexBuffer (var lpVBDesc: TD3DVertexBufferDesc; var lpD3DVertexBuffer: IDirect3DVertexBuffer; dwFlags: DWORD; pUnkOuter: IUnknown) : HResult; stdcall; function EnumZBufferFormats (const riidDevice: TRefClsID; lpEnumCallback: TD3DEnumPixelFormatsCallback; lpContext: pointer) : HResult; stdcall; function EvictManagedTextures : HResult; stdcall; end; IDirect3D7 = interface (IUnknown) ['{f5049e77-4861-11d2-a407-00a0c90629a8}'] (*** IDirect3D7 methods ***) function EnumDevices(lpEnumDevicesCallback: TD3DEnumDevicesCallback7; lpUserArg: pointer) : HResult; stdcall; function CreateDevice (const rclsid: TGUID; lpDDS: IDirectDrawSurface7; out lplpD3DDevice: IDirect3DDevice7) : HResult; stdcall; function CreateVertexBuffer (const lpVBDesc: TD3DVertexBufferDesc; out lplpD3DVertexBuffer: IDirect3DVertexBuffer7; dwFlags: DWORD) : HResult; stdcall; function EnumZBufferFormats (const riidDevice: TGUID; lpEnumCallback: TD3DEnumPixelFormatsCallback; lpContext: pointer) : HResult; stdcall; function EvictManagedTextures : HResult; stdcall; end; (* * Direct3D Device interfaces *) IDirect3DDevice = interface (IUnknown) ['{64108800-957d-11d0-89ab-00a0c9054129}'] (*** IDirect3DDevice methods ***) function Initialize (lpd3d: IDirect3D; lpGUID: PGUID; var lpd3ddvdesc: TD3DDeviceDesc) : HResult; stdcall; function GetCaps (var lpD3DHWDevDesc: TD3DDeviceDesc; var lpD3DHELDevDesc: TD3DDeviceDesc) : HResult; stdcall; function SwapTextureHandles (lpD3DTex1: IDirect3DTexture; lpD3DTex2: IDirect3DTexture) : HResult; stdcall; function CreateExecuteBuffer (var lpDesc: TD3DExecuteBufferDesc ; var lplpDirect3DExecuteBuffer: IDirect3DExecuteBuffer; pUnkOuter: IUnknown) : HResult; stdcall; function GetStats (var lpD3DStats: TD3DStats) : HResult; stdcall; function Execute (lpDirect3DExecuteBuffer: IDirect3DExecuteBuffer; lpDirect3DViewport: IDirect3DViewport; dwFlags: DWORD) : HResult; stdcall; function AddViewport (lpDirect3DViewport: IDirect3DViewport) : HResult; stdcall; function DeleteViewport (lpDirect3DViewport: IDirect3DViewport) : HResult; stdcall; function NextViewport (lpDirect3DViewport: IDirect3DViewport; var lplpDirect3DViewport: IDirect3DViewport; dwFlags: DWORD) : HResult; stdcall; function Pick (lpDirect3DExecuteBuffer: IDirect3DExecuteBuffer; lpDirect3DViewport: IDirect3DViewport; dwFlags: DWORD; var lpRect: TD3DRect) : HResult; stdcall; function GetPickRecords (var lpCount: DWORD; var lpD3DPickRec: TD3DPickRecord) : HResult; stdcall; function EnumTextureFormats (lpd3dEnumTextureProc: TD3DEnumTextureFormatsCallback; lpArg: Pointer) : HResult; stdcall; function CreateMatrix (var lpD3DMatHandle: TD3DMatrixHandle) : HResult; stdcall; function SetMatrix (d3dMatHandle: TD3DMatrixHandle; var lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function GetMatrix (var lpD3DMatHandle: TD3DMatrixHandle; var lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function DeleteMatrix (d3dMatHandle: TD3DMatrixHandle) : HResult; stdcall; function BeginScene: HResult; stdcall; function EndScene: HResult; stdcall; function GetDirect3D (var lpD3D: IDirect3D) : HResult; stdcall; end; IDirect3DDevice2 = interface (IUnknown) ['{93281501-8cf8-11d0-89ab-00a0c9054129}'] (*** IDirect3DDevice2 methods ***) function GetCaps (var lpD3DHWDevDesc: TD3DDeviceDesc; var lpD3DHELDevDesc: TD3DDeviceDesc) : HResult; stdcall; function SwapTextureHandles (lpD3DTex1: IDirect3DTexture2; lpD3DTex2: IDirect3DTexture2) : HResult; stdcall; function GetStats (var lpD3DStats: TD3DStats) : HResult; stdcall; function AddViewport (lpDirect3DViewport2: IDirect3DViewport2) : HResult; stdcall; function DeleteViewport (lpDirect3DViewport: IDirect3DViewport2) : HResult; stdcall; function NextViewport (lpDirect3DViewport: IDirect3DViewport2; var lplpDirect3DViewport: IDirect3DViewport2; dwFlags: DWORD) : HResult; stdcall; function EnumTextureFormats ( lpd3dEnumTextureProc: TD3DEnumTextureFormatsCallback; lpArg: Pointer) : HResult; stdcall; function BeginScene: HResult; stdcall; function EndScene: HResult; stdcall; function GetDirect3D (var lpD3D: IDirect3D2) : HResult; stdcall; (*** DrawPrimitive API ***) function SetCurrentViewport (lpd3dViewport2: IDirect3DViewport2) : HResult; stdcall; function GetCurrentViewport (var lplpd3dViewport2: IDirect3DViewport2) : HResult; stdcall; function SetRenderTarget (lpNewRenderTarget: IDirectDrawSurface) : HResult; stdcall; function GetRenderTarget (var lplpNewRenderTarget: IDirectDrawSurface) : HResult; stdcall; function Begin_ (d3dpt: TD3DPrimitiveType; d3dvt: TD3DVertexType; dwFlags: DWORD) : HResult; stdcall; function BeginIndexed (dptPrimitiveType: TD3DPrimitiveType; dvtVertexType: TD3DVertexType; lpvVertices: pointer; dwNumVertices: DWORD; dwFlags: DWORD) : HResult; stdcall; function Vertex (lpVertexType: pointer) : HResult; stdcall; function Index (wVertexIndex: WORD) : HResult; stdcall; function End_ (dwFlags: DWORD) : HResult; stdcall; function GetRenderState (dwRenderStateType: TD3DRenderStateType; var lpdwRenderState) : HResult; stdcall; function SetRenderState (dwRenderStateType: TD3DRenderStateType; dwRenderState: DWORD) : HResult; stdcall; function GetLightState (dwLightStateType: TD3DLightStateType; var lpdwLightState) : HResult; stdcall; function SetLightState (dwLightStateType: TD3DLightStateType; dwLightState: DWORD) : HResult; stdcall; function SetTransform (dtstTransformStateType: TD3DTransformStateType; var lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function GetTransform (dtstTransformStateType: TD3DTransformStateType; var lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function MultiplyTransform (dtstTransformStateType: TD3DTransformStateType; var lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function DrawPrimitive (dptPrimitiveType: TD3DPrimitiveType; dvtVertexType: TD3DVertexType; var lpvVertices; dwVertexCount, dwFlags: DWORD) : HResult; stdcall; function DrawIndexedPrimitive (dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc: DWORD; lpvVertices: pointer; dwVertexCount: DWORD; var lpwIndices: WORD; dwIndexCount, dwFlags: DWORD) : HResult; stdcall; function SetClipStatus (var lpD3DClipStatus: TD3DClipStatus) : HResult; stdcall; function GetClipStatus (var lpD3DClipStatus: TD3DClipStatus) : HResult; stdcall; end; IDirect3DDevice3 = interface (IUnknown) ['{b0ab3b60-33d7-11d1-a981-00c04fd7b174}'] (*** IDirect3DDevice2 methods ***) function GetCaps (var lpD3DHWDevDesc: TD3DDeviceDesc; var lpD3DHELDevDesc: TD3DDeviceDesc) : HResult; stdcall; function GetStats (var lpD3DStats: TD3DStats) : HResult; stdcall; function AddViewport (lpDirect3DViewport: IDirect3DViewport3) : HResult; stdcall; function DeleteViewport (lpDirect3DViewport: IDirect3DViewport3) : HResult; stdcall; function NextViewport (lpDirect3DViewport: IDirect3DViewport3; var lplpAnotherViewport: IDirect3DViewport3; dwFlags: DWORD) : HResult; stdcall; function EnumTextureFormats ( lpd3dEnumPixelProc: TD3DEnumPixelFormatsCallback; lpArg: Pointer) : HResult; stdcall; function BeginScene: HResult; stdcall; function EndScene: HResult; stdcall; function GetDirect3D (var lpD3D: IDirect3D3) : HResult; stdcall; function SetCurrentViewport (lpd3dViewport: IDirect3DViewport3) : HResult; stdcall; function GetCurrentViewport (var lplpd3dViewport: IDirect3DViewport3) : HResult; stdcall; function SetRenderTarget (lpNewRenderTarget: IDirectDrawSurface4) : HResult; stdcall; function GetRenderTarget (var lplpNewRenderTarget: IDirectDrawSurface4) : HResult; stdcall; function Begin_ (d3dpt: TD3DPrimitiveType; dwVertexTypeDesc: DWORD; dwFlags: DWORD) : HResult; stdcall; function BeginIndexed (dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc: DWORD; lpvVertices: pointer; dwNumVertices: DWORD; dwFlags: DWORD) : HResult; stdcall; function Vertex (lpVertex: pointer) : HResult; stdcall; function Index (wVertexIndex: WORD) : HResult; stdcall; function End_ (dwFlags: DWORD) : HResult; stdcall; function GetRenderState (dwRenderStateType: TD3DRenderStateType; var lpdwRenderState) : HResult; stdcall; function SetRenderState (dwRenderStateType: TD3DRenderStateType; dwRenderState: DWORD) : HResult; stdcall; function GetLightState (dwLightStateType: TD3DLightStateType; var lpdwLightState) : HResult; stdcall; function SetLightState (dwLightStateType: TD3DLightStateType; dwLightState: DWORD) : HResult; stdcall; function SetTransform (dtstTransformStateType: TD3DTransformStateType; var lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function GetTransform (dtstTransformStateType: TD3DTransformStateType; var lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function MultiplyTransform (dtstTransformStateType: TD3DTransformStateType; var lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function DrawPrimitive (dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc: DWORD; const lpvVertices; dwVertexCount, dwFlags: DWORD) : HResult; stdcall; function DrawIndexedPrimitive (dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc: DWORD; const lpvVertices; dwVertexCount: DWORD; var lpwIndices: WORD; dwIndexCount, dwFlags: DWORD) : HResult; stdcall; function SetClipStatus (var lpD3DClipStatus: TD3DClipStatus) : HResult; stdcall; function GetClipStatus (var lpD3DClipStatus: TD3DClipStatus) : HResult; stdcall; function DrawPrimitiveStrided (dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc : DWORD; var lpVertexArray: TD3DDrawPrimitiveStridedData; dwVertexCount, dwFlags: DWORD) : HResult; stdcall; function DrawIndexedPrimitiveStrided (dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc : DWORD; var lpVertexArray: TD3DDrawPrimitiveStridedData; dwVertexCount: DWORD; var lpwIndices: WORD; dwIndexCount, dwFlags: DWORD) : HResult; stdcall; function DrawPrimitiveVB (dptPrimitiveType: TD3DPrimitiveType; lpd3dVertexBuffer: IDirect3DVertexBuffer; dwStartVertex, dwNumVertices, dwFlags: DWORD) : HResult; stdcall; function DrawIndexedPrimitiveVB (dptPrimitiveType: TD3DPrimitiveType; lpd3dVertexBuffer: IDirect3DVertexBuffer; var lpwIndices: WORD; dwIndexCount, dwFlags: DWORD) : HResult; stdcall; function ComputeSphereVisibility (var lpCenters: TD3DVector; var lpRadii: TD3DValue; dwNumSpheres, dwFlags: DWORD; var lpdwReturnValues: DWORD) : HResult; stdcall; function GetTexture (dwStage: DWORD; var lplpTexture: IDirect3DTexture2) : HResult; stdcall; function SetTexture (dwStage: DWORD; lplpTexture: IDirect3DTexture2) : HResult; stdcall; function GetTextureStageState (dwStage: DWORD; dwState: TD3DTextureStageStateType; var lpdwValue: DWORD) : HResult; stdcall; function SetTextureStageState (dwStage: DWORD; dwState: TD3DTextureStageStateType; lpdwValue: DWORD) : HResult; stdcall; function ValidateDevice (var lpdwExtraPasses: DWORD) : HResult; stdcall; end; IDirect3DDevice7 = interface (IUnknown) ['{f5049e79-4861-11d2-a407-00a0c90629a8}'] (*** IDirect3DDevice7 methods ***) function GetCaps(out lpD3DDevDesc: TD3DDeviceDesc7) : HResult; stdcall; function EnumTextureFormats(lpd3dEnumPixelProc: TD3DEnumPixelFormatsCallback; lpArg: Pointer) : HResult; stdcall; function BeginScene: HResult; stdcall; function EndScene: HResult; stdcall; function GetDirect3D(out lpD3D: IDirect3D7) : HResult; stdcall; function SetRenderTarget(lpNewRenderTarget: IDirectDrawSurface7; dwFlags: DWORD) : HResult; stdcall; function GetRenderTarget(out lplpRenderTarget: IDirectDrawSurface7) : HResult; stdcall; function Clear(dwCount: DWORD; lpRects: PD3DRect; dwFlags, dwColor: DWORD; dvZ: TD3DValue; dwStencil: DWORD) : HResult; stdcall; function SetTransform(dtstTransformStateType: TD3DTransformStateType; const lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function GetTransform(dtstTransformStateType: TD3DTransformStateType; out lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function SetViewport(const lpViewport: TD3DViewport7) : HResult; stdcall; function MultiplyTransform(dtstTransformStateType: TD3DTransformStateType; const lpD3DMatrix: TD3DMatrix) : HResult; stdcall; function GetViewport(out lpViewport: TD3DViewport7) : HResult; stdcall; function SetMaterial(const lpMaterial: TD3DMaterial7) : HResult; stdcall; function GetMaterial(out lpMaterial: TD3DMaterial7) : HResult; stdcall; function SetLight(dwLightIndex: DWORD; const lpLight: TD3DLight7) : HResult; stdcall; function GetLight(dwLightIndex: DWORD; out lpLight: TD3DLight7) : HResult; stdcall; function SetRenderState(dwRenderStateType: TD3DRenderStateType; dwRenderState: DWORD) : HResult; stdcall; function GetRenderState(dwRenderStateType: TD3DRenderStateType; out dwRenderState: DWORD) : HResult; stdcall; function BeginStateBlock : HResult; stdcall; function EndStateBlock(out lpdwBlockHandle: DWORD) : HResult; stdcall; function PreLoad(lpddsTexture: IDirectDrawSurface7) : HResult; stdcall; function DrawPrimitive(dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc: DWORD; const lpvVertices; dwVertexCount, dwFlags: DWORD) : HResult; stdcall; function DrawIndexedPrimitive(dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc: DWORD; const lpvVertices; dwVertexCount: DWORD; var lpwIndices: WORD; dwIndexCount, dwFlags: DWORD) : HResult; stdcall; function SetClipStatus(const lpD3DClipStatus: TD3DClipStatus) : HResult; stdcall; function GetClipStatus(out lpD3DClipStatus: TD3DClipStatus) : HResult; stdcall; function DrawPrimitiveStrided(dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc : DWORD; const lpVertexArray: TD3DDrawPrimitiveStridedData; dwVertexCount, dwFlags: DWORD) : HResult; stdcall; function DrawIndexedPrimitiveStrided(dptPrimitiveType: TD3DPrimitiveType; dwVertexTypeDesc : DWORD; const lpVertexArray: TD3DDrawPrimitiveStridedData; dwVertexCount: DWORD; var lpwIndices: WORD; dwIndexCount, dwFlags: DWORD) : HResult; stdcall; function DrawPrimitiveVB(dptPrimitiveType: TD3DPrimitiveType; lpd3dVertexBuffer: IDirect3DVertexBuffer7; dwStartVertex, dwNumVertices, dwFlags: DWORD) : HResult; stdcall; function DrawIndexedPrimitiveVB(dptPrimitiveType: TD3DPrimitiveType; lpd3dVertexBuffer: IDirect3DVertexBuffer7; dwStartVertex, dwNumVertices: DWORD; var lpwIndices: WORD; dwIndexCount, dwFlags: DWORD) : HResult; stdcall; function ComputeSphereVisibility(const lpCenters: TD3DVector; var lpRadii: TD3DValue; dwNumSpheres, dwFlags: DWORD; var lpdwReturnValues: DWORD) : HResult; stdcall; function GetTexture(dwStage: DWORD; out lplpTexture: IDirectDrawSurface7) : HResult; stdcall; function SetTexture(dwStage: DWORD; lpTexture: IDirectDrawSurface7) : HResult; stdcall; function GetTextureStageState(dwStage: DWORD; dwState: TD3DTextureStageStateType; out lpdwValue: DWORD) : HResult; stdcall; function SetTextureStageState(dwStage: DWORD; dwState: TD3DTextureStageStateType; lpdwValue: DWORD) : HResult; stdcall; function ValidateDevice(out lpdwExtraPasses: DWORD) : HResult; stdcall; function ApplyStateBlock(dwBlockHandle: DWORD) : HResult; stdcall; function CaptureStateBlock(dwBlockHandle: DWORD) : HResult; stdcall; function DeleteStateBlock(dwBlockHandle: DWORD) : HResult; stdcall; function CreateStateBlock(d3dsbType: TD3DStateBlockType; out lpdwBlockHandle: DWORD) : HResult; stdcall; function Load(lpDestTex: IDirectDrawSurface7; lpDestPoint: PPoint; lpSrcTex: IDirectDrawSurface7; lprcSrcRect: PRect; dwFlags: DWORD) : HResult; stdcall; function LightEnable(dwLightIndex: DWORD; bEnable: BOOL) : HResult; stdcall; function GetLightEnable(dwLightIndex: DWORD; out bEnable: BOOL) : HResult; stdcall; function SetClipPlane(dwIndex: DWORD; var pPlaneEquation: TD3DValue) : HResult; stdcall; function GetClipPlane(dwIndex: DWORD; out pPlaneEquation: TD3DValue) : HResult; stdcall; function GetInfo(dwDevInfoID: DWORD; pDevInfoStruct: Pointer; dwSize: DWORD) : HResult; stdcall; end; (* * Execute Buffer interface *) IDirect3DExecuteBuffer = interface (IUnknown) ['{4417C145-33AD-11CF-816F-0000C020156E}'] (*** IDirect3DExecuteBuffer methods ***) function Initialize (lpDirect3DDevice: IDirect3DDevice; var lpDesc: TD3DExecuteBufferDesc) : HResult; stdcall; function Lock (var lpDesc: TD3DExecuteBufferDesc) : HResult; stdcall; function Unlock: HResult; stdcall; function SetExecuteData (var lpData: TD3DExecuteData) : HResult; stdcall; function GetExecuteData (var lpData: TD3DExecuteData) : HResult; stdcall; function Validate (var lpdwOffset: DWORD; lpFunc: TD3DValidateCallback; lpUserArg: Pointer; dwReserved: DWORD) : HResult; stdcall; (*** Warning! Optimize is defined differently in the header files and the online documentation ***) function Optimize (dwFlags: DWORD) : HResult; stdcall; end; (* * Light interfaces *) IDirect3DLight = interface (IUnknown) ['{4417C142-33AD-11CF-816F-0000C020156E}'] (*** IDirect3DLight methods ***) function Initialize (lpDirect3D: IDirect3D) : HResult; stdcall; function SetLight (var lpLight: TD3DLight2) : HResult; stdcall; function GetLight (var lpLight: TD3DLight2) : HResult; stdcall; end; (* * Material interfaces *) IDirect3DMaterial = interface (IUnknown) ['{4417C144-33AD-11CF-816F-0000C020156E}'] (*** IDirect3DMaterial methods ***) function Initialize (lpDirect3D: IDirect3D) : HResult; stdcall; function SetMaterial (var lpMat: TD3DMaterial) : HResult; stdcall; function GetMaterial (var lpMat: TD3DMaterial) : HResult; stdcall; function GetHandle (lpDirect3DDevice: IDirect3DDevice; var lpHandle: TD3DMaterialHandle) : HResult; stdcall; function Reserve: HResult; stdcall; function Unreserve: HResult; stdcall; end; IDirect3DMaterial2 = interface (IUnknown) ['{93281503-8cf8-11d0-89ab-00a0c9054129}'] (*** IDirect3DMaterial2 methods ***) function SetMaterial (var lpMat: TD3DMaterial) : HResult; stdcall; function GetMaterial (var lpMat: TD3DMaterial) : HResult; stdcall; function GetHandle (lpDirect3DDevice: IDirect3DDevice2; var lpHandle: TD3DMaterialHandle) : HResult; stdcall; end; IDirect3DMaterial3 = interface (IUnknown) ['{ca9c46f4-d3c5-11d1-b75a-00600852b312}'] (*** IDirect3DMaterial2 methods ***) function SetMaterial (var lpMat: TD3DMaterial) : HResult; stdcall; function GetMaterial (var lpMat: TD3DMaterial) : HResult; stdcall; function GetHandle (lpDirect3DDevice: IDirect3DDevice3; var lpHandle: TD3DMaterialHandle) : HResult; stdcall; end; (* * Texture interfaces *) IDirect3DTexture = interface (IUnknown) ['{2CDCD9E0-25A0-11CF-A31A-00AA00B93356}'] (*** IDirect3DTexture methods ***) function Initialize (lpD3DDevice: IDirect3DDevice; lpDDSurface: IDirectDrawSurface) : HResult; stdcall; function GetHandle (lpDirect3DDevice: IDirect3DDevice; var lpHandle: TD3DTextureHandle) : HResult; stdcall; function PaletteChanged (dwStart: DWORD; dwCount: DWORD) : HResult; stdcall; function Load (lpD3DTexture: IDirect3DTexture) : HResult; stdcall; function Unload: HResult; stdcall; end; IDirect3DTexture2 = interface (IUnknown) ['{93281502-8cf8-11d0-89ab-00a0c9054129}'] (*** IDirect3DTexture2 methods ***) function GetHandle (lpDirect3DDevice: IDirect3DDevice2; var lpHandle: TD3DTextureHandle) : HResult; stdcall; function PaletteChanged (dwStart: DWORD; dwCount: DWORD) : HResult; stdcall; function Load (lpD3DTexture: IDirect3DTexture2) : HResult; stdcall; end; (* * Viewport interfaces *) IDirect3DViewport = interface (IUnknown) ['{4417C146-33AD-11CF-816F-0000C020156E}'] (*** IDirect3DViewport methods ***) function Initialize (lpDirect3D: IDirect3D) : HResult; stdcall; function GetViewport (out lpData: TD3DViewport) : HResult; stdcall; function SetViewport (const lpData: TD3DViewport) : HResult; stdcall; function TransformVertices (dwVertexCount: DWORD; const lpData: TD3DTransformData; dwFlags: DWORD; out lpOffscreen: DWORD) : HResult; stdcall; function LightElements (dwElementCount: DWORD; var lpData: TD3DLightData) : HResult; stdcall; function SetBackground (hMat: TD3DMaterialHandle) : HResult; stdcall; function GetBackground (out hMat: TD3DMaterialHandle) : HResult; stdcall; function SetBackgroundDepth (lpDDSurface: IDirectDrawSurface) : HResult; stdcall; function GetBackgroundDepth (out lplpDDSurface: IDirectDrawSurface; out lpValid: BOOL) : HResult; stdcall; function Clear (dwCount: DWORD; const lpRects: TD3DRect; dwFlags: DWORD) : HResult; stdcall; function AddLight (lpDirect3DLight: IDirect3DLight) : HResult; stdcall; function DeleteLight (lpDirect3DLight: IDirect3DLight) : HResult; stdcall; function NextLight (lpDirect3DLight: IDirect3DLight; out lplpDirect3DLight: IDirect3DLight; dwFlags: DWORD) : HResult; stdcall; end; IDirect3DViewport2 = interface (IUnknown) ['{93281500-8cf8-11d0-89ab-00a0c9054129}'] (*** IDirect3DViewport2 methods ***) function Initialize (lpDirect3D: IDirect3D) : HResult; stdcall; function GetViewport (out lpData: TD3DViewport) : HResult; stdcall; function SetViewport (const lpData: TD3DViewport) : HResult; stdcall; function TransformVertices (dwVertexCount: DWORD; const lpData: TD3DTransformData; dwFlags: DWORD; out lpOffscreen: DWORD) : HResult; stdcall; function LightElements (dwElementCount: DWORD; var lpData: TD3DLightData) : HResult; stdcall; function SetBackground (hMat: TD3DMaterialHandle) : HResult; stdcall; function GetBackground (out hMat: TD3DMaterialHandle) : HResult; stdcall; function SetBackgroundDepth (lpDDSurface: IDirectDrawSurface) : HResult; stdcall; function GetBackgroundDepth (out lplpDDSurface: IDirectDrawSurface; out lpValid: BOOL) : HResult; stdcall; function Clear (dwCount: DWORD; const lpRects: TD3DRect; dwFlags: DWORD) : HResult; stdcall; function AddLight (lpDirect3DLight: IDirect3DLight) : HResult; stdcall; function DeleteLight (lpDirect3DLight: IDirect3DLight) : HResult; stdcall; function NextLight (lpDirect3DLight: IDirect3DLight; out lplpDirect3DLight: IDirect3DLight; dwFlags: DWORD) : HResult; stdcall; (*** IDirect3DViewport2 methods ***) function GetViewport2 (out lpData: TD3DViewport2) : HResult; stdcall; function SetViewport2 (const lpData: TD3DViewport2) : HResult; stdcall; end; IDirect3DViewport3 = interface (IUnknown) ['{b0ab3b61-33d7-11d1-a981-00c04fd7b174}'] (*** IDirect3DViewport3 methods ***) function Initialize (lpDirect3D: IDirect3D) : HResult; stdcall; function GetViewport (out lpData: TD3DViewport) : HResult; stdcall; function SetViewport (const lpData: TD3DViewport) : HResult; stdcall; function TransformVertices (dwVertexCount: DWORD; const lpData: TD3DTransformData; dwFlags: DWORD; out lpOffscreen: DWORD) : HResult; stdcall; function LightElements (dwElementCount: DWORD; var lpData: TD3DLightData) : HResult; stdcall; function SetBackground (hMat: TD3DMaterialHandle) : HResult; stdcall; function GetBackground (var hMat: TD3DMaterialHandle) : HResult; stdcall; function SetBackgroundDepth ( lpDDSurface: IDirectDrawSurface) : HResult; stdcall; function GetBackgroundDepth (out lplpDDSurface: IDirectDrawSurface; out lpValid: BOOL) : HResult; stdcall; function Clear (dwCount: DWORD; const lpRects: TD3DRect; dwFlags: DWORD) : HResult; stdcall; function AddLight (lpDirect3DLight: IDirect3DLight) : HResult; stdcall; function DeleteLight (lpDirect3DLight: IDirect3DLight) : HResult; stdcall; function NextLight (lpDirect3DLight: IDirect3DLight; out lplpDirect3DLight: IDirect3DLight; dwFlags: DWORD) : HResult; stdcall; function GetViewport2 (out lpData: TD3DViewport2) : HResult; stdcall; function SetViewport2 (const lpData: TD3DViewport2) : HResult; stdcall; function SetBackgroundDepth2 ( lpDDSurface: IDirectDrawSurface4) : HResult; stdcall; function GetBackgroundDepth2 (out lplpDDSurface: IDirectDrawSurface4; out lpValid: BOOL) : HResult; stdcall; function Clear2 (dwCount: DWORD; const lpRects: TD3DRect; dwFlags: DWORD; dwColor: DWORD; dvZ: TD3DValue; dwStencil: DWORD) : HResult; stdcall; end; IDirect3DVertexBuffer = interface (IUnknown) ['{7a503555-4a83-11d1-a5db-00a0c90367f8}'] (*** IDirect3DVertexBuffer methods ***) function Lock (dwFlags: DWORD; var lplpData: pointer; var lpdwSize: DWORD) : HResult; stdcall; function Unlock : HResult; stdcall; function ProcessVertices (dwVertexOp, dwDestIndex, dwCount: DWORD; lpSrcBuffer: IDirect3DVertexBuffer; dwSrcIndex: DWORD; lpD3DDevice: IDirect3DDevice3; dwFlags: DWORD) : HResult; stdcall; function GetVertexBufferDesc (var lpVBDesc: TD3DVertexBufferDesc) : HResult; stdcall; function Optimize(lpD3DDevice: IDirect3DDevice3; dwFlags: DWORD) : HResult; stdcall; end; IDirect3DVertexBuffer7 = interface (IUnknown) ['{f5049e7d-4861-11d2-a407-00a0c90629a8}'] (*** IDirect3DVertexBuffer methods ***) function Lock (dwFlags: DWORD; out lplpData: Pointer; out lpdwSize: DWORD) : HResult; stdcall; function Unlock : HResult; stdcall; function ProcessVertices (dwVertexOp, dwDestIndex, dwCount: DWORD; lpSrcBuffer: IDirect3DVertexBuffer7; dwSrcIndex: DWORD; lpD3DDevice: IDirect3DDevice7; dwFlags: DWORD) : HResult; stdcall; function GetVertexBufferDesc (out lpVBDesc: TD3DVertexBufferDesc) : HResult; stdcall; function Optimize(lpD3DDevice: IDirect3DDevice7; dwFlags: DWORD) : HResult; stdcall; function ProcessVerticesStrided(dwVertexOp, dwDestIndex, dwCount: DWORD; lpVertexArray: TD3DDrawPrimitiveStridedData; dwVertexTypeDesc: DWORD; lpD3DDevice: IDirect3DDevice7; dwFlags: DWORD) : HResult; stdcall; end; type IID_IDirect3D = IDirect3D; IID_IDirect3D2 = IDirect3D2; IID_IDirect3D3 = IDirect3D3; IID_IDirect3D7 = IDirect3D7; IID_IDirect3DDevice = IDirect3DDevice; IID_IDirect3DDevice2 = IDirect3DDevice2; IID_IDirect3DDevice3 = IDirect3DDevice3; IID_IDirect3DDevice7 = IDirect3DDevice7; IID_IDirect3DTexture = IDirect3DTexture; IID_IDirect3DTexture2 = IDirect3DTexture2; IID_IDirect3DLight = IDirect3DLight; IID_IDirect3DMaterial = IDirect3DMaterial; IID_IDirect3DMaterial2 = IDirect3DMaterial2; IID_IDirect3DMaterial3 = IDirect3DMaterial3; IID_IDirect3DExecuteBuffer = IDirect3DExecuteBuffer; IID_IDirect3DViewport = IDirect3DViewport; IID_IDirect3DViewport2 = IDirect3DViewport2; IID_IDirect3DViewport3 = IDirect3DViewport3; IID_IDirect3DVertexBuffer = IDirect3DVertexBuffer; IID_IDirect3DVertexBuffer7 = IDirect3DVertexBuffer7; const (**************************************************************************** * * Flags for IDirect3DDevice::NextViewport * ****************************************************************************) (* * Return the next viewport *) D3DNEXT_NEXT = $00000001; (* * Return the first viewport *) D3DNEXT_HEAD = $00000002; (* * Return the last viewport *) D3DNEXT_TAIL = $00000004; (**************************************************************************** * * Flags for DrawPrimitive/DrawIndexedPrimitive * Also valid for Begin/BeginIndexed * Also valid for VertexBuffer::CreateVertexBuffer ****************************************************************************) (* * Wait until the device is ready to draw the primitive * This will cause DP to not return DDERR_WASSTILLDRAWING *) D3DDP_WAIT = $00000001; (* * Hint that it is acceptable to render the primitive out of order. *) D3DDP_OUTOFORDER = $00000002; (* * Hint that the primitives have been clipped by the application. *) D3DDP_DONOTCLIP = $00000004; (* * Hint that the extents need not be updated. *) D3DDP_DONOTUPDATEEXTENTS = $00000008; (* * Hint that the lighting should not be applied on vertices. *) D3DDP_DONOTLIGHT = $00000010; (* * Direct3D Errors * DirectDraw error codes are used when errors not specified here. *) const MAKE_DDHRESULT = HResult($88760000); D3D_OK = DD_OK; D3DERR_BADMAJORVERSION = MAKE_DDHRESULT + 700; D3DERR_BADMINORVERSION = MAKE_DDHRESULT + 701; (* * An invalid device was requested by the application. *) D3DERR_INVALID_DEVICE = MAKE_DDHRESULT + 705; D3DERR_INITFAILED = MAKE_DDHRESULT + 706; (* * SetRenderTarget attempted on a device that was * QI'd off the render target. *) D3DERR_DEVICEAGGREGATED = MAKE_DDHRESULT + 707; D3DERR_EXECUTE_CREATE_FAILED = MAKE_DDHRESULT + 710; D3DERR_EXECUTE_DESTROY_FAILED = MAKE_DDHRESULT + 711; D3DERR_EXECUTE_LOCK_FAILED = MAKE_DDHRESULT + 712; D3DERR_EXECUTE_UNLOCK_FAILED = MAKE_DDHRESULT + 713; D3DERR_EXECUTE_LOCKED = MAKE_DDHRESULT + 714; D3DERR_EXECUTE_NOT_LOCKED = MAKE_DDHRESULT + 715; D3DERR_EXECUTE_FAILED = MAKE_DDHRESULT + 716; D3DERR_EXECUTE_CLIPPED_FAILED = MAKE_DDHRESULT + 717; D3DERR_TEXTURE_NO_SUPPORT = MAKE_DDHRESULT + 720; D3DERR_TEXTURE_CREATE_FAILED = MAKE_DDHRESULT + 721; D3DERR_TEXTURE_DESTROY_FAILED = MAKE_DDHRESULT + 722; D3DERR_TEXTURE_LOCK_FAILED = MAKE_DDHRESULT + 723; D3DERR_TEXTURE_UNLOCK_FAILED = MAKE_DDHRESULT + 724; D3DERR_TEXTURE_LOAD_FAILED = MAKE_DDHRESULT + 725; D3DERR_TEXTURE_SWAP_FAILED = MAKE_DDHRESULT + 726; D3DERR_TEXTURE_LOCKED = MAKE_DDHRESULT + 727; D3DERR_TEXTURE_NOT_LOCKED = MAKE_DDHRESULT + 728; D3DERR_TEXTURE_GETSURF_FAILED = MAKE_DDHRESULT + 729; D3DERR_MATRIX_CREATE_FAILED = MAKE_DDHRESULT + 730; D3DERR_MATRIX_DESTROY_FAILED = MAKE_DDHRESULT + 731; D3DERR_MATRIX_SETDATA_FAILED = MAKE_DDHRESULT + 732; D3DERR_MATRIX_GETDATA_FAILED = MAKE_DDHRESULT + 733; D3DERR_SETVIEWPORTDATA_FAILED = MAKE_DDHRESULT + 734; D3DERR_INVALIDCURRENTVIEWPORT = MAKE_DDHRESULT + 735; D3DERR_INVALIDPRIMITIVETYPE = MAKE_DDHRESULT + 736; D3DERR_INVALIDVERTEXTYPE = MAKE_DDHRESULT + 737; D3DERR_TEXTURE_BADSIZE = MAKE_DDHRESULT + 738; D3DERR_INVALIDRAMPTEXTURE = MAKE_DDHRESULT + 739; D3DERR_MATERIAL_CREATE_FAILED = MAKE_DDHRESULT + 740; D3DERR_MATERIAL_DESTROY_FAILED = MAKE_DDHRESULT + 741; D3DERR_MATERIAL_SETDATA_FAILED = MAKE_DDHRESULT + 742; D3DERR_MATERIAL_GETDATA_FAILED = MAKE_DDHRESULT + 743; D3DERR_INVALIDPALETTE = MAKE_DDHRESULT + 744; D3DERR_ZBUFF_NEEDS_SYSTEMMEMORY = MAKE_DDHRESULT + 745; D3DERR_ZBUFF_NEEDS_VIDEOMEMORY = MAKE_DDHRESULT + 746; D3DERR_SURFACENOTINVIDMEM = MAKE_DDHRESULT + 747; D3DERR_LIGHT_SET_FAILED = MAKE_DDHRESULT + 750; D3DERR_LIGHTHASVIEWPORT = MAKE_DDHRESULT + 751; D3DERR_LIGHTNOTINTHISVIEWPORT = MAKE_DDHRESULT + 752; D3DERR_SCENE_IN_SCENE = MAKE_DDHRESULT + 760; D3DERR_SCENE_NOT_IN_SCENE = MAKE_DDHRESULT + 761; D3DERR_SCENE_BEGIN_FAILED = MAKE_DDHRESULT + 762; D3DERR_SCENE_END_FAILED = MAKE_DDHRESULT + 763; D3DERR_INBEGIN = MAKE_DDHRESULT + 770; D3DERR_NOTINBEGIN = MAKE_DDHRESULT + 771; D3DERR_NOVIEWPORTS = MAKE_DDHRESULT + 772; D3DERR_VIEWPORTDATANOTSET = MAKE_DDHRESULT + 773; D3DERR_VIEWPORTHASNODEVICE = MAKE_DDHRESULT + 774; D3DERR_NOCURRENTVIEWPORT = MAKE_DDHRESULT + 775; D3DERR_INVALIDVERTEXFORMAT = MAKE_DDHRESULT + 2048; (* * Attempted to CreateTexture on a surface that had a color key *) D3DERR_COLORKEYATTACHED = MAKE_DDHRESULT + 2050; D3DERR_VERTEXBUFFEROPTIMIZED = MAKE_DDHRESULT + 2060; D3DERR_VBUF_CREATE_FAILED = MAKE_DDHRESULT + 2061; D3DERR_VERTEXBUFFERLOCKED = MAKE_DDHRESULT + 2062; D3DERR_ZBUFFER_NOTPRESENT = MAKE_DDHRESULT + 2070; D3DERR_STENCILBUFFER_NOTPRESENT = MAKE_DDHRESULT + 2071; D3DERR_WRONGTEXTUREFORMAT = MAKE_DDHRESULT + 2072; D3DERR_UNSUPPORTEDCOLOROPERATION = MAKE_DDHRESULT + 2073; D3DERR_UNSUPPORTEDCOLORARG = MAKE_DDHRESULT + 2074; D3DERR_UNSUPPORTEDALPHAOPERATION = MAKE_DDHRESULT + 2075; D3DERR_UNSUPPORTEDALPHAARG = MAKE_DDHRESULT + 2076; D3DERR_TOOMANYOPERATIONS = MAKE_DDHRESULT + 2077; D3DERR_CONFLICTINGTEXTUREFILTER = MAKE_DDHRESULT + 2078; D3DERR_UNSUPPORTEDFACTORVALUE = MAKE_DDHRESULT + 2079; D3DERR_CONFLICTINGRENDERSTATE = MAKE_DDHRESULT + 2081; D3DERR_UNSUPPORTEDTEXTUREFILTER = MAKE_DDHRESULT + 2082; D3DERR_TOOMANYPRIMITIVES = MAKE_DDHRESULT + 2083; D3DERR_INVALIDMATRIX = MAKE_DDHRESULT + 2084; D3DERR_TOOMANYVERTICES = MAKE_DDHRESULT + 2085; D3DERR_CONFLICTINGTEXTUREPALETTE = MAKE_DDHRESULT + 2086; D3DERR_INVALIDSTATEBLOCK = MAKE_DDHRESULT + 2100; D3DERR_INBEGINSTATEBLOCK = MAKE_DDHRESULT + 2101; D3DERR_NOTINBEGINSTATEBLOCK = MAKE_DDHRESULT + 2102; procedure DisableFPUExceptions; procedure EnableFPUExceptions; (*************************************************************************** * * Copyright (C) 1998-1999 Microsoft Corporation. All Rights Reserved. * * File: dxfile.h * * Content: DirectX File public header file * ***************************************************************************) var DXFileDLL : HMODULE; function DXFileErrorString(Value: HResult) : string; type TDXFileFormat = ( DXFILEFORMAT_BINARY, DXFILEFORMAT_TEXT, DXFILEFORMAT_COMPRESSED ); TDXFileLoadOptions = ( DXFILELOAD_FROMFILE, DXFILELOAD_FROMRESOURCE, DXFILELOAD_FROMMEMORY, DXFILELOAD_INVALID_3, DXFILELOAD_FROMSTREAM, DXFILELOAD_INVALID_5, DXFILELOAD_INVALID_6, DXFILELOAD_INVALID_7, DXFILELOAD_FROMURL ); PDXFileLoadResource = ^TDXFileLoadResource; TDXFileLoadResource = packed record hModule: HModule; lpName: PAnsiChar; lpType: PAnsiChar; end; PDXFileLoadMemory = ^TDXFileLoadMemory; TDXFileLoadMemory = packed record lpMemory: Pointer; dSize: DWORD; end; (* * DirectX File object types. *) IDirectXFile = interface; IDirectXFileEnumObject = interface; IDirectXFileSaveObject = interface; IDirectXFileObject = interface; IDirectXFileData = interface; IDirectXFileDataReference = interface; IDirectXFileBinary = interface; (* * DirectX File interfaces. *) IDirectXFile = interface (IUnknown) ['{3d82ab40-62da-11cf-ab39-0020af71e433}'] function CreateEnumObject (pvSource: Pointer; dwLoadOptions: TDXFileLoadOptions; var ppEnumObj: IDirectXFileEnumObject) : HResult; stdcall; function CreateSaveObject (szFileName: PChar; dwFileFormat: TDXFileFormat; var ppSaveObj: IDirectXFileSaveObject) : HResult; stdcall; function RegisterTemplates (pvData: Pointer; cbSize: DWORD) : HResult; stdcall; end; IDirectXFileEnumObject = interface (IUnknown) ['{3d82ab41-62da-11cf-ab39-0020af71e433}'] function GetNextDataObject (var ppDataObj: IDirectXFileData) : HResult; stdcall; function GetDataObjectById (const rguid: TGUID; var ppDataObj: IDirectXFileData) : HResult; stdcall; function GetDataObjectByName (szName: PChar; var ppDataObj: IDirectXFileData) : HResult; stdcall; end; IDirectXFileSaveObject = interface (IUnknown) ['{3d82ab42-62da-11cf-ab39-0020af71e433}'] function SaveTemplates (cTemplates: DWORD; var ppguidTemplates: PGUID) : HResult; stdcall; function CreateDataObject (const rguidTemplate: TGUID; szName: PChar; pguid: PGUID; cbSize: DWORD; pvData: Pointer; var ppDataObj: IDirectXFileData) : HResult; stdcall; function SaveData (pDataObj: IDirectXFileData) : HResult; stdcall; end; IDirectXFileObject = interface (IUnknown) ['{3d82ab43-62da-11cf-ab39-0020af71e433}'] function GetName (pstrNameBuf: PChar; var dwBufLen: DWORD) : HResult; stdcall; function GetId (var pGuidBuf: TGUID) : HResult; stdcall; end; IDirectXFileData = interface (IDirectXFileObject) ['{3d82ab44-62da-11cf-ab39-0020af71e433}'] function GetData (szMember: PChar; var pcbSize: DWORD; var ppvData: Pointer) : HResult; stdcall; function GetType (var ppguid: PGUID) : HResult; stdcall; function GetNextObject (var ppChildObj: IDirectXFileObject) : HResult; stdcall; function AddDataObject (pDataObj: IDirectXFileData) : HResult; stdcall; function AddDataReference (szRef: PChar; pguidRef: PGUID) : HResult; stdcall; function AddBinaryObject (szName: PChar; pguid: PGUID; szMimeType: PChar; pvData: Pointer; cbSize: DWORD) : HResult; stdcall; end; IDirectXFileDataReference = interface (IDirectXFileObject) ['{3d82ab45-62da-11cf-ab39-0020af71e433}'] function Resolve (var ppDataObj: IDirectXFileData) : HResult; stdcall; end; IDirectXFileBinary = interface (IDirectXFileObject) ['{3d82ab46-62da-11cf-ab39-0020af71e433}'] function GetSize (var pcbSize: DWORD) : HResult; stdcall; function GetMimeType (var pszMimeType: PChar) : HResult; stdcall; function Read(pvData: Pointer; cbSize: DWORD; pcbRead: PDWORD{?}) : HResult; stdcall; end; const (* * DirectXFile Object Class Id (for CoCreateInstance()) *) CLSID_CDirectXFile: TGUID = (D1:$4516ec43;D2:$8f20;D3:$11d0;D4:($9b,$6d,$00,$00,$c0,$78,$1b,$c3)); (* * DirectX File Interface GUIDs. *) type IID_IDirectXFile = IDirectXFile; IID_IDirectXFileEnumObject = IDirectXFileEnumObject; IID_IDirectXFileSaveObject = IDirectXFileSaveObject; IID_IDirectXFileObject = IDirectXFileObject; IID_IDirectXFileData = IDirectXFileData; IID_IDirectXFileDataReference = IDirectXFileDataReference; IID_IDirectXFileBinary = IDirectXFileBinary; (* * DirectX File Header template's GUID. *) const TID_DXFILEHeader: TGUID = (D1:$3d82ab43;D2:$62da;D3:$11cf;D4:($ab,$39,$00,$20,$af,$71,$e4,$33)); (* * DirectX File errors. *) const DXFILE_OK = 0; DXFILEERR_BADOBJECT = MAKE_DDHRESULT or 850; DXFILEERR_BADVALUE = MAKE_DDHRESULT or 851; DXFILEERR_BADTYPE = MAKE_DDHRESULT or 852; DXFILEERR_BADSTREAMHANDLE = MAKE_DDHRESULT or 853; DXFILEERR_BADALLOC = MAKE_DDHRESULT or 854; DXFILEERR_NOTFOUND = MAKE_DDHRESULT or 855; DXFILEERR_NOTDONEYET = MAKE_DDHRESULT or 856; DXFILEERR_FILENOTFOUND = MAKE_DDHRESULT or 857; DXFILEERR_RESOURCENOTFOUND = MAKE_DDHRESULT or 858; DXFILEERR_URLNOTFOUND = MAKE_DDHRESULT or 859; DXFILEERR_BADRESOURCE = MAKE_DDHRESULT or 860; DXFILEERR_BADFILETYPE = MAKE_DDHRESULT or 861; DXFILEERR_BADFILEVERSION = MAKE_DDHRESULT or 862; DXFILEERR_BADFILEFLOATSIZE = MAKE_DDHRESULT or 863; DXFILEERR_BADFILECOMPRESSIONTYPE = MAKE_DDHRESULT or 864; DXFILEERR_BADFILE = MAKE_DDHRESULT or 865; DXFILEERR_PARSEERROR = MAKE_DDHRESULT or 866; DXFILEERR_NOTEMPLATE = MAKE_DDHRESULT or 867; DXFILEERR_BADARRAYSIZE = MAKE_DDHRESULT or 868; DXFILEERR_BADDATAREFERENCE = MAKE_DDHRESULT or 869; DXFILEERR_INTERNALERROR = MAKE_DDHRESULT or 870; DXFILEERR_NOMOREOBJECTS = MAKE_DDHRESULT or 871; DXFILEERR_BADINTRINSICS = MAKE_DDHRESULT or 872; DXFILEERR_NOMORESTREAMHANDLES = MAKE_DDHRESULT or 873; DXFILEERR_NOMOREDATA = MAKE_DDHRESULT or 874; DXFILEERR_BADCACHEFILE = MAKE_DDHRESULT or 875; DXFILEERR_NOINTERNET = MAKE_DDHRESULT or 876; (* * API for creating IDirectXFile interface. *) var DirectXFileCreate : function (out lplpDirectXFile: IDirectXFile) : HResult; stdcall; (* D3DRM XFile templates in binary form *) const D3DRM_XTEMPLATES: array [0..3214] of byte = ( $78, $6f, $66, $20, $30, $33, $30, $32, $62, $69, $6e, $20, $30, $30, $36, $34, $1f, 0, $1, 0, $6, 0, 0, 0, $48, $65, $61, $64, $65, $72, $a, 0, $5, 0, $43, $ab, $82, $3d, $da, $62, $cf, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $28, 0, $1, 0, $5, 0, 0, 0, $6d, $61, $6a, $6f, $72, $14, 0, $28, 0, $1, 0, $5, 0, 0, 0, $6d, $69, $6e, $6f, $72, $14, 0, $29, 0, $1, 0, $5, 0, 0, 0, $66, $6c, $61, $67, $73, $14, 0, $b, 0, $1f, 0, $1, 0, $6, 0, 0, 0, $56, $65, $63, $74, $6f, $72, $a, 0, $5, 0, $5e, $ab, $82, $3d, $da, $62, $cf, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $2a, 0, $1, 0, $1, 0, 0, 0, $78, $14, 0, $2a, 0, $1, 0, $1, 0, 0, 0, $79, $14, 0, $2a, 0, $1, 0, $1, 0, 0, 0, $7a, $14, 0, $b, 0, $1f, 0, $1, 0, $8, 0, 0, 0, $43, $6f, $6f, $72, $64, $73, $32, $64, $a, 0, $5, 0, $44, $3f, $f2, $f6, $86, $76, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $2a, 0, $1, 0, $1, 0, 0, 0, $75, $14, 0, $2a, 0, $1, 0, $1, 0, 0, 0, $76, $14, 0, $b, 0, $1f, 0, $1, 0, $9, 0, 0, 0, $4d, $61, $74, $72, $69, $78, $34, $78, $34, $a, 0, $5, 0, $45, $3f, $f2, $f6, $86, $76, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $34, 0, $2a, 0, $1, 0, $6, 0, 0, 0, $6d, $61, $74, $72, $69, $78, $e, 0, $3, 0, $10, 0, 0, 0, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $9, 0, 0, 0, $43, $6f, $6c, $6f, $72, $52, $47, $42, $41, $a, 0, $5, 0, $e0, $44, $ff, $35, $7c, $6c, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $2a, 0, $1, 0, $3, 0, 0, 0, $72, $65, $64, $14, 0, $2a, 0, $1, 0, $5, 0, 0, 0, $67, $72, $65, $65, $6e, $14, 0, $2a, 0, $1, 0, $4, 0, 0, 0, $62, $6c, $75, $65, $14, 0, $2a, 0, $1, 0, $5, 0, 0, 0, $61, $6c, $70, $68, $61, $14, 0, $b, 0, $1f, 0, $1, 0, $8, 0, 0, 0, $43, $6f, $6c, $6f, $72, $52, $47, $42, $a, 0, $5, 0, $81, $6e, $e1, $d3, $35, $78, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $2a, 0, $1, 0, $3, 0, 0, 0, $72, $65, $64, $14, 0, $2a, 0, $1, 0, $5, 0, 0, 0, $67, $72, $65, $65, $6e, $14, 0, $2a, 0, $1, 0, $4, 0, 0, 0, $62, $6c, $75, $65, $14, 0, $b, 0, $1f, 0, $1, 0, $c, 0, 0, 0, $49, $6e, $64, $65, $78, $65, $64, $43, $6f, $6c, $6f, $72, $a, 0, $5, 0, $20, $b8, $30, $16, $42, $78, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $5, 0, 0, 0, $69, $6e, $64, $65, $78, $14, 0, $1, 0, $9, 0, 0, 0, $43, $6f, $6c, $6f, $72, $52, $47, $42, $41, $1, 0, $a, 0, 0, 0, $69, $6e, $64, $65, $78, $43, $6f, $6c, $6f, $72, $14, 0, $b, 0, $1f, 0, $1, 0, $7, 0, 0, 0, $42, $6f, $6f, $6c, $65, $61, $6e, $a, 0, $5, 0, $a0, $a6, $7d, $53, $37, $ca, $d0, $11, $94, $1c, 0, $80, $c8, $c, $fa, $7b, $29, 0, $1, 0, $9, 0, 0, 0, $74, $72, $75, $65, $66, $61, $6c, $73, $65, $14, 0, $b, 0, $1f, 0, $1, 0, $9, 0, 0, 0, $42, $6f, $6f, $6c, $65, $61, $6e, $32, $64, $a, 0, $5, 0, $63, $ae, $85, $48, $e8, $78, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $1, 0, $7, 0, 0, 0, $42, $6f, $6f, $6c, $65, $61, $6e, $1, 0, $1, 0, 0, 0, $75, $14, 0, $1, 0, $7, 0, 0, 0, $42, $6f, $6f, $6c, $65, $61, $6e, $1, 0, $1, 0, 0, 0, $76, $14, 0, $b, 0, $1f, 0, $1, 0, $c, 0, 0, 0, $4d, $61, $74, $65, $72, $69, $61, $6c, $57, $72, $61, $70, $a, 0, $5, 0, $60, $ae, $85, $48, $e8, $78, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $1, 0, $7, 0, 0, 0, $42, $6f, $6f, $6c, $65, $61, $6e, $1, 0, $1, 0, 0, 0, $75, $14, 0, $1, 0, $7, 0, 0, 0, $42, $6f, $6f, $6c, $65, $61, $6e, $1, 0, $1, 0, 0, 0, $76, $14, 0, $b, 0, $1f, 0, $1, 0, $f, 0, 0, 0, $54, $65, $78, $74, $75, $72, $65, $46, $69, $6c, $65, $6e, $61, $6d, $65, $a, 0, $5, 0, $e1, $90, $27, $a4, $10, $78, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $31, 0, $1, 0, $8, 0, 0, 0, $66, $69, $6c, $65, $6e, $61, $6d, $65, $14, 0, $b, 0, $1f, 0, $1, 0, $8, 0, 0, 0, $4d, $61, $74, $65, $72, $69, $61, $6c, $a, 0, $5, 0, $4d, $ab, $82, $3d, $da, $62, $cf, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $1, 0, $9, 0, 0, 0, $43, $6f, $6c, $6f, $72, $52, $47, $42, $41, $1, 0, $9, 0, 0, 0, $66, $61, $63, $65, $43, $6f, $6c, $6f, $72, $14, 0, $2a, 0, $1, 0, $5, 0, 0, 0, $70, $6f, $77, $65, $72, $14, 0, $1, 0, $8, 0, 0, 0, $43, $6f, $6c, $6f, $72, $52, $47, $42, $1, 0, $d, 0, 0, 0, $73, $70, $65, $63, $75, $6c, $61, $72, $43, $6f, $6c, $6f, $72, $14, 0, $1, 0, $8, 0, 0, 0, $43, $6f, $6c, $6f, $72, $52, $47, $42, $1, 0, $d, 0, 0, 0, $65, $6d, $69, $73, $73, $69, $76, $65, $43, $6f, $6c, $6f, $72, $14, 0, $e, 0, $12, 0, $12, 0, $12, 0, $f, 0, $b, 0, $1f, 0, $1, 0, $8, 0, 0, 0, $4d, $65, $73, $68, $46, $61, $63, $65, $a, 0, $5, 0, $5f, $ab, $82, $3d, $da, $62, $cf, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $29, 0, $1, 0, $12, 0, 0, 0, $6e, $46, $61, $63, $65, $56, $65, $72, $74, $65, $78, $49, $6e, $64, $69, $63, $65, $73, $14, 0, $34, 0, $29, 0, $1, 0, $11, 0, 0, 0, $66, $61, $63, $65, $56, $65, $72, $74, $65, $78, $49, $6e, $64, $69, $63, $65, $73, $e, 0, $1, 0, $12, 0, 0, 0, $6e, $46, $61, $63, $65, $56, $65, $72, $74, $65, $78, $49, $6e, $64, $69, $63, $65, $73, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $d, 0, 0, 0, $4d, $65, $73, $68, $46, $61, $63, $65, $57, $72, $61, $70, $73, $a, 0, $5, 0, $c0, $c5, $1e, $ed, $a8, $c0, $d0, $11, $94, $1c, 0, $80, $c8, $c, $fa, $7b, $29, 0, $1, 0, $f, 0, 0, 0, $6e, $46, $61, $63, $65, $57, $72, $61, $70, $56, $61, $6c, $75, $65, $73, $14, 0, $34, 0, $1, 0, $9, 0, 0, 0, $42, $6f, $6f, $6c, $65, $61, $6e, $32, $64, $1, 0, $e, 0, 0, 0, $66, $61, $63, $65, $57, $72, $61, $70, $56, $61, $6c, $75, $65, $73, $e, 0, $1, 0, $f, 0, 0, 0, $6e, $46, $61, $63, $65, $57, $72, $61, $70, $56, $61, $6c, $75, $65, $73, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $11, 0, 0, 0, $4d, $65, $73, $68, $54, $65, $78, $74, $75, $72, $65, $43, $6f, $6f, $72, $64, $73, $a, 0, $5, 0, $40, $3f, $f2, $f6, $86, $76, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $e, 0, 0, 0, $6e, $54, $65, $78, $74, $75, $72, $65, $43, $6f, $6f, $72, $64, $73, $14, 0, $34, 0, $1, 0, $8, 0, 0, 0, $43, $6f, $6f, $72, $64, $73, $32, $64, $1, 0, $d, 0, 0, 0, $74, $65, $78, $74, $75, $72, $65, $43, $6f, $6f, $72, $64, $73, $e, 0, $1, 0, $e, 0, 0, 0, $6e, $54, $65, $78, $74, $75, $72, $65, $43, $6f, $6f, $72, $64, $73, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $10, 0, 0, 0, $4d, $65, $73, $68, $4d, $61, $74, $65, $72, $69, $61, $6c, $4c, $69, $73, $74, $a, 0, $5, 0, $42, $3f, $f2, $f6, $86, $76, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $a, 0, 0, 0, $6e, $4d, $61, $74, $65, $72, $69, $61, $6c, $73, $14, 0, $29, 0, $1, 0, $c, 0, 0, 0, $6e, $46, $61, $63, $65, $49, $6e, $64, $65, $78, $65, $73, $14, 0, $34, 0, $29, 0, $1, 0, $b, 0, 0, 0, $66, $61, $63, $65, $49, $6e, $64, $65, $78, $65, $73, $e, 0, $1, 0, $c, 0, 0, 0, $6e, $46, $61, $63, $65, $49, $6e, $64, $65, $78, $65, $73, $f, 0, $14, 0, $e, 0, $1, 0, $8, 0, 0, 0, $4d, $61, $74, $65, $72, $69, $61, $6c, $f, 0, $b, 0, $1f, 0, $1, 0, $b, 0, 0, 0, $4d, $65, $73, $68, $4e, $6f, $72, $6d, $61, $6c, $73, $a, 0, $5, 0, $43, $3f, $f2, $f6, $86, $76, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $8, 0, 0, 0, $6e, $4e, $6f, $72, $6d, $61, $6c, $73, $14, 0, $34, 0, $1, 0, $6, 0, 0, 0, $56, $65, $63, $74, $6f, $72, $1, 0, $7, 0, 0, 0, $6e, $6f, $72, $6d, $61, $6c, $73, $e, 0, $1, 0, $8, 0, 0, 0, $6e, $4e, $6f, $72, $6d, $61, $6c, $73, $f, 0, $14, 0, $29, 0, $1, 0, $c, 0, 0, 0, $6e, $46, $61, $63, $65, $4e, $6f, $72, $6d, $61, $6c, $73, $14, 0, $34, 0, $1, 0, $8, 0, 0, 0, $4d, $65, $73, $68, $46, $61, $63, $65, $1, 0, $b, 0, 0, 0, $66, $61, $63, $65, $4e, $6f, $72, $6d, $61, $6c, $73, $e, 0, $1, 0, $c, 0, 0, 0, $6e, $46, $61, $63, $65, $4e, $6f, $72, $6d, $61, $6c, $73, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $10, 0, 0, 0, $4d, $65, $73, $68, $56, $65, $72, $74, $65, $78, $43, $6f, $6c, $6f, $72, $73, $a, 0, $5, 0, $21, $b8, $30, $16, $42, $78, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $d, 0, 0, 0, $6e, $56, $65, $72, $74, $65, $78, $43, $6f, $6c, $6f, $72, $73, $14, 0, $34, 0, $1, 0, $c, 0, 0, 0, $49, $6e, $64, $65, $78, $65, $64, $43, $6f, $6c, $6f, $72, $1, 0, $c, 0, 0, 0, $76, $65, $72, $74, $65, $78, $43, $6f, $6c, $6f, $72, $73, $e, 0, $1, 0, $d, 0, 0, 0, $6e, $56, $65, $72, $74, $65, $78, $43, $6f, $6c, $6f, $72, $73, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $4, 0, 0, 0, $4d, $65, $73, $68, $a, 0, $5, 0, $44, $ab, $82, $3d, $da, $62, $cf, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $29, 0, $1, 0, $9, 0, 0, 0, $6e, $56, $65, $72, $74, $69, $63, $65, $73, $14, 0, $34, 0, $1, 0, $6, 0, 0, 0, $56, $65, $63, $74, $6f, $72, $1, 0, $8, 0, 0, 0, $76, $65, $72, $74, $69, $63, $65, $73, $e, 0, $1, 0, $9, 0, 0, 0, $6e, $56, $65, $72, $74, $69, $63, $65, $73, $f, 0, $14, 0, $29, 0, $1, 0, $6, 0, 0, 0, $6e, $46, $61, $63, $65, $73, $14, 0, $34, 0, $1, 0, $8, 0, 0, 0, $4d, $65, $73, $68, $46, $61, $63, $65, $1, 0, $5, 0, 0, 0, $66, $61, $63, $65, $73, $e, 0, $1, 0, $6, 0, 0, 0, $6e, $46, $61, $63, $65, $73, $f, 0, $14, 0, $e, 0, $12, 0, $12, 0, $12, 0, $f, 0, $b, 0, $1f, 0, $1, 0, $14, 0, 0, 0, $46, $72, $61, $6d, $65, $54, $72, $61, $6e, $73, $66, $6f, $72, $6d, $4d, $61, $74, $72, $69, $78, $a, 0, $5, 0, $41, $3f, $f2, $f6, $86, $76, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $1, 0, $9, 0, 0, 0, $4d, $61, $74, $72, $69, $78, $34, $78, $34, $1, 0, $b, 0, 0, 0, $66, $72, $61, $6d, $65, $4d, $61, $74, $72, $69, $78, $14, 0, $b, 0, $1f, 0, $1, 0, $5, 0, 0, 0, $46, $72, $61, $6d, $65, $a, 0, $5, 0, $46, $ab, $82, $3d, $da, $62, $cf, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $e, 0, $12, 0, $12, 0, $12, 0, $f, 0, $b, 0, $1f, 0, $1, 0, $9, 0, 0, 0, $46, $6c, $6f, $61, $74, $4b, $65, $79, $73, $a, 0, $5, 0, $a9, $46, $dd, $10, $5b, $77, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $7, 0, 0, 0, $6e, $56, $61, $6c, $75, $65, $73, $14, 0, $34, 0, $2a, 0, $1, 0, $6, 0, 0, 0, $76, $61, $6c, $75, $65, $73, $e, 0, $1, 0, $7, 0, 0, 0, $6e, $56, $61, $6c, $75, $65, $73, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $e, 0, 0, 0, $54, $69, $6d, $65, $64, $46, $6c, $6f, $61, $74, $4b, $65, $79, $73, $a, 0, $5, 0, $80, $b1, $6, $f4, $3b, $7b, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $4, 0, 0, 0, $74, $69, $6d, $65, $14, 0, $1, 0, $9, 0, 0, 0, $46, $6c, $6f, $61, $74, $4b, $65, $79, $73, $1, 0, $6, 0, 0, 0, $74, $66, $6b, $65, $79, $73, $14, 0, $b, 0, $1f, 0, $1, 0, $c, 0, 0, 0, $41, $6e, $69, $6d, $61, $74, $69, $6f, $6e, $4b, $65, $79, $a, 0, $5, 0, $a8, $46, $dd, $10, $5b, $77, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $7, 0, 0, 0, $6b, $65, $79, $54, $79, $70, $65, $14, 0, $29, 0, $1, 0, $5, 0, 0, 0, $6e, $4b, $65, $79, $73, $14, 0, $34, 0, $1, 0, $e, 0, 0, 0, $54, $69, $6d, $65, $64, $46, $6c, $6f, $61, $74, $4b, $65, $79, $73, $1, 0, $4, 0, 0, 0, $6b, $65, $79, $73, $e, 0, $1, 0, $5, 0, 0, 0, $6e, $4b, $65, $79, $73, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $10, 0, 0, 0, $41, $6e, $69, $6d, $61, $74, $69, $6f, $6e, $4f, $70, $74, $69, $6f, $6e, $73, $a, 0, $5, 0, $c0, $56, $bf, $e2, $f, $84, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $a, 0, 0, 0, $6f, $70, $65, $6e, $63, $6c, $6f, $73, $65, $64, $14, 0, $29, 0, $1, 0, $f, 0, 0, 0, $70, $6f, $73, $69, $74, $69, $6f, $6e, $71, $75, $61, $6c, $69, $74, $79, $14, 0, $b, 0, $1f, 0, $1, 0, $9, 0, 0, 0, $41, $6e, $69, $6d, $61, $74, $69, $6f, $6e, $a, 0, $5, 0, $4f, $ab, $82, $3d, $da, $62, $cf, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $e, 0, $12, 0, $12, 0, $12, 0, $f, 0, $b, 0, $1f, 0, $1, 0, $c, 0, 0, 0, $41, $6e, $69, $6d, $61, $74, $69, $6f, $6e, $53, $65, $74, $a, 0, $5, 0, $50, $ab, $82, $3d, $da, $62, $cf, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $e, 0, $1, 0, $9, 0, 0, 0, $41, $6e, $69, $6d, $61, $74, $69, $6f, $6e, $f, 0, $b, 0, $1f, 0, $1, 0, $a, 0, 0, 0, $49, $6e, $6c, $69, $6e, $65, $44, $61, $74, $61, $a, 0, $5, 0, $a0, $ee, $23, $3a, $b1, $94, $d0, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $e, 0, $1, 0, $6, 0, 0, 0, $42, $49, $4e, $41, $52, $59, $f, 0, $b, 0, $1f, 0, $1, 0, $3, 0, 0, 0, $55, $72, $6c, $a, 0, $5, 0, $a1, $ee, $23, $3a, $b1, $94, $d0, $11, $ab, $39, 0, $20, $af, $71, $e4, $33, $29, 0, $1, 0, $5, 0, 0, 0, $6e, $55, $72, $6c, $73, $14, 0, $34, 0, $31, 0, $1, 0, $4, 0, 0, 0, $75, $72, $6c, $73, $e, 0, $1, 0, $5, 0, 0, 0, $6e, $55, $72, $6c, $73, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $f, 0, 0, 0, $50, $72, $6f, $67, $72, $65, $73, $73, $69, $76, $65, $4d, $65, $73, $68, $a, 0, $5, 0, $60, $c3, $63, $8a, $7d, $99, $d0, $11, $94, $1c, 0, $80, $c8, $c, $fa, $7b, $e, 0, $1, 0, $3, 0, 0, 0, $55, $72, $6c, $13, 0, $1, 0, $a, 0, 0, 0, $49, $6e, $6c, $69, $6e, $65, $44, $61, $74, $61, $f, 0, $b, 0, $1f, 0, $1, 0, $4, 0, 0, 0, $47, $75, $69, $64, $a, 0, $5, 0, $e0, $90, $27, $a4, $10, $78, $cf, $11, $8f, $52, 0, $40, $33, $35, $94, $a3, $29, 0, $1, 0, $5, 0, 0, 0, $64, $61, $74, $61, $31, $14, 0, $28, 0, $1, 0, $5, 0, 0, 0, $64, $61, $74, $61, $32, $14, 0, $28, 0, $1, 0, $5, 0, 0, 0, $64, $61, $74, $61, $33, $14, 0, $34, 0, $2d, 0, $1, 0, $5, 0, 0, 0, $64, $61, $74, $61, $34, $e, 0, $3, 0, $8, 0, 0, 0, $f, 0, $14, 0, $b, 0, $1f, 0, $1, 0, $e, 0, 0, 0, $53, $74, $72, $69, $6e, $67, $50, $72, $6f, $70, $65, $72, $74, $79, $a, 0, $5, 0, $e0, $21, $f, $7f, $e1, $bf, $d1, $11, $82, $c0, 0, $a0, $c9, $69, $72, $71, $31, 0, $1, 0, $3, 0, 0, 0, $6b, $65, $79, $14, 0, $31, 0, $1, 0, $5, 0, 0, 0, $76, $61, $6c, $75, $65, $14, 0, $b, 0, $1f, 0, $1, 0, $b, 0, 0, 0, $50, $72, $6f, $70, $65, $72, $74, $79, $42, $61, $67, $a, 0, $5, 0, $e1, $21, $f, $7f, $e1, $bf, $d1, $11, $82, $c0, 0, $a0, $c9, $69, $72, $71, $e, 0, $1, 0, $e, 0, 0, 0, $53, $74, $72, $69, $6e, $67, $50, $72, $6f, $70, $65, $72, $74, $79, $f, 0, $b, 0, $1f, 0, $1, 0, $e, 0, 0, 0, $45, $78, $74, $65, $72, $6e, $61, $6c, $56, $69, $73, $75, $61, $6c, $a, 0, $5, 0, $a0, $6a, $11, $98, $ba, $bd, $d1, $11, $82, $c0, 0, $a0, $c9, $69, $72, $71, $1, 0, $4, 0, 0, 0, $47, $75, $69, $64, $1, 0, $12, 0, 0, 0, $67, $75, $69, $64, $45, $78, $74, $65, $72, $6e, $61, $6c, $56, $69, $73, $75, $61, $6c, $14, 0, $e, 0, $12, 0, $12, 0, $12, 0, $f, 0, $b, 0); implementation uses DXCommon; function DXFileErrorString(Value: HResult) : string; begin case Value of DXFILE_OK: Result := 'Command completed successfully. Equivalent to DD_OK.'; DXFILEERR_BADVALUE: Result := 'Parameter is invalid.'; DXFILEERR_BADTYPE: Result := 'Object type is invalid.'; DXFILEERR_BADALLOC: Result := 'Memory allocation failed.'; DXFILEERR_NOTFOUND: Result := 'Object could not be found.'; DXFILEERR_FILENOTFOUND: Result := 'File could not be found.'; DXFILEERR_RESOURCENOTFOUND: Result := 'Resource could not be found.'; DXFILEERR_URLNOTFOUND: Result := 'URL could not be found.'; DXFILEERR_BADRESOURCE: Result := 'Resource is invalid.'; DXFILEERR_BADFILETYPE: Result := 'File is not a DirectX file.'; DXFILEERR_BADFILEVERSION: Result := 'File version is not valid.'; DXFILEERR_BADFILEFLOATSIZE: Result := 'Floating-point size is invalid.'; DXFILEERR_BADFILE: Result := 'File is invalid.'; DXFILEERR_PARSEERROR: Result := 'File could not be parsed.'; DXFILEERR_BADARRAYSIZE: Result := 'Array size is invalid.'; DXFILEERR_BADDATAREFERENCE: Result := 'Data reference is invalid.'; DXFILEERR_NOMOREOBJECTS: Result := 'All objects have been enumerated.'; DXFILEERR_NOMOREDATA: Result := 'No further data is available.'; else Result := 'Unrecognized Error'; end; end; function D3DFVF_TEXCOORDSIZE3(CoordIndex: DWORD) : DWORD; begin Result := (D3DFVF_TEXTUREFORMAT3 shl (CoordIndex*2 + 16)); end; function D3DFVF_TEXCOORDSIZE2(CoordIndex: DWORD) : DWORD; begin Result := (D3DFVF_TEXTUREFORMAT2); end; function D3DFVF_TEXCOORDSIZE4(CoordIndex: DWORD) : DWORD; begin Result := (D3DFVF_TEXTUREFORMAT4 shl (CoordIndex*2 + 16)); end; function D3DFVF_TEXCOORDSIZE1(CoordIndex: DWORD) : DWORD; begin Result := (D3DFVF_TEXTUREFORMAT1 shl (CoordIndex*2 + 16)); end; function D3DVal(val: variant) : float; begin Result := val; end; function D3DDivide(a,b: double) : float; begin Result := a / b; end; function D3DMultiply(a,b: double) : float; begin Result := a * b; end; // #define CI_GETALPHA(ci) ((ci) >> 24) function CI_GETALPHA(ci: DWORD) : DWORD; begin Result := ci shr 24; end; // #define CI_GETINDEX(ci) (((ci) >> 8) & 0xffff) function CI_GETINDEX(ci: DWORD) : DWORD; begin Result := (ci shr 8) and $ffff; end; // #define CI_GETFRACTION(ci) ((ci) & 0xff) function CI_GETFRACTION(ci: DWORD) : DWORD; begin Result := ci and $ff; end; // #define CI_ROUNDINDEX(ci) CI_GETINDEX((ci) + 0x80) function CI_ROUNDINDEX(ci: DWORD) : DWORD; begin Result := CI_GETINDEX(ci + $80); end; // #define CI_MASKALPHA(ci) ((ci) & 0xffffff) function CI_MASKALPHA(ci: DWORD) : DWORD; begin Result := ci and $ffffff; end; // #define CI_MAKE(a, i, f) (((a) << 24) | ((i) << 8) | (f)) function CI_MAKE(a,i,f: DWORD) : DWORD; begin Result := (a shl 24) or (i shl 8) or f; end; // #define RGBA_GETALPHA(rgb) ((rgb) >> 24) function RGBA_GETALPHA(rgb: TD3DColor) : DWORD; begin Result := rgb shr 24; end; // #define RGBA_GETRED(rgb) (((rgb) >> 16) & 0xff) function RGBA_GETRED(rgb: TD3DColor) : DWORD; begin Result := (rgb shr 16) and $ff; end; // #define RGBA_GETGREEN(rgb) (((rgb) >> 8) & 0xff) function RGBA_GETGREEN(rgb: TD3DColor) : DWORD; begin Result := (rgb shr 8) and $ff; end; // #define RGBA_GETBLUE(rgb) ((rgb) & 0xff) function RGBA_GETBLUE(rgb: TD3DColor) : DWORD; begin Result := rgb and $ff; end; // #define RGBA_MAKE(r, g, b, a) ((TD3DColor) (((a) << 24) | ((r) << 16) | ((g) << 8) | (b))) function RGBA_MAKE(r, g, b, a: DWORD) : TD3DColor; begin Result := (a shl 24) or (r shl 16) or (g shl 8) or b; end; // #define D3DRGB(r, g, b) \ // (0xff000000L | (((long)((r) * 255)) << 16) | (((long)((g) * 255)) << 8) | (long)((b) * 255)) function D3DRGB(r, g, b: float) : TD3DColor; begin Result := $ff000000 or (round(r * 255) shl 16) or (round(g * 255) shl 8) or round(b * 255); end; // #define D3DRGBA(r, g, b, a) \ // ( (((long)((a) * 255)) << 24) | (((long)((r) * 255)) << 16) \ // | (((long)((g) * 255)) << 8) | (long)((b) * 255) \ // ) function D3DRGBA(r, g, b, a: float) : TD3DColor; begin Result := (round(a * 255) shl 24) or (round(r * 255) shl 16) or (round(g * 255) shl 8) or round(b * 255); end; // #define RGB_GETRED(rgb) (((rgb) >> 16) & 0xff) function RGB_GETRED(rgb: TD3DColor) : DWORD; begin Result := (rgb shr 16) and $ff; end; // #define RGB_GETGREEN(rgb) (((rgb) >> 8) & 0xff) function RGB_GETGREEN(rgb: TD3DColor) : DWORD; begin Result := (rgb shr 8) and $ff; end; // #define RGB_GETBLUE(rgb) ((rgb) & 0xff) function RGB_GETBLUE(rgb: TD3DColor) : DWORD; begin Result := rgb and $ff; end; // #define RGBA_SETALPHA(rgba, x) (((x) << 24) | ((rgba) & 0x00ffffff)) function RGBA_SETALPHA(rgba: TD3DColor; x: DWORD) : TD3DColor; begin Result := (x shl 24) or (rgba and $00ffffff); end; // #define RGB_MAKE(r, g, b) ((TD3DColor) (((r) << 16) | ((g) << 8) | (b))) function RGB_MAKE(r, g, b: DWORD) : TD3DColor; begin Result := (r shl 16) or (g shl 8) or b; end; // #define RGBA_TORGB(rgba) ((TD3DColor) ((rgba) & 0xffffff)) function RGBA_TORGB(rgba: TD3DColor) : TD3DColor; begin Result := rgba and $00ffffff; end; // #define RGB_TORGBA(rgb) ((TD3DColor) ((rgb) | 0xff000000)) function RGB_TORGBA(rgb: TD3DColor) : TD3DColor; begin Result := rgb or $ff000000; end; function D3DSTATE_OVERRIDE(StateType: DWORD) : DWORD; begin Result := StateType + D3DSTATE_OVERRIDE_BIAS; end; function D3DTRIFLAG_STARTFLAT(len: DWORD) : DWORD; begin if not (len in [1..29]) then len := 0; result := len; end; // #define D3DRENDERSTATE_STIPPLEPATTERN(y) (D3DRENDERSTATE_STIPPLEPATTERN00 + (y)) function D3DRENDERSTATE_STIPPLEPATTERN(y: integer) : TD3DRenderStateType; begin Result := TD3DRenderStateType(Ord(D3DRENDERSTATE_STIPPLEPATTERN00) + y); end; // Addition and subtraction function VectorAdd(const v1, v2: TD3DVector) : TD3DVector; begin result.x := v1.x+v2.x; result.y := v1.y+v2.y; result.z := v1.z+v2.z; end; function VectorSub(const v1, v2: TD3DVector) : TD3DVector; begin result.x := v1.x-v2.x; result.y := v1.y-v2.y; result.z := v1.z-v2.z; end; // Scalar multiplication and division function VectorMulS(const v: TD3DVector; s: TD3DValue) : TD3DVector; begin result.x := v.x*s; result.y := v.y*s; result.z := v.z*s; end; function VectorDivS(const v: TD3DVector; s: TD3DValue) : TD3DVector; begin result.x := v.x/s; result.y := v.y/s; result.z := v.z/s; end; // Memberwise multiplication and division function VectorMul(const v1, v2: TD3DVector) : TD3DVector; begin result.x := v1.x*v2.x; result.y := v1.y*v2.y; result.z := v1.z*v2.z; end; function VectorDiv(const v1, v2: TD3DVector) : TD3DVector; begin result.x := v1.x/v2.x; result.y := v1.y/v2.y; result.z := v1.z/v2.z; end; // Vector dominance function VectorSmaller(v1, v2: TD3DVector) : boolean; begin result := (v1.x < v2.x) and (v1.y < v2.y) and (v1.z < v2.z); end; function VectorSmallerEquel(v1, v2: TD3DVector) : boolean; begin result := (v1.x <= v2.x) and (v1.y <= v2.y) and (v1.z <= v2.z); end; // Bitwise equality function VectorEquel(v1, v2: TD3DVector) : boolean; begin result := (v1.x = v2.x) and (v1.y = v2.y) and (v1.z = v2.z); end; // Length-related functions function VectorSquareMagnitude(v: TD3DVector) : TD3DValue; begin result := (v.x*v.x) + (v.y*v.y) + (v.z*v.z); end; function VectorMagnitude(v: TD3DVector) : TD3DValue; begin result := sqrt((v.x*v.x) + (v.y*v.y) + (v.z*v.z)); end; // Returns vector with same direction and unit length function VectorNormalize(const v: TD3DVector) : TD3DVector; begin result := VectorDivS(v,VectorMagnitude(v)); end; // Return min/max component of the input vector function VectorMin(v: TD3DVector) : TD3DValue; var ret : TD3DValue; begin ret := v.x; if (v.y < ret) then ret := v.y; if (v.z < ret) then ret := v.z; result := ret; end; function VectorMax(v: TD3DVector) : TD3DValue; var ret : TD3DValue; begin ret := v.x; if (ret < v.y) then ret := v.y; if (ret < v.z) then ret := v.z; result := ret; end; // Return memberwise min/max of input vectors function VectorMinimize(const v1, v2: TD3DVector) : TD3DVector; begin if v1.x < v2.x then result.x := v1.x else result.x := v2.x; if v1.y < v2.y then result.y := v1.y else result.y := v2.y; if v1.z < v2.z then result.z := v1.z else result.z := v2.z; end; function VectorMaximize(const v1, v2: TD3DVector) : TD3DVector; begin if v1.x > v2.x then result.x := v1.x else result.x := v2.x; if v1.y > v2.y then result.y := v1.y else result.y := v2.y; if v1.z > v2.z then result.z := v1.z else result.z := v2.z; end; // Dot and cross product function VectorDotProduct(v1, v2: TD3DVector) : TD3DValue; begin result := (v1.x*v2.x) + (v1.y * v2.y) + (v1.z*v2.z); end; function VectorCrossProduct(const v1, v2: TD3DVector) : TD3DVector; begin result.x := (v1.y*v2.z) - (v1.z*v2.y); result.y := (v1.z*v2.x) - (v1.x*v2.z); result.z := (v1.x*v2.y) - (v1.y*v2.x); end; procedure DisableFPUExceptions; var FPUControlWord: WORD; asm FSTCW FPUControlWord; OR FPUControlWord, $4 + $1; { Divide by zero + invalid operation } FLDCW FPUControlWord; end; procedure EnableFPUExceptions; var FPUControlWord: WORD; asm FSTCW FPUControlWord; AND FPUControlWord, $FFFF - $4 - $1; { Divide by zero + invalid operation } FLDCW FPUControlWord; end; function D3DErrorString(Value: HResult) : string; //Full description not available yet begin case Value of D3D_OK: Result := 'No error'; D3DERR_BADMAJORVERSION: Result := 'D3DERR_BADMAJORVERSION'; D3DERR_BADMINORVERSION: Result := 'D3DERR_BADMINORVERSION'; D3DERR_INVALID_DEVICE: Result := 'D3DERR_INITFAILED'; D3DERR_INITFAILED: Result := 'D3DERR_INITFAILED'; D3DERR_DEVICEAGGREGATED: Result := 'D3DERR_DEVICEAGGREGATED'; D3DERR_EXECUTE_CREATE_FAILED: Result := 'D3DERR_EXECUTE_CREATE_FAILED'; D3DERR_EXECUTE_DESTROY_FAILED: Result := 'D3DERR_EXECUTE_DESTROY_FAILED'; D3DERR_EXECUTE_LOCK_FAILED: Result := 'D3DERR_EXECUTE_LOCK_FAILED'; D3DERR_EXECUTE_UNLOCK_FAILED: Result := 'D3DERR_EXECUTE_UNLOCK_FAILED'; D3DERR_EXECUTE_LOCKED: Result := 'D3DERR_EXECUTE_LOCKED'; D3DERR_EXECUTE_NOT_LOCKED: Result := 'D3DERR_EXECUTE_NOT_LOCKED'; D3DERR_EXECUTE_FAILED: Result := 'D3DERR_EXECUTE_FAILED'; D3DERR_EXECUTE_CLIPPED_FAILED: Result := 'D3DERR_EXECUTE_CLIPPED_FAILED'; D3DERR_TEXTURE_NO_SUPPORT: Result := 'D3DERR_TEXTURE_NO_SUPPORT'; D3DERR_TEXTURE_CREATE_FAILED: Result := 'D3DERR_TEXTURE_CREATE_FAILED'; D3DERR_TEXTURE_DESTROY_FAILED: Result := 'D3DERR_TEXTURE_DESTROY_FAILED'; D3DERR_TEXTURE_LOCK_FAILED: Result := 'D3DERR_TEXTURE_LOCK_FAILED'; D3DERR_TEXTURE_UNLOCK_FAILED: Result := 'D3DERR_TEXTURE_UNLOCK_FAILED'; D3DERR_TEXTURE_LOAD_FAILED: Result := 'D3DERR_TEXTURE_LOAD_FAILED'; D3DERR_TEXTURE_SWAP_FAILED: Result := 'D3DERR_TEXTURE_SWAP_FAILED'; D3DERR_TEXTURE_LOCKED: Result := 'D3DERR_TEXTURELOCKED'; D3DERR_TEXTURE_NOT_LOCKED: Result := 'D3DERR_TEXTURE_NOT_LOCKED'; D3DERR_TEXTURE_GETSURF_FAILED: Result := 'D3DERR_TEXTURE_GETSURF_FAILED'; D3DERR_MATRIX_CREATE_FAILED: Result := 'D3DERR_MATRIX_CREATE_FAILED'; D3DERR_MATRIX_DESTROY_FAILED: Result := 'D3DERR_MATRIX_DESTROY_FAILED'; D3DERR_MATRIX_SETDATA_FAILED: Result := 'D3DERR_MATRIX_SETDATA_FAILED'; D3DERR_MATRIX_GETDATA_FAILED: Result := 'D3DERR_MATRIX_GETDATA_FAILED'; D3DERR_SETVIEWPORTDATA_FAILED: Result := 'D3DERR_SETVIEWPORTDATA_FAILED'; D3DERR_INVALIDCURRENTVIEWPORT: Result := 'D3DERR_INVALIDCURRENTVIEWPORT'; D3DERR_INVALIDPRIMITIVETYPE: Result := 'D3DERR_INVALIDPRIMITIVETYPE'; D3DERR_INVALIDVERTEXTYPE: Result := 'D3DERR_INVALIDVERTEXTYPE'; D3DERR_TEXTURE_BADSIZE: Result := 'D3DERR_TEXTURE_BADSIZE'; D3DERR_INVALIDRAMPTEXTURE: Result := 'D3DERR_INVALIDRAMPTEXTURE'; D3DERR_MATERIAL_CREATE_FAILED: Result := 'D3DERR_MATERIAL_CREATE_FAILED'; D3DERR_MATERIAL_DESTROY_FAILED: Result := 'D3DERR_MATERIAL_DESTROY_FAILED'; D3DERR_MATERIAL_SETDATA_FAILED: Result := 'D3DERR_MATERIAL_SETDATA_FAILED'; D3DERR_MATERIAL_GETDATA_FAILED: Result := 'D3DERR_MATERIAL_GETDATA_FAILED'; D3DERR_INVALIDPALETTE: Result := 'D3DERR_INVALIDPALETTE'; D3DERR_ZBUFF_NEEDS_SYSTEMMEMORY: Result := 'D3DERR_ZBUFF_NEEDS_SYSTEMMEMORY'; D3DERR_ZBUFF_NEEDS_VIDEOMEMORY: Result := 'D3DERR_ZBUFF_NEEDS_VIDEOMEMORY'; D3DERR_SURFACENOTINVIDMEM: Result := 'D3DERR_SURFACENOTINVIDMEM'; D3DERR_LIGHT_SET_FAILED: Result := 'D3DERR_LIGHT_SET_FAILED'; D3DERR_LIGHTHASVIEWPORT: Result := 'D3DERR_LIGHTHASVIEWPORT'; D3DERR_LIGHTNOTINTHISVIEWPORT: Result := 'D3DERR_LIGHTNOTINTHISVIEWPORT'; D3DERR_SCENE_IN_SCENE: Result := 'D3DERR_SCENE_IN_SCENE'; D3DERR_SCENE_NOT_IN_SCENE: Result := 'D3DERR_SCENE_NOT_IN_SCENE'; D3DERR_SCENE_BEGIN_FAILED: Result := 'D3DERR_SCENE_BEGIN_FAILED'; D3DERR_SCENE_END_FAILED: Result := 'D3DERR_SCENE_END_FAILED'; D3DERR_INBEGIN: Result := 'D3DERR_INBEGIN'; D3DERR_NOTINBEGIN: Result := 'D3DERR_NOTINBEGIN'; D3DERR_NOVIEWPORTS: Result := 'D3DERR_NOVIEWPORTS'; D3DERR_VIEWPORTDATANOTSET: Result := 'D3DERR_VIEWPORTDATANOTSET'; D3DERR_VIEWPORTHASNODEVICE: Result := 'D3DERR_VIEWPORTHASNODEVICE'; D3DERR_NOCURRENTVIEWPORT: Result := 'D3DERR_NOCURRENTVIEWPORT'; D3DERR_INVALIDVERTEXFORMAT: Result := 'D3DERR_INVALIDVERTEXFORMAT'; D3DERR_COLORKEYATTACHED: Result := 'D3DERR_COLORKEYATTACHED'; D3DERR_VERTEXBUFFEROPTIMIZED: Result := 'D3DERR_VERTEXBUFFEROPTIMIZED'; D3DERR_VBUF_CREATE_FAILED: Result := 'D3DERR_VBUF_CREATE_FAILED'; D3DERR_VERTEXBUFFERLOCKED: Result := 'D3DERR_VERTEXBUFFERLOCKED'; D3DERR_ZBUFFER_NOTPRESENT: Result := 'D3DERR_ZBUFFER_NOTPRESENT'; D3DERR_STENCILBUFFER_NOTPRESENT: Result := 'D3DERR_STENCILBUFFER_NOTPRESENT'; D3DERR_WRONGTEXTUREFORMAT: Result := 'D3DERR_WRONGTEXTUREFORMAT'; D3DERR_UNSUPPORTEDCOLOROPERATION: Result := 'D3DERR_UNSUPPORTEDCOLOROPERATION'; D3DERR_UNSUPPORTEDCOLORARG: Result := 'D3DERR_UNSUPPORTEDCOLORARG'; D3DERR_UNSUPPORTEDALPHAOPERATION: Result := 'D3DERR_UNSUPPORTEDALPHAOPERATION'; D3DERR_UNSUPPORTEDALPHAARG: Result := 'D3DERR_UNSUPPORTEDALPHAARG'; D3DERR_TOOMANYOPERATIONS: Result := 'D3DERR_TOOMANYOPERATIONS'; D3DERR_CONFLICTINGTEXTUREFILTER: Result := 'D3DERR_CONFLICTINGTEXTUREFILTER'; D3DERR_UNSUPPORTEDFACTORVALUE: Result := 'D3DERR_UNSUPPORTEDFACTORVALUE'; D3DERR_CONFLICTINGRENDERSTATE: Result := 'D3DERR_CONFLICTINGRENDERSTATE'; D3DERR_UNSUPPORTEDTEXTUREFILTER: Result := 'D3DERR_UNSUPPORTEDTEXTUREFILTER'; D3DERR_TOOMANYPRIMITIVES: Result := 'D3DERR_TOOMANYPRIMITIVES'; D3DERR_INVALIDMATRIX: Result := 'D3DERR_INVALIDMATRIX'; D3DERR_TOOMANYVERTICES: Result := 'D3DERR_TOOMANYVERTICES'; D3DERR_CONFLICTINGTEXTUREPALETTE: Result := 'D3DERR_CONFLICTINGTEXTUREPALETTE'; else Result := 'Unrecognized Error'; end; end; initialization begin DisableFPUExceptions; if not IsNTandDelphiRunning then begin DXFileDLL := LoadLibrary('D3DXOF.DLL'); DirectXFileCreate := GetProcAddress(DXFileDLL,'DirectXFileCreate'); end; end; finalization begin FreeLibrary(DXFileDLL); end; end.
unit Utils.TArrayUtil; interface type TArrayUtil<T> = class public class procedure Append(var AArray: TArray<T>; const AValue: T); end; implementation { TArrayUtil<T> } class procedure TArrayUtil<T>.Append(var AArray: TArray<T>; const AValue: T); begin SetLength(AArray, Length(AArray) + 1); AArray[High(AArray)] := AValue; end; end.
unit xn.grid.link.sample; interface uses System.SysUtils, System.Classes, Generics.Collections, xn.grid.common; type IxnGridLinkCustom<T> = interface(IxnGridLink) ['{29DA3AC6-EA0C-4CE0-934D-D6D0A48CEF4C}'] procedure First; procedure Last; procedure Prior; procedure Next; procedure Clear; procedure Append(aString: string); procedure Insert(aIndex: Integer; aString: string); procedure Edit(aIndex: Integer; aString: string); procedure Delete(aIndex: Integer); procedure LogSet(aValue: TStrings); function LogGet: TStrings; end; TxnGridLinkCustom<T> = class(TInterfacedObject, IxnGridLinkCustom<T>) strict private fLog: TStrings; fItems: TList<string>; fRecNo: Integer; fNotify: TxnGridLinkNotify; function RowCountGet: Integer; procedure RecNoSet(aIndex: Integer); function RecNoGet: Integer; procedure NotifySet(aRowEvent: TxnGridLinkNotify); procedure LogSet(aValue: TStrings); function LogGet: TStrings; procedure LogString(aString: String); procedure Move(aIndex: Integer); public constructor Create; destructor Destroy; override; procedure First; procedure Last; procedure Prior; procedure Next; procedure Clear; procedure Append(aString: string); procedure Insert(aIndex: Integer; aString: string); procedure Edit(aIndex: Integer; aString: string); procedure Delete(aIndex: Integer); function ValueString(aCol, aRow: Integer): String; function ValueFloat(aCol, aRow: Integer): Double; end; TxnGridLinkSample = class(TxnGridLinkCustom<string>) end; implementation { TxnGridLinkSample } procedure TxnGridLinkCustom<T>.Append(aString: string); begin LogString(Format('TxnGridLinkCustom<T>.Append()', [])); Insert(RowCountGet, aString); end; procedure TxnGridLinkCustom<T>.Insert(aIndex: Integer; aString: string); begin LogString(Format('TxnGridLinkCustom<T>.Insert(%d)', [aIndex])); fItems.Insert(aIndex, aString); if Assigned(fNotify) then fNotify(xnGridNotifyDataCreateLinkEvent(aIndex, gekAdd)); RecNoSet(aIndex); end; procedure TxnGridLinkCustom<T>.Delete(aIndex: Integer); begin LogString(Format('TxnGridLinkCustom<T>.Delete(%d)', [aIndex])); fItems.Delete(aIndex); if Assigned(fNotify) then fNotify(xnGridNotifyDataCreateLinkEvent(aIndex, gekDel)); RecNoSet(aIndex); end; procedure TxnGridLinkCustom<T>.Edit(aIndex: Integer; aString: string); begin LogString(Format('TxnGridLinkCustom<T>.Edit(%d)', [aIndex])); fItems[aIndex] := aString; if Assigned(fNotify) then fNotify(xnGridNotifyDataCreateLinkEvent(aIndex, gekEdit)); RecNoSet(aIndex); end; procedure TxnGridLinkCustom<T>.Move(aIndex: Integer); begin LogString(Format('TxnGridLinkCustom<T>.Move.Outer(%d)', [aIndex])); if RecNoGet() = aIndex then Exit; LogString(Format('TxnGridLinkCustom<T>.Move.Inner(%d)', [aIndex])); if Assigned(fNotify) then fNotify(xnGridNotifyDataCreateLinkEvent(aIndex, gekMove)); RecNoSet(aIndex); end; procedure TxnGridLinkCustom<T>.First; begin LogString(Format('TxnGridLinkCustom<T>.First(%d)', [0])); if RecNoGet() > 0 then Move(0); end; procedure TxnGridLinkCustom<T>.Last; var r: Integer; begin r := RowCountGet() - 1; LogString(Format('TxnGridLinkCustom<T>.Last(%d)', [r])); if RecNoGet() < r then Move(r); end; procedure TxnGridLinkCustom<T>.Prior; var r: Integer; begin r := RecNoGet(); LogString(Format('TxnGridLinkCustom<T>.Prior(%d)', [r - 1])); if r > 0 then Move(r - 1); end; procedure TxnGridLinkCustom<T>.Next; var r: Integer; begin r := RecNoGet(); LogString(Format('TxnGridLinkCustom<T>.Next(%d)', [r + 1])); if r < RowCountGet() - 1 then Move(r + 1); end; function TxnGridLinkCustom<T>.LogGet: TStrings; begin Result := fLog end; procedure TxnGridLinkCustom<T>.LogSet(aValue: TStrings); begin fLog := aValue end; procedure TxnGridLinkCustom<T>.LogString(aString: String); begin if fLog <> nil then fLog.add(aString); end; procedure TxnGridLinkCustom<T>.Clear; begin LogString(Format('TxnGridLinkCustom<T>.Clear()', [])); fItems.Clear; if Assigned(fNotify) then fNotify(xnGridNotifyDataCreateLinkEvent(0, gekAdd)); RecNoSet(-1); end; constructor TxnGridLinkCustom<T>.Create; begin fLog := nil; fNotify := nil; fRecNo := -1; fItems := TList<string>.Create; end; destructor TxnGridLinkCustom<T>.Destroy; begin fLog := nil; fItems.Clear; fItems.Free; inherited; end; function TxnGridLinkCustom<T>.RecNoGet(): Integer; begin Result := fRecNo end; procedure TxnGridLinkCustom<T>.RecNoSet(aIndex: Integer); begin LogString(Format('TxnGridLinkCustom<T>.RecNoSet(%d)', [aIndex])); if aIndex < 0 then aIndex := 0; if aIndex > RowCountGet - 1 then aIndex := RowCountGet - 1; if fRecNo <> aIndex then fRecNo := aIndex; end; function TxnGridLinkCustom<T>.RowCountGet: Integer; begin Result := fItems.Count; end; procedure TxnGridLinkCustom<T>.NotifySet(aRowEvent: TxnGridLinkNotify); begin fNotify := aRowEvent; end; function TxnGridLinkCustom<T>.ValueFloat(aCol, aRow: Integer): Double; begin Result := StrToFloat(ValueString(aCol, aRow)); end; function TxnGridLinkCustom<T>.ValueString(aCol, aRow: Integer): String; begin if aRow < 0 then Exit(''); if aRow >= fItems.Count then Exit(''); Result := fItems[aRow] end; end.
unit SingleDriverRoundTripGenericResponseUnit; interface uses REST.Json.Types, AddressUnit, RouteParametersUnit; type TSingleDriverRoundTripGenericResponse = class private [JSONNameAttribute('addresses')] FAddresses: TAddressesArray; [JSONNameAttribute('parameters')] FParameters: TRouteParameters; [JSONNameAttribute('optimization_problem_id')] FOptimizationProblemId: String; [JSONNameAttribute('state')] FMyState: integer; public // Using the defined "RouteParameters", can use user-defined class instead property Parameters: TRouteParameters read FParameters write FParameters; // Using the defined class "Address", can use user-defined class instead property Addresses: TAddressesArray read FAddresses write FAddresses; property OptimizationProblemId: String read FOptimizationProblemId write FOptimizationProblemId; property MyState: integer read FMyState write FMyState; end; implementation end.
unit Model.FileControl; interface uses Model.Interfaces, System.Classes, System.SysUtils; type TModelFileControl = class(TInterfacedObject, iModelFileControl) private FStringList: TStringList; public constructor Create; Destructor Destroy; override; class function New : iModelFileControl; function Add( aValue : String) : iModelFileControl; function Clear : iModelFileControl; function SaveToFile( aValue : String) : iModelFileControl; function Text : String; end; implementation { TModelStringListControl } function TModelFileControl.Add(aValue: String): iModelFileControl; begin Result := Self; FStringList.Add(aValue); end; function TModelFileControl.Clear: iModelFileControl; begin Result := Self; FStringList.Clear; end; constructor TModelFileControl.Create; begin FStringList := TStringList.Create; end; destructor TModelFileControl.Destroy; begin FStringList.DisposeOf; inherited; end; class function TModelFileControl.New: iModelFileControl; begin Result := Self.Create; end; function TModelFileControl.SaveToFile(aValue: String): iModelFileControl; begin Result := Self; if ForceDirectories(ExtractFilePath(aValue)) then FStringList.SaveToFile(aValue); end; function TModelFileControl.Text: String; begin Result := FStringList.Text; end; end.
unit ComboAccessProviderParams_Const; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "EVD" // Модуль: "w:/common/components/rtl/Garant/EVD/ComboAccessProviderParams_Const.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<Tag::Class>> Shared Delphi Low Level::EVD::Standard::evdTasks::ComboAccessProviderParams // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Константы для значений тега ComboAccessProviderParams . // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\EVD\evdDefine.inc} interface uses k2Base {a}, evdTasks_Schema ; function k2_attrDataServerHostName: Integer; function k2_attrDataServerPort: Integer; function k2_typComboAccessProviderParams: ComboAccessProviderParamsTag; implementation uses k2Facade {a}, k2Attributes {a} ; var g_ComboAccessProviderParams : ComboAccessProviderParamsTag = nil; // start class ComboAccessProviderParamsTag function k2_typComboAccessProviderParams: ComboAccessProviderParamsTag; begin if (g_ComboAccessProviderParams = nil) then begin Assert(Tk2TypeTable.GetInstance Is TevdTasksSchema); g_ComboAccessProviderParams := TevdTasksSchema(Tk2TypeTable.GetInstance).t_ComboAccessProviderParams; end;//g_ComboAccessProviderParams = nil Result := g_ComboAccessProviderParams; end; var g_k2_attrDataServerHostName: Integer = -1; function k2_attrDataServerHostName: Integer; begin if (g_k2_attrDataServerHostName = -1) then g_k2_attrDataServerHostName := Tk2Attributes.Instance.CheckIDByName('DataServerHostName'); Result := g_k2_attrDataServerHostName; end; var g_k2_attrDataServerPort: Integer = -1; function k2_attrDataServerPort: Integer; begin if (g_k2_attrDataServerPort = -1) then g_k2_attrDataServerPort := Tk2Attributes.Instance.CheckIDByName('DataServerPort'); Result := g_k2_attrDataServerPort; end; end.
unit uFiltroOrcamento; interface uses uFiltroProspect, System.SysUtils, uFiltroUsuario, uFiltroCliente; type TFiltroOrcamento = class private FProspect: TFiltroProspect; FUsuario: TFiltroUsuario; FData: string; FDataFinal: string; FDataInicial: string; FCliente: TFiltroCliente; FSituacao: string; FIdTipo: string; FSubTipo: Integer; FEmailEnviado: string; FDataSituacaoFinal: string; FDataSituacaoInicial: string; FId: Integer; FNumero: Integer; procedure SetProspect(const Value: TFiltroProspect); procedure SetUsuario(const Value: TFiltroUsuario); procedure SetDataFinal(const Value: string); procedure SetDataInicial(const Value: string); procedure SetCliente(const Value: TFiltroCliente); procedure SetSituacao(const Value: string); procedure SetIdTipo(const Value: string); procedure SetSubTipo(const Value: Integer); procedure SetEmailEnviado(const Value: string); procedure SetDataSituacaoFinal(const Value: string); procedure SetDataSituacaoInicial(const Value: string); procedure SetNumero(const Value: Integer); public property DataInicial: string read FDataInicial write SetDataInicial; property DataFinal: string read FDataFinal write SetDataFinal; property Usuario: TFiltroUsuario read FUsuario write SetUsuario; property Prospect: TFiltroProspect read FProspect write SetProspect; property Cliente: TFiltroCliente read FCliente write SetCliente; property Situacao: string read FSituacao write SetSituacao; property IdTipo: string read FIdTipo write SetIdTipo; property SubTipo: Integer read FSubTipo write SetSubTipo; property EmailEnviado: string read FEmailEnviado write SetEmailEnviado; property DataSituacaoInicial: string read FDataSituacaoInicial write SetDataSituacaoInicial; property DataSituacaoFinal: string read FDataSituacaoFinal write SetDataSituacaoFinal; property Id: Integer read FId write FId; property Numero: Integer read FNumero write SetNumero; constructor Create; destructor Destroy; override; end; implementation { TFiltroOrcamento } constructor TFiltroOrcamento.Create; begin inherited Create; FUsuario := TFiltroUsuario.Create; FProspect := TFiltroProspect.Create; FCliente := TFiltroCliente.Create; end; destructor TFiltroOrcamento.Destroy; begin FreeAndNil(FUsuario); FreeAndNil(FProspect); FreeAndNil(FCliente); inherited; end; procedure TFiltroOrcamento.SetCliente(const Value: TFiltroCliente); begin FCliente := Value; end; procedure TFiltroOrcamento.SetDataFinal(const Value: string); begin FDataFinal := Value; end; procedure TFiltroOrcamento.SetDataInicial(const Value: string); begin FDataInicial := Value; end; procedure TFiltroOrcamento.SetDataSituacaoFinal(const Value: string); begin FDataSituacaoFinal := Value; end; procedure TFiltroOrcamento.SetDataSituacaoInicial(const Value: string); begin FDataSituacaoInicial := Value; end; procedure TFiltroOrcamento.SetEmailEnviado(const Value: string); begin FEmailEnviado := Value; end; procedure TFiltroOrcamento.SetIdTipo(const Value: string); begin FIdTipo := Value; end; procedure TFiltroOrcamento.SetNumero(const Value: Integer); begin FNumero := Value; end; procedure TFiltroOrcamento.SetProspect(const Value: TFiltroProspect); begin FProspect := Value; end; procedure TFiltroOrcamento.SetSituacao(const Value: string); begin FSituacao := Value; end; procedure TFiltroOrcamento.SetSubTipo(const Value: Integer); begin FSubTipo := Value; end; procedure TFiltroOrcamento.SetUsuario(const Value: TFiltroUsuario); begin FUsuario := Value; end; end.
{ *********************************************************** } { * TForge Library * } { * Copyright (c) Sergey Kasandrov 1997, 2016 * } { *********************************************************** } unit tfByteVectors; {$I TFL.inc} {$R-} // range checking is not allowed interface uses tfTypes, SysUtils; // named ByteVector to avoid name conflict with SysUtils.TByteArray type PByteVectorEnum = ^TByteVectorEnum; PByteVector = ^TByteVector; PPByteVector = ^PByteVector; TByteVector = record private const FUsedSize = SizeOf(Integer); // because SizeOf(FUsed) does not compile public type {$IFDEF DEBUG} TData = array[0..7] of Byte; {$ELSE} TData = array[0..0] of Byte; {$ENDIF} public FVTable: Pointer; FRefCount: Integer; FCapacity: Integer; // number of bytes allocated // FBigEndian: Boolean; FUsed: Integer; // number of bytes used FData: TData; class function AllocVector(var A: PByteVector; NBytes: Cardinal): TF_RESULT; static; class function GetEnum(Inst: PByteVector; var AEnum: PByteVectorEnum): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetHashCode(Inst: PByteVector): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetLen(A: PByteVector): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function SetLen(A: PByteVector; L: Integer): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetRawData(A: PByteVector): PByte; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function AssignBytes(A: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function CopyBytes(A: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function CopyBytes1(A: PByteVector; var R: PByteVector; I: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function CopyBytes2(A: PByteVector; var R: PByteVector; I, L: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function RemoveBytes1(A: PByteVector; var R: PByteVector; I: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function RemoveBytes2(A: PByteVector; var R: PByteVector; I, L: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ReverseBytes(A: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ConcatBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function InsertBytes(A: PByteVector; Index: Cardinal; B: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EqualBytes(A, B: PByteVector): Boolean; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function AddBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function SubBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function AndBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function OrBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function XorBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function AppendByte(A: PByteVector; B: Byte; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function InsertByte(A: PByteVector; Index: Cardinal; B: Byte; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EqualToByte(A: PByteVector; B: Byte): Boolean; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function AppendPByte(A: PByteVector; P: PByte; L: Cardinal; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function InsertPByte(A: PByteVector; Index: Cardinal; P: PByte; L: Cardinal; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function EqualToPByte(A: PByteVector; P: PByte; L: Integer): Boolean; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ToDec(A: PByteVector; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function Incr(A: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function Decr(A: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function IncrLE(A: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function DecrLE(A: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure Burn(A: PByteVector); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class procedure Fill(A: PByteVector; Value: Byte); {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ToInt(A: PByteVector; Data: PByte; L: Cardinal; Reversed: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ShiftLeft(A: PByteVector; Shift: Cardinal; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function ShiftRight(A: PByteVector; Shift: Cardinal; var R: PByteVector): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetBitSet(A: PByteVector; Shift: Cardinal): Boolean; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; class function GetSeniorBit(A: PByteVector): Integer; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static; end; // for .. in iteration support TByteVectorEnum = record private FVTable: Pointer; FRefCount: Integer; FVector: PByteVector; FIndex: Integer; public class function Release(Inst: PByteVectorEnum): Integer; stdcall; static; class function Init(var Inst: PByteVectorEnum; AVector: PByteVector): TF_RESULT; static; class function GetCurrent(Inst: PByteVectorEnum): Byte; static; class function MoveNext(Inst: PByteVectorEnum): Boolean; static; class procedure Reset(Inst: PByteVectorEnum); static; end; function ByteVectorAlloc(var A: PByteVector; ASize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorAllocEx(var A: PByteVector; ASize: Cardinal; Filler: Byte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorAllocRand(var A: PByteVector; ASize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorReAlloc(var A: PByteVector; ASize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorSetLen(var A: PByteVector; L: Integer): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorFromPByte(var A: PByteVector; P: PByte; L: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorFromPByteEx(var A: PByteVector; P: PByte; L: Cardinal; Reversed: Boolean): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorParse(var A: PByteVector; P: PByte; L: Cardinal; CharSize: Cardinal; Delimiter: Byte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorFromPCharHex(var A: PByteVector; P: PByte; L: Cardinal; CharSize: Cardinal): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorParseHex(var A: PByteVector; P: PByte; L: Cardinal; CharSize: Cardinal; Delimiter: Byte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} function ByteVectorFromByte(var A: PByteVector; Value: Byte): TF_RESULT; {$IFDEF TFL_STDCALL}stdcall;{$ENDIF} implementation uses tfRecords, tfUtils, tfRandEngines; const ByteVecVTable: array[0..40] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TForgeInstance.Release, @TByteVector.Burn, @TByteVector.GetEnum, @TByteVector.GetHashCode, @TByteVector.GetLen, @TByteVector.SetLen, @TByteVector.GetRawData, @TByteVector.AssignBytes, @TByteVector.CopyBytes, @TByteVector.CopyBytes1, @TByteVector.CopyBytes2, @TByteVector.RemoveBytes1, @TByteVector.RemoveBytes2, @TByteVector.ReverseBytes, @TByteVector.ConcatBytes, @TByteVector.InsertBytes, @TByteVector.EqualBytes, @TByteVector.AddBytes, @TByteVector.SubBytes, @TByteVector.AndBytes, @TByteVector.OrBytes, @TByteVector.XorBytes, @TByteVector.AppendByte, @TByteVector.InsertByte, @TByteVector.EqualToByte, @TByteVector.AppendPByte, @TByteVector.InsertPByte, @TByteVector.EqualToByte, @TByteVector.ToDec, @TByteVector.Incr, @TByteVector.Decr, @TByteVector.Fill, @TByteVector.ToInt, @TByteVector.IncrLE, @TByteVector.DecrLE, @TByteVector.ShiftLeft, @TByteVector.ShiftRight, @TByteVector.GetBitSet, @TByteVector.GetSeniorBit ); const ByteVecEnumVTable: array[0..5] of Pointer = ( @TForgeInstance.QueryIntf, @TForgeInstance.Addref, @TByteVectorEnum.Release, @TByteVectorEnum.GetCurrent, @TByteVectorEnum.MoveNext, @TByteVectorEnum.Reset ); const ZeroVector: TByteVector = ( FVTable: @ByteVecVTable; FRefCount: -1; FCapacity: 0; // FBigEndian: True; FUsed: 0; {$IFDEF DEBUG} FData: (0, 0, 0, 0, 0, 0, 0, 0); {$ELSE} FData: (0); {$ENDIF} ); { TByteVector } const ByteVecPrefixSize = SizeOf(TByteVector) - SizeOf(TByteVector.TData); MaxCapacity = $01000000; class function TByteVector.AllocVector(var A: PByteVector; NBytes: Cardinal): TF_RESULT; var BytesRequired: Cardinal; begin if NBytes >= MaxCapacity then begin Result:= TF_E_NOMEMORY; Exit; end; if NBytes = 0 then begin A:= @ZeroVector; Result:= TF_S_OK; Exit; end; BytesRequired:= NBytes + ByteVecPrefixSize; BytesRequired:= (BytesRequired + 7) and not 7; try GetMem(A, BytesRequired); A^.FVTable:= @ByteVecVTable; A^.FRefCount:= 1; // A^.FBigEndian:= True; A^.FCapacity:= BytesRequired - ByteVecPrefixSize; A^.FUsed:= NBytes; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; class function TByteVector.GetLen(A: PByteVector): Integer; begin Result:= A.FUsed; end; class function TByteVector.SetLen(A: PByteVector; L: Integer): TF_RESULT; begin if Cardinal(L) <= Cardinal(A.FCapacity) then begin A.FUsed:= L; Result:= TF_S_OK; end else Result:= TF_E_INVALIDARG; end; class function TByteVector.ShiftLeft(A: PByteVector; Shift: Cardinal; var R: PByteVector): TF_RESULT; var ByteShift: Cardinal; BitShift: Cardinal; UsedA, N: Cardinal; Tmp: PByteVector; Carry: Byte; W: Word; Src, Tgt: PByte; begin UsedA:= A.FUsed; Result:= AllocVector(Tmp, UsedA); if Result <> TF_S_OK then Exit; FillChar(Tmp.FData, UsedA, 0); ByteShift:= Shift shr 3; if ByteShift < UsedA then begin BitShift:= Shift and 7; N:= UsedA - ByteShift; // N > 0 if BitShift = 0 then begin Move(A.FData[ByteShift], Tmp.FData, N); end else begin Src:= @A.FData[ByteShift]; Tgt:= @Tmp.FData; Carry:= 0; repeat W:= Src^; W:= W shl BitShift; Tgt^:= WordRec(W).Lo or Carry; Carry:= WordRec(W).Hi; Dec(N); Inc(Src); Inc(Tgt); until N = 0; end; end; tfFreeInstance(R); // if R <> nil then TtfRecord.Release(R); R:= Tmp; Result:= TF_S_OK; end; class function TByteVector.ShiftRight(A: PByteVector; Shift: Cardinal; var R: PByteVector): TF_RESULT; var ByteShift: Cardinal; BitShift: Cardinal; UsedA, N: Cardinal; Tmp: PByteVector; Carry: Byte; W: Word; Src, Tgt: PByte; begin UsedA:= A.FUsed; Result:= AllocVector(Tmp, UsedA); if Result <> TF_S_OK then Exit; FillChar(Tmp.FData, UsedA, 0); ByteShift:= Shift shr 3; if ByteShift < UsedA then begin BitShift:= Shift and 7; N:= UsedA - ByteShift; // N > 0 if BitShift = 0 then begin Move(A.FData, Tmp.FData[ByteShift], N); end else begin Src:= @A.FData; Tgt:= @Tmp.FData[ByteShift]; Carry:= 0; repeat W:= Src^; W:= W shl (8 - BitShift); Tgt^:= WordRec(W).Hi or Carry; Carry:= WordRec(W).Lo; Dec(N); Inc(Src); Inc(Tgt); until N = 0; end; end; tfFreeInstance(R); // if R <> nil then TtfRecord.Release(R); R:= Tmp; Result:= TF_S_OK; end; class function TByteVector.GetBitSet(A: PByteVector; Shift: Cardinal): Boolean; var ByteShift: Cardinal; BitShift: Cardinal; UsedA, N: Cardinal; B: Byte; Mask: Byte; begin UsedA:= A.FUsed; ByteShift:= Shift shr 3; if (ByteShift < UsedA) then begin BitShift:= Shift and 7; B:= A.FData[UsedA - ByteShift - 1]; Mask:= 1 shl BitShift; Result:= B and Mask <> 0; end else Result:= False; end; class function TByteVector.GetSeniorBit(A: PByteVector): Integer; var N: Integer; P: PByte; Mask: Byte; begin N:= A.FUsed; P:= @A.FData; while (N > 0) do begin if (P^ = 0) then begin Dec(N); Inc(P); end else begin Mask:= $80; Result:= N shl 3 - 1; while Mask and P^ = 0 do begin Dec(Result); Mask:= Mask shr 1; end; Exit; end; end; Result:= -1; end; class function TByteVector.GetEnum(Inst: PByteVector; var AEnum: PByteVectorEnum): TF_RESULT; var Tmp: PByteVectorEnum; begin Result:= TByteVectorEnum.Init(Tmp, Inst); if Result = TF_S_OK then begin if AEnum <> nil then TByteVectorEnum.Release(AEnum); AEnum:= Tmp; end; end; class function TByteVector.GetHashCode(Inst: PByteVector): Integer; begin Result:= TJenkins1.Hash(Inst.FData, Inst.FUsed); end; class function TByteVector.ConcatBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; var UsedA, UsedB: Cardinal; P: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; UsedB:= B.FUsed; Result:= AllocVector(Tmp, UsedA + UsedB); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; P:= @Tmp.FData; Move(A.FData, P^, UsedA); Inc(P, UsedA); Move(B.FData, P^, UsedB); Tmp.FUsed:= UsedA + UsedB; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.CopyBytes(A: PByteVector; var R: PByteVector): TF_RESULT; begin Result:= ByteVectorFromPByte(R, @A.FData, A.FUsed); end; class function TByteVector.ReverseBytes(A: PByteVector; var R: PByteVector): TF_RESULT; var LUsed: Integer; Tmp: PByteVector; PA, PTmp: PByte; begin LUsed:= A.FUsed; Result:= TByteVector.AllocVector(Tmp, LUsed); if Result = TF_S_OK then begin // Tmp.FBigEndian:= A.FBigEndian; PA:= @A.FData; PTmp:= @Tmp.FData; Inc(PA, LUsed); while LUsed > 0 do begin Dec(PA); PTmp^:= PA^; Inc(PTmp); Dec(LUsed); end; tfFreeInstance(R); //if R <> nil then TtfRecord.Release(R); R:= Tmp; end; end; class function TByteVector.CopyBytes1(A: PByteVector; var R: PByteVector; I: Cardinal): TF_RESULT; var L: Cardinal; begin L:= A.FUsed; if (I < L) then L:= L - I else L:= 0; Result:= ByteVectorFromPByte(R, @A.FData[I], L); end; class function TByteVector.CopyBytes2(A: PByteVector; var R: PByteVector; I, L: Cardinal): TF_RESULT; var LL: Cardinal; begin LL:= A.FUsed; if (I < LL) then begin if (LL - I < L) then L:= LL - I; end else L:= 0; Result:= ByteVectorFromPByte(R, @A.FData[I], L); end; class function TByteVector.RemoveBytes1(A: PByteVector; var R: PByteVector; I: Cardinal): TF_RESULT; var L: Cardinal; begin L:= A.FUsed; if (I < L) then L:= I; Result:= ByteVectorFromPByte(R, @A.FData, L); end; class function TByteVector.RemoveBytes2(A: PByteVector; var R: PByteVector; I, L: Cardinal): TF_RESULT; var LL: Cardinal; UsedA: Cardinal; Tmp: PByteVector; PTmp: PByte; begin UsedA:= A.FUsed; LL:= UsedA; if (I < UsedA) then LL:= I; if (L > UsedA - LL) then L:= UsedA - LL; Result:= AllocVector(Tmp, UsedA - L); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; PTmp:= @Tmp.FData; if LL > 0 then begin Move(A.FData, PTmp^, LL); Inc(PTmp, LL); end; if UsedA - L > LL then Move(A.FData[UsedA - L], PTmp^, UsedA - L - LL); Tmp.FUsed:= UsedA - L; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.EqualBytes(A, B: PByteVector): Boolean; begin Result:= (A.FUsed = B.FUsed) and CompareMem(@A.FData, @B.FData, A.FUsed); end; class function TByteVector.AddBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; var UsedA, UsedB, UsedR: Cardinal; PA, PB, PR: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; UsedB:= B.FUsed; UsedR:= UsedA; if UsedR > UsedB then UsedR:= UsedB; Result:= AllocVector(Tmp, UsedR); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; Tmp.FUsed:= UsedR; PA:= @A.FData; PB:= @B.FData; PR:= @Tmp.FData; while UsedR > 0 do begin PR^:= PA^+PB^; Inc(PA); Inc(PB); Inc(PR); Dec(UsedR); end; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.SubBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; var UsedA, UsedB, UsedR: Cardinal; PA, PB, PR: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; UsedB:= B.FUsed; UsedR:= UsedA; if UsedR > UsedB then UsedR:= UsedB; Result:= AllocVector(Tmp, UsedR); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; Tmp.FUsed:= UsedR; PA:= @A.FData; PB:= @B.FData; PR:= @Tmp.FData; while UsedR > 0 do begin PR^:= PA^ - PB^; Inc(PA); Inc(PB); Inc(PR); Dec(UsedR); end; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.AndBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; var UsedA, UsedB, UsedR: Cardinal; PA, PB, PR: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; UsedB:= B.FUsed; UsedR:= UsedA; if UsedR > UsedB then UsedR:= UsedB; Result:= AllocVector(Tmp, UsedR); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; Tmp.FUsed:= UsedR; PA:= @A.FData; PB:= @B.FData; PR:= @Tmp.FData; while UsedR > 0 do begin PR^:= PA^ and PB^; Inc(PA); Inc(PB); Inc(PR); Dec(UsedR); end; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.OrBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; var UsedA, UsedB, UsedR: Cardinal; PA, PB, PR: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; UsedB:= B.FUsed; UsedR:= UsedA; if UsedR > UsedB then UsedR:= UsedB; Result:= AllocVector(Tmp, UsedR); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; Tmp.FUsed:= UsedR; PA:= @A.FData; PB:= @B.FData; PR:= @Tmp.FData; while UsedR > 0 do begin PR^:= PA^ or PB^; Inc(PA); Inc(PB); Inc(PR); Dec(UsedR); end; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.XorBytes(A, B: PByteVector; var R: PByteVector): TF_RESULT; var UsedA, UsedB, UsedR: Cardinal; PA, PB, PR: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; UsedB:= B.FUsed; UsedR:= UsedA; if UsedR > UsedB then UsedR:= UsedB; Result:= AllocVector(Tmp, UsedR); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; Tmp.FUsed:= UsedR; PA:= @A.FData; PB:= @B.FData; PR:= @Tmp.FData; while UsedR > 0 do begin PR^:= PA^ xor PB^; Inc(PA); Inc(PB); Inc(PR); Dec(UsedR); end; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.AssignBytes(A: PByteVector; var R: PByteVector): TF_RESULT; begin tfFreeInstance(R); //if R <> nil then TtfRecord.Release(R); R:= A; tfAddrefInstance(A); //if A <> nil then TtfRecord.AddRef(A); Result:= TF_S_OK; end; class function TByteVector.ToInt(A: PByteVector; Data: PByte; L: Cardinal; Reversed: Boolean): TF_RESULT; var LA, LL: Cardinal; P, Sent: PByte; begin LA:= A.FUsed; if (L > LA) then begin FillChar((Data + (L - LA))^, L - LA, 0); LL:= LA; end else begin if (L < LA) then begin P:= @A.FData; if Reversed then begin Sent:= P + (LA - L); end else begin Sent:= P + LA; Inc(P, L); end; repeat if P^ <> 0 then begin Result:= TF_E_INVALIDARG; Exit; end; Inc(P); until P = Sent; end; LL:= L; end; if LA > 0 then begin if Reversed then TBigEndian.ReverseCopy(PByte(@A.FData) + (LA - LL), PByte(@A.FData) + LA, Data) else Move(A.FData, Data^, LL); end; Result:= TF_S_OK; end; class function TByteVector.ToDec(A: PByteVector; var R: PByteVector): TF_RESULT; var Tmp: PByteVector; PA, PTmp: PByte; B: Byte; UsedA: Integer; begin UsedA:= A.FUsed; if (UsedA = 0) then begin tfFreeInstance(R); //if R <> nil then TtfRecord.Release(R); R:= @ZeroVector; Result:= TF_S_OK; Exit; end; Result:= AllocVector(Tmp, A.FUsed * 4); if Result <> TF_S_OK then Exit; PA:= @A.FData; PTmp:= @Tmp.FData; repeat B:= PA^; if B >= 100 then begin PTmp^:= B div 100 + $30; B:= B mod 100; Inc(PTmp); PTmp^:= B div 10 + $30; Inc(PTmp); PTmp^:= B mod 10 + $30; end else if B >= 10 then begin PTmp^:= B div 10 + $30; Inc(PTmp); PTmp^:= B mod 10 + $30; end else begin PTmp^:= B + $30; end; Inc(PTmp); PTmp^:= 0; Inc(PA); Inc(PTmp); Dec(UsedA); until UsedA = 0; // last #0 is not included in the length Tmp.FUsed:= NativeInt(PTmp) - NativeInt(@Tmp.FData) - 1; tfFreeInstance(R); //if R <> nil then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.AppendByte(A: PByteVector; B: Byte; var R: PByteVector): TF_RESULT; var UsedA: Cardinal; P: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; Result:= AllocVector(Tmp, UsedA + 1); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; P:= @Tmp.FData; Move(A.FData, P^, UsedA); Inc(P, UsedA); P^:= B; Tmp.FUsed:= UsedA + 1; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class procedure TByteVector.Burn(A: PByteVector); begin FillChar(A.FData, A.FUsed, 0); A.FUsed:= 1; end; class procedure TByteVector.Fill(A: PByteVector; Value: Byte); begin FillChar(A.FData, A.FUsed, Value); end; class function TByteVector.Incr(A: PByteVector): TF_RESULT; var N: Integer; begin N:= A.FUsed; while N > 0 do begin Dec(N); Inc(A.FData[N]); if A.FData[N] <> 0 then Break; end; Result:= TF_S_OK; end; class function TByteVector.IncrLE(A: PByteVector): TF_RESULT; var N: Integer; P: PByte; begin N:= A.FUsed; P:= @A.FData; while N > 0 do begin Inc(P^); if P^ <> 0 then Break; Inc(P); Dec(N); end; Result:= TF_S_OK; end; class function TByteVector.Decr(A: PByteVector): TF_RESULT; var N: Integer; P: PByte; begin N:= A.FUsed; while N > 0 do begin Dec(N); Dec(A.FData[N]); if A.FData[N] <> $FF then Break; end; Result:= TF_S_OK; end; class function TByteVector.DecrLE(A: PByteVector): TF_RESULT; var N: Integer; P: PByte; begin N:= A.FUsed; P:= @A.FData; while N > 0 do begin Dec(P^); if P^ <> $FF then Break; Inc(P); Dec(N); end; Result:= TF_S_OK; end; class function TByteVector.InsertByte(A: PByteVector; Index: Cardinal; B: Byte; var R: PByteVector): TF_RESULT; var UsedA: Cardinal; PTmp: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; Result:= AllocVector(Tmp, UsedA + 1); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; if Index > UsedA then Index:= UsedA; PTmp:= @Tmp.FData; if Index > 0 then begin Move(A.FData, PTmp^, Index); Inc(PTmp, Index); end; PTmp^:= B; Inc(PTmp); Move(A.FData[Index], PTmp^, UsedA - Index); Tmp.FUsed:= UsedA + 1; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.EqualToByte(A: PByteVector; B: Byte): Boolean; begin Result:= (A.FUsed = 1) and (A.FData[0] = B); end; class function TByteVector.AppendPByte(A: PByteVector; P: PByte; L: Cardinal; var R: PByteVector): TF_RESULT; var UsedA: Cardinal; PA: PByte; Tmp: PByteVector; begin UsedA:= A.FUsed; if L >= MaxCapacity then Result:= TF_E_NOMEMORY else Result:= AllocVector(Tmp, UsedA + L); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; PA:= @Tmp.FData; Move(A.FData, PA^, UsedA); Inc(PA, UsedA); Move(P^, PA^, L); Tmp.FUsed:= UsedA + L; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.InsertPByte(A: PByteVector; Index: Cardinal; P: PByte; L: Cardinal; var R: PByteVector): TF_RESULT; var UsedA: Cardinal; Tmp: PByteVector; PTmp: PByte; begin UsedA:= A.FUsed; if L >= MaxCapacity then Result:= TF_E_NOMEMORY else Result:= AllocVector(Tmp, UsedA + L); if Result <> TF_S_OK then Exit; // Tmp.FBigEndian:= A.FBigEndian; if Index > UsedA then Index:= UsedA; PTmp:= @Tmp.FData; if Index > 0 then begin Move(A.FData, PTmp^, Index); Inc(PTmp, Index); end; Move(P^, PTmp^, L); Inc(PTmp, L); Move(A.FData[Index], PTmp^, UsedA - Index); Tmp.FUsed:= UsedA + L; tfFreeInstance(R); //if (R <> nil) then TtfRecord.Release(R); R:= Tmp; end; class function TByteVector.InsertBytes(A: PByteVector; Index: Cardinal; B: PByteVector; var R: PByteVector): TF_RESULT; begin Result:= InsertPByte(A, Index, @B.FData, B.FUsed, R); end; class function TByteVector.GetRawData(A: PByteVector): PByte; begin Result:= @A.FData; end; class function TByteVector.EqualToPByte(A: PByteVector; P: PByte; L: Integer): Boolean; begin Result:= (A.FUsed = L) and CompareMem(@A.FData, P, L); end; function ByteVectorAlloc(var A: PByteVector; ASize: Cardinal): TF_RESULT; var Tmp: PByteVector; begin Result:= TByteVector.AllocVector(Tmp, ASize); if Result = TF_S_OK then begin tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); A:= Tmp; end; end; function ByteVectorAllocEx(var A: PByteVector; ASize: Cardinal; Filler: Byte): TF_RESULT; var Tmp: PByteVector; begin Result:= TByteVector.AllocVector(Tmp, ASize); if Result = TF_S_OK then begin FillChar(Tmp.FData, ASize, Filler); tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); A:= Tmp; end; end; function ByteVectorAllocRand(var A: PByteVector; ASize: Cardinal): TF_RESULT; var Tmp: PByteVector; begin Result:= TByteVector.AllocVector(Tmp, ASize); if Result = TF_S_OK then begin Result:= GetRand(@Tmp.FData, ASize); if Result = TF_S_OK then begin tfFreeInstance(A); A:= Tmp; end; end; end; function ByteVectorReAlloc(var A: PByteVector; ASize: Cardinal): TF_RESULT; var Tmp: PByteVector; L: Cardinal; begin Result:= TByteVector.AllocVector(Tmp, ASize); if Result = TF_S_OK then begin if A <> nil then begin // Tmp.FBigEndian:= A.FBigEndian; L:= A.FUsed; if L > ASize then L:= ASize; Move(A.FData, Tmp.FData, L); tfReleaseInstance(A); //TtfRecord.Release(A); end; A:= Tmp; end; end; function ByteVectorSetLen(var A: PByteVector; L: Integer): TF_RESULT; begin if (A.FRefCount = 1) and (Cardinal(L) <= Cardinal(A.FCapacity)) then begin A.FUsed:= L; Result:= TF_S_OK; end else Result:= ByteVectorReAlloc(A, L); end; function ByteVectorFromPByte(var A: PByteVector; P: PByte; L: Cardinal): TF_RESULT; var Tmp: PByteVector; begin // not needed now after TByteVector.AllocVector(Tmp, 0) sets Tmp:= @ZeroVector; // if L = 0 then begin // if A <> nil then TtfRecord.Release(A); // A:= @ZeroVector; // Result:= TF_S_OK; // Exit; // end; Result:= TByteVector.AllocVector(Tmp, L); if Result = TF_S_OK then begin Move(P^, Tmp.FData, L); // Tmp.FUsed:= L; tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); A:= Tmp; end; end; function ByteVectorFromPByteEx(var A: PByteVector; P: PByte; L: Cardinal; Reversed: Boolean): TF_RESULT; var Tmp: PByteVector; begin Result:= TByteVector.AllocVector(Tmp, L); if (Result = TF_S_OK) then begin // Tmp.FBigEndian:= Reversed; if (L > 0) then begin if Reversed then TBigEndian.ReverseCopy(P, P + L, @Tmp.FData) else Move(P^, Tmp.FData, L); end; tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); A:= Tmp; end; end; function GetNibble(var B: Byte): Boolean; const ASCII_0 = Ord('0'); ASCII_9 = Ord('9'); ASCII_A = Ord('A'); ASCII_F = Ord('F'); var LB: Byte; begin LB:= B; if LB < ASCII_0 then begin Result:= False; Exit; end; if LB <= ASCII_9 then begin B:= LB - ASCII_0; Result:= True; Exit; end; LB:= LB and not $20; // UpCase if (LB < ASCII_A) or (LB > ASCII_F) then begin Result:= False; Exit; end; B:= LB + 10 - ASCII_A; Result:= True; end; function ByteVectorFromPCharHex(var A: PByteVector; P: PByte; L: Cardinal; CharSize: Cardinal): TF_RESULT; var Tmp: PByteVector; B, Nibble: Byte; PA: PByte; begin if Odd(L) then begin Result:= TF_E_INVALIDARG; Exit; end; if L = 0 then begin tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); A:= @ZeroVector; Result:= TF_S_OK; Exit; end; L:= L shr 1; Result:= TByteVector.AllocVector(Tmp, L); if Result = TF_S_OK then begin Tmp.FUsed:= L; PA:= @Tmp.FData; repeat B:= P^; if not GetNibble(B) then begin tfReleaseInstance(Tmp); // TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; Inc(P, CharSize); Nibble:= P^; if not GetNibble(Nibble) then begin tfReleaseInstance(Tmp); // TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; PA^:= B shl 4 + Nibble; Inc(PA); Inc(P, CharSize); Dec(L); until L = 0; tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); A:= Tmp; end; end; function ByteVectorParse(var A: PByteVector; P: PByte; L: Cardinal; CharSize: Cardinal; Delimiter: Byte): TF_RESULT; const ASCII_ZERO: Cardinal = Ord('0'); ASCII_NINE: Cardinal = Ord('9'); ASCII_SPACE: Cardinal = Ord(' '); var Buffer: array[0..4095] of Byte; BufCount: Cardinal; Tmp: PByteVector; TmpP: PByte; Value: Cardinal; ValueExists: Boolean; TmpSize: Cardinal; B, Nibble: Byte; IsHex: Boolean; begin // skip leading spaces while (L > 0) and (P^ <= ASCII_SPACE) do begin Inc(P, CharSize); Dec(L); end; Tmp:= nil; TmpSize:= 0; BufCount:= 0; while (L > 0) do begin Value:= 0; // State:= 0; ValueExists:= False; IsHex:= False; // 3 chars required for a valid $.. hex byte if (L > 2) and (P^ = Byte('$')) then begin Inc(P, CharSize); Dec(L); IsHex:= True; end; // 4 chars required for a valid 0x.. hex byte if (L > 3) and (P^ = ASCII_ZERO) and ((P + CharSize)^ = Byte('x')) then begin Inc(P, 2 * CharSize); Dec(L, 2); IsHex:= True; end; if IsHex then begin B:= P^; if not GetNibble(B) then begin tfFreeInstance(Tmp); //if Tmp <> nil then TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; Inc(P, CharSize); Dec(L); Nibble:= P^; if not GetNibble(Nibble) then begin tfFreeInstance(Tmp); //if Tmp <> nil then TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; Inc(P, CharSize); Dec(L); ValueExists:= True; Value:= B * 16 + Nibble; // next byte should not be a valid hex digit if (L > 0) and GetNibble(Nibble) then begin tfFreeInstance(Tmp); //if Tmp <> nil then TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; end else begin repeat B:= P^; // Inc(P, CharSize); // Dec(L); if (B >= ASCII_ZERO) and (B <= ASCII_NINE) then begin ValueExists:= True; Value:= Value * 10 + (B - ASCII_ZERO); if Value > 255 then begin tfFreeInstance(Tmp); //if Tmp <> nil then TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; Inc(P, CharSize); Dec(L); end else Break; until L = 0; end; if ValueExists then begin if BufCount = SizeOf(Buffer) then begin Inc(TmpSize, SizeOf(Buffer)); Result:= ByteVectorRealloc(Tmp, TmpSize); if Result <> TF_S_OK then begin tfFreeInstance(Tmp); //if Tmp <> nil then TtfRecord.Release(Tmp); Exit; end; TmpP:= PByte(@Tmp.FData) + TmpSize - SizeOf(Buffer); Move(Buffer, TmpP^, SizeOf(Buffer)); BufCount:= 0; end; Buffer[BufCount]:= Value; Inc(BufCount); // Inc(State); end else begin tfFreeInstance(Tmp); //if Tmp <> nil then TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; // skip spaces while (L > 0) and (P^ <= ASCII_SPACE) do begin Inc(P, CharSize); Dec(L); end; // skip delimiter if (Delimiter > 0) and (L > 0) and (P^ = Delimiter) then begin Inc(P, CharSize); Dec(L); end; // skip spaces while (L > 0) and (P^ <= ASCII_SPACE) do begin Inc(P, CharSize); Dec(L); end; end; if BufCount > 0 then begin Inc(TmpSize, BufCount); Result:= ByteVectorRealloc(Tmp, TmpSize); if Result <> TF_S_OK then begin tfFreeInstance(Tmp); //if Tmp <> nil then TtfRecord.Release(Tmp); Exit; end; TmpP:= PByte(@Tmp.FData) + TmpSize - BufCount; Move(Buffer, TmpP^, BufCount); // BufCount:= 0; end; tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); if Tmp = nil then begin A:= @ZeroVector; end else A:= Tmp; Result:= TF_S_OK; end; (* case State of 0: if (B >= ASCII_ZERO) and (B <= ASCII_NINE) then begin ValueExists:= True; Value:= Value * 10 + (B - ASCII_ZERO); if Value > 255 then begin if Tmp <> nil then TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; Inc(P, CharSize); Dec(L); end else Inc(State); 1: if ValueExists then begin // todo: if BufCount = SizeOf(Buffer) then begin Inc(TmpSize, SizeOf(Buffer)); Result:= ByteVectorRealloc(Tmp, TmpSize); if Result <> TF_S_OK then begin if Tmp <> nil then TtfRecord.Release(Tmp); Exit; end; TmpP:= PByte(@Tmp.FData) + TmpSize - SizeOf(Buffer); Move(Buffer, TmpP^, SizeOf(Buffer)); BufCount:= 0; end; Buffer[BufCount]:= Value; Inc(BufCount); Inc(State); end else begin if Tmp <> nil then TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; 2: begin // skip spaces while (L > 0) and (P^ <= ASCII_SPACE) do begin Inc(P, CharSize); Dec(L); end; Inc(State); end; 3: begin // skip delimiter if (Delimiter > 0) and (L > 0) and (P^ = Delimiter) then begin Inc(P, CharSize); Dec(L); end; Inc(State); end; 4: begin // skip spaces while (L > 0) and (P^ <= ASCII_SPACE) do begin Inc(P, CharSize); Dec(L); end; State:= 0; end; end {case}; until (L = 0); // or (PBuffer = Sentinel); else begin if Tmp <> nil then TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; until (L = 0) or (PBuffer = Sentinel); until L = 0; *) function ByteVectorParseHex(var A: PByteVector; P: PByte; L: Cardinal; CharSize: Cardinal; Delimiter: Byte): TF_RESULT; var Tmp: PByteVector; B, Nibble: Byte; PA: PByte; Cnt: Integer; begin if L = 0 then begin tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); A:= @ZeroVector; Result:= TF_S_OK; Exit; end; // L:= L shr 1; Result:= TByteVector.AllocVector(Tmp, L shr 1); if Result = TF_S_OK then begin // Tmp.FUsed:= L; PA:= @Tmp.FData; Cnt:= 0; repeat while ((P^ = $20) or (P^ = Delimiter)) and (L > 0) do begin Inc(P, CharSize); Dec(L); end; if L > 0 then begin B:= P^; if not GetNibble(B) then begin tfReleaseInstance(Tmp); //TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; Inc(P, CharSize); Dec(L); if L = 0 then begin tfReleaseInstance(Tmp); //TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; Nibble:= P^; if not GetNibble(Nibble) then begin tfReleaseInstance(Tmp); //TtfRecord.Release(Tmp); Result:= TF_E_INVALIDARG; Exit; end; PA^:= B shl 4 + Nibble; Inc(Cnt); Inc(PA); Inc(P, CharSize); Dec(L); end; until L = 0; Tmp.FUsed:= Cnt; tfFreeInstance(A); //if A <> nil then TtfRecord.Release(A); A:= Tmp; end; end; function ByteVectorFromByte(var A: PByteVector; Value: Byte): TF_RESULT; var Tmp: PByteVector; begin Result:= TByteVector.AllocVector(Tmp, 1); if Result = TF_S_OK then begin Tmp.FData[0]:= Value; tfFreeInstance(A); //if (A <> nil) then TtfRecord.Release(A); A:= Tmp; end; end; { TByteVectorEnum } class function TByteVectorEnum.Release(Inst: PByteVectorEnum): Integer; begin // we need this check because FRefCount = -1 is allowed if Inst.FRefCount > 0 then begin Result:= tfDecrement(Inst.FRefCount); if Result = 0 then begin IBytes(Inst.FVector)._Release; FreeMem(Inst); end; end else Result:= Inst.FRefCount; end; class function TByteVectorEnum.Init(var Inst: PByteVectorEnum; AVector: PByteVector): TF_RESULT; var BytesRequired: Cardinal; begin BytesRequired:= (SizeOf(TByteVectorEnum) + 7) and not 7; try GetMem(Inst, BytesRequired); Inst^.FVTable:= @ByteVecEnumVTable; Inst^.FRefCount:= 1; IBytes(AVector)._Addref; Inst^.FVector:= AVector; Inst^.FIndex:= -1; Result:= TF_S_OK; except Result:= TF_E_OUTOFMEMORY; end; end; class function TByteVectorEnum.GetCurrent(Inst: PByteVectorEnum): Byte; begin Result:= Inst.FVector.FData[Inst.FIndex]; end; class function TByteVectorEnum.MoveNext(Inst: PByteVectorEnum): Boolean; begin Result:= Inst.FIndex + 1 < Inst.FVector.FUsed; if Result then Inc(Inst.FIndex); end; class procedure TByteVectorEnum.Reset(Inst: PByteVectorEnum); begin Inst.FIndex:= -1; end; end.
unit SpriteUtils; interface uses SpriteImages; type TFlipType = ( ftNone, ftHorizontal, ftVertical, ftBoth ); function SpriteFlip( Source : TFrameImage; FlipType : TFlipType ) : TFrameImage; function SpriteStretch( Source : TFrameImage; NewWidth, NewHeight : cardinal ) : TFrameImage; function SpriteFlipStretch( Source : TFrameImage; NewWidth, NewHeight : cardinal; Flip : TFlipType ) : TFrameImage; implementation uses Windows, Classes, BitBlt, Graphics, CanvasBmp, SpeedBmp; function SpriteFlip( Source : TFrameImage; FlipType : TFlipType ) : TFrameImage; begin Result := SpriteFlipStretch( Source, Source.Width, Source.Height, FlipType ); end; function SpriteStretch( Source : TFrameImage; NewWidth, NewHeight : cardinal ) : TFrameImage; begin Result := SpriteFlipStretch( Source, NewWidth, NewHeight, ftNone ); end; function SpriteFlipStretch( Source : TFrameImage; NewWidth, NewHeight : cardinal; Flip : TFlipType ) : TFrameImage; var i : cardinal; SrcWidth : cardinal; SrcBuffer : TSpeedBitmap; DstBuffer : TSpeedBitmap; begin SrcWidth := Source.Width; if ( cardinal(SrcWidth) <> NewWidth ) or ( cardinal(Source.Height) <> NewHeight ) then begin SrcBuffer := TSpeedBitmap.CreateSized( SrcWidth, -abs(Source.Height), 8 ); DstBuffer := TSpeedBitmap.CreateSized( NewWidth, -abs(NewHeight), 8 ); try Result := TFrameImage.Create( NewWidth, NewHeight ); try Result.NewFrames( Source.FrameCount ); Result.TranspIndx := Source.TranspIndx; for i := 0 to Source.FrameCount - 1 do begin Result.FrameDelay[i] := Source.FrameDelay[i]; case Flip of ftNone : BltCopyOpaque( Source.PixelAddr[0, 0, i], SrcBuffer.ScanLines, SrcWidth, Source.Height, Source.StorageWidth, SrcBuffer.StorageWidth ); ftVertical : BltCopyFlipVertical( Source.PixelAddr[0, 0, i], SrcBuffer.ScanLines, SrcWidth, Source.Height, Source.StorageWidth, SrcBuffer.StorageWidth ); ftHorizontal : BltCopyFlipHorizontal( Source.PixelAddr[0, 0, i], SrcBuffer.ScanLines, SrcWidth, Source.Height, Source.StorageWidth, SrcBuffer.StorageWidth ); ftBoth : BltCopyFlipBoth( Source.PixelAddr[0, 0, i], SrcBuffer.ScanLines, SrcWidth, Source.Height, Source.StorageWidth, SrcBuffer.StorageWidth ); end; SrcBuffer.StretchDrawOnDC( DstBuffer.Canvas.Handle, DstBuffer.ClientRect, cmSrcCopy ); BltCopyOpaque( DstBuffer.ScanLines, Result.PixelAddr[0, 0, i], NewWidth, NewHeight, DstBuffer.StorageWidth, Result.StorageWidth ); end; except Result := nil; raise; end; finally SrcBuffer.Free; DstBuffer.Free; end; end else begin Result := TFrameImage.Create( NewWidth, NewHeight ); try Result.NewFrames( Source.FrameCount ); Result.TranspIndx := Source.TranspIndx; for i := 0 to Source.FrameCount - 1 do begin Result.FrameDelay[i] := Source.FrameDelay[i]; case Flip of ftNone : BltCopyOpaque( Source.PixelAddr[0, 0, i], Result.PixelAddr[0, 0, i], SrcWidth, Source.Height, Source.StorageWidth, Result.StorageWidth ); ftVertical : BltCopyFlipVertical( Source.PixelAddr[0, 0, i], Result.PixelAddr[0, 0, i], SrcWidth, Source.Height, Source.StorageWidth, Result.StorageWidth ); ftHorizontal : BltCopyFlipHorizontal( Source.PixelAddr[0, 0, i], Result.PixelAddr[0, 0, i], SrcWidth, Source.Height, Source.StorageWidth, Result.StorageWidth ); ftBoth : BltCopyFlipBoth( Source.PixelAddr[0, 0, i], Result.PixelAddr[0, 0, i], SrcWidth, Source.Height, Source.StorageWidth, Result.StorageWidth ); end; end; except raise; end; end; end; end.
{******************************************************************************* 作者: dmzn@163.com 2020-08-13 描述: 基础档案 *******************************************************************************} unit UFormBaseInfo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFormNormal, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore, dxSkinsDefaultPainters, dxLayoutControl, StdCtrls, cxContainer, cxEdit, cxMemo, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCheckBox; type TfFormBaseInfo = class(TfFormNormal) EditTypes: TcxComboBox; dxLayout1Item3: TdxLayoutItem; EditMemo: TcxMemo; dxLayout1Item5: TdxLayoutItem; EditName: TcxComboBox; dxLayout1Item6: TdxLayoutItem; Check1: TcxCheckBox; dxLayout1Item4: TdxLayoutItem; EditParamA: TcxTextEdit; dxLayout1Item7: TdxLayoutItem; CheckDef: TcxCheckBox; dxLayout1Item8: TdxLayoutItem; dxGroup2: TdxLayoutGroup; dxLayout1Item9: TdxLayoutItem; EditParamB: TcxTextEdit; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnOKClick(Sender: TObject); procedure EditTypesPropertiesEditValueChanged(Sender: TObject); procedure EditNameKeyPress(Sender: TObject; var Key: Char); private { Private declarations } FRecordID: string; {*记录编号*} FBaseData: Integer; {*基础档案*} FSaveResult: Integer; procedure InitFormData(const nID: string); procedure ResetFormData; {*界面数据*} public { Public declarations } class function CreateForm(const nPopedom: string = ''; const nParam: Pointer = nil): TWinControl; override; class function FormID: integer; override; function OnVerifyCtrl(Sender: TObject; var nHint: string): Boolean; override; end; implementation {$R *.dfm} uses ULibFun, UFormCtrl, UFormBase, UMgrControl, USysDB, USysConst, USysBusiness, UDataModule; class function TfFormBaseInfo.CreateForm(const nPopedom: string; const nParam: Pointer): TWinControl; var nP: PFormCommandParam; begin Result := nil; if Assigned(nParam) then nP := nParam else Exit; case nP.FCommand of cCmd_AddData: with TfFormBaseInfo.Create(Application) do begin FRecordID := ''; FBaseData := nP.FParamA; if FBaseData < 0 then Caption := '添加' else Caption := Format('添加 - %s', [cBaseData[FBaseData].FDesc]); InitFormData(''); ShowModal; nP.FCommand := cCmd_ModalResult; nP.FParamA := FSaveResult; Free; end; cCmd_EditData: with TfFormBaseInfo.Create(Application) do begin FRecordID := nP.FParamA; FBaseData := -1; InitFormData(FRecordID); ShowModal; nP.FCommand := cCmd_ModalResult; nP.FParamA := FSaveResult; Free; end; end; end; class function TfFormBaseInfo.FormID: integer; begin Result := cFI_FormBaseInfo; end; procedure TfFormBaseInfo.FormCreate(Sender: TObject); begin inherited; FSaveResult := mrCancel; LoadFormConfig(Self); end; procedure TfFormBaseInfo.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveFormConfig(Self); inherited; end; procedure TfFormBaseInfo.InitFormData(const nID: string); var nStr: string; nIdx: Integer; begin if nID <> '' then begin Check1.Checked := False; Check1.Visible := False; nStr := Format('Select * From %s Where B_ID=%s', [sTable_BaseInfo, nID]); with FDM.QueryTemp(nStr) do begin if RecordCount < 1 then begin BtnOK.Enabled := False; ShowMsg('档案数据已丢失', sHint); Exit; end; EditName.Text := FieldByName('B_Text').AsString; EditMemo.Text := FieldByName('B_Memo').AsString; EditParamA.Text := FieldByName('B_ParamA').AsString; EditParamB.Text := FieldByName('B_ParamB').AsString; CheckDef.Checked := FieldByName('B_Default').AsString = sFlag_Yes; nStr := FieldByName('B_Group').AsString; for nIdx:=Low(cBaseData) to High(cBaseData) do if cBaseData[nIdx].FName = nStr then begin FBaseData := nIdx; Caption := Format('修改 - %s', [cBaseData[nIdx].FDesc]); Break; end; end; end; with EditTypes.Properties do begin Items.Clear; for nIdx:=Low(cBaseData) to High(cBaseData) do begin Items.AddObject(IntToStr(nIdx+1) + '.' + cBaseData[nIdx].FDesc, Pointer(nIdx)); if nIdx = FBaseData then EditTypes.ItemIndex := nIdx; //xxxxx end; end; if EditTypes.ItemIndex >= 0 then ActiveControl := EditName; //xxxxx end; //Desc: 重置界面数据 procedure TfFormBaseInfo.ResetFormData; begin EditName.Clear; EditMemo.Clear; CheckDef.Checked := False; end; procedure TfFormBaseInfo.EditTypesPropertiesEditValueChanged(Sender: TObject); var nIdx: Integer; begin with EditName.Properties do begin Items.Clear; if EditTypes.ItemIndex < 0 then Exit; nIdx := Integer(EditTypes.Properties.Items.Objects[EditTypes.ItemIndex]); if cBaseData[nIdx].FValue <> '' then SplitStr(cBaseData[nIdx].FValue, Items, 0, '|'); //xxxxx end; end; procedure TfFormBaseInfo.EditNameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; BtnOK.Click(); end; end; function TfFormBaseInfo.OnVerifyCtrl(Sender: TObject; var nHint: string): Boolean; begin Result := True; if Sender = EditTypes then begin nHint := '请选择类型'; Result := EditTypes.ItemIndex >= 0; if Result then FBaseData := Integer(EditTypes.Properties.Items.Objects[EditTypes.ItemIndex]); //xxxxx end else if Sender = EditName then begin Result := Trim(EditName.Text) <> ''; nHint := '请填写名称'; end; end; procedure TfFormBaseInfo.BtnOKClick(Sender: TObject); var nVal: TBaseDataItem; begin if not IsDataValid then Exit; //verify data with nVal do begin FRecord := FRecordID; FGroup := cBaseData[FBaseData].FName; FGroupName := cBaseData[FBaseData].FDesc; FName := EditName.Text; FParamA := EditParamA.Text; FParamB := EditParamB.Text; FMemo := EditMemo.Text; FDefault := CheckDef.Checked; end; SaveBaseDataItem(@nVal, True); FSaveResult := mrOk; if Check1.Checked then begin ResetFormData; ShowMsg('保存成功', sHint); end else ModalResult := mrOk; end; initialization gControlManager.RegCtrl(TfFormBaseInfo, TfFormBaseInfo.FormID); end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_MeshAnimation * Implements the Animation resource and other Animation classes *********************************************************************************************************************** } Unit TERRA_MeshAnimation; {$I terra.inc} Interface Uses TERRA_String, TERRA_Utils, TERRA_Stream, TERRA_Resource, TERRA_Vector3D, TERRA_Math, TERRA_Matrix4x4, TERRA_Vector2D, TERRA_Color, TERRA_Quaternion, TERRA_ResourceManager, TERRA_MeshSkeleton; Const TimeCompressionLimit = 20000; CompressionLimit1 = 127; CompressionLimit2 = 20000; Type BoneAnimation = Class; VectorKeyFrame=Record Time:Single; Value:Vector3D; End; VectorKeyframeArray = Class(TERRAObject) Protected _Owner:BoneAnimation; Public Keyframes:Array Of VectorKeyFrame; Count:Integer; Constructor Create(Owner:BoneAnimation); Procedure Clone(Other:VectorKeyframeArray); Function GetKey(Time:Single):Integer; Procedure AddKey(Time:Single; Value:Vector3D); Function GetExactKey(Time:Single):Integer; Procedure Load(Source:Stream); Procedure Save(Dest:Stream); Function GetLength():Single; Procedure Crop(Time:Single); Procedure CloseLoop(); Procedure Clear(); Property Owner:BoneAnimation Read _Owner; Property Length:Single Read GetLength; End; Animation = Class; AnimationTransformBlock = Object Translation:Vector3D; Scale:Vector3D; Rotation:Quaternion; End; BoneAnimation = Class(TERRAObject) Name:TERRAString; ID:Integer; Owner:Animation; Positions:VectorKeyframeArray; Rotations:VectorKeyframeArray; Scales:VectorKeyframeArray; Constructor Create(ID:Integer; Owner:Animation); Procedure Release; Override; Procedure Load(Source:Stream); Procedure Save(Dest:Stream); Function GetLength():Single; Procedure Crop(Time:Single); Procedure CloseLoop(); Procedure GetTransform(Time:Single; Out Block:AnimationTransformBlock); Property Length:Single Read GetLength; End; Animation = Class(Resource) Protected _BoneCount:Integer; _Bones:Array Of BoneAnimation; _Duration:Single; // max * last key Public FPS:Single; Loop:Boolean; LoopPoint:Single; Speed:Single; Next:TERRAString; Procedure Clone(Other:Animation); Function Load(Source:Stream):Boolean; Override; Procedure Save(Dest:Stream); Overload; Procedure Save(FileName:TERRAString); Overload; Class Function GetManager:Pointer; Override; Function GetLength:Single; Procedure Crop(Time:Single); Procedure CloseLoop(); Function AddBone(Const Name:TERRAString):BoneAnimation; Function GetBone(Index:Integer):BoneAnimation; Function GetBoneIndex(Const Name:TERRAString):Integer; Function Unload:Boolean; Override; Function Update:Boolean; Override; Property BoneCount:Integer Read _BoneCount; Property Length:Single Read GetLength; End; AnimationManager = Class(ResourceManager) Public Procedure Release; Override; Class Function Instance:AnimationManager; Function GetAnimation(Name:TERRAString; ValidateError:Boolean = True):Animation; End; Function FrameToTime(Frame, FPS:Single):Single; Function TimeToFrame(Time, FPS:Single):Integer; Implementation Uses TERRA_Error, TERRA_Log, TERRA_Application, TERRA_OS, TERRA_FileManager, TERRA_Mesh, TERRA_GraphicsManager, TERRA_FileStream, TERRA_FileUtils; Var _AnimationManager:ApplicationObject; Function FrameToTime(Frame, FPS:Single):Single; Begin If (FPS>0) Then Result := Frame / FPS Else Result := 0; End; Function TimeToFrame(Time, FPS:Single):Integer; Begin If (FPS>0) Then Result := Trunc(Time * FPS) Else Result := 0; End; { AnimationManager } Class Function AnimationManager.Instance:AnimationManager; Begin If _AnimationManager = Nil Then Begin _AnimationManager := InitializeApplicationComponent(AnimationManager, Nil); AnimationManager(_AnimationManager.Instance).AutoUnload := False; End; Result := AnimationManager(_AnimationManager.Instance); End; Procedure AnimationManager.Release; Begin Inherited; _AnimationManager := Nil; End; Function AnimationManager.GetAnimation(Name:TERRAString; ValidateError:Boolean):Animation; Var S:TERRAString; Begin Result := Nil; Name := StringTrim(Name); If (Name='') Then Exit; If (StringFirstChar(Name) = Ord('@')) Then Name := StringCopy(Name, 2, MaxInt); Result := Animation(GetResource(Name)); If (Not Assigned(Result)) Then Begin S := FileManager.Instance.SearchResourceFile(Name+'.anim'); If S<>'' Then Begin Result := Animation.Create(rtLoaded, S); Result.Priority := 70; Self.AddResource(Result); End Else If ValidateError Then RaiseError('Could not find animation. ['+Name +']'); End; End; { VectorKeyframeArray } Function VectorKeyframeArray.GetKey(Time:Single):Integer; Var I:Integer; Begin If (Count > 0) And (Time >= KeyFrames[Pred(Count)].Time) Then Begin Result := Pred(Count); Exit; End; Result := 0; For I:=1 To Pred(Count) Do Begin If (KeyFrames[I].Time >= Time) Then Begin Result := I; Break; End; End; End; Function VectorKeyframeArray.GetExactKey(Time:Single):Integer; Var I:Integer; Begin Result := -1; For I:=0 To Pred(Count) Do Begin If (Abs(KeyFrames[I].Time-Time)<=0.001) Then Begin Result := I; Exit; End; End; End; Procedure VectorKeyframeArray.AddKey(Time:Single; Value:Vector3D); Var I, N:Integer; Begin If (Time<0) Then Time := 0; N := -1; For I:=0 To Pred(Count) Do If KeyFrames[I].Time>Time Then Begin N := I; Break; End; Inc(Count); SetLength(KeyFrames, Count); If (N>=0) Then Begin For I:=Pred(Count) DownTo Succ(N) Do KeyFrames[I] := KeyFrames[I-1]; End Else N := Pred(Count); KeyFrames[N].Time := Time; KeyFrames[N].Value := Value; End; Procedure VectorKeyframeArray.Load(Source:Stream); Var I:Integer; Time:Word; Range:Vector3D; MaxTime:Single; PX,PY,PZ:SmallInt; SX,SY,SZ:ShortInt; Begin Source.Read(@Count, 4); Source.Read(@Range, SizeOf(Vector3D)); Source.Read(@MaxTime, 4); { If (StringLower(_Owner.Owner.Name)='monster084_idle') Then IntToString(2);} SetLength(KeyFrames, Count); For I:=0 To Pred(Count) Do Begin Source.Read(@Time, 2); KeyFrames[I].Time := (Time/TimeCompressionLimit) * MaxTime; If (KeyFrames[I].Time>MaxTime) Then IntToString(TRunc(KeyFrames[I].Time+MaxTime)); {Source.Read(@PX, 2); Source.Read(@PY, 2); Source.Read(@PZ, 2); KeyFrames[I].Value.X := (PX/CompressionLimit2)* Range.X; KeyFrames[I].Value.Y := (PY/CompressionLimit2)* Range.Y; KeyFrames[I].Value.Z := (PZ/CompressionLimit2)* Range.Z;} Source.Read(@SX, 1); Source.Read(@SY, 1); Source.Read(@SZ, 1); KeyFrames[I].Value.X := (SX/CompressionLimit1)* Range.X; KeyFrames[I].Value.Y := (SY/CompressionLimit1)* Range.Y; KeyFrames[I].Value.Z := (SZ/CompressionLimit1)* Range.Z; //Source.Read(@KeyFrames[I].Value, SizeOf(Vector3D)); End; End; Procedure VectorKeyframeArray.Save(Dest:Stream); Var I:Integer; Time:Word; MaxTime:Single; PX,PY,PZ:SmallInt; SX,SY,SZ:ShortInt; Range:Vector3D; Begin Range := VectorZero; MaxTime := 0; For I:=0 To Pred(Count) Do Begin Range.X := FloatMax(Range.X, Abs(KeyFrames[I].Value.X)); Range.Y := FloatMax(Range.Y, Abs(KeyFrames[I].Value.Y)); Range.Z := FloatMax(Range.Z, Abs(KeyFrames[I].Value.Z)); MaxTime := FloatMax(MaxTime, KeyFrames[I].Time); End; If Range.Length<=0 Then Count := 0; Dest.Write(@Count, 4); Dest.Write(@Range, SizeOf(Vector3D)); Dest.Write(@MaxTime, 4); For I:=0 To Pred(Count) Do Begin Time := Trunc(SafeDiv(KeyFrames[I].Time, MaxTime)*TimeCompressionLimit); Dest.Write(@Time, 2); SX := Trunc(SafeDiv(KeyFrames[I].Value.X,Range.X)*CompressionLimit1); SY := Trunc(SafeDiv(KeyFrames[I].Value.Y,Range.Y)*CompressionLimit1); SZ := Trunc(SafeDiv(KeyFrames[I].Value.Z,Range.Z)*CompressionLimit1); Dest.Write(@SX, 1); Dest.Write(@SY, 1); Dest.Write(@SZ, 1); {PX := Trunc((KeyFrames[I].Value.X/Range.X)*CompressionLimit2); PY := Trunc((KeyFrames[I].Value.Y/Range.Y)*CompressionLimit2); PZ := Trunc((KeyFrames[I].Value.Z/Range.Z)*CompressionLimit2); Dest.Write(@PX, 2); Dest.Write(@PY, 2); Dest.Write(@PZ, 2);} // Dest.Write(@KeyFrames[I].Value, SizeOf(Vector3D)); End; End; Procedure VectorKeyframeArray.CloseLoop; Begin If Count<=0 Then Exit; Keyframes[Pred(Count)].Value := Keyframes[0].Value; End; { BoneAnimation } Constructor BoneAnimation.Create(ID:Integer; Owner:Animation); Begin Self.ID := ID; Self.Owner := Owner; Self.Positions := VectorKeyframeArray.Create(Self); Self.Rotations := VectorKeyframeArray.Create(Self); Self.Scales := VectorKeyframeArray.Create(Self); End; Procedure BoneAnimation.Release; Begin ReleaseObject(Positions); ReleaseObject(Rotations); ReleaseObject(Scales); End; Procedure BoneAnimation.Crop(Time: Single); Begin Positions.Crop(Time); Rotations.Crop(Time); Scales.Crop(Time); End; Procedure BoneAnimation.CloseLoop; Begin Positions.CloseLoop(); Rotations.CloseLoop(); Scales.CloseLoop(); End; Function BoneAnimation.GetLength: Single; Begin Result := FloatMax(Self.Positions.Length, FloatMax(Self.Rotations.Length, Self.Scales.Length)); End; Procedure BoneAnimation.Load(Source:Stream); Begin Source.ReadString(Name); Positions.Load(Source); Rotations.Load(Source); Scales.Load(Source); End; Procedure BoneAnimation.Save(Dest:Stream); Var I:Integer; Begin Dest.WriteString(Name); Positions.Save(Dest); Rotations.Save(Dest); Scales.Save(Dest); End; Procedure BoneAnimation.GetTransform(Time:Single; Out Block:AnimationTransformBlock); Var Key, LastKey:Integer; DeltaTime : Single; Fraction : Single; Q1,Q2:Quaternion; Begin // Find appropriate position key frame Key := Positions.GetKey(Time); If ( Key > 0 ) Then Begin LastKey := Pred(Key); // Interpolate between 2 key frames // time between the 2 key frames deltaTime := Positions.KeyFrames[Key].Time - Positions.KeyFrames[LastKey].Time; // relative position of interpolation point to the keyframes [0..1] Fraction := ((Time - Positions.KeyFrames[LastKey].Time) / deltaTime); If (Fraction < 0.0) Then Fraction := 0.0 Else If (Fraction > 1.0) Then Fraction := 1.0; Block.Translation.X := Positions.KeyFrames[LastKey].Value.X + fraction * (Positions.KeyFrames[Key].Value.X - Positions.KeyFrames[LastKey].Value.X); Block.Translation.Y := Positions.KeyFrames[LastKey].Value.Y + fraction * (Positions.KeyFrames[Key].Value.Y - Positions.KeyFrames[LastKey].Value.Y); Block.Translation.Z := Positions.KeyFrames[LastKey].Value.Z + fraction * (Positions.KeyFrames[Key].Value.Z - Positions.KeyFrames[LastKey].Value.Z); End Else If (Key=0) And (Positions.Count>0) Then Block.Translation := Positions.KeyFrames[Key].Value Else Block.Translation := VectorZero; // Rotation // Find appropriate rotation key frame Key := Rotations.GetKey(Time); If (Key > 0) Then Begin LastKey := Pred(Key); // Interpolate between 2 key frames // time between the 2 key frames deltaTime := Rotations.Keyframes[Key].Time - Rotations.Keyframes[LastKey].Time; // relative position of interpolation point to the keyframes [0..1] Fraction := (Time - Rotations.Keyframes[LastKey].Time) / deltaTime; If (Fraction<0.0) Then Fraction := 0.0; If (Fraction>1.0) Then Fraction := 1.0; Q1 := QuaternionRotation(Rotations.Keyframes[LastKey].Value); Q2 := QuaternionRotation(Rotations.Keyframes[Key].Value); Block.Rotation := QuaternionSlerp(Q1,Q2, Fraction); End Else If (Key=0) And (Rotations.Count>0) Then Begin Block.Rotation := QuaternionRotation(Rotations.Keyframes[Key].Value); End Else Block.Rotation := QuaternionRotation(VectorZero); //TODO Block.Scale := VectorOne; End; { VectorKeyFrameArray } Constructor VectorKeyframeArray.Create(Owner:BoneAnimation); Begin Self._Owner := Owner; End; Procedure VectorKeyframeArray.Clone(Other: VectorKeyframeArray); Var I:Integer; Begin If Other = Nil Then Exit; Self.Count := Other.Count; SetLength(Self.Keyframes, Count); For I:=0 To Pred(Count) Do Self.Keyframes[I] := Other.Keyframes[I]; End; Procedure VectorKeyframeArray.Clear; Begin Count := 0; End; Function VectorKeyframeArray.GetLength: Single; Begin If Count>0 Then Result := Keyframes[Pred(Count)].Time Else Result := 0; End; Procedure VectorKeyframeArray.Crop(Time: Single); Var I:Integer; Begin For I:=1 To Pred(Count) Do If (Keyframes[I].Time>Time) Then Begin Self.Count := Pred(I); SetLength(Keyframes, Self.Count); Exit; End; End; { Animation } Class Function Animation.GetManager: Pointer; Begin Result := AnimationManager.Instance; End; Function Animation.Load(Source:Stream):Boolean; Var Header:FileHeader; I, J, Count:Integer; S:TERRAString; Bone:BoneAnimation; Begin Source.Read(@Header, 4); If (Not CompareFileHeader(Header, 'ANIM')) Then Begin Result := False; Exit; End; Source.Read(@FPS, 4); Source.Read(@Loop, 1); Source.Read(@LoopPoint, 4); Source.Read(@Speed, 4); Source.ReadString(Next); Source.Read(@Count, 4); For I:=0 To Pred(Count) Do Begin Bone := Self.AddBone(''); Bone.Load(Source); End; SetStatus(rsReady); Result := True; End; Procedure Animation.Save(FileName:TERRAString); Var Stream:FileStream; Begin Stream := FileStream.Create(FileName); Save(Stream); ReleaseObject(Stream); End; Procedure Animation.Save(Dest:Stream); Var Header:FileHeader; I:Integer; Begin Header := 'ANIM'; Dest.Write(@Header, 4); Dest.Write(@FPS, 4); Dest.Write(@Loop, 1); Dest.Write(@LoopPoint, 4); Dest.Write(@Speed, 4); Dest.WriteString(Next); Dest.Write(@_BoneCount, 4); For I:=0 To Pred(_BoneCount) Do _Bones[I].Save(Dest); End; Function Animation.GetBoneIndex(Const Name:TERRAString):Integer; Var I:Integer; Begin For I:=0 To Pred(Self._BoneCount) Do If (StringEquals(Self._Bones[I].Name, Name)) Then Begin Result:=I; Exit; End; Result := -1; End; Function Animation.AddBone(Const Name:TERRAString):BoneAnimation; Begin Result := BoneAnimation.Create(_BoneCount, Self); Result.Name := Name; Inc(_BoneCount); SetLength(_Bones, _BoneCount); _Bones[Pred(_BoneCount)] := Result; End; Function Animation.Unload: Boolean; Var I,J:Integer; Begin For I:=0 To Pred(_BoneCount) Do ReleaseObject(_Bones[I]); SetLength(_Bones,0); _BoneCount := 0; Result := Inherited Unload(); End; Function Animation.Update: Boolean; Begin Inherited Update(); Result := True; End; (* Linear interpolation (Vectors, scalars): delta = b - a; // alpha = [0..1] c = a + delta*alpha 3x3 rotation matrix form (right-hand element evaluated first): delta = b * transpose(a) // transpose(a) followed by b. delta.getAxisAngle(axis,deltaAngle) // alpha = [0..1] c = axisAngleToMatrix(axis,deltaAngle*alpha) * a inline void interpolate(const Mat3 & a,const Mat3 & b,flt alpha,Mat3 & c) { Mat3 delta = b ^ !a; // ^ = matrix product, ! = matrix transpose. Vec3 axis; flt deltaAngle; delta.getAxisAngle(axis,deltaAngle); Mat3 rm(axis,deltaAngle*alpha); c = rm ^ a; } // interpolate *) Function Animation.GetBone(Index: Integer): BoneAnimation; Begin If (Index<0) Or (Index>=_BoneCount) Then Result := Nil Else Result := _Bones[Index]; End; Procedure Animation.Clone(Other: Animation); Var I,J:Integer; Begin If Other = Nil Then Exit; Self._BoneCount := Other.BoneCount; SetLength(Self._Bones, _BoneCount); For I:=0 To Pred(_BoneCount) Do Begin _Bones[I] := BoneAnimation.Create(I, Self); _Bones[I].Name := Other._Bones[I].Name; _Bones[I].Positions := VectorKeyframeArray.Create(_Bones[I]); _Bones[I].Positions.Clone(Other._Bones[I].Positions); _Bones[I].Rotations := VectorKeyframeArray.Create(_Bones[I]); _Bones[I].Rotations.Clone(Other._Bones[I].Rotations); _Bones[I].Scales := VectorKeyframeArray.Create(_Bones[I]); _Bones[I].Scales.Clone(Other._Bones[I].Scales); End; Self.FPS := Other.FPS; Self.Loop := Other.Loop; Self.LoopPoint := Other.LoopPoint; Self.Speed := Other.Speed; Self.Next := Other.Next; End; Function Animation.GetLength: Single; Var I:Integer; Begin Result := 0; If (System.Length(_Bones)<Self.BoneCount) Then Exit; For I:=0 To Pred(Self.BoneCount) Do Result := FloatMax(Result, _Bones[I].GetLength()); End; Procedure Animation.Crop(Time: Single); Var I:Integer; Begin For I:=0 To Pred(Self.BoneCount) Do _Bones[I].Crop(Time); End; Procedure Animation.CloseLoop; Var I:Integer; Begin For I:=0 To Pred(Self.BoneCount) Do _Bones[I].CloseLoop(); End; End.
unit uImagemProporcional; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, libGeral, Jpeg, PngImage, Vcl.StdCtrls, Vcl.Buttons; type TfrmImagemProporcional = class(TForm) imgProporcional: TImage; Panel1: TPanel; btnFechar: TBitBtn; procedure btnFecharClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure CarregaImagem(imgStream: TStream); end; var frmImagemProporcional: TfrmImagemProporcional; implementation {$R *.dfm} uses Matop050; procedure TfrmImagemProporcional.btnFecharClick(Sender: TObject); begin Close; end; procedure TfrmImagemProporcional.CarregaImagem(imgStream: TStream); var Jpg : TJPEGImage; MemoryStream : TMemoryStream; begin try Jpg := TJpegImage.Create; imgStream.Position := 0; Jpg.LoadFromStream(imgStream); imgProporcional.Picture.Assign(Jpg); finally Jpg.Free; imgStream.Free; end; end; initialization Classes.RegisterClass(TfrmImagemProporcional); finalization Classes.UnRegisterClass(TfrmImagemProporcional); end.
unit UAccessFileDBF; interface uses UAccessFile, UAccessContainer, DB, VKDBFDataSet; type { TODO : Сделать обратные правила! } TSAVAccessFilesDBF = class(TSAVAccessFiles) private FTable: TVKDBFNTX; // D-A-G-U FrTable: TVKDBFNTX; // U-G-A-D { TODO : При групповых обработках нужно FLock вначале и UnLock в конце } FWorkDir: string; FFilePriorityIndex: string; FFilePriorityIndexReverse: string; procedure DataSourceAfterDelete(DataSet: TDataSet); procedure DataSourceBeforeInsert(DataSet: TDataSet); procedure DataSourceBeforeEdit(DataSet: TDataSet); procedure DataSourceAfterPost(DataSet: TDataSet); public property FilePriorityIndex: string read FFilePriorityIndex; property FilePriorityIndexReverse: string read FFilePriorityIndexReverse; property WorkDir: string read FWorkDir; function TableCreate(const aTable: string): Boolean; function IndexCreate(const aTableName, aIndexName: string): Boolean; procedure TablePrepare(aTable: TVKDBFNTX; const ReadOnly: Boolean = True); constructor Create(aContainer: TSAVAccessContainer); overload; destructor Destroy; override; end; implementation uses SysUtils, UAccessConstant, VKDBFNTX, VKDBFIndex, VKDBFSorters, Classes; { TSAVAccessFilesDBF } constructor TSAVAccessFilesDBF.Create(aContainer: TSAVAccessContainer); function DoDBFFileCreate(aTable: TVKDBFNTX; aIndexName: string): boolean; var t, i: boolean; begin t := True; i := True; TablePrepare(aTable, False); if not FileExists(aTable.DBFFileName) then begin t := TableCreate(aTable.DBFFileName); i := IndexCreate(aTable.DBFFileName, aIndexName); end; if not FileExists(aIndexName) then i := IndexCreate(aTable.DBFFileName, aIndexName); if not (t) then raise Exception.Create(csTableCreateError + aTable.DBFFileName) else if not (i) then raise Exception.Create(csIndexCreateError + aIndexName); Result := i and t; if Result then begin with aTable.Indexes.Add as TVKNTXIndex do NTXFileName := aIndexName; aTable.Open; aTable.SetOrder(1); end; end; begin inherited Create(aContainer); FWorkDir := IncludeTrailingPathDelimiter(Container.WorkDir); FTable := TVKDBFNTX.Create(nil); FrTable := TVKDBFNTX.Create(nil); FTable.AfterDelete := DataSourceAfterDelete; FTable.BeforeInsert:=DataSourceBeforeInsert; FTable.BeforeEdit:=DataSourceBeforeEdit; FTable.AfterPost:=DataSourceAfterPost; FrTable.AfterDelete := DataSourceAfterDelete; FrTable.BeforeInsert:=DataSourceBeforeInsert; FrTable.BeforeEdit:=DataSourceBeforeEdit; FrTable.AfterPost:=DataSourceAfterPost; FTable.DBFFileName := FWorkDir + csTableFiles; FrTable.DBFFileName := FWorkDir + csTableFilesReverse; FFilePriorityIndex := FWorkDir + csIndexFilePriority; FFilePriorityIndexReverse := FWorkDir + csIndexFilePriorityR; DoDBFFileCreate(FTable, FFilePriorityIndex); DataSource := FTable; DoDBFFileCreate(FrTable, FFilePriorityIndexReverse); RDataSource := FrTable; end; procedure TSAVAccessFilesDBF.DataSourceAfterDelete(DataSet: TDataSet); begin with DataSet as TVKDBFNTX do begin Pack; Reindex; end; end; procedure TSAVAccessFilesDBF.DataSourceAfterPost(DataSet: TDataSet); begin TVKDBFNTX(DataSet).UnLock; end; procedure TSAVAccessFilesDBF.DataSourceBeforeEdit(DataSet: TDataSet); begin if not TVKDBFNTX(DataSet).FLock then raise Exception.Create(csFLockError + TVKDBFNTX(DataSet).DBFFileName); end; procedure TSAVAccessFilesDBF.DataSourceBeforeInsert(DataSet: TDataSet); begin if not TVKDBFNTX(DataSet).FLock then raise Exception.Create(csFLockError + TVKDBFNTX(DataSet).DBFFileName); end; destructor TSAVAccessFilesDBF.Destroy; begin FTable.Close; FreeAndNil(FTable); FrTable.Close; FreeAndNil(FrTable); DataSource := nil; RDataSource := nil; inherited; end; function TSAVAccessFilesDBF.IndexCreate(const aTableName, aIndexName: string): Boolean; var table1: TVKDBFNTX; begin table1 := TVKDBFNTX.Create(nil); table1.DBFFileName := aTableName; table1.AccessMode.AccessMode := 66; table1.oem := True; Result := True; try table1.Open; with table1.Indexes.Add as TVKNTXIndex do begin NTXFileName := aIndexName; ClipperVer := v501; KeyExpresion := csFieldPrority; CreateIndex(True); end; table1.Close; except Result := False; end; FreeAndNil(table1); end; function TSAVAccessFilesDBF.TableCreate(const aTable: string): Boolean; var table1: TVKDBFNTX; begin table1 := TVKDBFNTX.Create(nil); table1.DBFFileName := aTable; table1.AccessMode.AccessMode := 66; table1.oem := True; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldPrority; field_type := 'N'; len := 5; end; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldSrvrFile; field_type := 'C'; len := 50; end; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldVersion; field_type := 'C'; len := 30; end; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldClntFile; field_type := 'C'; len := 254; end; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldExt; field_type := 'C'; len := 10; end; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldType; field_type := 'C'; len := 1; end; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldAction; field_type := 'N'; len := 3; end; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldMD5; field_type := 'C'; len := 32; end; with table1.DBFFieldDefs.Add as TVKDBFFieldDef do begin Name := csFieldDescription; field_type := 'C'; len := 150; end; Result := True; try table1.CreateTable; except Result := False; end; FreeAndNil(table1); end; procedure TSAVAccessFilesDBF.TablePrepare(aTable: TVKDBFNTX; const ReadOnly: Boolean = True); begin if ReadOnly then aTable.AccessMode.AccessMode := 64 else aTable.AccessMode.AccessMode := 66; aTable.OEM := True; aTable.DbfVersion := xClipper; aTable.LockProtocol := lpClipperLock; aTable.LobLockProtocol := lpClipperLock; aTable.TrimInLocate := True; aTable.TrimCType := True; end; end.
unit AddressActionsUnit; interface uses SysUtils, BaseActionUnit, AddressParametersUnit, AddressUnit; type TAddressActions = class(TBaseAction) public function Get(AddressParameters: TAddressParameters; out ErrorString: String): TAddress; /// <summary> /// Mark an address as visited. /// </summary> procedure MarkAsVisited(RouteId: String; AddressId, MemberId: integer; IsVisited: boolean; out ErrorString: String); /// <summary> /// Mark a destination of a route as departed. /// </summary> procedure MarkAsDeparted(RouteId: String; AddressId, MemberId: integer; IsDeparted: boolean; out ErrorString: String); /// <summary> /// The example refers to the process of marking an address as Detected as Visited. /// </summary> procedure MarkAsDetectedAsVisited(RouteId: String; RouteDestinationId: integer; IsVisited: boolean; out ErrorString: String); /// <summary> /// The example refers to the process of marking an address as Detected as Departed. /// </summary> procedure MarkAsDetectedAsDeparted(RouteId: String; RouteDestinationId: integer; IsDeparted: boolean; out ErrorString: String); end; implementation { TAddressActions } uses SettingsUnit, GenericParametersUnit, GetAddressUnit, StatusResponseUnit, MarkAddressAsDetectedAsVisitedRequestUnit, MarkAddressAsDetectedAsDepartedRequestUnit, CommonTypesUnit; function TAddressActions.Get(AddressParameters: TAddressParameters; out ErrorString: String): TAddress; begin Result := FConnection.Get(TSettings.EndPoints.GetAddress, AddressParameters, TAddress, ErrorString) as TAddress; end; procedure TAddressActions.MarkAsDeparted(RouteId: String; AddressId, MemberId: integer; IsDeparted: boolean; out ErrorString: String); var Response: TStatusResponse; Request: TGenericParameters; begin Request := TGenericParameters.Create; try Request.AddParameter('route_id', RouteId); Request.AddParameter('address_id', IntToStr(AddressId)); Request.AddParameter('member_id', IntToStr(MemberId)); if IsDeparted then Request.AddParameter('is_departed', '1') else Request.AddParameter('is_departed', '0'); Response := FConnection.Get(TSettings.EndPoints.MarkAddressAsDeparted, Request, TStatusResponse, ErrorString) as TStatusResponse; try if ((Response = nil) or (Response.Status = False)) and (ErrorString = EmptyStr) then ErrorString := 'Mark As Departed fault'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; procedure TAddressActions.MarkAsDetectedAsDeparted(RouteId: String; RouteDestinationId: integer; IsDeparted: boolean; out ErrorString: String); var Address: TAddress; Request: TMarkAddressAsDetectedAsDepartedRequest; begin Request := TMarkAddressAsDetectedAsDepartedRequest.Create( RouteId, RouteDestinationId, IsDeparted); try Address := FConnection.Put(TSettings.EndPoints.Address, Request, TAddress, ErrorString) as TAddress; try if (Address = nil) and (ErrorString = EmptyStr) then ErrorString := 'Mark As Detected As Departed fault'; finally FreeAndNil(Address); end; finally FreeAndNil(Request); end; end; procedure TAddressActions.MarkAsDetectedAsVisited(RouteId: String; RouteDestinationId: integer; IsVisited: boolean; out ErrorString: String); var Address: TAddress; Request: TMarkAddressAsDetectedAsVisitedRequest; begin Request := TMarkAddressAsDetectedAsVisitedRequest.Create( RouteId, RouteDestinationId, IsVisited); try Address := FConnection.Put(TSettings.EndPoints.Address, Request, TAddress, ErrorString) as TAddress; try if (Address = nil) and (ErrorString = EmptyStr) then ErrorString := 'Mark As Detected As Visited fault'; finally FreeAndNil(Address); end; finally FreeAndNil(Request); end; end; procedure TAddressActions.MarkAsVisited(RouteId: String; AddressId, MemberId: integer; IsVisited: boolean; out ErrorString: String); var Response: TSimpleString; Request: TGenericParameters; begin Request := TGenericParameters.Create; try Request.AddParameter('route_id', RouteId); Request.AddParameter('address_id', IntToStr(AddressId)); Request.AddParameter('member_id', IntToStr(MemberId)); if IsVisited then Request.AddParameter('is_visited', '1') else Request.AddParameter('is_visited', '0'); Response := FConnection.Get(TSettings.EndPoints.MarkAddressAsVisited, Request, TSimpleString, ErrorString) as TSimpleString; try if ((Response = nil) or (Response.Value = '0')) and (ErrorString = EmptyStr) then ErrorString := 'Mark As Visited fault'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; end.
unit Unit_gds_parser; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Unit_GDSClasses, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls; type Tfrm_simple_gdsparser = class(TForm) mmo_debug: TMemo; pnl1: TPanel; btn_LoadGDS_FILE: TBitBtn; dlgOpenGDS: TOpenDialog; statGDSBrowser: TStatusBar; procedure btn_LoadGDS_FILEClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } FTokenList: TTokenList; end; var frm_simple_gdsparser: Tfrm_simple_gdsparser; implementation {$R *.dfm} procedure Tfrm_simple_gdsparser.btn_LoadGDS_FILEClick(Sender: TObject); var FILENAME: String; i, j: integer; LINESTR: String; GDSToken: TGDSToken; begin if dlgOpenGDS.execute then begin FILENAME := dlgOpenGDS.FILENAME; statGDSBrowser.SimpleText := ' start browsing ' + FILENAME; FTokenList.parseGDSfile(FILENAME); statGDSBrowser.SimpleText := ' start show data ' + FILENAME; for j := 0 to FTokenList.count - 1 do begin GDSToken := FTokenList.Items[j]; LINESTR := ' '; for i := 0 to high(GDSToken.Data.BufferBytes) do begin LINESTR := LINESTR + ByteToHex(GDSToken.Data.BufferBytes[i]) + ' '; end; mmo_debug.Lines.Add(''); mmo_debug.Lines.Add('type ' + ByteToHex(GDSToken.ID)); mmo_debug.Lines.Add('name ' + GDSToken.Name); mmo_debug.Lines.Add ('len ' + ByteToHex(Length(GDSToken.Data.BufferBytes))); mmo_debug.Lines.Add('data type ' + GDSToken.GDSDataType); mmo_debug.Lines.Add('data#row ' + LINESTR); mmo_debug.Lines.Add('data#str ' + GDSToken.DataString); statGDSBrowser.SimpleText := ' writing TokenCount ' + InTToStr(j) + ' out of ' + InTToStr(FTokenList.count); end; statGDSBrowser.SimpleText := ' end show ' + FILENAME + ' TokenCount ' + InTToStr(FTokenList.count); end; end; procedure Tfrm_simple_gdsparser.FormCreate(Sender: TObject); begin FTokenList := TTokenList.Create; end; end.
program GameMain; {$IFNDEF UNIX} {$r GameLauncher.res} {$ENDIF} uses sgTypes, sgCore, sgAudio, sgText, sgGraphics, sgResources, sgInput, sgPhysics; function ColorAt(x,y : Integer; offset : Double):Color; var hue : Double; begin hue := (offset + ((x+y)/(ScreenWidth()+ScreenHeight()))/2); result := HSBColor(hue, 0.9, 0.8); end; procedure MyClearScreen(offset : Double); var x,y :Integer; c : Color; begin x := 0; while x < ScreenWidth() do begin y := 0; while y < ScreenHeight() do begin c := ColorAt(x,y,offset); DrawPixel(c,x,y); y := y + 1; end; end; end; procedure Main(); var offset : Double; begin OpenAudio(); OpenGraphicsWindow('Screen Saver', 800, 600); // assign offset a value of either 0 or 1 offset:=0; repeat ProcessEvents(); MyClearScreen(offset); RefreshScreen(); offset := offset + 0.1; if offset > 1 then; begin offset := offset -1; end; until WindowCloseRequested(); CloseAudio(); ReleaseAllResources(); end; begin Main(); end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2023 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { 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 FB4D.Helpers; interface uses System.Classes, System.Types, System.SysUtils, System.StrUtils, {$IFNDEF LINUX64} System.Sensors, {$ENDIF} System.JSON, System.Generics.Collections, REST.Types, FB4D.Interfaces; type TOnSimpleDownloadError = procedure(const DownloadURL, ErrMsg: string) of object; TOnSimpleDownloadSuccess = procedure(const DownloadURL: string) of object; TOnLog = procedure(const Text: string) of object; TFirebaseHelpers = class class var OnLog: TOnLog; // Time conversion functions class function CodeRFC3339DateTime(DateTimeStamp: TDateTime): string; class function DecodeRFC3339DateTime(DateTimeStamp: string): TDateTime; class function ConvertTimeStampToUTCDateTime(TimeStamp: Int64): TDateTime; class function ConvertRFC5322ToUTCDateTime(DateTime: string): TDateTime; class function ConvertRFC5322ToLocalDateTime(DateTime: string): TDateTime; class function ConvertTimeStampToLocalDateTime(Timestamp: Int64): TDateTime; class function ConvertToLocalDateTime(DateTimeStampUTC: TDateTime): TDateTime; // Query parameter helpers class function EncodeQueryParams(QueryParams: TQueryParams): string; class function EncodeQueryParamsWithToken(QueryParams: TQueryParams; const EncodedToken: string): string; // Request parameter helpers class function EncodeResourceParams(Params: TRequestResourceParam): string; class function AddParamToResParams(Params: TRequestResourceParam; const Param: string): TRequestResourceParam; // Encode token for URL based token transmission class function EncodeToken(const Token: string): string; // Array of string helpers class function ArrStrToCommaStr(Arr: array of string): string; class function ArrStrToQuotedCommaStr(Arr: array of string): string; class function FirestorePath(const Path: string): TRequestResourceParam; deprecated 'Use TFirestorePath.ConvertToDocPath instead'; // FBID is based on charset of cBase64: Helpers and converter to GUID // PUSHID is based on charset of cPushID64: Supports chronological sorting type TIDKind = (FBID {random 22 Chars}, PUSHID {timestamp and random: total 20 Chars}); class function CreateAutoID(IDKind: TIDKind = FBID): string; class function ConvertGUIDtoFBID(Guid: TGuid): string; class function ConvertFBIDtoGUID(const FBID: string): TGuid; class function ConvertTimeStampAndRandomPatternToPUSHID(timestamp: TDateTime; Random: TBytes): string; class function DecodeTimeStampFromPUSHID(const PUSHID: string; ConvertToLocalTime: boolean = true): TDateTime; // File helpers class procedure SimpleDownload(const DownloadUrl: string; Stream: TStream; OnSuccess: TOnSimpleDownloadSuccess; OnError: TOnSimpleDownloadError = nil); class procedure SimpleDownloadSynchronous(const DownloadUrl: string; Stream: TStream); {$IF Defined(FMX) OR Defined(FGX)} class function ContentTypeToFileExt(const ContentType: string): string; class function ImageStreamToContentType(Stream: TStream): TRESTContentType; {$ENDIF} // Miscellaneous functions class function IsEMailAdress(const EMail: string): boolean; // Application helpers class procedure Log(msg: string); class procedure LogFmt(msg: string; const Args: array of const); class function AppIsTerminated: boolean; class procedure SleepAndMessageLoop(SleepInMs: cardinal); class function IsMainThread: boolean; class function GetConfigAndPlatform: string; class function GetPlatform: string; // ML helpers class function GetLanguageInEnglishFromCode(const Code: string): string; private const cBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'; // The last two chars '_' and '-' are not real Base64 because '+' and '/' // causes troubles in IDs cPushID64 = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; // This notification is used in the Realtime DB for Post and Push operation end; TFirestorePath = class class function TrimStartAndEndPathDelimiters(const Path: string): string; class function ConvertToDocPath(const Path: string): TRequestResourceParam; class function GetDocPath(Params: TRequestResourceParam): string; class function ContainsPathDelim(const Path: string): boolean; class function ExtractLastCollection(const Path: string): string; class function DocPathWithoutLastCollection( const Path: string): TRequestResourceParam; end; TFirestoreMap = array of TJSONPair; TFirestoreArr = array of TJSONValue; TJSONHelpers = class helper for TJSONObject // String function GetStringValue: string; overload; function GetStringValue(const Name: string): string; overload; function GetStringValueDef(const Name: string; const Default: string = ''): string; class function SetStringValue(const Val: string): TJSONObject; class function SetString(const VarName, Val: string): TJSONPair; // Integer function GetIntegerValue: integer; overload; function GetIntegerValue(const Name: string): integer; overload; function GetIntegerValueDef(const Name: string; Default: integer = 0): integer; function GetInt64Value: Int64; overload; function GetInt64Value(const Name: string): Int64; overload; function GetInt64ValueDef(const Name: string; Default: Int64 = 0): Int64; class function SetIntegerValue(Val: integer): TJSONObject; class function SetInteger(const VarName: string; Val: integer): TJSONPair; class function SetInt64Value(Val: Int64): TJSONObject; class function SetInt64(const VarName: string; Val: Int64): TJSONPair; // Boolean function GetBooleanValue: boolean; overload; function GetBooleanValue(const Name: string): boolean; overload; function GetBooleanValueDef(const Name: string; Default: boolean = false): boolean; class function SetBooleanValue(Val: boolean): TJSONObject; class function SetBoolean(const VarName: string; Val: boolean): TJSONPair; // Double function GetDoubleValue: double; overload; function GetDoubleValue(const Name: string): double; overload; function GetDoubleValueDef(const Name: string; Default: double = 0): double; class function SetDoubleValue(Val: double): TJSONObject; class function SetDouble(const VarName: string; Val: double): TJSONPair; // TimeStamp function GetTimeStampValue(TimeZone: TTimeZone = tzUTC): TDateTime; overload; function GetTimeStampValue(const Name: string; TimeZone: TTimeZone = tzUTC): TDateTime; overload; function GetTimeStampValueDef(const Name: string; Default: TDateTime = 0; TimeZone: TTimeZone = tzUTC): TDateTime; class function SetTimeStampValue(Val: TDateTime): TJSONObject; class function SetTimeStamp(const VarName: string; Val: TDateTime): TJSONPair; // Null class function SetNullValue: TJSONObject; class function SetNull(const VarName: string): TJSONPair; function IsNull: boolean; // Reference function GetReference: string; overload; function GetReference(const Name: string): string; overload; function GetReferenceDef(const Name: string; const Default: string = ''): string; class function SetReferenceValue(const ProjectID, Ref: string; const Database: string = cDefaultDatabaseID): TJSONObject; class function SetReference(const Name, ProjectID, Ref: string): TJSONPair; // GeoPoint function GetGeoPoint: TLocationCoord2D; overload; function GetGeoPoint(const Name: string): TLocationCoord2D; overload; function GetGeoPointDef(const Name: string; Default: TLocationCoord2D): TLocationCoord2D; class function SetGeoPointValue(Val: TLocationCoord2D): TJSONObject; class function SetGeoPoint(const VarName: string; Val: TLocationCoord2D): TJSONPair; // Bytes function GetBytes: TBytes; overload; function GetBytes(const Name: string): TBytes; overload; class function SetBytesValue(Val: TBytes): TJSONObject; class function SetBytes(const VarName: string; Val: TBytes): TJSONPair; // Map function GetMapSize: integer; overload; function GetMapSize(const Name: string): integer; overload; function GetMapItem(Ind: integer): TJSONPair; overload; function GetMapItem(const Name: string): TJSONObject; overload; function GetMapItem(const Name: string; Ind: integer): TJSONPair; overload; function GetMapValue(const Name: string; Ind: integer): TJSONObject; class function SetMapValue(MapVars: TFirestoreMap): TJSONObject; class function SetMap(const VarName: string; MapVars: TFirestoreMap): TJSONPair; // Array function GetArraySize: integer; overload; function GetArraySize(const Name: string): integer; overload; function GetArrayItem(Ind: integer): TJSONObject; overload; function GetArrayItem(const Name: string; Ind: integer): TJSONObject; overload; function GetStringArray: TStringDynArray; class function SetArray(const VarName: string; FSArr: TFirestoreArr): TJSONPair; class function SetStringArray(const VarName: string; Strings: TStringDynArray): TJSONPair; overload; class function SetStringArray(const VarName: string; Strings: TStringList): TJSONPair; overload; class function SetStringArray(const VarName: string; Strings: TList<string>): TJSONPair; overload; end; TQueryParamsHelper = class helper for TQueryParams class function CreateQueryParams(CheckThisInstanceFirst: TQueryParams = nil): TQueryParams; function AddOrderBy(const FieldName: string): TQueryParams; function AddOrderByType(const TypeName: string): TQueryParams; function AddLimitToFirst(LimitToFirst: integer): TQueryParams; function AddLimitToLast(LimitToLast: integer): TQueryParams; function AddTransaction( Transaction: TFirestoreReadTransaction): TQueryParams; function AddPageSize(PageSize: integer): TQueryParams; function AddPageToken(const PageToken: string): TQueryParams; end; resourcestring rsFBFailureIn = '%s Firebase failure in %s: %s'; implementation uses System.Character, {$IFDEF MSWINDOWS} WinAPI.Windows, {$ENDIF} {$IF Defined(CONSOLE)} {$ELSEIF Defined(VCL)} VCL.Forms, {$ELSEIF Defined(FMX)} FMX.Types, FMX.Forms, FMX.Graphics, FMX.Consts, {$ELSEIF Defined(FGX)} FGX.Forms, FGX.Logs, {$ELSE} FMX.Types, FMX.Forms, {$ENDIF} System.DateUtils, System.NetEncoding, System.JSONConsts, System.Math, System.Net.HttpClient, System.Hash, IdGlobalProtocols; resourcestring rsArrayItemOutOfBounds = 'Array item %d out of bounds'; rsInvalidArrayItem = 'Invalid array item %d'; rsMapItemOutOfBounds = 'Map item %d out of bounds'; { TFirestoreHelpers } class function TFirebaseHelpers.CodeRFC3339DateTime( DateTimeStamp: TDateTime): string; var UTC: TDateTime; begin // Convert to UTC UTC := TTimeZone.Local.ToUniversalTime(DateTimeStamp); // Format RFC3339 result := FormatDateTime('yyyy-mm-dd', UTC) + 'T' + FormatDateTime('hh:mm:ss', UTC) + 'Z'; end; class function TFirebaseHelpers.DecodeRFC3339DateTime( DateTimeStamp: string): TDateTime; begin result := ISO8601ToDate(DateTimeStamp, false); // To local time end; class function TFirebaseHelpers.ConvertRFC5322ToLocalDateTime( DateTime: string): TDateTime; begin result := ConvertToLocalDateTime(ConvertRFC5322ToUTCDateTime(DateTime)); end; class function TFirebaseHelpers.ConvertRFC5322ToUTCDateTime( DateTime: string): TDateTime; begin result := StrInternetToDateTime(DateTime); end; class function TFirebaseHelpers.ConvertTimeStampToLocalDateTime( Timestamp: Int64): TDateTime; begin result := ConvertToLocalDateTime(ConvertTimeStampToUTCDateTime(Timestamp)); end; class function TFirebaseHelpers.ConvertTimeStampToUTCDateTime( TimeStamp: Int64): TDateTime; begin result := UnixToDateTime(TimeStamp div 1000); end; class function TFirebaseHelpers.ConvertToLocalDateTime( DateTimeStampUTC: TDateTime): TDateTime; begin result := TTimeZone.Local.ToLocalTime(DateTimeStampUTC); end; class function TFirebaseHelpers.EncodeQueryParams( QueryParams: TQueryParams): string; var Param: TPair<string, TStringDynArray>; ParVal: string; begin if (not assigned(QueryParams)) or not(QueryParams.Count > 0) then exit(''); result := '?'; for Param in QueryParams do for ParVal in Param.Value do begin if result <> '?' then result := result + '&'; result := result + TNetEncoding.URL.Encode(Param.Key) + '=' + TNetEncoding.URL.Encode(ParVal); end; end; class function TFirebaseHelpers.EncodeQueryParamsWithToken( QueryParams: TQueryParams; const EncodedToken: string): string; var Param: TPair<string, TStringDynArray>; ParVal: string; begin result := '?auth=' + EncodedToken; if assigned(QueryParams) then for Param in QueryParams do for ParVal in Param.Value do result := result + '&' + TNetEncoding.URL.Encode(Param.Key) + '=' + TNetEncoding.URL.Encode(ParVal); end; class function TFirebaseHelpers.EncodeResourceParams( Params: TRequestResourceParam): string; const PathUnsafeChars: TURLEncoding.TUnsafeChars = [Ord('"'), Ord('<'), Ord('>'), Ord('^'), Ord('`'), Ord('{'), Ord('}'), Ord('|'), Ord('/'), Ord('\'), Ord('?'), Ord('#'), Ord('+')]; Option: TURLEncoding.TEncodeOptions = [TURLEncoding.TEncodeOption.SpacesAsPlus, TURLEncoding.TEncodeOption.EncodePercent]; var i: integer; begin result := ''; for i := low(Params) to high(Params) do result := result + '/' + TNetEncoding.URL.Encode(Params[i], PathUnsafeChars, Option); end; class function TFirebaseHelpers.EncodeToken(const Token: string): string; begin if Token.IsEmpty then result := '' else result := '?auth=' + TNetEncoding.URL.Encode(Token); end; class function TFirebaseHelpers.FirestorePath( const Path: string): TRequestResourceParam; begin if Path.StartsWith('/') or Path.StartsWith('\') then result := Path.Substring(1).Split(['/', '\']) else result := Path.Split(['/', '\']); end; class function TFirebaseHelpers.ArrStrToCommaStr(Arr: array of string): string; var i: integer; begin result := ''; for i := low(Arr) to high(Arr) do if i = low(Arr) then result := Arr[i] else result := result + ',' + Arr[i]; end; class function TFirebaseHelpers.ArrStrToQuotedCommaStr( Arr: array of string): string; function DoubleQuotedStr(const S: string): string; var i: integer; begin result := S; for i := result.Length - 1 downto 0 do if result.Chars[i] = '"' then result := result.Insert(i, '"'); result := '"' + result + '"'; end; var i: integer; begin result := ''; for i := low(Arr) to high(Arr) do if i = low(Arr) then result := DoubleQuotedStr(Arr[i]) else result := result + ',' + DoubleQuotedStr(Arr[i]); end; class procedure TFirebaseHelpers.Log(msg: string); begin if AppIsTerminated then exit; {$IF Defined(FMX)} {$IFDEF LINUX} writeln(msg); // Workaround for RSP-32303 {$ELSE} FMX.Types.Log.d(msg, []); // there is a bug in DE 10.2 when the wrong method is calling? {$ENDIF} {$ELSEIF Defined(FGX)} TfgLog.Debug(msg); {$ELSEIF Defined(VCL)} OutputDebugString(PChar(msg)); {$ELSEIF Defined(MSWINDOWS)} OutputDebugString(PChar(msg)); {$ELSEIF Defined(CONSOLE)} writeln(msg); {$ENDIF} if Assigned(OnLog) then OnLog(msg); end; class procedure TFirebaseHelpers.LogFmt(msg: string; const Args: array of const); begin Log(Format(msg, args)); end; class function TFirebaseHelpers.AddParamToResParams( Params: TRequestResourceParam; const Param: string): TRequestResourceParam; var c: integer; begin SetLength(result, length(Params) + 1); for c := low(Params) to high(Params) do result[c] := Params[c]; result[length(Params)] := Param; end; class function TFirebaseHelpers.AppIsTerminated: boolean; begin {$IF Defined(VCL) OR Defined(FMX)} result := Application.Terminated; {$ELSE} result := false; {$ENDIF} end; class procedure TFirebaseHelpers.SleepAndMessageLoop(SleepInMs: cardinal); begin {$IF Defined(VCL) OR Defined(FMX)} Application.ProcessMessages; {$ENDIF} Sleep(SleepInMs); end; class procedure TFirebaseHelpers.SimpleDownload(const DownloadUrl: string; Stream: TStream; OnSuccess: TOnSimpleDownloadSuccess; OnError: TOnSimpleDownloadError); var ErrMsg: string; begin TThread.CreateAnonymousThread( procedure var Client: THTTPClient; Response: IHTTPResponse; begin Client := THTTPClient.Create; try try Response := Client.Get(DownloadUrl, Stream); if Response.StatusCode = 200 then begin if assigned(OnSuccess) then TThread.Queue(nil, procedure begin OnSuccess(DownloadUrl); end); end else begin {$IFDEF DEBUG} TFirebaseHelpers.Log(Response.ContentAsString); {$ENDIF} if assigned(OnError) then TThread.Queue(nil, procedure begin OnError(DownloadUrl, Response.StatusText); end); end; except on e: exception do if assigned(OnError) then begin ErrMsg := e.Message; TThread.Queue(nil, procedure begin OnError(DownloadUrl, ErrMsg); end) end else TFirebaseHelpers.LogFmt(rsFBFailureIn, ['FirebaseHelpers.SimpleDownload', DownloadUrl, e.Message]); end; finally Client.Free; end; end).Start; end; class procedure TFirebaseHelpers.SimpleDownloadSynchronous( const DownloadUrl: string; Stream: TStream); var Client: THTTPClient; Response: IHTTPResponse; begin Client := THTTPClient.Create; try Response := Client.Get(DownloadUrl, Stream); if Response.StatusCode <> 200 then begin {$IFDEF DEBUG} TFirebaseHelpers.Log(Response.ContentAsString); {$ENDIF} raise EFirebaseResponse.Create(Response.StatusText); end; finally Client.Free; end; end; class function TFirebaseHelpers.CreateAutoID(IDKind: TIDKind = FBID): string; begin // use OS to generate a random number case IDKind of FBID: result := ConvertGUIDtoFBID(TGuid.NewGuid); PUSHID: result := ConvertTimeStampAndRandomPatternToPUSHID(now, THashMD5.GetHashBytes(GuidToString(TGUID.NewGuid))); end; end; class function TFirebaseHelpers.ConvertGUIDtoFBID(Guid: TGuid): string; function GetBase64(b: Byte): char; begin result := cBase64[low(cBase64) + b and $3F]; end; var D1: cardinal; D2, D3: Word; begin SetLength(result, 22); D1 := Guid.D1; result[1] := GetBase64(D1 and $FF); D1 := D1 shr 6; result[2] := GetBase64(D1 and $FF); D1 := D1 shr 6; result[3] := GetBase64(D1 and $FF); D1 := D1 shr 6; result[4] := GetBase64(D1 and $FF); D1 := D1 shr 6; result[5] := GetBase64(D1 and $FF); D2 := Guid.D2; result[6] := GetBase64(D2 and $FF); D2 := D2 shr 6; result[7] := GetBase64(D2 and $FF); D2 := D2 shr 6; result[8] := GetBase64(D2 and $F + (D1 and $C0) shr 2); D3 := Guid.D3; result[9] := GetBase64(D3 and $FF); D3 := D3 shr 6; result[10] := GetBase64(D3 and $FF); D3 := D3 shr 6; result[11] := GetBase64(D3 and $F + (Guid.D4[0] and $C0) shr 2); result[12] := GetBase64(Guid.D4[0]); result[13] := GetBase64(Guid.D4[1]); result[14] := GetBase64(Guid.D4[2]); result[15] := GetBase64(Guid.D4[3]); result[16] := GetBase64(Guid.D4[4]); result[17] := GetBase64(Guid.D4[5]); result[18] := GetBase64(Guid.D4[6]); result[19] := GetBase64(Guid.D4[7]); result[20] := GetBase64((Guid.D4[1] and $C0) shr 6 + (Guid.D4[2] and $C0) shr 4 + (Guid.D4[3] and $C0) shr 2); result[21] := GetBase64((Guid.D4[4] and $C0) shr 6 + (Guid.D4[5] and $C0) shr 4 + (Guid.D4[6] and $C0) shr 2); result[22] := GetBase64((Guid.D4[7] and $C0) shr 6); end; class function TFirebaseHelpers.ConvertFBIDtoGUID(const FBID: string): TGuid; var c: integer; Base64: array[1..22] of byte; begin for c := low(Base64) to high(Base64) do Base64[c] := 0; // Zero for ID that are shorter than 22 for c := 1 to max(length(FBID), high(Base64)) do Base64[c] := pos(FBID[c], cBase64) - 1; result.D1 := Base64[1] + Base64[2] shl 6 + Base64[3] shl 12 + Base64[4] shl 18 + Base64[5] shl 24 + (Base64[8] and $30) shl 26; result.D2 := Base64[6] + Base64[7] shl 6 + (Base64[8] and $F) shl 12; result.D3 := Base64[9] + Base64[10] shl 6 + (Base64[11] and $F) shl 12; result.D4[0] := Base64[12] + (Base64[11] and $30) shl 2; result.D4[1] := Base64[13] + (Base64[20] and $03) shl 6; result.D4[2] := Base64[14] + (Base64[20] and $0C) shl 4; result.D4[3] := Base64[15] + (Base64[20] and $30) shl 2; result.D4[4] := Base64[16] + (Base64[21] and $03) shl 6; result.D4[5] := Base64[17] + (Base64[21] and $0C) shl 4; result.D4[6] := Base64[18] + (Base64[21] and $30) shl 2; result.D4[7] := Base64[19] + (Base64[22] and $03) shl 6; end; class function TFirebaseHelpers.ConvertTimeStampAndRandomPatternToPUSHID( timestamp: TDateTime; Random: TBytes): string; var tsi: int64; c: integer; begin Assert(length(Random) >= 12, 'Too short random pattern'); tsi := System.DateUtils.DateTimeToUnix(timestamp, false) * 1000; result := ''; for c := 1 to 8 do begin result := cPushID64[(tsi mod 64) + low(cPushID64)] + result; tsi := tsi shr 6; end; for c := 0 to 11 do result := result + cPushID64[Random[c] and $3F + low(cPushID64)]; end; class function TFirebaseHelpers.DecodeTimeStampFromPUSHID( const PUSHID: string; ConvertToLocalTime: boolean): TDateTime; var tsi: int64; c: integer; begin Assert(length(PUSHID) = 20, 'Invalid PUSHID length'); tsi := 0; for c := low(PUSHID) to low(PUSHID) + 7 do tsi := tsi shl 6 + pos(PUSHID[c], cPushID64) - low(cPushID64); result := UnixToDateTime(tsi div 1000); if ConvertToLocalTime then result := TTimeZone.Local.ToLocalTime(result); end; {$IF Defined(FMX) OR Defined(FGX)} class function TFirebaseHelpers.ContentTypeToFileExt( const ContentType: string): string; {$IF CompilerVersion < 35} // Delphi 10.4 and before function SameText(const ContentType: string; AContentType: TRESTContentType): boolean; begin result := System.SysUtils.SameText(ContentType, ContentTypeToString(AContentType)); end; {$ENDIF} begin if SameText(ContentType, TRESTContentType.ctIMAGE_JPEG) then result := SJPGImageExtension else if SameText(ContentType, TRESTContentType.ctIMAGE_GIF) then result := SGIFImageExtension else if SameText(ContentType, TRESTContentType.ctIMAGE_PNG) then result := SPNGImageExtension else if SameText(ContentType, TRESTContentType.ctIMAGE_TIFF) then result := STIFFImageExtension else if SameText(ContentType, TRESTContentType.ctIMAGE_SVG_XML) or SameText(ContentType, TRESTContentType.ctAPPLICATION_XML) or SameText(ContentType, TRESTContentType.ctTEXT_XML) then result := '.xml' else if SameText(ContentType, TRESTContentType.ctAPPLICATION_JSON) then result := '.json' else if SameText(ContentType, TRESTContentType.ctAPPLICATION_PDF) then result := '.pdf' else if SameText(ContentType, TRESTContentType.ctAPPLICATION_ZIP) then result := '.zip' else if SameText(ContentType, TRESTContentType.ctTEXT_HTML) then result := '.htm' else if SameText(ContentType, TRESTContentType.ctTEXT_CSS) then result := '.css' else if SameText(ContentType, TRESTContentType.ctTEXT_JAVASCRIPT) or SameText(ContentType, TRESTContentType.ctAPPLICATION_JAVASCRIPT)then result := '.js' else if SameText(ContentType, TRESTContentType.ctTEXT_PLAIN) then result := '.txt' else if SameText(ContentType, TRESTContentType.ctTEXT_CSV) then result := '.csv' else if SameText(ContentType, TRESTContentType.ctTEXT_X_MARKDOWN) then result := '.md' else result := ''; end; class function TFirebaseHelpers.ImageStreamToContentType( Stream: TStream): TRESTContentType; var ImgType: string; begin ImgType := TImageTypeChecker.GetType(Stream); if ImgType = SJPGImageExtension then result := TRESTContentType.ctIMAGE_JPEG else if ImgType = SGIFImageExtension then result := TRESTContentType.ctIMAGE_GIF else if ImgType = SPNGImageExtension then result := TRESTContentType.ctIMAGE_PNG else if ImgType = STIFFImageExtension then result := TRESTContentType.ctIMAGE_TIFF else // if ImgType = SBMPImageExtension then // Unsupported image type! {$IF CompilerVersion < 35} // Delphi 10.4 and before result := ctNone; {$ELSE} result := ''; {$ENDIF} end; {$ENDIF} class function TFirebaseHelpers.IsEMailAdress(const EMail: string): boolean; // Returns True if the email address is valid // Inspired by Ernesto D'Spirito function IsAtomChars(c: Char): boolean; begin result := (c >= #33) and (c <= #255) and not c.IsInArray( ['(', ')', '<', '>', '@', ',', ';', ':', '\', '/', '"', '.', '[', ']', #127]); end; function IsQuotedStringChars(c: Char): boolean; begin result := (c < #255) and not c.IsInArray(['"', #13, '\']); end; type States = (stBegin, stAtom, stQText, st_QChar, stQuote, stLocalPeriod, stExpectingSubDomain, stSubDomain, stHyphen); var State: States; i, subdomains: integer; c: char; begin State := stBegin; subdomains := 1; for i := low(email) to high(email) do begin c := email[i]; case State of stBegin: if IsAtomChars(c) then State := stAtom else if c = '"' then State := stQText else exit(false); stAtom: if c = '@' then State := stExpectingSubDomain else if c = '.' then State := stLocalPeriod else if not IsAtomChars(c) then exit(false); stQText: if c = '\' then State := st_QChar else if c = '"' then State := stQuote else if not IsQuotedStringChars(c) then exit(false); st_QChar: State := stQText; stQuote: if c = '@' then State := stExpectingSubDomain else if c = '.' then State := stLocalPeriod else exit(false); stLocalPeriod: if IsAtomChars(c) then State := stAtom else if c = '"' then State := stQText else exit(false); stExpectingSubDomain: if c.IsLetter then State := stSubDomain else exit(false); stSubDomain: if c = '.' then begin inc(subdomains); State := stExpectingSubDomain end else if c = '-' then State := stHyphen else if not c.IsLetterOrDigit then exit((i = high(email)) and (subdomains >= 2)); stHyphen: if c.IsLetterOrDigit then State := stSubDomain else if c <> '-' then exit(false); end; end; result := (State = stSubDomain) and (subdomains >= 2); end; class function TFirebaseHelpers.IsMainThread: boolean; begin result := TThread.Current.ThreadID = System.MainThreadID; end; class function TFirebaseHelpers.GetPlatform: string; begin {$IF defined(WIN32)} result := 'Win32'; {$ELSEIF defined(WIN64)} result := 'Win64'; {$ELSEIF defined(MACOS32)} result := 'Mac32'; {$ELSEIF defined(MACOS64)} result := 'Mac64'; {$ELSEIF defined(IOS32)} result := 'iOS32'; {$ELSEIF defined(IOS64)} result := 'iOS64'; {$ELSEIF defined(ANDROID32)} result := 'Android32'; {$ELSEIF defined(ANDROID64)} result := 'Android64'; {$ELSEIF defined(LINUX32)} result := 'Linux32'; {$ELSEIF defined(Linux64)} result := 'Linux64'; {$ELSE} result := 'Platform?'; {$ENDIF} end; class function TFirebaseHelpers.GetConfigAndPlatform: string; begin {$IF defined(RELEASE)} result := 'Release Build/'; {$ELSEIF defined(DEBUG)} result := 'Debug Build/'; {$ELSE} result := 'Unknown Build/'; {$ENDIF} result := result + GetPlatform; end; class function TFirebaseHelpers.GetLanguageInEnglishFromCode( const Code: string): string; begin if SameText(Code, 'af') then result := 'Afrikaans' else if SameText(Code, 'am') then result := 'Amharic' else if SameText(Code, 'ar') then result := 'Arabic' else if SameText(Code, 'arn') then result := 'Mapudungun' else if SameText(Code, 'as') then result := 'Assamese' else if SameText(Code, 'az') then result := 'Azeri' else if SameText(Code, 'ba') then result := 'Bashkir' else if SameText(Code, 'be') then result := 'Belarusian' else if SameText(Code, 'bg') then result := 'Bulgarian' else if SameText(Code, 'bn') then result := 'Bengali' else if SameText(Code, 'bo') then result := 'Tibetan' else if SameText(Code, 'br') then result := 'Breton' else if SameText(Code, 'bs') then result := 'Bosnian' else if SameText(Code, 'ca') then result := 'Catalan' else if SameText(Code, 'co') then result := 'Corsican' else if SameText(Code, 'cs') then result := 'Czech' else if SameText(Code, 'cy') then result := 'Welsh' else if SameText(Code, 'da') then result := 'Danish' else if SameText(Code, 'de') then result := 'German' else if SameText(Code, 'dsb') then result := 'Lower Sorbian' else if SameText(Code, 'dv') then result := 'Divehi' else if SameText(Code, 'el') then result := 'Greek' else if SameText(Code, 'en') then result := 'English' else if SameText(Code, 'es') then result := 'Spanish' else if SameText(Code, 'et') then result := 'Estonian' else if SameText(Code, 'eu') then result := 'Basque' else if SameText(Code, 'fa') then result := 'Persian' else if SameText(Code, 'fi') then result := 'Finnish' else if SameText(Code, 'fil') then result := 'Filipino' else if SameText(Code, 'fo') then result := 'Faroese' else if SameText(Code, 'fr') then result := 'French' else if SameText(Code, 'fy') then result := 'Frisian' else if SameText(Code, 'ga') then result := 'Irish' else if SameText(Code, 'gd') then result := 'Scottish Gaelic' else if SameText(Code, 'gl') then result := 'Galician' else if SameText(Code, 'gsw') then result := 'Alsatian' else if SameText(Code, 'gu') then result := 'Gujarati' else if SameText(Code, 'ha') then result := 'Hausa' else if SameText(Code, 'he') then result := 'Hebrew' else if SameText(Code, 'hi') then result := 'Hindi' else if SameText(Code, 'hr') then result := 'Croatian' else if SameText(Code, 'hsb') then result := 'Upper Sorbian' else if SameText(Code, 'hu') then result := 'Hungarian' else if SameText(Code, 'hy') then result := 'Armenian' else if SameText(Code, 'id') then result := 'Indonesian' else if SameText(Code, 'ig') then result := 'Igbo' else if SameText(Code, 'ii') then result := 'Yi' else if SameText(Code, 'is') then result := 'Icelandic' else if SameText(Code, 'it') then result := 'Italian' else if SameText(Code, 'iu') then result := 'Inuktitut' else if SameText(Code, 'ja') then result := 'Japanese' else if SameText(Code, 'ka') then result := 'Georgian' else if SameText(Code, 'kk') then result := 'Kazakh' else if SameText(Code, 'kl') then result := 'Greenlandic' else if SameText(Code, 'km') then result := 'Khmer' else if SameText(Code, 'kn') then result := 'Kannada' else if SameText(Code, 'ko') then result := 'Korean' else if SameText(Code, 'kok') then result := 'Konkani' else if SameText(Code, 'ky') then result := 'Kyrgyz' else if SameText(Code, 'la') then result := 'Latin' else if SameText(Code, 'lb') then result := 'Luxembourgish' else if SameText(Code, 'li') then result := 'Limburgan' else if SameText(Code, 'lo') then result := 'Lao' else if SameText(Code, 'ln') then result := 'Lingala' else if SameText(Code, 'lt') then result := 'Lithuanian' else if SameText(Code, 'lu') then result := 'Luba-Katanga' else if SameText(Code, 'lv') then result := 'Latvian' else if SameText(Code, 'mi') then result := 'Maori' else if SameText(Code, 'mk') then result := 'Macedonian' else if SameText(Code, 'ml') then result := 'Malayalam' else if SameText(Code, 'mn') then result := 'Mongolian' else if SameText(Code, 'moh') then result := 'Mohawk' else if SameText(Code, 'mr') then result := 'Marathi' else if SameText(Code, 'ms') then result := 'Malay' else if SameText(Code, 'mt') then result := 'Maltese' else if SameText(Code, 'my') then result := 'Burmese' else if SameText(Code, 'nb') then result := 'Norwegian (Bokmål)' else if SameText(Code, 'ne') then result := 'Nepali' else if SameText(Code, 'nl') then result := 'Dutch' else if SameText(Code, 'nn') then result := 'Norwegian (Nynorsk)' else if SameText(Code, 'no') then result := 'Norwegian' else if SameText(Code, 'nso') then result := 'Sesotho' else if SameText(Code, 'oc') then result := 'Occitan' else if SameText(Code, 'or') then result := 'Oriya' else if SameText(Code, 'pa') then result := 'Punjabi' else if SameText(Code, 'pl') then result := 'Polish' else if SameText(Code, 'prs') then result := 'Dari' else if SameText(Code, 'ps') then result := 'Pashto' else if SameText(Code, 'pt') then result := 'Portuguese' else if SameText(Code, 'quc') then result := 'K''iche' else if SameText(Code, 'quz') then result := 'Quechua' else if SameText(Code, 'rm') then result := 'Romansh' else if SameText(Code, 'ro') then result := 'Romanian' else if SameText(Code, 'ru') then result := 'Russian' else if SameText(Code, 'rw') then result := 'Kinyarwanda' else if SameText(Code, 'sa') then result := 'Sanskrit' else if SameText(Code, 'sah') then result := 'Yakut' else if SameText(Code, 'se') then result := 'Sami (Northern)' else if SameText(Code, 'si') then result := 'Sinhala' else if SameText(Code, 'sk') then result := 'Slovak' else if SameText(Code, 'sl') then result := 'Slovenian' else if SameText(Code, 'sma') then result := 'Sami (Southern)' else if SameText(Code, 'smj') then result := 'Sami (Lule)' else if SameText(Code, 'smn') then result := 'Sami (Inari)' else if SameText(Code, 'sms') then result := 'Sami (Skolt)' else if SameText(Code, 'sq') then result := 'Albanian' else if SameText(Code, 'sr') then result := 'Serbian' else if SameText(Code, 'sv') then result := 'Swedish' else if SameText(Code, 'sw') then result := 'Kiswahili' else if SameText(Code, 'syr') then result := 'Syriac' else if SameText(Code, 'ta') then result := 'Tamil' else if SameText(Code, 'te') then result := 'Telugu' else if SameText(Code, 'tg') then result := 'Tajik' else if SameText(Code, 'th') then result := 'Thai' else if SameText(Code, 'tk') then result := 'Turkmen' else if SameText(Code, 'tn') then result := 'Setswana' else if SameText(Code, 'tr') then result := 'Turkish' else if SameText(Code, 'tt') then result := 'Tatar' else if SameText(Code, 'tzm') then result := 'Tamazight' else if SameText(Code, 'ug') then result := 'Uyghur' else if SameText(Code, 'uk') then result := 'Ukrainian' else if SameText(Code, 'ur') then result := 'Urdu' else if SameText(Code, 'uz') then result := 'Uzbek' else if SameText(Code, 'vi') then result := 'Vietnamese' else if SameText(Code, 'wo') then result := 'Wolof' else if SameText(Code, 'xh') then result := 'isiXhosa' else if SameText(Code, 'yo') then result := 'Yoruba' else if SameText(Code, 'zh') then result := 'Chinese' else if SameText(Code, 'zu') then result := 'isiZulu' else result := Code + '?'; end; { TFirestorePath } class function TFirestorePath.ContainsPathDelim(const Path: string): boolean; begin result := (pos('/', Path) >= 0) or (pos('\', Path) >= 0); end; class function TFirestorePath.TrimStartAndEndPathDelimiters( const Path: string): string; begin if Path.StartsWith('/') or Path.StartsWith('\') then begin if Path.EndsWith('/') or Path.EndsWith('\') then result := Path.Substring(1, length(Path) - 2) else result := Path.Substring(1) end else if Path.EndsWith('/') or Path.EndsWith('\') then result := Path.Substring(0, length(Path) - 1) else result := Path; end; class function TFirestorePath.ConvertToDocPath( const Path: string): TRequestResourceParam; begin result := TrimStartAndEndPathDelimiters(Path).Split(['/', '\']); end; class function TFirestorePath.ExtractLastCollection(const Path: string): string; var TrimmedPath: string; c: integer; begin TrimmedPath := TrimStartAndEndPathDelimiters(Path); {$IF CompilerVersion < 34} // Delphi 10.3 and before c := TrimmedPath.LastDelimiter('/\'); {$ELSE} c := TrimmedPath.LastDelimiter(['/', '\']); {$ENDIF} if c < 0 then result := TrimmedPath else result := TrimmedPath.Substring(c + 1); end; class function TFirestorePath.GetDocPath(Params: TRequestResourceParam): string; var i: integer; begin result := ''; for i := low(Params) to high(Params) do result := result + '/' + Params[i]; end; class function TFirestorePath.DocPathWithoutLastCollection( const Path: string): TRequestResourceParam; var TrimmedPath: string; c: integer; begin TrimmedPath := TrimStartAndEndPathDelimiters(Path); {$IF CompilerVersion < 34} // Delphi 10.3 and before c := TrimmedPath.LastDelimiter('/\'); {$ELSE} c := TrimmedPath.LastDelimiter(['/', '\']); {$ENDIF} if c < 0 then result := [] else result := ConvertToDocPath(TrimmedPath.Substring(0, c)); end; { TJSONHelpers } function TJSONHelpers.GetIntegerValue: integer; begin result := GetValue<integer>('integerValue'); end; function TJSONHelpers.GetInt64Value: Int64; begin result := GetValue<Int64>('integerValue'); end; function TJSONHelpers.GetIntegerValue(const Name: string): integer; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetIntegerValue else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetIntegerValueDef(const Name: string; Default: integer): integer; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetIntegerValue else result := Default; end; function TJSONHelpers.GetInt64Value(const Name: string): Int64; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetInt64Value else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetInt64ValueDef(const Name: string; Default: Int64): Int64; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetInt64Value else result := Default; end; function TJSONHelpers.GetStringValue: string; begin result := GetValue<string>('stringValue'); end; function TJSONHelpers.GetStringValue(const Name: string): string; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetStringValue else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetStringValueDef(const Name, Default: string): string; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetStringValue else result := Default; end; function TJSONHelpers.GetBooleanValue: boolean; begin result := GetValue<boolean>('booleanValue'); end; function TJSONHelpers.GetBooleanValue(const Name: string): boolean; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetBooleanValue else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetBooleanValueDef(const Name: string; Default: boolean): boolean; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetBooleanValue else result := Default; end; function TJSONHelpers.GetDoubleValue: double; begin result := GetValue<double>('doubleValue'); end; function TJSONHelpers.GetDoubleValue(const Name: string): double; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetDoubleValue else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetDoubleValueDef(const Name: string; Default: double): double; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetDoubleValue else result := Default; end; function TJSONHelpers.GetTimeStampValue( TimeZone: FB4D.Interfaces.TTimeZone): TDateTime; begin result := GetValue<TDateTime>('timestampValue'); if TimeZone = tzLocalTime then result := TFirebaseHelpers.ConvertToLocalDateTime(result); end; function TJSONHelpers.GetTimeStampValue(const Name: string; TimeZone: FB4D.Interfaces.TTimeZone): TDateTime; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then begin result := (Val as TJSONObject).GetTimeStampValue; if TimeZone = tzLocalTime then result := TFirebaseHelpers.ConvertToLocalDateTime(result); end else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetTimeStampValueDef(const Name: string; Default: TDateTime; TimeZone: FB4D.Interfaces.TTimeZone): TDateTime; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then begin result := (Val as TJSONObject).GetTimeStampValue; if TimeZone = tzLocalTime then result := TFirebaseHelpers.ConvertToLocalDateTime(result); end else result := Default; end; function TJSONHelpers.GetGeoPoint: TLocationCoord2D; var Val: TJSONValue; begin Val := GetValue<TJSONValue>('geoPointValue'); result := TLocationCoord2D.Create(Val.GetValue<double>('latitude'), Val.GetValue<double>('longitude')) end; function TJSONHelpers.GetGeoPoint(const Name: string): TLocationCoord2D; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetGeoPoint else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetGeoPointDef(const Name: string; Default: TLocationCoord2D): TLocationCoord2D; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetGeoPoint else result := Default; end; class function TJSONHelpers.SetStringValue(const Val: string): TJSONObject; begin result := TJSONObject.Create(TJSONPair.Create('stringValue', TJSONString.Create(Val))); end; class function TJSONHelpers.SetString(const VarName, Val: string): TJSONPair; begin result := TJSONPair.Create(VarName, SetStringValue(Val)); end; class function TJSONHelpers.SetIntegerValue(Val: integer): TJSONObject; begin result := TJSONObject.Create(TJSONPair.Create('integerValue', TJSONNumber.Create(Val))); end; class function TJSONHelpers.SetInt64Value(Val: Int64): TJSONObject; begin result := TJSONObject.Create(TJSONPair.Create('integerValue', TJSONNumber.Create(Val))); end; class function TJSONHelpers.SetInt64(const VarName: string; Val: Int64): TJSONPair; begin result := TJSONPair.Create(VarName, SetInt64Value(Val)); end; class function TJSONHelpers.SetInteger(const VarName: string; Val: integer): TJSONPair; begin result := TJSONPair.Create(VarName, SetIntegerValue(Val)); end; class function TJSONHelpers.SetDoubleValue(Val: double): TJSONObject; begin result := TJSONObject.Create(TJSONPair.Create('doubleValue', TJSONNumber.Create(Val))); end; class function TJSONHelpers.SetDouble(const VarName: string; Val: double): TJSONPair; begin result := TJSONPair.Create(VarName, SetDoubleValue(Val)); end; class function TJSONHelpers.SetBooleanValue(Val: boolean): TJSONObject; begin result := TJSONObject.Create(TJSONPair.Create('booleanValue', TJSONBool.Create(Val))); end; class function TJSONHelpers.SetBoolean(const VarName: string; Val: boolean): TJSONPair; begin result := TJSONPair.Create(VarName, SetBooleanValue(Val)); end; class function TJSONHelpers.SetTimeStampValue(Val: TDateTime): TJSONObject; begin result := TJSONObject.Create(TJSONPair.Create('timestampValue', TJSONString.Create(TFirebaseHelpers.CodeRFC3339DateTime(Val)))); end; class function TJSONHelpers.SetTimeStamp(const VarName: string; Val: TDateTime): TJSONPair; begin result := TJSONPair.Create(VarName, SetTimeStampValue(Val)); end; class function TJSONHelpers.SetNullValue: TJSONObject; begin result := TJSONObject.Create(TJSONPair.Create('nullValue', TJSONNull.Create)); end; class function TJSONHelpers.SetNull(const VarName: string): TJSONPair; begin result := TJSONPair.Create(VarName, SetNullValue); end; function TJSONHelpers.IsNull: boolean; begin result := GetValue<TJSONValue>('nullValue') is TJSONNull; end; function TJSONHelpers.GetReference: string; begin result := GetValue<string>('referenceValue'); end; function TJSONHelpers.GetReference(const Name: string): string; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetReference else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetReferenceDef(const Name, Default: string): string; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetReference else result := Default; end; class function TJSONHelpers.SetReferenceValue(const ProjectID, Ref: string; const Database: string): TJSONObject; function ConvertRefPath(const ProjectID, Reference: string): string; var RefWithPath: string; begin RefWithPath := Reference; if not RefWithPath.StartsWith('/') then RefWithPath := '/' + RefWithPath; result := System.SysUtils.Format(cFirestoreDocumentPath, [ProjectID, Database, RefWithPath]); end; begin result := TJSONObject.Create(TJSONPair.Create('referenceValue', TJSONString.Create(ConvertRefPath(ProjectID, Ref)))); end; class function TJSONHelpers.SetReference(const Name, ProjectID, Ref: string): TJSONPair; begin result := TJSONPair.Create(Name, SetReferenceValue(ProjectID, Ref)); end; class function TJSONHelpers.SetGeoPointValue(Val: TLocationCoord2D): TJSONObject; var Geo: TJSONObject; begin Geo := TJSONObject.Create; Geo.AddPair('latitude', TJSONNumber.Create(Val.Latitude)); Geo.AddPair('longitude', TJSONNumber.Create(Val.Longitude)); result := TJSONObject.Create(TJSONPair.Create('geoPointValue', Geo)); end; class function TJSONHelpers.SetGeoPoint(const VarName: string; Val: TLocationCoord2D): TJSONPair; begin result := TJSONPair.Create(VarName, SetGeoPointValue(Val)); end; class function TJSONHelpers.SetBytesValue(Val: TBytes): TJSONObject; begin result := TJSONObject.Create(TJSONPair.Create('bytesValue', TJSONString.Create(TNetEncoding.Base64.EncodeBytesToString(Val)))); end; class function TJSONHelpers.SetBytes(const VarName: string; Val: TBytes): TJSONPair; begin result := TJSONPair.Create(VarName, SetBytesValue(Val)); end; function TJSONHelpers.GetBytes: TBytes; begin result := TNetEncoding.Base64.DecodeStringToBytes( GetValue<string>('bytesValue')); end; function TJSONHelpers.GetBytes(const Name: string): TBytes; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetBytes else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetMapSize: integer; begin result := GetValue<TJSONObject>('mapValue'). GetValue<TJSONObject>('fields').Count; end; function TJSONHelpers.GetMapSize(const Name: string): integer; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetMapSize else result := 0; end; function TJSONHelpers.GetMapItem(Ind: integer): TJSONPair; var Obj: TJSONObject; begin Obj := GetValue<TJSONObject>('mapValue').GetValue<TJSONObject>('fields'); if (Ind < 0) or (Ind >= Obj.Count) then raise EJSONException.CreateFmt(rsMapItemOutOfBounds, [Ind]); result := Obj.Pairs[Ind]; end; function TJSONHelpers.GetMapItem(const Name: string): TJSONObject; var Obj: TJSONObject; Ind: integer; begin result := nil; Obj := GetValue<TJSONObject>('mapValue').GetValue<TJSONObject>('fields'); if assigned(Obj) then for Ind := 0 to Obj.Count - 1 do if SameText(Obj.Pairs[Ind].JsonString.Value, Name) then exit(Obj.Pairs[Ind].JsonValue as TJSONObject); end; function TJSONHelpers.GetMapItem(const Name: string; Ind: integer): TJSONPair; var Val: TJSONValue; begin result := nil; Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetMapItem(Ind) end; function TJSONHelpers.GetMapValue(const Name: string; Ind: integer): TJSONObject; begin result := GetMapItem(Name, Ind).JsonValue as TJSONObject; end; class function TJSONHelpers.SetMapValue(MapVars: TFirestoreMap): TJSONObject; var Map: TJSONObject; c: integer; begin Map := TJSONObject.Create; for c := 0 to length(mapVars) - 1 do Map.AddPair(MapVars[c]); result := TJSONObject.Create(TJSONPair.Create('mapValue', TJSONObject.Create(TJSONPair.Create('fields', Map)))); end; class function TJSONHelpers.SetMap(const VarName: string; MapVars: TFirestoreMap): TJSONPair; begin result := TJSONPair.Create(VarName, SetMapValue(MapVars)); end; class function TJSONHelpers.SetArray(const VarName: string; FSArr: TFirestoreArr): TJSONPair; function SetArrayValue(FSArr: TFirestoreArr): TJSONObject; var Arr: TJSONArray; c: integer; begin Arr := TJSONArray.Create; for c := 0 to length(FSArr) - 1 do Arr.AddElement(FSArr[c]); result := TJSONObject.Create(TJSONPair.Create('arrayValue', TJSONObject.Create(TJSONPair.Create('values', Arr)))); end; begin result := TJSONPair.Create(VarName, SetArrayValue(FSArr)); end; class function TJSONHelpers.SetStringArray(const VarName: string; Strings: TStringDynArray): TJSONPair; var Arr: TFirestoreArr; c: integer; begin SetLength(Arr, length(Strings)); for c := 0 to length(Strings) - 1 do Arr[c] := TJSONObject.SetStringValue(Strings[c]); result := SetArray(VarName, Arr); end; class function TJSONHelpers.SetStringArray(const VarName: string; Strings: TStringList): TJSONPair; var Arr: TFirestoreArr; c: integer; begin SetLength(Arr, Strings.Count); for c := 0 to Strings.Count - 1 do Arr[c] := TJSONObject.SetStringValue(Strings[c]); result := SetArray(VarName, Arr); end; class function TJSONHelpers.SetStringArray(const VarName: string; Strings: TList<string>): TJSONPair; var Arr: TFirestoreArr; c: integer; begin SetLength(Arr, Strings.Count); for c := 0 to Strings.Count - 1 do Arr[c] := TJSONObject.SetStringValue(Strings[c]); result := SetArray(VarName, Arr); end; function TJSONHelpers.GetArraySize: integer; var Val : TJSONValue; begin Val := GetValue<TJSONObject>('arrayValue').FindValue('values'); if assigned(Val) then result := TJSONArray(Val).Count else result := 0; end; function TJSONHelpers.GetArraySize(const Name: string): integer; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetArraySize else result := 0; end; function TJSONHelpers.GetArrayItem(Ind: integer): TJSONObject; var Arr: TJSONArray; Obj: TJSONObject; begin Arr := GetValue<TJSONObject>('arrayValue').GetValue<TJSONArray>('values'); if (Ind < 0) or (Ind >= Arr.Count) then raise EJSONException.CreateFmt(rsArrayItemOutOfBounds, [Ind]); if not(Arr.Items[Ind] is TJSONObject) then raise EJSONException.CreateFmt(rsInvalidArrayItem, [Ind]); Obj := Arr.Items[Ind] as TJSONObject; if Obj.Count <> 1 then raise EJSONException.CreateFmt(rsInvalidArrayItem, [Ind]); result := Obj; end; function TJSONHelpers.GetArrayItem(const Name: string; Ind: integer): TJSONObject; var Val: TJSONValue; begin Val := GetValue(Name); if assigned(Val) then result := (Val as TJSONObject).GetArrayItem(Ind) else raise EJSONException.CreateFmt(SValueNotFound, [Name]); end; function TJSONHelpers.GetStringArray: TStringDynArray; var Arr: TJSONArray; c: integer; begin Arr := GetValue<TJSONObject>('arrayValue').GetValue<TJSONArray>('values'); SetLength(result, Arr.Count); for c := 0 to Arr.Count - 1 do result[c] := (Arr.Items[0] as TJSONObject).GetStringValue; end; { TQueryParamsHelper } class function TQueryParamsHelper.CreateQueryParams( CheckThisInstanceFirst: TQueryParams): TQueryParams; begin if Assigned(CheckThisInstanceFirst) then result := CheckThisInstanceFirst else result := TQueryParams.Create; end; function TQueryParamsHelper.AddLimitToFirst( LimitToFirst: integer): TQueryParams; begin Add(cGetQueryParamLimitToFirst, [LimitToFirst.ToString]); result := self; end; function TQueryParamsHelper.AddLimitToLast(LimitToLast: integer): TQueryParams; begin Add(cGetQueryParamLimitToLast, [LimitToLast.ToString]); result := self; end; function TQueryParamsHelper.AddOrderBy(const FieldName: string): TQueryParams; begin if not FieldName.IsEmpty then Add(cGetQueryParamOrderBy, ['"' + StringReplace(FieldName, '"', '""', [rfReplaceAll]) + '"']); result := self; end; function TQueryParamsHelper.AddOrderByType( const TypeName: string): TQueryParams; const sQuery = '"$%s"'; begin if not TypeName.IsEmpty then Add(cGetQueryParamOrderBy, [Format(sQuery, [TypeName])]); result := self; end; function TQueryParamsHelper.AddPageSize(PageSize: integer): TQueryParams; begin Add(cFirestorePageSize, [PageSize.ToString]); result := self; end; function TQueryParamsHelper.AddPageToken(const PageToken: string): TQueryParams; begin if not PageToken.IsEmpty then Add(cFirestorePageToken, [PageToken]); result := self; end; function TQueryParamsHelper.AddTransaction( Transaction: TFirestoreReadTransaction): TQueryParams; begin if not Transaction.IsEmpty then Add(cFirestoreTransaction, [Transaction]); result := self; end; end.
unit TranscendBlock; interface uses Collection, Kernel, Environmental, BackupInterfaces, Accounts, Surfaces, Protocol, CacheAgent; type TMetaTranscendBlock = class( TMetaEnvironmentalBlock ) public constructor Create( anId : string; aLevelReq : string; aTime : integer; aBlockClass : CBlock ); private fLevelReq : string; fTime : integer; public property LevelReq : string read fLevelReq; property Time : integer read fTime; public procedure StoreExtraInfoToCache( Cache : TObjectCache ); override; protected procedure ModifyMetaFacility( MetaFacility : TMetaFacility ); override; public function Transcends(Facility : TFacility) : boolean; override; end; TTranscendBlock = class( TEnvironmentalBlock ) public function Evaluate : TEvaluationResult; override; public function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; procedure AutoConnect( loaded : boolean ); override; public procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; procedure BlockLoaded; override; public procedure StoreToCache( Cache : TObjectCache ); override; private fTranscended : boolean; fOwnerName : string; fWordsOfWisdom : string; fCanceled : boolean; published property Transcended : boolean read fTranscended write fTranscended; property Canceled : boolean read fCanceled write fCanceled; published procedure RDOSetWordsOfWisdom( words : widestring ); procedure RDOCacncelTransc; end; procedure RegisterBackup; implementation uses SysUtils, SimHints, Languages, ClassStorage, Logs, MetaInstances; // TMetaTranscendBlock constructor TMetaTranscendBlock.Create( anId : string; aLevelReq : string; aTime : integer; aBlockClass : CBlock ); begin inherited Create( anId, aBlockClass ); fLevelReq := aLevelReq; fTime := aTime; IsTransBlock := true; end; procedure TMetaTranscendBlock.StoreExtraInfoToCache( Cache : TObjectCache ); var Level : TTycoonLevel; begin inherited; Level := TTycoonLevel(TheClassStorage.ClassById[tidClassFamily_TycoonLevels, fLevelReq]); if Level <> nil then Cache.WriteInteger( 'RequiredLevel', Level.Tier ); end; procedure TMetaTranscendBlock.ModifyMetaFacility( MetaFacility : TMetaFacility ); { var i : integer; Level : TTycoonLevel; } begin inherited; { Level := TTycoonLevel(TheClassStorage.ClassById[tidClassFamily_TycoonLevels, fLevelReq]); for i := 0 to pred(LangList.Count) do MetaFacility.Requires_MLS.Values[LangList[i]] := SimHints.GetHintText( mtidDescFactoryReq.Values[LangList[i]], [0] ) + ' ' + Level.Name_MLS.Values[LangList[i]]; } end; function TMetaTranscendBlock.Transcends(Facility : TFacility) : boolean; begin if (Facility.CurrBlock <> nil) and ObjectIs('TTranscendBlock', Facility.CurrBlock) then result := not TTranscendBlock(Facility.CurrBlock).Canceled else result := false; end; // TTranscendBlock function TTranscendBlock.Evaluate : TEvaluationResult; var Tycoon : TTycoon; i : integer; Amount : TMoney; facAge : integer; begin result := inherited Evaluate; // >> Check this!!! facAge := Facility.Age; if not fTranscended and (facAge >= TMetaTranscendBlock(MetaBlock).Time*365*24) and (Facility.Company <> nil) and (Facility.Company.Owner <> nil) then begin Tycoon := Facility.Company.Owner; // Calculate debts Amount := 0; for i := 0 to pred(Tycoon.Loans.Count) do Amount := Amount + TLoan(Tycoon.Loans).Amount; // Check if he owns money to any bank if Amount = 0 then begin // >> Time to die fTranscended := true; if (Facility.Town <> nil) and not Facility.Company.Owner.IsRole // Mayors, Presidents and Ministers cannot trascend then begin Tycoon.Transcending := true; Facility.Town.ModelFactory.ResetTycoon(Tycoon); end; end; end; end; function TTranscendBlock.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; begin result := inherited GetStatusText( kind, ToTycoon ); case kind of sttMain : result := fOwnerName; sttSecondary : if not fTranscended then result := result + SimHints.GetHintText( mtidPlayerWillTranscend.Values[ToTycoon.Language], [round(TMetaTranscendBlock(MetaBlock).Time*365 - Facility.Age/24)] ) else result := result + fOwnerName + ': ' + fWordsOfWisdom; sttHint : if not fTranscended then result := result + SimHints.GetHintText( mtidBewareOfTranscend.Values[ToTycoon.Language], [fOwnerName] ); end; end; procedure TTranscendBlock.AutoConnect( loaded : boolean ); begin inherited; if not loaded then fOwnerName := Facility.Company.Owner.Name; end; procedure TTranscendBlock.LoadFromBackup( Reader : IBackupReader ); begin inherited; fTranscended := Reader.ReadBoolean( 'Transcended', false ); fOwnerName := Reader.ReadString( 'OwnerName', '' ); fWordsOfWisdom := Reader.ReadString( 'WordsOfWisdom', '' ); end; procedure TTranscendBlock.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteBoolean( 'Transcended', fTranscended ); Writer.WriteString( 'OwnerName', fOwnerName ); Writer.WriteString( 'WordsOfWisdom', fWordsOfWisdom ); end; procedure TTranscendBlock.BlockLoaded; begin inherited; // Patch if (Facility <> nil) and Facility.Deleted then Facility.Deleted := false; if (Facility <> nil) and Facility.Stopped then Facility.Stopped := false; end; procedure TTranscendBlock.StoreToCache( Cache : TObjectCache ); begin inherited; Cache.WriteString( 'WordsOfWisdom', fWordsOfWisdom ); Cache.WriteString( 'OwnerName', fOwnerName ); Cache.WriteBoolean( 'Transcended', fTranscended ); Cache.WriteBoolean('TransCanceled', fCanceled); end; procedure TTranscendBlock.RDOSetWordsOfWisdom( words : widestring ); var Tycoon : TTycoon; begin if (Facility.Town <> nil) and (Facility.Town.WorldLocator <> nil) then Tycoon := Facility.Town.WorldLocator.GetTycoonByName(fOwnerName) else Tycoon := nil; if (Tycoon <> nil) and Tycoon.CheckOpAuthenticity then begin fWordsOfWisdom := words; Facility.Cache(false, true); end; end; procedure TTranscendBlock.RDOCacncelTransc; var Tycoon : TTycoon; begin if (Facility.Town <> nil) and (Facility.Town.WorldLocator <> nil) then Tycoon := Facility.Town.WorldLocator.GetTycoonByName(fOwnerName) else Tycoon := nil; if (Tycoon <> nil) and Tycoon.CheckOpAuthenticity then begin fCanceled := true; Facility.Town.ModelFactory.RequestDeletion(Facility); end; end; // RegisterBackup procedure RegisterBackup; begin BackupInterfaces.RegisterClass( TTranscendBlock ); end; end.
unit d_StrEdit; { $Id: d_StrEdit.pas,v 1.4 2013/04/19 13:05:16 lulin Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, BottomBtnDlg, StdCtrls, Buttons, ExtCtrls; type TStringEditDlg = class(TBottomBtnDlg) lblText: TLabel; edtValue: TEdit; private function GetValue : AnsiString; procedure SetValue(aValue : AnsiString); procedure SetLabelText(aValue : AnsiString); public property Value : AnsiString read GetValue write SetValue; property LabelText : AnsiString write SetLabelText; end; function RequestStringValue(var aValue : AnsiString; AOwner: TComponent; aCaption : AnsiString = ''; aLabel : AnsiString = '') : Boolean; implementation {$R *.DFM} function RequestStringValue(var aValue : AnsiString; AOwner: TComponent; aCaption : AnsiString = ''; aLabel : AnsiString = '') : Boolean; begin With TStringEditDlg.Create(AOwner) do try Caption := aCaption; LabelText := aLabel; Value := aValue; Result := Execute; If Result then aValue := Value; finally Free; end; end; function TStringEditDlg.GetValue : AnsiString; begin Result := edtValue.Text; end; procedure TStringEditDlg.SetValue(aValue : AnsiString); begin edtValue.Text := aValue; end; procedure TStringEditDlg.SetLabelText(aValue : AnsiString); begin lblText.Caption := aValue; end; end.
unit BaiduMapAPI.PoiSearchService; //author:Xubzhlin //Email:371889755@qq.com //百度地图API Poi检索 单元 //TSearchResult 检索结果 //TPoiResult poi搜索结果 //TPoiDetailResult 详情搜索结果 //TPoiIndoorResult 室内POI搜索结果 //TPoiSortType Poi 结果排序 //TPoiBoundSearchOption POI范围内检索参数 //TPoiCitySearchOption POI城市内检索参数 //TPoiNearbySearchOption 附近检索参数 interface uses System.Generics.Collections, FMX.Maps, BaiduMapAPI.Search.CommTypes; type TPoiIndoorInfo = record address:string; bid:string; floor:string; name:string; phone:string; price:Double; latLng:TMapCoordinate; starLevel:Integer; isGroup:Boolean; isTakeOut:Boolean; isWaited:Boolean; uid:string; tag:string; groupNum:Integer; end; TPoiResult = class(TSearchResult) PoisInfo:TList<TPoiInfo>; CitysInfo:TList<TCityInfo>; PoiAddrsInfo:TList<TPoiAddrInfo>; CurrentPageCapacity:Integer; //获取单页容量,单页容量可以通过检索参数指定 CurrentPageNum:Integer; //获取当前分页编号 TotalPageNum:Integer; //获取总分页数 TotalPoiNum:Integer; //获取POI总数 isHasAddrInfo:Boolean; //是否包含门址类数据 constructor Create; destructor Destroy; override; end; TPoiDetailResult = class(TSearchResult) name:string; location:TMapCoordinate; address:string; telephone:string; uid:string; tag:string; detailUrl:string; &type:string; price:Double; overallRating:Double; tasteRating:Double; serviceRating:Double; environmentRating:Double; facilityRating:Double; hygieneRating:Double; technologyRating:Double; imageNum:Integer; grouponNum:Integer; commentNum:Integer; favoriteNum:Integer; checkinNum:Integer; shopHours:string; end; TPoiIndoorResult = class(TSearchResult) PoiIndoorsInfo:TList<TPoiIndoorInfo>; CurrentPageCapacity:Integer; //获取单页容量,单页容量可以通过检索参数指定 CurrentPageNum:Integer; //获取当前分页编号 TotalPoiNum:Integer; //获取POI总数 constructor Create; destructor Destroy; override; end; TOnGetPoiResult = procedure(Sender:TObject; PoiResult:TPoiResult) of object; TOnGetPoiDetailResult = procedure(Sender:TObject; PoiDetailResult:TPoiDetailResult) of object; TOnGetPoiIndoorResult = procedure(Sender:TObject; PoiIndoorResult:TPoiIndoorResult) of object; //Poi 检索 排序类型 TPoiSortType = (comprehensive, distance_from_near_to_far); //Poi Search 基础类 TPoiSearchrOption = class(TObject) Keyword:string; //检索关键字 PageCapacity:Integer; //设置每页容量,默认为每页10条 PageNum:Integer; //分页编号 constructor Create; end; //Poi Bound Search Option POI范围内检索参数 TPoiBoundSearchOption = class(TPoisearchrOption) NorthEast:TMapCoordinate; SouthWest:TMapCoordinate; end; //Poi City Search Option poi城市内检索参数 TPoiCitySearchOption = class(TPoisearchrOption) City:String; IsReturnAddr:Boolean; end; //Poi Near Search Option 附近检索参数 TPoiNearbySearchOption = class(TPoisearchrOption) Location:TMapCoordinate; Radius:Integer; sortType:TPoiSortType; end; IBaiduMapPoiSearchService = interface ['{C7E5EA1F-0A74-493E-AE97-29E97C4C5100}'] // Poi搜索 function PoiSearch(Option:TPoiSearchrOption):Boolean; // Poi 详情检索 function SearchPoiDetail(Uid:string):Boolean; end; TBaiduMapPoiSearchService = class(TInterfacedObject, IBaiduMapPoiSearchService) private FOnGetPoiResult:TOnGetPoiResult; FOnGetPoiDetailResult:TOnGetPoiDetailResult; FOnGetPoiIndoorResult:TOnGetPoiIndoorResult; protected function DoPoiSearch(Option:TPoiSearchrOption):Boolean; virtual; abstract; function DoSearchPoiDetail(Uid:string):Boolean; virtual; abstract; procedure GetPoiResult(PoiResult:TPoiResult); procedure GetPoiDetailResult(PoiDetailResult:TPoiDetailResult); procedure GetPoiIndoorResult(PoiIndoorResult:TPoiIndoorResult); public function PoiSearch(Option:TPoiSearchrOption):Boolean; function SearchPoiDetail(Uid:string):Boolean; property OnGetPoiResult:TOnGetPoiResult read FOnGetPoiResult write FOnGetPoiResult; property OnGetPoiDetailResult:TOnGetPoiDetailResult read FOnGetPoiDetailResult write FOnGetPoiDetailResult; property OnGetPoiIndoorResult:TOnGetPoiIndoorResult read FOnGetPoiIndoorResult write FOnGetPoiIndoorResult; end; TBaiduMapPoiSearch = class(TObject) private FPoiSearchService:TBaiduMapPoiSearchService; public constructor Create; destructor Destroy; override; property PoiSearchService:TBaiduMapPoiSearchService read FPoiSearchService; end; implementation {$IFDEF IOS} uses BaiduMapAPI.PoiSearchService.iOS; {$ENDIF} {$IFDEF ANDROID} uses BaiduMapAPI.PoiSearchService.Android; {$ENDIF ANDROID} { TPoiResult } constructor TPoiResult.Create; begin inherited Create; PoisInfo:=TList<TPoiInfo>.Create; CitysInfo:=TList<TCityInfo>.Create; PoiAddrsInfo:=TList<TPoiAddrInfo>.Create; end; destructor TPoiResult.Destroy; begin PoisInfo.Free; CitysInfo.Free; PoiAddrsInfo.Free; inherited; end; { TPoiIndoorResult } constructor TPoiIndoorResult.Create; begin PoiIndoorsInfo:=TList<TPoiIndoorInfo>.Create; end; destructor TPoiIndoorResult.Destroy; begin PoiIndoorsInfo.Free; inherited; end; { TPoiSearchrOption } constructor TPoiSearchrOption.Create; begin PageNum:=0; PageCapacity:=10; //设置每页容量,默认为每页10条 end; { TBaiduMapPoiSearchService } procedure TBaiduMapPoiSearchService.GetPoiDetailResult( PoiDetailResult: TPoiDetailResult); begin if Assigned(FOnGetPoiDetailResult) then FOnGetPoiDetailResult(Self, PoiDetailResult); end; procedure TBaiduMapPoiSearchService.GetPoiIndoorResult( PoiIndoorResult: TPoiIndoorResult); begin if Assigned(FOnGetPoiIndoorResult) then FOnGetPoiIndoorResult(Self, PoiIndoorResult); end; procedure TBaiduMapPoiSearchService.GetPoiResult(PoiResult: TPoiResult); begin if Assigned(FOnGetPoiResult) then FOnGetPoiResult(Self, PoiResult); end; function TBaiduMapPoiSearchService.PoiSearch(Option: TPoiSearchrOption):Boolean; begin Result:=DoPoiSearch(Option); end; function TBaiduMapPoiSearchService.SearchPoiDetail(Uid: string):Boolean; begin Result:=SearchPoiDetail(Uid); end; { TBaiduMapPoiSearch } constructor TBaiduMapPoiSearch.Create; begin inherited Create; {$IFDEF IOS} FPoiSearchService:=TiOSBaiduMapPoiSearchService.Create; {$ENDIF} {$IFDEF ANDROID} FPoiSearchService:=TAndroidBaiduMapPoiSearchService.Create; {$ENDIF ANDROID} end; destructor TBaiduMapPoiSearch.Destroy; begin FPoiSearchService.Free; inherited; end; end.
unit StockAppPath; interface uses SysUtils, BaseApp, BaseWinApp, define_datasrc, define_dealitem, define_dealstore_file; type TStockAppPathData = record StockItemDBPathRoot: string; StockIndexDBPathRoot: string; StockDetailDBPath_163: string; StockDetailDBPath_Sina: string; end; TStockAppPath = class(TBaseWinAppPath) protected fStockAppPathData: TStockAppPathData; function GetDataBasePath(ADBType, ADataType: integer; ADataSrc: integer): WideString; overload; override; function GetDataBasePath(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; overload; function GetInstallPath: WideString; override; public constructor Create(App: TBaseApp); override; function GetRootPath: WideString; override; function GetFileRelativePath(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; override; function GetFilePath(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; override; function GetFileName(ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; override; function GetFileExt(ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; override; function GetFileUrl(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; override; function CheckOutFileUrl(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; override; end; implementation uses IniFiles, //UtilsLog, define_price; {$IFNDEF RELEASE} const LOGTAG = 'StockAppPath.pas'; {$ENDIF} { TStockDay163AppPath } constructor TStockAppPath.Create(App: TBaseApp); begin inherited; FillChar(fStockAppPathData, SizeOf(fStockAppPathData), 0); fStockAppPathData.StockItemDBPathRoot := FilePath_StockData; fStockAppPathData.StockIndexDBPathRoot := FilePath_StockIndexData; end; function TStockAppPath.GetRootPath: WideString; begin Result := GetInstallPath; end; function TStockAppPath.GetFileRelativePath(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; var tmpDataSrcCode: string; tmpFileUrl: string; tmpReadIni: string; tmpIni: TIniFile; begin Result := ''; if DBType_Item_China = ADBType then Result := fStockAppPathData.StockItemDBPathRoot; if DBType_Index_China = ADBType then Result := fStockAppPathData.StockIndexDBPathRoot; if '' = Result then exit; tmpDataSrcCode := GetDataSrcCode(ADataSrc); case ADataType of DataType_Item: begin Result := Result + '\' + 's_dic' + '\'; end; DataType_Class: begin Result := Result + '\' + 's_class' + '\'; end; DataType_Info: begin Result := Result + '\' + 's_info' + '\'; end; DataType_DayData: begin if AParamType = Integer(weightNone) then begin Result := Result + '\' + FileExt_StockDay + tmpDataSrcCode + '\'; end else begin Result := Result + '\' + FileExt_StockDay + tmpDataSrcCode + IntToStr(AParamType) + '\'; end; end; DataType_DetailData: begin if DBType_Item_China = ADBType then begin if DataSrc_163 = ADataSrc then begin if '' <> fStockAppPathData.StockDetailDBPath_163 then begin //Log(LOGTAG, 'DataType_DetailData 163: ' + fStockAppPathData.StockDetailDBPath_163); Result := fStockAppPathData.StockDetailDBPath_163; exit; end; end; if DataSrc_Sina = ADataSrc then begin if '' <> fStockAppPathData.StockDetailDBPath_Sina then begin //Log(LOGTAG, 'DataType_DetailData sina: ' + fStockAppPathData.StockDetailDBPath_Sina); Result := fStockAppPathData.StockDetailDBPath_Sina; exit; end; end; tmpReadIni := ''; tmpFileUrl := ChangeFileExt(ParamStr(0), '.ini'); if FileExists(tmpFileUrl) then begin tmpIni := TIniFile.Create(tmpFileUrl); try tmpReadIni := tmpIni.ReadString('Path', 'DetailRoot_' + tmpDataSrcCode, ''); finally tmpIni.Free; end; end; if '' = tmpReadIni then begin tmpFileUrl := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'stockdata.ini'; if FileExists(tmpFileUrl) then begin tmpIni := TIniFile.Create(tmpFileUrl); try tmpReadIni := tmpIni.ReadString('Path', 'DetailRoot_' + tmpDataSrcCode, ''); finally tmpIni.Free; end; end; end; if '' = tmpReadIni then begin tmpReadIni := Result + '\' + FileExt_StockDetail + tmpDataSrcCode + '\'; end; if DataSrc_163 = ADataSrc then begin fStockAppPathData.StockDetailDBPath_163 := tmpReadIni; //Log(LOGTAG, 'fStockAppPathData.StockDetailDBPath_163: ' + fStockAppPathData.StockDetailDBPath_163); end; if DataSrc_Sina = ADataSrc then begin fStockAppPathData.StockDetailDBPath_Sina := tmpReadIni; //Log(LOGTAG, 'fStockAppPathData.StockDetailDBPath_Sina: ' + fStockAppPathData.StockDetailDBPath_Sina); end; Result := tmpReadIni; end else begin Result := Result + '\' + FileExt_StockDetail + tmpDataSrcCode + '\'; end; end; DataType_MinuteData: begin Result := Result + '\' + FileExt_StockMinute + IntToStr(AParamType) + tmpDataSrcCode + '\'; end; DataType_InstantData: begin Result := Result + '\' + FileExt_StockInstant + tmpDataSrcCode + '\'; end; DataType_ValueData: begin Result := Result + '\' + FileExt_StockSummaryValue + tmpDataSrcCode + '\'; end; else begin if '' <> tmpDataSrcCode then Result := Result + '\' + 's' + tmpDataSrcCode + '\' else Result := Result + '\'; end; end; end; function TStockAppPath.GetDataBasePath(ADBType, ADataType: integer; ADataSrc: integer): WideString; begin Result := GetDataBasePath(ADBType, ADataType, ADataSrc, 0, nil); end; function TStockAppPath.GetDataBasePath(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; var tmpPath: string; begin Result := ''; tmpPath := GetFileRelativePath(ADBType, ADataType, ADataSrc, AParamType, AParam); if '' = tmpPath then exit; if DataType_DetailData = ADataType then begin if '' <> tmpPath then begin if DirectoryExists(tmpPath) then begin if '' = ExtractFileDrive(tmpPath) then begin if PathDelim = tmpPath[1] then begin Result := ExtractFilePath(ParamStr(0)) + tmpPath; end else begin Result := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + tmpPath; end; end else begin Result := tmpPath; end; end else begin Result := GetInstallPath + tmpPath; end; end; end else begin Result := GetInstallPath + tmpPath; end; if '' <> Result then begin Sysutils.ForceDirectories(Result); end; end; function TStockAppPath.GetFilePath(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; begin Result := ''; case ADataType of DataType_DayData: begin Result := GetDataBasePath(ADBType, ADataType, ADataSrc, AParamType, AParam); end; DataType_DetailData: begin if nil = AParam then exit; Result := GetDataBasePath(ADBType, ADataType, ADataSrc, AParamType, AParam); if '' <> Result then begin Result := Result + Copy(PRT_DealItem(AParam).sCode, 1, 4) + '\' + PRT_DealItem(AParam).sCode + '\'; if 0 < AParamType then begin Result := Result + Copy(FormatDateTime('yyyymmdd', AParamType), 1, 4) + '\'; end; end; end; else begin Result := GetDataBasePath(ADBType, ADataType, ADataSrc, AParamType, AParam); end; end; end; function TStockAppPath.GetFileName(ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; begin Result := ''; case ADataType of DataType_Item: begin Result := 'items'; end; DataType_DayData: begin if nil <> AParam then begin Result := PRT_DealItem(AParam).sCode; end; end; DataType_MinuteData: begin Result := PRT_DealItem(AParam).sCode; end; DataType_DetailData: begin Result := PRT_DealItem(AParam).sCode + '_' + FormatDateTime('yyyymmdd', AParamType); end; DataType_Class: begin Result := 'sclass'; end; DataType_Info: begin end; end; if '' <> Result then begin if '' <> AFileExt then begin if Pos('.', AFileExt) > 0 then begin Result := Result + AFileExt; end else begin Result := Result + '.' + AFileExt; end; end else begin Result := Result + '.' + GetFileExt(ADataType, ADataSrc, AParamType, AParam); end; end; //Log(LOGTAG, 'GetFileName:' + Result); end; function TStockAppPath.GetFileExt(ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer): WideString; begin Result := ''; case ADataType of DataType_Item: begin Result := 'dic'; end; DataType_DayData: begin if Integer(weightNone) = AParamType then begin Result := FileExt_StockDay + '_' + IntToStr(ADataSrc); end else begin Result := FileExt_StockDay + IntToStr(AParamType) + '_' + IntToStr(ADataSrc); end; end; DataType_Class: begin Result := 's3'; end; DataType_Info: begin end; DataType_DetailData: begin Result := FileExt_StockDetail + IntToStr(ADataSrc); end; DataType_MinuteData: begin Result := FileExt_StockMinute + inttostr(AParamType) + '_' + IntToStr(ADataSrc); end; DataType_InstantData: begin Result := FileExt_StockInstant + IntToStr(ADataSrc); end; DataType_WeightData: begin Result := FileExt_StockWeight + IntToStr(ADataSrc); end; DataType_ValueData: begin Result := FileExt_StockSummaryValue + IntToStr(ADataSrc); end; end; end; function TStockAppPath.CheckOutFileUrl(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; var tmpFileName: AnsiString; tmpFilePath: AnsiString; begin Result := ''; tmpFilePath := GetFilePath(ADBType, ADataType, ADataSrc, AParamType, AParam); tmpFileName := GetFileName(ADataType, ADataSrc, AParamType, AParam, AFileExt); if ('' <> tmpFilePath) and ('' <> tmpFileName) then begin ForceDirectories(tmpFilePath); Result := tmpFilePath + tmpFileName; end; end; function TStockAppPath.GetFileUrl(ADBType, ADataType: integer; ADataSrc: integer; AParamType: integer; AParam: Pointer; AFileExt: WideString): WideString; var tmpExeName: AnsiString; tmpFileName: AnsiString; tmpFilePath: AnsiString; begin Result := ''; if DataType_Item = ADataType then begin tmpExeName := lowercase(ParamStr(0)); tmpFileName := ''; if 0 < Pos('sh', tmpExeName) then tmpFileName := 'items_sh.dic'; if 0 < Pos('sz', tmpExeName) then tmpFileName := 'items_sz.dic'; if 0 < Pos('zx', tmpExeName) then tmpFileName := 'items_zx.dic'; if 0 < Pos('cy', tmpExeName) then tmpFileName := 'items_cy.dic'; if '' <> tmpFileName then begin tmpFilePath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))); if '' <> tmpFilePath then begin if FileExists(IncludeTrailingPathDelimiter(tmpFilePath) + tmpFileName) then begin Result := IncludeTrailingPathDelimiter(tmpFilePath) + tmpFileName; end; end; if '' = Result then begin tmpFilePath := GetFilePath(ADBType, ADataType, ADataSrc, AParamType, AParam); if '' <> tmpFilePath then begin if FileExists(IncludeTrailingPathDelimiter(tmpFilePath) + tmpFileName) then begin Result := IncludeTrailingPathDelimiter(tmpFilePath) + tmpFileName; end; end; end; end; if '' = Result then begin tmpFileName := ChangeFileExt(ParamStr(0), '.dic'); if FileExists(tmpFileName) then Result := tmpFileName; end; end; if '' = Result then begin tmpFilePath := GetFilePath(ADBType, ADataType, ADataSrc, AParamType, AParam); if ('' <> tmpFilePath) then begin tmpFileName := GetFileName(ADataType, ADataSrc, AParamType, AParam, AFileExt); if ('' <> tmpFileName) then begin Result := tmpFilePath + tmpFileName; end; end; end; end; function TStockAppPath.GetInstallPath: WideString; begin Result := ExtractFilePath(ParamStr(0)); end; end.
{ This example shows how to manipulate with imagse for each cell. Also support sorting by column clicking and way to drawing in a cell The initial developer of this code is Sasa Zeman. Mailto: public@szutils.net or sasaz72@mail.ru Web site: www.szutils.net Created: 7 Jun 2004 Modified: 10 March 2005 This example is distributed "AS IS", WITHOUT WARRANTY OF ANY KIND, either express or implied. You use it at your own risk! Adapted for LCL by Luiz Américo } unit Unit1; {$MODE Delphi} interface uses DelphiCompat, LCLIntf, LCLType, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, VirtualTrees, LResources; type { TForm1 } TForm1 = class(TForm) VST1: TVirtualStringTree; ImageList1: TImageList; ImageList2: TImageList; procedure FormCreate(Sender: TObject); procedure VST1BeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); procedure VST1HeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo); procedure VST1InitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); procedure VST1GetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); procedure VST1GetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); procedure VST1Checking(Sender: TBaseVirtualTree; Node: PVirtualNode; var NewState: TCheckState; var Allowed: Boolean); procedure VST1CompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); private { Private declarations } public { Public declarations } end; PMyRec = ^TMyRec; TMyRec = record Main: String; One, Two: integer; Percent : integer; Index: Integer; end; var Form1: TForm1; implementation uses Math; procedure TForm1.FormCreate(Sender: TObject); begin // Link images in ImageList2 to VST1.StateImages if it // not set already in Oject Inspector // It is important to link to VST1.StateImages // since we need to use images to all cells // (in all columns, not only for main column) // Otherwise it will not work properly with VST1.Images // VST1.StateImages:= ImageList2; // Set data size of data record used for each tree VST1.NodeDataSize := SizeOf(TMyRec); // Number of initial nodes VST1.RootNodeCount := 20; // Set XP syle for CheckImage VST1.CheckImageKind:=ckXP; //Start random number generator Randomize end; procedure TForm1.VST1BeforeCellPaint(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect; var ContentRect: TRect); var I, PercentageSize, RndPercent: integer; ColorStart: Word; Data: PMyRec; R,G,B: byte; begin if (Column = 3) then begin Data := Sender.GetNodeData(Node); RndPercent:=Data.Percent; InflateRect(CellRect, -1, -1); DrawEdge(TargetCanvas.Handle, CellRect, EDGE_SUNKEN, BF_ADJUST or BF_RECT); PercentageSize := (CellRect.Right - CellRect.Left) * RndPercent div 100; if True then //Multi color approach begin ColorStart :=clYellow; R:= GetRValue(ColorStart); G:= GetGValue(ColorStart); B:= GetBValue(ColorStart); for I := CellRect.Right downto CellRect.Left do begin TargetCanvas.Brush.Color := RGB(R,G,B); if CellRect.Right - CellRect.Left <= PercentageSize then TargetCanvas.FillRect(CellRect); Dec(CellRect.Right); Dec(G); end; end else //One color approach begin CellRect.Right := CellRect.Left + PercentageSize; if RndPercent = 100 then TargetCanvas.Brush.Color := clRed else TargetCanvas.Brush.Color := clLime; TargetCanvas.FillRect(CellRect); end; end; end; procedure TForm1.VST1HeaderClick(Sender: TVTHeader; HitInfo: TVTHeaderHitInfo); begin // Determinate sorting direction if HitInfo.Button=mbLeft then with Sender do begin if SortColumn <> HitInfo.Column then SortColumn := HitInfo.Column else begin if SortDirection = sdAscending then SortDirection := sdDescending else SortDirection := sdAscending end; // Initiate sorting VST1.SortTree(HitInfo.Column, Sender.SortDirection, False); end; end; procedure TForm1.VST1InitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); var Data: PMyRec; s: string; begin Data:=Sender.GetNodeData(Node); // Data nitialization during node initialization s:= Format('Level %3d, Index %3d', [Sender.GetNodeLevel(Node), Node.Index]); Data.Main:='Main ' + s; Data.One := Random(ImageList2.Count); Data.Two := Random(ImageList2.Count); Data.Percent := Random (101); //fpc does not has RandomRange //Data.Percent := RandomRange(0,100); Data.Index:= Node.Index; // Following code can be coded much efficiantly, // but than again it works for now // and determinate CheckType for each node if Data.Index>=0 then // Set RadioButton Node.CheckType := ctRadioButton; if Data.Index>=4 then // Set CheckBox Node.CheckType:= ctCheckBox; if Data.Index>=8 then // Set Button Node.CheckType:= ctButton; if Data.Index>=12 then // Set ctTriStateCheckBox Node.CheckType:= ctTriStateCheckBox; if Data.Index>=16 then // Set nothing Node.CheckType:= ctNone; end; procedure TForm1.VST1GetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); var Data: PMyRec; begin Data:=Sender.GetNodeData(Node); case column of 0: CellText:=Data.Main; 1: CellText:=IntToStr(Data.One); 2: CellText:=IntToStr(Data.Two); 3: CellText:=IntToStr(Data.Percent)+'%'; end end; procedure TForm1.VST1GetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer); var Data: PMyRec; begin Data := Sender.GetNodeData(Node); { Kind:=ikNormal; ikNormal, ikSelected, ikState, ikOverlay } // Conditional image index setting for each cell (node and column) case Column of 0: if Data.Index<12 then ImageIndex:=3 else ImageIndex:=25; 1: ImageIndex:=Data.One; 2: ImageIndex:=Data.Two; end; end; procedure TForm1.VST1Checking(Sender: TBaseVirtualTree; Node: PVirtualNode; var NewState: TCheckState; var Allowed: Boolean); var Data: PMyRec; s: string; begin Data := Sender.GetNodeData(Node); // Determinate which CheckType is pressed // Instead of this, here can be some real action case Node.CheckType of ctTriStateCheckBox: s:='TriStateCheckBox'; ctCheckBox : s:='CheckBox'; ctRadioButton : s:='RadioButton'; ctButton : s:='Button'; end; caption:=s+' '+Data.Main; Allowed:=true end; procedure TForm1.VST1CompareNodes(Sender: TBaseVirtualTree; Node1, Node2: PVirtualNode; Column: TColumnIndex; var Result: Integer); var Data1, Data2: PMyRec; begin Data1:=Sender.GetNodeData(Node1); Data2:=Sender.GetNodeData(Node2); // Depending on column in VST1.SortTree(...) // returns comparing result to internal sorting procedure Result:=0; case column of 0: Result:=CompareStr(Data1.Main,Data2.Main); 1: begin Result:=CompareValue(Data1.One,Data2.One); // If numbers are equal, compare value from next column // On this way we product more complex sorting if Result=0 then Result:=CompareValue(Data1.Two,Data2.Two); end; 2: Result:=CompareValue(Data1.Two,Data2.Two); 3: Result:=CompareValue(Data1.Percent,Data2.Percent); end end; initialization {$i Unit1.lrs} end.
unit RecorderDemoMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Actions, FMX.ActnList, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Media; const AUDIO_FILENAME = 'test.mp3'; // 录音保存的文件名 type TRecorderdDemoForm = class(TForm) ActionList1: TActionList; acStartRecording: TAction; acStopRecording: TAction; acPlay: TAction; acStop: TAction; MediaPlayer1: TMediaPlayer; Button2: TButton; Button3: TButton; Button4: TButton; Button5: TButton; Label1: TLabel; Label2: TLabel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean); procedure Button5Click(Sender: TObject); procedure acStopExecute(Sender: TObject); procedure acStartRecordingExecute(Sender: TObject); procedure acPlayExecute(Sender: TObject); private { Private declarations } public { Public declarations } FMicrophone: TAudioCaptureDevice; function HasMicrophone: Boolean; function IsMicrophoneRecording: Boolean; end; var RecorderdDemoForm: TRecorderdDemoForm; implementation uses System.IOUtils; // 需要引入 {$R *.fmx} // 得到不同平台的录音文件保存路径 function GetAudioFileName(const AFileName: string): string; begin {$IFDEF ANDROID} Result := TPath.GetTempPath + '/' + AFileName; {$ELSE} {$IFDEF IOS} Result := TPath.GetHomePath + '/Documents/' + AFileName; {$ELSE} Result := AFileName; {$ENDIF} {$ENDIF} end; procedure TRecorderdDemoForm.acPlayExecute(Sender: TObject); begin if IsMicrophoneRecording then // 如果在录音,则先停止录音 acStopRecording.Execute; // 以下播放录音文件 AUDIO_FILENAME MediaPlayer1.FileName := GetAudioFileName(AUDIO_FILENAME); MediaPlayer1.Play; end; procedure TRecorderdDemoForm.acStartRecordingExecute(Sender: TObject); begin acStop.Execute; // 选择停止录音 if HasMicrophone then begin // 准备将录音保存到文件 'test.mp3' FMicrophone.FileName := GetAudioFileName(AUDIO_FILENAME); try FMicrophone.StartCapture; // 开始录音 except ShowMessage('该设备不支持录音操作。'); end; end else ShowMessage('没有麦克风设备。'); end; procedure TRecorderdDemoForm.acStopExecute(Sender: TObject); begin MediaPlayer1.Stop; end; procedure TRecorderdDemoForm.ActionList1Update(Action: TBasicAction; var Handled: Boolean); begin // 判断图片的可见性 case (HasMicrophone and (FMicrophone.State = TCaptureDeviceState.Capturing)) of True: Label2.Text := '录音'; False: Label2.Text := '停止录音'; end; // 判断 4 个按钮的是否可按下 acStartRecording.Enabled := not IsMicrophoneRecording and HasMicrophone; acStopRecording.Enabled := IsMicrophoneRecording; acStop.Enabled := Assigned(MediaPlayer1.Media) and (MediaPlayer1.State = TMediaState.Playing); acPlay.Enabled := FileExists(GetAudioFileName(AUDIO_FILENAME)) and (MediaPlayer1.State <> TMediaState.Playing); end; procedure TRecorderdDemoForm.Button1Click(Sender: TObject); begin acStop.Execute; // 选择停止录音 if HasMicrophone then begin // 准备将录音保存到文件 'test.mp3' FMicrophone.FileName := GetAudioFileName(AUDIO_FILENAME); try FMicrophone.StartCapture; // 开始录音 except ShowMessage('该设备不支持录音操作。'); end; end else ShowMessage('没有麦克风设备。'); end; procedure TRecorderdDemoForm.Button5Click(Sender: TObject); begin if IsMicrophoneRecording then // 如果正在录音 try FMicrophone.StopCapture; { 停止录音 } except ShowMessage('该设备不支持停止录音操作。'); end; end; // 判断是否有麦克风 procedure TRecorderdDemoForm.FormCreate(Sender: TObject); begin // 初始化录音设备 FMicrophone := TCaptureDeviceManager.Current.DefaultAudioCaptureDevice; end; function TRecorderdDemoForm.HasMicrophone: Boolean; begin Result := Assigned(FMicrophone); end; // 判断是否在录音 function TRecorderdDemoForm.IsMicrophoneRecording: Boolean; begin Result := HasMicrophone and (FMicrophone.State = TCaptureDeviceState.Capturing); end; end.
unit uRumours; interface function RumBegin(): string; function RumEnd(): string; function RaceName(ARaceID, AGender: Integer): string; function NewLevel(AName: string; ARaceID, AGender, ALevel: Integer): string; function NewPC(AName: string; ARaceID, AGender: Integer): string; function Death(AName: string; ARaceID, AGender: Integer; ALoc: string): string; implementation uses Classes, SysUtils, uUtils; function RumBegin(): string; var S: TStringList; begin S := TStringList.Create; try S.DelimitedText := '"До вас дошли слухи, что", "Вам стало известно, что",' + '"Ходят слухи, что", "Некто рассказывал, что", "В таверне рассказывают, что",' + '"Слухами мир полнится", "Говорят, что", "Стало известно, что",' + '"В таверне бурно обсуждают", "За соседними столами обсуждают", "Длинные языки говорят, что"'; Result := S[Random(S.Count - 1)] + '...'; finally S.Free; end; end; function RumEnd(): string; var S: TStringList; begin S := TStringList.Create; try S.DelimitedText := '"но кто верит слухам?..", "слухам нельзя верить!..",' + '"да вранье все это!..", "и это правда?..", "вранье это все и не правда!..",' + '"ложь, ложь и снова ложь!..", "да кому нужна такая правда?..", "а вдруг все так и было?..",' + '"с трудом вериться...", "тьма окутывает землю...", "каждый скажет, что это все ложь!.."'; Result := '...' + S[Random(S.Count - 1)]; finally S.Free; end; end; function RaceName(ARaceID, AGender: Integer): string; begin // Названия рас case ARaceID of 1: Result := 'карлик'; 2: Result := 'гном'; 3: if (AGender = 0) then Result := 'орчиха' else Result := 'орк'; 4: if (AGender = 0) then Result := 'лесная эльфийка' else Result := 'лесной эльф'; 5: Result := 'ящер'; 6: Result := 'морлок'; 7: if (AGender = 0) then Result := 'темная эльфийка' else Result := 'темный эльф'; else Result := ''; end; // Прозвища if (Rand(1, 6) = 1) and (ARaceID = 5) then if (AGender = 0) then Result := 'ящерица' else Result := 'драконид'; if (Rand(1, 3) = 1) and (ARaceID in [4, 7]) then if (AGender = 0) then Result := 'эльфийка' else Result := 'эльф'; if (Rand(1, 5) = 1) and (ARaceID = 3) then if (AGender = 0) then Result := 'зеленокожая' else Result := 'зеленокожий'; if (Rand(1, 4) = 1) and (ARaceID = 1) then if (AGender = 0) then Result := 'карла' else if (Rand(1, 2) = 1) then Result := 'малорослик' else Result := 'карл'; if (Rand(1, 3) = 1) and (ARaceID = 6) then if (AGender = 0) then Result := 'морла' else if (Rand(1, 2) = 1) then Result := 'тритон' else Result := 'рыбоящер'; end; function NewLevel(AName: string; ARaceID, AGender, ALevel: Integer): string; var G, H, K: string; begin if (AGender = 0) then begin G := 'ась'; K := 'а'; end else begin G := 'ся'; K := ''; end; if (Rand(1, 2) = 2) then Inc(ALevel, Rand(1, 2)); if (Rand(1, 2) = 1) then H := AnsiLowerCase(RaceName(ARaceID, AGender)) + #32 + AName else H := AName; case Rand(1, 5) of 1: Result := '...' + Trim(Format('%s поднял%s на %d-й уровень.', [H, G, ALevel])); 2: Result := '...' + Trim(Format('%s повысил%s свой уровень.', [H, K])); 3: Result := '...' + Trim(Format('%s теперь на %d-м уровне.', [H, ALevel])); 4: Result := '...' + Trim(Format('%s добил%s успехов, теперь он%s на %d-м уровне.', [H, G, K, ALevel])); else Result := '...' + Trim(Format('%s получил%s новый уровень.', [H, K]));; end; end; function NewPC(AName: string; ARaceID, AGender: Integer): string; var G, L, D, P, H: string; begin if (AGender = 0) then begin G := 'a'; case Rand(1, 3) of 1: L := ''; 2: L := 'новая героиня'; else L := 'героиня'; end; end else begin G := ''; case Rand(1, 5) of 1: L := ''; 2: L := 'путник'; 3: L := 'новый путник'; 4: L := 'новый герой'; else L := 'герой'; end; end; case Rand(1, 4) of 1: if (AGender = 0) then D := 'спустилась' else D := 'спустился'; 2: if (AGender = 0) then D := 'пришла' else D := 'пришел'; 3: if (AGender = 0) then D := 'нашла дорогу' else D := 'нашел дорогу'; else D := 'прибыл' + G; end; case Rand(1, 9) of 1: P := 'Атар'; 2: P := 'Эль-Атром'; 3: P := 'нашу деревню'; 4: P := 'деревню'; 5: P := 'это селение'; 6: P := 'эту дыру'; 7: P := 'эту помойную яму'; 8: P := 'этот муравейник'; else P := 'Дром'; end; if (Rand(1, 2) = 1) then H := AnsiLowerCase(RaceName(ARaceID, AGender)) + #32 + AName else H := AName; Result := '...' + Trim(Format('%s %s %s в %s!', [L, H, D, P])); end; function Death(AName: string; ARaceID, AGender: Integer; ALoc: string): string; var G, V, H, F, P, Z, U: string; begin if (AGender = 0) then F := 'a' else F := ''; if (AGender = 0) then P := 'лa' else P := ''; case Rand(1, 3) of 1: Z := 'врагами'; 2: Z := 'гнусными тварями'; else Z := ''; end; case Rand(1, 2) of 1: case Rand(1, 3) of 1: G := 'погиб' + P; 2: G := 'умер' + P; else G := 'повержен' + F + ' ' + Z; end; else if (AGender = 0) then G := 'нашла свою смерть' else G := 'нашел свою смерть'; end; case Rand(1, 2) of 1: V := 'гроте'; else V := 'пещере'; end; if (Rand(1, 2) = 1) then H := RaceName(ARaceID, AGender) + #32 + AName else H := AName; if (Rand(1, 3) = 1) then H := 'некто ' + AName; case Rand(1, 2) of 1: U := 'в глубокой пещере нашли растерзанное тело.'; 2: U := 'в дальних пещерах снова нашли тело.'; end; case Rand(1, 6) of 1: Result := '...' + Trim(Format('%s %s в %s #%s...', [Trim(H), Trim(G), V, ALoc])); 2: Result := '...в одной из дальних пещер ' + Trim(H) + ' ' + Trim(G) + '...'; 3: Result := '...' + U + ' Кто-то предположил, что это был' + F + ' ' + Trim(H) + '...'; 4: Result := '...' + U + ' Возможно это был' + F + ' ' + Trim(H) + '...'; 5: Result := '...' + U + ' Многие говорят, что это был' + F + ' ' + Trim(H) + '...'; 6: Result := '...' + U + ' Говорят, это' + F + ' ' + Trim(H) + '...'; end; end; end.
unit CardHash; interface uses JunoApi4Delphi.Interfaces; type TCardHash = class(TInterfacedObject, iCardHash) private FCardHash : String; public constructor Create; destructor Destroy; override; class function New : iCardHash; function CardNumber(Value : String) : iCardHash; function holderName(Value : String) : iCardHash; function securityCode(Value : String) : iCardHash; function expirationMonth(Value : String) : iCardHash; function expirationYear(Value : String) : iCardHash; function cardHash : String; end; implementation { TCardHash } function TCardHash.cardHash: String; begin Result := FCardHash; end; function TCardHash.CardNumber(Value: String): iCardHash; begin Result := Self; end; constructor TCardHash.Create; begin end; destructor TCardHash.Destroy; begin inherited; end; function TCardHash.expirationMonth(Value: String): iCardHash; begin end; function TCardHash.expirationYear(Value: String): iCardHash; begin Result := Self; end; function TCardHash.holderName(Value: String): iCardHash; begin Result := Self; end; class function TCardHash.New: iCardHash; begin Result := Self.Create; end; function TCardHash.securityCode(Value: String): iCardHash; begin Result := Self; end; end.
unit LIB.Raytrace.Material; interface //#################################################################### ■ uses LUX, LUX.D3, LUX.Matrix.L4, LUX.Color, LUX.Raytrace, LUX.Raytrace.Material, LIB.Raytrace; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMyMaterial TMyMaterial = class( TRayMaterial ) private protected _DiffRatio :TSingleRGB; public constructor Create; ///// プロパティ property DiffRatio :TSingleRGB read _DiffRatio write _DiffRatio; ///// メソッド function Scatter( const WorldRay_:TRayRay; const WorldHit_:TRayHit ) :TSingleRGB; override; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TMyMaterial //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TMyMaterial.Create; begin inherited; _DiffRatio := TSingleRGB.Create( 1, 1, 1 ); end; /////////////////////////////////////////////////////////////////////// メソッド function TMyMaterial.Scatter( const WorldRay_:TRayRay; const WorldHit_:TRayHit ) :TSingleRGB; var I :Integer; L :TRayLight; A :TRayRay; H :TRayHit; D :Single; begin Result := TSingleRGB.Create( 0, 0, 0 ); for I := 0 to World.LightsN-1 do begin L := World.Lights[ I ]; with A do begin Emt := @WorldHit_; Ord := WorldRay_.Ord + 1; Ray.Pos := WorldHit_.Pos; //Ray.Vec //Len Hit := @H; end; with H do begin Ray := @A; Obj := nil; //Nor //Tan //Bin //Tex end; if L.RayJoins( A, H ) then begin D := DotProduct( WorldHit_.Nor, A.Ray.Vec ); if D < 0 then D := 0; Result := Result + D * L.Color * _DiffRatio; end; end; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit AsxCriticalSections; interface uses Windows, SyncObjs; type TAsymetrixCriticalSection = class public constructor Create; destructor Destroy; override; public function BeginRead ( timeout : dword ) : TWaitResult; function BeginWrite( timeout : dword ) : TWaitResult; procedure EndRead; procedure EndWrite; private fCanRead : TEvent; fCanWrite : TEvent; fInnerLocking : TCriticalSection; fInnerUnlocking : TCriticalSection; fReadCount : integer; fWriteCount : integer; private procedure LockWrite; procedure LockRead; procedure UnlockWrite; procedure UnlockRead; end; implementation uses SysUtils, Logs; // TAsymetrixCriticalSection constructor TAsymetrixCriticalSection.Create; begin inherited Create; fCanRead := TEvent.Create( nil, true, true, '' ); fCanWrite := TEvent.Create( nil, true, true, '' ); fInnerLocking := TCriticalSection.Create; fInnerUnlocking := TCriticalSection.Create; end; destructor TAsymetrixCriticalSection.Destroy; begin try Logs.Log( 'Demolition', TimeToStr(Now) + ' - ' + ClassName ); except end; fCanRead.Free; fCanWrite.Free; fInnerLocking.Free; fInnerUnlocking.Free; inherited; end; function TAsymetrixCriticalSection.BeginRead( timeout : dword ) : TWaitResult; begin fInnerLocking.Enter; result := fCanRead.WaitFor( timeout ); LockWrite; fInnerLocking.Leave; end; function TAsymetrixCriticalSection.BeginWrite( timeout : dword ) : TWaitResult; begin fInnerLocking.Enter; result := fCanRead.WaitFor( timeout ); if result = wrSignaled then result := fCanWrite.WaitFor( timeout ); LockWrite; LockRead; fInnerLocking.Leave; end; procedure TAsymetrixCriticalSection.EndRead; begin fInnerUnlocking.Enter; UnlockWrite; fInnerUnlocking.Leave; end; procedure TAsymetrixCriticalSection.EndWrite; begin fInnerUnlocking.Enter; UnlockWrite; UnlockRead; fInnerUnlocking.Leave; end; procedure TAsymetrixCriticalSection.LockWrite; begin if fWriteCount = 0 then fCanWrite.ResetEvent; inc( fWriteCount ); end; procedure TAsymetrixCriticalSection.LockRead; begin if fReadCount = 0 then fCanRead.ResetEvent; inc( fReadCount ); end; procedure TAsymetrixCriticalSection.UnlockWrite; begin dec( fWriteCount ); if fWriteCount = 0 then fCanWrite.SetEvent; end; procedure TAsymetrixCriticalSection.UnlockRead; begin dec( fReadCount ); if fReadCount = 0 then fCanRead.SetEvent; end; end.
unit EvaluatedBlock; interface uses ClassStorageInt, Protocol, Kernel, WorkCenterBlock, Surfaces, OutputEvaluators, Accounts, BackupInterfaces, Inventions, Languages; const msgBlockOverloaded = 10000; msgBlockOperationRatio = 10001; const tidIndustriesInvention = 'Industries'; type TBlockOverloadedMsg = record Cmd : word; Gate : TMetaGate; Perc : TPercent; Result : boolean; end; TMetaEvaluatedBlock = class(TMetaWorkCenter) public constructor Create(anId : string; aCapacities : array of TFluidValue; aSupplyAccount : TAccountId; aProdAccount : TAccountId; aSalaryAccount : TAccountId; aMantainanceAccount : TAccountId; aBlockClass : CBlock); destructor Destroy; override; private fMantainanceAccount : TAccountId; fMetaEvaluatorPool : TMetaEvaluatorPool; fDesignProfPerc : TPercent; fNetProfit : TMoney; fCargoKind : TCargoKind; fWeatherEnvelope : integer; fLimitWeatherCond : single; private function GetNetProfit : TMoney; function GetOperationCost : TMoney; protected property MetaEvaluatorPool : TMetaEvaluatorPool read fMetaEvaluatorPool; property DesignProfPerc : TPercent read fDesignProfPerc write fDesignProfPerc; property NetProfit : TMoney read GetNetProfit; property OperationCost : TMoney read GetOperationCost; property WeatherEnvelope : integer read fWeatherEnvelope write fWeatherEnvelope; property LimitWeatherCond : single read fLimitWeatherCond write fLimitWeatherCond; private function GetDesignEffic : single; procedure SetDesignEffic(value : single); function GetDesignK : TPercent; procedure SetDesignK (value : TPercent); public property MantainanceAccount : TAccountId read fMantainanceAccount; property CargoKind : TCargoKind read fCargoKind write fCargoKind; property DesignEffic : single read GetDesignEffic write SetDesignEffic; property DesignK : TPercent read GetDesignK write SetDesignK; public procedure Register( ClassFamily : TClassFamilyId ); procedure EvaluateTexts; override; end; TEvaluatedBlock = class(TFinanciatedWorkCenter) protected constructor Create(aMetaBlock : TMetaBlock; aFacility : TFacility); override; public destructor Destroy; override; protected function Evaluate : TEvaluationResult; override; public procedure AutoConnect( loaded : boolean ); override; private fEvaluatorPool : TEvaluatorPool; fBeautyModifier : TSurfaceModifier; protected function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; public procedure LoadFromBackup(Reader : IBackupReader); override; procedure StoreToBackup (Writer : IBackupWriter); override; procedure Stop; override; procedure CopySettingsFrom(Block : TBlock; Options : integer); override; function RenderCloneMenu(lang : string) : string; override; private procedure msgOverloaded(var Msg : TBlockOverloadedMsg); message msgBlockOverloaded; procedure msgGetOperationRatio(var Msg : TBlockOverloadedMsg); message msgBlockOperationRatio; protected function Producing : boolean; function GetVisualClassId : TVisualClassId; override; public property EvaluatorPool : TEvaluatorPool read fEvaluatorPool; property BeautyModifier : TSurfaceModifier read fBeautyModifier; public procedure GetInventionsEffect(var QEffect : TInventionEfficiencyEffect; var KEffect : integer; DsgnK : TPercent); function GetWeatherConditions : single; function AdverseWeatherConditions : boolean; protected procedure Deleted; override; protected procedure RecalculateInventionsEffect; override; end; TIndustryInvention = class(TWorkCenterInvention) public constructor Load(xmlObj : OleVariant); override; private fEffic : integer; fQuality : integer; public property Effic : integer read fEffic; property Quality : integer read fQuality; public function GetClientProps(Company : TObject; LangId : TLanguageId) : string; override; end; procedure RegisterInventionClass; implementation uses StdFluids, ClassStorage, PyramidalModifier, Classes, SysUtils, SimHints, MathUtils, Collection, MetaInstances, Logs, CloneOptions; // TMetaEvaluatedBlock constructor TMetaEvaluatedBlock.Create(anId : string; aCapacities : array of TFluidValue; aSupplyAccount : TAccountId; aProdAccount : TAccountId; aSalaryAccount : TAccountId; aMantainanceAccount : TAccountId; aBlockClass : CBlock); begin inherited Create(anId, aCapacities, aSupplyAccount, aProdAccount, aSalaryAccount, aBlockClass); fMetaEvaluatorPool := TMetaEvaluatorPool.Create; fMantainanceAccount := aMantainanceAccount; fDesignProfPerc := 45; // If operation ratio is over this % and having Input, Effic, Price = 100% it produces incomes > 0 HasPeopleCargo := true; CargoKind := carLight; MinCompSup := 0.75; fWeatherEnvelope := noIndex; fLimitWeatherCond := 0; MaxUpgrade := 100; end; destructor TMetaEvaluatedBlock.Destroy; begin fMetaEvaluatorPool.Free; inherited; end; function TMetaEvaluatedBlock.GetNetProfit : TMoney; function GetInputCost : TMoney; var i : integer; MetaInput : TMetaInput; begin result := 0; for i := 0 to pred(MetaInputs.Count) do begin MetaInput := TMetaInput(MetaInputs[i]); if not (mfWorkForce in MetaInput.MetaFluid.Options) then result := result + MetaInput.MetaFluid.MarketPrice*MetaInput.MaxFluid.Q; end; end; var nPrf : TMoney; iPrf : TMoney; wPrf : TMoney; begin if fNetProfit = 0 then begin nPrf := fMetaEvaluatorPool.NetProfit; iPrf := GetInputCost; wPrf := WorkForceCost; fNetProfit := nPrf - iPrf - wPrf; end; result := fNetProfit; end; function TMetaEvaluatedBlock.GetOperationCost : TMoney; begin result := (fDesignProfPerc/100)*NetProfit; end; function TMetaEvaluatedBlock.GetDesignEffic : single; begin result := MetaEvaluatorPool[0].DesignEffic; end; procedure TMetaEvaluatedBlock.SetDesignEffic(value : single); var i : integer; begin for i := 0 to pred(MetaEvaluatorPool.EvaluatorCount) do MetaEvaluatorPool[i].DesignEffic := value; end; function TMetaEvaluatedBlock.GetDesignK : TPercent; begin result := MetaEvaluatorPool[0].DesignMaxK; end; procedure TMetaEvaluatedBlock.SetDesignK(value : TPercent); var i : integer; begin for i := 0 to pred(MetaEvaluatorPool.EvaluatorCount) do MetaEvaluatorPool[i].DesignMaxK := value; end; procedure TMetaEvaluatedBlock.Register( ClassFamily : TClassFamilyId ); begin MetaEvaluatorPool.EnlargeInputs(EnlargeFactor); inherited Register( ClassFamily ); end; procedure TMetaEvaluatedBlock.EvaluateTexts; var i, j, k : integer; Outp : string; Inp : string; Inputs : TStringList; lang : string; Desc : string; begin for k := 0 to pred(LangList.Count) do begin lang := LangList[k]; Outp := SimHints.GetHintText( mtidDescFactoryHead.Values[lang], [0] ) + ' '; Inputs := TStringList.Create; Desc := ''; for i := 0 to pred(MetaEvaluatorPool.EvaluatorCount) do with MetaEvaluatorPool.MetaEvaluators[i] do begin Outp := Outp + SimHints.GetHintText( mtidDescFactoryHeadN.Values[lang], [MetaOutput.MetaFluid.FormatValue( MetaOutput.MaxFluid.Q, lang ), lowercase(MetaOutput.MetaFluid.Name_MLS.Values[lang])] ); if i < pred(MetaEvaluatorPool.EvaluatorCount) then Outp := Outp + ', '; for j := 0 to pred(InputInfoList.Count) do with TMetaInputInfo(InputInfoList[j]) do if (pos( MetaInput.MetaFluid.Name_MLS.Values[lang], Inp ) = 0) and (InputKind = ikBasic) then Inputs.Add( SimHints.GetHintText( mtidDescFactoryReqN.Values[lang], [lowercase(MetaInput.MetaFluid.Name_MLS.Values[lang])] )); end; if Desc <> '' then Desc := Desc + ' '; if Inputs.Count > 0 then begin Inp := SimHints.GetHintText( mtidDescFactoryReq.Values[lang], [0] ) + ' '; for i := 0 to pred(Inputs.Count) do begin Inp := Inp + Inputs[i]; if i < Inputs.Count - 1 then if i < Inputs.Count - 2 then Inp := Inp + ', ' else Inp := Inp + ' ' + mtidAND.Values[lang] + ' '; // >> MLS2 end; Desc := Outp + '. ' + Inp + '.' end else Desc := Outp + '.'; Inputs.Free; if Desc_MLS.Values[lang] <> '' then Desc_MLS.Values[lang] := Desc_MLS.Values[lang] + ' '; Desc_MLS.Values[lang] := Desc_MLS.Values[lang] + Desc; end; end; // TEvaluatedBlock constructor TEvaluatedBlock.Create(aMetaBlock : TMetaBlock; aFacility : TFacility); begin inherited; fEvaluatorPool := TMetaEvaluatedBlock(aMetaBlock).fMetaEvaluatorPool.Instantiate(self); end; destructor TEvaluatedBlock.Destroy; begin fEvaluatorPool.Free; fBeautyModifier.Delete; inherited; end; function TEvaluatedBlock.Evaluate : TEvaluationResult; var WFEffic : single; DsgnProf : TPercent; OprRatio : TPercent; DsgnCost : TMoney; WthrCond : single; begin result := inherited Evaluate; if not Facility.CriticalTrouble then try // Workforce Effic if Facility.Trouble and facNeedsWorkForce <> 0 then WFEffic := 0 else WFEffic := WorkForceEfficiency; // Weather conditions WthrCond := GetWeatherConditions; // Evaluate result := fEvaluatorPool.Evaluate(WFEffic, WthrCond <= TMetaEvaluatedBlock(MetaBlock).LimitWeatherCond); // Charge variable cost OprRatio := fEvaluatorPool.OperationRatio; if OprRatio > 0 then begin DsgnProf := TMetaEvaluatedBlock(MetaBlock).fDesignProfPerc; DsgnCost := realmax(0, TMetaEvaluatedBlock(MetaBlock).OperationCost); if OprRatio < DsgnProf then BlockGenMoney(-DsgnCost*dt, TMetaEvaluatedBlock(MetaBlock).MantainanceAccount) else BlockGenMoney(-DsgnCost*dt*(100 - OprRatio)/(100 - DsgnProf), TMetaEvaluatedBlock(MetaBlock).MantainanceAccount); end; // Hire Workforce if WthrCond <= TMetaEvaluatedBlock(MetaBlock).LimitWeatherCond then HireWorkForce(0) else HireWorkForce(1); // Set cargo values SetCargoValue( TMetaEvaluatedBlock(MetaBlock).CargoKind, OprRatio/10 ); // Inc the complex facilities if Facility.CompanyDir <> nil then Facility.CompanyDir.ComplexFacs := Facility.CompanyDir.ComplexFacs + 1; except result := evrError; end else SetCargoValue( TMetaEvaluatedBlock(MetaBlock).CargoKind, 0 ); end; procedure TEvaluatedBlock.AutoConnect( loaded : boolean ); begin inherited; fBeautyModifier := TPyramidalModifier.Create( tidEnvironment_Beauty, Point(xOrigin, yOrigin), MetaBlock.Beauty, MetaBlock.BeautyStrength ); end; function TEvaluatedBlock.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; var OutputAbstract : string; k : TPeopleKind; i : integer; begin result := inherited GetStatusText( kind, ToTycoon ); case kind of sttMain : begin if not Facility.CriticalTrouble then if not AdverseWeatherConditions then if Facility.Trouble and facNeedsWorkForce = 0 then begin OutputAbstract := ''; for i := 0 to pred(fEvaluatorPool.EvaluatorCount) do begin OutputAbstract := OutputAbstract + fEvaluatorPool.Evaluators[i].FormatOutput(Self, kind, fEvaluatorPool.EvaluatorCount > 1, ToTycoon); if i < pred(fEvaluatorPool.EvaluatorCount) then OutputAbstract := OutputAbstract + LineBreak; end; result := result + OutputAbstract; end else result := result + SimHints.GetHintText( mtidHiringWorkForce.Values[ToTycoon.Language], [round(100*WorkForceEfficiency)] ); //'Hiring workforce at ' + IntToStr(round(100*WorkForceEfficiency)) + '%.'; end; sttSecondary : begin if not Facility.CriticalTrouble // (Facility.Trouble = facNoTrouble) or (Facility.Trouble = facInsuficientInput) then if AdverseWeatherConditions then result := SimHints.GetHintText( mtidStoppedDueWeather.Values[ToTycoon.Language], [0] )//'Stopped because of weather conditions.' else if Facility.Trouble and facNeedsWorkForce = 0 then begin OutputAbstract := fEvaluatorPool.GetSecondaryTextHeader(ToTycoon.Language); for i := 0 to pred(fEvaluatorPool.EvaluatorCount) do begin OutputAbstract := OutputAbstract + fEvaluatorPool.Evaluators[i].FormatOutput(Self, kind, true, ToTycoon) + '. '; end; result := result + OutputAbstract; end else if not AdverseWeatherConditions then with TMetaWorkCenter(MetaBlock) do for k := low(k) to high(k) do if Capacity[k] > 0 then begin if WorkersMax[k].Q > 0 then begin result := result + SimHints.GetHintText( mtidHiringWorkForceSec.Values[ToTycoon.Language], [ mtidWorkforceKindName[k].Values[ToTycoon.Language], round(Workers[k].Q), round(WorkersMax[k].Q) ] ); end; end; result := Format(mtidUpgradeLevel.Values[ToTycoon.Language], [UpgradeLevel]) + ' ' + result; end; sttHint : if not Facility.CriticalTrouble then case Facility.AccessLevelOf( ToTycoon ) of acsFull, acsModerate : begin if not Facility.HasTechnology then result := GetHintText(mtidEvalBlockNeedTechnology.Values[ToTycoon.Language], [Facility.MetaFacility.Technology.Name]) else if AdverseWeatherConditions then result := GetHintText(mtidEvalBlockBadWeatherCond.Values[ToTycoon.Language], [0]) else if Facility.Trouble and facNeedCompSupport <> 0 then result := GetHintText(mtidNeedsCompSupport.Values[ToTycoon.Language], [0]) else if Facility.Trouble and facNeedsWorkForce <> 0 then result := GetHintText(mtidBlockNeedsWorkForce.Values[ToTycoon.Language], [mtidPeopleKindName[WFRequired].Values[ToTycoon.Language]]) else result := fEvaluatorPool.GetHint(ToTycoon); end; end; end; end; procedure TEvaluatedBlock.LoadFromBackup(Reader : IBackupReader); begin inherited; fEvaluatorPool := TMetaEvaluatedBlock(MetaBlock).fMetaEvaluatorPool.Instantiate(self); fEvaluatorPool.LoadFromBackup(Reader); end; procedure TEvaluatedBlock.StoreToBackup(Writer : IBackupWriter); begin inherited; fEvaluatorPool.StoreToBackup(Writer); end; procedure TEvaluatedBlock.Stop; var i : integer; begin inherited; for i := 0 to pred(fEvaluatorPool.EvaluatorCount) do with fEvaluatorPool.Evaluators[i] do begin BiasRatio := 0; SupplyRatio := 0; DonotProduce(Self); end; end; procedure TEvaluatedBlock.CopySettingsFrom(Block : TBlock; Options : integer); var i : integer; inpIdx : integer; begin inherited; if ObjectIs(ClassName, Block) then try if (Block.Facility.MetaFacility.FacId = Facility.MetaFacility.FacId) and (Options and cloneOption_OutputPrices <> 0) then for i := 0 to pred(EvaluatorPool.EvaluatorCount) do begin inpIdx := EvaluatorPool.Evaluators[i].MetaEvaluator.MetaOutput.Index; Outputs[inpIdx].PricePerc := Block.Outputs[inpIdx].PricePerc; end; except Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' Error in TEvaluatedBlock.CopySettingsFrom.'); end; end; function TEvaluatedBlock.RenderCloneMenu(lang : string) : string; var aux : string; begin aux := mtidEvalBlockCloneMenu.Values[lang]; result := inherited RenderCloneMenu(lang); if aux <> '' then result := result + Format(aux, [cloneOption_OutputPrices, cloneOption_Suppliers, cloneOption_Clients]); // FIX MLS 'Price|%d|Suppliers|%d|Clients|%d|' end; procedure TEvaluatedBlock.msgOverloaded(var Msg : TBlockOverloadedMsg); begin msgGetOperationRatio(Msg); Msg.Result := Msg.Perc < 100; end; procedure TEvaluatedBlock.msgGetOperationRatio(var Msg : TBlockOverloadedMsg); var i, cnt : integer; begin i := 0; cnt := fEvaluatorPool.EvaluatorCount; while (i < cnt) and (fEvaluatorPool.Evaluators[i].MetaEvaluator.MetaOutput.MetaFluid <> Msg.Gate.MetaFluid) do inc(i); Msg.Perc := fEvaluatorPool.Evaluators[i].OperationRatio; end; function TEvaluatedBlock.Producing : boolean; var i, cnt : integer; begin i := 0; cnt := fEvaluatorPool.EvaluatorCount; while (i < cnt) and (fEvaluatorPool.Evaluators[i].OperationRatio = 0) do inc(i); result := i < cnt; end; function TEvaluatedBlock.GetVisualClassId : TVisualClassId; begin case MetaBlock.VisualStages of 2 : if Facility.CriticalTrouble or not Producing then result := 0 else result := 1; else result := 0; end; end; procedure TEvaluatedBlock.GetInventionsEffect(var QEffect : TInventionEfficiencyEffect; var KEffect : integer; DsgnK : TPercent); var i : integer; QltPts : integer; QltSum : integer; Effic : integer; Invention : TIndustryInvention; DsgnPts : single; begin QltPts := 0; QltSum := 0; Effic := 0; for i := 0 to pred(MetaBlock.Inventions.Count) do begin Invention := TIndustryInvention(MetaBlock.Inventions[i]); if Invention.Quality > 0 then inc(QltSum, Invention.Quality); if Facility.Company.HasInvention[Invention.NumId] then begin QltPts := QltPts + Invention.Quality; Effic := Effic + Invention.Effic; end; end; DsgnPts := DsgnK*QltSum/100; if QltSum > 0 then KEffect := min(150, round(100*(DsgnPts + QltPts)/QltSum)) else KEffect := 0; { if QltSum > 0 then KEffect := min(100, round(100*Quality/QltSum)) else KEffect := 0; } QEffect := 1 + Effic/100; end; function TEvaluatedBlock.GetWeatherConditions : single; begin with TMetaEvaluatedBlock(MetaBlock) do if WeatherEnvelope <> noIndex then result := WeatherEnvelopValue[WeatherEnvelope] else result := 1; end; function TEvaluatedBlock.AdverseWeatherConditions : boolean; begin result := GetWeatherConditions <= TMetaEvaluatedBlock(MetaBlock).LimitWeatherCond; end; procedure TEvaluatedBlock.Deleted; begin fBeautyModifier.Delete; fBeautyModifier := nil; inherited; end; procedure TEvaluatedBlock.RecalculateInventionsEffect; var i : integer; OE : TOutputEvaluator; begin for i := 0 to pred(fEvaluatorPool.EvaluatorCount) do begin OE := fEvaluatorPool.Evaluators[i]; OE.RecalculateInventionsEffect(self); end; end; // TIndustryInvention constructor TIndustryInvention.Load(xmlObj : OleVariant); var Aux : OleVariant; begin inherited Load(xmlObj); Aux := xmlObj.children.item(tidInvElement_Props, Unassigned); fQuality := GetProperty(Aux, tidInvAttr_Q); fEffic := GetProperty(Aux, tidInvAttr_Effic); end; function TIndustryInvention.GetClientProps(Company : TObject; LangId : TLanguageId) : string; begin result := inherited GetClientProps(Company, LangId); if fEffic <> 0 then result := result + SimHints.GetHintText(mtidInvEff.Values[LangId], [FormatDelta(fEffic)]) + LineBreak; if Quality <> 0 then result := result + SimHints.GetHintText(mtidInvQ.Values[LangId], [FormatDelta(Quality)]) + LineBreak; end; // RegisterInventionClass procedure RegisterInventionClass; begin TheClassStorage.RegisterClass( tidClassFamily_InvClasses, tidIndustriesInvention, TInventionClass.Create(TIndustryInvention)); end; end.
unit nsDictionDocumentContainer; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "DictionLikeDocumentProcessing" // Автор: Люлин А.В. // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/DictionLikeDocumentProcessing/nsDictionDocumentContainer.pas" // Начат: 19.11.2010 14:43 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Встроенные продукты::DictionLike::DictionLikeDocumentProcessing::DocumentContainers::TnsDictionDocumentContainer // // Контейнер документа толкового словаря // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses eeDocumentContainer, DocumentUnit, nevTools, DocumentInterfaces, F1TagDataProviderInterface, afwInterfaces, l3Interfaces, nevBase, k2Base, Classes, nevPrintableDocumentContainer, l3IID ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _nsDocumentContainer_Parent_ = TeeDocumentContainer; {$Include w:\garant6x\implementation\Garant\GbaNemesis\F1DocumentProcessing\nsDocumentContainer.imp.pas} TnsDictionDocumentContainer = class(_nsDocumentContainer_) {* Контейнер документа толкового словаря } protected // overridden protected methods function GetDocument: InevTag; override; end;//TnsDictionDocumentContainer {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses Document_Const, Block_Const, k2Tags, nsF1DocumentTagNode, DictEntry_Const, SysUtils, nsIDocumentDataObject, nsDocumentPreview, nsHAFPainter, LoggingInterfaces, nsDocumentPrintEvent, deDocInfo, DataAdapter, evdTypes, nsTypes, LeafPara_Const, nsTagString, evParaTools, afwFacade ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type _Instance_R_ = TnsDictionDocumentContainer; {$Include w:\garant6x\implementation\Garant\GbaNemesis\F1DocumentProcessing\nsDocumentContainer.imp.pas} // start class TnsDictionDocumentContainer function TnsDictionDocumentContainer.GetDocument: InevTag; //#UC START# *47F27DA80172_4CE662B803DA_var* var l_D : InevTag; l_ID : Integer; l_Index : Integer; l_B : InevTag; l_P : IDocumentTextProvider; //#UC END# *47F27DA80172_4CE662B803DA_var* begin //#UC START# *47F27DA80172_4CE662B803DA_impl* Result := inherited GetDocument; if (Result = nil) then begin Result := k2_typDictEntry.MakeTag; //Result := k2_typDocument.MakeTag; try l_ID := Ord(f_DocumentInfo.Language) + 101; f_DocumentInfo.Doc.GetTextProvider(false, l_P); Assert(l_P <> nil); l_D := TnsF1DocumentTagNode.Make(l_P); Assert(l_D <> nil); Result.IntA[k2_tiExternalHandle] := l_D.IntA[k2_tiExternalHandle]; with l_D do begin Assert(IsValid); for l_Index := 0 to Pred(ChildrenCount) do begin l_B := Child[l_Index]; if l_B.InheritsFrom(k2_idBlock) then if (l_B.IntA[k2_tiHandle] = l_ID) then begin Result.AddChild(l_B); Assert(l_B.Owner.IsSame(Result)); Exit; end;//l_B.IntA[k2_tiHandle] = l_ID end;//for l_Index Assert(false, 'Не найден блок языка - ' + IntToStr(l_ID)); end;//with l_D finally Document := Result; // - это СПЕЦИАЛЬНО ПОСЛЕ создания оглавления end;//try..finally end;//Result = nil //#UC END# *47F27DA80172_4CE662B803DA_impl* end;//TnsDictionDocumentContainer.GetDocument {$IfEnd} //not Admin AND not Monitorings end.
unit tfwAutoregisteredDiction; {* Словарь с базовой аксиоматикой } // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwAutoregisteredDiction.pas" // Стереотип: "SimpleClass" // Элемент модели: "TtfwAutoregisteredDiction" MUID: (4DB05FF60115) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , tfwStandardDictionary , tfwDictionaryEx , l3Interfaces , tfwScriptingInterfaces ; type TtfwAutoregisteredDiction = class(TtfwStandardDictionary) {* Словарь с базовой аксиоматикой } private f_AllAxiomaticsDefined: Boolean; protected procedure pm_SetAllAxiomaticsDefined(aValue: Boolean); virtual; function DoCheckWord(const aName: Il3CString): TtfwKeyWord; override; procedure ClearFields; override; function IsAxiom: Boolean; override; function Add(aWord: TtfwKeyWord): Integer; override; public constructor Create; reintroduce; function DictionaryByWord(const aWord: Il3CString): TtfwDictionaryEx; function CheckDictionaryByWordAndUse(const aWord: Il3CString): Boolean; class function Instance: TtfwAutoregisteredDiction; {* Метод получения экземпляра синглетона TtfwAutoregisteredDiction } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } public property AllAxiomaticsDefined: Boolean read f_AllAxiomaticsDefined write pm_SetAllAxiomaticsDefined; end;//TtfwAutoregisteredDiction {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , tfwStandardDictionaries , l3String , SysUtils , l3Chars , tfwCStringFactory , l3Base //#UC START# *4DB05FF60115impl_uses* //#UC END# *4DB05FF60115impl_uses* ; var g_TtfwAutoregisteredDiction: TtfwAutoregisteredDiction = nil; {* Экземпляр синглетона TtfwAutoregisteredDiction } procedure TtfwAutoregisteredDictionFree; {* Метод освобождения экземпляра синглетона TtfwAutoregisteredDiction } begin l3Free(g_TtfwAutoregisteredDiction); end;//TtfwAutoregisteredDictionFree procedure TtfwAutoregisteredDiction.pm_SetAllAxiomaticsDefined(aValue: Boolean); //#UC START# *52EF85600031_4DB05FF60115set_var* //#UC END# *52EF85600031_4DB05FF60115set_var* begin //#UC START# *52EF85600031_4DB05FF60115set_impl* Assert(not f_AllAxiomaticsDefined OR aValue); f_AllAxiomaticsDefined := aValue; //#UC END# *52EF85600031_4DB05FF60115set_impl* end;//TtfwAutoregisteredDiction.pm_SetAllAxiomaticsDefined constructor TtfwAutoregisteredDiction.Create; //#UC START# *559E658901B3_4DB05FF60115_var* //#UC END# *559E658901B3_4DB05FF60115_var* begin //#UC START# *559E658901B3_4DB05FF60115_impl* inherited Create(TtfwCStringFactory.C('axiom:axiom'), []); TtfwStandardDictionaries.Instance.Add(Self); //#UC END# *559E658901B3_4DB05FF60115_impl* end;//TtfwAutoregisteredDiction.Create function TtfwAutoregisteredDiction.DictionaryByWord(const aWord: Il3CString): TtfwDictionaryEx; //#UC START# *55B22CD10358_4DB05FF60115_var* const cDot : AnsiChar = '.'; procedure Split(const aSt: Il3CString; C: AnsiChar; var P, S: Il3CString); var l_St : Il3CString; begin//Split l_St := aSt; while l3Starts(l3PCharLen(PAnsiChar(@C), 1), l3PCharLen(l_St), true) do l3Delete(l_St, 0, 1); l3Split(l_St, C, P, S); while l3Starts(l3PCharLen(PAnsiChar(@C), 1), l3PCharLen(S), true) do l3Delete(S, 0, 1); while l3Starts(l3PCharLen(PAnsiChar(@cDot), 1), l3PCharLen(P), true) do l3Delete(P, 0, 1); while l3Starts(l3PCharLen(PAnsiChar(@cDot), 1), l3PCharLen(S), true) do l3Delete(S, 0, 1); while not l3IsNil(P) AND not(l3Char(P, 0) in cc_ANSILetter) do l3Delete(P, 0, 1); end;//Split const cSep : AnsiChar = ':'; var l_P : Il3CString; l_S : Il3CString; l_D : TtfwStandardDictionary; //#UC END# *55B22CD10358_4DB05FF60115_var* begin //#UC START# *55B22CD10358_4DB05FF60115_impl* Result := Self; Split(aWord, cSep, l_P, l_S); if not l3IsNil(l_P) AND not l3IsNil(l_S) then begin if l3Same(l_P, l3PCharLen('pop'), true) OR l3Same(l_P, l3PCharLen('current'), true) OR l3Same(l_P, l3PCharLen('focused'), true) OR l3Same(l_P, l3PCharLen('byname'), true) then begin Split(l_S, cSep, l_P, l_S); end;//l3Same(l_P, l3PCharLen('pop'), true) if not l3IsNil(l_P) AND not l3IsNil(l_S) then begin if not l3Starts(l3PCharLen(cSep), l3PCharLen(l_S), true) then begin l_D := TtfwStandardDictionaries.Instance.CheckDictionary(TtfwCStringFactory.Cat(TtfwCStringFactory.C('axiom:'), l_P)); Assert(l_D <> nil); //if not l3Same(l_P, l3PCharLen('^'), true) then //if not l3Same(l_P, l3PCharLen('='), true) then if not l3Same(l_P, l3PCharLen('class'), true) then if not l3Same(l_P, l3PCharLen('guid'), true) then if not l3Same(l_P, l3PCharLen('object'), true) then if not l3Same(l_P, l3PCharLen('interface'), true) then if not l3Same(l_P, l3PCharLen('string'), true) then if not l3Same(l_P, l3PCharLen('strings'), true) then if not l3Same(l_P, l3PCharLen('w-string'), true) then if not l3Same(l_P, l3PCharLen('wstring'), true) then if not l3Same(l_P, l3PCharLen('text'), true) then if not l3Same(l_P, l3PCharLen('file'), true) then if not l3Same(l_P, l3PCharLen('integer'), true) then if not l3Same(l_P, l3PCharLen('array'), true) then if not l3Same(l_P, l3PCharLen('exception'), true) then if not l3Same(l_P, l3PCharLen('char'), true) then begin Result := l_D; end;//not l3Same(l_P, l3PCharLen('class'), true).. end;//not l3Starts(l3PCharLen(cSep), l3PCharLen(l_S), true) end;//not l3IsNil(l_S) end//not l3IsNil(l_S) else begin Split(aWord, cDot, l_P, l_S); if not l3IsNil(l_P) AND not l3IsNil(l_S) then begin l_D := TtfwStandardDictionaries.Instance.CheckDictionary(TtfwCStringFactory.Cat(TtfwCStringFactory.C('axiom:'), l_P)); Result := l_D; end;//not l3IsNil(l_P) AND not l3IsNil(l_S) end;//not l3IsNil(l_P) AND not l3IsNil(l_S) Assert(Result <> nil); //#UC END# *55B22CD10358_4DB05FF60115_impl* end;//TtfwAutoregisteredDiction.DictionaryByWord function TtfwAutoregisteredDiction.CheckDictionaryByWordAndUse(const aWord: Il3CString): Boolean; //#UC START# *55B22D3C019E_4DB05FF60115_var* var l_DtoAdd : TtfwDictionaryEx; //#UC END# *55B22D3C019E_4DB05FF60115_var* begin //#UC START# *55B22D3C019E_4DB05FF60115_impl* Result := false; if (Self.DRbyCName[aWord] <> nil) then Result := true else begin l_DtoAdd := DictionaryByWord(aWord); if (l_DtoAdd <> nil) then begin if (l_DtoAdd <> Self) then begin if (l_DtoAdd.DRbyCName[aWord] <> nil) then begin Result := true; Self.UseDictionary(l_DtoAdd); Self.ExportDictionary(l_DtoAdd); end;//l_DtoAdd.DRbyCName[aWord] <> nil end;//l_DtoAdd <> Self end;//l_DtoAdd <> nil end;//Self.DRbyCName[aWord] <> nil //#UC END# *55B22D3C019E_4DB05FF60115_impl* end;//TtfwAutoregisteredDiction.CheckDictionaryByWordAndUse class function TtfwAutoregisteredDiction.Instance: TtfwAutoregisteredDiction; {* Метод получения экземпляра синглетона TtfwAutoregisteredDiction } begin if (g_TtfwAutoregisteredDiction = nil) then begin l3System.AddExitProc(TtfwAutoregisteredDictionFree); g_TtfwAutoregisteredDiction := Create; end; Result := g_TtfwAutoregisteredDiction; end;//TtfwAutoregisteredDiction.Instance class function TtfwAutoregisteredDiction.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TtfwAutoregisteredDiction <> nil; end;//TtfwAutoregisteredDiction.Exists function TtfwAutoregisteredDiction.DoCheckWord(const aName: Il3CString): TtfwKeyWord; //#UC START# *4F465D580021_4DB05FF60115_var* var i : Integer; l_W : TtfwKeyWord; l_DtoAdd : TtfwDictionaryEx; //#UC END# *4F465D580021_4DB05FF60115_var* begin //#UC START# *4F465D580021_4DB05FF60115_impl* l_DtoAdd := DictionaryByWord(aName); if l_DtoAdd.FindData(l3PCharLen(aName), i, l_DtoAdd.SortIndex) then Result := TtfwKeyWord(l_DtoAdd.Items[i]) else begin l_W := TtfwKeyWord.Create(l_DtoAdd, aName); try //l_DtoAdd.DirectInsert(i, l_W); l_DtoAdd.Insert(i, l_W); Result := l_W; finally FreeAndNil(l_W); end;//try..finally end;//FindData... //#UC END# *4F465D580021_4DB05FF60115_impl* end;//TtfwAutoregisteredDiction.DoCheckWord procedure TtfwAutoregisteredDiction.ClearFields; //#UC START# *5000565C019C_4DB05FF60115_var* //#UC END# *5000565C019C_4DB05FF60115_var* begin //#UC START# *5000565C019C_4DB05FF60115_impl* inherited; f_AllAxiomaticsDefined := false; //#UC END# *5000565C019C_4DB05FF60115_impl* end;//TtfwAutoregisteredDiction.ClearFields function TtfwAutoregisteredDiction.IsAxiom: Boolean; //#UC START# *55A7ECD8020D_4DB05FF60115_var* //#UC END# *55A7ECD8020D_4DB05FF60115_var* begin //#UC START# *55A7ECD8020D_4DB05FF60115_impl* Result := true; //#UC END# *55A7ECD8020D_4DB05FF60115_impl* end;//TtfwAutoregisteredDiction.IsAxiom function TtfwAutoregisteredDiction.Add(aWord: TtfwKeyWord): Integer; //#UC START# *55B0E87401FA_4DB05FF60115_var* var l_DtoAdd : TtfwDictionaryEx; //#UC END# *55B0E87401FA_4DB05FF60115_var* begin //#UC START# *55B0E87401FA_4DB05FF60115_impl* l_DtoAdd := DictionaryByWord(aWord.AsCStr); Assert(l_DtoAdd <> nil); if (l_DtoAdd = Self) then Result := inherited Add(aWord) else begin aWord.ChangeDictionary(l_DtoAdd); Result := l_DtoAdd.Add(aWord); end;//l_D = Self //#UC END# *55B0E87401FA_4DB05FF60115_impl* end;//TtfwAutoregisteredDiction.Add {$IfEnd} // NOT Defined(NoScripts) end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, REST.Backend.ServiceTypes, REST.Backend.MetaTypes, System.JSON, System.Rtti, System.Bindings.Outputs, Vcl.Bind.Editors, Data.Bind.EngExt, Vcl.Bind.DBEngExt, Vcl.StdCtrls, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.BindSource, REST.Backend.ServiceComponents, REST.Backend.KinveyServices, Vcl.ExtCtrls, REST.Backend.Providers, Vcl.ComCtrls, REST.Backend.ParseServices; type TForm1 = class(TForm) BackendQuery1: TBackendQuery; MemoJSONResult: TMemo; LinkControlToFieldJSONResult: TLinkControlToField; BindingsList1: TBindingsList; BackendStorage1: TBackendStorage; PageControl1: TPageControl; tabFetch: TTabSheet; tabAdd: TTabSheet; tabDelete: TTabSheet; Button1: TButton; MemoQueryStrings: TMemo; Button2: TButton; edtPhone: TLabeledEdit; edtName: TLabeledEdit; Label1: TLabel; btnDelete: TButton; edtDeleteObjectID: TLabeledEdit; LinkControlToField3: TLinkControlToField; tabSettings: TTabSheet; EditBackendClassName: TLabeledEdit; ComboBoxBackendService: TComboBox; Label3: TLabel; LinkControlToField1: TLinkControlToField; LinkFillControlToField1: TLinkFillControlToField; ListView1: TListView; Panel1: TPanel; Label2: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure btnDeleteClick(Sender: TObject); private { Private declarations } public { Public declarations } end; TCustomer = class strict private FName: string; FPhone: string; FFoo: string; published property Phone : string read FPhone write FPhone; property Name : string read FName write FName; property Foo : string read FFoo write FFoo; end; var Form1: TForm1; implementation {$R *.dfm} uses Unit2; procedure TForm1.btnDeleteClick(Sender: TObject); begin BackendStorage1.Storage.DeleteObject(EditBackendClassName.Text,edtDeleteObjectID.Text) end; procedure TForm1.Button1Click(Sender: TObject); var Customer : TCustomer; LVI: TListItem; Customers: TBackendObjectList<TCustomer>; I: Integer; QueryStr: TArray<string>; begin BackendQuery1.Execute; // OR for objects you can get the objects back using the following code. // Customers := TBackendObjectList<TCustomer>.Create; try QueryStr := TArray<string>.Create(MemoQueryStrings.Lines.Text); BackendStorage1.Storage.QueryObjects<TCustomer>('Customer',QueryStr,Customers); ListView1.Items.Clear; for I := 0 to Customers.Count -1 do begin Customer := Customers.Items[I]; LVI := ListView1.Items.Add; LVI.Caption := Customer.Name; LVI.SubItems.Add(Customer.Phone); LVI.SubItems.Add(Customers.EntityValues[Customer].ObjectID); end; finally Customers.Free; end; end; procedure TForm1.Button2Click(Sender: TObject); Var LValue : TBackendEntityValue; LCustomer : TCustomer; begin LCustomer := TCustomer.Create; try LCustomer.Name := edtName.Text; LCustomer.Phone := edtPhone.Text; LCustomer.Foo := 'Foo'; BackendStorage1.Storage.CreateObject<TCustomer>(EditBackendClassName.Text,LCustomer, LValue); edtDeleteObjectID.Text := LValue.ObjectID; finally LCustomer.Free; end; end; end.
unit UserActionsUnit; interface uses SysUtils, BaseActionUnit, System.Generics.Collections, DataObjectUnit, GenericParametersUnit, UserUnit, EnumsUnit, CommonTypesUnit, NullableBasicTypesUnit, UserParametersUnit; type TUserActions = class(TBaseAction) public function Get(MemberId: integer; out ErrorString: String): TUser; overload; function Get(out ErrorString: String): TUserList; overload; /// <summary> /// Authentication of a user with an email and password /// </summary> /// <returns> /// SessionGuid /// </returns> procedure Authentication(Email, Password: String; out ErrorString: String; out SessionId: NullableInteger; out SessionGuid: NullableString); /// <summary> /// Check if a session is valid. /// </summary> function IsSessionValid(SessionId: String; MemberId: integer; out ErrorString: String): boolean; /// <summary> /// Check if a session is valid. /// </summary> /// <returns> /// Member Id of added user /// </returns> function RegisterAccount(Plan, Industry, FirstName, LastName, Email: String; Terms: boolean; DeviceType: TDeviceType; Password, PasswordConfirmation: String; out ErrorString: String): NullableInteger; deprecated; /// <summary> /// Create new user /// </summary> /// <returns> /// Member Id of added user /// </returns> function AddNewUser(Parameters: TUserParameters; out ErrorString: String): NullableInteger; /// <summary> /// Update an existing user /// </summary> /// <returns> /// Member Id of added user /// </returns> procedure Update(Parameters: TUserParameters; out ErrorString: String); /// <summary> /// Remove existing user from a memberТs account. /// </summary> function Remove(MemberId: integer; out ErrorString: String): boolean; function DeviceLicense(DeviceId: String; DeviceType: TDeviceType; out ErrorString: String): boolean; function UserLicense(MemberId, SessionId: integer; DeviceId: String; DeviceType: TDeviceType; Subscription: String; Token: String; Payload: String; out ErrorString: String): boolean; function RegisterWebinar(Email, FirstName, LastName, Phone, Company: String; MemberId: integer; StartDate: TDateTime; out ErrorString: String): boolean; function AddConfigValue(Key, Value: String; out ErrorString: String): Boolean; function UpdateConfigValue(Key, Value: String; out ErrorString: String): Boolean; function DeleteConfigValue(Key: String; out ErrorString: String): Boolean; function GetAllConfigValues(out ErrorString: String): TListStringPair; function GetConfigValue(Key: string; out ErrorString: String): NullableString; end; implementation { TUserActions } uses SettingsUnit, ValidateSessionResponseUnit, AddNewUserResponseUnit, RegisterAccountResponseUnit, StatusResponseUnit, RemoveUserRequestUnit, AuthenticationResponseUnit, DeviceLicenseRequestUnit, UserLicenseRequestUnit, RegisterWebinarRequestUnit, DeviceLicenseResponseUnit, ConfigValueRequestUnit, ConfigValueResponseUnit, GetConfigValueResponseUnit; function TUserActions.RegisterAccount(Plan, Industry, FirstName, LastName, Email: String; Terms: boolean; DeviceType: TDeviceType; Password, PasswordConfirmation: String; out ErrorString: String): NullableInteger; var Parameters: TGenericParameters; Response: TRegisterAccountResponse; begin Result := NullableInteger.Null; Parameters := TGenericParameters.Create; try Parameters.AddParameter('plan', Plan); Parameters.AddBodyParameter('strIndustry', Industry); Parameters.AddBodyParameter('strFirstName', FirstName); Parameters.AddBodyParameter('strLastName', LastName); Parameters.AddBodyParameter('strEmail', Email); Parameters.AddBodyParameter('format', 'json'); if Terms then Parameters.AddBodyParameter('chkTerms', '1') else Parameters.AddBodyParameter('chkTerms', '0'); Parameters.AddBodyParameter('device_type', TDeviceTypeDescription[DeviceType]); Parameters.AddBodyParameter('strPassword_1', Password); Parameters.AddBodyParameter('strPassword_2', PasswordConfirmation); Response := FConnection.Post(TSettings.EndPoints.RegisterAccount, Parameters, TRegisterAccountResponse, ErrorString) as TRegisterAccountResponse; try if (Response <> nil) then if (Length(Response.Errors) > 0) then ErrorString := String.Join('; ', Response.Errors) else Result := Response.MemberId else if (ErrorString = EmptyStr) then ErrorString := 'New user not added'; finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; end; function TUserActions.RegisterWebinar(Email, FirstName, LastName, Phone, Company: String; MemberId: integer; StartDate: TDateTime; out ErrorString: String): boolean; var Request: TRegisterWebinarRequest; Response: TSimpleString; begin Result := False; Request := TRegisterWebinarRequest.Create(Email, FirstName, LastName, Phone, Company, MemberId, StartDate); try // todo 5: узнать какой ответ в случае успеха Response := FConnection.Post(TSettings.EndPoints.RegisterWebinar, Request, TSimpleString, ErrorString) as TSimpleString; try if (Response = nil) and (ErrorString = EmptyStr) then ErrorString := 'RegisterWebinar fault'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TUserActions.Remove(MemberId: integer; out ErrorString: String): boolean; var Request: TRemoveUserRequest; Response: TStatusResponse; begin Request := TRemoveUserRequest.Create(MemberId); try Response := FConnection.Delete(TSettings.EndPoints.Users, Request, TStatusResponse, ErrorString) as TStatusResponse; try Result := (Response <> nil) and (Response.Status); if ((Response = nil) and (ErrorString = EmptyStr)) or ((Response <> nil) and (not Response.Status)) then ErrorString := 'User not removed'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; procedure TUserActions.Update(Parameters: TUserParameters; out ErrorString: String); var Response: TAddNewUserResponse; begin Response := FConnection.Put(TSettings.EndPoints.Users, Parameters, TAddNewUserResponse, ErrorString) as TAddNewUserResponse; try if (Response = nil) and (ErrorString = EmptyStr) then ErrorString := 'User not updated'; finally FreeAndNil(Response); end; end; function TUserActions.UpdateConfigValue(Key, Value: String; out ErrorString: String): Boolean; const SuccessResultCode = 'OK'; var Request: TConfigValueRequest; Response: TConfigValueResponse; begin Request := TConfigValueRequest.Create(Key, Value); try Response := FConnection.Put(TSettings.EndPoints.ConfigurationSettings, Request, TConfigValueResponse, ErrorString) as TConfigValueResponse; try if (Response = nil) and (ErrorString = EmptyStr) or (Response <> nil) and (Response.Result.IsNull) then ErrorString := 'UpdateConfigValue fault' else if (Response <> nil) and (Response.Result.Value <> SuccessResultCode) then ErrorString := Response.Result.Value; Result := (Response <> nil) and (Response.Result.IsNotNull) and (Response.Result.Value = SuccessResultCode); finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TUserActions.UserLicense(MemberId, SessionId: integer; DeviceId: String; DeviceType: TDeviceType; Subscription: String; Token: String; Payload: String; out ErrorString: String): boolean; var Request: TUserLicenseRequest; Response: TSimpleString; begin Result := False; Request := TUserLicenseRequest.Create(MemberId, SessionId, DeviceId, DeviceType, Subscription, Token, Payload); try Response := FConnection.Post(TSettings.EndPoints.UserLicense, Request, TSimpleString, ErrorString) as TSimpleString; try if (Response <> nil) and (ErrorString = EmptyStr) then ErrorString := Response.Value; if (Response = nil) and (ErrorString = EmptyStr) then ErrorString := 'UserLicense fault'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TUserActions.AddConfigValue(Key, Value: String; out ErrorString: String): Boolean; const SuccessResultCode = 'OK'; var Request: TConfigValueRequest; Response: TConfigValueResponse; begin Request := TConfigValueRequest.Create(Key, Value); try Response := FConnection.Post(TSettings.EndPoints.ConfigurationSettings, Request, TConfigValueResponse, ErrorString) as TConfigValueResponse; try if (Response = nil) and (ErrorString = EmptyStr) or (Response <> nil) and (Response.Result.IsNull) then ErrorString := 'AddConfigValue fault' else if (Response <> nil) and (Response.Result.Value <> SuccessResultCode) then ErrorString := Response.Result.Value; Result := (Response <> nil) and (Response.Result.IsNotNull) and (Response.Result.Value = SuccessResultCode); finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TUserActions.AddNewUser(Parameters: TUserParameters; out ErrorString: String): NullableInteger; var Response: TAddNewUserResponse; EMail: String; begin Result := NullableInteger.Null; if (Parameters.Email.IsNotNull) then begin EMail := Parameters.Email; StringReplace(EMail, ' ', '+', [rfReplaceAll]); Parameters.Email := EMail; end; Response := FConnection.Post(TSettings.EndPoints.Users, Parameters, TAddNewUserResponse, ErrorString) as TAddNewUserResponse; try if (Response <> nil) then Result := Response.MemberId else if (Response = nil) and (ErrorString = EmptyStr) then ErrorString := 'New user not added'; finally FreeAndNil(Response); end; end; procedure TUserActions.Authentication(Email, Password: String; out ErrorString: String; out SessionId: NullableInteger; out SessionGuid: NullableString); var Parameters: TGenericParameters; Response: TObject; PossibleResponses: TClassArray; begin SessionGuid := NullableString.Null; SessionId := NullableInteger.Null; Parameters := TGenericParameters.Create; try Parameters.AddBodyParameter('strEmail', Email); Parameters.AddBodyParameter('strPassword', Password); Parameters.AddBodyParameter('format', 'json'); SetLength(PossibleResponses, 2); PossibleResponses[0] := TGoodAuthenticationResponse; PossibleResponses[1] := TBadAuthenticationResponse; Response := FConnection.Post(TSettings.EndPoints.Authenticate, Parameters, PossibleResponses, ErrorString); if (Response <> nil) then begin if Response is TGoodAuthenticationResponse then begin if (TGoodAuthenticationResponse(Response).Status) then begin SessionGuid := TGoodAuthenticationResponse(Response).SessionGuid; SessionId := TGoodAuthenticationResponse(Response).SessionId; end else ErrorString := 'User authentication error'; end else ErrorString := (Response as TBadAuthenticationResponse).Error; end else if (Response = nil) and (ErrorString = EmptyStr) then ErrorString := 'User authentication error'; finally FreeAndNil(Parameters); end; end; function TUserActions.DeleteConfigValue(Key: String; out ErrorString: String): Boolean; const SuccessResultCode = 'OK'; var Request: TConfigValueRequest; Response: TConfigValueResponse; begin Request := TConfigValueRequest.Create(Key); try Response := FConnection.Delete(TSettings.EndPoints.ConfigurationSettings, Request, TConfigValueResponse, ErrorString) as TConfigValueResponse; try if (Response = nil) and (ErrorString = EmptyStr) or (Response <> nil) and (Response.Result.IsNull) then ErrorString := 'DeleteConfigValue fault' else if (Response <> nil) and (Response.Result.Value <> SuccessResultCode) then ErrorString := Response.Result.Value; Result := (Response <> nil) and (Response.Result.IsNotNull) and (Response.Result.Value = SuccessResultCode); finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TUserActions.DeviceLicense(DeviceId: String; DeviceType: TDeviceType; out ErrorString: String): boolean; var Request: TDeviceLicenseRequest; Response: TObject; ResponseClasses: TClassArray; begin Result := False; Request := TDeviceLicenseRequest.Create(DeviceId, DeviceType, 'json'); try SetLength(ResponseClasses, 2); ResponseClasses[0] := TDeviceLicenseResponse; ResponseClasses[1] := TSimpleString; Response := FConnection.Post(TSettings.EndPoints.VerifyDeviceLicense, Request, ResponseClasses, ErrorString); try if (Response <> nil) then begin if (Response is TSimpleString) then begin if (ErrorString = EmptyStr) then ErrorString := TSimpleString(Response).Value; end else Result := (Response as TDeviceLicenseResponse).Status; end; if (not Result) and (ErrorString = EmptyStr) then ErrorString := 'DeviceLicense fault'; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TUserActions.Get(MemberId: integer; out ErrorString: String): TUser; var Parameters: TGenericParameters; begin Parameters := TGenericParameters.Create; try Parameters.AddParameter('member_id', IntToStr(MemberId)); Result := FConnection.Get(TSettings.EndPoints.Users, Parameters, TUser, ErrorString) as TUser; if (Result = nil) and (ErrorString = EmptyStr) then ErrorString := 'User details not got'; finally FreeAndNil(Parameters); end; end; function TUserActions.Get(out ErrorString: String): TUserList; var Parameters: TGenericParameters; begin Parameters := TGenericParameters.Create; try Result := FConnection.Get(TSettings.EndPoints.GetUsers, Parameters, TUserList, ErrorString) as TUserList; if (Result = nil) then Result := TUserList.Create; Result.OwnsObjects := True; finally FreeAndNil(Parameters); end; end; function TUserActions.GetAllConfigValues(out ErrorString: String): TListStringPair; const SuccessResultCode = 'OK'; var Request: TGenericParameters; Response: TGetConfigValueResponse; i: Integer; begin Result := TListStringPair.Create; Request := TGenericParameters.Create; try Response := FConnection.Get(TSettings.EndPoints.ConfigurationSettings, Request, TGetConfigValueResponse, ErrorString) as TGetConfigValueResponse; try if (Response = nil) and (ErrorString = EmptyStr) or (Response <> nil) and (Response.Result.IsNull) then ErrorString := 'GetAllConfigValues fault' else if (Response <> nil) and (Response.Result.Value <> SuccessResultCode) then ErrorString := Response.Result.Value; if (ErrorString = EmptyStr) then for i := 0 to High(Response.ConfigValues) do Result.Add(Response.ConfigValues[i].AsStringPair); finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TUserActions.GetConfigValue(Key: string; out ErrorString: String): NullableString; const SuccessResultCode = 'OK'; var Request: TGenericParameters; Response: TGetConfigValueResponse; begin Result := NullableString.Null; Request := TGenericParameters.Create; try Request.AddParameter('config_key', Key); Response := FConnection.Get(TSettings.EndPoints.ConfigurationSettings, Request, TGetConfigValueResponse, ErrorString) as TGetConfigValueResponse; try if (Response = nil) and (ErrorString = EmptyStr) or (Response <> nil) and (Response.Result.IsNull) then ErrorString := 'GetConfigValue fault' else if (Response <> nil) and (Response.Result.Value <> SuccessResultCode) then ErrorString := Response.Result.Value; if (ErrorString = EmptyStr) and (Length(Response.ConfigValues) > 0) then Result := Response.ConfigValues[0].Value; finally FreeAndNil(Response); end; finally FreeAndNil(Request); end; end; function TUserActions.IsSessionValid(SessionId: String; MemberId: integer; out ErrorString: String): boolean; var Parameters: TGenericParameters; Response: TValidateSessionResponse; begin Result := False; Parameters := TGenericParameters.Create; try Parameters.AddParameter('session_guid', SessionId); Parameters.AddParameter('member_id', IntToStr(MemberId)); Parameters.AddParameter('format', 'json'); Response := FConnection.Get(TSettings.EndPoints.ValidateSession, Parameters, TValidateSessionResponse, ErrorString) as TValidateSessionResponse; try if (Response <> nil) then Result := Response.Authenticated else if (ErrorString = EmptyStr) then ErrorString := 'Session not validated'; finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; end; end.
unit ODM_TLB; { This file contains pascal declarations imported from a type library. This file will be written during each import or refresh of the type library editor. Changes to this file will be discarded during the refresh process. } { ODM Library } { Version 1.0 } interface uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL; const LIBID_ODM: TGUID = '{8B08BB10-0BE8-11D4-BEA3-0080C8915F01}'; const { Component class GUIDs } Class_DirectoryManager: TGUID = '{8B08BB12-0BE8-11D4-BEA3-0080C8915F01}'; type { Forward declarations: Interfaces } IDirectoryManager = interface; IDirectoryManagerDisp = dispinterface; { Forward declarations: CoClasses } DirectoryManager = IDirectoryManager; { Dispatch interface for DirectoryManager Object } IDirectoryManager = interface(IDispatch) ['{8B08BB11-0BE8-11D4-BEA3-0080C8915F01}'] procedure Init(const aDirName: WideString; SetSecurity: WordBool); safecall; function FullPathKeyExists(const FullPathKey: WideString): OleVariant; safecall; function KeyExists(const KeyName: WideString): OleVariant; safecall; function GetKeyNames: OleVariant; safecall; function GetValueNames: OleVariant; safecall; function WriteBoolean(const Name: WideString; Value: WordBool): OleVariant; safecall; function WriteInteger(const Name: WideString; Value: Integer): OleVariant; safecall; function WriteFloat(const Name: WideString; Value: Double): OleVariant; safecall; function WriteString(const Name, Value: WideString): OleVariant; safecall; function WriteDate(const Name: WideString; Value: TDateTime): OleVariant; safecall; function ReadBoolean(const Name: WideString): OleVariant; safecall; function ReadInteger(const Name: WideString): OleVariant; safecall; function ReadFloat(const Name: WideString): OleVariant; safecall; function ReadString(const Name: WideString): OleVariant; safecall; function ReadDate(const Name: WideString): OleVariant; safecall; function FullPathValueExists(const FullPathName: WideString): OleVariant; safecall; function ValueExists(const Name: WideString): OleVariant; safecall; function DeleteFullPathNode(const FullPathNode: WideString): OleVariant; safecall; function DeleteNode(const NodeName: WideString): OleVariant; safecall; function FullQuery(const aQuery: WideString): OleVariant; safecall; function Query(const aQuery: WideString): OleVariant; safecall; function CreateFullPathKey(const FullPathKey: WideString; ForcePath: WordBool): OleVariant; safecall; function CreateKey(const KeyName: WideString): OleVariant; safecall; function SetSecurityOfKey(const FullKeyName: WideString; Security: WordBool): OleVariant; safecall; function KeysCount: OleVariant; safecall; function ValuesCount: OleVariant; safecall; function WriteCurrency(const Name: WideString; Value: Currency): OleVariant; safecall; function ReadCurrency(const Name: WideString): OleVariant; safecall; function IntegrateValues(const RelValuePath: WideString): OleVariant; safecall; function QueryKey(const FullKeyName, ValueNameList: WideString): OleVariant; safecall; function GetCurrentKey: OleVariant; safecall; function SetCurrentKey(const FullPathKey: WideString): OleVariant; safecall; function ReadDateAsStr(const Name: WideString): OleVariant; safecall; function WriteDateFromStr(const Name, Value: WideString): OleVariant; safecall; end; { DispInterface declaration for Dual Interface IDirectoryManager } IDirectoryManagerDisp = dispinterface ['{8B08BB11-0BE8-11D4-BEA3-0080C8915F01}'] procedure Init(const aDirName: WideString; SetSecurity: WordBool); dispid 1; function FullPathKeyExists(const FullPathKey: WideString): OleVariant; dispid 3; function KeyExists(const KeyName: WideString): OleVariant; dispid 4; function GetKeyNames: OleVariant; dispid 6; function GetValueNames: OleVariant; dispid 7; function WriteBoolean(const Name: WideString; Value: WordBool): OleVariant; dispid 8; function WriteInteger(const Name: WideString; Value: Integer): OleVariant; dispid 9; function WriteFloat(const Name: WideString; Value: Double): OleVariant; dispid 10; function WriteString(const Name, Value: WideString): OleVariant; dispid 11; function WriteDate(const Name: WideString; Value: TDateTime): OleVariant; dispid 12; function ReadBoolean(const Name: WideString): OleVariant; dispid 13; function ReadInteger(const Name: WideString): OleVariant; dispid 14; function ReadFloat(const Name: WideString): OleVariant; dispid 15; function ReadString(const Name: WideString): OleVariant; dispid 16; function ReadDate(const Name: WideString): OleVariant; dispid 17; function FullPathValueExists(const FullPathName: WideString): OleVariant; dispid 18; function ValueExists(const Name: WideString): OleVariant; dispid 19; function DeleteFullPathNode(const FullPathNode: WideString): OleVariant; dispid 20; function DeleteNode(const NodeName: WideString): OleVariant; dispid 21; function FullQuery(const aQuery: WideString): OleVariant; dispid 22; function Query(const aQuery: WideString): OleVariant; dispid 23; function CreateFullPathKey(const FullPathKey: WideString; ForcePath: WordBool): OleVariant; dispid 24; function CreateKey(const KeyName: WideString): OleVariant; dispid 25; function SetSecurityOfKey(const FullKeyName: WideString; Security: WordBool): OleVariant; dispid 26; function KeysCount: OleVariant; dispid 27; function ValuesCount: OleVariant; dispid 28; function WriteCurrency(const Name: WideString; Value: Currency): OleVariant; dispid 29; function ReadCurrency(const Name: WideString): OleVariant; dispid 30; function IntegrateValues(const RelValuePath: WideString): OleVariant; dispid 31; function QueryKey(const FullKeyName, ValueNameList: WideString): OleVariant; dispid 32; function GetCurrentKey: OleVariant; dispid 5; function SetCurrentKey(const FullPathKey: WideString): OleVariant; dispid 33; function ReadDateAsStr(const Name: WideString): OleVariant; dispid 2; function WriteDateFromStr(const Name, Value: WideString): OleVariant; dispid 34; end; { DirectoryManagerObject } CoDirectoryManager = class class function Create: IDirectoryManager; class function CreateRemote(const MachineName: string): IDirectoryManager; end; implementation uses ComObj; class function CoDirectoryManager.Create: IDirectoryManager; begin Result := CreateComObject(Class_DirectoryManager) as IDirectoryManager; end; class function CoDirectoryManager.CreateRemote(const MachineName: string): IDirectoryManager; begin Result := CreateRemoteComObject(MachineName, Class_DirectoryManager) as IDirectoryManager; end; end.
unit main; { * Copyright 2015 E Spelt for test project stuff * * 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. * Implemented by E. Spelt for Delphi } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.StdCtrls, FMX.Media, FMX.Platform, FMX.MultiView, FMX.ListView.Types, FMX.ListView, FMX.Layouts, System.Actions, FMX.ActnList, FMX.TabControl, FMX.ListBox, Threading, BarcodeFormat, ReadResult, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, ScanManager, FMX.Ani {$IFDEF ANDROID} ,Androidapi.JNIBridge ,System.Rtti ,Androidapi.JNI.Hardware ,FMX.Media.Android ,CameraConfigurationUtils {$ENDIF} ; type TMainForm = class(TForm) btnStartCamera: TButton; btnStopCamera: TButton; lblScanStatus: TLabel; imgCamera: TImage; ToolBar1: TToolBar; btnMenu: TButton; Layout2: TLayout; ToolBar3: TToolBar; CameraComponent1: TCameraComponent; Memo1: TMemo; lblStatus: TLabel; lytScanMask: TLayout; Rectangle1: TRectangle; Rectangle2: TRectangle; Rectangle3: TRectangle; Rectangle4: TRectangle; lytScanWindow: TLayout; Line1: TLine; FloatAnimation1: TFloatAnimation; rectLefTop: TRectangle; rectTopRight: TRectangle; rectLeftBottom: TRectangle; rectRightTop: TRectangle; rectTopLeft: TRectangle; rectRightBottom: TRectangle; Rectangle5: TRectangle; Rectangle6: TRectangle; Text1: TText; chkAutoFocus: TCheckBox; btnAvailableSettings: TSpeedButton; procedure btnStartCameraClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnStopCameraClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure CameraComponent1SampleBufferReady(Sender: TObject; const ATime: TMediaTime); procedure btnAvailableSettingsClick(Sender: TObject); private { Private declarations } FStartTime: TDateTime; FScanManager: TScanManager; FScanInProgress: Boolean; frameTake: Integer; procedure GetImage(); procedure FocusReady; function AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} {$R *.NmXhdpiPh.fmx ANDROID} {$R *.LgXhdpiPh.fmx ANDROID} {$R *.iPhone55in.fmx IOS} type TMyCamera = class(TCameraComponent) end; {$IFDEF ANDROID} TAndroidCameraCallback = class(TJavaLocal, JCamera_AutoFocusCallback) private [Weak] FMainForm: TMainForm; public procedure onAutoFocus(success: Boolean; camera: JCamera); cdecl; end; procedure TAndroidCameraCallback.onAutoFocus(success: Boolean; camera: JCamera); cdecl; begin FMainForm.FocusReady; end; var CameraCallBack: TAndroidCameraCallback = nil; function GetCameraCallBack: TAndroidCameraCallback; begin if CameraCallBack = nil then CameraCallBack := TAndroidCameraCallback.Create; Result := TAndroidCameraCallback.Create; end; {$ENDIF} procedure TMainForm.FocusReady; begin end; procedure TMainForm.FormCreate(Sender: TObject); var AppEventSvc: IFMXApplicationEventService; begin lblScanStatus.Text := ''; frameTake := 0; { by default, we start with Front Camera and Flash Off } { cbFrontCamera.IsChecked := True; CameraComponent1.Kind := FMX.Media.TCameraKind.ckFrontCamera; cbFlashOff.IsChecked := True; if CameraComponent1.HasFlash then CameraComponent1.FlashMode := FMX.Media.TFlashMode.fmFlashOff; } { Add platform service to see camera state. } if TPlatformServices.Current.SupportsPlatformService (IFMXApplicationEventService, IInterface(AppEventSvc)) then AppEventSvc.SetApplicationEventHandler(AppEvent); CameraComponent1.Quality := FMX.Media.TVideoCaptureQuality.MediumQuality; lblScanStatus.Text := ''; FScanManager := TScanManager.Create(TBarcodeFormat.Auto, nil); end; procedure TMainForm.FormDestroy(Sender: TObject); begin FScanManager.Free; end; procedure TMainForm.btnAvailableSettingsClick(Sender: TObject); var Settings: TArray<TVideoCaptureSetting>; I: Integer; s: string; begin // Settings := CameraComponent1.AvailableCaptureSettings; for I := 0 to High(Settings) do begin s := Format('%d: Width=%d, Height=%d, FrameRate=%f, Min=%f, Max=%f', [I+1, Settings[I].Width, Settings[I].Height, Settings[I].FrameRate, Settings[I].MinFrameRate, Settings[I].MaxFrameRate]); Memo1.Lines.Add(s); end; end; procedure TMainForm.btnStartCameraClick(Sender: TObject); var Setting: TVideoCaptureSetting; {$IFDEF ANDROID} JC: JCamera; Device: TCaptureDevice; ClassRef: TClass; ctx: TRttiContext; t: TRttiType; Params: JCamera_Parameters; {$ENDIF} begin FStartTime := Now; frameTake := 0; CameraComponent1.Active := False; Setting:= CameraComponent1.CaptureSetting; Setting.Width := 352; Setting.Height := 288; Setting.FrameRate := 30; Setting.SetFrameRate(30, 30); if chkAutoFocus.IsChecked then CameraComponent1.FocusMode := TFocusMode.ContinuousAutoFocus else CameraComponent1.FocusMode := TFocusMode.AutoFocus; CameraComponent1.SetCaptureSetting(Setting); CameraComponent1.Quality := TVideoCaptureQuality.MediumQuality; CameraComponent1.Kind := FMX.Media.TCameraKind.BackCamera; {$IFDEF ANDROID} Device := TMyCamera(CameraComponent1).Device; ClassRef := Device.ClassType; ctx := TRttiContext.Create; try t := ctx.GetType(ClassRef); JC := t.GetProperty('Camera').GetValue(Device).AsInterface as JCamera; TCameraConfigurationUtils.setBarcodeSceneMode(JC.getParameters); TCameraConfigurationUtils.setVideoStabilization(JC.getParameters); //JC.cancelAutoFocus(); //GetCameraCallback().FMainForm := Self; //JC.autoFocus(GetCameraCallback()); finally ctx.Free; end; {$ENDIF} CameraComponent1.Active := True; lblScanStatus.Text := ''; memo1.Lines.Clear; lytScanMask.Visible := True; FloatAnimation1.StopValue := lytScanWindow.Height; FloatAnimation1.Start; end; procedure TMainForm.btnStopCameraClick(Sender: TObject); begin CameraComponent1.Active := False; //self.imgCamera.Bitmap.Clear(0); FloatAnimation1.Stop; lytScanMask.Visible := False; end; procedure TMainForm.CameraComponent1SampleBufferReady(Sender: TObject; const ATime: TMediaTime); begin TThread.Synchronize(TThread.CurrentThread, GetImage); end; procedure TMainForm.GetImage; var scanBitmap: TBitmap; ReadResult: TReadResult; dt: TDateTime; fps: double; w, h, x, y: Integer; begin CameraComponent1.SampleBufferToBitmap(imgCamera.Bitmap, True); if (FScanInProgress) then begin Exit; end; inc(frameTake); // if (frameTake mod 4 <> 0) then // begin // Exit; // end; dt := (Now - FStartTime) * SecsPerDay; fps := (frameTake / dt); lblStatus.Text := Format('Frame:%d, FPS:%.2f', [frameTake, fps]); w := imgCamera.Bitmap.Width; h := imgCamera.Bitmap.Height; x := Round(w * lytScanWindow.Position.X / imgCamera.Width); y := Round(h * lytScanWindow.Position.Y / imgCamera.Height); scanBitmap := TBitmap.Create(); scanBitmap.SetSize(w - 2 * x, h - 2 * y); scanBitmap.Canvas.DrawBitmap(imgCamera.Bitmap, RectF(x, y, w - x, h - y), RectF(0,0,scanBitmap.Width, scanBitmap.Height), 1); // scanBitmap.Assign(imgCamera.Bitmap); TTask.Run( procedure begin try FScanInProgress := True; scanBitmap.Assign(imgCamera.Bitmap); ReadResult := FScanManager.Scan(scanBitmap); FScanInProgress := False; except on E: Exception do begin FScanInProgress := False; TThread.Synchronize(nil, procedure begin // lblScanStatus.Text := E.Message; // lblScanResults.Text := ''; end); if (scanBitmap <> nil) then begin scanBitmap.Free; end; Exit; end; end; TThread.Synchronize(nil, procedure begin if (length(lblScanStatus.Text) > 10) then begin lblScanStatus.Text := '*'; end; lblScanStatus.Text := lblScanStatus.Text + '*'; if (ReadResult <> nil) then begin memo1.Lines.Insert(0,ReadResult.Text); if Memo1.Lines.Count >= 10 then Memo1.Lines.Clear; end; if (scanBitmap <> nil) then begin scanBitmap.Free; end; FreeAndNil(ReadResult); end); end); end; { Make sure the ca mera is released if you're going away. } function TMainForm.AppEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; begin case AAppEvent of TApplicationEvent.WillBecomeInactive: CameraComponent1.Active := False; TApplicationEvent.EnteredBackground: CameraComponent1.Active := False; TApplicationEvent.WillTerminate: CameraComponent1.Active := False; end; end; initialization finalization //CameraCallBack.Free; end.
unit xtMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, Buttons, XMLTool, Menus, ExtCtrls; type TfrmXmlToolEditor = class(TForm) edXPath: TEdit; Label1: TLabel; edFileName: TEdit; Label2: TLabel; btnLoad: TBitBtn; btnSave: TBitBtn; odLoadXML: TOpenDialog; sdSaveXML: TSaveDialog; edNodeText: TEdit; Label3: TLabel; ppmNodeMenu: TPopupMenu; mniNodeSetEmpty: TMenuItem; mniEraseNode: TMenuItem; mniCopy: TMenuItem; mniPaste: TMenuItem; N1: TMenuItem; Panel1: TPanel; edXMLSource: TRichEdit; Splitter2: TSplitter; tvXMLTree: TTreeView; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnLoadClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure tvXMLTreeClick(Sender: TObject); procedure edXPathKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edNodeTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure pgcMainChange(Sender: TObject); procedure tvXMLTreeContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); procedure mniNodeSetEmptyClick(Sender: TObject); procedure mniEraseNodeClick(Sender: TObject); procedure mniCopyClick(Sender: TObject); procedure mniPasteClick(Sender: TObject); private FXmlTool: TXMLTool; public procedure RefreshViewer; end; var frmXmlToolEditor: TfrmXmlToolEditor; implementation {$R *.dfm} uses XMLIntf, XMLDoc, Clipbrd; procedure TfrmXmlToolEditor.FormCreate(Sender: TObject); begin FXmlTool := TXMLTool.Create; end; procedure TfrmXmlToolEditor.FormDestroy(Sender: TObject); begin FXmlTool.Free; end; procedure TfrmXmlToolEditor.RefreshViewer; procedure DrawTree(TreeNode: TTreeNode; XPath: string); var SubNode: TTreeNode; begin if (XPath <> '') and (XPath[Length(XPath)] <> '/') then XPath := XPath + '/'; with FXmlTool.SubNodes[XPath] do repeat if NodeIsText then begin SubNode := tvXMLTree.Items.AddChildObject( TreeNode, NodeName + ' = ''' + NodeText + '''', Pointer(Node) ); end else begin SubNode := tvXMLTree.Items.AddChildObject( TreeNode, NodeName, Pointer(Node) ); end; if NodeHasChild or NodeHasAttr then DrawTree(SubNode, NodeXPath); until not Next; if XPath = edXPath.Text + '/' then begin tvXMLTree.Selected := TreeNode; TreeNode.Expanded := True; end; end; begin edXPath.Enabled := True; edNodeText.Enabled := True; tvXMLTree.Items.Clear; DrawTree(tvXMLTree.Items.AddChildObject(nil, '/', Pointer(FXmlTool.Node['/'])), '/'); tvXMLTree.Items[0].Expanded := True; if (tvXMLTree.Selected = nil) and (tvXMLTree.Items.Count > 0) then tvXMLTree.Selected := tvXMLTree.Items[0]; tvXMLTreeClick(nil); end; procedure TfrmXmlToolEditor.btnLoadClick(Sender: TObject); begin if odLoadXML.Execute then begin FXmlTool.LoadFromFile(odLoadXML.FileName); edFileName.Text := odLoadXML.FileName; RefreshViewer; end; end; procedure TfrmXmlToolEditor.btnSaveClick(Sender: TObject); begin sdSaveXML.FileName := edFileName.Text; if sdSaveXML.Execute then begin FXmlTool.SaveToFile(sdSaveXML.FileName); edFileName.Text := sdSaveXML.FileName; end; end; procedure TfrmXmlToolEditor.tvXMLTreeClick(Sender: TObject); begin if tvXMLTree.Selected <> nil then begin edXPath.Text := FXMLTool.NodeToXPath(IXMLNode(tvXMLTree.Selected.Data)); edNodeText.Text := FXmlTool[edXPath.Text]; edXMLSource.Text := FXmlTool.NodeXML[edXPath.Text]; end; end; procedure TfrmXmlToolEditor.edXPathKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 13 then begin if not FXmlTool.NodeExists(edXPath.Text) then FXmlTool[edXPath.Text] := edNodeText.Text else edNodeText.Text := FXmlTool[edXPath.Text]; RefreshViewer; end; end; procedure TfrmXmlToolEditor.edNodeTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = 13 then begin FXmlTool[edXPath.Text] := edNodeText.Text; RefreshViewer; if edNodeText.Text <> FXmlTool[edXPath.Text] then edNodeText.Text := FXmlTool[edXPath.Text]; end; end; procedure TfrmXmlToolEditor.pgcMainChange(Sender: TObject); begin RefreshViewer; end; procedure TfrmXmlToolEditor.tvXMLTreeContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean); var NodeRect: TRect; begin if tvXMLTree.Selected <> nil then begin NodeRect := tvXMLTree.Selected.DisplayRect(True); if (MousePos.X > NodeRect.Left) and (MousePos.X < NodeRect.Right) and (MousePos.Y > NodeRect.Top) and (MousePos.Y < NodeRect.Bottom) then begin MousePos := tvXMLTree.ClientToScreen(MousePos); ppmNodeMenu.Popup(MousePos.X, MousePos.Y); end; end; Handled := True; end; procedure TfrmXmlToolEditor.mniCopyClick(Sender: TObject); begin Clipboard.AsText := FXMLTool.NodeXML[edXPath.Text]; end; procedure TfrmXmlToolEditor.mniPasteClick(Sender: TObject); begin FXMLTool.NodeXML[edXPath.Text] := Clipboard.AsText; RefreshViewer; end; procedure TfrmXmlToolEditor.mniNodeSetEmptyClick(Sender: TObject); begin FXMLTool.NodeSetEmpty(edXPath.Text); edNodeText.Text := FXMLTool[edXPath.Text]; RefreshViewer; end; procedure TfrmXmlToolEditor.mniEraseNodeClick(Sender: TObject); var XPath: string; begin XPath := FXMLTool.ExtractNodePath(edXPath.Text); FXMLTool.NodeErase(edXPath.Text); edXPath.Text := XPath; edNodeText.Text := FXMLTool[edXPath.Text]; RefreshViewer; end; end.
unit d01.coverage.CreditCard; interface uses DateUtils; type TCreditCard = class public constructor Create(expDate: TDateTime); function IsExpired(): Boolean; end; implementation var expirationDate: TDateTime; constructor TCreditCard.Create(expDate: TDateTime); begin expirationDate := expDate; end; function TCreditCard.IsExpired(): Boolean; var today: TDateTime; localExpDate: TDateTime; begin localExpDate := TTimeZone.Local.ToLocalTime(expirationDate); today := today; if (CompareDate(today, localExpDate) < 0) then Result := True else Result := False end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.4 2004.02.03 5:45:42 PM czhower Name changes Rev 1.3 24/01/2004 23:16:26 CCostelloe Removed short-circuits Rev 1.2 24/01/2004 19:28:28 CCostelloe Cleaned up warnings Rev 1.1 5/2/2003 01:16:00 PM JPMugaas Microware OS/9 and MPE/iX support. Rev 1.0 4/21/2003 05:32:08 PM JPMugaas Filename converstion rourintes. Todo: Somehow, figure out what to do about pathes and add more platform support. } unit IdOSFileName; interface {$i IdCompilerDefines.inc} uses IdBaseComponent, IdFTPCommon; function FileNameUnixToVMS(const AUnixFileName : String) : String; function FileNameVMSToUnix(const AVMSFileName : String) : String; function FileNameMSDOSToUnix(const AMSDOSFileName : String) : String; function FileNameUnixToMSDOS(const AUnixFileName : String):String; function FileNameUnixToWin32(const AUnixFileName : String):String; function FileNameWin32ToUnix(const AWin32FileName : String): String; function FileNameUnixToVMCMS(const AUnixFileName : String): String; function FileNameVMCMSToUnix(const AVMCMSFileName : String): String; function FileNameUnixToMUSICSP(const AUnixFileName : String) : String; function FileNameMUSICSPToUnix(const AMUSICSPFileName : String) : String; function FileNameUnixToMVS(const AUnixFileName : String; const AUserID : String; const AUseAnotherID : Boolean=False) : String; function FileNameMVSToUnix(const AMVSFileName : String) : String; function FileNameUnixToMPEiXTraditional(const AUnixFileName : String; const AGroupName : String=''; const AAcountName : String=''): String; function FileNameUnixToMPEiXHFS(const AUnixFileName : String; const IsRoot : Boolean=False): String; function FileNameUnixToOS9(const AUnixFileName : String) : String; implementation uses IdException, IdGlobal, IdGlobalProtocols, SysUtils; function EnsureValidCharsByValidSet(const AFilePart, AValidChars : String; const AReplaceWith : String='_'): String; var i : Integer; begin Result := ''; for i := 1 to Length(AFilePart) do begin if CharIsInSet(AFilePart, i, AValidChars) then begin Result := Result + AFilePart[i]; end else begin Result := Result + AReplaceWith; end; end; end; function EnsureValidCharsByInvalidSet(const AFilePart, AInvalidChars : String; const AReplaceWith : String='_'): String; var i : Integer; begin Result := ''; for i := 1 to Length(AFilePart) do begin if not CharIsInSet(AFilePart, i, AInValidChars) then begin Result := Result + AFilePart[i]; end else begin Result := Result + AReplaceWith; end; end; end; function FileNameUnixToVMS(const AUnixFileName : String) : String; var LFName, LFExt : String; {sample VMS fully qualified filename: DKA0:[MYDIR.SUBDIR1.SUBDIR2]MYFILE.TXT;1 Note VMS uses 39 chars for name and type valid chars are: letters A through Z numbers 0 through 9 underscore ( _ ) hyphen ( -) dollar sign ( $ ) See: http://www.uh.edu/infotech/services/documentation/vms/v0505.html } var VMS_Valid_Chars : String; begin VMS_Valid_Chars := CharRange('A','Z')+CharRange('0','9')+'_-$'; //VMS is case insensitive - UpperCase to simplify processing Result := UpperCase(AUnixFileName); LFName := Fetch(Result,'.'); LFExt := Fetch(Result,'.'); LFExt := Fetch(LFExt,';'); LFName := Copy(LFName,1,39); LFName := EnsureValidCharsByValidSet(LFName,VMS_Valid_Chars); LFExt := Copy(LFExt,1,39); LFExt := EnsureValidCharsByValidSet(LFExt,VMS_Valid_Chars); Result := LFName; if LFExt <>'' then begin Result := Result + '.'+LFExt; end; end; function FileNameVMSToUnix(const AVMSFileName : String) : String; begin Result := AVMSFileName; //We strip off the version marker because that doesn't make sense in //Win32 and Unix. In VMS, there's a crude type of version control in the file system where //different versions of the same file are kept. //For example, if you open IDABOUT.PAS;1, make a change, and save it, it is saved //as IDABOUT.PAS;2. Make a further change and save it and it will be saved as //IDABOUT.PAS;3. Result := Fetch(Result,';'); //VMS is case insensitive Result := LowerCase(AVMSFileName); end; function FileNameMSDOSToUnix(const AMSDOSFileName : String) : String; begin Result := LowerCase(AMSDOSFileName); end; function FileNameUnixToMSDOS(const AUnixFileName : String):String; var LFName, LFExt : String; //From: http://macinfo.its.queensu.ca/Mark/AMT2/AMTCrossPlatfrom.html //Window V3.1 and DOS file names compatibility: //Windows 3.1/DOS names cannot have more than eight characters and can //contain only the letters A through Z, the numbers 0 through 9 and the //following special characters: //underscore (_), dollar sign ($), tilde (~), exclamation point (!), //number sign (#), percent sign (%), ampersand (&), hyphen (-), braces ({}), parenthesis (), at sign (@), apostrophe ('), and the grave accent ('). //Note: Macintosh does not allow colin (:) in it's file name and supports upto 32 characters. var MSDOS_Valid_Chars : String; begin MSDOS_Valid_Chars := CharRange('A','Z')+CharRange('0','9')+'_$~!#%&-{}()@'''+Char(180); Result := UpperCase(AUnixFileName); LFName := Fetch(Result,'.'); LFName := Copy(LFName,1,8); LFName := EnsureValidCharsByValidSet(LFExt,MSDOS_Valid_Chars); LFExt := Fetch(Result,'.'); LFExt := Copy(LFExt,1,3); LFExt := EnsureValidCharsByValidSet(LFExt,MSDOS_Valid_Chars); Result := LFName; if LFExt <> '' then begin Result := Result + '.'+LFExt; end; end; function FileNameUnixToWin32(const AUnixFileName : String):String; //from: http://linux-ntfs.sourceforge.net/ntfs/concepts/filename_namespace.html const WIN32_INVALID_CHARS = '"*/:<>?\|' + #0; WIN32_INVALID_LAST = ' .'; //not permitted as the last character in Win32 begin Result := EnsureValidCharsByInvalidSet(AUnixFileName,WIN32_INVALID_CHARS); if Result <> '' then begin if CharIsInSet(Result, Length(Result), WIN32_INVALID_LAST) then begin Delete(Result,Length(Result),1); if Result = '' then begin Result := '_'; end; end; end; end; function FileNameWin32ToUnix(const AWin32FileName : String): String; //from http://linux-ntfs.sourceforge.net/ntfs/concepts/filename_namespace.html //const UNIX_INVALID_CHARS : TIdValidChars = [#0,'/']; begin Result := LowerCase(AWin32FileName); end; function FileNameUnixToVMCMS(const AUnixFileName : String): String; // From: CMS Introductory Guide at the University of Kentuckey // http://ukcc.uky.edu/~ukccinfo.391/cmsintro.html // Under CMS a file is identified by a fileid with three parts: the filename, the // filetype, and the filemode. The filemode, from this point on in this guide, will // always be A1. In most cases, the filemode is optional when referring to files. // The filename and filetype can contain from one to eight characters (letters, // numbers, and these seven special characters: @#$+-:_). Choose filenames and // filetypes that help to identify the contents of the file. var LFName, LFExt : String; Valid_VMCMS_Chars : String; begin Valid_VMCMS_Chars := CharRange('A','Z')+ CharRange('0','9')+'@#$+-:_'; Result := UpperCase(AUnixFileName); LFName := Fetch(Result,'.'); LFName := EnsureValidCharsByValidSet(LFExt,VALID_VMCMS_CHARS); LFName := Copy(LFName,1,8); LFExt := Fetch(Result,'.'); LFExt := EnsureValidCharsByValidSet(LFExt,VALID_VMCMS_CHARS); LFExt := Copy(LFExt,1,8); Result := LFName; if LFExt <> '' then begin Result := Result + '.'+LFExt; end; end; function FileNameVMCMSToUnix(const AVMCMSFileName : String): String; begin Result := LowerCase(AVMCMSFileName); end; function FileNameUnixToMUSICSP(const AUnixFileName : String) : String; { Obtained from a ftphelp.txt on a Music/SP Server The MUSIC/SP file system has a directory structure similar to that of DOS and Unix. The separator character between directory names is a backslash (\), but the FTP client can use either a slash (/) or a backslash (\). Directory names can be up to 17 characters. File names within a directory can be up to 17 characters. The total name, including directory names on the front, can be up to 50 characters. Upper/lower case is not significant in file names. Letters (A to Z), digits (0 to 9), and some special characters (including $ # @ _ + - . % & !) can be used, but the first character of each part must not be a digit or + - . % & !. } var Valid_MUSICSP : String; MUSICSP_Cant_Start : String; begin Valid_MUSICSP := CharRange('A','Z')+CharRange('0','9')+'$#@_+-.%&!'; MUSICSP_Cant_Start := CharRange('0','9')+ '+-.%!'; // note we have to do our vality checks before truncating the length in // case we need to replace the default replacement char and the length changes // because of that. Result := UpperCase(AUnixFileName); Result := EnsureValidCharsByValidSet(Result,VALID_MUSICSP); Result := Copy(Result,1,15); if Result <> '' then begin if CharIsInSet(Result, 1, MUSICSP_CANT_START) then begin if Length(Result) > 1 then begin Delete(Result,1,1); end else begin Result[1] := '_'; end; end; end; end; function FileNameMUSICSPToUnix(const AMUSICSPFileName : String) : String; begin Result := LowerCase(AMUSICSPFileName); end; function FileNameUnixToMVS(const AUnixFileName : String; const AUserID : String; const AUseAnotherID : Boolean=False) : String; const MVS_FQN_MAX_LEN = 44; MVS_MAX_QUAL_LEN = 8; var LQualifier : String; LMaxLen : Integer; LBuf : String; MVS_Valid_Qual_Chars : String; MVS_Valid_First_Char : String; begin MVS_Valid_Qual_Chars := CharRange('0','9')+CharRange('A','Z')+'@$#'; MVS_Valid_First_Char := CharRange('A','Z'); //in MVS, there's a maximum of 44 characters and MVS prepends a prefix with the userID and //sometimes process name. Thus, the dataset name can have 44 characters minus the user ID - 1 (for the dot) // //e.g. CZHOWER can have a fully qualified name with a maximum of 36 characters // JPMUGAAS can have a fully qualified name with a maximum of 35 characters // //if AUseAnotherID is true, we give a fully qualified name with a prefix in '' which //is called ticks. That permits someone to access another user's dataset. // //e.g. CZHOWER could access a dataset created by JPMUGAAS (named INDY.IDABOUT.PAS) // by using the name: // //'JPMUGAAS.INDY.IDABOUT.PAS' // //JPMUGAAS can access the same data with the name: // //INDY.IDABOUT.PAS // //where the JPMUGAAS. prefix is implied. LMaxLen := MVS_FQN_MAX_LEN - 1 - Length(AUserID); LBuf := UpperCase(AUnixFileName); Result := ''; repeat LQualifier := Fetch(LBuf,'.'); if LQualifier <>'' then begin repeat if ((CharIsInSet(LQualifier, 1, MVS_VALID_FIRST_CHAR))=False) then begin Delete(LQualifier,1,1); if LQualifier='' then begin break; end; end else begin Break; end; until False; end; //we do it this way in case the qualifier only had an invalid char such as # if LQualifier <> '' then begin LQualifier := EnsureValidCharsByValidSet(LQualifier,MVS_VALID_QUAL_CHARS,''); end; LQualifier := Copy(LQualifier,1,MVS_MAX_QUAL_LEN); if LQualifier <> '' then begin Result := Result + '.' +LQualifier; if Result<>'' then begin if Result[1]='.' then begin Delete(Result,1,1); end; end; if (Length(Result)>LMaxLen) or (LBuf='') then begin Result := Copy(Result,1,LMaxLen); Break; end; end; if LBuf = '' then begin Break; end; until False; if AUseAnotherID then begin Result := ''''+AUserID+'.'+Result+''''; end; end; function FileNameMVSToUnix(const AMVSFileName : String) : String; begin Result := LowerCase(AMVSFileName); end; { Note that Account name does not necessarily imply a username. When logging in, the user provides both the username and account. It's like the username is the key to a cabnet (several people can have their keys to that cabnit. The group name is like a drawer in a cabnet. That is only needed if you are logged in with an account and group but wish to access a file in a different group. That's how the manual described it. The MPE/iX file system is basically flat with an account, group, and file name. } function MPEiXValidateFIlePart(AFilePart : String) : String; var Valid_MPEIX_Start : String; Valid_MPEIX_FName : String; begin Valid_MPEIX_Start := CharRange('A','Z'); Valid_MPEIX_FName := Valid_MPEIX_Start + CharRange('0','9'); Result := UpperCase(AFilePart); if IndyPos('.',Result)>1 then begin Result := Fetch(Result,'.'); end; if Result<>'' then begin Result := EnsureValidCharsByValidSet(Result,VALID_MPEIX_FNAME,''); repeat if not CharIsInSet(Result, 1, VALID_MPEIX_START) then begin Delete(Result,1,1); if Result='' then begin break; end; end else begin Break; end; until False; end; //no more than 8 chars Result := COpy(Result,1,8); end; function FileNameUnixToMPEiXTraditional(const AUnixFileName : String; const AGroupName : String=''; const AAcountName : String=''): String; //based on http://docs.hp.com/mpeix/onlinedocs/32650-90871/32650-90871.html // //1) Starts with a letter - case insensitive //2) Contains only letters and numbers //3) No other charactors (a / is acceptable but it means a lockword which can cause // you to be unable to retreive the file //4) No more than 8 chars // //Note that fullname and groupname are 1 to 8 chars and follow the same rules //just to eliminate some double processing for tests var LBuf : String; begin Result := MPEiXValidateFIlePart(AUnixFileName); LBuf := MPEiXValidateFIlePart(AGroupName); if LBuf <> '' then begin //if no group, we skip the account part Result := Result + '.'+LBuf; LBuf := MPEIxValidateFilePart(AAcountName); if LBuf <> '' then begin Result := Result + '.'+LBuf; end; end; end; function FileNameUnixToMPEiXHFS(const AUnixFileName : String; const IsRoot : Boolean=False): String; //based on: http://docs.hp.com/mpeix/onlinedocs/32650-90492/32650-90492.html { http://docs.hp.com/mpeix/onlinedocs/32650-90492/32650-90492.html FS pathnames differ from MPE pathnames in the following ways: Names are separated with forward slashes (/), rather than dots. The order of the file name, group name, and account name are presented in reverse order compared to MPE syntax (/ACCT/GROUP/FILE versus FILE.GROUP.ACCT). Slash (/) at the beginning of a pathname indicates the root directory. Dot-slash (./) at the beginning of a pathname indicates the current working directory (CWD). The CWD is the directory in which you are currently working. Pathnames can be up to 1023 characters whereas traditional MPE names must be less than or equal to 26 characters (names can be up to 35 characters if a lockword is used). See Table 2-2 for CI restrictions. Using these conventions, the format of the MPE pathname MYFILE.PAYROLL.FINANCE appears as follows in HFS syntax: /FINANCE/PAYROLL/MYFILE In this example, it is assumed that MYFILE is a file under the PAYROLL group and FINANCE account. However, FINANCE and PAYROLL need not necessarily be an account and a group as they must in MPE syntax. Using HFS syntax, MYFILE could be a file under the PAYROLL HFS subdirectory, which is under the FINANCE HFS directory, which is under the root directory. } var MPEIX_Valid_Chars : String; MPEIX_CantStart : String; begin MPEIX_Valid_Chars := CharRange('a','z')+CharRange('A','Z')+CharRange('0','9')+'._-'; MPEIX_CantStart := '-'; Result := AUnixFileName; if Result<>'' then begin Result := EnsureValidCharsByValidSet(Result,MPEIX_VALID_CHARS,'_'); repeat if CharIsInSet(Result, 1, MPEIX_CANTSTART) then begin Delete(Result,1,1); if Result='' then begin break; end; end else begin Break; end; until False; end; //note that this for clarrifying that this is a HFS file instead of a Traditional //MPEiX file. //A file in the foot folder uses the / and a file in the current dir uses ./ if IsRoot then begin Result := '/'+Result; end else begin Result := './'+Result; end; Result := Copy(result,1,255); end; function FileNameUnixToOS9(const AUnixFileName : String) : String; //based on: //http://www.roug.org/soren/6809/os9guide/os9guide.pdf { Names can have one to 29 characters, all of which are used for matching. They must becin with an upper- or lower-case letter followed by any combination of the following characters: UpperCase letters: A - Z LowerCase letters: a - z decimal digits: 0 - 9 underscore: _ period: . } var OS9_Must_Start : String; OS9_Valid_Char : String; begin OS9_Must_Start := CharRange('a','z')+CharRange('A','Z'); OS9_Valid_Char := CharRange('0','9')+'_.'; Result := AUnixFileName; if Result<>'' then begin Result := EnsureValidCharsByValidSet(Result,OS9_VALID_CHAR,'_'); repeat if ((CharIsInSet(Result, 1, OS9_MUST_START))=False) then begin Delete(Result,1,1); if Result='' then begin break; end; end else begin Break; end; until False; end; Result := Copy(Result,1,29); end; end.
unit xdf_main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Mask, ToolEdit, ComCtrls; type TMainForm = class(TForm) feXMLFile: TFilenameEdit; btnDo: TButton; ProgressBar: TProgressBar; procedure btnDoClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation uses ddUtils, ddMailTools, l3Base, dt_Types, dt_Const, dt_Doc, dt_Sab, dt_Query, dt_SrchQueries, dt_LinkServ, Dt_ReNum, JclStreams, JclSimpleXML; {$R *.dfm} procedure TMainForm.btnDoClick(Sender: TObject); var I, J: Integer; l_BakFileName: string; l_DocIDStr: string; l_Elem: TJclSimpleXMLElem; l_ID: TDocID; l_Idx: Integer; l_Prop, l_GarProp: TJclSimpleXMLProp; l_XML: TJclSimpleXML; l_Q : TdtQuery; l_Res: ISabCursor; l_XMLIsUpdated: Boolean; begin if FileExists(feXMLFile.FileName) then begin Screen.Cursor := crHourGlass; btnDo.Enabled := False; ProgressBar.Visible := True; ProgressBar.Position := 0; l_XMLIsUpdated := False; try l3System.Msg2Log('Обработка файла %s', [feXMLFile.FileName]); l_XML := TJclSimpleXML.Create; try l_XML.LoadFromFile(feXMLFile.FileName); if l_XML.Root.Name = 'list' then begin ProgressBar.Max := l_XML.Root.Items.Count; for I := 0 to l_XML.Root.Items.Count - 1 do begin l_Elem := l_XML.Root.Items[I]; if l_Elem.Name = 'material' then begin l_GarProp := l_Elem.Properties.ItemNamed['garant']; if (l_GarProp <> nil) and (l_GarProp.Value = '') then begin l_Prop := l_Elem.Properties.ItemNamed['full_title']; if l_Prop <> nil then begin l_Q := SQText2Query(l_Prop.Value); try if (l_Q <> nil) and (l_Q.FoundList.Count > 0) then begin l_Res := l_Q.FoundList.MakeSabCursor([fId_Fld]); try if l_Res.Count = 1 then begin l_ID := PDocID(l_Res.GetItem(0))^; l_ID := LinkServer(CurrentFamily).Renum.GetExtDocID(l_ID); l_GarProp.IntValue := l_ID; l_XMLIsUpdated := True; end else begin if l_Res.Count <= 5 then begin l_DocIDStr := ''; for J := 0 to l_Res.Count - 1 do begin l_ID := PDocID(l_Res.GetItem(J))^; l_ID := LinkServer(CurrentFamily).Renum.GetExtDocID(l_ID); if J > 0 then l_DocIDStr := l_DocIDStr + ', '; l_DocIDStr := l_DocIDStr + IntToStr(l_ID); end; l3System.Msg2Log('"%s": документы %s', [l_Prop.Value, l_DocIDStr]); end else l3System.Msg2Log('"%s": %s', [l_Prop.Value, NumSuffix(l_Res.Count, 'документ', 'документа', 'документов')]); end; finally l_Res := nil; end; end else l3System.Msg2Log('"%s": не найдено ни одного документа', [l_Prop.Value]); finally FreeAndNil(l_Q); end; end; end; end else l3System.Msg2Log('Невалидное имя элемента: %s', [l_Elem.Name]); ProgressBar.Position := I; Application.ProcessMessages; end; end else l3System.Msg2Log('Неверный формат XML'); if l_XMLIsUpdated then begin l_BakFileName := ChangeFileExt(feXMLFile.FileName, '.bak'); DeleteFile(l_BakFileName); RenameFile(feXMLFile.FileName, l_BakFileName); l_XML.Options := [sxoAutoIndent, sxoAutoEncodeEntity]; l_XML.SaveToFile(feXMLFile.FileName); end; finally FreeAndNil(l_XML); end; finally Screen.Cursor := crDefault; btnDo.Enabled := True; end; end else MessageDlg('Файл не найден.', mtError, [mbOK], 0); end; end.
unit vtShockwaveEx; //////////////////////////////////////////////////////////////////////////////// // Библиотека : VT. // Назначение : Компонент для показа flash-ролика. // Версия : $Id: vtShockwaveEx.pas,v 1.51 2016/04/06 09:57:35 morozov Exp $ //////////////////////////////////////////////////////////////////////////////// (*------------------------------------------------------------------------------- $Log: vtShockwaveEx.pas,v $ Revision 1.51 2016/04/06 09:57:35 morozov Забыл Revision 1.50 2015/07/02 13:42:26 dinishev {Requestlink:602949503} Revision 1.49 2015/06/05 14:17:43 migel - change: работа с флешом, когда он не установлен в системе. Revision 1.48 2015/04/24 14:28:21 lulin - правильный include. Revision 1.47 2015/04/16 14:03:55 lulin - перерисовываем. Revision 1.46 2014/02/05 17:29:48 lulin - запускаем тесты сервера автоматизации. Revision 1.45 2013/10/02 11:38:09 morozov {RequestLink: 426675069} Revision 1.44 2012/11/01 09:42:28 lulin - забыл точку с запятой. Revision 1.43 2012/11/01 07:44:16 lulin - делаем возможность логирования процесса загрузки модулей. Revision 1.42 2012/02/07 10:49:46 gensnet http://mdp.garant.ru/pages/viewpage.action?pageId=335151860 Revision 1.41 2012/01/30 09:47:22 gensnet http://mdp.garant.ru/pages/viewpage.action?pageId=331613120 Revision 1.40 2012/01/18 09:15:58 gensnet http://mdp.garant.ru/pages/viewpage.action?pageId=266409753 Revision 1.39 2012/01/17 12:28:35 gensnet http://mdp.garant.ru/pages/viewpage.action?pageId=266409753 Revision 1.38 2012/01/13 11:35:39 gensnet http://mdp.garant.ru/pages/viewpage.action?pageId=266409753 Revision 1.37 2012/01/12 08:48:52 gensnet http://mdp.garant.ru/pages/viewpage.action?pageId=266409753 Revision 1.36 2012/01/11 13:08:22 gensnet http://mdp.garant.ru/pages/viewpage.action?pageId=266409753 для проверки на молебоксенной оболочке Revision 1.35 2011/10/11 09:11:07 lulin {RequestLink:272666285}. Revision 1.34 2011/09/29 13:06:43 lulin {RequestLink:278854662}. Revision 1.33 2011/07/05 14:38:59 lulin {RequestLink:272666656}. Revision 1.32 2011/06/17 10:16:27 lulin {RequestLink:259892691}. Revision 1.31 2011/05/06 14:28:10 lulin - правим IfDef'ы. Revision 1.30 2010/07/05 10:50:38 oman - fix: {RequestLink:222758113} Revision 1.29 2010/07/05 10:00:29 oman - fix: {RequestLink:222758113} Revision 1.28 2009/11/16 13:00:48 migel - change: отключили фикс (не всегда работает как нужно). Revision 1.27 2009/11/12 13:44:33 migel - fix: избавляемся от проблемы черных квадратов (К: 146900520). Revision 1.26 2009/04/22 16:38:41 lulin [$145098206]. Revision 1.25 2009/04/21 08:35:00 lulin [$124453728]. Revision 1.24 2009/04/20 11:18:45 lulin [$142610585]. Читаем флеш не через кишочки, а через временный файл. Revision 1.23 2009/02/19 06:30:54 oman - fix: Сообщаем об ошибках отрисовки (К-136254180) Revision 1.22 2009/02/05 14:14:17 lulin - <K>: 136261219. Revision 1.21 2009/02/05 09:49:18 lulin - <K>: 128289358. Revision 1.20 2009/02/04 09:08:46 oman - fix: Порядок деинициализации (К-136258579) Revision 1.19 2009/02/02 13:52:04 oman Комментарий Revision 1.18 2009/02/02 12:20:36 oman - fix: Пытаемся цеплять самостийный ocx (К-136255443) Revision 1.17 2009/01/29 14:55:08 lulin - <K>: 136253229. Заготовка приложения. Меряем время. Revision 1.16 2009/01/29 12:26:34 lulin - для тестового приложения не подправляем данные. Revision 1.15 2009/01/29 12:14:37 lulin http://mdp.garant.ru/pages/viewpage.action?pageId=136253229&focusedCommentId=136254375#comment-136254375 Revision 1.14 2009/01/29 11:59:44 lulin http://mdp.garant.ru/pages/viewpage.action?pageId=136253229&focusedCommentId=136254311#comment-136254311 Revision 1.13 2009/01/28 16:23:33 lulin - не читаем размеры лишний раз. Revision 1.12 2008/12/17 14:53:42 lulin - <K>: 127767427. Revision 1.11 2008/12/15 12:26:53 lulin - <K>: 127771001. Revision 1.10 2008/10/06 13:31:07 lulin - чистка кода. Revision 1.9 2008/09/30 12:42:27 lulin - если ролик не масштабируется, то подгоняем под него размеры компонента <K>: 119472469. Revision 1.8 2008/09/25 08:26:10 oman - fix: Артефакты после загрузки (К-119472687) Revision 1.7 2008/09/12 07:46:40 oman - fix: Обрабатываем шорткаты до ActiveX (К-115344251) Revision 1.6 2008/08/21 09:32:10 mmorozov - new behaviour: проверяем результат при работе с методами потока, плюс свойство IsLoadFromStreamSupported (<K> - 108626065); Revision 1.5 2008/08/13 11:43:59 mmorozov - new: загрузка ролика по требованию (K<104432737>); Revision 1.4 2008/07/25 04:32:57 mmorozov - new: опубликован компонент для показа flash; Revision 1.3 2008/07/03 09:00:25 mmorozov - change: компонент flash переехал в библиотеку VT. Revision 1.2 2008/07/03 05:51:02 mmorozov - new: горячие клавиши во flash (K<97846208>). Revision 1.1 2008/07/03 05:21:05 mmorozov - new: местный компонента для работы с flash-роликом. -------------------------------------------------------------------------------*) {$Include vtDefine.inc} interface {$If not defined(NoFlash)} uses Messages, Windows, SysUtils, Classes, Controls, OleCtrls, ExtCtrls, Forms, ActiveX {$IFNDEF VER130} , Types {$ENDIF}, ShockwaveFlashObjects_TLB ; type _afwShortcutsHandler_Parent_ = TShockwaveFlash; {$Include afwShortcutsHandler.imp.pas} TvtShockwaveFlashEx = class(_afwShortcutsHandler_) private // fields f_WasDown : boolean; f_OleObject : IOleObject; f_PaintCount : Integer; f_IsLoadByRequest : Boolean; f_NeedDropAlignOnLoad : Boolean; f_ReCreateWndTimer : TTimer; procedure pm_SetNeedDropAlignOnLoad(const Value: Boolean); private // events f_OnMouseDown : TMouseEvent; f_OnMouseUp : TMouseEvent; f_OnMouseMove : TMouseMoveEvent; f_OnClick : TNotifyEvent; f_OnLoadFlash : TNotifyEvent; f_OnError : TNotifyEvent; f_OnChangeFrameInFlash : TNotifyEvent; public LoadedWidth : Integer; LoadedHeight : Integer; private f_Width : Integer; f_Height : Integer; f_ParentResizeSet : Boolean; private // methods procedure DoOnChangeFrameInFlash; {* - Обработчик изменения фрейма из-за нажатия ссылки. } procedure DoOnLoadFlash; {* - вызвать событие загрузки ролика. } procedure CreateReCreateWndTimer; {* - создает и запускает таймер для вызова ReCreateWnd. } procedure DestroyReCreateWndTimer; procedure ReCreateWndWithTimer; procedure OnReCreateWndTimer(Sender: TObject); procedure ParentResize(aSender : TObject); public procedure FitToParent; procedure CheckDimensions; private procedure SetParent(AParent: TWinControl); override; private // messages procedure WMPaint(var Message: TWMPaint); message WM_Paint; {-} private // property methods function pm_GetIsLoadFromStreamSupported: Boolean; {* - определяет доступна ли загрузка из потока для установленной версии flash-а. } private // properties property IsLoadByRequest: Boolean read f_IsLoadByRequest write f_IsLoadByRequest; {* - определяет необходимость загрузки ролика по требованию. } protected // methods procedure WndProc(var Message:TMessage); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure Click; override; procedure InitControlInterface(const Obj: IUnknown); override; procedure Resize; override; public // methods destructor Destroy; override; procedure LoadMovieFromStream(Src: TStream); procedure LoadByRequest; {* - загрузить ролик по требованию. } public // properties property IsLoadFromStreamSupported: Boolean read pm_GetIsLoadFromStreamSupported; {* - определяет доступна ли загрузка из потока для установленной версии flash-а. } property NeedDropAlignOnLoad: Boolean read f_NeedDropAlignOnLoad write pm_SetNeedDropAlignOnLoad; published // properties property OnMouseDown: TMouseEvent read f_OnMouseDown write f_OnMouseDown; property OnMouseUp: TMouseEvent read f_OnMouseUp write f_OnMouseUp; property OnMouseMove: TMouseMoveEvent read f_OnMouseMove write f_OnMouseMove; property OnClick: TNotifyEvent read f_OnClick write f_OnClick; property OnLoadFlash: TNotifyEvent read f_OnLoadFlash write f_OnLoadFlash; {* - событие загрузки flash, для загрузки по требованию. } property OnError: TNotifyEvent read f_OnError write f_OnError; property OnChangeFrameInFlash: TNotifyEvent read f_OnChangeFrameInFlash write f_OnChangeFrameInFlash; end; {$IfEnd} implementation {$If not defined(NoFlash)} uses ComObj, l3Base, l3MinMax, l3Stream, l3Types, l3FileUtils, // vtShockwaveFix, OvcConst, OvcBase, ZLib {$If not defined(NoScripts)} , vtFlashWordsPack {$IfEnd} //not NoScripts ; {$Include afwShortcutsHandler.imp.pas} var g_Handle: THandle = 0; g_Factory: IClassFactory = nil; type TDLLGetClassObject = function (const CLSID, IID: TGUID; var Obj): HResult; stdcall; THackOleControl = class(TWinControl) private FControlData: PControlData; FRefCount: Longint; FEventDispatch: TEventDispatch; FObjectData: HGlobal; FOleObject: IOleObject; end; procedure FreeFlash; begin g_Factory := nil; if g_Handle <> 0 then FreeLibrary(g_Handle); g_Handle := 0; end; function GetFlashFactory: IClassFactory; var l_Name: String; l_Proc: TDLLGetClassObject; begin if g_Factory = nil then begin l_Name := ExtractFilePath(ParamStr(0))+'flash.ocx'; if FileExists(l_Name) then begin g_Handle := LoadLibrary(PChar(l_Name)); l_Proc := TDLLGetClassObject(GetProcAddress(g_Handle, 'DllGetClassObject')); if not Succeeded(l_Proc(CLASS_ShockwaveFlash, IClassFactory, g_Factory)) then g_Factory := nil; end; end; Result := g_Factory; end; procedure TvtShockwaveFlashEx.InitControlInterface(const Obj: IUnknown); var l_Obj: IShockwaveFlash; l_OLE: IOLEObject; l_Factory: IClassFactory; begin f_OleObject := Obj as IOleObject; // ПРИ СМЕНЕ ВЕРСИИ ФЛЕША В ОБОЛОЧКЕ ПРОВЕРИТЬ СРАВНЕНИЕ FlashVersion if (Obj = nil) or (Supports(Obj, IShockwaveFlash, l_Obj) and (l_Obj.FlashVersion <> $90000)) then begin // Если версия не устраивает l_Obj := nil; l_Factory := GetFlashFactory; if Assigned(l_Factory) then begin if Succeeded(l_Factory.CreateInstance(nil, IOLEObject, l_OLE)) then begin // всхачили f_OleObject := l_OLE; THackOleControl(Self).FOleObject := l_OLE; end; end; end; end; procedure TvtShockwaveFlashEx.LoadMovieFromStream(Src: TStream); var l_F : Tl3FileStream; l_N : String; begin l_N := l3GetTempFileName('fl'); l_F := Tl3FileStream.Create(l_N, l3_fmWrite); try l3CopyStream(Src, l_F); finally FreeAndNil(l_F); end;//try..finally LoadMovie(0, l_N); DeleteFile(l_N); end; (* var unCompress: TStream; Mem, Mem2: TMemoryStream; SRCSize: longint; PersistStream: IPersistStreamInit; SAdapt: TStreamAdapter; ISize: int64; B: byte; ASign: array [0..2] of char; isCompress: boolean; ZStream: TDeCompressionStream; begin // prepare src movie Src.Read(ASign, 3); isCompress := ASign = 'CWS'; if isCompress then begin unCompress := TMemoryStream.Create; ASign := 'FWS'; unCompress.Write(ASign, 3); unCompress.CopyFrom(Src, 1); // version SRC.Read(SRCSize, 4); unCompress.Write(SRCSize, 4); ZStream := TDeCompressionStream.Create(Src); try unCompress.CopyFrom(ZStream, SRCSize - 8); finally ZStream.free; end; unCompress.Position := 0; end else begin Src.Position := Src.Position - 3; SRCSize := Src.Size - Src.Position; unCompress := Src; end; // store "template" EmbedMovie := false; f_OleObject.QueryInterface(IPersistStreamInit, PersistStream); OleCheck(PersistStream.GetSizeMax(ISize)); Mem := TMemoryStream.Create; Mem.SetSize(ISize); SAdapt := TStreamAdapter.Create(Mem); OleCheck(PersistStream.Save(SAdapt, true)); SAdapt.Free; // insetr movie to "template" Mem.Position := 1; Mem2 := TMemoryStream.Create; B := $66; // magic flag: "f" - embed swf; "g" - without swf; Mem2.Write(B, 1); Mem2.CopyFrom(Mem, 3); Mem2.Write(SRCSize, 4); Mem2.CopyFrom(unCompress, SRCSize); Mem2.CopyFrom(Mem, Mem.Size - Mem.Position); // load activeX data Mem2.Position := 0; SAdapt := TStreamAdapter.Create(Mem2); OleCheck(PersistStream.Load(SAdapt)); SAdapt.Free; // free all Mem2.Free; Mem.Free; PersistStream := nil; if isCompress then unCompress.Free; end;*) procedure TvtShockwaveFlashEx.WMPaint(var Message: TWMPaint); //message WM_Paint; {-} var PS: TPaintStruct; begin if IsLoadByRequest then begin (* BeginPaint(Handle, PS); EndPaint(Handle, PS);*) inherited; DoOnLoadFlash; Invalidate; end else try Inc(f_PaintCount); try if (f_PaintCount > 1) then Exit; Assert(f_PaintCount = 1); inherited; finally Dec(f_PaintCount); end;//try..finally except // - ловим все исключения if Assigned(f_OnError) then f_OnError(Self); end;//try..except end; procedure TvtShockwaveFlashEx.WndProc(var Message: TMessage); var x,y : Integer; xy : TPoint; ShiftState : TShiftState;//cga l_CF : Integer; begin if (Message.Msg >= WM_MOUSEFIRST) and (Message.Msg <= WM_MOUSELAST) then begin if (Message.Msg <> WM_MOUSEWHEEL) then begin if not (csDesigning in ComponentState) then begin l_CF := CurrentFrame; try ShiftState:=KeysToShiftState(TWMMouse(Message).Keys);//cga x:=TSmallPoint(Message.LParam).x; y:=TSmallPoint(Message.LParam).y; case Message.Msg of CM_MOUSELEAVE: f_WasDown:=false; WM_LBUTTONDOWN: begin MouseDown(mbLeft,ShiftState,x,y); f_WasDown:=true; end; WM_RBUTTONDOWN: f_WasDown:=true; WM_RBUTTONUP: if (PopupMenu<>nil) and (f_WasDown) then begin f_WasDown:=false; xy.X:=x; xy.Y:=y; xy:=ClientToScreen(xy); PopupMenu.Popup(xy.X,xy.Y); end; WM_LBUTTONUP: begin MouseUp(mbLeft,ShiftState,x,y); f_WasDown:=false; end; WM_MOUSEMOVE: MouseMove(ShiftState,x,y); end; // if (((Message.Msg=WM_RBUTTONDOWN) or (Message.Msg=WM_RBUTTONUP)) and not Menu) then Message.Result := 0 else inherited WndProc(Message); Exit; finally if (l_CF <> CurrentFrame) then begin CheckDimensions; DoOnChangeFrameInFlash; end; end;//try..finally end;//not (csDesigning in ComponentState) end//Message.Msg <> WM_MOUSEWHEEL else begin if not (csDesigning in ComponentState) then begin if (Parent <> nil) then begin // Транслировать событие родителю - не получается, поэтому приравниваем // его к скроллированию if (TWMMouseWheel(Message).WheelDelta < 0) then begin Parent.Perform(WM_VSCROLL, SB_LINEDOWN, 0); Parent.Perform(WM_VSCROLL, SB_LINEDOWN, 0); end//TWMMouseWheel(Message).WheelDelta < 0 else if (TWMMouseWheel(Message).WheelDelta > 0) then begin Parent.Perform(WM_VSCROLL, SB_LINEUP, 0); Parent.Perform(WM_VSCROLL, SB_LINEUP, 0); end;//TWMMouseWheel(Message).WheelDelta > 0 Exit; end;//Parent <> nil end;//not (csDesigning in ComponentState) end;//Message.Msg <> WM_MOUSEWHEEL end;//Message.Msg >= WM_MOUSEFIRST inherited WndProc(Message); end; procedure TvtShockwaveFlashEx.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(f_OnMouseDown) then begin f_OnMouseDown(Self, Button, Shift, X, Y); end; end; procedure TvtShockwaveFlashEx.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Assigned(f_OnMouseUp) then begin f_OnMouseUp(Self, Button, Shift, X, Y); end; if f_WasDown Then Click; end; procedure TvtShockwaveFlashEx.MouseMove(Shift: TShiftState; X, Y: Integer); begin if Assigned(f_OnMouseMove) then f_OnMouseMove(Self, Shift, X, Y); end; procedure TvtShockwaveFlashEx.Click; begin if Assigned(f_OnClick) then f_OnClick(Self); end; procedure TvtShockwaveFlashEx.Resize; begin inherited; // http://mdp.garant.ru/pages/viewpage.action?pageId=266409753 // not IsLoadByRequest - т.к. на х64 может падать при Resize, который происходит еще до DoOnLoadFlash if not IsLoadByRequest then ReCreateWndWithTimer; end; procedure TvtShockwaveFlashEx.ReCreateWndWithTimer; begin DestroyReCreateWndTimer; try ReCreateWnd; except // может случиться на x64 системе - http://mdp.garant.ru/pages/viewpage.action?pageId=266409753 on EOleError do CreateReCreateWndTimer; end; end; procedure TvtShockwaveFlashEx.CreateReCreateWndTimer; begin f_ReCreateWndTimer := TTimer.Create(nil); f_ReCreateWndTimer.Enabled := false; try f_ReCreateWndTimer.OnTimer := OnReCreateWndTimer; f_ReCreateWndTimer.Interval := 200; finally f_ReCreateWndTimer.Enabled := true; end;//try..finally end; procedure TvtShockwaveFlashEx.OnReCreateWndTimer(Sender: TObject); begin ReCreateWndWithTimer; end; procedure TvtShockwaveFlashEx.DestroyReCreateWndTimer; begin if f_ReCreateWndTimer <> nil then begin l3Free(f_ReCreateWndTimer); f_ReCreateWndTimer := nil; end; end; destructor TvtShockwaveFlashEx.Destroy; begin DestroyReCreateWndTimer; inherited Destroy; end; procedure TvtShockwaveFlashEx.DoOnLoadFlash; begin IsLoadByRequest := False; ReCreateWndWithTimer; // http://mdp.garant.ru/pages/viewpage.action?pageId=331613120 if Assigned(f_OnLoadFlash) then begin f_Height := 0; // http://mdp.garant.ru/pages/viewpage.action?pageId=335151860 f_OnLoadFlash(Self); CheckDimensions; end;//Assigned(f_OnLoadFlash) end; procedure TvtShockwaveFlashEx.ParentResize(aSender : TObject); begin FitToParent; end; type THackWinControl = class(TWinControl) end;//THackWinControl procedure TvtShockwaveFlashEx.FitToParent; begin Assert(Parent <> nil); if (Parent = nil) then Exit; (* if (f_Width > Parent.Width) OR (f_Height > Parent.Height) then*) begin Align := alNone; if (f_Width > Parent.Width) then begin Left := 0; Width := f_Width; end//f_Width > Parent.Width else begin Left := (Parent.Width - f_Width) div 2; //Width := Parent.Width; Width := f_Width; end;//f_Width > Parent.Width if true // http://mdp.garant.ru/pages/viewpage.action?pageId=272666285 {(f_Height > Parent.Height)} then begin Top := 0; //http://mdp.garant.ru/pages/viewpage.action?pageId=426675069 if (f_Height > Parent.Height) or (f_Height > Height) then Height := f_Height; end//f_Height > Parent.Height else begin Top := (Parent.Height - f_Height) div 2; //Height := Parent.Height; Height := f_Height end;//f_Height > Parent.Height end//f_Width > Parent.Width (* else Align := alClient*); end; procedure TvtShockwaveFlashEx.CheckDimensions; var l_LoadedOrParentHeight: Integer; begin if (ScaleMode = 3) AND ((Align <> alClient) or NeedDropAlignOnLoad) then begin (* Width := Trunc(TGetPropertyAsNumber('_root', 8)); Height := Trunc(TGetPropertyAsNumber('_root', 9));*) (* Width := Max(1024, Trunc(TGetPropertyAsNumber('/', 8))); Height := Max(768, Trunc(TGetPropertyAsNumber('/', 9)));*) LoadedWidth := Trunc(TGetPropertyAsNumber('/', 8)); LoadedHeight := Trunc(TGetPropertyAsNumber('/', 9)); {$If Defined(nsTest) AND not Defined(InsiderTest)} f_Width := LoadedWidth; f_Height := LoadedHeight; {$Else} f_Width := Min(5000, LoadedWidth); // Может так получиться, что LoadedHeight посчитана неправильно и схема // не влезет по высоте // http://mdp.garant.ru/pages/viewpage.action?pageId=426675069 l_LoadedOrParentHeight := Max(Parent.Height, LoadedHeight); // используем максимальную высоту из всех открытых фреймов, чтобы не было // http://mdp.garant.ru/pages/viewpage.action?pageId=335151860 f_Height := Max(f_Height, Min(5000, (*LoadedHeight*)l_LoadedOrParentHeight)); {$IfEnd} if (AlignMode = 5) then AlignMode := 15; // http://mdp.garant.ru/pages/viewpage.action?pageId=278854662&focusedCommentId=288788048#comment-288788048 if NeedDropAlignOnLoad then begin NeedDropAlignOnLoad := false; if (AlignMode <> 15) then Align := alNone; end;//NeedDropAlignOnLoad if (f_Width <> Width) OR (f_Height <> Height) then begin if (AlignMode = 15) then begin if (Parent = nil) then Exit; f_ParentResizeSet := true; THackWinControl(Parent).OnResize := ParentResize; FitToParent; end//AlignMode = 15 else begin if (Parent <> nil) then begin Parent.Perform(WM_VSCROLL, SB_TOP, 0); Parent.Perform(WM_HSCROLL, SB_TOP, 0); end;//Parent <> nil Width := f_Width; Height := f_Height; end;//AlignMode = 15 end;//f_Width <> Width end;//ScaleMode = 3.. end; procedure TvtShockwaveFlashEx.SetParent(AParent: TWinControl); begin if f_ParentResizeSet then begin if (Parent <> nil) then THackWinControl(Parent).OnResize := nil; f_ParentResizeSet := false; inherited; if (Parent <> nil) then begin THackWinControl(Parent).OnResize := ParentResize; f_ParentResizeSet := true; end;//Parent <> nil end//AlignMode = 15 else inherited; end; procedure TvtShockwaveFlashEx.LoadByRequest; begin IsLoadByRequest := True; Invalidate; end; function TvtShockwaveFlashEx.pm_GetIsLoadFromStreamSupported: Boolean; (*var l_Stream : IPersistStreamInit; l_Size : Int64; l_Error : HResult;*) begin Result := true; (* if Supports(f_OleObject, IPersistStreamInit, l_Stream) then begin l_Error := l_Stream.GetSizeMax(l_Size); Result := l_Error = S_OK; // Загрузка из потока может не поддерживаться установленной версией ActiveX, // про другие ошибки сообщим: if not Result and (l_Error <> E_NOTIMPL) then OleCheck(l_Error); end else Result := False;*) end; procedure TvtShockwaveFlashEx.pm_SetNeedDropAlignOnLoad( const Value: Boolean); begin if (f_NeedDropAlignOnLoad <> Value) then begin f_NeedDropAlignOnLoad := Value; if NeedDropAlignOnLoad then ParentColor := True; end;//f_NeedDropAlignOnLoad <> Value end; type PCoCreateInstance = ^TCoCreateInstance; TCoCreateInstance = function(const clsid: TCLSID; unkOuter: IUnknown; dwClsContext: Longint; const iid: TIID; out pv): HResult; stdcall; var g_CoCreateInstance: TCoCreateInstance = nil; function CoCreateInstanceHook(const clsid: TCLSID; unkOuter: IUnknown; dwClsContext: Longint; const iid: TIID; out pv): HResult; stdcall; var l_FlashFactory: IClassFactory; l_OLEObject: IOLEObject; begin Result := g_CoCreateInstance(clsid, unkOuter, dwClsContext, iid, pv); if ((Result <> S_OK) and IsEqualCLSID(clsid, CLASS_ShockwaveFlash)) then begin l_FlashFactory := GetFlashFactory; if (Assigned(l_FlashFactory) and Succeeded(l_FlashFactory.CreateInstance(nil, IOLEObject, l_OLEObject))) then begin IOLEObject(pv) := l_OLEObject; Result := S_OK; end; end; end; procedure SetCoCreateInstanceHook; var l_Pointer: PAnsiChar; l_Protect: DWORD; begin l_Pointer := @CoCreateInstance; if (l_Pointer^ = AnsiChar($FF)) then begin Inc(l_Pointer); if (l_Pointer^ = AnsiChar($25)) then begin l_Pointer := PPointer(l_Pointer+1)^; g_CoCreateInstance := PCoCreateInstance (l_Pointer)^; VirtualProtect(l_Pointer, Sizeof(l_Pointer), PAGE_READWRITE, l_Protect); try PCoCreateInstance(l_Pointer)^ := @CoCreateInstanceHook; finally VirtualProtect(l_Pointer, Sizeof(l_Pointer), l_Protect, l_Protect); end; end; end; end; procedure TvtShockwaveFlashEx.DoOnChangeFrameInFlash; begin if Assigned(f_OnChangeFrameInFlash) then f_OnChangeFrameInFlash(Self); end; initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\gui\Garant\VT\vtShockwaveEx.pas initialization enter'); {$EndIf} SetCoCreateInstanceHook; // поддерживаем загрузку для "flash.ocx" напрямую l3System.AddExitProc(FreeFlash); RegisterClass(TvtShockwaveFlashEx); {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\gui\Garant\VT\vtShockwaveEx.pas initialization leave'); {$EndIf} finalization UnRegisterClass(TvtShockwaveFlashEx); {$IfEnd} end.
unit uchecksum; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TChecksum = class private public end; { TIBAN } TIBAN = class(TChecksum) private public function calcIBAN(iban: string): integer; function createChecksum(iban: string): string; function checkIBAN(iban: string): boolean; function createIBAN(countrycode, accountnumber, bankcode: string): string; end; { TGTIN } TGTIN = class(TChecksum) private public function createGTIN(gtin: string): string; function checkGTIN(gtin: string): boolean; function createChecksum(gtin: string): string; end; { TIMEI } TIMEI = class(TChecksum) private public function createIMEI(imei: string): string; function checkIMEI(imei: string): boolean; function createChecksum(imei: string): string; end; implementation { TIMEI } function TIMEI.createIMEI(imei: string): string; begin Result := imei + createChecksum(imei); end; function TIMEI.checkIMEI(imei: string): boolean; begin Result := createChecksum(imei) = '0'; end; function TIMEI.createChecksum(imei: string): string; var curr, number, checksum, i, add: integer; begin number := 0; for i := 1 to length(imei) do begin curr := StrToInt(imei[i]); //Wenn eine durch 2 teilbare Stelle erreicht ist, verdoppel die Zahl if i mod 2 = 0 then begin curr := curr * 2; end; //Wenn curr größer als 9 ist, bilde die Quersumme der Zahl und setze sie auf add if curr > 9 then begin add := 0; while (curr > 0) do begin add := add + curr mod 10; curr := curr div 10; end; end //Wenn nicht, dann setze add auf curr else add := curr; //Addiere add mit der number number := number + add; end; checksum := number mod 10; if checksum = 0 then Result := IntToStr(checksum) else Result := IntToStr(10 - checksum); end; { TGTIN } function TGTIN.createGTIN(gtin: string): string; begin Result := gtin + createChecksum(gtin); end; function TGTIN.checkGTIN(gtin: string): boolean; begin Result := StrToInt(createChecksum(gtin)) = 0; end; function TGTIN.createChecksum(gtin: string): string; var i: integer; checksum: integer; product: string; begin product := '1'; for i := 2 to length(gtin) do begin if product[i - 1] = '1' then product[i] := '3' else product[i] := '1'; end; checksum := 0; for i := 1 to length(gtin) do checksum := checksum + StrToInt(gtin[i]) * StrToInt(product[i]); checksum := checksum mod 10; if checksum > 0 then checksum := 10 - checksum; Result := IntToStr(checksum); end; { TIBAN } function TIBAN.calcIBAN(iban: string): integer; var k, n, rest: integer; c: char; begin n := length(iban); if (n < 5) or (n > 34) then exit; rest := 0; k := 5; repeat // Zeichen der IBAN in geänderter Reihenfolge per Modulo-97 prüfen c := iban[k]; case c of '0'..'9': // Ziffer als solche berücksichtigen rest := (rest * 10 + Ord(c) - 48) mod 97; 'A'..'Z': // 'A' wie '10', 'B' wie '11' usw. rest := (rest * 100 + Ord(c) - 55) mod 97 else exit end; Inc(k); if k > n then k := 1 until k = 5; Result := rest; end; function TIBAN.createChecksum(iban: string): string; var checksum: string; rest: integer; begin rest := calcIBAN(iban); //Prüfsumme formatieren, falls nur einstellig führende Null anhängen if length(IntToStr(98 - rest)) = 1 then checksum := '0' + IntToStr(98 - rest) else checksum := IntToStr(98 - rest); Result := checksum; end; function TIBAN.checkIBAN(iban: string): boolean; var rest: integer; begin rest := calcIBAN(iban); Result := rest = 1; end; function TIBAN.createIBAN(countrycode, accountnumber, bankcode: string): string; var iban: string; begin iban := countrycode + '00' + bankcode + accountnumber; iban := countrycode + createChecksum(iban) + bankcode + accountnumber; Result := iban; end; end.
unit FCT.Setting; /// Factory ERP /// Date: 01-26-2020 /// Author: Marcio Silva /// Git: github.com/marciosdev /// Mail: marciosdev@icloud.com interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Win.Registry, Uni, PostgreSQLUniProvider; type TFCTSetting = class private function GetSetting(const psKeyName: string): Variant; public function GetPostgreServer: string; function GetPostgrePort: integer; function GetPostgreUser: string; function GetPostgrePass: string; function GetPostgreProvider: string; end; implementation uses FCT.Constant; { TFCTSetting } function TFCTSetting.GetPostgrePass: string; begin Result := GetSetting(SETTING_POSTGRE_PASS); end; function TFCTSetting.GetPostgrePort: integer; begin Result := GetSetting(SETTING_POSTGRE_PORT); end; function TFCTSetting.GetPostgreProvider: string; begin Result := SETTING_POSTGRE_PROVIDER; end; function TFCTSetting.GetPostgreServer: string; begin Result := GetSetting(SETTING_POSTGRE_SERVER); end; function TFCTSetting.GetPostgreUser: string; begin Result := GetSetting(SETTING_POSTGRE_USER); end; function TFCTSetting.GetSetting(const psKeyName: string): Variant; var oReg: TRegistry; begin Result := EmptyStr; oReg := TRegistry.Create(KEY_WRITE or KEY_WOW64_64KEY); try oReg.Lazywrite := False; oReg.RootKey := HKEY_LOCAL_MACHINE; oReg.OpenKeyReadOnly(HKEY_FACTORY); try Result := oReg.ReadString(psKeyName); except Result := oReg.ReadInteger(psKeyName); end; oReg.CloseKey; finally FreeAndNil(oReg); end; end; end.
_COLLECTION_ = class (TOwnedCollection) protected function GetItem (const aIndex : Integer) : _COLLECTION_ITEM_; procedure SetItem (const aIndex : Integer; const aValue : _COLLECTION_ITEM_); public constructor Create (const aOwner : TComponent); function Add : _COLLECTION_ITEM_; function FindItemID (const aID : Integer) : _COLLECTION_ITEM_; function Insert (const aIndex : Integer) : _COLLECTION_ITEM_; property Items [const aIndex : Integer] : _COLLECTION_ITEM_ read GetItem write SetItem; end;
unit kwPopEditorMergeCells; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorMergeCells.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_MergeCells // // *Формат:* aMergeType anEditorControl pop:editor:MergeCells // *Описание:* Объединяет выделенные ячейки таблицы. Параметры: aMergeType - Integer - константы // см. ArchiSystem.script (ed_maAll , ed_maHorz и ed_maVert). // *Пример:* // {code} // (ed_maAll focused:control:push pop:editor:MergeCells // {code} // *Результат:* Объединяет выделенный диапазон ячеек. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses evCustomEditor, tfwScriptingInterfaces, evCustomEditorWindow, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas} TkwPopEditorMergeCells = {final} class(_kwEditorWithToolsFromStackWord_) {* *Формат:* aMergeType anEditorControl pop:editor:MergeCells *Описание:* Объединяет выделенные ячейки таблицы. Параметры: aMergeType - Integer - константы см. ArchiSystem.script (ed_maAll , ed_maHorz и ed_maVert). *Пример:* [code] (ed_maAll focused:control:push pop:editor:MergeCells [code] *Результат:* Объединяет выделенный диапазон ячеек. } protected // realized methods procedure DoEditorWithTools(const aCtx: TtfwContext; anEditor: TevCustomEditor); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorMergeCells {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses evEditorInterfaces, tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorMergeCells; {$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas} // start class TkwPopEditorMergeCells procedure TkwPopEditorMergeCells.DoEditorWithTools(const aCtx: TtfwContext; anEditor: TevCustomEditor); //#UC START# *4F4DD89102E4_4F759F1803AF_var* var l_Table : IedTable; l_Range : IedRange; l_Cells : IedCells; l_MergeType : Integer; //#UC END# *4F4DD89102E4_4F759F1803AF_var* begin //#UC START# *4F4DD89102E4_4F759F1803AF_impl* l_Range := anEditor.Range; if l_Range <> nil then begin l_Table := l_Range.Table; if l_Table <> nil then l_Cells := l_Table.Cells else Assert(False, 'Не удалось получить таблицу!'); if aCtx.rEngine.IsTopInt then l_MergeType := aCtx.rEngine.PopInt else Assert(False, 'Не задан тип объединения'); if l_Cells <> nil then l_Cells.Merge(TedMergeAlgorythm(l_MergeType)) else Assert(False, 'Не удалось получить диапазон ячеек!') end // if l_Range <> nil then else Assert(False, 'Не удалось получить выделение.'); //#UC END# *4F4DD89102E4_4F759F1803AF_impl* end;//TkwPopEditorMergeCells.DoEditorWithTools class function TkwPopEditorMergeCells.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:MergeCells'; end;//TkwPopEditorMergeCells.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorWithToolsFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit EventUnit; interface uses System.SysUtils, DateUtils, Constants, Global, XSuperObject; type TEvents = class(TObject) public ID : int64; DevID : integer; DevClass : Byte; CustID : integer; AddInfo : string; Signal : string; DateTime : TDateTime; XoID : integer; EventCode : integer; procedure Clear; procedure Write; constructor Create; end; procedure GenEvent(DevID: integer; DevClass: byte; SysMesID: integer; AddInfo: string = ''; CustID: integer = -1); implementation uses DataUnit, Service, HTTP_Client; procedure GenEvent(DevID: integer; DevClass: byte; SysMesID: integer; AddInfo: string = ''; CustID: integer = -1); var Event: TEvents; begin Event := TEvents.Create; Event.DevID := DevID; Event.DevClass := DevClass; Event.CustID := CustID; Event.AddInfo := AddInfo; Event.DateTime := Now; Event.Signal := ''; Event.XoID := -1; Event.EventCode := SysMesID; Event.Write; Event.Free; end; constructor TEvents.Create; begin Clear; end; procedure TEvents.Clear; begin DevID := InvalidID; CustID := InvalidID; AddInfo := ''; Signal := ''; DateTime := Now; XoID := InvalidID; end; procedure TEvents.Write; var JSON: ISuperObject; begin ID := 0; JSON := SO(); JSON.S[KEY_MES_TYPE] := 'event'; JSON.I['ID'] := ID; JSON.I['DEV_ID'] := DevID; JSON.I['DEV_CLASS'] := DevClass; JSON.I['CUST_ID'] := CustID; JSON.I['CODE_ID'] := EventCode; JSON.I['XO_ID'] := XoID; JSON.S['ADD_INFO'] := AddInfo; JSON.S['DATE_TIME'] := DateTimeToStr(Now); JSON.S['SIGNAL'] := Signal; HttpLink.BufferIO(JSON); end; end.
{ *************************************************************************** Copyright (c) 2016-2021 Kike Pérez Unit : Quick.Expression Description : Expression parser & validator Author : Kike Pérez Version : 1.0 Created : 04/05/2019 Modified : 06/02/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Expression; {$i QuickLib.inc} interface uses SysUtils, StrUtils, TypInfo, RTTI, Quick.Commons, Quick.RTTI.Utils, Quick.Value, Quick.Value.RTTI; type TOperator = (opNone, opEqual, opNotEqual, opGreater, opEqualOrGreater, opLower, opEqualOrLower, opContains, opLike, opLikeR, opLikeL); TCombine = (coNone, coAND, coOR, coXOR); TExpression = class private fCombine : TCombine; public property Combine : TCombine read fCombine write fCombine; function Validate(const aValue : TValue) : Boolean; virtual; abstract; function IsNull : Boolean; virtual; abstract; end; TSingleExpression = class(TExpression) private fValue1 : string; fOperator : TOperator; fValue2 : TFlexValue; {$IFNDEF FPC} function ListContains(aArrayObj : TObject; const aValue : string): Boolean; function IListContains(aArrayObj : TValue; const aValue : string): Boolean; {$ENDIF} function ArrayContains(aArray : TValue; const aValue : string): Boolean; class function IsEqual(aValue1, aValue2 : TFlexValue) : Boolean; class function IsEqualOrLower(aValue1, aValue2 : TFlexValue) : Boolean; class function IsEqualOrGreater(aValue1, aValue2 : TFlexValue) : Boolean; class function IsGreater(aValue1, aValue2 : TFlexValue) : Boolean; class function IsLower(aValue1, aValue2 : TFlexValue) : Boolean; public property Value1 : string read fValue1 write fValue1; property &Operator : TOperator read fOperator write fOperator; property Value2 : TFlexValue read fValue2 write fValue2; function Validate(const aValue : TValue) : Boolean; override; function IsNull : Boolean; override; end; TExpressionArray = array of TExpression; TMultiExpression = class(TExpression) private fArray : TExpressionArray; public destructor Destroy; override; property Items : TExpressionArray read fArray write fArray; function Validate(const aValue : TValue) : Boolean; override; function IsNull : Boolean; override; procedure Add(aExpression : TExpression); end; TExpressionParser = class private class function IsSingleExpression(const aExpression : string) : Boolean; class function GetSingleExpression(const aExpression : string) : TSingleExpression; class function GetMultiExpression(const aExpression : string) : TMultiExpression; class function GetOperator(const aOperator : string) : TOperator; class function GetCombine(const aValue : string) : TCombine; public class function Parse(const aExpression : string) : TExpression; class function Validate(const aValue : TValue; const aExpression : string) : Boolean; overload; class function Validate(const aExpression : string) : Boolean; overload; end; ENotValidExpression = class(Exception); EExpressionValidateError = class(Exception); EExpressionNotSupported = class(Exception); implementation const OperatorStr : array[Low(TOperator)..TOperator.opLike] of string = ('none','=','<>','>','>=','<','<=','CONTAINS','LIKE'); {$IFDEF NEXTGEN} LOWSTR = 0; {$ELSE} LOWSTR = 1; {$ENDIF} { TExpressionParser } //a > 10 //(a > 10) AND (b < 1) //((a > 10) AND (b < 1)) OR (c = 10) class function TExpressionParser.GetCombine(const aValue: string): TCombine; begin if CompareText(aValue,'AND') = 0 then Result := TCombine.coAND else if CompareText(aValue,'OR') = 0 then Result := TCombine.coOR else if CompareText(aValue,'XOR') = 0 then Result := TCombine.coXOR else if aValue.IsEmpty then Result := TCombine.coNone else raise EExpressionNotSupported.Create('Operator not supported!'); end; class function TExpressionParser.GetMultiExpression(const aExpression : string) : TMultiExpression; var count : Integer; i : Integer; idx : Integer; exp : string; combine : string; rexp : TExpression; str : string; begin i := LOWSTR; idx := LOWSTR; count := 0; Result := TMultiExpression.Create; exp := aExpression.TrimLeft; while not exp.IsEmpty do begin if exp[i] = '(' then begin Inc(count); if count = 1 then idx := i; end else if exp[i] = ')' then Dec(count); if (count = 0) and (idx > 0) then begin str := ExtractStr(exp,idx,i - idx +1); exp := exp.TrimLeft; if IsSingleExpression(str) then rexp := GetSingleExpression(str) else begin //remove outer parentesis if str.StartsWith('(') then str := Copy(str,LOWSTR + 1,str.Length - 2); rexp := GetMultiExpression(str); end; //get combine combine := ExtractStr(exp,LOWSTR,exp.IndexOf(' ')); exp := exp.TrimLeft; rexp.Combine := GetCombine(combine); if (rexp.Combine = TCombine.coNone) and not (exp.IsEmpty) then raise ENotValidExpression.Create('Not valid expression defined!'); //add to multiexpression Result.Add(rexp); idx := LOWSTR; i := 0; end; Inc(i); end; end; class function TExpressionParser.GetOperator(const aOperator: string): TOperator; var op : TOperator; begin for op := Low(TOperator) to High(TOperator) do begin if CompareText(OperatorStr[op],aOperator) = 0 then Exit(op); end; raise ENotValidExpression.Create('Not valid operator defined!'); end; class function TExpressionParser.GetSingleExpression(const aExpression: string) : TSingleExpression; var exp : string; begin if aExpression.StartsWith('(') then exp := GetSubString(aExpression,'(',')') else exp := aExpression; Result := TSingleExpression.Create; Result.Value1 := ExtractStr(exp,LOWSTR,exp.IndexOf(' ')); exp := exp.TrimLeft; Result.&Operator := GetOperator(ExtractStr(exp,LOWSTR,exp.IndexOf(' '))); Result.Value2 := UnDbQuotedStr(exp); //determine like if Result.&Operator = opLike then begin if Result.Value2.AsString.CountChar('%') = 2 then Result.Value2 := Copy(Result.Value2.AsString, 2, Result.Value2.AsString.Length - 2) else if Result.Value2.AsString.StartsWith('%') then begin Result.&Operator := TOperator.opLikeR; Result.Value2 := Copy(Result.Value2.AsString, 2, Result.Value2.AsString.Length); end else if Result.Value2.AsString.EndsWith('%') then begin Result.&Operator := TOperator.opLikeL; Result.Value2 := Copy(Result.Value2.AsString,LOWSTR,Result.Value2.AsString.Length - 1); end else raise ENotValidExpression.Create('Not valid Like specified!'); end; end; class function TExpressionParser.IsSingleExpression(const aExpression: string): Boolean; begin Result := (aExpression.CountChar('(') < 2) and (aExpression.CountChar(')') < 2); end; class function TExpressionParser.Parse(const aExpression : string) : TExpression; var exp : string; begin if aExpression.IsEmpty then raise ENotValidExpression.Create('Expression is empty'); exp := aExpression.TrimLeft; //single expression or multiexpression if IsSingleExpression(exp) then Exit(GetSingleExpression(exp)) else Result := GetMultiExpression(exp); end; class function TExpressionParser.Validate(const aExpression: string): Boolean; begin Result := Validate(nil,aExpression); end; class function TExpressionParser.Validate(const aValue: TValue; const aExpression: string): Boolean; var exp : TExpression; begin exp := TExpressionParser.Parse(aExpression); try Result := exp.Validate(aValue); finally exp.Free; end; end; { TSingleExpression } class function TSingleExpression.IsEqual(aValue1, aValue2: TFlexValue): Boolean; begin case aValue1.DataType of TValueDataType.dtNull : Exit(False); TValueDataType.dtString, TValueDataType.dtWideString, TValueDataType.dtAnsiString : Result := CompareText(aValue1,aValue2) = 0; TValueDataType.dtInteger, TValueDataType.dtInt64 : Result := aValue1.AsInt64 = aValue2.AsInt64; TValueDataType.dtExtended, TValueDataType.dtDouble : Result := aValue1.AsExtended = aValue2.AsExtended; TValueDataType.dtBoolean : Result := aValue1.AsBoolean = aValue2.AsBoolean; else raise EExpressionNotSupported.Create('Expression type not supported!'); end; end; class function TSingleExpression.IsEqualOrGreater(aValue1, aValue2: TFlexValue): Boolean; begin case aValue1.DataType of TValueDataType.dtNull : Exit(False); TValueDataType.dtString, TValueDataType.dtWideString, TValueDataType.dtAnsiString : Result := CompareText(aValue1,aValue2) >= 0; TValueDataType.dtInteger, TValueDataType.dtInt64 : Result := aValue1.AsInt64 >= aValue2.AsInt64; TValueDataType.dtExtended, TValueDataType.dtDouble : Result := aValue1.AsExtended >= aValue2.AsExtended; TValueDataType.dtBoolean : Result := aValue1.AsBoolean >= aValue2.AsBoolean; else raise EExpressionNotSupported.Create('Expression type not supported!'); end; end; class function TSingleExpression.IsEqualOrLower(aValue1, aValue2: TFlexValue): Boolean; begin case aValue1.DataType of TValueDataType.dtNull : Exit(False); TValueDataType.dtString, TValueDataType.dtWideString, TValueDataType.dtAnsiString : Result := CompareText(aValue1,aValue2) <= 0; TValueDataType.dtInteger, TValueDataType.dtInt64 : Result := aValue1.AsInt64 <= aValue2.AsInt64; TValueDataType.dtExtended, TValueDataType.dtDouble, TValueDataType.dtDateTime : Result := aValue1.AsExtended <= aValue2.AsExtended; TValueDataType.dtBoolean : Result := aValue1.AsBoolean <= aValue2.AsBoolean; else raise EExpressionNotSupported.Create('Expression type not supported!'); end; end; class function TSingleExpression.IsGreater(aValue1, aValue2: TFlexValue): Boolean; begin case aValue1.DataType of TValueDataType.dtNull : Exit(False); TValueDataType.dtString, TValueDataType.dtWideString, TValueDataType.dtAnsiString : Result := CompareText(aValue1,aValue2) > 0; TValueDataType.dtInteger, TValueDataType.dtInt64 : Result := aValue1.AsInt64 > aValue2.AsInt64; TValueDataType.dtExtended, TValueDataType.dtDouble, TValueDataType.dtDateTime : Result := aValue1.AsExtended > aValue2.AsExtended; TValueDataType.dtBoolean : Result := aValue1.AsBoolean > aValue2.AsBoolean; else raise EExpressionNotSupported.Create('Expression type not supported!'); end; end; class function TSingleExpression.IsLower(aValue1, aValue2: TFlexValue): Boolean; begin case aValue1.DataType of TValueDataType.dtNull : Exit(False); TValueDataType.dtString, TValueDataType.dtWideString, TValueDataType.dtAnsiString : Result := CompareText(aValue1,aValue2) < 0; TValueDataType.dtInteger, TValueDataType.dtInt64 : Result := aValue1.AsInt64 < aValue2.AsInt64; TValueDataType.dtExtended, TValueDataType.dtDouble, TValueDataType.dtDateTime : Result := aValue1.AsExtended < aValue2.AsExtended; TValueDataType.dtBoolean : Result := aValue1.AsBoolean < aValue2.AsBoolean; else raise EExpressionNotSupported.Create('Expression type not supported!'); end; end; function TSingleExpression.IsNull: Boolean; begin Result := (fValue1.IsEmpty) or (fValue2.IsNullOrEmpty); end; function TSingleExpression.Validate(const aValue : TValue) : Boolean; var value1 : TFlexValue; begin Result := False; if aValue.IsEmpty then value1 := fValue1 else begin if aValue.IsObject then begin if fValue1.Contains('.') then value1.AsTValue := TRTTI.GetPathValue(aValue.AsObject,fValue1) else value1.AsTValue := TRTTI.GetPropertyValueEx(aValue.AsObject,fValue1); end else value1.AsTValue := aValue; end; case fOperator of TOperator.opEqual : Result := IsEqual(value1,fValue2); TOperator.opNotEqual : Result := not IsEqual(value1,fValue2); TOperator.opGreater : Result := IsGreater(value1,fValue2); TOperator.opEqualOrGreater : Result := IsEqualOrGreater(value1,fValue2); TOperator.opLower : Result := IsLower(value1,fValue2); TOperator.opEqualOrLower : Result := IsEqualOrLower(value1,fValue2); TOperator.opLike : Result := {$IFNDEF FPC}ContainsText(value1,fValue2);{$ELSE}AnsiContainsText(value1.AsAnsiString,fValue2);{$ENDIF} TOperator.opLikeR : Result := EndsText(fValue2,value1); TOperator.opLikeL : Result := StartsText(fValue2,value1); TOperator.opContains : begin {$IFNDEF FPC} if value1.IsObject then Result := ListContains(value1.AsObject,fValue2) else if value1.IsInterface then Result := IListContains(value1.AsTValue,fValue2) else if value1.IsArray then Result := ArrayContains(value1.AsTValue,fValue2); {$ELSE} if value1.IsArray then Result := ArrayContains(value1.AsTValue,fValue2); {$ENDIF} end else raise ENotValidExpression.Create('Operator not defined'); end; end; //function TSingleExpression.Validate(aValue : TObject) : Boolean; //var // value1 : TFlexValue; // //rvalue : TValue; //begin // Result := False; // if aValue = nil then Exit; // value1.AsTValue := TRTTI.GetPathValue(aValue,fValue1); // //rvalue := TRTTI.GetPathValue(aValue,fValue1); // case fOperator of // TOperator.opEqual : // begin // if value1.IsString then Result := CompareText(value1,fValue2) = 0 // else Result := value1{$IFDEF FPC}.AsAnsiString{$ENDIF} = fValue2; // end; // TOperator.opNotEqual : Result := value1{$IFDEF FPC}.AsAnsiString{$ENDIF} <> fValue2; // TOperator.opGreater : Result := value1{$IFDEF FPC}.AsAnsiString{$ENDIF} > fValue2; // TOperator.opEqualOrGreater : Result := value1{$IFDEF FPC}.AsAnsiString{$ENDIF} >= fValue2; // TOperator.opLower : Result := value1{$IFDEF FPC}.AsAnsiString{$ENDIF} < fValue2; // TOperator.opEqualOrLower : Result := value1{$IFDEF FPC}.AsAnsiString{$ENDIF} <= fValue2; // TOperator.opLike : Result := {$IFNDEF FPC}ContainsText(value1,fValue2);{$ELSE}AnsiContainsText(value1.AsAnsiString,fValue2);{$ENDIF} // TOperator.opLikeR : Result := EndsText(fValue2,value1); // TOperator.opLikeL : Result := StartsText(fValue2,value1); // TOperator.opContains : // begin // {$IFNDEF FPC} // if value1.IsObject then Result := ListContains(value1.AsObject,fValue2) // else if value1.IsInterface then Result := IListContains(value1.AsTValue,fValue2) // else if value1.IsArray then Result := ArrayContains(value1.AsTValue,fValue2); // {$ELSE} // if value1.IsArray then Result := ArrayContains(value1.AsTValue,fValue2); // {$ENDIF} // end // else raise ENotValidExpression.Create('Operator not defined'); // end; //end; {$IFNDEF FPC} function TSingleExpression.ListContains(aArrayObj : TObject; const aValue : string): Boolean; var ctx : TRttiContext; rType: TRttiType; rMethod: TRttiMethod; value: TValue; begin Result := False; rType := ctx.GetType(aArrayObj.ClassInfo); rMethod := rType.GetMethod('ToArray'); if Assigned(rMethod) then begin value := rMethod.Invoke(aArrayObj, []); Result := Self.ArrayContains(value,aValue); end; end; function TSingleExpression.IListContains(aArrayObj : TValue; const aValue : string): Boolean; var ctx : TRttiContext; rType: TRttiType; rMethod: TRttiMethod; value: TValue; obj : TObject; begin Result := False; try obj := TObject(aArrayObj.AsInterface); rType := ctx.GetType(obj.ClassInfo); rMethod := rType.GetMethod('ToArray'); if Assigned(rMethod) then begin value := rMethod.Invoke(obj, []); Result := Self.ArrayContains(value,aValue); end; except raise EExpressionValidateError.Create('Interface property not supported'); end; end; {$ENDIF} function TSingleExpression.ArrayContains(aArray : TValue; const aValue : string): Boolean; var count : Integer; arrItem : TValue; begin Result := False; if not aArray.IsArray then Exit(False); count := aArray.GetArrayLength; while count > 0 do begin Dec(count); arrItem := aArray.GetArrayElement(count); case arrItem.Kind of {$IFNDEF FPC} tkString, {$ENDIF} tkUnicodeString, tkWideString : Result := CompareText(arrItem.AsString,aValue) = 0; tkInteger, tkInt64 : Result := arrItem.AsInt64 = aValue.ToInt64; tkFloat : Result := arrItem.AsExtended = aValue.ToExtended; else raise EExpressionNotSupported.CreateFmt('Type Array<%s> not supported',[arrItem.TypeInfo.Name]); end; if Result then Exit; end; end; { TMultiExpression } procedure TMultiExpression.Add(aExpression: TExpression); begin fArray := fArray + [aExpression]; end; destructor TMultiExpression.Destroy; var exp : TExpression; begin for exp in fArray do exp.Free; inherited; end; function TMultiExpression.IsNull: Boolean; begin Result := High(fArray) < 0; end; function TMultiExpression.Validate(const aValue : TValue) : Boolean; var i : Integer; begin Result := False; for i := Low(fArray) to High(fArray) do begin if i = Low(fArray) then Result := fArray[i].Validate(aValue) else begin case fArray[i-1].Combine of TCombine.coAND : Result := Result and fArray[i].Validate(aValue); TCombine.coOR : Result := Result or fArray[i].Validate(aValue); TCombine.coXOR : Result := Result xor fArray[i].Validate(aValue); else Exit; end; end; end; end; end.
unit main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons; type TMainForm = class(TForm) SourcePanel: TPanel; DestinationPanel: TPanel; SourceMemo: TMemo; DestinationMemo: TMemo; CharNumberEdit: TEdit; CharNumberInfoLabel: TLabel; CharNumberPanel: TPanel; CharNumberEditLabel: TLabel; SourceLabel: TLabel; DestinationLabel: TLabel; OnlyOneCheckBox: TCheckBox; FirstButton: TSpeedButton; PrevButton: TSpeedButton; NextButton: TSpeedButton; LastButton: TSpeedButton; Bevel1: TBevel; LoadButton: TButton; SaveButton: TButton; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; procedure SourceMemoChange(Sender: TObject); procedure CharNumberEditKeyPress(Sender: TObject; var Key: Char); procedure CharNumberEditChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure OnlyOneCheckBoxClick(Sender: TObject); procedure LoadButtonClick(Sender: TObject); procedure SaveButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; const MinimumChar = 50; var MainForm: TMainForm; NumberOfChar: integer; WasSave: boolean; WasLoad: boolean; implementation {$R *.DFM} procedure TMainForm.FormCreate(Sender: TObject); begin NumberOfChar:=150; CharNumberEdit.Text:='150'; OnlyOneCheckBox.Checked:=False; FirstButton.Enabled:=False; PrevButton.Enabled:=False; NextButton.Enabled:=False; LastButton.Enabled:=False; WasSave:=False; WasLoad:=False; end; procedure TMainForm.SourceMemoChange(Sender: TObject); var CharNum, MessNum, WordStart, NextPos: integer; OpenStr: string; Mess: string; EndStr: string; FinalMess: string; NextWord: string; Finish: boolean; begin if NumberOfChar < MinimumChar then begin DestinationMemo.Lines.Text:='Error:'+#13+'Characters per message are less than minimum. '+ 'Minimum is '+IntToStr(MinimumChar); end else begin CharNum:=Length(SourceMemo.Lines.Text); CharNumberPanel.Caption:=IntToStr(CharNum); if CharNum <= NumberOfChar then DestinationMemo.Lines:=SourceMemo.Lines else begin FinalMess:=''; MessNum:=1; Finish:=False; WordStart:=1; repeat OpenStr:='.'+IntToStr(MessNum)+'. '; EndStr:=' ...'; Mess:=''; NextWord:=''; NextPos:=0; while (Length(OpenStr+Mess+NextWord+EndStr) <= NumberOfChar) and (WordStart <= Length(SourceMemo.Lines.Text)) do begin Mess:=Mess+NextWord; WordStart:=WordStart+NextPos; while (SourceMemo.Lines.Text[WordStart] = ' ') and ((WordStart) <= Length(SourceMemo.Lines.Text)) do WordStart:=WordStart+1; if Mess <> '' then NextWord:=' ' else NextWord:=''; NextPos:=0; while (SourceMemo.Lines.Text[WordStart+NextPos] <> ' ') and (SourceMemo.Lines.Text[WordStart+NextPos] <> #13) and ((WordStart+NextPos) <= Length(SourceMemo.Lines.Text)) do begin NextWord:=NextWord+SourceMemo.Lines.Text[WordStart+NextPos]; NextPos:=NextPos+1; end; end; Mess:=OpenStr+Mess+EndStr; while Length(Mess) < NumberOfChar do Mess:=Mess+' '; FinalMess:=FinalMess+Mess; MessNum:=MessNum+1; Finish:=WordStart > Length(SourceMemo.Lines.Text); until Finish; DestinationMemo.Lines.Text:=FinalMess; end; end; end; procedure TMainForm.CharNumberEditKeyPress(Sender: TObject; var Key: Char); begin if ((Key < '0') or (Key > '9')) and (Key <> #8) then Key:=#0; end; procedure TMainForm.CharNumberEditChange(Sender: TObject); begin if CharNumberEdit.Text <> '' then NumberOfChar:=StrToInt(CharNumberEdit.Text) else NumberOfChar:=0; if NumberOfChar >= MinimumChar then SourceMemoChange(Sender); end; procedure TMainForm.OnlyOneCheckBoxClick(Sender: TObject); begin If OnlyOnecheckBox.Checked then begin FirstButton.Enabled:=True; PrevButton.Enabled:=True; NextButton.Enabled:=True; LastButton.Enabled:=True; end else begin FirstButton.Enabled:=False; PrevButton.Enabled:=False; NextButton.Enabled:=False; LastButton.Enabled:=False; end; end; procedure TMainForm.LoadButtonClick(Sender: TObject); begin if WasSave then OpenDialog.InitialDir:=SaveDialog.InitialDir; OpenDialog.FileName:='*.*'; if OpenDialog.Execute then begin SourceMemo.Lines.LoadFromFile(OpenDialog.FileName); WasLoad:=True; end; end; procedure TMainForm.SaveButtonClick(Sender: TObject); begin if WasLoad then SaveDialog.InitialDir:=OpenDialog.InitialDir; SaveDialog.FileName:='*.*'; if SaveDialog.Execute then begin SourceMemo.Lines.SaveToFile(SaveDialog.FileName); WasSave:=True; end; end; end.
unit pgUserManager; // Модуль: "w:\common\components\rtl\Garant\PG\pgUserManager.pas" // Стереотип: "UtilityPack" // Элемент модели: "pgUserManager" MUID: (57AB03D00397) {$Include w:\common\components\rtl\Garant\PG\pgDefine.inc} interface {$If Defined(UsePostgres)} uses l3IntfUses , Classes , daTypes , l3ProtoObject , daInterfaces , l3DatLst , daArchiUserList , daUserStatusChangedSubscriberList , pgConnection , pgFunctionFactory , pgFreeIDHelperHolder , pgTableModifier , l3LongintList ; type TpgUserManager = class(Tl3ProtoObject, IdaUserManager, IdaComboAccessUserManagerHelper) private f_Factory: IdaTableQueryFactory; f_PasswordQuery: IdaTabledQuery; f_UserFlagsQuery: IdaTabledQuery; f_AllUsers: Tl3StringDataList; f_AllGroups: Tl3StringDataList; f_UserNameQuery: IdaTabledQuery; f_ArchiUsers: TdaArchiUserList; f_UserStatusChangedSubscriberList: TdaUserStatusChangedSubscriberList; f_UserLoginQuery: IdaTabledQuery; f_PriorityCalculator: IdaPriorityCalculator; f_AllArchiUsersQuery: IdaTabledQuery; f_AllGroupsQuery: IdaTabledQuery; f_IsMemberOfGroupQuery: IdaTabledQuery; f_UserGroupsQuery: IdaTabledQuery; f_Connection: TpgConnection; f_FunctionFactory: TpgFunctionFactory; f_FreeIDHelperHolder: TpgFreeIDHelperHolder; f_Journal: IdaJournal; f_GroupModifier: TpgTableModifier; f_GroupUsersQuery: IdaTabledQuery; f_CacheActiveUserList: TStringList; private procedure FillListByResultSet(aList: Tl3StringDataList; const aResultSet: IdaResultSet; const anIDFieldName: AnsiString; aDataSize: Integer; const aNameFieldName: AnsiString; AddRegion: Boolean); procedure FillAllUsers(aList: Tl3StringDataList); procedure FillAllGroups(aList: Tl3StringDataList); procedure SortUsersInList(aList: Tl3StringDataList); function UserNameQuery: IdaTabledQuery; function UserLoginQuery: IdaTabledQuery; function AllArchiUsersQuery: IdaTabledQuery; function AllGroupsQuery: IdaTabledQuery; function IsMemberOfGroupQuery: IdaTabledQuery; function UserGroupsQuery: IdaTabledQuery; procedure AddUserGroupWithID(anID: TdaUserGroupID; const aName: AnsiString); function GroupModifier: TpgTableModifier; function GroupUsersQuery: IdaTabledQuery; procedure LoadFiltredUserList(aList: TStringList; aOnlyActive: Boolean); protected function CheckPassword(const aLogin: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TdaUserID): TdaLoginError; function IsUserAdmin(anUserID: TdaUserID): Boolean; function Get_AllUsers: Tl3StringDataList; function Get_AllGroups: Tl3StringDataList; function GetUserName(anUserID: TdaUserID): AnsiString; function GetUserPriorities(aGroupId: TdaUserID; var aImportPriority: TdaPriority; var aExportPriority: TdaPriority): Boolean; procedure ReSortUserList; function Get_ArchiUsersCount: Integer; function UserByID(aID: TdaUserID): IdaArchiUser; function UserByLogin(const aLogin: AnsiString): IdaArchiUser; procedure UpdateUserInfo(aUserID: TdaUserID; aIsGroup: Boolean); procedure MakeFullArchiUsersList; function GetUserDisplayName(anID: TdaUserID): AnsiString; function IsUserExists(anID: TdaUserID): Boolean; procedure RegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber); procedure UnRegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber); procedure NotifyUserActiveChanged(anUserID: TdaUserID; anActive: Boolean); function CSCheckPassword(const aLogin: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TdaUserID): Boolean; procedure GetUserInfo(aUser: TdaUserID; var aUserName: AnsiString; var aLoginName: AnsiString; var aActFlag: Byte); function Get_PriorityCalculator: IdaPriorityCalculator; function IsMemberOfGroup(aUserGroupID: TdaUserGroupID; aUserID: TdaUserID): Boolean; function GetUserGroups(aUserID: TdaUserID): TdaUserGroupIDArray; procedure GetUserGroupsList(aUser: TdaUserID; aList: Tl3StringDataList); overload; procedure GetUserGroupsList(aUser: TdaUserID; aList: Tl3LongintList); overload; procedure SetUserGroupsList(aUser: TdaUserID; aList: Tl3StringDataList); function AddUserGroup(const aName: AnsiString): TdaUserGroupID; procedure EditUserGroup(aGroupID: TdaUserGroupID; const aName: AnsiString; aImportPriority: TdaPriority; aExportPriority: TdaPriority); procedure DelUserGroup(aGroupID: TdaUserGroupID); procedure AddUserGroupShadow(anID: TdaUserGroupID; const aName: AnsiString); procedure RemoveUserFromAllGroups(aUser: TdaUserID); procedure SetUserGroup(aUser: TdaUserID; aGroup: TdaUserGroupID; Add: Boolean = True); procedure AdminChangePassWord(aUser: TdaUserID; const NewPass: AnsiString); procedure GetHostUserListOnGroup(aGroupID: TdaUserGroupID; aList: Tl3StringDataList; NeedSort: Boolean = False); procedure SetHostUserListOnGroup(aGroupID: TdaUserGroupID; aList: Tl3StringDataList); function AddUser(const aUserName: AnsiString; const aLoginName: AnsiString; const aPassword: AnsiString; ActFlag: Byte): TdaUserID; function AddUserID(anID: TdaUserID; const aUserName: AnsiString; const aLoginName: AnsiString; const aPassword: AnsiString; ActFlag: Byte): TdaUserID; procedure EditUser(aUser: TdaUserID; const aUserName: AnsiString; const aLoginName: AnsiString; ActFlag: Byte; const EditMask: TdaUserEditMask); procedure DelUser(aUser: TdaUserID); procedure GetUserListOnGroup(aUsGroup: TdaUserGroupID; aList: Tl3StringDataList; GetActiveUsersOnly: Boolean = False); procedure GetFiltredUserList(aList: TStrings; aOnlyActive: Boolean = False); procedure GetDocGroupData(aUserGroup: TdaUserGroupID; aFamily: TdaFamilyID; aDocDataList: Tl3StringDataList); procedure PutDocGroupData(aUserGroup: TdaUserGroupID; aFamily: TdaFamilyID; aDocDataList: Tl3StringDataList); procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aTableFactory: IdaTableQueryFactory; const aJournal: IdaJournal; aFunctionFactory: TpgFunctionFactory; aFreeIDHelperHolder: TpgFreeIDHelperHolder; aConnection: TpgConnection); reintroduce; class function Make(const aTableFactory: IdaTableQueryFactory; const aJournal: IdaJournal; aFunctionFactory: TpgFunctionFactory; aFreeIDHelperHolder: TpgFreeIDHelperHolder; aConnection: TpgConnection): IdaUserManager; reintroduce; procedure IterateArchiUsersF(anAction: ArchiUsersIterator_IterateArchiUsersF_Action); procedure IterateUserGroupsF(anAction: ArchiUsersIterator_IterateUserGroupsF_Action); end;//TpgUserManager function CompareUsers(anID1: TdaUserID; const aName1: AnsiString; anID2: TdaUserID; const aName2: AnsiString): Integer; {$IfEnd} // Defined(UsePostgres) implementation {$If Defined(UsePostgres)} uses l3ImplUses , SysUtils , daScheme , daUserManagerUtils , l3Base , daDataProvider , pgPriorityCalculator , daArchiUser , daSchemeConsts , l3MinMax , pgInterfaces , daUtils //#UC START# *57AB03D00397impl_uses* //#UC END# *57AB03D00397impl_uses* ; function CompareStringsUser(List: TStringList; Index1: Integer; Index2: Integer): Integer; //#UC START# *57AB04080295_57AB03D00397_var* //#UC END# *57AB04080295_57AB03D00397_var* begin //#UC START# *57AB04080295_57AB03D00397_impl* Result := CompareUsers(TdaUserID(List.Objects[Index1]), List[Index1], TdaUserID(List.Objects[Index2]), List[Index2]); //#UC END# *57AB04080295_57AB03D00397_impl* end;//CompareStringsUser function CompareUsers(anID1: TdaUserID; const aName1: AnsiString; anID2: TdaUserID; const aName2: AnsiString): Integer; //#UC START# *57AB04B800BA_57AB03D00397_var* var l_Reg1, l_Reg2: TdaRegionID; //#UC END# *57AB04B800BA_57AB03D00397_var* begin //#UC START# *57AB04B800BA_57AB03D00397_impl* // сначала сравниваем регионы l_Reg1 := GetUserRegion(anID1); l_Reg2 := GetUserRegion(anID2); if l_Reg1 <> l_Reg2 then begin // если регион наш, родной, то он должен быть наверху, однозначно! if l_Reg1 = GlobalDataProvider.RegionID then begin Result := -1; Exit; end else if l_Reg2 = GlobalDataProvider.RegionID then begin Result := 1; Exit; end end; // По региону не вышел наверх. Сортируем по имени (к которому название региона уже приклеено) if aName1 < aName2 then Result := -1 else if aName1 > aName2 then Result := 1 else Result := 0; //#UC END# *57AB04B800BA_57AB03D00397_impl* end;//CompareUsers constructor TpgUserManager.Create(const aTableFactory: IdaTableQueryFactory; const aJournal: IdaJournal; aFunctionFactory: TpgFunctionFactory; aFreeIDHelperHolder: TpgFreeIDHelperHolder; aConnection: TpgConnection); //#UC START# *562A074E0321_5629FC88034B_var* //#UC END# *562A074E0321_5629FC88034B_var* begin //#UC START# *562A074E0321_5629FC88034B_impl* inherited Create; f_Factory := aTableFactory; f_Journal := aJournal; aConnection.SetRefTo(f_Connection); aFunctionFactory.SetRefTo(f_FunctionFactory); aFreeIDHelperHolder.SetRefTo(f_FreeIDHelperHolder); f_ArchiUsers := TdaArchiUserList.Create; f_UserStatusChangedSubscriberList := TdaUserStatusChangedSubscriberList.Make; f_PasswordQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtPassword))); f_PasswordQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtPassword)['Password'])); f_PasswordQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtPassword)['User_ID'])); f_PasswordQuery.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtPassword)['ShortName'], da_copEqual, 'p_ShortName'); f_PasswordQuery.Prepare; f_UserFlagsQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtUsers))); f_UserFlagsQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['user_name'])); f_UserFlagsQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['Active'])); f_UserFlagsQuery.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtUsers)['ID'], da_copEqual, 'p_UserID'); f_UserFlagsQuery.Prepare; //#UC END# *562A074E0321_5629FC88034B_impl* end;//TpgUserManager.Create class function TpgUserManager.Make(const aTableFactory: IdaTableQueryFactory; const aJournal: IdaJournal; aFunctionFactory: TpgFunctionFactory; aFreeIDHelperHolder: TpgFreeIDHelperHolder; aConnection: TpgConnection): IdaUserManager; var l_Inst : TpgUserManager; begin l_Inst := Create(aTableFactory, aJournal, aFunctionFactory, aFreeIDHelperHolder, aConnection); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TpgUserManager.Make procedure TpgUserManager.FillListByResultSet(aList: Tl3StringDataList; const aResultSet: IdaResultSet; const anIDFieldName: AnsiString; aDataSize: Integer; const aNameFieldName: AnsiString; AddRegion: Boolean); //#UC START# *57172C740069_5629FC88034B_var* var l_ID: TdaUserID; l_Name: AnsiString; //#UC END# *57172C740069_5629FC88034B_var* begin //#UC START# *57172C740069_5629FC88034B_impl* aList.Changing; try aList.Clear; aList.DataSize := aDataSize; aList.NeedAllocStr := True; while not aResultSet.EOF do begin l_ID := aResultSet.Field[anIDFieldName].AsLargeInt; l_Name := aResultSet.Field[aNameFieldName].AsString; if AddRegion then l_Name := ConcatRegionAndUserNames(l_ID, l_Name); aList.AddStr(l_Name, @l_ID); aResultSet.Next; end; finally aList.Changed; end; //#UC END# *57172C740069_5629FC88034B_impl* end;//TpgUserManager.FillListByResultSet procedure TpgUserManager.FillAllUsers(aList: Tl3StringDataList); //#UC START# *5715E71600DD_5629FC88034B_var* var l_Query: IdaTabledQuery; l_ResultSet: IdaResultSet; //#UC END# *5715E71600DD_5629FC88034B_var* begin //#UC START# *5715E71600DD_5629FC88034B_impl* l_Query := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtUsers))); try l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['id'])); l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['user_name'])); l_Query.Prepare; l_ResultSet := l_Query.OpenResultSet; try FillListByResultSet(aList, l_ResultSet, 'id', cUserIDSize, 'user_name', True); finally l_ResultSet := nil; end; finally l_Query := nil; end; //#UC END# *5715E71600DD_5629FC88034B_impl* end;//TpgUserManager.FillAllUsers procedure TpgUserManager.FillAllGroups(aList: Tl3StringDataList); //#UC START# *5715E74402CA_5629FC88034B_var* var l_Query: IdaTabledQuery; l_ResultSet: IdaResultSet; //#UC END# *5715E74402CA_5629FC88034B_var* begin //#UC START# *5715E74402CA_5629FC88034B_impl* l_Query := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtGroups))); try l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroups)['id'])); l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroups)['group_name'])); l_Query.Prepare; l_ResultSet := l_Query.OpenResultSet; try FillListByResultSet(aList, l_ResultSet, 'id', cGroupIDSize, 'group_name', False); finally l_ResultSet := nil; end; finally l_Query := nil; end; //#UC END# *5715E74402CA_5629FC88034B_impl* end;//TpgUserManager.FillAllGroups procedure TpgUserManager.SortUsersInList(aList: Tl3StringDataList); //#UC START# *5715ED0002E0_5629FC88034B_var* function l_CompareUsers(I, J: Integer): Integer; begin Result := CompareUsers(TdaUserID(aList.DataInt[I]), aList.PasStr[I], TdaUserID(aList.DataInt[J]), aList.PasStr[J]); end; //#UC END# *5715ED0002E0_5629FC88034B_var* begin //#UC START# *5715ED0002E0_5629FC88034B_impl* aList.SortF(l3LocalStub(@l_CompareUsers)); //#UC END# *5715ED0002E0_5629FC88034B_impl* end;//TpgUserManager.SortUsersInList function TpgUserManager.UserNameQuery: IdaTabledQuery; //#UC START# *5718C16B036E_5629FC88034B_var* //#UC END# *5718C16B036E_5629FC88034B_var* begin //#UC START# *5718C16B036E_5629FC88034B_impl* if f_UserNameQuery = nil then begin f_UserNameQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtUsers))); f_UserNameQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['user_name'])); f_UserNameQuery.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtUsers)['ID'], da_copEqual, 'p_UserID'); f_UserNameQuery.Prepare; end; Result := f_UserNameQuery; //#UC END# *5718C16B036E_5629FC88034B_impl* end;//TpgUserManager.UserNameQuery function TpgUserManager.UserLoginQuery: IdaTabledQuery; //#UC START# *573B0837013B_5629FC88034B_var* //#UC END# *573B0837013B_5629FC88034B_var* begin //#UC START# *573B0837013B_5629FC88034B_impl* if f_UserLoginQuery = nil then begin f_UserLoginQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtPassword))); f_UserLoginQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtPassword)['ShortName'])); f_UserLoginQuery.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtPassword)['User_ID'], da_copEqual, 'p_UserID'); f_UserLoginQuery.Prepare; end; Result := f_UserLoginQuery; //#UC END# *573B0837013B_5629FC88034B_impl* end;//TpgUserManager.UserLoginQuery function TpgUserManager.AllArchiUsersQuery: IdaTabledQuery; //#UC START# *57514203013A_5629FC88034B_var* //#UC END# *57514203013A_5629FC88034B_var* begin //#UC START# *57514203013A_5629FC88034B_impl* if f_AllArchiUsersQuery = nil then begin f_AllArchiUsersQuery := f_Factory.MakeTabledQuery( f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtUsers), 'u').Join( f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtPassword), 'p'), da_jkLeftOuter).SetCondition(f_Factory.MakeJoinCondition('u', TdaScheme.Instance.Table(da_mtUsers)['id'], 'p', TdaScheme.Instance.Table(da_mtPassword)['User_ID'])) ); f_AllArchiUsersQuery.AddSelectField(f_Factory.MakeSelectField('u', TdaScheme.Instance.Table(da_mtUsers)['id'])); f_AllArchiUsersQuery.AddSelectField(f_Factory.MakeSelectField('u', TdaScheme.Instance.Table(da_mtUsers)['user_name'])); f_AllArchiUsersQuery.AddSelectField(f_Factory.MakeSelectField('u', TdaScheme.Instance.Table(da_mtUsers)['active'])); f_AllArchiUsersQuery.AddSelectField(f_Factory.MakeSelectField('p', TdaScheme.Instance.Table(da_mtPassword)['ShortName'])); f_AllArchiUsersQuery.AddSelectField(f_Factory.MakeSelectField('p', TdaScheme.Instance.Table(da_mtPassword)['Password'])); f_AllArchiUsersQuery.Prepare; end; Result := f_AllArchiUsersQuery; //#UC END# *57514203013A_5629FC88034B_impl* end;//TpgUserManager.AllArchiUsersQuery function TpgUserManager.AllGroupsQuery: IdaTabledQuery; //#UC START# *575809C5019A_5629FC88034B_var* //#UC END# *575809C5019A_5629FC88034B_var* begin //#UC START# *575809C5019A_5629FC88034B_impl* if f_AllGroupsQuery = nil then begin f_AllGroupsQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtGroups))); f_AllGroupsQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroups)['id'])); f_AllGroupsQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroups)['group_name'])); f_AllGroupsQuery.AddOrderBy(f_Factory.MakeSortField(f_AllGroupsQuery.SelectFieldByName('group_name'))); f_AllGroupsQuery.Prepare; end; Result := f_AllGroupsQuery; //#UC END# *575809C5019A_5629FC88034B_impl* end;//TpgUserManager.AllGroupsQuery function TpgUserManager.IsMemberOfGroupQuery: IdaTabledQuery; //#UC START# *575FA96B0019_5629FC88034B_var* //#UC END# *575FA96B0019_5629FC88034B_var* begin //#UC START# *575FA96B0019_5629FC88034B_impl* if f_IsMemberOfGroupQuery = nil then begin f_IsMemberOfGroupQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtGroupMembers))); f_IsMemberOfGroupQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroupMembers)['user_id'])); f_IsMemberOfGroupQuery.WhereCondition := f_Factory.MakeLogicCondition(f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtGroupMembers)['user_id'], da_copEqual, 'p_UserID'), da_loAnd, f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtGroupMembers)['group_id'], da_copEqual, 'p_GroupID')); f_IsMemberOfGroupQuery.Prepare; end; Result := f_IsMemberOfGroupQuery; //#UC END# *575FA96B0019_5629FC88034B_impl* end;//TpgUserManager.IsMemberOfGroupQuery function TpgUserManager.UserGroupsQuery: IdaTabledQuery; //#UC START# *5762975302C1_5629FC88034B_var* //#UC END# *5762975302C1_5629FC88034B_var* begin //#UC START# *5762975302C1_5629FC88034B_impl* if f_UserGroupsQuery = nil then begin f_UserGroupsQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtGroupMembers))); f_UserGroupsQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroupMembers)['group_id'])); f_UserGroupsQuery.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtGroupMembers)['user_id'], da_copEqual, 'p_UserID'); f_UserGroupsQuery.Prepare; end; Result := f_UserGroupsQuery; //#UC END# *5762975302C1_5629FC88034B_impl* end;//TpgUserManager.UserGroupsQuery procedure TpgUserManager.AddUserGroupWithID(anID: TdaUserGroupID; const aName: AnsiString); //#UC START# *5770D18002D5_5629FC88034B_var* var l_Modifier: TpgTableModifier; //#UC END# *5770D18002D5_5629FC88034B_var* begin //#UC START# *5770D18002D5_5629FC88034B_impl* l_Modifier := GroupModifier.Use; try l_Modifier.BeginTransaction; try l_Modifier.Params['id'].AsLargeInt := anID; l_Modifier.Params['group_name'].AsString := aName; l_Modifier.Params['name_length'].AsInteger := Length(aName); l_Modifier.Params['import_priority'].AsInteger := 0; l_Modifier.Params['import_priority'].AsInteger := 0; l_Modifier.Insert; l_Modifier.CommitTransaction; except l_Modifier.RollBackTransaction; raise; end; finally FreeAndNil(l_Modifier); end; f_Journal.LogEditDict(TdaScheme.Instance.Table(da_mtGroups).FamilyID, da_dlNone, da_eoAdd); if f_AllGroups <> nil then begin f_AllGroups.NeedAllocStr:=True; f_AllGroups.Add(PAnsiChar(aName), @anID); end; //#UC END# *5770D18002D5_5629FC88034B_impl* end;//TpgUserManager.AddUserGroupWithID function TpgUserManager.GroupModifier: TpgTableModifier; //#UC START# *577CC28003A6_5629FC88034B_var* //#UC END# *577CC28003A6_5629FC88034B_var* begin //#UC START# *577CC28003A6_5629FC88034B_impl* if f_GroupModifier = nil then f_GroupModifier := TpgTableModifier.Create(da_mtGroups, f_Connection, f_Factory.DataConverter); Result := f_GroupModifier; //#UC END# *577CC28003A6_5629FC88034B_impl* end;//TpgUserManager.GroupModifier function TpgUserManager.GroupUsersQuery: IdaTabledQuery; //#UC START# *5784910F00BF_5629FC88034B_var* //#UC END# *5784910F00BF_5629FC88034B_var* begin //#UC START# *5784910F00BF_5629FC88034B_impl* if f_GroupUsersQuery = nil then begin f_GroupUsersQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtGroupMembers))); f_GroupUsersQuery.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroupMembers)['user_id'])); f_GroupUsersQuery.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtGroupMembers)['group_id'], da_copEqual, 'p_GroupID'); f_GroupUsersQuery.Prepare; end; Result := f_GroupUsersQuery; //#UC END# *5784910F00BF_5629FC88034B_impl* end;//TpgUserManager.GroupUsersQuery procedure TpgUserManager.LoadFiltredUserList(aList: TStringList; aOnlyActive: Boolean); //#UC START# *57AAF3DF0284_5629FC88034B_var* var l_Query: IdaTabledQuery; l_ResultSet: IdaResultSet; l_IDField: IdaField; l_NameField: IdaField; //#UC END# *57AAF3DF0284_5629FC88034B_var* begin //#UC START# *57AAF3DF0284_5629FC88034B_impl* aList.Clear; l_Query := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtUsers), 'u')); try l_Query.WhereCondition := nil; if aOnlyActive then l_Query.WhereCondition := f_Factory.MakeBitWiseCondition('u', TdaScheme.Instance.Table(da_mtUsers)['active'], da_bwAnd, usActive); l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['id'])); l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['user_name'])); l_Query.Prepare; l_ResultSet := l_Query.OpenResultSet; try l_IDField := l_ResultSet.Field['id']; l_NameField := l_ResultSet.Field['user_name']; while not l_ResultSet.EOF do begin aList.AddObject(ConcatRegionAndUserNames(l_IDField.AsLargeInt, l_NameField.AsString), TObject(l_IDField.AsLargeInt)); l_ResultSet.Next; end; finally l_ResultSet := nil; end; finally l_Query := nil; end; aList.CustomSort(@CompareStringsUser); //#UC END# *57AAF3DF0284_5629FC88034B_impl* end;//TpgUserManager.LoadFiltredUserList function TpgUserManager.CheckPassword(const aLogin: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TdaUserID): TdaLoginError; //#UC START# *5628D14D0151_5629FC88034B_var* var l_ResultSet: IdaResultSet; l_Flags: Byte; //#UC END# *5628D14D0151_5629FC88034B_var* begin //#UC START# *5628D14D0151_5629FC88034B_impl* theUserID := 0; Result := da_leUserParamsWrong; if (AnsiLowerCase(aLogin) = c_SupervisorUserName) and not RequireAdminRights then Exit; f_PasswordQuery.Param['p_ShortName'].AsString := aLogin; l_ResultSet := f_PasswordQuery.OpenResultSet; try if l_ResultSet.IsEmpty then Exit; if (l_ResultSet.Field['Password'].AsString <> '') and (not AnsiSameText(l_ResultSet.Field['Password'].AsString, aPassword)) then Exit; theUserID := l_ResultSet.Field['User_ID'].AsLargeInt; f_UserFlagsQuery.Param['p_UserID'].AsLargeInt := theUserID; finally l_ResultSet := nil; end; if theUserID <> usSupervisor then begin l_ResultSet := f_UserFlagsQuery.OpenResultSet; try l_Flags := l_ResultSet.Field['Active'].AsByte; if (l_Flags and usActive) <> usActive then Exit; if RequireAdminRights and ((l_Flags and usAdmin) <> usAdmin) then begin Result := da_leInsufficientRights; Exit; end; Result := da_leOk; finally l_ResultSet := nil; end; end else Result := da_leOk; //#UC END# *5628D14D0151_5629FC88034B_impl* end;//TpgUserManager.CheckPassword function TpgUserManager.IsUserAdmin(anUserID: TdaUserID): Boolean; //#UC START# *56EA993D0218_5629FC88034B_var* var l_ResultSet: IdaResultSet; //#UC END# *56EA993D0218_5629FC88034B_var* begin //#UC START# *56EA993D0218_5629FC88034B_impl* Result := (anUserID = usSupervisor); if not Result then begin f_UserFlagsQuery.Param['p_UserID'].AsLargeInt := anUserID; l_ResultSet := f_UserFlagsQuery.OpenResultSet; try Result := not l_ResultSet.IsEmpty and ((l_ResultSet.Field['Active'].AsByte and usAdmin) = usAdmin); finally l_ResultSet := nil; end; end; //#UC END# *56EA993D0218_5629FC88034B_impl* end;//TpgUserManager.IsUserAdmin function TpgUserManager.Get_AllUsers: Tl3StringDataList; //#UC START# *5715DEF20209_5629FC88034Bget_var* //#UC END# *5715DEF20209_5629FC88034Bget_var* begin //#UC START# *5715DEF20209_5629FC88034Bget_impl* if f_AllUsers = nil then begin f_AllUsers := Tl3StringDataList.Create; FillAllUsers(f_AllUsers); SortUsersInList(f_AllUsers); end; Result:=f_AllUsers; //#UC END# *5715DEF20209_5629FC88034Bget_impl* end;//TpgUserManager.Get_AllUsers function TpgUserManager.Get_AllGroups: Tl3StringDataList; //#UC START# *5715DF0D03C2_5629FC88034Bget_var* //#UC END# *5715DF0D03C2_5629FC88034Bget_var* begin //#UC START# *5715DF0D03C2_5629FC88034Bget_impl* if f_AllGroups = nil then begin f_AllGroups := Tl3StringDataList.Create; FillAllGroups(f_AllGroups); end; Result := f_AllGroups; //#UC END# *5715DF0D03C2_5629FC88034Bget_impl* end;//TpgUserManager.Get_AllGroups function TpgUserManager.GetUserName(anUserID: TdaUserID): AnsiString; //#UC START# *5718B5CF0399_5629FC88034B_var* var l_ResultSet: IdaResultSet; //#UC END# *5718B5CF0399_5629FC88034B_var* begin //#UC START# *5718B5CF0399_5629FC88034B_impl* UserNameQuery.Param['p_UserID'].AsLargeInt := anUserID; l_ResultSet := UserNameQuery.OpenResultSet; try Result := l_ResultSet.Field['user_name'].AsString; finally l_ResultSet := nil; end; //#UC END# *5718B5CF0399_5629FC88034B_impl* end;//TpgUserManager.GetUserName function TpgUserManager.GetUserPriorities(aGroupId: TdaUserID; var aImportPriority: TdaPriority; var aExportPriority: TdaPriority): Boolean; //#UC START# *571DCFB50217_5629FC88034B_var* var l_Query: IdaTabledQuery; l_ResultSet: IdaResultSet; //#UC END# *571DCFB50217_5629FC88034B_var* begin //#UC START# *571DCFB50217_5629FC88034B_impl* l_Query := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtGroups))); try l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroups)['import_priority'])); l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtGroups)['export_priority'])); l_Query.WhereCondition := f_Factory.MakeParamsCondition('', TdaScheme.Instance.Table(da_mtGroups)['ID'], da_copEqual, 'p_GroupID'); l_Query.Prepare; l_Query.Param['p_GroupID'].AsLargeInt := aGroupId; l_ResultSet := l_Query.OpenResultSet; try Result := not l_ResultSet.IsEmpty; if Result then begin aImportPriority := TdaPriority(l_ResultSet.Field['import_priority'].AsInteger); aExportPriority := TdaPriority(l_ResultSet.Field['export_priority'].AsInteger); end; finally l_ResultSet := nil; end; finally l_Query := nil; end; //#UC END# *571DCFB50217_5629FC88034B_impl* end;//TpgUserManager.GetUserPriorities procedure TpgUserManager.ReSortUserList; //#UC START# *5721F5E60367_5629FC88034B_var* //#UC END# *5721F5E60367_5629FC88034B_var* begin //#UC START# *5721F5E60367_5629FC88034B_impl* if f_AllUsers <> nil then SortUsersInList(f_AllUsers); //#UC END# *5721F5E60367_5629FC88034B_impl* end;//TpgUserManager.ReSortUserList function TpgUserManager.Get_ArchiUsersCount: Integer; //#UC START# *5729C59E00D5_5629FC88034Bget_var* //#UC END# *5729C59E00D5_5629FC88034Bget_var* begin //#UC START# *5729C59E00D5_5629FC88034Bget_impl* if f_ArchiUsers.Count = 0 then MakeFullArchiUsersList; Result := f_ArchiUsers.Count; //#UC END# *5729C59E00D5_5629FC88034Bget_impl* end;//TpgUserManager.Get_ArchiUsersCount procedure TpgUserManager.IterateArchiUsersF(anAction: ArchiUsersIterator_IterateArchiUsersF_Action); //#UC START# *5729DD530330_5629FC88034B_var* type PIdaArchiUser = ^IdaArchiUser; function DoIt(aData : PIdaArchiUser; anIndex : Integer) : Boolean; begin Result := anAction(aData^); end; //#UC END# *5729DD530330_5629FC88034B_var* begin //#UC START# *5729DD530330_5629FC88034B_impl* f_ArchiUsers.IterateAllF(l3L2IA(@DoIt)); //#UC END# *5729DD530330_5629FC88034B_impl* end;//TpgUserManager.IterateArchiUsersF function TpgUserManager.UserByID(aID: TdaUserID): IdaArchiUser; //#UC START# *57358B940211_5629FC88034B_var* var i: Integer; l_AU: IdaArchiUser; //#UC END# *57358B940211_5629FC88034B_var* begin //#UC START# *57358B940211_5629FC88034B_impl* Result := nil; if f_ArchiUsers.Count = 0 then MakeFullArchiUsersList; for i := 0 to f_ArchiUsers.Hi do begin l_AU := f_ArchiUsers.Items[i]; if l_AU.ID = aID then begin Result := l_AU; break; end; end //#UC END# *57358B940211_5629FC88034B_impl* end;//TpgUserManager.UserByID function TpgUserManager.UserByLogin(const aLogin: AnsiString): IdaArchiUser; //#UC START# *57358BCB0360_5629FC88034B_var* var i: Integer; l_AU: IdaArchiUser; //#UC END# *57358BCB0360_5629FC88034B_var* begin //#UC START# *57358BCB0360_5629FC88034B_impl* Result := nil; if f_ArchiUsers.Count = 0 then MakeFullArchiUsersList; for i := 0 to f_ArchiUsers.Hi do begin l_AU := f_ArchiUsers.Items[i]; if CompareText(l_AU.LoginName, aLogin) = 0 then begin Result := l_AU; break; end; end //#UC END# *57358BCB0360_5629FC88034B_impl* end;//TpgUserManager.UserByLogin procedure TpgUserManager.UpdateUserInfo(aUserID: TdaUserID; aIsGroup: Boolean); //#UC START# *5735AE4D0017_5629FC88034B_var* //#UC END# *5735AE4D0017_5629FC88034B_var* begin //#UC START# *5735AE4D0017_5629FC88034B_impl* MakeFullArchiUsersList; (* if not aIsGroup then begin GetUserInfo(aUserID, l_Username, l_LoginName, l_AFlag); l_AU:= xxxUserByID(aUserID); if l_AU = nil then begin l_AU:= IdaArchiUser.Make(CalcUserPriorities); try l_AU.ID:= aUserID; l_AU.UserName:= l_UserName; l_AU.LoginName:= l_LoginName; l_AU.Active := Boolean(l_AFlag); finally l3Free(l_AU); end; end; end; *) //#UC END# *5735AE4D0017_5629FC88034B_impl* end;//TpgUserManager.UpdateUserInfo procedure TpgUserManager.MakeFullArchiUsersList; //#UC START# *5735AE7F0071_5629FC88034B_var* var l_ResultSet: IdaResultSet; l_IDField: IdaField; l_NameField: IdaField; l_LoginField: IdaField; l_PasswordField: IdaField; l_FlagsField: IdaField; l_UserInfo : IdaArchiUser; //#UC END# *5735AE7F0071_5629FC88034B_var* begin //#UC START# *5735AE7F0071_5629FC88034B_impl* l_ResultSet := AllArchiUsersQuery.OpenResultSet; try l_IDField := l_ResultSet.Field['id']; l_NameField := l_ResultSet.Field['user_name']; l_LoginField := l_ResultSet.Field['ShortName']; l_PasswordField := l_ResultSet.Field['Password']; l_FlagsField := l_ResultSet.Field['active']; while not l_ResultSet.EOF do begin l_UserInfo := TdaArchiUser.Make(Get_PriorityCalculator); try l_UserInfo.ID := l_IDField.AsLargeInt; l_UserInfo.UserName := l_NameField.AsString; l_UserInfo.LoginName:= l_LoginField.AsString; l_UserInfo.Password := l_PasswordField.AsString; l_UserInfo.Active := (l_FlagsField.AsByte and usActive) = usActive; l_UserInfo.HasAdminRights := (l_UserInfo.ID = usSupervisor) or ((l_FlagsField.AsByte and usAdmin) = usAdmin); f_ArchiUsers.Add(l_UserInfo); finally l_UserInfo := nil; end; l_ResultSet.Next; end; finally l_ResultSet := nil; end; //#UC END# *5735AE7F0071_5629FC88034B_impl* end;//TpgUserManager.MakeFullArchiUsersList function TpgUserManager.GetUserDisplayName(anID: TdaUserID): AnsiString; //#UC START# *5735AECA0121_5629FC88034B_var* var l_Name : AnsiString; l_Flags : Byte; lUser : IdaArchiUser; //#UC END# *5735AECA0121_5629FC88034B_var* begin //#UC START# *5735AECA0121_5629FC88034B_impl* lUser := UserByID(anID); if lUser <> nil then l_Name := lUser.UserName; if l_Name = '' then l_Name := 'Пользователь #'+ IntToStr(anID); Result := ConcatRegionAndUserNames(GetRegionStringFromUserID(anID), l_Name); //#UC END# *5735AECA0121_5629FC88034B_impl* end;//TpgUserManager.GetUserDisplayName function TpgUserManager.IsUserExists(anID: TdaUserID): Boolean; //#UC START# *5739732402E4_5629FC88034B_var* var l_ResultSet: IdaResultSet; //#UC END# *5739732402E4_5629FC88034B_var* begin //#UC START# *5739732402E4_5629FC88034B_impl* UserNameQuery.Param['p_UserID'].AsLargeInt := anID; l_ResultSet := UserNameQuery.OpenResultSet; try Result := not l_ResultSet.IsEmpty; finally l_ResultSet := nil; end; //#UC END# *5739732402E4_5629FC88034B_impl* end;//TpgUserManager.IsUserExists procedure TpgUserManager.RegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber); //#UC START# *5739832A00A2_5629FC88034B_var* //#UC END# *5739832A00A2_5629FC88034B_var* begin //#UC START# *5739832A00A2_5629FC88034B_impl* if f_UserStatusChangedSubscriberList.IndexOf(aSubscriber) = -1 then f_UserStatusChangedSubscriberList.Add(aSubscriber); //#UC END# *5739832A00A2_5629FC88034B_impl* end;//TpgUserManager.RegisterUserStatusChangedSubscriber procedure TpgUserManager.UnRegisterUserStatusChangedSubscriber(const aSubscriber: IdaUserStatusChangedSubscriber); //#UC START# *5739834700B2_5629FC88034B_var* //#UC END# *5739834700B2_5629FC88034B_var* begin //#UC START# *5739834700B2_5629FC88034B_impl* f_UserStatusChangedSubscriberList.Remove(aSubscriber); //#UC END# *5739834700B2_5629FC88034B_impl* end;//TpgUserManager.UnRegisterUserStatusChangedSubscriber procedure TpgUserManager.NotifyUserActiveChanged(anUserID: TdaUserID; anActive: Boolean); //#UC START# *5739835200CF_5629FC88034B_var* type PIdaUserStatusChangedSubscriber = ^IdaUserStatusChangedSubscriber; function DoIt(aData : PIdaUserStatusChangedSubscriber; anIndex : Integer) : Boolean; begin aData^.UserStatusChanged(anUserID, anActive); Result := True; end; //#UC END# *5739835200CF_5629FC88034B_var* begin //#UC START# *5739835200CF_5629FC88034B_impl* f_UserStatusChangedSubscriberList.IterateAllF(l3L2IA(@DoIt)); //#UC END# *5739835200CF_5629FC88034B_impl* end;//TpgUserManager.NotifyUserActiveChanged function TpgUserManager.CSCheckPassword(const aLogin: AnsiString; const aPassword: AnsiString; RequireAdminRights: Boolean; out theUserID: TdaUserID): Boolean; //#UC START# *573AC17202BF_5629FC88034B_var* var l_AU: IdaArchiUser; l_HasAdminRights: Boolean; //#UC END# *573AC17202BF_5629FC88034B_var* begin //#UC START# *573AC17202BF_5629FC88034B_impl* Result := False; if (AnsiLowerCase(aLogin) = c_SupervisorUserName) and not RequireAdminRights then Exit; l_AU := UserByLogin(aLogin); if l_AU <> nil then begin Result := l_AU.Active and ((l_AU.Password = '') or (AnsiCompareText(aPassword, l_AU.Password) = 0)); if Result and RequireAdminRights then Result := l_AU.HasAdminRights; if Result then begin l_AU.LoginDate := Now; theUserID := l_AU.ID; end; end; // l_AU <> nil //#UC END# *573AC17202BF_5629FC88034B_impl* end;//TpgUserManager.CSCheckPassword procedure TpgUserManager.GetUserInfo(aUser: TdaUserID; var aUserName: AnsiString; var aLoginName: AnsiString; var aActFlag: Byte); //#UC START# *573AEE9902DF_5629FC88034B_var* var l_ResultSet: IdaResultSet; //#UC END# *573AEE9902DF_5629FC88034B_var* begin //#UC START# *573AEE9902DF_5629FC88034B_impl* UserLoginQuery.Param['p_UserID'].AsLargeInt := aUser; l_ResultSet := UserLoginQuery.OpenResultSet; try if not l_ResultSet.IsEmpty then aLoginName := l_ResultSet.Field['ShortName'].AsString else aLoginName := c_UnknownLogin; finally l_ResultSet := nil; end; f_UserFlagsQuery.Param['p_UserID'].AsLargeInt := aUser; l_ResultSet := f_UserFlagsQuery.OpenResultSet; try if not l_ResultSet.IsEmpty then begin aUserName := l_ResultSet.Field['user_name'].AsString; aActFlag := l_ResultSet.Field['Active'].AsByte; end else begin aUserName := Format(c_UnknownUserName, [GetRegionStringFromUserID(aUser), aUser]); aActFlag := 0; // не активный и не админ end; finally l_ResultSet := nil; end; //#UC END# *573AEE9902DF_5629FC88034B_impl* end;//TpgUserManager.GetUserInfo function TpgUserManager.Get_PriorityCalculator: IdaPriorityCalculator; //#UC START# *575020410175_5629FC88034Bget_var* //#UC END# *575020410175_5629FC88034Bget_var* begin //#UC START# *575020410175_5629FC88034Bget_impl* if f_PriorityCalculator = nil then f_PriorityCalculator := TpgPriorityCalculator.Make(f_Factory); Result := f_PriorityCalculator; //#UC END# *575020410175_5629FC88034Bget_impl* end;//TpgUserManager.Get_PriorityCalculator procedure TpgUserManager.IterateUserGroupsF(anAction: ArchiUsersIterator_IterateUserGroupsF_Action); //#UC START# *5757D9BB0116_5629FC88034B_var* var Hack : Pointer absolute anAction; l_ResultSet: IdaResultSet; l_IDField: IdaField; l_NameField: IdaField; //#UC END# *5757D9BB0116_5629FC88034B_var* begin //#UC START# *5757D9BB0116_5629FC88034B_impl* try l_ResultSet := AllGroupsQuery.OpenResultSet; try l_IDField := l_ResultSet.Field['id']; l_NameField := l_ResultSet.Field['group_name']; while not l_ResultSet.EOF do begin if not anAction(l_NameField.AsString, l_IDField.AsInteger) then break; l_ResultSet.Next; end; finally l_ResultSet := nil; end; finally l3FreeLocalStub(Hack); end;//try..finally //#UC END# *5757D9BB0116_5629FC88034B_impl* end;//TpgUserManager.IterateUserGroupsF function TpgUserManager.IsMemberOfGroup(aUserGroupID: TdaUserGroupID; aUserID: TdaUserID): Boolean; //#UC START# *575A8B790353_5629FC88034B_var* var l_ResultSet: IdaResultSet; //#UC END# *575A8B790353_5629FC88034B_var* begin //#UC START# *575A8B790353_5629FC88034B_impl* IsMemberOfGroupQuery.Param['p_UserID'].AsLargeInt := aUserID; IsMemberOfGroupQuery.Param['p_GroupID'].AsLargeInt := aUserGroupID; l_ResultSet := IsMemberOfGroupQuery.OpenResultSet; try Result := not l_ResultSet.IsEmpty; finally l_ResultSet := nil; end; //#UC END# *575A8B790353_5629FC88034B_impl* end;//TpgUserManager.IsMemberOfGroup function TpgUserManager.GetUserGroups(aUserID: TdaUserID): TdaUserGroupIDArray; //#UC START# *57625B5002DD_5629FC88034B_var* var l_ResultSet: IdaResultSet; l_Field: IdaField; l_IDX: Integer; //#UC END# *57625B5002DD_5629FC88034B_var* begin //#UC START# *57625B5002DD_5629FC88034B_impl* UserGroupsQuery.Param['p_UserID'].AsLargeInt := aUserID; l_ResultSet := UserGroupsQuery.OpenResultSet(False); try if l_ResultSet.IsEmpty then Result := nil else begin SetLength(Result, l_ResultSet.CalcRecordCount); l_IDX := 0; l_Field := l_ResultSet.Field['group_id']; while not l_ResultSet.EOF do begin Assert(l_IDX < Length(Result)); Result[l_IDX] := l_Field.AsLargeInt; inc(l_IDX); l_ResultSet.Next; end; end; finally l_ResultSet := nil; end; //#UC END# *57625B5002DD_5629FC88034B_impl* end;//TpgUserManager.GetUserGroups procedure TpgUserManager.GetUserGroupsList(aUser: TdaUserID; aList: Tl3StringDataList); //#UC START# *576289510024_5629FC88034B_var* var l_ResultSet: IdaResultSet; l_TmpIndex: LongInt; l_TmpID: TdaUserGroupID; l_Field: IdaField; //#UC END# *576289510024_5629FC88034B_var* begin //#UC START# *576289510024_5629FC88034B_impl* aList.Changing; aList.LockModifiedFlag:=True; try aList.Clear; aList.HostDataList := Get_AllGroups; UserGroupsQuery.Param['p_UserID'].AsLargeInt := aUser; l_ResultSet := UserGroupsQuery.OpenResultSet; try l_Field := l_ResultSet.Field['group_id']; while not l_ResultSet.EOF do begin l_TmpID := l_Field.AsLargeInt; l_TmpIndex := aList.IndexOfData(l_TmpID, cGroupIDSize, 0); if l_TmpIndex <> -1 then aList.Select[l_TmpIndex]:=True; l_ResultSet.Next; end; finally l_ResultSet := nil; end; finally aList.Changed; aList.LockModifiedFlag := False; end; //#UC END# *576289510024_5629FC88034B_impl* end;//TpgUserManager.GetUserGroupsList procedure TpgUserManager.GetUserGroupsList(aUser: TdaUserID; aList: Tl3LongintList); //#UC START# *57628A9403C6_5629FC88034B_var* var l_ResultSet: IdaResultSet; l_TmpID: TdaUserGroupID; l_Field: IdaField; //#UC END# *57628A9403C6_5629FC88034B_var* begin //#UC START# *57628A9403C6_5629FC88034B_impl* //aList.Changing; try aList.Clear; UserGroupsQuery.Param['p_UserID'].AsLargeInt := aUser; l_ResultSet := UserGroupsQuery.OpenResultSet; try l_Field := l_ResultSet.Field['group_id']; while not l_ResultSet.EOF do begin l_TmpID := l_Field.AsLargeInt; aList.Add(l_TmpID); l_ResultSet.Next; end; finally l_ResultSet := nil; end; finally //aList.Changed; end; //#UC END# *57628A9403C6_5629FC88034B_impl* end;//TpgUserManager.GetUserGroupsList procedure TpgUserManager.SetUserGroupsList(aUser: TdaUserID; aList: Tl3StringDataList); //#UC START# *5767ABE002DC_5629FC88034B_var* var l_IDX: Integer; l_Modifier: TpgTableModifier; l_GroupID: TdaUserGroupID; //#UC END# *5767ABE002DC_5629FC88034B_var* begin //#UC START# *5767ABE002DC_5629FC88034B_impl* l_Modifier := TpgTableModifier.Create(da_mtGroupMembers, f_Connection, f_Factory.DataConverter); try l_Modifier.BeginTransaction; try RemoveUserFromAllGroups(aUser); for l_IDX := 0 to aList.Count-1 do if aList.Select[l_IDX] then begin l_GroupID := 0; l3Move(aList.Data[l_IDX]^, l_GroupID, Min(SizeOf(l_GroupID), aList.DataSize)); l_Modifier.Params['user_id'].AsLargeInt := aUser; l_Modifier.Params['group_id'].AsLargeInt := l_GroupID; l_Modifier.Insert; end; l_Modifier.CommitTransaction; except l_Modifier.RollBackTransaction; raise; end; finally FreeAndNil(l_Modifier); end; //#UC END# *5767ABE002DC_5629FC88034B_impl* end;//TpgUserManager.SetUserGroupsList function TpgUserManager.AddUserGroup(const aName: AnsiString): TdaUserGroupID; //#UC START# *576B95A600B9_5629FC88034B_var* //#UC END# *576B95A600B9_5629FC88034B_var* begin //#UC START# *576B95A600B9_5629FC88034B_impl* Result := f_FreeIDHelperHolder.GetFree(da_mtGroups); AddUserGroupWithID(Result, aName); //#UC END# *576B95A600B9_5629FC88034B_impl* end;//TpgUserManager.AddUserGroup procedure TpgUserManager.EditUserGroup(aGroupID: TdaUserGroupID; const aName: AnsiString; aImportPriority: TdaPriority; aExportPriority: TdaPriority); //#UC START# *576B960500C5_5629FC88034B_var* Var l_IDX : LongInt; l_Modifier: TpgTableModifier; //#UC END# *576B960500C5_5629FC88034B_var* begin //#UC START# *576B960500C5_5629FC88034B_impl* l_Modifier := GroupModifier.Use; try l_Modifier.BeginTransaction; try l_Modifier.OldParams['id'].AsLargeInt := aGroupID; l_Modifier.Params['group_name'].AsString := aName; l_Modifier.Params['name_length'].AsInteger := Length(aName); l_Modifier.Params['import_priority'].AsInteger := Ord(aImportPriority); l_Modifier.Params['export_priority'].AsInteger := Ord(aExportPriority); l_Modifier.Update; l_Modifier.CommitTransaction; except l_Modifier.RollBackTransaction; raise; end; finally FreeAndNil(l_Modifier); end; f_Journal.LogEditDict(TdaScheme.Instance.Table(da_mtGroups).FamilyID, da_dlNone, da_eoEdit); (* //!! !!! Что с кэшами в словарях!! if Assigned(fItemList) then if fItemList.FindData(aID,tmpIndex) then TDictITem(fItemList.Items[tmpIndex]).SetSt(aName,StrLen(aName)); *) if f_AllGroups <> nil then begin l_IDX := f_AllGroups.IndexOfData(aGroupID, SizeOf(TdaUserGroupID), 0); f_AllGroups.NeedAllocStr := True; if aName <> '' then f_AllGroups.Strings[l_IDX] := @aName[1] else f_AllGroups.Strings[l_IDX] := nil; end; //#UC END# *576B960500C5_5629FC88034B_impl* end;//TpgUserManager.EditUserGroup procedure TpgUserManager.DelUserGroup(aGroupID: TdaUserGroupID); //#UC START# *576BAC4402D8_5629FC88034B_var* Var l_IDX : LongInt; l_Modifier: TpgTableModifier; l_Function: IdaFunction; //#UC END# *576BAC4402D8_5629FC88034B_var* begin //#UC START# *576BAC4402D8_5629FC88034B_impl* try if f_Connection.BeginTransaction([da_mtGroups, da_mtFree, da_mtGroupMembers, da_mtAccess]) then try // AccessServer.fMaskTbl.DelUserGroup(aUsGroupID); - Опять проблема с синглетонами - HT уже удалит к этому времени все. //!! !!! Needs to be implemented !!! l_Function := f_FunctionFactory.MakeFunction('delete_all_users_from_group'); try l_Function.Param['p_group_id'].AsLargeInt := aGroupID; l_Function.Execute; finally l_Function := nil; end; l_Modifier := GroupModifier.Use; try l_Modifier.OldParams['id'].AsLargeInt := aGroupID; l_Modifier.Delete; finally FreeAndNil(l_Modifier); end; f_Journal.LogEditDict(TdaScheme.Instance.Table(da_mtGroups).FamilyID, da_dlNone, da_eoDelete); f_FreeIDHelperHolder.PutFree(da_mtGroups, aGroupID); f_Connection.CommitTransaction; except f_Connection.RollBackTransaction; raise; end else raise EpgError.Create('Таблицы захвачены, попробуйте позже'); finally FreeAndNil(f_AllGroups); end; //#UC END# *576BAC4402D8_5629FC88034B_impl* end;//TpgUserManager.DelUserGroup procedure TpgUserManager.AddUserGroupShadow(anID: TdaUserGroupID; const aName: AnsiString); //#UC START# *576D17770327_5629FC88034B_var* //#UC END# *576D17770327_5629FC88034B_var* begin //#UC START# *576D17770327_5629FC88034B_impl* AddUserGroupWithID(anID, aName); f_FreeIDHelperHolder.ExcludeFree(da_mtGroups, anID); //#UC END# *576D17770327_5629FC88034B_impl* end;//TpgUserManager.AddUserGroupShadow procedure TpgUserManager.RemoveUserFromAllGroups(aUser: TdaUserID); //#UC START# *577F6AD90170_5629FC88034B_var* var l_Function: IdaFunction; //#UC END# *577F6AD90170_5629FC88034B_var* begin //#UC START# *577F6AD90170_5629FC88034B_impl* l_Function := f_FunctionFactory.MakeFunction('delete_user_from_all_groups'); try l_Function.Param['p_user_id'].AsLargeInt := aUser; l_Function.Execute; finally l_Function := nil; end; //#UC END# *577F6AD90170_5629FC88034B_impl* end;//TpgUserManager.RemoveUserFromAllGroups procedure TpgUserManager.SetUserGroup(aUser: TdaUserID; aGroup: TdaUserGroupID; Add: Boolean = True); //#UC START# *577F80C503AF_5629FC88034B_var* var l_Modifier: TpgTableModifier; //#UC END# *577F80C503AF_5629FC88034B_var* begin //#UC START# *577F80C503AF_5629FC88034B_impl* l_Modifier := TpgTableModifier.Create(da_mtGroupMembers, f_Connection, f_Factory.DataConverter); try l_Modifier.Params['user_id'].AsLargeInt := aUser; l_Modifier.Params['group_id'].AsLargeInt := aGroup; if Add then l_Modifier.Insert else l_Modifier.Delete; finally FreeAndNil(l_Modifier); end; //#UC END# *577F80C503AF_5629FC88034B_impl* end;//TpgUserManager.SetUserGroup procedure TpgUserManager.AdminChangePassWord(aUser: TdaUserID; const NewPass: AnsiString); //#UC START# *5783537E00A1_5629FC88034B_var* var l_Function: IdaFunction; //#UC END# *5783537E00A1_5629FC88034B_var* begin //#UC START# *5783537E00A1_5629FC88034B_impl* if not GlobalDataProvider.AdminRights then raise EpgError.Create('Нет прав для доступа'); l_Function := f_FunctionFactory.MakeFunction('change_password'); try l_Function.Param['p_user_id'].AsLargeInt := aUser; l_Function.Param['p_new_password'].AsString := AnsiUpperCase(NewPass); l_Function.Execute; if l_Function.Param[l_Function.Name+'.Result'].AsInteger <> 1 then raise EpgError.Create('Элемент не найден'); finally l_Function := nil; end; //#UC END# *5783537E00A1_5629FC88034B_impl* end;//TpgUserManager.AdminChangePassWord procedure TpgUserManager.GetHostUserListOnGroup(aGroupID: TdaUserGroupID; aList: Tl3StringDataList; NeedSort: Boolean = False); //#UC START# *578392E7026A_5629FC88034B_var* Var TmpID, TmpIndex : LongInt; l_ResultSet: IdaResultSet; l_Field: IdaField; //#UC END# *578392E7026A_5629FC88034B_var* begin //#UC START# *578392E7026A_5629FC88034B_impl* if f_AllUsers = nil then Get_AllUsers; if NeedSort then f_AllUsers.Sort; try aList.Clear; aList.HostDataList := f_AllUsers; if aGroupID <> 0 then begin GroupUsersQuery.Param['p_GroupID'].AsLargeInt := aGroupID; l_ResultSet := GroupUsersQuery.OpenResultSet; try l_Field := l_ResultSet.Field['user_id']; aList.LockModifiedFlag:=True; while not l_ResultSet.EOF do begin TmpID := l_Field.AsLargeInt; TmpIndex:=aList.IndexOfData(TmpID, aList.DataSize, 0); if TmpIndex<>-1 then aList.Select[TmpIndex]:=True; l_ResultSet.Next; end; aList.LockModifiedFlag:=False; finally l_ResultSet := nil; end; end; finally if NeedSort then ReSortUserList; end; //#UC END# *578392E7026A_5629FC88034B_impl* end;//TpgUserManager.GetHostUserListOnGroup procedure TpgUserManager.SetHostUserListOnGroup(aGroupID: TdaUserGroupID; aList: Tl3StringDataList); //#UC START# *5783933A010B_5629FC88034B_var* var l_IDX: Integer; aID : LongInt; //#UC END# *5783933A010B_5629FC88034B_var* begin //#UC START# *5783933A010B_5629FC88034B_impl* for l_IDX := 0 to aList.Count-1 do if aList.Flags[l_IDX] and lfSelModified = lfSelModified then begin aID:=0; l3Move(aList.Data[l_IDX]^, aID, aList.DataSize); SetUserGroup(aID, aGroupID, aList.Select[l_IDX]); with aList do begin LockSelModify; try Flags[l_IDX] := Flags[l_IDX] and not lfSelModified; finally UnLockSelModify; end; end; end; //#UC END# *5783933A010B_5629FC88034B_impl* end;//TpgUserManager.SetHostUserListOnGroup function TpgUserManager.AddUser(const aUserName: AnsiString; const aLoginName: AnsiString; const aPassword: AnsiString; ActFlag: Byte): TdaUserID; //#UC START# *5784BBF10299_5629FC88034B_var* //#UC END# *5784BBF10299_5629FC88034B_var* begin //#UC START# *5784BBF10299_5629FC88034B_impl* Result := AddUserID(0, aUserName, aLoginName, aPassword, ActFlag); //#UC END# *5784BBF10299_5629FC88034B_impl* end;//TpgUserManager.AddUser function TpgUserManager.AddUserID(anID: TdaUserID; const aUserName: AnsiString; const aLoginName: AnsiString; const aPassword: AnsiString; ActFlag: Byte): TdaUserID; //#UC START# *5784BC420208_5629FC88034B_var* var l_UserName: String; l_Region: TdaRegionID; l_Modifier: TpgTableModifier; //#UC END# *5784BC420208_5629FC88034B_var* begin //#UC START# *5784BC420208_5629FC88034B_impl* if IsUserExists(anID) then raise EpgError.Create('Идентификатор уже используется'); Result := anID; if f_Connection.BeginTransaction([da_mtUsers, da_mtFree, da_mtPassword]) then begin try // В таблице FREE хранятся ID пользователей БЕЗ кода региона, // если добавляем пользователя с существующим ID - таблизу FREE нужно подкорректировать... if (Result <> 0) then begin l_Region := GetUserRegion(Result); if l_Region = GlobalDataProvider.RegionID then // исключаем из FREE только "своих" пользователей f_FreeIDHelperHolder.ExcludeFree(da_mtUsers, GetLocalUserID(Result)); end; if Result >= usAdminReservedHard then raise EpgError.Create('Операция невозможна'); if Result = 0 then begin Result := f_FreeIDHelperHolder.GetFree(da_mtUsers); if GlobalDataProvider.RegionID = cBadRegion then raise EpgError.Create('Не задан код региона!'); // приклеиваем номер региона в старший байт Result := CalcGlobalUserID(Result, GlobalDataProvider.RegionID); end; Assert(not IsWrongUser(Result)); l_Modifier := TpgTableModifier.Create(da_mtUsers, f_Connection, f_Factory.DataConverter); try l_Modifier.Params['id'].AsLargeInt := Result; l_Modifier.Params['user_name'].AsString := aUserName; l_Modifier.Params['name_length'].AsInteger := Length(aUserName); l_Modifier.Params['active'].AsByte := ActFlag; l_Modifier.Insert; finally FreeAndNil(l_Modifier); end; if aLoginName <> '' then begin l_Modifier := TpgTableModifier.Create(da_mtPassword, f_Connection, f_Factory.DataConverter); try l_Modifier.Params['ShortName'].AsString := AnsiUpperCase(aLoginName); l_Modifier.Params['Password'].AsString := AnsiUpperCase(aPassword); l_Modifier.Params['User_ID'].AsLargeInt := Result; l_Modifier.Insert; finally FreeAndNil(l_Modifier); end; end; f_Journal.LogEditDict(TdaScheme.Instance.Table(da_mtUsers).FamilyID, da_dlNone, da_eoAdd); f_Connection.CommitTransaction; except f_Connection.RollBackTransaction; raise; end; end else raise EpgError.Create('Таблицы захвачены, попробуйте позже'); l_UserName := ConcatRegionAndUserNames(Result, aUserName); if f_AllUsers <> nil then begin f_AllUsers.NeedAllocStr := True; f_AllUsers.Add(@l_UserName[1], @Result); SortUsersInList(f_AllUsers); end; //#UC END# *5784BC420208_5629FC88034B_impl* end;//TpgUserManager.AddUserID procedure TpgUserManager.EditUser(aUser: TdaUserID; const aUserName: AnsiString; const aLoginName: AnsiString; ActFlag: Byte; const EditMask: TdaUserEditMask); //#UC START# *5784BD1501E8_5629FC88034B_var* Var TmpIndex : LongInt; // TmpSize : Word; l_UserName: AnsiString; l_Function: IdaFunction; const cMap: array[Boolean] of Integer = (0, 1); //#UC END# *5784BD1501E8_5629FC88034B_var* begin //#UC START# *5784BD1501E8_5629FC88034B_impl* if f_Connection.BeginTransaction([da_mtUsers, da_mtPassword]) then Try l_Function := f_FunctionFactory.MakeFunction('update_user'); try l_Function.Param['p_user_id'].AsLargeInt := aUser; l_Function.Param['p_user_name'].AsString := aUserName; l_Function.Param['p_user_login'].AsString := AnsiUpperCase(aLoginName); l_Function.Param['p_flags'].AsInteger := ActFlag; l_Function.Param['p_change_login'].AsInteger := cMap[EditMask.LoginName]; l_Function.Param['p_change_name'].AsInteger := cMap[EditMask.Name]; l_Function.Param['p_change_flags'].AsInteger := cMap[EditMask.ActivFlag]; l_Function.Execute; finally l_Function := nil; end; f_Journal.LogEditDict(TdaScheme.Instance.Table(da_mtUsers).FamilyID, da_dlNone, da_eoEdit); f_Connection.CommitTransaction; except f_Connection.RollBackTransaction; raise; end else raise EpgError.Create('Таблицы захвачены, попробуйте позже'); if EditMask.Name then begin l_UserName := ConcatRegionAndUserNames(aUser, aUserName); if f_AllUsers <> nil then begin TmpIndex := f_AllUsers.IndexOfData(aUser, SizeOf(TdaUserID), 0); f_AllUsers.NeedAllocStr := True; f_AllUsers.Strings[TmpIndex] := @l_UserName[1]; SortUsersInList(f_AllUsers); end; (* if fIndUList<>nil then begin fIndUList.NeedAllocStr:=True; TmpSize:=StrLen(PAnsichar(@aUserName[1])); fIndUList.Strings[aUser]:=@aUserName[1]; fIndUList.Data[aUser]:=@TmpSize; end; *) end; //#UC END# *5784BD1501E8_5629FC88034B_impl* end;//TpgUserManager.EditUser procedure TpgUserManager.DelUser(aUser: TdaUserID); //#UC START# *5784BE1E02F7_5629FC88034B_var* Var TmpIndex : LongInt; l_Modifier: TpgTableModifier; l_ResultSet: IdaResultSet; //#UC END# *5784BE1E02F7_5629FC88034B_var* begin //#UC START# *5784BE1E02F7_5629FC88034B_impl* if f_Connection.BeginTransaction([da_mtUsers, da_mtFree, da_mtPassword, da_mtGroupMembers]) then Try RemoveUserFromAllGroups(aUser); UserLoginQuery.Param['p_UserID'].AsLargeInt := aUser; l_ResultSet := UserLoginQuery.OpenResultSet; try if not l_ResultSet.IsEmpty then begin l_Modifier := TpgTableModifier.Create(da_mtPassword, f_Connection, f_Factory.DataConverter); try l_Modifier.OldParams['ShortName'].AsString := l_ResultSet.Field['ShortName'].AsString; l_Modifier.Delete; finally FreeAndNil(l_Modifier); end; end; finally l_ResultSet := nil; end; l_Modifier := TpgTableModifier.Create(da_mtUsers, f_Connection, f_Factory.DataConverter); try l_Modifier.OldParams['id'].AsLargeInt := aUser; l_Modifier.Delete; finally FreeAndNil(l_Modifier); end; f_FreeIDHelperHolder.PutFree(da_mtUsers, aUser); f_Journal.LogEditDict(TdaScheme.Instance.Table(da_mtUsers).FamilyID, da_dlNone, da_eoDelete); f_Connection.CommitTransaction; except f_Connection.RollBackTransaction; raise; end else raise EpgError.Create('Таблицы захвачены, попробуйте позже'); if f_AllUsers <> nil then begin TmpIndex := f_AllUsers.IndexOfData(aUser, SizeOf(TdaUserID), 0); f_AllUsers.Delete(TmpIndex); end; //#UC END# *5784BE1E02F7_5629FC88034B_impl* end;//TpgUserManager.DelUser procedure TpgUserManager.GetUserListOnGroup(aUsGroup: TdaUserGroupID; aList: Tl3StringDataList; GetActiveUsersOnly: Boolean = False); //#UC START# *57A87EF901F3_5629FC88034B_var* var l_Query: IdaTabledQuery; l_ResultSet: IdaResultSet; //#UC END# *57A87EF901F3_5629FC88034B_var* begin //#UC START# *57A87EF901F3_5629FC88034B_impl* if aUsGroup = 0 then FillAllUsers(aList) else begin l_Query := f_Factory.MakeTabledQuery( f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtUsers), 'u').Join( f_Factory.MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtGroupMembers), 'm'), da_jkLeftOuter).SetCondition(f_Factory.MakeJoinCondition('u', TdaScheme.Instance.Table(da_mtUsers)['id'], 'm', TdaScheme.Instance.Table(da_mtGroupMembers)['user_id'])) ); try l_Query.WhereCondition := f_Factory.MakeParamsCondition('m', TdaScheme.Instance.Table(da_mtGroupMembers).Field['group_id'], da_copEqual, 'p_GroupID'); if GetActiveUsersOnly then l_Query.WhereCondition := f_Factory.MakeLogicCondition(l_Query.WhereCondition, da_loAnd, f_Factory.MakeBitWiseCondition('u', TdaScheme.Instance.Table(da_mtUsers)['active'], da_bwAnd, usActive)); l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['id'])); l_Query.AddSelectField(f_Factory.MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['user_name'])); l_Query.Prepare; l_Query.Param['p_GroupID'].AsLargeInt := aUsGroup; l_ResultSet := l_Query.OpenResultSet; try FillListByResultSet(aList, l_ResultSet, 'id', cUserIDSize, 'user_name', True); finally l_ResultSet := nil; end; finally l_Query := nil; end; end; SortUsersInList(aList); //#UC END# *57A87EF901F3_5629FC88034B_impl* end;//TpgUserManager.GetUserListOnGroup procedure TpgUserManager.GetFiltredUserList(aList: TStrings; aOnlyActive: Boolean = False); //#UC START# *57A9DF2103CE_5629FC88034B_var* var l_List: TStringList; //#UC END# *57A9DF2103CE_5629FC88034B_var* begin //#UC START# *57A9DF2103CE_5629FC88034B_impl* Assert(Self <> nil); if not aOnlyActive then begin l_List := TStringList.Create; try LoadFiltredUserList(l_List, false); aList.Assign(l_List); finally FreeAndNil(l_List); end; end else begin if f_CacheActiveUserList = nil then begin f_CacheActiveUserList := TStringList.Create; LoadFiltredUserList(f_CacheActiveUserList, true); end; aList.Assign(f_CacheActiveUserList); end; //#UC END# *57A9DF2103CE_5629FC88034B_impl* end;//TpgUserManager.GetFiltredUserList procedure TpgUserManager.GetDocGroupData(aUserGroup: TdaUserGroupID; aFamily: TdaFamilyID; aDocDataList: Tl3StringDataList); //#UC START# *57AC28890131_5629FC88034B_var* //#UC END# *57AC28890131_5629FC88034B_var* begin //#UC START# *57AC28890131_5629FC88034B_impl* Assert(False); //!! !!! Needs to be implemented !!! //#UC END# *57AC28890131_5629FC88034B_impl* end;//TpgUserManager.GetDocGroupData procedure TpgUserManager.PutDocGroupData(aUserGroup: TdaUserGroupID; aFamily: TdaFamilyID; aDocDataList: Tl3StringDataList); //#UC START# *57AC289F0257_5629FC88034B_var* //#UC END# *57AC289F0257_5629FC88034B_var* begin //#UC START# *57AC289F0257_5629FC88034B_impl* Assert(False); //!! !!! Needs to be implemented !!! //#UC END# *57AC289F0257_5629FC88034B_impl* end;//TpgUserManager.PutDocGroupData procedure TpgUserManager.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5629FC88034B_var* //#UC END# *479731C50290_5629FC88034B_var* begin //#UC START# *479731C50290_5629FC88034B_impl* FreeAndNil(f_ArchiUsers); FreeAndNil(f_UserStatusChangedSubscriberList); FreeAndNil(f_AllUsers); FreeAndNil(f_AllGroups); FreeAndNil(f_CacheActiveUserList); f_PasswordQuery := nil; f_UserFlagsQuery := nil; f_UserNameQuery := nil; f_UserLoginQuery := nil; f_PriorityCalculator := nil; f_AllArchiUsersQuery := nil; f_AllGroupsQuery := nil; f_IsMemberOfGroupQuery := nil; f_UserGroupsQuery := nil; f_GroupUsersQuery := nil; f_Factory := nil; f_Journal := nil; FreeAndNil(f_GroupModifier); FreeAndNil(f_FunctionFactory); FreeAndNil(f_FreeIDHelperHolder); FreeAndNil(f_Connection); inherited; //#UC END# *479731C50290_5629FC88034B_impl* end;//TpgUserManager.Cleanup {$IfEnd} // Defined(UsePostgres) end.
unit cCadTipoCulto; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils; // LISTA DE UNITS type TTipoCulto = class private // VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE ConexaoDB: TFDConnection; F_id: Integer; F_descricao: string; F_objetivo: string; public constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA function Inserir: Boolean; function Atualizar: Boolean; function Apagar: Boolean; function Selecionar(id: Integer): Boolean; published // VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE // PARA FORNECER INFORMAÇÕESD EM RUMTIME property id: Integer read F_id write F_id; property descricao: string read F_descricao write F_descricao; property objetivo: string read F_objetivo write F_objetivo; end; implementation {$REGION 'Constructor and Destructor'} constructor TTipoCulto.Create; begin ConexaoDB := aConexao; end; destructor TTipoCulto.Destroy; begin inherited; end; {$ENDREGION} {$REGION 'CRUD'} function TTipoCulto.Apagar: Boolean; var Qry: TFDQuery; begin if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' + IntToStr(F_id) + #13 + 'Descrição: ' + F_descricao, mtConfirmation, [mbYes, mbNo], 0) = mrNO then begin Result := false; Abort; end; Try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM tipo_culto WHERE id=:id '); Qry.ParamByName('id').AsInteger := F_id; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; Finally if Assigned(Qry) then FreeAndNil(Qry) End; end; function TTipoCulto.Atualizar: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE tipo_culto SET descricao=:descricao, objetivo=:objetivo '+ ' WHERE id=:id;'); Qry.ParamByName('id').AsInteger := F_id ; Qry.ParamByName('descricao').AsString := F_descricao; Qry.ParamByName('objetivo').AsString := F_objetivo; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TTipoCulto.Inserir: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO tipo_culto '+ ' (descricao, objetivo) '+ ' VALUES(:descricao, :objetivo)'); Qry.ParamByName('descricao').AsString := F_descricao; Qry.ParamByName('objetivo').AsString := F_objetivo; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TTipoCulto.Selecionar(id: Integer): Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT id, descricao, objetivo FROM tipo_culto '+ ' where id=:id '); Qry.ParamByName('id').AsInteger := id; try Qry.Open; Self.F_id := Qry.FieldByName('id').AsInteger; Self.F_descricao := Qry.FieldByName('descricao').AsString; Self.F_objetivo := Qry.FieldByName('objetivo').AsString; Except Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; {$ENDREGION} end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Edit, FMX.Layouts, FMX.Memo, Script.Interfaces ; type TForm1 = class(TForm, IscriptLog) Button1: TButton; Button2: TButton; Button3: TButton; Edit1: TEdit; Run: TButton; TokensLog: TMemo; procedure Button1Click(Sender: TObject); procedure RunClick(Sender: TObject); private { Private declarations } procedure Log(const aString: String); public { Public declarations } end; var Form1: TForm1; implementation uses Script.Engine ; {$R *.fmx} procedure TForm1.Log(const aString: String); begin TokensLog.Lines.Add(aString); end; procedure TForm1.Button1Click(Sender: TObject); begin Edit1.Text := (Sender As TButton).Text; end; procedure TForm1.RunClick(Sender: TObject); begin TScriptEngine.RunScript('FirstScript.script', Self); end; end.
unit ConnectionSettings; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, DialMessages, Utils, Placemnt, DataErrors; type TConnectionSettingsForm = class(TForm) ConnectionPropsGroupBox: TGroupBox; ServerAddressEdit: TEdit; ServerAddressLabel: TLabel; ServerPortEdit: TEdit; ServerPortLabel: TLabel; ConnectionTimeoutEdit: TEdit; ConnectionTimeoutLabel: TLabel; RequestTimeoutLabel: TLabel; RequestTimeoutEdit: TEdit; CancelButton: TButton; OKButton: TButton; ConnectionTimeoutUnitLabel: TLabel; RequestTimeoutUnitLabel: TLabel; FormPlacement: TFormPlacement; procedure ServerPortEditExit(Sender: TObject); procedure ConnectionTimeoutEditExit(Sender: TObject); procedure RequestTimeoutEditExit(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } public { Public declarations } end; var ConnectionSettingsForm: TConnectionSettingsForm; implementation {$R *.dfm} const MinPortNumber: Integer = 1; MaxPortNumber: Integer = 65535; MinConnectionTimeout: Integer = 100; MaxConnectionTimeout: Integer = 60000; MinRequestTimeout: Integer = 100; MaxRequestTimeout: Integer = 60000; resourcestring rsServerAddressEmpty = 'Server address is empty!'; rsServerPortEmpty = 'Port is empty!'; rsBadServerPort = 'Bad port number!'; rsWrongServerPort = 'Port number must be from %d to %d!'; rsConnectionTimeoutEmpty = 'Connection timeout is empty!'; rsBadConnectionTimeout = 'Bad connection timeout!'; rsWrongConnectionTimeout = 'Connection timeout value must be from %d to %d!'; rsRequestTimeoutEmpty = 'Request timeout is empty!'; rsBadRequestTimeout = 'Bad request timeout!'; rsWrongRequestTimeout = 'Request timeout value must be from %d to %d!'; procedure TConnectionSettingsForm.ServerPortEditExit(Sender: TObject); begin with ServerPortEdit do begin if Text <> EmptyStr then begin if IsError(not StrConsistsOfChars(Text, DecCharSet), rsBadServerPort) then begin SetFocus; end else begin if IsError(not IntBetween(StrToInt(Text), MinPortNumber, MaxPortNumber), Format(rsWrongServerPort, [MinPortNumber, MaxPortNumber])) then begin SetFocus; end; end; end; end; end; procedure TConnectionSettingsForm.ConnectionTimeoutEditExit( Sender: TObject); begin with ConnectionTimeoutEdit do begin if Text <> EmptyStr then begin if IsError(not StrConsistsOfChars(Text, DecCharSet), rsBadConnectionTimeout) then begin SetFocus; end else begin if IsError(not IntBetween(StrToInt(Text), MinConnectionTimeout, MaxConnectionTimeout), Format(rsWrongConnectionTimeout, [MinConnectionTimeout, MaxConnectionTimeout])) then begin SetFocus; end; end; end; end; end; procedure TConnectionSettingsForm.RequestTimeoutEditExit(Sender: TObject); begin with RequestTimeoutEdit do begin if Text <> EmptyStr then begin if IsError(not StrConsistsOfChars(Text, DecCharSet), rsBadRequestTimeout) then begin SetFocus; end else begin if IsError(not IntBetween(StrToInt(Text), MinRequestTimeout, MaxRequestTimeout), Format(rsWrongConnectionTimeout, [MinRequestTimeout, MaxRequestTimeout])) then begin SetFocus; end; end; end; end; end; procedure TConnectionSettingsForm.FormClose(Sender: TObject; var Action: TCloseAction); var ErrorStr: string; begin if ModalResult = mrOk then begin ErrorStr := EmptyStr; CheckError(ServerAddressEdit.Text = EmptyStr, ErrorStr, rsServerAddressEmpty); CheckError(ServerPortEdit.Text = EmptyStr, ErrorStr, rsServerPortEmpty); CheckError(ConnectionTimeoutEdit.Text = EmptyStr, ErrorStr, rsConnectionTimeoutEmpty); CheckError(RequestTimeoutEdit.Text = EmptyStr, ErrorStr, rsRequestTimeoutEmpty); TryCloseModal(ErrorStr, Action); end; end; end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Core.Tick; interface uses Behavior3.Core.Blackboard; type (** * A new Tick object is instantiated every tick by BehaviorTree. It is passed * as parameter to the nodes through the tree during the traversal. * * The role of the Tick class is to store the instances of tree, debug, * target and blackboard. So, all nodes can access these informations. * * For internal uses, the Tick also is useful to store the open node after * the tick signal, in order to let `BehaviorTree` to keep track and close * them when necessary. * * This class also makes a bridge between nodes and the debug, passing the * node state to the debug if the last is provided. * * @module b3 * @class Tick **) TB3Tick = class(TObject) public (** * The tree reference. * @property {b3.BehaviorTree} tree * @readOnly **) FTree: TObject; //use Behavior3.Helper to access Tree as TB3BehaviorTree (** * The debug reference. * @property {Object} debug * @readOnly **) Debug: TObject; (** * The target object reference. * @property {Object} target * @readOnly **) Target: TObject; (** * The blackboard reference. * @property {b3.Blackboard} blackboard * @readOnly **) Blackboard: TB3Blackboard; (** * The list of open nodes. Update during the tree traversal. * @property {Array} _openNodes * @protected * @readOnly **) F_OpenNodes: TObject; //use Behavior3.Helper to access _OpenNodesas TB3BaseNodeList (** * The number of nodes entered during the tick. Update during the tree * traversal. * * @property {Integer} _nodeCount * @protected * @readOnly **) _NodeCount: Integer; (** * Initialization method. * @method initialize * @constructor **) constructor Create; virtual; destructor Destroy; override; (** * Called when entering a node (called by BaseNode). * @method _enterNode * @param {Object} node The node that called this method. * @protected **) procedure _EnterNode(Node: TObject); (** * Callback when opening a node (called by BaseNode). * @method _openNode * @param {Object} node The node that called this method. * @protected **) procedure _OpenNode(Node: TObject); (** * Callback when ticking a node (called by BaseNode). * @method _tickNode * @param {Object} node The node that called this method. * @protected **) procedure _TickNode(Node: TObject); (** * Callback when closing a node (called by BaseNode). * @method _closeNode * @param {Object} node The node that called this method. * @protected **) procedure _CloseNode(Node: TObject); (** * Callback when exiting a node (called by BaseNode). * @method _exitNode * @param {Object} node The node that called this method. * @protected **) procedure _ExitNode(Node: TObject); end; implementation { TB3Tick } uses Behavior3.Helper, Behavior3.Core.BaseNode; constructor TB3Tick.Create; begin inherited; F_OpenNodes := TB3BaseNodeList.Create(False); end; destructor TB3Tick.Destroy; begin _OpenNodes.Free; inherited; end; procedure TB3Tick._EnterNode(Node: TObject); begin Inc(_NodeCount); _OpenNodes.Add(Node as TB3BaseNode); // TODO: call debug here end; procedure TB3Tick._OpenNode(Node: TObject); begin // TODO: call debug here end; procedure TB3Tick._TickNode(Node: TObject); begin // TODO: call debug here end; procedure TB3Tick._CloseNode(Node: TObject); begin // TODO: call debug here _openNodes.Remove(Node as TB3BaseNode); // _OpenNodes.Delete(_OpenNodes.Count - 1); end; procedure TB3Tick._ExitNode(Node: TObject); begin // TODO: call debug here end; end.
unit uInterfaceEmail; interface type IEmail = interface; IEstrategiaEnvio = Interface ['{354DBF1C-7BBB-40C0-82B8-999BB4BB6B02}'] procedure Enviar(email: IEmail; SSL : Boolean = True; aFileAnexo : String = ''); end; IEmail = Interface ['{8A3E0D05-AC6D-4ED0-BBF7-616A66B1C49C}'] procedure SetAssunto(const Value: String); procedure SetDestinatarioEmail(const Value: String); procedure SetDestinatarioNome(const Value: String); procedure SetSenha(const Value: String); procedure SetPorta(const Value: Integer); procedure SetRemetenteEmail(const Value: String); procedure SetRemetenteNome(const Value: String); procedure SetUsuario(const Value: String); procedure SetMensagem(const Value: String); procedure SetHost(const Value: String); procedure SetAnexo(const Value: String); procedure SetAnexo2(const Value: String); procedure SetListaAnexos(const Value : String); function GetAssunto : String; function GetDestinatarioNome : String; function GetDestinatarioEmail : String; function GetRemetenteEmail : String; function GetRemetenteNome : String; function GetMensagem : String; function GetSenha : String; function GetHost : String; function GetUsuario : String; function GetPorta : Integer; function GetAnexo : String; function GetAnexo2 : String; Function GetListaAnexos : String; property RemetenteEmail : String read GetRemetenteEmail write SetRemetenteEmail; property DestinatarioEmail : String read GetDestinatarioEmail write SetDestinatarioEmail; property RemetenteNome : String read GetRemetenteNome write SetRemetenteNome; property DestinatarioNome : String read GetDestinatarioNome write SetDestinatarioNome; property Assunto : String read GetAssunto write SetAssunto; property Mensagem : String read GetMensagem write SetMensagem; property Usuario : String read GetUsuario write SetUsuario; property Senha : String read GetSenha write SetSenha; property Host : String read GetHost write SetHost; property Porta : Integer read GetPorta write SetPorta; property Anexo : String read GetAnexo write SetAnexo; property Anexo2 : String read GetAnexo2 write SetAnexo2; property ListaAnexos : String read GetListaAnexos write SetListaAnexos; procedure Enviar(EstrategiaDeEnvio:IEstrategiaEnvio; SSL : Boolean = True; aFileAnexo : String = ''); end; EmailContexto = class(TInterfacedObject, IEmail) private FEstrategiaDeEnvio: IEstrategiaEnvio; FDestinatarioEmail: String; FRemetenteNome: String; FPorta: Integer; FRemetenteEmail: String; FAssunto: String; FSenha : String; FDestinatarioNome: String; FMensagem : String; FHost : String; FUsuario : String; FAnexo : String; FAnexo2 : String; FListaAnexos : String; function GetAssunto: String; function GetDestinatarioEmail: String; function GetDestinatarioNome: String; function GetHost: String; function GetMensagem: String; function GetPorta: Integer; function GetRemetenteEmail: String; function GetRemetenteNome: String; function GetSenha: String; function GetUsuario: String; function GetAnexo : String; function GetAnexo2 : String; Function GetListaAnexos : String; procedure SetAssunto(const Value: String); procedure SetDestinatarioEmail(const Value: String); procedure SetDestinatarioNome(const Value: String); procedure SetHost(const Value: String); procedure SetMensagem(const Value: String); procedure SetPorta(const Value: Integer); procedure SetRemetenteEmail(const Value: String); procedure SetRemetenteNome(const Value: String); procedure SetSenha(const Value: String); procedure SetUsuario(const Value: String); procedure SetGetAnexo(const Value: String); procedure SetAnexo(const Value: String); procedure SetAnexo2(const Value: String); procedure SetListaAnexos(const Value : String); public property RemetenteEmail : String read GetRemetenteEmail write SetRemetenteEmail; property DestinatarioEmail : String read GetDestinatarioEmail write SetDestinatarioEmail; property RemetenteNome : String read GetRemetenteNome write SetRemetenteNome; property DestinatarioNome : String read GetDestinatarioNome write SetDestinatarioNome; property Assunto : String read GetAssunto write SetAssunto; property Mensagem : String read GetMensagem write SetMensagem; property Usuario : String read GetUsuario write SetUsuario; property Senha : String read GetSenha write SetSenha; property Host : String read GetHost write SetHost; property Porta : Integer read GetPorta write SetPorta; property Anexo : String read GetAnexo write SetAnexo; property Anexo2 : String read GetAnexo2 write SetAnexo2; property ListaAnexos : String read GetListaAnexos write SetListaAnexos; procedure Enviar(EstrategiaDeEnvio:IEstrategiaEnvio; SSL : Boolean = True; aFileAnexo : String = ''); end; implementation { EmailContexto } procedure EmailContexto.Enviar(EstrategiaDeEnvio: IEstrategiaEnvio; SSL: Boolean; aFileAnexo : String); begin FEstrategiaDeEnvio := EstrategiaDeEnvio; FEstrategiaDeEnvio.Enviar(self, SSL); end; function EmailContexto.GetAnexo: String; begin Result := FAnexo; end; function EmailContexto.GetAnexo2: String; begin Result := FAnexo2; end; function EmailContexto.GetAssunto: String; begin result := FAssunto; end; function EmailContexto.GetDestinatarioEmail: String; begin result := FDestinatarioEmail; end; function EmailContexto.GetDestinatarioNome: String; begin result := FDestinatarioNome; end; function EmailContexto.GetHost: String; begin result := FHost; end; function EmailContexto.GetListaAnexos: String; begin Result := FListaAnexos; end; function EmailContexto.GetMensagem: String; begin result := FMensagem; end; function EmailContexto.GetPorta: Integer; begin result := FPorta; end; function EmailContexto.GetRemetenteEmail: String; begin result := FRemetenteEmail; end; function EmailContexto.GetRemetenteNome: String; begin result := FRemetenteNome; end; function EmailContexto.GetSenha: String; begin result := FSenha; end; function EmailContexto.GetUsuario: String; begin result := FUsuario; end; procedure EmailContexto.SetAnexo(const Value: String); begin FAnexo := Value; end; procedure EmailContexto.SetAnexo2(const Value: String); begin FAnexo2 := Value; end; procedure EmailContexto.SetAssunto(const Value: String); begin FAssunto := value; end; procedure EmailContexto.SetDestinatarioEmail(const Value: String); begin FDestinatarioEmail := value; end; procedure EmailContexto.SetDestinatarioNome(const Value: String); begin FDestinatarioNome := value; end; procedure EmailContexto.SetGetAnexo(const Value: String); begin FAnexo := Value; end; procedure EmailContexto.SetHost(const Value: String); begin FHost := value; end; procedure EmailContexto.SetListaAnexos(const Value: String); begin FListaAnexos := Value; end; procedure EmailContexto.SetMensagem(const Value: String); begin FMensagem := value; end; procedure EmailContexto.SetPorta(const Value: Integer); begin FPorta := value; end; procedure EmailContexto.SetRemetenteEmail(const Value: String); begin FRemetenteEmail := value; end; procedure EmailContexto.SetRemetenteNome(const Value: String); begin FRemetenteNome := value; end; procedure EmailContexto.SetSenha(const Value: String); begin FSenha := Value; end; procedure EmailContexto.SetUsuario(const Value: String); begin FUsuario := Value; end; end.
unit MemMapFile; interface uses Windows; type TFileMap = class public constructor Create(const aFileName : string); destructor Destroy; override; private fFileHandle : THandle; fFileMap : THandle; fAddress : pointer; fSize : integer; public property Address : pointer read fAddress; property Size : integer read fSize; end; implementation uses SysUtils; constructor TFileMap.Create(const aFileName : string); begin inherited Create; fFileHandle := CreateFile(pchar(aFilename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); //runerror( 7 ); if fFileHandle = INVALID_HANDLE_VALUE then raise Exception.Create('Cannot open file'); fSize := GetFileSize(fFileHandle, nil); try fFileMap := CreateFileMapping(fFileHandle, nil, PAGE_READONLY, 0, fSize, nil); if fFileMap = 0 then raise Exception.Create('Cannot map file'); try fAddress := MapViewOfFile(fFileMap, FILE_MAP_READ, 0, 0, 0); if fAddress = nil then raise Exception.Create('Cannot get map file pointer'); except CloseHandle(fFileMap); raise; end; except CloseHandle(fFileHandle); raise; end; end; destructor TFileMap.Destroy; begin UnmapViewOfFile(fAddress); CloseHandle(fFileMap); CloseHandle(fFileHandle); inherited; end; end.
{ Date Created: 5/24/00 2:00:44 PM } unit InfoSOACODESTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoSOACODESRecord = record PCode: String[3]; PDescription: String[13]; End; TInfoSOACODESBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoSOACODESRecord end; TEIInfoSOACODES = (InfoSOACODESPrimaryKey); TInfoSOACODESTable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetEnumIndex(Value: TEIInfoSOACODES); function GetEnumIndex: TEIInfoSOACODES; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoSOACODESRecord; procedure StoreDataBuffer(ABuffer:TInfoSOACODESRecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoSOACODES read GetEnumIndex write SetEnumIndex; end; { TInfoSOACODESTable } procedure Register; implementation procedure TInfoSOACODESTable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; end; { TInfoSOACODESTable.CreateFields } procedure TInfoSOACODESTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoSOACODESTable.SetActive } procedure TInfoSOACODESTable.Validate; begin { Enter Validation Code Here } end; { TInfoSOACODESTable.Validate } procedure TInfoSOACODESTable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoSOACODESTable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoSOACODESTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoSOACODESTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoSOACODESTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 3, N'); Add('Description, String, 13, N'); end; end; procedure TInfoSOACODESTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoSOACODESTable.SetEnumIndex(Value: TEIInfoSOACODES); begin case Value of InfoSOACODESPrimaryKey : IndexName := ''; end; end; function TInfoSOACODESTable.GetDataBuffer:TInfoSOACODESRecord; var buf: TInfoSOACODESRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; result := buf; end; procedure TInfoSOACODESTable.StoreDataBuffer(ABuffer:TInfoSOACODESRecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; end; function TInfoSOACODESTable.GetEnumIndex: TEIInfoSOACODES; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoSOACODESPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoSOACODESTable, TInfoSOACODESBuffer ] ); end; { Register } function TInfoSOACODESBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; end; end; end. { InfoSOACODESTable }
unit GradientBox; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TGradientDirection = (gdHorizontal, gdVertical); type TGradientBox = class(TGraphicControl) public constructor Create(AOwner : TComponent); override; destructor Destroy; override; protected fFromColor : TColor; fToColor : TColor; fDirection : TGradientDirection; fBitmap : TBitMap; private procedure ReDrawBmp; public procedure Paint; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private procedure SetDirection(aDirection : TGradientDirection); procedure SetFromColor(aColor : TColor); procedure SetToColor(aColor : TColor); published property Direction : TGradientDirection read fDirection write SetDirection; property FromColor : TColor read fFromColor write SetFromColor; property ToColor : TColor read fToColor write SetToColor; property Align; property Text; property DragCursor; property DragMode; property Enabled; property Font; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; //property TabOrder; //property TabStop; property Visible; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation uses GradientUtils; constructor TGradientBox.Create(AOwner : TComponent); begin inherited; fBitmap := TBitmap.Create; fFromColor := clWhite; fToColor := clBlack; end; destructor TGradientBox.Destroy; begin fBitmap.Free; inherited; end; procedure TGradientBox.ReDrawBmp; begin GradientUtils.Gradient(fBitmap.Canvas, fFromColor, fToColor, fDirection = gdHorizontal, ClientRect); end; procedure TGradientBox.Paint; begin Canvas.CopyRect(ClientRect, fBitmap.Canvas, ClientRect); end; procedure TGradientBox.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited; fBitmap.Width := Width; fBitmap.Height := Height; ReDrawBmp; end; procedure TGradientBox.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TGradientBox.SetDirection(aDirection : TGradientDirection); begin fDirection := aDirection; ReDrawBmp; Invalidate; end; procedure TGradientBox.SetFromColor(aColor : TColor); begin fFromColor := ColorToRGB(aColor); ReDrawBmp; Invalidate; end; procedure TGradientBox.SetToColor(aColor : TColor); begin fToColor := ColorToRGB(aColor); ReDrawBmp; Invalidate; end; procedure Register; begin RegisterComponents('Five', [TGradientBox]); end; end.
unit WPIOMime; //****************************************************************************** // WPTools V6 - THE word processing component for VCL and .NET // Copyright (C) 2008 by WPCubed GmbH and Julian Ziersch, all rights reserved // WEB: http://www.wpcubed.com mailto: support@wptools.de //****************************************************************************** // WPIOMIME - WPTools 7 MIME writer and reader. // requires the units mimemess, mimepart, // synafpc, synachar, synacode, synautil, mimeinln // of the library Synapse: http://www.ararat.cz/synapse/ //****************************************************************************** interface uses SysUtils, Classes, WPRTEDefs, WPRTEDefsConsts, WPIOAnsi, WPIOHtml, // 3rd party SYNAPSE units mimemess, mimepart, synafpc, synachar, synacode, synautil, mimeinln; type TWPMimeWriter = class(TWPHTMLWriter) private FMessage: TMimeMess; FMultiPart, FHTMLPart, FTextPart: TMimePart; FOld_fpOut: TStream; FOptNoHTML: Boolean; FOptNoPLAIN: Boolean; FNullStream: TStream; function GetHeader: TMessHeader; protected class function UseForFilterName(const Filtername: string): Boolean; override; // RTF, HTML or classname public property MimeHeader: TMessHeader read GetHeader; constructor Create(RTFDataCollection: TWPRTFDataCollectionBase); override; destructor Destroy; override; procedure SetOptions(optstr: string); override; function WriteHeader: Boolean; override; procedure WriteMainText; override; function WriteFooter: Boolean; override; //:: Option -nohtml, do not save HTML text property OptNoHTML: Boolean read FOptNoHTML write FOptNoHTML; //:: Option -noplain, do not save PLAIN text property OptNoPLAIN: Boolean read FOptNoPLAIN write FOptNoPLAIN; end; TWPMimeReader = class(TWPHTMLReader) { from WPTools.RTE.Defs } protected class function UseForFilterName(const Filtername: string): Boolean; override; class function UseForContents(const First500Char: AnsiString): Boolean; override; public procedure SetOptions(optstr: string); override; function Parse(datastream: TStream): TWPRTFDataBlock; override; end; implementation // ----------------------------------------------------------------------------- type TWPNullStream = class(TStream) private FSize, FPosition: Integer; public function Read(var Buffer; Count: Longint): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; end; function TWPNullStream.Read(var Buffer; Count: Longint): Longint; begin inc(FPosition, Count); Result := Count; end; function TWPNullStream.Write(const Buffer; Count: Longint): Longint; begin inc(FPosition, Count); if FPosition > FSize then FSize := FPosition; Result := Count; end; function TWPNullStream.Seek(Offset: Longint; Origin: Word): Longint; begin case Origin of soFromBeginning: FPosition := Offset; soFromCurrent: Inc(FPosition, Offset); soFromEnd: FPosition := FSize + Offset; end; Result := FPosition; end; // ----------------------------------------------------------------------------- class function TWPMimeReader.UseForFilterName(const Filtername: string): Boolean; begin Result := (CompareText(Filtername, 'TWPMimeReader') = 0) // not "inherited" or (CompareText(Filtername, 'MIME') = 0) or (CompareText(Filtername, 'MHT') = 0) or (CompareText(Filtername, 'MSG') = 0) or (CompareText(Filtername, 'EML') = 0); end; class function TWPMimeReader.UseForContents(const First500Char: AnsiString): Boolean; var i: Integer; begin i := Pos('MIME-Version:', First500Char); if i = 0 then i := Pos('X-Envelope-', First500Char); if i = 0 then i := Pos('Content-Type:', First500Char); Result := (i > 0); end; procedure TWPMimeReader.SetOptions(optstr: string); begin inherited SetOptions(optstr); FSkipCRNL := true; end; function TWPMimeReader.Parse(datastream: TStream): TWPRTFDataBlock; var FMessage: TMimeMess; p, imgnr: Integer; FHTMLPart, FTextPart: TMimePart; old_fpin: TStream; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure ProcessMimePart(subpart: TMimePart); var n: Integer; p, s: string; img: TWPTextReaderWriterEmbeddedData; // requires $DEFINE WP6 procedure Check(part: TMimePart); function GetParam(n: string): string; var a: Integer; pn: string; begin Result := ''; for a := 0 to part.Headers.Count - 1 do begin pn := part.Headers[a]; if SameText(n, Copy(pn, 1, Length(n))) then begin Result := Trim(Copy(pn, Length(n) + 1, Length(pn))); break; end; end; end; var buf: AnsiString; jj: Integer; begin p := LowerCase(part.Primary); s := LowerCase(part.Secondary); if (s = 'html') and (p = 'text') then begin FHTMLPart := part; {$IFDEF xx_DEBUG_SAVEBODY} part.DecodePart; part.DecodedLines.SaveToFile( 'c:\' + LoadName + '.htm' ); {$ENDIF} end else if (s = 'plain') and (p = 'text') then begin if FTextPart=nil then FTextPart := part; end else if p = 'multipart' then begin ProcessMimePart(part); end else if (p = 'image') or (p = 'application') or (s='unknown') then try if (s='unknown') then s := Lowercase(Copy(ExtractFileExt( part.FileName ),2, 10)); if Pos('jpeg',s)>0 then s := 'jpeg'; // image/x-citrix-jpeg - 7.8.2012 if (s = 'gif') or (s = 'bmp') or (s = 'jpeg') or (s = 'png') or (s = 'jpg') or (s = 'emf') or (s = 'wmf') then begin img := AddEmbeddedImageData; img.Cid := part.ContentID; img.FileName := part.FileName; img.Location := GetParam('Content-Location:'); inc(imgnr); if img.FileName = '' then img.FileName := 'image' + IntToStr(imgnr) + '.' + s; // SYNAPSE WorkAround for Binary Data if SameText(part.Encoding, 'Binary') then begin part.DecodedLines.Clear; for jj := 0 to part.PartBody.Count - 1 do begin buf := part.PartBody[jj]; if Length(buf) > 0 then part.DecodedLines.Write(buf[1], Length(buf)); end; end else part.DecodePart; img.DataRef := part.DecodedLines; end; except end; end; begin if CompareText(subpart.primary, 'multipart') <> 0 then Check(subpart); for n := 0 to subpart.GetSubPartCount - 1 do Check(subpart.GetSubPart(n)); end; // We need to load binary ++++++++++++++++++++++++++++++++++++++++++++++++++++ procedure LoadIntoStringList(str: TStringList; const Value: AnsiString); var P, Start: PAnsiChar; S: AnsiString; l: Integer; begin str.BeginUpdate; try str.Clear; P := Pointer(Value); l := Length(Value); if P <> nil then while l > 0 do begin Start := P; while not (P^ = #10) and (l > 0) do begin dec(l); Inc(P); end; if P^ = #10 then begin dec(l); Inc(P); end; SetString(S, Start, P - Start); while (Length(s)>0) and ((s[Length(s)]=#13) or (s[Length(s)]=#10)) do Delete(s, Length(s),1); str.Add(S); end; finally str.EndUpdate; end; end; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ var data: AnsiString; begin Result := nil; imgnr := 0; FMessage := nil; FHTMLPart := nil; FTextPart := nil; p := datastream.Position; if datastream.Size - p>0 then try FMessage := TMimeMess.Create; SetLength(data, datastream.Size - p); datastream.Read(data[1], Length(data)); LoadIntoStringList(FMessage.Lines, data); SetLength(data, 0); try FMessage.DecodeMessage; ProcessMimePart(FMessage.MessagePart); if FHTMLPart <> nil then begin FHTMLPart.Decodepart; old_fpin := fpin; fpin := FHTMLPart.DecodedLines; FCopyOfBodyData := TMemoryStream.Create; FCopyOfBodyData.LoadFromStream( FHTMLPart.DecodedLines ); FCopyOfBodyData.Position := 0; FHTMLPart.DecodedLines.Position := 0; _UseImageElements := true; //DEBUG {$IFDEF WPDEBUG} //FHTMLPart.DecodedLines.SaveToFile('s:\debug\a.htm'); {$ENDIF} try Result := inherited Parse(FHTMLPart.DecodedLines); finally fpin := old_fpin; end; end else if FTextPart <> nil then begin FTextPart.Decodepart; {$IFDEF WPDEBUG} //FTextPart.DecodedLines.SaveToFile('s:\debug\a.txt'); {$ENDIF} old_fpin := fpin; fpin := FTextPart.DecodedLines; _UseImageElements := false; OptIgnoreSTDHTML := true; FOptuseCR := true; try Result := inherited Parse(FTextPart.DecodedLines); finally fpin := old_fpin; end; end; except datastream.Position := p; Result := inherited Parse(datastream); end; finally FMessage.Free; end; end; // ----------------------------------------------------------------------------- constructor TWPMimeWriter.Create(RTFDataCollection: TWPRTFDataCollectionBase); begin inherited Create(RTFDataCollection); FMessage := TMimeMess.Create; FNullStream := TWPNullStream.Create; FMessage.Header.XMailer := 'WPTools/TextDynamic'; FMultiPart := FMessage.AddPartMultipart('', nil); _UseImageElements := TRUE; FBeforeHeader := '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'; end; destructor TWPMimeWriter.Destroy; begin FMessage.Free; FNullStream.Free; inherited Destroy; end; function TWPMimeWriter.GetHeader: TMessHeader; begin Result := FMessage.Header; end; class function TWPMimeWriter.UseForFilterName(const Filtername: string): Boolean; begin Result := (CompareText(Filtername, 'TWPMimeWriter') = 0) // not "inherited" or (CompareText(Filtername, 'MIME') = 0) or (CompareText(Filtername, 'MHT') = 0) or (CompareText(Filtername, 'MSG') = 0) or (CompareText(Filtername, 'EML') = 0); end; procedure TWPMimeWriter.SetOptions(optstr: string); var i: Integer; aoptstr: string; begin i := Pos('-', optstr); if i > 0 then begin aoptstr := lowercase(Copy(optstr, i, Length(optstr) - i + 1)) + ','; FOptNoHTML := Pos('-nohtml,', aoptstr) > 0; FOptNoPLAIN := Pos('-noplain,', aoptstr) > 0; end; inherited SetOptions(optstr); end; // Start writing - redirect the HTML output to a stream or "null" function TWPMimeWriter.WriteHeader: Boolean; begin FOld_fpOut := fpOut; if not OptNoHTML then begin FHTMLPart := FMessage.AddPart(FMultiPart); fpOut := FHTMLPart.DecodedLines; end else fpOut := FNullStream; if not OptNoPlain then begin FTextPart := FMessage.AddPart(FMultiPart); end; Result := inherited WriteHeader; end; procedure TWPMimeWriter.WriteMainText; begin // Now we save the body (--> WPIOHTML.WriteBody) inherited; end; function TWPMimeWriter.WriteFooter: Boolean; var FBinary: TMimePart; i: Integer; data: TWPTextReaderWriterEmbeddedData; ex: string; AnsiWriter: TWPCustomTextWriter; mem: TMemoryStream; str: TStringList; begin Result := inherited WriteFooter; WriteBufferFlush; fpOut := FOld_fpOut; FOld_fpOut := nil; // --------------------------------------------------------------------------- if not OptNoPlain then begin AnsiWriter := TWPTextWriter.Create(RTFDataCollection); mem := TMemoryStream.Create; str := TStringList.Create; try AnsiWriter.WriteImagePlaceholder := true; AnsiWriter.WriteOnlySelection := WriteOnlySelection; AnsiWriter.WriteCellSelection := WriteCellSelection; AnsiWriter.WriteText(mem, _body, _spar, _epar, _spos, _epos); mem.Position := 0; str.LoadFromStream(mem); FTextPart := FMessage.AddPartText(str, FMultiPart); FTextPart.EncodePart; FTextPart.EncodePartHeader; finally mem.Free; str.Free; AnsiWriter.Free; end; end; // --------------------------------------------------------------------------- if FHTMLPart <> nil then with FHTMLPart do begin Primary := 'text'; Secondary := 'html'; Description := 'Message text'; Disposition := 'inline'; CharsetCode := UTF_8; EncodingCode := ME_QUOTED_PRINTABLE; EncodePart; EncodePartHeader; end; // --------------------------------------------------------------------------- RTFDataCollection.FinalizeMIME(Self); // --------------------------------------------------------------------------- for i := 0 to EmbeddedImageElements.Count - 1 do begin data := EmbeddedImageElements[i]; if data <> nil then begin EmbeddedImageElements[i] := nil; try // Dont use FileName FBinary := FMessage.AddPartHTMLBinary(data.data, '', data.Cid, FMultiPart); FBinary.Description := data.Description; if data.FileName <> '' then begin ex := lowercase(ExtractFileExt(data.FileName)); if (ex <> '') and (ex[1] = '.') then begin Delete(ex, 1, 1); if ex = 'jpg' then ex := 'jpeg'; if (ex = 'gif') or (ex = 'bmp') or (ex = 'emf') or (ex = 'wmf') or (ex = 'jpeg') or (ex = 'png') then FBinary.Primary := 'image' else FBinary.Primary := 'application'; FBinary.Secondary := ex; end; end; FBinary.EncodePartHeader; // Encode changes to properties if data.Location <> '' then FBinary.Headers.Append('Content-Location: ' + data.Location) else if data.Filename <> '' then FBinary.Headers.Append('Content-Location: ' + data.Filename); finally data.Free; end; end; end; // --------------------------------------------------------------------------- FMessage.EncodeMessage; FMessage.Lines.SaveToStream(fpout); end; initialization WPHasMIMEFilter := true; if GlobalWPToolsCustomEnviroment <> nil then begin GlobalWPToolsCustomEnviroment.RegisterReader([TWPMimeReader]); GlobalWPToolsCustomEnviroment.RegisterWriter([TWPMimeWriter]); end; end.
unit QuickList_MinuteData; interface uses QuickSortList, define_datetime, define_stock_quotes; type {---------------------------------------} PMinuteDataListItem = ^TMinuteDataListItem; TMinuteDataListItem = record //StockDateTime: Double; StockDateTime: TDateTimeStock; MinuteData: PRT_Quote_Minute; end; { 行情分钟线数据访问 } TMinuteDataList = class(TALBaseQuickSortList) public function GetItem(Index: Integer): TDateTimeStock; procedure SetItem(Index: Integer; const AStockDateTime: TDateTimeStock); function GetMinuteData(Index: Integer): PRT_Quote_Minute; procedure PutMinuteData(Index: Integer; AMinuteData: PRT_Quote_Minute); public procedure Notify(Ptr: Pointer; Action: TListNotification); override; procedure InsertItem(Index: Integer; const AStockDateTime: TDateTimeStock; AMinuteData: PRT_Quote_Minute); function CompareItems(const Index1, Index2: Integer): Integer; override; public function IndexOf(AStockDateTime: TDateTimeStock): Integer; function IndexOfMinuteData(AMinuteData: PRT_Quote_Minute): Integer; Function AddMinuteData(const AStockDateTime: TDateTimeStock; AMinuteData: PRT_Quote_Minute): Integer; function Find(AStockDateTime: TDateTimeStock; var Index: Integer): Boolean; procedure InsertObject(Index: Integer; const AStockDateTime: TDateTimeStock; AMinuteData: PRT_Quote_Minute); property MinuteTime[Index: Integer]: TDateTimeStock read GetItem write SetItem; default; property MinuteData[Index: Integer]: PRT_Quote_Minute read GetMinuteData write PutMinuteData; end; implementation {********************************************************************************} function TMinuteDataList.AddMinuteData(const AStockDateTime: TDateTimeStock; AMinuteData: PRT_Quote_Minute): Integer; begin if not Sorted then begin Result := FCount end else if Find(AStockDateTime, Result) then begin case Duplicates of lstDupIgnore: Exit; lstDupError: Error(@SALDuplicateItem, 0); end; end; InsertItem(Result, AStockDateTime, AMinuteData); end; {*****************************************************************************************} procedure TMinuteDataList.InsertItem(Index: Integer; const AStockDateTime: TDateTimeStock; AMinuteData: PRT_Quote_Minute); Var tmpDoubleListItem: PMinuteDataListItem; begin New(tmpDoubleListItem); tmpDoubleListItem^.StockDateTime := AStockDateTime; tmpDoubleListItem^.MinuteData := AMinuteData; try inherited InsertItem(index, tmpDoubleListItem); except Dispose(tmpDoubleListItem); raise; end; end; {***************************************************************************} function TMinuteDataList.CompareItems(const Index1, Index2: integer): Integer; var tmpItem1, tmpItem2: PMinuteDataListItem; begin tmpItem1 := PMinuteDataListItem(Get(Index1)); tmpItem2 := PMinuteDataListItem(Get(Index2)); Result := tmpItem1^.StockDateTime.Date.Value - tmpItem2^.StockDateTime.Date.Value; if 0 = Result then begin Result := tmpItem1^.StockDateTime.Time.Value - tmpItem2^.StockDateTime.Time.Value; end; //result := PMinuteDataListItem(Get(Index1))^.FDouble - PMinuteDataListItem(Get(Index2))^.FDouble; end; {***********************************************************************} function TMinuteDataList.Find(AStockDateTime: TDateTimeStock; var Index: Integer): Boolean; var L: Integer; H: Integer; I: Integer; C: double; begin Result := False; L := 0; H := FCount - 1; while L <= H do begin I := (L + H) shr 1; C := Integer(GetItem(I)) - Integer(AStockDateTime); if C < 0 then begin L := I + 1 end else begin H := I - 1; if C = 0 then begin Result := True; if Duplicates <> lstDupAccept then L := I; end; end; end; Index := L; end; {*******************************************************} function TMinuteDataList.GetItem(Index: Integer): TDateTimeStock; begin Result := PMinuteDataListItem(Get(index))^.StockDateTime end; {******************************************************} function TMinuteDataList.IndexOf(AStockDateTime: TDateTimeStock): Integer; begin if not Sorted then Begin Result := 0; while (Result < FCount) and (Integer(GetItem(result)) <> Integer(AStockDateTime)) do begin Inc(Result); end; if Result = FCount then begin Result := -1; end; end else begin if not Find(AStockDateTime, Result) then Result := -1; end; end; {*******************************************************************************************} procedure TMinuteDataList.InsertObject(Index: Integer; const AStockDateTime: TDateTimeStock; AMinuteData: PRT_Quote_Minute); Var tmpDoubleListItem: PMinuteDataListItem; begin New(tmpDoubleListItem); tmpDoubleListItem^.StockDateTime := AStockDateTime; tmpDoubleListItem^.MinuteData := AMinuteData; try inherited insert(index, tmpDoubleListItem); except Dispose(tmpDoubleListItem); raise; end; end; {***********************************************************************} procedure TMinuteDataList.Notify(Ptr: Pointer; Action: TListNotification); begin if Action = lstDeleted then dispose(ptr); inherited Notify(Ptr, Action); end; {********************************************************************} procedure TMinuteDataList.SetItem(Index: Integer; const AStockDateTime: TDateTimeStock); Var tmpDoubleListItem: PMinuteDataListItem; begin New(tmpDoubleListItem); tmpDoubleListItem^.StockDateTime := AStockDateTime; tmpDoubleListItem^.MinuteData := nil; Try Put(Index, tmpDoubleListItem); except Dispose(tmpDoubleListItem); raise; end; end; {*********************************************************} function TMinuteDataList.GetMinuteData(Index: Integer): PRT_Quote_Minute; begin if (Index < 0) or (Index >= FCount) then Error(@SALListIndexError, Index); Result := PMinuteDataListItem(Get(index))^.MinuteData; end; {***************************************************************} function TMinuteDataList.IndexOfMinuteData(AMinuteData: PRT_Quote_Minute): Integer; begin for Result := 0 to Count - 1 do begin if GetMinuteData(Result) = AMinuteData then begin Exit; end; end; Result := -1; end; {*******************************************************************} procedure TMinuteDataList.PutMinuteData(Index: Integer; AMinuteData: PRT_Quote_Minute); begin if (Index < 0) or (Index >= FCount) then begin Error(@SALListIndexError, Index); end; PMinuteDataListItem(Get(index))^.MinuteData := AMinuteData; end; end.
unit kwCompiledWordWorkerWord; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\kwCompiledWordWorkerWord.pas" // Стереотип: "SimpleClass" // Элемент модели: "TkwCompiledWordWorkerWord" MUID: (4F21976E01C2) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses , tfwWordWorker , tfwScriptingInterfaces , kwCompiledWordWorkerWordRunner , tfwScriptingTypes , tfwDictionaryPrim , kwCompiledWordWorker , kwCompiledWordPrim , kwTemporaryCompiledCode ; type RkwCompiledWordWorkerWord = class of TkwCompiledWordWorkerWord; TkwImmediateTemporaryCompiledCode = class(TkwTemporaryCompiledCode) public procedure SetResultTypeInfo(aValue: TtfwWordInfo; const aCtx: TtfwContext); override; end;//TkwImmediateTemporaryCompiledCode TkwCompiledWordWorkerWord = class(TtfwWordWorker) private f_Compiled: TtfwWord; protected function RunnerClass(const aCtx: TtfwContext): RkwCompiledWordWorkerWordRunner; function TreatUnknownAsStringInParam(const aContext: TtfwContext; aParamNumber: Integer): Boolean; function ParamHasModifer(const aContext: TtfwContext; aParamNumber: Integer; aModifier: TtfwWordModifier): Boolean; overload; function ParamHasModifer(const aContext: TtfwContext; aParamNumber: Integer; aModifier: TtfwLinkType): Boolean; overload; function CompiledWorkerClass(const aCtx: TtfwContext): RkwCompiledWordWorker; override; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DoDoIt(const aCtx: TtfwContext); override; procedure UnknownWord(var aContext: TtfwContext; aWordNumber: Integer); override; function AfterWordMaxCount(const aCtx: TtfwContext): Integer; override; function CompiledWordClass(const aCtx: TtfwContext): RkwCompiledWordPrim; override; class function ReallyNeedRegister: Boolean; override; procedure FillCompiledWorker(aWorker: TtfwWord; const aContext: TtfwContext); override; function SuppressNextImmediate(const aContext: TtfwContext; aWordNumber: Integer): TtfwSuppressNextImmediate; override; function pm_GetWordProducer: TtfwWord; override; procedure pm_SetWordProducer(aValue: TtfwWord); override; function pm_GetInnerDictionary: TtfwDictionaryPrim; override; function pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; override; function pm_GetParentWord: TtfwWord; override; procedure DoKeyword(var aContext: TtfwContext; aWord: TtfwWord; aFinder: TtfwWord; aWordNumber: Integer); override; public constructor Create(aCompiled: TtfwWord); reintroduce; function IsAnonimous(const aCtx: TtfwContext): Boolean; override; procedure SetResultTypeInfo(aValue: TtfwWordInfo; const aCtx: TtfwContext); override; function GetRefForCompare: TtfwWord; override; public property Compiled: TtfwWord read f_Compiled; end;//TkwCompiledWordWorkerWord {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , SysUtils , tfwWordRefList , kwCompiledWordWorkerWordPack //#UC START# *4F21976E01C2impl_uses* //#UC END# *4F21976E01C2impl_uses* ; procedure TkwImmediateTemporaryCompiledCode.SetResultTypeInfo(aValue: TtfwWordInfo; const aCtx: TtfwContext); //#UC START# *52EA6A2C0111_557562DF00B8_var* //#UC END# *52EA6A2C0111_557562DF00B8_var* begin //#UC START# *52EA6A2C0111_557562DF00B8_impl* // - ничего не делаем. СПЕЦИАЛЬНО //#UC END# *52EA6A2C0111_557562DF00B8_impl* end;//TkwImmediateTemporaryCompiledCode.SetResultTypeInfo constructor TkwCompiledWordWorkerWord.Create(aCompiled: TtfwWord); //#UC START# *4F219F0F0176_4F21976E01C2_var* //#UC END# *4F219F0F0176_4F21976E01C2_var* begin //#UC START# *4F219F0F0176_4F21976E01C2_impl* inherited Create; aCompiled.SetRefTo(f_Compiled); //#UC END# *4F219F0F0176_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.Create function TkwCompiledWordWorkerWord.RunnerClass(const aCtx: TtfwContext): RkwCompiledWordWorkerWordRunner; //#UC START# *4F3FAC0C0170_4F21976E01C2_var* //#UC END# *4F3FAC0C0170_4F21976E01C2_var* begin //#UC START# *4F3FAC0C0170_4F21976E01C2_impl* Result := TkwCompiledWordWorkerWordRunner; //#UC END# *4F3FAC0C0170_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.RunnerClass function TkwCompiledWordWorkerWord.TreatUnknownAsStringInParam(const aContext: TtfwContext; aParamNumber: Integer): Boolean; //#UC START# *55893819034D_4F21976E01C2_var* //#UC END# *55893819034D_4F21976E01C2_var* begin //#UC START# *55893819034D_4F21976E01C2_impl* Result := ParamHasModifer(aContext, aParamNumber, tfw_wmTreatUnknownAsString); //#UC END# *55893819034D_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.TreatUnknownAsStringInParam function TkwCompiledWordWorkerWord.ParamHasModifer(const aContext: TtfwContext; aParamNumber: Integer; aModifier: TtfwWordModifier): Boolean; //#UC START# *5589721B0279_4F21976E01C2_var* var l_P : TtfwWord; //#UC END# *5589721B0279_4F21976E01C2_var* begin //#UC START# *5589721B0279_4F21976E01C2_impl* l_P := Compiled.GetRightParam(aContext, aParamNumber); if (l_P = nil) then Result := false else Result := l_P.ResultTypeInfo[aContext].Has(aModifier); //#UC END# *5589721B0279_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.ParamHasModifer function TkwCompiledWordWorkerWord.ParamHasModifer(const aContext: TtfwContext; aParamNumber: Integer; aModifier: TtfwLinkType): Boolean; //#UC START# *55C23E4D0305_4F21976E01C2_var* var l_P : TtfwWord; //#UC END# *55C23E4D0305_4F21976E01C2_var* begin //#UC START# *55C23E4D0305_4F21976E01C2_impl* l_P := Compiled.GetRightParam(aContext, aParamNumber); if (l_P = nil) then Result := false else Result := l_P.ResultTypeInfo[aContext].Has(aModifier); //#UC END# *55C23E4D0305_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.ParamHasModifer function TkwCompiledWordWorkerWord.CompiledWorkerClass(const aCtx: TtfwContext): RkwCompiledWordWorker; //#UC START# *4DCBD67C0362_4F21976E01C2_var* //#UC END# *4DCBD67C0362_4F21976E01C2_var* begin //#UC START# *4DCBD67C0362_4F21976E01C2_impl* Result := RunnerClass(aCtx); //#UC END# *4DCBD67C0362_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.CompiledWorkerClass procedure TkwCompiledWordWorkerWord.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4F21976E01C2_var* //#UC END# *479731C50290_4F21976E01C2_var* begin //#UC START# *479731C50290_4F21976E01C2_impl* FreeAndNil(f_Compiled); inherited; //#UC END# *479731C50290_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.Cleanup procedure TkwCompiledWordWorkerWord.DoDoIt(const aCtx: TtfwContext); //#UC START# *4DAEEDE10285_4F21976E01C2_var* //#UC END# *4DAEEDE10285_4F21976E01C2_var* begin //#UC START# *4DAEEDE10285_4F21976E01C2_impl* CompilerAssert(aCtx.rParser <> nil, 'Возможно компиляция запускается из уже откомпилированнного кода. Вызов операторов по ссылке пока не поддерживается', aCtx); // - возможно здесь можно сделать, чтобы параметры справа брались из скомпилированного кода (* Тогда можно будет делать: operator X ^ IN aRight aRight DO ; // X @SELF -> X 2 . *) inherited; //#UC END# *4DAEEDE10285_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.DoDoIt procedure TkwCompiledWordWorkerWord.UnknownWord(var aContext: TtfwContext; aWordNumber: Integer); //#UC START# *4DB6F2760023_4F21976E01C2_var* //#UC END# *4DB6F2760023_4F21976E01C2_var* begin //#UC START# *4DB6F2760023_4F21976E01C2_impl* if TreatUnknownAsStringInParam(aContext, aWordNumber) then DoStringToken(aContext, aContext.rWordCompilingNow, aContext.rParser.TokenLongString) else inherited; //#UC END# *4DB6F2760023_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.UnknownWord function TkwCompiledWordWorkerWord.AfterWordMaxCount(const aCtx: TtfwContext): Integer; //#UC START# *4DB9B446039A_4F21976E01C2_var* //#UC END# *4DB9B446039A_4F21976E01C2_var* begin //#UC START# *4DB9B446039A_4F21976E01C2_impl* Result := Compiled.RightParamsCount(aCtx); //#UC END# *4DB9B446039A_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.AfterWordMaxCount function TkwCompiledWordWorkerWord.CompiledWordClass(const aCtx: TtfwContext): RkwCompiledWordPrim; //#UC START# *4DBAEE0D028D_4F21976E01C2_var* //#UC END# *4DBAEE0D028D_4F21976E01C2_var* begin //#UC START# *4DBAEE0D028D_4F21976E01C2_impl* if Self.ResultTypeInfo[aCtx].Has(tfw_wmImmediate) then Result := TkwImmediateTemporaryCompiledCode else Result := TkwTemporaryCompiledCode; //#UC END# *4DBAEE0D028D_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.CompiledWordClass class function TkwCompiledWordWorkerWord.ReallyNeedRegister: Boolean; //#UC START# *4DC2E05B03DD_4F21976E01C2_var* //#UC END# *4DC2E05B03DD_4F21976E01C2_var* begin //#UC START# *4DC2E05B03DD_4F21976E01C2_impl* Result := false; //#UC END# *4DC2E05B03DD_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.ReallyNeedRegister procedure TkwCompiledWordWorkerWord.FillCompiledWorker(aWorker: TtfwWord; const aContext: TtfwContext); //#UC START# *4F219FA10268_4F21976E01C2_var* var l_LeftWordRefCount : Integer; l_CodeIndex : Integer; l_Code : TtfwWordRefList; //#UC END# *4F219FA10268_4F21976E01C2_var* begin //#UC START# *4F219FA10268_4F21976E01C2_impl* Compiled.Key := Self.Key; (aWorker As TkwCompiledWordWorkerWordRunner).WordToRun := Compiled; l_LeftWordRefCount := Compiled.LeftWordRefParamsCount(aContext); if (l_LeftWordRefCount > 0) then begin l_CodeIndex := aContext.rWordCompilingNow.CodeCount; CompilerAssert(l_LeftWordRefCount <= l_CodeIndex, 'Нужно ' + IntToStr(l_LeftWordRefCount) + ' штук слов перед ' + Self.Key.AsString + ', а их там ' + IntToStr(l_CodeIndex), aContext); Dec(l_CodeIndex); CompilerAssert(aContext.rWordCompilingNow Is TkwCompiledWordPrim, 'Нужно компилируемое слово', aContext); l_Code := TkwCompiledWordPrim(aContext.rWordCompilingNow).GetCode(aContext); CompilerAssert(l_Code <> nil, 'Нужно слово перед ' + Self.Key.AsString, aContext); while (l_LeftWordRefCount > 0) do begin aWorker.AddLeftWordRefValue(aContext, l_Code.Items[l_CodeIndex]); l_Code.Delete(l_CodeIndex); Dec(l_LeftWordRefCount); Dec(l_CodeIndex); end;//l_LeftWordRefCount > 0) end;//l_LeftWordRefCount > 0 inherited; if (aContext.rCompiler = nil) then (aWorker As TkwCompiledWordWorkerWordRunner).Caller := nil else (aWorker As TkwCompiledWordWorkerWordRunner).Caller := aContext.rCompiler.GetAsCaller(aContext); // м.б. тут надо aContext.rWordDefiningNow // см. TkwCompilingWordSelf.DoDoIt // см. ещё Assert выше //#UC END# *4F219FA10268_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.FillCompiledWorker function TkwCompiledWordWorkerWord.IsAnonimous(const aCtx: TtfwContext): Boolean; //#UC START# *4F3AB3600008_4F21976E01C2_var* //#UC END# *4F3AB3600008_4F21976E01C2_var* begin //#UC START# *4F3AB3600008_4F21976E01C2_impl* Result := false; //#UC END# *4F3AB3600008_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.IsAnonimous function TkwCompiledWordWorkerWord.SuppressNextImmediate(const aContext: TtfwContext; aWordNumber: Integer): TtfwSuppressNextImmediate; //#UC START# *4F3AB3B101FC_4F21976E01C2_var* //#UC END# *4F3AB3B101FC_4F21976E01C2_var* begin //#UC START# *4F3AB3B101FC_4F21976E01C2_impl* if ParamHasModifer(aContext, aWordNumber, tfw_ltLink) then // - если у параметра указан модификатор LINK, то мы игнорируем ВСЕ непосредственные слова // Например для WordAlias. Result := tfw_sniForce else if ParamHasModifer(aContext, aWordNumber, tfw_ltReference) then // - если у параметра указан модификатор REFERENCE, то мы игнорируем ВСЕ непосредственные слова // Например для [EXPORT]. Result := tfw_sniYes else if TreatUnknownAsStringInParam(aContext, aWordNumber) then // - если мы рассматриваем параметр как идентификатор, а не как слово, // то логично не раскрывать оператор соответствующий этому идентификатору. //Result := tfw_sniForce Result := tfw_sniYes else // - иначе - надо всё раскрывать, т.к. иначе можем получить ерунду и // исключение 'Возможно компиляция запускается из уже откомпилированнного кода' Result := tfw_sniNo; //Result := inherited SupressNextImmediate(aContext, aWordNumber); //#UC END# *4F3AB3B101FC_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.SuppressNextImmediate function TkwCompiledWordWorkerWord.pm_GetWordProducer: TtfwWord; //#UC START# *4F43C9A10139_4F21976E01C2get_var* //#UC END# *4F43C9A10139_4F21976E01C2get_var* begin //#UC START# *4F43C9A10139_4F21976E01C2get_impl* Result := Compiled.WordProducer; //#UC END# *4F43C9A10139_4F21976E01C2get_impl* end;//TkwCompiledWordWorkerWord.pm_GetWordProducer procedure TkwCompiledWordWorkerWord.pm_SetWordProducer(aValue: TtfwWord); //#UC START# *4F43C9A10139_4F21976E01C2set_var* //#UC END# *4F43C9A10139_4F21976E01C2set_var* begin //#UC START# *4F43C9A10139_4F21976E01C2set_impl* Compiled.WordProducer := aValue; //#UC END# *4F43C9A10139_4F21976E01C2set_impl* end;//TkwCompiledWordWorkerWord.pm_SetWordProducer function TkwCompiledWordWorkerWord.pm_GetInnerDictionary: TtfwDictionaryPrim; //#UC START# *52B43311021D_4F21976E01C2get_var* //#UC END# *52B43311021D_4F21976E01C2get_var* begin //#UC START# *52B43311021D_4F21976E01C2get_impl* Result := Compiled.InnerDictionary; //#UC END# *52B43311021D_4F21976E01C2get_impl* end;//TkwCompiledWordWorkerWord.pm_GetInnerDictionary function TkwCompiledWordWorkerWord.pm_GetResultTypeInfo(const aCtx: TtfwContext): TtfwWordInfo; //#UC START# *52CFC11603C8_4F21976E01C2get_var* //#UC END# *52CFC11603C8_4F21976E01C2get_var* begin //#UC START# *52CFC11603C8_4F21976E01C2get_impl* if (Compiled <> nil) then Result := Compiled.ResultTypeInfo[aCtx] else Result := inherited pm_GetResultTypeInfo(aCtx); //#UC END# *52CFC11603C8_4F21976E01C2get_impl* end;//TkwCompiledWordWorkerWord.pm_GetResultTypeInfo function TkwCompiledWordWorkerWord.pm_GetParentWord: TtfwWord; //#UC START# *52CFCF4B02C6_4F21976E01C2get_var* //#UC END# *52CFCF4B02C6_4F21976E01C2get_var* begin //#UC START# *52CFCF4B02C6_4F21976E01C2get_impl* Result := Compiled.ParentWord; //#UC END# *52CFCF4B02C6_4F21976E01C2get_impl* end;//TkwCompiledWordWorkerWord.pm_GetParentWord procedure TkwCompiledWordWorkerWord.SetResultTypeInfo(aValue: TtfwWordInfo; const aCtx: TtfwContext); //#UC START# *52EA6A2C0111_4F21976E01C2_var* //#UC END# *52EA6A2C0111_4F21976E01C2_var* begin //#UC START# *52EA6A2C0111_4F21976E01C2_impl* inherited; if (Compiled <> nil) then Compiled.SetResultTypeInfo(aValue, aCtx); //#UC END# *52EA6A2C0111_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.SetResultTypeInfo procedure TkwCompiledWordWorkerWord.DoKeyword(var aContext: TtfwContext; aWord: TtfwWord; aFinder: TtfwWord; aWordNumber: Integer); //#UC START# *53E21481021D_4F21976E01C2_var* //#UC END# *53E21481021D_4F21976E01C2_var* begin //#UC START# *53E21481021D_4F21976E01C2_impl* if TreatUnknownAsStringInParam(aContext, aWordNumber) then DoStringToken(aContext, aContext.rWordCompilingNow, aContext.rParser.TokenLongString) else inherited; //#UC END# *53E21481021D_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.DoKeyword function TkwCompiledWordWorkerWord.GetRefForCompare: TtfwWord; //#UC START# *57500A22001C_4F21976E01C2_var* //#UC END# *57500A22001C_4F21976E01C2_var* begin //#UC START# *57500A22001C_4F21976E01C2_impl* Result := f_Compiled; if (Result <> nil) then Result := Result.GetRefForCompare; //#UC END# *57500A22001C_4F21976E01C2_impl* end;//TkwCompiledWordWorkerWord.GetRefForCompare initialization TkwImmediateTemporaryCompiledCode.RegisterClass; {* Регистрация TkwImmediateTemporaryCompiledCode } TkwCompiledWordWorkerWord.RegisterInEngine; {* Регистрация TkwCompiledWordWorkerWord } {$IfEnd} // NOT Defined(NoScripts) end.
program inchToCent(input, output); const CENT_PER_INCH = 2.54; var inches, cent: Real; (* This is a comment *) begin write('Enter a length in inches: '); readln(inches); cent := CENT_PER_INCH * inches; writeln('That equals ', cent :1:1, ' centimeters.'); writeln('****'); writeln('* *'); writeln('* *'); writeln('****'); writeln('****'); writeln('* *'); writeln('* *'); writeln('****'); end.
unit ForecastUploadBreakDown; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, DataModule, ComCtrls, StdCtrls, DirOutln, OleServer, Excel2000, Excel97; type TForeUpBreakDown_Form = class(TForm) ForeUpBreakDown_Label: TLabel; FileName_Label: TLabel; FileName_Edit: TEdit; Browse_Button: TButton; ForecastFilleNameDialog: TOpenDialog; Start_Button: TButton; Close_Button: TButton; procedure Browse_ButtonClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Start_ButtonClick(Sender: TObject); procedure FileName_EditChange(Sender: TObject); private { Private declarations } fDefaultFilePathLabel: String; fFilePathLabel: String; fFileSelected:boolean; public { Public declarations } property FilePathLabel: String read fFilePathLabel write fFilePathLabel; function Execute: boolean; end; var ForeUpBreakDown_Form: TForeUpBreakDown_Form; implementation uses ForecastBreakdownF; {$R *.dfm} function TForeUpBreakDown_Form.Execute: boolean; Begin Result:= True; try try fFileSelected:=False; ShowModal; except On E:Exception do showMessage('Unable to generate Forecast Info. Upload & Break Down screen.' + #13 + 'ERROR:' + #13 + E.Message); end; finally If ModalResult = mrCancel Then Result:= False; end; end; //Execute procedure TForeUpBreakDown_Form.Browse_ButtonClick(Sender: TObject); begin with ForecastFilleNameDialog do begin Filter := 'Text Forecast File (*.txt)|*.txt'; DefaultExt := 'txt'; Filename := 'prel'; Options := [ofHideReadOnly, ofFileMustExist, ofPathMustExist]; if Execute then begin if ofExtensionDifferent in Options then MessageDlg ('Not a file with the .TXT extension', mtError, [mbOK], 0) else FilePathLabel := FileName; FileName_Edit.Text := FilePathLabel; fFileselected:=TRUE; end; end; end; procedure TForeUpBreakDown_Form.FormCreate(Sender: TObject); begin fDefaultFilePathLabel := '[Type file path and name here or click Browse]'; FilePathLabel := fDefaultFilePathLabel; FileName_Edit.Text := FilePathLabel; end; procedure TForeUpBreakDown_Form.Start_ButtonClick(Sender: TObject); var breakdown:TForecastBreakdown_Form; begin try if fFileSelected then begin breakdown:=TForecastBreakdown_Form.Create(self); breakdown.filename:=ForecastFilleNameDialog.FileName; breakdown.SupplierCode:=data_Module.fiSupplierCode.AsString; breakdown.FileKind:=fText; breakdown.Show; if not breakdown.Execute then Showmessage('Forecast has not been added, please retry'); breakdown.Free; close; end else ShowMessage('Please select a valid file first'); except on e:exception do ShowMessage('Err: ' + e.Message); end; end; procedure TForeUpBreakDown_Form.FileName_EditChange(Sender: TObject); begin fFileSelected:=True; end; end.
unit ProtocolKOP; interface uses ProtocolCommon, Constants; type TSendedPacket = class (TObject) OutBuf : TBuf500; dSize : Word; // размер отправленного пакета MyPacketID : word; // номер отправленного пакета PacketType : Byte; // тип отправленного пакета PartNum : Word; // номер части PartCount : Word; // кол-во частей DateTime : TDateTime; SendCount : byte; //кол-во отправок end; const DataPartMaxSize = 400; DallasKeySize = 8; NumericKeyMaxSize = 12; AlarmSensorCount = 8; OutputsCount = 4; OrionMaxZoneInd = 127; OrionMaxPartInd = 63; type TPacketId = Uint8; TSessionId = uint16 ; //Идентификатор сессии TDeviceId = uint16 ; //Идентификатор прибора TLocalId = uint8; //Идентификатор в локальной сети TNixDateTime = uint32; //POSIX time TSensorMask = uint16; //Битовая маска шлейфов type PacketType = ( PacketTypeInvalid = 0, //Недопустимый тип пакета PacketTypePing = 1, PacketTypePong, PacketTypeConfirm, PacketTypeError, //Ошибка PacketTypeInvalidSession, //Неактивная сессия PacketTypeLast ); type ServerPacketType = ( ServerPacketTypeFirst = Integer(PacketTypeLast), ServerPacketTypeAccept, //- 7 ServerPacketTypeGetFWVersion, //Запрос версии ПО контроллера - 8 ServerPacketTypeDateTimeSet, //Установить дату-время ServerPacketTypeFWPart, //Часть прошивки КОП ServerPacketTypeSensorCommandSet, //Комманда на взятие шлейфа ServerPacketTypeSensorCommandSetByMask, //Комманда на взятие шлейфоф по маске ServerPacketTypeSensorCommandUnset, //Комманда на снятие шлейфов по маске ServerPacketTypeGetSensorState, //Опрос состояния шлейфа X ServerPacketTypeGetSensorsState, //Опрос состояния всех шлейфов ServerPacketTypeDeviceDisable, //Вывод из обслуживания ServerPacketTypeDeviceEnable, //Ввод в обслуживание ServerPacketTypeGetBalance, //Запрос баланса ServerPacketTypeGetPhoneNumber, //Запрос номера телефона ServerPacketTypeConfigSet, //Установить новую конфигурацию ServerPacketTypeConfigGet, //Запрос конфига КОП ServerPacketTypeGetState, //Запрос состояния КОП ServerPacketTypeSwitchSim, //Переключить SIM-карту ServerPacketTypeDriverCommand, // команда интернет драйверу ServerPacketTypeOrionPacket, // пакет на шину Modbus ServerPacketTypeOrionCommandSetByList, //Команда на взятие/снятие шлейфов и вкл/выкл реле по маске на шине ORION ServerPacketTypeOrionPartCommandSetByList, //Команда на взятие/снятие шлейфов и вкл/выкл реле по маске на шине ORION ServerPacketTypeOrionZoneStatus, //команда на опрос зоны ServerPacketTypeOrionPartStatus, //команда на опрос раздела ServerPacketTypeOrionZonesStatus, //команда на опрос списка зон ServerPacketTypeOrionPartsStatus, //команда на опрос списка разделов ServerPacketTypeLast); type KopPacketType = ( KopPacketTypeFirst = Integer(PacketTypeLast), KopPacketTypeHello, //- 7 KopPacketTypeFWVersion, //Версия ПО микроконтроллера - 8 KopPacketTypeFWUpdateResult, //Результат обновления прошивки KopPacketTypeConfigPart, //Настройки контроллера KopPacketTypeConfigSetResult, //Настройки изменены KopPacketTypeDateTimeGet, //Запрос на получение даты-времени KopPacketTypeEvent, //Событие КОП KopPacketTypeSensorRequest, //Запрос на взятие/снятие шлейфа KopPacketTypeSensorsStatus, //обобщенное состояние шлейфов контроллера KopPacketTypeSensorStatus, //состояние шлейфа контроллера KopPacketTypeState, //Состояние КОП KopPacketTypeOrionEvent, // пакет от прибора Orion Bolid KopPacketTypeOrionZoneStatus, //19 KopPacketTypeOrionPartStatus, //20 KopPacketTypeOrionZonesStatus, //21 KopPacketTypeOrionPartsStatus, //22 KopPacketTypeLast); type KopEventTypes = ( EventCodeBegin, EventCodeSystemStart, //Сброс процессора EventCodeConfigChanged, //Изменены настройки устройства EventCodeFirmwareUpdated, //Обновлена прошивка EventCodeChanellChanged, //Смена канала связи EventCodePowerSwitchToBackup, //Переход на АКБ EventCodePowerSwitchToMain, //Переход на основное питание EventCodeGuardSensorSet, //Взят ШС EventCodeGuardSensorUnset, //Снят ШС EventCodeGuardSensorAlarm, //Тревога ШС EventCodeGuardSensorNoSetAlarm, //Тревога не взят EventCodeGuardSensorNoSet, //Не взят EventCodeGuardSensorNoUnset, //Не снят EventCodeAlarmSensorAlarm, //Тревожная кнопка EventCodeAlarmSensorRestore, //Восстановление ШС EventCodeAlarmPowerOn, //Тревога при включении питания EventCodeSensorBadReset, //Не удачное перевзятие ШС EventCodeCaseOpened, //Корпус вкрыт EventCodeCaseClosed, //Корпус закрыт EventCodeOutputShort, //Обрыв выхода EventCodeOutputRestore, //Восстановление выхода EventCodeBackupChanellError, //Ошибка проверки резервного канала EventCodeWaterSale, //Отпуск воды EventCodeLast); type TAlarmSensorState = // статусы тревожного ШС ( AlarmSensorStateUnknown = 0, AlarmSensorStateNormal, // в норме AlarmSensorStateDefectBreak, //дефект обрыв AlarmSensorStateDefectShort, //дефект кз AlarmSensorStateBreak, //тревога обрыв AlarmSensorStateShort //тревога кз ); // способы взятия ШС на охрану type TSensorTakeType = ( SensorTakeTypeImmediately = 0, //Сразу SensorTakeTypeAfterExit, //После выхода SensorTakeTypeWithDelay //С задержкой ); TDallasKey = packed record B : TBuf8; end; TNumericKey = packed record B : TBuf13; end; type TDataPart = packed record Number : Uint8; TotalParts : Uint8; Size : Uint16; Data : TBuf400; end; PDataPart = ^TDataPart; TPacketConfirm = packed record PacketID: TPacketId; end; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// type TServerPacketConfigGet = packed record PartNumber : UInt8; end; TFrZoneBuf = array[0..MaxMaskZoneCnt] of Uint32; type TServerPacketDriverCommand = packed record CmdID : Uint8; end; type TServerPacketDateTimeSet = packed record DateTime: UInt32; end; type TServerPacketAccept = packed record SessID: UInt16; end; // взять ШС TServerSensorCommandSet = packed record Sensor :UInt8; //Шлейф для взятия AlarmEnableDelay :UInt16; //Время через которое включается сирена, сек SetDelay :UInt16; //Задержка взятия, сек ExternalIndicatorEnableTime:UInt16; //Время работы ВИ "Охрана", сек TakeType :UInt8; //Способ взятия - SensorTakeType end; // взять ШС по маске TServerSensorCommandSetByMask = packed record SensorMask : Uint16; //Шлейфы для взятия AlarmEnableDelay : UInt16; //Время через которое включается сирена, сек SetDelay : UInt16; //Задержка взятия, сек ExternalIndicatorEnableTime:UInt16; //Время работы ВИ "Охрана", сек TakeType :UInt8; //Способ взятия - SensorTakeType end; // снять ШС по маске TServerSensorCommandUnSet = packed record Mask :UInt16; // маска для снятия ШС end; TServerPacketGetSensorState = packed record //Запрос статуса зоны Sensor :UInt8; // номер ШС end; TOrionCmdType = ( OrionCmdTypeRelayOff = 0, OrionCmdTypeSetZone = 24, OrionCmdTypeUnsetZone = 109, OrionCmdTypeRelayOn = 255 ); TOrionEventType = ( OrionSetFail = 17, OrionZoneSet = 24, OrionZoneUnset = 109, OrionPartSet = 241, OrionPartUnset = 242 ); TServerPacketOrionCommandSetByList = packed record SensorCount : Uint8; //Кол-во шлейфов для взятия SetDelay : UInt8; //Задержка взятия, сек CmdType : UInt8; //109 – снятие ШС; 24 – взятие ШС; Sensors : array[0..OrionMaxZoneInd] of Byte; // массив номеров ШС для взятия end; TServerPacketOrionPartCommandSetByList = packed record PartCount : Uint8; //Кол-во шлейфов для взятия SetDelay : UInt8; //Задержка взятия, сек CmdType : UInt8; //109 – снятие ШС; 24 – взятие ШС; Parts : array[0..OrionMaxPartInd] of Byte; // массив номеров ШС для взятия end; TServerPacketOrionZoneStatus = packed record ZoneNum: UInt8; end; TServerPacketOrionZonesStatus = packed record Count: UInt8; Zones: array[0..OrionMaxZoneInd] of byte; end; TServerPacketOrionPartStatus = packed record PartNum: UInt8; end; TServerPacketOrionPartsStatus = packed record Count: UInt8; Parts: array[0..OrionMaxPartInd] of byte; end; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// type TKopPacketEmpty = packed record Reserved : Uint8; end; type TCommunicationChannelFlags = ( CommunicationChannelFlagReserve = 0, CommunicationChannelFlagMain = 2, //Основной канал связи CommunicationChannelFlagMainSim = 4, //Основная SIM-карта CommunicationChannelFlagMainServer = 8); //Основной сервер // CommunicationChannelFlags; Это битовая маска. Могут быть любые комбинации битов type TCommunicationChannel = ( CommunicationChannelUnknown = 0, CommunicationChannelEthernet, CommunicationChannelGPRSSim1, CommunicationChannelGPRSSim2); DecryptPacketError = ( DecryptPacketErrorOK = 0, //Нет ошибки DecryptPacketErrorBeginMark, //Ошибка метки начала пакета DecryptPacketErrorHeaderCRC, //Ошибка сrc заголовка DecryptPacketErrorEncryptedDataSize, //Некоректный размер зашифрованных данных DecryptPacketErrorReceivedSize, //Несовпадение размера полученных данных и размера из заголовков DecryptPacketErrorDecryptedDataSize, //Некоректный размер расшифрованных данных DecryptPacketErrorDecryptedDataCRC); //Ошибка сrc расшифрованных данных BolidErrorCode = ( BolidErrorCodeOk, //0 BolidErrorCodeNotResponse, //1 BolidErrorCodeUnkonown, //2 BolidErrorCodeLast); TKopPacketHello = packed record Id : TDeviceId; Version : TBuf20; Chanell : Uint8; //TCommunicationChannel ChanellFlags : Uint8; //TCommunicationChannelFlags end; TKopPacketFWVersion = packed record //KopPacketTypeFWVersion Version : TBuf20; end; //KopPacketTypeConfigPart TKopPacketConfigPart = TDataPart; TKopPacketConfigSetResult = packed record //KopPacketTypeFWUpdateResult Ok : Uint8; end; TKopPacketFWUpdateResult = packed record //KopPacketTypeFWUpdateResult Ok : Uint8; end; TKopPacketDateTimeGet = TKopPacketEmpty; TKopPacketMaskWithKey = packed record Mask : TSensorMask; Tm : TDallasKey; Key : TNumericKey; end; TKopPacketMaskSetRequest = TKopPacketMaskWithKey; TKopPacketMaskUnsetRequest = TKopPacketMaskWithKey; // типы взятия/снятия type TKopSensorRequestType = (KopSensorRequestTypeNone = 0, //Не используется и не передаётся KopSensorRequestTypeSetByMask, //взять шлейфы по маске KopSensorRequestTypeUnsetByMask); //снять шлейфы по маске TKopSensorRequest = packed record SensorRequestType : Uint8; //KopSensorRequestType Mask : TSensorMask; Current : TSensorMask; Tm : TDallasKey; Key : TNumericKey; end; TKopPacketSensorsStatus = packed record Sensors : TBuf8; SensorsInGuard : TSensorMask; GuardSensorsInAlarm : TSensorMask; GuardSensors : TSensorMask; end; TSensorStateFlag = ( SensorStateFlagInGuard, //Взят-не взят SensorStateFlagInAlarm, //В состоянии тревоги, только для охранного шлейфа SensorStateFlagIsGuardSensor //Флаг охранного шлейфа ) ; TKopPacketSensorStatus = packed record //KopPacketTypeSensorStatus Sensor :Uint8; //номер ШС State :Uint8; //текущее состояние шлейфов Flags :Uint8; //TSensorStateFlag Resistance :Uint16; // сопротивление ШС end; TKopEvent = packed record DateTime : TNixDateTime; EType : Uint8; Arg : Uint32; Flags : Uint8; end; TKopPacketTypeOrionEvent = packed record DateTime : TNixDateTime; EType : Uint8; // код события XoNum : Uint16; //Порядковый номер пользователя в базе данных «С2000-ПП» PartNum : Uint16; //номер раздела ZoneNum : Uint16; //порядковый номер зоны RelayNum : Uint16; //порядковый номер реле Relay : Uint16; //состояние реле PartID : Uint16; //идентификатор раздела в системе «Орион» end; TKopBolidSetTime = packed record BolidSetTime : TBuf15; end; TKopBolidTime = packed record BolidTime : TBuf11; end; const KopEventSize = sizeof(TKopEvent); type TConnection = packed record IsConnected : Uint8; Chanell : UInt8; ChanellFlags : Uint8; Session : TSessionId; end; //Статус "Пожар" type KopFireState = ( KopFireStateNone = 0, KopFireStateNormal, KopFireStateDefect, KopFireStateAlarm ); //Статус "Охрана" type KopGuardState = ( KopGuardStateNone = 0, KopGuardStateNormal, KopGuardStateDefect, KopGuardStateAlarm); type TKopState = record //{ // struct // { // uint8_t isConnected; // uint8_t chanell; //CommunicationChannel // uint8_t chanellFlags; //CommunicationChannelFlags; // SessionId session; // } connection; // // uint8_t sensors[AlarmSensorCount]; // uint8_t outputs[OutputsCount]; // // SensorMask sensorsInGuard; // SensorMask guardSensorsInAlarm; // SensorMask unsetUserRequestMask; // // uint8_t caseOpen; // // uint8_t fireState; // uint8_t guardState; // // float voltageLevel; // uint8_t isMainPowerSource; // // float sim1Balance; // float sim2Balance; // //} KopState PACKED_STRUCT; Connection :TConnection; Sensors :TBuf8; Outputs :TBuf4; SensorsInGuard : TSensorMask; GuardSensorsInAlarm : TSensorMask; UnsetUserRequestMask : TSensorMask; CaseOpen :Uint8; FireState :Uint8; GuardState :Uint8; VoltageLevel :Single; IsMainPowerSource :Uint8; Sim1Balance :Single; Sim2Balance :Single; end; TKopPacketState = TKopState; TKopPacketEvent = TKopEvent; //KopPacketTypeEvent function GetServerPacketName(Num: byte): string; function GetKopPacketName(Num: byte): string; implementation function GetServerPacketName(Num: byte): string; begin case Num of Byte(PacketTypeInvalid) :result := 'PacketTypeInvalid'; Byte(PacketTypePing) :result := 'PacketTypePing'; Byte(PacketTypePong) :result := 'PacketTypePong'; Byte(PacketTypeConfirm) :result := 'PacketTypeConfirm'; Byte(PacketTypeError) :result := 'PacketTypeError'; Byte(PacketTypeInvalidSession) :result := 'PacketTypeInvalidSession'; Byte(PacketTypeLast) :result := 'PacketTypeLast'; Byte(ServerPacketTypeAccept) :result := 'ServerPacketTypeAccept'; Byte(ServerPacketTypeGetFWVersion) :result := 'ServerPacketTypeGetFWVersion'; Byte(ServerPacketTypeDateTimeSet) :result := 'ServerPacketTypeDateTimeSet'; Byte(ServerPacketTypeFWPart) :result := 'ServerPacketTypeFWPart'; Byte(ServerPacketTypeSensorCommandSet) :result := 'ServerPacketTypeSensorCommandSet'; Byte(ServerPacketTypeSensorCommandSetByMask) :result := 'ServerPacketTypeSensorCommandSetByMask'; Byte(ServerPacketTypeSensorCommandUnset) :result := 'ServerPacketTypeSensorCommandUnset'; Byte(ServerPacketTypeGetSensorState) :result := 'ServerPacketTypeGetSensorState'; Byte(ServerPacketTypeGetSensorsState) :result := 'ServerPacketTypeGetSensorsState'; Byte(ServerPacketTypeDeviceDisable) :result := 'ServerPacketTypeDeviceDisable'; Byte(ServerPacketTypeDeviceEnable) :result := 'ServerPacketTypeDeviceEnable'; Byte(ServerPacketTypeGetBalance) :result := 'ServerPacketTypeGetBalance'; Byte(ServerPacketTypeGetPhoneNumber) :result := 'ServerPacketTypeGetPhoneNumber'; Byte(ServerPacketTypeConfigSet) :result := 'ServerPacketTypeConfigSet'; Byte(ServerPacketTypeConfigGet) :result := 'ServerPacketTypeConfigGet'; Byte(ServerPacketTypeGetState) :result := 'ServerPacketTypeGetState'; Byte(ServerPacketTypeSwitchSim) :result := 'ServerPacketTypeSwitchSim'; // Byte(KopPacketTypeHello) :result := 'KopPacketTypeHello'; // Byte(KopPacketTypeFWVersion) :result := 'KopPacketTypeFWVersion'; // Byte(KopPacketTypeFWUpdateResult) :result := 'KopPacketTypeFWUpdateResult'; // Byte(KopPacketTypeConfigPart) :result := 'KopPacketTypeConfigPart'; // Byte(KopPacketTypeConfigSetResult) :result := 'KopPacketTypeConfigSetResult'; // Byte(KopPacketTypeDateTimeGet) :result := 'KopPacketTypeDateTimeGet'; // Byte(KopPacketTypeEvent) :result := 'KopPacketTypeEvent'; // Byte(KopPacketTypeSensorRequest) :result := 'KopPacketTypeSensorRequest'; // Byte(KopPacketTypeSensorsStatus) :result := 'KopPacketTypeSensorsStatus'; // Byte(KopPacketTypeSensorStatus) :result := 'KopPacketTypeSensorStatus'; // Byte(KopPacketTypeState) :result := 'KopPacketTypeState'; end; end; function GetKopPacketName(Num: byte): string; begin case Num of Byte(PacketTypeInvalid) :result := 'PacketTypeInvalid'; Byte(PacketTypePing) :result := 'PacketTypePing'; Byte(PacketTypePong) :result := 'PacketTypePong'; Byte(PacketTypeConfirm) :result := 'PacketTypeConfirm'; Byte(PacketTypeError) :result := 'PacketTypeError'; Byte(PacketTypeInvalidSession) :result := 'PacketTypeInvalidSession'; Byte(PacketTypeLast) :result := 'PacketTypeLast'; // Byte(ServerPacketTypeAccept) :result := 'ServerPacketTypeAccept'; // Byte(ServerPacketTypeGetFWVersion) :result := 'ServerPacketTypeGetFWVersion'; // Byte(ServerPacketTypeDateTimeSet) :result := 'ServerPacketTypeDateTimeSet'; // Byte(ServerPacketTypeFWPart) :result := 'ServerPacketTypeFWPart'; // Byte(ServerPacketTypeSensorCommandSet) :result := 'ServerPacketTypeSensorCommandSet'; // Byte(ServerPacketTypeSensorCommandSetByMask) :result := 'ServerPacketTypeSensorCommandSetByMask'; // Byte(ServerPacketTypeSensorCommandUnset) :result := 'ServerPacketTypeSensorCommandUnset'; // Byte(ServerPacketTypeGetSensorState) :result := 'ServerPacketTypeGetSensorState'; // Byte(ServerPacketTypeGetSensorsState) :result := 'ServerPacketTypeGetSensorsState'; // Byte(ServerPacketTypeDeviceDisable) :result := 'ServerPacketTypeDeviceDisable'; // Byte(ServerPacketTypeDeviceEnable) :result := 'ServerPacketTypeDeviceEnable'; // Byte(ServerPacketTypeGetBalance) :result := 'ServerPacketTypeGetBalance'; // Byte(ServerPacketTypeGetPhoneNumber) :result := 'ServerPacketTypeGetPhoneNumber'; // Byte(ServerPacketTypeConfigSet) :result := 'ServerPacketTypeConfigSet'; // Byte(ServerPacketTypeConfigGet) :result := 'ServerPacketTypeConfigGet'; // Byte(ServerPacketTypeGetState) :result := 'ServerPacketTypeGetState'; // Byte(ServerPacketTypeSwitchSim) :result := 'ServerPacketTypeSwitchSim'; Byte(KopPacketTypeHello) :result := 'KopPacketTypeHello'; Byte(KopPacketTypeFWVersion) :result := 'KopPacketTypeFWVersion'; Byte(KopPacketTypeFWUpdateResult) :result := 'KopPacketTypeFWUpdateResult'; Byte(KopPacketTypeConfigPart) :result := 'KopPacketTypeConfigPart'; Byte(KopPacketTypeConfigSetResult) :result := 'KopPacketTypeConfigSetResult'; Byte(KopPacketTypeDateTimeGet) :result := 'KopPacketTypeDateTimeGet'; Byte(KopPacketTypeEvent) :result := 'KopPacketTypeEvent'; Byte(KopPacketTypeSensorRequest) :result := 'KopPacketTypeSensorRequest'; Byte(KopPacketTypeSensorsStatus) :result := 'KopPacketTypeSensorsStatus'; Byte(KopPacketTypeSensorStatus) :result := 'KopPacketTypeSensorStatus'; Byte(KopPacketTypeState) :result := 'KopPacketTypeState'; end; end; end.
unit cCadClasseProfessor; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils; // LISTA DE UNITS type TClasseProfessor = class private // VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE ConexaoDB: TFDConnection; F_codigo: Integer; F_cod_classe: Integer; F_classe: string; F_cod_professor: Integer; F_professor: string; F_cod_congregacao: Integer; public constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA function Inserir: Boolean; function Atualizar: Boolean; function Apagar: Boolean; function Selecionar(id: Integer): Boolean; published // VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE // PARA FORNECER INFORMAÇÕESD EM RUMTIME property codigo: Integer read F_codigo write F_codigo; property cod_classe: Integer read F_cod_classe write F_cod_classe; property classe: string read F_classe write F_classe; property cod_professor: Integer read F_cod_professor write F_cod_professor; property professor: string read F_professor write F_professor; property cod_congregacao: Integer read F_cod_congregacao write F_cod_congregacao; end; implementation {$REGION 'Constructor and Destructor'} constructor TClasseProfessor.Create; begin ConexaoDB := aConexao; end; destructor TClasseProfessor.Destroy; begin inherited; end; {$ENDREGION} {$REGION 'CRUD'} function TClasseProfessor.Apagar: Boolean; var Qry: TFDQuery; begin if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' + IntToStr(F_codigo) + #13 + 'Descrição: ' + F_professor, mtConfirmation, [mbYes, mbNo], 0) = mrNO then begin Result := false; Abort; end; Try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM tb_classe_professor WHERE codigo=:codigo '); Qry.ParamByName('codigo').AsInteger := F_codigo; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; Finally if Assigned(Qry) then FreeAndNil(Qry) End; end; function TClasseProfessor.Atualizar: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE tb_classe_professor '+ ' SET cod_professor=:cod_professor, professor=:professor, cod_classe=:cod_classe, classe=:classe '+ ' WHERE codigo=:codigo'); Qry.ParamByName('codigo').AsInteger := F_codigo; Qry.ParamByName('cod_classe').AsInteger := F_cod_classe; Qry.ParamByName('classe').AsString := F_classe; Qry.ParamByName('cod_professor').AsInteger := F_cod_professor; Qry.ParamByName('professor').AsString := F_professor; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TClasseProfessor.Inserir: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO tb_classe_professor '+ ' (cod_professor, professor, cod_classe, classe, cod_congregacao) '+ ' VALUES(:cod_professor,:professor,:cod_classe,:classe ,:cod_congregacao)'); Qry.ParamByName('classe').AsString := Self.F_classe; Qry.ParamByName('professor').AsString := Self.F_professor; Qry.ParamByName('cod_classe').AsInteger := Self.F_cod_classe; Qry.ParamByName('cod_professor').AsInteger := Self.F_cod_professor; Qry.ParamByName('cod_congregacao').AsInteger := Self.F_cod_congregacao; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TClasseProfessor.Selecionar(id: Integer): Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT codigo, cod_professor, professor, cod_classe, classe,cod_congregacao '+ ' FROM tb_classe_professor where codigo=:codigo '); Qry.ParamByName('codigo').AsInteger := id; try Qry.Open; Self.F_codigo := Qry.FieldByName('codigo').AsInteger; Self.F_cod_classe := Qry.FieldByName('cod_classe').AsInteger; Self.F_classe := Qry.FieldByName('classe').AsString; Self.F_cod_professor := Qry.FieldByName('cod_professor').AsInteger; Self.F_professor := Qry.FieldByName('professor').AsString; Self.F_cod_congregacao := Qry.FieldByName('cod_congregacao').AsInteger; Except Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; {$ENDREGION} end.
unit Loading; interface uses System.SysUtils, System.UITypes, FMX.Types, FMX.Controls, FMX.StdCtrls, FMX.Objects, FMX.Effects, FMX.Layouts, FMX.Forms, FMX.Graphics, FMX.Ani, FMX.VirtualKeyboard, FMX.Platform; type TLoading = class private class var Layout : TLayout; class var Background : TRectangle; class var ArcLoad : TArc; class var MessageLoad : TLabel; class var Animation : TFloatAnimation; class var Circle : TCircle; class var LabelX : TLabel; public class procedure Show(const AForm : TForm; const AMessage : string); class procedure Hide; end; implementation { TLoading } class procedure TLoading.Hide; begin if Assigned(Layout) then begin try if Assigned(MessageLoad) then MessageLoad.DisposeOf; if Assigned(Animation) then Animation.DisposeOf; if Assigned(ArcLoad) then ArcLoad.DisposeOf; if Assigned(Background) then Background.DisposeOf; if Assigned(Layout) then Layout.DisposeOf; except end; end; MessageLoad := nil; Animation := nil; ArcLoad := nil; Layout := nil; Background := nil; end; class procedure TLoading.Show(const AForm : TForm; const AMessage: string); var FService: IFMXVirtualKeyboardService; begin //BackGround Background := TRectangle.Create(AForm); Background.Opacity := 0; Background.Parent := AForm; Background.Visible := true; Background.Align := TAlignLayout.Contents; Background.Fill.Color := TAlphaColorRec.Black; Background.Fill.Kind := TBrushKind.Solid; Background.Stroke.Kind := TBrushKind.None; Background.Visible := True; //Layout Text Layout := TLayout.Create(AForm); Layout.Opacity := 0; Layout.Parent := AForm; Layout.Visible := True; Layout.Align := TAlignLayout.Contents; Layout.Width := 250; Layout.Height := 78; Layout.Visible := True; Circle := TCircle.Create(AForm); Circle.Parent := Layout; Circle.Width := 60; Circle.Height := 60; Circle.Visible := True; Circle.Fill.Kind := TBrushKind.Solid; Circle.Fill.Color := TAlphaColorRec.Black; Circle.Opacity := 0.6; Circle.Stroke.Kind := TBrushKind.None; Circle.Align := TAlignLayout.Center; LabelX := TLabel.Create(Circle); LabelX.Parent := Circle; LabelX.Align := TAlignLayout.Center; LabelX.Width := 75; LabelX.TextSettings.Font.Size := 10; LabelX.TextSettings.FontColor := TAlphaColorRec.White; LabelX.StyledSettings := LabelX.StyledSettings - [TStyledSetting.Size, TStyledSetting.FontColor]; LabelX.Text := 'Aguarde'; LabelX.TextSettings.HorzAlign := TTextAlign.Center; LabelX.TextSettings.VertAlign := TTextAlign.Center; LabelX.BringToFront; //Arco Menor ArcLoad := TArc.Create(Circle); ArcLoad.Opacity := 1; ArcLoad.Visible := true; ArcLoad.Parent := Circle; ArcLoad.Align := TAlignLayout.Center; ArcLoad.Margins.Bottom := 55; ArcLoad.Width := 60; ArcLoad.Height := 60; ArcLoad.EndAngle := 280; ArcLoad.Stroke.Color := $FFFEFFFF; ArcLoad.Stroke.Thickness := 3; ArcLoad.Position.X := Trunc((Circle.Width - ArcLoad.Width) / 2); ArcLoad.Position.Y := 0; //Animation Animation := TFloatAnimation.Create(AForm); Animation.Parent := ArcLoad; Animation.StartValue := 0; Animation.StopValue := 360; Animation.Duration := 0.8; Animation.Loop := True; Animation.PropertyName := 'RotationAngle'; Animation.AnimationType := TAnimationType.InOut; Animation.Interpolation := TInterpolationType.Linear; Animation.Start; //Show Controls Background.AnimateFloat('Opacity', 0.0); Layout.AnimateFloat('Opacity', 1); Layout.BringToFront; //Hide KeyBoard TPlatformServices.Current.SupportsPlatformService(IFMXVirtualKeyboardService, IInterface(FService)); if (FService <> nil) then FService.HideVirtualKeyboard; FService := nil; end; end.
unit uRouleMap; interface uses MVC.Roule; type TRouleMap = class(TRoule) public constructor Create(); override; end; implementation uses IndexController, MainController, RoleController, UserController, VIPController, PayController; constructor TRouleMap.Create; begin inherited; //路径,控制器,视图目录,拦截器(默认拦截) SetRoule('', TIndexController, '', False); SetRoule('Main', TMainController, ''); SetRoule('User', TUserController, 'User'); SetRoule('Role', TRoleController, 'Role'); SetRoule('VIP', TVIPController, 'VIP'); SetRoule('Pay', TPayController, 'Pay'); end; end.
{*********************************************************************************************************************** * * TERRA Game Engine * ========================================== * * Copyright (C) 2003, 2014 by SÚrgio Flores (relfos@gmail.com) * *********************************************************************************************************************** * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ********************************************************************************************************************** * TERRA_SoundSource * Implements a 3D sound source *********************************************************************************************************************** } Unit TERRA_SoundSource; {$I terra.inc} {$IFDEF ANDROID} {$DEFINE USEJAVA} {$ENDIF} Interface Uses {$IFDEF USEDEBUGUNIT}TERRA_Debug,{$ENDIF} TERRA_Utils, TERRA_Math, TERRA_Vector3D, TERRA_Sound, TERRA_OS,TERRA_AL {$IFDEF USEJAVA},TERRA_Java{$ENDIF}; {$IFDEF USEJAVA} Const AudioTrackJavaClass = 'com.pascal.terra.TERRAAudioTrack'; {$ENDIF} Type SoundSource = Class; SoundSourceCallback = Procedure(MySource:SoundSource) Of Object; SoundSource = Class(TERRAObject) Protected _Handle:Integer; _Sound:Sound; _StartTime:Cardinal; _Pitch:Single; _Volume:Single; _Loop:Boolean; _Position:Vector3D; _Velocity:Vector3D; _Waiting:Boolean; {$IFDEF USEJAVA} _Track:JavaObject; {$ENDIF} _Callback:SoundSourceCallback; Function GetStatus:Integer; Procedure SetPitch(Value:Single); Procedure SetVolume(Value:Single); Procedure SetLoop(Value:Boolean); Procedure SetPosition(Position:Vector3D); Procedure SetVelocity(Velocity:Vector3D); Procedure UpdateSettings; Procedure Clear; Public Constructor Create; Procedure Release; Override; Procedure Bind(MySound:Sound); Procedure Start; Procedure Play; Procedure Pause; Procedure Stop; Procedure OnFinish(); Procedure SetCallback(Callback:SoundSourceCallback); Property Handle:Integer Read _Handle; Property Sound:TERRA_Sound.Sound Read _Sound; Property Status:Integer Read GetStatus; Property StartTime:Cardinal Read _StartTime; Property Pitch:Single Read _Pitch Write SetPitch; Property Volume:Single Read _Volume Write SetVolume; Property Loop:Boolean Read _Loop Write SetLoop; Property Waiting:Boolean Read _Waiting; Property Position:Vector3D Read _Position Write SetPosition; Property Velocity:Vector3D Read _Velocity Write SetVelocity; End; Implementation Uses TERRA_GraphicsManager, TERRA_SoundManager, TERRA_Log; // SoundSource Constructor SoundSource.Create; Begin _Handle := 0; _Sound := Nil; _Volume := 1.0; _Pitch := 1.0; _Position := VectorZero; //GraphicsManager.Instance().MainViewport.Camera.Position; _Velocity := VectorZero; _Loop := False; {$IFDEF USEJAVA} _Track := Nil; {$ENDIF} End; Procedure SoundSource.Release; Begin Clear; End; Procedure SoundSource.Clear; {$IFDEF USEJAVA} Var Frame:JavaFrame; {$ENDIF} Begin {$IFDEF DISABLESOUND} Exit; {$ENDIF} Stop; If Assigned(_Sound) Then _Sound.RemoveSource(Self); {$IFDEF USEJAVA} If (_Track<>Nil) Then Begin Java_Begin(Frame); _Track.CallVoidMethod(Frame, 'release', Nil); ReleaseObject(_Track); _Track := Nil; Java_End(Frame); End; {$ELSE} If (_Handle<>0) Then Begin alDeleteSources(1,@_Handle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} _Handle:=0; End; {$ENDIF} End; Procedure SoundSource.UpdateSettings; {$IFDEF USEJAVA} Var Params:JavaArguments; Frame:JavaFrame; {$ENDIF} Begin Exit; {$IFDEF USEJAVA} If _Track<>Nil Then Begin Log(logDebug, 'SoundSource', 'Setting volume'); Java_Begin(Frame); Params := JavaArguments.Create(Frame); Params.AddFloat(_Volume); _Track.CallVoidMethod(Frame, 'setVolume', Params); ReleaseObject(Params); Log(logDebug, 'SoundSource', 'Setting loop'); Params := JavaArguments.Create(Frame); Params.AddBoolean(_Loop); _Track.CallVoidMethod(Frame, 'setLoop', Params); ReleaseObject(Params); Java_End(Frame); End; {$ELSE} If (_Handle<=0) Then Exit; //alSourcef(_Handle, AL_PITCH, _Pitch); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} If (Self._Sound.Channels<=1) Then Begin alSourcef(_Handle, AL_GAIN, _Volume); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} alSourcefv(_Handle, AL_POSITION, @_Position); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} alSourcefv(_Handle, AL_VELOCITY, @_Velocity); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} alSourcef(_Handle, AL_REFERENCE_DISTANCE, 30.0); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} alSourcef(_Handle, AL_MAX_DISTANCE, 5000.0); alSourcef(_Handle, AL_ROLLOFF_FACTOR, 2.0); End; alSourcei(_Handle, AL_LOOPING, Integer(_Loop)); {$ENDIF} End; Procedure SoundSource.SetPitch(Value: Single); Begin If (Value=_Pitch) Then Exit; _Pitch := Value; UpdateSettings; End; Procedure SoundSource.SetVolume(Value:Single); Begin If (_Volume=Value) Then Exit; _Volume := Value; UpdateSettings; End; Procedure SoundSource.SetLoop(Value:Boolean); Begin _Loop := Value; UpdateSettings; End; Procedure SoundSource.SetPosition(Position: Vector3D); Begin _Position := Position; UpdateSettings; End; Procedure SoundSource.SetVelocity(Velocity: Vector3D); Begin _Velocity := Velocity; UpdateSettings; End; Procedure SoundSource.Bind(MySound:Sound); Begin If (_Sound=MySound) Or (Not Assigned(MySound)) Then Exit; Log(logDebug, 'SoundSource', 'Binding '+MySound.Name); If Assigned(_Sound) Then Clear; _Sound := MySound; _Sound.AttachSource(Self); _Waiting := True; End; Procedure SoundSource.Start; {$IFDEF USEJAVA} Var Params:JavaArguments; Samples:Integer; Frame:JavaFrame; {$ENDIF} Begin _Waiting := False; Log(logDebug, 'SoundSource', 'Updating '+ Sound.Name); Sound.Update; {$IFDEF USEJAVA} Samples := (Sound.Size Div Sound.SampleSize); Java_Begin(Frame); Params := JavaArguments.Create(Frame); Params.AddInteger(Sound.Channels); Params.AddInteger(Sound.Frequency); Params.AddInteger(Sound.Size); Params.AddWordArray(Sound.Data, Samples); _Track := JavaObject.Create(AudioTrackJavaClass, Params, Frame); ReleaseObject(Params); Java_End(Frame); Log(logDebug, 'SoundSource', 'Ready!'); {$ELSE} If (_Handle=0) Then Begin alGenSources(1, @_Handle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} End; alSourcei(_Handle, AL_BUFFER, Sound.Buffer); {$ENDIF} UpdateSettings; Self.Play; End; Procedure SoundSource.Play; Var I:Integer; {$IFDEF USEJAVA} Frame:JavaFrame; {$ENDIF} Begin //If (Status<>sndPlaying) Then Begin _StartTime := Application.GetTime; {$IFDEF USEJAVA} If (_Track<>Nil) Then Begin Log(logDebug, 'SoundSource', 'Playing track'); Java_Begin(Frame); _Track.CallVoidMethod(Frame, 'play', Nil); Java_End(Frame); End; {$ELSE} If (Assigned(SoundManager.Instance().Ambience)) Then alSource3i(_Handle, AL_AUXILIARY_SEND_FILTER, SoundManager.Instance().Ambience.Handle, 0, AL_FILTER_NULL); alSourcei(_Handle, AL_LOOPING, Integer(_Loop)); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} alSourcePlay(_Handle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} {$ENDIF} End; End; Procedure SoundSource.Pause; Begin If Status=sndPlaying Then Begin {$IFDEF USEJAVA} Self.Stop(); {$ELSE} alSourcePause(_Handle); {$ENDIF} End Else Play; End; Procedure SoundSource.Stop; {$IFDEF USEJAVA} Var Frame:JavaFrame; {$ENDIF} Begin If (Status<>sndStopped) Then Begin {$IFDEF USEJAVA} If _Track<>Nil Then Begin Log(logDebug, 'SoundSource', 'Stopping track'); Java_Begin(Frame); _Track.CallVoidMethod(Frame, 'stop', Nil); ReleaseObject(_Track); _Track := Nil; Java_End(Frame); End; {$ELSE} alSourceStop(_Handle); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} If (Assigned(SoundManager.Instance().Ambience)) Then Begin alSource3i(_Handle, AL_AUXILIARY_SEND_FILTER, AL_EFFECTSLOT_NULL, 0, AL_FILTER_NULL); {$IFDEF FULLDEBUG}DebugOpenAL;{$ENDIF} End; {$ENDIF} End; End; Function SoundSource.GetStatus:Integer; Var State:Integer; {$IFDEF USEJAVA} Frame:JavaFrame; {$ENDIF} Begin {$IFDEF USEJAVA} If _Track<>Nil Then Begin Java_Begin(Frame); Result := _Track.CallIntMethod(Frame, 'getState', Nil); Java_End(Frame); //Log(logDebug, 'Sound', 'Result='+IntToString(Result)); End Else Result := sndStopped; {$ELSE} alGetSourcei(_Handle, AL_SOURCE_STATE, @State); Case State Of AL_PLAYING: Result := sndPlaying; AL_PAUSED: Result := sndPaused; Else Result := sndStopped; End; {$ENDIF} End; Procedure SoundSource.SetCallback(Callback: SoundSourceCallback); Begin _Callback := Callback; End; Procedure SoundSource.OnFinish; Begin If Assigned(_Callback) Then Begin _Callback(Self); _Callback := Nil; End; End; End.
{ pagemngr unit Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit pagemngr; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ComCtrls; const pageNull = -1; DefStatusMessage = 'Step %d from %d'; type TPageOwner = TPageControl; TCheckPageEnabled = function (APageIndex:integer): Boolean of object; TPageManagerOption = (pmoSetFormCaption, pmoSetInfoControl); TPageManagerOptions = set of TPageManagerOption; { TPageManager } TPageManager = class(TComponent) private FNextBtn: TControl; FOnCheckPageEnabled: TCheckPageEnabled; FOnPageChanged: TNotifyEvent; FOptions: TPageManagerOptions; FPageOwner: TPageOwner; FPriorBtn: TControl; FSaveBtnNextClick: TNotifyEvent; FSaveBtnPriorClick: TNotifyEvent; FStatusControl: TControl; FStatusMessage: string; function GetPageCount: Integer; function GetPageIndex: Integer; procedure SetNextBtn(const AValue: TControl); procedure SetOnCheckPageEnabled(const AValue: TCheckPageEnabled); procedure SetOptions(const AValue: TPageManagerOptions); procedure SetPageIndex(const AValue: Integer); procedure SetPageOwner(const AValue: TPageOwner); procedure SetPriorBtn(const AValue: TControl); procedure BtnClickNext(Sender: TObject); procedure BtnClickPrior(Sender: TObject); procedure SetStatusControl(const AValue: TControl); procedure SetStatusMessage(const AValue: string); procedure SyncBtnNextClick(Sync: Boolean); procedure SyncBtnPriorClick(Sync: Boolean); protected function GetPriorPageIndex(Page: Integer): Integer; virtual; function GetNextPageIndex(Page: Integer): Integer; virtual; procedure Loaded; override; public constructor Create(AOwner: TComponent); virtual; procedure CheckBtnEnabled; procedure NextPage; procedure PriorPage; procedure PageChanged;virtual; property PageCount: Integer read GetPageCount; property PageIndex: Integer read GetPageIndex write SetPageIndex; published property PageOwner: TPageOwner read FPageOwner write SetPageOwner; property NextBtn: TControl read FNextBtn write SetNextBtn; property PriorBtn: TControl read FPriorBtn write SetPriorBtn; property OnCheckPageEnabled:TCheckPageEnabled read FOnCheckPageEnabled write SetOnCheckPageEnabled; property OnPageChanged: TNotifyEvent read FOnPageChanged write FOnPageChanged; property Options:TPageManagerOptions read FOptions write SetOptions default []; property StatusControl:TControl read FStatusControl write SetStatusControl; property StatusMessage:string read FStatusMessage write SetStatusMessage; end; implementation { TPageManager } procedure TPageManager.SetNextBtn(const AValue: TControl); begin if FNextBtn=AValue then exit; SyncBtnNextClick(false); FNextBtn:=AValue; SyncBtnNextClick(true); end; function TPageManager.GetPageCount: Integer; begin if Assigned(FPageOwner) then Result := FPageOwner.PageCount else Result := 0; end; function TPageManager.GetPageIndex: Integer; begin if Assigned(PageOwner) then Result := PageOwner.ActivePageIndex else Result := pageNull; end; procedure TPageManager.SetOnCheckPageEnabled(const AValue: TCheckPageEnabled); begin if FOnCheckPageEnabled=AValue then exit; FOnCheckPageEnabled:=AValue; end; procedure TPageManager.SetOptions(const AValue: TPageManagerOptions); begin if FOptions=AValue then exit; FOptions:=AValue; end; procedure TPageManager.SetPageIndex(const AValue: Integer); begin if Assigned(FPageOwner) and (FPageOwner.ActivePageIndex <> AValue) then begin FPageOwner.ActivePageIndex:=AValue; PageChanged; end; end; procedure TPageManager.SetPageOwner(const AValue: TPageOwner); begin if FPageOwner=AValue then exit; FPageOwner:=AValue; end; procedure TPageManager.SetPriorBtn(const AValue: TControl); begin if FPriorBtn=AValue then exit; SyncBtnPriorClick(false); FPriorBtn:=AValue; SyncBtnPriorClick(true); end; procedure TPageManager.BtnClickNext(Sender: TObject); begin if Assigned(FPageOwner) then begin FPageOwner.ActivePageIndex:=GetNextPageIndex(FPageOwner.ActivePageIndex); PageChanged; end; end; procedure TPageManager.BtnClickPrior(Sender: TObject); begin if Assigned(FPageOwner) then begin FPageOwner.ActivePageIndex:=GetPriorPageIndex(FPageOwner.ActivePageIndex); PageChanged; end; end; procedure TPageManager.SetStatusControl(const AValue: TControl); begin if FStatusControl=AValue then exit; FStatusControl:=AValue; end; procedure TPageManager.SetStatusMessage(const AValue: string); begin if FStatusMessage=AValue then exit; FStatusMessage:=AValue; end; procedure TPageManager.SyncBtnNextClick(Sync: Boolean); begin if Assigned(FNextBtn) and not (csDesigning in ComponentState) then begin if Sync then begin FSaveBtnNextClick := FNextBtn.OnClick; FNextBtn.OnClick := @BtnClickNext; end else begin FNextBtn.OnClick := FSaveBtnNextClick; FSaveBtnNextClick := nil; end; end; end; procedure TPageManager.SyncBtnPriorClick(Sync: Boolean); begin if Assigned(FPriorBtn) and not (csDesigning in ComponentState) then begin if Sync then begin FSaveBtnPriorClick := FPriorBtn.OnClick; FPriorBtn.OnClick := @BtnClickPrior; end else begin FPriorBtn.OnClick := FSaveBtnPriorClick; FSaveBtnPriorClick := nil; end; end; end; function TPageManager.GetPriorPageIndex(Page: Integer): Integer; begin Result:=Page; while Page > 0 do begin Dec(Page); if Assigned(FOnCheckPageEnabled) then begin if FOnCheckPageEnabled(Page) then break else if Page = 0 then exit; end else break; end; Result:=Page; end; function TPageManager.GetNextPageIndex(Page: Integer): Integer; begin Result:=Page; if not Assigned(FPageOwner) then exit; while Page < FPageOwner.PageCount-1 do begin Inc(Page); if Assigned(FOnCheckPageEnabled) then begin if FOnCheckPageEnabled(Page) then break else if Page = FPageOwner.PageCount then exit; end else break; end; Result:=Page; end; procedure TPageManager.PageChanged; var S:string; begin if Assigned(OnPageChanged) then OnPageChanged(Self); if FStatusMessage <> '' then begin S:=Format(FStatusMessage, [PageIndex+1, PageCount]); if (pmoSetFormCaption in Options) and Assigned(Owner) and (Owner is TCustomForm) then TCustomForm(Owner).Caption:=S; if (pmoSetInfoControl in Options) and Assigned(FStatusControl) then FStatusControl.Caption:=S; end; CheckBtnEnabled; end; procedure TPageManager.Loaded; begin inherited Loaded; if not (csDesigning in ComponentState) then begin SyncBtnNextClick(true); SyncBtnPriorClick(true); PageChanged; end; end; constructor TPageManager.Create(AOwner: TComponent); begin inherited Create(AOwner); FStatusMessage:=DefStatusMessage; end; procedure TPageManager.CheckBtnEnabled; var P:integer; begin P:=PageIndex; FNextBtn.Enabled:=GetNextPageIndex(P)>P; FPriorBtn.Enabled:=GetPriorPageIndex(P)<P; end; procedure TPageManager.NextPage; begin BtnClickNext(nil); end; procedure TPageManager.PriorPage; begin BtnClickPrior(nil); end; end.
unit SoundTypes; interface type TSoundInfo = record name : string; kind : integer; priority : integer; looped : boolean; volume : single; // 0 .. 1 pan : single; // -1 .. 1 end; implementation end.
unit Intro; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, jpeg, StdCtrls; type TIntroForm = class(TForm) IntroImage: TImage; IntroLabel: TLabel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure IntroImageClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure OnCloseTimer(Sender: TObject); private { Private declarations } public { Public declarations } end; var IntroForm: TIntroForm; CloseTimer: TTimer; implementation uses Main; {$R *.dfm} procedure TIntroForm.FormClose(Sender: TObject; var Action: TCloseAction); var pMainForm: Pointer; begin // Освобождаем ненужный таймер FreeAndNil(CloseTimer); // Закрываем Интро-Форму, // меняем адресс главной формы на MainForm и показываем ее Application.CreateForm(TMainForm, MainForm); pMainForm := @Application.MainForm; Pointer(pMainForm^) := MainForm; MainForm.Show; // После смены главной формы обновляем панель задач Application.MainFormOnTaskBar := False; Application.MainFormOnTaskBar := True; // Удаляем форму из пмяти Action := caFree; end; procedure TIntroForm.FormShow(Sender: TObject); begin CloseTimer := TTimer.Create(Self); CloseTimer.Interval := 5000; //5 Seconds CloseTimer.OnTimer := IntroForm.OnCloseTimer; CloseTimer.Enabled := True; end; procedure TIntroForm.IntroImageClick(Sender: TObject); begin Close; end; procedure TIntroForm.OnCloseTimer(Sender: TObject); begin Close; end; end.
unit ATxToolbarList; interface uses Controls, Classes, StdCtrls, ComCtrls, Menus; const cToolbarButtonsMax = 100; type PToolbarButtonRec = ^TToolbarButtonRec; TToolbarButtonRec = record FMenuItem: TMenuItem; FOldShortcut: TShortCut; FCheck: boolean; FDropdownMenu: TPopupMenu; FToolButton: TToolButton; FEn: boolean; end; type TToolbarList = class private FButtonsNum: integer; FCurrentsNum: integer; FButtons: array[1..cToolbarButtonsMax] of TToolbarButtonRec; FCurrents: array[1..cToolbarButtonsMax] of integer; FCurrentsDefaults: string; FImageList: TImageList; //function IsValidAvailIndex(N: integer): boolean; function IsValidCurrentIndex(N: integer): boolean; function MenuIndex(const AName: string): integer; procedure SetCurrentString(const AValue: string); function GetCurrentString: string; public constructor Create(AImageList: TImageList = nil; const ACurrentsDefault: string = ''); destructor Destroy; override; procedure Disable(const Name: string); procedure Clear; procedure ClearCurrents; function AddAvail(AMenuItem: TMenuItem; APopupMenu: TPopupMenu = nil): boolean; function AddCurrent(AMenuItem: TMenuItem): boolean; overload; function AddCurrent(AIndex: integer): boolean; overload; function AddCurrentAfter(AAvailNum, ACurrentNum: integer): boolean; function RemoveCurrent(ACurrentNum: integer): boolean; function IsAvailCurrent(AAvailNum: integer): boolean; function IndexOf(AMenuItem: TMenuItem): integer; function GetAvail(N: integer; var ARec: PToolbarButtonRec): boolean; function GetCurrent(N: integer; var AAvailNum: integer): boolean; function GetToolButton(AMenuItem: TMenuItem): TToolButton; procedure CopyTo(ADest: TToolbarList); procedure ApplyTo(AToolbar: TToolbar); procedure Update(AMenuItem: TMenuItem; AEnabled: boolean; AChecked: integer = -1; AVisible: integer = -1); property ImageList: TImageList read FImageList write FImageList; function MoveCurrentUp(N: integer): boolean; function MoveCurrentDown(N: integer): boolean; procedure ResetCurrents; function UpdateCaptions: string; property CurrentString: string read GetCurrentString write SetCurrentString; procedure PrepareShortcuts; procedure RestoreShortcuts; procedure UpdateImageIndex(AMenuItem: TMenuItem; AIndex: Integer); end; var sMsgButtonSeparator: string = '(Separator)'; function GetToolbarButtonId(const Rec: TToolbarButtonRec): string; implementation uses Windows, SysUtils, atViewerMsg, ATxMsgProc, Dialogs, Consts; { Helper functions } function GetToolbarButtonId(const Rec: TToolbarButtonRec): string; begin with Rec do Result:= Copy(FMenuItem.Name, 4, MaxInt); end; { TToolbarList } { function TToolbarList.IsValidAvailIndex(N: integer): boolean; begin Result:= (N>=1) and (N<=FButtonsNum); end; } function TToolbarList.IsValidCurrentIndex(N: integer): boolean; begin Result:= (N>=1) and (N<=FCurrentsNum); end; constructor TToolbarList.Create(AImageList: TImageList = nil; const ACurrentsDefault: string = ''); begin Clear; FImageList:= AImageList; FCurrentsDefaults:= ACurrentsDefault; end; destructor TToolbarList.Destroy; begin Clear; inherited; end; procedure TToolbarList.Clear; begin FButtonsNum:= 0; ClearCurrents; end; procedure TToolbarList.ClearCurrents; begin FCurrentsNum:= 0; end; function TToolbarList.AddAvail(AMenuItem: TMenuItem; APopupMenu: TPopupMenu = nil): boolean; begin ClearCurrents; Result:= FButtonsNum<cToolbarButtonsMax; if Result then begin Inc(FButtonsNum); with FButtons[FButtonsNum] do begin FMenuItem:= AMenuItem; FOldShortcut:= 0; FCheck:= (AMenuItem.Checked) or (AMenuItem.RadioItem); FDropdownMenu:= APopupMenu; FToolButton:= nil; FEn:= true; end; AMenuItem.Tag:= FButtonsNum; end; end; function TToolbarList.AddCurrent(AMenuItem: TMenuItem): boolean; begin Result:= AddCurrent(IndexOf(AMenuItem)); end; function TToolbarList.AddCurrent(AIndex: integer): boolean; begin Result:= FCurrentsNum<cToolbarButtonsMax; if Result then begin Inc(FCurrentsNum); FCurrents[FCurrentsNum]:= AIndex; end; end; procedure TToolbarList.CopyTo(ADest: TToolbarList); var i: integer; begin ADest.FImageList:= FImageList; ADest.FCurrentsDefaults:= FCurrentsDefaults; ADest.Clear; ADest.FButtonsNum:= FButtonsNum; ADest.FCurrentsNum:= FCurrentsNum; for i:= 1 to FButtonsNum do begin ADest.FButtons[i].FMenuItem:= FButtons[i].FMenuItem; ADest.FButtons[i].FOldShortcut:= FButtons[i].FOldShortcut; ADest.FButtons[i].FCheck:= FButtons[i].FCheck; ADest.FButtons[i].FDropdownMenu:= FButtons[i].FDropdownMenu; ADest.FButtons[i].FToolButton:= FButtons[i].FToolButton; end; for i:= 1 to FCurrentsNum do ADest.FCurrents[i]:= FCurrents[i]; end; function TToolbarList.GetAvail(N: integer; var ARec: PToolbarButtonRec): boolean; begin Result:= (N>0) and (N<=FButtonsNum); if Result then ARec:= @FButtons[N]; end; function TToolbarList.GetCurrent(N: integer; var AAvailNum: integer): boolean; begin Result:= IsValidCurrentIndex(N); if Result then AAvailNum:= FCurrents[N]; end; function TToolbarList.IsAvailCurrent(AAvailNum: integer): boolean; var i: integer; begin Result:= false; for i:= 1 to FCurrentsNum do if FCurrents[i]=AAvailNum then begin Result:= true; Break end; end; procedure TToolbarList.ApplyTo(AToolbar: TToolbar); var i: integer; begin for i:= Low(FButtons) to High(FButtons) do with FButtons[i] do FToolButton:= nil; with AToolbar do for i:= ButtonCount-1 downto 0 do Buttons[i].Free; AToolbar.Images:= FImageList; AToolbar.ButtonWidth:= FImageList.Width; AToolbar.ButtonHeight:= FImageList.Height; for i:= FCurrentsNum downto 1 do with FButtons[FCurrents[i]] do begin FToolButton:= TToolButton.Create(AToolbar); with FToolButton do begin Parent:= AToolbar; if FMenuItem.Caption = '-' then begin Style:= tbsSeparator; Hint:= ''; Width:= 6; end else begin Style:= tbsButton; Hint:= MsgStrip(FMenuItem.Caption); ImageIndex:= FMenuItem.ImageIndex; if FCheck then Style:= tbsCheck; if Assigned(FDropdownMenu) then begin Style:= tbsDropDown; DropdownMenu:= FDropdownMenu; end; OnClick:= FMenuItem.OnClick; end; end; end; end; procedure TToolbarList.Update(AMenuItem: TMenuItem; AEnabled: boolean; AChecked: integer = -1; AVisible: integer = -1); var Btn: TToolButton; en: boolean; begin with AMenuItem do begin if Tag>0 then begin Btn:= FButtons[Tag].FToolButton; En:= FButtons[Tag].FEn end else begin Btn:= nil; En:= True end; Enabled:= En and AEnabled; if Assigned(Btn) then Btn.Enabled:= Enabled; if AChecked>=0 then begin Checked:= (AChecked<>0); if Assigned(Btn) then Btn.Down:= Checked; end; if AVisible>=0 then begin //Visible:= (AVisible<>0); if Assigned(Btn) then Btn.Visible:= (AVisible<>0); end; end; end; function TToolbarList.IndexOf(AMenuItem: TMenuItem): integer; var i: integer; begin Result:= 0; for i:= 1 to FButtonsNum do if FButtons[i].FMenuItem=AMenuItem then begin Result:= i; Break end; end; function TToolbarList.AddCurrentAfter(AAvailNum, ACurrentNum: integer): boolean; var i: integer; begin if not IsValidCurrentIndex(ACurrentNum) then Result:= AddCurrent(AAvailNum) else begin Result:= FCurrentsNum<cToolbarButtonsMax; if Result then begin Inc(FCurrentsNum); for i:= FCurrentsNum downto ACurrentNum+2 do FCurrents[i]:= FCurrents[i-1]; FCurrents[ACurrentNum+1]:= AAvailNum; end; end; end; function TToolbarList.RemoveCurrent(ACurrentNum: integer): boolean; var i: integer; begin Result:= IsValidCurrentIndex(ACurrentNum); if Result then begin Dec(FCurrentsNum); for i:= ACurrentNum to FCurrentsNum do FCurrents[i]:= FCurrents[i+1]; end; end; { procedure TToolbarList.ShowCurrents; var i: integer; s: string; begin s:= ''; for i:= 1 to FCurrentsNum do s:= s + Format('%d: #%d: %s', [i, FCurrents[i], FButtons[FCurrents[i]].FMenuItem.Name]) + #13; ShowMessage(s); end; } function TToolbarList.MoveCurrentUp(N: integer): boolean; var i: integer; begin Result:= IsValidCurrentIndex(N) and (N>1); if Result then begin i:= FCurrents[N-1]; FCurrents[N-1]:= FCurrents[N]; FCurrents[N]:= i; end; end; function TToolbarList.MoveCurrentDown(N: integer): boolean; var i: integer; begin Result:= IsValidCurrentIndex(N) and (N<FCurrentsNum); if Result then begin i:= FCurrents[N+1]; FCurrents[N+1]:= FCurrents[N]; FCurrents[N]:= i; end; end; function SGetItem(var SList: string): string; var k: integer; begin k:= Pos(' ', SList); if k=0 then k:= MaxInt; Result:= Copy(SList, 1, k-1); Delete(SList, 1, k); end; procedure TToolbarList.SetCurrentString(const AValue: string); var Items, Item: string; N: integer; begin ClearCurrents; Items:= AValue; repeat Item:= SGetItem(Items); if Item='' then Break; Insert('mnu', Item, 1); N:= MenuIndex(Item); if N=0 then Continue; AddCurrent(N); until false; end; function TToolbarList.MenuIndex(const AName: string): integer; var i: integer; begin Result:= 0; for i:= 1 to FButtonsNum do if FButtons[i].FMenuItem.Name=AName then begin Result:= i; Break end; end; procedure TToolbarList.Disable(const Name: string); var i: integer; begin i:= MenuIndex('mnu'+Name); if i>0 then with FButtons[i] do begin FEn:= false; if Assigned(FMenuItem) then FMenuItem.Enabled:= false; if Assigned(FToolButton) then FToolButton.Enabled:= false; end else MsgError('Unknown command: ' + Name); end; function TToolbarList.GetCurrentString: string; var i: integer; begin Result:= ''; for i:= 1 to FCurrentsNum do Result:= Result+GetToolbarButtonId(FButtons[FCurrents[i]])+' '; end; procedure TToolbarList.ResetCurrents; begin SetCurrentString(FCurrentsDefaults); end; function TToolbarList.UpdateCaptions: string; var i: integer; begin for i:= 1 to FButtonsNum do with FButtons[i] do begin if Assigned(FToolButton) then FToolButton.Hint:= MsgStrip(FMenuItem.Caption); end; end; //Note: PrepareShortcuts double call shoud not break already saved shortcuts! procedure TToolbarList.PrepareShortcuts; var i: integer; S: string; Key: Word; Shift: TShiftState; begin for i:= 1 to FButtonsNum do with FButtons[i] do if Assigned(FMenuItem) and (FOldShortcut = 0) then begin S:= ShortcutToText(FMenuItem.ShortCut); ShortcutToKey(FMenuItem.ShortCut, Key, Shift); if (Length(S) = 1) or ((Key = VK_DELETE) and (Shift = [])) then begin FOldShortcut:= FMenuItem.ShortCut; FMenuItem.ShortCut:= TextToShortCut( {$ifdef MENX} MenuKeyCaps[mkcAlt] {$else} smkcAlt {$endif} {'Alt+'} + S); end; end; end; procedure TToolbarList.RestoreShortcuts; var i: integer; begin for i:= 1 to FButtonsNum do with FButtons[i] do if Assigned(FMenuItem) and (FOldShortcut <> 0) then begin FMenuItem.ShortCut:= FOldShortcut; FOldShortcut:= 0; end; end; function TToolbarList.GetToolButton(AMenuItem: TMenuItem): TToolButton; var N: Integer; begin N:= IndexOf(AMenuItem); if N > 0 then Result:= FButtons[N].FToolButton else Result:= nil; end; procedure TToolbarList.UpdateImageIndex(AMenuItem: TMenuItem; AIndex: Integer); var B: TToolButton; begin B:= GetToolButton(AMenuItem); if Assigned(B) then B.ImageIndex:= AIndex; end; end.
unit RESTRequest4D.Request.Params.Intf; interface uses REST.Types, System.Classes; type /// <summary> /// Interface to represent the parameters that a request can have. /// </summary> IRequestParams = interface ['{CB53222E-B9FD-4DF1-BDF6-4E0EA6E462A5}'] /// <summary> /// Removes all added parameters. /// </summary> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Clear: IRequestParams; /// <summary> /// Adds a new parameter. /// </summary> /// <param name="AName"> /// Name of the parameter. /// </param> /// <param name="AValue"> /// Parameter value. /// </param> /// <param name="AKind"> /// Type of parameter. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> /// <remarks> /// If the parameter already exists, its value will change. /// </remarks> function Add(const AName, AValue: string; const AKind: TRESTRequestParameterKind = TRESTRequestParameterKind.pkQUERY): IRequestParams; overload; /// <summary> /// Adds a new parameter. /// </summary> /// <param name="AName"> /// Name of the parameter. /// </param> /// <param name="AValue"> /// Parameter value. /// </param> /// <param name="AKind"> /// Type of parameter. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> /// <remarks> /// If the parameter already exists, its value will change. /// </remarks> function Add(const AName: string; const AValue: Currency; const AKind: TRESTRequestParameterKind = TRESTRequestParameterKind.pkQUERY): IRequestParams; overload; /// <summary> /// Adds a new parameter. /// </summary> /// <param name="AName"> /// Name of the parameter. /// </param> /// <param name="AValue"> /// Parameter value. /// </param> /// <returns> /// Returns the instance itself following the fluent API pattern. /// </returns> function Add(const AName: string; const AValue: TStream): IRequestParams; overload; end; implementation end.
unit SCS_Telemetry_Condensed; {==============================================================================} { SCS Telemetry API headers condenser, version 1.0a } { Condensed on: Wednesday 2014-05-07 02:18:25 } {==============================================================================} interface {$IFDEF CPUX64} {$DEFINE SCS_ARCHITECTURE_x64} {$ELSE} {$DEFINE SCS_ARCHITECTURE_x86} {$ENDIF} {.$DEFINE AssertTypeSize} {$IFDEF Debug} {$DEFINE AssertTypeSize} {$ENDIF} {$IFDEF Release} {$UNDEF AssertTypeSize} {$ENDIF} {=== scssdk.pas ===============================================================} (** * @file scssdk.h * * @brief Common SDK types and structures. *) // String types used in the API. type TUTF8Char = type AnsiChar; PUTF8Char = ^TUTF8Char; TelemetryString = type UTF8String; // Types used trough the SDK. scs_u8_t = Byte; p_scs_u8_t = ^scs_u8_t; scs_u16_t = Word; p_scs_u16_t = ^scs_u16_t; scs_s32_t = LongInt; {Integer} p_scs_s32_t = ^scs_s32_t; scs_u32_t = LongWord;{Cardinal} p_scs_u32_t = ^scs_u32_t; scs_u64_t = UInt64; p_scs_u64_t = ^scs_u64_t; scs_float_t = Single; p_scs_float_t = ^scs_float_t; scs_double_t = Double; p_scs_double_t = ^scs_double_t; scs_string_t = PUTF8Char; p_scs_string_t = ^scs_string_t; const SCS_U32_NIL = scs_u32_t(-1); (** * @brief Type of value provided during callback registration and passed back * to the callback. *) type scs_context_t = Pointer; (** * @brief Timestamp value. * * Value is expressed in microseconds. *) type scs_timestamp_t = scs_u64_t; p_scs_timestamp_t = ^scs_timestamp_t; // Common return codes. type scs_result_t = scs_s32_t; p_scs_result_t = ^scs_result_t; const SCS_RESULT_ok = scs_result_t(0); // Operation succeeded. SCS_RESULT_unsupported = scs_result_t(-1); // Operation or specified parameters are not supported. (e.g. the plugin does not support the requested version of the API) SCS_RESULT_invalid_parameter = scs_result_t(-2); // Specified parameter is not valid (e.g. null value of callback, invalid combination of flags). SCS_RESULT_already_registered = scs_result_t(-3); // There is already a registered callback for the specified function (e.g. event/channel). SCS_RESULT_not_found = scs_result_t(-4); // Specified item (e.g. channel) was not found. SCS_RESULT_unsupported_type = scs_result_t(-5); // Specified value type is not supported (e.g. channel does not provide that value type). SCS_RESULT_not_now = scs_result_t(-6); // Action (event/callback registration) is not allowed in the current state. Indicates incorrect use of the api. SCS_RESULT_generic_error = scs_result_t(-7); // Error not convered by other existing code. // Types of messages printed to log. type scs_log_type_t = scs_s32_t; p_scs_log_type_t = ^scs_log_type_t; const SCS_LOG_TYPE_message = scs_log_type_t(0); SCS_LOG_TYPE_warning = scs_log_type_t(1); SCS_LOG_TYPE_error = scs_log_type_t(2); (** * @brief Logs specified message to the game log. * * @param type Type of message. Controls generated prefixes and colors in console. * @param message Message to log. *) type scs_log_t = procedure(const aType: scs_log_type_t; const aMessage: scs_string_t); stdcall; // Common initialization structures. (** * @brief Initialization parameters common to most APIs provided * by the SDK. *) type scs_sdk_init_params_v100_t = Record (** * @brief Name of the game for display purposes. * * This is UTF8 encoded string containing name of the game * for display to the user. The exact format is not defined, * might be changed between versions and should be not parsed. * * This pointer will be never NULL. *) game_name: scs_string_t; (** * @brief Identification of the game. * * If the library wants to identify the game to do any * per-game configuration, this is the field which should * be used. * * This string contains only following characters: * @li lower-cased letters * @li digits * @li underscore * * This pointer will be never NULL. *) game_id: scs_string_t; (** * @brief Version of the game for purpose of the specific api * which is being initialized. * * Does NOT match the patch level of the game. *) game_version: scs_u32_t; {$IFDEF SCS_ARCHITECTURE_x64} (** * @brief Explicit alignment for the 64 bit pointer. *) _padding: scs_u32_t; {$ENDIF} (** * @brief Function used to write messages to the game log. * * Each message is printed on a separate line. * * This pointer will be never NULL. *) log: scs_log_t; end; p_scs_sdk_init_params_v100_t = ^scs_sdk_init_params_v100_t; // Routines for API strings conversions. Function APIStringToTelemetryString(const Str: scs_string_t): TelemetryString; Function TelemetryStringToAPIString(const Str: TelemetryString): scs_string_t; procedure APIStringFree(var Str: scs_string_t); Function TelemetryStringDecode(const Str: TelemetryString): String; Function TelemetryStringEncode(const Str: String): TelemetryString; // Routines replacing some of the C macros functionality. Function SCSCheckSize(ActualSize, Expected32, Expected64: Cardinal): Boolean; Function SCSMakeVersion(Major, Minor: scs_u16_t): scs_u32_t; Function SCSGetMajorVersion(Version: scs_u32_t): scs_u16_t; Function SCSGetMinorVersion(Version: scs_u32_t): scs_u16_t; Function SCSGetVersionAsString(Version: scs_u32_t): String; {=== scssdk_value.pas =========================================================} (** * @file scssdk_value.h * * @brief Structures representing varying type values in the SDK. *) type scs_value_type_t = scs_u32_t; p_scs_value_type_t = ^scs_value_type_t; const SCS_VALUE_TYPE_INVALID = scs_value_type_t(0); SCS_VALUE_TYPE_bool = scs_value_type_t(1); SCS_VALUE_TYPE_s32 = scs_value_type_t(2); SCS_VALUE_TYPE_u32 = scs_value_type_t(3); SCS_VALUE_TYPE_u64 = scs_value_type_t(4); SCS_VALUE_TYPE_float = scs_value_type_t(5); SCS_VALUE_TYPE_double = scs_value_type_t(6); SCS_VALUE_TYPE_fvector = scs_value_type_t(7); SCS_VALUE_TYPE_dvector = scs_value_type_t(8); SCS_VALUE_TYPE_euler = scs_value_type_t(9); SCS_VALUE_TYPE_fplacement = scs_value_type_t(10); SCS_VALUE_TYPE_dplacement = scs_value_type_t(11); SCS_VALUE_TYPE_string = scs_value_type_t(12); SCS_VALUE_TYPE_LAST = SCS_VALUE_TYPE_string; {SCS_VALUE_TYPE_string} (** * @name Simple data types. *) type //@{ scs_value_bool_t = Record value: scs_u8_t; //< Nonzero value is true, zero false. end; p_scs_value_bool_t = ^scs_value_bool_t; scs_value_s32_t = Record value: scs_s32_t; end; p_scs_value_s32_t = ^scs_value_s32_t; scs_value_u32_t = Record value: scs_u32_t; end; p_scs_value_u32_t = ^scs_value_u32_t; scs_value_u64_t = Record value: scs_u64_t; end; p_scs_value_u64_t = ^scs_value_u64_t; scs_value_float_t = Record value: scs_float_t; end; p_scs_value_float_t = ^scs_value_float_t; scs_value_double_t = Record value: scs_double_t; end; p_scs_value_double_t = ^scs_value_double_t; //@} (** * @brief String value. * * The provided value is UTF8 encoded however in some documented * cases only limited ASCII compatible subset might be present. * * The pointer is never NULL. *) scs_value_string_t = Record value: scs_string_t; end; p_scs_value_string_t = ^scs_value_string_t; (** * @name Vector types. * * In local space the X points to right, Y up and Z backwards. * In world space the X points to east, Y up and Z south. *) //@{ scs_value_fvector_t = Record x: scs_float_t; y: scs_float_t; z: scs_float_t; end; p_scs_value_fvector_t = ^scs_value_fvector_t; scs_value_dvector_t = Record x: scs_double_t; y: scs_double_t; z: scs_double_t; end; p_scs_value_dvector_t = ^scs_value_dvector_t; //@} (** * @brief Orientation of object. *) scs_value_euler_t = Record (** * @name Heading. * * Stored in unit range where <0,1) corresponds to <0,360). * * The angle is measured counterclockwise in horizontal plane when looking * from top where 0 corresponds to forward (north), 0.25 to left (west), * 0.5 to backward (south) and 0.75 to right (east). *) heading: scs_float_t; (** * @name Pitch * * Stored in unit range where <-0.25,0.25> corresponds to <-90,90>. * * The pitch angle is zero when in horizontal direction, * with positive values pointing up (0.25 directly to zenith), * and negative values pointing down (-0.25 directly to nadir). *) pitch: scs_float_t; (** * @name Rool * * Stored in unit range where <-0.5,0.5> corresponds to <-180,180>. * * The angle is measured in counterclockwise when looking in direction of * the roll axis. *) roll: scs_float_t; end; p_scs_value_euler_t = ^scs_value_euler_t; (** * @name Combination of position and orientation. *) //@{ scs_value_fplacement_t = Record position: scs_value_fvector_t; orientation: scs_value_euler_t; end; p_scs_value_fplacement_t = ^scs_value_fplacement_t; scs_value_dplacement_t = Record position: scs_value_dvector_t; orientation: scs_value_euler_t; _padding: scs_u32_t; // Explicit padding. end; p_scs_value_dplacement_t = ^scs_value_dplacement_t; //@} (** * @brief Varying type storage for values. *) scs_value_t = Record (** * @brief Type of the value. *) _type: scs_value_type_t; //"type" is reserved word in pascal (** * @brief Explicit alignment for the union. *) _padding: scs_u32_t; (** * @brief Storage. *) Case Integer of 0: (value_bool: scs_value_bool_t); 1: (value_s32: scs_value_s32_t); 2: (value_u32: scs_value_u32_t); 3: (value_u64: scs_value_u64_t); 4: (value_float: scs_value_float_t); 5: (value_double: scs_value_double_t); 6: (value_fvector: scs_value_fvector_t); 7: (value_dvector: scs_value_dvector_t); 8: (value_euler: scs_value_euler_t); 9: (value_fplacement: scs_value_fplacement_t); 10: (value_dplacement: scs_value_dplacement_t); 11: (value_string: scs_value_string_t); end; p_scs_value_t = ^scs_value_t; (** * @brief Combination of value and its name. *) scs_named_value_t = Record (** * @brief Name of this value. * * ASCII subset of UTF-8. *) name: scs_string_t; (** * @brief Zero-based index of the value for array-like values. * * For non-array values it is set to SCS_U32_NIL. *) index: scs_u32_t; {$IFDEF SCS_ARCHITECTURE_x64} (** * @brief Explicit 8-byte alignment for the value part. *) _padding: scs_u32_t; {$ENDIF} (** * @brief The value itself. *) value: scs_value_t; end; p_scs_named_value_t = ^scs_named_value_t; {=== scssdk_telemetry_event.pas ===============================================} (** * @file scssdk_telemetry_event.h * * @brief Telemetry SDK - events. *) type scs_event_t = scs_u32_t; p_scs_event_t = ^scs_event_t; (** * @name Telemetry event types. *) //{ const (** * @brief Used to mark invalid value of event type. *) SCS_TELEMETRY_EVENT_invalid = scs_event_t(0); (** * @brief Generated before any telemetry data for current frame. * * The event_info parameter for this event points to * scs_telemetry_frame_start_t structure. *) SCS_TELEMETRY_EVENT_frame_start = scs_event_t(1); (** * @brief Generated after all telemetry data for current frame. *) SCS_TELEMETRY_EVENT_frame_end = scs_event_t(2); (** * @brief Indicates that the game entered paused state (e.g. menu) * * If the recipient generates some form of force feedback effects, * it should probably stop them until SCS_TELEMETRY_EVENT_started * event is received. * * After sending this event, the game stop sending telemetry data * unless specified otherwise in description of specific telemetry. * The frame start and event events are still generated. *) SCS_TELEMETRY_EVENT_paused = scs_event_t(3); (** * @brief Indicates that the player is now driving. *) SCS_TELEMETRY_EVENT_started = scs_event_t(4); (** * @brief Provides set of attributes which change only * in special situations (e.g. parameters of the vehicle). * * The event_info parameter for this event points to * scs_telemetry_configuration_t structure. * * The initial configuration info is delivered to the plugin * after its scs_telemetry_init() function succeeds and before * any other callback is called. If the the plugin is interested * in the configuration info, it must register for this event * during its initialization call to ensure that it does * not miss it. Future changes in configuration are * delivered as described in the event sequence bellow. *) SCS_TELEMETRY_EVENT_configuration = scs_event_t(5); //@} // Sequence of events during frame. // // @li Optionally one or more CONFIGURATION events if the configuration changed. // @li Optionally one from PAUSED or STARTED if there was change since last frame. // @li FRAME_START // @li Cannel callbacks // @li FRAME_END (** * @brief Indicates that timers providing the frame timing info * were restarted since last frame. * * When timer is restarted, it will start counting from zero. *) SCS_TELEMETRY_FRAME_START_FLAG_timer_restart = scs_u32_t($00000001); (** * @brief Parameters the for SCS_TELEMETRY_EVENT_frame_start event callback. *) type scs_telemetry_frame_start_t = Record (** * @brief Additional information about this event. * * Combination of SCS_TELEMETRY_FRAME_START_FLAG_* values. *) flags: scs_u32_t; (** * @brief Explicit alignment for the 64 bit timestamps. *) _padding: scs_u32_t; (** * @brief Time controlling the visualization. * * Its step changes depending on rendering FPS. *) render_time: scs_timestamp_t; (** * @brief Time controlling the physical simulation. * * Usually changes with fixed size steps so it oscilates * around the render time. This value changes even if the * physics simulation is currently paused. *) simulation_time: scs_timestamp_t; (** * @brief Similar to simulation time however it stops * when the physics simulation is paused. *) paused_simulation_time: scs_timestamp_t; end; p_scs_telemetry_frame_start_t = ^scs_telemetry_frame_start_t; (** * @brief Parameters for the SCS_TELEMETRY_EVENT_configuration event callback. *) scs_telemetry_configuration_t = Record (** * @brief Set of logically grouped configuration parameters this * event describes (e.g. truck configuration, trailer configuration). * * See SCS_TELEMETRY_CONFIGURATION_ID_* constants for the game in question. * * This pointer will be never NULL. *) id: scs_string_t; (** * @brief Array of individual attributes. * * The array is terminated by entry whose name pointer is set to NULL. * * Names of the attributes are the SCS_TELEMETRY_ATTRIBUTE_ID_* constants * for the game in question. * * This pointer will be never NULL. *) attributes: p_scs_named_value_t; end; p_scs_telemetry_configuration_t = ^scs_telemetry_configuration_t; (** * @brief Type of function registered to be called for event. * * @param event Event in question. Allows use of single callback with more than one event. * @param event_info Structure with additional event information about the event. * @param context Context information passed during callback registration. *) scs_telemetry_event_callback_t = procedure(event: scs_event_t; event_info: Pointer; context: scs_context_t); stdcall; (** * @brief Registers callback to be called when specified event happens. * * At most one callback can be registered for each event. * * This funtion can be called from scs_telemetry_init or from within any * event callback other than the callback for the event itself. * * @param event Event to register for. * @param callback Callback to register. * @param context Context value passed to the callback. * @return SCS_RESULT_ok on successful registration. Error code otherwise. *) scs_telemetry_register_for_event_t = Function(event: scs_event_t; callback: scs_telemetry_event_callback_t; context: scs_context_t): scs_result_t; stdcall; (** * @brief Unregisters callback registered for specified event. * * This function can be called from scs_telemetry_shutdown, scs_telemetry_init * or from within any event callback. Including callback of the event itself. * Any event left registered after scs_telemetry_shutdown ends will * be unregistered automatically. * * @param event Event to unregister from. * @return SCS_RESULT_ok on successful unregistration. Error code otherwise. *) scs_telemetry_unregister_from_event_t = Function(event: scs_event_t): scs_result_t; stdcall; {=== scssdk_telemetry_channel.pas =============================================} (** * @file scssdk_telemetry_channel.h * * @brief Telemetry SDK - channels. *) (** * @name Telemetry channel flags. *) //{ const (** * @brief No specific flags. *) SCS_TELEMETRY_CHANNEL_FLAG_none = scs_u32_t($00000000); (** * @brief Call the callback even if the value did not change. * * The default behavior is to only call the callback if the * value changes. Note that there might be some special situations * where the callback might be called even if the value did not * change and this flag is not present. For example when the * provider of the channel value is reconfigured or when the value * changes so frequently that filtering would be only waste of time. * * Note that even this flag does not guarantee that the * callback will be called. For example it might be not called * when the value is currently unavailable and the * SCS_TELEMETRY_CHANNEL_FLAG_no_value flag was not provided. *) SCS_TELEMETRY_CHANNEL_FLAG_each_frame = scs_u32_t($00000001); (** * @brief Call the callback even if the value is currently * unavailable. * * By default the callback is only called when the value is * available. If this flag is specified, the callback will be * called even when the value is unavailable. In that case * the value parameter of the callback will be set to NULL. *) SCS_TELEMETRY_CHANNEL_FLAG_no_value = scs_u32_t($00000002); //@} type (** * @brief Type of function registered to be called with value of single telemetry channel. * * @param name Name of the channel. Intended for debugging purposes only. * @param index Index of entry for array-like channels. * @param value Current value of the channel. Will use the type provided during the registration. * Will be NULL if and only if the SCS_TELEMETRY_CHANNEL_FLAG_no_value flag was specified * during registration and the value is currently unavailable. * @param context Context information passed during callback registration. *) scs_telemetry_channel_callback_t = procedure(name: scs_string_t; index: scs_u32_t; value: p_scs_value_t; context: scs_context_t); stdcall; (** * @brief Registers callback to be called with value of specified telemetry channel. * * At most one callback can be registered for each combination of channel name, index and type. * * Note that order in which the registered callbacks are called is undefined. * * This funtion can be called from scs_telemetry_init or from within any * event (NOT channel) callback. * * @param name Name of channel to register to. * @param index Index of entry for array-like channels. Set to SCS_U32_NIL for normal channels. * @param type Desired type of the value. Only some types are supported (see documentation of specific channel). If the channel can not be returned using that type a SCS_RESULT_unsupported_type will be returned. * @param flags Flags controlling delivery of the channel. * @param callback Callback to register. * @param context Context value passed to the callback. * @return SCS_RESULT_ok on successful registration. Error code otherwise. *) scs_telemetry_register_for_channel_t = Function(name: scs_string_t; index: scs_u32_t; _type: scs_value_type_t; flags: scs_u32_t; callback: scs_telemetry_channel_callback_t; context: scs_context_t): scs_result_t; stdcall; (** * @brief Unregisters callback registered for specified telemetry channel. * * This function can be called from scs_telemetry_shutdown, scs_telemetry_init * or from within any event (NOT channel) callback. Any channel left registered * after scs_telemetry_shutdown ends will be unregistered automatically. * * @param name Name of channel to register from. * @param index Index of entry for array-like channels. Set to SCS_U32_NIL for normal channels. * @param type Type of value to unregister from. * @return SCS_RESULT_ok on successful unregistration. Error code otherwise. *) scs_telemetry_unregister_from_channel_t = Function(name: scs_string_t; index: scs_u32_t; _type: scs_value_type_t): scs_result_t; stdcall; {=== scssdk_telemetry.pas =====================================================} (** * @file scssdk_telemetry.h * * @brief Telemetry SDK. *) (** * @name Versions of the telemetry SDK * * Changes in the major version indicate incompatible changes in the API. * Changes in the minor version indicate additions (e.g. more events, defined * types as long layout of existing fields in scs_value_t does not change). *) //@{ const SCS_TELEMETRY_VERSION_1_00 = (1 shl 16) or 0 {0x00010000}; SCS_TELEMETRY_VERSION_CURRENT = SCS_TELEMETRY_VERSION_1_00; //@} // Structures used to pass additional data to the initialization function. type (** * @brief Common ancestor to all structures providing parameters to the telemetry * initialization. *) //scs_telemetry_init_params_t = Record //end; //see further (** * @brief Initialization parameters for the 1.00 version of the telemetry API. *) scs_telemetry_init_params_v100_t = Record (** * @brief Common initialization parameters. *) common: scs_sdk_init_params_v100_t; (** * @name Functions used to handle registration of event callbacks. *) //@{ register_for_event: scs_telemetry_register_for_event_t; unregister_from_event: scs_telemetry_unregister_from_event_t; //@} (** * @name Functions used to handle registration of telemetry callbacks. *) //@{ register_for_channel: scs_telemetry_register_for_channel_t; unregister_from_channel: scs_telemetry_unregister_from_channel_t; //@} end; p_scs_telemetry_init_params_v100_t = ^scs_telemetry_init_params_v100_t; scs_telemetry_init_params_t = scs_telemetry_init_params_v100_t; p_scs_telemetry_init_params_t = ^scs_telemetry_init_params_t; // Functions which should be exported by the dynamic library serving as // recipient of the telemetry. (** * @brief Initializes telemetry support. * * This function must be provided by the library if it wants to support telemetry API. * * The engine will call this function with API versions it supports starting from the latest * until the function returns SCS_RESULT_ok or error other than SCS_RESULT_unsupported or it * runs out of supported versions. * * At the time this function is called, the telemetry is in the paused state. * * @param version Version of the API to initialize. * @param params Structure with additional initialization data specific to the specified API version. * @return SCS_RESULT_ok if version is supported and library was initialized. Error code otherwise. *) scs_telemetry_init_t = Function(version: scs_u32_t; params: p_scs_telemetry_init_params_t): scs_result_t; stdcall; (** * @brief Shuts down the telemetry support. * * The engine will call this function if available and if the scs_telemetry_init indicated * success. *) scs_telemetry_shutdown_t = procedure; stdcall; {=== common/scssdk_telemetry_common_configs.pas ===============================} (** * @file scssdk_telemetry_common_configs.h * * @brief Telemetry specific constants for configs. * * This file defines truck specific telemetry constants which * might be used by more than one SCS game. See game-specific * file to determine which constants are supported by specific * game. *) const (** * @brief Configuration of the substances. * * Attribute index is index of the substance. * * Supported attributes: * @li id * TODO: Whatever additional info necessary. *) SCS_TELEMETRY_CONFIG_substances = TelemetryString('substances'); (** * @brief Static configuration of the controls. * * @li shifter_type *) SCS_TELEMETRY_CONFIG_controls = TelemetryString('controls'); (** * @brief Configuration of the h-shifter. * * When evaluating the selected gear, find slot which matches * the handle position and bitmask of on/off state of selectors. * If one is found, it contains the resulting gear. Otherwise * a neutral is assumed. * * Supported attributes: * @li selector_count * @li resulting gear index for each slot * @li handle position index for each slot * @li bitmask of selectors for each slot *) SCS_TELEMETRY_CONFIG_hshifter = TelemetryString('hshifter'); (** * @brief Static configuration of the truck. * * If empty set of attributes is returned, there is no configured truck. * * Supported attributes: * @li brand_id * @li brand * @li id * @li name * @li fuel_capacity * @li fuel_warning_factor * @li adblue_capacity * @li air_pressure_warning * @li air_pressure_emergency * @li oil_pressure_warning * @li water_temperature_warning * @li battery_voltage_warning * @li rpm_limit * @li foward_gear_count * @li reverse_gear_count * @li retarder_step_count * @li cabin_position * @li head_position * @li hook_position * @li wheel_count * @li wheel positions for wheel_count wheels *) SCS_TELEMETRY_CONFIG_truck = TelemetryString('truck'); (** * @brief Static configuration of the trailer. * * If empty set of attributes is returned, there is no configured trailer. * * Supported attributes: * @li id * @li cargo_accessory_id * @li hook_position * @li wheel_count * @li wheel offsets for wheel_count wheels *) SCS_TELEMETRY_CONFIG_trailer = TelemetryString('trailer'); // Attributes (** * @brief Brand id for configuration purposes. * * Limited to C-identifier characters. * * Type: string *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_brand_id = TelemetryString('brand_id'); (** * @brief Brand for display purposes. * * Localized using the current in-game language. * * Type: string *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_brand = TelemetryString('brand'); (** * @brief Name for internal use by code. * * Limited to C-identifier characters and dots. * * Type: string *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_id = TelemetryString('id'); (** * @brief Name of cargo accessory for internal use by code. * * Limited to C-identifier characters and dots. * * Type: string *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_cargo_accessory_id = TelemetryString('cargo.accessory.id'); (** * @brief Name for display purposes. * * Localized using the current in-game language. * * Type: string *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_name = TelemetryString('name'); (** * @brief Fuel tank capacity in litres. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_fuel_capacity = TelemetryString('fuel.capacity'); (** * @brief Fraction of the fuel capacity bellow which * is activated the fuel warning. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_fuel_warning_factor = TelemetryString('fuel.warning.factor'); (** * @brief AdBlue tank capacity in litres. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_adblue_capacity = TelemetryString('adblue.capacity'); (** * @brief Pressure of the air in the tank bellow which * the warning activates. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_air_pressure_warning = TelemetryString('brake.air.pressure.warning'); (** * @brief Pressure of the air in the tank bellow which * the emergency brakes activate. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_air_pressure_emergency = TelemetryString('brake.air.pressure.emergency'); (** * @brief Pressure of the oil bellow which the warning activates. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_oil_pressure_warning = TelemetryString('oil.pressure.warning'); (** * @brief Temperature of the water above which the warning activates. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_water_temperature_warning = TelemetryString('water.temperature.warning'); (** * @brief Voltage of the battery bellow which the warning activates. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_battery_voltage_warning = TelemetryString('battery.voltage.warning'); (** * @brief Maximal rpm value. * * Type: float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_rpm_limit = TelemetryString('rpm.limit'); (** * @brief Number of forward gears on undamaged truck. * * Type: u32 *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_forward_gear_count = TelemetryString('gears.forward'); (** * @brief Number of reversee gears on undamaged truck. * * Type: u32 *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_reverse_gear_count = TelemetryString('gears.reverse'); (** * @brief Number of steps in the retarder. * * Set to zero if retarder is not mounted to the truck. * * Type: u32 *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_retarder_step_count = TelemetryString('retarder.steps'); (** * @brief Position of the cabin in the vehicle space. * * This is position of the joint around which the cabin rotates. * This attribute might be not present if the vehicle does not * have a separate cabin. * * Type: fvector *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_cabin_position = TelemetryString('cabin.position'); (** * @brief Default position of the head in the cabin space. * * Type: fvector *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_head_position = TelemetryString('head.position'); (** * @brief Position of the trailer connection hook in vehicle * space. * * Type: fvector *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_hook_position = TelemetryString('hook.position'); (** * @brief Number of wheels * * Type: u32 *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_count = TelemetryString('wheels.count'); (** * @brief Position of respective wheels in the vehicle space. * * Type: indexed fvector *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_position = TelemetryString('wheel.position'); (** * @brief Is the wheel steerable? * * Type: indexed bool *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_steerable = TelemetryString('wheel.steerable'); (** * @brief Is the wheel physicaly simulated? * * Type: indexed bool *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_simulated = TelemetryString('wheel.simulated'); (** * @brief Radius of the wheel * * Type: indexed float *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_wheel_radius = TelemetryString('wheel.radius'); (** * @brief Number of selectors (e.g. range/splitter toggles). * * Type: u32 *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_selector_count = TelemetryString('selector.count'); (** * @brief Gear selected when requirements for this h-shifter slot are meet. * * Type: indexed s32 *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_slot_gear = TelemetryString('slot.gear'); (** * @brief Position of h-shifter handle. * * Zero corresponds to neutral position. Mapping to physical position of * the handle depends on input setup. * * Type: indexed u32 *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_slot_handle_position = TelemetryString('slot.handle.position'); (** * @brief Bitmask of required on/off state of selectors. * * Only first selector_count bits are relevant. * * Type: indexed u32 *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_slot_selectors = TelemetryString('slot.selectors'); (** * @brief Type of the shifter. * * One from SCS_SHIFTER_TYPE_* values. * * Type: string *) SCS_TELEMETRY_CONFIG_ATTRIBUTE_shifter_type = TelemetryString('shifter.type'); SCS_SHIFTER_TYPE_arcade = TelemetryString('arcade'); SCS_SHIFTER_TYPE_automatic = TelemetryString('automatic'); SCS_SHIFTER_TYPE_manual = TelemetryString('manual'); SCS_SHIFTER_TYPE_hshifter = TelemetryString('hshifter'); {=== common/scssdk_telemetry_common_channels.pas ==============================} (** * @file scssdk_telemetry_common_channels.h * * @brief Telemetry specific channels which might be used by more than one game. *) const (** * @brief Scale applied to distance and time to compensate * for the scale of the map (e.g. 1s of real time corresponds to local_scale * seconds of simulated game time). * * Games which use real 1:1 maps will not provide this * channel. * * Type: float *) SCS_TELEMETRY_CHANNEL_local_scale = TelemetryString('local.scale'); {=== common/scssdk_telemetry_trailer_common_channels.pas ======================} (** * @file scssdk_telemetry_trailer_common_channels.h * * @brief Trailer telemetry specific constants for channels. * * See scssdk_telemetry_truck_common_channels.h for more info. *) const (** * @brief Is the trailer connected to the truck? * * Type: bool *) SCS_TELEMETRY_TRAILER_CHANNEL_connected = TelemetryString('trailer.connected'); (** * @name Channels similar to the truck ones * * See scssdk_telemetry_truck_common_channels.h for description of * corresponding truck channels *) //@{ SCS_TELEMETRY_TRAILER_CHANNEL_world_placement = TelemetryString('trailer.world.placement'); SCS_TELEMETRY_TRAILER_CHANNEL_local_linear_velocity = TelemetryString('trailer.velocity.linear'); SCS_TELEMETRY_TRAILER_CHANNEL_local_angular_velocity = TelemetryString('trailer.velocity.angular'); SCS_TELEMETRY_TRAILER_CHANNEL_local_linear_acceleration = TelemetryString('trailer.acceleration.linear'); SCS_TELEMETRY_TRAILER_CHANNEL_local_angular_acceleration = TelemetryString('trailer.acceleration.angular'); // Damage. SCS_TELEMETRY_TRAILER_CHANNEL_wear_chassis = TelemetryString('trailer.wear.chassis'); // Wheels. SCS_TELEMETRY_TRAILER_CHANNEL_wheel_susp_deflection = TelemetryString('trailer.wheel.suspension.deflection'); SCS_TELEMETRY_TRAILER_CHANNEL_wheel_on_ground = TelemetryString('trailer.wheel.on_ground'); SCS_TELEMETRY_TRAILER_CHANNEL_wheel_substance = TelemetryString('trailer.wheel.substance'); SCS_TELEMETRY_TRAILER_CHANNEL_wheel_velocity = TelemetryString('trailer.wheel.angular_velocity'); SCS_TELEMETRY_TRAILER_CHANNEL_wheel_steering = TelemetryString('trailer.wheel.steering'); SCS_TELEMETRY_TRAILER_CHANNEL_wheel_rotation = TelemetryString('trailer.wheel.rotation'); //@} {=== common/scssdk_telemetry_truck_common_channels.pas ========================} (** * @file scssdk_telemetry_truck_common_channels.h * * @brief Truck telemetry specific constants for channels. * * This file defines truck specific telemetry constants which * might be used by more than one SCS game. See game-specific * file to determine which constants are supported by specific * game. * * Unless state otherwise, following rules apply. * @li Whenever channel has float based type (float, fvector, fplacement) * is can also provide double based values (double, dvector, dplacement) * and vice versa. Note that using the non-native type might incur * conversion costs or cause precision loss (double->float in * world-space context). * @li Whenever channel has u32 type is can also provide u64 value. * Note that using the non-native type might incur conversion costs. * @li Whenever channel uses placement based type (dplacement, fplacement), * it also supports euler type containg just the rotational part and * dvector/fvector type containing just the positional part. * @li Indexed entries are using zero-based indices. *) // Movement. const (** * @brief Represents world space position and orientation of the truck. * * Type: dplacement *) SCS_TELEMETRY_TRUCK_CHANNEL_world_placement = TelemetryString('truck.world.placement'); (** * @brief Represents vehicle space linear velocity of the truck measured * in meters per second. * * Type: fvector *) SCS_TELEMETRY_TRUCK_CHANNEL_local_linear_velocity = TelemetryString('truck.local.velocity.linear'); (** * @brief Represents vehicle space angular velocity of the truck measured * in rotations per second. * * Type: fvector *) SCS_TELEMETRY_TRUCK_CHANNEL_local_angular_velocity = TelemetryString('truck.local.velocity.angular'); (** * @brief Represents vehicle space linear acceleration of the truck measured * in meters per second^2 * * Type: fvector *) SCS_TELEMETRY_TRUCK_CHANNEL_local_linear_acceleration = TelemetryString('truck.local.acceleration.linear'); (** * @brief Represents vehicle space angular acceleration of the truck meassured * in rotations per second^2 * * Type: fvector *) SCS_TELEMETRY_TRUCK_CHANNEL_local_angular_acceleration = TelemetryString('truck.local.acceleration.angular'); (** * @brief Represents a vehicle space position and orientation delta * of the cabin from its default position. * * Type: fplacement *) SCS_TELEMETRY_TRUCK_CHANNEL_cabin_offset = TelemetryString('truck.cabin.offset'); (** * @brief Represents cabin space angular velocity of the cabin measured * in rotations per second. * * Type: fvector *) SCS_TELEMETRY_TRUCK_CHANNEL_cabin_angular_velocity = TelemetryString('truck.cabin.velocity.angular'); (** * @brief Represents cabin space angular acceleration of the cabin * measured in rotations per second^2 * * Type: fvector *) SCS_TELEMETRY_TRUCK_CHANNEL_cabin_angular_acceleration = TelemetryString('truck.cabin.acceleration.angular'); (** * @brief Represents a cabin space position and orientation delta * of the driver head from its default position. * * Note that this value might change rapidly as result of * the user switching between cameras or camera presets. * * Type: fplacement *) SCS_TELEMETRY_TRUCK_CHANNEL_head_offset = TelemetryString('truck.head.offset'); (** * @brief Speedometer speed in meters per second. * * Uses negative value to represent reverse movement. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_speed = TelemetryString('truck.speed'); // Powertrain related (** * @brief RPM of the engine. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_engine_rpm = TelemetryString('truck.engine.rpm'); (** * @brief Gear currently selected in the engine. * * @li >0 - Forwad gears * @li 0 - Neutral * @li <0 - Reverse gears * * Type: s32 *) SCS_TELEMETRY_TRUCK_CHANNEL_engine_gear = TelemetryString('truck.engine.gear'); // Driving (** * @brief Steering received from input <-1;1>. * * Note that it is interpreted counterclockwise. * * If the user presses the steer right button on digital input * (e.g. keyboard) this value goes immediatelly to -1.0 * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_input_steering = TelemetryString('truck.input.steering'); (** * @brief Throttle received from input <0;1> * * If the user presses the forward button on digital input * (e.g. keyboard) this value goes immediatelly to 1.0 * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_input_throttle = TelemetryString('truck.input.throttle'); (** * @brief Brake received from input <0;1> * * If the user presses the brake button on digital input * (e.g. keyboard) this value goes immediatelly to 1.0 * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_input_brake = TelemetryString('truck.input.brake'); (** * @brief Clutch received from input <0;1> * * If the user presses the clutch button on digital input * (e.g. keyboard) this value goes immediatelly to 1.0 * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_input_clutch = TelemetryString('truck.input.clutch'); (** * @brief Steering as used by the simulation <-1;1> * * Note that it is interpreted counterclockwise. * * Accounts for interpolation speeds and simulated * counterfoces for digital inputs. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_effective_steering = TelemetryString('truck.effective.steering'); (** * @brief Throttle pedal input as used by the simulation <0;1> * * Accounts for the press attack curve for digital inputs * or cruise-control input. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_effective_throttle = TelemetryString('truck.effective.throttle'); (** * @brief Brake pedal input as used by the simulation <0;1> * * Accounts for the press attack curve for digital inputs. Does * not contain retarder, parking or motor brake. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_effective_brake = TelemetryString('truck.effective.brake'); (** * @brief Clutch pedal input as used by the simulation <0;1> * * Accounts for the automatic shifting or interpolation of * player input. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_effective_clutch = TelemetryString('truck.effective.clutch'); (** * @brief Speed selected for the cruise control in m/s * * Is zero if cruise control is disabled. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_cruise_control = TelemetryString('truck.cruise_control'); // Gearbox related (** * @brief Gearbox slot the h-shifter handle is currently in. * * 0 means that no slot is selected. * * Type: u32 *) SCS_TELEMETRY_TRUCK_CHANNEL_hshifter_slot = TelemetryString('truck.hshifter.slot'); (** * @brief Enabled state of range/splitter selector toggles. * * Mapping between the range/splitter functionality and * selector index is described by HSHIFTER configuration. * * Type: indexed bool *) SCS_TELEMETRY_TRUCK_CHANNEL_hshifter_selector = TelemetryString('truck.hshifter.select'); // Brakes. (** * @brief Is the parking brake enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_parking_brake = TelemetryString('truck.brake.parking'); (** * @brief Is the motor brake enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_motor_brake = TelemetryString('truck.brake.motor'); (** * @brief Current level of the retarder. * * <0;max> where 0 is disabled retarder and max is maximal * value found in TRUCK configuration. * * Type: u32 *) SCS_TELEMETRY_TRUCK_CHANNEL_retarder_level = TelemetryString('truck.brake.retarder'); (** * @brief Pressure in the brake air tank in psi * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure = TelemetryString('truck.brake.air.pressure'); (** * @brief Is the air pressure warning active? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_warning = TelemetryString('truck.brake.air.pressure.warning'); (** * @brief Are the emergency brakes active as result of low air pressure? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_brake_air_pressure_emergency = TelemetryString('truck.brake.air.pressure.emergency'); (** * @brief Temperature of the brakes in degrees celsius. * * Aproximated for entire truck, not at the wheel level. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_brake_temperature = TelemetryString('truck.brake.temperature'); // Various = TelemetryString('consumables' (** * @brief Amount of fuel in liters * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_fuel = TelemetryString('truck.fuel.amount'); (** * @brief Is the low fuel warning active? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_fuel_warning = TelemetryString('truck.fuel.warning'); (** * @brief Average consumption of the fuel in liters/km * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_fuel_average_consumption = TelemetryString('truck.fuel.consumption.average'); (** * @brief Amount of AdBlue in liters * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_adblue = TelemetryString('truck.adblue'); (** * @brief Is the low adblue warning active? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_adblue_warning = TelemetryString('truck.adblue.warning'); (** * @brief Average consumption of the adblue in liters/km * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_adblue_average_consumption = TelemetryString('truck.adblue.consumption.average'); // Oil (** * @brief Pressure of the oil in psi * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_oil_pressure = TelemetryString('truck.oil.pressure'); (** * @brief Is the oil pressure warning active? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_oil_pressure_warning = TelemetryString('truck.oil.pressure.warning'); (** * @brief Temperature of the oil in degrees celsius. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_oil_temperature = TelemetryString('truck.oil.temperature'); // Temperature in various systems. (** * @brief Temperature of the water in degrees celsius. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_water_temperature = TelemetryString('truck.water.temperature'); (** * @brief Is the water temperature warning active? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_water_temperature_warning = TelemetryString('truck.water.temperature.warning'); // Battery (** * @brief Voltage of the battery in volts. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_battery_voltage = TelemetryString('truck.battery.voltage'); (** * @brief Is the battery voltage/not charging warning active? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_battery_voltage_warning = TelemetryString('truck.battery.voltage.warning'); // Enabled state of various elements. (** * @brief Is the electric enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_electric_enabled = TelemetryString('truck.electric.enabled'); (** * @brief Is the engine enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_engine_enabled = TelemetryString('truck.engine.enabled'); (** * @brief Is the left blinker enabled? * * This represents the logical enable state of the blinker. It * it is true as long the blinker is enabled regardless of the * physical enabled state of the light (i.e. it does not blink * and ignores enable state of electric). * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_lblinker = TelemetryString('truck.lblinker'); (** * @brief Is the right blinker enabled? * * This represents the logical enable state of the blinker. It * it is true as long the blinker is enabled regardless of the * physical enabled state of the light (i.e. it does not blink * and ignores enable state of electric). * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_rblinker = TelemetryString('truck.rblinker'); (** * @brief Is the light in the left blinker currently on? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_light_lblinker = TelemetryString('truck.light.lblinker'); (** * @brief Is the light in the right blinker currently on? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_light_rblinker = TelemetryString('truck.light.rblinker'); (** * @brief Are the parking lights enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_light_parking = TelemetryString('truck.light.parking'); (** * @brief Are the low beam lights enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_light_low_beam = TelemetryString('truck.light.beam.low'); (** * @brief Are the high beam lights enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_light_high_beam = TelemetryString('truck.light.beam.high'); (** * @brief Are the auxiliary front lights active? * * Those lights have several intensity levels: * @li 1 - dimmed state * @li 2 - full state * * Type: u32 *) SCS_TELEMETRY_TRUCK_CHANNEL_light_aux_front = TelemetryString('truck.light.aux.front'); (** * @brief Are the auxiliary roof lights active? * * Those lights have several intensity levels: * @li 1 - dimmed state * @li 2 - full state * * Type: u32 *) SCS_TELEMETRY_TRUCK_CHANNEL_light_aux_roof = TelemetryString('truck.light.aux.roof'); (** * @brief Are the beacon lights enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_light_beacon = TelemetryString('truck.light.beacon'); (** * @brief Is the brake light active? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_light_brake = TelemetryString('truck.light.brake'); (** * @brief Is the reverse light active? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_light_reverse = TelemetryString('truck.light.reverse'); (** * @brief Are the wipers enabled? * * Type: bool *) SCS_TELEMETRY_TRUCK_CHANNEL_wipers = TelemetryString('truck.wipers'); (** * @brief Intensity of the dashboard backlight as factor <0;1> * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_dashboard_backlight = TelemetryString('truck.dashboard.backlight'); // Wear info. (** * @brief Wear of the engine accessory as <0;1> * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_wear_engine = TelemetryString('truck.wear.engine'); (** * @brief Wear of the transmission accessory as <0;1> * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_wear_transmission = TelemetryString('truck.wear.transmission'); (** * @brief Wear of the cabin accessory as <0;1> * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_wear_cabin = TelemetryString('truck.wear.cabin'); (** * @brief Wear of the chassis accessory as <0;1> * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_wear_chassis = TelemetryString('truck.wear.chassis'); (** * @brief Average wear across the wheel accessories as <0;1> * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_wear_wheels = TelemetryString('truck.wear.wheels'); (** * @brief The value of the odometer in km. * * Type: float *) SCS_TELEMETRY_TRUCK_CHANNEL_odometer = TelemetryString('truck.odometer'); // Wheels. (** * @brief Vertical displacement of the wheel from its * neutral position in meters. * * Type: indexed float *) SCS_TELEMETRY_TRUCK_CHANNEL_wheel_susp_deflection = TelemetryString('truck.wheel.suspension.deflection'); (** * @brief Is the wheel in contact with ground? * * Type: indexed bool *) SCS_TELEMETRY_TRUCK_CHANNEL_wheel_on_ground = TelemetryString('truck.wheel.on_ground'); (** * @brief Substance bellow the whell. * * Index of substance as delivered trough SUBSTANCE config. * * Type: indexed u32 *) SCS_TELEMETRY_TRUCK_CHANNEL_wheel_substance = TelemetryString('truck.wheel.substance'); (** * @brief Angular velocity of the wheel in rotations per * second. * * Positive velocity corresponds to forward movement. * * Type: indexed float *) SCS_TELEMETRY_TRUCK_CHANNEL_wheel_velocity = TelemetryString('truck.wheel.angular_velocity'); (** * @brief Steering rotation of the wheel in rotations. * * Value is from <-0.25,0.25> range in counterclockwise direction * when looking from top (e.g. 0.25 corresponds to left and * -0.25 corresponds to right). * * Set to zero for non-steered wheels. * * Type: indexed float *) SCS_TELEMETRY_TRUCK_CHANNEL_wheel_steering = TelemetryString('truck.wheel.steering'); (** * @brief Rolling rotation of the wheel in rotations. * * Value is from <0.0,1.0) range in which value * increase corresponds to forward movement. * * Type: indexed float *) SCS_TELEMETRY_TRUCK_CHANNEL_wheel_rotation = TelemetryString('truck.wheel.rotation'); {=== eurotrucks2/scssdk_eut2.pas ==============================================} (** * @file scssdk_eut2.h * * @brief ETS 2 specific constants. *) const (** * @brief Value used in the scs_sdk_init_params_t::game_id to identify this game. *) SCS_GAME_ID_EUT2 = TelemetryString('eut2'); {=== eurotrucks2/scssdk_telemetry_eut2.pas ====================================} (** * @file scssdk_telemetry_eut2.h * * @brief ETS 2 telemetry specific constants. *) (** * @name Value used in the scs_sdk_init_params_t::game_version * * Changes in the major version indicate incompatible changes (e.g. changed interpretation * of the channel value). Change of major version is highly discouraged, creation of * alternative channel is preferred solution if necessary. * Changes in the minor version indicate compatible changes (e.g. added channel, more supported * value types). Removal of channel is also compatible change however it is recommended * to keep the channel with some default value. * * Changes: * 1.01 - added brake_air_pressure_emergency channel and air_pressure_emergency config * 1.02 - replaced cabin_orientation channel with cabin_offset channel * 1.03 - fixed reporting of invalid index value for wheels.count attribute * 1.04 - added lblinker_light and rblinker_light channels * 1.05 - fixed content of brand_id and brand attributes * 1.06 - fixed index value for selector_count attribute. It is now SCS_U32_NIL as the * attribute is not indexed. For backward compatibility additional copy with * index 0 is also present however it will be removed in the future. * 1.07 - fixed calculation of cabin_angular_acceleration channel. * 1.08 - a empty truck/trailer configuration event is generated when truck is removed * (e.g. after completion of quick job) *) //@{ const SCS_TELEMETRY_EUT2_GAME_VERSION_1_00 = (1 shl 16) or 0 {0x00010000}; SCS_TELEMETRY_EUT2_GAME_VERSION_1_01 = (1 shl 16) or 1 {0x00010001}; SCS_TELEMETRY_EUT2_GAME_VERSION_1_02 = (1 shl 16) or 2 {0x00010002}; SCS_TELEMETRY_EUT2_GAME_VERSION_1_03 = (1 shl 16) or 3 {0x00010003}; SCS_TELEMETRY_EUT2_GAME_VERSION_1_04 = (1 shl 16) or 4 {0x00010004}; SCS_TELEMETRY_EUT2_GAME_VERSION_1_05 = (1 shl 16) or 5 {0x00010005}; // Patch 1.4 SCS_TELEMETRY_EUT2_GAME_VERSION_1_06 = (1 shl 16) or 6 {0x00010006}; SCS_TELEMETRY_EUT2_GAME_VERSION_1_07 = (1 shl 16) or 7 {0x00010007}; // Patch 1.6 SCS_TELEMETRY_EUT2_GAME_VERSION_1_08 = (1 shl 16) or 8 {0x00010008}; // Patch 1.9 SCS_TELEMETRY_EUT2_GAME_VERSION_CURRENT = SCS_TELEMETRY_EUT2_GAME_VERSION_1_08; //@} // Channels defined in scssdk_telemetry_common_channels.h, // scssdk_telemetry_truck_common_channels.h and // scssdk_telemetry_trailer_common_channels.h are supported // with following exceptions and limitations as of v1.00: // // @li Adblue related channels are not supported. // @li The fuel_average_consumption is currently mostly static and depends // on presence of the trailer and skills of the driver instead // of the workload of the engine. // @li Rolling rotation of trailer wheels is determined from linear // movement. // @li The pressures, temperatures and voltages are not simulated. // They are very loosely approximated. // Additionally following channels are supported: // TODO: Date time, next rest stop, remaining distance // Configurations defined in scssdk_telemetry_common_configs.h are // supported with following exceptions and limitations as of v1.00: // // @li The localized strings are not updated when different in-game // language is selected. // Additionally following configurations are supported: // TODO: Job info {******************************************************************************} {******************************************************************************} {******************************************************************************} implementation uses SysUtils; {=== scssdk.pas ===============================================================} Function APIStringToTelemetryString(const Str: scs_string_t): TelemetryString; begin If Assigned(Str) then begin SetLength(Result,StrLen(PAnsiChar(Str))); Move(Str^,PUTF8Char(Result)^,Length(Result)); end else Result := ''; end; //------------------------------------------------------------------------------ Function TelemetryStringToAPIString(const Str: TelemetryString): scs_string_t; begin If Length(Str) > 0 then Result := scs_string_t(StrNew(PAnsiChar(Str))) else Result := nil; end; //------------------------------------------------------------------------------ procedure APIStringFree(var Str: scs_string_t); begin If Assigned(Str) then begin StrDispose(PAnsiChar(Str)); Str := nil; end; end; //------------------------------------------------------------------------------ Function TelemetryStringDecode(const Str: TelemetryString): String; begin {$IFDEF Unicode} Result := UTF8Decode(Str); {$ELSE} Result := UTF8ToAnsi(Str); {$ENDIF} end; //------------------------------------------------------------------------------ Function TelemetryStringEncode(const Str: String): TelemetryString; begin {$IFDEF Unicode} Result := UTF8Encode(Str); {$ELSE} Result := AnsiToUTF8(Str); {$ENDIF} end; //------------------------------------------------------------------------------ Function SCSCheckSize(ActualSize, Expected32, Expected64: Cardinal): Boolean; begin {$IFDEF SCS_ARCHITECTURE_x64} Result := ActualSize = Expected64; {$ELSE} {$IFDEF SCS_ARCHITECTURE_x86} Result := ActualSize = Expected32; {$ELSE} {$MESSAGE FATAL 'Undefined architecture!'} //better prevent compilation Halt(666); //architecture is not known, initiate immediate abnormal termination {$ENDIF} {$ENDIF} end; //------------------------------------------------------------------------------ Function SCSMakeVersion(Major, Minor: scs_u16_t): scs_u32_t; begin Result := (Major shl 16) or Minor; end; //------------------------------------------------------------------------------ Function SCSGetMajorVersion(Version: scs_u32_t): scs_u16_t; begin Result := (Version shr 16) and $FFFF; end; //------------------------------------------------------------------------------ Function SCSGetMinorVersion(Version: scs_u32_t): scs_u16_t; begin Result := Version and $FFFF; end; //------------------------------------------------------------------------------ Function SCSGetVersionAsString(Version: scs_u32_t): String; begin Result := IntToStr(SCSGetMajorVersion(Version)) + '.' + IntToStr(SCSGetMinorVersion(Version)); end; {******************************************************************************} {******************************************************************************} {******************************************************************************} {$IFDEF AssertTypeSize} initialization {=== scssdk.pas ===============================================================} Assert(SCSCheckSize(SizeOf(scs_sdk_init_params_v100_t),16,32)); {=== scssdk_value.pas =========================================================} Assert(SCSCheckSize(SizeOf(scs_value_bool_t),1,)); Assert(SCSCheckSize(SizeOf(scs_value_s32_t),4,4)); Assert(SCSCheckSize(SizeOf(scs_value_u32_t),4,4)); Assert(SCSCheckSize(SizeOf(scs_value_u64_t),8,8)); Assert(SCSCheckSize(SizeOf(scs_value_float_t),4,4)); Assert(SCSCheckSize(SizeOf(scs_value_double_t),8,8)); Assert(SCSCheckSize(SizeOf(scs_value_fvector_t),12,12)); Assert(SCSCheckSize(SizeOf(scs_value_dvector_t),24,24)); Assert(SCSCheckSize(SizeOf(scs_value_fplacement_t),24,24)); Assert(SCSCheckSize(SizeOf(scs_value_dplacement_t),40,40)); Assert(SCSCheckSize(SizeOf(scs_value_string_t),4,8)); Assert(SCSCheckSize(SizeOf(scs_value_t),48,48)); Assert(SCSCheckSize(SizeOf(scs_named_value_t),56,64)); {=== scssdk_telemetry_event.pas ===============================================} Assert(SCSCheckSize(SizeOf(scs_telemetry_frame_start_t),32,32)); Assert(SCSCheckSize(SizeOf(scs_telemetry_configuration_t),8,16)); {=== scssdk_telemetry.pas =====================================================} Assert(SCSCheckSize(SizeOf(scs_telemetry_init_params_v100_t),32,64)); {$ENDIF} end.
{ ---------------------------------------------------------------------------- zbnc - Multi user IRC bouncer Copyright (c) Michael "Zipplet" Nixon 2009. Licensed under the MIT license, see license.txt in the project trunk. Unit: ircparser.pas Purpose: IRC parsing unit (for connections to IRC servers) ---------------------------------------------------------------------------- } unit ircparser; // ----------------------------------------------------------------------------- // NBs - search for them to find the relevant code // NB@2: Nothing is done if an unknown cmode is seen and // options.auto_cmode_add is disabled. Maybe should raise an error? // all: Exception handling for on handlers // ----------------------------------------------------------------------------- // Switches for the IRC parser // safenames: If declared, /names list names will be checked to make sure that // they do not already exist before being added. Generally this is a stupid check // but it could be required for example when testing a broken IRCD or a bug. //{$define safenames} // debug: If declared, exceptions + onwarning() report more information about the // location of the fault, possibly even the function last called. Also, tirc // will maintain a "circular buffer" of the most recently sent and received IRC // traffic. This is an option because it compiles a slower tirc. {$define debug} // Do we want to be *core (bewareserv core units) compatible? // This is required for freepascal compilation - but if you are compiling this // using delphi and want to use the VCL, please undefine this. If you fail to // set this properly, tirc will not compile, or timers will not function. {$define usecore} interface uses {$ifdef win32} {$ifdef usecore} wcore, // needed for the timer {$else} extctrls, // needed for the timer {$endif} wsocket, {$else} {$ifndef usecore} {$ifdef fpc}{$FATAL Cannot compile for Linux/Unix without usecore defined!}{$endif} {$endif} lsocket, lcore, {$ifdef VER1_0} linux, {$else} baseunix, unix, unixutil, {$endif} {$endif} classes, sysutils, zipplet, btime; // Note: unitstrtok -> zipplet. const ircparser_version: string = 'v0.4.1 20051024'; // --------------------------------------------------------------------------- // List mode types, in order // --------------------------------------------------------------------------- CINVALID = 0; // No such mode? CLIST = 1; // Mode is a list mode CSETUNSET = 2; // Mode is a set/unset (+k hi, -k hi) CSET = 3; // Mode is a set (+l 10, -l) CBOOL = 4; // Mode is boolean // --------------------------------------------------------------------------- // IRC list mode numerics // --------------------------------------------------------------------------- INUM_BAN_ITEM = '367'; INUM_BAN_END = '368'; INUM_EXCEPT_ITEM = '348'; INUM_EXCEPT_END = '349'; INUM_INVITE_ITEM = '346'; INUM_INVITE_END = '347'; // --------------------------------------------------------------------------- // Bitfield table (this is faster than calculating it using SHL) // --------------------------------------------------------------------------- bf_bit: array[0..15] of integer = ( 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 ); // --------------------------------------------------------------------------- // IRC limits // --------------------------------------------------------------------------- maxmessagelength = 510; // maximum IRC message length - 2 maxparamcount = 16; // max number of params (tokens) - 1 // --------------------------------------------------------------------------- // Debugging // --------------------------------------------------------------------------- {$ifdef debug} circular_size = 10; // debug circular queue size {$endif} // --------------------------------------------------------------------------- // irclower table // --------------------------------------------------------------------------- ircltable: array[0..255] of byte = ( { $00 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $10 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $20 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $30 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $40 } $00,$61,$62,$63,$64,$65,$66,$67,$68,$69,$6A,$6B,$6C,$6D,$6E,$6F, { $50 } $70,$71,$72,$73,$74,$75,$76,$77,$78,$79,$7A,$7B,$7C,$7D,$00,$00, { $60 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $70 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $80 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $90 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $A0 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $B0 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $C0 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $D0 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $E0 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, { $F0 } $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00 ); type // --------------------------------------------------------------------------- // Enumerations // --------------------------------------------------------------------------- nqueue = (nq_all, nq_whois, nq_userhost); nwaitresult = (nw_event, nw_timeout, nw_destroyed, nw_failed); // --------------------------------------------------------------------------- // Exceptions // --------------------------------------------------------------------------- ESocketAlreadyConnected = class(exception); ESocketNotConnected = class(exception); ESocketConnectFailure = class(exception); ESocketWriteError = class(exception); ESocketReadError = class(exception); EInvalidConnectState = class(exception); EBadMessageSize = class(exception); EInternalError = class(exception); ELostState = class(exception); EBadModeChar = class(exception); ENilEvent = class(exception); // --------------------------------------------------------------------------- // Channel mode record // --------------------------------------------------------------------------- cmode = record // The boolval has a special use for list modes // If its false, the next 367 or whatever should clear the list, then it // will become true until the end of the list is received. boolval: boolean; strval: shortstring; list: tstringlist; tslist: tstringlist; wholist: tstringlist; // trustable - true if the list has been fully filled by a 368 or so trustable: boolean; end; // --------------------------------------------------------------------------- // WHOIS result record // --------------------------------------------------------------------------- rwhois = record nick, host, fullname: string; channels: tstringlist; server, serverinfo: string; seconds_idle: integer; signonts: integer; account: string; ircop: boolean; awaymsg: string; away: boolean; failed: boolean; realhost, realip: string; realinfo: boolean; end; // --------------------------------------------------------------------------- // Callback types // --------------------------------------------------------------------------- twhoisevent = procedure(nick: string; data: rwhois; timedout: boolean) of object; tuserhostevent = procedure(nick, host: string; timedout: boolean) of object; // --------------------------------------------------------------------------- // Queue classes // --------------------------------------------------------------------------- tirc_queue = class(tobject) ptr_prev: tirc_queue; // linked list pointer: previous ptr_next: tirc_queue; // linked list pointer: next ts: integer; // timestamp event was issued itemtype: nqueue; // Queue item type waiting, destroying: boolean; // Queue object is being destroyed or waited for processed: boolean; // Object processed and waiting for destroy timedout: boolean; // Timed out? end; tirc_queuewhois = class(tirc_queue) notify: twhoisevent; // func to call when whois lookup completes nick: string; // nick we are looking up end; tirc_queueuserhost = class(tirc_queue) notify: tuserhostevent; // func to call when whois lookup completes nick: string; // nick we are looking up end; // --------------------------------------------------------------------------- // tirc object class: user in channel // --------------------------------------------------------------------------- tirc_user = class(tobject) ptr_prev: tirc_user; // previous linkedlist item ptr_next: tirc_user; // next linkedlist item nick: string; // nickname host: string; // host (ident@host) modes: integer; // membermodes (bitfield) server: string; // Server fullname: string; // Full name away: boolean; // Away or here? ircop: boolean; // IRCop? end; // --------------------------------------------------------------------------- // tirc object class: channel // --------------------------------------------------------------------------- tirc_channel = class(tobject) ptr_prev: tirc_channel; // previous linkedlist item ptr_next: tirc_channel; // next linkedlist item name: string; // channel name, including prefix topic: string; // topic topicnick, topichost: string; // who set the topic topicts: integer; // topic set timestamp createdts: integer; // channel created timestamp user: tirc_user; // users in the channel user_last: tirc_user; // last user in the channel modes: array of cmode; // channel modes usercount: integer; // speedup: users in channel expecting_users: boolean; // wipe userlist when we get a name? sync, syncfull, syncwho: boolean; // Synchronisation event flags end; // --------------------------------------------------------------------------- // IRC options // --------------------------------------------------------------------------- rircoptions = record who_on_join: boolean; // Send WHO on channeljoin? onwho_always: boolean; // Always send this even more than once? queue_interval: integer; // Interval (milliseconds) to check queue auto_cmode_add: boolean; // Try to add "unknown" modes automatically action_onaction: boolean; // ACTION ctcps use onaction not onctcp? end; // If not using *core units, we want to use delphi's timer. {$ifndef usecore} tltimer = ttimer; {$endif} // --------------------------------------------------------------------------- // tirc class // --------------------------------------------------------------------------- tirc = class(tobject) // ------------------------------------------------------------------------- // user useable vars // ------------------------------------------------------------------------- nickname, email, fullname: string; // Identification options: rircoptions; // Options // ------------------------------------------------------------------------- // Internal variables, do not touch // ------------------------------------------------------------------------- socket: TWSocket; // twsocket queuetimer: tltimer; // Queue timer queue_busy: boolean; // Queue "locked"? int_whois: rwhois; // Internel whois record channel: tirc_channel; // first channel item channel_last: tirc_channel; // Last channel item channelcount: integer; // number of channel items queue: tirc_queue; // First queue item queue_last: tirc_queue; // Last queue item supports_bans: boolean; // Server supports bans? supports_excepts: boolean; // Server supports excepts? supports_invites: boolean; // Server supports invites? serverhost: string; // Connection: server info serverircd: string; // connection info: server serverpassword: string; // server password serverport: integer; // Connection: server port linebuffer: string; // Line parsing buffer param: array[0..maxparamcount] of string; // parser params params: integer; // parser params count got001: boolean; // Did we get 001 (auth?) got005: boolean; // Did we get 005? notready: boolean; // got 005 + motd? connected: boolean; // connected? membermodes: string; // member modes membermodel: string; // member modes shown (list) mmodelookup: array[0..255] of integer; // Power of 2 lookup table symbols mmodelookupm: array[0..255] of integer; // Power of 2 lookup table modes usermodes: string; // allowed user modes cmodelookup: array[0..255] of integer; // chanmode -> array lookup cmodetype: array[0..255] of integer; // chanmode type cmodelist: array of boolean; // Is listmode in array? numcmode: integer; // number of channel modes hostmask: string; // Our hostmask mymodes: array[0..255] of boolean; // what usermodes we have set isupport_key, isupport_value: tstringlist; // ISUPPORT (005) settings // ------------------------------------------------------------------------- // Error tracking // ------------------------------------------------------------------------- {$ifdef debug} in_circular: array[0..circular_size] of string; out_circular: array[0..circular_size] of string; in_ptrcircular, out_ptrcircular: integer; lastcall: string; // last called sub/func lastcall_info: string; // last call info {$endif} // ------------------------------------------------------------------------- // Method pointers (event callbacks) // ------------------------------------------------------------------------- onwarning: procedure(msg: string) of object; onrawin: procedure(msg: string) of object; onrawout: procedure(msg: string) of object; onconnectsuccess: procedure of object; ondisconnected: procedure of object; onmynickchange: procedure(newnick: string) of object; onauthed: procedure of object; onready: procedure of object; onnickinuse: procedure of object; onpasswordincorrect: procedure of object; onmejoin: procedure(chan: tirc_channel) of object; onmepart: procedure(chan: string) of object; onmekick: procedure(chan: string; nick, host, reason: string) of object; onjoinsync: procedure(chan: tirc_channel) of object; onjoinsyncfull: procedure(chan: tirc_channel) of object; onwho: procedure(chan: tirc_channel) of object; onwhois: procedure(data: rwhois) of object; onjoin: procedure(chan: tirc_channel; user: tirc_user) of object; onpart: procedure(chan: tirc_channel; nick, host: string; reason: string) of object; onkick: procedure(chan: tirc_channel; kickednick, nick, host, reason: string) of object; onquit: procedure(nick, host, reason: string) of object; onquitchan: procedure(nick, host, reason: string; c: tirc_channel); onprivmsg: procedure(target, msg, nick, host: string) of object; onprivmsgme: procedure(target, msg, nick, host: string) of object; onnotice: procedure(target, msg, nick, host: string) of object; onnoticeme: procedure(target, msg, nick, host: string) of object; onctcp: procedure(target, command, params, nick, host: string) of object; onctcpme: procedure(target, command, params, nick, host: string) of object; onaction: procedure(target, msg, nick, host: string) of object; onactionme: procedure(target, msg, nick, host: string) of object; onaddedboolmode: procedure(modechar: string) of object; onlistban: procedure(c: tirc_channel) of object; onlistexcept: procedure(c: tirc_channel) of object; onlistinvite: procedure(c: tirc_channel) of object; // ------------------------------------------------------------------------- // Timer callbacks // ------------------------------------------------------------------------- procedure queuetimerevent(sender: tobject); // ------------------------------------------------------------------------- // Socket callbacks // ------------------------------------------------------------------------- procedure SocketDataAvailable(Sender: TObject; Error: Word); procedure SocketSessionConnected(Sender: TObject; Error: Word); procedure SocketSessionClosed(Sender: TObject; Error: Word); procedure SocketBGException(Sender: TObject; E: Exception; var CanClose: Boolean); // ------------------------------------------------------------------------- // Functions and procedures that can be used by the outside world // ------------------------------------------------------------------------- procedure connect(host: string; port: integer; password: string); procedure lineout(msg: string); procedure changenick(newnick: string); procedure joinchannel(channel: string; key: string = ''); procedure partchannel(channel: string; reason: string = ''); procedure privmsg(destination, msg: string); procedure ctcp(destination, command: string; params: string = ''); procedure ctcpreply(destination, command: string; params: string = ''); procedure quit(reason: string = ''); function queue_whois(nick: string; remote: boolean; event: twhoisevent; timeout: integer): tirc_queue; function queue_userhost(nick: string; event: tuserhostevent; timeout: integer): tirc_queue; procedure queue_flush(eventtype: nqueue); procedure queue_delete(q: tirc_queue); function queue_count(eventtype: nqueue): integer; function queue_wait(q: tirc_queue; timeout: integer): nwaitresult; function format_mymodes: string; function format_chanmodes: string; function format_prefix: string; function format_usermodes: string; function format_isupportlist: string; function format_prefixmode(u: tirc_user): string; function format_prefixmodeall(u: tirc_user): string; function format_chanmodestring(c: tirc_channel): string; function get_isupport(key: string): string; function get_isupportdefined(key: string): boolean; function get_ircdversion: string; function is_connected: boolean; function is_registered: boolean; function is_ready: boolean; function is_onchannel(cname: string): boolean; function is_nickonchannel(channel: tirc_channel; nick: string): boolean; function is_umodeset(umode: string): boolean; procedure set_addchanmode(modechar: string; modetype: integer); procedure set_flushmodelist; procedure set_prefixlist(prefixchars: string; prefixsymbols: string); procedure set_usermodelist(newusermodes: string); procedure set_isupport(key, value: string); function find_channel(chan: string): tirc_channel; function find_nickonchannel(chan: tirc_channel; nick: string): tirc_user; procedure req_banlist(chan: string); // ------------------------------------------------------------------------- // Internal stuff // ------------------------------------------------------------------------- function validnick(nick: string): boolean; function lastword(s: string): string; procedure start_queuetimer; procedure stop_queuetimer; procedure handlewhois; procedure cleanchannels; procedure resetstate; procedure sendauth; procedure parse(msg: string); procedure parsecmd(nick, host: string; fromserver, prefix: boolean); procedure parse005(s: string); function new_channel: tirc_channel; procedure del_channel(chan: tirc_channel); function new_user(chan: tirc_channel): tirc_user; procedure del_user(c: tirc_channel; u: tirc_user); procedure flush_users(c: tirc_channel); procedure parse_modes(ischan: boolean; c: tirc_channel; base: integer; nick: string); constructor create; destructor destroy; override; end; // ----------------------------------------------------------------------------- // Non class functions/procedures // ----------------------------------------------------------------------------- function sockreason(error: integer): string; procedure splitnickhost(s: string; var s1, s2: string); function irclower(s: string): string; implementation // ----------------------------------------------------------------------------- // IRC RFC1459 version of lowercase() // ----------------------------------------------------------------------------- function irclower(s: string): string; var i: integer; begin //Because of IRC's scandanavian origin, the characters {}| are // considered to be the lower case equivalents of the characters []\, setlength(result, length(s)); for i := 1 to length(s) do if ircltable[ord(s[i])] <> 0 then result[i] := chr(ircltable[ord(s[i])]) else result[i] := s[i]; end; // ----------------------------------------------------------------------------- // Request the banlist for the channel named // ----------------------------------------------------------------------------- procedure tirc.req_banlist(chan: string); begin lineout('MODE ' + chan + ' +b'); end; // ----------------------------------------------------------------------------- // Return a channel mode string for <c>. // Example: result := 'Ccntlk 50 key' // ----------------------------------------------------------------------------- function tirc.format_chanmodestring(c: tirc_channel): string; var i, a: integer; s, s2: string; begin s := ''; s2 := ''; for i := 0 to 255 do begin if cmodetype[i] <> CLIST then begin a := cmodelookup[i]; if cmodetype[i] = CBOOL then begin if c.modes[a].boolval then s := s + chr(i); end; if (cmodetype[i] = CSET) or (cmodetype[i] = CSETUNSET) then begin if c.modes[a].strval <> '' then begin s := s + chr(i); s2 := s2 + c.modes[a].strval + ' '; end; end; end; end; result := trim(s + ' ' + s2); end; // ----------------------------------------------------------------------------- // Returns TRUE if the specified usermode is set // ----------------------------------------------------------------------------- function tirc.is_umodeset(umode: string): boolean; begin if length(umode) <> 1 then begin raise EBadModeChar.create('Bad is_umodeset umode param'); exit; end; result := mymodes[ord(umode[1])]; end; // ----------------------------------------------------------------------------- // Parse modes for a target (channel or self) // if <ischan> is true, the mode string has a channel as a target. Otherwise, // the target is the local user. // ----------------------------------------------------------------------------- procedure tirc.parse_modes(ischan: boolean; c: tirc_channel; base: integer; nick: string); var addmode: boolean; modestr: string; modechar: integer; a, i, n, cpos: integer; u: tirc_user; s: string; begin addmode := true; cpos := base; modestr := param[base]; if not ischan then begin // ------------------------------------------------------------------------- // Usermodes parsing // ------------------------------------------------------------------------- for i := 1 to length(modestr) do begin if (modestr[i] = '+') or (modestr[i] = '-') then begin if modestr[i] = '+' then addmode := true else addmode := false; end else begin // Only modify the mode if it exists a := pos(modestr[i], usermodes); if a <> 0 then mymodes[ord(modestr[i])] := addmode; end; end; end else begin // ------------------------------------------------------------------------- // Channel mode parsing // ------------------------------------------------------------------------- for i := 1 to length(modestr) do begin if (modestr[i] = '+') or (modestr[i] = '-') then begin if modestr[i] = '+' then addmode := true else addmode := false; end else begin modechar := ord(modestr[i]); // --------------------------------------------------------------------- // First, check for membership modes // These are most common so we will check them first // --------------------------------------------------------------------- a := mmodelookupm[modechar]; if a <> 0 then begin // ------------------------------------------------------------------- // Membership mode // ------------------------------------------------------------------- inc(cpos); if cpos > (params - 1) then exit; // bad mode string... s := param[cpos]; u := find_nickonchannel(c, s); if assigned(u) then begin if addmode then u.modes := u.modes or a else u.modes := u.modes and (not a); //end else exit; // bad user... end; // instead, be more fair - try to ignore this slip-up from the ircd. end else begin // ------------------------------------------------------------------- // Channel mode lookup. // ------------------------------------------------------------------- n := cmodetype[modechar]; if n <> CINVALID then begin a := cmodelookup[modechar]; // ----------------------------------------------------------------- // Process channel mode // ----------------------------------------------------------------- case n of CINVALID: begin if options.auto_cmode_add then begin // We will add it on the fly as a bool mode. set_addchanmode(chr(modechar), CBOOL); a := cmodelookup[modechar]; if assigned(onaddedboolmode) then onaddedboolmode(chr(modechar)); c.modes[a].boolval := addmode; end else begin // What do we do? :( // It would be added as a bool mode anyway, so, // we can try to ignore it. // NB@2 end; end; CLIST: begin inc(cpos); if cpos > (params - 1) then exit; if addmode then begin c.modes[a].list.Add(param[cpos]); c.modes[a].wholist.add(nick); c.modes[a].tslist.add(inttostr(unixtimeint)); end else begin n := c.modes[a].list.IndexOf(param[cpos]); if n <> -1 then begin c.modes[a].list.Delete(n); c.modes[a].wholist.delete(n); c.modes[a].tslist.delete(n); end; end; end; CSETUNSET: begin inc(cpos); if cpos > (params - 1) then exit; if addmode then begin c.modes[a].strval := param[cpos]; end else begin c.modes[a].strval := ''; end; end; CSET: begin if addmode then begin inc(cpos); if cpos > (params - 1) then exit; c.modes[a].strval := param[cpos]; end else begin c.modes[a].strval := ''; end; end; CBOOL: begin c.modes[a].boolval := addmode; end; end; end; end; end; end; end; end; // ----------------------------------------------------------------------------- // Return the prefix mode string for this user - only the highest mode // ----------------------------------------------------------------------------- function tirc.format_prefixmode(u: tirc_user): string; var i: integer; begin result := ''; for i := 1 to length(membermodel) do begin if (u.modes and mmodelookup[ord(membermodel[i])]) <> 0 then begin result := membermodel[i]; break; end; end; end; // ----------------------------------------------------------------------------- // Return the prefix mode string for this user, all modes // ----------------------------------------------------------------------------- function tirc.format_prefixmodeall(u: tirc_user): string; var i: integer; begin result := ''; for i := 1 to length(membermodel) do begin if (u.modes and mmodelookup[ord(membermodel[i])]) <> 0 then begin result := result + membermodel[i]; end; end; end; // ----------------------------------------------------------------------------- // Flush (remove) all users on this channel // ----------------------------------------------------------------------------- procedure tirc.flush_users(c: tirc_channel); var ptr, ptr2: tirc_user; begin ptr := c.user; while assigned(ptr) do begin ptr2 := ptr.ptr_next; ptr.Free; ptr := ptr2; end; c.user := nil; c.user_last := nil; c.usercount := 0; end; // ----------------------------------------------------------------------------- // Find <nick> on <chan> // ----------------------------------------------------------------------------- function tirc.find_nickonchannel(chan: tirc_channel; nick: string): tirc_user; var ptr: tirc_user; begin result := nil; ptr := chan.user; while assigned(ptr) do begin if irclower(nick) = irclower(ptr.nick) then begin result := ptr; break; end; ptr := ptr.ptr_next; end; end; // ----------------------------------------------------------------------------- // Add a new user to this channel // ----------------------------------------------------------------------------- function tirc.new_user(chan: tirc_channel): tirc_user; begin result := tirc_user.Create; if chan.usercount = 0 then begin // No users result.ptr_prev := nil; result.ptr_next := nil; chan.user := result; chan.user_last := result; end else begin // Add ours to the end result.ptr_prev := chan.user_last; result.ptr_next := nil; chan.user_last.ptr_next := result; chan.user_last := result; end; inc(chan.usercount); // Initialise with defaults result.nick := ''; result.host := ''; result.modes := 0; end; // ----------------------------------------------------------------------------- // Delete an existing user from this channel // ----------------------------------------------------------------------------- procedure tirc.del_user(c: tirc_channel; u: tirc_user); begin if assigned(u.ptr_prev) then u.ptr_prev.ptr_next := u.ptr_next; if assigned(u.ptr_next) then u.ptr_next.ptr_prev := u.ptr_prev; if not assigned(u.ptr_prev) then c.user := u.ptr_next; if not assigned(u.ptr_next) then c.user_last := u.ptr_prev; u.free; dec(c.usercount); end; // ----------------------------------------------------------------------------- // Is the user on the channel? // ----------------------------------------------------------------------------- function tirc.is_nickonchannel(channel: tirc_channel; nick: string): boolean; var ptr: tirc_user; begin result := false; ptr := channel.user; while assigned(ptr) do begin if irclower(nick) = irclower(ptr.nick) then begin result := true; break; end; ptr := ptr.ptr_next; end; end; // ----------------------------------------------------------------------------- // Find the channel given. If it is not found, nil is returned. // ----------------------------------------------------------------------------- function tirc.find_channel(chan: string): tirc_channel; var ptr: tirc_channel; begin result := nil; //if channelcount = 0 then exit; ptr := channel; while assigned(ptr) do begin if lowercase(chan) = lowercase(ptr.name) then begin result := ptr; break; end; ptr := ptr.ptr_next; end; end; // ----------------------------------------------------------------------------- // Remove a channel from the linked list // ----------------------------------------------------------------------------- procedure tirc.del_channel(chan: tirc_channel); var uptr, uptrnext: tirc_user; i: integer; begin if assigned(chan.ptr_prev) then chan.ptr_prev.ptr_next := chan.ptr_next; if assigned(chan.ptr_next) then chan.ptr_next.ptr_prev := chan.ptr_prev; if not assigned(chan.ptr_prev) then channel := chan.ptr_next; if not assigned(chan.ptr_next) then channel_last := chan.ptr_prev; // Clean up memory structures used by the channel // Clean users //if chan.usercount <> 0 then begin uptr := chan.user; while assigned(uptr) do begin uptrnext := uptr.ptr_next; uptr.free; uptr := uptrnext; end; //end; // Clean mode lists for i := low(chan.modes) to high(chan.modes) do begin // List modes must be cleaned up if cmodelist[i] then begin chan.modes[i].list.Free; chan.modes[i].tslist.Free; chan.modes[i].wholist.free; end; end; setlength(chan.modes, 0); chan.free; dec(channelcount); end; // ----------------------------------------------------------------------------- // Add a new channel to the linked list and return a pointer to it // ----------------------------------------------------------------------------- function tirc.new_channel: tirc_channel; var i: integer; begin result := tirc_channel.create; if channelcount = 0 then begin // No channels at all! result.ptr_prev := nil; result.ptr_next := nil; channel := result; channel_last := channel; end else begin // add ours to the end of the list result.ptr_prev := channel_last; result.ptr_next := nil; channel_last.ptr_next := result; channel_last := result; end; inc(channelcount); // We must allocate the modes list and create stringlists for any listmodes // that are in use. setlength(result.modes, numcmode); for i := 0 to (numcmode - 1) do begin result.modes[i].boolval := false; result.modes[i].strval := ''; result.modes[i].trustable := false; if cmodelist[i] then begin result.modes[i].list := tstringlist.Create; result.modes[i].list.CaseSensitive := false; result.modes[i].wholist := tstringlist.Create; result.modes[i].wholist.CaseSensitive := false; result.modes[i].tslist := tstringlist.Create; result.modes[i].tslist.CaseSensitive := false; end; end; // Initialise with defaults result.expecting_users := true; result.name := ''; result.topic := ''; result.topicnick := ''; result.topichost := ''; result.topicts := 0; result.createdts := 0; result.usercount := 0; result.sync := false; result.syncfull := false; result.syncwho := false; end; // ----------------------------------------------------------------------------- // Returns TRUE if we are on the channel specified. Non case sensitive. // ----------------------------------------------------------------------------- function tirc.is_onchannel(cname: string): boolean; var ptr: tirc_channel; begin result := false; //if channelcount = 0 then exit; ptr := channel; while assigned(ptr) do begin if lowercase(cname) = lowercase(ptr.name) then begin result := true; break; end; ptr := ptr.ptr_next; end; end; // ----------------------------------------------------------------------------- // Return the IRCD software name and version, if known // ----------------------------------------------------------------------------- function tirc.get_ircdversion: string; begin result := serverircd; end; // ----------------------------------------------------------------------------- // Returns TRUE if the socket is connected, FALSE otherwise. // ----------------------------------------------------------------------------- function tirc.is_connected: boolean; begin result := connected; end; // ----------------------------------------------------------------------------- // Returns TRUE if we have registered and can send commands. // ----------------------------------------------------------------------------- function tirc.is_registered: boolean; begin result := got001; end; // ----------------------------------------------------------------------------- // Returns TRUE if the connection is ready (stable, know chanmodes, etc) // ----------------------------------------------------------------------------- function tirc.is_ready: boolean; begin result := not notready; end; // ----------------------------------------------------------------------------- // gracefully quit (with optional quit reason) // ----------------------------------------------------------------------------- procedure tirc.quit(reason: string = ''); begin if reason <> '' then lineout('QUIT :' + reason) else lineout('QUIT'); end; // ----------------------------------------------------------------------------- // search the isupport table to see if <key> is defined. Returns TRUE if it is // defined, otherwise false. // ----------------------------------------------------------------------------- function tirc.get_isupportdefined(key: string): boolean; var i: integer; begin result := false; for i := 0 to (isupport_key.Count - 1) do if uppercase(key) = isupport_key.strings[i] then begin result := true; break; end; end; // ----------------------------------------------------------------------------- // Search the isupport table for the key (non case sensitive) and return its val // if it is defined - else return nothing. // Warning: If a key is simply defined with no data, the return value is STILL // nothing. To cater for this, use get_isupportdefined to check if a key exists. // ----------------------------------------------------------------------------- function tirc.get_isupport(key: string): string; var i: integer; begin result := ''; for i := 0 to (isupport_key.Count - 1) do if uppercase(key) = isupport_key.strings[i] then begin result := isupport_value.strings[i]; break; end; end; // ----------------------------------------------------------------------------- // Return a list of keys in the isupport table. // ----------------------------------------------------------------------------- function tirc.format_isupportlist: string; var i: integer; begin result := ''; for i := 0 to (isupport_key.count - 1) do result := result + isupport_key.strings[i] + ' '; result := trim(result); end; // ----------------------------------------------------------------------------- // Add the specified pair to the ISUPPORT table. Replaces entries that already // exist. Case insensitive - uppercase forced. Updates state if required // (for example, chanmodes) // ----------------------------------------------------------------------------- procedure tirc.set_isupport(key, value: string); var s, c, mlist: string; i, ptr: integer; begin {$ifdef debug} lastcall := 'tirc.set_isupport'; lastcall_info := key + '=' + value; {$endif} s := uppercase(key); ptr := -1; for i := 0 to (isupport_key.Count - 1) do begin if isupport_key.Strings[i] = s then begin ptr := i; break; end; end; if ptr = -1 then begin // Not in list. isupport_key.add(s); isupport_value.add(value); end else begin; // In list, replace existing isupport_key.strings[ptr] := s; isupport_value.strings[ptr] := value; end; // We might need to act on the s. // --------------------------------------------------------------------------- // PREFIX=(ov)@+ // --------------------------------------------------------------------------- if s = 'PREFIX' then begin if length(value) < 4 then begin if assigned(onwarning) then onwarning('set_isupport: bad PREFIX'); exit; end; if value[1] <> '(' then begin if assigned(onwarning) then onwarning('set_isupport: bad PREFIX'); exit; end; i := pos(')', s); if (i > (length(s) - 1)) or (i < 3) then begin if assigned(onwarning) then onwarning('set_isupport: bad PREFIX'); exit; end; set_prefixlist(copy(s, 2, i - 2), copy(s, i + 1, length(s) - i)); end; // --------------------------------------------------------------------------- // CHANMODES=list,setunset,set,bool // --------------------------------------------------------------------------- if s = 'CHANMODES' then begin if length(value) < 3 then begin if assigned(onwarning) then onwarning('set_isupport: bad CHANMODES'); exit; end; c := value; set_flushmodelist; // -------------------- // list modes // -------------------- i := pos(',', c); if i = 0 then begin raise ELostState.create('channel mode table not generated properly - premature end-of-chanmodes'); exit; end; if i = 1 then begin mlist := ''; if length(c) > 1 then c := copy(c, 2, length(c) - 1) else c := ''; end else begin mlist := copy(c, 1, i - 1); if length(c) > (1 + length(mlist)) then c := copy(c, 2 + length(mlist), length(c) - 1) else c := ''; end; for i := 1 to length(mlist) do set_addchanmode(mlist[i], CLIST); // -------------------- // setunset modes // -------------------- i := pos(',', c); if i = 0 then begin raise ELostState.create('channel mode table not generated properly - premature end-of-chanmodes'); exit; end; if i = 1 then begin mlist := ''; if length(c) > 1 then c := copy(c, 2, length(c) - 1) else c := ''; end else begin mlist := copy(c, 1, i - 1); if length(c) > (1 + length(mlist)) then c := copy(c, 2 + length(mlist), length(c) - 1) else c := ''; end; for i := 1 to length(mlist) do set_addchanmode(mlist[i], CSETUNSET); // -------------------- // set modes // -------------------- i := pos(',', c); if i = 0 then begin raise ELostState.create('channel mode table not generated properly - premature end-of-chanmodes'); exit; end; if i = 1 then begin mlist := ''; if length(c) > 1 then c := copy(c, 2, length(c) - 1) else c := ''; end else begin mlist := copy(c, 1, i - 1); if length(c) > (1 + length(mlist)) then c := copy(c, 2 + length(mlist), length(c) - 1) else c := ''; end; for i := 1 to length(mlist) do set_addchanmode(mlist[i], CSET); // -------------------- // bool modes // -------------------- if c <> '' then begin mlist := c; for i := 1 to length(mlist) do set_addchanmode(mlist[i], CBOOL); end; end; end; // ----------------------------------------------------------------------------- // Parse a key=value string (stripped from 005) and update state information // and the ISUPPORT list. // ----------------------------------------------------------------------------- procedure tirc.parse005(s: string); var i: integer; begin {$ifdef debug} lastcall := 'tirc.parse005'; lastcall_info := s; {$endif} i := pos('=', s); if i = 0 then begin // No value set_isupport(s, ''); end else begin if (i < 2) or (i > length(s) - 1) then begin if assigned(onwarning) then onwarning('parse005: bad key'); exit; end; set_isupport(copy(s, 1, i - 1), copy(s, i + 1, length(s) - i)); end; end; // ----------------------------------------------------------------------------- // Flush the channel mode list // ----------------------------------------------------------------------------- procedure tirc.set_flushmodelist; var i: integer; begin {$ifdef debug} lastcall := 'tirc.set_flushmodelist'; lastcall_info := ''; {$endif} // Clear mode lookup table for i := 0 to 255 do cmodetype[i] := CINVALID; numcmode := 0; setlength(cmodelist, 0); end; // ----------------------------------------------------------------------------- // Return a formatted string listing the user modes we currently have set. // "iwso" // ----------------------------------------------------------------------------- function tirc.format_mymodes: string; var i: integer; begin {$ifdef debug} lastcall := 'tirc.format_mymodes'; lastcall_info := ''; {$endif} result := ''; for i := 1 to length(usermodes) do begin if mymodes[ord(usermodes[i])] then result := result + usermodes[i]; end; end; // ----------------------------------------------------------------------------- // Return a formatted string listing the supported channel modes (005) // "b,k,l,nm" // ----------------------------------------------------------------------------- function tirc.format_chanmodes: string; var i: integer; begin {$ifdef debug} lastcall := 'tirc.format_chanmodes'; lastcall_info := ''; {$endif} result := ''; for i := 0 to 255 do begin if cmodetype[i] = CLIST then result := result + chr(i); end; result := result + ','; for i := 0 to 255 do begin if cmodetype[i] = CSETUNSET then result := result + chr(i); end; result := result + ','; for i := 0 to 255 do begin if cmodetype[i] = CSET then result := result + chr(i); end; result := result + ','; for i := 0 to 255 do begin if cmodetype[i] = CBOOL then result := result + chr(i); end; end; // ----------------------------------------------------------------------------- // Return a formatted string listing the allowed prefixes. // "(ov)@+" // ----------------------------------------------------------------------------- function tirc.format_prefix: string; begin {$ifdef debug} lastcall := 'tirc.format_prefix'; lastcall_info := ''; {$endif} result := '(' + membermodes + ')' + membermodel; end; // ----------------------------------------------------------------------------- // Return a formatted string listing allowed usermodes. // "iwso" // ----------------------------------------------------------------------------- function tirc.format_usermodes: string; begin {$ifdef debug} lastcall := 'tirc.format_usermodes'; lastcall_info := ''; {$endif} result := usermodes; end; // ----------------------------------------------------------------------------- // Send a privmsg to a target (channel or user) // ----------------------------------------------------------------------------- procedure tirc.privmsg(destination, msg: string); begin {$ifdef debug} lastcall := 'tirc.privmsg'; lastcall_info := destination + ' "' + msg + '"'; {$endif} lineout('PRIVMSG ' + destination + ' :' + msg); end; // ----------------------------------------------------------------------------- // Add a channel mode to the channelmode cache list. If you are going to use // this, please be very careful. It will resize any channelmode arrays for // channels you are already on. This procedure can be used to manually "hack" // modes into the parser if the IRCD makes up non-boolean chanmodes on the fly // (uses modes without specifying them in ISUPPORT). Hence, you can support // broken IRCDs using this. // NOTE: boolean chanmodes on-the-fly are automatically added. Don't do it // yourself unless you must. // NOTE: listmodes that are added after channels exist will AV the parser. This // could be fixed, but it involves expensive reverse lookups, so for now I wont // do it. It is not needed anyway. // ----------------------------------------------------------------------------- procedure tirc.set_addchanmode(modechar: string; modetype: integer); var ptr: tirc_channel; begin {$ifdef debug} lastcall := 'tirc.set_addchanmode'; lastcall_info := ''; {$endif} // Check support booleans. if (modechar = 'b') and (modetype = CLIST) then supports_bans := true; if (modechar = 'e') and (modetype = CLIST) then supports_excepts := true; if (modechar = 'I') and (modetype = CLIST) then supports_invites := true; cmodelookup[ord(modechar[1])] := numcmode; cmodetype[ord(modechar[1])] := modetype; inc(numcmode); setlength(cmodelist, numcmode); if modetype = CLIST then cmodelist[numcmode - 1] := true else cmodelist[numcmode - 1] := false; // If we are on any channels we need to resize things... if channelcount <> 0 then begin // Walk the linked list ptr := channel; repeat setlength(ptr.modes, numcmode); ptr := ptr.ptr_next; until not assigned(ptr); end; end; // ----------------------------------------------------------------------------- // Rewrite the default or obtained (ISUPPORT) prefix list (member mode) list // with your own modes, for supporting broken IRCDs. Example: // set_prefixlist('ohv', '@%+'); // Modes are listed in the priority order. // CAUTION: This function does not reorder the bitfield! If you change the order // of modes or insert modes in the middle, you will corrupt the internal state. // ----------------------------------------------------------------------------- procedure tirc.set_prefixlist(prefixchars: string; prefixsymbols: string); var i: integer; begin {$ifdef debug} lastcall := 'tirc.set_prefixlist'; lastcall_info := ''; {$endif} membermodes := prefixchars; membermodel := prefixsymbols; for i := 0 to 255 do mmodelookup[i] := 0; for i := 1 to length(prefixchars) do mmodelookup[ord(prefixsymbols[i])] := bf_bit[i - 1]; for i := 0 to 255 do mmodelookupm[i] := 0; for i := 1 to length(prefixchars) do mmodelookupm[ord(prefixchars[i])] := bf_bit[i - 1]; end; // ----------------------------------------------------------------------------- // Rewrite the user mode list with your own list for supporting broken IRCDs. // CAUTION: This function does not reorder the bitfield! If you change the order // of modes or insert modes in the middle, you will corrupt the internal state. // ----------------------------------------------------------------------------- procedure tirc.set_usermodelist(newusermodes: string); begin {$ifdef debug} lastcall := 'tirc.set_usermodelist'; lastcall_info := ''; {$endif} usermodes := newusermodes; end; // ----------------------------------------------------------------------------- // Get rid of all channels (and users) // ----------------------------------------------------------------------------- procedure tirc.cleanchannels; var ptr, ptrnext: tirc_channel; uptr, uptrnext: tirc_user; i: integer; begin {$ifdef debug} lastcall := 'tirc.cleanchannels'; lastcall_info := ''; {$endif} //if channelcount = 0 then exit; ptr := channel; while assigned(ptr) do begin // remove users in the channel if ptr.usercount <> 0 then begin // need to remove users uptr := ptr.user; repeat uptrnext := uptr.ptr_next; uptr.free; uptr := uptrnext; until not assigned(uptr); // done end; // clean mode lists for i := low(ptr.modes) to high(ptr.modes) do begin if assigned(ptr.modes[i].list) then ptr.modes[i].list.Free; end; setlength(ptr.modes, 0); // get next channel and kill old one ptrnext := ptr.ptr_next; ptr.Free; ptr := ptrnext; end; channelcount := 0; // done end; // ----------------------------------------------------------------------------- // Join a channel or channels (#chan,#chan) // ----------------------------------------------------------------------------- procedure tirc.joinchannel(channel: string; key: string = ''); begin {$ifdef debug} lastcall := 'tirc.joinchannel'; lastcall_info := channel; {$endif} if key = '' then lineout('JOIN ' + channel) else lineout('JOIN ' + channel + ' ' + key); end; // ----------------------------------------------------------------------------- // Part a channel or channels // ----------------------------------------------------------------------------- procedure tirc.partchannel(channel: string; reason: string = ''); begin {$ifdef debug} lastcall := 'tirc.partchannel'; lastcall_info := channel; {$endif} if reason <> '' then lineout('PART ' + channel + ' :' + reason) else lineout('PART ' + channel); end; // ----------------------------------------------------------------------------- // change nick // ----------------------------------------------------------------------------- procedure tirc.changenick(newnick: string); begin {$ifdef debug} lastcall := 'tirc.newnick'; lastcall_info := newnick; {$endif} lineout('NICK ' + newnick); end; // ----------------------------------------------------------------------------- // return the last word in a string // ----------------------------------------------------------------------------- function tirc.lastword(s: string): string; var i: integer; begin {$ifdef debug} lastcall := 'tirc.lastword'; lastcall_info := s; {$endif} result := s; for i := length(s) downto 1 do begin if s[i] = #32 then begin result := copy(s, i + 1, length(s) - i); exit; end; end; end; // ----------------------------------------------------------------------------- // irc parser core // ----------------------------------------------------------------------------- procedure tirc.parsecmd(nick, host: string; fromserver, prefix: boolean); var base: integer; cmd: string; s, s1, s2, s3, s4, s5: string; i, a, n: integer; b: boolean; tchan: tirc_channel; tuser: tirc_user; q, q2: tirc_queue; begin {$ifdef debug} lastcall := 'tirc.parsecmd'; if fromserver then lastcall_info := 'server' else lastcall_info := 'client,' + nick + '!' + host; {$endif} if prefix then base := 1 else base := 0; if base > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: illegal line'); exit; end; cmd := uppercase(param[base]); // --------------------------------------------------------------------------- // Pings // --------------------------------------------------------------------------- if cmd = 'PING' then begin if fromserver then begin if (base + 1) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad PING'); exit; end; lineout('PONG :' + param[base + 1]); exit; end; end; // --------------------------------------------------------------------------- // Looking for the "fully registered" state - that is, a state when we can // assume that isupport is pretty much ready by now. Look for end of motd, // motd missing, and 251. // --------------------------------------------------------------------------- if ((cmd = '376') or (cmd = '251') or (cmd = '422')) and notready then begin notready := false; if assigned(onready) then onready; //exit; // need to fall through end; // --------------------------------------------------------------------------- // 004: An earlier ISUPPORT // :hinata.zipplet.co.uk 004 Zipplet hinata.zipplet.co.uk u2.10.11.07+asuka(1.2.1) dioswkgxXInR biklmnopstvrDcCNu bklov // --------------------------------------------------------------------------- if cmd = '004' then begin if (base + 5) > (params - 1) then begin // 6, but we only need 5 if assigned(onwarning) then onwarning('tirc.parsecmd: bad 004'); exit; end; set_usermodelist(param[base + 4]); // also set the server hostname serverhost := param[base + 2]; serverircd := param[base + 3]; exit; end; // --------------------------------------------------------------------------- // 005: ISUPPORT // :hinata.zipplet.co.uk 005 Zipplet WHOX WALLCHOPS WALLVOICES USERIP CPRIVMSG CNOTICE // --------------------------------------------------------------------------- if cmd = '005' then begin if (base + 2) > (params - 2) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 005'); exit; end; for i := base + 2 to (params - 2) do parse005(param[i]); got005 := true; exit; end; // --------------------------------------------------------------------------- // 001: registered // --------------------------------------------------------------------------- if cmd = '001' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 001'); exit; end; got001 := true; // some ircds (join me) send "nick!ident@host" at the end of the string, // so we get the nickname from the target instead. //s := lastword(param[base + 2]); s := param[base + 1]; if lowercase(s) <> lowercase(nickname) then begin nickname := s; if assigned(onmynickchange) then onmynickchange(nickname); end; if assigned(onauthed) then onauthed; exit; end; // --------------------------------------------------------------------------- // 433: nickname already in use // --------------------------------------------------------------------------- if cmd = '433' then begin if assigned(onnickinuse) then onnickinuse; exit; end; // --------------------------------------------------------------------------- // 464: password incorrect // --------------------------------------------------------------------------- if cmd = '464' then begin if assigned(onpasswordincorrect) then onpasswordincorrect; exit; end; // --------------------------------------------------------------------------- // PRIVMSG // --------------------------------------------------------------------------- if cmd = 'PRIVMSG' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad privmsg'); exit; end; if lowercase(param[base + 1]) <> lowercase(nickname) then begin // Check if its a CTCP. //onctcp: procedure(target, command, params, nick, host: string) of object; //onctcpme: procedure(target, command, params, nick, host: string) of object; if length(param[base + 2]) > 2 then begin if (param[base + 2][1] = chr(1)) and (param[base + 2][length(param[base + 2])] = chr(1)) then begin // It is a CTCP. s := copy(param[base + 2], 2, length(param[base + 2]) - 2); i := pos(' ', s); if (i > 1) and (i < length(s)) then begin s1 := copy(s, 1, i - 1); s2 := copy(s, i + 1, length(s) - i); end else begin s1 := s; s2 := ''; end; if options.action_onaction and (s1 = 'ACTION') then begin if assigned(onaction) then onaction(param[base + 1], s2, nick, host); end else begin if assigned(onctcp) then onctcp(param[base + 1], s1, s2, nick, host); end; end else begin // Can't be a CTCP if assigned(onprivmsg) then onprivmsg(param[base + 1], param[base + 2], nick, host); end; end else begin // Can't be a CTCP if assigned(onprivmsg) then onprivmsg(param[base + 1], param[base + 2], nick, host); end; end else begin if length(param[base + 2]) > 2 then begin if (param[base + 2][1] = chr(1)) and (param[base + 2][length(param[base + 2])] = chr(1)) then begin // It is a CTCP. s := copy(param[base + 2], 2, length(param[base + 2]) - 2); i := pos(' ', s); if (i > 1) and (i < length(s)) then begin s1 := copy(s, 1, i - 1); s2 := copy(s, i + 1, length(s) - i); end else begin s1 := s; s2 := ''; end; if options.action_onaction and (s1 = 'ACTION') then begin if assigned(onactionme) then onaction(param[base + 1], s2, nick, host); end else begin if assigned(onctcpme) then onctcpme(param[base + 1], s1, s2, nick, host); end; end else begin // Can't be a CTCP if assigned(onprivmsgme) then onprivmsgme(param[base + 1], param[base + 2], nick, host); end; end else begin // Can't be a CTCP if assigned(onprivmsgme) then onprivmsgme(param[base + 1], param[base + 2], nick, host); end; end; exit; end; // --------------------------------------------------------------------------- // JOIN // --------------------------------------------------------------------------- if cmd = 'JOIN' then begin if (base + 1) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad join'); exit; end; if not fromserver then begin i := 1; s1 := param[base + 1]; while strtok(s1, ',', i, false, s2) do begin // For every channel, process a join // Is this us (me?) if lowercase(nick) = lowercase(nickname) then begin // Yes, check if we are already on the channel (for broken IRCDs like // join me, which send TWO!) if not is_onchannel(s2) then begin // Add the channel - no users initially... tchan := new_channel; tchan.name := s2; // Also send a modes request lineout('MODE ' + s2); if options.who_on_join then lineout('WHO ' + s2); // Raise the join event if assigned(onmejoin) then onmejoin(tchan); exit; end else begin if assigned(onwarning) then onwarning('tirc.parsecmd: join: already on ' + s2); exit; end; end else begin // we are not on it, its someone joining a channel we are in tchan := find_channel(s2); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: join for user on channel we are not on'); exit; end; if is_nickonchannel(tchan, nick) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: join for user already on channel'); end else begin tuser := new_user(tchan); tuser.nick := nick; tuser.host := host; if assigned(onjoin) then onjoin(tchan, tuser); end; exit; end; end; end else begin // Joins are not allowed to be from servers! if assigned(onwarning) then onwarning('tirc.parsecmd: bad join'); exit; end; exit; end; // --------------------------------------------------------------------------- // NAMES - add names // --------------------------------------------------------------------------- if cmd = '353' then begin if (base + 4) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad names 353'); exit; end; tchan := find_channel(param[base + 3]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 353 for nonexistant channel'); exit; end; if tchan.expecting_users then begin // Yep we were able to take a new names list, so wipe the current flush_users(tchan); end; i := 1; s1 := param[base + 4]; while strtok(s1, ' ', i, false, s2) do begin // s2 is the nick // We need to parse the prefix chars and add them to the modelist. b := false; for a := 1 to length(s2) do begin if mmodelookup[ord(s2[a])] = 0 then begin b := true; break; end; end; if b then begin {$ifdef safenames} if not is_nickonchannel(tchan, s2) then begin {$endif} tuser := new_user(tchan); tuser.nick := copy(s2, a, length(s2) - a + 1); tuser.host := ''; tuser.modes := 0; // Assign modes! for n := 1 to a - 1 do begin tuser.modes := tuser.modes or mmodelookup[ord(s2[n])]; end; {$ifdef safenames} end; {$endif} end else begin if assigned(onwarning) then onwarning('tirc.parsecmd: 353: badnick'); end; end; // Done! tchan.expecting_users := false; exit; end; // --------------------------------------------------------------------------- // Names - end of names // first onjoinsync // --------------------------------------------------------------------------- if cmd = '366' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad names 366'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 366 for nonexistant channel'); exit; end; tchan.expecting_users := true; if not tchan.sync then begin tchan.sync := true; if assigned(onjoinsync) then onjoinsync(tchan); end; exit; end; // --------------------------------------------------------------------------- // 329 - channel created TS + fully synced // --------------------------------------------------------------------------- if cmd = '329' then begin if (base + 3) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 329'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 329 for nonexistant channel'); exit; end; try tchan.createdts := strtoint(param[base + 3]); except on e: exception do begin if assigned(onwarning) then onwarning('tirc.parsecmd: 329: timestamp not an int'); exit; end; end; // Fully synced. if not tchan.syncfull then begin tchan.syncfull := true; if assigned(onjoinsyncfull) then onjoinsyncfull(tchan); end; exit; end; // --------------------------------------------------------------------------- // KICK - kicked from a channel // --------------------------------------------------------------------------- if cmd = 'KICK' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad kick'); exit; end; if (base + 3) <= (params - 1) then s := param[base + 3] else s := ''; if lowercase(param[base + 2]) = lowercase(nickname) then begin // We were kicked... tchan := find_channel(param[base + 1]); if assigned(tchan) then begin s2 := tchan.name; del_channel(tchan); if assigned(onmekick) then onmekick(s2, nick, host, s); end else begin // Kick for a channel we are not on if assigned(onwarning) then onwarning('tirc.parsecmd: bad kick for a channel we are not on'); exit; end; end else begin // Not us, someone else tchan := find_channel(param[base + 1]); if assigned(tchan) then begin tuser := find_nickonchannel(tchan, param[base + 2]); if assigned(tuser) then begin del_user(tchan, tuser); if assigned(onkick) then onkick(tchan, param[base + 2], nick, host, s); end; exit; end else begin // Kick for a channel we are not on if assigned(onwarning) then onwarning('tirc.parsecmd: bad kick for a channel we are not on'); exit; end; end; exit; end; // --------------------------------------------------------------------------- // PART - parting a channel // --------------------------------------------------------------------------- if cmd = 'PART' then begin if (base + 1) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad part'); exit; end; if not fromserver then begin // Setting part reason if (base + 2) <= (params - 1) then s2 := param[base + 2] else s2 := ''; i := 1; s := param[base + 1]; while strtok(s, ',', i, false, s1) do begin // Is it us? if lowercase(nick) = lowercase(nickname) then begin // Yea, us tchan := find_channel(s1); if assigned(tchan) then begin // Remove us from this channel s3 := tchan.name; del_channel(tchan); if assigned(onmepart) then onmepart(s3); end; end else begin // No, someone else // Remove them from this channel if they are on it tchan := find_channel(s1); if assigned(tchan) then begin tuser := find_nickonchannel(tchan, nick); if assigned(tuser) then begin s4 := tuser.nick; s5 := tuser.host; del_user(tchan, tuser); if assigned(onpart) then onpart(tchan, s4, s5, s2); end; end; end; end; end else begin // parts are not allowed to be from servers! if assigned(onwarning) then onwarning('tirc.parsecmd: bad part'); exit; end; exit; end; // --------------------------------------------------------------------------- // QUIT - leaving the IRC network // --------------------------------------------------------------------------- if cmd = 'QUIT' then begin if (base + 1) <= (params - 1) then s := param[base + 1] else s := ''; // We need to make sure any channels of ours the user is on - is removed. tchan := channel; if assigned(tchan) then begin repeat tuser := find_nickonchannel(tchan, nick); if assigned(tuser) then del_user(tchan, tuser); if assigned(onquitchan) then onquitchan(nick, host, s, tchan); tchan := tchan.ptr_next; until not assigned(tchan); end; if assigned(onquit) then onquit(nick, host, s); exit; end; // --------------------------------------------------------------------------- // NOTICE // --------------------------------------------------------------------------- if cmd = 'NOTICE' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad notice'); exit; end; if not fromserver then begin if lowercase(param[base + 1]) <> lowercase(nickname) then begin if assigned(onnotice) then onprivmsg(param[base + 1], param[base + 2], nick, host); end else begin if assigned(onnoticeme) then onprivmsgme(param[base + 1], param[base + 2], nick, host); end; end; exit; end; // --------------------------------------------------------------------------- // 324 - channel modes // --------------------------------------------------------------------------- if cmd = '324' then begin if (base + 3) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 324'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 324 for nonexistant channel'); exit; end; parse_modes(true, tchan, base + 3, nick); exit; end; // --------------------------------------------------------------------------- // MODE changes // --------------------------------------------------------------------------- if cmd = 'MODE' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad mode'); exit; end; if lowercase(param[base + 1]) = lowercase(nickname) then begin // Usermodes parse_modes(false, nil, base + 2, nick); end else begin // Chanmodes tchan := find_channel(param[base + 1]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: mode for nonexistant channel'); exit; end; parse_modes(true, tchan, base + 2, nick); end; exit; end; // --------------------------------------------------------------------------- // 367 - ban list - adding a ban // 367 nick channel banmask bywho timestamp // --------------------------------------------------------------------------- if cmd = INUM_BAN_ITEM then begin if not supports_bans then exit; if (base + 5) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 367'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 367 for nonexistant channel'); exit; end; i := cmodelookup[ord('b')]; if not tchan.modes[i].boolval then begin tchan.modes[i].list.Clear; tchan.modes[i].wholist.Clear; tchan.modes[i].tslist.Clear; tchan.modes[i].trustable := false; end; tchan.modes[i].list.Add(param[base + 3]); tchan.modes[i].wholist.Add(param[base + 4]); tchan.modes[i].tslist.Add(param[base + 5]); tchan.modes[i].boolval := true; exit; end; // --------------------------------------------------------------------------- // 368 - end of ban list // --------------------------------------------------------------------------- if cmd = INUM_BAN_END then begin if not supports_bans then exit; if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 368'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 368 for nonexistant channel'); exit; end; i := cmodelookup[ord('b')]; tchan.modes[i].boolval := false; tchan.modes[i].trustable := true; if assigned(onlistban) then onlistban(tchan); exit; end; // --------------------------------------------------------------------------- // 332 - topic // --------------------------------------------------------------------------- if cmd = '332' then begin //for i := base to (params - 1) do // lineout('privmsg #anders :[' + inttostr(i) + '] ' + param[i]); if (base + 3) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 332'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 332 for nonexistant channel'); exit; end; tchan.topic := param[base + 3]; exit; end; // --------------------------------------------------------------------------- // 333 - topic info // --------------------------------------------------------------------------- if cmd = '333' then begin //for i := base to (params - 1) do // lineout('privmsg #anders :[' + inttostr(i) + '] ' + param[i]); if (base + 4) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 333'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 333 for nonexistant channel'); exit; end; splitnickhost(param[base + 3], s1, s2); tchan.topicnick := s1; tchan.topichost := s2; try tchan.topicts := strtoint(param[base + 4]); except tchan.topicts := 0; if assigned(onwarning) then onwarning('tirc.parsecmd: 333: bad topic time'); end; exit; end; // --------------------------------------------------------------------------- // TOPIC - handle topic change. // --------------------------------------------------------------------------- if cmd = 'TOPIC' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad topic'); exit; end; tchan := find_channel(param[base + 1]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: topic for nonexistant channel'); exit; end; tchan.topic := param[base + 2]; tchan.topicnick := nick; tchan.topichost := host; tchan.topicts := unixtimeint; exit; end; // --------------------------------------------------------------------------- // End of WHO list // --------------------------------------------------------------------------- if cmd = '315' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 315'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 315 for nonexistant channel'); exit; end; if (options.onwho_always) or (not tchan.syncwho) then begin if assigned(onwho) then onwho(tchan); end; tchan.syncwho := true; exit; end; // --------------------------------------------------------------------------- // Standard WHO reply //<- :irc.shockerz.net 352 Zipplet #animewonder ~bot bot.animewonder * AnimeWonder H@ :0 AnimeWonder bot // --------------------------------------------------------------------------- if cmd = '352' then begin if (base + 8) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 352'); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 352 for nonexistant channel'); exit; end; //<- :chii.CodersIRC.org 352 Zipplet #anders ~anders malmo-65-215.skbbip.com chii.CodersIRC.org Anders H@w :0 Anders Bergh //<- :chii.CodersIRC.org 352 Zipplet #anders zipplet loves.himeko chii.CodersIRC.org Zipplet H*@iwsgx :0 http://www.zipplet.co.uk/ // 352 self channel ident host server nick flags hops+realname // 0 1 2 3 4 5 6 7 8 tuser := find_nickonchannel(tchan, param[base + 6]); if not assigned(tuser) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: 352 for nonexistant nick'); exit; end; // Save host and server name tuser.host := param[base + 3] + '@' + param[base + 4]; tuser.server := param[base + 5]; // Set fullname s := param[params - 1]; i := pos(' ', s); if (i > 1) and (i < length(s)) then begin tuser.fullname := copy(s, i + 1, length(s) - i); end; // Set H (Here) or G (Gone) if param[base + 7][1] = 'H' then tuser.away := false else tuser.away := true; // Check for operator (will always be second char if so) if length(param[base + 7]) >= 2 then begin if param[base + 7][2] = '*' then tuser.ircop := false else tuser.ircop := true; end else tuser.ircop := false; exit; end; // --------------------------------------------------------------------------- // USERHOST reply //<- :chii.CodersIRC.org 302 Zipplet :Anders=+anders@loves.chikane // --------------------------------------------------------------------------- if cmd = '302' then begin if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 302'); exit; end; if param[base + 2] = '' then begin // Failed lookup. // Currently there isn't much we can do as the name isnt returned.. exit; end; i := pos('=', param[base + 2]); {if not ((i > 1) and (i < length(param[base + 2]))) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 302'); exit; end;} if not ((i > 1) and ((i + 1) < length(param[base + 2]))) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 302'); exit; end; s := copy(param[base + 2], 1, i - 1); s2 := copy(param[base + 2], i + 2, length(param[base + 2]) - 2); //s2 := copy(param[base + 2], i + 1, length(param[base + 2]) - 1); {if s2[1] = '+' then begin if length(s2) = 1 then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 302'); exit; end else begin s2 := copy(s2, 2, length(s2) - 1); end; end;} if s[length(s)] = '*' then begin if length(s) = 1 then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 302'); exit; end else begin s := copy(s, 1, length(s) - 1); end; end; // Search for a queue object with this in it q := queue; while assigned(q) do begin q2 := q.ptr_next; if q.itemtype = nq_userhost then begin if irclower(tirc_queueuserhost(q).nick) = irclower(s) then begin tirc_queueuserhost(q).notify(s, s2, false); if q.waiting then begin q.destroying := true; q.processed := true; end else begin queue_delete(q); end; end; end; q := q2; end; end; // --------------------------------------------------------------------------- // WHOIS reply: Name field // <- :chii.CodersIRC.org 311 Zipplet Anders anders loves.chikane * :Anders Bergh // --------------------------------------------------------------------------- if cmd = '311' then begin // 311 self nick ident host * :realname // 0 1 2 3 4 5 6 if (base + 6) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 311'); exit; end; if int_whois.nick <> '' then begin if irclower(int_whois.nick) <> irclower(param[base + 2]) then begin handlewhois; end; end; int_whois.nick := param[base + 2]; int_whois.host := param[base + 3] + '@' + param[base + 4]; int_whois.fullname := param[params - 1]; // Flush all other info int_whois.channels.Clear; int_whois.server := ''; int_whois.serverinfo := ''; int_whois.seconds_idle := 0; int_whois.signonts := 0; int_whois.account := ''; int_whois.ircop := false; int_whois.awaymsg := ''; int_whois.away := false; int_whois.failed := false; int_whois.realhost := ''; int_whois.realip := ''; int_whois.realinfo := false; exit; end; // --------------------------------------------------------------------------- // WHOIS reply: Server field // <- :chii.CodersIRC.org 312 Zipplet Anders chii.CodersIRC.org :Chii! // --------------------------------------------------------------------------- if cmd = '312' then begin // 312 self nick server :serverinfo // 0 1 2 3 4 if (base + 4) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 312'); exit; end; if int_whois.nick <> param[base + 2] then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 312: out of sequence nick'); exit; end; int_whois.server := param[base + 3]; int_whois.serverinfo := param[base + 4]; exit; end; // --------------------------------------------------------------------------- // WHOIS reply: ircu account field // <- :chii.CodersIRC.org 330 Zipplet Anders Anders1 :is logged in as // --------------------------------------------------------------------------- if cmd = '330' then begin // 330 self nick auth msg // 0 1 2 3 4 if (base + 4) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 330'); exit; end; if int_whois.nick <> param[base + 2] then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 330: out of sequence nick'); exit; end; int_whois.account := param[base + 3]; exit; end; // --------------------------------------------------------------------------- // WHOIS reply: Real host and ip // <- :chii.CodersIRC.org 338 Zipplet Anders ~anders@malmo-65-215.skbbip.com 62.181.65.215 :Actual user@host, Actual IP // --------------------------------------------------------------------------- if cmd = '338' then begin // 338 self nick host ip msg // 0 1 2 3 4 5 if (base + 5) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 338'); exit; end; if int_whois.nick <> param[base + 2] then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 338: out of sequence nick'); exit; end; int_whois.realinfo := true; int_whois.realhost := param[base + 3]; int_whois.realip := param[base + 4]; exit; end; // --------------------------------------------------------------------------- // WHOIS reply: seconds idle and possibly signon TS // <- :chii.CodersIRC.org 317 Zipplet Anders 453 1120160740 :seconds idle, signon time // --------------------------------------------------------------------------- if cmd = '317' then begin // Form 1: // 317 self nick idle :msg // 0 1 2 3 4 // Form 2: // 317 self nick idle signonts :msg // 0 1 2 3 4 5 if (base + 4) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 317'); exit; end; if int_whois.nick <> param[base + 2] then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 317: out of sequence nick'); exit; end; try int_whois.seconds_idle := strtoint(param[base + 3]); except if assigned(onwarning) then onwarning('tirc.parsecmd: bad 317: strtoint failed, seconds_idle'); exit; end; if (base + 5) <= (params - 1) then begin try int_whois.signonts := strtoint(param[base + 4]); except if assigned(onwarning) then onwarning('tirc.parsecmd: bad 317: strtoint failed, signonts'); exit; end; end; exit; end; // --------------------------------------------------------------------------- // WHOIS reply: channelslist // <- :chii.CodersIRC.org 319 Zipplet Anders :#CodersIRC @#anders @#Zipplet @#reirc // --------------------------------------------------------------------------- if cmd = '319' then begin // 319 self nick :channel channel channel.... // 0 1 2 3 if (base + 3) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 319'); exit; end; if int_whois.nick <> param[base + 2] then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad 319: out of sequence nick'); exit; end; i := 1; while strtok(param[params - 1], ' ', i, false, s) do begin int_whois.channels.Add(s); end; exit; end; // --------------------------------------------------------------------------- // WHOIS reply: End of reply // --------------------------------------------------------------------------- if cmd = '318' then begin handlewhois; exit; end; // --------------------------------------------------------------------------- // Except list item // --------------------------------------------------------------------------- if cmd = INUM_EXCEPT_ITEM then begin if not supports_excepts then exit; if (base + 5) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad ' + INUM_EXCEPT_ITEM); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: ' + INUM_EXCEPT_ITEM + ' for nonexistant channel'); exit; end; i := cmodelookup[ord('e')]; if not tchan.modes[i].boolval then begin tchan.modes[i].list.Clear; tchan.modes[i].wholist.Clear; tchan.modes[i].tslist.Clear; tchan.modes[i].trustable := false; end; tchan.modes[i].list.Add(param[base + 3]); tchan.modes[i].wholist.Add(param[base + 4]); tchan.modes[i].tslist.Add(param[base + 5]); tchan.modes[i].boolval := true; exit; end; // --------------------------------------------------------------------------- // End of except list // --------------------------------------------------------------------------- if cmd = INUM_EXCEPT_END then begin if not supports_excepts then exit; if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad ' + INUM_EXCEPT_END); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: ' + INUM_EXCEPT_END + ' for nonexistant channel'); exit; end; i := cmodelookup[ord('e')]; tchan.modes[i].boolval := false; tchan.modes[i].trustable := true; if assigned(onlistexcept) then onlistexcept(tchan); exit; end; // --------------------------------------------------------------------------- // Invite list item // --------------------------------------------------------------------------- if cmd = INUM_INVITE_ITEM then begin if not supports_invites then exit; if (base + 5) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad ' + INUM_INVITE_ITEM); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: ' + INUM_INVITE_ITEM + ' for nonexistant channel'); exit; end; i := cmodelookup[ord('I')]; if not tchan.modes[i].boolval then begin tchan.modes[i].list.Clear; tchan.modes[i].wholist.Clear; tchan.modes[i].tslist.Clear; tchan.modes[i].trustable := false; end; tchan.modes[i].list.Add(param[base + 3]); tchan.modes[i].wholist.Add(param[base + 4]); tchan.modes[i].tslist.Add(param[base + 5]); tchan.modes[i].boolval := true; exit; end; // --------------------------------------------------------------------------- // End of invite list // --------------------------------------------------------------------------- if cmd = INUM_INVITE_END then begin if not supports_invites then exit; if (base + 2) > (params - 1) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: bad ' + INUM_INVITE_END); exit; end; tchan := find_channel(param[base + 2]); if not assigned(tchan) then begin if assigned(onwarning) then onwarning('tirc.parsecmd: ' + INUM_INVITE_END + ' for nonexistant channel'); exit; end; i := cmodelookup[ord('I')]; tchan.modes[i].boolval := false; tchan.modes[i].trustable := true; if assigned(onlistinvite) then onlistinvite(tchan); exit; end; end; // ----------------------------------------------------------------------------- // IRC Parser: "preamp" // ----------------------------------------------------------------------------- procedure tirc.parse(msg: string); var i, start: integer; src_host, src_nick: string; src_server: boolean; begin {$ifdef debug} lastcall := 'tirc.parse'; lastcall_info := msg; {$endif} // --------------------------------------------------------------------------- // Seperate into parameters // --------------------------------------------------------------------------- i := 0; start := 1; params := 0; repeat inc(i); if msg[i] = #32 then begin if (msg[start] = ':') and (params <> 0) then begin // we hit the "#32:" seperator, special case i := length(msg); end else begin inc(params); if params > maxparamcount then begin if assigned(onwarning) then onwarning('tirc.parse: illegal number of parameters in line'); exit; end; param[params - 1] := copy(msg, start, i - start); start := i + 1; end; end; until i = length(msg); if msg[i] <> #32 then begin // final param if params > 0 then if msg[start] = ':' then inc(start); inc(params); if params > maxparamcount then begin if assigned(onwarning) then onwarning('tirc.parse: illegal number of parameters in line'); exit; end; param[params - 1] := copy(msg, start, i - start + 1); end; // Deal with the prefix if param[0][1] = ':' then begin if pos('@', param[0]) = 0 then begin src_server := true; src_host := copy(param[0], 2, length(param[0]) - 1); src_nick := ''; end else begin i := pos('!', param[0]); src_nick := copy(param[0], 2, i - 2); src_host := copy(param[0], i + 1, length(param[0]) - i); src_server := false; end; parsecmd(src_nick, src_host, src_server, true); end else begin src_host := serverhost; parsecmd(src_nick, src_host, true, false); end; end; // ----------------------------------------------------------------------------- // Constructor // ----------------------------------------------------------------------------- constructor tirc.create; begin inherited create; {$ifdef debug} lastcall := 'tirc.create'; lastcall_info := ''; {$endif} socket := twsocket.create(nil); socket.OnDataAvailable := self.SocketDataAvailable; // note: connected has a nonzero error if it failed socket.OnSessionConnected := self.SocketSessionConnected; // note: nonzero error if failed socket.OnSessionClosed := self.SocketSessionClosed; // trap for errors in the dataavailable function socket.OnBgException := socketbgexception; isupport_key := tstringlist.create; isupport_value := tstringlist.create; // set some sane defaults nickname := 'guest'; email := 'guest@localhost'; fullname := 'tirc ' + ircparser_version + ' - Pascal IRC unit'; serverhost := ''; serverpassword := ''; serverport := 0; // Default options options.who_on_join := true; options.onwho_always := false; options.queue_interval := 5000; options.auto_cmode_add := true; options.action_onaction := true; int_whois.channels := tstringlist.Create; // not connected state resetstate; end; // ----------------------------------------------------------------------------- // Is the passed nickname valid? RFC1459 // ----------------------------------------------------------------------------- function tirc.validnick(nick: string): boolean; const validnickchars: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-[]\`^{}_'; var i: integer; begin {$ifdef debug} lastcall := 'tirc.validnick'; lastcall_info := nick; {$endif} result := false; // <nick> ::= <letter> { <letter> | <number> | <special> } // <letter> ::= 'a' ... 'z' | 'A' ... 'Z' // <number> ::= '0' ... '9' // <special> ::= '-' | '[' | ']' | '\' | '`' | '^' | '{' | '}' // Must not be empty if length(nick) = 0 then exit; // First character must be a letter if (ord(nick[1]) < 97) and (ord(nick[1]) > 122) and // a - z (ord(nick[1]) < 65) and (ord(nick[1]) > 90) then begin // A - Z exit; end; // Remaining characters must only be letters, numbers, or specials for i := 2 to length(nick) do if pos(nick[i], validnickchars) = 0 then exit; result := true; end; // ----------------------------------------------------------------------------- // Auth to the server - send pass, user, nick etc // ----------------------------------------------------------------------------- procedure tirc.sendauth; begin {$ifdef debug} lastcall := 'tirc.connect'; lastcall_info := ''; {$endif} if serverpassword <> '' then lineout('PASS ' + serverpassword); lineout('NICK ' + nickname); lineout('USER ' + copy(email, 1, pos('@', email) - 1) + ' ' + socket.getpeeraddr +' ' + serverhost + ' :' + fullname); end; // ----------------------------------------------------------------------------- // Initialise a connection to a remote server // ----------------------------------------------------------------------------- procedure tirc.connect(host: string; port: integer; password: string); var i: integer; begin {$ifdef debug} lastcall := 'tirc.connect'; lastcall_info := host + ':' + inttostr(port) + '-' + password; {$endif} if connected then begin raise ESocketAlreadyConnected.create('Already connected'); exit; end; // Check that everything needed to connect is ready i := pos('@', email); if (i < 2) or (i > length(email) - 2) then begin raise EInvalidConnectState.create('email is invalid'); exit; end; // Validate the nickname if not validnick(nickname) then begin raise EInvalidConnectState.create('nickname is invalid'); exit; end; // Fullname if length(fullname) < 0 then begin raise EInvalidConnectState.create('fullname is invalid'); exit; end; serverport := port; serverhost := host; serverpassword := password; resetstate; socket.proto := 'tcp'; socket.port := inttostr(serverport); socket.addr := serverhost; try socket.connect; except on e: exception do begin raise ESocketConnectFailure.create(e.message); end; end; end; // ----------------------------------------------------------------------------- // send a terminated line out of the socket // ----------------------------------------------------------------------------- procedure tirc.lineout(msg: string); {$ifdef debug} var lastlastcall: string; {$endif} begin {$ifdef debug} lastlastcall := lastcall; lastcall := 'tirc.lineout'; lastcall_info := msg; {$endif} if not connected then begin {$ifdef debug} raise ESocketNotConnected.create('socket is not connected - "' + msg + '" possibly from ' + lastlastcall); {$else} raise ENotConnected.create('socket is not connected - "' + msg + '"'); {$endif} exit; end; if length(msg) > maxmessagelength then begin raise EBadMessageSize.create('tried to send a message of length ' + inttostr(length(msg)) + ', > ' + inttostr(maxmessagelength)); exit; end; {$ifdef debug} out_ptrcircular := (out_ptrcircular + 1) mod circular_size; out_circular[out_ptrcircular] := msg; {$endif} // Send the line try socket.SendStr(msg + #13 + #10); except on e: exception do begin connected := false; raise ESocketWriteError.create(e.message); socket.Close; exit; end; end; if assigned(onrawout) then onrawout(msg); end; // ----------------------------------------------------------------------------- // Resets the internal state to the not connected state. // ----------------------------------------------------------------------------- procedure tirc.resetstate; var i: integer; begin {$ifdef debug} lastcall := 'tirc.resetstate'; lastcall_info := ''; {$endif} got001 := false; got005 := false; notready := true; connected := false; linebuffer := ''; hostmask := ''; serverircd := ''; supports_bans := false; supports_excepts := false; supports_invites := false; // RFC1459 member modes set_prefixlist('ov', '@+'); usermodes := 'iswo'; // RFC1459 channel (not member) modes { p - private channel flag; s - secret channel flag; i - invite-only channel flag; t - topic settable by channel operator only flag; n - no messages to channel from clients on the outside; m - moderated channel; l - set the user limit to channel; b - set a ban mask to keep users out; k - set a channel key (password). } set_flushmodelist; set_addchanmode('p', CBOOL); set_addchanmode('s', CBOOL); set_addchanmode('i', CBOOL); set_addchanmode('t', CBOOL); set_addchanmode('n', CBOOL); set_addchanmode('m', CBOOL); set_addchanmode('l', CSET); set_addchanmode('b', CLIST); set_addchanmode('k', CSETUNSET); // Clean channels linkedlist and users in it cleanchannels; // Clean usermodes for i := 0 to 255 do mymodes[i] := false; // Clean isupport list isupport_key.clear; isupport_value.clear; {$ifdef debug} in_ptrcircular := circular_size - 1; out_ptrcircular := circular_size - 1; {$endif} // Queue setup stop_queuetimer; queue_flush(nq_all); queue_busy := false; int_whois.nick := ''; end; // ----------------------------------------------------------------------------- // Destructor // ----------------------------------------------------------------------------- destructor tirc.destroy; begin {$ifdef debug} lastcall := 'tirc.destroy'; lastcall_info := ''; {$endif} int_whois.channels.Destroy; socket.Release; inherited destroy; end; // ----------------------------------------------------------------------------- // socket: data available to read. pass on to the parser // ----------------------------------------------------------------------------- procedure tirc.SocketDataAvailable(Sender: TObject; Error: Word); var s, s2: string; i: integer; begin {$ifdef debug} lastcall := 'tirc.SocketDataAvailable'; lastcall_info := inttostr(error); {$endif} try s := socket.ReceiveStr; except on e: exception do begin connected := false; raise ESocketReadError.create(e.message); socket.Close; exit; end; end; // Parse the string - split into lines // #10 - seperator, #13 = ignored for i := 1 to length(s) do begin if s[i] = #10 then begin if length(linebuffer) <> 0 then begin {$ifdef debug} in_ptrcircular := (in_ptrcircular + 1) mod circular_size; in_circular[in_ptrcircular] := linebuffer; {$endif} if assigned(onrawin) then onrawin(linebuffer); s2 := linebuffer; linebuffer := ''; parse(s2); end; end else begin if s[i] <> #13 then linebuffer := linebuffer + s[i]; end; end; end; // ----------------------------------------------------------------------------- // Session is connected, or failed to connect (error != 0) // ----------------------------------------------------------------------------- procedure tirc.SocketSessionConnected(Sender: TObject; Error: Word); begin {$ifdef debug} lastcall := 'tirc.SocketSessionConnected'; lastcall_info := inttostr(error); {$endif} if error <> 0 then begin // We didn't actually connect raise ESocketConnectFailure.create(sockreason(error)); exit; end; connected := true; if assigned(onconnectsuccess) then onconnectsuccess; start_queuetimer; sendauth; end; // ----------------------------------------------------------------------------- // Socket closed naturally or with error (error != 0) // ----------------------------------------------------------------------------- procedure tirc.SocketSessionClosed(Sender: TObject; Error: Word); begin {$ifdef debug} lastcall := 'tirc.SocketSessionClosed'; lastcall_info := inttostr(error); {$endif} stop_queuetimer; connected := false; if error <> 0 then begin raise ESocketReadError(sockreason(error)); exit; end; if assigned(ondisconnected) then ondisconnected; end; // ----------------------------------------------------------------------------- // socket background exception. Fired if untrapped error occurs in the parser // or socket dataavailable. CanClose = TRUE by default, tells if the socket will // close or not. // ----------------------------------------------------------------------------- procedure tirc.SocketBGException(Sender: TObject; E: Exception; var CanClose: Boolean); begin {$ifdef debug} raise EInternalError.create('SocketBGException: An unhandled exception of type "' + e.message + '" was raised. Location "' + lastcall + '" Info "' + lastcall_info + '"'); {$else} raise EInternalError.create('SocketBGException: An unhandled exception of type "' + e.message + '" was raised. Release build (no debug information)'); {$endif} end; // ----------------------------------------------------------------------------- // sockreason // numeric socker error -> string // used with permission from beware // ----------------------------------------------------------------------------- function sockreason(error:integer):string; begin case error of 0:result := 'Read error: EOF from client'; 24:result := 'Too many open files'; 10022:result := 'Invalid argument'; 32, 10032:result := 'Broken pipe'; 10050:result := 'Read error: Network is down'; 10051:result := 'Read error: Network is unreachable'; { 10053:result := 'Software caused connection abort'; windows 2000, as i tested, often returns 10053, hiding the real error code. i do this because it looks better (more ircd like) } 54, 104, 10053, 10054:result := 'Read error: Connection reset by peer'; 110, 10060:result := 'Connection timed out'; 111, 10061:result := 'Connection refused'; 10064:result := 'Read error: Host is down'; 113, 10065:result := 'Read error: No route to host'; {(Read error: 60 (Operation timed out))} else result := 'socket error '+inttostr(error); end; end; // ----------------------------------------------------------------------------- // Split a fullhost <s> into s1 and s2. // nick!ident@host -> nick, ident@host // ----------------------------------------------------------------------------- procedure splitnickhost(s: string; var s1, s2: string); var i: integer; begin i := pos(s, '!'); if (i < 2) or (i > (length(s) - 1)) then begin s1 := s; s2 := ''; end else begin s1 := copy(s, 1, i - 1); s2 := copy(s, i + 1, length(s) - i); end; end; // ----------------------------------------------------------------------------- // Queue timer event. Check objects for expiry. // ----------------------------------------------------------------------------- procedure tirc.queuetimerevent(sender: tobject); var q, qn: tirc_queue; ts: integer; begin {$ifdef debug} lastcall := 'tirc.queuetimerevent'; lastcall_info := ''; {$endif} // queue_busy stops this code from being re-entered if the users code // called by the timer events happens to take a long time and processes the // message loop; this could make the queue timer fire again before it finished // processing. In that case, without this, tirc could crash because the // linked-list walking would be re-entered before the previous walk finished, // and an event could fire twice. It also stops the timer from firing if a // queue event is being executed for another reason. if queue_busy then exit; queue_busy := true; q := queue; ts := unixtimeint; while assigned(q) do begin qn := q.ptr_next; if (ts >= q.ts) and (not q.destroying) then begin // This item timed out. Send a timeout event and destroy it. case q.itemtype of nq_whois: begin tirc_queuewhois(q).notify(tirc_queuewhois(q).nick, int_whois, true); end; nq_userhost: begin tirc_queueuserhost(q).notify(tirc_queueuserhost(q).nick, '', true); end; end; // remove from linked list - inlined for speed if q.waiting then begin // Waiting for it. Instead, mark it q.destroying := true; q.timedout := true; end else begin if assigned(q.ptr_prev) then q.ptr_prev.ptr_next := q.ptr_next; if assigned(q.ptr_next) then q.ptr_next.ptr_prev := q.ptr_prev; if not assigned(q.ptr_prev) then queue := q.ptr_next; if not assigned(q.ptr_next) then queue_last := q.ptr_prev; q.Destroy; end; end; q := qn; end; queue_busy := false; end; // ----------------------------------------------------------------------------- // Delete the passed queue object. // ----------------------------------------------------------------------------- procedure tirc.queue_delete(q: tirc_queue); begin {$ifdef debug} lastcall := 'tirc.queue_delete'; lastcall_info := ''; {$endif} if q.destroying then exit; if q.waiting then begin q.destroying := true; exit; end; if assigned(q.ptr_prev) then q.ptr_prev.ptr_next := q.ptr_next; if assigned(q.ptr_next) then q.ptr_next.ptr_prev := q.ptr_prev; if not assigned(q.ptr_prev) then queue := q.ptr_next; if not assigned(q.ptr_next) then queue_last := q.ptr_prev; q.Destroy; end; // ----------------------------------------------------------------------------- // Delete all queue items of this type. // ----------------------------------------------------------------------------- procedure tirc.queue_flush(eventtype: nqueue); var q, qn: tirc_queue; begin {$ifdef debug} lastcall := 'tirc.queue_flush'; lastcall_info := ''; {$endif} q := queue; while assigned(q) do begin qn := q.ptr_next; if (q.itemtype = eventtype) or (eventtype = nq_all) then begin if not q.destroying then begin if q.waiting then begin q.destroying := true; end else begin if assigned(q.ptr_prev) then q.ptr_prev.ptr_next := q.ptr_next; if assigned(q.ptr_next) then q.ptr_next.ptr_prev := q.ptr_prev; if not assigned(q.ptr_prev) then queue := q.ptr_next; if not assigned(q.ptr_next) then queue_last := q.ptr_prev; q.Destroy; end; end; end; q := qn; end; end; // ----------------------------------------------------------------------------- // Add a whois event to the queue. // ----------------------------------------------------------------------------- function tirc.queue_whois(nick: string; remote: boolean; event: twhoisevent; timeout: integer): tirc_queue; var q: tirc_queuewhois; nowts: integer; begin {$ifdef debug} lastcall := 'tirc.queue_whois'; lastcall_info := nick; {$endif} if not assigned(event) then begin raise enilevent.Create('event must be assigned'); exit; end; nowts := unixtimeint; // Create the queue object q := tirc_queuewhois.Create; q.notify := event; q.nick := nick; q.ts := nowts + timeout; q.itemtype := nq_whois; // Add it to the linked list q.ptr_prev := nil; q.ptr_next := nil; q.waiting := false; q.destroying := false; q.processed := false; q.timedout := false; if not assigned(queue) then begin queue := q; end else begin q.ptr_prev := queue_last; queue_last.ptr_next := q; queue_last := q; end; // Send the WHOIS. if not remote then lineout('WHOIS ' + nick) else lineout('WHOIS ' + nick + ' ' + nick); result := q; end; // ----------------------------------------------------------------------------- // Add a userhost event to the queue // ----------------------------------------------------------------------------- function tirc.queue_userhost(nick: string; event: tuserhostevent; timeout: integer): tirc_queue; var q: tirc_queueuserhost; nowts: integer; begin {$ifdef debug} lastcall := 'tirc.queue_userhost'; lastcall_info := nick; {$endif} if not assigned(event) then begin raise enilevent.Create('event must be assigned'); exit; end; nowts := unixtimeint; // Create the queue object q := tirc_queueuserhost.Create; q.notify := event; q.nick := nick; q.ts := nowts + timeout; q.itemtype := nq_userhost; // Add it to the linked list q.ptr_prev := nil; q.ptr_next := nil; q.waiting := false; q.destroying := false; q.processed := false; q.timedout := false; if not assigned(queue) then begin queue := q; queue_last := q; end else begin q.ptr_prev := queue_last; queue_last.ptr_next := q; queue_last := q; end; // Send the userhost. lineout('USERHOST ' + nick); result := q; end; // ----------------------------------------------------------------------------- // Count and return the number of queue events matching the type specified. // ----------------------------------------------------------------------------- function tirc.queue_count(eventtype: nqueue): integer; var q, qn: tirc_queue; i: integer; begin {$ifdef debug} lastcall := 'tirc.queue_count'; lastcall_info := ''; {$endif} q := queue; i := 0; while assigned(q) do begin qn := q.ptr_next; if (q.itemtype = eventtype) or (eventtype = nq_all) then begin inc(i); end; q := qn; end; result := i; end; // ----------------------------------------------------------------------------- // Wait for a queue object. Returns status. // ----------------------------------------------------------------------------- function tirc.queue_wait(q: tirc_queue; timeout: integer): nwaitresult; var nowts, waitts: integer; begin {$ifdef debug} lastcall := 'tirc.queue_wait'; lastcall_info := ''; {$endif} //nwaitresult = (nw_event, nw_timeout, nw_destroyed, nw_failed); nowts := unixtimeint; waitts := nowts + timeout; result := nw_failed; q.waiting := true; repeat // Go to sleep sleep(1); nowts := unixtimeint; // Check the object if q.destroying then begin // Something happened. if q.timedout then begin // The object timed out result := nw_timeout; break; end; if q.processed then begin // Object was processed result := nw_event; break; end; // User destroyed it... result := nw_destroyed; end; // Process the message queue {$ifdef usecore} processmessages; {$else} application.processmessages; {$endif} until nowts >= waitts; if result <> nw_failed then begin // Destroy the queue object. if assigned(q.ptr_prev) then q.ptr_prev.ptr_next := q.ptr_next; if assigned(q.ptr_next) then q.ptr_next.ptr_prev := q.ptr_prev; if not assigned(q.ptr_prev) then queue := q.ptr_next; if not assigned(q.ptr_next) then queue_last := q.ptr_prev; q.Destroy; end; end; // ----------------------------------------------------------------------------- // Send a CTCP // ----------------------------------------------------------------------------- procedure tirc.ctcp(destination, command: string; params: string = ''); begin {$ifdef debug} lastcall := 'tirc.ctcp'; lastcall_info := destination; {$endif} if params = '' then begin lineout('PRIVMSG ' + destination + ' :' + #1 + command + #1); end else begin lineout('PRIVMSG ' + destination + ' :' + #1 + command + ' ' + params + #1); end; end; // ----------------------------------------------------------------------------- // Send a CTCP reply // ----------------------------------------------------------------------------- procedure tirc.ctcpreply(destination, command: string; params: string = ''); begin {$ifdef debug} lastcall := 'tirc.ctcpreply'; lastcall_info := destination; {$endif} if params = '' then begin lineout('NOTICE ' + destination + ' :' + #1 + command + #1); end else begin lineout('NOTICE ' + destination + ' :' + #1 + command + ' ' + params + #1); end; end; // ----------------------------------------------------------------------------- // Handle a finished whois reply // ----------------------------------------------------------------------------- procedure tirc.handlewhois; var q, q2: tirc_queue; begin q := queue; while assigned(q) do begin q2 := q.ptr_next; if q.itemtype = nq_whois then begin if irclower(tirc_queuewhois(q).nick) = irclower(int_whois.nick) then begin tirc_queuewhois(q).notify(int_whois.nick, int_whois, false); if q.waiting then begin q.destroying := true; q.processed := true; end else begin queue_delete(q); end; end; end; q := q2; end; if assigned(onwhois) then onwhois(int_whois); int_whois.nick := ''; end; // ----------------------------------------------------------------------------- // Start the queue timer // ----------------------------------------------------------------------------- procedure tirc.start_queuetimer; begin if assigned(queuetimer) then exit; queuetimer := tltimer.Create(nil); queuetimer.enabled := true; queuetimer.interval := options.queue_interval; queuetimer.OnTimer := self.queuetimerevent; end; // ----------------------------------------------------------------------------- // Stop the queue timer // ----------------------------------------------------------------------------- procedure tirc.stop_queuetimer; begin if not assigned(queuetimer) then exit; queuetimer.OnTimer := nil; queuetimer.release; end; end.
unit Model.AssinaturaJornal; interface type TAssinaturaJornal = class private var FId: Integer; FCodigo: String; FModalidade: Integer; FProduto: String; FOrdem: Integer; FQtde: Integer; FNome: String; FTipoLogradouro : String; FNomeLogradouro: String; FNumeroLogradouro: String; FComplemento: String; FBairro: String; FCidade: String; FEstado: String; FCEP: String; FReferencia: String; FRoteiro: String; FLog: String; public property ID: integer read FId write FId; property Codigo: String read FCodigo write FCodigo; property Modalidade: Integer read FModalidade write FModalidade; property Produto: String read FProduto write FProduto; property Ordem: Integer read FOrdem write FOrdem; property Qtde: Integer read FQtde write FQtde; property Nome: String read FNome write FNome; property TipoLogradouro: String read FTipoLogradouro write FTipoLogradouro; property NomeLogradouro: String read FNomeLogradouro write FNomeLogradouro; property NumeroLogradouro: String read FNumeroLogradouro write FNumeroLogradouro; property Complemento: String read FComplemento write FComplemento; property Bairro: String read FBairro write FBairro; property Cidade: String read FCidade write FCidade; property Estado: String read FEstado write FEstado; property CEP: String read FCEP write FCEP; property Referencia: String read FReferencia write FReferencia; property Roteiro: String read FRoteiro write FRoteiro; property Log: String read FLog write FLog; constructor Create; overload; constructor Create(pFId: Integer; pFCodigo: String;pFModalidade: Integer; pFProduto:String; pFOrdem: Integer; pFQtde: Integer; pFNome: String; pFTipoLogradouro : String; pFNomeLogradouro: String; pFNumeroLogradouro: String; pFComplemento: String; pFBairro: String; pFCidade: String; pFEstado: String; pFCEP: String; pFReferencia: String; pFRoteiro: String; pFLog: String); overload; end; implementation constructor TAssinaturaJornal.Create; begin inherited Create; end; constructor TAssinaturaJornal.Create(pFId: Integer; pFCodigo: String; pFModalidade: Integer; pFProduto: string; pFOrdem: Integer; pFQtde: Integer; pFNome: string; pFTipoLogradouro: string; pFNomeLogradouro: string; pFNumeroLogradouro: string; pFComplemento: string; pFBairro: string; pFCidade: string; pFEstado: string; pFCEP: string; pFReferencia: string; pFRoteiro: string; pFLog: string); begin FId := pFId; FCodigo := pFCodigo; FModalidade := pFModalidade; FProduto := pFProduto; FOrdem := pFOrdem; FQtde := pFQtde; FNome := pFNome; FTipoLogradouro := pFTipoLogradouro; FNomeLogradouro := pFNomeLogradouro; FNumeroLogradouro := pFNumeroLogradouro; FComplemento := pFComplemento; FBairro := pFBairro; FCidade := pFCidade; FEstado := pFEstado; FCEP := pFCEP; FReferencia := pFReferencia; FRoteiro := pFRoteiro; FLog := FLog; end; end.
unit csCommandsTypes; {$I csDefine.inc} interface uses //l3Base, Classes, CsDataPipe, ddAppConfigTypes, ddServerTask, csProcessTask, l3SimpleObject ; type // TcsCommandRequirement = (cs_crAll, cs_crSystem, cs_crUserList, cs_crGroupList); TcsCommandExecuteEvent = procedure (aTask: TddTaskItem) of object; TcsCommand = class(Tl3SimpleObject) private f_Caption: AnsiString; f_CommandID: Integer; f_NeedRespond: Boolean; f_OnExecute: TcsCommandExecuteEvent{TNotifyEvent}; f_RequireAdminRights: Boolean; function pm_GetCaption: AnsiString; function pm_GetCommandID: Integer; function pm_GetNeedRespond: Boolean; procedure pm_SetNeedRespond(const Value: Boolean); public constructor Create(aCommandID: Integer; const aCaption: AnsiString); overload; constructor Create(aCommandID: Integer; const aCaption: AnsiString; anOnExecute: TcsCommandExecuteEvent{TNotifyEvent}); overload; constructor Create(aStream: TStream{; anOnExecute: TcsCommandExecuteEvent}); overload; procedure Execute(aTask: TddTaskItem); procedure Load(aStream: TStream); procedure Save(aStream: TStream); property Caption: AnsiString read pm_GetCaption {write pm_SetCaption}; property CommandID: Integer read pm_GetCommandID {write pm_SetCommandID}; property NeedRespond: Boolean read pm_GetNeedRespond write pm_SetNeedRespond; property RequireAdminRights: Boolean read f_RequireAdminRights write f_RequireAdminRights; property OnExecute: TcsCommandExecuteEvent read f_OnExecute; end; TcsCommands = (acmdNone, // служба acmdStart, acmdStop, acmdPause, acmdContinue, acmdRestart, // задания acmdStopAndGoAll, acmdDeleteTask, acmdConfig, acmdSendMessage, acmdAutoLogoff, acmdLogMessages, acmdCheckTables, acmdUpdateTables, acmdLockBase, acmdUnlockBase, acmdCompileDictionaries, acmdUpdateText, acmdDoEverydayUpdate, acmdBuildTextIndex, acmdCheckFreeSpace, acmdCheckTexts, acmdClearLocks, acmdEmailNotify, acmdFamilyBackup, acmdFullBackup, acmdGardocBridge, acmdIsDeltaReady, acmdLoadDelta, acmdLoadEQ, acmdLoadKW, acmdMakeDelta, acmdMakeLoadDelta, acmdPauseTask, acmdPreventiveUpdate, acmdRefresh, acmdRestoreFamily, acmdRunTask, acmdSetHighestPriority, acmdSetHighPriority, acmdSetLowestPriority, acmdSetLowPriority, acmdSetNormalPriority, acmdStack2Log, acmdStopNGoAnnoExport, acmdStopNGoExport, acmdStopNGoImport, acmdSwitchToRealBase, acmdSwitchToTempBase, acmdUndoRestore, acmdUpdateDictEntryIndex, acmdUpdateHeaderIndex, acmdUpdateIndex, acmdUserInfo, acmdWeeklyUpdate ); implementation uses SysUtils, ddStreamUtils, l3FileUtils ; constructor TcsCommand.Create(aCommandID: Integer; const aCaption: AnsiString); begin inherited Create; f_CommandID := aCommandID; f_Caption:= aCaption; f_NeedRespond:= False; end; constructor TcsCommand.Create(aCommandID: Integer; const aCaption: AnsiString; anOnExecute: TcsCommandExecuteEvent{TNotifyEvent}); begin Create(aCommandID, aCaption); f_OnExecute := anOnExecute; end; constructor TcsCommand.Create(aStream: TStream); begin Create(0, ''); Load(aStream); end; procedure TcsCommand.Execute(aTask: TddTaskItem); begin if Assigned(f_OnExecute) then f_OnExecute(aTask); end; procedure TcsCommand.Load(aStream: TStream); begin aStream.Read(f_CommandID, SizeOf(f_CommandID)); ReadString(aStream, f_Caption); aStream.Read(f_NeedRespond, SizeOf(f_NeedRespond)); end; function TcsCommand.pm_GetCaption: AnsiString; begin Result:= f_Caption; end; function TcsCommand.pm_GetCommandID: Integer; begin Result:= f_CommandID; end; function TcsCommand.pm_GetNeedRespond: Boolean; begin Result := f_NeedRespond; end; procedure TcsCommand.pm_SetNeedRespond(const Value: Boolean); begin f_NeedRespond := Value; end; procedure TcsCommand.Save(aStream: TStream); begin aStream.Write(f_CommandID, SizeOf(f_CommandID)); WriteString(aStream, f_Caption); aStream.Write(f_NeedRespond, SizeOf(f_NeedRespond)); end; end.
unit SimpleHeap; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {$mode objfpc}{$H+} {$macro on} interface uses CoreTypes, SysUtils, Variants; type THeapItem = record Value:Variant; index:Int32; end; THeapArray = Array of THeapItem; THeapItemI = record Value:Int32; index:Int32; end; THeapArrayI = Array of THeapItemI; THeapItemF = record Value:Single; index:Int32; end; THeapArrayF = Array of THeapItemF; THeapItemD = record Value:Double; index:Int32; end; THeapArrayD = Array of THeapItemD; (* heap using variant, for general usage *) procedure hPush(var h:THeapArray; item:Variant; idx:Int32; HiLo:Boolean=True); Inline; function hPop(var h:THeapArray; HiLo:Boolean=True): THeapItem; Inline; (* Specialized heap using Integer *) procedure hPush(var h:THeapArrayI; item:Int32; idx:Int32; HiLo:Boolean=True); Inline; overload; function hPop(var h:THeapArrayI; HiLo:Boolean=True): THeapItemI; Inline; overload; (* Specialized heap using Single *) procedure hPush(var h:THeapArrayF; item:Single; idx:Int32; HiLo:Boolean=True); Inline; overload; function hPop(var h:THeapArrayF; HiLo:Boolean=True): THeapItemF; Inline; overload; (* Specialized heap using Double *) procedure hPush(var h:THeapArrayD; item:Double; idx:Int32; HiLo:Boolean=True); Inline; overload; function hPop(var h:THeapArrayD; HiLo:Boolean=True): THeapItemD; Inline; overload; //----------------------------------------------------------------------------\\ implementation //----------------------------------------------------------------------------\\ //---| Variant |---------------------------------------------------------------> procedure _movedownHI(var heap:THeapArray; startpos, pos:Int32); Inline; var parentpos: Int32; parent,newitem:THeapItem; begin newitem := heap[pos]; while (pos > startpos) do begin parentpos := (pos - 1) shr 1; parent := heap[parentpos]; if (newitem.value < parent.value) then begin heap[pos] := parent; pos := parentpos; continue; end; break; end; heap[pos] := newitem; end; procedure _movedownLO(var heap:THeapArray; startpos, pos:Int32); Inline; var parentpos: Int32; parent,newitem:THeapItem; begin newitem := heap[pos]; while (pos > startpos) do begin parentpos := (pos - 1) shr 1; parent := heap[parentpos]; if (newitem.value > parent.value) then begin heap[pos] := parent; pos := parentpos; continue; end; break; end; heap[pos] := newitem; end; procedure _moveupHI(var heap:THeapArray; pos:Int32); Inline; var endpos,startpos,childpos,rightpos:Int32; newitem: THeapItem; begin endpos := length(heap); startpos := pos; newitem := heap[pos]; childpos := 2 * pos + 1; while childpos < endpos do begin rightpos := childpos + 1; if (rightpos < endpos) and not(heap[childpos].value < heap[rightpos].value) then childpos := rightpos; heap[pos] := heap[childpos]; pos := childpos; childpos := 2 * pos + 1; end; heap[pos] := newitem; _movedownHI(heap, startpos, pos) end; procedure _moveupLO(var heap:THeapArray; pos:Int32); Inline; var endpos,startpos,childpos,rightpos:Int32; newitem: THeapItem; begin endpos := length(heap); startpos := pos; newitem := heap[pos]; childpos := 2 * pos + 1; while childpos < endpos do begin rightpos := childpos + 1; if (rightpos < endpos) and not(heap[childpos].value > heap[rightpos].value) then childpos := rightpos; heap[pos] := heap[childpos]; pos := childpos; childpos := 2 * pos + 1; end; heap[pos] := newitem; _movedownLO(heap, startpos, pos) end; procedure hPush(var h:THeapArray; item:Variant; idx:Int32; HiLo:Boolean=True); Inline; var hi:Int32; begin hi := Length(h); SetLength(h,hi+1); h[hi].value := item; h[hi].index := idx; case HiLo of True: _movedownHI(h, 0, hi); False:_movedownLO(h, 0, hi); end; end; function hPop(var h:THeapArray; HiLo:Boolean=True): THeapItem; Inline; var m:THeapItem; begin m := h[High(h)]; SetLength(h, high(h)); if (High(h) >= 0) then begin Result := h[0]; h[0] := m; case HiLo of True: _moveupHI(h, 0); False:_moveupLO(h, 0); end; end else Exit(m); end; //----------------------------------------------------------------------------\\ //---| Integer |---------------------------------------------------------------> procedure _movedownHI(var heap:THeapArrayI; startpos, pos:Int32); Inline; overload; var parentpos: Int32; parent,newitem:THeapItemI; begin newitem := heap[pos]; while (pos > startpos) do begin parentpos := (pos - 1) shr 1; parent := heap[parentpos]; if (newitem.value < parent.value) then begin heap[pos] := parent; pos := parentpos; continue; end; break; end; heap[pos] := newitem; end; procedure _moveupHI(var heap:THeapArrayI; pos:Int32); Inline; overload; var endpos,startpos,childpos,rightpos:Int32; newitem: THeapItemI; begin endpos := length(heap); startpos := pos; newitem := heap[pos]; childpos := 2 * pos + 1; while childpos < endpos do begin rightpos := childpos + 1; if (rightpos < endpos) and not(heap[childpos].value < heap[rightpos].value) then childpos := rightpos; heap[pos] := heap[childpos]; pos := childpos; childpos := 2 * pos + 1; end; heap[pos] := newitem; _movedownHI(heap, startpos, pos) end; procedure _movedownLO(var heap:THeapArrayI; startpos, pos:Int32); Inline; overload; var parentpos: Int32; parent,newitem:THeapItemI; begin newitem := heap[pos]; while (pos > startpos) do begin parentpos := (pos - 1) shr 1; parent := heap[parentpos]; if (newitem.value > parent.value) then begin heap[pos] := parent; pos := parentpos; continue; end; break; end; heap[pos] := newitem; end; procedure _moveupLO(var heap:THeapArrayI; pos:Int32); Inline; overload; var endpos,startpos,childpos,rightpos:Int32; newitem: THeapItemI; begin endpos := length(heap); startpos := pos; newitem := heap[pos]; childpos := 2 * pos + 1; while childpos < endpos do begin rightpos := childpos + 1; if (rightpos < endpos) and not(heap[childpos].value > heap[rightpos].value) then childpos := rightpos; heap[pos] := heap[childpos]; pos := childpos; childpos := 2 * pos + 1; end; heap[pos] := newitem; _movedownLO(heap, startpos, pos) end; procedure hPush(var h:THeapArrayI; item:Int32; idx:Int32; HiLo:Boolean=True); Inline; overload; var hi:Int32; begin hi := Length(h); SetLength(h,hi+1); h[hi].value := item; h[hi].index := idx; case HiLo of True: _movedownHI(h, 0, hi); False:_movedownLO(h, 0, hi); end; end; function hPop(var h:THeapArrayI; HiLo:Boolean=True): THeapItemI; Inline; overload; var m:THeapItemI; begin m := h[High(h)]; SetLength(h, high(h)); if (High(h) >= 0) then begin Result := h[0]; h[0] := m; case HiLo of True: _moveupHI(h, 0); False:_moveupLO(h, 0); end; end else Exit(m); end; //----------------------------------------------------------------------------\\ //---| Single |----------------------------------------------------------------> procedure _movedownHI(var heap:THeapArrayF; startpos, pos:Int32); Inline; overload; var parentpos: Int32; parent,newitem:THeapItemF; begin newitem := heap[pos]; while (pos > startpos) do begin parentpos := (pos - 1) shr 1; parent := heap[parentpos]; if (newitem.value < parent.value) then begin heap[pos] := parent; pos := parentpos; continue; end; break; end; heap[pos] := newitem; end; procedure _moveupHI(var heap:THeapArrayF; pos:Int32); Inline; overload; var endpos,startpos,childpos,rightpos:Int32; newitem: THeapItemF; begin endpos := length(heap); startpos := pos; newitem := heap[pos]; childpos := 2 * pos + 1; while childpos < endpos do begin rightpos := childpos + 1; if (rightpos < endpos) and not(heap[childpos].value < heap[rightpos].value) then childpos := rightpos; heap[pos] := heap[childpos]; pos := childpos; childpos := 2 * pos + 1; end; heap[pos] := newitem; _movedownHI(heap, startpos, pos) end; procedure _movedownLO(var heap:THeapArrayF; startpos, pos:Int32); Inline; overload; var parentpos: Int32; parent,newitem:THeapItemF; begin newitem := heap[pos]; while (pos > startpos) do begin parentpos := (pos - 1) shr 1; parent := heap[parentpos]; if (newitem.value > parent.value) then begin heap[pos] := parent; pos := parentpos; continue; end; break; end; heap[pos] := newitem; end; procedure _moveupLO(var heap:THeapArrayF; pos:Int32); Inline; overload; var endpos,startpos,childpos,rightpos:Int32; newitem: THeapItemF; begin endpos := length(heap); startpos := pos; newitem := heap[pos]; childpos := 2 * pos + 1; while childpos < endpos do begin rightpos := childpos + 1; if (rightpos < endpos) and not(heap[childpos].value > heap[rightpos].value) then childpos := rightpos; heap[pos] := heap[childpos]; pos := childpos; childpos := 2 * pos + 1; end; heap[pos] := newitem; _movedownLO(heap, startpos, pos) end; procedure hPush(var h:THeapArrayF; item:Single; idx:Int32; HiLo:Boolean=True); Inline; overload; var hi:Int32; begin hi := Length(h); SetLength(h,hi+1); h[hi].value := item; h[hi].index := idx; case HiLo of True: _movedownHI(h, 0, hi); False:_movedownLO(h, 0, hi); end; end; function hPop(var h:THeapArrayF; HiLo:Boolean=True): THeapItemF; Inline; overload; var m:THeapItemF; begin m := h[High(h)]; SetLength(h, high(h)); if (High(h) >= 0) then begin Result := h[0]; h[0] := m; case HiLo of True: _moveupHI(h, 0); False:_moveupLO(h, 0); end; end else Exit(m); end; //----------------------------------------------------------------------------\\ //---| Double |----------------------------------------------------------------> procedure _movedownHI(var heap:THeapArrayD; startpos, pos:Int32); Inline; overload; var parentpos: Int32; parent,newitem:THeapItemD; begin newitem := heap[pos]; while (pos > startpos) do begin parentpos := (pos - 1) shr 1; parent := heap[parentpos]; if (newitem.value < parent.value) then begin heap[pos] := parent; pos := parentpos; continue; end; break; end; heap[pos] := newitem; end; procedure _moveupHI(var heap:THeapArrayD; pos:Int32); Inline; overload; var endpos,startpos,childpos,rightpos:Int32; newitem: THeapItemD; begin endpos := length(heap); startpos := pos; newitem := heap[pos]; childpos := 2 * pos + 1; while childpos < endpos do begin rightpos := childpos + 1; if (rightpos < endpos) and not(heap[childpos].value < heap[rightpos].value) then childpos := rightpos; heap[pos] := heap[childpos]; pos := childpos; childpos := 2 * pos + 1; end; heap[pos] := newitem; _movedownHI(heap, startpos, pos) end; procedure _movedownLO(var heap:THeapArrayD; startpos, pos:Int32); Inline; overload; var parentpos: Int32; parent,newitem:THeapItemD; begin newitem := heap[pos]; while (pos > startpos) do begin parentpos := (pos - 1) shr 1; parent := heap[parentpos]; if (newitem.value > parent.value) then begin heap[pos] := parent; pos := parentpos; continue; end; break; end; heap[pos] := newitem; end; procedure _moveupLO(var heap:THeapArrayD; pos:Int32); Inline; overload; var endpos,startpos,childpos,rightpos:Int32; newitem: THeapItemD; begin endpos := length(heap); startpos := pos; newitem := heap[pos]; childpos := 2 * pos + 1; while childpos < endpos do begin rightpos := childpos + 1; if (rightpos < endpos) and not(heap[childpos].value > heap[rightpos].value) then childpos := rightpos; heap[pos] := heap[childpos]; pos := childpos; childpos := 2 * pos + 1; end; heap[pos] := newitem; _movedownLO(heap, startpos, pos) end; procedure hPush(var h:THeapArrayD; item:Double; idx:Int32; HiLo:Boolean=True); Inline; overload; var hi:Int32; begin hi := Length(h); SetLength(h,hi+1); h[hi].value := item; h[hi].index := idx; case HiLo of True: _movedownHI(h, 0, hi); False:_movedownLO(h, 0, hi); end; end; function hPop(var h:THeapArrayD; HiLo:Boolean=True): THeapItemD; Inline; overload; var m:THeapItemD; begin m := h[High(h)]; SetLength(h, high(h)); if (High(h) >= 0) then begin Result := h[0]; h[0] := m; case HiLo of True: _moveupHI(h, 0); False:_moveupLO(h, 0); end; end else Exit(m); end; end.
unit defaults; {$MODE Delphi} {$DEFINE private_version} { Activate for private version } { Settings, global constants and global parameters of program WASI. } interface uses LCLIntf, LCLType, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; const ProgramInfo = 'WASI - Water color simulator'; vers: string = 'Version 5.2 - Latest update: 4 Aug 2020'; flag_public : boolean = TRUE; { public version of WASI? } INI_public = 'WASI5_2.INI'; { File with public default values } INI_private = 'private\PRIVATE.INI'; { File with private default values } MaxChannels = 1300; { Max. number of spectral channels } M1 = 50; { Max. number of fit parameters } FC = 4; { Max. number of fit curves } type spektrum = array[1..MaxChannels]of double; { Spectral data } spec_types = (S_Ed_GC, S_Lup, S_rrs, S_R, { Types of spectra } S_Rsurf, S_a, S_Kd, S_Rbottom, S_test, S_Ed_Gege); param = record { fit variables } c : array[1..M1]of double; { fit parameters } step_c : array[1..M1]of double; { initial steps } cmin : array[1..M1]of double; { minimum allowed } cmax : array[1..M1]of double; { maximum allowed } fit : array[1..M1]of byte; { fitted? 0=no, 1=yes } map : array[1..M1]of byte; { used for mapping } name : array[1..M1]of string; { parameter name } desc : array[1..M1]of string; { parameter description } end; Attr_spec = record { Spectral data files } ParText : String; { Parameter name and units } FName : String; { File name } Header : integer; { Header lines } XColumn : byte; { Column with x-values } YColumn : byte; { Column with y-values } y : spektrum; { Spectral data } sim : boolean; { Simulated spectrum? } avg : double; { Average from Lmin to Lmax } end; Fitparameters = record fw : double; { value in forward model } default : double; { default value for invers model } actual : double; { actual value in invers model } min : double; { minimum value of fit } max : double; { maximum value of fit } f_step : double; { initial step of fit } f_err : double; { allowed error of fit parameter } fit : byte; { used as fit variable? (1=YES) } sv : byte; { save in reconstruction mode? (1=YES) } merk : double; { save fitparameters? } merkFw : double; { save parameters of forward mode? } merkFit : byte; { save parameters of inverse mode? } active : boolean; { active? } end; { **************************************************************************** } { *********** Settings of WASI.INI *********** } { **************************************************************************** } var { Input spectra specified in WASI.INI } x : ^Attr_spec; { x-values (wavelengths) } FWHM : ^Attr_spec; { Spectral resolution } offsetS : ^Attr_spec; { Measurement offset spectrum } scaleS : ^Attr_spec; { Measurement scale spectrum } noiseS : ^Attr_spec; { Measurement noise spectrum } E0 : ^Attr_spec; { Extraterrestrial solar irradiance } aO2 : ^Attr_spec; { Absorption coefficient of oxygen } aO3 : ^Attr_spec; { Absorption coefficient of ozone } aWV : ^Attr_spec; { Absorption coefficient of water vapor } a_ice : Attr_spec; { Absorption coefficient of pure ice } aW : ^Attr_spec; { Absorption coefficient of pure water } dadT : ^Attr_spec; { Temperature gradient of water absorption coefficient } aP : array[0..5]of ^Attr_spec; { Specific absorption coefficient of phytoplankton } aNAP : ^Attr_spec; { Specific absorption coefficient of NAP non-algal particles) } aY : ^Attr_spec; { Specific absorption coefficient of CDOM } bPhyN : ^Attr_spec; { Normalized scattering coefficient of phytoplankton } bXN : ^Attr_spec; { Normalized scattering coefficient of particles type I } albedo : array[0..5]of ^Attr_spec; { Bottom albedo spectra } a_nw : ^Attr_spec; { Albedo of non-water area } meas : ^Attr_spec; { Measured spectrum } R : ^Attr_spec; { Irradiance reflectance } Ed : ^Attr_spec; { Downwelling irradiance } Ls : ^Attr_spec; { Sky radiance } Kd : ^Attr_spec; { Diffuse attenuation for downwelling irradiance } gew : ^Attr_spec; { Weight factors for inversion } HSI_img : ^Attr_spec; { Hyperspectral image } file_LUT : array[1..2]of string; { Lookup tables } const { Files and directories specified in WASI.INI} Name_LdBatch : String = 'd:\frei\*.fwd'; { Spectra inverted in batch mode } DIR_saveFwd : String = 'd:\frei'; { Directory for saving forward calculations } DIR_saveInv : String = 'd:\frei'; { Directory for saving invers calculations } DIR_saveFit : String = 'd:\frei'; { Directory for saving image fits } { General settings and parameters specified in WASI.INI } MinX : integer = 100; { lowest x-value allowed for data import and calculation } MaxX : integer = 1000; { highest x-value allowed for data import and calculation } MinDX : double = 0.1; { lowest dx-value allowed for calculation } MinY : double = -100; { lowest y-value allowed for display } MaxY : double = 100000; { highest y-value allowed for display } xu : double = 395.0; { lowest x-coordinate displayed } xo : double = 905.0; { highest x-coordinate displayed } yu : double = 0.0; { lowest y-coordinate displayed } yo : double = 3.0; { highest y-coordinate displayed } xub : double = 300.0; { lowest x-coordinate calculated } xob : double = 950.0; { highest x-coordinate calculated } dxb : double = 1.0; { wavelength interval for calculation } dsmpl : integer = 1; { resampling distance (channels); 0 = no resampling } dxs : integer = 2; { interval for saving data (channels) } FWHM0 : single = 3.0; { spectral resolution (nm) } FWHM0_min : single = 1.0; { lowest allowed spectral resolution (nm) } FWHM0_max : single = 50.0; { highest allowed spectral resolution (nm) } dotsize : word = 3; { size of plotted dots } dotMaxN : word = 100; { max. number of data points to plot dots } PopupDirW : integer = 600; { width of popup window 'directories' } Ed_factor : double = 3.1415926; { multiplicator of E_down spectrum } E0_factor : double = 0.10; { multiplicator of E0 spectrum } Rrs_factor : double = 0.319; { multiplicator of R_rs spectrum } spec_type : spec_types = S_Rrs; { type of spectrum: 0 = E_d 1 = L_up 2 = R_rs 3 = R 4 = R_surf 5 = a 6 = K_d 7 = R_bottom 8 = Test 9 = Ed_Gege } Model_Ed : byte = 1; { Ed model: 0 = without separation direct / diffuse 1 = with separation direct / diffuse } Model_R : byte = 0; { R model: 0 = Gordon, 1 = Prieur } Model_R_rsA : byte = 0; { R_rs model above water surface: 0 = function of R_rs(0-) 1 = function of R 2 = function of both } Model_R_rsB : byte = 0; { R_rs model below water surface: 0 = f_rs * bb / (a+bb) 1 = f_rs * bb / a 2 = R / Q } Model_f : byte = 4; { f model: 0 = const. 1 = Kirk (1984) 2 = Morel & Gentili (1991) 3 = Sathyendranath + Platt (1997) 4 = Albert & Mobley (2003) } Model_f_rs : byte = 0; { f_rs model: 0 = Albert & Mobley (2003) 1 = f / Q } Model_Kdd : byte = 0; { K_dd model: 0 = Gege (2012) 1 = Grötsch (Diploma thesis } bottom_fill : ShortInt = -1; { bottom surface type adjusted to yield sum weights = 1} clPlotBk : TColor = $00E1FFFF; { color of plot background } clMaskImg : TColor = $00000000; { color of image mask } { Flags specified in WASI5.INI: 0 = FALSE, 1 = TRUE } flag_SubGrid : boolean = FALSE; { draw subgrid? } flag_Grid : boolean = TRUE; { draw grid? } flag_Dots : boolean = TRUE; { draw dots? } flag_Autoscale : boolean = TRUE; { autoscale plot? } flag_showFile : boolean = TRUE; { display filename? } flag_showPath : boolean = FALSE; { display path? } flag_leg_left : boolean = FALSE; { Adjust parameter legend left } flag_leg_top : boolean = TRUE; { Adjust parameter legend top } flag_INI : boolean = FALSE; { save INI file automatically? } flag_sv_table : boolean = FALSE; { save forward-spectra as table? } flag_save_t : boolean = TRUE; { save calculation time? } flag_mult_Ed : boolean = TRUE; { multiply E_down with Ed_factor? } flag_mult_E0 : boolean = TRUE; { multiply E0 with E0_factor? } flag_mult_Rrs : boolean = TRUE; { multiply R_rs with Rrs_factor? } flag_x_file : boolean = FALSE; { read x-values from file? } flag_fwhm : boolean = FALSE; { use sensor resolution? } flag_read_day : boolean = FALSE; { Read day of year angle from file? } flag_read_sun : boolean = FALSE; { Read sun zenith angle from file? } flag_read_view : boolean = FALSE; { Read viewing angle from file? } flag_read_dphi : boolean = FALSE; { Read azimuth difference between sun and viewing angle from file? } flag_sun_unit : boolean = TRUE; { sun zenith angle in deg? } Par1_log : boolean = FALSE; { Parameter 1 of batch mode: logarithmic? } Par2_log : boolean = FALSE; { Parameter 2 of batch mode: logarithmic? } Par3_log : boolean = FALSE; { Parameter 3 of batch mode: logarithmic? } flag_batch : boolean = TRUE; { batch mode (including forward mode)? } flag_bunt : boolean = TRUE; { change color when calculating a series of spectra } flag_b_SaveFwd : boolean = FALSE; { save all spectra of forward mode? } flag_b_SaveInv : boolean = FALSE; { save all spectra of invers mode? } flag_b_LoadAll : boolean = FALSE; { batch mode: load all spectra? } flag_b_Reset : boolean = FALSE; { batch mode: reset start values? } flag_b_Invert : boolean = FALSE; { batch mode: invert spectra? } flag_avg_err : boolean = TRUE; { reconstruction mode: save average errors? } flag_multi : boolean = FALSE; { multiple spectra in single file? } flag_Res_log : boolean = FALSE; { weight residuals logarithmically? } flag_Y_exp : boolean = TRUE; { exponential Gelbstoff absorption? } flag_surf_inv : boolean = TRUE; { wavelength dependent surface reflections? } flag_surf_fw : boolean = TRUE; { wavelength dependent surface reflections? } flag_fluo : boolean = TRUE; { include fluorescence of chl-a } flag_MP : boolean = FALSE; { apply melt pond models } flag_use_Ed : boolean = TRUE; { make use of Ed measurement } flag_use_Ls : boolean = FALSE; { make use of Ls measurement } flag_use_R : boolean = TRUE; { make use of R measurement } flag_radiom : boolean = FALSE; { reduce radiometric resolution } flag_offset : boolean = FALSE; { add measurement offset } flag_offset_c : boolean = FALSE; { offset is constant } flag_scale : boolean = FALSE; { add measurement scale } flag_scale_c : boolean = FALSE; { scale is constant } flag_noise : boolean = FALSE; { add measurement noise } flag_noise_c : boolean = TRUE; { noise is constant? } flag_Tab : boolean = FALSE; { only TAB (#9) separates columns } flag_aW : boolean = TRUE; { include pure water absorption in a-modeling } flag_above : boolean = TRUE; { above water } flag_shallow : boolean = FALSE; { shallow water } flag_L : boolean = TRUE; { type of bottom reflectance (0: albedo, 1: radiance reflectance) } flag_autoiniR : boolean = TRUE; { automatic determination of R start values } flag_anX_R : boolean = TRUE; { analytic X start value for R spectra in deep waters } flag_anX_Rsh : boolean = TRUE; { analytic X start value for R spectra in shallow waters } flag_anCY_R : boolean = TRUE; { analytic C, Y start values for R spectra } flag_anzB : boolean = TRUE; { analytic zB start value } flag_Fresnel_view : boolean = true; { calculate Fresnel reflectance for viewing angle } flag_bX_file : boolean = TRUE; { scattering coeff. of particles Type I from file } flag_bX_linear : boolean = TRUE; { scattering coeff. of particles Type I linear with C_L } flag_CXisC0 : boolean = FALSE; { set C_X = C[0] } flag_norm_NAP : boolean = TRUE; { normalise NAP spectrum from file } flag_norm_Y : boolean = TRUE; { normalise CDOM spectrum from file } { Settings for batch mode } iter_type : integer = 2; { which parameter is iterated: see list of Par3_Type } rangeMin : single = 0.0; { First value of successive calculation } rangeMax : single = 10.0; { Last value of successive calculation } rangeDelta : single = 1.0; { Interval of successive calculation } Par1_Type : integer = 1; { Parameter 1 of batch mode: } Par2_Type : integer = 7; { Parameter 2 of batch mode: } Par3_Type : integer = 0; { Parameter 3 of batch mode: 0 = none 1 = C[0] 2 = C[1] 3 = C[2] 4 = C[3] 5 = C[4] 6 = C[5] 7 = C_X 8 = C_Mie 9 = C_Y 10 = S 11 = n 12 = T_W 13 = Q 14 = fluo 15 = rho_L 16 = rho_dd 17 = rho_ds 18 = beta 19 = alpha 20 = f_dd 21 = f_ds 22 = H_oz 23 = WV 24 = f 25 = z 26 = zB 27 = sun 28 = view 29 = dphi - private 30 = fA[0] 31 = fA[1] 32 = fA[2] 33 = fA[3] 34 = fA[4] 35 = fA[5] 36 = bbs_phy 37 = g_dd 38 = g_dsr 39 = g_dsa 40 = delta_r - private 41 = alpha_d - private 42 = beta_d - private 43 = gamma_d - private 44 = delta_d - private 45 = dummy - private 46 = test - private 47 = alpha_r - - private 48 = beta_r - - private 49 = gamma_r - - private 50 = f_nw } Par1_Min : double = 0.0; { Parameter 1 of batch mode: Minimum } Par2_Min : double = 0.0; { Parameter 2 of batch mode: Minimum } Par3_Min : double = 0.0; { Parameter 3 of batch mode: Minimum } Par1_Max : double = 10.0; { Parameter 1 of batch mode: Maximum } Par2_Max : double = 10.0; { Parameter 2 of batch mode: Maximum } Par3_Max : double = 10.0; { Parameter 3 of batch mode: Maximum } Par1_N : integer = 11; { Parameter 1 of batch mode: Steps } Par2_N : integer = 11; { Parameter 2 of batch mode: Steps } Par3_N : integer = 11; { Parameter 3 of batch mode: Steps } ycol_max : integer = 70; { Max. number of y columns } { Settings for inverse mode } fit_min : array[1..FC]of double = (400, 700, 400, 400); { first wavelength that is fitted } fit_max : array[1..FC]of double = (800, 800, 800, 800); { last wavelength that is fitted } fit_dL : array[1..FC]of byte = (1, 1, 1, 1); { wavelength interval of fit } MaxIter : array[1..FC]of integer = (100, 100, 100, 100); { max. number of iterations } fitsh_min : array[1..FC]of double = (400, 700, 400, 400); { Rsh: first wavelength that is fitted } fitsh_max : array[1..FC]of double = (800, 800, 500, 800); { Rsh: last wavelength that is fitted } fitsh_dL : array[1..FC]of byte = (5, 5, 5, 1); { Rsh: wavelength interval of fit } MaxItersh : array[1..FC]of integer = (100, 100, 100, 100); { Rsh: max. number of iterations } LambdaLf : array[1..2]of double = (800, 900); { wavelengths for C_L and f initialisation } dLambdaLf : array[1..2]of double = (0, 0); { wavelengths intervals for C_L and f initialisation } LambdaLsh : double = 800; { wavelength for C_L initialisation in shallow water } dLambdaLsh : double = 0; { wavelengths interval for C_L initialisation in shallow water} LambdaCY : array[1..3]of double = (412.5, 442.5, 430); { wavelengths for C_P and Y initialisation } dLambdaCY : array[1..3]of double = (0,0,0); { wavelengths intervals for C_P and Y initialisation } LambdazB : double = 650; { wavelength for zB initialisation } dLambdazB : double = 50; { wavelength interval for zB initialisation } zB_inimin : double = 0.1; { minimum during initial value determination of zB } CL_inimin : double = 0.1; { minimum during initial value determination of C_L for shallow water } C0_inimin : double = 0.1; { minimum during initial value determination of C[0] for shallow water } CY_inimin : double = 0.01; { minimum during initial value determination of C_Y for shallow water } a_ini : double = 5.0; { start value of absorption (C[0]+C_Y) for nested interval during initial determination } da_ini : double = 1.0; { step of absorption (C[0]+C_Y) for nested interval during initial determination } delta_min : double = 0.01; { threshold of spectrum change for nested intervals } SfA_min : double = 0.5; { minimum sum of fA[i] } SfA_max : double = 2; { maximum sum of fA[i] } res_max : double = 9e-5; { maximum allowed residuum } res_mode : byte = 0; { 0 = least squares, 1 = absolute differences, 2 = relative differences, 3 = spectral angle } { Model constants defined in WASI.INI } day : integer = 100; { Day of year } T_W0 : double = 20.0; { Reference temperature of water in °C } nW : double = 1.33; { Refractive index of water } Lambda_a : double = 550; { Reference wavelength for aerosol optical thickness (nm) } Lambda_0 : single = 440.0; { Reference wavelength for Gelbstoff and detritus absorption } Lambda_L : double = 550.0; { Reference wavelength for scattering of particles Type I } Lambda_S : double = 500.0; { Reference wavelength for scattering of particles Type II } Lambda_f0 : double = 685.0; { Wavelength of chl-a fluorescence (nm) } Sigma_f0 : double = 10.6; { Stddev. of chl-a fluorescence (nm) } Q_a : double = 0.5; { Portion of emitted fluorescence not reabsorbed within the cell } PAR_min : integer = 400; { PAR range: lower boundary (nm) } PAR_max : integer = 700; { PAR range: upper boundary (nm) } Lmin : integer = 400; { Spectrum average: lower boundary (nm) } Lmax : integer = 800; { Spectrum average: upper boundary (nm) } aNAP440 : double = 0.027; { Specific absorption coefficient of NAP (m^2/g) } bbW500 : double = 0.00111; { Backscattering coefficient of pure water } bbX_A : double = 0.0006; { Factor A in backscattering to concentration relationship } bbX_B : double = -0.37; { Factor B in backscattering to concentration relationship } bb_ice : double = 10; { Backscattering coefficient of ice (m^-1) } bb_X : double = 0.0086; { spec. backsc. coeff. of particles Type I } bb_Mie : double = 0.01; { spec. backsc. coeff. of particles Type II } b_X : double = 0.45; { spec. scattering coeff. of particles Type I } b_Mie : double = 0.3; { spec. scattering coeff. of particles Type II } rho0 : double = 0.05825; { rho_ds polynomial: 0th order value } rho1 : double = 0.04405; { rho_ds polynomial: 1st order value } rho2 : double = 0.1722; { rho_ds polynomial: 2nd order value } rho_Eu : double = 0.54; { Reflection factor for upwelling irradiance } rho_Ed : double = 0.03; { Reflection factor for downwelling irradiance } rho_Lu : double = 0.02; { Reflection factor for upwelling radiance } dynamics : double = 0.001; { radiometric resolution } offset_c : double = 0.0001; { constant measurement offset } scale_c : double = 1.0; { constant measurement scale factor } noise_std : double = 0.0001; { noise level (standard deviation) } ldd : double = 1.0; { path length factor of direct irradiance } ldda : double = 0.0; { path length factor of direct irradiance } lddb : double = 0.0; { path length factor of direct irradiance } lds0 : double = 1.139; { path length factor of diffuse irradiance } lds1 : double = 0.5715; { path length factor of diffuse irradiance } ld : double = 1.0546; { path length factor for Ed } ldd_ice : double = 1.0; { Relative path length of direct radiation in ice } Q_ice_p : double = 6.3; { Anisotropy factor of downwelling radiation at top of ice layer } Q_ice_m : double = 1.68; { Anisotropy factor of downwelling radiation at bottom of ice layer } BRDF : array[0..5]of double { BRDF of bottom surface #n } = (0.31, 0.31, 0.31, 0.31, 0.31, 0.31); { Parameters of 2D module defined in WASI.INI } flag_bk_2D : boolean = FALSE; { Invert 2D data in background mode (1=TRUE) } flag_3bands : boolean = TRUE; { Preview 3 bands / 1 band } flag_LUT : boolean = TRUE; { Use lookup table } flag_JoinBands : boolean = FALSE; { Identical scaling for 3 preview bands } flag_ENVI : boolean = TRUE; { Read ENVI header file } flag_use_ROI : boolean = FALSE; { Analyse image for region of interest } flag_scale_ROI : boolean = FALSE; { Scale image for region of interest } Width_in : word = 500; { Input image width } Height_in : word = 400; { Input image height } Channels_in : word = 87; { Input image channels } Channels_out : word = 1; { Output image channels } HSI_header : word = 0; { Input image header bytes } frame_min : word = 0; { First line of processed image } frame_max : word = 0; { Last line of processed image; 0: all lines } pixel_min : word = 0; { First column of processed image } pixel_max : word = 0; { Last column of processed image; 0: all columns } band_R : word = 11; { Preview band red } band_G : word = 7; { Preview band green } band_B : word = 2; { Preview band blue } band_mask : word = 15; { Preview band of mask } interleave_in : byte = 0; { Input image interleave: 0=BIL, 1=BSQ, 2=BIP } interleave_out : byte = 0; { Output image interleave: 0=BIL, 1=BSQ, 2=BIP } Datentyp : byte = 2; { Input image data type: 1 = 8-bit byte 2 = 16-bit signed integer 3 = 32-bit signed long integer 4 = 32-bit floating point 7 = text 12 = 16-bit unsigned integer } x_scale : single = 1; { Scale factor of x-axis } y_scale : single = 1; { Scale factor of y-axis } thresh_below : single = 0.0; { Mask threshold min } thresh_above : single = 0.001; { Mask threshold max } Plot2D_delta : integer = 10; { interval to plot spectrum } contrast : single = 1.0; { Preview image contrast } Par0_Type : integer = 26; { Preview parameter during inversion } Par0_Min : double = 0.0; { Preview parameter min } Par0_Max : double = 6.0; { Preview parameter max } N_avg : integer = 15; { Averaged pixels for parameter initialization } { Model parameters defined in WASI.INI } var C : array[0..5]of Fitparameters; { Concentration of phytoplankton } C_X : Fitparameters; { Concentration of suspended particles Type I } C_Mie : Fitparameters; { Concentration of suspended particles Type II } bbs_phy : Fitparameters; { Specific backscattering coefficient of phytoplankton (m^2/mg)} C_Y : Fitparameters; { Gelbstoff absorption } S : Fitparameters; { Gelbstoff exponent } n : Fitparameters; { Angström exponent of particle scattering } T_W : Fitparameters; { Water temperature (°C) } Q : Fitparameters; { Q-factor (1/sr) } rho_dd : Fitparameters; { reflection factor of Edd } rho_L : Fitparameters; { Fresnel reflection at the water surface } rho_ds : Fitparameters; { Reflectance factor of Eds } beta : Fitparameters; { Turbidity coefficient } alpha : Fitparameters; { Angström exponent of aerosol scattering } f_nw : Fitparameters; { Fraction of non-water area } f_dd : Fitparameters; { Fraction of direct irradiance } f_ds : Fitparameters; { Fraction of diffuse irradiance } H_oz : Fitparameters; { Ozone scale height } WV : Fitparameters; { Precipitable water } f : Fitparameters; { f-factor of R } z : Fitparameters; { depth } zB : Fitparameters; { bottom depth } sun : Fitparameters; { sun zenith angle } view : Fitparameters; { view zenith angle } dphi : Fitparameters; { azimuth difference sun - view } fA : array[0..5]of Fitparameters; { bottom albedo fractions } fluo : Fitparameters; { chl-a fluorescence quantum yield } g_dd : Fitparameters; { Reflected fraction of sky irradiance due to direct solar radiation} g_dsr : Fitparameters; { Reflected fraction of sky irradiance due to Rayleigh scattering } g_dsa : Fitparameters; { Reflected fraction of sky irradiance due to aerosol scattering } dummy : Fitparameters; { NOT USED } { **************************************************************************** } { *********** Program internal settings *********** } { **************************************************************************** } const { Model constants } Lambda_R : double = 534.10; { Scaling factor for Rayleigh scattering } Lambda_M : double = 549.66; { Scaling factor for Mie scattering } T0 : double = 20.0; { Temperature of water absorption spectrum } { Constants of the shallow water model of Albert (2004) } fp1 : double = 0.1034; { f-parameter p1 } fp2 : double = 3.3586; { f-parameter p2 } fp3 : double = -6.5358; { f-parameter p3 } fp4 : double = 4.6638; { f-parameter p4 } fp5 : double = 2.4121; { f-parameter p5 } frsp1 : double = 0.0512; { frs-parameter p1 } frsp2 : double = 4.6659; { frs-parameter p2 } frsp3 : double = -7.8387; { frs-parameter p3 } frsp4 : double = 5.4571; { frs-parameter p4 } frsp5 : double = 0.1098; { frs-parameter p5 } frsp7 : double = 0.4021; { frs-parameter p7 } K1W : double = 1.9991; { shallow water coefficient of KuW for R } K2W : double = 0.2995; { shallow water coefficient of KuW for R } K1B : double = 1.2441; { shallow water coefficient of KuB for R } K2B : double = 0.5182; { shallow water coefficient of KuB for R } K1Wrs : double = 3.5421; { shallow water coefficient of KuW for Rrs } K2Wrs : double = -0.2786; { shallow water coefficient of KuW for Rrs } K1Brs : double = 2.2658; { shallow water coefficient of KuB for Rrs } K2Brs : double = 0.0577; { shallow water coefficient of KuB for Rrs } A1 : double = 1.0546; { shallow water coefficient of R } A2 : double = 0.9755; { shallow water coefficient of R } A1rs : double = 1.1576; { shallow water coefficient of Rrs } A2rs : double = 1.0389; { shallow water coefficient of Rrs } { Constants of the irradiance model of Gregg & Carder (1990) } GC_M : double = 1.15; { air mass } GC_P : double = 1013.25; { air pressure (mbar) } omega_a : double = 1.13; { single scattering albedo } F_a : double = 0.9; { aerosol forward scattering probability } H_a : double = 1.0; { aerosol scale height (km) } AM : byte = 1; { air mass type } RH : double = 60; { relative humidity (%) } M_oz : double = 1; { ozone path length (cm) } const { Files and directories } CHANGES : string = 'CHANGES.TXT'; { File with changing parameters } FITPARS = 'FITPARS.TXT'; { File with fitted parameters } FW_TABLE : string = 'SPEC'; { Filename of table with spectra in forward mode } SCREENSHOT : string = 'WASI_plot.png'; { Filename of plot screenshot } WASI_IMG : string = 'WASI_img.png'; { Filename of image screenshot } path_resampl = 'data\resample\'; { Path with resampled spectra } path_exe : string = 'd:\wasi5\'; { Path of WASI.EXE } EXT_FWD : String = 'fwd'; { Extension of spectra from forward calculation } EXT_INV : String = 'inv'; { Extension of spectra from invers calculation } EXT_PAR : String = 'par'; { Extension of parameter file } ActualFile : String = ''; { Name of actual file } { File header info and data format } XText : String = 'Wavelength (nm)'; { Text of x-axis } YText : String = ''; { Text of y-axis } line_sun : integer = 10; { Line with sun zenith angle } col_sun : integer = 5; { Column with sun zenith angle } line_day : integer = 7; { Line with day of year } col_day : integer = 2; { Column with day of year } line_view : integer = 10; { Line with viewing angle } col_view : integer = 5; { Column with viewing angle } line_dphi : integer = 10; { Line with azimuth difference angle } col_dphi : integer = 5; { Column with azimuth difference angle } { Constants for screen layout } GUI_scale : double = 1; { Scale factor of GUI size } GUI_Height : integer = 704; { Height of WASI GUI (pixels) } GUI_Width : integer = 992; { Width of WASI GUI (pixels) } DX_par : integer = 315; { Width of parameter panel (pixels) } DX_leg : integer = 70; { Width of legend (pixels) } DX_right : integer = 16; { Distance of right border (pixels) } DY_par : integer = 552; { Height of parameter panel (pixels) } DY_Gege : integer = 114; { Extra height for parameters of Gege's Ed model } DY_leg : integer = 64; { Height of legend (pixels); is calcuated } DY_top : integer = 48; { Distance of top border (pixels) } DY_modes : integer = 170; { Height of modi panel(pixels); is calculated } DY_batch : integer = 130; { Distance of fw mode panel(pixels) } DY_bottom : integer = 6; { Distance of bottom border (pixels) } tu_ofs : integer = 20; { Offset fuer Achsenbeschriftung unten } to_ofs : integer = 6; { Offset fuer Achsenbeschriftung unten } tl_ofs : integer = 40; { Offset fuer Achsenbeschriftung links } roh = 8; { Rahmenoffset horizontal } rov = 8; { Rahmenoffset vertikal } ZwischenX = 5; { Zwischenstriche x-Achse } SIG = 3; { signifikante Stellen } label_X = 8; { length of x-labels } label_Y = 6; { length of y-labels } Text_X = 12; { distance of x-axis text } Text_y = 10; { distance of x-axis text } { Constants used for program operation } N_spectypes = 10; { number of spectrum types } MaxSpectra = 130; { max. number of output spectra } p_Ed : integer = 1; { percentage of remaining irradiance } nenner_min = 1.0e-12; { avoid division by zero } exp_min = -100; { lowest exponent } exp_max = 30; { highest exponent } FWHM_sigma = 2.355; { conversion FWHM --> sigma for Gauss curve } var { Model parameters calculated during run-time } Chl_a : double; { Chlorophyll-a concentration } sun_earth : double; { correction factor of E0 for sun-earth distance } I0 : double = 100; { Integral of solar constant } sz_cos : double; { Cosine of sun zenith angle } { Parameters used for program operation } Nspectra : integer = 0; { Number of output spectra } S_actual : integer = 1; { actual no. of output spectrum } TimeCalc : double = 0; { Calculation time in seconds } TimeStartCalc : TDateTime; { Start time of calculation } farbS : array[1..MaxSpectra]of TColor; { colours of spectra } c1 : double; { iterated parameter #1 } c2 : double; { iterated parameter #2 } c3 : double; { iterated parameter #3 } ABBRUCH : boolean; { stop processing after ^C } { Parameters used for inverse mode } flag_fit_running : boolean = FALSE; { fit is running } flag_Simpl_ini : boolean = TRUE; { initialize Simplex } fit_dk : integer = 1; { difference between fitted channels } N_fit_bot : integer = 0; { Number of bottom types which are fitted } NIter : Integer; { number of iterations needed } Resid : double; { residuum } SAngle : double; { spectral angle } fileChanges : text; fileFitpars : text; ch_fit_min : array[1..4]of integer; { first channel that is fitted } ch_fit_max : array[1..4]of integer; { last channel that is fitted } FIT : byte; { 1 = Ed (deep), a (shallow) 2 = r1_IR, Lup_IR 3 = r1_UV, Lup_UV 4 = r1, Lup, a } { Parameters used for analytic calculation of sensor depth for irradiance measurement} LambdaRN : double = 680; { wavelength for ratio calculation; Nenner } LambdaRZ : double = 800; { wavelength for ratio calculation; Zaehler } dLambdaRN : double = 5; { wavelengths interval for ratio calculation: Nenner } dLambdaRZ : double = 5; { wavelengths interval for ratio calculation: Nenner } var { Spectra calculated during run-time } xx : ^Attr_spec; { temporary x-values } bbW : ^Attr_spec; { Backscattering coefficient of pure water } bMie : ^Attr_spec; { Scattering coeff. of particles type II } bbMie : ^Attr_spec; { Backscattering coeff. of particles type II } GC_T_o2 : ^Attr_spec; { Transmittance of the atmosphere after oxygene absorption } GC_T_o3 : ^Attr_spec; { Transmittance of the atmosphere after ozone absorption } GC_T_wv : ^Attr_spec; { Transmittance of the atmosphere after water vapor absorption } GC_tau_a : ^Attr_spec; { Aerosol optical thickness } GC_T_r : ^Attr_spec; { Transmittance of the atmosphere after Rayleigh scattering } GC_T_as : ^Attr_spec; { Transmittance of the atmosphere after aerosol scattering } GC_T_aa : ^Attr_spec; { Transmittance of the atmosphere after aerosol absorption } Ed0 : ^Attr_spec; { Downwelling irradiance just beneath water surface } GC_Edd : ^Attr_spec; { Direct component of downwelling irradiance } GC_Eds : ^Attr_spec; { Diffuse component of downwelling irradiance } GC_Edsr : ^Attr_spec; { Diffuse component of Ed caused by Rayleigh scattering } GC_Edsa : ^Attr_spec; { Diffuse component of Ed caused by aerosol scattering } r_d : ^Attr_spec; { Ratio of direct to diffuse Ed component } Lu : ^Attr_spec; { Upwelling radiance } Lr : ^Attr_spec; { Radiance reflected from the surface } Lf : ^Attr_spec; { Fluorescence radiance } Kdd : ^Attr_spec; { Attenuation for direct downwelling irradiance } Kds : ^Attr_spec; { Attenuation for diffuse downwelling irradiance } KE_uW : ^Attr_spec; { attenuation of E reflected in water } KE_uB : ^Attr_spec; { attenuation of E reflected at bottom } kL_uW : ^Attr_spec; { attenuation of L reflected in water } kL_uB : ^Attr_spec; { attenuation of L reflected at bottom } z_Ed : ^Attr_spec; { depth at which p_Ed % of surface irradiance remains } r_rs : ^Attr_spec; { Radiance reflectance } Rrs : ^Attr_spec; { Remote sensing reflectance } Rrs_surf : ^Attr_spec; { Surface reflectance } Rrsf : ^Attr_spec; { Fluorescence radiance reflectance } f_R : ^Attr_spec; { Scaling factor of irradiance reflectance } f_rs : ^Attr_spec; { Scaling factor of radiance reflectance } Q_f : ^Attr_spec; { Q derived from f_R and f_rs } bottom : ^Attr_spec; { bottom albedo } a : ^Attr_spec; { Absorption coefficient of water layer } b : ^Attr_spec; { Scattering coefficient of water layer } bb : ^Attr_spec; { Backscattering coefficient of water layer } a_calc : ^Attr_spec; { calculated absorption spectrum } aP_calc : ^Attr_spec; { calculated phytoplankton absorption } aNAP_calc : ^Attr_spec; { calculated NAP absorption } aCDOM_calc : ^Attr_spec; { calculated CDOM absorption } b_calc : ^Attr_spec; { calculated scattering spectrum } bb_calc : ^Attr_spec; { calculated backscattering spectrum } bb_phy : ^Attr_spec; { phytoplankton backscattering coefficient } bb_NAP : ^Attr_spec; { NAP backscattering coefficient } omega_b : ^Attr_spec; { w_b = bb/(a+bb) or bb/a } Stest : ^Attr_spec; { Test spectrum } // Spectra for simulation of meltponds MP_ro : Attr_spec; { Reflectance of ocean under ice surface (sr^-1)} MP_RRo : Attr_spec; { Reflectance of ocean above ice surface (sr^-1) } MP_ri : Attr_spec; { Reflectance of ice in ice layer (sr^-1) } MP_ri_inf : Attr_spec; { Reflectance of optically thick ice (sr^-1) } MP_RRi : Attr_spec; { Reflectance of ice above ice layer (sr^-1) } MP_rp : Attr_spec; { Reflectance of pond under water surface (sr^-1) } MP_RRp : Attr_spec; { Reflectance of pond above water surface (sr^-1) } MP_tau_io : Attr_spec; { Transmission of boundary ice - ocean } MP_tau_pi : Attr_spec; { Transmission of boundary pond - ice } MP_tau_ap : Attr_spec; { Transmission of boundary air - pond } MP_a_i : Attr_spec; { Absorption coefficient of ice layer (m^-1)} MP_bb_i : Attr_spec; { Backscattering coefficient of ice layer } MP_Kd_i : Attr_spec; { Irradiance extinction coefficient for ice (m^-1) } MP_ku_i : Attr_spec; { Radiance extinction coefficient for ice (m^-1) } MP_Td_i : Attr_spec; { Irradiance transmission coefficient for ice } MP_tu_i : Attr_spec; { Radiance transmission coefficient for ice } MP_p_ice : Attr_spec; { Path length ratio in ice } MP_lds_ice : Attr_spec; { Relative path length of diffuse radiation in ice } MP_Kd_p : Attr_spec; { Irradiance extinction coefficient for melt pond (m^-1) } MP_ku_p : Attr_spec; { Radiance extinction coefficient for melt pond (m^-1) } MP_Td_p : Attr_spec; { Irradiance transmission coefficient for pond } MP_tu_p : Attr_spec; { Radiance transmission coefficient for pond } MP_rp_inf : Attr_spec; { Reflectance of optically thick pond (sr^-1) } MP_frsi : Attr_spec; { Scaling factor of radiance reflectance of ice (sr^-1) } MP_fi : Attr_spec; { Scaling factor of irradiance reflectance of ice } MP_ui : Attr_spec; { Gordon's IOP of ice } MP_Qi : Attr_spec; { Anisotropy factor of upwelling radiation in ice (sr) } var { Parameters required for reconstruction mode } acc_N : integer; { Number of spectra in batch mode } acc_iter : LongInt; { Number of iterations } acc_resid : double; { sum of residuums } acc_fill : double; { fill factor } acc_fills : double; { sum of fill factors } acc_iterM : LongInt; { maximum number of iterations } acc_residM : double; { maximum sum of residuums } acc_fillM : double; { fill factor } acc_fillsM : double; { sum of fill factors } acc_fsum : array[1..3]of double; { Sum of forward calculated parameters in batch mode } acc_fmax : array[1..3]of double; { Maximum of forward calculated parameters in batch mode } acc_isum : array[1..M1]of double; { Sum of inverted parameters in batch mode } acc_imax : array[1..M1]of double; { Maximum of inverted parameters in batch mode } acc_esum : array[1..M1]of double; { Sum of relative errors } acc_emax : array[1..M1]of double; { Maximum of relative errors } { Parameters required for program operation } spec : array[1..MaxSpectra]of ^Attr_spec; par : param; { Model parameters of inverse mode } error_INI : byte; { 0: ok, 1: file not found, 2:error } error_file : byte; { 0: ok, 1: y constant, 2: <3 y-values, 3: error in file, 4: file not found } error_msg : String; { error message } Channel_number : integer; { actual number of channels } xfile_xu : single; { first x-value of x-file } xfile_xo : single; { last x-value of x-file } xfile_dx : single; { x-interval of x-file } var { Flags } flag_Legend : boolean = TRUE; { draw legend? } flag_clear : boolean = TRUE; { clear old plot? } flag_del_rsmpl : boolean = FALSE; { delete resampled spectra? } flag_Fresnel_sun : boolean = TRUE; { calculate Fresnel reflectance for sun angle? } flag_Background : boolean = FALSE; { Run program in background mode? } flag_loadFile : boolean = FALSE; { measurement imported from file? } flag_panel_fw : boolean = TRUE; { panel shows fw-values? } flag_calc_rho_ds : boolean = TRUE; { calculate rho_ds from sun zenith angle? } { **************************************************************************************** } { *********** Program internal settings of 2D module *********** } { **************************************************************************************** } const { Constants of 2D module } ENVI_Keys = 12; { Number of supported ENVI header keywords } name_progress = '/PROGRESS.TXT'; { File name of progress log file } { Constants for screen layout of 2D module } img_dX : integer = 0; { x-position of image } img_dY : integer = 0; { y-position of image } scale_dY = 50; { height of scale and text } RGB_left : integer = 60; { x-position of RGB label } RGB_top : integer = 5; { y-position of RGB label } RGB_width : integer = 150; { width of RGB label } RGB_height : integer = 20; { height of RGB label } mean_R : double = 0; { mean residuum } type { Type definitions of 2D module } line_bool = array of boolean; line_byte = array of byte; { data line, data type #1 } line_int16 = array of smallInt; { data line, data type #2 } line_int32 = array of integer; { data line, data type #3 } line_single = array of single; { data line, data type #4 } line_word = array of word; { data line, data type #12 } frame_bool = array of line_bool; frame_byte = array of line_byte; { data frame, data type #1 } frame_int16 = array of line_int16; { data frame, data type #2 } frame_int32 = array of line_int32; { data frame, data type #3 } frame_single = array of line_single; { data frame, data type #4 } frame_word = array of line_word; { data frame, data type #12 } cube_single = array of frame_single; { hyperspectral data cube } var { Parameters of 2D module used during runtime } HSI_width : qword; { Width of HSI image } Np_masked : qword; { Number of masked pixels } Np_water : qword; { Number of water pixels to be processed } cube_HSI4 : cube_single; { data cube of 4 bands (RGB, mask) } cube_fitpar : cube_single; { result: fit parameters } HSI_byte : line_byte; HSI_int16 : line_int16; HSI_int32 : line_int32; HSI_single : line_single; HSI_word : line_word; WaterMask : frame_bool; { mask: FALSE = no water, TRUE = water } channel_R : frame_byte; { preview: red channel } channel_G : frame_byte; { preview: green channel } channel_B : frame_byte; { preview: blue channel } x_FName : String; { filename of wavelength file } x_flag : boolean; { temporary flag_x_file } fwhm_flag : boolean; { temporary flag_fwhm } bandname : array[1..MaxChannels]of string; { band names } dpX, dpF : integer; { size of ROI } x_Header : integer; x_Xcol : byte; x_Ycol : byte; max_R : double; { maximum signal of red band } max_G : double; { maximum signal of green band } max_B : double; { maximum signal of blue band } lox, rux : integer; { x-coordinates of selected rectangle } loy, ruy : integer; { y-coordinates of selected rectangle } Output_HSI : string; LUT_R, LUT_G, LUT_B : array[1..2, 0..255]of byte; { look up tables } flag_2D_inv : boolean = FALSE; { invert HSI image? } flag_preview : boolean = FALSE; { preview image exists } flag_update_prv : boolean = FALSE; { update preview image } flag_Plot2D : boolean = TRUE; { plot actual spectrum } flag_map : boolean = FALSE; { display geographical coordinates } flag_extract : boolean = FALSE; { spectrum 'spec' was extracted from image } flag_avg : boolean = FALSE; { spectra 'spec' are averages of image pixels } flag_merk_batch : boolean = FALSE; flag_merk_b_Invert : boolean = FALSE; flag_merk_b_LoadAll : boolean = FALSE; flag_HSI_wv : boolean = TRUE; { Channels of HSI image are wavelength } map_N0 : double = 0; { coordinate North of first pixel } map_E0 : double = 0; { coordinate East of first pixel } map_dN : double = 0; { pixel size North } map_dE : double = 0; { pixel size East } map_sinr : double = 0; { Sinus of image rotation angle } map_cosr : double = 1; { Cosinus of image rotation angle } map_SIG : integer = 3; { significant digits for coordinate display } map_info : string = ''; { map info } HSI_Stream : TFileStream; { Hyperspectral image file } HSI_old : string = ''; { Filename of previously loaded image file } file_lambda : string = 'lambda.txt'; { Wavelength file } ENVI_Keyword : array[1..ENVI_Keys]of string = { Keywords of ENVI header file } ('samples', 'lines', 'bands', 'header offset', 'data type', 'interleave', 'wavelength units =', 'wavelength =', 'fwhm', 'default bands', 'map info', 'band names'); VIP_no : integer = 26; { very important parameter number } VIP_min : double = 1; { very important parameter initialization minimum } VIP_max : double = 6; { very important parameter initialization maximum } implementation begin {$IFDEF private_version} flag_public:=FALSE; { $ELSE flag_MP:=FALSE; } {$ENDIF} end.
unit ICDconst; interface const CST_INI_CRITERIA: string = 'choléra'; CST_INI_SEARCH_NUMBER: integer = 10; CST_CONNEXION_STRING: string = 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=testICD;Data Source=DEV-DANY'; CST_QUERY: string = 'SELECT TOP %d * FROM ICD_10 WHERE %s LIKE %s'; CST_CODE_FIELD: string = 'ICD_10_CODE'; CST_FR_DESC_FIELD: string = 'FR_DESCRIPTION'; CST_NL_DESC_FIELD: string = 'NL_DESCRIPTION'; implementation end.
unit AddPolygonAvoidanceZoneUnit; interface uses SysUtils, BaseExampleUnit, NullableBasicTypesUnit; type TAddPolygonAvoidanceZone = class(TBaseExample) public function Execute: NullableString; end; implementation uses TerritoryContourUnit, AvoidanceZoneUnit, PositionUnit; function TAddPolygonAvoidanceZone.Execute: NullableString; var ErrorString: String; AvoidanceZone: TAvoidanceZone; Territory: TTerritoryContour; NewAvoidanceZone: TAvoidanceZone; TerritoryName, TerritoryColor: String; begin Result := NullableString.Null; TerritoryName := 'Polygon Territory'; TerritoryColor := 'ff0000'; Territory := TTerritoryContour.MakePolygonContour([ TPosition.Create(37.7697528227865, -77.6783325195313), TPosition.Create(37.7588671630534, -77.6897480010986), TPosition.Create(37.7697528227865, -77.6783325195313), TPosition.Create(37.7588671630534, -77.6897480010986), TPosition.Create(37.7476396605445, -77.6917221069336), TPosition.Create(37.7465508430681, -77.6886322021484), TPosition.Create(37.7502255383101, -77.6812507629394), TPosition.Create(37.7479799127443, -77.6749851226806), TPosition.Create(37.7332796020606, -77.6411678314209), TPosition.Create(37.7443051067953, -77.6317264556884), TPosition.Create(37.7664192584704, -77.6684619903564) ]); AvoidanceZone := TAvoidanceZone.Create(TerritoryName, TerritoryColor, Territory); try NewAvoidanceZone := Route4MeManager.AvoidanceZone.Add(AvoidanceZone, ErrorString); try WriteLn(''); if (NewAvoidanceZone <> nil) then begin WriteLn('AddPolygonAvoidanceZone executed successfully'); WriteLn(Format('Territory ID: %s', [NewAvoidanceZone.TerritoryId.Value])); Result := NewAvoidanceZone.TerritoryId; end else WriteLn(Format('AddPolygonAvoidanceZone error: "%s"', [ErrorString])); finally FreeAndNil(NewAvoidanceZone); end; finally FreeAndNil(AvoidanceZone); end; end; end.
unit Gradients; interface uses Graphics; procedure Gradient(Bitmap : TBitmap; horizontal : boolean); implementation procedure Gradient(Bitmap : TBitmap; horizontal : boolean); type TRGBRec = record R : byte; B : byte; G : byte; I : byte; end; var ri : single; gi : single; bi : single; fr : single; fg : single; fb : single; Color : TColor; dist : integer; procedure HorizontalGradient; var i : integer; j : integer; begin for i := 0 to pred(Width) do begin for j := 0 to pred(Height) do fBitmap.Canvas.Pixels[i, j] := Color; with TRGBRec(Color) do begin fr := fr + ri; R := round(fr); fg := fg + gi; G := round(fg); fb := fb + bi; B := round(fb); end; end; end; procedure VerticalGradient; var i : integer; j : integer; begin for j := 0 to pred(Height) do begin for i := 0 to pred(Width) do fBitmap.Canvas.Pixels[i, j] := Color; with TRGBRec(Color) do begin fr := fr + ri; R := round(fr); fg := fg + gi; G := round(fg); fb := fb + bi; B := round(fb); end; end; end; begin if horizontal then dist := fBitmap.Width else dist := fBitmap.Height; if dist > 0 then begin ri := (TRGBRec(fToColor).R - TRGBRec(fFromColor).R)/dist; gi := (TRGBRec(fToColor).G - TRGBRec(fFromColor).G)/dist; bi := (TRGBRec(fToColor).B - TRGBRec(fFromColor).B)/dist; Color := fFromColor; with TRGBRec(Color) do begin fr := R; fg := G; fb := B; end; if horizontal then HorizontalGradient else VerticalGradient; end; end; end.