text
stringlengths
14
6.51M
unit GX_IdeEnhance; {$I GX_CondDefine.inc} interface uses Classes, Graphics, ComCtrls, Menus, GX_MultiLinePalette, GX_MultilineHost, GX_IdeFormEnhancer; type TIdeEnhancements = class(TObject) private // Fonts FOIFont: TFont; FOldOIFont: TFont; FOIFontEnabled: Boolean; FOICustomFontNames: Boolean; // File saving FAutoSave: Boolean; FAutoSaveInterval: Integer; // Menus {$IFDEF VER150} // Delphi 7 only procedure SetCPTabSelectButton(Value: Boolean); procedure TabSelectButtonClick(Sender: TObject); {$ENDIF VER150} procedure SetAutoSave(const Value: Boolean); procedure SetAutoSaveInterval(const Value: Integer); procedure SetOIFont(Value: TFont); procedure SetOIFontEnabled(Value: Boolean); procedure OIFontChange(Sender: TObject); procedure SetOICustomFontNames(const Value: Boolean); private // Component palette FCPMultiLine: Boolean; FCPHotTracking: Boolean; FCPAsButtons: Boolean; FCPRaggedRight: Boolean; FCPScrollOpposite: Boolean; FCPFlatButtons: Boolean; FCPTabsInPopup: Boolean; FCPTabsInPopupAlphaSort: Boolean; FOldCPPopupEvent: TNotifyEvent; FCPFontEnabled: Boolean; FCPFont: TFont; FOldCPFont: TFont; FMultiLineTabDockHostManager: TGxMultiLineTabDockHostsManager; FMultiLineTabManager: TMultiLineTabManager; procedure InstallMultiLineComponentTabs; procedure RemoveMultiLineComponentTabs; procedure AddTabsToPopup(Sender: TObject); procedure DeleteCPPopupMenuItems(Popup: TPopupMenu); procedure SetActiveTab(Sender: TObject); procedure SetCPMultiLine(Value: Boolean); procedure SetCPAsButtons(Value: Boolean); procedure SetCPTabsInPopup(Value: Boolean); procedure SetCPTabsInPopupAlphaSort(Value: Boolean); procedure InstallMultiLineHostTabs; procedure RemoveMultiLineHostTabs; function GetDefaultMultiLineTabDockHost: Boolean; procedure SetDefaultMultiLineTabDockHost(const Value: Boolean); function GetMultiLineTabDockHost: Boolean; procedure SetMultiLineTabDockHost(const Value: Boolean); procedure SetCPFont(Value: TFont); procedure SetCPFontEnabled(Value: Boolean); procedure CPFontChange(Sender: TObject); procedure SetCPFlatButtons(const Value: Boolean); procedure SetCPRaggedRight(const Value: Boolean); procedure SetCPScrollOpposite(const Value: Boolean); procedure Remove; function ConfigurationKey: string; procedure SetEnhanceIDEForms(const Value: Boolean); function GetEnhanceIDEForms: Boolean; function GetEnhanceSearchPath: Boolean; procedure SetEnhanceSearchPath(const Value: Boolean); function GetEnhanceToolProperties: Boolean; procedure SetEnhanceToolProperties(const Value: Boolean); function GetEnhanceInstallPackages: Boolean; procedure SetEnhanceInstallPackages(const Value: Boolean); function GetEnhanceGotoDialog: boolean; procedure SetEnhanceGotoDialog(const Value: Boolean); function GetIdeFormsAllowResize: Boolean; function GetIdeFormsRememberPosition: Boolean; procedure SetIdeFormsAllowResize(const Value: Boolean); procedure SetIdeFormsRememberPosition(const Value: Boolean); public constructor Create; destructor Destroy; override; procedure Initialize; procedure LoadSettings; procedure SaveSettings; // IDE property EnhanceIDEForms: Boolean read GetEnhanceIDEForms write SetEnhanceIDEForms; property IdeFormsAllowResize: Boolean read GetIdeFormsAllowResize write SetIdeFormsAllowResize; property IdeFormsRememberPosition: Boolean read GetIdeFormsRememberPosition write SetIdeFormsRememberPosition; // Install Packages dialog property EnhanceInstallPackages: boolean read GetEnhanceInstallPackages write SetEnhanceInstallPackages; // Search path property EnhanceSearchPath: Boolean read GetEnhanceSearchPath write SetEnhanceSearchPath; // Tool Options dialog property EnhanceToolProperties: Boolean read GetEnhanceToolProperties write SetEnhanceToolProperties; // Goto dialog property EnhanceGotoDialog: Boolean read GetEnhanceGotoDialog write SetEnhanceGotoDialog; // Fonts property OIFontEnabled: Boolean read FOIFontEnabled write SetOIFontEnabled; property OIFont: TFont read FOIFont; property OICustomFontNames: Boolean read FOICustomFontNames write SetOICustomFontNames; // File saving property AutoSave: Boolean read FAutoSave write SetAutoSave; property AutoSaveInterval: Integer read FAutoSaveInterval write SetAutoSaveInterval; property CPFontEnabled: Boolean read FCPFontEnabled write SetCPFontEnabled; property CPFont: TFont read FCPFont; // Component palette property CPMultiLine: Boolean read FCPMultiLine write SetCPMultiLine; property CPHotTracking: Boolean read FCPHotTracking write FCPHotTracking; property CPAsButtons: Boolean read FCPAsButtons write SetCPAsButtons; property CPFlatButtons: Boolean read FCPFlatButtons write SetCPFlatButtons; property CPScrollOpposite: Boolean read FCPScrollOpposite write SetCPScrollOpposite; property CPRaggedRight: Boolean read FCPRaggedRight write SetCPRaggedRight; property CPTabsInPopup: Boolean read FCPTabsInPopup write SetCPTabsInPopup; property CPTabsInPopupAlphaSort: Boolean read FCPTabsInPopupAlphaSort write SetCPTabsInPopupAlphaSort; // Multi-line tab dock host property MultiLineTabDockHost: Boolean read GetMultiLineTabDockHost write SetMultiLineTabDockHost; property DefaultMultiLineTabDockHost: Boolean read GetDefaultMultiLineTabDockHost write SetDefaultMultiLineTabDockHost; end; function IdeEnhancements: TIdeEnhancements; procedure FreeIdeEnhancements; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} {$IFDEF MSWINDOWS} VCLEditors, {$ENDIF MSWINDOWS} {$IFDEF VER150} Controls, Buttons, {$ENDIF VER150} SysUtils, Forms, GX_GenericUtils, GX_GxUtils, GX_IdeUtils, GX_OtaUtils, GX_ConfigurationInfo, GX_IdeSearchPathEnhancer, GX_IdeProjectOptionsEnhancer, GX_IdeToolPropertiesEnhancer, GX_IdeInstallPackagesEnhancer, GX_IdeGotoEnhancer; { TIdeEnhancements } constructor TIdeEnhancements.Create; begin {$IFOPT D+} SendDebug('TIdeEnhancements.Create'); {$ENDIF} inherited Create; if IsStandAlone then Exit; FOIFont := TFont.Create; FOIFont.OnChange := OIFontChange; FCPFont := TFont.Create; FCPFont.OnChange := CPFontChange; end; procedure TIdeEnhancements.Initialize; begin Assert(Application.MainForm <> nil, 'No MainForm found'); {$IFOPT D+} SendDebug('Installing IDE Enhancements and loading settings'); {$ENDIF} LoadSettings; {$IFOPT D+} SendDebug('Loaded IDE Enhancement settings'); {$ENDIF} if CPMultiLine then InstallMultiLineComponentTabs; end; procedure TIdeEnhancements.Remove; begin EnhanceIDEForms := False; // MultiLine component palette CPMultiLine := False; CPAsButtons := False; CPHotTracking := False; CPTabsInPopup := False; CPTabsInPopupAlphaSort := False; // Fonts CPFontEnabled := False; RemoveMultiLineComponentTabs; RemoveMultiLineHostTabs; OIFontEnabled := False; // Don't call SaveSettings after this point end; procedure TIdeEnhancements.SetEnhanceIDEForms(const Value: Boolean); begin TIDEFormEnhancements.SetEnabled(Value); end; procedure TIdeEnhancements.SetEnhanceInstallPackages(const Value: Boolean); begin TGxIdeInstallPackagesEnhancer.SetEnabled(Value); end; procedure TIdeEnhancements.SetEnhanceSearchPath(const Value: Boolean); begin TGxIdeSearchPathEnhancer.SetEnabled(Value); TGxIdeProjectOptionsEnhancer.SetEnabled(Value); end; procedure TIdeEnhancements.SetEnhanceToolProperties(const Value: Boolean); begin TGxIdeToolPropertiesEnhancer.SetEnabled(Value); end; procedure TIdeEnhancements.SetEnhanceGotoDialog(const Value: Boolean); begin TGxIdeGotoEnhancer.SetEnabled(Value); end; procedure TIdeEnhancements.SetIdeFormsAllowResize(const Value: Boolean); begin TIDEFormEnhancements.SetAllowResize(Value); end; procedure TIdeEnhancements.SetIdeFormsRememberPosition(const Value: Boolean); begin TIDEFormEnhancements.SetRememberPosition(Value); end; destructor TIdeEnhancements.Destroy; begin if IsStandAlone then Exit; Remove; FreeAndNil(FOIFont); FreeAndNil(FCPFont); inherited Destroy; end; procedure TIdeEnhancements.LoadSettings; var Settings: TGExpertsSettings; ExpSettings: TExpertSettings; begin Assert(ConfigInfo <> nil, 'No ConfigInfo found'); // do not localize any of the below items ExpSettings := nil; Settings := TGExpertsSettings.Create; try ExpSettings := Settings.CreateExpertSettings(ConfigurationKey); EnhanceIDEForms := ExpSettings.ReadBool('EnhanceIDEForms', False); IdeFormsAllowResize := ExpSettings.ReadBool('IdeFormsAllowResize', False); IdeFormsRememberPosition := ExpSettings.ReadBool('IdeFormsRememberPosition', False); EnhanceSearchPath := ExpSettings.ReadBool('EnhanceSearchPath', False); EnhanceToolProperties := ExpSettings.ReadBool('EnhanceToolProperties', False); EnhanceInstallPackages := ExpSettings.ReadBool('EnhanceInstallPackages', False); EnhanceGotoDialog := ExpSettings.ReadBool('EnhanceGotoDialog', False); // File saving AutoSave := ExpSettings.ReadBool('AutoSave', False); AutoSaveInterval := ExpSettings.ReadInteger('AutoSaveInterval', 5); // Fonts ExpSettings.LoadFont('OIFont', OIFont); OIFontEnabled := ExpSettings.ReadBool('EnableOIFont', False); OICustomFontNames := ExpSettings.ReadBool('OICustomFontNames', False); // Component palette CPFontEnabled := ExpSettings.ReadBool('EnableCPFont', False); ExpSettings.LoadFont('CPFont', CPFont); CPMultiLine := ExpSettings.ReadBool('CPMultiLine', False); CPScrollOpposite := ExpSettings.ReadBool('CPScrollOpposite', False); CPRaggedRight := ExpSettings.ReadBool('CPRaggedRight', False); CPFlatButtons := ExpSettings.ReadBool('CPFlatButtons', False); CPAsButtons := ExpSettings.ReadBool('CPAsButtons', False); CPTabsInPopup := ExpSettings.ReadBool('CPTabsInPopup', False); CPTabsInPopupAlphaSort := ExpSettings.ReadBool('CPTabsInPopupAlphaSort', False); CPHotTracking := ExpSettings.ReadBool('CPHotTracking', False); // MultiLine tab dock host MultiLineTabDockHost := ExpSettings.ReadBool('MultiLineTabDockHost', False); DefaultMultiLineTabDockHost := ExpSettings.ReadBool('DefaultMultiLineTabDockHost', True); finally FreeAndNil(ExpSettings); FreeAndNil(Settings); end; end; procedure TIdeEnhancements.SaveSettings; var Settings: TGExpertsSettings; ExpSettings: TExpertSettings; begin Assert(ConfigInfo <> nil, 'No ConfigInfo found'); // do not localize any of the below items ExpSettings := nil; Settings := TGExpertsSettings.Create; try ExpSettings := Settings.CreateExpertSettings(ConfigurationKey); ExpSettings.WriteBool('EnhanceIDEForms', EnhanceIDEForms); ExpSettings.WriteBool('IdeFormsAllowResize', IdeFormsAllowResize); ExpSettings.WriteBool('IdeFormsRememberPosition', IdeFormsRememberPosition); ExpSettings.WriteBool('EnhanceSearchPath', EnhanceSearchPath); ExpSettings.WriteBool('EnhanceToolProperties', EnhanceToolProperties); ExpSettings.WriteBool('EnhanceInstallPackages', EnhanceInstallPackages); ExpSettings.WriteBool('EnhanceGotoDialog', EnhanceGotoDialog); // File saving ExpSettings.WriteBool('AutoSave', AutoSave); ExpSettings.WriteInteger('AutoSaveInterval', AutoSaveInterval); // Fonts ExpSettings.WriteBool('EnableOIFont', OIFontEnabled); ExpSettings.WriteBool('OICustomFontNames', OICustomFontNames); ExpSettings.SaveFont('OIFont', OIFont); // Component palette ExpSettings.SaveFont('CPFont', CPFont); ExpSettings.WriteBool('EnableCPFont', CPFontEnabled); ExpSettings.WriteBool('CPTabsInPopupAlphaSort', CPTabsInPopupAlphaSort); ExpSettings.WriteBool('CPTabsInPopup', CPTabsInPopup); ExpSettings.WriteBool('CPMultiLine', CPMultiLine); ExpSettings.WriteBool('CPScrollOpposite', CPScrollOpposite); ExpSettings.WriteBool('CPRaggedRight', CPRaggedRight); ExpSettings.WriteBool('CPHotTracking', CPHotTracking); ExpSettings.WriteBool('CPAsButtons', CPAsButtons); ExpSettings.WriteBool('CPFlatButtons', CPFlatButtons); // MultiLine tab dock host ExpSettings.WriteBool('MultiLineTabDockHost', MultiLineTabDockHost); ExpSettings.WriteBool('DefaultMultiLineTabDockHost', DefaultMultiLineTabDockHost); finally FreeAndNil(ExpSettings); FreeAndNil(Settings); end; end; procedure TIdeEnhancements.AddTabsToPopup(Sender: TObject); var CPPopupMenu: TPopupMenu; procedure AddPopupMenuItems; var StartInsertingAt: Integer; i: Integer; Menu: TMenuItem; TabNames: TStringList; TabControl: TTabControl; begin Menu := TMenuItem.Create(nil); Menu.Caption := '-'; Menu.Tag := -1; Menu.Name := 'GX_PopupSeparator'; CPPopupMenu.Items.Add(Menu); StartInsertingAt := CPPopupMenu.Items.Count; TabControl := GetComponentPaletteTabControl; if TabControl <> nil then begin TabNames := TStringList.Create; try for i := 0 to TabControl.Tabs.Count - 1 do TabNames.AddObject(TabControl.Tabs[i], TObject(i)); if CPTabsInPopupAlphaSort then TabNames.Sort; for i := 0 to TabControl.Tabs.Count - 1 do begin Menu := TMenuItem.Create(nil); Menu.Caption := TabNames[i]; Menu.Tag := -1; Menu.Name := 'GX_Palette' + IntToStr(Integer(TabNames.Objects[i])); Menu.RadioItem := True; Menu.GroupIndex := 99; Menu.Checked := Integer(TabNames.Objects[i]) = TabControl.TabIndex; Menu.OnClick := SetActiveTab; // This allows a max of 20 tabs per column. Not perfect, but // still nicer than menu items disappearing off the screen. if (i > 0) and ((StartInsertingAt + i - 1) mod 20 = 0) then Menu.Break := mbBarBreak; CPPopupMenu.Items.Add(Menu) end; finally FreeAndNil(TabNames); end; end; end; begin if (Sender = nil) or (not (Sender is TPopupMenu)) then Exit; CPPopupMenu := TPopupMenu(Sender); DeleteCPPopupMenuItems(CPPopupMenu); if Assigned(FOldCPPopupEvent) then FOldCPPopupEvent(Sender); AddPopupMenuItems; end; procedure TIdeEnhancements.DeleteCPPopupMenuItems(Popup: TPopupMenu); var i: Integer; Menu: TMenuItem; begin i := 0; while i <= Popup.Items.Count - 1 do begin if Popup.Items[i].Tag = -1 then begin Menu := Popup.Items[i]; Popup.Items.Delete(i); FreeAndNil(Menu); end else Inc(i); end; end; procedure TIdeEnhancements.SetActiveTab(Sender: TObject); var TabControl: TTabControl; Tab: string; i: Integer; begin TabControl := GetComponentPaletteTabControl; if TabControl <> nil then begin Tab := TMenuItem(Sender).Caption; // Compensate for AutoHotKeys Tab := StringReplace(Tab, '&', '', [rfReplaceAll]); for i := 0 to TabControl.Tabs.Count - 1 do if TabControl.Tabs[i] = Tab then begin TabControl.TabIndex := i; TabControl.OnChange(TabControl); Break; end; end; end; procedure TIdeEnhancements.SetAutoSave(const Value: Boolean); begin // Do something here FAutoSave := Value; end; procedure TIdeEnhancements.SetAutoSaveInterval(const Value: Integer); begin // Do something here FAutoSaveInterval := Value; end; { --- Window menu enhancement --- } procedure TIdeEnhancements.SetCPMultiLine(Value: Boolean); var CPTabControl: TTabControl; begin {$IFOPT D+} SendDebug('Setting multiline palette to ' + BooleanText(Value)); {$ENDIF} if FCPMultiLine <> Value then begin FCPMultiLine := Value; CPTabControl := GetComponentPaletteTabControl; if CPTabControl = nil then begin {$IFOPT D+} SendDebug('Unable to reset OldCPResizeHandler (no tab control)'); {$ENDIF} Exit; end; if FCPMultiLine then InstallMultiLineComponentTabs else RemoveMultiLineComponentTabs; end; end; procedure TIdeEnhancements.SetCPFlatButtons(const Value: Boolean); var TabControl: TTabControl; begin if FCPFlatButtons <> Value then begin FCPFlatButtons := Value; TabControl := GetComponentPaletteTabControl; if TabControl = nil then Exit; if CPAsButtons then begin if FCPFlatButtons then TabControl.Style := tsFlatButtons else TabControl.Style := tsButtons; end; end; end; procedure TIdeEnhancements.SetCPAsButtons(Value: Boolean); var TabControl: TTabControl; begin if FCPAsButtons <> Value then begin FCPAsButtons := Value; TabControl := GetComponentPaletteTabControl; if TabControl = nil then Exit; {$IFOPT D+} SendDebug('Removing CP Buttons'); {$ENDIF} if Value then begin if CPFlatButtons then TabControl.Style := tsFlatButtons else TabControl.Style := tsButtons; end else TabControl.Style := tsTabs; end; end; procedure TIdeEnhancements.SetCPRaggedRight(const Value: Boolean); var TabControl: TTabControl; begin if FCPRaggedRight <> Value then begin FCPRaggedRight := Value; TabControl := GetComponentPaletteTabControl; if TabControl = nil then Exit; TabControl.RaggedRight := FCPRaggedRight; end; end; procedure TIdeEnhancements.SetCPScrollOpposite(const Value: Boolean); var TabControl: TTabControl; begin TabControl := GetComponentPaletteTabControl; if Assigned(TabControl) then begin if Value <> TabControl.ScrollOpposite then TabControl.ScrollOpposite := Value; FCPScrollOpposite := TabControl.ScrollOpposite; end; end; procedure TIdeEnhancements.SetCPTabsInPopupAlphaSort(Value: Boolean); begin if FCPTabsInPopupAlphaSort <> Value then FCPTabsInPopupAlphaSort := Value; end; {$IFDEF VER150} procedure TIdeEnhancements.TabSelectButtonClick(Sender: TObject); var Button: TSpeedButton; MainForm: TCustomForm; begin if Sender is TSpeedButton then begin Button := TSpeedButton(Sender); MainForm := GetIdeMainForm; if not Assigned(Button.PopupMenu) and Assigned(MainForm) then begin Button.PopupMenu := TPopupMenu.Create(MainForm); Button.PopupMenu.OnPopup := AddTabsToPopup; end; if Assigned(Button.PopupMenu) then Button.PopupMenu.Popup(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; end; procedure TIdeEnhancements.SetCPTabSelectButton(Value: Boolean); const ButtonName = 'GXTabSelectButton'; var MainForm: TCustomForm; Button: TSpeedButton; begin if Value then begin // Create CP select button MainForm := GetIdeMainForm; if not Assigned(MainForm) then Exit; if MainForm.FindComponent(ButtonName) <> nil then Exit; Button := TSpeedButton.Create(MainForm); Button.Align := alRight; Button.Width := 18; Button.Caption := '...'; Button.Name := ButtonName; Button.Parent := GetComponentPaletteTabControl; Button.OnClick := TabSelectButtonClick; end else begin // Remove CP select button MainForm := GetIdeMainForm; if not Assigned(MainForm) then Exit; Button := TSpeedButton(MainForm.FindComponent(ButtonName)); FreeAndNil(Button); end; end; procedure TIdeEnhancements.SetCPTabsInPopup(Value: Boolean); begin if FCPTabsInPopup <> Value then begin FCPTabsInPopup := Value; SetCPTabSelectButton(Value); end; end; {$ELSE not VER150} procedure TIdeEnhancements.SetCPTabsInPopup(Value: Boolean); var CPPopupMenu: TPopupMenu; begin if FCPTabsInPopup <> Value then begin FCPTabsInPopup := Value; CPPopupMenu := GetComponentPalettePopupMenu; if CPPopupMenu = nil then Exit; if Value then begin FOldCPPopupEvent := CPPopupMenu.OnPopup; CPPopupMenu.OnPopup := AddTabsToPopup; end else CPPopupMenu.OnPopup := FOldCPPopupEvent; end; end; {$ENDIF not VER150} procedure TIdeEnhancements.SetOIFont(Value: TFont); var OIForm: TCustomForm; begin OIForm := GetObjectInspectorForm; if OIForm <> nil then begin if FOldOIFont = nil then begin FOldOIFont := TFont.Create; FOldOIFont.Assign(OIForm.Font); end; OIForm.Font.Assign(Value) end; end; procedure TIdeEnhancements.SetOIFontEnabled(Value: Boolean); begin if FOIFontEnabled <> Value then begin FOIFontEnabled := Value; if Value then SetOIFont(OIFont) else if FOldOIFont <> nil then begin SetOIFont(FOldOIFont); FreeAndNil(FOldOIFont); end; end; end; procedure TIdeEnhancements.OIFontChange(Sender: TObject); begin {$IFOPT D+} SendDebug('OI font changed'); {$ENDIF} if OIFontEnabled then SetOIFont(OIFont); end; procedure TIdeEnhancements.SetCPFont(Value: TFont); var CPTabControl: TTabControl; begin CPTabControl := GetComponentPaletteTabControl; if CPTabControl <> nil then begin if FOldCPFont = nil then begin FOldCPFont := TFont.Create; FOldCPFont.Assign(CPTabControl.Font); end; CPTabControl.Font.Assign(Value) end; end; procedure TIdeEnhancements.SetCPFontEnabled(Value: Boolean); begin if FCPFontEnabled <> Value then begin FCPFontEnabled := Value; if Value then SetCPFont(CPFont) else if FOldCPFont <> nil then begin SetCPFont(FOldCPFont); FreeAndNil(FOldCPFont); end; end; end; procedure TIdeEnhancements.CPFontChange(Sender: TObject); begin {$IFOPT D+} SendDebug('CP font changed'); {$ENDIF} if CPFontEnabled then SetCPFont(CPFont); end; procedure TIdeEnhancements.InstallMultiLineComponentTabs; begin if GetComponentPaletteTabControl = nil then Exit; if FMultiLineTabManager = nil then FMultiLineTabManager := TMultiLineTabManager.Create(GetIdeMainForm); end; procedure TIdeEnhancements.RemoveMultiLineComponentTabs; begin FreeAndNil(FMultiLineTabManager); end; procedure TIdeEnhancements.SetDefaultMultiLineTabDockHost(const Value: Boolean); begin GX_MultilineHost.DefaultToMultiLine := Value; end; function TIdeEnhancements.GetDefaultMultiLineTabDockHost: Boolean; begin Result := GX_MultilineHost.DefaultToMultiLine; end; function TIdeEnhancements.GetEnhanceGotoDialog: boolean; begin Result := TGxIdeGotoEnhancer.GetEnabled; end; function TIdeEnhancements.GetEnhanceIDEForms: Boolean; begin Result := TIDEFormEnhancements.GetEnabled; end; function TIdeEnhancements.GetEnhanceInstallPackages: Boolean; begin Result := TGxIdeInstallPackagesEnhancer.GetEnabled; end; function TIdeEnhancements.GetEnhanceSearchPath: Boolean; begin Result := TGxIdeSearchPathEnhancer.GetEnabled; end; function TIdeEnhancements.GetEnhanceToolProperties: Boolean; begin Result := TGxIdeToolPropertiesEnhancer.GetEnabled; end; function TIdeEnhancements.GetIdeFormsAllowResize: Boolean; begin Result := TIDEFormEnhancements.GetAllowResize; end; function TIdeEnhancements.GetIdeFormsRememberPosition: Boolean; begin Result := TIDEFormEnhancements.GetRememberPosition; end; function TIdeEnhancements.GetMultiLineTabDockHost: Boolean; begin Result := (FMultiLineTabDockHostManager <> nil); end; procedure TIdeEnhancements.SetMultiLineTabDockHost(const Value: Boolean); begin if Value then InstallMultiLineHostTabs else RemoveMultiLineHostTabs; end; procedure TIdeEnhancements.InstallMultiLineHostTabs; begin if MultilineTabDockHostPossible and (FMultiLineTabDockHostManager = nil) then FMultiLineTabDockHostManager := TGxMultiLineTabDockHostsManager.Create; end; procedure TIdeEnhancements.RemoveMultiLineHostTabs; begin FreeAndNil(FMultiLineTabDockHostManager); end; procedure TIdeEnhancements.SetOICustomFontNames(const Value: Boolean); begin {$IFDEF MSWINDOWS} FontNamePropertyDisplayFontNames := Value; {$ENDIF MSWINDOWS} FOICustomFontNames := Value; end; function TIdeEnhancements.ConfigurationKey: string; begin Result := 'IDEEnhancements'; end; // Internal Singleton management code var PrivateIdeEnhancements: TIdeEnhancements = nil; CanCreate: Boolean = True; function IdeEnhancements: TIdeEnhancements; begin {$IFOPT D+} SendDebug('Calling IdeEnhancements'); {$ENDIF D+} Assert(CanCreate, 'CanCreate not set'); if PrivateIdeEnhancements = nil then PrivateIdeEnhancements := TIdeEnhancements.Create; Result := PrivateIdeEnhancements; end; procedure FreeIdeEnhancements; begin {$IFOPT D+} SendDebug('FreeIdeEnhancements'); {$ENDIF D+} CanCreate := False; FreeAndNil(PrivateIdeEnhancements); end; initialization {$IFOPT D+} SendDebug('Initializing IDE enhancements unit'); {$ENDIF D+} finalization FreeIdeEnhancements; end.
unit GX_SetFocusControl; interface implementation uses Classes, ActnList, Menus, Windows, Controls, StdCtrls, Contnrs, Types, Math, ToolsAPI, GX_Experts, GX_GExperts, GX_OtaUtils; type TGxSetFocusControlExpert = class(TGX_Expert) protected procedure UpdateAction(Action: TCustomAction); override; public constructor Create; override; class function GetName: string; override; function GetActionCaption: string; override; function HasConfigOptions: Boolean; override; function HasDesignerMenuItem: Boolean; override; procedure Execute(Sender: TObject); override; end; TLabelHack = class(TCustomLabel); { TGxSetFocusControlExpert } constructor TGxSetFocusControlExpert.Create; begin inherited; //ShortCut := Menus.ShortCut(Word('F'), [ssShift, ssCtrl]); end; function TGxSetFocusControlExpert.GetActionCaption: string; resourcestring SMenuCaption = 'Set &FocusControl'; begin Result := SMenuCaption; end; class function TGxSetFocusControlExpert.GetName: string; begin Result := 'SetFocusControl'; end; function TGxSetFocusControlExpert.HasConfigOptions: Boolean; begin Result := False; end; function TGxSetFocusControlExpert.HasDesignerMenuItem: Boolean; begin Result := True; end; procedure TGxSetFocusControlExpert.UpdateAction(Action: TCustomAction); begin Action.Enabled := GxOtaCurrentlyEditingForm; end; procedure TGxSetFocusControlExpert.Execute(Sender: TObject); var Form: IOTAFormEditor; FirstControlSelected: Boolean; procedure SetFocusControl(ALabel: TCustomLabel; AControl: TWinControl; Force: Boolean); var OTALabel: IOTAComponent; begin if Force or (TLabelHack(ALabel).FocusControl = nil) then begin TLabelHack(ALabel).FocusControl := AControl; OTALabel := Form.FindComponent(ALabel.Name); if Assigned(OTALabel) then OTALabel.Select(FirstControlSelected); FirstControlSelected := True; end; end; function ProcessFixed: Boolean; var Component1, Component2: TComponent; begin if Form.GetSelCount = 2 then begin Component1 := GxOtaGetNativeComponent(Form.GetSelComponent(0)); Component2 := GxOtaGetNativeComponent(Form.GetSelComponent(1)); if (Component1 is TCustomLabel) and (Component2 is TWinControl) then SetFocusControl(TCustomLabel(Component1), TWinControl(Component2), True) else if (Component2 is TCustomLabel) and (Component1 is TWinControl) then SetFocusControl(TCustomLabel(Component2), TWinControl(Component1), True); end; Result := FirstControlSelected; end; function LabelDistance(ALabel: TCustomLabel; AControl: TWinControl): Integer; begin if (ALabel.Left > (AControl.Left + AControl.Width)) or (ALabel.Top > (AControl.Top + AControl.Height)) then Result := MaxInt else Result := Max(Abs(AControl.Left - ALabel.Left), Abs(AControl.Top - ALabel.Top)); end; function LabelInControlRange(ALabel: TCustomLabel; AControl: TWinControl): Boolean; var Intersection: TRect; LeftRect, TopRect: TRect; const LeftDistLimit = 130; TopDistLimit = 30; begin LeftRect := Rect(AControl.Left - LeftDistLimit, AControl.Top, AControl.Left, AControl.Top + AControl.Height); TopRect := Rect(AControl.Left, AControl.Top - TopDistLimit, AControl.Left + AControl.Width, AControl.Top); Result := IntersectRect(Intersection, ALabel.BoundsRect, LeftRect) or IntersectRect(Intersection, ALabel.BoundsRect, TopRect); end; function FindNearestLabel(AControl: TWinControl; Labels: TComponentList; out ResultLabel: TCustomLabel): Boolean; var LeastDistance, Distance: Integer; i: Integer; ALabel: TCustomLabel; begin ResultLabel := nil; Result := False; LeastDistance := MaxInt; for i := 0 to Labels.Count - 1 do begin ALabel := TCustomLabel(Labels[i]); if ALabel.Parent = AControl.Parent then begin Distance := LabelDistance(ALabel, AControl); if LabelInControlRange(ALabel, AControl) and ((Distance < LeastDistance) or ((Distance = LeastDistance) and Assigned(ResultLabel) and (ALabel.Top > ResultLabel.Top))) then begin LeastDistance := Distance; ResultLabel := ALabel; Result := True; end; end; end; end; procedure ProcessAutomatic; var Labels, Controls: TComponentList; Force: Boolean; i: Integer; ALabel: TCustomLabel; AControl: TWinControl; begin Labels := TComponentList.Create(False); Controls := TComponentList.Create(False); try GxOtaGetComponentList(Form, Labels, TCustomLabel); if (Form.GetSelCount = 0) or GxOtaSelectedComponentIsRoot(Form) then GxOtaGetComponentList(Form, Controls, TWinControl) else GxOtaGetSelectedComponents(Form, Controls, TWinControl); Force := GetKeyState(VK_SHIFT) < 0; for i := 0 to Controls.Count - 1 do begin AControl := TWinControl(Controls[i]); if AControl.TabStop and (not (AControl is TButtonControl)) then if FindNearestLabel(AControl, Labels, ALabel) then SetFocusControl(ALabel, AControl, Force); end; finally Labels.Free; Controls.Free; end; end; begin Form := GxOtaGetCurrentFormEditor; FirstControlSelected := False; if not ProcessFixed then ProcessAutomatic; end; initialization RegisterGX_Expert(TGxSetFocusControlExpert); end.
unit uTesteuConstantes; interface uses DUnitX.TestFramework, uConstantes; type [TestFixture] TTesteuConstantes = class(TObject) public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] [TestCase('PROTOCOLO', PROTOCOLO)] [TestCase('DOMINIO', DOMINIO)] [TestCase('SITE_OFICIAL', SITE_OFICIAL)] [TestCase('RADIUS_SUB_DOMINIO', RADIUS_SUB_DOMINIO)] [TestCase('RADIUS_URL_ATUALIZACAO', RADIUS_URL_ATUALIZACAO)] [TestCase('RADIUS_ARQUIVO_WEB_ATUALIZACAO', RADIUS_ARQUIVO_WEB_ATUALIZACAO)] [TestCase('RADIUS_WEB_SERVICE_ATUALIZACAO', RADIUS_WEB_SERVICE_ATUALIZACAO)] [TestCase('RADIUS_URL_SUPORTE', RADIUS_URL_SUPORTE)] [TestCase('RADIUS_ARQUIVO_WEB_SUPORTE', RADIUS_ARQUIVO_WEB_SUPORTE)] [TestCase('RADIUS_WEB_SERVICE_SUPORTE', RADIUS_WEB_SERVICE_SUPORTE)] [TestCase('RADIUS_BUILD', RADIUS_BUILD)] procedure testeConstantePreenchidas(const constante:string); [Test] [TestCase('DOMINIO', DOMINIO)] [TestCase('SITE_OFICIAL', SITE_OFICIAL)] [TestCase('RADIUS_SUB_DOMINIO', RADIUS_SUB_DOMINIO)] procedure testeEnderecosValidos(const endereco:string); [Test] procedure testeConexaoPrincipal(); end; implementation uses internet; procedure TTesteuConstantes.Setup; begin end; procedure TTesteuConstantes.TearDown; begin end; procedure TTesteuConstantes.testeConexaoPrincipal; begin Assert.IsTrue(conexaoSistema <> nil, 'Conexão não instanciada!'); end; procedure TTesteuConstantes.testeConstantePreenchidas(const constante:string); begin Assert.IsNotEmpty(constante); end; procedure TTesteuConstantes.testeEnderecosValidos(const endereco:string); begin Assert.IsTrue(checkUrl(endereco)); end; initialization TDUnitX.RegisterTestFixture(TTesteuConstantes); end.
unit UAccessConstant; interface const { Directory default name } csDefUserDir='U'; csDefDomainDir='D'; csDefJournalDir='J'; csDefGroupDir='G'; csDefADGroupDir='A'; { Default filenames } csTemplateMain='main.tpl'; csContainerCfg='container.cfg'; csClientData='clientdata.cds'; csWorkGroupsLst='workgroups.lst'; csWorkADGroupsLst='workgadroups.lst'; csManagersList='managers.pwd'; csTCPLog='ip.log'; { Tables filename } csTableDomains = 'domains.dbf'; //Домены csTableFiles = 'files.dbf'; //Настройки к файлам csTableFilesReverse='rfiles.dbf'; csTableGroups = 'groups.dbf'; //Группы доступа csTableADGroups = 'adgroups.dbf'; //Группы доступа csTableIni = 'ini.dbf'; //Настройки к ini-файлам csTableOULink = 'ou-links.dbf'; //Связи орг.модулей csTableOU = 'orgunit.dbf'; //Орг.модули (подразделения) csTableProjects = 'projects.dbf'; //Проекты (программы) csTableUsers = 'users.dbf'; //Пользователи csTableExt = 'extens.dbf'; csTableAction = 'actions.dbf'; csTableSupport = 'support.dbf'; { Indexes filename } csUsersSIDIndex='users_sid.ntx'; csIndexFilePriority='file_prio.ntx'; csIndexFilePriorityR='rfile_prio.ntx'; csIndexDomainVersion='dom_vers.ntx'; csIndexDomainName='dom_name.ntx'; csIndexADGroupVersion='adg_vers.ntx'; csIndexADGroupName='adg_name.ntx'; csIndexGroupVersion='grp_vers.ntx'; csIndexGroupName='grp_name.ntx'; csIndexUserVersion='usr_vers.ntx'; csIndexUserName='usr_name.ntx'; csIndexExtensExt='ext_ext.ntx'; { Fields name} csFieldCaption = 'NAME'; csFieldChild='CHILD'; csFieldDescription = 'DESCR'; csFieldDomain='DOMAIN'; csFieldID = 'ID'; csFieldFID = 'FID'; csFieldIni='INIPATH'; csFieldParent='PARENT'; csFieldPath='FILEPATH'; csFieldPrority='PRIORITY'; csFieldSID = 'SID'; csFieldVersion = 'VERSION'; csFieldClntFile='CLNTFILE'; csFieldSrvrFile='SRVRFILE'; csFieldType='TYPE'; csFieldExt='EXT'; csFieldAction='ACTION'; csFieldMD5='MD5'; csFieldSource='SOURCE'; csFieldSAMAccount='sAMAccountName'; csFieldADDescription='description'; csFieldCN='CN'; csFieldDisting='distinguishedName'; { ini-files } csIniUsers='users'; csIniGroups='groups'; csIniADGroups='adgroups'; { errors} csOpenError='Ошибка открытия '; csSaveError='Ошибка сохранения '; csFLockError='Unable FLock table! '; csTableCreateError='Table create error! '; csIndexCreateError='Index create error! '; { Others } csPattern='pattern'; csDefaultUser = 'DEFAULT'; csNotFound='!!! NOT FOUND !!!'; implementation end.
unit Unit1; interface type {接口} IEat = interface function Eating():Integer; end; TDog = class(TInterfacedObject,IEat) public function Eating():Integer; end; TCat = class(TInterfacedObject,IEat) private FEat:IEat; public {利用属性Eat委托实现IEat接口,Eat必须是IEat的类型了。实际中将实现了IEat接口的类赋值给Eat即可, 也就是多态,继承了接口的类可以赋值给接口变量} property Eat:IEat read FEat write FEat implements IEat; end; implementation { TDog } function TDog.Eating: Integer; begin Writeln('狗吃东西'); end; end.
unit SelectLenderDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, TCWODT; type TSelectLenderDialog = class(TComponent) private { Private declarations } FSelectedLender: string; FAutoSelectSingle: boolean; FLenderCount: integer; FCaption: string; procedure SetAutoSelectSingle(const Value: boolean); procedure SetCaption(const Value: string); protected { Protected declarations } public { Public declarations } function Execute(ADaapi:IDaapiGlobal; ALenderGroup:string; ALastLender:string):boolean; property SelectedLender:string read FSelectedLender; property LenderCount:integer read FLenderCount; published { Published declarations } property AutoSelectSingle:boolean read FAutoSelectSingle write SetAutoSelectSingle; property Caption:string read FCaption write SetCaption; end; procedure Register; implementation uses SelectLenderForm, ffsutils; procedure Register; begin RegisterComponents('FFS Dialogs', [TSelectLenderDialog]); end; { TSelectLenderDialog } function TSelectLenderDialog.Execute(ADaapi: IDaapiGlobal; ALenderGroup: string; ALastLender: string): boolean; var frmLend : TfrmSelectLender; vlist : TStringList; DoDlg : boolean; begin fselectedLender := ''; vlist := TStringList.create; try doDlg := false; vlist.commatext := ADaapi.LendGrpGetListByName(ALenderGroup); FLenderCount := vlist.Count; // case of 0 if vlist.count = 0 then begin result := false; MsgInformation('There are not any lenders available for the current user. Check with the system administrator.'); end else doDlg := true; // if single then check for auto select if (vlist.count = 1) and (AutoSelectSingle) then begin FSelectedLender := vlist[0]; result := true; doDlg := false; end; // if there is a list then present it if doDlg then begin frmLend := TfrmSelectLEnder.create(Self, ADaapi, ALenderGroup, ALastLender); try if not empty(FCaption) then frmLend.caption := FCaption; if frmLend.showmodal = mrOk then begin fSelectedLender := frmLend.grdLender.cells[frmLend.CollNumber,frmLend.grdLender.Row]; result := true; end else result := false; finally frmLend.free; end; end; finally vlist.free; end; end; procedure TSelectLenderDialog.SetAutoSelectSingle(const Value: boolean); begin FAutoSelectSingle := Value; end; procedure TSelectLenderDialog.SetCaption(const Value: string); begin FCaption := Value; end; end.
unit evNative_AttrValues; {* Локализуемые значения атрибутов значений тегов таблицы тегов evNative } // Модуль: "w:\common\components\gui\Garant\Everest\evNative_AttrValues.pas" // Стереотип: "UtilityPack" // Элемент модели: "evNative_AttrValues" MUID: (060E2B49C828) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3StringIDEx ; const {* Локализуемые строки AttrValues } str_TextStyle_ToLeft_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ToLeft_Name_Value'; rValue : 'Прижатый влево'); {* Локализуемое значения атрибута TextStyle_ToLeft_Name_Value } str_TextStyle_TxtHeader1_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtHeader1_Name_Value'; rValue : 'Заголовок 1'); {* Локализуемое значения атрибута TextStyle_TxtHeader1_Name_Value } str_TextStyle_TxtHeader2_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtHeader2_Name_Value'; rValue : 'Заголовок 2'); {* Локализуемое значения атрибута TextStyle_TxtHeader2_Name_Value } str_TextStyle_TxtHeader3_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtHeader3_Name_Value'; rValue : 'Заголовок 3'); {* Локализуемое значения атрибута TextStyle_TxtHeader3_Name_Value } str_TextStyle_TxtHeader4_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtHeader4_Name_Value'; rValue : 'Заголовок 4'); {* Локализуемое значения атрибута TextStyle_TxtHeader4_Name_Value } str_TextStyle_NormalNote_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_NormalNote_Name_Value'; rValue : 'Нормальный (справка)'); {* Локализуемое значения атрибута TextStyle_NormalNote_Name_Value } str_TextStyle_TxtComment_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtComment_Name_Value'; rValue : 'Комментарий'); {* Локализуемое значения атрибута TextStyle_TxtComment_Name_Value } {$If NOT Defined(Archi)} str_TextStyle_TxtComment_ShortName_D_Garant_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtComment_ShortName_D_Garant_Value'; rValue : 'ГАРАНТ:'); {* Локализуемое значения атрибута TextStyle_TxtComment_ShortName_D_Garant_Value } {$IfEnd} // NOT Defined(Archi) {$If Defined(Archi)} str_TextStyle_TxtComment_ShortName_D_Archi_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtComment_ShortName_D_Archi_Value'; rValue : ' '); {* Локализуемое значения атрибута TextStyle_TxtComment_ShortName_D_Archi_Value } {$IfEnd} // Defined(Archi) {$If Defined(nsTest) AND Defined(Nemesis) AND NOT Defined(InsiderTest) AND NOT Defined(Archi)} str_TextStyle_TxtComment_ShortName_D_DailyTests_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtComment_ShortName_D_DailyTests_Value'; rValue : 'Комментарий ГАРАНТа:'); {* Локализуемое значения атрибута TextStyle_TxtComment_ShortName_D_DailyTests_Value } {$IfEnd} // Defined(nsTest) AND Defined(Nemesis) AND NOT Defined(InsiderTest) AND NOT Defined(Archi) str_TextStyle_VersionInfo_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_VersionInfo_Name_Value'; rValue : 'Информация о версии'); {* Локализуемое значения атрибута TextStyle_VersionInfo_Name_Value } {$If NOT Defined(Archi)} str_TextStyle_VersionInfo_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_VersionInfo_ShortName_Value'; rValue : 'Информация об изменениях:'); {* Локализуемое значения атрибута TextStyle_VersionInfo_ShortName_Value } {$IfEnd} // NOT Defined(Archi) {$If Defined(Archi)} str_TextStyle_VersionInfo_ShortName_D_Archi_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_VersionInfo_ShortName_D_Archi_Value'; rValue : ' '); {* Локализуемое значения атрибута TextStyle_VersionInfo_ShortName_D_Archi_Value } {$IfEnd} // Defined(Archi) str_TextStyle_PromptTree_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_PromptTree_Name_Value'; rValue : 'Подсказки для контекста'); {* Локализуемое значения атрибута TextStyle_PromptTree_Name_Value } str_TextStyle_HLE1_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE1_Name_Value'; rValue : 'Необходимые документы'); {* Локализуемое значения атрибута TextStyle_HLE1_Name_Value } str_TextStyle_HLE1_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE1_ShortName_Value'; rValue : 'Необходимые документы'); {* Локализуемое значения атрибута TextStyle_HLE1_ShortName_Value } str_TextStyle_HLE2_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE2_Name_Value'; rValue : 'Куда обратиться?'); {* Локализуемое значения атрибута TextStyle_HLE2_Name_Value } str_TextStyle_HLE2_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE2_ShortName_Value'; rValue : 'Куда обратиться?'); {* Локализуемое значения атрибута TextStyle_HLE2_ShortName_Value } str_TextStyle_HLE3_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE3_Name_Value'; rValue : 'Внимание: недобросовестность!'); {* Локализуемое значения атрибута TextStyle_HLE3_Name_Value } str_TextStyle_HLE3_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE3_ShortName_Value'; rValue : 'Внимание: недобросовестность!'); {* Локализуемое значения атрибута TextStyle_HLE3_ShortName_Value } str_TextStyle_HLE4_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE4_Name_Value'; rValue : 'Внимание: криминал!!'); {* Локализуемое значения атрибута TextStyle_HLE4_Name_Value } str_TextStyle_HLE4_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE4_ShortName_Value'; rValue : 'Внимание: криминал!!'); {* Локализуемое значения атрибута TextStyle_HLE4_ShortName_Value } str_TextStyle_HLE5_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE5_Name_Value'; rValue : 'Примечание.'); {* Локализуемое значения атрибута TextStyle_HLE5_Name_Value } str_TextStyle_HLE5_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE5_ShortName_Value'; rValue : 'Примечание.'); {* Локализуемое значения атрибута TextStyle_HLE5_ShortName_Value } str_TextStyle_HLE6_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE6_Name_Value'; rValue : 'Пример.'); {* Локализуемое значения атрибута TextStyle_HLE6_Name_Value } str_TextStyle_HLE6_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HLE6_ShortName_Value'; rValue : 'Пример'); {* Локализуемое значения атрибута TextStyle_HLE6_ShortName_Value } str_TextStyle_HeaderForChangesInfo_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HeaderForChangesInfo_Name_Value'; rValue : 'Заголовок для информации об изменениях'); {* Локализуемое значения атрибута TextStyle_HeaderForChangesInfo_Name_Value } str_TextStyle_FooterForChangesInfo_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_FooterForChangesInfo_Name_Value'; rValue : 'Подвал для информации об изменениях'); {* Локализуемое значения атрибута TextStyle_FooterForChangesInfo_Name_Value } str_TextStyle_TextForChangesInfo_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TextForChangesInfo_Name_Value'; rValue : 'Текст информации об изменениях'); {* Локализуемое значения атрибута TextStyle_TextForChangesInfo_Name_Value } str_TextStyle_ChangesInfo_Header_HeaderC_Text_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ChangesInfo_Header_HeaderC_Text_Value'; rValue : '(информация об изменениях >>)'); {* Локализуемое значения атрибута TextStyle_ChangesInfo_Header_HeaderC_Text_Value } str_TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value'; rValue : 'Открыть справку к документу'); {* Локализуемое значения атрибута TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value } str_TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value'; rValue : 'script:op::enDocument_opGetRelatedDocFrmAct'); {* Локализуемое значения атрибута TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value } str_TextStyle_ChangesInfo_Footer_FooterC_Text_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ChangesInfo_Footer_FooterC_Text_Value'; rValue : 'Подробнее см. в справке к документу'); {* Локализуемое значения атрибута TextStyle_ChangesInfo_Footer_FooterC_Text_Value } str_TextStyle_ChangesInfo_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ChangesInfo_Name_Value'; rValue : 'Информация об изменениях'); {* Локализуемое значения атрибута TextStyle_ChangesInfo_Name_Value } str_TextStyle_ChangesInfo_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ChangesInfo_ShortName_Value'; rValue : 'С изменениями и дополнениями от:'); {* Локализуемое значения атрибута TextStyle_ChangesInfo_ShortName_Value } str_TextStyle_SubHeaderForChangesInfo_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_SubHeaderForChangesInfo_Name_Value'; rValue : 'Подзаголовок для информации об изменениях'); {* Локализуемое значения атрибута TextStyle_SubHeaderForChangesInfo_Name_Value } str_TextStyle_ControlsBlockHeader_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ControlsBlockHeader_Name_Value'; rValue : 'Заголовок группы контролов'); {* Локализуемое значения атрибута TextStyle_ControlsBlockHeader_Name_Value } str_TextStyle_CloakHeader_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_CloakHeader_Name_Value'; rValue : 'Заголовок распахивающейся части диалога'); {* Локализуемое значения атрибута TextStyle_CloakHeader_Name_Value } str_TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value'; rValue : 'Официальная копия графической публикации (Интернет-ссылка)'); {* Локализуемое значения атрибута TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value } str_TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value'; rValue : 'script:op::enDocument_opGetGraphicImage'); {* Локализуемое значения атрибута TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value } str_TextStyle_LinkToPublication_Header_FooterC_Text_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_LinkToPublication_Header_FooterC_Text_Value'; rValue : 'См. графическую копию официальной публикации'); {* Локализуемое значения атрибута TextStyle_LinkToPublication_Header_FooterC_Text_Value } str_TextStyle_LinkToPublication_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_LinkToPublication_Name_Value'; rValue : 'Ссылка на официальную публикацию'); {* Локализуемое значения атрибута TextStyle_LinkToPublication_Name_Value } str_TextStyle_UnderlinedText_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_UnderlinedText_Name_Value'; rValue : 'Подчёркнутый текст'); {* Локализуемое значения атрибута TextStyle_UnderlinedText_Name_Value } str_TextStyle_NodeGroupHeader_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_NodeGroupHeader_Name_Value'; rValue : 'Заголовок группы редакций'); {* Локализуемое значения атрибута TextStyle_NodeGroupHeader_Name_Value } str_TextStyle_TxtNormalAACSeeAlso_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TxtNormalAACSeeAlso_Name_Value'; rValue : 'Текст ЭР (см. также)'); {* Локализуемое значения атрибута TextStyle_TxtNormalAACSeeAlso_Name_Value } str_TextStyle_HeaderAACLeftWindow_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HeaderAACLeftWindow_Name_Value'; rValue : 'Заголовок ЭР (левое окно)'); {* Локализуемое значения атрибута TextStyle_HeaderAACLeftWindow_Name_Value } str_TextStyle_HeaderAACRightWindow_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_HeaderAACRightWindow_Name_Value'; rValue : 'Заголовок ЭР (правое окно)'); {* Локализуемое значения атрибута TextStyle_HeaderAACRightWindow_Name_Value } str_TextStyle_ContextAACRightWindows_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ContextAACRightWindows_Name_Value'; rValue : 'ЭР-содержание (правое окно)'); {* Локализуемое значения атрибута TextStyle_ContextAACRightWindows_Name_Value } str_TextStyle_FormulaInAAC_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_FormulaInAAC_Name_Value'; rValue : 'Формула'); {* Локализуемое значения атрибута TextStyle_FormulaInAAC_Name_Value } str_TextStyle_TwoColorTable_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_TwoColorTable_Name_Value'; rValue : 'Таблица с полосатой заливкой'); {* Локализуемое значения атрибута TextStyle_TwoColorTable_Name_Value } str_TextStyle_BoldSelection_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_BoldSelection_Name_Value'; rValue : 'Выделение жирным'); {* Локализуемое значения атрибута TextStyle_BoldSelection_Name_Value } str_TextStyle_ExpandedText_Header_HeaderC_Text_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ExpandedText_Header_HeaderC_Text_Value'; rValue : 'Разворачиваемый текст >>'); {* Локализуемое значения атрибута TextStyle_ExpandedText_Header_HeaderC_Text_Value } str_TextStyle_ExpandedText_Name_Value: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'TextStyle_ExpandedText_Name_Value'; rValue : 'Разворачиваемый текст'); {* Локализуемое значения атрибута TextStyle_ExpandedText_Name_Value } implementation uses l3ImplUses //#UC START# *060E2B49C828impl_uses* //#UC END# *060E2B49C828impl_uses* ; initialization str_TextStyle_ToLeft_Name_Value.Init; {* Инициализация str_TextStyle_ToLeft_Name_Value } str_TextStyle_TxtHeader1_Name_Value.Init; {* Инициализация str_TextStyle_TxtHeader1_Name_Value } str_TextStyle_TxtHeader2_Name_Value.Init; {* Инициализация str_TextStyle_TxtHeader2_Name_Value } str_TextStyle_TxtHeader3_Name_Value.Init; {* Инициализация str_TextStyle_TxtHeader3_Name_Value } str_TextStyle_TxtHeader4_Name_Value.Init; {* Инициализация str_TextStyle_TxtHeader4_Name_Value } str_TextStyle_NormalNote_Name_Value.Init; {* Инициализация str_TextStyle_NormalNote_Name_Value } str_TextStyle_TxtComment_Name_Value.Init; {* Инициализация str_TextStyle_TxtComment_Name_Value } {$If NOT Defined(Archi)} str_TextStyle_TxtComment_ShortName_D_Garant_Value.Init; {* Инициализация str_TextStyle_TxtComment_ShortName_D_Garant_Value } {$IfEnd} // NOT Defined(Archi) {$If Defined(Archi)} str_TextStyle_TxtComment_ShortName_D_Archi_Value.Init; {* Инициализация str_TextStyle_TxtComment_ShortName_D_Archi_Value } {$IfEnd} // Defined(Archi) {$If Defined(nsTest) AND Defined(Nemesis) AND NOT Defined(InsiderTest) AND NOT Defined(Archi)} str_TextStyle_TxtComment_ShortName_D_DailyTests_Value.Init; {* Инициализация str_TextStyle_TxtComment_ShortName_D_DailyTests_Value } {$IfEnd} // Defined(nsTest) AND Defined(Nemesis) AND NOT Defined(InsiderTest) AND NOT Defined(Archi) str_TextStyle_VersionInfo_Name_Value.Init; {* Инициализация str_TextStyle_VersionInfo_Name_Value } {$If NOT Defined(Archi)} str_TextStyle_VersionInfo_ShortName_Value.Init; {* Инициализация str_TextStyle_VersionInfo_ShortName_Value } {$IfEnd} // NOT Defined(Archi) {$If Defined(Archi)} str_TextStyle_VersionInfo_ShortName_D_Archi_Value.Init; {* Инициализация str_TextStyle_VersionInfo_ShortName_D_Archi_Value } {$IfEnd} // Defined(Archi) str_TextStyle_PromptTree_Name_Value.Init; {* Инициализация str_TextStyle_PromptTree_Name_Value } str_TextStyle_HLE1_Name_Value.Init; {* Инициализация str_TextStyle_HLE1_Name_Value } str_TextStyle_HLE1_ShortName_Value.Init; {* Инициализация str_TextStyle_HLE1_ShortName_Value } str_TextStyle_HLE2_Name_Value.Init; {* Инициализация str_TextStyle_HLE2_Name_Value } str_TextStyle_HLE2_ShortName_Value.Init; {* Инициализация str_TextStyle_HLE2_ShortName_Value } str_TextStyle_HLE3_Name_Value.Init; {* Инициализация str_TextStyle_HLE3_Name_Value } str_TextStyle_HLE3_ShortName_Value.Init; {* Инициализация str_TextStyle_HLE3_ShortName_Value } str_TextStyle_HLE4_Name_Value.Init; {* Инициализация str_TextStyle_HLE4_Name_Value } str_TextStyle_HLE4_ShortName_Value.Init; {* Инициализация str_TextStyle_HLE4_ShortName_Value } str_TextStyle_HLE5_Name_Value.Init; {* Инициализация str_TextStyle_HLE5_Name_Value } str_TextStyle_HLE5_ShortName_Value.Init; {* Инициализация str_TextStyle_HLE5_ShortName_Value } str_TextStyle_HLE6_Name_Value.Init; {* Инициализация str_TextStyle_HLE6_Name_Value } str_TextStyle_HLE6_ShortName_Value.Init; {* Инициализация str_TextStyle_HLE6_ShortName_Value } str_TextStyle_HeaderForChangesInfo_Name_Value.Init; {* Инициализация str_TextStyle_HeaderForChangesInfo_Name_Value } str_TextStyle_FooterForChangesInfo_Name_Value.Init; {* Инициализация str_TextStyle_FooterForChangesInfo_Name_Value } str_TextStyle_TextForChangesInfo_Name_Value.Init; {* Инициализация str_TextStyle_TextForChangesInfo_Name_Value } str_TextStyle_ChangesInfo_Header_HeaderC_Text_Value.Init; {* Инициализация str_TextStyle_ChangesInfo_Header_HeaderC_Text_Value } str_TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value.Init; {* Инициализация str_TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value } str_TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value.Init; {* Инициализация str_TextStyle_ChangesInfo_Footer_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value } str_TextStyle_ChangesInfo_Footer_FooterC_Text_Value.Init; {* Инициализация str_TextStyle_ChangesInfo_Footer_FooterC_Text_Value } str_TextStyle_ChangesInfo_Name_Value.Init; {* Инициализация str_TextStyle_ChangesInfo_Name_Value } str_TextStyle_ChangesInfo_ShortName_Value.Init; {* Инициализация str_TextStyle_ChangesInfo_ShortName_Value } str_TextStyle_SubHeaderForChangesInfo_Name_Value.Init; {* Инициализация str_TextStyle_SubHeaderForChangesInfo_Name_Value } str_TextStyle_ControlsBlockHeader_Name_Value.Init; {* Инициализация str_TextStyle_ControlsBlockHeader_Name_Value } str_TextStyle_CloakHeader_Name_Value.Init; {* Инициализация str_TextStyle_CloakHeader_Name_Value } str_TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value.Init; {* Инициализация str_TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_Address_ShortName_Value } str_TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value.Init; {* Инициализация str_TextStyle_LinkToPublication_Header_FooterC_Segments_Hyperlinks_Hyperlink_URL_Value } str_TextStyle_LinkToPublication_Header_FooterC_Text_Value.Init; {* Инициализация str_TextStyle_LinkToPublication_Header_FooterC_Text_Value } str_TextStyle_LinkToPublication_Name_Value.Init; {* Инициализация str_TextStyle_LinkToPublication_Name_Value } str_TextStyle_UnderlinedText_Name_Value.Init; {* Инициализация str_TextStyle_UnderlinedText_Name_Value } str_TextStyle_NodeGroupHeader_Name_Value.Init; {* Инициализация str_TextStyle_NodeGroupHeader_Name_Value } str_TextStyle_TxtNormalAACSeeAlso_Name_Value.Init; {* Инициализация str_TextStyle_TxtNormalAACSeeAlso_Name_Value } str_TextStyle_HeaderAACLeftWindow_Name_Value.Init; {* Инициализация str_TextStyle_HeaderAACLeftWindow_Name_Value } str_TextStyle_HeaderAACRightWindow_Name_Value.Init; {* Инициализация str_TextStyle_HeaderAACRightWindow_Name_Value } str_TextStyle_ContextAACRightWindows_Name_Value.Init; {* Инициализация str_TextStyle_ContextAACRightWindows_Name_Value } str_TextStyle_FormulaInAAC_Name_Value.Init; {* Инициализация str_TextStyle_FormulaInAAC_Name_Value } str_TextStyle_TwoColorTable_Name_Value.Init; {* Инициализация str_TextStyle_TwoColorTable_Name_Value } str_TextStyle_BoldSelection_Name_Value.Init; {* Инициализация str_TextStyle_BoldSelection_Name_Value } str_TextStyle_ExpandedText_Header_HeaderC_Text_Value.Init; {* Инициализация str_TextStyle_ExpandedText_Header_HeaderC_Text_Value } str_TextStyle_ExpandedText_Name_Value.Init; {* Инициализация str_TextStyle_ExpandedText_Name_Value } end.
unit uUsuarioPermissaoVO; interface uses System.SysUtils, uKeyField, uTableName, System.Generics.Collections; type [TableName('Usuario_Permissao')] TUsuarioPermissaoVO = class private FIdUsuario: Integer; FId: Integer; FSigla: string; procedure SetId(const Value: Integer); procedure SetIdUsuario(const Value: Integer); procedure SetSigla(const Value: string); public [KeyField('UsuP_Id')] property Id: Integer read FId write SetId; [FieldName('UsuP_Usuario')] property IdUsuario: Integer read FIdUsuario write SetIdUsuario; [FieldName('UsuP_Sigla')] property Sigla: string read FSigla write SetSigla; end; TListaUsuarioPermissao = TObjectList<TUsuarioPermissaoVO>; implementation { TUsuarioPermissaoVO } procedure TUsuarioPermissaoVO.SetId(const Value: Integer); begin FId := Value; end; procedure TUsuarioPermissaoVO.SetIdUsuario(const Value: Integer); begin FIdUsuario := Value; end; procedure TUsuarioPermissaoVO.SetSigla(const Value: string); begin FSigla := Value; end; end.
{ ******************************************************************************* Copyright (c) 2004-2010 by Edyard Tolmachev IMadering project http://imadering.com ICQ: 118648 E-mail: imadering@mail.ru ******************************************************************************* } unit ContactSearchUnit; interface {$REGION 'Uses'} uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, Buttons, Menus, VarsUnit, JvExComCtrls, JvListView, ExtDlgs; type TContactSearchForm = class(TForm) CenterPanel: TPanel; BottomPanel: TPanel; NotPreviousClearCheckBox: TCheckBox; OnlyOnlineCheckBox: TCheckBox; SearchBitBtn: TBitBtn; StatusPanel: TPanel; ResultPanel: TPanel; ResultClearSpeedButton: TSpeedButton; QMessageEdit: TEdit; SendQMessageSpeedButton: TSpeedButton; SearchResultPopupMenu: TPopupMenu; ICQStatusCheckSM: TMenuItem; AccountNameCopySM: TMenuItem; SendMessageSM: TMenuItem; SearchNextPageBitBtn: TBitBtn; ContactInfoSM: TMenuItem; AddContactInCLSM: TMenuItem; SearchResultJvListView: TJvListView; TopPanel: TPanel; GlobalSearchGroupBox: TGroupBox; NickLabel: TLabel; NickEdit: TEdit; NameLabel: TLabel; NameEdit: TEdit; FamilyLabel: TLabel; FamilyEdit: TEdit; GenderLabel: TLabel; GenderComboBox: TComboBox; AgeLabel: TLabel; AgeComboBox: TComboBox; MaritalLabel: TLabel; MaritalComboBox: TComboBox; CountryLabel: TLabel; CountryComboBox: TComboBox; CityLabel: TLabel; CityEdit: TEdit; LangLabel: TLabel; LangComboBox: TComboBox; KeyWordLabel: TLabel; KeyWordEdit: TEdit; Bevel3: TBevel; GlobalSearchCheckBox: TCheckBox; UINSearchGroupBox: TGroupBox; GroupBox1: TGroupBox; GroupBox2: TGroupBox; UINSearchCheckBox: TCheckBox; UINSearchEdit: TEdit; EmailSearchCheckBox: TCheckBox; EmailSearchEdit: TEdit; KeyWordSearchCheckBox: TCheckBox; KeyWordSearchEdit: TEdit; SaveSM: TMenuItem; LoadSM: TMenuItem; LoadSearchResultFileDialog: TOpenTextFileDialog; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure QMessageEditEnter(Sender: TObject); procedure QMessageEditExit(Sender: TObject); procedure SearchBitBtnClick(Sender: TObject); procedure ResultClearSpeedButtonClick(Sender: TObject); procedure SendQMessageSpeedButtonClick(Sender: TObject); procedure SearchNextPageBitBtnClick(Sender: TObject); procedure ICQStatusCheckSMClick(Sender: TObject); procedure AccountNameCopySMClick(Sender: TObject); procedure SendMessageSMClick(Sender: TObject); procedure AddContactInCLSMClick(Sender: TObject); procedure ContactInfoSMClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure SearchResultJvListViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SearchResultJvListViewChanging(Sender: TObject; Item: TListItem; Change: TItemChange; var AllowChange: Boolean); procedure SearchResultJvListViewGetSubItemImage(Sender: TObject; Item: TListItem; SubItem: Integer; var ImageIndex: Integer); procedure SearchResultJvListViewColumnClick(Sender: TObject; Column: TListColumn); procedure SearchResultJvListViewGetImageIndex(Sender: TObject; Item: TListItem); procedure UINSearchEditChange(Sender: TObject); procedure EmailSearchEditChange(Sender: TObject); procedure KeyWordSearchEditChange(Sender: TObject); procedure NickEditChange(Sender: TObject); procedure UINSearchCheckBoxClick(Sender: TObject); procedure EmailSearchCheckBoxClick(Sender: TObject); procedure KeyWordSearchCheckBoxClick(Sender: TObject); procedure GlobalSearchCheckBoxClick(Sender: TObject); procedure SearchResultJvListViewDblClick(Sender: TObject); procedure SearchResultPopupMenuPopup(Sender: TObject); procedure LoadSMClick(Sender: TObject); procedure SaveSMClick(Sender: TObject); procedure FormDblClick(Sender: TObject); private { Private declarations } SPage: Word; SPageInc: Boolean; function GetColimnAtX(X: Integer): Integer; procedure OpenAnketa; procedure OpenChatResult; procedure GlobalSearch; public { Public declarations } procedure TranslateForm; end; {$ENDREGION} var ContactSearchForm: TContactSearchForm; implementation {$R *.dfm} {$REGION 'MyUses'} uses MainUnit, IcqProtoUnit, UtilsUnit, AddContactUnit, ContactInfoUnit, IcqOptionsUnit, JvSimpleXml, OverbyteIcsUrl; {$ENDREGION} {$REGION 'MyConst'} const C_IcqSearchF = 'icq_search_form'; {$ENDREGION} {$REGION 'GlobalSearch'} procedure TContactSearchForm.GlobalSearch; var CountryInd, LangInd, MaritalInd: Integer; begin // Ищем новым способом if IsNotNull([NickEdit.Text, NameEdit.Text, FamilyEdit.Text, CityEdit.Text, KeyWordEdit.Text, GenderComboBox.Text, AgeComboBox.Text, MaritalComboBox.Text, CountryComboBox.Text, LangComboBox.Text]) then begin // Управляем счётчиком страниц if SPageInc then begin Inc(SPage); SearchNextPageBitBtn.Caption := Format(Lang_Vars[126].L_S, [SPage]); end else SPage := 0; // Получаем коды из текста CountryInd := -1; LangInd := -1; MaritalInd := -1; with IcqOptionsForm do begin // Страна if CountryComboBox.ItemIndex > 0 then CountryInd := StrToInt(IsolateTextString(CountryComboBox.Text, '[', ']')); // Язык if LangComboBox.ItemIndex > 0 then LangInd := StrToInt(IsolateTextString(LangComboBox.Text, '[', ']')); // Брак if MaritalComboBox.ItemIndex > 0 then MaritalInd := StrToInt(IsolateTextString(MaritalComboBox.Text, '[', ']')); end; // Начинаем поиск StatusPanel.Caption := Lang_Vars[121].L_S; ICQ_SearchNewBase(NickEdit.Text, NameEdit.Text, FamilyEdit.Text, CityEdit.Text, KeyWordEdit.Text, GenderComboBox.ItemIndex, AgeComboBox.ItemIndex, MaritalInd, CountryInd, LangInd, SPage, OnlyOnlineCheckBox.Checked); end; end; {$ENDREGION} {$REGION 'OpenAnketa'} procedure TContactSearchForm.OpenAnketa; begin if not Assigned(ContactInfoForm) then ContactInfoForm := TContactInfoForm.Create(Self); // Присваиваем UIN инфу которого хотим смотреть ContactInfoForm.ReqUIN := SearchResultJvListView.Selected.SubItems[1]; ContactInfoForm.ReqProto := C_Icq; // Загружаем информацию о нем ContactInfoForm.LoadUserUnfo; // Отображаем окно XShowForm(ContactInfoForm); end; {$ENDREGION} {$REGION 'OpenChatResult'} procedure TContactSearchForm.OpenChatResult; {var RosterItem: TListItem;} begin {// Ищем эту запись в Ростере RosterItem := RosterForm.ReqRosterItem(SearchResultJvListView.Selected.SubItems[1]); if RosterItem = nil then begin // Ищем группу "Не в списке" в Ростере RosterItem := RosterForm.ReqRosterItem(C_NoCL); if RosterItem = nil then // Если группу не нашли begin // Добавляем такую группу в Ростер RosterItem := RosterForm.RosterJvListView.Items.Add; RosterItem.Caption := C_NoCL; // Подготавиливаем все значения RosterForm.RosterItemSetFull(RosterItem); RosterItem.SubItems[1] := URLEncode(Lang_Vars[33].L_S); end; // Добавляем этот контакт в Ростер RosterItem := RosterForm.RosterJvListView.Items.Add; with RosterItem do begin Caption := SearchResultJvListView.Selected.SubItems[1]; // Подготавиливаем все значения RosterForm.RosterItemSetFull(RosterItem); // Обновляем субстроки if SearchResultJvListView.Selected.SubItems[2] = EmptyStr then SubItems[0] := SearchResultJvListView.Selected.SubItems[1] else SubItems[0] := SearchResultJvListView.Selected.SubItems[2]; SubItems[1] := C_NoCL; SubItems[2] := 'none'; SubItems[3] := C_Icq; SubItems[6] := '214'; SubItems[35] := '0'; end; // Обновляем КЛ RosterForm.UpdateFullCL; end; // Открываем чат с этим контактом RosterForm.OpenChatPage(nil, SearchResultJvListView.Selected.SubItems[1]);} end; {$ENDREGION} {$REGION 'TranslateForm'} procedure TContactSearchForm.TranslateForm; begin // Создаём шаблон для перевода // CreateLang(Self); // Применяем язык SetLang(Self); // Присваиваем списки комбобоксам if Assigned(IcqOptionsForm) then begin with IcqOptionsForm do begin // Присваиваем Брак MaritalComboBox.Items.Assign(PersonalMaritalInfoComboBox.Items); SetCustomWidthComboBox(MaritalComboBox); // Присваиваем Страну CountryComboBox.Items.Assign(CountryInfoComboBox.Items); SetCustomWidthComboBox(CountryComboBox); // Присваиваем Язык LangComboBox.Items.Assign(Lang1InfoComboBox.Items); SetCustomWidthComboBox(LangComboBox); // Присваиваем Пол GenderComboBox.Items.Assign(PersonalGenderInfoComboBox.Items); SetCustomWidthComboBox(GenderComboBox); end; end; // Другое QMessageEdit.Text := Lang_Vars[102].L_S; end; {$ENDREGION} {$REGION 'Other'} procedure TContactSearchForm.UINSearchCheckBoxClick(Sender: TObject); begin // Активируем поиск по UIN if UINSearchCheckBox.Checked then begin EmailSearchCheckBox.Checked := False; KeyWordSearchCheckBox.Checked := False; GlobalSearchCheckBox.Checked := False; end; end; procedure TContactSearchForm.UINSearchEditChange(Sender: TObject); begin // Активируем поиск по UIN if not UINSearchCheckBox.Checked then begin UINSearchCheckBox.Checked := True; EmailSearchCheckBox.Checked := False; KeyWordSearchCheckBox.Checked := False; GlobalSearchCheckBox.Checked := False; end; end; procedure TContactSearchForm.SaveSMClick(Sender: TObject); begin // Сохраняем результаты поиска в файл with MainForm do begin SaveTextAsFileDialog.FileName := 'ICQ search result'; if SaveTextAsFileDialog.Execute then SearchResultJvListView.SaveToCSV(SaveTextAsFileDialog.FileName); end; end; {$ENDREGION} {$REGION 'SearchBitBtnClick'} procedure TContactSearchForm.SearchBitBtnClick(Sender: TObject); var I: Integer; begin // Сбрасываем стрелочки сортировки во всех столбцах for I := 0 to SearchResultJvListView.Columns.Count - 1 do SearchResultJvListView.Columns[I].ImageIndex := -1; // Если не стоит галочка "Не очищать предыдущие резульаты", то стираем их if not NotPreviousClearCheckBox.Checked then begin SearchResultJvListView.Clear; ResultPanel.Caption := '0'; end; // Ищем по ICQ UIN if (UINSearchCheckBox.Checked) and (UINSearchEdit.Text <> EmptyStr) then begin // Нормализуем UIN UINSearchEdit.Text := NormalizeScreenName(UINSearchEdit.Text); UINSearchEdit.Text := NormalizeIcqNumber(UINSearchEdit.Text); if not ExIsValidCharactersDigit(UINSearchEdit.Text) then begin UINSearchEdit.Clear; Exit; end; if ICQ_Work_Phaze then begin StatusPanel.Caption := Lang_Vars[121].L_S; ICQ_SearchPoUIN_new(UINSearchEdit.Text); end; end // Ищем по Email else if (EmailSearchCheckBox.Checked) and (EmailSearchEdit.Text <> EmptyStr) then begin if ICQ_Work_Phaze then begin StatusPanel.Caption := Lang_Vars[121].L_S; ICQ_SearchPoEmail_new(EmailSearchEdit.Text); end; end // Ищем по ключевым словам else if (KeyWordSearchCheckBox.Checked) and (KeyWordSearchEdit.Text <> EmptyStr) then begin if ICQ_Work_Phaze then begin StatusPanel.Caption := Lang_Vars[121].L_S; ICQ_SearchPoText_new(KeyWordSearchEdit.Text, OnlyOnlineCheckBox.Checked); end; end // Ищем по расширенным параметрам else if GlobalSearchCheckBox.Checked then begin if ICQ_Work_Phaze then begin // Сбрасываем кнопку листания страниц в результатов SPageInc := False; SearchNextPageBitBtn.Caption := Lang_Vars[7].L_S; // Ищем GlobalSearch; end; end; end; {$ENDREGION} {$REGION 'Other'} procedure TContactSearchForm.SearchNextPageBitBtnClick(Sender: TObject); begin // Начинаем листать страницы SPageInc := True; GlobalSearch; end; procedure TContactSearchForm.EmailSearchCheckBoxClick(Sender: TObject); begin // Активируем поиск по Email if EmailSearchCheckBox.Checked then begin UINSearchCheckBox.Checked := False; KeyWordSearchCheckBox.Checked := False; GlobalSearchCheckBox.Checked := False; end; end; procedure TContactSearchForm.EmailSearchEditChange(Sender: TObject); begin // Активируем поиск по Email if not EmailSearchCheckBox.Checked then begin UINSearchCheckBox.Checked := False; EmailSearchCheckBox.Checked := True; KeyWordSearchCheckBox.Checked := False; GlobalSearchCheckBox.Checked := False; end; end; procedure TContactSearchForm.QMessageEditEnter(Sender: TObject); var FOptions: TFontStyles; begin // Сбрасываем текст в поле быстрых сообщений with QMessageEdit do begin if Tag = 1 then begin Clear; FOptions := []; Font.Style := FOptions; Tag := 0; end; end; end; procedure TContactSearchForm.QMessageEditExit(Sender: TObject); var FOptions: TFontStyles; begin // Восстанавливаем with QMessageEdit do begin if Text = EmptyStr then begin FOptions := []; Include(FOptions, FsBold); Font.Style := FOptions; Text := C_BN + Lang_Vars[102].L_S; Tag := 1; end; end; end; {$ENDREGION} {$REGION 'FormClose'} procedure TContactSearchForm.FormClose(Sender: TObject; var Action: TCloseAction); begin // Выводим окно списка контактов на передний план BringWindowToTop(MainForm.Handle); // Уничтожаем окно SearchResultJvListView.HeaderImages := nil; Action := CaFree; ContactSearchForm := nil; end; {$ENDREGION} {$REGION 'FormCreate'} procedure TContactSearchForm.FormCreate(Sender: TObject); var JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; begin // Инициализируем XML JvXML_Create(JvXML); try with JvXML do begin // Загружаем настройки if FileExists(V_ProfilePath + C_SettingsFileName) then begin LoadFromFile(V_ProfilePath + C_SettingsFileName); if Root <> nil then begin XML_Node := Root.Items.ItemNamed[C_IcqSearchF]; if XML_Node <> nil then begin // Загружаем позицию окна Top := XML_Node.Properties.IntValue('t'); Left := XML_Node.Properties.IntValue('l'); Height := XML_Node.Properties.IntValue('h'); Width := XML_Node.Properties.IntValue('w'); // Определяем не находится ли окно за пределами экрана FormSetInWorkArea(Self); end; end; end; end; finally JvXML.Free; end; // Переводим форму на другие языки TranslateForm; // Устанавливаем иконки на форму и кнопки MainForm.AllImageList.GetIcon(235, Icon); MainForm.AllImageList.GetBitmap(235, SearchBitBtn.Glyph); MainForm.AllImageList.GetBitmap(159, ResultClearSpeedButton.Glyph); MainForm.AllImageList.GetBitmap(239, SendQMessageSpeedButton.Glyph); MainForm.AllImageList.GetBitmap(166, SearchNextPageBitBtn.Glyph); // Делаем окно независимым и помещаем его кнопку на панель задач SetWindowLong(Handle, GWL_HWNDPARENT, 0); SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); // Делаем окно прилипающим к краям экрана ScreenSnap := True; end; {$ENDREGION} {$REGION 'FormDestroy'} procedure TContactSearchForm.FormDestroy(Sender: TObject); var JvXML: TJvSimpleXml; XML_Node: TJvSimpleXmlElem; begin // Создаём необходимые папки ForceDirectories(V_ProfilePath); // Сохраняем настройки положения окна в xml // Инициализируем XML JvXML_Create(JvXML); try with JvXML do begin if FileExists(V_ProfilePath + C_SettingsFileName) then LoadFromFile(V_ProfilePath + C_SettingsFileName); if Root <> nil then begin // Очищаем раздел формы если он есть XML_Node := Root.Items.ItemNamed[C_IcqSearchF]; if XML_Node <> nil then XML_Node.Clear else XML_Node := Root.Items.Add(C_IcqSearchF); // Сохраняем позицию окна XML_Node.Properties.Add('t', Top); XML_Node.Properties.Add('l', Left); XML_Node.Properties.Add('h', Height); XML_Node.Properties.Add('w', Width); // Записываем сам файл SaveToFile(V_ProfilePath + C_SettingsFileName); end; end; finally JvXML.Free; end; end; {$ENDREGION} {$REGION 'Other'} procedure TContactSearchForm.FormDblClick(Sender: TObject); begin // Устанавливаем перевод TranslateForm; end; procedure TContactSearchForm.GlobalSearchCheckBoxClick(Sender: TObject); begin // Активируем глобальный поиск if GlobalSearchCheckBox.Checked then begin UINSearchCheckBox.Checked := False; EmailSearchCheckBox.Checked := False; KeyWordSearchCheckBox.Checked := False; end; end; procedure TContactSearchForm.ICQStatusCheckSMClick(Sender: TObject); begin // Проверяем статус if SearchResultJvListView.Selected <> nil then ICQ_ReqStatus0215(SearchResultJvListView.Selected.SubItems[1]); end; procedure TContactSearchForm.KeyWordSearchCheckBoxClick(Sender: TObject); begin // Активируем поиск по ключ. словам if KeyWordSearchCheckBox.Checked then begin UINSearchCheckBox.Checked := False; EmailSearchCheckBox.Checked := False; GlobalSearchCheckBox.Checked := False; end; end; procedure TContactSearchForm.KeyWordSearchEditChange(Sender: TObject); begin // Активируем поиск по ключ. словам if not KeyWordSearchCheckBox.Checked then begin UINSearchCheckBox.Checked := False; EmailSearchCheckBox.Checked := False; KeyWordSearchCheckBox.Checked := True; GlobalSearchCheckBox.Checked := False; end; end; procedure TContactSearchForm.LoadSMClick(Sender: TObject); begin // Загружаем результаты поиска из файла SearchResultJvListView.Clear; if LoadSearchResultFileDialog.Execute then SearchResultJvListView.LoadFromCSV(LoadSearchResultFileDialog.FileName); end; procedure TContactSearchForm.NickEditChange(Sender: TObject); begin // Активируем глобальный поиск if not GlobalSearchCheckBox.Checked then begin UINSearchCheckBox.Checked := False; EmailSearchCheckBox.Checked := False; KeyWordSearchCheckBox.Checked := False; GlobalSearchCheckBox.Checked := True; end; end; procedure TContactSearchForm.AccountNameCopySMClick(Sender: TObject); begin // Копируем имя учётной записи в буфер обмена if SearchResultJvListView.Selected <> nil then SetClipboardText(SearchResultJvListView.Selected.SubItems[1]); end; procedure TContactSearchForm.SendMessageSMClick(Sender: TObject); begin // Открываем чат с выбранным контактом if SearchResultJvListView.Selected <> nil then OpenChatResult; end; procedure TContactSearchForm.ContactInfoSMClick(Sender: TObject); begin // Открываем анкету if SearchResultJvListView.Selected <> nil then OpenAnketa; end; {$ENDREGION} {$REGION 'AddContactInCLSMClick'} procedure TContactSearchForm.AddContactInCLSMClick(Sender: TObject); { var FrmAddCnt: TIcqAddContactForm; } begin // Создаём окно добавления контакта в КЛ { FrmAddCnt := TIcqAddContactForm.Create(Self); try with FrmAddCnt do begin // Составляем список групп из Ростера BuildGroupList(S_Icq); // Заносим имя учётной записи AccountEdit.Text := SearchResultJvListView.Selected.SubItems[1]; AccountEdit.readonly := True; AccountEdit.Color := ClBtnFace; // Заносим имя учётной записи if SearchResultJvListView.Selected.SubItems[2] = EmptyStr then NameEdit.Text := SearchResultJvListView.Selected.SubItems[1] else NameEdit.Text := SearchResultJvListView.Selected.SubItems[2]; // Заполняем протокол контакта ContactType := S_Icq; // Отображаем окно модально ShowModal; end; finally FreeAndNil(FrmAddCnt); end; } end; {$ENDREGION} {$REGION 'SearchResultJvListViewColumnClick'} procedure TContactSearchForm.SearchResultJvListViewColumnClick(Sender: TObject; Column: TListColumn); var I: Integer; begin if (Column.index = 0) or (Column.index = 1) or (Column.index = 8) then begin // Сбрасываем стрелочки сортировки во всех столбцах for I := 0 to SearchResultJvListView.Columns.Count - 1 do SearchResultJvListView.Columns[I].ImageIndex := -1; Exit; end; // Выставляем стрелочку сортировки if Column.ImageIndex <> 234 then Column.ImageIndex := 234 else Column.ImageIndex := 233; // Сбрасываем стрелочки сортировки в других столбцах for I := 0 to SearchResultJvListView.Columns.Count - 1 do if SearchResultJvListView.Columns[I] <> Column then SearchResultJvListView.Columns[I].ImageIndex := -1; end; {$ENDREGION} {$REGION 'Other'} procedure TContactSearchForm.SearchResultJvListViewChanging(Sender: TObject; Item: TListItem; Change: TItemChange; var AllowChange: Boolean); begin // Заносим количество найденных в панель ResultPanel.Caption := IntToStr(SearchResultJvListView.Items.Count); end; procedure TContactSearchForm.SearchResultJvListViewDblClick(Sender: TObject); begin // Выводим диалог добавления контакта в список контактов AddContactInCLSMClick(Self); end; procedure TContactSearchForm.SearchResultJvListViewGetImageIndex(Sender: TObject; Item: TListItem); begin // Ставим иконку просмотра анкеты о контакте Item.ImageIndex := 237; end; procedure TContactSearchForm.SearchResultJvListViewGetSubItemImage(Sender: TObject; Item: TListItem; SubItem: Integer; var ImageIndex: Integer); begin // Ставим иконку открытия чата с этим контактом if SubItem = 0 then ImageIndex := 238; // Ставим иконки отправки быстрых сообщений if Item.Checked then begin if SubItem = 7 then ImageIndex := 240; end else begin if SubItem = 7 then ImageIndex := 239; end; end; procedure TContactSearchForm.ResultClearSpeedButtonClick(Sender: TObject); begin // Очищаем список от результатов SearchResultJvListView.Clear; ResultPanel.Caption := '0'; end; {$ENDREGION} {$REGION 'GetColimnAtX'} function TContactSearchForm.GetColimnAtX(X: Integer): Integer; var I, RelativeX, ColStartX: Integer; begin Result := 0; with SearchResultJvListView do begin // Теперь попробуем найти колонку RelativeX := X - Selected.Position.X - BorderWidth; ColStartX := Columns[0].Width; for I := 1 to Columns.Count - 1 do begin if RelativeX < ColStartX then Break; if RelativeX <= ColStartX + Columns[I].Width then begin Result := I; Break; end; Inc(ColStartX, Columns[I].Width); end; end; end; {$ENDREGION} {$REGION 'SearchResultJvListViewMouseDown'} procedure TContactSearchForm.SearchResultJvListViewMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = MbLeft then begin with SearchResultJvListView do begin if Selected <> nil then begin case GetColimnAtX(X) of 0: OpenAnketa; // Открываем анкету этого контакта 1: OpenChatResult; // Открываем чат с этим контактом 8: SendQMessageSpeedButtonClick(Self); end; end; end; end; end; {$ENDREGION} {$REGION 'SearchResultPopupMenuPopup'} procedure TContactSearchForm.SearchResultPopupMenuPopup(Sender: TObject); begin // Блокируем нужные пункты меню if SearchResultJvListView.Selected <> nil then begin ICQStatusCheckSM.Enabled := True; AccountNameCopySM.Enabled := True; SendMessageSM.Enabled := True; ContactInfoSM.Enabled := True; AddContactInCLSM.Enabled := True; end else begin ICQStatusCheckSM.Enabled := False; AccountNameCopySM.Enabled := False; SendMessageSM.Enabled := False; ContactInfoSM.Enabled := False; AddContactInCLSM.Enabled := False; end; if SearchResultJvListView.Items.Count > 0 then SaveSM.Enabled := True else SaveSM.Enabled := False; end; {$ENDREGION} {$REGION 'SendQMessageSpeedButtonClick'} procedure TContactSearchForm.SendQMessageSpeedButtonClick(Sender: TObject); begin with SearchResultJvListView do begin if Selected <> nil then begin // Если уже отправляли сообщение или оно пустое, то выходим if (Selected.Checked) or (QMessageEdit.Tag = 1) or (QMessageEdit.Text = EmptyStr) then Exit; // Отправляем быстрое сообщение этому контакту if ICQ_Work_Phaze then begin ICQ_SendMessage_0406(Selected.SubItems[1], QMessageEdit.Text, True); Selected.Checked := True; end; end; end; end; {$ENDREGION} end.
unit fcDBCommon; interface uses db, dbtables, classes, typinfo; Function fcGetControlDataSource(ctrl: TComponent): TDataSource; Function fcGetControlMasterSource(ctrl: TComponent): TDataSource; Function fcGetControlMasterDataSet(ctrl: TComponent): TDataSet; Function fcSetDatabaseName(ctrl: TDataset; df: string): boolean; Function fcGetDatabaseName(dataSet: TDataSet): String; Function fcGetTableName(dataSet: TDataSet): String; Function fcSetSQLProp(ctrl: TDataset; sql: TStrings): boolean; Function fcSetParamsProp(ctrl: TDataset; Params: TParams): boolean; Function fcGetParamsProp(ctrl: TDataset): TParams; implementation Function fcGetControlDataSource(ctrl: TComponent): TDataSource; var PropInfo: PPropInfo; begin Result:= Nil; PropInfo:= Typinfo.GetPropInfo(ctrl.ClassInfo,'DataSource'); if PropInfo<>Nil then begin result:= TDataSource(GetOrdProp(ctrl, PropInfo)); end end; Function fcGetControlMasterSource(ctrl: TComponent): TDataSource; var PropInfo: PPropInfo; begin Result:= Nil; PropInfo:= Typinfo.GetPropInfo(ctrl.ClassInfo,'MasterSource'); if PropInfo<>Nil then begin result:= TDataSource(GetOrdProp(ctrl, PropInfo)); end end; Function fcGetControlMasterDataSet(ctrl: TComponent): TDataSet; var PropInfo: PPropInfo; begin Result:= Nil; PropInfo:= Typinfo.GetPropInfo(ctrl.ClassInfo,'Master'); if PropInfo<>Nil then begin result:= TDataSet(GetOrdProp(ctrl, PropInfo)); end end; Function fcSetSQLProp(ctrl: TDataset; sql: TStrings): boolean; var PropInfo: PPropInfo; begin result:= False; PropInfo:= Typinfo.GetPropINfo(ctrl.ClassInfo,'SQL'); if (PropInfo <> nil) and (PropInfo^.Proptype^.Kind = tkClass) then begin SetOrdProp(Ctrl,PropInfo,LongInt(sql)); result:= True; end end; Function fcSetDatabaseName(ctrl: TDataset; df: string): boolean; var PropInfo: PPropInfo; begin Result:= False; PropInfo:= Typinfo.GetPropINfo(ctrl.ClassInfo,'DatabaseName'); {$IFDEF WIN32} if (PropInfo<>nil) and (PropInfo^.Proptype^.Kind = tklString) then begin {$ELSE} if (PropInfo<>nil) and (PropInfo^.PropType^.Kind = tkString) then begin {$ENDIF} SetStrProp(Ctrl,PropInfo,df); result:= True; end end; Function fcGetDatabaseName(dataSet: TDataSet): String; var PropInfo: PPropInfo; begin Result:= ''; PropInfo:= Typinfo.GetPropInfo(DataSet.ClassInfo, 'DatabaseName'); if PropInfo<>Nil then result:= GetStrProp(DataSet, PropInfo); end; Function fcGetTableName(dataSet: TDataSet): String; var PropInfo: PPropInfo; begin Result:= ''; PropInfo:= Typinfo.GetPropInfo(DataSet.ClassInfo, 'TableName'); if PropInfo<>Nil then result:= GetStrProp(DataSet, PropInfo); // if dataSet is TwwTable then result:= TwwTable(dataSet).tableName // else result:= '?'; end; Function fcGetParamsProp(ctrl: TDataset): TParams; var PropInfo: PPropInfo; begin result:= nil; PropInfo:= Typinfo.GetPropINfo(ctrl.ClassInfo,'Params'); if (PropInfo <> nil) and (PropInfo^.Proptype^.Kind = tkClass) then result:= TParams(GetOrdProp(Ctrl,PropInfo)); end; Function fcSetParamsProp(ctrl: TDataset; Params: TParams): boolean; var PropInfo: PPropInfo; begin result:= False; PropInfo:= Typinfo.GetPropInfo(ctrl.ClassInfo,'Params'); if (PropInfo <> nil) and (PropInfo^.Proptype^.Kind = tkClass) then begin fcGetParamsProp(ctrl).Assign(Params); result:= True; end; end; end.
unit FrontEnd; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, XPMan, BackEnd; type TMainForm = class(TForm) LabelTask: TLabel; LabelOutput: TLabel; LabelInput: TLabel; InputStringGrid: TStringGrid; ButtonFind: TButton; ButtonCleanAll: TButton; ButtonOpenFile: TButton; ButtonAddCol: TButton; ButtonDelCol: TButton; ButtonSaveFile: TButton; OutputStringGrid: TStringGrid; OpenFileDialog: TOpenDialog; SaveFileDialog: TSaveDialog; XPButtonsStyle: TXPManifest; procedure InputStringGridKeyPress(Sender: TObject; var Key: Char); procedure ButtonOpenFileClick(Sender: TObject); procedure ButtonDelColClick(Sender: TObject); procedure ButtonAddColClick(Sender: TObject); procedure ButtonFindClick(Sender: TObject); procedure ButtonSaveFileClick(Sender: TObject); procedure ButtonCleanAllClick(Sender: TObject); procedure InputStringGridClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; InputArray, OutputArray: TDynamicArray; implementation {$R *.dfm} // Key Press procedure TMainForm.InputStringGridKeyPress(Sender: TObject; var Key: Char); var EditField: TStringGrid; newText: String; const EnabledKeys = ['0'..'9']; begin EditField := (Sender as TStringGrid); with EditField do newText := Cells[col,row]; if (length(newText) >= 7) and (not(Key = #8)) then key := #0; if (not(key in EnabledKeys)) and (not(key = #8)) then key := #0 ; if (length(newText) = 0) and (key = '0') then key := #0; end; procedure TMainForm.ButtonOpenFileClick(Sender: TObject); begin OpenFileDialog.Filter := 'Text Files only |*.txt'; CleanFields(OutputStringGrid); if OpenFileDialog.Execute and ReadingArray(InputArray, OpenFileDialog.FileName) then begin ExtendFields(InputStringGrid, length(InputArray)); PrintArray(InputArray, InputStringGrid, 0); end; end; procedure TMainForm.ButtonDelColClick(Sender: TObject); begin if InputStringGrid.ColCount > 2 then begin CleanFields(OutputStringGrid); InputStringGrid.Cols[InputStringGrid.ColCount - 1].Text := ''; InputStringGrid.ColCount := InputStringGrid.ColCount - 1; end; end; procedure TMainForm.ButtonAddColClick(Sender: TObject); begin InputStringGrid.ColCount := InputStringGrid.ColCount + 1; CleanFields(OutputStringGrid); end; procedure TMainForm.ButtonFindClick(Sender: TObject); begin if ReadingGrid(InputArray, InputStringGrid) then begin FindOddNumbers(InputArray, OutputArray); ExtendFields(OutputStringGrid, length(OutputArray)); PrintArray(OutputArray, OutputStringGrid, 0); end else ShowMessage('Заполните корректно поля(Исходный файл)'); end; procedure TMainForm.ButtonSaveFileClick(Sender: TObject); begin if length(OutputStringGrid.Cells[0,0]) <> 0 then begin SaveFileDialog.Filter := 'Text Files only |*.txt'; if SaveFileDialog.Execute then begin PrintArrayIntoFile(OutputArray, SaveFileDialog.FileName); ShowMessage('Запись в файл прошла успешно'); end; end else ShowMEssage('ЭЭЭНЕЕТ. Пустой файл мы сейвить не будем'); end; procedure TMainForm.ButtonCleanAllClick(Sender: TObject); begin CleanFields(InputStringGrid); CleanFields(OutputStringGrid); end; procedure TMainForm.InputStringGridClick(Sender: TObject); begin CleanFields(OutputStringGrid); end; end.
unit Choice; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ImgList, ComCtrls, Menus, ExtCtrls, ImageList, LevelFunctions; type TLevelChoice = class(TForm) PlayBtn: TButton; CancelBtn: TButton; LevelImageList: TImageList; LevelPopupMenu: TPopupMenu; PLoadLevel: TMenuItem; PRefreshList: TMenuItem; PreviewGrp: TGroupBox; PreviewImage: TImage; LevelGrp: TGroupBox; LevelList: TListView; procedure PlayBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure LevelListClick(Sender: TObject); procedure LevelListChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure PRefreshListClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure RefreshList; procedure DrawLevelPreview(Level: TLevel); public function SelectedLevel: string; end; var LevelChoice: TLevelChoice; implementation {$R *.dfm} uses Functions, Constants; procedure TLevelChoice.DrawLevelPreview(Level: TLevel); var PlaygroundMatrix: TPlayGroundMatrix; y, x: integer; indent: Integer; Image: TImage; BackgroundColor: TColor; const PREVIEW_BLOCK_SIZE = 10; // Enthält Field und Abstand PREVIEW_TAB_SIZE = PREVIEW_BLOCK_SIZE div 2; // 5 begin Image := PreviewImage; BackgroundColor := Self.Color; ClearImage(Image, BackgroundColor); Level.FillPlaygroundMatrix(PlaygroundMatrix, false); try for x := Low(PlaygroundMatrix.Fields) to High(PlaygroundMatrix.Fields) do begin for y := Low(PlaygroundMatrix.Fields[x]) to High(PlaygroundMatrix.Fields[x]) do begin // Rectange filling case PlaygroundMatrix.Fields[x,y].FieldType of ftFullSpace: Image.Canvas.Brush.Color := BackgroundColor; // invisible ftEmpty: Image.Canvas.Brush.Color := clWhite; ftGreen: Image.Canvas.Brush.Color := clLime; ftYellow: Image.Canvas.Brush.Color := clYellow; ftRed: Image.Canvas.Brush.Color := clRed; end; // Rectangle border if PlaygroundMatrix.Fields[x,y].Goal then Image.Canvas.Pen.Color := clBlack else begin if PlaygroundMatrix.Fields[x,y].FieldType = ftFullSpace then Image.Canvas.Pen.Color := BackgroundColor // invisible else Image.Canvas.Pen.Color := clLtGray; end; // Draw the rectangle indent := PlaygroundMatrix.Fields[x,y].Indent; Image.Canvas.Rectangle(x*PREVIEW_BLOCK_SIZE + indent*PREVIEW_TAB_SIZE, y*PREVIEW_BLOCK_SIZE, x*PREVIEW_BLOCK_SIZE + indent*PREVIEW_TAB_SIZE + PREVIEW_BLOCK_SIZE, y*PREVIEW_BLOCK_SIZE + PREVIEW_BLOCK_SIZE); end; end; finally PlaygroundMatrix.ClearMatrix(true); end; end; function TLevelChoice.SelectedLevel: string; begin result := Format(LVL_FILE, [LevelList.Selected.Caption]); end; procedure TLevelChoice.PlayBtnClick(Sender: TObject); var Level: TLevel; begin if Assigned(LevelList.Selected) then begin if LevelList.Selected.ImageIndex = 2 then begin Level := TLevel.Create(Format(LVL_FILE, [LevelList.Selected.Caption])); try if Level.CheckLevelIntegrity(true) <> leNone then begin exit; end; finally FreeAndNil(Level); end; end; ModalResult := mrOk; end; end; procedure TLevelChoice.CancelBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TLevelChoice.FormShow(Sender: TObject); begin RefreshList; end; procedure TLevelChoice.LevelListClick(Sender: TObject); var LevelFile: string; Level: TLevel; begin PlayBtn.Enabled := Assigned(LevelList.Selected); PLoadLevel.Enabled := Assigned(LevelList.Selected); if Assigned(LevelList.Selected) then begin LevelFile := Format(LVL_FILE, [LevelList.Selected.Caption]); Level := TLevel.Create(LevelFile); try DrawLevelPreview(Level); finally FreeAndNil(Level); end; end else begin ClearImage(PreviewImage, Color); end; end; procedure TLevelChoice.LevelListChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if Change = ctState then LevelListClick(self); end; procedure TLevelChoice.PRefreshListClick(Sender: TObject); begin RefreshList; end; procedure TLevelChoice.RefreshList; var s: TSearchRec; Level: TLevel; begin LevelList.Clear; // Levels auflisten if FindFirst(Format(LVL_FILE, ['*']), faAnyFile, s) = 0 then begin repeat with LevelList.Items.Add do begin Caption := Copy(s.Name, 1, Length(s.Name)-Length(LVL_EXT)); Level := TLevel.Create(LVL_PATH + s.Name); if Level.CheckLevelIntegrity <> leNone then ImageIndex := 2{Error} else case Level.GameMode of gmNormal: ImageIndex := 0{Normal}; gmDiagonal: ImageIndex := 1{Diagonal}; gmUndefined: ImageIndex := 2{Error}; end; end; until FindNext(s) <> 0; FindClose(s); end; end; procedure TLevelChoice.FormCreate(Sender: TObject); begin if not ForceDirectories(ExtractFilePath(Application.ExeName) + LVL_PATH) then begin MessageDlg(Format(LNG_COULD_NOT_CREATE_DIR, [LVL_PATH]), mtError, [mbOK], 0); end; end; end.
unit CreateNewMaze; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, MazeMain; type TFCreateNewMaze = class(TForm) lbHead: TLabel; lbAlgGenText: TLabel; cbAlgGen: TComboBox; lbMazeSizeText: TLabel; cbMazeSize: TComboBox; btnCreateMaze: TButton; procedure btnCreateMazeClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbAlgGenChange(Sender: TObject); procedure cbMazeSizeChange(Sender: TObject); procedure cbDelLbClick(Sender: TObject); private MazeAlgGen: TMazeGenAlg; MazeSize: TMazeSize; cbFlag1, cbFlag2: Boolean; { Private declarations } public { Public declarations } end; implementation uses MainMenu, MazeView; {$R *.dfm} procedure TFCreateNewMaze.cbDelLbClick(Sender: TObject); begin if (TComboBox(Sender).ItemIndex <> 0) and (TComboBox(Sender).Items[0] = 'Выбрать...') then TComboBox(Sender).Items.Delete(0); end; //Chose Generation Alg and SizeOf Maze procedure TFCreateNewMaze.cbAlgGenChange(Sender: TObject); begin if cbAlgGen.Items[0] = 'Выбрать...' then exit; MazeAlgGen := TMazeGenAlg(cbAlgGen.ItemIndex); cbFlag1 := True; if cbFlag2 = True then begin btnCreateMaze.Enabled := True; btnCreateMaze.SetFocus; end; end; procedure TFCreateNewMaze.cbMazeSizeChange(Sender: TObject); begin if cbMazeSize.Items[0] = 'Выбрать...' then exit; MazeSize := TMazeSize(cbMazeSize.ItemIndex); cbFlag2 := True; if cbFlag1 = True then begin btnCreateMaze.Enabled := True; btnCreateMaze.SetFocus; end; end; //Show New Form procedure TFCreateNewMaze.btnCreateMazeClick(Sender: TObject); begin FMazeView.CreateFirstMaze(MazeSize, MazeAlgGen); FMazeView.Position := poOwnerFormCenter; FMazeView.Show(MainMenuForm); end; procedure TFCreateNewMaze.FormClose(Sender: TObject; var Action: TCloseAction); begin Self.Hide; end; end.
unit WpcStatements; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Fgl, DateUtils, WpcStatementProperties, WpcScriptCommons, WpcCommonTypes, WpcWallpaperStyles, WpcExceptions; type { IWpcScriptStatement } IWpcBaseScriptStatement = class public function GetId() : TWpcStatemetId; virtual; abstract; end; { TWpcWaitStatement } TWpcWaitStatement = class(IWpcBaseScriptStatement) private FDelay : TWpcDelayStatementProperty; FProbability : TWpcProbabilityStatementProperty; FTimes : TWpcTimesStatementProperty; public constructor Create(Delay : LongWord); destructor Destroy(); override; public procedure SetDelay(Delay : LongWord); function GetDelay() : LongWord; procedure SetProbability(Probability : Byte); function GetProbability() : Byte; procedure SetTimes(Times : LongWord); function GetTimes() : LongWord; function GetId() : TWpcStatemetId; override; end; { TWpcWallpaperStatement } TWpcWallpaperStatement = class(IWpcBaseScriptStatement) private FImage : TWpcImage; FStyle : TWallpaperStyle; FDelay : TWpcDelayStatementProperty; FProbability : TWpcProbabilityStatementProperty; public constructor Create(Image : TWpcImage); destructor Destroy(); override; public procedure SetImage(Image : TWpcImage); function GetImage() : TWpcImage; procedure SetStyle(Style : TWallpaperStyle); function GetStyle() : TWallpaperStyle; procedure SetDelay(Delay : LongWord); function GetDelay() : LongWord; procedure SetProbability(Probability : Byte); function GetProbability() : Byte; function GetId() : TWpcStatemetId; override; end; { TWpcStopStatement } TWpcStopStatement = class(IWpcBaseScriptStatement) private FProbability : TWpcProbabilityStatementProperty; public constructor Create(); destructor Destroy(); override; public procedure SetProbability(Probability : Byte); function GetProbability() : Byte; function GetId() : TWpcStatemetId; override; end; { IWpcBranchReferrer } IWpcBranchReferrer = class abstract(IWpcBaseScriptStatement) protected FBarnchName : String; public procedure SetBarnchName(BranchName : String); function GetBranchName() : String; end; { TWpcSwitchBranch } TWpcSwitchBranchStatement = class(IWpcBranchReferrer) private FProbability : TWpcProbabilityStatementProperty; public constructor Create(BranchName : String); destructor Destroy(); override; public procedure SetProbability(Probability : Byte); function GetProbability() : Byte; function GetId() : TWpcStatemetId; override; end; { TWpcUseBranchStatement } TWpcUseBranchStatement = class(TWpcSwitchBranchStatement) private FTimes : TWpcTimesStatementProperty; public constructor Create(BranchName : String); destructor Destroy(); override; public procedure SetTimes(Times : LongWord); function GetTimes() : LongWord; function GetId() : TWpcStatemetId; override; end; { TWpcChooserItem } // This class should be located inside TWpcAbstarctChooserStatement and // Statement field should be generic filed (exactly as T in TWpcAbstarctChooserStatement), // but due to limitations of Free Pascal and fgl it is here along with comparator function. TWpcChooserItem = class(TObject) public Statement : IWpcBaseScriptStatement; Weight : LongWord; // All TWpcAbstarctChooserStatement.Selector types are converted into sequental values end; TListOfChooserItems = specialize TFPGList<TWpcChooserItem>; { IWpcChooserItems } IWpcChooserItems = class abstract(IWpcBaseScriptStatement) function GetItems() : TListOfChooserItems; virtual; abstract; end; { TWpcAbstarctChooserStatement } TWpcSelector = (S_WEIGHT, S_SEASON, S_WEEKDAY, S_MONTH, S_DATE, S_TIME, S_DATETIME); TWpcSelectorValueHolder = record case Byte of 1: (Weight : LongWord); 2: (DateTime : TDateTime); 3: (Sequential : Integer); end; generic TWpcAbstarctChooserStatement<T : IWpcBaseScriptStatement> = class abstract(IWpcChooserItems) protected FSelector : TWpcSelector; FItems : TListOfChooserItems; FFinished : Boolean; // Locks AddItem after ChooseItem call FTotalWeight : LongWord; // Is used to cache sum of item's weights public constructor Create(Selector : TWpcSelector); destructor Destroy(); override; public function GetSelector() : TWpcSelector; function GetItems() : TListOfChooserItems; override; procedure AddItem(Item : T; SelectorValue : TWpcSelectorValueHolder); function ChooseItem(): T; protected function ChooseItemByWeight() : T; function ChooseItemBySeason() : T; function ChooseItemByCurrentSequentialValue(CurrentValue : LongWord) : T; function ConvertToSequentialValue(DateTimeValue : TDateTime) : LongWord; function GetTotalWeight(): LongWord; private procedure AddWeightItem(Item : T; Weight : LongWord); procedure AddDateTimeItem(Item : T; DateTime : TDateTime); procedure AddSequentialItem(Item : T; SequentialNumber : Integer); procedure EnsureNoDuplicateSelectorValueExists(SelectorValue : LongWord); function FindItemByWeight(Weight : LongWord) : Integer; end; { TWpcWallpaperChooserStatement } TWpcWallpaperChooserStatement = class(specialize TWpcAbstarctChooserStatement<TWpcWallpaperStatement>) public function GetId() : TWpcStatemetId; override; end; { TWpcSwitchBranchChooserStatement } TWpcSwitchBranchChooserStatement = class(specialize TWpcAbstarctChooserStatement<TWpcSwitchBranchStatement>) public function GetId() : TWpcStatemetId; override; end; { TWpcUseBranchChooserStatement } TWpcUseBranchChooserStatement = class(specialize TWpcAbstarctChooserStatement<TWpcUseBranchStatement>) public function GetId() : TWpcStatemetId; override; end; { TWpcBranchStatement } TListOfBranchStatements = specialize TFPGList<IWpcBaseScriptStatement>; TWpcBranchStatement = class(IWpcBaseScriptStatement) private FStatements : TListOfBranchStatements; FBranchName : String; public constructor Create(BranchName : String); destructor Destroy(); override; public procedure AddStatement(Statement : IWpcBaseScriptStatement); function GetStatement(StatementNumber : Integer) : IWpcBaseScriptStatement; function GetBranchStatements() : TListOfBranchStatements; function CountStatements() : Integer; function GetName() : String; function GetId() : TWpcStatemetId; override; end; // Due to Free Pascal limitations it is here, but should be in implementation section. function ComparatorTWpcChooserItem(const Item1, Item2 : TWpcChooserItem) : Integer; implementation { TWpcWaitStatement } function TWpcWaitStatement.GetId() : TWpcStatemetId; begin Result := WPC_WAIT_STATEMENT_ID; end; constructor TWpcWaitStatement.Create(Delay : LongWord); begin FDelay := TWpcDelayStatementProperty.Create(); FProbability := TWpcProbabilityStatementProperty.Create(); FTimes := TWpcTimesStatementProperty.Create(); FDelay.Delay := Delay; end; destructor TWpcWaitStatement.Destroy(); begin FDelay.Free(); FProbability.Free(); FTimes.Free(); inherited Destroy; end; procedure TWpcWaitStatement.SetDelay(Delay : LongWord); begin FDelay.Delay := Delay; end; function TWpcWaitStatement.GetDelay() : LongWord; begin Result := FDelay.Delay; end; procedure TWpcWaitStatement.SetProbability(Probability : Byte); begin FProbability.Probability := Probability; end; function TWpcWaitStatement.GetProbability() : Byte; begin Result := FProbability.Probability; end; procedure TWpcWaitStatement.SetTimes(Times : LongWord); begin FTimes.Times := Times; end; function TWpcWaitStatement.GetTimes() : LongWord; begin Result := FTimes.Times; end; { TWpcWallpaperStatement } function TWpcWallpaperStatement.GetId() : TWpcStatemetId; begin Result := WPC_WALLPAPER_STATEMENT_ID; end; constructor TWpcWallpaperStatement.Create(Image : TWpcImage); begin if (Image = nil) then raise TWpcIllegalArgumentException.Create('Wallpaper image is mandatory.'); FImage := Image; FDelay := TWpcDelayStatementProperty.Create(); FProbability := TWpcProbabilityStatementProperty.Create(); end; destructor TWpcWallpaperStatement.Destroy(); begin FImage.Free(); FDelay.Free(); FProbability.Free(); inherited Destroy(); end; procedure TWpcWallpaperStatement.SetImage(Image : TWpcImage); begin if (Image <> nil) then FImage := Image; end; function TWpcWallpaperStatement.GetImage() : TWpcImage; begin Result := FImage; end; procedure TWpcWallpaperStatement.SetStyle(Style : TWallpaperStyle); begin FStyle := Style; end; function TWpcWallpaperStatement.GetStyle() : TWallpaperStyle; begin Result := FStyle; end; procedure TWpcWallpaperStatement.SetDelay(Delay : LongWord); begin FDelay.Delay := Delay; end; function TWpcWallpaperStatement.GetDelay() : LongWord; begin Result := FDelay.Delay; end; procedure TWpcWallpaperStatement.SetProbability(Probability : Byte); begin FProbability.Probability := Probability; end; function TWpcWallpaperStatement.GetProbability() : Byte; begin Result := FProbability.Probability; end; { TWpcStopStatement } function TWpcStopStatement.GetId() : TWpcStatemetId; begin Result := WPC_STOP_STATEMENT_ID; end; constructor TWpcStopStatement.Create(); begin FProbability := TWpcProbabilityStatementProperty.Create(); end; destructor TWpcStopStatement.Destroy(); begin FProbability.Free(); inherited Destroy(); end; procedure TWpcStopStatement.SetProbability(Probability : Byte); begin FProbability.Probability := Probability; end; function TWpcStopStatement.GetProbability() : Byte; begin Result := FProbability.Probability; end; { IWpcBranchReferrer } procedure IWpcBranchReferrer.SetBarnchName(BranchName : String); begin FBarnchName := BranchName; end; function IWpcBranchReferrer.GetBranchName() : String; begin Result := FBarnchName; end; { TWpcSwitchBranchStatement } function TWpcSwitchBranchStatement.GetId() : TWpcStatemetId; begin Result := WPC_SWITCH_BRANCH_STATEMENT_ID; end; constructor TWpcSwitchBranchStatement.Create(BranchName : String); begin FBarnchName := BranchName; FProbability := TWpcProbabilityStatementProperty.Create(); end; destructor TWpcSwitchBranchStatement.Destroy(); begin FProbability.Free(); inherited Destroy(); end; procedure TWpcSwitchBranchStatement.SetProbability(Probability : Byte); begin FProbability.Probability := Probability; end; function TWpcSwitchBranchStatement.GetProbability() : Byte; begin Result := FProbability.Probability; end; { TWpcUseBranchStatement } function TWpcUseBranchStatement.GetId() : TWpcStatemetId; begin Result := WPC_USE_BRANCH_STATEMENT_ID; end; constructor TWpcUseBranchStatement.Create(BranchName : String); begin FTimes := TWpcTimesStatementProperty.Create(); inherited Create(BranchName); end; destructor TWpcUseBranchStatement.Destroy(); begin FTimes.Free(); inherited Destroy(); end; procedure TWpcUseBranchStatement.SetTimes(Times : LongWord); begin FTimes.Times := Times; end; function TWpcUseBranchStatement.GetTimes() : LongWord; begin Result := FTimes.Times; end; { TWpcAbstarctChooserStatement } constructor TWpcAbstarctChooserStatement.Create(Selector : TWpcSelector); begin FFinished := False; FSelector := Selector; FItems := TListOfChooserItems.Create(); end; destructor TWpcAbstarctChooserStatement.Destroy(); var Item : TWpcChooserItem; begin for Item in FItems do begin Item.Statement.Free(); Item.Free(); end; FItems.Free(); inherited Destroy(); end; function TWpcAbstarctChooserStatement.GetSelector() : TWpcSelector; begin Result := FSelector; end; { Returns Chooser items. Any changes in returned list will affect the chooser. } function TWpcAbstarctChooserStatement.GetItems() : TListOfChooserItems; begin Result := FItems; end; { Adds an item to the Chooser list. Depending on Chooser selector, selector value is interpretted in different ways: - WEIGHT selector: as a weight of item - S_SEASON and S_WEEKDAY: as a sequential number of the specified selector - S_MONTH, S_DATE, S_TIME, S_DATETIME as a DateTime encoded into FileDate } procedure TWpcAbstarctChooserStatement.AddItem(Item : T; SelectorValue : TWpcSelectorValueHolder); begin if (FFinished) then raise TWpcUseErrorException.Create('This container is completed'); if (FSelector = TWpcSelector.S_WEIGHT) then AddWeightItem(Item, SelectorValue.Weight) else if (FSelector in [S_SEASON, S_MONTH, S_WEEKDAY]) then AddSequentialItem(Item, SelectorValue.Sequential) else if (FSelector in [S_DATE, S_TIME, S_DATETIME]) then AddDateTimeItem(Item, SelectorValue.DateTime) else raise TWpcIllegalArgumentException.Create('Unknown selector type.'); end; { Returns chose item. Can be used many times. Each call will cause reselect. After call of this method, calling of AddItem will couse an error. } function TWpcAbstarctChooserStatement.ChooseItem() : T; begin if (FItems.Count < 2) then raise TWpcUseErrorException.Create('Choose statement should contain at least 2 elements'); if (not FFinished) then begin FFinished := True; if (FSelector = S_WEIGHT) then FTotalWeight := GetTotalWeight() else FItems.Sort(@ComparatorTWpcChooserItem); end; case FSelector of S_WEIGHT: Result := ChooseItemByWeight(); S_SEASON: Result := ChooseItemBySeason(); S_WEEKDAY: Result := ChooseItemByCurrentSequentialValue(DayOfWeek(Now())); S_MONTH: Result := ChooseItemByCurrentSequentialValue(MonthOf(Now())); S_DATE: Result := ChooseItemByCurrentSequentialValue(DayOfTheYear(Now())); S_TIME: Result := ChooseItemByCurrentSequentialValue(SecondOfTheDay(Now())); S_DATETIME: Result := ChooseItemByCurrentSequentialValue(SecondOfTheYear(Now())); end; end; { This function selects value from the items list by random but proportionally to the items weights. } function TWpcAbstarctChooserStatement.ChooseItemByWeight() : T; var ChoseNumber : Integer; Sum : Integer; i : Integer; begin ChoseNumber := Random(FTotalWeight) + 1; Sum := 0; for i:=0 to (FItems.Count - 1) do begin Sum := Sum + FItems[i].Weight; if (Sum >= ChoseNumber) then break; end; // Cast is safe here, because Add methods use T in its argument Result := T(FItems[i].Statement); end; function TWpcAbstarctChooserStatement.ChooseItemBySeason() : T; var CurrentSeason : LongWord; begin // 1 - Winter, .. , 4 - Autumn case MonthOf(Now()) of 1,2,12: CurrentSeason := 1; 3,4,5: CurrentSeason := 2; 6,7,8: CurrentSeason := 3; 9,10,11: CurrentSeason := 4; end; Result := ChooseItemByCurrentSequentialValue(CurrentSeason); end; { This function selects value from the items list which correspond current value, i.e. searches for item with >= value than given (current). Note, that list 'is cycled', i.e. if given value is less than first then last item will be returned. Also items list should be sorted before first call. } function TWpcAbstarctChooserStatement.ChooseItemByCurrentSequentialValue(CurrentValue : LongWord) : T; var i : Integer; begin // finds next item number for i:=0 to (FItems.Count - 1) do if (FItems[i].Weight > CurrentValue) then break; // now previous item is the wanted one if (i = 0) then i := FItems.Count - 1 else Dec(i); // Cast is safe here, because Add method use T in its argument Result := T(FItems[i].Statement); end; { Converts given date-time to its sequental value, Convertation algorithm depends on FChooseBy: MONTH: 1 - January, .. , 12 - December DATE: to sequential number of day in a year TIME: to sequential number of second in a day DATETIME: to sequential number of second in a year } function TWpcAbstarctChooserStatement.ConvertToSequentialValue(DateTimeValue : TDateTime) : LongWord; begin case (FSelector) of S_DATE: Result := DayOfTheYear(DateTimeValue); S_TIME: Result := SecondOfTheDay(DateTimeValue); S_DATETIME: Result := SecondOfTheYear(DateTimeValue); else raise TWpcUseErrorException.Create('Cannot convert selector to sequential value.'); end; end; function TWpcAbstarctChooserStatement.GetTotalWeight() : LongWord; var Item : TWpcChooserItem; TotalWeight : LongWord; begin TotalWeight := 0; for Item in FItems do TotalWeight := TotalWeight + Item.Weight; Result := TotalWeight; end; procedure TWpcAbstarctChooserStatement.AddWeightItem(Item : T; Weight : LongWord); var ChooserItem : TWpcChooserItem; begin ChooserItem := TWpcChooserItem.Create(); ChooserItem.Statement := Item; ChooserItem.Weight := Weight; FItems.Add(ChooserItem); end; procedure TWpcAbstarctChooserStatement.AddDateTimeItem(Item : T; DateTime : TDateTime); var ChooserItem : TWpcChooserItem; begin ChooserItem := TWpcChooserItem.Create(); ChooserItem.Statement := Item; ChooserItem.Weight := ConvertToSequentialValue(DateTime); EnsureNoDuplicateSelectorValueExists(ChooserItem.Weight); FItems.Add(ChooserItem); end; procedure TWpcAbstarctChooserStatement.AddSequentialItem(Item : T; SequentialNumber : Integer); var ChooserItem : TWpcChooserItem; begin ChooserItem := TWpcChooserItem.Create(); ChooserItem.Statement := Item; ChooserItem.Weight := SequentialNumber; EnsureNoDuplicateSelectorValueExists(ChooserItem.Weight); FItems.Add(ChooserItem); end; procedure TWpcAbstarctChooserStatement.EnsureNoDuplicateSelectorValueExists(SelectorValue : LongWord); begin if (FindItemByWeight(SelectorValue) <> -1) then raise TWpcIllegalArgumentException.Create('Duplicate selector value: "' + IntToStr(SelectorValue) + '".'); end; { Findsfor item with given weight and returns its index. If specified item not found -1 will be returned. } function TWpcAbstarctChooserStatement.FindItemByWeight(Weight : LongWord) : Integer; var i : Integer; begin for i:=0 to (FItems.Count - 1) do if (FItems[i].Weight = Weight) then begin Result := i; exit; end; Result := -1; end; // Comparator for TWpcChooserItem function ComparatorTWpcChooserItem(const Item1, Item2 : TWpcChooserItem) : Integer; begin if (Item1.Weight > Item2.Weight) then Result := 1 else if (Item1.Weight < Item2.Weight) then Result := -1 else Result := 0 end; { TWpcWallpaperChooserStatement } function TWpcWallpaperChooserStatement.GetId() : TWpcStatemetId; begin Result := WPC_WALLPAPER_CHOOSER_STATEMENT_ID; end; { TWpcSwitchBranchChooserStatement } function TWpcSwitchBranchChooserStatement.GetId() : TWpcStatemetId; begin Result := WPC_BRANCH_TO_SWITCH_CHOOSER_STATEMENT_ID; end; { TWpcUseBranchChooserStatement } function TWpcUseBranchChooserStatement.GetId() : TWpcStatemetId; begin Result := WPC_BRANCH_TO_USE_CHOOSER_STATEMENT_ID; end; { TWpcBranchStatement } function TWpcBranchStatement.GetId() : TWpcStatemetId; begin Result := WPC_BRANCH_STATEMENT_ID; end; constructor TWpcBranchStatement.Create(BranchName : String); begin FBranchName := BranchName; FStatements := TListOfBranchStatements.Create(); end; destructor TWpcBranchStatement.Destroy(); var Statement : IWpcBaseScriptStatement; begin for Statement in FStatements do Statement.Free(); FStatements.Free(); inherited Destroy(); end; procedure TWpcBranchStatement.AddStatement(Statement : IWpcBaseScriptStatement); begin FStatements.Add(Statement); end; function TWpcBranchStatement.GetStatement(StatementNumber : Integer) : IWpcBaseScriptStatement; begin Result := FStatements[StatementNumber]; end; function TWpcBranchStatement.GetBranchStatements() : TListOfBranchStatements; begin Result := FStatements; end; function TWpcBranchStatement.CountStatements() : Integer; begin Result := FStatements.Count; end; function TWpcBranchStatement.GetName() : String; begin Result := FBranchName; end; end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.MessageList.Settings; { Persistable settings associated with the messagelist viewer. } interface {$REGION 'documentation'} { TODO: - column settings for - TimeStamp columns - Name columns - Value columns - default filtered messages } {$ENDREGION} uses System.Classes, Spring, DDuce.Logger.Interfaces, LogViewer.Resources, LogViewer.Watches.Settings; type TLogMessageTypes = set of TLogMessageType; TMessageListSettings = class(TPersistent) private FAutoScrollMessages : Boolean; FAutoFilterMessages : Boolean; FDynamicAutoSizeColumns : Boolean; FOnChanged : Event<TNotifyEvent>; FVisibleMessageTypes : TLogMessageTypes; FWatchSettings : TWatchSettings; FLeftPanelWidth : Integer; FRightPanelWidth : Integer; FVisibleValueTypes : TStringList; protected {$REGION 'property access methods'} function GetVisibleValueTypes: TStrings; function GetAutoScrollMessages: Boolean; procedure SetAutoScrollMessages(const Value: Boolean); function GetOnChanged: IEvent<TNotifyEvent>; function GetVisibleMessageTypes: TLogMessageTypes; procedure SetVisibleMessageTypes(const Value: TLogMessageTypes); function GetAutoFilterMessages: Boolean; procedure SetAutoFilterMessages(const Value: Boolean); function GetDynamicAutoSizeColumns: Boolean; procedure SetDynamicAutoSizeColumns(const Value: Boolean); function GetLeftPanelWidth: Integer; procedure SetLeftPanelWidth(const Value: Integer); function GetRightPanelWidth: Integer; procedure SetRightPanelWidth(const Value: Integer); {$ENDREGION} procedure FVisibleValueTypesChange(Sender: TObject); procedure Changed; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure Assign(Source: TPersistent); override; property OnChanged: IEvent<TNotifyEvent> read GetOnChanged; property VisibleMessageTypes: TLogMessageTypes read GetVisibleMessageTypes write SetVisibleMessageTypes; property VisibleValueTypes: TStrings read GetVisibleValueTypes; property WatchSettings: TWatchSettings read FWatchSettings; published property AutoScrollMessages: Boolean read GetAutoScrollMessages write SetAutoScrollMessages; property AutoFilterMessages: Boolean read GetAutoFilterMessages write SetAutoFilterMessages; property DynamicAutoSizeColumns: Boolean read GetDynamicAutoSizeColumns write SetDynamicAutoSizeColumns; property LeftPanelWidth: Integer read GetLeftPanelWidth write SetLeftPanelWidth; property RightPanelWidth: Integer read GetRightPanelWidth write SetRightPanelWidth; end; implementation {$REGION 'construction and destruction'} procedure TMessageListSettings.AfterConstruction; begin inherited AfterConstruction; FOnChanged.UseFreeNotification := False; FVisibleValueTypes := TStringList.Create; FVisibleValueTypes.OnChange := FVisibleValueTypesChange; FVisibleValueTypes.Sorted := True; FVisibleValueTypes.Duplicates := dupIgnore; FVisibleMessageTypes := ALL_MESSAGES; FLeftPanelWidth := 250; FRightPanelWidth := 250; FWatchSettings := TWatchSettings.Create; end; procedure TMessageListSettings.BeforeDestruction; begin FVisibleValueTypes.Free; FWatchSettings.Free; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'property access methods'} function TMessageListSettings.GetAutoFilterMessages: Boolean; begin Result := FAutoFilterMessages; end; procedure TMessageListSettings.SetAutoFilterMessages(const Value: Boolean); begin if Value <> AutoFilterMessages then begin FAutoFilterMessages := Value; Changed; end; end; function TMessageListSettings.GetAutoScrollMessages: Boolean; begin Result := FAutoScrollMessages; end; procedure TMessageListSettings.SetAutoScrollMessages(const Value: Boolean); begin if Value <> AutoScrollMessages then begin FAutoScrollMessages := Value; Changed; end; end; function TMessageListSettings.GetDynamicAutoSizeColumns: Boolean; begin Result := FDynamicAutoSizeColumns; end; procedure TMessageListSettings.SetDynamicAutoSizeColumns(const Value: Boolean); begin if Value <> DynamicAutoSizeColumns then begin FDynamicAutoSizeColumns := Value; Changed; end; end; function TMessageListSettings.GetLeftPanelWidth: Integer; begin Result := FLeftPanelWidth; end; procedure TMessageListSettings.SetLeftPanelWidth(const Value: Integer); begin if Value <> LeftPanelWidth then begin FLeftPanelWidth := Value; Changed; end; end; function TMessageListSettings.GetVisibleMessageTypes: TLogMessageTypes; begin Result := FVisibleMessageTypes; end; procedure TMessageListSettings.SetVisibleMessageTypes( const Value: TLogMessageTypes); begin if Value <> VisibleMessageTypes then begin FVisibleMessageTypes := Value; Changed; end; end; function TMessageListSettings.GetVisibleValueTypes: TStrings; begin Result := FVisibleValueTypes; end; function TMessageListSettings.GetOnChanged: IEvent<TNotifyEvent>; begin Result := FOnChanged; end; function TMessageListSettings.GetRightPanelWidth: Integer; begin Result := FRightPanelWidth; end; procedure TMessageListSettings.SetRightPanelWidth(const Value: Integer); begin if Value <> RightPanelWidth then begin FRightPanelWidth := Value; Changed; end; end; {$ENDREGION} {$REGION 'event handlers'} procedure TMessageListSettings.FVisibleValueTypesChange(Sender: TObject); begin Changed; end; {$ENDREGION} {$REGION 'event dispatch methods'} procedure TMessageListSettings.Changed; begin FOnChanged.Invoke(Self); end; {$ENDREGION} {$REGION 'public methods'} procedure TMessageListSettings.Assign(Source: TPersistent); var LSettings: TMessageListSettings; begin if Source is TMessageListSettings then begin LSettings := TMessageListSettings(Source); AutoScrollMessages := LSettings.AutoScrollMessages; VisibleMessageTypes := LSettings.VisibleMessageTypes; DynamicAutoSizeColumns := LSettings.DynamicAutoSizeColumns; LeftPanelWidth := LSettings.LeftPanelWidth; RightPanelWidth := LSettings.RightPanelWidth; WatchSettings.Assign(LSettings.WatchSettings); end else inherited Assign(Source); end; {$ENDREGION} end.
{$I ACBr.inc} unit pciotMotoristaW; interface uses SysUtils, Classes, pcnAuxiliar, pcnConversao, pciotCIOT, ASCIOTUtil; type TGeradorOpcoes = class; TMotoristaW = class(TPersistent) private FGerador: TGerador; FMotorista: TMotorista; FOperacao: TpciotOperacao; FOpcoes: TGeradorOpcoes; public constructor Create(AOwner: TMotorista; AOperacao: TpciotOperacao = opObter); destructor Destroy; override; function GerarXML: boolean; published property Gerador: TGerador read FGerador write FGerador; property Motorista: TMotorista read FMotorista write FMotorista; property Opcoes: TGeradorOpcoes read FOpcoes write FOpcoes; end; TGeradorOpcoes = class(TPersistent) private FAjustarTagNro: boolean; FNormatizarMunicipios: boolean; FGerarTagAssinatura: TpcnTagAssinatura; FPathArquivoMunicipios: string; FValidarInscricoes: boolean; FValidarListaServicos: boolean; published property AjustarTagNro: boolean read FAjustarTagNro write FAjustarTagNro; property NormatizarMunicipios: boolean read FNormatizarMunicipios write FNormatizarMunicipios; property GerarTagAssinatura: TpcnTagAssinatura read FGerarTagAssinatura write FGerarTagAssinatura; property PathArquivoMunicipios: string read FPathArquivoMunicipios write FPathArquivoMunicipios; property ValidarInscricoes: boolean read FValidarInscricoes write FValidarInscricoes; property ValidarListaServicos: boolean read FValidarListaServicos write FValidarListaServicos; end; //////////////////////////////////////////////////////////////////////////////// implementation { TMotoristaW } uses ASCIOT; constructor TMotoristaW.Create(AOwner: TMotorista; AOperacao: TpciotOperacao); begin FMotorista := AOwner; FOperacao := AOperacao; FGerador := TGerador.Create; FGerador.FIgnorarTagNivel := '|?xml version|CTe xmlns|infCTe versao|obsCont|obsFisco|'; FOpcoes := TGeradorOpcoes.Create; FOpcoes.FAjustarTagNro := True; FOpcoes.FNormatizarMunicipios := False; FOpcoes.FGerarTagAssinatura := taSomenteSeAssinada; FOpcoes.FValidarInscricoes := False; FOpcoes.FValidarListaServicos := False; end; destructor TMotoristaW.Destroy; begin FGerador.Free; FOpcoes.Free; inherited Destroy; end; function TMotoristaW.GerarXML: boolean; var chave: AnsiString; Gerar: boolean; xProtCTe : String; begin Gerador.ArquivoFormatoXML := ''; Gerador.Opcoes.IdentarXML := True; // Gerador.Opcoes.TagVaziaNoFormatoResumido := False; case FOperacao of opObter: begin Gerador.wGrupo('ObterRequest ' + NAME_SPACE_EFRETE_MOTORISTAS_EFRETE); Gerador.wCampo(tcInt, 'CP2', 'CNH', 001, 007, 1, FMotorista.CNH, ''); Gerador.wCampo(tcInt, 'CP03', 'CPF', 001, 008, 1, FMotorista.CPF, ''); Gerador.wCampo(tcStr, 'CP04', 'Integrador', 001, 001, 1, TAmsCIOT( FMotorista.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'CP06', 'Versao', 001, 001, 1, 2, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('/ObterRequest'); end; opAdicionar: begin Gerador.wGrupo('GravarRequest ' + NAME_SPACE_EFRETE_MOTORISTAS_EFRETE, 'MP01'); Gerador.wCampo(tcStr, 'MP02', 'Integrador', 001, 001, 1, TAmsCIOT( FMotorista.Owner ).Configuracoes.Integradora.Identificacao, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'MP04', 'Versao', 001, 001, 1, 1, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'MP05', 'CNH', 001, 001, 1, FMotorista.CNH, 'Número de CNH do motorista'); Gerador.wCampo(tcStr, 'MP06', 'CPF', 001, 011, 1, FMotorista.CPF, 'CPF do motorista'); Gerador.wCampo(tcDat, 'MP07', 'DataNascimento', 001, 001, 1, FMotorista.DataNascimento, ''); with FMotorista do begin Gerador.wGrupo('Endereco', 'MP08'); Gerador.wCampo(tcStr, 'MP09', 'Bairro', 001, 001, 1, Endereco.Bairro, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'MP10', 'CEP', 001, 009, 1, Copy(Endereco.CEP, 1, 5) + '-' + Copy(Endereco.CEP, 6, 3), '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'MP11', 'CodigoMunicipio', 001, 007, 1, Endereco.CodigoMunicipio, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'MP12', 'Rua', 001, 001, 1, Endereco.Rua, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'MP13', 'Numero', 001, 001, 1, Endereco.Numero, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wCampo(tcStr, 'MP14', 'Complemento', 001, 001, 1, Endereco.Complemento, '', ' ' + NAME_SPACE_EFRETE_OBJECTS); Gerador.wGrupo('/Endereco'); end; Gerador.wCampo(tcStr, 'MP15', 'Nome', 001, 001, 1, FMotorista.Nome, ''); Gerador.wCampo(tcStr, 'MP16', 'NomeDeSolteiraDaMae', 001, 001, 1, FMotorista.NomeDeSolteiraDaMae, 'Será utilizado para autenticação no caso de ligação do motorista para o serviço de 0800.'); with FMotorista.Telefones do begin Gerador.wGrupo('Telefones', 'MP17'); Gerador.wGrupo('Celular ' + NAME_SPACE_EFRETE_OBJECTS, 'MP18'); Gerador.wCampo(tcInt, 'MP19', 'DDD', 001, 002, 1, Celular.DDD, ''); Gerador.wCampo(tcInt, 'MP20', 'Numero', 001, 009, 1, Celular.Numero, ''); Gerador.wGrupo('/Celular'); Gerador.wGrupo('Fax ' + NAME_SPACE_EFRETE_OBJECTS, 'MP21'); Gerador.wCampo(tcInt, 'MP22', 'DDD', 001, 002, 1, Fax.DDD, ''); Gerador.wCampo(tcInt, 'MP23', 'Numero', 001, 009, 1, Fax.Numero, ''); Gerador.wGrupo('/Fax'); Gerador.wGrupo('Fixo ' + NAME_SPACE_EFRETE_OBJECTS, 'MP24'); Gerador.wCampo(tcInt, 'MP25', 'DDD', 001, 002, 1, Fixo.DDD, ''); Gerador.wCampo(tcInt, 'MP26', 'Numero', 001, 009, 1, Fixo.Numero, ''); Gerador.wGrupo('/Fixo'); Gerador.wGrupo('/Telefones'); end; Gerador.wGrupo('/GravarRequest'); end; end; // Gerador.gtAjustarRegistros(Motorista.infCTe.ID); Result := (Gerador.ListaDeAlertas.Count = 0); end; end.
unit tmsUXlsEncodeFormula; {$INCLUDE ..\FLXCOMPILER.INC} interface uses tmsXlsFormulaMessages, tmsXlsMessages, tmsUXlsFormulaParser, tmsUFlxStack, tmsUXlsStrings, SysUtils, tmsUXlsBaseRecordLists, tmsUXlsRowColEntries, {$IFDEF DELPHI2008UP} Character, {$ENDIF} tmsUFlxMessages; type TParseString= class private ParsePos: integer; Fw: UTF16String; FParsedData: array of byte; FParsedArrayData: array of byte; MaxErrorLen: integer; DirectlyInFormula: UTF16String; LastRefOp: integer; FCellList: TCellList; StackWs: TWhiteSpaceStack; Default3DExternSheet: UTF16String; Force3d: boolean; //Named ranges InitialRefMode: TFmReturnType; function IsNumber(const c: UTF16Char): boolean; function IsAlpha(const c: UTF16Char): boolean; function IsAZ(const c: UTF16Char): boolean; function ATo1(const c: UTF16Char): integer; function NextChar: boolean; function PeekChar(out c: UTF16Char): boolean; function Peek2Char(out c: UTF16Char): boolean; function PeekCharWs(out c: UTF16Char): boolean; procedure GetNumber; procedure GetString; procedure GetAlpha; procedure GetArray; procedure GetFormulaArgs(const Index: integer; out ArgCount: integer); procedure GetFormula(const s: UTF16String); function GetBool(const s: UTF16String): boolean; function IsErrorCode(const s: UTF16String; out b: byte): boolean; procedure GetError; procedure GetOneReference(out RowAbs, ColAbs: boolean;out Row, Col: integer; out IsFullRowRange: Boolean; out IsFullColRange: Boolean); function GetReference(const OnlyPeek: boolean): boolean; procedure Factor; // [Whitespace]* Function | Number | String | Cell Reference | 3d Ref | (Expression) | NamedRange | Boolean | Err | Array procedure RefTerm; // Factor [ : | ' ' | , Factor] procedure NegTerm; // [-]* RefTerm procedure PerTerm; // NegTerm [%]* procedure ExpTerm; // PerTerm [ ^ PerTerm]* procedure MulTerm; // ExpTerm [ *|/ ExpTerm ]* procedure AddTerm; // MulTerm [ +|- MulTerm]* procedure AndTerm; // AddTerm [ & AddTerm]* procedure ComTerm; // AndTerm [ = | < | > | <= | >= | <> AndTerm]* procedure Expression; procedure SkipWhiteSpace; procedure UndoSkipWhiteSpace(const SaveParsePos: integer); procedure PopWhiteSpace; procedure AddParsed(const s: array of byte; const PopWs: boolean=true); procedure AddParsedArray(const s: array of byte); function FindComTerm(var Ptg: byte): boolean; procedure GetGeneric3dRef(const ExternSheet: UTF16String); procedure GetQuotedRef3d; procedure GetRef3d(const s: UTF16String); function GetExternSheet(const ExternSheet: UTF16String): word; procedure ConvertLastRefValueType(const RefMode: TFmReturnType); function GetLastRefOp: byte; class function GetPtgMode(const aptg: byte): TFmReturnType; procedure SetLastRefOp(const aptg: byte; const RefMode: TFmReturnType); procedure ConvertLastRefValueTypeOnce(const RefMode: TFmReturnType; var First: boolean); function IsDirectlyInFormula: boolean; procedure DiscardNormalWhiteSpace; procedure MakeLastWhitespaceNormal; function GetSecondAreaPart(const ExternSheet: UTF16String; const OnlyPeek: Boolean; Row1, Col1: Int32; const RowAbs1, ColAbs1, IsFullRowRange1, IsFullColRange1: Boolean): Boolean; procedure DoExternNamedRange(const ExternSheet: UTF16String); procedure AddParsedArea(const Rw1, Rw2, grBit1, grBit2: Int32); procedure AddParsed3dArea(const ExternSheet: UTF16String; const Rw1, Rw2, grBit1, grBit2: Int32); procedure AddParsed3dRef(const ExternSheet: UTF16String; const Rw1, grBit1: Int32); procedure AddParsedRef(const Rw1, grBit1: Int32); procedure AddParsedExternName(const ExternSheet, ExternName: UTF16String); public constructor Create(const aw: UTF16String; const aCellList: TCellList; const ReturnType: TFmReturnType); constructor CreateExt(const aw: UTF16String; const aCellList: TCellList; const aForce3D: Boolean; const aDefault3DExternSheet: UTF16String; const ReturnType: TFmReturnType); destructor Destroy; override; procedure Parse; function TotalSize: integer; procedure CopyToPtr(const Ptr: PArrayOfByte; const aPos: integer); procedure CopyToPtrNoLen(const Ptr: PArrayOfByte; const destIndex: integer); end; implementation function GetRealPtg(const PtgBase: word; const ReturnType: TFmReturnType): word; begin case ReturnType of fmArray: Result:=PtgBase+$40; fmRef : Result:=PtgBase; else Result:=PtgBase+$20; end; //case end; { TParseString } constructor TParseString.Create(const aw: UTF16String; const aCellList: TCellList; const ReturnType: TFmReturnType); begin inherited Create; Fw:= aw; ParsePos:=1; StackWs:=TWhiteSpaceStack.Create; FCellList:=aCellList; Force3D := false; InitialRefMode:=ReturnType; MaxErrorLen:=Length(fmErrNull); if MaxErrorLen<Length( fmErrDiv0 ) then MaxErrorLen:=Length(fmErrDiv0 ); if MaxErrorLen<Length( fmErrValue) then MaxErrorLen:=Length(fmErrValue); if MaxErrorLen<Length( fmErrRef ) then MaxErrorLen:=Length(fmErrRef ); if MaxErrorLen<Length( fmErrName ) then MaxErrorLen:=Length(fmErrName ); if MaxErrorLen<Length( fmErrNum ) then MaxErrorLen:=Length(fmErrNum ); if MaxErrorLen<Length( fmErrNA ) then MaxErrorLen:=Length(fmErrNA ); end; constructor TParseString.CreateExt(const aw: UTF16String; const aCellList: TCellList; const aForce3D: Boolean; const aDefault3DExternSheet: UTF16String; const ReturnType: TFmReturnType); begin Create(aw, aCellList, ReturnType); Default3DExternSheet := aDefault3DExternSheet; Force3D := aForce3d; end; destructor TParseString.Destroy; begin FreeAndNil(StackWs); inherited; end; function TParseString.GetLastRefOp: byte; begin Result:= FParsedData[LastRefOp]; end; procedure TParseString.SetLastRefOp(const aptg: byte; const RefMode: TFmReturnType); var newptg: Byte; begin newptg := Byte(aptg); if (Byte(aptg) and 96) <> 0 then begin case RefMode of fmRef: newptg := Byte((newptg and 159) or 32); fmValue: newptg := Byte((newptg and 159) or 64); fmArray: newptg := Byte(newptg or 96); end; //case end; FParsedData[LastRefOp] :=newptg; end; class function TParseString.GetPtgMode(const aptg: byte): TFmReturnType; var PtgMode: TFmReturnType; begin PtgMode := fmValue; if ((aptg = ptgRange) or (aptg = ptgIsect)) or (aptg = ptgUnion) then PtgMode := fmRef; case aptg and 96 of 32: PtgMode := fmRef; 96: PtgMode := fmArray; end; //case Result := PtgMode; end; procedure TParseString.ConvertLastRefValueType(const RefMode: TFmReturnType); var aptg: byte; PtgMode: TFmReturnType; begin if LastRefOp < 0 then raise Exception.Create(ErrInternal); aptg := GetLastRefOp; PtgMode := GetPtgMode(aptg); case RefMode of fmValue: begin if PtgMode <> fmArray then SetLastRefOp(aptg, fmValue); end; fmArray: begin SetLastRefOp(aptg, fmArray); end; end; end; procedure TParseString.ConvertLastRefValueTypeOnce(const RefMode: TFmReturnType; var First: boolean); begin if (First) then ConvertLastRefValueType(RefMode); First:=false; end; procedure TParseString.GetRef3d(const s: UTF16String); var c: UTF16Char; begin c := ' '; if not PeekChar(c) or (c <> fmExternalRef) then raise Exception.CreateFmt(ErrUnexpectedChar, [c, ParsePos, Fw]); NextChar; GetGeneric3dRef(s); end; procedure TParseString.GetQuotedRef3d; var e: UTF16Char; d: UTF16Char; More: Boolean; sq: UTF16String; c: UTF16Char; s: UTF16String; begin SkipWhiteSpace; s := ''; c := ' '; sq := fmSingleQuote; if not PeekChar(c) or (c <> sq) then raise Exception.CreateFmt(ErrUnexpectedChar, [c, ParsePos, Fw]); NextChar; repeat More := False; if PeekChar(c) and (c <> sq) then begin s:=s+c; NextChar; More := True; end else begin d := ' '; e := ' '; if PeekChar(d) and (d = sq) and Peek2Char(e) and (e = sq) then begin s:=s+sq; NextChar; NextChar; More := True; end; end; until not More; if not PeekChar(c) or (c <> sq) then raise Exception.CreateFmt(ErrUnterminatedString, [Fw]); NextChar; GetRef3d(s); end; procedure TParseString.Factor; var c: UTF16Char; begin if PeekCharWs(c) then begin if ord(c)>255 then raise Exception.CreateFmt(ErrUnexpectedChar, [AnsiChar(c), ParsePos, Fw]); if c= fmOpenParen then begin SkipWhiteSpace; NextChar; DirectlyInFormula := DirectlyInFormula + '0'; try Expression; finally Delete(DirectlyInFormula, Length(DirectlyInFormula), 1); end; if not (PeekCharWs(c)) or (c<>fmCloseParen) then raise Exception.CreateFmt(ErrMissingParen, [Fw]); SkipWhiteSpace; NextChar; PopWhiteSpace; AddParsed([ptgParen]); end else if c=fmStr then GetString else if c=fmOpenArray then GetArray else if c=fmErrStart then GetError else if not GetReference(false) then if (IsNumber(c) or (c = fmFormulaDecimal)) then GetNumber //Is number must go after getreference, to handle things like =sum(1:2) else if IsAlpha(c) then GetAlpha else if c=fmSingleQuote then GetQuotedRef3d(); end else raise Exception.CreateFmt(ErrUnexpectedEof, [Fw]); end; function TParseString.IsDirectlyInFormula: boolean; begin if (Length(DirectlyInFormula) <=0) then Result:= false else begin Result := DirectlyInFormula[Length(DirectlyInFormula)]='1'; end; end; procedure TParseString.RefTerm; // Factor [ : | ' ' | , Factor] var c: UTF16Char; b: byte; First: boolean; begin First:=true; Factor; //Pending: see how to fix intersect (on popwhitespace, if there are two references, is an intersect). //Union is only valid if we are not inside a function. For example A2:A3,B5 is ok. But HLookup(0,A2:A3,B5,1, true) is not ok. while PeekCharWS(c) and (((c=fmUnion) and not IsDirectlyInFormula) or (c=fmRangeSep) {or (c=fmIntersect)}) do begin ConvertLastRefValueTypeOnce(fmRef, First); SkipWhiteSpace; NextChar; Factor; ConvertLastRefValueType(fmRef); if (c=fmUnion) then b:=ptgUnion else if (c=fmRangeSep) then b:=ptgRange else if (c=fmIntersect) then b:=ptgIsect else raise Exception.Create(ErrInternal); AddParsed(b); end; end; procedure TParseString.NegTerm; //[-]* RefTerm var c: UTF16Char; i: integer; s: UTF16String; begin s:=''; while PeekCharWs(c) and ((c=fmMinus) or (c=fmPlus))do begin SkipWhiteSpace; NextChar; s:=s+c; end; RefTerm; if Length(s)>0 then begin ConvertLastRefValueType(fmValue); for i:=1 to Length(s) do if (s[i] = fmMinus) then AddParsed([ptgUminus]) else AddParsed([ptgUplus]); end; end; procedure TParseString.PerTerm; // NegTerm [%]* var c: UTF16Char; First: boolean; begin First:=true; NegTerm; while PeekCharWs(c) and (c=fmPercent) do begin ConvertLastRefValueTypeOnce(fmValue, First); SkipWhiteSpace; NextChar; AddParsed([ptgPercent]); end; end; procedure TParseString.ExpTerm; // PerTerm [ ^ PerTerm]* var c: UTF16Char; First: boolean; begin First:=true; PerTerm; while PeekCharWs(c) and (c=fmPower) do begin ConvertLastRefValueTypeOnce(fmValue, First); SkipWhiteSpace; NextChar; PerTerm; ConvertLastRefValueType(fmValue); AddParsed([ptgPower]); end; end; procedure TParseString.MulTerm; // ExpTerm [ *|/ ExpTerm ]* var c: UTF16Char; First: boolean; begin First:=true; ExpTerm; while PeekCharWs(c) and ((c=fmMul) or (c=fmDiv)) do begin ConvertLastRefValueTypeOnce(fmValue, First); SkipWhiteSpace; NextChar; ExpTerm; ConvertLastRefValueType(fmValue); if (c=fmMul) then AddParsed([ptgMul]) else AddParsed([ptgDiv]); end; end; procedure TParseString.AddTerm; // MulTerm [ +|- MulTerm]* var c: UTF16Char; First: boolean; begin First:=true; MulTerm; while PeekCharWs(c) and ((c=fmPlus) or (c=fmMinus)) do begin ConvertLastRefValueTypeOnce(fmValue, First); SkipWhiteSpace; NextChar; MulTerm; ConvertLastRefValueType(fmValue); if (c=fmPlus) then AddParsed([ptgAdd]) else AddParsed([ptgSub]); end; end; procedure TParseString.AndTerm; // AddTerm [ & AddTerm]* var c: UTF16Char; First: boolean; begin First:=true; AddTerm; while PeekCharWs(c) and (c=fmAnd) do begin ConvertLastRefValueTypeOnce(fmValue, First); SkipWhiteSpace; NextChar; AddTerm; ConvertLastRefValueType(fmValue); AddParsed([ptgConcat]); end; end; function TParseString.FindComTerm(var Ptg: byte): boolean; var c,d:UTF16Char; s: UTF16String; One: boolean; begin Result:= PeekCharWs(c) and ((c=fmEQ) or (c=fmLT) or (c=fmGT)); if Result then begin One:=true; SkipWhiteSpace; //Already granted we will add a ptg NextChar; if PeekChar(d)and((d=fmEQ) or (d=fmGT)) then begin s:=c; s:=s+d; One:=False; if s = fmGE then begin; NextChar; Ptg:=ptgGE; end else if s = fmLE then begin; NextChar; Ptg:=ptgLE; end else if s = fmNE then begin; NextChar; Ptg:=ptgNE; end else One:=True; end; If One then if c= fmEQ then Ptg:=ptgEQ else if c= fmLT then Ptg:=ptgLT else if c= fmGT then Ptg:=ptgGT else raise Exception.Create(ErrInternal); end; end; procedure TParseString.ComTerm; // AndTerm [ = | < | > | <= | >= | <> AndTerm]* var c: UTF16Char; Ptg: byte; First: boolean; begin First:=true; AndTerm; while PeekCharWs(c) and FindComTerm(Ptg) do begin //no NextChar or SkipWhitespace here. It is added by FindComTerm ConvertLastRefValueTypeOnce(fmValue, First); AndTerm; ConvertLastRefValueType(fmValue); AddParsed([Ptg]); end; end; procedure TParseString.Expression; begin ComTerm; end; procedure TParseString.GetNumber; var c: UTF16Char; d: double; w: word; ab: array[0..7] of byte; start: integer; begin SkipWhiteSpace; start:=ParsePos; while PeekChar(c) and (IsNumber(c)or (c=fmFormulaDecimal)) do NextChar; if PeekChar(c) and ((c='e')or (c='E')) then //numbers like 1e+23 begin NextChar; if PeekChar(c) and ((c=fmPlus)or (c=fmMinus)) then NextChar; while PeekChar(c) and IsNumber(c) do NextChar; //no decimals allowed here end; d:=fmStrToFloat(copy(FW, start, ParsePos-Start)); if (round(d)=d) and (d<=$FFFF)and (d>=0) then begin w:=round(d); AddParsed([ptgInt, byte(w), hi(word(w))]); end else begin move(d, ab[0], length(ab)); AddParsed([ptgNum, ab[0], ab[1], ab[2], ab[3], ab[4], ab[5], ab[6], ab[7]]); end; end; procedure TParseString.GetString; var c,d,e: UTF16Char; s: UTF16String; Xs: TExcelString; St: array of byte; More: boolean; begin s:=''; SkipWhiteSpace; if not PeekChar(c) or (c<>fmStr) then raise Exception.Create(ErrNotAString); NextChar; repeat More:=false; if PeekChar(c) and (c<>fmStr) then begin s:=s+c; NextChar; More:=true; end else begin if PeekChar(d) and (d=fmStr) and Peek2Char(e) and (e=fmStr) then begin s:=s+fmStr; NextChar; NextChar; More:=true; end; end; until not more; if not PeekChar(c) then raise Exception.CreateFmt(ErrUnterminatedString,[Fw]); NextChar; Xs:=TExcelString.Create(1,s); try SetLength(St, Xs.TotalSize+1); St[0]:=ptgStr; Xs.CopyToPtr(PArrayOfByte(St),1); AddParsed(St); finally FreeAndNil(Xs); end; //finally end; procedure TParseString.GetAlpha; // Possibilities: { 1 -> Formula - We know by the "(" at the end 2 -> Boolean - We just see if text is "true" or "false" 3 -> Error - No, we already cached this 4 -> Reference - Look if it is one of the strings between A1..IV65536 (and $A$1) As it might start with $, we don't look at it here. 5 -> 3d Ref - Search for a '!' As it migh start with "'" we don't look at it here. 6 -> Named Range - if it isn't anything else... } var Start: integer; s: string; //no need for widestring c: UTF16Char; begin SkipWhiteSpace; start:=ParsePos; while PeekChar(c) and ( IsAlpha(c) or IsNumber(c) or (c='.')or (c=':')) do NextChar; s:=UpperCase(copy(FW, start, ParsePos-Start)); if PeekChar(c) and (c=fmOpenParen) then GetFormula(s) else if PeekChar(c) and (c=fmExternalRef) then GetRef3d(s) else if not GetBool(s) then raise Exception.CreateFmt(ErrUnexpectedId,[s,Fw]); end; function TParseString.GetBool(const s: UTF16String): boolean; var b: byte; begin if s=fmTrue then b:=1 else if s=fmFalse then b:=0 else begin Result:=false; exit; end; AddParsed([ptgBool, b]); Result:=true; end; procedure TParseString.GetOneReference(out RowAbs, ColAbs: boolean; out Row, Col: integer; out IsFullRowRange: Boolean; out IsFullColRange: Boolean); var c: UTF16Char; begin RowAbs:=false; ColAbs:=false; IsFullColRange := true; //Something like 'B:B' IsFullRowRange := true; //something like '1:3' if PeekChar(c) and (c=fmAbsoluteRef) then begin ColAbs:=true; NextChar; end; Col:=0; while (PeekChar(c) and IsAZ(c)) and (Col <= (Max_Columns + 1)) do begin IsFullRowRange := false; NextChar; Col := (Col * ATo1('Z')) + ATo1(c); end; if ColAbs and IsFullRowRange then begin ColAbs := false; RowAbs := true; end else begin if PeekChar(c) and (c=fmAbsoluteRef) then begin RowAbs:=true; NextChar; end; end; Row:=0; while PeekChar(c) and IsNumber(c) and (Row<=Max_Rows+1) do begin NextChar; IsFullColRange := false; Row:=Row*10+(ord(c)-ord('0')); end; end; function TParseString.GetExternSheet(const ExternSheet: UTF16String): word; var i: integer; SheetName: UTF16String; Sheet1, Sheet2: integer; begin i:= pos (fmRangeSep, ExternSheet); if (i>0) then SheetName:=Copy(ExternSheet,1, i-1) else SheetName:=ExternSheet; if not FCellList.FindSheet(SheetName, Sheet1) then raise Exception.CreateFmt(ErrInvalidSheet, [SheetName]); if (i>0) then begin SheetName:=Copy(ExternSheet,i+1, Length(ExternSheet)); if not FCellList.FindSheet(SheetName, Sheet2) then raise Exception.CreateFmt(ErrInvalidSheet, [SheetName]); end else Sheet2:=Sheet1; Result:=FCellList.AddExternSheet(Sheet1, Sheet2); end; procedure TParseString.AddParsedRef(const Rw1: Int32; const grBit1: Int32); begin if Force3D then begin AddParsed3dRef(Default3DExternSheet, Rw1, grBit1 and not $0C000); exit; end; AddParsed([GetRealPtg(ptgRef,fmRef) , byte(Rw1), hi(word(Rw1)), byte(grBit1), hi(word(grBit1))]); end; procedure TParseString.AddParsed3dRef(const ExternSheet: UTF16String; const Rw1: Int32; const grBit1: Int32); var ESheet: word; begin ESheet:=GetExternSheet(ExternSheet); AddParsed([GetRealPtg(ptgRef3d,fmRef) ,byte(ESheet), hi(word(ESheet)), byte(Rw1), hi(word(Rw1)), byte(grBit1), hi(word(grBit1))]); end; procedure TParseString.AddParsedArea(const Rw1: Int32; const Rw2: Int32; const grBit1: Int32; const grBit2: Int32); begin if Force3D then begin AddParsed3dArea(Default3DExternSheet, Rw1, Rw2, grBit1 and not $0C000, grBit2 and not $0C000); exit; end; AddParsed([GetRealPtg(ptgArea,fmRef) , byte(Rw1), hi(word(Rw1)), byte(Rw2), hi(word(Rw2)), byte(grBit1), hi(word(grBit1)), byte(grBit2), hi(word(grBit2))]); end; procedure TParseString.AddParsed3dArea(const ExternSheet: UTF16String; const Rw1: Int32; const Rw2: Int32; const grBit1: Int32; const grBit2: Int32); var ESheet: word; begin ESheet:=GetExternSheet(ExternSheet); AddParsed([GetRealPtg(ptgArea3d,fmRef) ,byte(ESheet), hi(word(ESheet)), byte(Rw1), hi(word(Rw1)), byte(Rw2), hi(word(Rw2)), byte(grBit1), hi(word(grBit1)), byte(grBit2), hi(word(grBit2))]); end; procedure TParseString.AddParsedExternName(const ExternSheet: UTF16String; const ExternName: UTF16String); begin raise Exception.Create('External names are not supported: ' + ExternName); end; function TParseString.GetSecondAreaPart(const ExternSheet: UTF16String; const OnlyPeek: Boolean; Row1: Int32; Col1: Int32; const RowAbs1: Boolean; const ColAbs1: Boolean; const IsFullRowRange1: Boolean; const IsFullColRange1: Boolean): Boolean; var RowAbs2: Boolean; ColAbs2: Boolean; Row2: Int32; Col2: Int32; ActualPos: Int32; IsFullRowRange2: Boolean; IsFullColRange2: Boolean; rw1: Int32; grBit1: Int32; rw2: Int32; grBit2: Int32; begin RowAbs2 := false; ColAbs2 := false; Row2 := 0; Col2 := 0; ActualPos := ParsePos; NextChar; GetOneReference(RowAbs2, ColAbs2, Row2, Col2, IsFullRowRange2, IsFullColRange2); if IsFullRowRange1 and IsFullRowRange2 then begin Col1 := 1; Col2 := Max_Columns + 1; end; if IsFullColRange1 and IsFullColRange2 then begin Row1 := 1; Row2 := Max_Rows + 1; end; if (((Row2 > (Max_Rows + 1)) or (Row2 <= 0)) or (Col2 <= 0)) or (Col2 > (Max_Columns + 1)) then begin ParsePos := ActualPos; begin Result := false; exit; end; end; rw1 := Row1 - 1; grBit1 := (Col1 - 1) and $FF; if not RowAbs1 then grBit1 := (grBit1 or $8000); if not ColAbs1 then grBit1 := (grBit1 or $4000); rw2 := Row2 - 1; grBit2 := (Col2 - 1) and $FF; if not RowAbs2 then grBit2 := (grBit2 or $8000); if not ColAbs2 then grBit2 := (grBit2 or $4000); if not OnlyPeek then begin if ExternSheet <> '' then AddParsed3dArea(ExternSheet, rw1, rw2, grBit1, grBit2) else AddParsedArea(rw1, rw2, grBit1, grBit2); end; Result := true; end; procedure TParseString.DoExternNamedRange(const ExternSheet: UTF16String); var start: Int32; c: UTF16Char; s: UTF16String; begin start := ParsePos; c := ' '; while PeekChar(c) and (((IsAlpha(c) or IsNumber(c)) or (c = '.')) or (c = ':')) do begin NextChar; end; s := UpperCase(Copy(Fw, start, ParsePos - start)); AddParsedExternName(ExternSheet, s); end; procedure TParseString.GetGeneric3dRef(const ExternSheet: UTF16String); var RowAbs1: Boolean; ColAbs1: Boolean; Row1: Int32; Col1: Int32; IsFullRowRange1: Boolean; IsFullColRange1: Boolean; SavedPos: Int32; d: UTF16Char; c: UTF16Char; IsArea: Boolean; rw1: Int32; grBit1: Int32; begin RowAbs1 := False; ColAbs1 := False; Row1 := 0; Col1 := 0; SavedPos := ParsePos; d := ' '; GetOneReference(RowAbs1, ColAbs1, Row1, Col1, IsFullRowRange1, IsFullColRange1); if ((((Row1 <= 0) and (Col1 <= 0)) or (Row1 > (Max_Rows + 1))) or (Col1 > (Max_Columns + 1))) or (PeekChar(d) and IsAlpha(d)) then begin //something like "a3a" //Wasn't a valid reference. It might be a name ParsePos := SavedPos; DoExternNamedRange(ExternSheet); exit; end; if not IsFullRowRange1 and not IsFullColRange1 then begin if (Row1 > Max_Rows + 1) or (Row1 <= 0) or (Col1 <= 0) or (Col1 > Max_Columns + 1) then raise Exception.CreateFmt(ErrUnexpectedId, [IntToStr(Row1)+ ', '+ IntToStr(Col1), Fw]); end; c := ' '; IsArea := false; if PeekChar(c) and (c = fmRangeSep) then begin IsArea := GetSecondAreaPart(ExternSheet, false, Row1, Col1, RowAbs1, ColAbs1, IsFullRowRange1, IsFullColRange1); end; if not IsArea then begin if IsFullColRange1 or IsFullRowRange1 then begin raise Exception.CreateFmt(ErrUnexpectedId, [IntToStr(Row1) + ', ' + IntToStr(Col1), Fw]); end; rw1 := Row1 - 1; grBit1 := (Col1 - 1) and $FF; if not RowAbs1 then grBit1 := (grBit1 or $8000); if not ColAbs1 then grBit1 := (grBit1 or $4000); AddParsed3dRef(ExternSheet, rw1, grBit1); end; end; function TParseString.GetReference(const OnlyPeek: Boolean): Boolean; var SaveParsePos: Int32; RowAbs1: Boolean; ColAbs1: Boolean; Row1: Int32; Col1: Int32; IsFullRowRange1: Boolean; IsFullColRange1: Boolean; c: UTF16Char; IsArea: Boolean; rw1: Int32; grBit1: Int32; begin SaveParsePos := ParsePos; SkipWhiteSpace; RowAbs1 := false; ColAbs1 := false; Row1 := 0; Col1 := 0; GetOneReference(RowAbs1, ColAbs1, Row1, Col1, IsFullRowRange1, IsFullColRange1); if not IsFullRowRange1 and not IsFullColRange1 then begin if (Row1>Max_Rows+1) or (Row1<=0) or (Col1<=0) or (Col1>Max_Columns+1) then begin UndoSkipWhiteSpace(SaveParsePos); Result := false; exit; end; end; IsArea := false; if PeekChar(c) and (c = fmRangeSep) then begin IsArea := GetSecondAreaPart('', OnlyPeek, Row1, Col1, RowAbs1, ColAbs1, IsFullRowRange1, IsFullColRange1); end; if not IsArea then begin if IsFullColRange1 or IsFullRowRange1 then begin UndoSkipWhiteSpace(SaveParsePos); begin Result := false; exit; end; end; rw1 := Row1 - 1; grBit1 := (Col1-1) and $FF; if not RowAbs1 then grBit1 := grBit1 or $8000; if not ColAbs1 then grBit1 := grBit1 or $4000; if not OnlyPeek then AddParsedRef(rw1, grBit1); end; if OnlyPeek then begin UndoSkipWhiteSpace(SaveParsePos); end; Result := true; end; function TParseString.IsErrorCode(const s: UTF16String; out b: byte): boolean; begin Result:=true; b:=0; if s= fmErrNull then b:=fmiErrNull else if s= fmErrDiv0 then b:=fmiErrDiv0 else if s= fmErrValue then b:=fmiErrValue else if s= fmErrRef then b:=fmiErrRef else if s= fmErrName then b:=fmiErrName else if s= fmErrNum then b:=fmiErrNum else if s= fmErrNA then b:=fmiErrNA else Result:=false; end; procedure TParseString.GetError; var b: byte; Start: integer; s: UTF16String; c: UTF16Char; begin SkipWhiteSpace; start:=ParsePos; while PeekChar(c) do begin NextChar; s:=WideUpperCase98(copy(FW, start, ParsePos-Start)); if IsErrorCode(s, b) then begin AddParsed([ptgErr, b]); exit; end; if Length(s)>MaxErrorLen then break; end; raise Exception.CreateFmt(ErrUnexpectedId,[s,Fw]); end; function FindFormula(const s: UTF16String; var Index: integer): boolean; var i:integer; begin //Pending: optimize this to be binary search for i:=low(FuncNameArray) to High(FuncNameArray) do if FuncNameArray[i].Name=s then begin Result:=true; Index:=i; exit; end; Result:=False; end; function FuncParamType(const Index: integer; Position: integer): TFmReturnType; begin if (Position+1 > Length(FuncNameArray[Index].ParamType) - 1) then Position := Length(FuncNameArray[Index].ParamType)-1; case (FuncNameArray[Index].ParamType[Position+1]) of 'A': Result:= fmArray; 'R': Result:= fmRef; 'V': Result:= fmValue; '-': Result:= fmValue; //Missing Arg. else raise Exception.Create(ErrInternal); end; //case end; procedure TParseString.GetFormulaArgs(const Index: integer; out ArgCount: integer); var c: UTF16Char; MoreToCome: boolean; ActualPos: integer; begin ArgCount:=0; NextChar; //skip parenthesis c:= ' '; MoreToCome:=true; while MoreToCome do begin ActualPos := ParsePos; Expression; if (ParsePos = ActualPos) then //missing parameter. begin SkipWhiteSpace; if (ArgCount > 0) or (PeekChar(c) and (c=fmFunctionSep)) then begin MakeLastWhitespaceNormal; //No real need to call this here, but this way it will behave the same as Excel. (An space before the closing parenthesis on a missing arg is not a post whitespace but a normal space) AddParsed([ptgMissArg]); end else begin PopWhiteSpace(); dec(ArgCount); //This is not a real argument, as in PI() end; end else begin ConvertLastRefValueType(FuncParamType(Index, ArgCount)); SkipWhiteSpace(); DiscardNormalWhiteSpace(); //No space is allowed before a ",". We only keep the whitespace if it is for closing a parenthesis. end; if PeekCharWs(c) then begin //We should not call SkipWhitespace here, as it was already called. if c=fmFunctionSep then begin NextChar; if (not PeekChar(c)) then raise Exception.CreateFmt(ErrUnexpectedEof, [Fw]); end else if c = fmCloseParen then begin MoreTocome:=false; end else raise Exception.CreateFmt(ErrUnexpectedChar, [char(c), ParsePos, Fw]); end else raise Exception.CreateFmt(ErrUnexpectedEof, [Fw]); inc(ArgCount); end; if not PeekChar(c) then raise Exception.CreateFmt(ErrMissingParen, [Fw]); NextChar; if (ArgCount < FuncNameArray[Index].MinArgCount) or (ArgCount > FuncNameArray[Index].MaxArgCount) then raise Exception.CreateFmt(ErrInvalidNumberOfParams,[FuncNameArray[Index].Name, FuncNameArray[Index].MinArgCount,ArgCount]); end; procedure TParseString.GetFormula(const s: UTF16String); var Index, ArgCount: integer; Ptg: byte; begin if not FindFormula(s, Index) then raise Exception.CreateFmt(ErrFunctionNotFound,[s,Fw]); DirectlyInFormula := DirectlyInFormula + '1'; try GetFormulaArgs(Index, Argcount); finally Delete(DirectlyInFormula, Length(DirectlyInFormula), 1); end; if FuncNameArray[Index].MinArgCount <> FuncNameArray[Index].MaxArgCount then begin Ptg:=GetRealPtg(ptgFuncVar, FuncNameArray[Index].ReturnType); AddParsed([Ptg, ArgCount, byte(FuncNameArray[Index].Index), hi(word(FuncNameArray[Index].Index))]); end else begin Ptg:=GetRealPtg(ptgFunc, FuncNameArray[Index].ReturnType); AddParsed([Ptg, byte(FuncNameArray[Index].Index), hi(word(FuncNameArray[Index].Index))]); end; end; procedure TParseString.GetArray; var Rows, Cols: integer; c: UTF16Char; begin raise exception.Create('Writing array formulas is not yet supported'); SkipWhiteSpace; if not PeekChar(c) or (c<>fmOpenArray) then raise Exception.CreateFmt(ErrUnexpectedChar, [char(c), ParsePos, Fw]); NextChar; while PeekChar(c) and (c<>fmCloseArray) do begin NextChar; if c=fmArrayRowSep then inc(Rows) else if c=fmArrayColSep then inc(Cols); end; AddParsedArray([byte(Cols-1), byte(Rows-1), hi(word(Rows-1))]); //pending: add the data to array. if not PeekChar(c) then raise Exception.CreateFmt(ErrMissingParen, [Fw]); AddParsed([ptgArray, 0, 0, 0, 0, 0, 0, 0]); end; function TParseString.NextChar: boolean; begin Result:=ParsePos<=Length(Fw); if Result then begin inc(ParsePos); if ParsePos>1024 then raise Exception.CreateFmt(ErrFormulaTooLong,[Fw]); end; end; function TParseString.PeekChar(out c: UTF16Char): boolean; begin Result:=ParsePos<=Length(Fw); if Result then begin c:=Fw[ParsePos]; end; end; function TParseString.Peek2Char(out c: UTF16Char): boolean; begin Result:=ParsePos+1<=Length(Fw); if Result then begin c:=Fw[ParsePos+1]; end; end; function TParseString.PeekCharWs(out c: UTF16Char): boolean; var aParsePos: integer; begin aParsePos:= ParsePos; while (aParsePos<=Length(Fw)) and (Fw[aParsePos] =' ') do begin inc(aParsePos); end; Result:=aParsePos<=Length(Fw); if Result then begin c:=Fw[aParsePos]; end; end; procedure TParseString.SkipWhiteSpace; var Ws: TWhitespace; c: UTF16Char; begin Ws.Count:=0; while PeekChar(c) and (c =' ') do begin NextChar; if (Ws.Count<255) then inc(Ws.Count); end; if ParsePos<=Length(Fw) then begin c:=Fw[ParsePos]; if (c=fmOpenParen) then Ws.Kind:=attr_bitFPreSpace else if (c=fmCloseParen) then Ws.Kind:=attr_bitFPostSpace else Ws.Kind:= attr_bitFSpace; StackWs.Push(Ws); end; end; procedure TParseString.UndoSkipWhiteSpace(const SaveParsePos: integer); var Ws: TWhiteSpace; begin StackWs.Pop(Ws); ParsePos:=SaveParsePos; end; procedure TParseString.Parse; var c: UTF16Char; Ptr: PArrayOfByte; begin LastRefOp := -1; DirectlyInFormula := ''; SetLength(FParsedData,0); SetLength(FParsedArrayData,0); if not PeekChar(c) or (c<>fmStartFormula) then raise Exception.CreateFmt(ErrFormulaStart,[Fw]); NextChar; Expression; ConvertLastRefValueType(InitialRefMode); if PeekChar(c) then raise Exception.CreateFmt(ErrUnexpectedChar,[char(c), ParsePos, Fw]); if StackWs.Count<>0 then raise Exception.Create(ErrInternal); //Try to decode what we encoded //something like "= >" will be encoded nicely, but will crash when decoded GetMem(Ptr, TotalSize); try CopyToPtr(Ptr, 0); try RPNToString(Ptr, 2, FCellList); except raise Exception.CreateFmt(ErrFormulaInvalid,[Fw]); end; finally FreeMem(Ptr); end; //finally end; procedure TParseString.PopWhiteSpace; var Ws: TWhiteSpace; begin StackWs.Pop(Ws); if Ws.Count>0 then AddParsed([ptgAttr,$40,Ws.Kind, Ws.Count], false); end; procedure TParseString.DiscardNormalWhiteSpace; var Ws: TWhiteSpace; begin StackWs.Pop(Ws); if (Ws.Count>0) and (Ws.Kind <> attr_bitFSpace) then AddParsed([ptgAttr,$40,Ws.Kind, Ws.Count], false); end; procedure TParseString.MakeLastWhitespaceNormal; var Ws: TWhiteSpace; begin StackWs.Peek(Ws); Ws.Kind := attr_bitFSpace; end; procedure TParseString.AddParsed(const s: array of byte; const PopWs: boolean=true); begin if Length(s)= 0 then exit; if PopWs then PopWhiteSpace; if (s[0] <> ptgParen) and (s[0] <> ptgAttr) then //Those are "transparent" for reference ops. begin LastRefOp := Length(FParsedData); end; SetLength(FParsedData, Length(FParsedData)+ Length(s)); move(s[0], FParsedData[Length(FParsedData)-Length(s)], Length(s)); end; procedure TParseString.AddParsedArray(const s: array of byte); begin if Length(s)= 0 then exit; SetLength(FParsedArrayData, Length(FParsedArrayData)+ Length(s)); move(s[0], FParsedArrayData[Length(FParsedArrayData)-Length(s)], Length(s)); end; function TParseString.TotalSize: integer; begin Result:=2+Length(FParsedData)+Length(FParsedArrayData); end; procedure TParseString.CopyToPtr(const Ptr: PArrayOfByte; const aPos: integer); var w: word; begin w:=Length(FParsedData)+Length(FParsedArrayData); Move(w,ptr[aPos],2); Move(FParsedData[0],ptr[aPos+2], Length(FParsedData)); Move(FParsedArrayData[0],ptr[aPos+Length(FParsedData)+2], Length(FParsedArrayData)); end; procedure TParseString.CopyToPtrNoLen(const Ptr: PArrayOfByte; const destIndex: integer); begin Move(FParsedData[0],ptr[destIndex], Length(FParsedData)); Move(FParsedArrayData[0],ptr[destIndex+Length(FParsedData)], Length(FParsedArrayData)); end; function TParseString.IsNumber(const c: UTF16Char): boolean; begin Result:=(ord(c)<255) and (AnsiChar(c) in ['0'..'9']) end; function TParseString.IsAlpha(const c: UTF16Char): boolean; begin {$IFDEF DELPHI2008UP} Result := TCharacter.IsLetter(c) or (c = '_') or (c = '\'); {$ELSE} Result:=(ord(c)<255) and (AnsiChar(c) in ['A'..'Z','_','\','a'..'z']) {$ENDIF} end; function TParseString.IsAZ(const c: UTF16Char): boolean; begin Result:=(ord(c)<255) and (AnsiChar(c) in ['A'..'Z','a'..'z']) end; function TParseString.ATo1(const c: UTF16Char): integer; begin Result:= ord(UpCase(AnsiChar(c)))-Ord('A')+1; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995,99 Inprise Corporation } { } {*******************************************************} unit AppEvnts; interface uses Windows, Messages, SysUtils, Classes, Forms, ActnList; type TCustomApplicationEvents = class(TComponent) private FOnActionExecute: TActionEvent; FOnActionUpdate: TActionEvent; FOnException: TExceptionEvent; FOnMessage: TMessageEvent; FOnHelp: THelpEvent; FOnHint: TNotifyEvent; FOnIdle: TIdleEvent; FOnDeactivate: TNotifyEvent; FOnActivate: TNotifyEvent; FOnMinimize: TNotifyEvent; FOnRestore: TNotifyEvent; FOnShortCut: TShortCutEvent; FOnShowHint: TShowHintEvent; procedure DoActionExecute(Action: TBasicAction; var Handled: Boolean); procedure DoActionUpdate(Action: TBasicAction; var Handled: Boolean); procedure DoActivate(Sender: TObject); procedure DoDeactivate(Sender: TObject); procedure DoException(Sender: TObject; E: Exception); procedure DoIdle(Sender: TObject; var Done: Boolean); function DoHelp(Command: Word; Data: Longint; var CallHelp: Boolean): Boolean; procedure DoHint(Sender: TObject); procedure DoMessage(var Msg: TMsg; var Handled: Boolean); procedure DoMinimize(Sender: TObject); procedure DoRestore(Sender: TObject); procedure DoShowHint(var HintStr: string; var CanShow: Boolean; var HintInfo: THintInfo); procedure DoShortcut(var Msg: TWMKey; var Handled: Boolean); protected property OnActionExecute: TActionEvent read FOnActionExecute write FOnActionExecute; property OnActionUpdate: TActionEvent read FOnActionUpdate write FOnActionUpdate; property OnActivate: TNotifyEvent read FOnActivate write FOnActivate; property OnDeactivate: TNotifyEvent read FOnDeactivate write FOnDeactivate; property OnException: TExceptionEvent read FOnException write FOnException; property OnIdle: TIdleEvent read FOnIdle write FOnIdle; property OnHelp: THelpEvent read FOnHelp write FOnHelp; property OnHint: TNotifyEvent read FOnHint write FOnHint; property OnMessage: TMessageEvent read FOnMessage write FOnMessage; property OnMinimize: TNotifyEvent read FOnMinimize write FOnMinimize; property OnRestore: TNotifyEvent read FOnRestore write FOnRestore; property OnShowHint: TShowHintEvent read FOnShowHint write FOnShowHint; property OnShortCut: TShortCutEvent read FOnShortCut write FOnShortCut; public constructor Create(AOwner: TComponent); override; procedure Activate; procedure CancelDispatch; end; TApplicationEvents = class(TCustomApplicationEvents) published property OnActionExecute; property OnActionUpdate; property OnActivate; property OnDeactivate; property OnException; property OnIdle; property OnHelp; property OnHint; property OnMessage; property OnMinimize; property OnRestore; property OnShowHint; property OnShortCut; end; implementation uses Contnrs, Consts, StdActns; type TMultiCaster = class(TComponent) private FAppEvents: TComponentList; FDispatching: Boolean; procedure DoActionExecute(Action: TBasicAction; var Handled: Boolean); procedure DoActionUpdate(Action: TBasicAction; var Handled: Boolean); procedure DoActivate(Sender: TObject); procedure DoDeactivate(Sender: TObject); procedure DoException(Sender: TObject; E: Exception); procedure DoIdle(Sender: TObject; var Done: Boolean); function DoHelp(Command: Word; Data: Longint; var CallHelp: Boolean): Boolean; procedure DoHint(Sender: TObject); procedure DoMessage(var Msg: TMsg; var Handled: Boolean); procedure DoMinimize(Sender: TObject); procedure DoRestore(Sender: TObject); procedure DoShowHint(var HintStr: string; var CanShow: Boolean; var HintInfo: THintInfo); procedure DoShortcut(var Msg: TWMKey; var Handled: Boolean); function GetCount: Integer; function GetAppEvents(Index: Integer): TCustomApplicationEvents; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Activate(AppEvent: TCustomApplicationEvents); procedure AddAppEvent(AppEvent: TCustomApplicationEvents); procedure CancelDispatch; procedure CheckDispatching; property AppEvents[Index: Integer]: TCustomApplicationEvents read GetAppEvents; default; property Count: Integer read GetCount; end; var MultiCaster: TMultiCaster = nil; { TCustomApplicationEvents } procedure TCustomApplicationEvents.Activate; begin MultiCaster.Activate(Self); end; procedure TCustomApplicationEvents.CancelDispatch; begin MultiCaster.CancelDispatch; end; constructor TCustomApplicationEvents.Create(AOwner: TComponent); begin inherited Create(AOwner); MultiCaster.AddAppEvent(Self); end; procedure TCustomApplicationEvents.DoActionExecute(Action: TBasicAction; var Handled: Boolean); begin if Assigned(FOnActionExecute) then FOnActionExecute(Action, Handled); end; procedure TCustomApplicationEvents.DoActionUpdate(Action: TBasicAction; var Handled: Boolean); begin if Assigned(FOnActionUpdate) then FOnActionUpdate(Action, Handled); end; procedure TCustomApplicationEvents.DoActivate(Sender: TObject); begin if Assigned(FOnActivate) then FOnActivate(Sender); end; procedure TCustomApplicationEvents.DoDeactivate(Sender: TObject); begin if Assigned(FOnDeactivate) then FOnDeactivate(Sender); end; procedure TCustomApplicationEvents.DoException(Sender: TObject; E: Exception); begin if E is Exception then begin if not (E is EAbort) then if Assigned(FOnException) then FOnException(Sender, E) else Application.ShowException(E); end else SysUtils.ShowException(E, ExceptAddr); end; function TCustomApplicationEvents.DoHelp(Command: Word; Data: Integer; var CallHelp: Boolean): Boolean; begin if Assigned(FOnHelp) then Result := FOnHelp(Command, Data, CallHelp) else Result := False; end; procedure TCustomApplicationEvents.DoHint(Sender: TObject); begin if Assigned(FOnHint) then FOnHint(Sender) else with THintAction.Create(Application) do try Hint := Application.Hint; Execute; finally Free; end; end; procedure TCustomApplicationEvents.DoIdle(Sender: TObject; var Done: Boolean); begin if Assigned(FOnIdle) then FOnIdle(Sender, Done); end; procedure TCustomApplicationEvents.DoMessage(var Msg: TMsg; var Handled: Boolean); begin if Assigned(FOnMessage) then FOnMessage(Msg, Handled); end; procedure TCustomApplicationEvents.DoMinimize(Sender: TObject); begin if Assigned(FOnMinimize) then FOnMinimize(Sender); end; procedure TCustomApplicationEvents.DoRestore(Sender: TObject); begin if Assigned(FOnRestore) then FOnRestore(Sender); end; procedure TCustomApplicationEvents.DoShortcut(var Msg: TWMKey; var Handled: Boolean); begin if Assigned(FOnShortcut) then FOnShortcut(Msg, Handled); end; procedure TCustomApplicationEvents.DoShowHint(var HintStr: string; var CanShow: Boolean; var HintInfo: THintInfo); begin if Assigned(FOnShowHint) then FOnShowHint(HintStr, CanShow, HintInfo); end; { TMultiCaster } procedure TMultiCaster.Activate(AppEvent: TCustomApplicationEvents); begin CheckDispatching; if FAppEvents.IndexOf(AppEvent) < FAppEvents.Count - 1 then begin FAppEvents.Remove(AppEvent); FAppEvents.Add(AppEvent); end; end; procedure TMultiCaster.AddAppEvent(AppEvent: TCustomApplicationEvents); begin if FAppEvents.IndexOf(AppEvent) = -1 then FAppEvents.Add(AppEvent); end; procedure TMultiCaster.CancelDispatch; begin FDispatching := False; end; procedure TMultiCaster.CheckDispatching; begin if FDispatching then raise Exception.CreateRes(@sOperationNotAllowed); end; constructor TMultiCaster.Create(AOwner: TComponent); begin inherited Create(AOwner); FAppEvents := TComponentList.Create(False); with Application do begin OnActionExecute := DoActionExecute; OnActionUpdate := DoActionUpdate; OnActivate := DoActivate; OnDeactivate := DoDeactivate; OnException := DoException; OnHelp := DoHelp; OnHint := DoHint; OnIdle := DoIdle; OnMessage := DoMessage; OnMinimize := DoMinimize; OnRestore := DoRestore; OnShowHint := DoShowHint; OnShortCut := DoShortcut; end; end; destructor TMultiCaster.Destroy; begin with Application do begin OnActionExecute := nil; OnActionUpdate := nil; OnActivate := nil; OnDeactivate := nil; OnException := nil; OnHelp := nil; OnHint := nil; OnIdle := nil; OnMessage := nil; OnMinimize := nil; OnRestore := nil; OnShowHint := nil; OnShortCut := nil; end; FAppEvents.Free; inherited Destroy; end; procedure TMultiCaster.DoActionExecute(Action: TBasicAction; var Handled: Boolean); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoActionExecute(Action, Handled); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoActionUpdate(Action: TBasicAction; var Handled: Boolean); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoActionUpdate(Action, Handled); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoActivate(Sender: TObject); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoActivate(Sender); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoDeactivate(Sender: TObject); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoDeactivate(Sender); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoException(Sender: TObject; E: Exception); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoException(Sender, E); if not FDispatching then Break; end; finally FDispatching := False; end; end; function TMultiCaster.DoHelp(Command: Word; Data: Integer; var CallHelp: Boolean): Boolean; var I: Integer; begin FDispatching := True; try Result := False; for I := Count - 1 downto 0 do begin Result := Result or AppEvents[I].DoHelp(Command, Data, CallHelp); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoHint(Sender: TObject); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoHint(Sender); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoIdle(Sender: TObject; var Done: Boolean); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoIdle(Sender, Done); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoMessage(var Msg: TMsg; var Handled: Boolean); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoMessage(Msg, Handled); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoMinimize(Sender: TObject); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoMinimize(Sender); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoRestore(Sender: TObject); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoRestore(Sender); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoShortcut(var Msg: TWMKey; var Handled: Boolean); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoShortcut(Msg, Handled); if not FDispatching then Break; end; finally FDispatching := False; end; end; procedure TMultiCaster.DoShowHint(var HintStr: string; var CanShow: Boolean; var HintInfo: THintInfo); var I: Integer; begin FDispatching := True; try for I := Count - 1 downto 0 do begin AppEvents[I].DoShowHint(HintStr, CanShow, HintInfo); if not FDispatching then Break; end; finally FDispatching := False; end; end; function TMultiCaster.GetAppEvents(Index: Integer): TCustomApplicationEvents; begin Result := TCustomApplicationEvents(FAppEvents[Index]); end; function TMultiCaster.GetCount: Integer; begin Result := FAppEvents.Count; end; initialization MultiCaster := TMultiCaster.Create(Application); end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Memo.Types, FMX.ScrollBox, FMX.Memo, DW.VOIP, FMX.Objects; type TForm1 = class(TForm) ReceiveCallTestButton: TButton; Memo1: TMemo; MakeCallTestButton: TButton; VOIPImage: TImage; procedure ReceiveCallTestButtonClick(Sender: TObject); private FToken: string; FVOIP: TVOIP; procedure SetToken(const AToken: string); procedure VOIPPushKitMessageReceivedHandler(Sender: TObject; const AJSON: string); procedure VOIPPushKitTokenReceivedHandler(Sender: TObject; const AToken: string; const AIsNew: Boolean); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation {$R *.fmx} uses System.JSON; { TForm1 } constructor TForm1.Create(AOwner: TComponent); begin inherited; VOIPImage.Visible := False; FVOIP := TVOIP.Create; FVOIP.Icon := VOIPImage.Bitmap; FVOIP.OnPushKitTokenReceived := VOIPPushKitTokenReceivedHandler; FVOIP.OnPushKitMessageReceived := VOIPPushKitMessageReceivedHandler; SetToken(FVOIP.StoredToken); FVOIP.Start; end; destructor TForm1.Destroy; begin FVOIP.Free; inherited; end; procedure TForm1.SetToken(const AToken: string); begin FToken := AToken; // Possibly take some action here, if AToken is not empty end; procedure TForm1.VOIPPushKitMessageReceivedHandler(Sender: TObject; const AJSON: string); var LJSON: TJSONValue; LId, LCaller: string; begin // AJSON contains the json sent in the push notification from your server, so the structure is whatever you determine // This example handler assumes the json is like this (for example): // { "id": "30DE53F0-8856-4059-881F-5BBDF5C92CCF", "caller": "Marco Cantu" } LJSON := TJSONObject.ParseJSONValue(AJSON); if LJSON <> nil then try if LJSON.TryGetValue('id', LId) then begin LCaller := 'Unknown'; LJSON.TryGetValue('caller', LCaller); FVOIP.ReportIncomingCall(LId, LCaller); end; finally LJSON.Free; end; end; procedure TForm1.VOIPPushKitTokenReceivedHandler(Sender: TObject; const AToken: string; const AIsNew: Boolean); begin SetToken(AToken); // This is where you would update your back end, if AIsNew is set to True Memo1.Lines.Add('Token: ' + AToken); end; procedure TForm1.ReceiveCallTestButtonClick(Sender: TObject); begin // This is to simulate receiving an incoming call. Normally you might do this in VOIPPushKitMessageReceivedHandler // The first parameter value is just a generated GUID FVOIP.ReportIncomingCall('30DE53F0-8856-4059-881F-5BBDF5C92CCF', 'Pete Za'); 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.3 24/01/2004 19:21:36 CCostelloe Cleaned up warnings Rev 1.2 1/15/2004 2:32:50 AM JPMugaas Attempt to add MD5 coder support for partial streams. THis is needed for the XMD5 command in the FTP Server. Rev 1.1 2003-10-12 22:36:40 HHellström Reimplemented, optimized and tested for both Win32 and dotNET. Rev 1.0 11/13/2002 07:53:40 AM JPMugaas } { Implementation of the MD2, MD4 and MD5 Message-Digest Algorithm as specified in RFC 1319 (1115), 1320 (1186), 1321 Author: Henrick Hellström <henrick@streamsec.se> Original Intellectual Property Statement: Author: Pete Mee Port to Indy 8.1 Doychin Bondzhev (doychin@dsoft-bg.com) Copyright: (c) Chad Z. Hower and The Winshoes Working Group. } unit IdHashMessageDigest; interface {$i IdCompilerDefines.inc} uses IdFIPS, IdGlobal, IdHash, Classes; type T4x4LongWordRecord = array[0..3] of LongWord; T16x4LongWordRecord = array[0..15] of LongWord; T4x4x4LongWordRecord = array[0..3] of T4x4LongWordRecord; T512BitRecord = array[0..63] of Byte; T384BitRecord = array[0..47] of Byte; T128BitRecord = array[0..15] of Byte; TIdHashMessageDigest = class(TIdHashNativeAndIntF) protected FCBuffer: TIdBytes; procedure MDCoder; virtual; abstract; procedure Reset; virtual; end; TIdHashMessageDigest2 = class(TIdHashMessageDigest) protected FX: T384BitRecord; FCheckSum: T128BitRecord; procedure MDCoder; override; procedure Reset; override; function InitHash : TIdHashIntCtx; override; function NativeGetHashBytes(AStream: TStream; ASize: TIdStreamSize): TIdBytes; override; function HashToHex(const AHash: TIdBytes): String; override; public constructor Create; override; class function IsIntfAvailable: Boolean; override; end; TIdHashMessageDigest4 = class(TIdHashMessageDigest) protected FState: T4x4LongWordRecord; function NativeGetHashBytes(AStream: TStream; ASize: TIdStreamSize): TIdBytes; override; function HashToHex(const AHash: TIdBytes): String; override; procedure MDCoder; override; function InitHash : TIdHashIntCtx; override; public constructor Create; override; class function IsIntfAvailable: Boolean; override; end; TIdHashMessageDigest5 = class(TIdHashMessageDigest4) protected procedure MDCoder; override; function InitHash : TIdHashIntCtx; override; public class function IsIntfAvailable : Boolean; override; end; implementation uses {$IFDEF DOTNET} System.Security.Cryptography, IdStreamNET, {$ELSE} IdStreamVCL, {$ENDIF} IdGlobalProtocols; { TIdHashMessageDigest } procedure TIdHashMessageDigest.Reset; begin FillBytes(FCBuffer, Length(FCBuffer), 0); end; { TIdHashMessageDigest2 } const MD2_PI_SUBST : array [0..255] of Byte = ( 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251, 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63, 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50, 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165, 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210, 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157, 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27, 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15, 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233, 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228, 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237, 31, 26, 219, 153, 141, 51, 159, 17, 131, 20); constructor TIdHashMessageDigest2.Create; begin inherited Create; SetLength(FCBuffer, 16); end; procedure TIdHashMessageDigest2.MDCoder; const NumRounds = 18; var x: Byte; i, j: Integer; T: Word; LCheckSumScore: Byte; begin // Move the next 16 bytes into the second 16 bytes of X. for i := 0 to 15 do begin x := FCBuffer[i]; FX[i + 16] := x; FX[i + 32] := x xor FX[i]; end; { Do 18 rounds. } T := 0; for i := 0 to NumRounds - 1 do begin for j := 0 to 47 do begin T := FX[j] xor MD2_PI_SUBST[T]; FX[j] := T and $FF; end; T := (T + i) and $FF; end; LCheckSumScore := FChecksum[15]; for i := 0 to 15 do begin x := FCBuffer[i] xor LCheckSumScore; LCheckSumScore := FChecksum[i] xor MD2_PI_SUBST[x]; FChecksum[i] := LCheckSumScore; end; end; // Clear Buffer and Checksum arrays procedure TIdHashMessageDigest2.Reset; var I: Integer; begin inherited Reset; for I := 0 to 15 do begin FCheckSum[I] := 0; FX[I] := 0; FX[I+16] := 0; FX[I+32] := 0; end; end; function TIdHashMessageDigest2.NativeGetHashBytes(AStream: TStream; ASize: TIdStreamSize): TIdBytes; var LStartPos: Integer; LSize: Integer; Pad: Byte; I: Integer; begin Result := nil; Reset; // Code the entire file in complete 16-byte chunks. while ASize >= 16 do begin LSize := ReadTIdBytesFromStream(AStream, FCBuffer, 16); // TODO: handle stream read error MDCoder; Dec(ASize, LSize); end; // Read the last set of bytes. LStartPos := ReadTIdBytesFromStream(AStream, FCBuffer, ASize); // TODO: handle stream read error Pad := 16 - LStartPos; // Step 1 for I := LStartPos to 15 do begin FCBuffer[I] := Pad; end; MDCoder; // Step 2 for I := 0 to 15 do begin FCBuffer[I] := FCheckSum[I]; end; MDCoder; SetLength(Result, SizeOf(LongWord)*4); for I := 0 to 3 do begin CopyTIdLongWord( FX[I*4] + (FX[I*4+1] shl 8) + (FX[I*4+2] shl 16) + (FX[I*4+3] shl 24), Result, SizeOf(LongWord)*I); end; end; function TIdHashMessageDigest2.HashToHex(const AHash: TIdBytes): String; begin Result := LongWordHashToHex(AHash, 4); end; function TIdHashMessageDigest2.InitHash: TIdHashIntCtx; begin Result := GetMD2HashInst; end; class function TIdHashMessageDigest2.IsIntfAvailable: Boolean; begin Result := IsHashingIntfAvail and IsMD2HashIntfAvail; end; { TIdHashMessageDigest4 } const MD4_INIT_VALUES: T4x4LongWordRecord = ( $67452301, $EFCDAB89, $98BADCFE, $10325476); {$Q-} // Arithmetic operations performed modulo $100000000 constructor TIdHashMessageDigest4.Create; begin inherited Create; SetLength(FCBuffer, 64); end; procedure TIdHashMessageDigest4.MDCoder; var A, B, C, D, i : LongWord; buff : T16x4LongWordRecord; // 64-byte buffer begin A := FState[0]; B := FState[1]; C := FState[2]; D := FState[3]; for i := 0 to 15 do begin buff[i] := FCBuffer[i*4+0] + (FCBuffer[i*4+1] shl 8) + (FCBuffer[i*4+2] shl 16) + (FCBuffer[i*4+3] shl 24); end; // Round 1 { Note: (x and y) or ( (not x) and z) is equivalent to (((z xor y) and x) xor z) -HHellström } for i := 0 to 3 do begin A := ROL((((D xor C) and B) xor D) + A + buff[i*4+0], 3); D := ROL((((C xor B) and A) xor C) + D + buff[i*4+1], 7); C := ROL((((B xor A) and D) xor B) + C + buff[i*4+2], 11); B := ROL((((A xor D) and C) xor A) + B + buff[i*4+3], 19); end; // Round 2 { Note: (x and y) or (x and z) or (y and z) is equivalent to ((x and y) or (z and (x or y))) -HHellström } for i := 0 to 3 do begin A := ROL(((B and C) or (D and (B or C))) + A + buff[0*4+i] + $5A827999, 3); D := ROL(((A and B) or (C and (A or B))) + D + buff[1*4+i] + $5A827999, 5); C := ROL(((D and A) or (B and (D or A))) + C + buff[2*4+i] + $5A827999, 9); B := ROL(((C and D) or (A and (C or D))) + B + buff[3*4+i] + $5A827999, 13); end; // Round 3 A := ROL((B xor C xor D) + A + buff[ 0] + $6ED9EBA1, 3); D := ROL((A xor B xor C) + D + buff[ 8] + $6ED9EBA1, 9); C := ROL((D xor A xor B) + C + buff[ 4] + $6ED9EBA1, 11); B := ROL((C xor D xor A) + B + buff[12] + $6ED9EBA1, 15); A := ROL((B xor C xor D) + A + buff[ 2] + $6ED9EBA1, 3); D := ROL((A xor B xor C) + D + buff[10] + $6ED9EBA1, 9); C := ROL((D xor A xor B) + C + buff[ 6] + $6ED9EBA1, 11); B := ROL((C xor D xor A) + B + buff[14] + $6ED9EBA1, 15); A := ROL((B xor C xor D) + A + buff[ 1] + $6ED9EBA1, 3); D := ROL((A xor B xor C) + D + buff[ 9] + $6ED9EBA1, 9); C := ROL((D xor A xor B) + C + buff[ 5] + $6ED9EBA1, 11); B := ROL((C xor D xor A) + B + buff[13] + $6ED9EBA1, 15); A := ROL((B xor C xor D) + A + buff[ 3] + $6ED9EBA1, 3); D := ROL((A xor B xor C) + D + buff[11] + $6ED9EBA1, 9); C := ROL((D xor A xor B) + C + buff[ 7] + $6ED9EBA1, 11); B := ROL((C xor D xor A) + B + buff[15] + $6ED9EBA1, 15); Inc(FState[0], A); Inc(FState[1], B); Inc(FState[2], C); Inc(FState[3], D); end; {$Q+} function TIdHashMessageDigest4.NativeGetHashBytes(AStream: TStream; ASize: TIdStreamSize): TidBytes; var LStartPos: Integer; LSize: TIdStreamSize; LBitSize: Int64; I, LReadSize: Integer; begin Result := nil; LSize := ASize; // A straight assignment would be by ref on dotNET. for I := 0 to 3 do begin FState[I] := MD4_INIT_VALUES[I]; end; while LSize >= 64 do begin LReadSize := ReadTIdBytesFromStream(AStream, FCBuffer, 64); // TODO: handle stream read error MDCoder; Dec(LSize, LReadSize); end; // Read the last set of bytes. LStartPos := ReadTIdBytesFromStream(AStream, FCBuffer, ASize); // TODO: handle stream read error // Append one bit with value 1 FCBuffer[LStartPos] := $80; Inc(LStartPos); // Must have sufficient space to insert the 64-bit size value if LStartPos > 56 then begin for I := LStartPos to 63 do begin FCBuffer[I] := 0; end; MDCoder; LStartPos := 0; end; // Pad with zeroes. Leave room for the 64 bit size value. for I := LStartPos to 55 do begin FCBuffer[I] := 0; end; // Append the Number of bits processed. LBitSize := ASize * 8; for I := 56 to 63 do begin FCBuffer[I] := LBitSize and $FF; LBitSize := LBitSize shr 8; end; MDCoder; SetLength(Result, SizeOf(LongWord)*4); for I := 0 to 3 do begin CopyTIdLongWord(FState[I], Result, SizeOf(LongWord)*I); end; end; function TIdHashMessageDigest4.InitHash : TIdHashIntCtx; begin Result := GetMD4HashInst; end; function TIdHashMessageDigest4.HashToHex(const AHash: TIdBytes): String; begin Result := LongWordHashToHex(AHash, 4); end; class function TIdHashMessageDigest4.IsIntfAvailable: Boolean; begin Result := IsHashingIntfAvail and IsMD4HashIntfAvail ; end; { TIdHashMessageDigest5 } const MD5_SINE : array[1..64] of LongWord = ( { Round 1. } $d76aa478, $e8c7b756, $242070db, $c1bdceee, $f57c0faf, $4787c62a, $a8304613, $fd469501, $698098d8, $8b44f7af, $ffff5bb1, $895cd7be, $6b901122, $fd987193, $a679438e, $49b40821, { Round 2. } $f61e2562, $c040b340, $265e5a51, $e9b6c7aa, $d62f105d, $02441453, $d8a1e681, $e7d3fbc8, $21e1cde6, $c33707d6, $f4d50d87, $455a14ed, $a9e3e905, $fcefa3f8, $676f02d9, $8d2a4c8a, { Round 3. } $fffa3942, $8771f681, $6d9d6122, $fde5380c, $a4beea44, $4bdecfa9, $f6bb4b60, $bebfbc70, $289b7ec6, $eaa127fa, $d4ef3085, $04881d05, $d9d4d039, $e6db99e5, $1fa27cf8, $c4ac5665, { Round 4. } $f4292244, $432aff97, $ab9423a7, $fc93a039, $655b59c3, $8f0ccc92, $ffeff47d, $85845dd1, $6fa87e4f, $fe2ce6e0, $a3014314, $4e0811a1, $f7537e82, $bd3af235, $2ad7d2bb, $eb86d391 ); {$Q-} // Arithmetic operations performed modulo $100000000 function TIdHashMessageDigest5.InitHash: TIdHashIntCtx; begin Result := GetMD5HashInst; end; class function TIdHashMessageDigest5.IsIntfAvailable: Boolean; begin Result := IsHashingIntfAvail and IsMD5HashIntfAvail ; end; procedure TIdHashMessageDigest5.MDCoder; var A, B, C, D : LongWord; i: Integer; x : T16x4LongWordRecord; // 64-byte buffer begin A := FState[0]; B := FState[1]; C := FState[2]; D := FState[3]; for i := 0 to 15 do begin x[i] := FCBuffer[i*4+0] + (FCBuffer[i*4+1] shl 8) + (FCBuffer[i*4+2] shl 16) + (FCBuffer[i*4+3] shl 24); end; { Round 1 } { Note: (x and y) or ( (not x) and z) is equivalent to (((z xor y) and x) xor z) -HHellström } A := ROL(A + (((D xor C) and B) xor D) + x[ 0] + MD5_SINE[ 1], 7) + B; D := ROL(D + (((C xor B) and A) xor C) + x[ 1] + MD5_SINE[ 2], 12) + A; C := ROL(C + (((B xor A) and D) xor B) + x[ 2] + MD5_SINE[ 3], 17) + D; B := ROL(B + (((A xor D) and C) xor A) + x[ 3] + MD5_SINE[ 4], 22) + C; A := ROL(A + (((D xor C) and B) xor D) + x[ 4] + MD5_SINE[ 5], 7) + B; D := ROL(D + (((C xor B) and A) xor C) + x[ 5] + MD5_SINE[ 6], 12) + A; C := ROL(C + (((B xor A) and D) xor B) + x[ 6] + MD5_SINE[ 7], 17) + D; B := ROL(B + (((A xor D) and C) xor A) + x[ 7] + MD5_SINE[ 8], 22) + C; A := ROL(A + (((D xor C) and B) xor D) + x[ 8] + MD5_SINE[ 9], 7) + B; D := ROL(D + (((C xor B) and A) xor C) + x[ 9] + MD5_SINE[10], 12) + A; C := ROL(C + (((B xor A) and D) xor B) + x[10] + MD5_SINE[11], 17) + D; B := ROL(B + (((A xor D) and C) xor A) + x[11] + MD5_SINE[12], 22) + C; A := ROL(A + (((D xor C) and B) xor D) + x[12] + MD5_SINE[13], 7) + B; D := ROL(D + (((C xor B) and A) xor C) + x[13] + MD5_SINE[14], 12) + A; C := ROL(C + (((B xor A) and D) xor B) + x[14] + MD5_SINE[15], 17) + D; B := ROL(B + (((A xor D) and C) xor A) + x[15] + MD5_SINE[16], 22) + C; { Round 2 } { Note: (x and z) or (y and (not z) ) is equivalent to (((y xor x) and z) xor y) -HHellström } A := ROL(A + (C xor (D and (B xor C))) + x[ 1] + MD5_SINE[17], 5) + B; D := ROL(D + (B xor (C and (A xor B))) + x[ 6] + MD5_SINE[18], 9) + A; C := ROL(C + (A xor (B and (D xor A))) + x[11] + MD5_SINE[19], 14) + D; B := ROL(B + (D xor (A and (C xor D))) + x[ 0] + MD5_SINE[20], 20) + C; A := ROL(A + (C xor (D and (B xor C))) + x[ 5] + MD5_SINE[21], 5) + B; D := ROL(D + (B xor (C and (A xor B))) + x[10] + MD5_SINE[22], 9) + A; C := ROL(C + (A xor (B and (D xor A))) + x[15] + MD5_SINE[23], 14) + D; B := ROL(B + (D xor (A and (C xor D))) + x[ 4] + MD5_SINE[24], 20) + C; A := ROL(A + (C xor (D and (B xor C))) + x[ 9] + MD5_SINE[25], 5) + B; D := ROL(D + (B xor (C and (A xor B))) + x[14] + MD5_SINE[26], 9) + A; C := ROL(C + (A xor (B and (D xor A))) + x[ 3] + MD5_SINE[27], 14) + D; B := ROL(B + (D xor (A and (C xor D))) + x[ 8] + MD5_SINE[28], 20) + C; A := ROL(A + (C xor (D and (B xor C))) + x[13] + MD5_SINE[29], 5) + B; D := ROL(D + (B xor (C and (A xor B))) + x[ 2] + MD5_SINE[30], 9) + A; C := ROL(C + (A xor (B and (D xor A))) + x[ 7] + MD5_SINE[31], 14) + D; B := ROL(B + (D xor (A and (C xor D))) + x[12] + MD5_SINE[32], 20) + C; { Round 3. } A := ROL(A + (B xor C xor D) + x[ 5] + MD5_SINE[33], 4) + B; D := ROL(D + (A xor B xor C) + x[ 8] + MD5_SINE[34], 11) + A; C := ROL(C + (D xor A xor B) + x[11] + MD5_SINE[35], 16) + D; B := ROL(B + (C xor D xor A) + x[14] + MD5_SINE[36], 23) + C; A := ROL(A + (B xor C xor D) + x[ 1] + MD5_SINE[37], 4) + B; D := ROL(D + (A xor B xor C) + x[ 4] + MD5_SINE[38], 11) + A; C := ROL(C + (D xor A xor B) + x[ 7] + MD5_SINE[39], 16) + D; B := ROL(B + (C xor D xor A) + x[10] + MD5_SINE[40], 23) + C; A := ROL(A + (B xor C xor D) + x[13] + MD5_SINE[41], 4) + B; D := ROL(D + (A xor B xor C) + x[ 0] + MD5_SINE[42], 11) + A; C := ROL(C + (D xor A xor B) + x[ 3] + MD5_SINE[43], 16) + D; B := ROL(B + (C xor D xor A) + x[ 6] + MD5_SINE[44], 23) + C; A := ROL(A + (B xor C xor D) + x[ 9] + MD5_SINE[45], 4) + B; D := ROL(D + (A xor B xor C) + x[12] + MD5_SINE[46], 11) + A; C := ROL(C + (D xor A xor B) + x[15] + MD5_SINE[47], 16) + D; B := ROL(B + (C xor D xor A) + x[ 2] + MD5_SINE[48], 23) + C; { Round 4. } A := ROL(A + ((B or not D) xor C) + x[ 0] + MD5_SINE[49], 6) + B; D := ROL(D + ((A or not C) xor B) + x[ 7] + MD5_SINE[50], 10) + A; C := ROL(C + ((D or not B) xor A) + x[14] + MD5_SINE[51], 15) + D; B := ROL(B + ((C or not A) xor D) + x[ 5] + MD5_SINE[52], 21) + C; A := ROL(A + ((B or not D) xor C) + x[12] + MD5_SINE[53], 6) + B; D := ROL(D + ((A or not C) xor B) + x[ 3] + MD5_SINE[54], 10) + A; C := ROL(C + ((D or not B) xor A) + x[10] + MD5_SINE[55], 15) + D; B := ROL(B + ((C or not A) xor D) + x[ 1] + MD5_SINE[56], 21) + C; A := ROL(A + ((B or not D) xor C) + x[ 8] + MD5_SINE[57], 6) + B; D := ROL(D + ((A or not C) xor B) + x[15] + MD5_SINE[58], 10) + A; C := ROL(C + ((D or not B) xor A) + x[ 6] + MD5_SINE[59], 15) + D; B := ROL(B + ((C or not A) xor D) + x[13] + MD5_SINE[60], 21) + C; A := ROL(A + ((B or not D) xor C) + x[ 4] + MD5_SINE[61], 6) + B; D := ROL(D + ((A or not C) xor B) + x[11] + MD5_SINE[62], 10) + A; C := ROL(C + ((D or not B) xor A) + x[ 2] + MD5_SINE[63], 15) + D; B := ROL(B + ((C or not A) xor D) + x[ 9] + MD5_SINE[64], 21) + C; Inc(FState[0], A); Inc(FState[1], B); Inc(FState[2], C); Inc(FState[3], D); end; {$Q+} end.
// The while loop represents the game. // Each iteration represents a turn of the game // where you are given inputs (the heights of the mountains) // and where you have to print an output (the index of the mountain to fire on) // The inputs you are given are automatically updated according to your last actions. program Answer; {$H+} uses sysutils, classes, math; // Helper to read a line and split tokens procedure ParseIn(Inputs: TStrings) ; var Line : string; begin readln(Line); Inputs.Clear; Inputs.Delimiter := ' '; Inputs.DelimitedText := Line; end; var mountainH : Int32; // represents the height of one mountain. i : Int32; Inputs: TStringList; highestMountIdx: Int32; highestMountH: Int32; begin Inputs := TStringList.Create; // game loop while true do begin highestMountH := 0; highestMountIdx := -1; for i := 0 to 7 do begin ParseIn(Inputs); mountainH := StrToInt(Inputs[0]); if mountainH > highestMountH then begin highestMountH := mountainH; highestMountIdx := i; end; end; // Write an action using writeln() // To debug: writeln(StdErr, 'Debug messages...'); writeln(IntToStr(highestMountIdx)); // The index of the mountain to fire on. flush(StdErr); flush(output); // DO NOT REMOVE end; end.
unit SpawnServer; { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Spawn server $jrsoftware: issrc/Projects/SpawnServer.pas,v 1.13 2010/04/17 19:30:25 jr Exp $ } interface {$I VERSION.INC} uses Windows, SysUtils, Messages; type TSpawnServer = class private FWnd: HWND; FSequenceNumber: Word; FCallStatus: Word; FResultCode: Integer; FNotifyRestartRequested: Boolean; FNotifyNewLanguage: Integer; function HandleExec(const IsShellExec: Boolean; const ADataPtr: Pointer; const ADataSize: Cardinal): LRESULT; procedure WndProc(var Message: TMessage); public constructor Create; destructor Destroy; override; property NotifyNewLanguage: Integer read FNotifyNewLanguage; property NotifyRestartRequested: Boolean read FNotifyRestartRequested; property Wnd: HWND read FWnd; end; procedure EnterSpawnServerDebugMode; function NeedToRespawnSelfElevated(const ARequireAdministrator, AEmulateHighestAvailable: Boolean): Boolean; procedure RespawnSelfElevated(const AExeFilename, AParams: String; var AExitCode: DWORD); implementation { For debugging only; remove 'x' to enable the define: } {x$DEFINE SPAWNSERVER_RESPAWN_ALWAYS} uses Classes, Forms, ShellApi, Int64Em, PathFunc, CmnFunc2, InstFunc, SpawnCommon; type TPtrAndSize = record Ptr: ^Byte; Size: Cardinal; end; procedure ProcessMessagesProc; begin Application.ProcessMessages; end; function ExtractBytes(var Data: TPtrAndSize; const Bytes: Cardinal; var Value: Pointer): Boolean; begin if Data.Size < Bytes then Result := False else begin Value := Data.Ptr; Dec(Data.Size, Bytes); Inc(Data.Ptr, Bytes); Result := True; end; end; function ExtractLongint(var Data: TPtrAndSize; var Value: Longint): Boolean; var P: Pointer; begin Result := ExtractBytes(Data, SizeOf(Longint), P); if Result then Value := Longint(P^); end; function ExtractString(var Data: TPtrAndSize; var Value: String): Boolean; var Len: Longint; P: Pointer; begin Result := ExtractLongint(Data, Len); if Result then begin if (Len < 0) or (Len > $FFFF) then Result := False else begin Result := ExtractBytes(Data, Len * SizeOf(Value[1]), P); if Result then SetString(Value, PChar(P), Len); end; end; end; type TOSVersionInfoExW = record dwOSVersionInfoSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformId: DWORD; szCSDVersion: array[0..127] of WideChar; wServicePackMajor: Word; wServicePackMinor: Word; wSuiteMask: Word; wProductType: Byte; wReserved: Byte; end; const VER_MINORVERSION = $0000001; VER_MAJORVERSION = $0000002; VER_SERVICEPACKMINOR = $0000010; VER_SERVICEPACKMAJOR = $0000020; VER_GREATER_EQUAL = 3; var VerSetConditionMaskFunc, VerifyVersionInfoWFunc: Pointer; { These are implemented in asm because Delphi 2 doesn't support functions that take 64-bit parameters or return a 64-bit result (in EDX:EAX) } procedure CallVerSetConditionMask(var dwlConditionMask: Integer64; dwTypeBitMask: DWORD; dwConditionMask: DWORD); asm push esi mov esi, eax // ESI = @dwlConditionMask push ecx // dwConditionMask push edx // dwTypeBitMask push dword ptr [esi+4] // dwlConditionMask.Hi push dword ptr [esi] // dwlConditionMask.Lo call VerSetConditionMaskFunc mov dword ptr [esi], eax // write dwlConditionMask.Lo mov dword ptr [esi+4], edx // write dwlConditionMask.Hi pop esi end; function CallVerifyVersionInfoW(const lpVersionInfo: TOSVersionInfoExW; dwTypeMask: DWORD; const dwlConditionMask: Integer64): BOOL; asm push dword ptr [ecx+4] // dwlConditionMask.Hi push dword ptr [ecx] // dwlConditionMask.Lo push edx // dwTypeMask push eax // lpVersionInfo call VerifyVersionInfoWFunc end; function IsReallyVista: Boolean; { Returns True if the OS is *really* Vista or later. VerifyVersionInfo is used because it appears to always check the true OS version number, whereas GetVersion(Ex) can return a fake version number (e.g. 5.x) if the program is set to run in compatibility mode, or if it is started by a program running in compatibility mode. } var ConditionMask: Integer64; VerInfo: TOSVersionInfoExW; begin Result := False; { These functions are present on Windows 2000 and later. NT 4.0 SP6 has VerifyVersionInfoW, but not VerSetConditionMask. Windows 9x/Me and early versions of NT 4.0 have neither. } if Assigned(VerSetConditionMaskFunc) and Assigned(VerifyVersionInfoWFunc) then begin ConditionMask.Lo := 0; ConditionMask.Hi := 0; { Docs say: "If you are testing the major version, you must also test the minor version and the service pack major and minor versions." } CallVerSetConditionMask(ConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); CallVerSetConditionMask(ConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); CallVerSetConditionMask(ConditionMask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); CallVerSetConditionMask(ConditionMask, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL); FillChar(VerInfo, SizeOf(VerInfo), 0); VerInfo.dwOSVersionInfoSize := SizeOf(VerInfo); VerInfo.dwMajorVersion := 6; Result := CallVerifyVersionInfoW(VerInfo, VER_MAJORVERSION or VER_MINORVERSION or VER_SERVICEPACKMAJOR or VER_SERVICEPACKMINOR, ConditionMask); end; end; const TokenElevationTypeDefault = 1; { User does not have a split token (they're not an admin, or UAC is turned off) } TokenElevationTypeFull = 2; { Has split token, process running elevated } TokenElevationTypeLimited = 3; { Has split token, process not running elevated } function GetTokenElevationType: DWORD; { Returns token elevation type (TokenElevationType* constant). In case of failure (e.g. not running Vista), 0 is returned. } const TokenElevationType = 18; var Token: THandle; ElevationType: DWORD; ReturnLength: DWORD; begin Result := 0; if OpenProcessToken(GetCurrentProcess, TOKEN_QUERY, {$IFNDEF Delphi3orHigher} @ {$ENDIF} Token) then begin ElevationType := 0; if GetTokenInformation(Token, {$IFDEF Delphi3orHigher} TTokenInformationClass {$ENDIF} (TokenElevationType), @ElevationType, SizeOf(ElevationType), ReturnLength) then Result := ElevationType; CloseHandle(Token); end; end; function NeedToRespawnSelfElevated(const ARequireAdministrator, AEmulateHighestAvailable: Boolean): Boolean; {$IFNDEF SPAWNSERVER_RESPAWN_ALWAYS} var ElevationType: DWORD; begin Result := False; if IsReallyVista and not IsAdminLoggedOn then begin if ARequireAdministrator then Result := True else if AEmulateHighestAvailable then begin { Emulate the "highestAvailable" requestedExecutionLevel: respawn if the user has a split token and the process isn't running elevated. (An inverted test for TokenElevationTypeLimited is used, so that if GetTokenElevationType unexpectedly fails or returns some value we don't recognize, we default to respawning.) } ElevationType := GetTokenElevationType; if (ElevationType <> TokenElevationTypeDefault) and (ElevationType <> TokenElevationTypeFull) then Result := True; end; end; end; {$ELSE} begin { For debugging/testing only: } Result := (Lo(GetVersion) >= 5); end; {$ENDIF} function GetFinalFileName(const Filename: String): String; { Calls GetFinalPathNameByHandle (new API in Vista) to expand any SUBST'ed drives, network drives, and symbolic links in Filename. This is needed for elevation to succeed on Windows Vista/7 when Setup is started from a SUBST'ed drive letter. } function ConvertToNormalPath(P: PChar): String; begin Result := P; if StrLComp(P, '\\?\', 4) = 0 then begin Inc(P, 4); if (PathStrNextChar(P) = P + 1) and (P[1] = ':') and PathCharIsSlash(P[2]) then Result := P else if StrLIComp(P, 'UNC\', 4) = 0 then begin Inc(P, 4); Result := '\\' + P; end; end; end; const FILE_SHARE_DELETE = $00000004; var GetFinalPathNameByHandleFunc: function(hFile: THandle; lpszFilePath: {$IFDEF UNICODE} PWideChar {$ELSE} PAnsiChar {$ENDIF}; cchFilePath: DWORD; dwFlags: DWORD): DWORD; stdcall; Attr, FlagsAndAttributes: DWORD; H: THandle; Res: Integer; Buf: array[0..4095] of Char; begin GetFinalPathNameByHandleFunc := GetProcAddress(GetModuleHandle(kernel32), {$IFDEF UNICODE} 'GetFinalPathNameByHandleW' {$ELSE} 'GetFinalPathNameByHandleA' {$ENDIF} ); if Assigned(GetFinalPathNameByHandleFunc) then begin Attr := GetFileAttributes(PChar(Filename)); if Attr <> $FFFFFFFF then begin { Backup semantics must be requested in order to open a directory } if Attr and FILE_ATTRIBUTE_DIRECTORY <> 0 then FlagsAndAttributes := FILE_FLAG_BACKUP_SEMANTICS else FlagsAndAttributes := 0; { Use zero access mask and liberal sharing mode to ensure success } H := CreateFile(PChar(Filename), 0, FILE_SHARE_READ or FILE_SHARE_WRITE or FILE_SHARE_DELETE, nil, OPEN_EXISTING, FlagsAndAttributes, 0); if H <> INVALID_HANDLE_VALUE then begin Res := GetFinalPathNameByHandleFunc(H, Buf, SizeOf(Buf) div SizeOf(Buf[0]), 0); CloseHandle(H); if (Res > 0) and (Res < (SizeOf(Buf) div SizeOf(Buf[0])) - 16) then begin { ShellExecuteEx fails with error 3 on \\?\UNC\ paths, so try to convert the returned path from \\?\ form } Result := ConvertToNormalPath(Buf); Exit; end; end; end; end; Result := Filename; end; function GetFinalCurrentDir: String; var Res: Integer; Buf: array[0..MAX_PATH-1] of Char; begin DWORD(Res) := GetCurrentDirectory(SizeOf(Buf) div SizeOf(Buf[0]), Buf); if (Res > 0) and (Res < SizeOf(Buf) div SizeOf(Buf[0])) then Result := GetFinalFileName(Buf) else begin RaiseFunctionFailedError('GetCurrentDirectory'); Result := ''; end; end; procedure RespawnSelfElevated(const AExeFilename, AParams: String; var AExitCode: DWORD); { Spawns a new process using the "runas" verb. Notes: 1. Despite the function's name, the spawned process may not actually be elevated / running as administrator on Vista. If UAC is disabled, "runas" behaves like "open". Also, if a non-admin user is a member of a special system group like Backup Operators, they can select their own user account at a UAC dialog. Therefore, it is critical that the caller include some kind of protection against respawning more than once. 2. If AExeFilename is on a network drive, Vista's ShellExecuteEx function is smart enough to substitute it with a UNC path. XP does not do this, which causes the function to fail with ERROR_PATH_NOT_FOUND because the new user doesn't retain the original user's drive mappings. } const SEE_MASK_NOZONECHECKS = $00800000; var ExpandedExeFilename, WorkingDir: String; Info: TShellExecuteInfo; WaitResult: DWORD; begin ExpandedExeFilename := GetFinalFileName(AExeFilename); WorkingDir := GetFinalCurrentDir; FillChar(Info, SizeOf(Info), 0); Info.cbSize := SizeOf(Info); Info.fMask := SEE_MASK_FLAG_NO_UI or SEE_MASK_FLAG_DDEWAIT or SEE_MASK_NOCLOSEPROCESS or SEE_MASK_NOZONECHECKS; Info.lpVerb := 'runas'; Info.lpFile := PChar(ExpandedExeFilename); Info.lpParameters := PChar(AParams); Info.lpDirectory := PChar(WorkingDir); Info.nShow := SW_SHOWNORMAL; if not ShellExecuteEx(@Info) then begin { Don't display error message if user clicked Cancel at UAC dialog } if GetLastError = ERROR_CANCELLED then Abort; Win32ErrorMsg('ShellExecuteEx'); end; if Info.hProcess = 0 then InternalError('ShellExecuteEx returned hProcess=0'); { Wait for the process to terminate, processing messages in the meantime } try repeat ProcessMessagesProc; WaitResult := MsgWaitForMultipleObjects(1, Info.hProcess, False, INFINITE, QS_ALLINPUT); until WaitResult <> WAIT_OBJECT_0+1; if WaitResult = WAIT_FAILED then Win32ErrorMsg('MsgWaitForMultipleObjects'); { Now that the process has exited, process any remaining messages. (If our window is handling notify messages (ANotifyWndPresent=False) then there may be an asynchronously-sent "restart request" message still queued if MWFMO saw the process terminate before checking for new messages.) } ProcessMessagesProc; if not GetExitCodeProcess(Info.hProcess, AExitCode) then Win32ErrorMsg('GetExitCodeProcess'); finally CloseHandle(Info.hProcess); end; end; procedure EnterSpawnServerDebugMode; { For debugging purposes only: Creates a spawn server window, but does not start a new process. Displays the server window handle in the taskbar. Terminates when F11 is pressed. } var Server: TSpawnServer; begin Server := TSpawnServer.Create; try Application.Title := Format('Wnd=$%x', [Server.FWnd]); while True do begin ProcessMessagesProc; if (GetFocus = Application.Handle) and (GetKeyState(VK_F11) < 0) then Break; WaitMessage; end; finally Server.Free; end; Halt(1); end; { TSpawnServer } constructor TSpawnServer.Create; begin inherited; FNotifyNewLanguage := -1; FWnd := AllocateHWnd(WndProc); if FWnd = 0 then RaiseFunctionFailedError('AllocateHWnd'); end; destructor TSpawnServer.Destroy; begin if FWnd <> 0 then DeallocateHWnd(FWnd); inherited; end; function TSpawnServer.HandleExec(const IsShellExec: Boolean; const ADataPtr: Pointer; const ADataSize: Cardinal): LRESULT; var Data: TPtrAndSize; EDisableFsRedir: Longint; EVerb, EFilename, EParams, EWorkingDir: String; EWait, EShowCmd: Longint; ClientCurrentDir, SaveCurrentDir: String; ExecResult: Boolean; begin { Recursive calls aren't supported } if FCallStatus = SPAWN_STATUS_RUNNING then begin Result := SPAWN_MSGRESULT_ALREADY_IN_CALL; Exit; end; Result := SPAWN_MSGRESULT_INVALID_DATA; Data.Ptr := ADataPtr; Data.Size := ADataSize; if IsShellExec then begin if not ExtractString(Data, EVerb) then Exit; end else begin if not ExtractLongint(Data, EDisableFsRedir) then Exit; end; if not ExtractString(Data, EFilename) then Exit; if not ExtractString(Data, EParams) then Exit; if not ExtractString(Data, EWorkingDir) then Exit; if not ExtractLongint(Data, EWait) then Exit; if not ExtractLongint(Data, EShowCmd) then Exit; if not ExtractString(Data, ClientCurrentDir) then Exit; if Data.Size <> 0 then Exit; Inc(FSequenceNumber); FResultCode := -1; FCallStatus := SPAWN_STATUS_RUNNING; try SaveCurrentDir := GetCurrentDir; try SetCurrentDir(ClientCurrentDir); Result := SPAWN_MSGRESULT_SUCCESS_BITS or FSequenceNumber; { Send back the result code now to unblock the client } ReplyMessage(Result); if IsShellExec then begin ExecResult := InstShellExec(EVerb, EFilename, EParams, EWorkingDir, TExecWait(EWait), EShowCmd, ProcessMessagesProc, FResultCode); end else begin ExecResult := InstExec(EDisableFsRedir <> 0, EFilename, EParams, EWorkingDir, TExecWait(EWait), EShowCmd, ProcessMessagesProc, FResultCode); end; if ExecResult then FCallStatus := SPAWN_STATUS_RETURNED_TRUE else FCallStatus := SPAWN_STATUS_RETURNED_FALSE; finally SetCurrentDir(SaveCurrentDir); end; finally { If the status is still SPAWN_STATUS_RUNNING here, then an unexpected exception must've occurred } if FCallStatus = SPAWN_STATUS_RUNNING then FCallStatus := SPAWN_STATUS_EXCEPTION; end; end; procedure TSpawnServer.WndProc(var Message: TMessage); var Res: LRESULT; begin case Message.Msg of WM_COPYDATA: begin try case TWMCopyData(Message).CopyDataStruct.dwData of CD_SpawnServer_Exec, CD_SpawnServer_ShellExec: begin Message.Result := HandleExec( TWMCopyData(Message).CopyDataStruct.dwData = CD_SpawnServer_ShellExec, TWMCopyData(Message).CopyDataStruct.lpData, TWMCopyData(Message).CopyDataStruct.cbData); end; end; except if ExceptObject is EOutOfMemory then Message.Result := SPAWN_MSGRESULT_OUT_OF_MEMORY else { Shouldn't get here; we don't explicitly raise any exceptions } Message.Result := SPAWN_MSGRESULT_UNEXPECTED_EXCEPTION; end; end; WM_SpawnServer_Query: begin Res := SPAWN_MSGRESULT_INVALID_SEQUENCE_NUMBER; if Message.LParam = FSequenceNumber then begin Res := SPAWN_MSGRESULT_INVALID_QUERY_OPERATION; case Message.WParam of SPAWN_QUERY_STATUS: Res := SPAWN_MSGRESULT_SUCCESS_BITS or FCallStatus; SPAWN_QUERY_RESULTCODE_LO: Res := SPAWN_MSGRESULT_SUCCESS_BITS or LongRec(FResultCode).Lo; SPAWN_QUERY_RESULTCODE_HI: Res := SPAWN_MSGRESULT_SUCCESS_BITS or LongRec(FResultCode).Hi; end; end; Message.Result := Res; end; WM_USER + 150: begin { Got a SetupNotifyWnd message. (See similar handling in SetupLdr.dpr) } if Message.WParam = 10000 then FNotifyRestartRequested := True else if Message.WParam = 10001 then FNotifyNewLanguage := Message.LParam; end; else Message.Result := DefWindowProc(FWnd, Message.Msg, Message.WParam, Message.LParam); end; end; var Kernel32Handle: HMODULE; initialization Kernel32Handle := GetModuleHandle(kernel32); VerSetConditionMaskFunc := GetProcAddress(Kernel32Handle, 'VerSetConditionMask'); VerifyVersionInfoWFunc := GetProcAddress(Kernel32Handle, 'VerifyVersionInfoW'); end.
{******************************************************************} { } { Borland Delphi Runtime Library } { RAS error messages and return code checking function } { } { Portions created by Microsoft are } { Copyright (C) 1995-1999 Microsoft Corporation. } { All Rights Reserved. } { } { The original Pascal code is: RasUtils.pas, released 02 Jan 2000 } { The initial developer of the Pascal code is Petr Vones } { (petr.v@mujmail.cz). } { } { Portions created by Petr Vones are } { Copyright (C) 1999 Petr Vones } { } { Obtained through: } { } { Joint Endeavour of Delphi Innovators (Project JEDI) } { } { You may retrieve the latest version of this file at the Project } { JEDI home page, located at http://delphi-jedi.org } { } { The contents of this file are used with permission, subject to } { the Mozilla Public License Version 1.1 (the "License"); you may } { not use this file except in compliance with the License. You may } { obtain a copy of the License at } { http://www.mozilla.org/MPL/MPL-1.1.html } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or } { implied. See the License for the specific language governing } { rights and limitations under the License. } { } {******************************************************************} unit RasUtils; interface uses Windows, SysUtils, Ras, RasError; function RasCheck(RetCode: DWORD): DWORD; function RasErrorMessage(RetCode: DWORD): String; function SysAndRasErrorMessage(RetCode: DWORD): String; function RasConnStatusString(State: TRasConnState; ErrorCode: DWORD = 0): String; implementation resourcestring sRasError = 'RAS Error code: %d.'#10'"%s"'; sRASCS_OpenPort = 'Port is about to be opened'; sRASCS_PortOpened = 'Port has been opened'; sRASCS_ConnectDevice = 'A device is about to be connected'; sRASCS_DeviceConnected = 'A device has connected successfully'; sRASCS_AllDevicesConnected = 'All devices in the device chain have successfully connected'; sRASCS_Authenticate = 'The authentication process is starting'; sRASCS_AuthNotify = 'An authentication event has occurred'; sRASCS_AuthRetry = 'The client has requested another validation attempt with a new user name/password/domain'; sRASCS_AuthCallback = 'The remote access server has requested a callback number'; sRASCS_AuthChangePassword = 'The client has requested to change the password on the account'; sRASCS_AuthProject = 'The projection phase is starting'; sRASCS_AuthLinkSpeed = 'The link-speed calculation phase is starting'; sRASCS_AuthAck = 'An authentication request is being acknowledged'; sRASCS_ReAuthenticate = 'Reauthentication (after callback) is starting'; sRASCS_Authenticated = 'The client has successfully completed authentication'; sRASCS_PrepareForCallback = 'The line is about to disconnect in preparation for callback'; sRASCS_WaitForModemReset = 'The client is delaying in order to give the modem time to reset itself in preparation for callback'; sRASCS_WaitForCallback = 'The client is waiting for an incoming call from the remote access server'; sRASCS_Projected = 'Projection result information is available'; sRASCS_StartAuthentication = 'User authentication is being initiated or retried'; sRASCS_CallbackComplete = 'Client has been called back and is about to resume authentication'; sRASCS_LogonNetwork = 'Client is logging on to the network'; sRASCS_SubEntryConnected = 'Subentry has been connected during the dialing process'; sRASCS_SubEntryDisconnected = 'Subentry has been disconnected during the dialing process'; sRASCS_Interactive = 'Terminal state supported by RASPHONE.EXE'; sRASCS_RetryAuthentication = 'Retry authentication state supported by RASPHONE.EXE'; sRASCS_CallbackSetByCaller = 'Callback state supported by RASPHONE.EXE'; sRASCS_PasswordExpired = 'Change password state supported by RASPHONE.EXE'; sRASCS_Connected = 'Connected'; sRASCS_Disconnected = 'Disconnected'; function RasErrorMessage(RetCode: DWORD): String; var C: array[0..1024] of AnsiChar; begin ZeroMemory(@C[0], 1025); if RasGetErrorStringA(RetCode, @C, Sizeof(C)) = SUCCESS then Result := C else Result := ''; end; function SysAndRasErrorMessage(RetCode: DWORD): String; begin // if (RetCode >= RASBASE) and (RetCode <= RASBASEEND) then Result := RasErrorMessage(RetCode); // else // Result := SysErrorMessage(RetCode); end; function RasCheck(RetCode: DWORD): DWORD; var Error: EWin32Error; begin if RetCode <> SUCCESS then begin Error := EWin32Error.CreateFmt(sRasError, [RetCode, SysAndRasErrorMessage(RetCode)]); Error.ErrorCode := RetCode; raise Error; end; Result := RetCode; end; function RasConnStatusString(State: TRasConnState; ErrorCode: DWORD = 0): String; begin if ErrorCode <> 0 then Result := SysAndRasErrorMessage(ErrorCode) else case State of RASCS_OpenPort: Result := sRASCS_OpenPort; RASCS_PortOpened: Result := sRASCS_PortOpened; RASCS_ConnectDevice: Result := sRASCS_ConnectDevice; RASCS_DeviceConnected: Result := sRASCS_DeviceConnected; RASCS_AllDevicesConnected: Result := sRASCS_AllDevicesConnected; RASCS_Authenticate: Result := sRASCS_Authenticate; RASCS_AuthNotify: Result := sRASCS_AuthNotify; RASCS_AuthRetry: Result := sRASCS_AuthRetry; RASCS_AuthCallback: Result := sRASCS_AuthCallback; RASCS_AuthChangePassword: Result := sRASCS_AuthChangePassword; RASCS_AuthProject: Result := sRASCS_AuthProject; RASCS_AuthLinkSpeed: Result := sRASCS_AuthLinkSpeed; RASCS_AuthAck: Result := sRASCS_AuthAck; RASCS_ReAuthenticate: Result := sRASCS_ReAuthenticate; RASCS_Authenticated: Result := sRASCS_Authenticated; RASCS_PrepareForCallback: Result := sRASCS_PrepareForCallback; RASCS_WaitForModemReset: Result := sRASCS_WaitForModemReset; RASCS_WaitForCallback: Result := sRASCS_WaitForCallback; RASCS_Projected: Result := sRASCS_Projected; RASCS_StartAuthentication: Result := sRASCS_StartAuthentication; RASCS_CallbackComplete: Result := sRASCS_CallbackComplete; RASCS_LogonNetwork: Result := sRASCS_LogonNetwork; RASCS_SubEntryConnected: Result := sRASCS_SubEntryConnected; RASCS_SubEntryDisconnected: Result := sRASCS_SubEntryDisconnected; RASCS_Interactive: Result := sRASCS_Interactive; RASCS_RetryAuthentication: Result := sRASCS_RetryAuthentication; RASCS_CallbackSetByCaller: Result := sRASCS_CallbackSetByCaller; RASCS_PasswordExpired: Result := sRASCS_PasswordExpired; RASCS_Connected: Result := sRASCS_Connected; RASCS_Disconnected: Result := sRASCS_Disconnected; else Result := ''; end; end; end.
unit ChromeLikeBaseThemedWindowCaptionButton; // Модуль: "w:\common\components\gui\Garant\ChromeLikeControls\ChromeLikeBaseThemedWindowCaptionButton.pas" // Стереотип: "GuiControl" // Элемент модели: "TChromeLikeBaseThemedWindowCaptionButton" MUID: (533D07A201C1) interface {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3IntfUses , ChromeLikeBaseWindowCaptionButton , UxTheme , Messages , Classes ; type TChromeLikeThemedWindowCaptionButtonPaintParams = record {* параметры отрисовки кнопок } rPartID: Integer; rStateID: Integer; end;//TChromeLikeThemedWindowCaptionButtonPaintParams TChromeLikeBaseThemedWindowCaptionButton = class(TChromeLikeBaseWindowCaptionButton) private f_Theme: HTHEME; private procedure WMThemeChanged(var aMessage: TMessage); message WM_THEMECHANGED; protected function pm_GetTheme: HTHEME; function GetPaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams; virtual; {$If NOT Defined(NoVCL)} procedure DestroyWnd; override; {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} procedure Paint; override; {$IfEnd} // NOT Defined(NoVCL) public constructor Create(AOwner: TComponent); override; protected property Theme: HTHEME read pm_GetTheme; end;//TChromeLikeBaseThemedWindowCaptionButton {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3ImplUses , Windows , SysUtils {$If NOT Defined(NoVCL)} , Controls {$IfEnd} // NOT Defined(NoVCL) , Graphics , l3Base {$If NOT Defined(NoScripts)} , TtfwClassRef_Proxy {$IfEnd} // NOT Defined(NoScripts) //#UC START# *533D07A201C1impl_uses* //#UC END# *533D07A201C1impl_uses* ; function TChromeLikeBaseThemedWindowCaptionButton.pm_GetTheme: HTHEME; //#UC START# *533D09010204_533D07A201C1get_var* const cWndClassName: PWideChar = 'WINDOW'; //#UC END# *533D09010204_533D07A201C1get_var* begin //#UC START# *533D09010204_533D07A201C1get_impl* if (f_Theme = 0) then f_Theme := OpenThemeData(Handle, cWndClassName); Result := f_Theme; //#UC END# *533D09010204_533D07A201C1get_impl* end;//TChromeLikeBaseThemedWindowCaptionButton.pm_GetTheme function TChromeLikeBaseThemedWindowCaptionButton.GetPaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams; //#UC START# *533D091902B8_533D07A201C1_var* //#UC END# *533D091902B8_533D07A201C1_var* begin //#UC START# *533D091902B8_533D07A201C1_impl* l3FillChar(Result, SizeOf(Result), 0); //#UC END# *533D091902B8_533D07A201C1_impl* end;//TChromeLikeBaseThemedWindowCaptionButton.GetPaintParams procedure TChromeLikeBaseThemedWindowCaptionButton.WMThemeChanged(var aMessage: TMessage); //#UC START# *533D08600262_533D07A201C1_var* //#UC END# *533D08600262_533D07A201C1_var* begin //#UC START# *533D08600262_533D07A201C1_impl* inherited; // Тема изменилась. Нужно закрыть старые данные темы, получить новые // и отрисоваться if (f_Theme <> 0) then begin CloseThemeData(f_Theme); f_Theme := 0; end; if IsAppThemed then Invalidate; //#UC END# *533D08600262_533D07A201C1_impl* end;//TChromeLikeBaseThemedWindowCaptionButton.WMThemeChanged constructor TChromeLikeBaseThemedWindowCaptionButton.Create(AOwner: TComponent); //#UC START# *47D1602000C6_533D07A201C1_var* //#UC END# *47D1602000C6_533D07A201C1_var* begin //#UC START# *47D1602000C6_533D07A201C1_impl* inherited Create(aOwner); f_Theme := HTHEME(0); DoubleBuffered := True; //#UC END# *47D1602000C6_533D07A201C1_impl* end;//TChromeLikeBaseThemedWindowCaptionButton.Create {$If NOT Defined(NoVCL)} procedure TChromeLikeBaseThemedWindowCaptionButton.DestroyWnd; //#UC START# *4CC841540158_533D07A201C1_var* //#UC END# *4CC841540158_533D07A201C1_var* begin //#UC START# *4CC841540158_533D07A201C1_impl* if (f_Theme <> 0) then CloseThemeData(f_Theme); inherited; //#UC END# *4CC841540158_533D07A201C1_impl* end;//TChromeLikeBaseThemedWindowCaptionButton.DestroyWnd {$IfEnd} // NOT Defined(NoVCL) {$If NOT Defined(NoVCL)} procedure TChromeLikeBaseThemedWindowCaptionButton.Paint; //#UC START# *5028A60300AD_533D07A201C1_var* const BS_INACTIVE = 5; // недокументированный флаг для рисования неактивной кнопки // в заголовке окна var l_PaintParams: TChromeLikeThemedWindowCaptionButtonPaintParams; l_Rect: TRect; //#UC END# *5028A60300AD_533D07A201C1_var* begin //#UC START# *5028A60300AD_533D07A201C1_impl* l_PaintParams := GetPaintParams; // Окно может быть неактивным. Кнопку для него нужно рисовать с отдельным флагом // BS_INACTIVE, если на нее не наведена мышь и если кнопка не нажата if (State = cbsNormal) and (not ParentForm.Active) then l_PaintParams.rStateID := BS_INACTIVE; Windows.GetClientRect(Handle, l_Rect); // кнопки на XP, Vista и W7 имеют скругления - под ними не должно быть серого фона, // нарисуем родительский фон (фон заголовка окна) if IsThemeBackgroundPartiallyTransparent(Theme, l_PaintParams.rPartID, l_PaintParams.rStateID) then DrawThemeParentBackground(Handle, Canvas.Handle, @l_Rect); DrawThemeBackground(Theme, Canvas.Handle, l_PaintParams.rPartID, l_PaintParams.rStateID, l_Rect, nil); //#UC END# *5028A60300AD_533D07A201C1_impl* end;//TChromeLikeBaseThemedWindowCaptionButton.Paint {$IfEnd} // NOT Defined(NoVCL) initialization {$If NOT Defined(NoScripts)} TtfwClassRef.Register(TChromeLikeBaseThemedWindowCaptionButton); {* Регистрация TChromeLikeBaseThemedWindowCaptionButton } {$IfEnd} // NOT Defined(NoScripts) {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) end.
{ Subroutine SST_W_C_SMENT_END_NCLOSE * * This routine is called to indicate that the "statement" started with * subroutine SST_W_C_SMENT_START is finished. The appropriate state * is popped/restored. The indentation level is decreased by one, since * is was incremented by one in SST_W_C_SMENT_START. } module sst_w_c_SMENT_END_NCLOSE; define sst_w_c_sment_end_nclose; %include 'sst_w_c.ins.pas'; procedure sst_w_c_sment_end_nclose; {done writing statement, leave line as is} var frame_p: frame_sment_p_t; {pointer to previous statement stack frame} begin sst_w.undent^; {restore indentation level to statement start} util_stack_last_frame ( {get pointer to last frame on stack} sst_stack, sizeof(frame_sment_p^), frame_p); if frame_p <> frame_sment_p then begin {our frame isn't last on stack ?} sys_message_bomb ('sst_c_write', 'stack_sment_frame_err', nil, 0); end; frame_p := frame_sment_p^.prev_p; {save pointer to previous sment stack frame} util_stack_pop (sst_stack, sizeof(frame_sment_p^)); {remove old stack frame} frame_sment_p := frame_p; {pop current frame back to previous frame} end;
unit NewsServerInterfaces; interface type INewsServer = interface procedure CreateNewsCenter ( World : string ); procedure CreateNewspaper ( World, Name, Style, Town : string ); procedure GenerateNewspapers( World : widestring; Date : TDateTime ); end; implementation end.
{ ********************************************************************* Gnostice eDocEngine Copyright (c) Gnostice Information Technologies Private Limited http://www.gnostice.com ********************************************************************* } {$I ..\gtSharedDefines.inc} { ------------------------------------ } { Editor Options } { ------------------------------------ } { } { Tab Stops = 2 } { Use Tab Character = True } { } { ------------------------------------ } unit gtGlyphInfo; interface uses Graphics, Windows, Classes, gtMLang; type TgtWordArray = array of Word; TgtGlyphType = (gdComplex, gdLigature, gdRTL); TgtScriptVisAttr = (svClusterStart, { :1 } // First glyph of representation of cluster svDiacritic, { :1 } // Diacritic svZeroWidth { :1 } // Blank, ZWJ, ZWNJ etc, with no width ); TgtScriptVisAttrs = set of TgtScriptVisAttr; TgtGlyphTypes = set of TgtGlyphType; TgtRunInfo = record GlyphType: TgtGlyphTypes; StartPos: Integer; EndPos: Integer; IsFontMapped: Boolean; VisAttr: array of TgtScriptVisAttrs; ScriptProcessingRequired: Boolean; MappedFontName: TFontName; end; TgtGlyphInfoList = class; TgtMapFont = class; // AText: Complete text // ARunIndex: Zero-based index for the script runs // AIsComplex: True if the text represents a complex script // AGlyphInfoList: List of TgtGlyphInfo objects for this script run TgtScriptRunCallback = procedure(AText: WideString; ARunIndex, ARunCount: Integer; var AGlyphInfoList: TgtGlyphInfoList; AGlyphDetail: TgtRunInfo; ALogClust: TgtWordArray) of object; TgtGlyphInfo = class(TPersistent) private FID: Word; FAdvWidth: Integer; FABCWidth: ABC; FPosition: Integer; FFontName: string; public constructor Create(AID: Word; AAdvWidth: Integer; AABCWidth: ABC; APos: Integer; AFont: TFont); overload; constructor Create; overload; destructor Destroy; override; procedure Assign(Source: TPersistent); override; property ID: Word read FID; property AdvWidth: Integer read FAdvWidth; property ABCWidth: ABC read FABCWidth; property Position: Integer read FPosition; property FontName: string read FFontName; end; TgtGlyphInfoList = class(TList) private FOwnsObjects: Boolean; function GetItem(Index: Integer): TgtGlyphInfo; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create; overload; constructor Create(AOwnsObjects: Boolean); overload; property Items[Index: Integer]: TgtGlyphInfo read GetItem; default; property OwnsObjects: Boolean read FOwnsObjects write FOwnsObjects; end; TgtStringAnalyzer = class private FMapFont: TgtMapFont; class function ZeroGlyphs(AGlyphIDs: array of Word; ACount: Integer): Boolean; public procedure StringAnalyze(AText: WideString; ABiDiMode: TBiDiMode; AFont: TFont; AScriptRunCallback: TgtScriptRunCallback; AMapFont: TgtMapFont); end; TgtMappedFont = class private FFontName: TFontName; procedure SetFontName(const Value: TFontName); public constructor Create(AFontName: TFontName); destructor Destroy; override; property FontName: TFontName read FFontName write SetFontName; end; TgtFontSizeMapping = class private FFont: TFont; FInputFontSize: Integer; procedure SetFont(const Value: TFont); procedure SetInputFontSize(const Value: Integer); public constructor Create(AFont: TFont); // input font destructor Destroy; override; property Font: TFont read FFont write SetFont; property InputFontSize: Integer read FInputFontSize write SetInputFontSize; end; TgtFontUnicodeSubRangeInfo = class private FLatinCharRange: Boolean; procedure SetLatinCharRange(const Value: Boolean); public constructor Create(AFontName: TFontName); destructor Destroy; override; property LatinCharRange: Boolean read FLatinCharRange write SetLatinCharRange; end; TgtMapFont = class private FLastResult: HRESULT; FPrevCodePages: DWORD; FHashCodePages: TStringList; FMappedFontSizeList: TStringList; FSysFontList: TStringList; FAllUsedFonts: TStringList; FMappedFonts: TStringList; FUnicodeRangeMappedFonts: TStringList; FUnicodeSubRangeInfo: TStringList; function IsTrueType(AFont: TFont): Boolean; procedure SetLastResult(const Value: HRESULT); // function GetDefaultFont: TFont; procedure SetPrevCodePages(const Value: DWORD); procedure SetAllUsedFonts(const Value: TStringList); public constructor Create; destructor Destroy; override; function GetNextInstalledFont(AFont: TFont; var AIndex: Integer): TFont; function GetNextFontFromUsedList(AFont: TFont; var AUsedFontIndex: Integer): TFont; function GetMappedFont(AText: LPCWSTR; AFont: TFont): TFont; function GetTrueTypeFont(AText: WideString; AFont: TFont): TFont; function GetFontSize(AFont: TFont): Integer; function IsLatinUnicodeRangePresent(AFont: TFont): Boolean; property LastResult: HRESULT read FLastResult write SetLastResult; property PrevCodePages: DWORD read FPrevCodePages write SetPrevCodePages; property AllUsedFonts: TStringList read FAllUsedFonts write SetAllUsedFonts; end; implementation uses Forms, {$IFDEF gtDelphi6Up} StrUtils, {$ENDIF} SysUtils, gtUtils3, gtConsts3, gtDocUsp10; var FontList: TStringList; I, LCount: Integer; ArialUni: string; constructor TgtGlyphInfo.Create(AID: Word; AAdvWidth: Integer; AABCWidth: ABC; APos: Integer; AFont: TFont); begin FID := AID; // FAdvWidth := AAdvWidth; FABCWidth := AABCWidth; { The TrueType rasterizer provides ABC character spacing after a specific point size has been selected. A spacing is the distance added to the current position before placing the glyph. B spacing is the width of the black part of the glyph. C spacing is the distance added to the current position to provide white space to the right of the glyph. The total advanced width is specified by A+B+C. } FAdvWidth := ABCWidth.abcA + Integer(ABCWidth.abcB) + ABCWidth.abcC; FPosition := APos; FFontName := AFont.Name; end; procedure TgtGlyphInfo.Assign(Source: TPersistent); begin with TgtGlyphInfo(Source) do begin Self.FID := FID; Self.FAdvWidth := FAdvWidth; Self.FABCWidth := FABCWidth; Self.FPosition := FPosition; Self.FFontName := FFontName; end; end; constructor TgtGlyphInfo.Create; begin inherited; end; destructor TgtGlyphInfo.Destroy; begin inherited; end; { TgtGlyphInfoList } constructor TgtGlyphInfoList.Create; begin inherited Create; FOwnsObjects := True; end; constructor TgtGlyphInfoList.Create(AOwnsObjects: Boolean); begin inherited Create; FOwnsObjects := AOwnsObjects; end; function TgtGlyphInfoList.GetItem(Index: Integer): TgtGlyphInfo; begin Result := TgtGlyphInfo( inherited Items[Index]); end; procedure TgtGlyphInfoList.Notify(Ptr: Pointer; Action: TListNotification); begin if OwnsObjects then if Action = lnDeleted then TgtGlyphInfo(Ptr).Free; inherited Notify(Ptr, Action); end; { TgtStringAnalyzer } class function TgtStringAnalyzer.ZeroGlyphs(AGlyphIDs: array of Word; ACount: Integer): Boolean; var LI: Integer; begin Result := False; for LI := 0 to (ACount - 1) do begin Result := (AGlyphIDs[LI] = 0); if (Result) then Break; end; end; procedure TgtStringAnalyzer.StringAnalyze(AText: WideString; ABiDiMode: TBiDiMode; AFont: TFont; AScriptRunCallback: TgtScriptRunCallback; AMapFont: TgtMapFont); var LPInChars: PWideChar; LScriptControl: TScriptControl; LScriptState: TScriptState; LScriptProperties: array of PScriptProperties; LScriptItems: array of TScriptItem; LScriptItemCount, LMaxScripts: Integer; LResult: HRESULT; LMaxScriptItems: Integer; LBiDiLevels: array of Byte; LVisual2Logical: array of Integer; LI, LJ, LK: Integer; LN, LAllUsedFontIndex: Integer; LHdc: HDC; LScriptCache: TScriptCache; LScriptItemLength: Integer; LMaxGlyphIDs: Integer; LItemGlyphCnt: Integer; LAdvWidths: array of Integer; LItemGlyphIDs: array of Word; LLogClust: TgtWordArray ; LVisAttr: array of TScriptVisAttr; LScriptVisiAttr: TgtScriptVisAttrs; LGlyphOffsets: array of TGOffset; LScriptItemABC: ABC; LRTL, LRTLSubString: Boolean; LGlyphInfo: TgtGlyphInfo; LPos: Integer; LFontMapped: Boolean; LMappedFont: TFont; LRunInfoList: TgtGlyphInfoList; LIsComplex, LIsFontMapped, LIsStringProcessingReq, LFontSupportsLatin, LIsReturnedComplex: Boolean; LStrInANSIRange: Boolean; LSubText: WideString; LX: Integer; LMapFont: TgtMappedFont; // LIndex: Integer; LRunInfo: TgtRunInfo; LUnicodeRange: TgtFontUnicodeSubRangeInfo; begin LRunInfoList := nil; FMapFont := AMapFont; LFontMapped := False; LRTLSubString := False; LIsReturnedComplex := False; if (AText = '') then Exit; if (not Assigned(AScriptRunCallback)) then Exit; LPInChars := PWideChar(AText); if (ABiDiMode = bdRightToLeft) or (ABiDiMode = bdRightToLeftNoAlign) or (ABiDiMode = bdRightToLeftReadingOnly) then LRTL := True else LRTL := False; // Init with LScriptControl do begin uDefaultLanguage := 0; fFlags := []; fReserved := 0; end; with LScriptState do begin fFlags := []; if LRTL then begin fFlags := [uBidiLevel_reserved1]; end else fFlags := []; end; // Applies the regional settings, digit substitution settings, to the specified // script control and script state structures. ScriptApplyDigitSubstitution(nil, @LScriptControl, @LScriptState); // ScriptItemize LMaxScriptItems := 2; repeat SetLength(LScriptItems, LMaxScriptItems); LResult := ScriptItemize(LPInChars, Length(AText), LMaxScriptItems, @LScriptControl, @LScriptState, @LScriptItems[0], @LScriptItemCount); if ((LResult <> S_OK) and (LResult <> E_OUTOFMEMORY)) then Break; Inc(LMaxScriptItems); until (LResult = S_OK); // ScriptLayout SetLength(LBiDiLevels, LScriptItemCount + 1); SetLength(LVisual2Logical, LScriptItemCount + 1); for LI := 0 to LScriptItemCount do begin LBiDiLevels[LI] := LScriptItems[LI].a.s.uBidiLevel; if (fRTL in LScriptItems[LI].a.fFlags) then LRTLSubString := True; end; ScriptLayout(LScriptItemCount + 1, @LBiDiLevels[0], @LVisual2Logical[0], nil); // ScriptShape LHdc := GetDC(0); SelectObject(LHdc, AFont.Handle); LPos := 0; LScriptCache := nil; LMappedFont := TFont.Create; LMappedFont.Assign(AFont); for LI := 0 to (LScriptItemCount - 1) do begin LRunInfo.IsFontMapped := False; LN := 0; LAllUsedFontIndex := 0; LIsFontMapped := False; LK := LVisual2Logical[LI]; LScriptItemLength := LScriptItems[LK + 1].iCharPos - LScriptItems [LK].iCharPos; LMaxGlyphIDs := LScriptItemLength; SetLength(LLogClust, LScriptItemLength); LPInChars := @(AText[LScriptItems[LK].iCharPos + 1]); LSubText := ''; LStrInANSIRange := True; for LX := (LScriptItems[LK].iCharPos + 1) to (LScriptItems[LK + 1].iCharPos) do begin LSubText := LSubText + AText[LX]; if not((ord(AText[LX]) >= 32) and (ord(AText[LX]) <= 255)) then LStrInANSIRange := False; end; // space, punctuation marks etc. are under SIC_NEUTRAL LIsComplex := (ScriptIsComplex(LPInChars, LScriptItemLength, SIC_COMPLEX) = S_OK); LFontSupportsLatin := AMapFont.IsLatinUnicodeRangePresent(AFont); // Checking for only the first char of 'LSubText' is sufficient, // bcoz ScriptItemize will break string according to unicode subranges // If font doesn't support Latin unicode Subrange, then if the font is already // mapped to other font for the same reason, then get the index of it // If the font is not already mapped then do script processing once, to get // Mapped font name // LIndex := -1; // if not LFontSupportsLatin and not LIsComplex and LStrInANSIRange then // LIndex := AMapFont.FUnicodeRangeMappedFonts.IndexOf(AFont.Name); // Below are the three condition for checking whether string requires script // processing, // In first 2 cases string doesn't require script processing // 1. when string is in range 32 to 255 and font supports Latin charset // 2. when string is in range 32 to 255 and font doesn't support Latin charset // but is already mapped // 3. when string is outside 255 or when font doesn't support latin charset // then it requires script processing if not LRTL and LFontSupportsLatin and not LIsComplex and LStrInANSIRange and not LIsReturnedComplex then begin // Font doesn't require any mapping. LRunInfo.GlyphType := []; // if LRTLSubString then // LRunInfo.GlyphType := LRunInfo.GlyphType + [gdRTL]; if LIsComplex then LRunInfo.GlyphType := LRunInfo.GlyphType + []; LRunInfo.StartPos := LScriptItems[LK].iCharPos; LRunInfo.EndPos := LScriptItems[LK + 1].iCharPos; LRunInfo.ScriptProcessingRequired := False; LRunInfo.MappedFontName := AFont.Name; AScriptRunCallback(LSubText, LI, LScriptItemCount, LRunInfoList, LRunInfo, LLogClust); end (* else if not LRTL and (not LFontSupportsLatin) and not LIsComplex and LStrInANSIRange and (LIndex <> -1) then begin //font doesn't support Latin unicode Subrange, //the same font is mapped to other font in the prev iteration- use it // if LRTLSubString then // LRunInfo.GlyphType := LRunInfo.GlyphType + [gdRTL]; LRunInfo.GlyphType := []; if LIsComplex then LRunInfo.GlyphType := LRunInfo.GlyphType + []; LRunInfo.StartPos := LScriptItems[LK].iCharPos; LRunInfo.EndPos := LScriptItems[LK + 1].iCharPos; LRunInfo.ScriptProcessingRequired := False; LMapFont := TgtMappedFont(AMapFont.FUnicodeRangeMappedFonts.Objects[LIndex]); LRunInfo.MappedFontName := LMapFont.FFontName; AScriptRunCallback(LSubText, LI, LScriptItemCount, LRunInfoList, LRunInfo, @LLogClust[0]); end *) else begin // Requires script processing if (LFontMapped) then begin FreeAndNil(LMappedFont); LMappedFont := TFont.Create; LMappedFont.Assign(AFont); SelectObject(LHdc, AFont.Handle); LFontMapped := False; end; repeat if LScriptCache <> nil then ScriptFreeCache(@LScriptCache); SetLength(LItemGlyphIDs, LMaxGlyphIDs); SetLength(LVisAttr, LMaxGlyphIDs); LResult := ScriptShape(LHdc, @LScriptCache, LPInChars, LScriptItemLength, LMaxGlyphIDs, @(LScriptItems[LK].a), @LItemGlyphIDs[0], @LLogClust[0], @LVisAttr[0], @LItemGlyphCnt); if (LResult = E_OUTOFMEMORY) then Inc(LMaxGlyphIDs) else if (LResult = E_PENDING) then begin ReleaseDC(0, LHdc); LHdc := GetDC(0); SelectObject(LHdc, AFont.Handle); end else if ((LResult = Integer(USP_E_SCRIPT_NOT_IN_FONT)) or (ZeroGlyphs(LItemGlyphIDs, LItemGlyphCnt))) then begin // If ZeroGlyphs, it means script not in font LResult := Integer(USP_E_SCRIPT_NOT_IN_FONT); if Assigned(LMappedFont) then FreeAndNil(LMappedFont); if (LAllUsedFontIndex < FMapFont.AllUsedFonts.Count) then begin LMappedFont := FMapFont.GetNextFontFromUsedList(AFont, LAllUsedFontIndex); // If original font is not vertical, but used font is vertical then // remove '@' from font name if (AFont.Name[1] <> '@') and (LMappedFont.Name[1] = '@') then LMappedFont.Name := RightStr(LMappedFont.Name, Length(LMappedFont.Name) - 1); end else if not LIsFontMapped then begin if Assigned(LMappedFont) then FreeAndNil(LMappedFont); LMappedFont := FMapFont.GetMappedFont(@LSubText[1], AFont); if (FMapFont.PrevCodePages = 0) or ((LMappedFont <> nil) and (AnsiCompareText(LMappedFont.Name, AFont.Name) = 0)) then begin if Assigned(LMappedFont) then FreeAndNil(LMappedFont); LMappedFont := FMapFont.GetNextInstalledFont(AFont, LN); if (AFont.Name[1] <> '@') and (LMappedFont.Name[1] = '@') then LMappedFont.Name := RightStr(LMappedFont.Name, Length(LMappedFont.Name) - 1); end; LIsFontMapped := True; end else begin if Assigned(LMappedFont) then FreeAndNil(LMappedFont); LMappedFont := FMapFont.GetNextInstalledFont(AFont, LN); if (AFont.Name[1] <> '@') and (LMappedFont.Name[1] = '@') then LMappedFont.Name := RightStr(LMappedFont.Name, Length(LMappedFont.Name) - 1); end; if not Assigned(LMappedFont) or (LIsFontMapped and (LN >= FMapFont.FSysFontList.Count)) then Break; SelectObject(LHdc, LMappedFont.Handle); LFontMapped := True; LRunInfo.IsFontMapped := True; end; // event can be invoked here to give opportuniy to specify different font to // map to - Sender, OriginalFont, MappedFont, NewFont, var MapToNewFont until (LResult = S_OK); if not LFontSupportsLatin and LStrInANSIRange and not LIsComplex then begin LMapFont := TgtMappedFont.Create(LMappedFont.Name); AMapFont.FUnicodeRangeMappedFonts.AddObject(AFont.Name, LMapFont); end; LRunInfo.MappedFontName := LMappedFont.Name; LRunInfo.GlyphType := []; LRunInfo.ScriptProcessingRequired := True; if LIsComplex then begin LRunInfo.GlyphType := LRunInfo.GlyphType + [gdComplex]; LIsReturnedComplex := True; end; if ((not LIsComplex) and (LItemGlyphCnt < LMaxGlyphIDs)) then begin LRunInfo.GlyphType := LRunInfo.GlyphType + [gdLigature]; LIsReturnedComplex := True; end; if (fRTL in LScriptItems[LK].a.fFlags) then begin LRunInfo.GlyphType := LRunInfo.GlyphType + [gdRTL]; LIsReturnedComplex := True; end; if (LResult = Integer(USP_E_SCRIPT_NOT_IN_FONT)) then Continue; if (FMapFont.AllUsedFonts.IndexOf(LMappedFont.Name) = -1) then FMapFont.AllUsedFonts.Add(LMappedFont.Name); // ScriptPlace SetLength(LAdvWidths, LItemGlyphCnt); SetLength(LGlyphOffsets, LItemGlyphCnt); ScriptPlace(LHdc, @LScriptCache, @LItemGlyphIDs[0], LItemGlyphCnt, @LVisAttr[0], @(LScriptItems[LK].a), @LAdvWidths[0], @LGlyphOffsets[0], @LScriptItemABC); LRunInfoList := TgtGlyphInfoList.Create(False); // ScriptGetGlyphABCWidth for LJ := 0 to (LItemGlyphCnt - 1) do begin ScriptGetGlyphABCWidth(LHdc, @LScriptCache, LItemGlyphIDs[LJ], @LScriptItemABC); LGlyphInfo := TgtGlyphInfo.Create(LItemGlyphIDs[LJ], LAdvWidths[LJ], LScriptItemABC, LPos, LMappedFont); Inc(LPos); LRunInfoList.Add(LGlyphInfo); end; LRunInfo.StartPos := LScriptItems[LK].iCharPos; LRunInfo.EndPos := LScriptItems[LK + 1].iCharPos; SetLength(LRunInfo.VisAttr, Length(LVisAttr)); for LJ := 0 to Length(LVisAttr) - 1 do begin LRunInfo.VisAttr[LJ] := []; if fClusterStart in LVisAttr[LJ].fFlags then LRunInfo.VisAttr[LJ] := LRunInfo.VisAttr[LJ] + [svClusterStart]; if fDiacritic in LVisAttr[LJ].fFlags then LRunInfo.VisAttr[LJ] := LRunInfo.VisAttr[LJ] + [svDiacritic]; if fZeroWidth in LVisAttr[LJ].fFlags then LRunInfo.VisAttr[LJ] := LRunInfo.VisAttr[LJ] + [svZeroWidth]; end; // Call back with info for this text script run if (Assigned(AScriptRunCallback)) then AScriptRunCallback(LSubText, LI, LScriptItemCount, LRunInfoList, LRunInfo, LLogClust); LAdvWidths := nil; LLogClust := nil; LVisAttr := nil; LGlyphOffsets := nil; LItemGlyphIDs := nil; end; end; ScriptFreeCache(@LScriptCache); ReleaseDC(0, LHdc); if Assigned(LMappedFont) then FreeAndNil(LMappedFont); end; { TgtMapFont } constructor TgtMapFont.Create; var ArialUni: string; LCount, I: Integer; begin FHashCodePages := TStringList.Create; FAllUsedFonts := TStringList.Create; FSysFontList := TStringList.Create; FSysFontList.AddStrings(Screen.Fonts); FMappedFonts := TStringList.Create; FUnicodeSubRangeInfo := TStringList.Create; FUnicodeRangeMappedFonts := TStringList.Create; FMappedFontSizeList := TStringList.Create; { while (FSysFontList.Count > 0) do begin if (FSysFontList.Strings[0][1] = '@') then FSysFontList.Delete(0) else Break; end; } // We'll use Arial Unicode MS as a last resort when performing font mapping // (when it has not been explicitly selected), as it's a very heavy font and // takes longer to process. ArialUni := UpperCase('Arial Unicode MS'); LCount := FSysFontList.Count - 1; for I := 0 to LCount do if UpperCase(FSysFontList[I]) = ArialUni then begin ArialUni := FSysFontList[I]; FSysFontList.Delete(I); FSysFontList.Append(ArialUni); Break; end; // initially stores list of known non-true type, mapped to true type fonts {$IFDEF gtDelphi6UP} FMappedFonts.CaseSensitive := False; {$ENDIF} if (FSysFontList.IndexOf('Courier New') <> -1) then FMappedFonts.AddObject('Courier', TgtMappedFont.Create('Courier New')); if (FSysFontList.IndexOf('Arial') <> -1) then FMappedFonts.AddObject('MS Sans Serif', TgtMappedFont.Create('Arial')); end; destructor TgtMapFont.Destroy; var LI: Integer; LMappedFont: TgtMappedFont; LUnicodeSubRange: TgtFontUnicodeSubRangeInfo; LMappedFontSize: TgtFontSizeMapping; begin if Assigned(FSysFontList) then FreeAndNil(FSysFontList); for LI := 0 to FHashCodePages.Count - 1 do begin LMappedFont := TgtMappedFont(FHashCodePages.Objects[LI]); LMappedFont.Free; end; FHashCodePages.Free; for LI := 0 to FMappedFonts.Count - 1 do begin LMappedFont := TgtMappedFont(FMappedFonts.Objects[LI]); LMappedFont.Free; end; FMappedFonts.Free; for LI := 0 to FUnicodeRangeMappedFonts.Count - 1 do begin LMappedFont := TgtMappedFont(FUnicodeRangeMappedFonts.Objects[LI]); LMappedFont.Free; end; FUnicodeRangeMappedFonts.Free; for LI := 0 to FUnicodeSubRangeInfo.Count - 1 do begin LUnicodeSubRange := TgtFontUnicodeSubRangeInfo (FUnicodeSubRangeInfo.Objects[LI]); LUnicodeSubRange.Free; end; FUnicodeSubRangeInfo.Free; for LI := 0 to FMappedFontSizeList.Count - 1 do begin LMappedFontSize := TgtFontSizeMapping(FMappedFontSizeList.Objects[LI]); LMappedFontSize.Free; end; FMappedFontSizeList.Free; FAllUsedFonts.Free; inherited; end; //function TgtMapFont.GetDefaultFont: TFont; //begin // Result := TFont.Create; //end; function TgtMapFont.GetFontSize(AFont: TFont): Integer; var LFont: TFont; // LFOntSize: Integer; LDC: HDC; LSaveFont: HFont; LTM: TTextMetric; LSaveMM: Integer; LI: Integer; LMappedFontSize: TgtFontSizeMapping; begin LFont := TFont.Create; try LFont.Assign(AFont); LI := FMappedFontSizeList.IndexOf(AFont.Name); LMappedFontSize := nil; if LI >= 0 then begin LMappedFontSize := TgtFontSizeMapping(FMappedFontSizeList.Objects[LI]); end; if (LMappedFontSize <> nil) and (LMappedFontSize.InputFontSize = AFont.Size) then begin LFont.Size := LMappedFontSize.FFont.Size; // LFOntSize := LFont.Size; end else begin LDC := GetDC(0); LSaveMM := GetMapMode(LDC); SetMapMode(LDC, MM_TEXT); LSaveFont := SelectObject(LDC, AFont.Handle); GetTextMetrics(LDC, LTM); LFont.Size := Round((Abs(AFont.Height) - LTM.tmInternalLeading) * CInchesToPoints / CPixelsPerInch); LMappedFontSize := TgtFontSizeMapping.Create(AFont); LMappedFontSize.FFont.Size := LFont.Size; FMappedFontSizeList.AddObject(AFont.Name, LMappedFontSize); SelectObject(LDC, LSaveFont); SetMapMode(LDC, LSaveMM); ReleaseDC(0, LDC); end; finally Result := LFont.Size; LFont.Free; end; end; function TgtMapFont.GetMappedFont(AText: LPCWSTR; AFont: TFont): TFont; // var // LDC: HDC; // LLangFontLink2: IMLangFontLink2; // LLogFont: TLOGFONT; // LCount, LFontIndex: Integer; // LActualCodePages, LFontCodePages: DWORD; // LActualCount: LongInt; // LHFont: HFont; // LChar: WChar; // LText: WideString; // LMappedFont: TgtMappedFont; begin Result := TFont.Create; // LDC := GetDC(0); // LLangFontLink2 := CoMLangFontLink2.Create; // SelectObject(LDC, AFont.Handle); // LCount := Length(AText); Result.Assign(AFont); Result.Name := 'Arial'; Result.Size := AFont.Size; // try // FLastResult := LLangFontLink2.GetFontCodePages(LDC, AFont.Handle, // @LFontCodePages); // // if (Succeeded(FLastResult)) then // begin // SetLength(LText, LCount); // LText := AText; // // while(LCount > 0) do // begin // FLastResult := LLangFontLink2.GetStrCodePages(@LText[1], LCount, // LFontCodePages, @LActualCodePages, @LActualCount); // FPrevCodePages := LActualCodePages; // // if (Succeeded(FLastResult)) then // begin // { if((LActualCodePages and LFontCodePages) <> 0) then // begin // Result.Name := AFont.Name; // end // else } // begin // if LActualCodePages = 0 then // begin // Result.Free; // Result := GetDefaultFont; // Exit; // end; // // LFontIndex := FHashCodePages.IndexOf(IntToStr(LActualCodePages)); // // if LFontIndex > -1 then // begin // LMappedFont := TgtMappedFont(FHashCodePages.Objects[LFontIndex]); // Result.Name := LMappedFont.FontName; // Exit; // end; // LChar := ' '; // FLastResult := LLangFontLink2.MapFont(LDC, LActualCodePages, LChar, // (@LHFont)); // if (Succeeded(FLastResult)) then // begin // FillChar(LLogFont, SizeOf(LLogFont), 0); // GetObject(LHFont, SizeOf(LLogFont), addr(LLogFont)); // Result.Name := LLogFont.lfFaceName; // // LMappedFont := TgtMappedFont.Create(Result.Name); // FHashCodePages.AddObject(IntToStr(LActualCodePages), LMappedFont); // LLangFontLink2.ReleaseFont(LHFont); // end; // end; // if (Failed(FLastResult)) then // begin // Result.Assign(GetDefaultFont); // Exit; // end; // // LCount := LCount - LActualCount; // // SetLength(LText, LCount); // // LText := AnsiRightStr(AText, LCount); // end; // end; // end; // finally // ReleaseDC(0, LDC); // end; end; function TgtMapFont.GetNextFontFromUsedList(AFont: TFont; var AUsedFontIndex: Integer): TFont; begin Result := TFont.Create; try if (AUsedFontIndex < FAllUsedFonts.Count) then begin Result.Charset := AFont.Charset; Result.Name := FAllUsedFonts.Strings [FAllUsedFonts.Count - 1 - AUsedFontIndex]; if (AnsiCompareStr(Result.Name, AFont.Name) <> 0) then begin Result.Size := AFont.Size; Inc(AUsedFontIndex); Exit; end; // if font name is same then.. Inc(AUsedFontIndex); if (AUsedFontIndex < FAllUsedFonts.Count) then begin Result.Name := FAllUsedFonts.Strings [FAllUsedFonts.Count - 1 - AUsedFontIndex]; Result.Size := AFont.Size; Inc(AUsedFontIndex); Exit; end; end; finally end; end; function TgtMapFont.GetNextInstalledFont(AFont: TFont; var AIndex: Integer): TFont; begin Result := TFont.Create; if ((AIndex < 0) or (AIndex >= FSysFontList.Count)) then begin Result.Assign(AFont); Exit; end; try // to pick a font which is not available in FAllUsedFonts list if (FAllUsedFonts.IndexOf(FSysFontList.Strings[AIndex]) <> -1) then begin while (FAllUsedFonts.IndexOf(FSysFontList.Strings[AIndex]) <> -1) do begin Inc(AIndex); end; end; if (AIndex < FSysFontList.Count) then begin Result.Name := FSysFontList.Strings[AIndex]; Result.Size := AFont.Size; Result.Charset := AFont.Charset; Inc(AIndex); end; except FreeAndNil(Result); end; end; function TgtMapFont.GetTrueTypeFont(AText: WideString; AFont: TFont): TFont; var LIndex, LI: Integer; LIsTrueType: Boolean; LMappedObj: TgtMappedFont; LFont: TFont; begin Result := AFont; try LIndex := FMappedFonts.IndexOf(AFont.Name); if (LIndex <> -1) then begin LMappedObj := TgtMappedFont(FMappedFonts.Objects[LIndex]); Result.Name := LMappedObj.FontName; end else begin LI := FSysFontList.IndexOf(AFont.Name); if (LI <> -1) then begin LIsTrueType := IsTrueType(AFont); if LIsTrueType then begin FMappedFonts.AddObject(AFont.Name, TgtMappedFont.Create(AFont.Name)); end else begin LFont := GetMappedFont(@AText[1], AFont); FMappedFonts.AddObject(AFont.Name, TgtMappedFont.Create(LFont.Name)); Result.Name := LFont.Name; LFont.Free; end; end else if (LI = -1) then begin LFont := GetMappedFont(@AText[1], AFont); FMappedFonts.AddObject(AFont.Name, TgtMappedFont.Create(LFont.Name)); Result.Name := LFont.Name; LFont.Free; end; end; finally end; end; function TgtMapFont.IsLatinUnicodeRangePresent(AFont: TFont): Boolean; var LIndex: Integer; LDC: HDC; LFontSig: TFontSignature; LUnicodeSubRange: TgtFontUnicodeSubRangeInfo; begin try LIndex := FUnicodeSubRangeInfo.IndexOf(AFont.Name); if (LIndex <> -1) then begin LUnicodeSubRange := TgtFontUnicodeSubRangeInfo (FUnicodeSubRangeInfo.Objects[LIndex]); Result := LUnicodeSubRange.FLatinCharRange; Exit; end; LUnicodeSubRange := TgtFontUnicodeSubRangeInfo.Create(AFont.Name); LDC := GetDC(0); SelectObject(LDC, AFont.Handle); GetTextCharsetInfo(LDC, @LFontSig, 0); if (LFontSig.fsUsb[0] and 1) > 0 then LUnicodeSubRange.FLatinCharRange := True else LUnicodeSubRange.FLatinCharRange := False; Result := LUnicodeSubRange.FLatinCharRange; ReleaseDC(0, LDC); FUnicodeSubRangeInfo.AddObject(AFont.Name, LUnicodeSubRange); finally end; end; function SetFontTypeFlag(var LogFont: TEnumLogFont; var ptm: TNewTextMetric; FontType: Integer; Data: Pointer): Integer; stdcall; begin boolTrueType := (ptm.tmPitchAndFamily and TMPF_TRUETYPE) = TMPF_TRUETYPE; Result := 0; end; function TgtMapFont.IsTrueType(AFont: TFont): Boolean; var LDC: HDC; // LI: LongWord; LogF: Cardinal; begin // Result := False; LDC := GetDC(0); try if (AFont.Name = 'Symbol') or (AFont.Name = 'Wingdings') or (AFont.Name = 'Wingdings 2') or (AFont.Name = 'Wingdings 3') or (AFont.Name = 'Webdings') or (AFont.Name = 'Marlett') then begin LogF := CreateFont(AFont.Height, TextSize('W', AFont).cx, 0, 0, FW_REGULAR, 0, 0, 0, SYMBOL_CHARSET, OUT_TT_ONLY_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_DONTCARE, PChar(AFont.Name)); SelectObject(LDC, LogF); end else SelectObject(LDC, AFont.Handle); EnumFontFamilies(LDC, PChar(AFont.Name), @SetFontTypeFlag, 0); Result := boolTrueType; // LI := GetFontData(LDC, 0, 0, nil, 0); // if (LI <> GDI_ERROR) then // begin // Result := True; // end; finally ReleaseDC(0, LDC); end; end; procedure TgtMapFont.SetAllUsedFonts(const Value: TStringList); begin FAllUsedFonts := Value; end; procedure TgtMapFont.SetLastResult(const Value: HRESULT); begin FLastResult := Value; end; procedure TgtMapFont.SetPrevCodePages(const Value: DWORD); begin FPrevCodePages := Value; end; { TgtUsedFont } constructor TgtMappedFont.Create(AFontName: TFontName); begin FontName := AFontName; end; destructor TgtMappedFont.Destroy; begin SetLength(FFontName, 0); FFontName := ''; end; procedure TgtMappedFont.SetFontName(const Value: TFontName); begin FFontName := Value; end; { TgtFontUnicodeSubRangeInfo } constructor TgtFontUnicodeSubRangeInfo.Create(AFontName: TFontName); begin FLatinCharRange := True; end; destructor TgtFontUnicodeSubRangeInfo.Destroy; begin inherited; end; procedure TgtFontUnicodeSubRangeInfo.SetLatinCharRange(const Value: Boolean); begin FLatinCharRange := Value; end; { TgtMappedFontSize } constructor TgtFontSizeMapping.Create(AFont: TFont); begin FFont := TFont.Create; FFont.Assign(AFont); FInputFontSize := AFont.Size; end; destructor TgtFontSizeMapping.Destroy; begin if Assigned(FFont) then FreeAndNil(FFont); inherited; end; procedure TgtFontSizeMapping.SetFont(const Value: TFont); begin FFont := Value; end; procedure TgtFontSizeMapping.SetInputFontSize(const Value: Integer); begin FInputFontSize := Value; end; initialization FontList := TStringList.Create; FontList.AddStrings(Screen.Fonts); { while (FontList.Count > 0) do begin if (FontList.Strings[0][1] = '@') then FontList.Delete(0) else Break; end; } // We'll use Arial Unicode MS as a last resort when performing font mapping // (when it has not been explicitly selected), as it's a very heavy font and // takes longer to process. ArialUni := UpperCase('Arial Unicode MS'); LCount := FontList.Count - 1; for I := 0 to LCount do if UpperCase(FontList[I]) = ArialUni then begin ArialUni := FontList[I]; FontList.Delete(I); FontList.Append(ArialUni); Break; end; finalization FontList.Free; end.
unit TokyoScript.Chars; { TokyoScript (c)2018 Execute SARL http://www.execute.Fr } interface type TCharType = ( // Char to CharType ctNull, // 0 ctBinary, // 1..8, 11..12, 14..31 ctPadding, // 9, ' ' ctLineFeed, // 10 ctReturn, // 13 ctDigit, // '0'..'9' ctAlpha, // 'a'..'z', 'A'..'Z', '_' ctExclamat, // '!' ctDoubleQuote, // '"' ctSharp, // '#' ctDollar, // '$' ctPercent, // '%' ctAmpersand, // '&' ctSimpleQuote, // ' ctLParent, // '(' ctRParent, // ')' ctStar, // '*' ctPlus, // '+' ctComma, // ',' ctMinus, // '-' ctDot, // '.' ctSlash, // '/' ctColon, // ':' ctSemiColon, // ';' ctLT, // '<' ctEQ, // '=' ctGT, // '>' ctQuestion, // '?' ctAt, // '@' ctLBracket, // '[' ctBackSlash, // '\' ctRBracket, // ']' ctPower, // '^' ctGrave, // '`' ctLBrace, // '{' ctPipe, // '|' ctRBrace, // '}' ctTilde, // '~' ctAnsi, // > 127 ctUnicode, // > 255 // more types ctNone, ctAssign, // ':=' ctGE, // '>=' ctLE, // '<=' ctNE, // '<>' ctRange, // '..' ctIdent, // ctApha + [ctAlpha|dtDigits]* ctKeyword, ctChar, // #[$]123 ctHexa, // $xxx ctNumber, // 123 ctReal, // 1.23 ctString // 'hello' ); TCharTypes = set of TCharType; function GetCharType(c: Char): TCharType; implementation const CHARTYPES : array[#0..#126] of TCharType = ( ctNull, // 0 ctBinary, ctBinary, ctBinary, ctBinary, // 1..8 ctBinary, ctBinary, ctBinary, ctBinary, ctPadding, // 9 ctLineFeed, // 10 ctBinary, ctBinary, // 11, 12 ctReturn, // 13 ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, // 14..31 ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctBinary, ctPadding, // 32 ctExclamat, // ! ctDoubleQuote, // " ctSharp, // # ctDollar, // $ ctPercent, // % ctAmpersand, // & ctSimpleQuote, // ' ctLParent, // ( ctRParent, // ) ctStar, // * ctPlus, // + ctComma, // , ctMinus, // - ctDot, // . ctSlash, // / ctDigit, ctDigit, ctDigit, ctDigit, ctDigit, // 0..9 ctDigit, ctDigit, ctDigit, ctDigit, ctDigit, ctColon, // : ctSemiColon, // ; ctLT, // < ctEQ, // = ctGT, // > ctQuestion, // ? ctAt, // @ ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, // A .. Z ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctLBracket, // [ ctBackSlash, // \ ctRBracket, // ] ctPower, // ^ ctAlpha, // _ ctGrave, // ` = Chr(96) ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, // a .. z ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctAlpha, ctLBrace, // { ctPipe, // | ctRBrace, // } ctTilde // ~ // 127 = DEL ); function GetCharType(c: Char): TCharType; begin if Ord(c) > 255 then Exit(ctUnicode); if Ord(c) > 126 then Exit(ctAnsi); Result := CHARTYPES[c]; end; end.
unit AutomaticEvaluatedBlocks; interface uses Collection, Kernel, OutputEvaluators; const MaxEvaluators = 8; // >> This figure might not change MaxInputsByEvaluator = 10; // >> This figure might change const InputValueEps = 0.5; // Value to lower bound input values type TShareOutTable = array[0..MaxEvaluators-1, 0..MaxInputsByEvaluator-1] of TFluidValue; TEvaluateTable = array[0..MaxEvaluators-1] of boolean; TAutomaticEvaluatedBlock = class(TBlock) public constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override; destructor Destroy; override; private fEvaluators : TCollection; private function GetEvaluatorCount : integer; function GetEvaluator(index : integer) : TOutputEvaluator; public property EvaluatorCount : integer read GetEvaluatorCount; property Evaluators[index : integer] : TOutputEvaluator read GetEvaluator; public function Evaluate : TEvaluationResult; override; public procedure RegisterOutputEvaluator(Evaluator : TOutputEvaluator); end; implementation uses Classes, SysUtils, MathUtils; // TAutomaticEvaluatedBlock constructor TAutomaticEvaluatedBlock.Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); begin inherited; fEvaluators := Collection.TCollection.Create(0, rkBelonguer); // >> ?? end; destructor TAutomaticEvaluatedBlock.Destroy; begin fEvaluators.Free; inherited; end; function TAutomaticEvaluatedBlock.GetEvaluatorCount : integer; begin result := fEvaluators.Count; end; function TAutomaticEvaluatedBlock.GetEvaluator(index : integer) : TOutputEvaluator; begin result := TOutputEvaluator(fEvaluators[index]); end; function TAutomaticEvaluatedBlock.Evaluate : TEvaluationResult; var ShareOutTable : TShareOutTable; EvaluateTable : TEvaluateTable; CurInput : TInput; CurEvaluator : TOutputEvaluator; i, j : integer; count : integer; share : TFluidValue; need : boolean; InputValue : TFluidValue; begin // Init shareout table FillChar(ShareOutTable, sizeof(ShareOutTable), 0); // Fill evaluator table count := 0; for i := 0 to pred(EvaluatorCount) do begin if Evaluators[i].ShouldProduce then begin EvaluateTable[i] := true; inc(count); end else EvaluateTable[i] := false; end; // Check if there is at least one to produce if count > 0 then begin // Check for inputs to find out who can and who cannot evaluate count := 0; for i := 0 to pred(InputCount) do begin CurInput := Inputs[i]; for j := 0 to pred(EvaluatorCount) do begin need := Evaluators[j].NeedsInput(CurInput); if not need then ShareOutTable[j, i] := -1 else EvaluateTable[i] := EvaluateTable[i] and (CurInput.FluidData.Q > 0) // >> end; if EvaluateTable[i] then inc(count); end; // Check if there are some one to evaluate if count > 0 then begin // Sharing inputs for i := 0 to pred(InputCount) do begin CurInput := Inputs[i]; InputValue := CurInput.FluidData.Q; while InputValue > InputValueEps do // >> begin for j := 0 to pred(EvaluatorCount) do begin CurEvaluator := Evaluators[j]; if EvaluateTable[j] and (ShareOutTable[j, i] <> -1) then begin share := CurEvaluator.ShareToPullFromImput(CurInput); InputValue := InputValue - share; ShareOutTable[j, i] := realmin( ShareOutTable[j, i] + share, CurEvaluator.MaxToPullFromImput(CurInput)); end; end; CurInput.FluidData.Q := InputValue; end; end; end; end; // For suitability in the algorithm, now lets clear the fluid to pull for i := 0 to InputCount do Inputs[i].ActualMaxFluid.Q := 0; // Evaluate & mix the remainders for i := 0 to pred(EvaluatorCount) do begin CurEvaluator := Evaluators[i]; if EvaluateTable[i] then begin for j := 0 to pred(InputCount) do begin InputValue := ShareOutTable[i, j]; if InputValue > 0 then Inputs[j].FluidData.Q := InputValue; end; CurEvaluator.Evaluate; end; CurEvaluator.MixRemainder; CurEvaluator.PlanInputForNextPeriod; end; result := evrNormal; end; procedure TAutomaticEvaluatedBlock.RegisterOutputEvaluator(Evaluator : TOutputEvaluator); begin if OutputsByName[Evaluator.MetaEvaluator.MetaOutput.Name] = nil then raise Exception.Create('Wrong output "' + Evaluator.MetaEvaluator.MetaOutput.Name + '" for this block') else fEvaluators.Insert(Evaluator); end; end.
unit U7; interface uses SingletonTemplate, SAVLib, UAccessBase, UAccessUser, UAccessGroup, UAccessADGroup, UAccessFile, UAccessDomain; type TSettings = class(TSingleton) protected constructor Create; override; public destructor Destroy; override; private FConfigFile: string; FSettingPath: string; FBase: TSAVAccessBase; FDomain: TSAVAccessDomain; FUser: TSAVAccessUser; FGroup: TSAVAccessGroup; FADGroup: TSAVAccessADGroup; procedure SetConfigFile(const Value: string); procedure SetBase(const Value: TSAVAccessBase); procedure SetDomain(const Value: TSAVAccessDomain); procedure SetGroup(const Value: TSAVAccessGroup); procedure SetUser(const Value: TSAVAccessUser); procedure SetADGroup(const Value: TSAVAccessADGroup); public property SettingPath: string read FSettingPath; property ConfigFile: string read FConfigFile write SetConfigFile; property Base: TSAVAccessBase read FBase write SetBase; property Domain: TSAVAccessDomain read FDomain write SetDomain; property User: TSAVAccessUser read FUser write SetUser; property Group: TSAVAccessGroup read FGroup write SetGroup; property ADGroup: TSAVAccessADGroup read FADGroup write SetADGroup; end; function Settings: TSettings; implementation uses IniFiles, SysUtils, DU1; function Settings: TSettings; begin Result := TSettings.GetInstance; end; { TSettings } constructor TSettings.Create; var ini: TMemIniFile; begin inherited; FSettingPath := GetSpecialFolderLocation(CSIDL_APPDATA, FOLDERID_RoamingAppData); if FSettingPath = '' then FSettingPath := GetCurrentDir; FSettingPath := IncludeTrailingPathDelimiter(FSettingPath) + 'SAVAccessAdmin\'; ini := TMemIniFile.Create(FSettingPath + 'SAVAccessAdmin.ini'); FConfigFile := ini.ReadString('option', 'config', ''); FreeAndNil(ini); FBase := TSAVAccessBase.Create; FBase.TableUsers := dtmdl1.vkdbfUsers; FBase.TableDomains := dtmdl1.vkdbfDomain; FBase.TableGroups := dtmdl1.vkdbfGroups; FBase.TableADGroups := dtmdl1.vkdbfADGroups; FDomain := TSAVAccessDomain.Create; FUser := TSAVAccessUser.Create; FGroup := TSAVAccessGroup.Create; FADGroup := TSAVAccessADGroup.Create; end; destructor TSettings.Destroy; var ini: TMemIniFile; begin if not (DirectoryExists(FSettingPath)) then ForceDirectories(FSettingPath); ini := TMemIniFile.Create(FSettingPath + 'SAVAccessAdmin.ini'); ini.WriteString('option', 'config', FConfigFile); ini.UpdateFile; FreeAndNil(ini); FreeAndNil(FBase); FreeAndNil(FDomain); FreeAndNil(FUser); FreeAndNil(FGroup); FreeAndNil(FADGroup); inherited; end; procedure TSettings.SetADGroup(const Value: TSAVAccessADGroup); begin FADGroup := Value; end; procedure TSettings.SetBase(const Value: TSAVAccessBase); begin FBase := Value; end; procedure TSettings.SetConfigFile(const Value: string); begin FConfigFile := Value; end; procedure TSettings.SetDomain(const Value: TSAVAccessDomain); begin FDomain := Value; end; procedure TSettings.SetGroup(const Value: TSAVAccessGroup); begin FGroup := Value; end; procedure TSettings.SetUser(const Value: TSAVAccessUser); begin FUser := Value; end; end.
{ CFPropertyList.h Copyright (c) 1998-2005, Apple, Inc. All rights reserved. } { Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, September 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CFPropertyList; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase,CFData,CFString,CFStream; {$ALIGN POWER} type CFPropertyListMutabilityOptions = SInt32; const kCFPropertyListImmutable = 0; kCFPropertyListMutableContainers = 1; kCFPropertyListMutableContainersAndLeaves = 2; { Creates a property list object from its XML description; xmlData should be the raw bytes of that description, possibly the contents of an XML file. Returns NULL if the data cannot be parsed; if the parse fails and errorString is non-NULL, a human-readable description of the failure is returned in errorString. It is the caller's responsibility to release either the returned object or the error string, whichever is applicable. } function CFPropertyListCreateFromXMLData( allocator: CFAllocatorRef; xmlData: CFDataRef; mutabilityOption: CFOptionFlags; errorString: CFStringRefPtr ): CFPropertyListRef; external name '_CFPropertyListCreateFromXMLData'; { Returns the XML description of the given object; propertyList must be one of the supported property list types, and (for composite types like CFArray and CFDictionary) must not contain any elements that are not themselves of a property list type. If a non-property list type is encountered, NULL is returned. The returned data is appropriate for writing out to an XML file. Note that a data, not a string, is returned because the bytes contain in them a description of the string encoding used. } function CFPropertyListCreateXMLData( allocator: CFAllocatorRef; propertyList: CFPropertyListRef ): CFDataRef; external name '_CFPropertyListCreateXMLData'; { Recursively creates a copy of the given property list (so nested arrays and dictionaries are copied as well as the top-most container). The resulting property list has the mutability characteristics determined by mutabilityOption. } function CFPropertyListCreateDeepCopy( allocator: CFAllocatorRef; propertyList: CFPropertyListRef; mutabilityOption: CFOptionFlags ): CFPropertyListRef; external name '_CFPropertyListCreateDeepCopy'; {#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED} type CFPropertyListFormat = SInt32; const kCFPropertyListOpenStepFormat = 1; kCFPropertyListXMLFormat_v1_0 = 100; kCFPropertyListBinaryFormat_v1_0 = 200; function CFPropertyListIsValid( plist: CFPropertyListRef; format: CFPropertyListFormat ): Boolean; external name '_CFPropertyListIsValid'; { Returns true if the object graph rooted at plist is a valid property list * graph -- that is, no cycles, containing only plist objects, and dictionary * keys are strings. The debugging library version spits out some messages * to be helpful. The plist structure which is to be allowed is given by * the format parameter. } function CFPropertyListWriteToStream( propertyList: CFPropertyListRef; stream: CFWriteStreamRef; format: CFPropertyListFormat; var errorString: CFStringRef ): CFIndex; external name '_CFPropertyListWriteToStream'; { Writes the bytes of a plist serialization out to the stream. The * stream must be opened and configured -- the function simply writes * a bunch of bytes to the stream. The output plist format can be chosen. * Leaves the stream open, but note that reading a plist expects the * reading stream to end wherever the writing ended, so that the * end of the plist data can be identified. Returns the number of bytes * written, or 0 on error. Error messages are not currently localized, but * may be in the future, so they are not suitable for comparison. } function CFPropertyListCreateFromStream( allocator: CFAllocatorRef; stream: CFReadStreamRef; streamLength: CFIndex; mutabilityOption: CFOptionFlags; var format: CFPropertyListFormat; var errorString: CFStringRef ): CFPropertyListRef; external name '_CFPropertyListCreateFromStream'; { Same as current function CFPropertyListCreateFromXMLData() * but takes a stream instead of data, and works on any plist file format. * CFPropertyListCreateFromXMLData() also works on any plist file format. * The stream must be open and configured -- the function simply reads a bunch * of bytes from it starting at the current location in the stream, to the END * of the stream, which is expected to be the end of the plist, or up to the * number of bytes given by the length parameter if it is not 0. Error messages * are not currently localized, but may be in the future, so they are not * suitable for comparison. } {#endif} end.
unit MainUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TMainForm = class(TForm) EditInput: TEdit; EditOutput: TEdit; ButtonConvert: TButton; procedure ButtonConvertClick(Sender: TObject); private { Private declarations } public { Public declarations } end; StackElement = ^TStack; TStack = Record CurrentElement: Char; NextElement: StackElement; end; var MainForm: TMainForm; implementation {$R *.dfm} procedure PushSymbolIntoStack(var InputStack: StackElement; Symbol: Char); var InsertElement: StackElement; begin New(InsertElement); InsertElement^.CurrentElement := Symbol; InsertElement^.NextElement := InputStack; InputStack := InsertElement; end; function PopSymbolFromStack(var InputStack: StackElement): Char; begin if InputStack <> nil then begin PopSymbolFromStack := InputStack^.CurrentElement; InputStack := InputStack^.NextElement; end else PopSymbolFromStack := #0; //стек пуст end; function GetStackSymbolPriority(InputSymbol: Char): Byte; begin case InputSymbol of '+','-' : Result := 2; '*','/' : Result := 4; '^' : Result := 5; 'a'..'z','A'..'Z' : Result := 8; '(' : Result := 0; else Result := 10; end; end; function GetInputSymbolPriority(InputSymbol: Char): Byte; begin case InputSymbol of '+','-' : Result := 1; '*','/' : Result := 3; '^' : Result := 6; 'a'..'z','A'..'Z' : Result := 7; '(' : Result := 9; ')' : Result := 0; else Result := 10; end; end; function GetCharRang (InputSymbol: Char): Integer; begin if InputSymbol in ['a'..'z', 'A'..'Z'] then Result := 1 else Result := - 1; end; function ConvertingIntoPolandRecord(InputMathExpression: String): String; var i: Integer; ExpressionRang: Integer; OutputMathExpression: String; DataStack: StackElement; TempSymbol: Char; ScobeRang: Integer; begin DataStack := nil; ExpressionRang := 0; ScobeRang := 0; OutputMathExpression := ''; for i := 1 to Length(InputMathExpression) do begin if InputMathExpression[i] = ')' then Inc(ScobeRang); if InputMathExpression[i] = '(' then Dec(ScobeRang); if ScobeRang > 1 then break; end; if ScobeRang <> 0 then ShowMessage('Проверьте правильность введённых скобок'); i := 1; while i <= Length(InputMathExpression) do begin if ((DataStack = nil) or ((GetInputSymbolPriority(InputMathExpression[i]) ) > GetStackSymbolPriority(DataStack^.CurrentElement))) then begin if (InputMathExpression[i] <> ')' ) then PushSymbolIntoStack(DataStack, InputMathExpression[i]); Inc(i); end else begin TempSymbol := PopSymbolFromStack(DataStack); if TempSymbol <> '(' then begin OutputMathExpression := OutputMathExpression + TempSymbol; ExpressionRang := ExpressionRang + GetCharRang(TempSymbol); end; end; end; // извлекаем из стека остаток символов while DataStack <> nil do begin TempSymbol := PopSymbolFromStack(DataStack); if TempSymbol <> '(' then begin OutputMathExpression := OutputMathExpression + TempSymbol; end; end; Inc(ExpressionRang, ScobeRang); ConvertingIntoPolandRecord := OutputMathExpression + ' | Rang = ' + IntToStr(ExpressionRang); if ExpressionRang <> 1 then ShowMessage('Исходная запись является неверной'); end; procedure TMainForm.ButtonConvertClick(Sender: TObject); begin EditOutput.Text := ConvertingIntoPolandRecord(EditInput.Text); end; end.
{******************************************************************************} { } { Hook and Translate } { } { The contents of this file are subject to the MIT License (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at https://opensource.org/licenses/MIT } { } { Software distributed under the License is distributed on an "AS IS" basis, } { WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for } { the specific language governing rights and limitations under the License. } { } { The Original Code is Main.pas. } { } { Contains various graphics related classes and subroutines required for } { creating a chart and its nodes, and visual chart interaction. } { } { Unit owner: Mišel Krstović } { Last modified: March 8, 2010 } { } {******************************************************************************} unit Main; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, ShellAPI, ComCtrls, ExtCtrls, Menus, IniFiles, JvAppInst{, CommCtrl}; const NULL = 0; WM_HOOK_AND_TRANSLATE = WM_USER + 1; BLANK_TRANSLATION = ''; type TfrmHookAndTranslateMain = class(TForm) JvAppInstances1: TJvAppInstances; ShutdownTimer: TTimer; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ShutdownTimerTimer(Sender: TObject); private { Private declarations } GlobalClose : Boolean; GlobalTraining : Boolean; GlobalGdiHooking : Boolean; GlobalTransHooking : Boolean; GlobalIniFile : TMemIniFile; GlobalSleepTime : Integer; FClassName : String; function GetKey(Section, Key : String) : String; procedure l8Translate(WindowName : String); overload; procedure l8Translate(hHandle : HWND); overload; procedure l8handlePrimaryObjects(Tray : HWND); procedure l8handleSecondaryObjects(Tray : HWND); procedure l8handleMenus(handle : HMENU; var MenuLevel : Integer); function l8GetClassName : String; procedure l8UpdateFont(adc : HDC); public { Public declarations } procedure WndProc(var AMessage: TMessage); override; end; var frmHookAndTranslateMain: TfrmHookAndTranslateMain; implementation uses Global, GDIHook; {$R *.dfm} procedure StartHook; stdcall; external 'GdiHook.dll'; procedure StopHook; stdcall; external 'GdiHook.dll'; procedure TfrmHookAndTranslateMain.WndProc(var AMessage: TMessage); var hHandle, FoundHandle : HWND; ClassName_ : array [0..200] of Char; MenuLevel : Integer; begin if AMessage.Msg = WM_HOOK_AND_TRANSLATE then begin hHandle := LONGWORD(AMessage.lParam); if IsWindow(hHandle) then begin l8Translate(hHandle); end else begin FoundHandle := FindWindow(PChar(l8GetClassName), nil); if GetClassName(FoundHandle, ClassName_, SizeOf(ClassName_))<>NULL then begin if ClassName_=l8GetClassName then begin // Menu translation MenuLevel := -1; l8handleMenus(GetMenu(FoundHandle), MenuLevel); SendMessage(FoundHandle, WM_NCPAINT, 1, 0); // Refresh the translated menu items end; end; end; end else begin inherited WndProc(AMessage); end; end; procedure TfrmHookAndTranslateMain.l8UpdateFont(adc : HDC); var newFont : HFONT; It, Ul, So: Cardinal; oldFont : TEXTMETRICA; faceName : String; begin // Only if a current font exists shall we send a new one if GetTextMetrics(adc, oldFont) then begin if GetTextFace(adc, length(faceName), PChar(faceName))=0 then faceName := 'Times New Roman'; if oldFOnt.tmItalic<>0 then It := 1 else It := 0; if oldFOnt.tmUnderlined<>0 then Ul := 1 else Ul := 0; if oldFOnt.tmStruckOut<>0 then So := 1 else So := 0; newFont := CreateFontA(oldFOnt.tmHeight, oldFOnt.tmAveCharWidth, 0, 0, FW_NORMAL, It, Ul, So, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, PChar(faceName)); end; SelectObject(adc, newFont); end; function TfrmHookAndTranslateMain.GetKey(Section, Key : String) : String; begin result := BLANK_TRANSLATION; // writeln('['+section+'] '+Key); Section := trim(Section); Key := trim(Key); Key := StringReplace(Key, #10, '', [rfReplaceAll]); Key := StringReplace(Key, #13, '\n', [rfReplaceAll]); try if GlobalIniFile.ValueExists(Section, Key) then begin result := GlobalIniFile.ReadString(Section, Key, BLANK_TRANSLATION); result := StringReplace(result, '\n', #13#10, [rfReplaceAll]); end else begin if GlobalTraining then begin GlobalIniFile.WriteString(Section, Key, BLANK_TRANSLATION); GlobalIniFile.UpdateFile; end; end; finally end; end; procedure TfrmHookAndTranslateMain.l8Translate(hHandle: HWND); begin if hHandle<>NULL then begin l8handlePrimaryObjects(hHandle); end; end; procedure TfrmHookAndTranslateMain.l8Translate(WindowName : String); var FoundHandle: HWND; begin FoundHandle := FindWindow(PChar(WindowName), nil); if FoundHandle<>NULL then begin l8handlePrimaryObjects(FoundHandle); end; end; procedure TfrmHookAndTranslateMain.ShutdownTimerTimer(Sender: TObject); var FoundHandle : HWND; WindowName : String; begin if GlobalClose then exit; ShutdownTimer.Enabled := false; try WindowName := l8GetClassName; if WindowName<>'' then begin FoundHandle := FindWindow(PChar(WindowName), nil); if FoundHandle=NULL then begin GlobalClose := true; Close; end; end; finally if not(GlobalClose) then begin ShutdownTimer.Interval := 1500; ShutdownTimer.Enabled := true; end; end; end; procedure TfrmHookAndTranslateMain.l8handlePrimaryObjects(Tray: HWND); var C: array [0..127] of Char; S: string; Len: Integer; Result : String; customfont : HFONT; faceName : String; TrayDC : HDC; oldFont : TEXTMETRICA; begin if GetClassName(Tray, C, SizeOf(C)) > 0 then begin S := StrPas(C); Len := SendMessage(Tray, WM_GETTEXTLENGTH, 0, 0); if Len>0 then begin TrayDC := GetDC(Tray); try SetLength(Result, Len+1); SendMessage(Tray, WM_GETTEXT, length(Result), LPARAM(PChar(Result))); result := Copy(result, 0, length(result)-1); if GetTextMetrics(TrayDC, oldFont) then begin if GetTextFace(TrayDC, length(faceName), PChar(faceName))=0 then faceName := 'Tahoma'; customfont := CreateFont(oldFOnt.tmHeight, oldFOnt.tmAveCharWidth, 0, 0, 400, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE, PChar(faceName)); SendMessage(Tray, WM_SETFONT, customfont, 0); end; Result := GetKey(UpperCase(S), result); if Result<>'' then begin SendMessage(Tray, WM_SETTEXT, 0, LPARAM(PChar(Result))); end; finally ReleaseDC(Tray, TrayDC); end; end else begin // SysTabControl32 // if S='SysTabControl32' then begin // if S='#32770' then begin // SendMessage(Tray, TCM_DELETEALLITEMS, 0, 0); // SendMessage(Tray, WM_COMMAND, SC_CLOSE, 0); // end else begin // writeln(S); // end; end; // l8handleSecondaryObjects(Tray); // todo: experimental end; end; { This function is no longer required, since the method used by utilizing a reflector hook is more than adequate in passing all the created windows/classes back for processing. } procedure TfrmHookAndTranslateMain.l8handleSecondaryObjects(Tray : HWND); var Child: HWND; C: array [0..127] of Char; S: string; Len: Integer; Result : String; customfont : HFONT; ChildDC : HDC; faceName : String; oldFont : TEXTMETRICA; begin Child := GetWindow(Tray, GW_CHILD); while Child <> 0 do begin if GetClassName(Child, C, SizeOf(C)) > 0 then begin S := StrPas(C); Len := SendMessage(Child, WM_GETTEXTLENGTH, 0, 0); if Len>0 then begin ChildDC := GetDC(Child); try SetLength(Result, Len+1); SendMessage(Child, WM_GETTEXT, length(Result), LPARAM(PChar(Result))); result := Copy(result, 0, length(result)-1); Result := GetKey(UpperCase(S), result); if Result<>'' then begin SendMessage(Child, WM_SETTEXT, 0, LPARAM(PChar(Result))); end; finally ReleaseDC(Child, ChildDC); end; end; end; Child := GetWindow(Child, GW_HWNDNEXT); l8handleSecondaryObjects(Child); end; end; function TfrmHookAndTranslateMain.l8GetClassName: String; begin if FClassName='' then begin FClassName := trim(GetKey('System','ClassName')); end; result := FClassName; end; procedure TfrmHookAndTranslateMain.l8handleMenus(handle : HMENU; var MenuLevel : Integer); var hSubMenu : HMENU; MenuName : String; Len, Count : Integer; I : Cardinal; Buffer : String; MenuItemStruc : tagMENUITEMINFO; begin if handle=NULL then exit; Count := GetMenuItemCount(handle); if Count=0 then exit; Inc(MenuLevel); for i := 0 to Count - 1 do begin len := GetMenuString(handle, i, PChar(MenuName), 0, MF_BYPOSITION); SetLength(MenuName, Len+1); if GetMenuString(handle, i, PChar(MenuName), length(MenuName), MF_BYPOSITION)<>0 then begin MenuName := Copy(MenuName, 0, length(MenuName)-1); Buffer := GetKey('THUNDERRT6MENU', MenuName); if Buffer<>'' then begin MenuItemStruc.cbSize := sizeof(MENUITEMINFO); MenuItemStruc.fMask := MIIM_STRING; MenuItemStruc.cch := length(Buffer)+1; MenuItemStruc.dwTypeData := PChar(Buffer); SetMenuItemInfo(handle, i, TRUE, MenuItemStruc); end; end; hSubMenu := GetSubMenu(handle, MenuLevel); if hSubMenu<>NULL then begin l8handleMenus(hSubMenu, MenuLevel); end; end; end; procedure TfrmHookAndTranslateMain.FormClose(Sender: TObject; var Action: TCloseAction); begin try ShutdownTimer.Enabled := false; Application.ProcessMessages; if GlobalTransHooking then begin RemoveGlobalHook; Sleep(GlobalSleepTime); end; if GlobalGdiHooking then begin StopHook; Sleep(GlobalSleepTime); end; finally GlobalIniFile.Free; end; end; procedure TfrmHookAndTranslateMain.FormCreate(Sender: TObject); var FileName : String; ExecResult : Cardinal; begin GlobalClose := false; GlobalIniFile := TMemIniFile.Create(ExtractFilePath(ParamStr(0))+PathDelim+'Settings.ini'); FileName := trim(GetKey('System','FileName'));; GlobalSleepTime := StrToIntDef(GetKey('System', 'SleepTime'), 1000); ExecResult := ShellExecute(GetDesktopWindow, 'open', PChar(FileName), nil, nil, SW_SHOWNORMAL); Sleep(GlobalSleepTime); if ExecResult>32 then begin GHookInstalled := false; LibLoaded := false; try GlobalTraining := lowercase(GetKey('System', 'Training')) = 'true'; GlobalGdiHooking := lowercase(GetKey('System', 'GdiHooking')) = 'true'; GlobalTransHooking := lowercase(GetKey('System', 'TransHooking')) = 'true'; if GlobalTransHooking then begin GHookInstalled := SetupGlobalHook; Sleep(GlobalSleepTime); end; if GlobalGdiHooking then begin StartHook; Sleep(GlobalSleepTime); end; finally // Do nothing end; ShutdownTimer.Interval := 10000; ShutdownTimer.Enabled := true; end; end; end.
unit ZMWorkFile19; (* ZMWorkFile19.pas - basic in/out for zip files Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TZipMaster is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip modified 2010-06-20 --------------------------------------------------------------------------- *) (* if Len < 0 then must process on this segment ????Full - gives error if not processed non-split ????Check - gives error if not all done // Len = int64 function Seek(offset: Int64; From: integer): Int64; virtual; procedure CopyTo(var dest: TZMWorkFile; Len: Int64; ErrId: Integer); virtual; // only operate on < 2G at a time procedure CopyToFull(var dest: TZMWorkFile; Len, ErrId: Integer); virtual; function Read(var Buffer; ReadLen: Integer): Integer; virtual; procedure ReadCheck(var Buffer; Len, ErrId: Integer); virtual; procedure ReadFull(var Buffer; ReadLen, DSErrIdent: Integer); virtual; function Write(const Buffer; Len: Integer): Integer; virtual; function WriteCheck(const Buffer; Len, ErrId: Integer): Integer; virtual; procedure WriteFull(const Buffer; Len, ErrIdent: Integer); virtual; *) interface uses Classes, Windows, SysUtils, ZipMstr19, ZMDelZip19, ZMCore19, ZMDrv19; // file signitures read by OpenEOC type TZipFileSigs = (zfsNone, zfsLocal, zfsMulti, zfsDOS); type TZipNumberScheme = (znsNone, znsVolume, znsName, znsExt); type TZipWrites = (zwDefault, zwSingle, zwMultiple); const ProgressActions: array [TZipShowProgress] of TActionCodes = (zacTick, zacProgress, zacXProgress); MustFitError = -10999; MustFitFlag = $20000; // much bigger than any 'fixed' field MustFitMask = $1FFFF; // removes flag limits 'fixed' length type // TBytArray = array of Byte; TByteBuffer = array of Byte; type TZMWorkFile = class(TObject) private fAllowedSize: Int64; FBoss: TZMCore; fBytesRead: Int64; fBytesWritten: Int64; fDiskNr: Integer; fFileName: String; fFile_Size: Int64; fHandle: Integer; fInfo: Cardinal; // fIsMultiDisk: Boolean; fIsOpen: Boolean; fIsTemp: Boolean; fLastWrite: TFileTime; fOpenMode: Cardinal; fRealFileName: String; fRealFileSize: Int64; FReqFileName: String; fShowProgress: TZipShowProgress; fSig: TZipFileSigs; fStampDate: Cardinal; fTotalDisks: Integer; fWorkDrive: TZMWorkDrive; fWorker: TZMCore; FZipDiskAction: TZMDiskAction; FZipDiskStatus: TZMZipDiskStatus; WBuf: array of Byte; function GetConfirmErase: Boolean; function GetExists: Boolean; function GetKeepFreeOnAllDisks: Cardinal; function GetKeepFreeOnDisk1: Cardinal; function GetLastWritten: Cardinal; function GetMaxVolumeSize: Int64; function GetMinFreeVolumeSize: Cardinal; function GetPosition_F: Int64; function GetSpanOptions: TZMSpanOpts; procedure SetBoss(const Value: TZMCore); procedure SetFileName(const Value: String); procedure SetHandle(const Value: Integer); procedure SetKeepFreeOnAllDisks(const Value: Cardinal); procedure SetKeepFreeOnDisk1(const Value: Cardinal); procedure SetMaxVolumeSize(const Value: Int64); procedure SetMinFreeVolumeSize(const Value: Cardinal); procedure SetPosition(const Value: Int64); procedure SetSpanOptions(const Value: TZMSpanOpts); procedure SetWorkDrive(const Value: TZMWorkDrive); protected fBufferPosition: Integer; fConfirmErase: Boolean; fDiskBuffer: TByteBuffer; FDiskWritten: Cardinal; fSavedFileInfo: _BY_HANDLE_FILE_INFORMATION; fIsMultiPart: Boolean; FNewDisk: Boolean; FNumbering: TZipNumberScheme; function ChangeNumberedName(const FName: String; NewNbr: Cardinal; Remove: boolean): string; procedure CheckForDisk(writing, UnformOk: Boolean); procedure ClearFloppy(const dir: String); function Copy_File(Source: TZMWorkFile): Integer; procedure Diag(const msg: String); function EOS: Boolean; procedure FlushDiskBuffer; function GetFileInformation(var FileInfo: _BY_HANDLE_FILE_INFORMATION): Boolean; function GetPosition: Int64; function HasSpanSig(const FName: String): boolean; function IsRightDisk: Boolean; procedure NewFlushDisk; function NewSegment: Boolean; function VolName(Part: Integer): String; function OldVolName(Part: Integer): String; function WriteSplit(const Buffer; ToWrite: Integer): Integer; function ZipFormat(const NewName: String): Integer; property AllowedSize: Int64 Read fAllowedSize Write fAllowedSize; property LastWrite: TFileTime read fLastWrite write fLastWrite; property OpenMode: Cardinal read fOpenMode; public constructor Create(wrkr: TZMCore); virtual; procedure AfterConstruction; override; function AskAnotherDisk(const DiskFile: String): Integer; function AskOverwriteSegment(const DiskFile: String; DiskSeq: Integer): Integer; procedure AssignFrom(Src: TZMWorkFile); virtual; procedure BeforeDestruction; override; function CheckRead(var Buffer; Len: Integer): Boolean; overload; procedure CheckRead(var Buffer; Len, ErrId: Integer); overload; function CheckReads(var Buffer; const Lens: array of Integer): Boolean; overload; procedure CheckReads(var Buffer; const Lens: array of Integer; ErrId: Integer); overload; function CheckSeek(offset: Int64; from, ErrId: Integer): Int64; function CheckWrite(const Buffer; Len: Integer): Boolean; overload; procedure CheckWrite(const Buffer; Len, ErrId: Integer); overload; function CheckWrites(const Buffer; const Lens: array of Integer): Boolean; overload; procedure CheckWrites(const Buffer; const Lens: array of Integer; ErrId: Integer); overload; procedure ClearFileInformation; function CopyFrom(Source: TZMWorkFile; Len: Int64): Int64; function CreateMVFileNameEx(const FileName: String; StripPartNbr, Compat: Boolean): String; function DoFileWrite(const Buffer; Len: Integer): Integer; function FileDate: Cardinal; procedure File_Close; procedure File_Close_F; function File_Create(const theName: String): Boolean; function File_CreateTemp(const Prefix, Where: String): Boolean; function File_Open(Mode: Cardinal): Boolean; function File_Rename(const NewName: string; const Safe: Boolean = false) : Boolean; function FinishWrite: Integer; procedure GetNewDisk(DiskSeq: Integer; AllowEmpty: Boolean); function LastWriteTime(var last_write: TFileTime): Boolean; function MapNumbering(Opts: TZMSpanOpts): TZMSpanOpts; procedure ProgReport(prog: TActionCodes; xprog: Integer; const Name: String; size: Int64); function Read(var Buffer; Len: Integer): Integer; function ReadFromFile(var Buffer; Len: Integer): Integer; function Reads(var Buffer; const Lens: array of Integer): Integer; function Reads_F(var Buffer; const Lens: array of Integer): Integer; function ReadTo(strm: TStream; Count: Integer): Integer; function Read_F(var Buffer; Len: Integer): Integer; function SaveFileInformation: Boolean; function Seek(offset: Int64; from: Integer): Int64; function SeekDisk(Nr: Integer): Integer; function SetEndOfFile: Boolean; function VerifyFileInformation: Boolean; function WBuffer(size: Integer): pByte; function Write(const Buffer; Len: Integer): Integer; function WriteFrom(strm: TStream; Count: Integer): Int64; function Writes(const Buffer; const Lens: array of Integer): Integer; function Writes_F(const Buffer; const Lens: array of Integer): Integer; function WriteToFile(const Buffer; Len: Integer): Integer; function Write_F(const Buffer; Len: Integer): Integer; property Boss: TZMCore read FBoss write SetBoss; property BytesRead: Int64 read fBytesRead write fBytesRead; property BytesWritten: Int64 read fBytesWritten write fBytesWritten; property ConfirmErase: Boolean read GetConfirmErase write fConfirmErase; property DiskNr: Integer read fDiskNr write fDiskNr; property Exists: Boolean read GetExists; property FileName: String read fFileName write SetFileName; property File_Size: Int64 read fFile_Size write fFile_Size; property Handle: Integer read fHandle write SetHandle; property info: Cardinal read fInfo write fInfo; property IsMultiPart: Boolean read fIsMultiPart write fIsMultiPart; property IsOpen: Boolean read fIsOpen; property IsTemp: Boolean read fIsTemp write fIsTemp; property KeepFreeOnAllDisks: Cardinal read GetKeepFreeOnAllDisks write SetKeepFreeOnAllDisks; property KeepFreeOnDisk1: Cardinal read GetKeepFreeOnDisk1 write SetKeepFreeOnDisk1; property LastWritten: Cardinal read GetLastWritten; property MaxVolumeSize: Int64 read GetMaxVolumeSize write SetMaxVolumeSize; property MinFreeVolumeSize: Cardinal read GetMinFreeVolumeSize write SetMinFreeVolumeSize; property NewDisk: Boolean Read FNewDisk Write FNewDisk; property Numbering: TZipNumberScheme Read FNumbering Write FNumbering; property Position: Int64 read GetPosition write SetPosition; property RealFileName: String read fRealFileName; property RealFileSize: Int64 read fRealFileSize write fRealFileSize; property ReqFileName: String Read FReqFileName Write FReqFileName; property ShowProgress : TZipShowProgress read fShowProgress write fShowProgress; property Sig: TZipFileSigs read fSig write fSig; property SpanOptions: TZMSpanOpts read GetSpanOptions write SetSpanOptions; // if non-zero set fileDate property StampDate: Cardinal read fStampDate write fStampDate; property TotalDisks: Integer read fTotalDisks write fTotalDisks; property WorkDrive: TZMWorkDrive read fWorkDrive write SetWorkDrive; property Worker: TZMCore read fWorker write fWorker; end; const // zfi_None: Cardinal = 0; // zfi_Open: Cardinal = 1; // zfi_Create: Cardinal = 2; zfi_Dirty: Cardinal = 4; zfi_MakeMask: Cardinal = $07; zfi_Error: Cardinal = 8; // zfi_NotFound: cardinal = $10; // named file not found // zfi_NoLast: cardinal = $20; // last file not found zfi_Loading: cardinal = $40; zfi_Cancelled: cardinal = $80; // loading was cancelled // zfi_FileMask: cardinal = $F0; function FileTimeToLocalDOSTime(const ft: TFileTime): Cardinal; implementation uses Forms, Controls, Dialogs, ZMMsgStr19, ZMCtx19, ZMCompat19, ZMDlg19, ZMStructs19, ZMUtils19, ZMMsg19, ZMXcpt19; {$I '.\ZipVers19.inc'} {$IFDEF VER180} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} const MAX_PARTS = 999; MaxDiskBufferSize = (4 * 1024 * 1024); // floppies only const SZipSet = 'ZipSet_'; SPKBACK = 'PKBACK#'; (* ? FormatFloppy *) function FormatFloppy(WND: HWND; const Drive: String): Integer; const SHFMT_ID_DEFAULT = $FFFF; { options } SHFMT_OPT_FULL = $0001; // SHFMT_OPT_SYSONLY = $0002; { return values } // SHFMT_ERROR = $FFFFFFFF; // -1 Error on last format, drive may be formatable // SHFMT_CANCEL = $FFFFFFFE; // -2 last format cancelled // SHFMT_NOFORMAT = $FFFFFFFD; // -3 drive is not formatable type TSHFormatDrive = function(WND: HWND; Drive, fmtID, Options: DWORD): DWORD; stdcall; var SHFormatDrive: TSHFormatDrive; var drv: Integer; hLib: THandle; OldErrMode: Integer; begin Result := -3; // error if not((Length(Drive) > 1) and (Drive[2] = ':') and CharInSet (Drive[1], ['A' .. 'Z', 'a' .. 'z'])) then exit; if GetDriveType(PChar(Drive)) <> DRIVE_REMOVABLE then exit; drv := Ord(Upcase(Drive[1])) - Ord('A'); OldErrMode := SetErrorMode(SEM_FAILCRITICALERRORS or SEM_NOGPFAULTERRORBOX); hLib := LoadLibrary('Shell32'); if hLib <> 0 then begin @SHFormatDrive := GetProcAddress(hLib, 'SHFormatDrive'); if @SHFormatDrive <> nil then try Result := SHFormatDrive(WND, drv, SHFMT_ID_DEFAULT, SHFMT_OPT_FULL); finally FreeLibrary(hLib); end; SetErrorMode(OldErrMode); end; end; function FileTimeToLocalDOSTime(const ft: TFileTime): Cardinal; var lf: TFileTime; wd: Word; wt: Word; begin Result := 0; if FileTimeToLocalFileTime(ft, lf) and FileTimeToDosDateTime(lf, wd, wt) then Result := (wd shl 16) or wt; end; { TZMWorkFile } constructor TZMWorkFile.Create(wrkr: TZMCore); begin inherited Create; fWorker := wrkr; fBoss := wrkr; end; procedure TZMWorkFile.AfterConstruction; begin inherited; fDiskBuffer := nil; fBufferPosition := -1; fInfo := 0; fHandle := -1; fIsMultiPart := false; fBytesWritten := 0; fBytesRead := 0; fOpenMode := 0; fNumbering := znsNone; fWorkDrive := TZMWorkDrive.Create; ClearFileInformation; end; function TZMWorkFile.AskAnotherDisk(const DiskFile: String): Integer; var MsgQ: String; tmpStatusDisk: TZMStatusDiskEvent; begin MsgQ := Boss.ZipLoadStr(DS_AnotherDisk); FZipDiskStatus := FZipDiskStatus + [zdsSameFileName]; tmpStatusDisk := worker.Master.OnStatusDisk; if Assigned(tmpStatusDisk) and not(zaaYesOvrwrt in Worker.AnswerAll) then begin FZipDiskAction := zdaOk; // The default action tmpStatusDisk(Boss.Master, 0, DiskFile, FZipDiskStatus, FZipDiskAction); case FZipDiskAction of zdaCancel: Result := idCancel; zdaReject: Result := idNo; zdaErase: Result := idOk; zdaYesToAll: begin Result := idOk; // Worker.AnswerAll := Worker.AnswerAll + [zaaYesOvrwrt]; end; zdaOk: Result := idOk; else Result := idOk; end; end else Result := Boss.ZipMessageDlgEx(Boss.ZipLoadStr(FM_Confirm), MsgQ, zmtWarning + DHC_SpanOvr, [mbOk, mbCancel]); end; function TZMWorkFile.AskOverwriteSegment(const DiskFile: String; DiskSeq: Integer): Integer; var MsgQ: String; tmpStatusDisk: TZMStatusDiskEvent; begin // Do we want to overwrite an existing file? if FileExists(DiskFile) then if (File_Age(DiskFile) = StampDate) and (Pred(DiskSeq) < DiskNr) then begin MsgQ := Boss.ZipFmtLoadStr(DS_AskPrevFile, [DiskSeq]); FZipDiskStatus := FZipDiskStatus + [zdsPreviousDisk]; end else begin MsgQ := Boss.ZipFmtLoadStr(DS_AskDeleteFile, [DiskFile]); FZipDiskStatus := FZipDiskStatus + [zdsSameFileName]; end else if not WorkDrive.DriveIsFixed then if (WorkDrive.VolumeSize <> WorkDrive.VolumeSpace) then FZipDiskStatus := FZipDiskStatus + [zdsHasFiles] // But not the same name else FZipDiskStatus := FZipDiskStatus + [zdsEmpty]; tmpStatusDisk := worker.Master.OnStatusDisk; if Assigned(tmpStatusDisk) and not(zaaYesOvrwrt in Worker.AnswerAll) then begin FZipDiskAction := zdaOk; // The default action tmpStatusDisk(Boss.Master, DiskSeq, DiskFile, FZipDiskStatus, FZipDiskAction); case FZipDiskAction of zdaCancel: Result := idCancel; zdaReject: Result := idNo; zdaErase: Result := idOk; zdaYesToAll: begin Result := idOk; Worker.AnswerAll := Worker.AnswerAll + [zaaYesOvrwrt]; end; zdaOk: Result := idOk; else Result := idOk; end; end else if ((FZipDiskStatus * [zdsPreviousDisk, zdsSameFileName]) <> []) and not ((zaaYesOvrwrt in Worker.AnswerAll) or Worker.Unattended) then begin Result := Boss.ZipMessageDlgEx(Boss.ZipLoadStr(FM_Confirm), MsgQ, zmtWarning + DHC_SpanOvr, [mbYes, mbNo, mbCancel, mbYesToAll]); if Result = mrYesToAll then begin Worker.AnswerAll := Worker.AnswerAll + [zaaYesOvrwrt]; Result := idOk; end; end else Result := idOk; end; // Src should not be open but not enforced procedure TZMWorkFile.AssignFrom(Src: TZMWorkFile); begin if (Src <> Self) and (Src <> nil) then begin fDiskBuffer := nil; fBufferPosition := -1; Move(Src.fSavedFileInfo, fSavedFileInfo, SizeOf(fSavedFileInfo)); fAllowedSize := Src.fAllowedSize; fBytesRead := Src.fBytesRead; fBytesWritten := Src.fBytesWritten; fDiskNr := Src.fDiskNr; fFile_Size := Src.fFile_Size; fFileName := Src.fFileName; fHandle := -1; // don't acquire handle fInfo := Src.fInfo; // fIsMultiDisk := Src.fIsMultiDisk; fIsOpen := False; fIsTemp := Src.fIsTemp; fLastWrite := Src.fLastWrite; fNumbering := Src.fNumbering; fOpenMode := Src.fOpenMode; fRealFileName := Src.fRealFileName; fReqFileName := Src.FReqFileName; fShowProgress := Src.fShowProgress; fSig := Src.fSig; fStampDate := Src.fStampDate; fTotalDisks := Src.fTotalDisks; fWorkDrive.AssignFrom(Src.WorkDrive); FZipDiskAction := Src.FZipDiskAction; FZipDiskStatus := Src.FZipDiskStatus; end; end; procedure TZMWorkFile.BeforeDestruction; begin File_Close; if IsTemp and FileExists(fRealFileName) then begin if Boss.Verbosity >= zvTrace then Diag('Trace: Deleting ' + fRealFileName); SysUtils.DeleteFile(fFileName); end; FreeAndNil(fWorkDrive); fDiskBuffer := nil; // ++ discard contents WBuf := nil; inherited; end; // uses 'real' number function TZMWorkFile.ChangeNumberedName(const FName: String; NewNbr: Cardinal; Remove: boolean): string; var ext: string; StripLen: Integer; begin if DiskNr > 999 then raise EZipMaster.CreateResDisp(DS_TooManyParts, True); ext := ExtractFileExt(FName); StripLen := 0; if Remove then StripLen := 3; Result := Copy(FName, 1, Length(FName) - Length(ext) - StripLen) + Copy(IntToStr(1000 + NewNbr), 2, 3) + ext; end; procedure TZMWorkFile.CheckForDisk(writing, UnformOk: Boolean); var OnGetNextDisktmp: TZMGetNextDiskEvent; AbortAction: Boolean; MsgFlag: Integer; MsgStr: String; Res: Integer; SizeOfDisk: Int64; totDisks: Integer; begin if TotalDisks <> 1 then // check IsMultiPart := True; if WorkDrive.DriveIsFixed then begin // If it is a fixed disk we don't want a new one. NewDisk := false; Boss.CheckCancel; exit; end; Boss.KeepAlive; // just ProcessMessages // First check if we want a new one or if there is a disk (still) present. while (NewDisk or (not WorkDrive.HasMedia(UnformOk))) do begin if Boss.Unattended then raise EZipMaster.CreateResDisp(DS_NoUnattSpan, True); MsgFlag := zmtWarning + DHC_SpanNxtW; // or error? if DiskNr < 0 then // want last disk begin MsgStr := Boss.ZipLoadStr(DS_InsertDisk); MsgFlag := zmtError + DHC_SpanNxtR; end else if writing then begin // This is an estimate, we can't know if every future disk has the same space available and // if there is no disk present we can't determine the size unless it's set by MaxVolumeSize. SizeOfDisk := WorkDrive.VolumeSize - KeepFreeOnAllDisks; if (MaxVolumeSize <> 0) and (MaxVolumeSize < WorkDrive.VolumeSize) then SizeOfDisk := MaxVolumeSize; TotalDisks := DiskNr + 1; if TotalDisks > MAX_PARTS then raise EZipMaster.CreateResDisp(DS_TooManyParts, True); if SizeOfDisk > 0 then begin totDisks := Trunc((File_Size + 4 + KeepFreeOnDisk1) / SizeOfDisk); if TotalDisks < totDisks then TotalDisks := totDisks; MsgStr := Boss.ZipFmtLoadStr (DS_InsertVolume, [DiskNr + 1, TotalDisks]); end else MsgStr := Boss.ZipFmtLoadStr(DS_InsertAVolume, [DiskNr + 1]); end else begin // reading - want specific disk if TotalDisks = 0 then MsgStr := Boss.ZipFmtLoadStr(DS_InsertAVolume, [DiskNr + 1]) else MsgStr := Boss.ZipFmtLoadStr(DS_InsertVolume, [DiskNr + 1, TotalDisks]); end; MsgStr := MsgStr + Boss.ZipFmtLoadStr(DS_InDrive, [WorkDrive.DriveStr]); OnGetNextDisktmp := Worker.Master.OnGetNextDisk; if Assigned(OnGetNextDisktmp) then begin AbortAction := false; OnGetNextDisktmp(Boss.Master, DiskNr + 1, TotalDisks, Copy (WorkDrive.DriveStr, 1, 1), AbortAction); if AbortAction then Res := idAbort else Res := idOk; end else Res := Boss.ZipMessageDlgEx('', MsgStr, MsgFlag, mbOkCancel); // Check if user pressed Cancel or memory is running out. if Res = 0 then raise EZipMaster.CreateResDisp(DS_NoMem, True); if Res <> idOk then begin Boss.Cancel := GE_Abort; info := info or zfi_Cancelled; raise EZipMaster.CreateResDisp(DS_Canceled, false); end; NewDisk := false; Boss.KeepAlive; end; end; function TZMWorkFile.CheckRead(var Buffer; Len: Integer): Boolean; begin if Len < 0 then Len := -Len; Result := Read(Buffer, Len) = Len; end; procedure TZMWorkFile.CheckRead(var Buffer; Len, ErrId: Integer); begin if Len < 0 then Len := -Len; if not CheckRead(Buffer, Len) then begin if ErrId = 0 then ErrId := DS_ReadError; raise EZipMaster.CreateResDisp(ErrId, True); end; end; function TZMWorkFile.CheckReads(var Buffer; const Lens: array of Integer) : Boolean; var c: Integer; i: Integer; begin c := 0; for i := Low(Lens) to High(Lens) do c := c + Lens[i]; Result := Reads(Buffer, Lens) = c; end; procedure TZMWorkFile.CheckReads(var Buffer; const Lens: array of Integer; ErrId: Integer); begin if not CheckReads(Buffer, Lens) then begin if ErrId = 0 then ErrId := DS_ReadError; raise EZipMaster.CreateResDisp(ErrId, True); end; end; function TZMWorkFile.CheckSeek(offset: Int64; from, ErrId: Integer): Int64; begin Result := Seek(offset, from); if Result < 0 then begin if ErrId = 0 then raise EZipMaster.CreateResDisp(DS_SeekError, True); if ErrId = -1 then ErrId := DS_FailedSeek; raise EZipMaster.CreateResDisp(ErrId, True); end; end; function TZMWorkFile.CheckWrite(const Buffer; Len: Integer): Boolean; begin if Len < 0 then Len := -Len; Result := Write(Buffer, Len) = Len; end; procedure TZMWorkFile.CheckWrite(const Buffer; Len, ErrId: Integer); begin if not CheckWrite(Buffer, Len) then begin if ErrId = 0 then ErrId := DS_WriteError; raise EZipMaster.CreateResDisp(ErrId, True); end; end; function TZMWorkFile.CheckWrites(const Buffer; const Lens: array of Integer) : Boolean; var c: Integer; i: Integer; begin c := 0; for i := Low(Lens) to High(Lens) do c := c + Lens[i]; Result := Writes(Buffer, Lens) = c; end; // must read from current part procedure TZMWorkFile.CheckWrites(const Buffer; const Lens: array of Integer; ErrId: Integer); begin if not CheckWrites(Buffer, Lens) then begin if ErrId = 0 then ErrId := DS_WriteError; raise EZipMaster.CreateResDisp(ErrId, True); end; end; procedure TZMWorkFile.ClearFileInformation; begin ZeroMemory(@fSavedFileInfo, sizeof(_BY_HANDLE_FILE_INFORMATION)); end; procedure TZMWorkFile.ClearFloppy(const dir: String); var Fname: String; SRec: TSearchRec; begin if FindFirst(dir + WILD_ALL, faAnyFile, SRec) = 0 then repeat Fname := dir + SRec.Name; if ((SRec.Attr and faDirectory) <> 0) and (SRec.Name <> DIR_THIS) and (SRec.Name <> DIR_PARENT) then begin Fname := Fname + PathDelim; ClearFloppy(Fname); if Boss.Verbosity >= zvTrace then Boss.ReportMsg(TM_Erasing, [Fname]) else Boss.KeepAlive; // allow time for OS to delete last file RemoveDir(Fname); end else begin if Boss.Verbosity >= zvTrace then Boss.ReportMsg(TM_Deleting, [Fname]) else Boss.KeepAlive; SysUtils.DeleteFile(Fname); end; until FindNext(SRec) <> 0; SysUtils.FindClose(SRec); end; function TZMWorkFile.CopyFrom(Source: TZMWorkFile; Len: Int64): Int64; var BufSize: Cardinal; SizeR: Integer; ToRead: Integer; wb: pByte; begin BufSize := 10 * 1024; // constant is somewhere wb := WBuffer(BufSize); Result := 0; while Len > 0 do begin ToRead := BufSize; if Len < BufSize then ToRead := Len; SizeR := Source.Read(wb^, ToRead); if SizeR <> ToRead then begin if SizeR < 0 then Result := SizeR else Result := -DS_ReadError; exit; end; if SizeR > 0 then begin ToRead := Write(wb^, SizeR); if SizeR <> ToRead then begin if ToRead < 0 then Result := ToRead else Result := -DS_WriteError; exit; end; Len := Len - SizeR; Result := Result + SizeR; ProgReport(zacProgress, PR_Copying, Source.FileName, SizeR); end; end; end; function TZMWorkFile.Copy_File(Source: TZMWorkFile): Integer; var fsize: Int64; r: Int64; begin try if not Source.IsOpen then Source.File_Open(fmOpenRead); Result := 0; fsize := Source.Seek(0, 2); Source.Seek(0, 0); ProgReport(zacXItem, PR_Copying, Source.FileName, fsize); r := self.CopyFrom(Source, fsize); if r < 0 then Result := Integer(r); except Result := -9; // general error end; end; function TZMWorkFile.CreateMVFileNameEx(const FileName: String; StripPartNbr, Compat: Boolean): String; var ext: String; begin // changes FileName into multi volume FileName if Compat then begin if DiskNr <> (TotalDisks - 1) then begin if DiskNr < 9 then ext := '.z0' else ext := '.z'; ext := ext + IntToStr(succ(DiskNr)); end else ext := EXT_ZIP; Result := ChangeFileExt(FileName, ext); end else Result := ChangeNumberedName(FileName, DiskNr + 1, StripPartNbr); end; procedure TZMWorkFile.Diag(const msg: String); begin if Boss.Verbosity >= zvTrace then Boss.ReportMessage(0, msg); end; function TZMWorkFile.DoFileWrite(const Buffer; Len: Integer): Integer; begin Result := FileWrite(fHandle, Buffer, Len); end; // return true if end of segment // WARNING - repositions to end of segment function TZMWorkFile.EOS: Boolean; begin Result := FileSeek64(Handle, 0, soFromCurrent) = FileSeek64 (Handle, 0, soFromEnd); end; function TZMWorkFile.FileDate: Cardinal; begin Result := FileGetDate(fHandle); end; procedure TZMWorkFile.File_Close; begin if fDiskBuffer <> nil then FlushDiskBuffer; File_Close_F; // inherited; end; procedure TZMWorkFile.File_Close_F; var th: Integer; begin if fHandle <> -1 then begin th := fHandle; fHandle := -1; // if open for writing set date if (StampDate <> 0) and ((OpenMode and (SysUtils.fmOpenReadWrite or SysUtils.fmOpenWrite)) <> 0) then begin FileSetDate(th, StampDate); if Boss.Verbosity >= zvTrace then Diag('Trace: Set file Date ' + fRealFileName + ' to ' + DateTimeToStr (FileDateToLocalDateTime(StampDate))); end; FileClose(th); if Boss.Verbosity >= zvTrace then Diag('Trace: Closed ' + fRealFileName); end; fIsOpen := false; end; function TZMWorkFile.File_Create(const theName: String): Boolean; var n: String; begin File_Close; Result := false; if theName <> '' then begin if FileName = '' then FileName := theName; n := theName; end else n := FileName; if n = '' then exit; if Boss.Verbosity >= zvTrace then Diag('Trace: Creating ' + n); fRealFileName := n; fHandle := FileCreate(n); if fHandle <> -1 then TZMCore(Worker).AddCleanupFile(n); fBytesWritten := 0; fBytesRead := 0; Result := fHandle <> -1; fIsOpen := Result; fOpenMode := SysUtils.fmOpenWrite; end; function TZMWorkFile.File_CreateTemp(const Prefix, Where: String): Boolean; var Buf: String; Len: DWORD; tmpDir: String; begin Result := false; if Length(Boss.TempDir) = 0 then begin if Length(Where) <> 0 then begin tmpDir := ExtractFilePath(Where); tmpDir := ExpandFileName(tmpDir); end; // if Length(Worker.TempDir) = 0 then // Get the system temp dir if Length(tmpDir) = 0 then // Get the system temp dir begin // 1. The path specified by the TMP environment variable. // 2. The path specified by the TEMP environment variable, if TMP is not defined. // 3. The current directory, if both TMP and TEMP are not defined. Len := GetTempPath(0, PChar(tmpDir)); SetLength(tmpDir, Len); GetTempPath(Len, PChar(tmpDir)); end; end else // Use Temp dir provided by ZipMaster begin tmpDir := Boss.TempDir; end; tmpDir := DelimitPath(tmpDir, True); SetLength(Buf, MAX_PATH + 12); if GetTempFileName(PChar(tmpDir), PChar(Prefix), 0, PChar(Buf)) <> 0 then begin FileName := PChar(Buf); IsTemp := True; // delete when finished if Boss.Verbosity >= zvTrace then Diag('Trace: Created temporary ' + FileName); fRealFileName := FileName; fBytesWritten := 0; fBytesRead := 0; fOpenMode := SysUtils.fmOpenWrite; Result := File_Open(fmOpenWrite); end; end; function TZMWorkFile.File_Open(Mode: Cardinal): Boolean; begin File_Close; if Boss.Verbosity >= zvTrace then Diag('Trace: Opening ' + fFileName); fRealFileName := fFileName; fHandle := FileOpen(fFileName, Mode); Result := fHandle <> -1; fIsOpen := Result; fOpenMode := Mode; end; function TZMWorkFile.File_Rename(const NewName: string; const Safe: Boolean = false): Boolean; begin if Boss.Verbosity >= zvTrace then Diag('Trace: Rename ' + RealFileName + ' to ' + NewName); IsTemp := false; if IsOpen then File_Close; if FileExists(FileName) then begin if FileExists(NewName) then begin if Boss.Verbosity >= zvTrace then Diag('Trace: Erasing ' + NewName); if (EraseFile(NewName, not Safe) <> 0) and (Boss.Verbosity >= zvTrace) then Diag('Trace: Erase failed ' + NewName); end; end; Result := RenameFile(FileName, NewName); if Result then begin fFileName := NewName; // success fRealFileName := NewName; end; end; // rename last part after Write function TZMWorkFile.FinishWrite: Integer; var fn: String; LastName: String; MsgStr: String; Res: Integer; OnStatusDisk: TZMStatusDiskEvent; begin // change extn of last file LastName := RealFileName; File_Close; Result := 0; if IsMultiPart then begin if ((Numbering = znsExt) and not AnsiSameText(ExtractFileExt(LastName), EXT_ZIP)) or ((Numbering = znsName) and (DiskNr = 0)) then begin Result := -1; fn := FileName; if (FileExists(fn)) then begin MsgStr := Boss.ZipFmtLoadStr(DS_AskDeleteFile, [fn]); FZipDiskStatus := FZipDiskStatus + [zdsSameFileName]; Res := idYes; if not(zaaYesOvrwrt in Worker.AnswerAll) then begin OnStatusDisk := Worker.Master.OnStatusDisk; if Assigned(OnStatusDisk) then // 1.77 begin FZipDiskAction := zdaOk; // The default action OnStatusDisk(Boss.Master, DiskNr, fn, FZipDiskStatus, FZipDiskAction); if FZipDiskAction = zdaYesToAll then begin Worker.AnswerAll := Worker.AnswerAll + [zaaYesOvrwrt]; FZipDiskAction := zdaOk; end; if FZipDiskAction = zdaOk then Res := idYes else Res := idNo; end else Res := Boss.ZipMessageDlgEx(MsgStr, Boss.ZipLoadStr(FM_Confirm) , zmtWarning + DHC_WrtSpnDel, [mbYes, mbNo]); end; if (Res = 0) then Boss.ShowZipMessage(DS_NoMem, ''); if (Res = idNo) then Boss.ReportMsg(DS_NoRenamePart, [LastName]); if (Res = idYes) then SysUtils.DeleteFile(fn); // if it exists delete old one end; if FileExists(LastName) then // should be there but ... begin RenameFile(LastName, fn); Result := 0; if Boss.Verbosity >= zvVerbose then Boss.Diag(Format('renamed %s to %s', [LastName, fn])); end; end; end; end; procedure TZMWorkFile.FlushDiskBuffer; var did: Integer; Len: Integer; begin Len := fBufferPosition; fBufferPosition := -1; // stop retrying on error if fDiskBuffer <> nil then begin Boss.KeepAlive; Boss.CheckCancel; if Len > 0 then begin repeat did := DoFileWrite(fDiskBuffer[0], Len); if did <> Len then begin NewFlushDisk; // abort or try again on new disk end; until (did = Len); end; fDiskBuffer := nil; end; end; function TZMWorkFile.GetConfirmErase: Boolean; begin Result := Worker.ConfirmErase; end; function TZMWorkFile.GetExists: Boolean; begin Result := false; if FileExists(FileName) then Result := True; end; function TZMWorkFile.GetFileInformation(var FileInfo: _BY_HANDLE_FILE_INFORMATION): Boolean; begin Result := IsOpen; if Result then Result := GetFileInformationByHandle(Handle, FileInfo); if not Result then ZeroMemory(@FileInfo, sizeof(_BY_HANDLE_FILE_INFORMATION)); end; function TZMWorkFile.GetKeepFreeOnAllDisks: Cardinal; begin Result := Worker.KeepFreeOnAllDisks; end; function TZMWorkFile.GetKeepFreeOnDisk1: Cardinal; begin Result := Worker.KeepFreeOnDisk1; end; function TZMWorkFile.GetLastWritten: Cardinal; var ft: TFileTime; begin Result := 0; if IsOpen and LastWriteTime(ft) then Result := FileTimeToLocalDOSTime(ft); end; function TZMWorkFile.GetMaxVolumeSize: Int64; begin Result := Worker.MaxVolumeSize; end; function TZMWorkFile.GetMinFreeVolumeSize: Cardinal; begin Result := Worker.MinFreeVolumeSize; end; procedure TZMWorkFile.GetNewDisk(DiskSeq: Integer; AllowEmpty: Boolean); begin File_Close; // Close the file on the old disk first. if (TotalDisks <> 1) or (DiskSeq <> 0) then IsMultiPart := True; DiskNr := DiskSeq; while True do begin repeat NewDisk := True; File_Close; CheckForDisk(false, spTryFormat in SpanOptions); if AllowEmpty and WorkDrive.HasMedia(spTryFormat in SpanOptions) then begin if WorkDrive.VolumeSpace = -1 then exit; // unformatted if WorkDrive.VolumeSpace = WorkDrive.VolumeSize then exit; // empty end; until IsRightDisk; if Boss.Verbosity >= zvVerbose then Boss.Diag(Boss.ZipFmtLoadStr(TM_GetNewDisk, [FileName])); if File_Open(fmShareDenyWrite or fmOpenRead) then break; // found if WorkDrive.DriveIsFixed then raise EZipMaster.CreateResDisp(DS_NoInFile, True) else Boss.ShowZipMessage(DS_NoInFile, ''); end; end; function TZMWorkFile.GetPosition: Int64; begin if fDiskBuffer <> nil then Result := fBufferPosition else Result := GetPosition_F; end; function TZMWorkFile.GetPosition_F: Int64; begin Result := FileSeek64(fHandle, 0, soFromCurrent); // from current end; function TZMWorkFile.GetSpanOptions: TZMSpanOpts; begin Result := Worker.SpanOptions; end; function TZMWorkFile.HasSpanSig(const FName: String): boolean; var fs: TFileStream; Sg: Cardinal; begin Result := False; if FileExists(FName) then begin fs := TFileStream.Create(FName, fmOpenRead); try if (fs.Size > (sizeof(TZipLocalHeader) + sizeof(Sg))) and (fs.Read(Sg, sizeof(Sg)) = sizeof(Sg)) then Result := (Sg = ExtLocalSig) and (fs.Read(Sg, sizeof(Sg)) = sizeof(Sg)) and (Sg = LocalFileHeaderSig); finally fs.Free; end; end; end; function TZMWorkFile.IsRightDisk: Boolean; var fn: String; VName: string; begin Result := True; if (Numbering < znsName) and (not WorkDrive.DriveIsFixed) then begin VName := WorkDrive.DiskName; Boss.Diag('Checking disk ' + VName + ' need ' + VolName(DiskNr)); if (AnsiSameText(VName, VolName(DiskNr)) or AnsiSameText(VName, OldVolName(DiskNr))) and FileExists(FileName) then begin Numbering := znsVolume; Boss.Diag('found volume ' + VName); exit; end; end; fn := FileName; if Numbering = znsNone then // not known yet begin FileName := CreateMVFileNameEx(FileName, True, True); // make compat name if FileExists(FileName) then begin Numbering := znsExt; exit; end; FileName := fn; FileName := CreateMVFileNameEx(FileName, True, false); // make numbered name if FileExists(FileName) then begin Numbering := znsName; exit; end; if WorkDrive.DriveIsFixed then exit; // always true - only needed name FileName := fn; // restore Result := false; exit; end; // numbering scheme already known if Numbering = znsVolume then begin Result := false; exit; end; FileName := CreateMVFileNameEx(FileName, True, Numbering = znsExt); // fixed drive always true only needed new filename if (not WorkDrive.DriveIsFixed) and (not FileExists(FileName)) then begin FileName := fn; // restore Result := false; end; end; function TZMWorkFile.LastWriteTime(var last_write: TFileTime): Boolean; var BHFInfo: TByHandleFileInformation; begin Result := false; last_write.dwLowDateTime := 0; last_write.dwHighDateTime := 0; if IsOpen then begin Result := GetFileInformationByHandle(fHandle, BHFInfo); if Result then last_write := BHFInfo.ftLastWriteTime; end; end; function TZMWorkFile.MapNumbering(Opts: TZMSpanOpts): TZMSpanOpts; var spans: TZMSpanOpts; begin Result := Opts; if Numbering <> znsNone then begin // map numbering type only if known spans := Opts - [spCompatName] + [spNoVolumeName]; case Numbering of znsVolume: spans := spans - [spNoVolumeName]; znsExt: spans := spans + [spCompatName]; end; Result := spans; end; end; procedure TZMWorkFile.NewFlushDisk; begin // need to allow another disk, check size, open file, name disk etc raise EZipMaster.CreateResDisp(DS_WriteError, True); end; function TZMWorkFile.NewSegment: Boolean; // true to 'continue' var DiskFile: String; DiskSeq: Integer; MsgQ: String; Res: Integer; SegName: String; OnGetNextDisk: TZMGetNextDiskEvent; OnStatusDisk: TZMStatusDiskEvent; begin Result := false; // If we write on a fixed disk the filename must change. // We will get something like: FileNamexxx.zip where xxx is 001,002 etc. // if CompatNames are used we get FileName.zxx where xx is 01, 02 etc.. last .zip if Numbering = znsNone then begin if spCompatName in SpanOptions then Numbering := znsExt else if WorkDrive.DriveIsFixed or (spNoVolumeName in SpanOptions) then Numbering := znsName else Numbering := znsVolume; end; DiskFile := FileName; if Numbering <> znsVolume then DiskFile := CreateMVFileNameEx(DiskFile, false, Numbering = znsExt); CheckForDisk(True, spWipeFiles in SpanOptions); OnGetNextDisk := Worker.Master.OnGetNextDisk; // Allow clearing of removeable media even if no volume names if (not WorkDrive.DriveIsFixed) and (spWipeFiles in SpanOptions) and ((FZipDiskAction = zdaErase) or not Assigned(OnGetNextDisk)) then begin // Do we want a format first? if Numbering = znsVolume then SegName := VolName(DiskNr) // default name else SegName := SZipSet + IntToStr(succ(DiskNr)); // Ok=6 NoFormat=-3, Cancel=-2, Error=-1 case ZipFormat(SegName) of // Start formating and wait until BeforeClose... - 1: raise EZipMaster.CreateResDisp(DS_Canceled, True); -2: raise EZipMaster.CreateResDisp(DS_Canceled, false); end; end; if WorkDrive.DriveIsFixed or (Numbering <> znsVolume) then DiskSeq := DiskNr + 1 else begin DiskSeq := StrToIntDef(Copy(WorkDrive.DiskName, 9, 3), 1); if DiskSeq < 0 then DiskSeq := 1; end; FZipDiskStatus := []; Res := AskOverwriteSegment(DiskFile, DiskSeq); if (Res = idYes) and (WorkDrive.DriveIsFixed) and (spCompatName in SpanOptions) and FileExists(ReqFileName) then begin Res := AskOverwriteSegment(ReqFileName, DiskSeq); if (Res = idYes) then EraseFile(ReqFileName, Worker.HowToDelete = htdFinal); end; if (Res = 0) or (Res = idCancel) or ((Res = idNo) and WorkDrive.DriveIsFixed) then raise EZipMaster.CreateResDisp(DS_Canceled, false); if Res = idNo then begin // we will try again... FDiskWritten := 0; NewDisk := True; Result := True; exit; end; // Create the output file. if not File_Create(DiskFile) then begin // change proposed by Pedro Araujo MsgQ := Boss.ZipLoadStr(DS_NoOutFile); Res := Boss.ZipMessageDlgEx('', MsgQ, zmtError + DHC_SpanNoOut, [mbRetry, mbCancel]); if Res = 0 then raise EZipMaster.CreateResDisp(DS_NoMem, True); if Res <> idRetry then raise EZipMaster.CreateResDisp(DS_Canceled, false); FDiskWritten := 0; NewDisk := True; Result := True; exit; end; // Get the free space on this disk, correct later if neccessary. WorkDrive.VolumeRefresh; // Set the maximum number of bytes that can be written to this disk(file). // Reserve space on/in all the disk/file. if (DiskNr = 0) and (KeepFreeOnDisk1 > 0) or (KeepFreeOnAllDisks > 0) then begin if (KeepFreeOnDisk1 mod WorkDrive.VolumeSecSize) <> 0 then KeepFreeOnDisk1 := succ(KeepFreeOnDisk1 div WorkDrive.VolumeSecSize) * WorkDrive.VolumeSecSize; if (KeepFreeOnAllDisks mod WorkDrive.VolumeSecSize) <> 0 then KeepFreeOnAllDisks := succ (KeepFreeOnAllDisks div WorkDrive.VolumeSecSize) * WorkDrive.VolumeSecSize; end; AllowedSize := WorkDrive.VolumeSize - KeepFreeOnAllDisks; if (MaxVolumeSize > 0) and (MaxVolumeSize < AllowedSize) then AllowedSize := MaxVolumeSize; // Reserve space on/in the first disk(file). if DiskNr = 0 then AllowedSize := AllowedSize - KeepFreeOnDisk1; // Do we still have enough free space on this disk. if AllowedSize < MinFreeVolumeSize then // No, too bad... begin OnStatusDisk := Worker.Master.OnStatusDisk; File_Close; SysUtils.DeleteFile(DiskFile); if Assigned(OnStatusDisk) then // v1.60L begin if Numbering <> znsVolume then DiskSeq := DiskNr + 1 else begin DiskSeq := StrToIntDef(Copy(WorkDrive.DiskName, 9, 3), 1); if DiskSeq < 0 then DiskSeq := 1; end; FZipDiskAction := zdaOk; // The default action FZipDiskStatus := [zdsNotEnoughSpace]; OnStatusDisk(Boss.Master, DiskSeq, DiskFile, FZipDiskStatus, FZipDiskAction); if FZipDiskAction = zdaCancel then Res := idCancel else Res := idRetry; end else begin MsgQ := Boss.ZipLoadStr(DS_NoDiskSpace); Res := Boss.ZipMessageDlgEx('', MsgQ, zmtError + DHC_SpanSpace, [mbRetry, mbCancel]); end; if Res = 0 then raise EZipMaster.CreateResDisp(DS_NoMem, True); if Res <> idRetry then raise EZipMaster.CreateResDisp(DS_Canceled, false); FDiskWritten := 0; NewDisk := True; // If all this was on a HD then this wouldn't be useful but... Result := True; end else begin // ok. it fits and the file is open // Set the volume label of this disk if it is not a fixed one. if not(WorkDrive.DriveIsFixed or (Numbering <> znsVolume)) then begin if not WorkDrive.RenameDisk(VolName(DiskNr)) then raise EZipMaster.CreateResDisp(DS_NoVolume, True); end; // if it is a floppy buffer it if (not WorkDrive.DriveIsFixed) and (AllowedSize <= MaxDiskBufferSize) then begin SetLength(fDiskBuffer, AllowedSize); fBufferPosition := 0; end; end; end; function TZMWorkFile.OldVolName(Part: Integer): String; begin Result := SPKBACK + ' ' + Copy(IntToStr(1001 + Part), 2, 3); end; procedure TZMWorkFile.ProgReport(prog: TActionCodes; xprog: Integer; const Name: String; size: Int64); var actn: TActionCodes; msg: String; begin actn := prog; if (Name = '') and (xprog > PR_Progress) then msg := Boss.ZipLoadStr(xprog) else msg := Name; case ShowProgress of zspNone: case prog of zacItem: actn := zacNone; zacProgress: actn := zacTick; zacEndOfBatch: actn := zacTick; zacCount: actn := zacNone; zacSize: actn := zacTick; zacXItem: actn := zacNone; zacXProgress: actn := zacTick; end; zspExtra: case prog of zacItem: actn := zacNone; // do nothing zacProgress: actn := zacXProgress; zacCount: actn := zacNone; // do nothing zacSize: actn := zacXItem; end; end; if actn <> zacNone then Boss.ReportProgress(actn, xprog, msg, size); end; function TZMWorkFile.Read(var Buffer; Len: Integer): Integer; var bp: PAnsiChar; SizeR: Integer; ToRead: Integer; begin try if IsMultiPart then begin ToRead := Len; if Len < 0 then ToRead := -Len; bp := @Buffer; Result := 0; while ToRead > 0 do begin SizeR := ReadFromFile(bp^, ToRead); if SizeR <> ToRead then begin // Check if we are at the end of a input disk. if SizeR < 0 then begin Result := SizeR; exit; end; // if error or (len <0 and read some) or (end segment) if ((Len < 0) and (SizeR <> 0)) or not EOS then begin Result := -DS_ReadError; exit; end; // It seems we are at the end, so get a next disk. GetNewDisk(DiskNr + 1, false); end; if SizeR > 0 then begin Inc(bp, SizeR); ToRead := ToRead - SizeR; Result := Result + SizeR; end; end; end else Result := Read_F(Buffer, Len); except on E: EZipMaster do Result := -E.ResId; on E: Exception do Result := -DS_ReadError; end; end; function TZMWorkFile.ReadFromFile(var Buffer; Len: Integer): Integer; begin if Len < 0 then Len := -Len; Result := FileRead(fHandle, Buffer, Len); if Result > 0 then BytesRead := BytesRead + Len else if Result < 0 then begin Result := -DS_ReadError; end; end; function TZMWorkFile.Reads(var Buffer; const Lens: array of Integer): Integer; var i: Integer; pb: PAnsiChar; r: Integer; begin Result := 0; if IsMultiPart then begin pb := @Buffer; for i := Low(Lens) to High(Lens) do begin r := Read(pb^, -Lens[i]); if r < 0 then begin Result := r; break; end; Result := Result + r; Inc(pb, r); end; end else Result := Reads_F(Buffer, Lens); end; function TZMWorkFile.Reads_F(var Buffer; const Lens: array of Integer): Integer; var c: Integer; i: Integer; begin c := 0; for i := Low(Lens) to High(Lens) do c := c + Lens[i]; Result := ReadFromFile(Buffer, c); end; function TZMWorkFile.ReadTo(strm: TStream; Count: Integer): Integer; const bsize = 20 * 1024; var done: Integer; sz: Integer; wbufr: array of Byte; begin Result := 0; SetLength(wbufr, bsize); while Count > 0 do begin sz := bsize; if sz > Count then sz := Count; done := Read(wbufr[0], sz); if done > 0 then begin if strm.write(wbufr[0], done) <> done then done := -DS_WriteError; end; if done <> sz then begin Result := -DS_FileError; if done < 0 then Result := done; break; end; Count := Count - sz; Result := Result + sz; end; end; function TZMWorkFile.Read_F(var Buffer; Len: Integer): Integer; begin Result := ReadFromFile(Buffer, Len); end; function TZMWorkFile.SaveFileInformation: Boolean; begin Result := GetFileInformation(fSavedFileInfo); end; function TZMWorkFile.Seek(offset: Int64; from: Integer): Int64; begin Result := FileSeek64(fHandle, offset, from); end; function TZMWorkFile.SeekDisk(Nr: Integer): Integer; begin if DiskNr <> Nr then GetNewDisk(Nr, false); Result := Nr; end; procedure TZMWorkFile.SetBoss(const Value: TZMCore); begin if FBoss <> Value then begin if Value = nil then FBoss := fWorker else FBoss := Value; end; end; function TZMWorkFile.SetEndOfFile: Boolean; begin if IsOpen then Result := Windows.SetEndOfFile(Handle) else Result := false; end; procedure TZMWorkFile.SetFileName(const Value: String); begin if fFileName <> Value then begin if IsOpen then File_Close; fFileName := Value; WorkDrive.DriveStr := Value; end; end; // dangerous - assumes file on same drive procedure TZMWorkFile.SetHandle(const Value: Integer); begin File_Close; fHandle := Value; fIsOpen := fHandle <> -1; end; procedure TZMWorkFile.SetKeepFreeOnAllDisks(const Value: Cardinal); begin Worker.KeepFreeOnAllDisks := Value; end; procedure TZMWorkFile.SetKeepFreeOnDisk1(const Value: Cardinal); begin Worker.KeepFreeOnDisk1 := Value; end; procedure TZMWorkFile.SetMaxVolumeSize(const Value: Int64); begin Worker.MaxVolumeSize := Value; end; procedure TZMWorkFile.SetMinFreeVolumeSize(const Value: Cardinal); begin Worker.MinFreeVolumeSize := Value; end; procedure TZMWorkFile.SetPosition(const Value: Int64); begin Seek(Value, 0); end; procedure TZMWorkFile.SetSpanOptions(const Value: TZMSpanOpts); begin Worker.SpanOptions := Value; end; procedure TZMWorkFile.SetWorkDrive(const Value: TZMWorkDrive); begin if fWorkDrive <> Value then begin fWorkDrive := Value; end; end; function TZMWorkFile.VerifyFileInformation: Boolean; var info: _BY_HANDLE_FILE_INFORMATION;//TWIN32FindData; begin GetFileInformation(info); Result := (info.ftLastWriteTime.dwLowDateTime = fSavedFileInfo.ftLastWriteTime.dwLowDateTime) and (info.ftLastWriteTime.dwHighDateTime = fSavedFileInfo.ftLastWriteTime.dwHighDateTime) and (info.ftCreationTime.dwLowDateTime = fSavedFileInfo.ftCreationTime.dwLowDateTime) and (info.ftCreationTime.dwHighDateTime = fSavedFileInfo.ftCreationTime.dwHighDateTime) and (info.nFileSizeLow = fSavedFileInfo.nFileSizeLow) and (info.nFileSizeHigh = fSavedFileInfo.nFileSizeHigh) and (info.nFileIndexLow = fSavedFileInfo.nFileIndexLow) and (info.nFileIndexHigh = fSavedFileInfo.nFileIndexHigh) and (info.dwFileAttributes = fSavedFileInfo.dwFileAttributes) and (info.dwVolumeSerialNumber = fSavedFileInfo.dwVolumeSerialNumber); end; function TZMWorkFile.VolName(Part: Integer): String; begin Result := SPKBACK + Copy(IntToStr(1001 + Part), 2, 3); end; function TZMWorkFile.WBuffer(size: Integer): pByte; begin if size < 1 then WBuf := nil else if HIGH(WBuf) < size then begin size := size or $3FF; SetLength(WBuf, size + 1); // reallocate end; Result := @WBuf[0]; end; function TZMWorkFile.Write(const Buffer; Len: Integer): Integer; begin if IsMultiPart then Result := WriteSplit(Buffer, Len) else Result := Write_F(Buffer, Len); end; function TZMWorkFile.WriteFrom(strm: TStream; Count: Integer): Int64; const bsize = 20 * 1024; var done: Integer; maxsize: Integer; sz: Integer; wbufr: array of Byte; begin Result := 0; SetLength(wbufr, bsize); maxsize := strm.size - strm.Position; if Count > maxsize then Count := maxsize; while Count > 0 do begin sz := bsize; if sz > Count then sz := Count; done := strm.Read(wbufr[0], sz); if done > 0 then done := Write(wbufr[0], done); // split ok? if done <> sz then begin Result := -DS_FileError; if done < 0 then Result := done; break; end; Count := Count - sz; Result := Result + sz; end; end; function TZMWorkFile.Writes(const Buffer; const Lens: array of Integer) : Integer; var c: Integer; i: Integer; begin if IsMultiPart then begin c := 0; for i := Low(Lens) to High(Lens) do c := c + Lens[i]; Result := Write(Buffer, -c); end else Result := Writes_F(Buffer, Lens); end; function TZMWorkFile.WriteSplit(const Buffer; ToWrite: Integer): Integer; var Buf: PAnsiChar; Len: Cardinal; MaxLen: Cardinal; MinSize: Cardinal; MustFit: Boolean; Res: Integer; begin { WriteSplit } try Result := 0; MustFit := false; if ToWrite >= 0 then begin Len := ToWrite; MinSize := 0; end else begin Len := -ToWrite; MustFit := (Len and MustFitFlag) <> 0; Len := Len and MustFitMask; MinSize := Len; end; Buf := @Buffer; Boss.KeepAlive; Boss.CheckCancel; // Keep writing until error or Buffer is empty. while True do begin // Check if we have an output file already opened, if not: create one, // do checks, gather info. if (not IsOpen) then begin NewDisk := DiskNr <> 0; // allow first disk in drive if NewSegment then begin NewDisk := True; continue; end; end; // Check if we have at least MinSize available on this disk, // headers are not allowed to cross disk boundaries. ( if zero than don't care.) if (MinSize <> 0) and (MinSize > AllowedSize) then begin // close this part // all parts must be same stamp if StampDate = 0 then StampDate := LastWritten; File_Close; FDiskWritten := 0; NewDisk := True; DiskNr := DiskNr + 1; // RCV270299 if not MustFit then continue; Result := MustFitError; break; end; // Don't try to write more bytes than allowed on this disk. MaxLen := HIGH(Integer); if AllowedSize < MaxLen then MaxLen := Integer(AllowedSize); if Len < MaxLen then MaxLen := Len; if fDiskBuffer <> nil then begin Move(Buf^, fDiskBuffer[fBufferPosition], MaxLen); Res := MaxLen; Inc(fBufferPosition, MaxLen); end else Res := WriteToFile(Buf^, MaxLen); if Res < 0 then raise EZipMaster.CreateResDisp(DS_NoWrite, True); // A write error (disk removed?) Inc(FDiskWritten, Res); Inc(Result, Res); AllowedSize := AllowedSize - MaxLen; if MaxLen = Len then break; // We still have some data left, we need a new disk. if StampDate = 0 then StampDate := LastWritten; File_Close; AllowedSize := 0; FDiskWritten := 0; DiskNr := DiskNr + 1; NewDisk := True; Inc(Buf, MaxLen); Dec(Len, MaxLen); end; { while(True) } except on E: EZipMaster do begin Result := -E.ResId; end; on E: Exception do begin Result := -DS_UnknownError; end; end; end; function TZMWorkFile.Writes_F(const Buffer; const Lens: array of Integer) : Integer; var c: Integer; i: Integer; begin c := 0; for i := Low(Lens) to High(Lens) do c := c + Lens[i]; Result := WriteToFile(Buffer, c); end; function TZMWorkFile.WriteToFile(const Buffer; Len: Integer): Integer; begin if Len < 0 then Len := (-Len) and MustFitMask; Result := DoFileWrite(Buffer, Len); if Result > 0 then BytesWritten := BytesWritten + Len; end; function TZMWorkFile.Write_F(const Buffer; Len: Integer): Integer; begin Result := WriteToFile(Buffer, Len); end; function TZMWorkFile.ZipFormat(const NewName: String): Integer; var msg: String; Res: Integer; Vol: String; begin if NewName <> '' then Vol := NewName else Vol := WorkDrive.DiskName; if Length(Vol) > 11 then Vol := Copy(Vol, 1, 11); Result := -3; if WorkDrive.DriveIsFloppy then begin if (spTryFormat in SpanOptions) then Result := FormatFloppy(Application.Handle, WorkDrive.DriveStr); if Result = -3 then begin if ConfirmErase then begin msg := Boss.ZipFmtLoadStr(FM_Erase, [WorkDrive.DriveStr]); Res := Boss.ZipMessageDlgEx(Boss.ZipLoadStr(FM_Confirm), msg, zmtWarning + DHC_FormErase, [mbYes, mbNo]); if Res <> idYes then begin Result := -3; // no was -2; // cancel exit; end; end; ClearFloppy(WorkDrive.DriveStr); Result := 0; end; WorkDrive.HasMedia(false); if (Result = 0) and (Numbering = znsVolume) then WorkDrive.RenameDisk(Vol); end; end; end.
unit fmuCashControl; interface uses // VCL Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, WinSock, ExtCtrls, Buttons, // This untPages, WSockets, untUtil; type { TfmCashControl } TfmCashControl = class(TPage) gbCashControlServer: TGroupBox; lblProtocol: TLabel; lblPort: TLabel; Memo: TMemo; rbTCP: TRadioButton; rbUDP: TRadioButton; edtPort: TEdit; btnOpenPort: TBitBtn; btnClosePort: TBitBtn; procedure btnOpenPortClick(Sender: TObject); procedure btnClosePortClick(Sender: TObject); private FUDPServer: TUDPServer; FTCPServer: TTCPServer; procedure ServerData(Sender: TObject; Socket: TSocket); property UDPServer: TUDPServer read FUDPServer; property TCPServer: TTCPServer read FTCPServer; public constructor Create(AOwner: TComponent); override; end; var fmCashControl: TfmCashControl; implementation {$R *.DFM} function DosToStr(const S: string): string; begin Result := S; OemToCharBuff(PChar(Result), PChar(Result), Length(Result)); end; { TfmCashControl } constructor TfmCashControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FUDPServer := TUDPServer.Create(Self); FTCPServer := TTCPServer.Create(Self); FUDPServer.OnData := ServerData; FTCPServer.OnData := ServerData; end; procedure TfmCashControl.ServerData(Sender: TObject; Socket: TSocket); var Data: string; SockAddrIn: TSockAddrIn; begin if Sender is TTCPServer then begin Data := (Sender as TTCPServer).Read(Socket); end else begin Data := (Sender as TUDPServer).Read(Socket, SockAddrIn); end; Memo.Lines.Text := Memo.Lines.Text + DosToStr(Data); end; procedure TfmCashControl.btnOpenPortClick(Sender: TObject); begin if rbTCP.Checked then begin TCPServer.Close; TCPServer.Port := edtPort.Text; TCPServer.Open; end else begin UDPServer.Close; UDPServer.Port := edtPort.Text; UDPServer.Open; end; btnOpenPort.Enabled := False; btnClosePort.Enabled := True; btnClosePort.SetFocus; end; procedure TfmCashControl.btnClosePortClick(Sender: TObject); begin UDPServer.Close; TCPServer.Close; btnClosePort.Enabled := False; btnOpenPort.Enabled := True; btnOpenPort.SetFocus; end; end.
unit uClienteEspecificacaoController; interface uses System.SysUtils, uDMClienteEspecificacao, uRegras, uDM, Data.DB, uEnumerador, Vcl.Forms, uFuncoesSIDomper; type TClienteEspecificacaoController = class private FModel: TDMClienteEspecificacao; FOperacao: TOperacao; procedure Post; public procedure LocalizarCodigo(AIdCliente: integer); procedure Cancelar; procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); procedure Salvar(AIdCliente, AIdUsuario: Integer); procedure Excluir(AIdUsuario, AId: Integer); procedure Imprimir(AIdUsuario: Integer); property Model: TDMClienteEspecificacao read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TClienteEmailController } procedure TClienteEspecificacaoController.Cancelar; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Cancel; end; constructor TClienteEspecificacaoController.Create; begin inherited Create; FModel := TDMClienteEspecificacao.Create(nil); end; destructor TClienteEspecificacaoController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TClienteEspecificacaoController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerMethods1Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CClienteEspPrograma, dm.IdUsuario, AId); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; DM.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TClienteEspecificacaoController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerMethods1Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Negocio.Excluir(CClienteEspPrograma, AIdUsuario, AId); FModel.CDSConsulta.Delete; DM.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TClienteEspecificacaoController.Imprimir(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CClienteEspPrograma, AIdUsuario); FModel.Rel.Print; DM.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TClienteEspecificacaoController.LocalizarCodigo(AIdCliente: integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.LocalizarCodigo(CClienteEspPrograma, AIdCliente); FModel.CDSConsulta.Open; DM.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TClienteEspecificacaoController.Novo(AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CClienteEspPrograma, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; FOperacao := opIncluir; DM.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TClienteEspecificacaoController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; procedure TClienteEspecificacaoController.Salvar(AIdCliente, AIdUsuario: Integer); var Negocio: TServerMethods1Client; begin if FModel.CDSCadastroCliEsp_Usuario.AsInteger = 0 then raise Exception.Create('Informe o Usuário!'); if Trim(FModel.CDSCadastroCliEsp_Nome.AsString) = '' then raise Exception.Create('Informe o Nome!'); if Trim(FModel.CDSCadastroCliEsp_Descricao.AsString) = '' then raise Exception.Create('Informe a Descrição!'); if Trim(FModel.CDSCadastroCliEsp_Anexo.AsString) <> '' then begin if not FileExists(FModel.CDSCadastroCliEsp_Anexo.AsString) then raise Exception.Create('Diretório não Encontrado.'); end; if FOperacao = opIncluir then FModel.CDSCadastroCliEsp_Cliente.AsInteger := AIdCliente; Post(); FModel.CDSCadastro.ApplyUpdates(0); DM.Conectar; Negocio := TServerMethods1Client.Create(DM.Conexao.DBXConnection); try Negocio.Salvar(CClienteEspPrograma, AIdUsuario); DM.Desconectar; finally FreeAndNil(Negocio); end; FOperacao := opNavegar; end; end.
unit Broadcast; interface uses Protocol, Kernel, WorkCenterBlock, Classes, Collection, BackupInterfaces, Surfaces, Accounts, StdFluids, Languages, CacheAgent, Inventions; const tidTownParameter_Broadcast = 'Broadcast'; tidEnvironmental_Broadcast = 'Broadcast'; tidAdvertisement_Quality = 100; const AntenaOpCost = 200; type TMetaBroadcaster = class( TMetaWorkCenter ) public constructor Create( anId : string; aBroadcastId : string; aBroadcastCost : TMoney; aCapacities : array of TFluidValue; aSupplyAccount : TAccountId; aProdAccount : TAccountId; aSalaryAccount : TAccountId; aBlockClass : CBlock ); private fBroadcastId : string; fBroadcastCost : TMoney; public property BroadcastId : string read fBroadcastId; property BroadcastCost : TMoney read fBroadcastCost; end; TBroadcaster = class( TFinanciatedWorkCenter ) protected constructor Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); override; public destructor Destroy; override; private fAdvertisement : TOutputData; private fAntennas : TLockableCollection; fHoursOnAir : byte; fBudget : TPercent; fCommercials : TPercent; published property HoursOnAir : byte read fHoursOnAir write fHoursOnAir; property Budget : TPercent read fBudget write fBudget; property Commercials : TPercent read fCommercials write fCommercials; public function Evaluate : TEvaluationResult; override; procedure Autoconnect( loaded : boolean ); override; function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; function ConnectTo ( Block : TBlock; Symetrical : boolean ) : string; override; procedure DisconnectFrom( Block : TBlock; Symetrical : boolean ); override; protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; public procedure StoreToCache( Cache : TObjectCache ); override; private fViewers : TFluidValue; fPresence : TSurfaceValue; fCompetition : TSurfaceValue; fRating : single; fLastViewers : integer; fInvEfficiency : integer; fInvQuality : integer; fQuality : integer; private procedure IntegrateInventions(out invEfficiency, invQuality : integer); protected procedure RecalculateInventionsEffect; override; end; TMetaAntenna = class( TMetaWorkCenter ) public constructor Create( anId : string; aCapacities : array of TFluidValue; aSupplyAccount : TAccountId; aProdAccount : TAccountId; aSalaryAccount : TAccountId; aBlockClass : CBlock ); private fBroadcastId : string; fPower : integer; fCostByViewer : TMoney; public property BroadcastId : string read fBroadcastId write fBroadcastId; property Power : integer read fPower write fPower; property CostByViewer : TMoney read fCostByViewer; end; TPeopleIntegrators = array[TPeopleKind] of TSurfaceIntegrator; TAntenna = class( TFinanciatedWorkCenter ) public destructor Destroy; override; private fBroadcaster : TBroadcaster; //fSignal : TSurfaceModifier; //fSignalInt : TSurfaceIntegrator; //fPeopleInt : TPeopleIntegrators; fQuality : single; fPeople : TFluidValue; fTownParm : TTownParameter; fIgnored : boolean; public function Evaluate : TEvaluationResult; override; procedure Autoconnect( loaded : boolean ); override; procedure EndOfPeriod(PeriodType : TPeriodType; PeriodCount : integer); override; function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; function ConnectTo ( Block : TBlock; Symetrical : boolean ) : string; override; procedure DisconnectFrom( Block : TBlock; Symetrical : boolean ); override; private procedure LinkToBroadcaster( aBroadcaster : TBroadcaster ); protected procedure LoadFromBackup( Reader : IBackupReader ); override; procedure StoreToBackup ( Writer : IBackupWriter ); override; end; const tidInventionClass_TVBlock = 'Television'; tidInvAttr_TVEfficiency = 'effic'; tidInvAttr_TVQuality = 'q'; type TTVInvention = class(TWorkCenterInvention) public constructor Load(xmlObj : OleVariant); override; private fEfficiency : integer; fQuality : integer; public property Efficiency : integer read fEfficiency; property Quality : integer read fQuality; public function GetClientProps(Company : TObject; LangId : TLanguageId) : string; override; end; procedure RegisterBackup; procedure RegisterInventionClass; procedure RegisterTownParameters; implementation uses ClassStorage, MetaInstances, SysUtils, PyramidalModifier, Population, MathUtils, SimHints, StdAccounts; const AvgAdTime = (1/(60*60))*45; // in seconds // TMetaAntena constructor TMetaAntenna.Create( anId : string; aCapacities : array of TFluidValue; aSupplyAccount : TAccountId; aProdAccount : TAccountId; aSalaryAccount : TAccountId; aBlockClass : CBlock ); begin inherited; fCostByViewer := StrToFloat(TheGlobalConfigHandler.GetConfigParm('AntennaCostByViewer', '0.25')); end; // TMetaBroadcaster constructor TMetaBroadcaster.Create( anId : string; aBroadcastId : string; aBroadcastCost : TMoney; aCapacities : array of TFluidValue; aSupplyAccount : TAccountId; aProdAccount : TAccountId; aSalaryAccount : TAccountId; aBlockClass : CBlock ); var Sample : TBroadcaster; begin inherited Create( anId, aCapacities, aSupplyAccount, aProdAccount, aSalaryAccount, aBlockClass ); fBroadcastId := aBroadcastId; fBroadcastCost := aBroadcastCost; Sample := nil; MetaOutputs.Insert( TMetaOutput.Create( tidGate_Advertisement, FluidData(qIlimited, 100), TPullOutput, TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_Advertisement]), 5, [mgoptCacheable, mgoptEditable], sizeof(Sample.fAdvertisement), Sample.Offset(Sample.fAdvertisement))); end; // TBroadcaster constructor TBroadcaster.Create( aMetaBlock : TMetaBlock; aFacility : TFacility ); begin inherited; fHoursOnAir := 24; fCommercials := 30; fBudget := 100; fAntennas := TLockableCollection.Create( 0, rkUse ); end; destructor TBroadcaster.Destroy; var i : integer; begin fAntennas.Lock; try for i := 0 to pred(fAntennas.Count) do TAntenna(fAntennas[i]).fBroadcaster := nil; finally fAntennas.Unlock; end; fAntennas.Free; inherited; end; function TBroadcaster.Evaluate : TEvaluationResult; var Quality : single; i, j : integer; WEffic : single; Antenna : TAntenna; TownPrm : TTownParameter; invEffic : single; InventQuality : single; begin result := inherited Evaluate; // Broadcasters sell to anyone if fTradeLevel <> tlvAnyone then SetTradeLevel(tlvAnyone); if not Facility.CriticalTrouble and Facility.HasTechnology then begin invEffic := realmax(0, realmin(2, 1 - fInvEfficiency/100)); if fCompetition > 0 then fRating := realmin(1, fPresence/fCompetition) else if fPresence > 0 then fRating := 1 else fRating := 0; WEffic := WorkForceEfficiency; //fViewers := fViewers*fRating; // Balance the formula using both numbers... fAdvertisement.Q := (fHoursOnAir/24)*(fCommercials/100)*fViewers*dt/(10*AvgAdTime); Quality := sqrt(WEffic)*(-(fCommercials-50)/50)*(1 - (fCommercials/100))*(fBudget/100); InventQuality := (1 - max(fCommercials - 40, 0)/60)*fInvQuality; Quality := RealMax(0.01, Quality + InventQuality/100); fQuality := min(100, round((100*Quality)/2)); fAdvertisement.K := tidAdvertisement_Quality; // with TMetaBroadcaster(MetaBlock) do BlockGenMoney( -invEffic*BroadcastCost*(fBudget/100)*(fHoursOnAir/24)*dt, accIdx_TV_Maintenance); fAntennas.Lock; try // Assign Quality and Sign as not abandoned all antennas for i := pred(fAntennas.Count) downto 0 do begin Antenna := TAntenna(fAntennas[i]); if Antenna.Facility.Deleted then fAntennas.Delete(Antenna) else begin Antenna.fQuality := realmax(0, fQuality); Antenna.fIgnored := Antenna.Facility.CriticalTrouble; end; end; // Ignore second Antennas for i := 0 to pred(fAntennas.Count) do begin Antenna := TAntenna(fAntennas[i]); if not Antenna.fIgnored then begin TownPrm := Antenna.fTownParm; for j := i + 1 to pred(fAntennas.Count) do with TAntenna(fAntennas[j]) do if fTownParm = TownPrm then fIgnored := true; end; end; finally fAntennas.Unlock; end; HireWorkForce( realmin(0.7, fHoursOnAir/24) ); end else begin fAdvertisement.Q := 0; fAdvertisement.K := 0; fLastViewers := 0; end; fLastViewers := round( fViewers ); fViewers := 0; fPresence := 0; fCompetition := 0; end; procedure TBroadcaster.Autoconnect( loaded : boolean ); begin inherited; fAntennas.Pack; //RDOSetTradeLevel( integer(tlvAnyone) ); >> end; function TBroadcaster.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; function SalesRatio : single; begin if fAdvertisement.Q > 0 then result := 1 - fAdvertisement.Extra.Q/fAdvertisement.Q else result := 0 end; var k : TPeopleKind; begin result := inherited GetStatusText( kind, ToTycoon ); if not Facility.CriticalTrouble and (Facility.Trouble and facNeedsWorkForce = 0) then case kind of sttMain : result := result + SimHints.GetHintText( mtidTVMainOne.Values[ToTycoon.Language], [fLastViewers] ) + LineBreak + SimHints.GetHintText( mtidTVMainTwo.Values[ToTycoon.Language], [round(100*fRating)] ); sttSecondary : result := result + SimHints.GetHintText( mtidTVSec.Values[ToTycoon.Language], [fHoursOnAir, fCommercials, round(100*SalesRatio), fAntennas.Count, fQuality, fInvEfficiency ] ); sttHint : if fAntennas.Count = 0 then result := result + SimHints.GetHintText( mtidTVWarning.Values[ToTycoon.Language], [0] ); end else if Facility.Trouble and facNeedsWorkForce <> 0 then case kind of sttMain : result := result + SimHints.GetHintText( mtidHiringWorkForce.Values[ToTycoon.Language], [round(100*WorkForceRatioAvg)] ); sttSecondary : with TMetaWorkCenter(MetaBlock) do for k := low(k) to high(k) do if Capacity[k] > 0 then 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; end; function TBroadcaster.ConnectTo( Block : TBlock; Symetrical : boolean ) : string; var report : string; begin result := inherited ConnectTo( Block, Symetrical ); if ObjectIs( TAntenna.ClassName, Block ) then begin if Block.Facility.Company.Owner = Facility.Company.Owner then if TAntenna(Block).fBroadcaster <> self then begin if TAntenna(Block).fBroadcaster <> nil then report := 'Antenna previously connected to ' + Block.Facility.Name + '.' + LineBreak + 'Now connected to ' + Facility.Name + '.' else report := 'Antenna successfully connected to ' + Facility.Name + '.'; TAntenna(Block).LinkToBroadcaster( self ); end else report := 'Antenna was already connected.' else report := 'You are not allowed to do that!'; if result <> '' then result := report + LineBreak + result else result := report; end; end; procedure TBroadcaster.DisconnectFrom( Block : TBlock; Symetrical : boolean ); begin inherited; end; procedure TBroadcaster.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject( 'Antennas', fAntennas, nil ); fHoursOnAir := Reader.ReadByte( 'HoursOnAir', 24 ); fBudget := Reader.ReadByte( 'Budget', 100 ); fCommercials := Reader.ReadByte( 'Commercials', 30 ); end; procedure TBroadcaster.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteObject( 'Antennas', fAntennas ); Writer.WriteByte( 'HoursOnAir', fHoursOnAir ); Writer.WriteByte( 'Budget', fBudget ); Writer.WriteByte( 'Commercials', fCommercials ); end; procedure TBroadcaster.StoreToCache(Cache : TObjectCache); var i : integer; iStr : string; Antenna : TAntenna; begin inherited; for i := 0 to pred(fAntennas.Count) do begin iStr := IntToStr(i); Antenna := TAntenna(fAntennas[i]); Cache.WriteString('antName' + iStr, Antenna.Facility.Name); Cache.WriteInteger('antX' + iStr, Antenna.xPos); Cache.WriteInteger('antY' + iStr, Antenna.yPos); Cache.WriteString('antTown' + iStr, Antenna.Facility.Town.Name); if not Antenna.Facility.CriticalTrouble then Cache.WriteInteger('antViewers' + iStr, round(Antenna.fPeople)) else Cache.WriteInteger('antViewers' + iStr, 0); if not Antenna.fIgnored then Cache.WriteString('antActive' + iStr, 'YES'); end; Cache.WriteInteger('antCount', fAntennas.Count); end; procedure TBroadcaster.IntegrateInventions(out invEfficiency, invQuality : integer); var Invention : TTVInvention; i : integer; MaxQuality: integer; MinQuality: integer; begin invEfficiency := 0; invQuality := 0; MaxQuality := 0; MinQuality := 0; for i := 0 to pred(MetaBlock.Inventions.Count) do begin Invention := TTVInvention(MetaBlock.Inventions[i]); if Invention.Quality > 0 then MaxQuality := MaxQuality + Invention.Quality else MinQuality := MinQuality + Invention.Quality; if Facility.Company.HasInvention[Invention.NumId] then begin invEfficiency := invEfficiency + Invention.Efficiency; invQuality := invQuality + Invention.Quality; end; end; invQuality := Round(((InvQuality - MinQuality)*100)/(MaxQuality - MinQuality)); end; procedure TBroadcaster.RecalculateInventionsEffect; begin IntegrateInventions(fInvEfficiency, fInvQuality); end; // TAntenna destructor TAntenna.Destroy; //var //kind : TPeopleKind; begin if fBroadcaster <> nil then fBroadcaster.fAntennas.Delete( self ); //fSignal.Delete; //for kind := low(kind) to high(kind) do //fPeopleInt[kind].Delete; //fSignalInt.Delete; inherited; end; function TAntenna.Evaluate : TEvaluationResult; var locFact : single; Strength : double; TownHall : TTownHall; Viewers : TFluidValue; theDt : single; begin result := inherited Evaluate; if (fBroadcaster <> nil) and fBroadcaster.Facility.Deleted then begin fBroadcaster := nil; fIgnored := false; fPeople := 0; end; if (fBroadcaster <> nil) and not fIgnored and (fTownParm <> nil) then begin theDt := dt; if fBroadcaster.Facility.Town = Facility.Town then locFact := 1 else locFact := 0.5; if fTownParm.Value > 0 then Strength := realmin(1, fQuality/fTownParm.Value) else Strength := 1; fTownParm.CurrValue := fTownParm.CurrValue + fQuality; Strength := locFact*Strength; fBroadcaster.fPresence := fBroadcaster.fPresence + fQuality; fBroadcaster.fCompetition := fBroadcaster.fCompetition + realmax(0, fTownParm.Value - fQuality); // Get the town hall TownHall := TTownHall(TInhabitedTown(Facility.Town).TownHall.CurrBlock); // Viewers Viewers := theDt*Strength*TownHall.TotalPopulation*4/24; // (1/6) Considering every people watches TV 4 hours a day fBroadcaster.fViewers := fBroadcaster.fViewers + Viewers; fPeople := round(Viewers); with TMetaAntenna(MetaBlock) do //fBroadcaster.BlockGenMoney(-realmax(AntenaOpCost, CostByViewer*Viewers)*theDt, accIdx_TV_Maintenance); //We got rid of the cost per viewer for the antennas fBroadcaster.BlockGenMoney(-AntenaOpCost*theDt, accIdx_TV_Maintenance); HireWorkForce(1); end; end; procedure TAntenna.Autoconnect( loaded : boolean ); {var kind : TPeopleKind;} begin inherited; {for kind := low(kind) to high(kind) do fPeopleInt[kind] := TSurfaceIntegrator.Create( PeopleKindPrefix[kind] + tidEnvironment_People, GetArea( TMetaAntenna(MetaBlock).Power, amdIncludeBlock ));} {fSignalInt := TSurfaceIntegrator.Create( TMetaAntenna(MetaBlock).BroadcastId, GetArea( TMetaAntenna(MetaBlock).Power, amdIncludeBlock ));} {fSignal := TPyramidalModifier.Create( TMetaAntenna(MetaBlock).BroadcastId, Point(xOrigin, yOrigin), 0, 1 ); fSignal.FixedArea := true;} {with TMetaAntenna(MetaBlock) do fSignal.Area := Rect( xOrigin - Power, yOrigin - Power, xOrigin + Power, yOrigin + Power );} fTownParm := Facility.Town.Parameters[tidTownParameter_Broadcast]; fIgnored := false; end; procedure TAntenna.EndOfPeriod(PeriodType : TPeriodType; PeriodCount : integer); begin inherited; case PeriodType of perDay : if fIgnored and not Facility.CriticalTrouble then Facility.Town.ModelFactory.RequestDeletion(Facility) else if not fIgnored and (fBroadcaster = nil) and (Facility.Age > 2*24*365) then Facility.Town.ModelFactory.RequestDeletion(Facility); end; end; function TAntenna.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; begin result := inherited GetStatusText( kind, ToTycoon ); case kind of sttSecondary : begin result := result + SimHints.GetHintText( mtidAntenaAudience.Values[ToTycoon.Language], [round(fPeople)] ); if (fBroadcaster <> nil) and not fIgnored then result := fBroadcaster.Facility.Name + ', ' + result + ' ' + SimHints.GetHintText( mtidAntenaRating.Values[ToTycoon.Language], [round(100*fBroadcaster.fRating)] ); end; sttHint : if fBroadcaster = nil then result := result + SimHints.GetHintText( mtidAntenaHint.Values[ToTycoon.Language], [0] ); end; end; function TAntenna.ConnectTo( Block : TBlock; Symetrical : boolean ) : string; begin result := inherited ConnectTo( Block, Symetrical ); end; procedure TAntenna.DisconnectFrom( Block : TBlock; Symetrical : boolean ); begin inherited; end; procedure TAntenna.LinkToBroadcaster( aBroadcaster : TBroadcaster ); begin if fBroadcaster <> nil then fBroadcaster.fAntennas.Delete( self ); fBroadcaster := aBroadcaster; fBroadcaster.fAntennas.Insert( self ); end; procedure TAntenna.LoadFromBackup( Reader : IBackupReader ); begin inherited; Reader.ReadObject( 'Broadcaster', fBroadcaster, nil ); end; procedure TAntenna.StoreToBackup( Writer : IBackupWriter ); begin inherited; Writer.WriteObjectRef( 'Broadcaster', fBroadcaster ); end; // TTVInvention constructor TTVInvention.Load(xmlObj : OleVariant); var Aux : OleVariant; begin inherited Load(xmlObj); Aux := xmlObj.children.item(tidInvElement_Props, Unassigned); fEfficiency := GetProperty(Aux, tidInvAttr_TVEfficiency); fQuality := GetProperty(Aux, tidInvAttr_TVQuality); end; function TTVInvention.GetClientProps(Company : TObject; LangId : TLanguageId) : string; begin result := inherited GetClientProps(Company, LangId ); if fEfficiency <> 0 then result := result + SimHints.GetHintText(mtidInvEff.Values[LangId], [FormatDelta(fEfficiency)]) + LineBreak; if fQuality <> 0 then result := result + SimHints.GetHintText(mtidInvQ.Values[LangId], [FormatDelta(fQuality)]) + LineBreak; end; procedure RegisterBackup; begin RegisterClass( TBroadcaster ); RegisterClass( TAntenna ); end; procedure RegisterInventionClass; begin TheClassStorage.RegisterClass( tidClassFamily_InvClasses, tidInventionClass_TVBlock, TInventionClass.Create(TTVInvention)); end; procedure RegisterTownParameters; begin TMetaTownParameter.Create(tidTownParameter_Broadcast, 'BroadCast', true).Register; end; end.
unit rdkafka_test; {$mode objfpc}{$H+} interface uses TestFramework; type TTestCaseFirst = class(TTestCase) published procedure TestWarning; procedure TestOne; procedure TestTwo; procedure TestThree; end; TClassA = class(TTestCase) published procedure TestClassA1; procedure TestClassA2; virtual; end; TClassB = class(TClassA) published procedure TestClassA2; override; procedure TestClassB1; procedure TestError; end; procedure RegisterTests; implementation uses sysutils; procedure RegisterTests; begin TestFramework.RegisterTest(TTestCaseFirst.Suite); TestFramework.RegisterTest(TClassB.Suite); end; { TTestCaseFirst } procedure TTestCaseFirst.TestWarning; begin // Do nothing here - should cause a Warning end; procedure TTestCaseFirst.TestOne; begin Check(1 + 1 = 3, 'Catastrophic arithmetic failure!'); end; procedure TTestCaseFirst.TestTwo; begin Check(1 + 1 = 2, 'Catastrophic arithmetic failure!'); end; procedure TTestCaseFirst.TestThree; var s: string; begin s := 'hello'; CheckEquals('Hello', s, 'Failed CheckEquals'); end; { TClassA } procedure TClassA.TestClassA1; begin fail('TClassA.TestClassA1'); end; procedure TClassA.TestClassA2; begin Fail('This virtual method should never appear.'); end; { TClassB } procedure TClassB.TestClassA2; begin Fail('Test overridden method'); end; procedure TClassB.TestClassB1; begin sleep(2264); Fail('Test sleep() causing extra time'); end; procedure TClassB.TestError; var x, y: integer; begin x := 10; y := 0; Check(x / y = 0, 'Failed on 1'); end; end.
unit evdF1HyperlinkCorrector; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "EVD" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/EVD/evdF1HyperlinkCorrector.pas" // Начат: 18.06.2010 19:15 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::EVD::Generators::TevdF1HyperlinkCorrector // // Фильтр исправляющий адреса ссылок из F1 // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\EVD\evdDefine.inc} interface uses k2TagGen, evdInterfaces, evdLeafParaFilter, k2Interfaces ; type TevdF1HyperlinkCorrector = class(TevdLeafParaFilter) {* Фильтр исправляющий адреса ссылок из F1 } private // private fields f_Converter : IevdExternalDocNumberToInternal; protected // overridden protected methods function ParaTypeForFiltering: Integer; override; {* Функция, определяющая тип абзацев, для которых будет выполняться фильтрация } procedure DoWritePara(const aLeaf: Ik2Tag); override; {* Запись конкретного абзаца в генератор. Позволяет вносить изменения в содержание абзаца } procedure ClearFields; override; public // public methods class function SetTo(var theGenerator: Tk2TagGenerator; const aConverter: IevdExternalDocNumberToInternal): Pointer; end;//TevdF1HyperlinkCorrector implementation uses HyperLink_Const, k2Tags, evdTypes, k2Const, evdVer ; // start class TevdF1HyperlinkCorrector class function TevdF1HyperlinkCorrector.SetTo(var theGenerator: Tk2TagGenerator; const aConverter: IevdExternalDocNumberToInternal): Pointer; //#UC START# *4C1B9990015E_4C1B8D2F039F_var* //#UC END# *4C1B9990015E_4C1B8D2F039F_var* begin //#UC START# *4C1B9990015E_4C1B8D2F039F_impl* Result := inherited SetTo(theGenerator); (theGenerator As TevdF1HyperlinkCorrector).f_Converter := aConverter; //#UC END# *4C1B9990015E_4C1B8D2F039F_impl* end;//TevdF1HyperlinkCorrector.SetTo function TevdF1HyperlinkCorrector.ParaTypeForFiltering: Integer; //#UC START# *49E488070386_4C1B8D2F039F_var* //#UC END# *49E488070386_4C1B8D2F039F_var* begin //#UC START# *49E488070386_4C1B8D2F039F_impl* Result := k2_idEmpty; if (CurrentVersion > evVer20Step) then if (CurrentVersion mod evFormatCurVersionStep = 1) then Result := k2_idHyperlink; //#UC END# *49E488070386_4C1B8D2F039F_impl* end;//TevdF1HyperlinkCorrector.ParaTypeForFiltering procedure TevdF1HyperlinkCorrector.DoWritePara(const aLeaf: Ik2Tag); //#UC START# *49E4883E0176_4C1B8D2F039F_var* var l_Index : Integer; l_DocID : Integer; //#UC END# *49E4883E0176_4C1B8D2F039F_var* begin //#UC START# *49E4883E0176_4C1B8D2F039F_impl* if (CurrentVersion > evVer20Step) then if (CurrentVersion mod evFormatCurVersionStep = 1) then begin for l_Index := 0 to aLeaf.ChildrenCount - 1 do with aLeaf.Child[l_Index] do begin l_DocID := IntA[k2_tiDocID]; if (l_DocID > 0) then begin if (l_DocID > 100000) then begin l_DocID := l_DocID - 100000; if (f_Converter <> nil) then l_DocID := f_Converter.ConvertExternalDocNumberToInternal(l_DocID); IntA[k2_tiDocID] := l_DocID; end//l_DocID > 100000 else Assert(false, 'Номер документа в ссылке из F1 меньше 100000'); end;//l_DocID > 0 end;//with aLeaf.Child[l_Index] end;//CurrentVersion mod evFormatCurVersionStep = 1 inherited; //#UC END# *49E4883E0176_4C1B8D2F039F_impl* end;//TevdF1HyperlinkCorrector.DoWritePara procedure TevdF1HyperlinkCorrector.ClearFields; {-} begin f_Converter := nil; inherited; end;//TevdF1HyperlinkCorrector.ClearFields end.
unit CommandSet.NVMe.WithoutDriver; interface uses Windows, SysUtils, OSFile.IoControl, CommandSet.NVMe, BufferInterpreter, Device.SMART.List, BufferInterpreter.SCSI, OS.SetupAPI; type TNVMeWithoutDriverCommandSet = class sealed(TNVMeCommandSet) public function IdentifyDevice: TIdentifyDeviceResult; override; function SMARTReadData: TSMARTValueList; override; function RAWIdentifyDevice: String; override; function RAWSMARTReadData: String; override; function IsExternal: Boolean; override; private type SCSI_COMMAND_DESCRIPTOR_BLOCK = record SCSICommand: UCHAR; MiscellaneousCDBInformation: UCHAR; LogicalBlockAddress: Array[0..7] of UCHAR; TransferParameterListAllocationLength: Array[0..3] of UCHAR; MiscellaneousCDBInformation2: UCHAR; Control: UCHAR; end; SCSI_PASS_THROUGH = record Length: USHORT; ScsiStatus: UCHAR; PathId: UCHAR; TargetId: UCHAR; Lun: UCHAR; CdbLength: UCHAR; SenseInfoLength: UCHAR; DataIn: UCHAR; DataTransferLength: ULONG; TimeOutValue: ULONG; DataBufferOffset: ULONG_PTR; SenseInfoOffset: ULONG; CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK; end; SCSI_24B_SENSE_BUFFER = record ResponseCodeAndValidBit: UCHAR; Obsolete: UCHAR; SenseKeyILIEOMFilemark: UCHAR; Information: Array[0..3] of UCHAR; AdditionalSenseLengthMinusSeven: UCHAR; CommandSpecificInformation: Array[0..3] of UCHAR; AdditionalSenseCode: UCHAR; AdditionalSenseCodeQualifier: UCHAR; FieldReplaceableUnitCode: UCHAR; SenseKeySpecific: Array[0..2] of UCHAR; AdditionalSenseBytes: Array[0..5] of UCHAR; end; SCSI_WITH_BUFFER = record Parameter: SCSI_PASS_THROUGH; SenseBuffer: SCSI_24B_SENSE_BUFFER; Buffer: TSmallBuffer; end; const SCSI_IOCTL_DATA_OUT = 0; SCSI_IOCTL_DATA_IN = 1; SCSI_IOCTL_DATA_UNSPECIFIED = 2; private IoInnerBuffer: SCSI_WITH_BUFFER; function GetCommonBuffer: SCSI_WITH_BUFFER; function GetCommonCommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK; procedure IfRealSCSIDeleteModel(var Model: String); procedure SetInnerBufferAsFlagsAndCdb(Flags: ULONG; CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK); function InterpretIdentifyDeviceBuffer: TIdentifyDeviceResult; procedure SetBufferAndIdentifyDevice; procedure SetInnerBufferToSendIdentifyDeviceCommand; end; implementation { TNVMeWithoutDriverCommandSet } function TNVMeWithoutDriverCommandSet.GetCommonBuffer: SCSI_WITH_BUFFER; const SATTargetId = 1; begin FillChar(result, SizeOf(result), #0); result.Parameter.Length := SizeOf(result.Parameter); result.Parameter.TargetId := SATTargetId; result.Parameter.CdbLength := 8; result.Parameter.SenseInfoLength := SizeOf(result.SenseBuffer); result.Parameter.DataTransferLength := SizeOf(result.Buffer); result.Parameter.TimeOutValue := 2; result.Parameter.DataBufferOffset := PAnsiChar(@result.Buffer) - PAnsiChar(@result); result.Parameter.SenseInfoOffset := PAnsiChar(@result.SenseBuffer) - PAnsiChar(@result); end; function TNVMeWithoutDriverCommandSet.GetCommonCommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK; begin FillChar(result, SizeOf(result), #0); end; procedure TNVMeWithoutDriverCommandSet.SetInnerBufferAsFlagsAndCdb (Flags: ULONG; CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK); begin IoInnerBuffer := GetCommonBuffer; IoInnerBuffer.Parameter.DataIn := Flags; IoInnerBuffer.Parameter.CommandDescriptorBlock := CommandDescriptorBlock; end; procedure TNVMeWithoutDriverCommandSet.SetBufferAndIdentifyDevice; begin SetInnerBufferToSendIdentifyDeviceCommand; IoControl(TIoControlCode.SCSIPassThrough, BuildOSBufferBy<SCSI_WITH_BUFFER, SCSI_WITH_BUFFER>(IoInnerBuffer, IoInnerBuffer)); end; procedure TNVMeWithoutDriverCommandSet. SetInnerBufferToSendIdentifyDeviceCommand; const InquiryCommand = $12; var CommandDescriptorBlock: SCSI_COMMAND_DESCRIPTOR_BLOCK; begin CommandDescriptorBlock := GetCommonCommandDescriptorBlock; CommandDescriptorBlock.SCSICommand := InquiryCommand; CommandDescriptorBlock.LogicalBlockAddress[1] := SizeOf(IoInnerBuffer.Buffer) shr 8; CommandDescriptorBlock.LogicalBlockAddress[2] := SizeOf(IoInnerBuffer.Buffer) and $FF; SetInnerBufferAsFlagsAndCdb(SCSI_IOCTL_DATA_IN, CommandDescriptorBlock); end; procedure TNVMeWithoutDriverCommandSet.IfRealSCSIDeleteModel( var Model: String); begin if Copy(Model, 1, 4) <> 'NVMe' then Model := ''; end; function TNVMeWithoutDriverCommandSet.IdentifyDevice: TIdentifyDeviceResult; var ReadCapacityResult: TIdentifyDeviceResult; begin SetBufferAndIdentifyDevice; result := InterpretIdentifyDeviceBuffer; IfRealSCSIDeleteModel(result.Model); result.StorageInterface := TStorageInterface.NVMe; SetBufferAndReadCapacity; ReadCapacityResult := InterpretReadCapacityBuffer; result.UserSizeInKB := ReadCapacityResult.UserSizeInKB; result.LBASize := ReadCapacityResult.LBASize; result.IsDataSetManagementSupported := false; end; function TNVMeWithoutDriverCommandSet.InterpretIdentifyDeviceBuffer: TIdentifyDeviceResult; var SCSIBufferInterpreter: TSCSIBufferInterpreter; begin SCSIBufferInterpreter := TSCSIBufferInterpreter.Create; result := SCSIBufferInterpreter.BufferToIdentifyDeviceResult(IoInnerBuffer.Buffer); FreeAndNil(SCSIBufferInterpreter); end; function TNVMeWithoutDriverCommandSet.IsExternal: Boolean; begin result := false; end; function TNVMeWithoutDriverCommandSet.RAWIdentifyDevice: String; begin raise ENotSupportedException.Create('Please install the driver'); end; function TNVMeWithoutDriverCommandSet.RAWSMARTReadData: String; begin raise ENotSupportedException.Create('Please install the driver'); end; function TNVMeWithoutDriverCommandSet.SMARTReadData: TSMARTValueList; begin raise ENotSupportedException.Create('Please install the driver'); end; end.
unit fMain; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, VirtualTrees, {$ifdef windows}ActiveX{$else}FakeActiveX{$endif}; type { TMainForm } TMainForm = class(TForm) ShowHeaderCheckBox: TCheckBox; ListBox1: TListBox; VirtualStringTree1: TVirtualStringTree; procedure ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); procedure ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure ShowHeaderCheckBoxChange(Sender: TObject); procedure VirtualStringTree1DragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; const Pt: TPoint; var Effect: Integer; Mode: TDropMode); procedure VirtualStringTree1DragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; const Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); procedure VirtualStringTree1GetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); procedure VirtualStringTree1GetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); procedure VirtualStringTree1InitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); private { private declarations } public { public declarations } end; var MainForm: TMainForm; implementation {$R *.lfm} type TNodeData = record Title: String; end; PNodeData = ^TNodeData; { TMainForm } procedure TMainForm.VirtualStringTree1GetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: String); begin CellText := PNodeData(Sender.GetNodeData(Node))^.Title; end; procedure TMainForm.VirtualStringTree1InitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates); begin PNodeData(Sender.GetNodeData(Node))^.Title := 'VTV Item ' + IntToStr(Node^.Index); end; procedure TMainForm.ListBox1DragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := (Source = VirtualStringTree1) or (Source = ListBox1); end; procedure TMainForm.ShowHeaderCheckBoxChange(Sender: TObject); begin if ShowHeaderCheckBox.Checked then VirtualStringTree1.Header.Options := VirtualStringTree1.Header.Options + [hoVisible] else VirtualStringTree1.Header.Options := VirtualStringTree1.Header.Options - [hoVisible]; end; procedure TMainForm.ListBox1DragDrop(Sender, Source: TObject; X, Y: Integer); var Node: PVirtualNode; begin if Source = VirtualStringTree1 then begin Node := VirtualStringTree1.FocusedNode; if Node <> nil then ListBox1.Items.Append(VirtualStringTree1.Text[Node, 0]); end; end; procedure TMainForm.VirtualStringTree1DragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; const Pt: TPoint; var Effect: Integer; Mode: TDropMode); var Node: PVirtualNode; NodeTitle: String; begin case Mode of dmAbove: Node := Sender.InsertNode(Sender.DropTargetNode, amInsertBefore); dmBelow: Node := Sender.InsertNode(Sender.DropTargetNode, amInsertAfter); dmNowhere: Exit; else Node := Sender.AddChild(Sender.DropTargetNode); end; Sender.ValidateNode(Node, True); if Source = ListBox1 then begin if ListBox1.ItemIndex = -1 then NodeTitle := 'Unknow Item from List' else NodeTitle := ListBox1.Items[ListBox1.ItemIndex]; end else if Source = Sender then begin if Sender.FocusedNode <> nil then NodeTitle := VirtualStringTree1.Text[Sender.FocusedNode, 0] else NodeTitle := 'Unknow Source Node'; end else NodeTitle := 'Unknow Source Control'; PNodeData(Sender.GetNodeData(Node))^.Title := NodeTitle; end; procedure TMainForm.VirtualStringTree1DragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; const Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean); begin Accept := (Sender = VirtualStringTree1) or (Source = ListBox1); end; procedure TMainForm.VirtualStringTree1GetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer); begin NodeDataSize := SizeOf(TNodeData); end; end.
program stackDataStructure; (*first in, last out*) (* procedures: 1. init 2. push 3. pop functions: 1. isFull 2. isEmpty *) uses crt; const size = 10; type stacktype = record data : array[0..size - 1] of integer; top : integer; //top of the stack initialize to -1(empty) end; var stack : stacktype; response : string; x : integer; procedure init(var s : stacktype); // initialization var i : Integer; begin s.top := -1; for i := 0 to size - 1 do s.data[i] := 0; end; function isFull(s : stacktype):Boolean;(*here use size - 1 cuz the array is zero-based*) begin isFull := s.top = size - 1; //check if the top of the stack is equal to size(number of spaces in the stack) end; function isEmpty(s : stacktype):Boolean; begin isEmpty := s.top = -1; end; procedure push(var s : stacktype; x : integer); (*store data*) begin if not isFull(s) then begin s.top := s.top + 1; s.data[s.top] := x; end; end; procedure pop(var s : stacktype; var x : Integer); (*retrieve data*) begin if not isEmpty(s) then begin x := s.data[s.top]; s.data[s.top] := 0; // zero means empty... s.top := s.top - 1; end; end; procedure printStack(s : stacktype); var i : Integer; begin writeln('------------------------------------------'); for i := size - 1 downto 0 do writeln(s.data[i]: 10); writeln('------------------------------------------'); end; begin writeln('Stack:'); init(stack); repeat WriteLn; writeln('1.Push data') ; writeln('2.Pop data'); write('> '); readln(response); if response = '1' then begin if not isFull(stack) then begin write('Enter the data to push > '); readln(x); push(stack, x); end else begin TextColor(Red); writeln('Stack overflow may occur :)'); TextColor(lightgray); end; end else if response = '2' then begin if not isEmpty(stack) then begin pop(stack, x); writeln('Pop data is ', x); end else begin TextColor(Red); WriteLn('Stack underflow may occur :/'); TextColor(lightgray); end; end; printStack(stack); until upcase(response) = 'EXIT'; end.
unit RDOProtocol; interface // Constants and functions used in the textual protocol const SelObjCmd = 'sel'; IdOfCmd = 'idof'; GetPropCmd = 'get'; SetPropCmd = 'set'; CallMethCmd = 'call'; const ErrorKeyWord = 'error'; ResultVarName = 'res'; ByRefParName = 'bref'; ObjIdVarName = 'objid'; const NameValueSep = '='; LiteralDelim = '"'; Quote = ''''; ParamDelim = ','; QueryTerm = ';'; Blank = ' '; const OrdinalId = '#'; SingleId = '!'; DoubleId = '@'; StringId = '$'; OLEStringId = '%'; VariantId = '^'; VoidId = '*'; const NormPrio = 'N'; AboveNormPrio = 'A'; BelowNormPrio = 'B'; HighestPrio = 'H'; IdlePrio = 'I'; LowestPrio = 'L'; TimeCritPrio = 'C'; const CallID = 'C'; AnswerID = 'A'; const WhiteSpace = [ #9, #10, #13, #32 ]; implementation end.
unit Model.EstoqueInsumos; interface type TEstoqueInsumos = class private var FID: Integer; FInsumo: Integer; FData: System.TDate; FQtde: Double; FUnitario: Double; FTotal: Double; FLog: String; public property ID: Integer read FID write FID; property Insumo: Integer read FInsumo write FInsumo; property Data: System.TDate read FData write FData; property Qtde: Double read FQtde write FQtde; property Unitario: Double read FUnitario write FUnitario; property Total: Double read FTotal write FTotal; property Log: String read FLog write FLog; constructor Create; overload; constructor Create(pFID: Integer; pFInsumo: Integer; pFData: System.TDate; pFQtde: Double; pFUnitario: Double; pFTotal: Double; pFLog: String); overload; end; implementation constructor TEstoqueInsumos.Create; begin inherited Create; end; constructor TEstoqueInsumos.Create(pFID: Integer; pFInsumo: Integer; pFData: System.TDate; pFQtde: Double; pFUnitario: Double; pFTotal: Double; pFLog: String); begin FID := pFID; FInsumo := pFInsumo; FData := pFData; FQtde := pFQtde; FUnitario := pFUnitario; FTotal := pFTotal; FLog := pFLog; end; end.
(**************************************************************************** * * WinLIRC plug-in for jetAudio * * Copyright (c) 2016 Tim De Baets * **************************************************************************** * * 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. * **************************************************************************** * * jetAudio User32.dll API hook * ****************************************************************************) unit UserHook; interface uses Windows, Messages, SysUtils, Common2; type TTrackPopupMenuEx = function(hMenu: HMENU; Flags: UINT; x, y: Integer; hWnd: HWND; TPMParams: Pointer): BOOL; stdcall; type TUserFunc = (TrackPopupMenuEx); TUserFuncAddresses = array[TUserFunc] of Pointer; const UserFuncNames: array[TUserFunc] of PChar = ('TrackPopupMenuEx'); var PrevUserFuncs: TUserFuncAddresses; UserFuncs: TUserFuncAddresses; implementation uses ApiHook, JFLircPluginClass; function NewTrackPopupMenuEx(hMenu: HMENU; Flags: UINT; x, y: Integer; hWnd: HWND; TPMParams: Pointer): BOOL; stdcall; var MenuId: Integer; begin Result := False; try if Assigned(JFLircPlugin) then begin MenuId := JFLircPlugin.FakeContextMenuId; if MenuId <> 0 then begin Result := BOOL(MenuId); SetLastError(0); Exit; end; end; Result := TTrackPopupMenuEx(PrevUserFuncs[TrackPopupMenuEx])(hMenu, Flags, x, y, hWnd, TPMParams); except on E: Exception do OutException(E, 'NewTrackPopupMenu'); end; end; initialization FillChar(PrevUserFuncs, SizeOf(PrevUserFuncs), 0); UserFuncs[TrackPopupMenuEx] := @NewTrackPopupMenuEx; end.
unit Model.TiposVerbasExpressas; interface uses Common.ENum, FireDAC.Comp.Client, Control.Sistema, DAO.Conexao; type TTiposVerbasExpressas = class private FAcao: TAcao; FDescricao: String; FCodigo: Integer; FColunas: String; FConexao: TConexao; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; public constructor Create(); property Codigo: Integer read FCodigo write FCodigo; property Descricao: String read FDescricao write FDescricao; property Colunas: String read FColunas write FColunas; property Acao: TAcao read FAcao write FAcao; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function RetornaListaSimples(memTable: TFDMemTable): boolean; function GetField(sField: String; sKey: String; sKeyValue: String): String; end; const TABLENAME = 'expressas_tipos_verbas'; implementation { TTiposVerbasExpressas } constructor TTiposVerbasExpressas.Create; begin FConexao := TConexao.Create; end; function TTiposVerbasExpressas.Delete: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_tipo = :pcod_tipo', [Codigo]); Result := True; finally FDQuery.Connection.Close; FDquery.Free; end; end; function TTiposVerbasExpressas.GetField(sField, sKey, sKeyValue: String): String; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Text := 'select ' + sField + ' from ' + TABLENAME + ' where ' + sKey + ' = ' + sKeyValue; FDQuery.Open(); if not FDQuery.IsEmpty then Result := FDQuery.FieldByName(sField).AsString; finally FDQuery.Free; end; end; function TTiposVerbasExpressas.Gravar: Boolean; begin case FAcao of tacIncluir: Insert(); tacAlterar: Update(); tacExcluir: Delete(); end; end; function TTiposVerbasExpressas.Insert: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('insert into ' + TABLENAME + ' (cod_tipo, des_tipo, des_colunas) ' + 'values ' + '(:pcod_tipo, :pdes_tipo, :pdes_colunas);', [Codigo, Descricao, Colunas]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TTiposVerbasExpressas.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin if Length(aParam) < 2 then Exit; FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('where cod_tipo = :pcod_tipo'); FDQuery.ParamByName('pcod_tipo').AsInteger := aParam[1]; end; if aParam[0] = 'DESCRICAO' then begin FDQuery.SQL.Add('where des_tipo like :pdes_tipo'); FDQuery.ParamByName('pdes_tipo').AsInteger := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); Result := FDQuery; end; function TTiposVerbasExpressas.RetornaListaSimples(memTable: TFDMemTable): boolean; var aParam: array of Variant; fdQuery: TFDQuery; begin try Result := False; fdQuery := FConexao.ReturnQuery; SetLength(aParam,3); aParam := ['APOIO','cod_tipo, des_tipo, des_colunas','']; fdQuery := Localizar(aParam); Finalize(aParam); if not fdQuery.IsEmpty then begin memTable.Data := fdQuery.Data; end; Result := True; finally fdQuery.Close; fdQuery.Connection.Close; fdQuery.Free; end; end; function TTiposVerbasExpressas.Update: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('update ' + TABLENAME + 'set ' + 'cod_tipo = :pcod_tipo, des_tipo = :pdes_tipo, des_colunas = :pdes_colunas ' + 'where ' + 'cod_tipo = :pcod_tipo;', [Descricao, Colunas, Codigo]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit ObjList; { $Id: ObjList.pas,v 1.12 2016/06/16 05:38:41 lukyanets Exp $ } interface uses WinTypes, l3DatLst, DragData, DocIntf, DT_Dict, DT_Active; type TDragDataType = (ddNone, ddDragObj, ddHyperLink, ddBackHyperLink, ddDoc, ddSrchObj, ddSrchID, ddDictItem, ddMailDocLink); PSrchObjAddr = ^TSrchObjAddr; TSrchObjAddr = Pointer; PSrchIDAddr = ^TSrchIDAddr; TSrchIDAddr = Longint; PDictItemAddr = ^TDictItemAddr; TDictItemAddr = Record FamID : Longint; DictID : Longint; ItemID : Longint; ItemTag : Pointer; end; TArchiObjectList = Class(Tl3StringDataList) private fMonoObjType : TDragDataType; procedure DragStopNotify(Sender: TObject); procedure RunDrag; public constructor Create; override; procedure AddObjRec(aName : PAnsiChar; aType : TDragDataType; aDataRec : PAnsiChar; aAddDataSize : Cardinal = 0); end; var ArchiObjectList : TArchiObjectList; function CursorByType(DDType : Integer) : HCursor; export; implementation uses SysUtils, Forms, Controls, DT_Const, daTypes, l3Base, ResShop; function CursorByType(DDType : Integer) : HCursor; begin case TDragDataType(DDType) of ddNone : Result := Screen.Cursors[crDefault]; ddDragObj : Result := Screen.Cursors[crDragObj]; ddHyperLink : Result := Screen.Cursors[crLink]; ddBackHyperLink : Result := Screen.Cursors[crSubLink]; ddMailDocLink : Result := Screen.Cursors[crLink]; else Result := Screen.Cursors[crDragObj]; end; end; {TArchiObjectList} constructor TArchiObjectList.Create; begin inherited Create; SetDataSize(SizeOf(TDictItemAddr) + 1); NeedAllocStr := True; NeedDisposeStr := True; end; procedure TArchiObjectList.AddObjRec(aName : PAnsiChar; aType : TDragDataType; aDataRec : PAnsiChar; aAddDataSize : Cardinal = 0); var I : Longint; ItData : PAnsiChar; lRecSize : Integer; begin if Count = 0 then begin fMonoObjType := aType; RunDrag; end else if fMonoObjType <> aType then fMonoObjType := ddDragObj; TDragDataSupport.Instance.DragDataType := Ord(fMonoObjType); I := Add(aName); if aAddDataSize = 0 then case aType of ddDoc : lRecSize := SizeOf(TdaGlobalCoordinateRec); ddSrchObj : lRecSize := SizeOf(TSrchObjAddr); ddSrchID : lRecSize := SizeOf(TSrchIDAddr ); ddDictItem : lRecSize := SizeOf(TDictItemAddr); ddBackHyperLink : lRecSize := SizeOf(TdaGlobalCoordinateRec); else lRecSize := SizeOf(TdaGlobalCoordinateRec); end else lRecSize := SizeOf(TDictItemAddr) + aAddDataSize; ItData := Data[I]; ItData[0] := AnsiChar(aType); StrMove(ItData + 1, aDataRec, lRecSize); end; procedure TArchiObjectList.RunDrag; begin with TDragDataSupport.Instance do begin DragData := Self; RunDragData(nil); OnDragStop := DragStopNotify; end; end; procedure TArchiObjectList.DragStopNotify(Sender: TObject); var I : Longint; l_ItemTag: Pointer; begin for I := 0 to pred(Count) do if (TDragDataType(Data[I][0]) = ddDictItem) then begin l_ItemTag := PDictItemAddr(Data[I] + 1)^.ItemTag; if l_ItemTag <> nil then IUnknown(l_ItemTag)._Release; end; // if (TDragDataType(Data[I][0]) = ddDictItem) then Clear; TDragDataSupport.Instance.OnDragStop := nil; end; (*************) procedure FinitArchiObjectList; Far; begin l3Free(ArchiObjectList); end; initialization AddExitProc(FinitArchiObjectList); ArchiObjectList := TArchiObjectList.Create; TDragDataSupport.Instance.OnGetCursorByType := CursorByType; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Description: TIcsBufferHandler is a class which encapsulate a data fifo to be used for TWSocket. Fifo is implemented using two doubly linked list of buffers. One linked list contain the buffers filled with data while the other contain the buffers already emptyed. When a buffer is emptyed it is placed in the free list. When a buffer is needed to hold more data, it is taken from the free list, if any, or a new one is created. Creation: June 11, 2006 (Built from basic version created in april 1996) Version: 6.02 (Initial version was 6.01 to match TWSocket version) EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1996-2011 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Updates: Mar 06, 1998 V2.00 Added a property and a parameter for the create method to select the buffer size. Using a 0 value will make the object use the default 1514 bytes (the largest size for an ethernet packet). Jul 08, 1998 V2.01 Adadpted for Delphi 4 Jan 19, 2003 V5.00 First pre-release for ICS-SSL. New major version number. Skipped version numbers to mach wsocket.pas major version number. Apr 17, 2004 V6.00 New major release started. Move all platform and runtime dependencies to separate units. New base component for handling component with window handle. Jan 26, 2004 V5.01 Use ICSDEFS.INC and reordered uses clause for FPC compatibility. May 23, 2005 V6.00b Added BufUsed property. Mar 25, 2006 V6.00c Fixed TBuffer.Write to correctly use the offset. Thanks to Frans van Daalen <ics@hedaal.nl> for providing a test case. June 11, 2006 V6.01 New version with TIcsBufferHandler. Take all of the buffer handling out of TWSocket. Apr 15, 2011 V6.02 Arno prepared for 64-bit. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsWSockBuf; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$I OverbyteIcsDefs.inc} {$IFDEF COMPILER14_UP} {$IFDEF NO_EXTENDED_RTTI} {$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])} {$ENDIF} {$ENDIF} {$IFDEF DELPHI6_UP} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} {$IFNDEF VER80} { Not for Delphi 1 } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF BCB3_UP} {$ObjExportAll On} {$ENDIF} interface uses {$IFDEF CLR} System.ComponentModel, System.IO, Windows, Classes, {$ELSE} Contnrs, {$ENDIF} {$IFDEF MSWINDOWS} Windows, {$ENDIF} SysUtils, OverbyteIcsTypes, OverbyteIcsLibrary; const WSockBufVersion = 602; CopyRight : String = ' TWSockBuf (c) 1996-2011 Francois Piette V6.02 '; type {$IFDEF CLR} TWSocketData = TBytes; {$ELSE} TWSocketData = type Pointer; {$ENDIF} TIcsBuffer = class(TObject) protected Buf : TWSocketData; FBufSize : Integer; WrCount : Integer; RdCount : Integer; FNext : TIcsBuffer; FPrev : TIcsBuffer; function GetBufUsed : Integer; procedure SetBufSize(newSize : Integer); public constructor Create(nSize : Integer); virtual; destructor Destroy; override; function Write(const Data : TWSocketData; Len : Integer) : Integer; overload; function Write(const Data : TWSocketData; Offset : Integer; Len : Integer) : Integer; overload; function Read(out Data : TWSocketData; Len : Integer) : Integer; function Peek(var Len : Integer) : TWSocketData; overload; function Peek(out Data : TWSocketData) : Integer; overload; function Remove(Len : Integer) : Integer; property BufSize : Integer read FBufSize write SetBufSize; property BufUsed : Integer read GetBufUsed; end; TIcsBufferLinkedList = class(TObject) protected Head : TIcsBuffer; Tail : TIcsBuffer; public destructor Destroy; override; procedure AddToListHead(Buf : TIcsBuffer); function RemoveFromListHead: TIcsBuffer; procedure AddToListTail(Buf: TIcsBuffer); end; {$IFDEF CLR} [DesignTimeVisibleAttribute(TRUE)] TIcsBufferHandler = class(System.ComponentModel.Component) {$ELSE} type TIcsBufferHandler = class(TComponent) {$ENDIF} protected FInUseList : TIcsBufferLinkedList; FFreeList : TIcsBufferLinkedList; FBufSize : Integer; FCritSect : TRTLCriticalSection; function GetBuffer: TIcsBuffer; public constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Lock; procedure UnLock; procedure Write(const Data : TWSocketData; Len : Integer); overload; procedure Write(const Data : TWSocketData; Offset : Integer; Len : Integer); overload; function Peek(var Len : Integer) : TWSocketData; overload; function Peek(out Data : TWSocketData) : Integer; overload; procedure Remove(Len : Integer); procedure DeleteAllData; function IsEmpty : Boolean; published property BufSize : Integer read FBufSize write FBufSize; end; function IncPtr(P : Pointer; N : Integer = 1): Pointer; {$IFDEF USE_INLINE} inline; {$ENDIF} implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function IncPtr(P : Pointer; N : Integer = 1): Pointer; begin Result := PAnsiChar(P) + N; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TIcsBuffer.Create(nSize : Integer); begin // OutputDebugString('TIcsBuffer.Create'); inherited Create; WrCount := 0; RdCount := 0; SetBufSize(nSize); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TIcsBuffer.Destroy; begin // OutputDebugString('TIcsBuffer.Destroy'); {$IFNDEF CLR} if Assigned(Buf) then FreeMem(Buf, FBufSize); {$ENDIF} inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBuffer.SetBufSize(newSize : Integer); {$IFNDEF CLR} var newBuf : TWSocketData; {$ENDIF} begin if newSize <= 0 then newSize := 1460; if newSize = FBufSize then Exit; {$IFDEF CLR} FBufSize := newSize; SetLength(Buf, FBufSize); {$ELSE} if WrCount = RdCount then begin // Buffer is empty if Assigned(Buf) then FreeMem(Buf, FBufSize); FBufSize := newSize; if FBufSize > 0 then GetMem(Buf, FBufSize) else Buf := nil; end else begin // Buffer contains data if newSize > 0 then begin GetMem(newBuf, newSize); Move(Buf^, newBuf^, WrCount); end else newBuf := nil; if Assigned(Buf) then FreeMem(Buf, FBufSize); FBufSize := newSize; Buf := newBuf; end; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBuffer.Write(const Data : TWSocketData; Len : Integer) : Integer; begin Result := Write(Data, 0, Len); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBuffer.Write(const Data: TWSocketData; Offset, Len: Integer): Integer; var Remaining : Integer; Copied : Integer; {$IFDEF CLR} I : Integer; {$ENDIF} begin Remaining := FBufSize - WrCount; if Remaining <= 0 then Result := 0 else begin if Len <= Remaining then Copied := Len else Copied := Remaining; {$IFDEF CLR} for I := 0 to Copied - 1 do Buf[WrCount + I] := Data[Offset + I]; {$ELSE} Move(IncPtr(Data, Offset)^, IncPtr(Buf, WrCount)^, Copied); {$ENDIF} WrCount := WrCount + Copied; Result := Copied; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBuffer.Read(out Data : TWSocketData; Len : Integer) : Integer; var Remaining : Integer; Copied : Integer; {$IFDEF CLR} I : Integer; {$ENDIF} begin Remaining := WrCount - RdCount; if Remaining <= 0 then Result := 0 else begin if Len <= Remaining then Copied := Len else Copied := Remaining; {$IFDEF CLR} for I := 0 to Copied - 1 do Data[I] := Buf[RdCount + I]; {$ELSE} Move(IncPtr(Buf, RdCount)^, Data^, Copied); {$ENDIF} RdCount := RdCount + Copied; if RdCount = WrCount then begin RdCount := 0; WrCount := 0; end; Result := Copied; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBuffer.Peek(var Len : Integer) : TWSocketData; var Remaining : Integer; {$IFDEF CLR} I : Integer; {$ENDIF} begin Remaining := WrCount - RdCount; if Remaining <= 0 then begin Len := 0; Result := nil; end else begin Len := Remaining; {$IFDEF CLR} SetLength(Result, Len); for I := 0 to Len - 1 do Result[I] := Buf[I]; {$ELSE} Result := IncPtr(Buf, RdCount); {$ENDIF} end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFNDEF CLR} function TIcsBuffer.Peek(out Data: TWSocketData): Integer; var Remaining : Integer; begin Remaining := WrCount - RdCount; if Remaining <= 0 then begin Result := 0; end else begin Data := IncPtr(Buf, RdCount); Result := Remaining; end; end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF CLR} function TIcsBuffer.Peek(out Data: TWSocketData): Integer; var Remaining : Integer; I : Integer; begin Remaining := WrCount - RdCount; if Remaining <= 0 then begin SetLength(Data, 0); Result := 0; end else begin // With .NET, we must copy the data SetLength(Data, Remaining); for I := 0 to Remaining - 1 do Data[I] := Buf[RdCount + I]; Result := Remaining; end; end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBuffer.Remove(Len : Integer) : Integer; var Remaining : Integer; Removed : Integer; begin Remaining := WrCount - RdCount; if Remaining <= 0 then Result := 0 else begin if Len < Remaining then Removed := Len else Removed := Remaining; RdCount := RdCount + Removed; if RdCount = WrCount then begin RdCount := 0; WrCount := 0; end; Result := Removed; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBuffer.GetBufUsed: Integer; begin Result := WrCount - RdCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { TIcsBufferHandler } constructor TIcsBufferHandler.Create(AOwner: TComponent); begin inherited Create(AOwner); FInUseList := TIcsBufferLinkedList.Create; FFreeList := TIcsBufferLinkedList.Create; FBufSize := 1460; InitializeCriticalSection(FCritSect); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TIcsBufferHandler.Destroy; begin FreeAndNil(FInUseList); FreeAndNil(FFreeList); DeleteCriticalSection(FCritSect); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferLinkedList.AddToListHead(Buf : TIcsBuffer); begin if not Assigned(Head) then begin Head := Buf; Tail := Buf; Buf.FNext := nil; Buf.FPrev := nil; end else begin Head.FPrev := Buf; Buf.FPrev := nil; Buf.FNext := Head; Head := Buf; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferLinkedList.AddToListTail(Buf : TIcsBuffer); begin if not Assigned(Tail) then begin Tail := Buf; Head := Buf; Buf.FPrev := nil; Buf.FNext := nil; end else begin Tail.FNext := Buf; Buf.FPrev := Tail; Buf.FNext := nil; Tail := Buf; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TIcsBufferLinkedList.Destroy; var Buf1, Buf2 : TIcsBuffer; begin Buf1 := Head; while Assigned(Buf1) do begin Buf2 := Buf1.FNext; Buf1.Free; Buf1 := Buf2; end; Head := nil; inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferLinkedList.RemoveFromListHead: TIcsBuffer; begin Result := Head; if Assigned(Result) then begin Head := Result.FNext; if Assigned(Head) then Head.FPrev := nil else Tail := nil; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferHandler.GetBuffer: TIcsBuffer; begin if Assigned(FFreeList.Head) then Result := FFreeList.RemoveFromListHead // Reuse any free buffer else Result := TIcsBuffer.Create(FBufSize); FInUseList.AddToListTail(Result); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferHandler.DeleteAllData; var Buf : TIcsBuffer; begin Buf := FInUseList.RemoveFromListHead; while Assigned(Buf) do begin Buf.RdCount := 0; // Clear data Buf.WrCount := 0; FFreeList.AddToListHead(Buf); // Put in free list Buf := FInUseList.RemoveFromListHead; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferHandler.IsEmpty: Boolean; begin Result := (FInUseList.Head = nil) or (FInUseList.Head.GetBufUsed = 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferHandler.Lock; begin EnterCriticalSection(FCritSect); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferHandler.UnLock; begin LeaveCriticalSection(FCritSect); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferHandler.Peek(var Len: Integer): TWSocketData; begin if not Assigned(FInUseList.Head) then begin Len := 0; Result := nil; end else Result := FInUseList.Head.Peek(Len); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TIcsBufferHandler.Peek(out Data: TWSocketData): Integer; begin if not Assigned(FInUseList.Head) then Result := 0 else Result := FInUseList.Head.Peek(Data); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferHandler.Remove(Len: Integer); var Buf : TIcsBuffer; begin if Len < 0 then raise Exception.Create('TIcsBufferHandler.Remove: Invalid Len ' + IntToStr(Len)); if not Assigned(FInUseList.Head) then raise Exception.Create('TIcsBufferHandler.Remove: nothing to remove'); Buf := FInUseList.Head; Buf.Remove(Len); if Buf.GetBufUsed = 0 then begin Buf := FInUseList.RemoveFromListHead; FFreeList.AddToListHead(Buf); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferHandler.Write( const Data : TWSocketData; Len : Integer); begin Write(Data, 0, Len); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TIcsBufferHandler.Write( const Data : TWSocketData; Offset : Integer; Len : Integer); var oBuffer : TIcsBuffer; iOffset : Integer; bMore : Boolean; cWritten : Integer; begin if not Assigned(FInUseList.Tail) then oBuffer := GetBuffer else oBuffer := FInUseList.Tail; iOffset := 0; bMore := TRUE; while bMore do begin cWritten := oBuffer.Write(Data, iOffset, Len); if cWritten >= Len then bMore := FALSE else begin Len := Len - cWritten; Inc(iOffset, cWritten); if Len < 0 then bMore := FALSE else begin oBuffer := GetBuffer; end; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit AutoMapper.MapEngine; interface uses AutoMapper.CfgMapper , AutoMapper.TypePair , AutoMapper.MapItem , AutoMapper.MappingExpression , AutoMapper.Exceptions ; type TMapEngine = class private FCfgMapper: TCfgMapper; function CreateInstance<TDestination>: TDestination; function GetExpression<TSource, TDestination>: TMapExpression<TSource, TDestination>; overload; public constructor Create(const ACfgMapper: TCfgMapper); destructor Destroy; override; function Map<TSource; TDestination>(const source: TSource): TDestination; overload; function Map<TSource; TDestination>(const source: TSource; const MapExpression: TMapExpression<TSource, TDestination>): TDestination; overload; function Map<TDestination>(const source: TObject): TDestination; overload; function Map<TDestination>(const source: TObject; const MapExpression: TMapExpression<TObject, TDestination>): TDestination; overload; end; implementation uses System.Rtti , System.TypInfo , System.SysUtils ; { TMapEngine } constructor TMapEngine.Create(const ACfgMapper: TCfgMapper); begin FCfgMapper := ACfgMapper; end; function TMapEngine.CreateInstance<TDestination>: TDestination; var Ctx: TRttiContext; RttiType: TRttiType; RttiInstance: TRttiInstanceType; DestObj: TObject absolute result; begin Ctx := TRttiContext.Create; RttiType := Ctx.GetType(TypeInfo(TDestination)); RttiInstance := RttiType.AsInstance; DestObj := RttiInstance.MetaclassType.Create; Ctx.Free; end; destructor TMapEngine.Destroy; begin FCfgMapper := nil; inherited; end; function TMapEngine.GetExpression<TSource, TDestination>: TMapExpression<TSource, TDestination>; var Map: TMap; ExpValue: TValue; Exp: TMapExpression<TSource, TDestination>; TypePair: TTypePair; begin TypePair := TTypePair.New<TSource, TDestination>; if not FCfgMapper.TryGetMap(TypePair, Map) then begin if not (TMapperSetting.Automap in FCfgMapper.Settings) then raise TGetMapItemException.Create(Format(CS_GET_MAPITEM_NOT_FOUND, [TypePair.SourceType, TypePair.DestinationType])); FCfgMapper.CreateMap<TSource, TDestination>(); FCfgMapper.TryGetMap(TTypePair.New<TSource, TDestination>, Map); end; Map.Exp.ExtractRawData(@Exp); Result := Exp; end; function TMapEngine.Map<TDestination>(const source: TObject): TDestination; var Ctx: TRttiContext; TypePair: TTypePair; Map: TMap; Exp: TMapExpression<TObject, TDestination>; Destination: TDestination; begin Ctx := TRttiContext.Create; TypePair := TypePair.Create(Ctx.GetType(source.ClassType).QualifiedName, Ctx.GetType(TypeInfo(TDestination)).QualifiedName); if not FCfgMapper.TryGetMap(TypePair, Map) then raise TGetMapItemException.Create(Format(CS_GET_MAPITEM_NOT_FOUND, [TypePair.SourceType, TypePair.DestinationType])); if Ctx.GetType(TypeInfo(TDestination)).IsInstance then Destination := CreateInstance<TDestination>(); Map.Exp.ExtractRawData(@Exp); Exp(source, Destination); Result := Destination; end; function TMapEngine.Map<TDestination>(const source: TObject; const MapExpression: TMapExpression<TObject, TDestination>): TDestination; var Ctx: TRttiContext; Destination: TDestination; begin Ctx := TRttiContext.Create; if Ctx.GetType(TypeInfo(TDestination)).IsInstance then Destination := CreateInstance<TDestination>(); MapExpression(source, Destination); Result := Destination; end; function TMapEngine.Map<TSource, TDestination>(const source: TSource; const MapExpression: TMapExpression<TSource, TDestination>): TDestination; var Ctx: TRttiContext; Destination: TDestination; begin Ctx := TRttiContext.Create; if Ctx.GetType(TypeInfo(TDestination)).IsInstance then Destination := CreateInstance<TDestination>(); MapExpression(source, Destination); Result := Destination; end; function TMapEngine.Map<TSource, TDestination>(const source: TSource): TDestination; var Ctx: TRttiContext; Destination: TDestination; Exp: TMapExpression<TSource, TDestination>; begin Exp := GetExpression<TSource, TDestination>(); Ctx := TRttiContext.Create; if Ctx.GetType(TypeInfo(TDestination)).IsInstance then Destination := CreateInstance<TDestination>(); Exp(source, Destination); Result := Destination; end; end.
{ Date Created: 6/2/00 4:10:37 PM } unit InfoTRANCODE_NEWTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoTRANCODE_NEWRecord = record PCode: String[2]; PDescription: String[30]; PGroup: Integer; PCertificateCoverage: Boolean; PActive: Boolean; End; TInfoTRANCODE_NEWBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoTRANCODE_NEWRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoTRANCODE_NEW = (InfoTRANCODE_NEWPrimaryKey); TInfoTRANCODE_NEWTable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFGroup: TIntegerField; FDFCertificateCoverage: TBooleanField; FDFActive: TBooleanField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPGroup(const Value: Integer); function GetPGroup:Integer; procedure SetPCertificateCoverage(const Value: Boolean); function GetPCertificateCoverage:Boolean; procedure SetPActive(const Value: Boolean); function GetPActive:Boolean; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoTRANCODE_NEW); function GetEnumIndex: TEIInfoTRANCODE_NEW; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoTRANCODE_NEWRecord; procedure StoreDataBuffer(ABuffer:TInfoTRANCODE_NEWRecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFGroup: TIntegerField read FDFGroup; property DFCertificateCoverage: TBooleanField read FDFCertificateCoverage; property DFActive: TBooleanField read FDFActive; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PGroup: Integer read GetPGroup write SetPGroup; property PCertificateCoverage: Boolean read GetPCertificateCoverage write SetPCertificateCoverage; property PActive: Boolean read GetPActive write SetPActive; published property Active write SetActive; property EnumIndex: TEIInfoTRANCODE_NEW read GetEnumIndex write SetEnumIndex; end; { TInfoTRANCODE_NEWTable } procedure Register; implementation function TInfoTRANCODE_NEWTable.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 { TInfoTRANCODE_NEWTable.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; { TInfoTRANCODE_NEWTable.GenerateNewFieldName } function TInfoTRANCODE_NEWTable.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; { TInfoTRANCODE_NEWTable.CreateField } procedure TInfoTRANCODE_NEWTable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFGroup := CreateField( 'Group' ) as TIntegerField; FDFCertificateCoverage := CreateField( 'CertificateCoverage' ) as TBooleanField; FDFActive := CreateField( 'Active' ) as TBooleanField; end; { TInfoTRANCODE_NEWTable.CreateFields } procedure TInfoTRANCODE_NEWTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoTRANCODE_NEWTable.SetActive } procedure TInfoTRANCODE_NEWTable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoTRANCODE_NEWTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoTRANCODE_NEWTable.SetPGroup(const Value: Integer); begin DFGroup.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPGroup:Integer; begin result := DFGroup.Value; end; procedure TInfoTRANCODE_NEWTable.SetPCertificateCoverage(const Value: Boolean); begin DFCertificateCoverage.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPCertificateCoverage:Boolean; begin result := DFCertificateCoverage.Value; end; procedure TInfoTRANCODE_NEWTable.SetPActive(const Value: Boolean); begin DFActive.Value := Value; end; function TInfoTRANCODE_NEWTable.GetPActive:Boolean; begin result := DFActive.Value; end; procedure TInfoTRANCODE_NEWTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 2, N'); Add('Description, String, 30, N'); Add('Group, Integer, 0, N'); Add('CertificateCoverage, Boolean, 0, N'); Add('Active, Boolean, 0, N'); end; end; procedure TInfoTRANCODE_NEWTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoTRANCODE_NEWTable.SetEnumIndex(Value: TEIInfoTRANCODE_NEW); begin case Value of InfoTRANCODE_NEWPrimaryKey : IndexName := ''; end; end; function TInfoTRANCODE_NEWTable.GetDataBuffer:TInfoTRANCODE_NEWRecord; var buf: TInfoTRANCODE_NEWRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PGroup := DFGroup.Value; buf.PCertificateCoverage := DFCertificateCoverage.Value; buf.PActive := DFActive.Value; result := buf; end; procedure TInfoTRANCODE_NEWTable.StoreDataBuffer(ABuffer:TInfoTRANCODE_NEWRecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFGroup.Value := ABuffer.PGroup; DFCertificateCoverage.Value := ABuffer.PCertificateCoverage; DFActive.Value := ABuffer.PActive; end; function TInfoTRANCODE_NEWTable.GetEnumIndex: TEIInfoTRANCODE_NEW; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoTRANCODE_NEWPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoTRANCODE_NEWTable, TInfoTRANCODE_NEWBuffer ] ); end; { Register } function TInfoTRANCODE_NEWBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('CODE','DESCRIPTION','GROUP','CERTIFICATECOVERAGE','ACTIVE' ); 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 TInfoTRANCODE_NEWBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftInteger; 4 : result := ftBoolean; 5 : result := ftBoolean; end; end; function TInfoTRANCODE_NEWBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; 3 : result := @Data.PGroup; 4 : result := @Data.PCertificateCoverage; 5 : result := @Data.PActive; end; end; end.
unit RVScroll; interface uses {$IFDEF FPC} RVLazIntf, LCLType, LCLIntf, {$ELSE} Windows, Messages, {$ENDIF} SysUtils, Classes, Forms, Controls, Graphics; type { TRVScroller } TRVScroller = class(TCustomControl) private FTracking: Boolean; FFullRedraw: Boolean; FVScrollVisible: Boolean; FOnVScrolled: TNotifyEvent; function GetVScrollPos: Integer; procedure SetVScrollPos(Pos: Integer); function GetVScrollMax: Integer; procedure SetVScrollVisible(vis: Boolean); protected SmallStep, HPos, VPos, XSize, YSize: Integer; procedure CreateParams(var Params: TCreateParams); //override; procedure CreateWnd; override; procedure UpdateScrollBars(XS, YS: Integer); procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN; procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE; procedure SetVPos(p: Integer); procedure SetHPos(p: Integer); procedure Paint; override; procedure ScrollChildren(dx, dy: Integer); procedure UpdateChildren; property FullRedraw: Boolean read FFullRedraw write FFullRedraw; protected // to be publised properties property Visible; property TabStop; property TabOrder; property Align; property HelpContext; property Tracking: Boolean read FTracking write FTracking; property VScrollVisible: Boolean read FVScrollVisible write SetVScrollVisible; property OnVScrolled: TNotifyEvent read FOnVScrolled write FOnVScrolled; public { Public declarations } constructor Create(AOwner: TComponent);override; procedure EraseBackground(DC: HDC); override; procedure ScrollTo(y: Integer); property VScrollPos: Integer read GetVScrollPos write SetVScrollPos; property VScrollMax: Integer read GetVScrollMax; end; procedure Tag2Y(AControl: TControl); implementation {------------------------------------------------------} procedure Tag2Y(AControl: TControl); begin if AControl.Tag>10000 then AControl.Top := 10000 else if AControl.Tag<-10000 then AControl.Top := -10000 else AControl.Top := AControl.Tag; end; {------------------------------------------------------} constructor TRVScroller.Create(AOwner: TComponent); begin inherited Create(AOwner); TabStop := True; FTracking := True; FFullRedraw := False; FVScrollVisible := True; end; procedure TRVScroller.EraseBackground(DC: HDC); begin end; {------------------------------------------------------} procedure TRVScroller.CreateParams(var Params: TCreateParams); begin //inherited CreateParams(Params); //CreateWindow Params.Style := Params.Style or WS_CLIPCHILDREN or WS_HSCROLL or WS_VSCROLL; end; {------------------------------------------------------} procedure TRVScroller.CreateWnd; begin inherited CreateWnd; SmallStep := 10; VPos := 0; HPos := 0; UpdateScrollBars(ClientWidth, (ClientHeight div SmallStep)); end; {------------------------------------------------------} procedure TRVScroller.UpdateScrollBars(XS, YS: Integer); var ScrollInfo: TScrollInfo; begin XSize := XS; YSize := YS; ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.fMask := SIF_ALL; ScrollInfo.nMin := 0; ScrollInfo.nPage := ClientHeight div SmallStep; ScrollInfo.nMax := YSize; ScrollInfo.nPos := VPos; ScrollInfo.nTrackPos := 0; SetScrollInfo(Handle, SB_VERT, ScrollInfo, True); if not FVScrollVisible then ShowScrollBar(Handle, SB_VERT, FVScrollVisible); ScrollInfo.fMask := SIF_ALL; ScrollInfo.nMin := 0; ScrollInfo.nMax := XSize-1; ScrollInfo.nPage := ClientWidth; ScrollInfo.nPos := VPos; ScrollInfo.nTrackPos := 0; SetScrollInfo(Handle, SB_HORZ, ScrollInfo, True); //UpdateChildren; end; {------------------------------------------------------} procedure TRVScroller.UpdateChildren; var i: Integer; begin for i:=0 to ControlCount-1 do Tag2Y(Controls[i]); end; {------------------------------------------------------} procedure TRVScroller.ScrollChildren(dx, dy: Integer); var i: Integer; begin if (dx=0) and (dy=0) then exit; for i:=0 to ControlCount-1 do begin if dy<>0 then begin Controls[i].Tag := Controls[i].Tag+dy; Tag2Y(Controls[i]); end; if dx<>0 then Controls[i].Left := Controls[i].Left + dx; end end; {------------------------------------------------------} procedure TRVScroller.WMHScroll(var Message: TWMHScroll); begin with Message do case ScrollCode of SB_LINEUP: SetHPos(HPos - SmallStep); SB_LINEDOWN: SetHPos(HPos + SmallStep); SB_PAGEUP: SetHPos(HPos-10*SmallStep); SB_PAGEDOWN: SetHPos(HPos+10*SmallStep); SB_THUMBPOSITION: SetHPos(Pos); SB_THUMBTRACK: if FTracking then SetHPos(Pos); SB_TOP: SetHPos(0); SB_BOTTOM: SetHPos(XSize); end; end; {------------------------------------------------------} procedure TRVScroller.WMVScroll(var Message: TWMVScroll); begin with Message do case ScrollCode of SB_LINEUP: SetVPos(VPos - 1); SB_LINEDOWN: SetVPos(VPos + 1); SB_PAGEUP: SetVPos(VPos-10); SB_PAGEDOWN: SetVPos(VPos+10); SB_THUMBPOSITION: SetVPos(Pos); SB_THUMBTRACK: if FTracking then SetVPos(Pos); SB_TOP: SetVPos(0); SB_BOTTOM: SetVPos(YSize); end; end; {------------------------------------------------------} procedure TRVScroller.WMKeyDown(var Message: TWMKeyDown); var vScrollNotify, hScrollNotify: Integer; begin vScrollNotify := -1; hScrollNotify := -1; with Message do case CharCode of VK_UP: vScrollNotify := SB_LINEUP; VK_PRIOR: vScrollNotify := SB_PAGEUP; VK_NEXT: vScrollNotify := SB_PAGEDOWN; VK_DOWN: vScrollNotify := SB_LINEDOWN; VK_HOME: vScrollNotify := SB_TOP; VK_END: vScrollNotify := SB_BOTTOM; VK_LEFT: hScrollNotify := SB_LINELEFT; VK_RIGHT: hScrollNotify := SB_LINERIGHT; end; if (vScrollNotify <> -1) then Perform(WM_VSCROLL, vScrollNotify, 0); if (hScrollNotify <> -1) then Perform(WM_HSCROLL, hScrollNotify, 0); {$IFDEF FPC} inherited WMKeyDown(Message); {$ELSE} inherited; {$ENDIF} end; {------------------------------------------------------} procedure TRVScroller.SetVPos(p: Integer); var ScrollInfo: TScrollInfo; oldPos: Integer; r: TRect; begin OldPos := VPos; VPos := p; ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.nPos := VPos; ScrollInfo.fMask := SIF_POS; SetScrollInfo(Handle, SB_VERT, ScrollInfo, True); GetScrollInfo(Handle, SB_VERT, ScrollInfo); VPos := ScrollInfo.nPos; r := ClientRect; if OldPos-VPos <> 0 then begin if FFullRedraw then begin ScrollChildren(0, (OldPos-VPos)*SmallStep); Refresh; end else begin {$IFDEF MSWINDOWS} ScrollWindowEx(Handle, 0, (OldPos-VPos)*SmallStep, nil, @r, 0, nil, SW_INVALIDATE {or SW_SCROLLCHILDREN}); {$ELSE} Invalidate; {$ENDIF} ScrollChildren(0, (OldPos-VPos)*SmallStep); end; if Assigned(FOnVScrolled) then FOnVScrolled(Self); end; end; {------------------------------------------------------} procedure TRVScroller.SetHPos(p: Integer); var ScrollInfo: TScrollInfo; oldPos: Integer; r: TRect; begin OldPos := HPos; HPos := p; ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.nPos := HPos; ScrollInfo.fMask := SIF_POS; SetScrollInfo(Handle, SB_HORZ, ScrollInfo, True); GetScrollInfo(Handle, SB_HORZ, ScrollInfo); HPos := ScrollInfo.nPos; r := ClientRect; if OldPos-HPos <> 0 then begin if FFullRedraw then begin ScrollChildren((OldPos-HPos), 0); Refresh; end else begin ScrollWindowEx(Handle, (OldPos-HPos), 0, nil, @r, 0, nil, SW_INVALIDATE{or SW_SCROLLCHILDREN}); ScrollChildren((OldPos-HPos), 0); end; end; end; {------------------------------------------------------} procedure TRVScroller.Paint; var i: Integer; begin Canvas.Font.Color := clRed; Canvas.Font.Size := 2; Canvas.FillRect(Canvas.ClipRect); for i := Canvas.ClipRect.Top div SmallStep -1 to Canvas.ClipRect.Bottom div SmallStep +1 do Canvas.TextOut(-HPos, i*SmallStep, IntToStr(i+VPos)); end; {------------------------------------------------------} procedure TRVScroller.ScrollTo(y: Integer); begin SetVPos(y div SmallStep); end; {-------------------------------------------------------} function TRVScroller.GetVScrollPos: Integer; begin GetVScrollPos := VPos; end; {-------------------------------------------------------} procedure TRVScroller.SetVScrollPos(Pos: Integer); begin SetVPos(Pos); end; {-------------------------------------------------------} function TRVScroller.GetVScrollMax: Integer; var ScrollInfo: TScrollInfo; begin ScrollInfo.cbSize := SizeOf(ScrollInfo); ScrollInfo.nPos := HPos; ScrollInfo.fMask := SIF_RANGE or SIF_PAGE; GetScrollInfo(Handle, SB_VERT, ScrollInfo); GetVScrollMax := ScrollInfo.nMax - Integer(ScrollInfo.nPage-1); end; {-------------------------------------------------------} procedure TRVScroller.SetVScrollVisible(vis: Boolean); begin FVScrollVisible := vis; ShowScrollBar(Handle, SB_VERT, vis); end; {-------------------------------------------------------} procedure TRVScroller.WMGetDlgCode(var Message: TWMGetDlgCode); begin Message.Result := DLGC_WANTARROWS; end; end.
unit InfoXPULLTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoXPULLRecord = record PItemNumber: String[1]; PSI: String[2]; PDescription: String[20]; PAbbreviation: String[12]; PModCount: SmallInt; End; TInfoXPULLClass2 = class public PItemNumber: String[1]; PSI: String[2]; PDescription: String[20]; PAbbreviation: String[12]; PModCount: SmallInt; End; // function CtoRInfoXPULL(AClass:TInfoXPULLClass):TInfoXPULLRecord; // procedure RtoCInfoXPULL(ARecord:TInfoXPULLRecord;AClass:TInfoXPULLClass); TInfoXPULLBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoXPULLRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoXPULL = (InfoXPULLPrimaryKey); TInfoXPULLTable = class( TDBISAMTableAU ) private FDFItemNumber: TStringField; FDFSI: TStringField; FDFDescription: TStringField; FDFAbbreviation: TStringField; FDFModCount: TSmallIntField; procedure SetPItemNumber(const Value: String); function GetPItemNumber:String; procedure SetPSI(const Value: String); function GetPSI:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPAbbreviation(const Value: String); function GetPAbbreviation:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoXPULL); function GetEnumIndex: TEIInfoXPULL; 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:TInfoXPULLRecord; procedure StoreDataBuffer(ABuffer:TInfoXPULLRecord); property DFItemNumber: TStringField read FDFItemNumber; property DFSI: TStringField read FDFSI; property DFDescription: TStringField read FDFDescription; property DFAbbreviation: TStringField read FDFAbbreviation; property DFModCount: TSmallIntField read FDFModCount; property PItemNumber: String read GetPItemNumber write SetPItemNumber; property PSI: String read GetPSI write SetPSI; property PDescription: String read GetPDescription write SetPDescription; property PAbbreviation: String read GetPAbbreviation write SetPAbbreviation; property PModCount: SmallInt read GetPModCount write SetPModCount; published property Active write SetActive; property EnumIndex: TEIInfoXPULL read GetEnumIndex write SetEnumIndex; end; { TInfoXPULLTable } TInfoXPULLQuery = class( TDBISAMQueryAU ) private FDFItemNumber: TStringField; FDFSI: TStringField; FDFDescription: TStringField; FDFAbbreviation: TStringField; FDFModCount: TSmallIntField; procedure SetPItemNumber(const Value: String); function GetPItemNumber:String; procedure SetPSI(const Value: String); function GetPSI:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPAbbreviation(const Value: String); function GetPAbbreviation: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:TInfoXPULLRecord; procedure StoreDataBuffer(ABuffer:TInfoXPULLRecord); property DFItemNumber: TStringField read FDFItemNumber; property DFSI: TStringField read FDFSI; property DFDescription: TStringField read FDFDescription; property DFAbbreviation: TStringField read FDFAbbreviation; property DFModCount: TSmallIntField read FDFModCount; property PItemNumber: String read GetPItemNumber write SetPItemNumber; property PSI: String read GetPSI write SetPSI; property PDescription: String read GetPDescription write SetPDescription; property PAbbreviation: String read GetPAbbreviation write SetPAbbreviation; property PModCount: SmallInt read GetPModCount write SetPModCount; published property Active write SetActive; end; { TInfoXPULLTable } procedure Register; implementation function TInfoXPULLTable.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 { TInfoXPULLTable.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; { TInfoXPULLTable.GenerateNewFieldName } function TInfoXPULLTable.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; { TInfoXPULLTable.CreateField } procedure TInfoXPULLTable.CreateFields; begin FDFItemNumber := CreateField( 'ItemNumber' ) as TStringField; FDFSI := CreateField( 'SI' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFAbbreviation := CreateField( 'Abbreviation' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; end; { TInfoXPULLTable.CreateFields } procedure TInfoXPULLTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXPULLTable.SetActive } procedure TInfoXPULLTable.SetPItemNumber(const Value: String); begin DFItemNumber.Value := Value; end; function TInfoXPULLTable.GetPItemNumber:String; begin result := DFItemNumber.Value; end; procedure TInfoXPULLTable.SetPSI(const Value: String); begin DFSI.Value := Value; end; function TInfoXPULLTable.GetPSI:String; begin result := DFSI.Value; end; procedure TInfoXPULLTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoXPULLTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoXPULLTable.SetPAbbreviation(const Value: String); begin DFAbbreviation.Value := Value; end; function TInfoXPULLTable.GetPAbbreviation:String; begin result := DFAbbreviation.Value; end; procedure TInfoXPULLTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoXPULLTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoXPULLTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('ItemNumber, String, 1, N'); Add('SI, String, 2, N'); Add('Description, String, 20, N'); Add('Abbreviation, String, 12, N'); Add('ModCount, SmallInt, 0, N'); end; end; procedure TInfoXPULLTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, ItemNumber;SI, Y, Y, N, N'); end; end; procedure TInfoXPULLTable.SetEnumIndex(Value: TEIInfoXPULL); begin case Value of InfoXPULLPrimaryKey : IndexName := ''; end; end; function TInfoXPULLTable.GetDataBuffer:TInfoXPULLRecord; var buf: TInfoXPULLRecord; begin fillchar(buf, sizeof(buf), 0); buf.PItemNumber := DFItemNumber.Value; buf.PSI := DFSI.Value; buf.PDescription := DFDescription.Value; buf.PAbbreviation := DFAbbreviation.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoXPULLTable.StoreDataBuffer(ABuffer:TInfoXPULLRecord); begin DFItemNumber.Value := ABuffer.PItemNumber; DFSI.Value := ABuffer.PSI; DFDescription.Value := ABuffer.PDescription; DFAbbreviation.Value := ABuffer.PAbbreviation; DFModCount.Value := ABuffer.PModCount; end; function TInfoXPULLTable.GetEnumIndex: TEIInfoXPULL; var iname : string; begin result := InfoXPULLPrimaryKey; iname := uppercase(indexname); if iname = '' then result := InfoXPULLPrimaryKey; end; function TInfoXPULLQuery.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 { TInfoXPULLQuery.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; { TInfoXPULLQuery.GenerateNewFieldName } function TInfoXPULLQuery.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; { TInfoXPULLQuery.CreateField } procedure TInfoXPULLQuery.CreateFields; begin FDFItemNumber := CreateField( 'ItemNumber' ) as TStringField; FDFSI := CreateField( 'SI' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFAbbreviation := CreateField( 'Abbreviation' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; end; { TInfoXPULLQuery.CreateFields } procedure TInfoXPULLQuery.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoXPULLQuery.SetActive } procedure TInfoXPULLQuery.SetPItemNumber(const Value: String); begin DFItemNumber.Value := Value; end; function TInfoXPULLQuery.GetPItemNumber:String; begin result := DFItemNumber.Value; end; procedure TInfoXPULLQuery.SetPSI(const Value: String); begin DFSI.Value := Value; end; function TInfoXPULLQuery.GetPSI:String; begin result := DFSI.Value; end; procedure TInfoXPULLQuery.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoXPULLQuery.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoXPULLQuery.SetPAbbreviation(const Value: String); begin DFAbbreviation.Value := Value; end; function TInfoXPULLQuery.GetPAbbreviation:String; begin result := DFAbbreviation.Value; end; procedure TInfoXPULLQuery.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoXPULLQuery.GetPModCount:SmallInt; begin result := DFModCount.Value; end; function TInfoXPULLQuery.GetDataBuffer:TInfoXPULLRecord; var buf: TInfoXPULLRecord; begin fillchar(buf, sizeof(buf), 0); buf.PItemNumber := DFItemNumber.Value; buf.PSI := DFSI.Value; buf.PDescription := DFDescription.Value; buf.PAbbreviation := DFAbbreviation.Value; buf.PModCount := DFModCount.Value; result := buf; end; procedure TInfoXPULLQuery.StoreDataBuffer(ABuffer:TInfoXPULLRecord); begin DFItemNumber.Value := ABuffer.PItemNumber; DFSI.Value := ABuffer.PSI; DFDescription.Value := ABuffer.PDescription; DFAbbreviation.Value := ABuffer.PAbbreviation; DFModCount.Value := ABuffer.PModCount; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoXPULLTable, TInfoXPULLQuery, TInfoXPULLBuffer ] ); end; { Register } function TInfoXPULLBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..5] of string = ('ITEMNUMBER','SI','DESCRIPTION','ABBREVIATION','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 TInfoXPULLBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftSmallInt; end; end; function TInfoXPULLBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PItemNumber; 2 : result := @Data.PSI; 3 : result := @Data.PDescription; 4 : result := @Data.PAbbreviation; 5 : result := @Data.PModCount; end; end; end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StJupsat.pas 4.04 *} {*********************************************************} {* SysTools: Astronomical Routines *} {* (for the four "Gallilean" moons of Jupiter *} {* Callisto, Europa, Ganymede, and Io) *} {*********************************************************} {$I StDefine.inc} { ************************************************************** } { Sources: } { 1. Astronomical Algorithms, Jean Meeus, Willmann-Bell, 1991. } { } { 2. Planetary and Lunar Coordinates (1984-2000), U.S. Govt, } { 1983. } { } { 3. Supplement to the American Ephemeris and Nautical Almanac,} { U.S. Govt, 1964. } { } { 4. MPO96-98 source files, Brian D. Warner, 1995-98. } { } { ************************************************************** } (* ************************************************************** The formulae in this unit are based on DYNAMICAL time, which is based on the actual rotation of the Earth and is gradually slowing. Universal Time is based on a fixed rotation rate. To directly compare results in the astronomical literature (and Meeus' examples), you must use a Universal Time that is adjusted by the value Delta T. This value is approximately 1 min in the latter part of the 20th century and will be about 80 seconds in the year 2020. As an example, to compare the High Precision positions for 1992 December 16 (Meeus' example), you must use a Universal Time of 1992 December 16 at 00:00:59 which equals 00:00:00 Dynamical Time The Shadows parameter is used for high precision calculations only. If True, the positions are calculated as seen from the SUN, not the Earth. For eclipses of the satellites by Jupiter, in effect, the position is in reference to the SHADOW of Jupiter in space, not the planet itself. For shadow transits, where the shadow of the satellite is projected onto the surface of the planet, the position is that of the satellite's shadow in reference to Jupiter and not the satellite itself. The purpose of the Shadows parameter is to complete the prediction for satellite phenomenon. For example, using Shadow := False, the result may indicate that a satellite goes behind Jupiter at a given instant but not if the satellite is visible because it is in Jupiter's shadow. Setting Shadow := True for the same time will indicate if the planet is in or out of Jupiter's shadow. (Shadow := FALSE) and (abs(satellite X-coordinate) = 1) ------------------------------------------------------- If the X-value is negative and heading towards 0, the satellite is entering the front of the planet. If the X-value is negative and increasing, the satellite is coming from behind the planet. If the X-value is positive and heading towards 0, the satellite is going behind the planet. If the X-value is positive and increasing, the satellite is leaving the front of the planet. (Shadow := TRUE) and (abs(satellite X-coordinate) = 1) ------------------------------------------------------- If the X-value is negative and heading towards 0, the satellite's shadow is entering the planet's disc. If the X-value is negative and increasing, the satellite is leaving the planet's shadow. If the X-value is positive and heading towards 0, the satellite entering the planet's shadow. If the X-value is positive and increasing, the satellite's shadow is leaving the planet. The X and Y coordinates are based on the equatorial radius of Jupiter. Because the planet is considerably flattened by its rapid rotation, the polar diameter is less than 1. To avoid dealing with an elliptical disc for Jupiter, multiply the Y values only by 1.071374. This creates a "circular Jupiter" and so makes determining if the satellite is above or below Jupiter easier (abs(Y-coordinate) > 1). ****************************************************************** *) unit StJupsat; interface type TStJupSatPos = packed record X : Double; Y : Double; end; TStJupSats = packed record Io : TStJupSatPos; Europa : TStJupSatPos; Ganymede : TStJupSatPos; Callisto : TStJupSatPos; end; function GetJupSats(JD : TDateTime; HighPrecision, Shadows : Boolean) : TStJupSats; implementation uses StDate, StAstro, StAstroP, StJup, StMath; type SunCoordsRec = packed record X, Y, Z : Double; L, B, R : Double; end; TranformRec = packed record A, B, C : array[1..6] of Double; end; function SunCoords(JD : Double) : SunCoordsRec; var L, B, R, T0, TM, RS, OB, A : Double; begin T0 := (JD - StdDate) / 365250; TM := T0/100; RS := radcor * 3600; OB := 0.4090928042223 - 4680.93/RS * TM - 1.55/RS * sqr(TM) + 1999.25/RS * sqr(TM) * TM - 51.38/RS * sqr(sqr(TM)) - 249.67/RS * sqr(sqr(TM)) * TM - 39.05/RS * sqr(sqr(TM)) * sqr(TM) + 7.12/RS * sqr(sqr(TM)) * sqr(TM) * TM + 27.87/RS * sqr(sqr(sqr(TM))); L := 175347046 + 3341656 * cos(4.6692568 + 6283.07585*T0) + 34894 * cos(4.6261000 + 12566.1517*T0) + 3497 * cos(2.7441000 + 5753.3849*T0) + 3418 * cos(2.8289000 + 3.5231*T0) + 3136 * cos(3.6277000 + 77713.7715*T0) + 2676 * cos(4.4181000 + 7860.4194*T0) + 2343 * cos(6.1352000 + 3930.2097*T0) + 1324 * cos(0.7425000 + 11506.7698*T0) + 1273 * cos(2.0371000 + 529.6910*T0) + 1199 * cos(1.1096000 + 1577.3435*T0) + 990 * cos(5.2330000 + 5884.9270*T0) + 902 * cos(2.0450000 + 26.1490*T0) + 857 * cos(3.5080000 + 398.149*T0) + 780 * cos(1.1790000 + 5223.694*T0) + 753 * cos(2.5330000 + 5507.553*T0) + 505 * cos(4.5830000 + 18849.228*T0) + 492 * cos(4.2050000 + 775.523*T0) + 357 * cos(2.9200000 + 0.067*T0) + 317 * cos(5.8490000 + 11790.626*T0) + 284 * cos(1.8990000 + 796.298*T0) + 271 * cos(0.3150000 + 10977.079*T0) + 243 * cos(0.3450000 + 5486.778*T0) + 206 * cos(4.8060000 + 2544.314*T0) + 205 * cos(1.8690000 + 5573.143*T0) + 202 * cos(2.4580000 + 6069.777*T0) + 156 * cos(0.8330000 + 213.299*T0) + 132 * cos(3.4110000 + 2942.463*T0) + 126 * cos(1.0830000 + 20.775*T0) + 115 * cos(0.6450000 + 0.980*T0) + 103 * cos(0.6360000 + 4694.003*T0) + 102 * cos(0.9760000 + 15720.839*T0) + 102 * cos(4.2670000 + 7.114*T0) + 99 * cos(6.2100000 + 2146.170*T0) + 98 * cos(0.6800000 + 155.420*T0) + 86 * cos(5.9800000 +161000.690*T0) + 85 * cos(1.3000000 + 6275.960*T0) + 85 * cos(3.6700000 + 71430.700*T0) + 80 * cos(1.8100000 + 17260.150*T0); A := 628331966747.0 + 206059 * cos(2.678235 + 6283.07585*T0) + 4303 * cos(2.635100 + 12566.1517*T0) + 425 * cos(1.590000 + 3.523*T0) + 119 * cos(5.796000 + 26.298*T0) + 109 * cos(2.966000 + 1577.344*T0) + 93 * cos(2.590000 + 18849.23*T0) + 72 * cos(1.140000 + 529.69*T0) + 68 * cos(1.870000 + 398.15*T0) + 67 * cos(4.410000 + 5507.55*T0) + 59 * cos(2.890000 + 5223.69*T0) + 56 * cos(2.170000 + 155.42*T0) + 45 * cos(0.400000 + 796.30*T0) + 36 * cos(0.470000 + 775.52*T0) + 29 * cos(2.650000 + 7.11*T0) + 21 * cos(5.340000 + 0.98*T0) + 19 * cos(1.850000 + 5486.78*T0) + 19 * cos(4.970000 + 213.30*T0) + 17 * cos(2.990000 + 6275.96*T0) + 16 * cos(0.030000 + 2544.31*T0); L := L + (A * T0); A := 52919 + 8720 * cos(1.0721 + 6283.0758*T0) + 309 * cos(0.867 + 12566.152*T0) + 27 * cos(0.050 + 3.52*T0) + 16 * cos(5.190 + 26.30*T0) + 16 * cos(3.68 + 155.42*T0) + 10 * cos(0.76 + 18849.23*T0) + 9 * cos(2.06 + 77713.77*T0) + 7 * cos(0.83 + 775.52*T0) + 5 * cos(4.66 + 1577.34*T0); L := L + (A * sqr(T0)); A := 289 * cos(5.844 + 6283.076*T0) + 35 + 17 * cos(5.49 + 12566.15*T0) + 3 * cos(5.20 + 155.42*T0) + 1 * cos(4.72 + 3.52*T0); L := L + (A * sqr(T0) * T0); A := 114 * cos(3.142); L := L + (A * sqr(sqr(T0))); L := L / 1.0E+8; {solar latitude} B := 280 * cos(3.199 + 84334.662*T0) + 102 * cos(5.422 + 5507.553*T0) + 80 * cos(3.88 + 5223.69*T0) + 44 * cos(3.70 + 2352.87*T0) + 32 * cos(4.00 + 1577.34*T0); A := 9 * cos(3.90 + 5507.550*T0) + 6 * cos(1.73 + 5223.690*T0); B := B + (A * T0); B := B / 1.0E+8; {solar radius vector (astronomical units)} R := 100013989 + 1670700 * cos(3.0984635 + 6283.07585*T0) + 13956 * cos(3.05525 + 12566.15170*T0) + 3084 * cos(5.1985 + 77713.7715*T0) + 1628 * cos(1.1739 + 5753.3849*T0) + 1576 * cos(2.8649 + 7860.4194*T0) + 925 * cos(5.453 + 11506.770*T0) + 542 * cos(4.564 + 3930.210*T0) + 472 * cos(3.661 + 5884.927*T0) + 346 * cos(0.964 + 5507.553*T0) + 329 * cos(5.900 + 5223.694*T0) + 307 * cos(0.299 + 5573.143*T0) + 243 * cos(4.273 + 11790.629*T0) + 212 * cos(5.847 + 1577.344*T0) + 186 * cos(5.022 + 10977.079*T0) + 175 * cos(3.012 + 18849.228*T0) + 110 * cos(5.055 + 5486.778*T0) + 98 * cos(0.89 + 6069.78*T0) + 86 * cos(5.69 + 15720.84*T0) + 86 * cos(1.27 +161000.69*T0) + 65 * cos(0.27 + 17260.15*T0) + 63 * cos(0.92 + 529.69*T0) + 57 * cos(2.01 + 83996.85*T0) + 56 * cos(5.24 + 71430.70*T0) + 49 * cos(3.25 + 2544.31*T0) + 47 * cos(2.58 + 775.52*T0) + 45 * cos(5.54 + 9437.76*T0) + 43 * cos(6.01 + 6275.96*T0) + 39 * cos(5.36 + 4694.00*T0) + 38 * cos(2.39 + 8827.39*T0) + 37 * cos(0.83 + 19651.05*T0) + 37 * cos(4.90 + 12139.55*T0) + 36 * cos(1.67 + 12036.46*T0) + 35 * cos(1.84 + 2942.46*T0) + 33 * cos(0.24 + 7084.90*T0) + 32 * cos(0.18 + 5088.63*T0) + 32 * cos(1.78 + 398.15*T0) + 28 * cos(1.21 + 6286.60*T0) + 28 * cos(1.90 + 6279.55*T0) + 26 * cos(4.59 + 10447.39*T0); R := R / 1.0E+8; A := 103019 * cos(1.107490 + 6283.075850*T0) + 1721 * cos(1.0644 + 12566.1517*T0) + 702 * cos(3.142) + 32 * cos(1.02 + 18849.23*T0) + 31 * cos(2.84 + 5507.55*T0) + 25 * cos(1.32 + 5223.69*T0) + 18 * cos(1.42 + 1577.34*T0) + 10 * cos(5.91 + 10977.08*T0) + 9 * cos(1.42 + 6275.96*T0) + 9 * cos(0.27 + 5486.78*T0); R := R + (A * T0 / 1.0E+8); A := 4359 * cos(5.7846 + 6283.0758*T0) + 124 * cos(5.579 + 12566.152*T0) + 12 * cos(3.14) + 9 * cos(3.63 + 77713.77*T0) + 6 * cos(1.87 + 5573.14*T0) + 3 * cos(5.47 + 18849.23*T0); R := R + (A * sqr(T0) / 1.0E+8); L := (L + PI); L := Frac(L / 2.0 / PI) * 2.0 * Pi; if L < 0 then L := L + (2.0*PI); B := -B; Result.L := L; Result.B := B; Result.R := R; Result.X := R * cos(B) * cos(L); Result.Y := R * (cos(B) * sin(L) * cos(OB) - sin(B) * sin(OB)); Result.Z := R * (cos(B) * sin(L) * sin(OB) + sin(B) * cos(OB)); end; {-------------------------------------------------------------------------} function JupSatsLo(AJD : Double) : TStJupSats; var DateDif, {d} ArgJup, {V} AnomE, {M} AnomJ, {N} DeltaLong, {J} ECenterE, {A} ECenterJ, {B} K, RVE, {R} RVJ, {r} EJDist, {Delta} Phase, {Psi} Lambda, {Lambda} DS, DE, {DS, DE} Mu1, Mu2, Mu3, Mu4, {Mu1 - Mu4} G, H, {G, H} TmpDbl1, TmpDbl2, R1, R2, R3, R4 {R1 - R4} : Double; begin AJD := DateTimeToAJD(AJD); DateDif := AJD - 2451545.0; ArgJup := 172.74 + (0.00111588 * DateDif); ArgJup := Frac(ArgJup/360.0) * 360.0; if (ArgJup < 0) then ArgJup := 360.0 + ArgJup; ArgJup := ArgJup / radcor; AnomE := 357.529 + (0.9856003 * DateDif); AnomE := Frac(AnomE/360.0) * 360.0; if (AnomE < 0) then AnomE := 360.0 + AnomE; AnomE := AnomE / radcor; AnomJ := 20.020 + (0.0830853 * DateDif + (0.329 * sin(ArgJup))); AnomJ := Frac(AnomJ/360.0) * 360.0; if (AnomJ < 0) then AnomJ := 360.0 + AnomJ; AnomJ := AnomJ / radcor; DeltaLong := 66.115 + (0.9025179 * DateDif - (0.329 * sin(ArgJup))); DeltaLong := Frac(DeltaLong/360.0) * 360.0; if (DeltaLong < 0) then DeltaLong := 360.0 + DeltaLong; DeltaLong := DeltaLong / radcor; ECenterE := 1.915 * sin(AnomE) + 0.020 * sin(2*AnomE); ECenterE := ECenterE / radcor; ECenterJ := 5.555 * sin(AnomJ) + 0.168 * sin(2*AnomJ); ECenterJ := ECenterJ / radcor; K := (DeltaLong + ECenterE - ECenterJ); RVE := 1.00014 - (0.01671 * cos(AnomE)) - (0.00014 * cos(2*AnomE)); RVJ := 5.20872 - (0.25208 * cos(AnomJ)) - (0.00611 * cos(2*AnomJ)); EJDist := sqrt(sqr(RVJ) + sqr(RVE) - (2 * RVJ * RVE * cos(K))); Phase := RVE/EJDist * sin(K); Phase := StInvSin(Phase); if ((sin(K) < 0) and (Phase > 0)) or ((sin(K) > 0) and (Phase < 0)) then Phase := -Phase; Lambda := 34.35 + (0.083091 * DateDif) + (0.329 * sin(ArgJup)); Lambda := Lambda / radcor + ECenterJ; DS := 3.12 * sin(Lambda + 42.8 / radcor); DE := DS - 2.22 * sin(Phase) * cos(Lambda + 22/radcor) - 1.30 * ((RVJ - EJDist) / EJDist) * sin(Lambda - 100.5/radcor); DE := DE / radcor; Mu1 := 163.8067 + 203.4058643 * (DateDif - (EJDist / 173)); Mu1 := Frac(Mu1/360.0) * 360.0; if (Mu1 < 0) then Mu1 := 360.0 + Mu1; Mu1 := Mu1 / radcor + Phase - ECenterJ; Mu2 := 358.4108 + 101.2916334 * (DateDif - (EJDist / 173)); Mu2 := Frac(Mu2/360.0) * 360.0; if (Mu2 < 0) then Mu2 := 360.0 + Mu2; Mu2 := Mu2 / radcor + Phase - ECenterJ; Mu3 := 5.7129 + 50.2345179 * (DateDif - (EJDist / 173)); Mu3 := Frac(Mu3/360.0) * 360.0; if (Mu3 < 0) then Mu3 := 360.0 + Mu3; Mu3 := Mu3 / radcor + Phase - ECenterJ; Mu4 := 224.8151 + 21.4879801 * (DateDif - (EJDist / 173)); Mu4 := Frac(Mu4/360.0) * 360.0; if (Mu4 < 0) then Mu4 := 360.0 + Mu4; Mu4 := Mu4 / radcor + Phase - ECenterJ; G := 331.18 + 50.310482 * (DateDif - (EJDist / 173)); G := Frac(G/360.0) * 360.0; if (G < 0) then G := 360.0 + G; G := G / radcor; H := 87.40 + 21.569231 * (DateDif - (EJDist / 173)); H := Frac(H/360.0) * 360.0; if (H < 0) then H := 360.0 + H; H := H / radcor; TmpDbl1 := 0.473 * sin(2 * (Mu1 - Mu2)) / radcor; TmpDbl2 := 1.065 * sin(2 * (Mu2 - Mu3)) / radcor; R1 := 5.9073 - 0.0244 * cos(2 * (Mu1 - Mu2)); R2 := 9.3991 - 0.0882 * cos(2 * (Mu2 - Mu3)); R3 := 14.9924 - 0.0216 * cos(G); R4 := 26.3699 - 0.1935 * cos(H); Mu1 := Mu1 + TmpDbl1; Mu2 := Mu2 + TmpDbl2; Mu3 := Mu3 + (0.165 * sin(G)) / radcor; Mu4 := Mu4 + (0.841 * sin(H)) / radcor; Result.Io.X := R1 * sin(Mu1); Result.Io.Y := -R1 * cos(Mu1) * sin(DE); Result.Europa.X := R2 * sin(Mu2); Result.Europa.Y := -R2 * cos(Mu2) * sin(DE); Result.Ganymede.X := R3 * sin(Mu3); Result.Ganymede.Y := -R3 * cos(Mu3) * sin(DE); Result.Callisto.X := R4 * sin(Mu4); Result.Callisto.Y := -R4 * cos(Mu4) * sin(DE); end; {-------------------------------------------------------------------------} function JupSatsHi(AJD : Double; Shadows : Boolean) : TStJupSats; var I : Integer; SunPos : SunCoordsRec; JupPos : TStEclipticalCord; SatX : array[1..5] of Double; SatY : array[1..5] of Double; SatZ : array[1..5] of Double; TD1, TD2, Angle, {Temporary Double values} AJDT, {AJD adjusted for light time (Tau)} JupX, JupY, JupZ, {Jupiter's geocentric rectangular coordinates} EJDist, {Delta} Jup1, Jup2, {/\, Alpha} DateDif, {t} L1, L2, L3, L4, {script L1-4} Pi1, Pi2, Pi3, Pi4, {Pi1-4} W1, W2, W3, W4, {Omega1-4} Inequality, {upside down L} PhiLambda, NodeJup, {Psi} AnomJup, {G} AnomSat, {G'} LongPerJ, S1, S2, S3, S4, {Sum1-4} TL1, TL2, TL3, TL4, {Capital L1-4} B1, B2, B3, B4, {tangent of latitude} R1, R2, R3, R4, {radius vector} T0, {Julian Centuries} Precession, {P} Inclination {I} : Double; Transforms : array[1..5] of TranformRec; begin FillChar(Result, SizeOf(TStJupSats), #0); AJD := DateTimeToAJD(AJD); SunPos := SunCoords(AJD); if not Shadows then begin TD1 := 5; AJDT := AJD - 0.0057755183 * TD1; {first guess} repeat JupPos := ComputeJupiter(AJDT); JupX := JupPos.R0 * cos(JupPos.B0) * cos(JupPos.L0) + SunPos.R * cos(SunPos.L); JupY := JupPos.R0 * cos(JupPos.B0) * sin(JupPos.L0) + SunPos.R * sin(SunPos.L); JupZ := JupPos.R0 * sin(JupPos.B0); EJDist := sqrt(sqr(JupX) + sqr(JupY) + sqr(JupZ)); TD2 := abs(EJDist - TD1); if abs(TD2) > 0.0005 then begin AJDT := AJD - 0.0057755183 * ((EJDist + TD1) / 2); TD1 := EJDist; end; until (TD2 <= 0.0005); end else begin JupPos := ComputeJupiter(AJD); JupX := JupPos.R0 * cos(JupPos.B0) * cos(JupPos.L0); JupY := JupPos.R0 * cos(JupPos.B0) * sin(JupPos.L0); JupZ := JupPos.R0 * sin(JupPos.B0); EJDist := sqrt(sqr(JupX+SunPos.X) + sqr(JupY+SunPos.Y) + sqr(JupZ+SunPos.Z)); end; Jup1 := StInvTan2(JupX, JupY); Jup2 := ArcTan(JupZ / sqrt(sqr(JupX) + sqr(JupY))); DateDif := AJD - 2443000.5 - (0.0057755183 * EJDist); L1 := 106.07947 + 203.488955432 * DateDif; L1 := Frac(L1/360.0) * 360.0; if (L1 < 0) then L1 := 360.0 + L1; L1 := L1 / radcor; L2 := 175.72938 + 101.374724550 * DateDif; L2 := Frac(L2/360.0) * 360.0; if (L2 < 0) then L2 := 360.0 + L2; L2 := L2 / radcor; L3 := 120.55434 + 50.317609110 * DateDif; L3 := Frac(L3/360.0) * 360.0; if (L3 < 0) then L3 := 360.0 + L3; L3 := L3 / radcor; L4 := 84.44868 + 21.571071314 * DateDif; L4 := Frac(L4/360.0) * 360.0; if (L4 < 0) then L4 := 360.0 + L4; L4 := L4 / radcor; Pi1 := 58.3329 + 0.16103936 * DateDif; Pi1 := Frac(Pi1/360.0) * 360.0; if (Pi1 < 0) then Pi1 := 360.0 + Pi1; Pi1 := Pi1 / radcor; Pi2 := 132.8959 + 0.04647985 * DateDif; Pi2 := Frac(Pi2/360.0) * 360.0; if (Pi2 < 0) then Pi2 := 360.0 + Pi2; Pi2 := Pi2 / radcor; Pi3 := 187.2887 + 0.00712740 * DateDif; Pi3 := Frac(Pi3/360.0) * 360.0; if (Pi3 < 0) then Pi3 := 360.0 + Pi3; Pi3 := Pi3 / radcor; Pi4 := 335.3418 + 0.00183998 * DateDif; Pi4 := Frac(Pi4/360.0) * 360.0; if (Pi4 < 0) then Pi4 := 360.0 + Pi4; Pi4 := Pi4 / radcor; W1 := 311.0793 - 0.13279430 * DateDif; W1 := Frac(W1/360.0) * 360.0; if (W1 < 0) then W1 := 360.0 + W1; W1 := W1 / radcor; W2 := 100.5099 - 0.03263047 * DateDif; W2 := Frac(W2/360.0) * 360.0; if (W2 < 0) then W2 := 360.0 + W2; W2 := W2 / radcor; W3 := 119.1688 - 0.00717704 * DateDif; W3 := Frac(W3/360.0) * 360.0; if (W3 < 0) then W3 := 360.0 + W3; W3 := W3 / radcor; W4 := 322.5729 - 0.00175934 * DateDif; W4 := Frac(W4/360.0) * 360.0; if (W4 < 0) then W4 := 360.0 + W4; W4 := W4 / radcor; Inequality := 0.33033 * sin((163.679 + 0.0010512*DateDif) / radcor) + 0.03439 * sin((34.486 - 0.0161731*DateDif) / radcor); Inequality := Inequality / radcor; PhiLambda := 191.8132 + 0.17390023 * DateDif; PhiLambda := Frac(PhiLambda / 360.0) * 360.0; if (PhiLambda < 0) then PhiLambda := 360.0 + PhiLambda; PhiLambda := PhiLambda / radcor; NodeJup := 316.5182 - 0.00000208 * DateDif; NodeJup := Frac(NodeJup / 360.0) * 360.0; if (NodeJup < 0) then NodeJup := 360.0 + NodeJup; NodeJup := NodeJup / radcor; AnomJup := 30.23756 + 0.0830925701 * DateDif; AnomJup := Frac(AnomJup / 360.0) * 360.0; if (AnomJup < 0) then AnomJup := 360.0 + AnomJup; AnomJup := AnomJup / radcor + Inequality; AnomSat := 31.97853 + 0.0334597339 * DateDif; AnomSat := Frac(AnomSat / 360.0) * 360.0; if (AnomSat < 0) then AnomSat := 360.0 + AnomSat; AnomSat := AnomSat / radcor; LongPerJ := 13.469942 / radcor; S1 := 0.47259 * sin(2*(L1-L2)) - 0.03480 * sin(Pi3-Pi4) - 0.01756 * sin(Pi1 + Pi3 - 2*LongPerJ - 2*AnomJup) + 0.01080 * sin(L2 - 2*L3 + Pi3) + 0.00757 * sin(PhiLambda) + 0.00663 * sin(L2 - 2*L3 + Pi4) + 0.00453 * sin(L1 - Pi3) + 0.00453 * sin(L2 - 2*L3 + Pi2) - 0.00354 * sin(L1-L2) - 0.00317 * sin(2*NodeJup - 2*LongPerJ) - 0.00269 * sin(L2 - 2*L3 + Pi1) + 0.00263 * sin(L1 - Pi4) + 0.00186 * sin(L1 - Pi1) - 0.00186 * sin(AnomJup) + 0.00167 * sin(Pi2 - Pi3) + 0.00158 * sin(4*(L1-L2)) - 0.00155 * sin(L1 - L3) - 0.00142 * sin(NodeJup + W3 - 2*LongPerJ - 2*AnomJup) - 0.00115 * sin(2*(L1 - 2*L2 + W2)) + 0.00089 * sin(Pi2 - Pi4) + 0.00084 * sin(W2 - W3) + 0.00084 * sin(L1 + Pi3 - 2*LongPerJ - 2*AnomJup) + 0.00053 * sin(NodeJup - W2); S2 := 1.06476 * sin(2*(L2-L3)) + 0.04253 * sin(L1 - 2*L2 + Pi3) + 0.03579 * sin(L2 - Pi3) + 0.02383 * sin(L1 - 2*L2 + Pi4) + 0.01977 * sin(L2 - Pi4) - 0.01843 * sin(PhiLambda) + 0.01299 * sin(Pi3 - Pi4) - 0.01142 * sin(L2 - L3) + 0.01078 * sin(L2 - Pi2) - 0.01058 * sin(AnomJup) + 0.00870 * sin(L2 - 2*L3 + Pi2) - 0.00775 * sin(2*(NodeJup - LongPerJ)) + 0.00524 * sin(2*(L1-L2)) - 0.00460 * sin(L1-L3) + 0.00450 * sin(L2 - 2*L3 + Pi1) + 0.00327 * sin(NodeJup - 2*AnomJup + W3 - 2*LongPerJ) - 0.00296 * sin(Pi1 + Pi3 - 2*LongPerJ - 2*AnomJup) - 0.00151 * sin(2*AnomJup) + 0.00146 * sin(NodeJup - W3) + 0.00125 * sin(NodeJup - W4) - 0.00117 * sin(L1 -2*L3 + Pi3) - 0.00095 * sin(2*(L2-W2)) + 0.00086 * sin(2*(L1-2*L2 +W2)) - 0.00086 * sin(5*AnomSat - 2*AnomJup + 52.225/radcor) - 0.00078 * sin(L2-L4) - 0.00064 * sin(L1 - 2*L3 + Pi4) - 0.00063 * sin(3*L3 - 7*L4 + 4*Pi4) + 0.00061 * sin(Pi1 - Pi4) + 0.00058 * sin(2*(NodeJup - LongPerJ - AnomJup)) + 0.00058 * sin(W3 - W4) + 0.00056 * sin(2*(L2-L4)) + 0.00055 * sin(2*(L1-L3)) + 0.00052 * sin(3*L3 - 7*L4 + Pi3 + 3*Pi4) - 0.00043 * sin(L1 - Pi3) + 0.00042 * sin(Pi3 - Pi2) + 0.00041 * sin(5*(L2-L3)) + 0.00041 * sin(Pi4 - LongPerJ) + 0.00038 * sin(L2 - Pi1) + 0.00032 * sin(W2 - W3) + 0.00032 * sin(2*(L3 - AnomJup - LongPerJ)) + 0.00029 * sin(Pi1 - Pi3); S3 := 0.16477 * sin(L3 - Pi3) + 0.09062 * sin(L3 - Pi4) - 0.06907 * sin(L2 - L3) + 0.03786 * sin(Pi3 - Pi4) + 0.01844 * sin(2*(L3-L4)) - 0.01340 * sin(AnomJup) + 0.00703 * sin(L2 - 2*L3 + Pi3) - 0.00670 * sin(2*(NodeJup - LongPerJ)) - 0.00540 * sin(L3-L4) + 0.00481 * sin(Pi1 + Pi3 -2*LongPerJ - 2*AnomJup) - 0.00409 * sin(L2 - 2*L3 + Pi2) + 0.00379 * sin(L2 - 2*L3 + Pi4) + 0.00235 * sin(NodeJup - W3) + 0.00198 * sin(NodeJup - W4) + 0.00180 * sin(PhiLambda) + 0.00129 * sin(3*(L3-L4)) + 0.00124 * sin(L1-L3) - 0.00119 * sin(5*AnomSat - 2*AnomJup + 52.225/radcor) + 0.00109 * sin(L1-L2) - 0.00099 * sin(3*L3 - 7*L4 + 4*Pi4) + 0.00091 * sin(W3 - W4) + 0.00081 * sin(3*L3 - 7*L4 + Pi3 + 3*Pi4) - 0.00076 * sin(2*L2 - 3*L3 + Pi3) + 0.00069 * sin(Pi4 - LongPerJ) - 0.00058 * sin(2*L3 - 3*L4 + Pi4) + 0.00057 * sin(L3 + Pi3 - 2*LongPerJ - 2*AnomJup) - 0.00057 * sin(L3 - 2*L4 + Pi4) - 0.00052 * sin(Pi2 - Pi3) - 0.00052 * sin(L2 - 2*L3 + Pi1) + 0.00048 * sin(L3 - 2*L4 + Pi3) - 0.00045 * sin(2*L2 - 3*L3 + Pi4) - 0.00041 * sin(Pi2 - Pi4) - 0.00038 * sin(2*AnomJup) - 0.00033 * sin(Pi3 - Pi4 + W3 - W4) - 0.00032 * sin(3*L3 - 7*L4 + 2*Pi3 + 2*Pi4) + 0.00030 * sin(4*(L3-L4)) - 0.00029 * sin(W3 + NodeJup - 2*LongPerJ - 2*AnomJup) + 0.00029 * sin(L3 + Pi4 - 2*LongPerJ - 2*AnomJup) + 0.00026 * sin(L3 - LongPerJ - AnomJup) + 0.00024 * sin(L2 - 3*L3 + 2*L4) + 0.00021 * sin(2*(L3 - LongPerJ - AnomJup)) - 0.00021 * sin(L3 - Pi2) + 0.00017 * sin(2*(L3 - Pi3)); S4 := 0.84109 * sin(L4 - Pi4) + 0.03429 * sin(Pi4 - Pi3) - 0.03305 * sin(2*(NodeJup - LongPerJ)) - 0.03211 * sin(AnomJup) - 0.01860 * sin(L4 - Pi3) + 0.01182 * sin(NodeJup - W4) + 0.00622 * sin(L4 + Pi4 - 2*AnomJup - 2*LongPerJ) + 0.00385 * sin(2*(L4 - Pi4)) - 0.00284 * sin(5*AnomSat - 2*AnomJup + 52.225/radcor) - 0.00233 * sin(2*(NodeJup - Pi4)) - 0.00223 * sin(L3 - L4) - 0.00208 * sin(L4 - LongPerJ) + 0.00177 * sin(NodeJup + W4 - 2*Pi4) + 0.00134 * sin(Pi4 - LongPerJ) + 0.00125 * sin(2*(L4 - AnomJup - LongPerJ)) - 0.00117 * sin(2*AnomJup) - 0.00112 * sin(2*(L3 - L4)) + 0.00106 * sin(3*L3 - 7*L4 + 4*Pi4) + 0.00102 * sin(L4 - AnomJup - LongPerJ) + 0.00096 * sin(2*L4 - NodeJup - W4) + 0.00087 * sin(2*(NodeJup - W4)) - 0.00087 * sin(3*L3 - 7*L4 + Pi3 + 3*Pi4) + 0.00085 * sin(L3 - 2*L4 + Pi4) - 0.00081 * sin(2*(L4 - NodeJup)) + 0.00071 * sin(L4 + Pi4 -2*LongPerJ - 3*AnomJup) + 0.00060 * sin(L1 - L4) - 0.00056 * sin(NodeJup - W3) - 0.00055 * sin(L3 - 2*L4 + Pi3) + 0.00051 * sin(L2 - L4) + 0.00042 * sin(2*(NodeJup - AnomJup - LongPerJ)) + 0.00039 * sin(2*(Pi4 - W4)) + 0.00036 * sin(NodeJup + LongPerJ - Pi4 - W4) + 0.00035 * sin(2*AnomSat - AnomJup + 188.37/radcor) - 0.00035 * sin(L4 - Pi4 + 2*LongPerJ - 2*NodeJup) - 0.00032 * sin(L4 + Pi4 - 2*LongPerJ - AnomJup) + 0.00030 * sin(3*L3 - 7*L4 + 2*Pi3 + 2*Pi4) + 0.00030 * sin(2*AnomSat - 2*AnomJup + 149.15/radcor) + 0.00028 * sin(L4 - Pi4 + 2*NodeJup - 2*LongPerJ) - 0.00028 * sin(2*(L4 - W4)) - 0.00027 * sin(Pi3 - Pi4 + W3 - W4) - 0.00026 * sin(5*AnomSat - 3*AnomJup + 188.37/radcor) + 0.00025 * sin(W4 - W3) - 0.00025 * sin(L2 - 3*L3 + 2*L4) - 0.00023 * sin(3*(L3 - L4)) + 0.00021 * sin(2*L4 - 2*LongPerJ - 3*AnomJup) - 0.00021 * sin(2*L3 - 3*L4 + Pi4) + 0.00019 * sin(L4 - Pi4 - AnomJup) - 0.00019 * sin(2*L4 - Pi3 - Pi4) - 0.00018 * sin(L4 - Pi4 + AnomJup) - 0.00016 * sin(L4 + Pi3 -2*LongPerJ - 2*AnomJup); S1 := S1/radcor; S2 := S2/radcor; S3 := S3/radcor; S4 := S4/radcor; TL1 := L1 + S1; TL2 := L2 + S2; TL3 := L3 + S3; TL4 := L4 + S4; B1 := 0.0006502 * sin(TL1 - W1) + 0.0001835 * sin(TL1 - W2) + 0.0000329 * sin(TL1 - W3) - 0.0000311 * sin(TL1 - NodeJup) + 0.0000093 * sin(TL1 - W4) + 0.0000075 * sin(3*TL1 - 4*L2 - 1.9927/radcor * S1 + W2) + 0.0000046 * sin(TL1 + NodeJup - 2*LongPerJ - 2*AnomJup); B1 := ArcTan(B1); B2 := 0.0081275 * sin(TL2 - W2) + 0.0004512 * sin(TL2 - W3) - 0.0003286 * sin(TL2 - NodeJup) + 0.0001164 * sin(TL2 - W4) + 0.0000273 * sin(L1 - 2*L3 + 1.0146/radcor * S2 + W2) + 0.0000143 * sin(TL2 + NodeJup - 2*LongPerJ - 2*AnomJup) - 0.0000143 * sin(TL2 - W1) + 0.0000035 * sin(TL2 - NodeJup + AnomJup) - 0.0000028 * sin(L1 - 2*L3 + 1.0146/radcor * S2 + W3); B2 := ArcTan(B2); B3 := 0.0032364 * sin(TL3 - W3) - 0.0016911 * sin(TL3 - NodeJup) + 0.0006849 * sin(TL3 - W4) - 0.0002806 * sin(TL3 - W2) + 0.0000321 * sin(TL3 + NodeJup - 2*LongPerJ - 2*AnomJup) + 0.0000051 * sin(TL3 - NodeJup + AnomJup) - 0.0000045 * sin(TL3 - NodeJup - AnomJup) - 0.0000045 * sin(TL3 + NodeJup - 2*LongPerJ) + 0.0000037 * sin(TL3 + NodeJup - 2*LongPerJ - 3*AnomJup) + 0.0000030 * sin(2*L2 - 3*TL3 + 4.03/radcor * S3 + W2) - 0.0000021 * sin(2*L2 - 3*TL3 + 4.03/radcor * S3 + W3); B3 := ArcTan(B3); B4 := -0.0076579 * sin(TL4 - NodeJup) + 0.0044148 * sin(TL4 - W4) - 0.0005106 * sin(TL4 - W3) + 0.0000773 * sin(TL4 + NodeJup - 2*LongPerJ - 2*AnomJup) + 0.0000104 * sin(TL4 - NodeJup + AnomJup) - 0.0000102 * sin(TL4 - NodeJup - AnomJup) + 0.0000088 * sin(TL4 + NodeJup - 2*LongPerJ - 3*AnomJup) - 0.0000038 * sin(TL4 + NodeJup - 2*LongPerJ - AnomJup); B4 := ArcTan(B4); R1 := -0.0041339 * cos(2*(L1-L2)) - 0.0000395 * cos(L1 - Pi3) - 0.0000214 * cos(L1 - Pi4) + 0.0000170 * cos(L1 - L2) - 0.0000162 * cos(L1 - Pi1) - 0.0000130 * cos(4*(L1-L2)) + 0.0000106 * cos(L1 - L3) - 0.0000063 * cos(L1 + Pi3 - 2*LongPerJ - 2*AnomJup); R2 := 0.0093847 * cos(L1-L2) - 0.0003114 * cos(L2 - Pi3) - 0.0001738 * cos(L2 - Pi4) - 0.0000941 * cos(L2 - Pi2) + 0.0000553 * cos(L2 - L3) + 0.0000523 * cos(L1 - L3) - 0.0000290 * cos(2*(L1-L2)) + 0.0000166 * cos(2*(L2-W2)) + 0.0000107 * cos(L1 - 2*L3 + Pi3) - 0.0000102 * cos(L2 - Pi1) - 0.0000091 * cos(2*(L1-L3)); R3 := -0.0014377 * cos(L3 - Pi3) - 0.0007904 * cos(L3 - Pi4) + 0.0006342 * cos(L2 - L3) - 0.0001758 * cos(2*(L3-L4)) + 0.0000294 * cos(L3 - L4) - 0.0000156 * cos(3*(L3-L4)) + 0.0000155 * cos(L1 - L3) - 0.0000153 * cos(L1 - L2) + 0.0000070 * cos(2*L2 - 3*L3 + Pi3) - 0.0000051 * cos(L3 + Pi3 - 2*LongPerJ - 2*AnomJup); R4 := -0.0073391 * cos(L4 - Pi4) + 0.0001620 * cos(L4 - Pi3) + 0.0000974 * cos(L3 - L4) - 0.0000541 * cos(L4 + Pi4 - 2*LongPerJ - 2*AnomJup) - 0.0000269 * cos(2*(L4-Pi4)) + 0.0000182 * cos(L4- LongPerJ) + 0.0000177 * cos(2*(L3-L4)) - 0.0000167 * cos(2*L4 - NodeJup - W4) + 0.0000167 * cos(NodeJup - W4) - 0.0000155 * cos(2*(L4-LongPerj-AnomJup)) + 0.0000142 * cos(2*(L4-NodeJup)) + 0.0000104 * cos(L1 - L4) + 0.0000092 * cos(L2 - L4) - 0.0000089 * cos(L4 - LongPerJ - AnomJup) - 0.0000062 * cos(L4 + Pi4 - 2*LongPerJ - 3*AnomJup) + 0.0000048 * cos(2*(L4-W4)); R1 := 5.90730 * (1 + R1); R2 := 9.39912 * (1 + R2); R3 := 14.99240 * (1 + R3); R4 := 26.36990 * (1 + R4); T0 := (AJD - 2433282.423) / 36525; Precession := (1.3966626*T0 + 0.0003088*sqr(T0)) / radcor; TL1 := TL1 + Precession; TL2 := TL2 + Precession; TL3 := TL3 + Precession; TL4 := TL4 + Precession; NodeJup := NodeJup + Precession; T0 := (AJD - AstJulianDatePrim(1900, 1, 1, 0)) / 36525; Inclination := (3.120262 + 0.0006*T0) / radcor; SatX[1] := R1 * cos(TL1 - NodeJup) * cos(B1); SatY[1] := R1 * sin(TL1 - NodeJup) * cos(B1); SatZ[1] := R1 * sin(B1); SatX[2] := R2 * cos(TL2 - NodeJup) * cos(B2); SatY[2] := R2 * sin(TL2 - NodeJup) * cos(B2); SatZ[2] := R2 * sin(B2); SatX[3] := R3 * cos(TL3 - NodeJup) * cos(B3); SatY[3] := R3 * sin(TL3 - NodeJup) * cos(B3); SatZ[3] := R3 * sin(B3); SatX[4] := R4 * cos(TL4 - NodeJup) * cos(B4); SatY[4] := R4 * sin(TL4 - NodeJup) * cos(B4); SatZ[4] := R4 * sin(B4); SatX[5] := 0; SatY[5] := 0; SatZ[5] := 1; T0 := (AJD - 2451545.0) / 36525.0; TD1 := 100.464441 + 1.0209550 * T0 + 0.00040117 * sqr(T0) + 0.000000569 * sqr(T0) * T0; TD1 := TD1 / radcor; TD2 := 1.303270 - 0.0054966 * T0 + 0.00000465 * sqr(T0) - 0.000000004 * sqr(T0) * T0; TD2 := TD2 / radcor; for I := 1 to 5 do begin Transforms[I].A[1] := SatX[I]; Transforms[I].B[1] := SatY[I] * cos(Inclination) - SatZ[I] * sin(Inclination); Transforms[I].C[1] := SatY[I] * sin(Inclination) + SatZ[I] * cos(Inclination); Transforms[I].A[2] := Transforms[I].A[1] * cos(NodeJup - TD1) - Transforms[I].B[1] * sin(NodeJup - TD1); Transforms[I].B[2] := Transforms[I].A[1] * sin(NodeJup - TD1) + Transforms[I].B[1] * cos(NodeJup - TD1); Transforms[I].C[2] := Transforms[I].C[1]; Transforms[I].A[3] := Transforms[I].A[2]; Transforms[I].B[3] := Transforms[I].B[2] * cos(TD2) - Transforms[I].C[2] * sin(TD2); Transforms[I].C[3] := Transforms[I].B[2] * sin(TD2) + Transforms[I].C[2] * cos(TD2); Transforms[I].A[4] := Transforms[I].A[3] * cos(TD1) - Transforms[I].B[3] * sin(TD1); Transforms[I].B[4] := Transforms[I].A[3] * sin(TD1) + Transforms[I].B[3] * cos(TD1); Transforms[I].C[4] := Transforms[I].C[3]; Transforms[I].A[5] := Transforms[I].A[4] * sin(Jup1) - Transforms[I].B[4] * cos(Jup1); Transforms[I].B[5] := Transforms[I].A[4] * cos(Jup1) + Transforms[I].B[4] * sin(Jup1); Transforms[I].C[5] := Transforms[I].C[4]; Transforms[I].A[6] := Transforms[I].A[5]; Transforms[I].B[6] := Transforms[I].C[5] * sin(Jup2) + Transforms[I].B[5] * cos(Jup2); Transforms[I].C[6] := Transforms[I].C[5] * cos(Jup2) - Transforms[I].B[5] * sin(Jup2); end; Angle := StInvTan2(Transforms[5].C[6], Transforms[5].A[6]); {Io calculations} Result.Io.X := Transforms[1].A[6] * cos(Angle) - Transforms[1].C[6] * sin(Angle); Result.Io.Y := Transforms[1].A[6] * sin(Angle) + Transforms[1].C[6] * cos(Angle); TD1 := Transforms[1].B[6]; {correct for light time} TD2 := abs(TD1) / 17295 * sqrt(1 - sqr(Result.Io.X/R1)); Result.Io.X := Result.Io.X + TD2; {correct for perspective} TD2 := EJDist / (EJDist + TD1/2095); Result.Io.X := Result.Io.X * TD2; Result.Io.Y := Result.Io.Y * TD2; {Europa calculations} Result.Europa.X := Transforms[2].A[6] * cos(Angle) - Transforms[2].C[6] * sin(Angle); Result.Europa.Y := Transforms[2].A[6] * sin(Angle) + Transforms[2].C[6] * cos(Angle); TD1 := Transforms[2].B[6]; {correct for light time} TD2 := abs(TD1) / 21819 * sqrt(1 - sqr(Result.Europa.X/R2)); Result.Europa.X := Result.Europa.X + TD2; {correct for perspective} TD2 := EJDist / (EJDist + TD1/2095); Result.Europa.X := Result.Europa.X * TD2; Result.Europa.Y := Result.Europa.Y * TD2; {Ganymede calculations} Result.Ganymede.X := Transforms[3].A[6] * cos(Angle) - Transforms[3].C[6] * sin(Angle); Result.Ganymede.Y := Transforms[3].A[6] * sin(Angle) + Transforms[3].C[6] * cos(Angle); TD1 := Transforms[3].B[6]; {correct for light time} TD2 := abs(TD1) / 27558 * sqrt(1 - sqr(Result.Ganymede.X/R3)); Result.Ganymede.X := Result.Ganymede.X + TD2; {correct for perspective} TD2 := EJDist / (EJDist + TD1/2095); Result.Ganymede.X := Result.Ganymede.X * TD2; Result.Ganymede.Y := Result.Ganymede.Y * TD2; {Callisto calculations} Result.Callisto.X := Transforms[4].A[6] * cos(Angle) - Transforms[4].C[6] * sin(Angle); Result.Callisto.Y := Transforms[4].A[6] * sin(Angle) + Transforms[4].C[6] * cos(Angle); TD1 := Transforms[4].B[6]; {correct for light time} TD2 := abs(TD1) / 36548 * sqrt(1 - sqr(Result.Callisto.X/R4)); Result.Callisto.X := Result.Callisto.X + TD2; {correct for perspective} TD2 := EJDist / (EJDist + TD1/2095); Result.Callisto.X := Result.Callisto.X * TD2; Result.Callisto.Y := Result.Callisto.Y * TD2; end; {-------------------------------------------------------------------------} function GetJupSats(JD : TDateTime; HighPrecision, Shadows : Boolean) : TStJupSats; begin if not HighPrecision then Result := JupSatsLo(JD) else Result := JupSatsHi(JD, Shadows); end; end.
{*********************************************************} {* VPEDELEM.PAS 1.03 *} {*********************************************************} {* ***** BEGIN LICENSE BLOCK ***** *} {* Version: MPL 1.1 *} {* *} {* The contents of this file are subject to the Mozilla Public License *} {* Version 1.1 (the "License"); you may not use this file except in *} {* compliance with the License. You may obtain a copy of the License at *} {* http://www.mozilla.org/MPL/ *} {* *} {* Software distributed under the License is distributed on an "AS IS" basis, *} {* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License *} {* for the specific language governing rights and limitations under the *} {* License. *} {* *} {* The Original Code is TurboPower Visual PlanIt *} {* *} {* The Initial Developer of the Original Code is TurboPower Software *} {* *} {* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *} {* TurboPower Software Inc. All Rights Reserved. *} {* *} {* Contributor(s): *} {* *} {* ***** END LICENSE BLOCK ***** *} {$I Vp.INC} unit VpEdElem; interface uses {$IFDEF LCL} LMessages,LCLProc,LCLType,LCLIntf, {$ELSE} Windows, {$ENDIF} Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, VpBase, VpSR, VpPrtFmt, ComCtrls; type TfrmEditElement = class(TForm) btnCancel: TButton; btnOk: TButton; btnShape: TButton; edName: TEdit; Label1: TLabel; Label2: TLabel; rgDayOffset: TRadioGroup; rgItemType: TRadioGroup; gbVisual: TGroupBox; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; rgMeasurement: TRadioGroup; rgRotation: TRadioGroup; edTop: TEdit; edLeft: TEdit; edHeight: TEdit; edWidth: TEdit; chkVisible: TCheckBox; gbCaption: TGroupBox; btnCaptionFont: TButton; FontDialog1: TFontDialog; edCaptionText: TEdit; lbCaptionText: TLabel; edOffset: TEdit; udOffset: TUpDown; udTop: TUpDown; udLeft: TUpDown; udHeight: TUpDown; udWidth: TUpDown; procedure btnCancelClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure rgItemTypeClick(Sender: TObject); procedure btnShapeClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnCaptionFontClick(Sender: TObject); procedure edCaptionTextChange(Sender: TObject); procedure rgMeasurementClick(Sender: TObject); procedure PosEditExit(Sender: TObject); procedure PosEditEnter(Sender: TObject); procedure UpDownClick(Sender: TObject; Button: TUDBtnType); private procedure SetMaxSpin(Spin: Integer); protected TheShape : TVpPrintShape; TheCaption : TVpPrintCaption; CurEdit : TEdit; MaxSpin : Integer; procedure SaveData(AnElement: TVpPrintFormatElementItem); procedure SetData(AnElement: TVpPrintFormatElementItem); procedure SetItemType(Index: Integer); function Validate: Boolean; { Private declarations } public function Execute(AnElement : TVpPrintFormatElementItem) : Boolean; { Public declarations } end; implementation uses VpEdShape; {$IFNDEF LCL} {$R *.DFM} {$ENDIF} function EvalFmt(Val : Extended) : string; begin Result := FormatFloat('0.00', Val); end; {=====} procedure TfrmEditElement.FormCreate(Sender: TObject); begin btnShape.Enabled := False; gbCaption.Enabled := False; edCaptionText.Enabled := False; lbCaptionText.Enabled := False; btnCaptionFont.Enabled := False; end; {=====} procedure TfrmEditElement.FormShow(Sender: TObject); begin edName.SetFocus; end; {=====} procedure TfrmEditElement.btnCaptionFontClick(Sender: TObject); begin if FontDialog1.Execute then TheCaption.Font := FontDialog1.Font; end; {=====} procedure TfrmEditElement.btnCancelClick(Sender: TObject); begin ModalResult := mrCancel; end; {=====} procedure TfrmEditElement.btnOkClick(Sender: TObject); begin if Validate then ModalResult := mrOk else begin ShowMessage(RSNeedElementName); edName.SetFocus; Exit; end; end; {=====} procedure TfrmEditElement.btnShapeClick(Sender: TObject); var frmEditShape: TfrmEditShape; begin Application.CreateForm(TfrmEditShape, frmEditShape); frmEditShape.Execute(TheShape); frmEditShape.Free; end; {=====} procedure TfrmEditElement.edCaptionTextChange(Sender: TObject); begin TheCaption.Caption := edCaptionText.Text; end; {=====} function TfrmEditElement.Execute(AnElement : TVpPrintFormatElementItem) : Boolean; begin SetData(AnElement); Result := ShowModal = mrOk; if Result then SaveData(AnElement); end; {=====} procedure TfrmEditElement.PosEditEnter(Sender: TObject); begin CurEdit := (Sender as TEdit); end; {=====} procedure TfrmEditElement.PosEditExit(Sender: TObject); var ed : TEdit; Val : Extended; begin ed := (Sender as TEdit); try Val := StrToFloat(ed.Text); if Val > MaxSpin then begin ed.Text := EvalFmt(MaxSpin); end else if Val < 0.0 then begin ed.Text := EvalFmt(0); end; except on EConvertError do begin ShowMessage('Please Enter a Floating Point Value'); ed.SetFocus; end; end; end; {=====} procedure TfrmEditElement.rgItemTypeClick(Sender: TObject); begin SetItemType(rgItemType.ItemIndex); end; {=====} procedure TfrmEditElement.rgMeasurementClick(Sender: TObject); begin SetMaxSpin(rgMeasurement.ItemIndex); end; {=====} procedure TfrmEditElement.SaveData(AnElement : TVpPrintFormatElementItem); begin AnElement.ElementName := edName.Text; AnElement.DayOffset := udOffset.Position; AnElement.Top := StrToFloat(edTop.Text); AnElement.Left := StrToFloat(edLeft.Text); AnElement.Height:= StrToFloat(edHeight.Text); AnElement.Width := StrToFloat(edWidth.Text); AnElement.ItemType := TVpItemType(rgItemType.ItemIndex); AnElement.DayOffsetUnits := TVpDayUnits(rgDayOffset.ItemIndex); AnElement.Rotation := TVpRotationAngle(rgRotation.ItemIndex); AnElement.Measurement := TVpItemMeasurement(rgMeasurement.ItemIndex); AnElement.Visible := chkVisible.Checked; end; {=====} procedure TfrmEditElement.SetData(AnElement : TVpPrintFormatElementItem); begin edName.Text := AnElement.ElementName; udOffset.Position := AnElement.DayOffset; rgItemType.ItemIndex := Ord(AnElement.ItemType); TheShape := AnElement.Shape; TheCaption := AnElement.Caption; rgDayOffset.ItemIndex := Ord(AnElement.DayOffsetUnits); rgRotation.ItemIndex := Ord(AnElement.Rotation); rgMeasurement.ItemIndex := Ord(AnElement.Measurement); SetMaxSpin(rgMeasurement.ItemIndex); edTop.Text := EvalFmt(AnElement.Top); udTop.Position := Trunc(AnElement.Top); edLeft.Text := EvalFmt(AnElement.Left); udLeft.Position := Trunc(AnElement.Left); edHeight.Text := EvalFmt(AnElement.Height); udHeight.Position := Trunc(AnElement.Height); edWidth.Text := EvalFmt(AnElement.Width); udWidth.Position := Trunc(AnElement.Width); edCaptionText.Text := AnElement.Caption.Caption; FontDialog1.Font := AnElement.Caption.Font; chkVisible.Checked := AnElement.Visible; end; {=====} procedure TfrmEditElement.SetItemType(Index : Integer); begin rgItemType.ItemIndex := Index; gbCaption.Enabled := False; edCaptionText.Enabled := False; lbCaptionText.Enabled := False; btnCaptionFont.Enabled := False; btnShape.Enabled := Index = 4; if Index = 5 then begin gbCaption.Enabled := True; edCaptionText.Enabled := True; lbCaptionText.Enabled := True; btnCaptionFont.Enabled := True; end; end; {=====} procedure TfrmEditElement.SetMaxSpin(Spin : Integer); begin case Spin of 0: MaxSpin := 2000; 1: MaxSpin := 100; 2: MaxSpin := 50; end; udLeft.Max := MaxSpin; udTop.Max := MaxSpin; udHeight.Max := MaxSpin; udWidth.Max := MaxSpin; end; {=====} procedure TfrmEditElement.UpDownClick(Sender: TObject; Button: TUDBtnType); var Val, Inc : Extended; begin if Sender = udLeft then CurEdit := edLeft ; if Sender = udTop then CurEdit := edTop ; if Sender = udHeight then CurEdit := edHeight; if Sender = udWidth then CurEdit := edWidth ; Val := 0.0; try Val := StrToFloat(CurEdit.Text); except on EConvertError do begin ShowMessage('Please Enter a Floating Point Value'); CurEdit.SetFocus; end; end; Inc := udLeft.Increment / 100; case Button of btNext: begin if Trunc(Val + Inc) > Trunc(Val) then (Sender as TUpDown).Position := (Sender as TUpDown).Position + 1; CurEdit.Text := FormatFloat('0.00 ', Val + Inc); end; btPrev: begin if Trunc(Val - Inc) < Trunc(Val) then (Sender as TUpDown).Position := (Sender as TUpDown).Position - 1; CurEdit.Text := FormatFloat('0.00 ', Val - Inc); end; end; end; {=====} function TfrmEditElement.Validate : Boolean; begin Result := edName.Text <> ''; end; {=====} end.
unit untSerialPortNativeThread; {$M+} {$TYPEINFO ON} interface uses Classes, SysUtils, Winapi.Windows, untUtils; type TReceivedData = procedure(Buffer: ByteArray) of Object; type TSerialPortNativeThread = class(TThread) private strCOMPort: string; nBaundRate: integer; hCOMFile: NativeUInt; barReceivedByteArray: ByteArray; bolConnected: boolean; evtReceivedData: TReceivedData; function OpenPort(COMPort: string; BaundRate: integer): integer; protected procedure Execute; override; public property OnReceivedData: TReceivedData read evtReceivedData write evtReceivedData; property Connected: boolean read bolConnected; constructor Create(CreateSuspend: boolean; COMPort: string; BaundRate: integer); destructor Destroy; override; function Write(const Buffer: ByteArray): integer; function Read(var Buffer: ByteArray): integer; published // property ProcessorCount; end; implementation { TSerialPortNativeThread } constructor TSerialPortNativeThread.Create(CreateSuspend: boolean; COMPort: string; BaundRate: integer); begin strCOMPort := COMPort; nBaundRate := BaundRate; if (OpenPort(strCOMPort, nBaundRate) <> 0) then bolConnected := false else bolConnected := true; inherited Create(CreateSuspend); end; destructor TSerialPortNativeThread.Destroy; begin CloseHandle(hCOMFile); end; procedure TSerialPortNativeThread.Execute; var NumberOfByteRead: integer; Buffer: ByteArray; begin inherited; while true do begin NumberOfByteRead := Read(Buffer); if (NumberOfByteRead <> 0) then begin Synchronize( procedure begin if (Assigned(evtReceivedData)) then evtReceivedData(Buffer); end); end; Sleep(10); end; end; function TSerialPortNativeThread.OpenPort(COMPort: string; BaundRate: integer): integer; var setting: DCB; timeouts: COMMTIMEOUTS; dwLastError: DWORD; begin hCOMFile := CreateFile(PWideChar(COMPort), GENERIC_WRITE or GENERIC_READ, 0, nil, OPEN_EXISTING, 0, 0); if hCOMFile = INVALID_HANDLE_VALUE then begin dwLastError := GetLastError; Result := -1; exit; end; SetupComm(hCOMFile, 5120, 128); GetCommState(hCOMFile, setting); setting.BaudRate := CBR_2400; setting.ByteSize := 8; setting.Parity := NOPARITY; setting.StopBits := ONESTOPBIT; setting.XonLim := 2560; setting.XonLim := 640; setting.XonChar := #17; setting.XoffChar := #19; setting.ErrorChar := '?'; setting.EofChar := #0; setting.EvtChar := #0; SetCommState(hCOMFile, setting); timeouts.ReadIntervalTimeout := 100; timeouts.ReadTotalTimeoutMultiplier := 10; timeouts.ReadTotalTimeoutConstant := 10; timeouts.WriteTotalTimeoutMultiplier := 10; timeouts.WriteTotalTimeoutConstant := 10; SetCommTimeouts(hCOMFile, timeouts); SetCommMask(hCOMFile, EV_RXCHAR or EV_TXEMPTY or EV_ERR); PurgeComm(hCOMFile, EV_CTS or EV_DSR or PURGE_TXCLEAR or PURGE_RXABORT or PURGE_TXABORT); Result := 0; end; function TSerialPortNativeThread.Read(var Buffer: ByteArray): integer; var NumberOfBytesRead: DWORD; dwLastError: DWORD; begin if (hCOMFile = INVALID_HANDLE_VALUE) then begin Result := 0; exit; end; SetLength(Buffer, 1024); if ReadFile(hCOMFile, PByte(Buffer)^, Length(Buffer), NumberOfBytesRead, nil) = false then begin dwLastError := GetLastError; Result := 0; exit; end; SetLength(Buffer, NumberOfBytesRead); Result := NumberOfBytesRead; end; function TSerialPortNativeThread.Write(const Buffer: ByteArray): integer; var NumberWritten: Cardinal; begin if (hCOMFile = INVALID_HANDLE_VALUE) then begin Result := 0; exit; end; NumberWritten := 0; WriteFile(hCOMFile, PChar(Buffer)^, Length(Buffer), NumberWritten, nil); Result := NumberWritten; end; end.
unit x1_010; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} {$ifndef windows}main_engine,{$endif} sound_engine,timer_engine; const VOL_BASE=(2*32*256/30); NUM_CHANNELS=16; type x1_010_channel=record status:byte; volume:byte; // volume / wave form no. frequency:byte; // frequency / pitch lo pitch_hi:byte; // reserved / pitch hi start:byte; // start address / envelope time end_:byte; // end address / envelope no. reserve:array[0..1] of byte; end; px1_010_channel=^x1_010_channel; tx1_010=class(snd_chip_class) constructor create(clock:dword); destructor free; public rom:array[0..$fffff] of byte; procedure reset; procedure update; function read16(direccion:word):word; procedure write16(direccion,valor:word); function read(direccion:word):byte; procedure write(direccion:word;valor:byte); function save_snapshot(data:pbyte):word; procedure load_snapshot(data:pbyte); private clock:dword; rate:single; reg:array[0..$1fff] of byte; hi_word_buf:array[0..$1fff] of byte; smp_offset:array[0..(NUM_CHANNELS-1)] of dword; env_offset:array[0..(NUM_CHANNELS-1)] of dword; lsignal,rsignal:smallint; tsample_:byte; end; var x1_010_0:tx1_010; implementation procedure x10_final_update; var ch,div_,vol:byte; reg:px1_010_channel; start,end_,smp_offs,delta,env_offs:dword; volL,volR:integer; data:shortint; env,freq:word; begin x1_010_0.lsignal:=0; x1_010_0.rsignal:=0; for ch:=0 to (NUM_CHANNELS-1) do begin reg:=@x1_010_0.reg[ch*sizeof(x1_010_channel)]; if (reg.status and 1)<>0 then begin //Key On div_:=(reg.status and $80) shr 7; if (reg.status and $2)=0 then begin //PCM Sampling start:=reg.start shl 12; end_:=($100-reg.end_) shl 12; volL:=trunc(((reg.volume shr 4) and $f)*VOL_BASE); volR:=trunc(((reg.volume shr 0) and $f)*VOL_BASE); smp_offs:=x1_010_0.smp_offset[ch]; freq:=reg.frequency shr div_; // Meta Fox does write the frequency register, but this is a hack to make it "work" with the current setup // This is broken for Arbalester (it writes 8), but that'll be fixed later. if (freq=0) then freq:=4; delta:=smp_offs shr 4; // sample ended? if ((start+delta)>=end_) then begin reg.status:=reg.status and $fe; // Key off break; end; data:=shortint(x1_010_0.rom[start+delta]); x1_010_0.lsignal:=x1_010_0.lsignal+((data*volL) shr 8); x1_010_0.rsignal:=x1_010_0.rsignal+((data*volR) shr 8); x1_010_0.smp_offset[ch]:=smp_offs+freq; end else begin //Wave form start:=(reg.volume shl 7)+$1000; smp_offs:=x1_010_0.smp_offset[ch]; freq:=((reg.pitch_hi shl 8)+reg.frequency) shr div_; env:=reg.end_ shl 7; env_offs:=x1_010_0.env_offset[ch]; delta:=env_offs shr 10; // Envelope one shot mode if (((reg.status and 4)<>0) and (delta>=$80)) then begin reg.status:=reg.status and $fe; // Key off break; end; vol:=x1_010_0.reg[env+(delta and $7f)]; volL:=trunc(((vol shr 4) and $f)*VOL_BASE); volR:=trunc(((vol shr 0) and $f)*VOL_BASE); data:=shortint(x1_010_0.reg[start+((smp_offs shr 10) and $7f)]); x1_010_0.lsignal:=x1_010_0.lsignal+((data*volL) shr 8); x1_010_0.rsignal:=x1_010_0.rsignal+((data*volR) shr 8); x1_010_0.smp_offset[ch]:=smp_offs+freq; x1_010_0.env_offset[ch]:=env_offs+reg.start; end; end; end; end; constructor tx1_010.create(clock:dword); begin self.clock:=clock; self.rate:=clock/512; self.reset; timers.init(sound_status.cpu_num,sound_status.cpu_clock/self.rate,x10_final_update,nil,true); self.tsample_:=init_channel; end; destructor tx1_010.free; begin end; procedure tx1_010.reset; var f:byte; begin for f:=0 to (NUM_CHANNELS-1) do begin self.smp_offset[f]:=0; self.env_offset[f]:=0; end; fillchar(self.reg,$2000,0); fillchar(self.hi_word_buf,$2000,0); self.rsignal:=0; self.lsignal:=0; end; procedure tx1_010.update; begin if sound_status.stereo then begin tsample[self.tsample_,sound_status.posicion_sonido]:=self.lsignal; tsample[self.tsample_,sound_status.posicion_sonido+1]:=self.rsignal; end else tsample[self.tsample_,sound_status.posicion_sonido]:=self.lsignal+self.rsignal; end; function tx1_010.save_snapshot(data:pbyte):word; begin end; procedure tx1_010.load_snapshot(data:pbyte); begin end; function tx1_010.read(direccion:word):byte; begin read:=self.reg[direccion]; end; procedure tx1_010.write(direccion:word;valor:byte); var channel,reg:byte; begin channel:=direccion div sizeof(x1_010_channel); reg:=direccion mod sizeof(x1_010_channel); if ((channel<NUM_CHANNELS) and (reg=0) and ((self.reg[direccion] and 1)=0) and ((valor and 1)<>0)) then begin self.smp_offset[channel]:=0; self.env_offset[channel]:=0; end; self.reg[direccion]:=valor; end; function tx1_010.read16(direccion:word):word; var ret:word; begin ret:=(self.hi_word_buf[direccion] shl 8) or self.reg[direccion]; read16:=ret; end; procedure tx1_010.write16(direccion,valor:word); begin self.hi_word_buf[direccion]:=valor shr 8; self.write(direccion,valor and $ff); end; end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.FingerprintCompressor; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.BitString, CP.Def; const kMaxNormalValue = integer(7); kNormalBits = integer(3); kExceptionBits = integer(5); type { TFingerprintCompressor } TFingerprintCompressor = class(TObject) private FResult: string; FBits: array of byte; private procedure WriteNormalBits(); procedure WriteExceptionBits(); procedure ProcessSubfingerprint(x: uint32); public constructor Create; function Compress(fingerprint: TUINT32Array; algorithm: integer = 0): string; end; TFingerprintDecompressor = class(TObject) private FResult: TUINT32Array; FBits: array of byte; function ReadNormalBits(reader: TBitStringReader): boolean; function ReadExceptionBits(reader: TBitStringReader): boolean; procedure UnpackBits(); public constructor Create; function Decompress(fingerprint: string; var algorithm: integer): TUINT32Array; end; function CompressFingerprint(Data: TUINT32Array; algorithm: integer = 0): string; inline; function DecompressFingerprint(Data: string; var algorithm: integer): TUINT32Array; inline; implementation uses Math {$IFDEF FPC} , DaMath {$ENDIF}; function CompressFingerprint(Data: TUINT32Array; algorithm: integer = 0): string; inline; var compressor: TFingerprintCompressor; begin compressor := TFingerprintCompressor.Create; try Result := compressor.Compress(Data, algorithm); finally compressor.Free; end; end; function DecompressFingerprint(Data: string; var algorithm: integer): TUINT32Array; inline; var decompressor: TFingerprintDecompressor; begin decompressor := TFingerprintDecompressor.Create; try Result := decompressor.Decompress(Data, algorithm); finally decompressor.Free; end; end; { TFingerprintCompressor } constructor TFingerprintCompressor.Create; begin end; procedure TFingerprintCompressor.ProcessSubfingerprint(x: uint32); var bit, last_bit, n: integer; begin bit := 1; last_bit := 0; while (x <> 0) do begin if ((x and 1) <> 0) then begin n := Length(FBits); SetLength(FBits, n + 1); FBits[n] := (bit - last_bit); last_bit := bit; end; x := x shr 1; Inc(bit); end; n := Length(FBits); SetLength(FBits, n + 1); FBits[n] := 0; end; procedure TFingerprintCompressor.WriteExceptionBits; var writer: TBitStringWriter; i: integer; begin writer := TBitStringWriter.Create; for i := 0 to Length(FBits) - 1 do begin if (FBits[i] >= kMaxNormalValue) then begin writer.Write(FBits[i] - kMaxNormalValue, kExceptionBits); end; end; writer.Flush(); FResult := FResult + writer.Value; writer.Free; end; procedure TFingerprintCompressor.WriteNormalBits; var writer: TBitStringWriter; i: integer; begin writer := TBitStringWriter.Create; for i := 0 to Length(FBits) - 1 do begin writer.Write(Math.Min(FBits[i], kMaxNormalValue), kNormalBits); end; writer.Flush(); FResult := FResult + writer.Value; writer.Free; end; function TFingerprintCompressor.Compress(fingerprint: TUINT32Array; algorithm: integer = 0): string; var i, n: integer; begin n := Length(fingerprint); if n > 0 then begin ProcessSubfingerprint(fingerprint[0]); for i := 1 to n - 1 do begin ProcessSubfingerprint(fingerprint[i] xor fingerprint[i - 1]); end; end; FResult := chr(algorithm and 255); FResult := FResult + chr((n shr 16) and 255); FResult := FResult + chr((n shr 8) and 255); FResult := FResult + chr(n and 255); WriteNormalBits(); WriteExceptionBits(); Result := FResult; end; { TFingerprintDecompressor } constructor TFingerprintDecompressor.Create; begin end; function TFingerprintDecompressor.Decompress(fingerprint: string; var algorithm: integer): TUINT32Array; var n: integer; reader: TBitStringReader; begin SetLength(Result, 0); if Length(fingerprint) < 4 then begin // OutputDebugString('FingerprintDecompressor::Decompress() -- Invalid fingerprint (shorter than 4 bytes)'); Exit; end; if algorithm <> 0 then algorithm := Ord(fingerprint[1]); n := (Ord(fingerprint[2]) shl 16) or (Ord(fingerprint[3]) shl 8) or (Ord(fingerprint[4])); reader := TBitStringReader.Create(fingerprint); reader.Read(8); reader.Read(8); reader.Read(8); reader.Read(8); if (reader.AvailableBits < n * kNormalBits) then begin // DEBUG("FingerprintDecompressor::Decompress() -- Invalid fingerprint (too short)"); reader.Free; Exit; end; SetLength(FResult, n); reader.Reset(); if (not ReadNormalBits(reader)) then begin reader.Free; Exit; end; reader.Reset(); if (not ReadExceptionBits(reader)) then begin reader.Free; Exit; end; UnpackBits(); Result := FResult; end; function TFingerprintDecompressor.ReadExceptionBits(reader: TBitStringReader): boolean; var i: integer; begin for i := 0 to Length(FBits) - 1 do begin if (FBits[i] = kMaxNormalValue) then begin if (reader.EOF) then begin // OutptuDebugString('FingerprintDecompressor.ReadExceptionBits() -- Invalid fingerprint (reached EOF while reading exception bits)'); Result := False; Exit; end; FBits[i] := FBits[i] + reader.Read(kExceptionBits); end; end; Result := True; end; function TFingerprintDecompressor.ReadNormalBits(reader: TBitStringReader): boolean; var i, bit, n: integer; begin i := 0; while (i < Length(FResult)) do begin bit := reader.Read(kNormalBits); if (bit = 0) then Inc(i); n := Length(FBits); SetLength(FBits, n + 1); FBits[n] := bit; end; Result := True; end; procedure TFingerprintDecompressor.UnpackBits; var i, last_bit, j, bit: integer; Value: uint32; begin i := 0; last_bit := 0; Value := 0; for j := 0 to Length(FBits) - 1 do begin bit := FBits[j]; if (bit = 0) then begin if (i > 0) then FResult[i] := Value xor FResult[i - 1] else FResult[i] := Value; Value := 0; last_bit := 0; Inc(i); continue; end; bit := bit + last_bit; last_bit := bit; Value := Value or (1 shl (bit - 1)); end; end; end.
unit PPMdSubAllocator; {$mode delphi} {$packrecords c} interface uses CTypes; type PPPMdSubAllocator = ^TPPMdSubAllocator; TPPMdSubAllocator = record Init: procedure(self: PPPMdSubAllocator); AllocContext: function(self: PPPMdSubAllocator): cuint32; AllocUnits: function(self: PPPMdSubAllocator; num: cint): cuint32; // 1 unit == 12 bytes, NU <= 128 ExpandUnits: function(self: PPPMdSubAllocator; oldoffs: cuint32; oldnum: cint): cuint32; ShrinkUnits: function(self: PPPMdSubAllocator; oldoffs: cuint32; oldnum: cint; newnum: cint): cuint32; FreeUnits: procedure(self: PPPMdSubAllocator; offs: cuint32; num: cint); end; procedure InitSubAllocator(self: PPPMdSubAllocator); inline; function AllocContext(self: PPPMdSubAllocator): cuint32; inline; function AllocUnits(self: PPPMdSubAllocator; num: cint): cuint32; inline; function ExpandUnits(self: PPPMdSubAllocator; oldoffs: cuint32; oldnum: cint): cuint32; inline; function ShrinkUnits(self: PPPMdSubAllocator; oldoffs: cuint32; oldnum: cint; newnum: cint): cuint32; inline; procedure FreeUnits(self: PPPMdSubAllocator; offs: cuint32; num: cint); inline; function OffsetToPointer(self: PPPMdSubAllocator; offset: cuint32): Pointer; function PointerToOffset(self: PPPMdSubAllocator; pointer: Pointer): cuint32; implementation procedure InitSubAllocator(self: PPPMdSubAllocator); begin self^.Init(self); end; function AllocContext(self: PPPMdSubAllocator): cuint32; begin Result:= self^.AllocContext(self); end; function AllocUnits(self: PPPMdSubAllocator; num: cint): cuint32; begin Result:= self^.AllocUnits(self, num); end; function ExpandUnits(self: PPPMdSubAllocator; oldoffs: cuint32; oldnum: cint): cuint32; begin Result:= self^.ExpandUnits(self, oldoffs, oldnum); end; function ShrinkUnits(self: PPPMdSubAllocator; oldoffs: cuint32; oldnum: cint; newnum: cint): cuint32; begin Result:= self^.ShrinkUnits(self, oldoffs, oldnum, newnum); end; procedure FreeUnits(self: PPPMdSubAllocator; offs: cuint32; num: cint); begin self^.FreeUnits(self, offs, num); end; // TODO: Keep pointers as pointers on 32 bit, and offsets on 64 bit. function OffsetToPointer(self: PPPMdSubAllocator; offset: cuint32): Pointer; begin if (offset = 0) then Exit(nil); Result:= pcuint8(self) + offset; end; function PointerToOffset(self: PPPMdSubAllocator; pointer: Pointer): cuint32; begin if (pointer = nil) then Exit(0); Result:= ptruint(pointer) - ptruint(self); end; end.
Unit CoreMath; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] 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} {$inline on} interface uses Math, SysUtils, CoreTypes; function Radians(Dgrs: Extended): Extended; Inline; function Degrees(Rads: Extended): Extended; Inline; {* "Real" modulo operation *} function Modulo(X,Y:Extended): Extended; Inline; overload; function Modulo(X,Y:Double): Double; Inline; overload; function Modulo(X,Y:Single): Single; Inline; overload; function Modulo(X,Y:Int32): Int32; Inline; overload; {* Angle between two angles *} function DeltaAngle(DegA,DegB:Extended): Extended; Inline; {* Distance calcs *} function DistManhattan(const pt1,pt2: TPoint): Extended; Inline; function DistEuclidean(const pt1,pt2: TPoint): Extended; Inline; function DistChebyshev(const pt1,pt2: TPoint): Extended; Inline; function DistOctagonal(const pt1,pt2: TPoint): Extended; Inline; function DistToLine(Pt, sA, sB: TPoint): Extended; Inline; {* In shape *} function InCircle(const Pt,Center:TPoint; Radius: Integer): Boolean; Inline; function InEllipse(const Pt,Center:TPoint; YRad, XRad: Integer): Boolean; Inline; function InRect(const Pt:TPoint; const A,B,C,D:TPoint): Boolean; Inline; function InPoly(x,y:Integer; const Poly:TPointArray): Boolean; Inline; function InPolyR(x,y:Integer; const Poly:TPointArray): Boolean; Inline; function InPolyW(x,y:Integer; const Poly:TPointArray): Boolean; Inline; function InBox(const Pt:TPoint; X1,Y1, X2,Y2: Integer): Boolean; Inline; function InTriangle(const Pt, v1, v2, v3:TPoint): Boolean; Inline; {* Prime *} function IsPrime(n: Integer): Boolean; Inline; function NextPrime(n: Integer): Integer; inline; function PrevPrime(n: Integer): Integer; inline; {* Next power of two minus 1 *} function NextPow2m1(n: Integer): Integer; Inline; {* Select min of 3 values *} function Min(X,Y,Z:Extended): Extended; Inline; overload; function Min(X,Y,Z:Double): Double; Inline; overload; function Min(X,Y,Z:Single): Single; Inline; overload; function Min(X,Y,Z:Int64): Int64; Inline; overload; function Min(X,Y,Z:Int32): Int32; Inline; overload; {* Select max of 3 values *} function Max(X,Y,Z:Extended): Extended; Inline; overload; function Max(X,Y,Z:Double): Double; Inline; overload; function Max(X,Y,Z:Single): Single; Inline; overload; function Max(X,Y,Z:Int64): Int64; Inline; overload; function Max(X,Y,Z:Int32): Int32; Inline; overload; //-------------------------------------------------- implementation uses CoreMisc; {* Converts Degrees in to radian *} function Radians(Dgrs: Extended): Extended; Inline; begin Result := Dgrs * (Pi/180); end; {* Converts Radian in to Degrees *} function Degrees(Rads: Extended): Extended; Inline; begin Result := Rads * (180/Pi); end; {* "Real" modulus function as seen in: WolframAlpha, MatLab and Python, and many more "modern" programming languages. *} function Modulo(X,Y:Extended): Extended; Inline; overload; begin Result := X - Floor(X / Y) * Y; end; function Modulo(X,Y:Double): Double; Inline; overload; begin Result := X - Floor(X / Y) * Y; end; function Modulo(X,Y:Single): Single; Inline; overload; begin Result := X - Floor(X / Y) * Y; end; function Modulo(X,Y:Int32): Int32; Inline; overload; begin Result := X - Floor(X / Y) * Y; end; {* Computes the delta of two angles. The result is in range of -180..180. *} function DeltaAngle(DegA,DegB:Extended): Extended; Inline; begin Result := Modulo((DegA - DegB + 180), 360) - 180; end; //============================================================================\\ {============================ DISTANCE CALCULATIONS ===========================} {==============================================================================} {* Manhattan distance is a simple, and cheap way to get distnace between two points *} function DistManhattan(const pt1,pt2: TPoint): Extended; Inline; begin Result := (Abs(pt1.x - pt2.x) + Abs(pt1.y - pt2.y)); end; {* Distance measured in a streight line from pt1 to pt2. Uses pythagorean theorem... *} function DistEuclidean(const pt1,pt2: TPoint): Extended; Inline; begin Result := Sqrt(Sqr(pt1.x - pt2.x) + Sqr(pt1.y - pt2.y)); end; {* Distance in the form of "amount of steps" in a any direction. EG: Think of the 8 possible moves the King can do on a chessboard, that = 1 distnace. *} function DistChebyshev(const pt1,pt2: TPoint): Extended; Inline; begin Result := Max(Abs(pt1.x - pt2.x), Abs(pt1.y - pt2.y)); end; {* Distance is measured as a middle-thing of Manhattan and Chebyshev-distance. This results in eight 45degr corners, aka a octagon. It's close to as fast as Chebyshev, and Manhattan. @magic_number: 0.414213562 = Sqrt(2)-1 *} function DistOctagonal(const pt1,pt2: TPoint): Extended; Inline; var dx,dy:Integer; begin dx := Abs(pt1.x - pt2.x); dy := Abs(pt1.y - pt2.y); if dx >= dy then Result := dx + (dy * 0.414213562) else Result := dy + (dx * 0.414213562); end; {* Distance from Pt to the line-segment defined by sA-sB. *} function DistToLine(Pt, sA, sB: TPoint): Extended; Inline; var dx,dy,d:integer; f: Single; qt:TPoint; begin dx := sB.x - sA.x; dy := sB.y - sA.y; d := dx*dx + dy*dy; if (d = 0) then Exit(DistEuclidean(pt, sA)); f := ((pt.x - sA.x) * (dx) + (pt.y - sA.y) * (dy)) / d; if (f < 0) then Exit(DistEuclidean(pt, sA)); if (f > 1) then Exit(DistEuclidean(pt, sB)); qt.x := Round(sA.x + f * dx); qt.y := Round(sA.y + f * dy); Result := DistEuclidean(pt, qt); end; //============================================================================\\ {============================= SHAPE CALCULATIONS =============================} {==============================================================================} {* Check if a point is within a circle. *} function InCircle(const Pt, Center: TPoint; Radius: Integer): Boolean; Inline; begin Result := Sqr(Pt.X - Center.X) + Sqr(Pt.Y - Center.Y) <= Sqr(Radius); end; {* Check if a point is within a ellipse. *} function InEllipse(const Pt,Center:TPoint; YRad, XRad: Integer): Boolean; Inline; var X, Y: Integer; begin X := Pt.X - Center.X; Y := Pt.Y - Center.Y; Result := (Sqr(X)*Sqr(YRad))+(Sqr(Y)*Sqr(XRad)) <= (Sqr(YRad)*Sqr(XRad)); end; {* Is the coordiants within a rectangle (defined by four points)? > C is not actually used, but for future extension/changes, i'll leave it here. *} function InRect(const Pt:TPoint; const A,B,C,D:TPoint): Boolean; Inline; var Vec:TPoint; Dot:Extended; begin Vec := Point(A.x-B.x, A.y-B.y); Dot := ((A.x-Pt.x) * Vec.x) + ((A.y-Pt.y) * Vec.y); if not((0 <= Dot) and (Dot <= (Sqr(Vec.x) + Sqr(Vec.y)))) then Exit(False); Vec := Point(A.x-D.x, A.y-D.y); Dot := ((A.x-Pt.x) * Vec.x) + ((A.y-Pt.y) * Vec.y); if not((0 <= Dot) and (Dot <= (Sqr(Vec.x) + Sqr(Vec.y)))) then Exit(False); Result := True; end; {* Is the coordiants within a box aligned with the axes? *} function InBox(const Pt:TPoint; X1,Y1, X2,Y2: Integer): Boolean; Inline; begin Result:= (Pt.X >= X1) and (Pt.X <= X2) and (Pt.Y >= Y1) and (Pt.Y <= Y2); end; {* Check if a point is within a polygon/shape by the given outline points (poly) The points must be in order, as if you would draw a line trough each point. @note: Ray casting combined with Winding number algorithm *} function InPoly(x,y:Integer; const Poly:TPointArray): Boolean; Inline; var WN,H,i,j:Integer; RC:Boolean; begin WN := 0; H := High(poly); j := H; RC := False; for i:=0 to H do begin if ((Poly[i].x = x) and (Poly[i].y = y)) then Exit(True); if ((poly[i].y < y) and (poly[j].y >= y) or (poly[j].y < y) and (poly[i].y >= y)) then if (poly[i].x+(y-poly[i].y) / (poly[j].y-poly[i].y) * (poly[j].x-poly[i].x) < x) then RC := Not(RC); if (poly[i].y <= y) then begin if (poly[j].y > y) then if (((poly[j].x-poly[i].x)*(y-poly[i].y)-(x-poly[i].x)*(poly[j].y-poly[i].y)) > 0) then Inc(WN); end else if poly[j].y <= y then if (((poly[j].x-poly[i].x)*(y-poly[i].y)-(x-poly[i].x)*(poly[j].y-poly[i].y)) < 0) then Dec(WN); j := i; end; Result := (WN <> 0) or (rc); end; {* Check if a point is within a polygon/shape by the given outline points (poly) The points must be in order, as if you would draw a line trough each point. @note: Ray casting algorithm *} function InPolyR(x,y:Integer; const Poly:TPointArray): Boolean; Inline; var j,i,H: Integer; begin H := High(poly); j := H; Result := False; for i:=0 to H do begin if ((poly[i].y < y) and (poly[j].y >= y) or (poly[j].y < y) and (poly[i].y >= y)) then if (poly[i].x+(y-poly[i].y) / (poly[j].y-poly[i].y) * (poly[j].x-poly[i].x) < x) then Result := not(Result); j := i; end; end; {* Check if a point is within a polygon/shape by the given outline points (poly) The points must be in order, as if you would draw a line trough each point. @note: Winding number algorithm *} function InPolyW(x,y:Integer; const Poly:TPointArray): Boolean; Inline; var wn,H,i,j:Integer; begin wn := 0; H := High(poly); j := H; for i:=0 to H do begin //if ((Poly[i].x = x) and (Poly[i].y = y)) then // Exit(True); if (poly[i].y <= y) then begin if (poly[j].y > y) then if (((poly[j].x-poly[i].x)*(y-poly[i].y)-(x-poly[i].x)*(poly[j].y-poly[i].y)) > 0) then Inc(wn); end else if poly[j].y <= y then if (((poly[j].x-poly[i].x)*(y-poly[i].y)-(x-poly[i].x)*(poly[j].y-poly[i].y)) < 0) then Dec(wn); j := i; end; Result := (wn <> 0); end; function InTriangle(const Pt, v1, v2, v3:TPoint): Boolean; Inline; var b1,b2,b3: Boolean; p1,p2,p3: TPoint; begin p1:=v1; p2:=v2; p3:=v3; if p3.y < p1.y then Exch(p1,p3); if p1.x > p2.x then Exch(p1,p2); b1 := (pt.x - p2.x) * (p1.y - p2.y) - (p1.x - p2.x) * (pt.y - p2.y) < 0; b2 := (pt.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (pt.y - p3.y) < 0; if (b1 <> b2) then Exit; b3 := (pt.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (pt.y - p1.y) < 0; if (b2 <> b3) then Exit; Result := True; end; //============================================================================\\ {=================================== GENERAL ==================================} {==============================================================================} function IsPrime(n: Integer): Boolean; Inline; var i:Integer; Hi: Single; begin if (n = 2) then Exit(True); if (n and 2 = 0) or (n<=1) then Exit(False); Hi := Sqrt(n)+1; i := 3; while i <= Hi do begin if ((n mod i) = 0) then Exit(False); i := i + 2; end; Result := True; end; function NextPrime(n: Integer): Integer; inline; begin Inc(n); while Not(IsPrime(n)) do Inc(n); Result := n; end; function PrevPrime(n: Integer): Integer; inline; begin Dec(n); while Not(IsPrime(n)) do Dec(n); Result := n; end; function NextPow2m1(n: Integer): Integer; Inline; begin n := n - 1; n := n or (n shr 1); n := n or (n shr 2); n := n or (n shr 4); n := n or (n shr 8); n := n or (n shr 16); n := n or (n shr 32); Result := n; end; {* Select min of 3 values. *} function Min(X,Y,Z:Extended): Extended; Inline; overload; begin Result := Min(x,Min(y,z)); end; function Min(X,Y,Z:Double): Double; Inline; overload; begin Result := Min(x,Min(y,z)); end; function Min(X,Y,Z:Single): Single; Inline; overload; begin Result := Min(x,Min(y,z)); end; function Min(X,Y,Z:Int64): Int64; Inline; overload; begin Result := Min(x,Min(y,z)); end; function Min(X,Y,Z:Int32): Int32; Inline; overload; begin Result := Min(x,Min(y,z)); end; {* Select max of 3 values. *} function Max(X,Y,Z:Extended): Extended; Inline; overload; begin Result := Max(x,Max(y,z)); end; function Max(X,Y,Z:Double): Double; Inline; overload; begin Result := Max(x,Max(y,z)); end; function Max(X,Y,Z:Single): Single; Inline; overload; begin Result := Max(x,Max(y,z)); end; function Max(X,Y,Z:Int64): Int64; Inline; overload; begin Result := Max(x,Max(y,z)); end; function Max(X,Y,Z:Int32): Int32; Inline; overload; begin Result := Max(x,Max(y,z)); 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.6 11/12/2004 11:31:06 AM JPMugaas IPv6 expansions. Rev 1.5 2004.02.03 5:45:00 PM czhower Name changes Rev 1.4 10/19/2003 11:48:12 AM DSiders Added localization comments. Rev 1.3 4/5/2003 7:27:48 PM BGooijen Checks for errors, added authorisation Rev 1.2 4/1/2003 4:14:22 PM BGooijen Fixed + cleaned up Rev 1.1 2/24/2003 08:20:46 PM JPMugaas Now should compile with new code. Rev 1.0 11/14/2002 02:16:10 PM JPMugaas } unit IdConnectThroughHttpProxy; { implements: http://www.web-cache.com/Writings/Internet-Drafts/draft-luotonen-web-proxy-tunneling-01.txt } interface {$i IdCompilerDefines.inc} uses IdCustomTransparentProxy, IdGlobal, IdIOHandler; type TIdConnectThroughHttpProxy = class(TIdCustomTransparentProxy) private FAuthorizationRequired: Boolean; protected FEnabled: Boolean; function GetEnabled: Boolean; override; procedure SetEnabled(AValue: Boolean); override; procedure MakeConnection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); override; procedure DoMakeConnection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const ALogin:boolean; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION);virtual; public published property Enabled; property Host; property Port; property ChainedProxy; property Username; property Password; end; implementation uses IdCoderMIME, IdExceptionCore, IdHeaderList, IdGlobalProtocols, SysUtils; { TIdConnectThroughHttpProxy } function TIdConnectThroughHttpProxy.GetEnabled: Boolean; begin Result := FEnabled; end; procedure TIdConnectThroughHttpProxy.DoMakeConnection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const ALogin: Boolean; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); var LStatus: string; LResponseCode: Integer; LHeaders: TIdHeaderList; LContentLength: Int64; begin LHeaders := TIdHeaderList.Create(QuoteHTTP); try AIOHandler.WriteLn(IndyFormat('CONNECT %s:%d HTTP/1.0', [AHost,APort])); {do not localize} if ALogin then begin with TIdEncoderMIME.Create do try AIOHandler.WriteLn('Proxy-Authorization: Basic ' + Encode(Username + ':' + Password)); {do not localize} finally Free; end; end; AIOHandler.WriteLn; LStatus := AIOHandler.ReadLn; if LStatus <> '' then begin // if empty response then we assume it succeeded AIOHandler.Capture(LHeaders, '', False); // TODO: support chunked replies... LContentLength := IndyStrToInt64(LHeaders.Values['Content-Length'], -1); {do not localize} if LContentLength > 0 then begin AIOHandler.Discard(LContentLength); end; Fetch(LStatus);// to remove the http/1.0 or http/1.1 LResponseCode := IndyStrToInt(Fetch(LStatus, ' ', False), 200); // if invalid response then we assume it succeeded if (LResponseCode = 407) and (Length(Username) > 0) and (not ALogin) then begin // authorization required if TextIsSame(LHeaders.Values['Proxy-Connection'], 'close') then begin {do not localize} // need to reconnect before trying again with login AIOHandler.Close; FAuthorizationRequired := True; try AIOHandler.Open; finally FAuthorizationRequired := False; end; end else begin // still connected so try again with login DoMakeConnection(AIOHandler, AHost, APort, True); end; end else if not (LResponseCode in [200]) then begin // maybe more responsecodes to add raise EIdHttpProxyError.Create(LStatus);//BGO: TODO: maybe split into more exceptions? end; end; finally LHeaders.Free; end; end; procedure TIdConnectThroughHttpProxy.MakeConnection(AIOHandler: TIdIOHandler; const AHost: string; const APort: TIdPort; const AIPVersion: TIdIPVersion = ID_DEFAULT_IP_VERSION); begin DoMakeConnection(AIOHandler, AHost, APort, FAuthorizationRequired); end; procedure TIdConnectThroughHttpProxy.SetEnabled(AValue: Boolean); begin FEnabled := AValue; end; end.
unit ICollections.Default; interface type IEnumerator<T> = interface function GetCurrent: T; property Current: T read GetCurrent; function MoveNext: Boolean; end; IEnumerable<T> = interface function GetEnumerator: IEnumerator<T>; end; implementation end.
unit NurseStationClientModuleU; interface uses System.SysUtils, System.Classes, IPPeerClient, REST.Backend.EMSProvider, REST.Backend.PushTypes, System.JSON, REST.Backend.EMSPushDevice, System.PushNotification, REST.Backend.EMSServices, REST.Backend.ServiceTypes, REST.Backend.MetaTypes, REST.Backend.BindSource, REST.Backend.ServiceComponents, Data.Bind.Components, Data.Bind.ObjectScope, REST.Backend.PushDevice, REST.Backend.Providers, REST.Client, REST.Backend.EndPoint; type TNurseStationClientModule = class(TDataModule) EMSProvider1: TEMSProvider; PushEvents1: TPushEvents; BackendAuth1: TBackendAuth; BackendUsers1: TBackendUsers; BackendEndpointSendMessageNurse: TBackendEndpoint; BackendEndpointSendMessagePatient: TBackendEndpoint; BackendEndpointGetPatient: TBackendEndpoint; BackendEndpointAddPatient: TBackendEndpoint; procedure PushEvents1PushReceived(Sender: TObject; const AData: TPushData); procedure PushEvents1DeviceTokenReceived(Sender: TObject); private { Private declarations } FOnPushReceived: TProc<string, TJSONObject>; FOnDeviceTokenReceived: TProc; public procedure AddPatientData(const APatient : TJSONObject); function GetPatientData(const AUserId : string): TJSONObject; public { Public declarations } procedure Login(const AUserName, APassword: string); procedure Logout; procedure Signup(const AUserName, APassword: string); procedure PushRegisterPatient; procedure PushRegisterNurse; procedure SendMessageNurse(const AStatus : string); procedure SendMessagePatient(const AUserId : String); function GetDescription: String; overload; function GetDescription(const AUserId : String): String; overload; property OnDeviceTokenReceived : TProc read FOnDeviceTokenReceived write FOnDeviceTokenReceived; property OnPushReceived : TProc<string, TJSONObject> read FOnPushReceived write FOnPushReceived; end; var NurseStationClientModule: TNurseStationClientModule; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} { TNurseStationClientModule } procedure TNurseStationClientModule.AddPatientData(const APatient: TJSONObject); var LBackend : TBackendEndpoint; begin LBackend := BackendEndpointAddPatient; LBackend.AddBody(APatient); LBackend.Execute(); end; function TNurseStationClientModule.GetDescription(const AUserId: String): String; var LUser : TBackendEntityValue; LArray : TJSOnArray; begin LArray := TJSONArray.Create(); try BackendUsers1.Users.FindUser(AUserId, LUser, LArray); Result := LArray.Items[0].GetValue<string>('description'); finally LArray.Free; end; end; function TNurseStationClientModule.GetPatientData(const AUserId : string): TJSONObject; var LBackend : TBackendEndpoint; begin LBackend := BackendEndpointGetPatient; LBackend.Params.Items[0].Value := AUserId; LBackend.Execute(); Result := (LBackend.Response.JSONValue as TJSONObject); end; procedure TNurseStationClientModule.Login(const AUserName, APassword: string); begin BackendAuth1.UserName := AUserName; BackendAuth1.Password := APassword; BackendAuth1.Login(); end; procedure TNurseStationClientModule.Logout; begin BackendAuth1.Logout(); end; procedure TNurseStationClientModule.PushEvents1DeviceTokenReceived( Sender: TObject); begin if Assigned(FOnDeviceTokenReceived) then FOnDeviceTokenReceived; end; procedure TNurseStationClientModule.PushEvents1PushReceived(Sender: TObject; const AData: TPushData); var LJSONObject: TJSONObject; begin if Assigned(FOnPushReceived) then begin LJSONObject := TJSONObject.Create; try AData.Extras.Save(LJSONObject, ''); FOnPushReceived(AData.Message, LJSONObject); finally LJSONObject.Free; end; end; end; procedure TNurseStationClientModule.PushRegisterNurse; var LProp : TJSONObject; begin if(PushEvents1.DeviceToken <> '')then begin LProp := TJSONObject.Create; try LProp.AddPair('nurseuser', 'nurses'); PushEvents1.RegisterDevice(LProp); finally LProp.Free; end; end; end; function TNurseStationClientModule.GetDescription : String; var LUser : TBackendEntityValue; LArray : TJSONArray; begin LArray := TJSONArray.Create; try BackendUsers1.Users.QueryUserName(BackendAuth1.UserName, LUser, LArray); Result := LArray.Items[0].GetValue<string>('description'); finally LArray.Free; end; end; procedure TNurseStationClientModule.PushRegisterPatient; var LProp : TJSONObject; LUser : TBackendEntityValue; begin if(PushEvents1.DeviceToken <> '')then begin LProp := TJSONObject.Create; try // Get the user Id BackendUsers1.Users.QueryUserName(BackendAuth1.UserName, LUser); LProp.AddPair('nurseuser', LUser.ObjectID); PushEvents1.RegisterDevice(LProp); finally LProp.Free; end; end; end; procedure TNurseStationClientModule.SendMessageNurse(const AStatus : string); var Backend : TBackendEndpoint; begin Backend := BackendEndpointSendMessageNurse; Backend.Params.Items[0].Value := AStatus; Backend.Execute(); end; procedure TNurseStationClientModule.SendMessagePatient(const AUserId: String); var Backend : TBackendEndpoint; begin Backend := BackendEndpointSendMessagePatient; backend.Params[0].Value := AUserId; Backend.Execute(); end; procedure TNurseStationClientModule.Signup(const AUserName, APassword: string); begin BackendAuth1.UserName := AUserName; BackendAuth1.Password := APassword; BackendAuth1.Signup(); end; end.
unit xdg_shell_unstable_v5_protocol; {$mode objfpc} {$H+} {$interfaces corba} interface uses Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol; type Pxdg_shell = Pointer; Pxdg_surface = Pointer; Pxdg_popup = Pointer; const XDG_SHELL_VERSION_CURRENT = 5; // Always the latest version XDG_SHELL_ERROR_ROLE = 0; // given wl_surface has another role XDG_SHELL_ERROR_DEFUNCT_SURFACES = 1; // xdg_shell was destroyed before children XDG_SHELL_ERROR_NOT_THE_TOPMOST_POPUP = 2; // the client tried to map or destroy a non-topmost popup XDG_SHELL_ERROR_INVALID_POPUP_PARENT = 3; // the client specified an invalid popup parent surface type Pxdg_shell_listener = ^Txdg_shell_listener; Txdg_shell_listener = record ping : procedure(data: Pointer; AXdgShell: Pxdg_shell; ASerial: DWord); cdecl; end; const XDG_SURFACE_RESIZE_EDGE_NONE = 0; // XDG_SURFACE_RESIZE_EDGE_TOP = 1; // XDG_SURFACE_RESIZE_EDGE_BOTTOM = 2; // XDG_SURFACE_RESIZE_EDGE_LEFT = 4; // XDG_SURFACE_RESIZE_EDGE_TOP_LEFT = 5; // XDG_SURFACE_RESIZE_EDGE_BOTTOM_LEFT = 6; // XDG_SURFACE_RESIZE_EDGE_RIGHT = 8; // XDG_SURFACE_RESIZE_EDGE_TOP_RIGHT = 9; // XDG_SURFACE_RESIZE_EDGE_BOTTOM_RIGHT = 10; // XDG_SURFACE_STATE_MAXIMIZED = 1; // the surface is maximized XDG_SURFACE_STATE_FULLSCREEN = 2; // the surface is fullscreen XDG_SURFACE_STATE_RESIZING = 3; // the surface is being resized XDG_SURFACE_STATE_ACTIVATED = 4; // the surface is now activated type Pxdg_surface_listener = ^Txdg_surface_listener; Txdg_surface_listener = record configure : procedure(data: Pointer; AXdgSurface: Pxdg_surface; AWidth: LongInt; AHeight: LongInt; AStates: Pwl_array; ASerial: DWord); cdecl; close : procedure(data: Pointer; AXdgSurface: Pxdg_surface); cdecl; end; Pxdg_popup_listener = ^Txdg_popup_listener; Txdg_popup_listener = record popup_done : procedure(data: Pointer; AXdgPopup: Pxdg_popup); cdecl; end; TXdgShell = class; TXdgSurface = class; TXdgPopup = class; IXdgShellListener = interface ['IXdgShellListener'] procedure xdg_shell_ping(AXdgShell: TXdgShell; ASerial: DWord); end; IXdgSurfaceListener = interface ['IXdgSurfaceListener'] procedure xdg_surface_configure(AXdgSurface: TXdgSurface; AWidth: LongInt; AHeight: LongInt; AStates: Pwl_array; ASerial: DWord); procedure xdg_surface_close(AXdgSurface: TXdgSurface); end; IXdgPopupListener = interface ['IXdgPopupListener'] procedure xdg_popup_popup_done(AXdgPopup: TXdgPopup); end; TXdgShell = class(TWLProxyObject) private const _DESTROY = 0; const _USE_UNSTABLE_VERSION = 1; const _GET_XDG_SURFACE = 2; const _GET_XDG_POPUP = 3; const _PONG = 4; public destructor Destroy; override; procedure UseUnstableVersion(AVersion: LongInt); function GetXdgSurface(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TXdgSurface}): TXdgSurface; function GetXdgPopup(ASurface: TWlSurface; AParent: TWlSurface; ASeat: TWlSeat; ASerial: DWord; AX: LongInt; AY: LongInt; AProxyClass: TWLProxyObjectClass = nil {TXdgPopup}): TXdgPopup; procedure Pong(ASerial: DWord); function AddListener(AIntf: IXdgShellListener): LongInt; end; TXdgSurface = class(TWLProxyObject) private const _DESTROY = 0; const _SET_PARENT = 1; const _SET_TITLE = 2; const _SET_APP_ID = 3; const _SHOW_WINDOW_MENU = 4; const _MOVE = 5; const _RESIZE = 6; const _ACK_CONFIGURE = 7; const _SET_WINDOW_GEOMETRY = 8; const _SET_MAXIMIZED = 9; const _UNSET_MAXIMIZED = 10; const _SET_FULLSCREEN = 11; const _UNSET_FULLSCREEN = 12; const _SET_MINIMIZED = 13; public destructor Destroy; override; procedure SetParent(AParent: TXdgSurface); procedure SetTitle(ATitle: String); procedure SetAppId(AAppId: String); procedure ShowWindowMenu(ASeat: TWlSeat; ASerial: DWord; AX: LongInt; AY: LongInt); procedure Move(ASeat: TWlSeat; ASerial: DWord); procedure Resize(ASeat: TWlSeat; ASerial: DWord; AEdges: DWord); procedure AckConfigure(ASerial: DWord); procedure SetWindowGeometry(AX: LongInt; AY: LongInt; AWidth: LongInt; AHeight: LongInt); procedure SetMaximized; procedure UnsetMaximized; procedure SetFullscreen(AOutput: TWlOutput); procedure UnsetFullscreen; procedure SetMinimized; function AddListener(AIntf: IXdgSurfaceListener): LongInt; end; TXdgPopup = class(TWLProxyObject) private const _DESTROY = 0; public destructor Destroy; override; function AddListener(AIntf: IXdgPopupListener): LongInt; end; var xdg_shell_interface: Twl_interface; xdg_surface_interface: Twl_interface; xdg_popup_interface: Twl_interface; implementation var vIntf_xdg_shell_Listener: Txdg_shell_listener; vIntf_xdg_surface_Listener: Txdg_surface_listener; vIntf_xdg_popup_Listener: Txdg_popup_listener; destructor TXdgShell.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; procedure TXdgShell.UseUnstableVersion(AVersion: LongInt); begin wl_proxy_marshal(FProxy, _USE_UNSTABLE_VERSION, AVersion); end; function TXdgShell.GetXdgSurface(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TXdgSurface}): TXdgSurface; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _GET_XDG_SURFACE, @xdg_surface_interface, nil, ASurface.Proxy); if AProxyClass = nil then AProxyClass := TXdgSurface; Result := TXdgSurface(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TXdgSurface) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TXdgSurface]); end; function TXdgShell.GetXdgPopup(ASurface: TWlSurface; AParent: TWlSurface; ASeat: TWlSeat; ASerial: DWord; AX: LongInt; AY: LongInt; AProxyClass: TWLProxyObjectClass = nil {TXdgPopup}): TXdgPopup; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _GET_XDG_POPUP, @xdg_popup_interface, nil, ASurface.Proxy, AParent.Proxy, ASeat.Proxy, ASerial, AX, AY); if AProxyClass = nil then AProxyClass := TXdgPopup; Result := TXdgPopup(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TXdgPopup) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TXdgPopup]); end; procedure TXdgShell.Pong(ASerial: DWord); begin wl_proxy_marshal(FProxy, _PONG, ASerial); end; function TXdgShell.AddListener(AIntf: IXdgShellListener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_xdg_shell_Listener, @FUserDataRec); end; destructor TXdgSurface.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; procedure TXdgSurface.SetParent(AParent: TXdgSurface); begin wl_proxy_marshal(FProxy, _SET_PARENT, AParent.Proxy); end; procedure TXdgSurface.SetTitle(ATitle: String); begin wl_proxy_marshal(FProxy, _SET_TITLE, PChar(ATitle)); end; procedure TXdgSurface.SetAppId(AAppId: String); begin wl_proxy_marshal(FProxy, _SET_APP_ID, PChar(AAppId)); end; procedure TXdgSurface.ShowWindowMenu(ASeat: TWlSeat; ASerial: DWord; AX: LongInt; AY: LongInt); begin wl_proxy_marshal(FProxy, _SHOW_WINDOW_MENU, ASeat.Proxy, ASerial, AX, AY); end; procedure TXdgSurface.Move(ASeat: TWlSeat; ASerial: DWord); begin wl_proxy_marshal(FProxy, _MOVE, ASeat.Proxy, ASerial); end; procedure TXdgSurface.Resize(ASeat: TWlSeat; ASerial: DWord; AEdges: DWord); begin wl_proxy_marshal(FProxy, _RESIZE, ASeat.Proxy, ASerial, AEdges); end; procedure TXdgSurface.AckConfigure(ASerial: DWord); begin wl_proxy_marshal(FProxy, _ACK_CONFIGURE, ASerial); end; procedure TXdgSurface.SetWindowGeometry(AX: LongInt; AY: LongInt; AWidth: LongInt; AHeight: LongInt); begin wl_proxy_marshal(FProxy, _SET_WINDOW_GEOMETRY, AX, AY, AWidth, AHeight); end; procedure TXdgSurface.SetMaximized; begin wl_proxy_marshal(FProxy, _SET_MAXIMIZED); end; procedure TXdgSurface.UnsetMaximized; begin wl_proxy_marshal(FProxy, _UNSET_MAXIMIZED); end; procedure TXdgSurface.SetFullscreen(AOutput: TWlOutput); begin wl_proxy_marshal(FProxy, _SET_FULLSCREEN, AOutput.Proxy); end; procedure TXdgSurface.UnsetFullscreen; begin wl_proxy_marshal(FProxy, _UNSET_FULLSCREEN); end; procedure TXdgSurface.SetMinimized; begin wl_proxy_marshal(FProxy, _SET_MINIMIZED); end; function TXdgSurface.AddListener(AIntf: IXdgSurfaceListener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_xdg_surface_Listener, @FUserDataRec); end; destructor TXdgPopup.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TXdgPopup.AddListener(AIntf: IXdgPopupListener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_xdg_popup_Listener, @FUserDataRec); end; procedure xdg_shell_ping_Intf(AData: PWLUserData; Axdg_shell: Pxdg_shell; ASerial: DWord); cdecl; var AIntf: IXdgShellListener; begin if AData = nil then Exit; AIntf := IXdgShellListener(AData^.ListenerUserData); AIntf.xdg_shell_ping(TXdgShell(AData^.PascalObject), ASerial); end; procedure xdg_surface_configure_Intf(AData: PWLUserData; Axdg_surface: Pxdg_surface; AWidth: LongInt; AHeight: LongInt; AStates: Pwl_array; ASerial: DWord); cdecl; var AIntf: IXdgSurfaceListener; begin if AData = nil then Exit; AIntf := IXdgSurfaceListener(AData^.ListenerUserData); AIntf.xdg_surface_configure(TXdgSurface(AData^.PascalObject), AWidth, AHeight, AStates, ASerial); end; procedure xdg_surface_close_Intf(AData: PWLUserData; Axdg_surface: Pxdg_surface); cdecl; var AIntf: IXdgSurfaceListener; begin if AData = nil then Exit; AIntf := IXdgSurfaceListener(AData^.ListenerUserData); AIntf.xdg_surface_close(TXdgSurface(AData^.PascalObject)); end; procedure xdg_popup_popup_done_Intf(AData: PWLUserData; Axdg_popup: Pxdg_popup); cdecl; var AIntf: IXdgPopupListener; begin if AData = nil then Exit; AIntf := IXdgPopupListener(AData^.ListenerUserData); AIntf.xdg_popup_popup_done(TXdgPopup(AData^.PascalObject)); end; const pInterfaces: array[0..27] of Pwl_interface = ( (nil), (nil), (nil), (nil), (nil), (nil), (nil), (nil), (@xdg_surface_interface), (@wl_surface_interface), (@xdg_popup_interface), (@wl_surface_interface), (@wl_surface_interface), (@wl_seat_interface), (nil), (nil), (nil), (@xdg_surface_interface), (@wl_seat_interface), (nil), (nil), (nil), (@wl_seat_interface), (nil), (@wl_seat_interface), (nil), (nil), (@wl_output_interface) ); xdg_shell_requests: array[0..4] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'use_unstable_version'; signature: 'i'; types: @pInterfaces[0]), (name: 'get_xdg_surface'; signature: 'no'; types: @pInterfaces[8]), (name: 'get_xdg_popup'; signature: 'nooouii'; types: @pInterfaces[10]), (name: 'pong'; signature: 'u'; types: @pInterfaces[0]) ); xdg_shell_events: array[0..0] of Twl_message = ( (name: 'ping'; signature: 'u'; types: @pInterfaces[0]) ); xdg_surface_requests: array[0..13] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'set_parent'; signature: '?o'; types: @pInterfaces[17]), (name: 'set_title'; signature: 's'; types: @pInterfaces[0]), (name: 'set_app_id'; signature: 's'; types: @pInterfaces[0]), (name: 'show_window_menu'; signature: 'ouii'; types: @pInterfaces[18]), (name: 'move'; signature: 'ou'; types: @pInterfaces[22]), (name: 'resize'; signature: 'ouu'; types: @pInterfaces[24]), (name: 'ack_configure'; signature: 'u'; types: @pInterfaces[0]), (name: 'set_window_geometry'; signature: 'iiii'; types: @pInterfaces[0]), (name: 'set_maximized'; signature: ''; types: @pInterfaces[0]), (name: 'unset_maximized'; signature: ''; types: @pInterfaces[0]), (name: 'set_fullscreen'; signature: '?o'; types: @pInterfaces[27]), (name: 'unset_fullscreen'; signature: ''; types: @pInterfaces[0]), (name: 'set_minimized'; signature: ''; types: @pInterfaces[0]) ); xdg_surface_events: array[0..1] of Twl_message = ( (name: 'configure'; signature: 'iiau'; types: @pInterfaces[0]), (name: 'close'; signature: ''; types: @pInterfaces[0]) ); xdg_popup_requests: array[0..0] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]) ); xdg_popup_events: array[0..0] of Twl_message = ( (name: 'popup_done'; signature: ''; types: @pInterfaces[0]) ); initialization Pointer(vIntf_xdg_shell_Listener.ping) := @xdg_shell_ping_Intf; Pointer(vIntf_xdg_surface_Listener.configure) := @xdg_surface_configure_Intf; Pointer(vIntf_xdg_surface_Listener.close) := @xdg_surface_close_Intf; Pointer(vIntf_xdg_popup_Listener.popup_done) := @xdg_popup_popup_done_Intf; xdg_shell_interface.name := 'xdg_shell'; xdg_shell_interface.version := 1; xdg_shell_interface.method_count := 5; xdg_shell_interface.methods := @xdg_shell_requests; xdg_shell_interface.event_count := 1; xdg_shell_interface.events := @xdg_shell_events; xdg_surface_interface.name := 'xdg_surface'; xdg_surface_interface.version := 1; xdg_surface_interface.method_count := 14; xdg_surface_interface.methods := @xdg_surface_requests; xdg_surface_interface.event_count := 2; xdg_surface_interface.events := @xdg_surface_events; xdg_popup_interface.name := 'xdg_popup'; xdg_popup_interface.version := 1; xdg_popup_interface.method_count := 1; xdg_popup_interface.methods := @xdg_popup_requests; xdg_popup_interface.event_count := 1; xdg_popup_interface.events := @xdg_popup_events; end.
{$I ATViewerOptions.inc} {$I-} unit UFormViewOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ATxToolbarList, ExtCtrls, TntDialogs, Spin, ecHotKeyEdit; type TFormProc = procedure of object; type TFormViewOptions = class(TForm) btnOk: TButton; btnCancel: TButton; FontDialog1: TFontDialog; ColorDialog1: TColorDialog; PageControl1: TPageControl; tabIntf: TTabSheet; tabShortcuts: TTabSheet; boxIntf: TGroupBox; labLang: TLabel; edLang: TComboBox; chkShell: TCheckBox; chkToolbar: TCheckBox; tabMisc: TTabSheet; ListKeys: TListView; HotKey1_: THotKey; labShortcut: TLabel; btnKeyOk: TButton; chkBorder: TCheckBox; chkSingleInst: TCheckBox; chkMenu: TCheckBox; chkStatusBar: TCheckBox; chkNav: TCheckBox; boxMisc: TGroupBox; chkResolveLinks: TCheckBox; chkShowHidden: TCheckBox; chkMenuIcons: TCheckBox; tabText: TTabSheet; tabMedia: TTabSheet; boxText: TGroupBox; labTextFixedWidth: TLabel; labTabSize: TLabel; labTextLength: TLabel; edTextWidth: TSpinEdit; chkTextWidthFit: TCheckBox; chkTextAutoCopy: TCheckBox; edTextTabSize: TSpinEdit; edTextLength: TSpinEdit; boxTextFont: TGroupBox; labTextFont1: TLabel; btnTextFont: TButton; labTextFontShow: TLabel; labTextColors: TLabel; btnTextColor: TButton; btnTextColorHexBack: TButton; btnTextColorHex1: TButton; btnTextColorHex2: TButton; btnTextColorGutter: TButton; chkTextOemSpecial: TCheckBox; btnTextFontOEM: TButton; labTextFontShowOEM: TLabel; boxImage: TGroupBox; chkImageResample: TCheckBox; chkImageTransp: TCheckBox; labColorImage: TLabel; btnMediaColor: TButton; btnMediaColorLabel: TButton; btnMediaColorLabelErr: TButton; boxTextSearch: TGroupBox; edSearchIndent: TSpinEdit; labSearchIndent: TLabel; chkSearchSel: TCheckBox; boxTextReload: TGroupBox; chkTextReload: TCheckBox; chkTextReloadBeep: TCheckBox; chkTextReloadTail: TCheckBox; chkSearchNoMsg: TCheckBox; FontDialog2: TFontDialog; boxPrint: TGroupBox; labFontFooter: TLabel; btnFontFooter: TButton; labFooterFontShow: TLabel; edIcon: TComboBox; labIcon: TLabel; Panel1: TPanel; Image1: TImage; chkTextWrap: TCheckBox; chkTextNonPrint: TCheckBox; chkImageFit: TCheckBox; chkImageFitBig: TCheckBox; chkImageCenter: TCheckBox; tabFile: TTabSheet; boxExt: TGroupBox; edText: TEdit; edImages: TEdit; edInet: TEdit; btnTextOptions: TButton; btnImageOptions: TButton; btnGutterOptions: TButton; labViewerTitle: TLabel; labViewerMode: TLabel; edViewerTitle: TComboBox; edViewerMode: TComboBox; chkImageFitWindow: TCheckBox; chkImageLabel: TCheckBox; boxInternet: TGroupBox; chkWebOffline: TCheckBox; SaveDialog1: TSaveDialog; chkTextURLs: TCheckBox; btnTextColorURL: TButton; labFileSort: TLabel; edFileSort: TComboBox; tabHistory: TTabSheet; boxHistory: TGroupBox; chkSaveFolder: TCheckBox; chkSavePosition: TCheckBox; chkSaveRecents: TCheckBox; chkSaveSearch: TCheckBox; btnClearRecent: TButton; btnClearSearch: TButton; chkShowCfm: TCheckBox; Label2: TLabel; chkShowConv: TCheckBox; edConv: TEdit; chkImages: TCheckBox; chkInet: TCheckBox; labConv: TLabel; labText: TLabel; chkSaveFile: TCheckBox; chkSearchNoCfm: TCheckBox; boxHMisc: TGroupBox; chkHText: TCheckBox; edHText: TSpinEdit; chkHImage: TCheckBox; edHImage: TSpinEdit; chkHWeb: TCheckBox; edHWeb: TSpinEdit; chkHRtf: TCheckBox; edHRtf: TSpinEdit; chkHPlug: TCheckBox; edHPlug: TSpinEdit; edIgnore: TEdit; chkIgnore: TCheckBox; chkToolbarFS: TCheckBox; chkRen: TCheckBox; btnTextColorHi: TButton; Timer1: TTimer; chkImageFitWidth: TCheckBox; chkImageFitHeight: TCheckBox; btnKeyReset: TButton; HotKey1: TecHotKey; procedure btnTextFontClick(Sender: TObject); procedure btnTextColorClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure btnTextOptionsClick(Sender: TObject); procedure chkTextWidthFitClick(Sender: TObject); procedure btnMediaColorClick(Sender: TObject); procedure btnTextColorHex1Click(Sender: TObject); procedure btnTextColorHex2Click(Sender: TObject); procedure edLangChange(Sender: TObject); procedure btnTextFontOEMClick(Sender: TObject); procedure ListKeysSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure btnKeyOkClick(Sender: TObject); procedure chkTextReloadClick(Sender: TObject); procedure btnTextColorHexBackClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnImageOptionsClick(Sender: TObject); procedure chkTextOemSpecialClick(Sender: TObject); procedure btnTextColorGutterClick(Sender: TObject); procedure btnMediaColorLabelClick(Sender: TObject); procedure btnMediaColorLabelErrClick(Sender: TObject); procedure btnClearRecentClick(Sender: TObject); procedure btnClearSearchClick(Sender: TObject); procedure btnFontFooterClick(Sender: TObject); procedure edIconChange(Sender: TObject); procedure btnGutterOptionsClick(Sender: TObject); procedure btnTextColorURLClick(Sender: TObject); procedure edHTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure chkHTextClick(Sender: TObject); procedure btnTextColorHiClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure btnKeyResetClick(Sender: TObject); private { Private declarations } procedure FSaveIconsNames(const FileName: string); public { Public declarations } FPlugin: string; ffImgList: TImageList; //Original (not current!) ImageList ffToolbar: TToolbarList; //Toolbar object ffTextFontName: string; ffTextFontSize: integer; ffTextFontColor: TColor; ffTextFontStyle: TFontStyles; ffTextFontCharset: TFontCharset; ffTextFontOEMName: string; ffTextFontOEMSize: integer; ffTextFontOEMColor: TColor; ffTextFontOEMStyle: TFontStyles; ffTextFontOEMCharset: TFontCharset; ffFooterFontName: string; ffFooterFontSize: integer; ffFooterFontColor: TColor; ffFooterFontStyle: TFontStyles; ffFooterFontCharset: TFontCharset; ffTextBackColor: TColor; ffTextHexColor1: TColor; ffTextHexColor2: TColor; ffTextHexColorBack: TColor; ffTextGutterColor: TColor; ffTextUrlColor: TColor; ffTextHiColor: TColor; ffTextDetect: boolean; ffTextDetectOEM: boolean; ffTextDetectUTF8: boolean; ffTextDetectSize: DWORD; ffTextDetectLimit: DWORD; ffMediaColor: TColor; ffMediaColorLabel: TColor; ffMediaColorLabelErr: TColor; ffOptLang: string; ffOptIcon: string; ffIViewEnabled: boolean; ffIViewExeName: string; ffIViewExtList: string; ffIViewHighPriority: boolean; ffIJLEnabled: boolean; ffIJLExtList: string; ffShowGutter: boolean; ffShowLines: boolean; ffLinesBufSize: integer; ffLinesCount: integer; ffLinesStep: integer; ffLinesExtUse: boolean; ffLinesExtList: string; ffGutterFontName: string; ffGutterFontSize: integer; ffGutterFontColor: TColor; ffGutterFontStyle: TFontStyles; ffGutterFontCharset: TFontCharSet; ffClearRecent: TFormProc; ffClearSearch: TFormProc; end; implementation uses ATViewer, ATViewerMsg, ATxSProc, ATxParamStr, ATxMsgProc, ATxMsg, ATxUtils, ATxIconsProc, Menus, UFormViewOptionsText, UFormViewOptionsImages, UFormViewOptionsGutter; {$R *.DFM} procedure TFormViewOptions.btnTextFontClick(Sender: TObject); begin with FontDialog1 do begin Font.Name:= ffTextFontName; Font.Size:= ffTextFontSize; Font.Color:= ffTextFontColor; Font.Style:= ffTextFontStyle; Font.CharSet:= ffTextFontCharset; if Execute then begin ffTextFontName:= Font.Name; ffTextFontSize:= Font.Size; ffTextFontColor:= Font.Color; ffTextFontStyle:= Font.Style; ffTextFontCharset:= Font.CharSet; labTextFontShow.Caption:= ffTextFontName + ', ' + IntToStr(ffTextFontSize); end; end; end; procedure TFormViewOptions.btnTextFontOEMClick(Sender: TObject); begin with FontDialog1 do begin Font.Name:= ffTextFontOEMName; Font.Size:= ffTextFontOEMSize; Font.Color:= ffTextFontOEMColor; Font.Style:= ffTextFontOEMStyle; Font.CharSet:= ffTextFontOEMCharset; if Execute then begin ffTextFontOEMName:= Font.Name; ffTextFontOEMSize:= Font.Size; ffTextFontOEMColor:= Font.Color; ffTextFontOEMStyle:= Font.Style; ffTextFontOEMCharset:= Font.CharSet; labTextFontShowOEM.Caption:= ffTextFontOEMName + ', ' + IntToStr(ffTextFontOEMSize); end; end; end; procedure TFormViewOptions.btnTextColorClick(Sender: TObject); begin with ColorDialog1 do begin Color:= ffTextBackColor; if Execute then ffTextBackColor:= Color; end; end; procedure TFormViewOptions.btnTextColorHexBackClick(Sender: TObject); begin with ColorDialog1 do begin Color:= ffTextHexColorBack; if Execute then ffTextHexColorBack:= Color; end; end; procedure TFormViewOptions.btnTextColorHex1Click(Sender: TObject); begin with ColorDialog1 do begin Color:= ffTextHexColor1; if Execute then ffTextHexColor1:= Color; end; end; procedure TFormViewOptions.btnTextColorHex2Click(Sender: TObject); begin with ColorDialog1 do begin Color:= ffTextHexColor2; if Execute then ffTextHexColor2:= Color; end; end; procedure TFormViewOptions.btnTextColorGutterClick(Sender: TObject); begin with ColorDialog1 do begin Color:= ffTextGutterColor; if Execute then ffTextGutterColor:= Color; end; end; procedure TFormViewOptions.btnTextColorURLClick(Sender: TObject); begin with ColorDialog1 do begin Color:= ffTextUrlColor; if Execute then ffTextUrlColor:= Color; end; end; procedure TFormViewOptions.FormShow(Sender: TObject); var h: THandle; fdA: TWin32FindDataA; fdW: TWin32FindDataW; Mask: WideString; S: string; n: integer; Rec: PToolbarButtonRec; begin //Init captions {$I Lang.FormViewOptions.inc} chkHText.Caption:= labText.Caption; chkHImage.Caption:= chkImages.Caption; chkHWeb.Caption:= chkInet.Caption; chkHPlug.Caption:= MsgStrip(MsgCaption(137))+':'; boxHMisc.Caption:= ' '+MsgCaption(811)+' '; chkIgnore.Caption:= MsgCaption(812); //Update controls labTextFontShow.Caption:= ffTextFontName + ', ' + IntToStr(ffTextFontSize); labTextFontShowOEM.Caption:= ffTextFontOEMName + ', ' + IntToStr(ffTextFontOEMSize); labFooterFontShow.Caption:= ffFooterFontName + ', ' + IntToStr(ffFooterFontSize); chkTextWidthFitClick(Self); chkTextOemSpecialClick(Self); chkTextReloadClick(Self); chkHTextClick(Self); //List languages Mask:= SLangFN('*'); if Win32Platform=VER_PLATFORM_WIN32_NT then h:= FindFirstFileW(PWChar(Mask), fdW) else h:= FindFirstFileA(PAnsiChar(AnsiString(Mask)), fdA); if h<>INVALID_HANDLE_VALUE then with edLang do try Items.BeginUpdate; Items.Clear; repeat if Win32Platform=VER_PLATFORM_WIN32_NT then S:= fdW.cFileName else S:= fdA.cFileName; S:= ChangeFileExt(S, ''); Items.Append(S); if Win32Platform=VER_PLATFORM_WIN32_NT then begin if not FindNextFileW(h, fdW) then Break end else begin if not FindNextFileA(h, fdA) then Break end; until false; n:= Items.IndexOf(ffOptLang); if n >= 0 then ItemIndex:= n else ItemIndex:= Items.IndexOf('English'); finally Windows.FindClose(h); Items.EndUpdate; end; //List icons with edIcon do try Items.BeginUpdate; Items.Clear; Items.Add(MsgViewerIconDef); Mask:= SIconsFN('*'); if Win32Platform=VER_PLATFORM_WIN32_NT then h:= FindFirstFileW(PWChar(Mask), fdW) else h:= FindFirstFileA(PAnsiChar(AnsiString(Mask)), fdA); if h<>INVALID_HANDLE_VALUE then repeat if Win32Platform=VER_PLATFORM_WIN32_NT then S:= fdW.cFileName else S:= fdA.cFileName; S:= ChangeFileExt(S, ''); Items.Append(S); if Win32Platform=VER_PLATFORM_WIN32_NT then begin if not FindNextFileW(h, fdW) then Break end else begin if not FindNextFileA(h, fdA) then Break end; until false; n:= Items.IndexOf(ffOptIcon); if n >= 0 then ItemIndex:= n else ItemIndex:= 0; Items.Add(MsgViewerIconSave); finally Windows.FindClose(h); Items.EndUpdate; end; //List shortcuts ffToolbar.RestoreShortcuts; with ListKeys do begin Items.BeginUpdate; Items.Clear; SmallImages:= ffToolbar.ImageList; for n:= 1 to cToolbarButtonsMax do begin if not ffToolbar.GetAvail(n, Rec) then Break; if Rec.FMenuItem.Caption<>'-' then with Items.Add do begin Caption:= GetToolbarButtonId(Rec^); SubItems.Add(ShortcutToText(Rec.FMenuItem.Shortcut)); ImageIndex:= Rec.FMenuItem.ImageIndex; Data:= pointer(n); end; end; Items.EndUpdate; if Items.Count>0 then Selected:= Items[0]; end; end; procedure TFormViewOptions.btnTextOptionsClick(Sender: TObject); begin with TFormViewOptionsText.Create(Self) do try chkDetect.Checked:= ffTextDetect; chkDetectOEM.Checked:= ffTextDetectOEM; chkDetectUTF8.Checked:= ffTextDetectUTF8; edDetectSize.Text:= IntToStr(ffTextDetectSize); edDetectLimit.Text:= IntToStr(ffTextDetectLimit); if ShowModal=mrOk then begin ffTextDetect:= chkDetect.Checked; ffTextDetectOEM:= chkDetectOEM.Checked; ffTextDetectUTF8:= chkDetectUTF8.Checked; ffTextDetectSize:= StrToIntDef(edDetectSize.Text, ffTextDetectSize); ffTextDetectLimit:= StrToIntDef(edDetectLimit.Text, ffTextDetectLimit); end; finally Release; end; end; procedure TFormViewOptions.chkTextWidthFitClick(Sender: TObject); begin edTextWidth.Enabled:= not chkTextWidthFit.Checked; labTextFixedWidth.Enabled:= edTextWidth.Enabled; end; procedure TFormViewOptions.btnMediaColorClick(Sender: TObject); begin with ColorDialog1 do begin Color:= ffMediaColor; if Execute then ffMediaColor:= Color; end; end; procedure TFormViewOptions.edLangChange(Sender: TObject); begin with edLang do begin if ItemIndex>=0 then ffOptLang:= Items[ItemIndex] else ffOptLang:= 'English'; DroppedDown:= false; end; SetMsgLanguage(ffOptLang); FormShow(Self); end; procedure TFormViewOptions.ListKeysSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); var Rec: PToolbarButtonRec; begin with ListKeys do begin btnKeyOk.Enabled:= Assigned(Selected); btnKeyReset.Enabled:= btnKeyOk.Enabled; HotKey1.Enabled:= btnKeyOk.Enabled; if Assigned(Selected) then if ffToolbar.GetAvail(integer(Selected.Data), Rec) then begin HotKey1.HotKey:= Rec.FMenuItem.Shortcut; HotKey1.Enabled:= Rec.FEn; btnKeyOk.Enabled:= HotKey1.Enabled; btnKeyReset.Enabled:= btnKeyOk.Enabled; end; end; end; procedure TFormViewOptions.btnKeyOkClick(Sender: TObject); var Rec: PToolbarButtonRec; i: integer; s: string; begin s:= ShortCutToText(HotKey1.HotKey); if s<>'' then with ListKeys do for i:= 0 to Items.Count-1 do if Items[i].SubItems[0] = s then begin MsgError(Format(MsgString(317), [Items[i].Caption]), Handle); Exit; end; with ListKeys do if Assigned(Selected) then with Selected do begin if ffToolbar.GetAvail(integer(Data), Rec) then begin Rec.FMenuItem.Shortcut:= HotKey1.HotKey; SubItems[0]:= s; end; end; end; procedure TFormViewOptions.chkTextReloadClick(Sender: TObject); begin chkTextReloadTail.Enabled:= chkTextReload.Checked; chkTextReloadBeep.Enabled:= chkTextReload.Checked; end; procedure TFormViewOptions.FormCreate(Sender: TObject); begin ffImgList:= nil; ffToolbar:= nil; end; procedure TFormViewOptions.btnImageOptionsClick(Sender: TObject); begin with TFormViewOptionsImages.Create(Self) do try chkUseIJL.Checked:= ffIJLEnabled; edExtIJL.Text:= ffIJLExtList; if ShowModal=mrOk then begin ffIJLEnabled:= chkUseIJL.Checked; ffIJLExtList:= edExtIJL.Text; end; finally Release; end; end; procedure TFormViewOptions.btnGutterOptionsClick(Sender: TObject); begin with TFormViewOptionsGutter.Create(Self) do try chkShowGutter.Checked:= ffShowGutter; chkShowLines.Checked:= ffShowLines; chkLineExt.Checked:= ffLinesExtUse; edLineExt.Text:= ffLinesExtList; edLineSize.Text:= IntToStr(ffLinesBufSize); edLineCount.Text:= IntToStr(ffLinesCount); edLineStep.Text:= IntToStr(ffLinesStep); ffFontName:= ffGutterFontName; ffFontSize:= ffGutterFontSize; ffFontColor:= ffGutterFontColor; ffFontStyle:= ffGutterFontStyle; ffFontCharset:= ffGutterFontCharset; if ShowModal=mrOk then begin ffShowGutter:= chkShowGutter.Checked; ffShowLines:= chkShowLines.Checked; ffLinesExtUse:= chkLineExt.Checked; ffLinesExtList:= edLineExt.Text; ffLinesBufSize:= StrToIntDef(edLineSize.Text, 300); ffLinesCount:= StrToIntDef(edLineCount.Text, 2000); ffLinesStep:= StrToIntDef(edLineStep.Text, 5); ffGutterFontName:= ffFontName; ffGutterFontSize:= ffFontSize; ffGutterFontColor:= ffFontColor; ffGutterFontStyle:= ffFontStyle; ffGutterFontCharset:= ffFontCharset; end; finally Release; end; end; procedure TFormViewOptions.chkTextOemSpecialClick(Sender: TObject); begin labTextFontShowOEM.Enabled:= chkTextOemSpecial.Checked; btnTextFontOEM.Enabled:= chkTextOemSpecial.Checked; end; procedure TFormViewOptions.btnMediaColorLabelClick(Sender: TObject); begin with ColorDialog1 do begin Color:= ffMediaColorLabel; if Execute then ffMediaColorLabel:= Color; end; end; procedure TFormViewOptions.btnMediaColorLabelErrClick(Sender: TObject); begin with ColorDialog1 do begin Color:= ffMediaColorLabelErr; if Execute then ffMediaColorLabelErr:= Color; end; end; procedure TFormViewOptions.btnClearRecentClick(Sender: TObject); begin if Assigned(ffClearRecent) then ffClearRecent; end; procedure TFormViewOptions.btnClearSearchClick(Sender: TObject); begin if Assigned(ffClearSearch) then ffClearSearch; end; procedure TFormViewOptions.btnFontFooterClick(Sender: TObject); begin with FontDialog2 do begin Font.Name:= ffFooterFontName; Font.Size:= ffFooterFontSize; Font.Color:= ffFooterFontColor; Font.Style:= ffFooterFontStyle; Font.CharSet:= ffFooterFontCharset; if Execute then begin ffFooterFontName:= Font.Name; ffFooterFontSize:= Font.Size; ffFooterFontColor:= Font.Color; ffFooterFontStyle:= Font.Style; ffFooterFontCharset:= Font.CharSet; labFooterFontShow.Caption:= ffFooterFontName + ', ' + IntToStr(ffFooterFontSize); end; end; end; procedure TFormViewOptions.FSaveIconsNames(const FileName: string); var f: TextFile; Rec: PToolbarButtonRec; n, i: integer; begin AssignFile(f, FileName); Rewrite(f); if IOResult <> 0 then Exit; Writeln(f, Format('Icons order in the saved "%s" file:', [ChangeFileExt(FileName, '.bmp')])); Writeln(f); try for i:= 0 to ffImgList.Count - 1 do for n:= 1 to cToolbarButtonsMax do if ffToolbar.GetAvail(n, Rec) then if Rec.FMenuItem.ImageIndex = i then begin Writeln(f, Format('%d %s', [i, GetToolbarButtonId(Rec^)])); Break; end; finally CloseFile(f); end; end; procedure TFormViewOptions.edIconChange(Sender: TObject); var L: TImageList; i: Integer; begin with edIcon do //Save template if (ItemIndex = Items.Count - 1) then begin with SaveDialog1 do if Execute then begin FSaveIcons(ffImgList, FileName); FSaveIconsNames(ChangeFileExt(FileName, '.txt')); end; end else //Default set if (ItemIndex = 0) then begin Panel1.Visible := False; ffOptIcon := ''; end else //Custom set with Image1 do begin Panel1.Visible := True; ffOptIcon := Text; L:= TImageList.CreateSize(16, 16); try FLoadIcons(L, SIconsFN(edIcon.Text)); with Panel1 do SetBounds(Left, edIcon.Top + edIcon.Height - L.Height, 6 * L.Width + 2, L.Height + 2); Picture.Bitmap.Width := Panel1.Width; Picture.Bitmap.Height := Panel1.Height; Canvas.Brush.Color:= clBtnFace; Canvas.FillRect(Rect(0, 0, Width, Height)); for i:= 0 to 6 do L.Draw(Canvas, i * L.Width, 0, i); finally L.Free; end; Invalidate; end; end; procedure TFormViewOptions.edHTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key=vk_escape) and (Shift=[]) then btnCancel.Click; if (Key=vk_return) and (Shift=[]) then btnOk.Click; end; procedure TFormViewOptions.chkHTextClick(Sender: TObject); begin edHText.Enabled:= chkHText.Checked; edHImage.Enabled:= chkHImage.Checked; edHWeb.Enabled:= chkHWeb.Checked; edHRtf.Enabled:= chkHRtf.Checked; edHPlug.Enabled:= chkHPlug.Checked; end; procedure TFormViewOptions.btnTextColorHiClick(Sender: TObject); begin with ColorDialog1 do begin Color:= ffTextHiColor; if Execute then ffTextHiColor:= Color; end; end; procedure TFormViewOptions.Timer1Timer(Sender: TObject); begin Timer1.Enabled:= false; if FPlugin = 'slister' then begin SendToBack; BringToFront; end; end; procedure TFormViewOptions.btnKeyResetClick(Sender: TObject); begin HotKey1.HotKey:= 0; btnKeyOkClick(Self); end; end.
unit MFichas.Model.Item.Metodos.Devolver; interface uses System.SysUtils, MFichas.Controller.Types, MFichas.Model.Item.Interfaces, MFichas.Model.Entidade.VENDAITENS, MFichas.Model.Venda.Interfaces; type TModelItemMetodosDevolver = class(TInterfacedObject, iModelItemMetodosDevolver) private [weak] FParent : iModelItem; FVenda : iModelVenda; FCodigo : String; FQuantidade: Double; FValor : Currency; constructor Create(AParent: iModelItem; AVenda: iModelVenda); procedure Gravar; public destructor Destroy; override; class function New(AParent: iModelItem; AVenda: iModelVenda): iModelItemMetodosDevolver; function Codigo(ACodigo: String) : iModelItemMetodosDevolver; function Quantidade(AQuantidade: Double) : iModelItemMetodosDevolver; function Valor(AValor: Currency) : iModelItemMetodosDevolver; function &End : iModelItemMetodos; end; implementation { TModelItemMetodosDevolver } function TModelItemMetodosDevolver.Codigo( ACodigo: String): iModelItemMetodosDevolver; begin Result := Self; FCodigo := ACodigo; end; function TModelItemMetodosDevolver.&End: iModelItemMetodos; begin //IMPLEMENTAR METODO DE DEVOLUÇAO DE ITEM Result := FParent.Metodos; Gravar; end; procedure TModelItemMetodosDevolver.Gravar; begin FParent.Entidade.VENDA := FVenda.Entidade.GUUID; FParent.Entidade.PRODUTO := FCodigo; FParent.Entidade.QUANTIDADE := FQuantidade; FParent.Entidade.PRECO := FValor; FParent.Entidade.TIPO := Integer(tvDevolucao); end; constructor TModelItemMetodosDevolver.Create(AParent: iModelItem; AVenda: iModelVenda); begin FParent := AParent; FVenda := AVenda; end; destructor TModelItemMetodosDevolver.Destroy; begin inherited; end; class function TModelItemMetodosDevolver.New(AParent: iModelItem; AVenda: iModelVenda): iModelItemMetodosDevolver; begin Result := Self.Create(AParent, AVenda); end; function TModelItemMetodosDevolver.Quantidade( AQuantidade: Double): iModelItemMetodosDevolver; begin Result := Self; FQuantidade := AQuantidade; end; function TModelItemMetodosDevolver.Valor( AValor: Currency): iModelItemMetodosDevolver; begin Result := Self; FValor := AValor; end; end.
unit UDropBoxDataStoreDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSCloudBase, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomDropBoxDataStore, FMX.TMSCloudDropBoxDataStore, System.Rtti, FMX.Objects, FMX.ListBox, FMX.Edit, FMX.Layouts, FMX.Grid, FMX.TMSCloudListView; type TForm12 = class(TForm) Panel1: TPanel; btConnect: TButton; btRemove: TButton; GroupBox1: TGroupBox; GroupBox2: TGroupBox; btSample: TButton; lvdatastores: TTMSFMXCloudListView; btCreate: TButton; edDataStore: TEdit; btSetMetaData: TButton; edTitle: TEdit; btDeleteDataStore: TButton; btGetByName: TButton; dsName: TEdit; cbRow: TComboBox; Label1: TLabel; Label2: TLabel; edTableName: TEdit; Label3: TLabel; Label4: TLabel; edField1: TEdit; edValue1: TEdit; edField2: TEdit; edValue2: TEdit; edField3: TEdit; edValue3: TEdit; edField4: TEdit; edValue4: TEdit; cb1: TCheckBox; cb2: TCheckBox; cb3: TCheckBox; cb4: TCheckBox; btDeleteRow: TButton; btInsertRow: TButton; btUpdateRow: TButton; btDeleteFields: TButton; btClear: TButton; Line1: TLine; edId: TEdit; TMSFMXCloudDropBoxDataStore1: TTMSFMXCloudDropBoxDataStore; procedure TMSFMXCloudDropBoxDataStore1ReceivedAccessToken(Sender: TObject); procedure btConnectClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btSampleClick(Sender: TObject); procedure btCreateClick(Sender: TObject); procedure btDeleteDataStoreClick(Sender: TObject); procedure btRemoveClick(Sender: TObject); procedure btGetByNameClick(Sender: TObject); procedure cbRowChange(Sender: TObject); procedure btClearClick(Sender: TObject); procedure btUpdateRowClick(Sender: TObject); procedure btDeleteRowClick(Sender: TObject); procedure btInsertRowClick(Sender: TObject); procedure btDeleteFieldsClick(Sender: TObject); procedure btSetMetaDataClick(Sender: TObject); procedure lvdatastoresClick(Sender: TObject); private { Private declarations } public { Public declarations } Opened: boolean; procedure FillData(Index: integer); procedure FillCheckedValue(Value: string); procedure ToggleControls; procedure ShowDataStores; procedure ShowRows; end; var Form12: TForm12; implementation {$R *.fmx} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE DROPBOX SERVICE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // DropBoxAppkey = 'xxxxxxxxx'; // DropBoxAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm12.btClearClick(Sender: TObject); begin edValue1.Text := ''; edValue2.Text := ''; edValue3.Text := ''; edValue4.Text := ''; end; procedure TForm12.btConnectClick(Sender: TObject); var acc: boolean; begin TMSFMXCloudDropBoxDataStore1.App.Key := DropBoxAppKey; TMSFMXCloudDropBoxDataStore1.App.Secret := DropBoxAppSecret; TMSFMXCloudDropBoxDataStore1.LoadTokens; acc := TMSFMXCloudDropBoxDataStore1.TestTokens; if acc then begin opened := true; ToggleControls; ShowDataStores; end else TMSFMXCloudDropBoxDataStore1.DoAuth; end; procedure TForm12.btCreateClick(Sender: TObject); var ds: TDataStore; begin if edDataStore.Text <> '' then begin ds := TMSFMXCloudDropBoxDataStore1.CreateDataStore(edDataStore.Text); if not Assigned(ds) then ShowMessage('Error creating datastore') else ShowDataStores; end else ShowMessage('Specify name for datastore'); end; procedure TForm12.btDeleteDataStoreClick(Sender: TObject); begin if lvDataStores.ItemIndex >= 0 then begin if TMSFMXCloudDropBoxDataStore1.DeleteDataStore(TMSFMXCloudDropBoxDataStore1.DataStoreList[lvDataStores.ItemIndex]) then ShowDataStores; end; end; procedure TForm12.btDeleteFieldsClick(Sender: TObject); var Fields: TStringList; ds: TDataStore; dr: TDataStoreRow; begin ds := TMSFMXCloudDropBoxDataStore1.DataStoreList[lvdatastores.ItemIndex]; dr := ds.Rows[cbRow.ItemIndex]; Fields := TStringList.Create; try if cb1.IsChecked then Fields.Add(dr.Fields[0].FieldName); if cb2.IsChecked then Fields.Add(dr.Fields[1].FieldName); if cb3.IsChecked then Fields.Add(dr.Fields[2].FieldName); if cb4.IsChecked then Fields.Add(dr.Fields[3].FieldName); if not ds.DeleteFields(dr, Fields) then ShowMessage(TMSFMXCloudDropBoxDataStore1.LastError); finally Fields.Free; end; end; procedure TForm12.btDeleteRowClick(Sender: TObject); var ds: TDataStore; begin if lvDataStores.ItemIndex >= 0 then begin ds := TMSFMXCloudDropBoxDataStore1.DataStoreList[lvdatastores.ItemIndex]; if not ds.DeleteRecord(ds.Rows[cbRow.ItemIndex]) then ShowMessage(TMSFMXCloudDropBoxDataStore1.LastError) else ShowRows; end; end; procedure TForm12.btGetByNameClick(Sender: TObject); var ds: TDataStore; begin if dsName.Text <> '' then begin ds := TMSFMXCloudDropBoxDataStore1.GetDataStoreByName(dsName.Text); if Assigned(ds) then begin lvDataStores.ItemIndex := TMSFMXCloudDropBoxDataStore1.DataStoreList.IndexOf(ds.ID); ShowMessage('Datastore <'+dsName.Text + '> found'#13'ID='+ds.ID+#13'Rev='+IntToStr(ds.Revision)); end else ShowMessage('Datastore not found'); end else ShowMessage('Please specify a datastore name'); end; procedure TForm12.btInsertRowClick(Sender: TObject); var ds: TDataStore; dr: TDataStoreRow; begin if edTableName.Text = '' then begin ShowMessage('Please specify a tablename'); Exit; end; if (lvDataStores.ItemIndex >= 0) then begin ds := TMSFMXCloudDropBoxDataStore1.DataStoreList[lvdatastores.ItemIndex]; dr := ds.Rows.Add; dr.ID := ds.GetNewID; dr.TableName := edTableName.Text; if (edField1.Text <> '') and (edValue1.Text <> '') then begin dr.AddData(edField1.Text, edValue1.Text); end; if (edField2.Text <> '') and (edValue2.Text <> '') then begin dr.AddData(edField2.Text, edValue2.Text); end; if (edField3.Text <> '') and (edValue3.Text <> '') then begin dr.AddData(edField3.Text, edValue3.Text); end; if (edField4.Text <> '') and (edValue4.Text <> '') then begin dr.AddData(edField4.Text, edValue4.Text); end; if not ds.InsertRecord(dr) then begin ShowMessage(TMSFMXCloudDropBoxDataStore1.LastError); end else ShowRows; end; end; procedure TForm12.btRemoveClick(Sender: TObject); begin TMSFMXCloudDropBoxDataStore1.ClearTokens(); Opened := False; ToggleControls; end; procedure TForm12.btSampleClick(Sender: TObject); var ds: TDataStore; dr: TDataStoreRow; begin if Assigned(TMSFMXCloudDropBoxDataStore1.DataStoreList.FindByName('demo')) then begin ShowMessage('Demo datastore already exists'); Exit; end; ds := TMSFMXCloudDropBoxDataStore1.CreateDataStore('demo'); dr := ds.Rows.Add; dr.ID := ds.GetNewID; dr.TableName := 'Capitals'; dr.Fields.AddPair('Name','Paris'); dr.Fields.AddPair('Country','France'); dr.Fields.AddPair('Citizens',10000000); dr.Fields.AddPair('Europe',true); ds.InsertRecord(dr); dr := ds.Rows.Add; dr.ID := ds.GetNewID; dr.TableName := 'Capitals'; dr.Fields.AddPair('Name','Brussels'); dr.Fields.AddPair('Country','Belgium'); dr.Fields.AddPair('Citizens',3000000); dr.Fields.AddPair('Europe',true); ds.InsertRecord(dr); dr := ds.Rows.Add; dr.ID := ds.GetNewID; dr.TableName := 'Capitals'; dr.Fields.AddPair('Name','Berlin'); dr.Fields.AddPair('Country','Germany'); dr.Fields.AddPair('Citizens',6000000); dr.Fields.AddPair('Europe',true); ds.InsertRecord(dr); dr := ds.Rows.Add; dr.ID := ds.GetNewID; dr.TableName := 'Capitals'; dr.Fields.AddPair('Name','London'); dr.Fields.AddPair('Country','United Kingdom'); dr.Fields.AddPair('Citizens',11000000); dr.Fields.AddPair('Europe',true); ds.InsertRecord(dr); dr := ds.Rows.Add; dr.ID := ds.GetNewID; dr.TableName := 'Capitals'; dr.Fields.AddPair('Name','Washington'); dr.Fields.AddPair('Country','USA'); dr.Fields.AddPair('Citizens',8000000); dr.Fields.AddPair('Europe',false); ds.InsertRecord(dr); ShowDataStores; end; procedure TForm12.btSetMetaDataClick(Sender: TObject); var ds: TDataStore; begin if (lvDataStores.ItemIndex >= 0) then begin ds := TMSFMXCloudDropBoxDataStore1.DataStoreList[lvDataStores.ItemIndex]; ds.SetMetaData(edTitle.Text, Now); ShowDataStores; end; end; procedure TForm12.btUpdateRowClick(Sender: TObject); var ds: TDataStore; dr: TDataStoreRow; begin if edTableName.Text = '' then begin ShowMessage('Please specify a tablename'); Exit; end; if lvDataStores.ItemIndex >= 0 then begin ds := TMSFMXCloudDropBoxDataStore1.DataStoreList[lvdatastores.ItemIndex]; dr := ds.Rows[cbRow.ItemIndex]; dr.ID := edID.Text; dr.TableName := edTableName.Text; if (edField1.Text <> '') and (edValue1.Text <> '') then begin dr.AddData(edField1.Text, edValue1.Text); end; if (edField2.Text <> '') and (edValue2.Text <> '') then begin dr.AddData(edField2.Text, edValue2.Text); end; if (edField3.Text <> '') and (edValue3.Text <> '') then begin dr.AddData(edField3.Text, edValue3.Text); end; if (edField4.Text <> '') and (edValue4.Text <> '') then begin dr.AddData(edField4.Text, edValue4.Text); end; if not ds.UpdateRecord(ds.Rows[cbRow.ItemIndex]) then ShowMessage(TMSFMXCloudDropBoxDataStore1.LastError) else ShowRows; end; end; procedure TForm12.cbRowChange(Sender: TObject); begin FillData(cbRow.ItemIndex); end; procedure TForm12.FillCheckedValue(Value: string); begin if cb1.IsChecked then edValue1.Text := Value; if cb2.IsChecked then edValue2.Text := Value; if cb3.IsChecked then edValue2.Text := Value; if cb4.IsChecked then edValue2.Text := Value; end; procedure TForm12.FillData(Index: integer); var ds: TDataStore; dr: TDataStoreRow; begin if cbRow.ItemIndex >= 0 then begin ds := TMSFMXCloudDropBoxDataStore1.DataStoreList[lvdatastores.ItemIndex]; dr := ds.Rows[Index]; edTableName.Text := dr.TableName; edId.Text := dr.ID; edField1.Text := ''; edField2.Text := ''; edField3.Text := ''; edField4.Text := ''; edValue1.Text := ''; edValue2.Text := ''; edValue3.Text := ''; edValue4.Text := ''; if dr.Fields.Count > 0 then begin edField1.Text := dr.Fields[0].FieldName; edValue1.Text := dr.Fields[0].Value.ToString; end; if dr.Fields.Count > 1 then begin edField2.Text := dr.Fields[1].FieldName; edValue2.Text := dr.Fields[1].Value.ToString; end; if dr.Fields.Count > 2 then begin edField3.Text := dr.Fields[2].FieldName; edValue3.Text := dr.Fields[2].Value.ToString; end; if dr.Fields.Count > 3 then begin edField4.Text := dr.Fields[3].FieldName; edValue4.Text := dr.Fields[3].Value.ToString; end; end; end; procedure TForm12.FormCreate(Sender: TObject); begin Opened := false; TMSFMXCloudDropBoxDataStore1.Logging := true; TMSFMXCloudDropBoxDataStore1.LogLevel := llDetail; TMSFMXCloudDropBoxDataStore1.PersistTokens.Key := ExtractFilePath(Paramstr(0)) + 'dropboxdatastore.ini'; ToggleControls; end; procedure TForm12.lvdatastoresClick(Sender: TObject); begin cbRow.Items.Clear; edField1.Text := ''; edField2.Text := ''; edField3.Text := ''; edField4.Text := ''; edValue1.Text := ''; edValue2.Text := ''; edValue3.Text := ''; edValue4.Text := ''; edTableName.Text := ''; edID.Text := ''; if Assigned(lvdatastores.Selected) then ShowRows; end; procedure TForm12.ShowDataStores; var i: integer; ds: TDataStore; lv: TListItem; begin TMSFMXCloudDropBoxDataStore1.GetDataStores(); lvDataStores.Items.Clear; for I := 0 to TMSFMXCloudDropBoxDataStore1.DataStoreList.Count - 1 do begin ds := TMSFMXCloudDropBoxDataStore1.DataStoreList[i]; lv := lvDataStores.Items.Add; lv.Text := ds.DataStoreName; lv.SubItems.Add(IntToStr(ds.Revision)); lv.SubItems.Add(ds.Title); lv.SubItems.Add(DateTimeToStr(ds.DateTime)); end; if lvDataStores.Items.Count > 0 then lvDataStores.ItemIndex := 0; end; procedure TForm12.ShowRows; var ds: TDataStore; i: integer; begin if lvDataStores.ItemIndex >= 0 then begin ds := TMSFMXCloudDropBoxDataStore1.DataStoreList[lvdatastores.ItemIndex]; ds.GetRecords; cbRow.Items.Clear; for i := 0 to ds.Rows.Count - 1 do cbRow.Items.Add(IntToStr(i + 1)); if (cbRow.Items.Count > 0) then begin cbrow.ItemIndex := 0; FillData(cbRow.ItemIndex); end; end; end; procedure TForm12.TMSFMXCloudDropBoxDataStore1ReceivedAccessToken( Sender: TObject); begin opened := true; ToggleControls(); TMSFMXCloudDropBoxDataStore1.SaveTokens; ShowDataStores; end; procedure TForm12.ToggleControls; begin btConnect.Enabled := not opened; btRemove.Enabled := opened; btCreate.Enabled := opened; btInsertRow.Enabled := opened; btDeleteRow.Enabled := opened; btUpdateRow.Enabled := opened; btSample.Enabled := opened; btDeleteDataStore.Enabled := opened; btGetByName.Enabled := opened; btSetMetaData.Enabled := opened; btDeleteFields.Enabled := opened; btClear.Enabled := opened; lvDataStores.Enabled := opened; cbRow.Enabled := opened; edField1.Enabled := opened; edField2.Enabled := opened; edField3.Enabled := opened; edField4.Enabled := opened; edValue1.Enabled := opened; edValue2.Enabled := opened; edValue3.Enabled := opened; edValue4.Enabled := opened; edTableName.Enabled := opened; edID.Enabled := opened; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.TabControl, System.Actions, FMX.ActnList, FMX.StdActns, FMX.Gestures, FMX.Platform, FMX.Layouts, FMX.Memo, FMX.Objects, Unit2; type TForm1 = class(TForm) TabControl1: TTabControl; ToolBar1: TToolBar; TabItem1: TTabItem; TabItem2: TTabItem; TabItem3: TTabItem; TabItem4: TTabItem; Label1: TLabel; Label2: TLabel; Label4: TLabel; ActionList1: TActionList; NextTabAction1: TNextTabAction; PreviousTabAction1: TPreviousTabAction; ChangeTabAction1: TChangeTabAction; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; Action1: TAction; ControlAction1: TControlAction; ValueRangeAction1: TValueRangeAction; GestureManager1: TGestureManager; Memo1: TMemo; Image1: TImage; procedure FormCreate(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure TabControl1Gesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); procedure FormResize(Sender: TObject); private iLastDistance: Integer; function OnApplicationEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses System.IOUtils; {$R *.fmx} type TMunchiesCategory = (Snacks, Crunchies, Smoothies); procedure TForm1.Action1Execute(Sender: TObject); var aNumberš: TAlignLayout; aString: String; pointToAĐ: ^Integer; begin pointToAĐ := @aNumberš; pointToAĐ^ := 6; aString := #68#101#108#112#104#105; TabControl1.TabIndex := Random(TabControl1.TabCount); end; procedure TForm1.FormCreate(Sender: TObject); var AES: IFMXApplicationEventService; begin { TODO: Restoring application state to be implemented } if TPlatformServices.Current.SupportsPlatformService(IFMXApplicationEventService, IInterface(AES)) then AES.SetApplicationEventHandler(OnApplicationEvent); {$IFDEF ANDROID} SpeedButton1.Visible := False; {$ENDIF} // Image1.Bitmap.LoadFromFile(TPath.Combine(TPath.GetDocumentsPath, 'Logo.jpg')); ShowMessage(IntToStr(Unit2.manufactured)); end; procedure TForm1.FormResize(Sender: TObject); var SC: IFMXScreenService; begin SC := TPlatformServices.Current.GetPlatformService(IFMXScreenService) as IFMXScreenService; case SC.GetScreenOrientation of TSCreenOrientation.Portrait: begin Label1.RotationAngle := 0; Memo1.RotationAngle := 0; end; TScreenOrientation.Landscape: begin Label1.RotationAngle := 90; Memo1.RotationAngle := 90; end; end; end; function TForm1.OnApplicationEvent(AAppEvent: TApplicationEvent; AContext: TObject): Boolean; var DataFile: String; begin DataFile := TPath.Combine(TPath.GetDocumentsPath, 'DelphiNavApp.dat'); Memo1.Lines.Add(DataFile); case AAppEvent of TApplicationEvent.FinishedLaunching: Memo1.Lines.Add('Read settings'); TApplicationEvent.BecameActive: begin try Memo1.Lines.LoadFromFile(DataFile); except Memo1.Lines.Add('Text file doesn''t exist'); end; Memo1.Lines.Add('Application running'); end; TApplicationEvent.EnteredBackground: begin Memo1.Lines.Add('Background mode'); Memo1.Lines.SaveToFile(DataFile); end; TApplicationEvent.WillBecomeInactive: Memo1.Lines.Add('Save state'); TApplicationEvent.WillBecomeForeground: Memo1.Lines.Add('Load state'); TApplicationEvent.WillTerminate: Memo1.Lines.Add('Application ending'); TApplicationEvent.LowMemory: Memo1.Lines.Add('Low memory'); end; Result := True; end; procedure TForm1.TabControl1Gesture(Sender: TObject; const EventInfo: TGestureEventInfo; var Handled: Boolean); begin if EventInfo.GestureID = igiZoom then begin if iLastDistance > EventInfo.Distance then Label1.Font.Size := Label1.Font.Size - 1 else Label1.Font.Size := Label1.Font.Size + 1; iLastDistance := EventInfo.Distance; Handled := True; end; if EventInfo.GestureID = igiPan then begin Label1.Text := FloatToStr(EventInfo.Location.X) + ',' + FloatToStr(EventInfo.Location.Y); Handled := True; end; end; end.
unit f2Scene; interface uses SimpleXML, d2dTypes, d2dInterfaces, d2dApplication, d2dGUI, d2dGUIButtons, d2dUtils, d2dFont, f2Application, f2Context; type Tf2Scene = class(Td2dScene) private function pm_GetF2App: Tf2Application; protected f_Context: Tf2Context; property F2App: Tf2Application read pm_GetF2App; function LoadButton(const aNode: IXmlNode; const aName: string): Td2dBitButton; public property Context: Tf2Context read f_Context write f_Context; end; implementation function Tf2Scene.pm_GetF2App: Tf2Application; begin Result := Tf2Application(Application); end; function Tf2Scene.LoadButton(const aNode: IXmlNode; const aName: string): Td2dBitButton; var l_Tex: Id2dTexture; l_BNode: IxmlNode; l_TX, l_TY, l_W, l_H, l_PosX, l_PosY: Integer; begin Result := nil; l_BNode := aNode.SelectSingleNode(aName); if l_BNode <> nil then begin l_Tex := F2App.Skin.Textures[l_BNode.GetAttr('tex')]; if l_Tex <> nil then begin l_TX := l_BNode.GetIntAttr('tx'); l_TY := l_BNode.GetIntAttr('ty'); l_W := l_BNode.GetIntAttr('width'); l_H := l_BNode.GetIntAttr('height'); l_PosX := l_BNode.GetIntAttr('posx'); l_PosY := l_BNode.GetIntAttr('posy'); if (l_H > 0) and (l_W > 0) then Result := Td2dBitButton.Create(l_PosX, l_PosY, l_Tex, l_TX, l_TY, l_W, l_H); end; end; end; end.
unit Classe.Pessoa; interface uses System.SysUtils, Classe.SQL; type TPessoa = class private FNome: String; FEtnia: string; FDataNasc: String; FSexo: String; function getNome: String; procedure setNome(Value: String); procedure SetEtnia(const Value: String); procedure SetDataNasc(const Value: String); procedure SetSexo(const Value: String); public property DataNasc: String read FDataNasc write SetDataNasc; property Sexo: String read FSexo write SetSexo; property Etnia: String read FEtnia write SetEtnia; property Nome: String read getNome write setNome; function Idade: Integer; function Receber(I : Integer) : String; overload; function Receber(X : Currency) : String; overload; function Receber(A, B : Integer) : String; overload; function RetornaNome : string; virtual; end; implementation { TPessoa } function TPessoa.Idade: Integer; begin Result := Trunc((now - StrToDate(DataNasc)) / 365.25); end; function TPessoa.Receber(X: Currency): String; begin Result := 'Recebi um Valor Currency : ' + CurrToStr(X); end; function TPessoa.Receber(I: Integer): String; begin Result := 'Recebi um Valor Inteiro: ' + IntToStr(I); end; procedure TPessoa.SetDataNasc(const Value: String); begin FDataNasc := Value; end; procedure TPessoa.SetEtnia(const Value: String); begin FEtnia := Value; end; function TPessoa.getNome: String; begin Result := FNome; end; procedure TPessoa.setNome(Value: String); begin if Value = '' then raise Exception.Create('Valor não pode ser vazio'); FNome := Value; end; procedure TPessoa.SetSexo(const Value: String); begin FSexo := Value; end; function TPessoa.Receber(A, B: Integer): String; begin Result := 'A Soma deste Inteiros é: ' + IntToStr(A + B); end; function TPessoa.RetornaNome: string; begin Result := 'Eu sou a classe TPessoa'; end; end.
unit GetAssetTrackingDataUnit; interface uses SysUtils, BaseExampleUnit; type TGetAssetTrackingData = class(TBaseExample) public procedure Execute(TrackingNumber: String); end; implementation uses TrackingHistoryUnit, TrackingHistoryResponseUnit, TrackingDataUnit; procedure TGetAssetTrackingData.Execute(TrackingNumber: String); var ErrorString: String; TrackingData: TTrackingData; begin TrackingData := Route4MeManager.Tracking.GetAssetTrackingData( TrackingNumber, ErrorString); try WriteLn(''); if (TrackingData <> nil) then begin WriteLn('GetAssetTrackingData executed successfully'); WriteLn(''); if TrackingData.Delivered.IsNotNull then if TrackingData.Delivered.Value then WriteLn('Package was delivered') else WriteLn('Package was not delivered'); end else WriteLn(Format('GetAssetTrackingData error: "%s"', [ErrorString])); finally FreeAndNil(TrackingData); end; end; end.
unit DDSOptions; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TFormDDSOptions = class(TForm) BtnOk: TButton; BtnCancel: TButton; BtnApply: TButton; GroupBox1: TGroupBox; cbOtn: TCheckBox; edOtn: TEdit; edAbs: TEdit; cbAbs: TCheckBox; procedure BtnOkClick(Sender: TObject); private { Private declarations } public { Public declarations } OtnValue,AbsValue:Double; function Validate:Boolean; end; var FormDDSOptions: TFormDDSOptions; implementation uses PressureGraphFrame; {$R *.DFM} { TFormFPGOptions } function TFormDDSOptions.Validate: Boolean; begin Result:=False; try edOtn.SetFocus; OtnValue:=StrToFloat(edOtn.Text); if (OtnValue<0.01) or (100<OtnValue) then exit; edAbs.SetFocus; AbsValue:=StrToFloat(edAbs.Text); if AbsValue<0 then exit; except exit; end; Result:=True; end; procedure TFormDDSOptions.BtnOkClick(Sender: TObject); begin if Validate then ModalResult:=TButton(Sender).ModalResult; end; end.
// Upgraded to Delphi 2009: Sebastian Zierer (* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower SysTools * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1996-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* SysTools: StDate.pas 4.04 *} {*********************************************************} {* SysTools: Date and time manipulation *} {*********************************************************} {$I StDefine.inc} {For BCB 3.0 package support.} unit StDate; interface uses Windows, SysUtils; type TStDate = Integer; {In STDATE, dates are stored in long integer format as the number of days since January 1, 1600} TDateArray = array[0..(MaxLongInt div SizeOf(TStDate))-1] of TStDate; {Type for StDate open array} TStDayType = (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday); {An enumerated type used when representing a day of the week} TStBondDateType = (bdtActual, bdt30E360, bdt30360, bdt30360psa); {An enumerated type used for calculating bond date differences} TStTime = Integer; {STDATE handles time in a manner similar to dates, representing a given time of day as the number of seconds since midnight} TStDateTimeRec = record {This record type simply combines the two basic date types defined by STDATE, Date and Time} D : TStDate; T : TStTime; end; const MinYear = 1600; {Minimum valid year for a date variable} MaxYear = 3999; {Maximum valid year for a date variable} Mindate = $00000000; {Minimum valid date for a date variable - 01/01/1600} Maxdate = $000D6025; {Maximum valid date for a date variable - 12/31/3999} Date1900 : Integer = $0001AC05; {Julian date for 01/01/1900} Date1970 : Integer = $00020FE4; {Julian date for 01/01/1970} Date1980 : Integer = $00021E28; {Julian date for 01/01/1980} Date2000 : Integer = $00023AB1; {Julian date for 01/01/2000} Days400Yr : Integer = 146097; {days in 400 years} {This value is used to represent an invalid date, such as 12/32/1992} BadDate = Integer($FFFFFFFF); DeltaJD = $00232DA8; {Days between 1/1/-4173 and 1/1/1600} MinTime = 0; {Minimum valid time for a time variable - 00:00:00 am} MaxTime = 86399; {Maximum valid time for a time variable - 23:59:59 pm} {This value is used to represent an invalid time of day, such as 12:61:00} BadTime = Integer($FFFFFFFF); SecondsInDay = 86400; {Number of seconds in a day} SecondsInHour = 3600; {Number of seconds in an hour} SecondsInMinute = 60; {Number of seconds in a minute} HoursInDay = 24; {Number of hours in a day} MinutesInHour = 60; {Number of minutes in an hour} MinutesInDay = 1440; {Number of minutes in a day} var DefaultYear : Integer; {default year--used by DateStringToDMY} DefaultMonth : ShortInt; {default month} {-------julian date routines---------------} function CurrentDate : TStDate; {-returns today's date as a Julian date} function ValidDate(Day, Month, Year, Epoch : Integer) : Boolean; {-Verify that day, month, year is a valid date} function DMYtoStDate(Day, Month, Year, Epoch : Integer) : TStDate; {-Convert from day, month, year to a Julian date} procedure StDateToDMY(Julian : TStDate; var Day, Month, Year : Integer); {-Convert from a Julian date to day, month, year} function IncDate(Julian : TStDate; Days, Months, Years : Integer) : TStDate; {-Add (or subtract) the number of days, months, and years to a date} function IncDateTrunc(Julian : TStDate; Months, Years : Integer) : TStDate; {-Add (or subtract) the specified number of months and years to a date} procedure DateDiff(Date1, Date2 : TStDate; var Days, Months, Years : Integer); {-Return the difference in days, months, and years between two valid Julian dates} function BondDateDiff(Date1, Date2 : TStDate; DayBasis : TStBondDateType) : TStDate; {-Return the difference in days between two valid Julian dates using a specific financial basis} function WeekOfYear(Julian : TStDate) : Byte; {-Returns the week number of the year given the Julian Date} function AstJulianDate(Julian : TStDate) : Double; {-Returns the Astronomical Julian Date from a TStDate} function AstJulianDatetoStDate(AstJulian : Double; Truncate : Boolean) : TStDate; {-Returns a TStDate from an Astronomical Julian Date. Truncate TRUE Converts to appropriate 0 hours then truncates FALSE Converts to appropriate 0 hours, then rounds to nearest;} function AstJulianDatePrim(Year, Month, Date : Integer; UT : TStTime) : Double; {-Returns an Astronomical Julian Date for any year, even those outside MinYear..MaxYear} function DayOfWeek(Julian : TStDate) : TStDayType; {-Return the day of the week for a Julian date} function DayOfWeekDMY(Day, Month, Year, Epoch : Integer) : TStDayType; {-Return the day of the week for the day, month, year} function IsLeapYear(Year : Integer) : Boolean; {-Return True if Year is a leap year} function DaysInMonth(Month : Integer; Year, Epoch : Integer) : Integer; {-Return the number of days in the specified month of a given year} function ResolveEpoch(Year, Epoch : Integer) : Integer; {-Convert 2 digit year to 4 digit year according to Epoch} {-------time routines---------------} function ValidTime(Hours, Minutes, Seconds : Integer) : Boolean; {-Return True if Hours:Minutes:Seconds is a valid time} procedure StTimeToHMS(T : TStTime; var Hours, Minutes, Seconds : Byte); {-Convert a time variable to hours, minutes, seconds} function HMStoStTime(Hours, Minutes, Seconds : Byte) : TStTime; {-Convert hours, minutes, seconds to a time variable} function CurrentTime : TStTime; {-Return the current time in seconds since midnight} procedure TimeDiff(Time1, Time2 : TStTime; var Hours, Minutes, Seconds : Byte); {-Return the difference in hours, minutes, and seconds between two times} function IncTime(T : TStTime; Hours, Minutes, Seconds : Byte) : TStTime; {-Add the specified hours, minutes, and seconds to a given time of day} function DecTime(T : TStTime; Hours, Minutes, Seconds : Byte) : TStTime; {-Subtract the specified hours, minutes, and seconds from a given time of day} function RoundToNearestHour(T : TStTime; Truncate : Boolean) : TStTime; {-Given a time, round it to the nearest hour, or truncate minutes and seconds} function RoundToNearestMinute(const T : TStTime; Truncate : Boolean) : TStTime; {-Given a time, round it to the nearest minute, or truncate seconds} {-------- routines for DateTimeRec records ---------} procedure DateTimeDiff(const DT1 : TStDateTimeRec; var DT2 : TStDateTimeRec; {!!.02} var Days : Integer; var Secs : Integer); {-Return the difference in days and seconds between two points in time} procedure IncDateTime(const DT1 : TStDateTimeRec; var DT2 : TStDateTimeRec; {!!.02} Days : Integer; Secs : Integer); {-Increment (or decrement) a date and time by the specified number of days and seconds} function DateTimeToStDate(DT : TDateTime) : TStDate; {-Convert Delphi TDateTime to TStDate} function DateTimeToStTime(DT : TDateTime) : TStTime; {-Convert Delphi TDateTime to TStTime} function StDateToDateTime(D : TStDate) : TDateTime; {-Convert TStDate to TDateTime} function StTimeToDateTime(T : TStTime) : TDateTime; {-Convert TStTime to TDateTime} function Convert2ByteDate(TwoByteDate : Word) : TStDate; {-Convert an Object Professional two byte date into a SysTools date} function Convert4ByteDate(FourByteDate : TStDate) : Word; {-Convert a SysTools date into an Object Professional two byte date} implementation uses StUtils; const First2Months = 59; {1600 was a leap year} FirstDayOfWeek = Saturday; {01/01/1600 was a Saturday} DateLen = 40; {maximum length of Picture strings} MaxMonthName = 15; MaxDayName = 15; //type { DateString = string[DateLen];} // SString = string[255]; function IsLeapYear(Year : Integer) : Boolean; {-Return True if Year is a leap year} begin Result := (Year mod 4 = 0) and (Year mod 4000 <> 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0)); end; function IsLastDayofMonth(Day, Month, Year : Integer) : Boolean; {-Return True if date is the last day in month} var Epoch : Integer; begin Epoch := (Year div 100) * 100; if ValidDate(Day + 1, Month, Year, Epoch) then Result := false else Result := true; end; function IsLastDayofFeb(Date : TStDate) : Boolean; {-Return True if date is the last day in February} var Day, Month, Year : Integer; begin StDateToDMY(Date, Day, Month, Year); if (Month = 2) and IsLastDayOfMonth(Day, Month, Year) then Result := true else Result := false; end; function ResolveEpoch(Year, Epoch : Integer) : Integer; {-Convert 2-digit year to 4-digit year according to Epoch} var EpochYear, EpochCent : Integer; begin if Word(Year) < 100 then begin EpochYear := Epoch mod 100; EpochCent := (Epoch div 100) * 100; if (Year < EpochYear) then Inc(Year,EpochCent+100) else Inc(Year,EpochCent); end; Result := Year; end; function CurrentDate : TStDate; {-Returns today's date as a julian} var Year, Month, Date : Word; begin DecodeDate(Now,Year,Month,Date); Result := DMYToStDate(Date,Month,Year,0); end; function DaysInMonth(Month : integer; Year, Epoch : Integer) : Integer; {-Return the number of days in the specified month of a given year} begin Year := ResolveEpoch(Year, Epoch); if (Year < MinYear) OR (Year > MaxYear) then begin Result := 0; Exit; end; case Month of 1, 3, 5, 7, 8, 10, 12 : Result := 31; 4, 6, 9, 11 : Result := 30; 2 : Result := 28+Ord(IsLeapYear(Year)); else Result := 0; end; end; function ValidDate(Day, Month, Year, Epoch : Integer) : Boolean; {-Verify that day, month, year is a valid date} begin Year := ResolveEpoch(Year, Epoch); if (Day < 1) or (Year < MinYear) or (Year > MaxYear) then Result := False else case Month of 1..12 : Result := Day <= DaysInMonth(Month, Year, Epoch); else Result := False; end end; function DMYtoStDate(Day, Month, Year, Epoch : Integer) : TStDate; {-Convert from day, month, year to a julian date} begin Year := ResolveEpoch(Year, Epoch); if not ValidDate(Day, Month, Year, Epoch) then Result := BadDate else if (Year = MinYear) and (Month < 3) then if Month = 1 then Result := Pred(Day) else Result := Day+30 else begin if Month > 2 then Dec(Month, 3) else begin Inc(Month, 9); Dec(Year); end; Dec(Year, MinYear); Result := ((Integer(Year div 100)*Days400Yr) div 4)+ ((Integer(Year mod 100)*1461) div 4)+ (((153*Month)+2) div 5)+Day+First2Months; end; end; function WeekOfYear(Julian : TStDate) : Byte; {-Returns the week number of the year given the Julian Date} var Day, Month, Year : Integer; FirstJulian : TStDate; begin if (Julian < MinDate) or (Julian > MaxDate) then begin Result := 0; Exit; end; Julian := Julian + 3 - ((6 + Ord(DayOfWeek(Julian))) mod 7); StDateToDMY(Julian,Day,Month,Year); FirstJulian := DMYToStDate(1,1,Year,0); Result := 1 + (Julian - FirstJulian) div 7; end; function AstJulianDate(Julian : TStDate) : Double; {-Returns the Astronomical Julian Date from a TStDate} begin {Subtract 0.5d since Astronomical JD starts at noon while TStDate (with implied .0) starts at midnight} Result := Julian - 0.5 + DeltaJD; end; function AstJulianDatePrim(Year, Month, Date : Integer; UT : TStTime) : Double; var A, B : integer; LY, GC : Boolean; begin Result := -MaxLongInt; if (not (Month in [1..12])) or (Date < 1) then Exit else if (Month in [1, 3, 5, 7, 8, 10, 12]) and (Date > 31) then Exit else if (Month in [4, 6, 9, 11]) and (Date > 30) then Exit else if (Month = 2) then begin LY := IsLeapYear(Year); if ((LY) and (Date > 29)) or (not (LY) and (Date > 28)) then Exit; end else if ((UT < 0) or (UT >= SecondsInDay)) then Exit; if (Month <= 2) then begin Year := Year - 1; Month := Month + 12; end; A := abs(Year div 100); if (Year > 1582) then GC := True else if (Year = 1582) then begin if (Month > 10) then GC := True else if (Month < 10) then GC := False else begin if (Date >= 15) then GC := True else GC := False; end; end else GC := False; if (GC) then B := 2 - A + abs(A div 4) else B := 0; Result := Trunc(365.25 * (Year + 4716)) + Trunc(30.6001 * (Month + 1)) + Date + B - 1524.5 + UT / SecondsInDay; end; function AstJulianDatetoStDate(AstJulian : Double; Truncate : Boolean) : TStDate; {-Returns a TStDate from an Astronomical Julian Date. Truncate TRUE Converts to appropriate 0 hours then truncates FALSE Converts to appropriate 0 hours, then rounds to nearest;} begin {Convert to TStDate, adding 0.5d for implied .0d of TStDate} AstJulian := AstJulian + 0.5 - DeltaJD; if (AstJulian < MinDate) OR (AstJulian > MaxDate) then begin Result := BadDate; Exit; end; if Truncate then Result := Trunc(AstJulian) else Result := Trunc(AstJulian + 0.5); end; procedure StDateToDMY(Julian : TStDate; var Day, Month, Year : Integer); {-Convert from a julian date to month, day, year} var I, J : Integer; begin if Julian = BadDate then begin Day := 0; Month := 0; Year := 0; end else if Julian <= First2Months then begin Year := MinYear; if Julian <= 30 then begin Month := 1; Day := Succ(Julian); end else begin Month := 2; Day := Julian-30; end; end else begin I := (4*Integer(Julian-First2Months))-1; J := (4*((I mod Days400Yr) div 4))+3; Year := (100*(I div Days400Yr))+(J div 1461); I := (5*(((J mod 1461)+4) div 4))-3; Day := ((I mod 153)+5) div 5; Month := I div 153; if Month < 10 then Inc(Month, 3) else begin Dec(Month, 9); Inc(Year); end; Inc(Year, MinYear); end; end; function IncDate(Julian : TStDate; Days, Months, Years : Integer) : TStDate; {-Add (or subtract) the number of months, days, and years to a date. Months and years are added before days. No overflow/underflow checks are made} var Day, Month, Year, Day28Delta : Integer; begin StDateToDMY(Julian, Day, Month, Year); Day28Delta := Day-28; if Day28Delta < 0 then Day28Delta := 0 else Day := 28; Inc(Year, Years); Inc(Year, Months div 12); Inc(Month, Months mod 12); if Month < 1 then begin Inc(Month, 12); Dec(Year); end else if Month > 12 then begin Dec(Month, 12); Inc(Year); end; Julian := DMYtoStDate(Day, Month, Year,0); if Julian <> BadDate then begin Inc(Julian, Days); Inc(Julian, Day28Delta); end; Result := Julian; end; function IncDateTrunc(Julian : TStDate; Months, Years : Integer) : TStDate; {-Add (or subtract) the specified number of months and years to a date} var Day, Month, Year : Integer; MaxDay, Day28Delta : Integer; begin StDateToDMY(Julian, Day, Month, Year); Day28Delta := Day-28; if Day28Delta < 0 then Day28Delta := 0 else Day := 28; Inc(Year, Years); Inc(Year, Months div 12); Inc(Month, Months mod 12); if Month < 1 then begin Inc(Month, 12); Dec(Year); end else if Month > 12 then begin Dec(Month, 12); Inc(Year); end; Julian := DMYtoStDate(Day, Month, Year,0); if Julian <> BadDate then begin MaxDay := DaysInMonth(Month, Year,0); if Day+Day28Delta > MaxDay then Inc(Julian, MaxDay-Day) else Inc(Julian, Day28Delta); end; Result := Julian; end; procedure DateDiff(Date1, Date2 : TStDate; var Days, Months, Years : Integer); {-Return the difference in days,months,years between two valid julian dates} var Day1, Day2, Month1, Month2, Year1, Year2 : Integer; begin {we want Date2 > Date1} if Date1 > Date2 then ExchangeLongInts(Date1, Date2); {convert dates to day,month,year} StDateToDMY(Date1, Day1, Month1, Year1); StDateToDMY(Date2, Day2, Month2, Year2); {days first} if (Day1 = DaysInMonth(Month1, Year1, 0)) then begin Day1 := 0; Inc(Month1); {OK if Month1 > 12} end; if (Day2 = DaysInMonth(Month2, Year2, 0)) then begin Day2 := 0; Inc(Month2); {OK if Month2 > 12} end; if (Day2 < Day1) then begin Dec(Month2); if Month2 = 0 then begin Month2 := 12; Dec(Year2); end; Days := Day2 + DaysInMonth(Month2, Year2, 0) - Day1; {!!.02} end else Days := Day2-Day1; {now months and years} if Month2 < Month1 then begin Inc(Month2, 12); Dec(Year2); end; Months := Month2-Month1; Years := Year2-Year1; end; function BondDateDiff(Date1, Date2 : TStDate; DayBasis : TStBondDateType) : TStDate; {-Return the difference in days between two valid Julian dates using one a specific accrual method} var Day1, Month1, Year1, Day2, Month2, Year2 : Integer; IY : Integer; begin {we want Date2 > Date1} if Date1 > Date2 then ExchangeLongInts(Date1, Date2); if (DayBasis = bdtActual) then Result := Date2-Date1 else begin StDateToDMY(Date1, Day1, Month1, Year1); StDateToDMY(Date2, Day2, Month2, Year2); if ((DayBasis = bdt30360PSA) and IsLastDayofFeb(Date1)) or (Day1 = 31) then Day1 := 30; if (DayBasis = bdt30E360) then begin if (Day2 = 31) then Day2 := 30 end else if (Day2 = 31) and (Day1 >= 30) then Day2 := 30; IY := 360 * (Year2 - Year1); Result := IY + 30 * (Month2 - Month1) + (Day2 - Day1); end; end; function DayOfWeek(Julian : TStDate) : TStDayType; {-Return the day of the week for the date. Returns TStDayType(7) if Julian = BadDate.} var B : Byte; begin if Julian = BadDate then begin B := 7; Result := TStDayType(B); end else Result := TStDayType( (Julian+Ord(FirstDayOfWeek)) mod 7 ); end; function DayOfWeekDMY(Day, Month, Year, Epoch : Integer) : TStDayType; {-Return the day of the week for the day, month, year} begin Result := DayOfWeek( DMYtoStDate(Day, Month, Year, Epoch) ); end; procedure StTimeToHMS(T : TStTime; var Hours, Minutes, Seconds : Byte); {-Convert a Time variable to Hours, Minutes, Seconds} begin if T = BadTime then begin Hours := 0; Minutes := 0; Seconds := 0; end else begin Hours := T div SecondsInHour; Dec(T, Integer(Hours)*SecondsInHour); Minutes := T div SecondsInMinute; Dec(T, Integer(Minutes)*SecondsInMinute); Seconds := T; end; end; function HMStoStTime(Hours, Minutes, Seconds : Byte) : TStTime; {-Convert Hours, Minutes, Seconds to a Time variable} var T : TStTime; begin Hours := Hours mod HoursInDay; T := (Integer(Hours)*SecondsInHour)+(Integer(Minutes)*SecondsInMinute)+Seconds; Result := T mod SecondsInDay; end; function ValidTime(Hours, Minutes, Seconds : Integer) : Boolean; {-Return true if Hours:Minutes:Seconds is a valid time} begin if (Hours < 0) or (Hours > 23) or (Minutes < 0) or (Minutes >= 60) or (Seconds < 0) or (Seconds >= 60) then Result := False else Result := True; end; function CurrentTime : TStTime; {-Returns current time in seconds since midnight} begin Result := Trunc(SysUtils.Time * SecondsInDay); end; procedure TimeDiff(Time1, Time2 : TStTime; var Hours, Minutes, Seconds : Byte); {-Return the difference in hours,minutes,seconds between two times} begin StTimeToHMS(Abs(Time1-Time2), Hours, Minutes, Seconds); end; function IncTime(T : TStTime; Hours, Minutes, Seconds : Byte) : TStTime; {-Add the specified hours,minutes,seconds to T and return the result} begin Inc(T, HMStoStTime(Hours, Minutes, Seconds)); Result := T mod SecondsInDay; end; function DecTime(T : TStTime; Hours, Minutes, Seconds : Byte) : TStTime; {-Subtract the specified hours,minutes,seconds from T and return the result} begin Hours := Hours mod HoursInDay; Dec(T, HMStoStTime(Hours, Minutes, Seconds)); if T < 0 then Result := T+SecondsInDay else Result := T; end; function RoundToNearestHour(T : TStTime; Truncate : Boolean) : TStTime; {-Round T to the nearest hour, or Truncate minutes and seconds from T} var Hours, Minutes, Seconds : Byte; begin StTimeToHMS(T, Hours, Minutes, Seconds); Seconds := 0; if not Truncate then if Minutes >= (MinutesInHour div 2) then Inc(Hours); Minutes := 0; Result := HMStoStTime(Hours, Minutes, Seconds); end; function RoundToNearestMinute(const T : TStTime; Truncate : Boolean) : TStTime; {-Round T to the nearest minute, or Truncate seconds from T} var Hours, Minutes, Seconds : Byte; begin StTimeToHMS(T, Hours, Minutes, Seconds); if not Truncate then if Seconds >= (SecondsInMinute div 2) then Inc(Minutes); Seconds := 0; Result := HMStoStTime(Hours, Minutes, Seconds); end; procedure DateTimeDiff(const DT1 : TStDateTimeRec; var DT2 : TStDateTimeRec; {!!.02} var Days : Integer; var Secs : Integer); {-Return the difference in days and seconds between two points in time} var tDT1, tDT2 : TStDateTimeRec; begin tDT1 := DT1; tDT2 := DT2; {swap if tDT1 later than tDT2} if (tDT1.D > tDT2.D) or ((tDT1.D = tDT2.D) and (tDT1.T > tDT2.T)) then ExchangeStructs(tDT1, tDT2,sizeof(TStDateTimeRec)); {the difference in days is easy} Days := tDT2.D-tDT1.D; {difference in seconds} if tDT2.T < tDT1.T then begin {subtract one day, add 24 hours} Dec(Days); Inc(tDT2.T, SecondsInDay); end; Secs := tDT2.T-tDT1.T; end; function DateTimeToStDate(DT : TDateTime) : TStDate; {-Convert Delphi TDateTime to TStDate} var Day, Month, Year : Word; begin DecodeDate(DT, Year, Month, Day); Result := DMYToStDate(Day, Month, Year, 0); end; function DateTimeToStTime(DT : TDateTime) : TStTime; {-Convert Delphi TDateTime to TStTime} var Hour, Min, Sec, MSec : Word; begin DecodeTime(DT, Hour, Min, Sec, MSec); Result := HMSToStTime(Hour, Min, Sec); end; function StDateToDateTime(D : TStDate) : TDateTime; {-Convert TStDate to TDateTime} var Day, Month, Year : Integer; begin Result := 0; if D <> BadDate then begin StDateToDMY(D, Day, Month, Year); Result := EncodeDate(Year, Month, Day); end; end; function StTimeToDateTime(T : TStTime) : TDateTime; {-Convert TStTime to TDateTime} var Hour, Min, Sec : Byte; begin Result := 0; if T <> BadTime then begin StTimeToHMS(T, Hour, Min, Sec); Result := EncodeTime(Hour, Min, Sec, 0); end; end; procedure IncDateTime(const DT1 : TStDateTimeRec; var DT2 : TStDateTimeRec; {!!.02} Days : Integer; Secs : Integer); {-Increment (or decrement) DT1 by the specified number of days and seconds and put the result in DT2} begin DT2 := DT1; {date first} Inc(DT2.D, Integer(Days)); if Secs < 0 then begin {change the sign} Secs := -Secs; {adjust the date} Dec(DT2.D, Secs div SecondsInDay); Secs := Secs mod SecondsInDay; if Secs > DT2.T then begin {subtract a day from DT2.D and add a day's worth of seconds to DT2.T} Dec(DT2.D); Inc(DT2.T, SecondsInDay); end; {now subtract the seconds} Dec(DT2.T, Secs); end else begin {increment the seconds} Inc(DT2.T, Secs); {adjust date if necessary} Inc(DT2.D, DT2.T div SecondsInDay); {force time to 0..SecondsInDay-1 range} DT2.T := DT2.T mod SecondsInDay; end; end; function Convert2ByteDate(TwoByteDate : Word) : TStDate; begin Result := Integer(TwoByteDate) + Date1900; end; function Convert4ByteDate(FourByteDate : TStDate) : Word; begin Result := Word(FourByteDate - Date1900); end; procedure SetDefaultYear; {-Initialize DefaultYear and DefaultMonth} var Month, Day, Year : Word; T : TDateTime; begin T := Now; DecodeDate(T, Year, Month, Day); DefaultYear := Year; DefaultMonth := Month; end; initialization {initialize DefaultYear and DefaultMonth} SetDefaultYear; end.
{ *************************************************************************** Copyright (c) 2015-2022 Kike P�rez Unit : Quick.YAML Description : YAML Object parser Author : Kike P�rez Version : 1.1 Created : 17/04/2019 Modified : 07/03/2022 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.YAML; {$i QuickLib.inc} interface uses Classes, SysUtils, Quick.Commons, Generics.Collections, Quick.Value; type TYamlScalar = TFlexValue; TYamlAncestor = class abstract protected fOwned : Boolean; function IsNull : Boolean; virtual; procedure AddDescendant(const aDescendent: TYamlAncestor); virtual; public constructor Create; property Owned : Boolean read fOwned write fOwned; property Null : Boolean read IsNull; function IsScalar : Boolean; virtual; end; TYamlValue = class abstract(TYamlAncestor) public function Value : TFlexValue; virtual; function AsString : string; virtual; abstract; end; TYamlString = class(TYamlValue) private fValue : string; fIsNull : Boolean; protected function IsNull : Boolean; override; public constructor Create; overload; constructor Create(const aValue : string); overload; function Value : TFlexValue; override; function IsScalar : Boolean; override; function AsString : string; override; end; TYamlInteger = class(TYamlValue) private fValue : Integer; fIsNull : Boolean; protected function IsNull : Boolean; override; public constructor Create; overload; constructor Create(const aValue : Integer); overload; function Value : TFlexValue; override; function IsScalar : Boolean; override; function AsString : string; override; end; TYamlFloat = class(TYamlValue) private fValue : Double; fIsNull : Boolean; protected function IsNull : Boolean; override; public constructor Create; overload; constructor Create(const aValue : Double); overload; function Value : TFlexValue; override; function IsScalar : Boolean; override; function AsString : string; override; end; TYamlBoolean = class(TYamlValue) private fValue : Boolean; fIsNull : Boolean; protected function IsNull : Boolean; override; public constructor Create; overload; constructor Create(const aValue : Boolean); overload; function Value : TFlexValue; override; function IsScalar : Boolean; override; function AsString : string; override; end; TYamlNull = class(TYamlValue) protected function IsNull: Boolean; override; public function Value : TFlexValue; override; function AsString : string; override; end; TYamlComment = class(TYamlValue) private fValue : string; fIsNull : Boolean; protected function IsNull : Boolean; override; public constructor Create; overload; constructor Create(const aComment : string); overload; function Value : TFlexValue; override; function IsScalar : Boolean; override; function AsString : string; override; end; TYamlPair = class(TYamlAncestor) private fName : string; fValue : TYamlValue; protected procedure AddDescendant(const aDescendent: TYamlAncestor); override; public constructor Create(const aName : string; const aValue : TYamlValue); overload; constructor Create(const aName : string; const aValue : string); overload; constructor Create(const aName : string; const aValue : Integer); overload; constructor Create(const aName : string; const aValue : Double); overload; destructor Destroy; override; property Name : string read fName write fName; property Value : TYamlValue read fValue write fValue; function ToYaml : string; end; TYamlWriter = class private fData : string; public constructor Create; property Text : string read fData; procedure Write(const aValue : string); procedure Writeln(const aValue : string); end; TYamlObject = class(TYamlValue) public type TEnumerator = class private fIndex: Integer; fObject: TYamlObject; public constructor Create(const aObject: TYamlObject); function GetCurrent: TYamlPair; inline; function MoveNext: Boolean; inline; property Current: TYamlPair read GetCurrent; end; private fMembers : TList<TYamlPair>; function GetCount : Integer; class function ParseValue(yaml : TList<string>; var vIndex : Integer): TYamlAncestor; class function ParsePairName(const aPair : string) : string; class function ParsePairValue(const aPair : string) : string; class function ParseArrayValue(const aValue : string) : TYamlValue; class function GetItemLevel(const aValue : string) : Integer; function ParseToYaml(aIndent : Integer) : string; protected procedure AddDescendant(const aDescendent: TYamlAncestor); override; public constructor Create; overload; constructor Create(const aData : string); overload; destructor Destroy; override; function GetValue(const aName: string): TYamlValue; property Values[const aName: string] : TYamlValue read GetValue; procedure ParseYaml(const aData : string); property Count : Integer read GetCount; class function ParseYamlValue(const aData : string) : TYamlAncestor; function GetPair(const aIndex : Integer) : TYamlPair; function GetPairByName(const aPairName : string) : TYamlPair; function AddPair(const aPair : TYamlPair): TYamlObject; overload; function AddPair(const aName : string; const aValue : TYamlValue): TYamlObject; overload; function AddPair(const aName : string; const aValue : string): TYamlObject; overload; function RemovePair(const aPairName: string): TYamlPair; function GetEnumerator: TEnumerator; inline; property Pairs[const aIndex: Integer]: TYamlPair read GetPair; function ToYaml : string; function AsString : string; override; end; { TYamlArray } TYamlArray = class(TYamlValue) public type TEnumerator = class private fIndex : Integer; fArray : TYamlArray; public constructor Create(const aArray: TYamlArray); function GetCurrent: TYamlValue; inline; function MoveNext: Boolean; inline; property Current: TYamlValue read GetCurrent; end; private fElements: TList<TYamlValue>; function ParseToYaml(aIndent : Integer; var vIsScalar : Boolean) : string; protected procedure AddDescendant(const aDescendant: TYamlAncestor); override; function GetCount: Integer; inline; function GetValue(const aIndex: Integer): TYamlValue; overload; inline; public constructor Create; overload; constructor Create(const aFirstElem: TYamlValue); overload; destructor Destroy; override; property Count: Integer read GetCount; property Items[const aIndex: Integer]: TYamlValue read GetValue; procedure AddElement(const aElement: TYamlValue); function GetEnumerator: TEnumerator; inline; function AsString : string; override; end; EYAMLException = class(Exception); implementation const NUM_INDENT = 2; { TYamlAncestor } procedure TYamlAncestor.AddDescendant(const aDescendent: TYamlAncestor); begin raise EYAMLException.CreateFmt('Cannot add value %s to %s',[aDescendent.ClassName,ClassName]); end; constructor TYamlAncestor.Create; begin inherited Create; fOwned := True; end; function TYamlAncestor.IsNull: Boolean; begin Result := False; end; function TYamlAncestor.IsScalar: Boolean; begin Result := False; end; { TYamlObject } function TYamlObject.AddPair(const aPair: TYamlPair): TYamlObject; begin if aPair <> nil then AddDescendant(aPair); Result := Self; end; function TYamlObject.AddPair(const aName: string; const aValue: TYamlValue): TYamlObject; begin if (not aName.IsEmpty) and (aValue <> nil) then AddPair(TYamlPair.Create(aName,aValue)); Result := Self; end; procedure TYamlObject.AddDescendant(const aDescendent: TYamlAncestor); begin if aDescendent <> nil then fMembers.Add(TYamlPair(aDescendent)); end; function TYamlObject.AddPair(const aName, aValue: string): TYamlObject; begin if not aName.IsEmpty and (not aValue.IsEmpty) then AddPair(TYamlPair.Create(aName,aValue)); Result := Self; end; function TYamlObject.AsString: string; begin Result := ToYaml; end; constructor TYamlObject.Create(const aData: string); begin inherited Create; ParseYaml(aData); end; constructor TYamlObject.Create; begin inherited Create; fMembers := TList<TYamlPair>.Create; end; destructor TYamlObject.Destroy; var member: TYamlAncestor; i: Integer; begin if Assigned(fMembers) then for i := 0 to fMembers.Count - 1 do begin {$IFNDEF FPC} member := fMembers.List[i]; {$ELSE} member := fMembers.Items[i]; {$ENDIF} if Assigned(member) and member.Owned then member.Free; end; FreeAndNil(fMembers); inherited; end; function TYamlObject.GetCount: Integer; begin Result := fMembers.Count; end; function TYamlObject.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(Self); end; class function TYamlObject.GetItemLevel(const aValue: string): Integer; var i : Integer; trimed : string; begin trimed := aValue.Trim; if trimed.IsEmpty or trimed.StartsWith('#') then Exit(99999); for i := Low(aValue) to aValue.Length do begin if aValue[i] <> ' ' then Exit(i); end; Result := Low(aValue); end; function TYamlObject.GetPair(const aIndex: Integer): TYamlPair; begin Result := fMembers[aIndex]; end; function TYamlObject.GetPairByName(const aPairName: string): TYamlPair; var yamlpair : TYamlPair; I: Integer; begin for i := 0 to Count - 1 do begin {$IFNDEF FPC} yamlpair := fMembers.List[i]; {$ELSE} yamlpair := fMembers.Items[i]; {$ENDIF} if CompareText(yamlpair.Name,aPairName) = 0 then Exit(yamlpair); end; Result := nil; end; function TYamlObject.GetValue(const aName: string): TYamlValue; var ymlpair: TYamlPair; i: Integer; begin for i := 0 to Count - 1 do begin {$IFNDEF FPC} ymlpair := fMembers.List[i]; {$ELSE} ymlpair := fMembers.Items[i]; {$ENDIF} if CompareText(ymlpair.Name,aName) = 0 then Exit(ymlpair.Value); end; Result := nil; end; class function TYamlObject.ParseArrayValue(const aValue: string): TYamlValue; var nint : Int64; nfloat : Double; begin if TryStrToInt64(aValue,nint) then Result := TYamlInteger.Create(nint) else if TryStrToFloat(aValue,nfloat) then Result := TYamlFloat.Create(nfloat) else Result := TYamlString.Create(aValue); end; class function TYamlObject.ParsePairName(const aPair: string): string; begin Result := Copy(aPair,0,aPair.IndexOf(':')); end; class function TYamlObject.ParsePairValue(const aPair: string): string; begin Result := AnsiDequotedStr(Copy(aPair,aPair.IndexOf(':')+2,aPair.Length).Trim, '"'); end; class function TYamlObject.ParseValue(yaml : TList<string>; var vIndex : Integer): TYamlAncestor; type TYamlType = (ytObject, ytArray, ytScalarArray, ytScalar); var name : string; value : string; yvalue : TYamlAncestor; level : Integer; nextlevel : Integer; aitem : string; yamlType : TYamlType; begin Result := nil; level := 0; while yaml.Count > vIndex do begin value := yaml[vIndex].Trim; name := ParsePairName(value); if (name.IsEmpty) or (value.IsEmpty) or (value.StartsWith('#')) or (value.StartsWith(#9)) then Exit(nil) //else if value.StartsWith('#') then Exit(TYamlComment.Create(value)) else if value.StartsWith('-') then begin yaml[vIndex] := StringReplace(yaml[vIndex],'-','',[]).TrimLeft; yamlType := ytObject; Dec(vIndex); end else if value.EndsWith(':') then begin if yaml[vIndex + 1].TrimLeft.StartsWith('-') then yamlType := ytArray else yamlType := ytObject; end else if value.IndexOf(':') < value.Length then begin value := ParsePairValue(value); if (value.StartsWith('[')) and (value.EndsWith(']')) then yamlType := ytScalarArray else yamlType := ytScalar; end else yamlType := TYamlType.ytScalar; case yamlType of ytArray : //is array begin yvalue := TYamlArray.Create; level := GetItemLevel(yaml[vIndex + 1]); repeat Inc(vIndex); yvalue.AddDescendant(ParseValue(yaml,vIndex)); until (yvalue = nil) or (vIndex >= yaml.Count - 1) or (GetItemLevel(yaml[vIndex + 1]) < level); Exit(TYamlPair.Create(name,TYamlValue(yvalue))); end; ytObject : //is object begin yvalue := TYamlObject.Create; repeat Inc(vIndex); nextlevel := GetItemLevel(yaml[vIndex]); if nextlevel <> 99999 then level := nextlevel; yvalue.AddDescendant(ParseValue(yaml,vIndex)); //level := GetItemLevel(yaml[vIndex]); //var level2 := GetItemLevel(yaml[offset + 1]); until (yvalue = nil) or (vIndex >= yaml.Count - 1) or (GetItemLevel(yaml[vIndex + 1]) < level); Exit(TYamlPair.Create(name,TYamlValue(yvalue))); end; ytScalarArray : //is scalar array begin yvalue := TYamlArray.Create; value := StringReplace(Copy(value,2,Value.Length-2),', ',#9,[rfReplaceAll]); for aitem in value.Split([#9]) do begin yvalue.AddDescendant(ParseArrayValue(aitem)); end; Exit(TYamlPair.Create(name,TYamlValue(yvalue))); end; else Exit(TYamlPair.Create(name,value)); //is scalar end; Inc(vIndex); end; end; procedure TYamlObject.ParseYaml(const aData: string); var yaml : TList<string>; line : string; data : string; yamlvalue : TYamlAncestor; vIndex : Integer; begin yaml := TList<string>.Create; try vIndex := 0; //normalize tabs data := StringReplace(aData,#9,Spaces(NUM_INDENT),[rfReplaceAll]); {$IFDEF MSWINDOWS} for line in data.Split([#13]) do yaml.Add(StringReplace(line,#10,'',[rfReplaceAll])); {$ELSE} for line in data.Split([#10]) do yaml.Add(StringReplace(line,#13,'',[rfReplaceAll])); {$ENDIF} while yaml.Count > vIndex do begin yamlvalue := ParseValue(yaml,vIndex); if yamlvalue <> nil then AddDescendant(yamlvalue); Inc(vIndex); end; finally yaml.Free; end; end; class function TYamlObject.ParseYamlValue(const aData : string) : TYamlAncestor; var yaml : TList<string>; line : string; data : string; yamlvalue : TYamlAncestor; vIndex : Integer; begin yaml := TList<string>.Create; try vIndex := 0; //normalize tabs data := StringReplace(aData,#9,Spaces(NUM_INDENT),[rfReplaceAll]); {$IFDEF MSWINDOWS} for line in data.Split([#13]) do yaml.Add(StringReplace(line,#10,'',[rfReplaceAll])); {$ELSE} for line in data.Split([#10]) do yaml.Add(StringReplace(line,#13,'',[rfReplaceAll])); {$ENDIF} if yaml[0].TrimLeft.StartsWith('- ') then Result := TYamlArray.Create else Result := TYamlObject.Create; while yaml.Count > vIndex do begin yamlvalue := ParseValue(yaml,vIndex); if yamlvalue <> nil then Result.AddDescendant(yamlvalue); Inc(vIndex); end; finally yaml.Free; end; end; function TYamlObject.RemovePair(const aPairName: string): TYamlPair; var yamlpair: TYamlPair; i: Integer; begin for i := 0 to Count - 1 do begin {$IFNDEF FPC} yamlpair := TYamlPair(FMembers.List[i]); {$ELSE} yamlpair := TYamlPair(fMembers.Items[i]); {$ENDIF} if CompareText(yamlpair.Name,aPairName) = 0 then begin fMembers.Remove(yamlpair); Exit(yamlpair); end; end; Result := nil; end; function TYamlObject.ToYaml: string; begin Result := ParseToYaml(0); end; function TYamlObject.ParseToYaml(aIndent : Integer) : string; const SPECIAL_CHARS: array[1..19] of Char = (':', '{', '}', '[', ']', ',', '&', '*', '#', '?', '|', '-', '<', '>', '=', '!', '%', '@', '\'); var i : Integer; member : TYamlPair; yaml : TYamlWriter; yvalue : TYamlAncestor; indent : string; isscalar : Boolean; scalar : string; rarray : string; begin yaml := TYamlWriter.Create; try indent := StringOfChar(' ',aIndent); for i := 0 to fMembers.Count - 1 do begin member := fMembers[i]; if member = nil then continue; yvalue := member.Value; if (yvalue.IsScalar) or (yvalue is TYamlNull) then begin if yvalue is TYamlComment then yaml.Writeln(Format('#%s%s',[indent,TYamlComment(member.Value).AsString])) else begin if yvalue is TYamlNull then scalar := 'null' else if (yvalue is TYamlFloat) or (yvalue is TYamlBoolean) then scalar := member.Value.AsString else scalar := member.Value.Value.AsString; if scalar.IsEmpty then scalar := '""'; if scalar.IndexOfAny(SPECIAL_CHARS) > -1 then scalar := AnsiQuotedStr(scalar, '"'); yaml.Writeln(Format('%s%s: %s',[indent,member.Name,scalar])); if (i < fMembers.Count - 1) and (fMembers[i+1].Value is TYamlComment) then yaml.Writeln(''); end; end else if (yvalue is TYamlObject) then begin yaml.Writeln(Format('%s%s:',[indent,member.Name])); yaml.Write((yvalue as TYamlObject).ParseToYaml(aIndent + NUM_INDENT)); if aIndent = 0 then yaml.Writeln(''); end else if (yvalue is TYamlArray) then begin isscalar := False; rarray := (yvalue as TYamlArray).ParseToYaml(aIndent + NUM_INDENT,isscalar); if isscalar then yaml.Writeln(Format('%s%s: %s',[indent,member.Name,rarray])) else begin yaml.Writeln(Format('%s%s:',[indent,member.Name])); yaml.Write(rarray); end; end; end; Result := yaml.Text; finally yaml.Free; end; end; { TYamlString } constructor TYamlString.Create(const aValue: string); begin inherited Create; fValue := aValue; fIsNull := False; end; constructor TYamlString.Create; begin inherited Create; fIsNull := True; end; function TYamlString.IsNull: Boolean; begin Result := fIsNull; end; function TYamlString.IsScalar: Boolean; begin Result := True; end; function TYamlString.AsString: string; begin Result := fValue; end; function TYamlString.Value: TFlexValue; begin Result := fValue; end; { TYamlInteger } constructor TYamlInteger.Create(const aValue: Integer); begin inherited Create; fValue := aValue; fIsNull := False; end; constructor TYamlInteger.Create; begin inherited Create; fIsNull := True; end; function TYamlInteger.IsNull: Boolean; begin Result := fIsNull; end; function TYamlInteger.IsScalar: Boolean; begin Result := True; end; function TYamlInteger.AsString: string; begin Result := IntToStr(fValue); end; function TYamlInteger.Value: TFlexValue; begin Result := fValue; end; { TYamlFloat } constructor TYamlFloat.Create(const aValue: Double); begin inherited Create; fValue := aValue; fIsNull := False; end; constructor TYamlFloat.Create; begin inherited Create; fIsNull := True; end; function TYamlFloat.IsNull: Boolean; begin Result := fIsNull; end; function TYamlFloat.IsScalar: Boolean; begin Result := True; end; function TYamlFloat.AsString: string; begin Result := FloatToStr(fValue); end; function TYamlFloat.Value: TFlexValue; begin Result := fValue; end; { TYamlPair } constructor TYamlPair.Create(const aName: string; const aValue: TYamlValue); begin inherited Create; fName := aName; fValue := aValue; end; constructor TYamlPair.Create(const aName, aValue: string); begin inherited Create; fName := aName; fValue := TYamlString.Create(aValue); end; constructor TYamlPair.Create(const aName: string; const aValue: Double); begin inherited Create; fName := aName; fValue := TYamlFloat.Create(aValue); end; constructor TYamlPair.Create(const aName: string; const aValue: Integer); begin inherited Create; fName := aName; fValue := TYamlInteger.Create(aValue); end; destructor TYamlPair.Destroy; begin if (fValue <> nil) and fValue.Owned then FreeAndNil(fValue); inherited Destroy; end; function TYamlPair.ToYaml: string; var isscalar : Boolean; begin if fValue = nil then Exit('null'); if fValue is TYamlObject then Result := TYamlObject(fValue).ToYaml else if fValue is TYamlArray then Result := TYamlArray(fValue).ParseToYaml(0,isscalar) else Result := Format('%s: %s',[fName,fValue.Value.AsString]); end; procedure TYamlPair.AddDescendant(const aDescendent: TYamlAncestor); begin if fName = '' then fName := TYamlString(aDescendent).Value else if fValue = nil then fValue:= TYamlValue(aDescendent) else inherited AddDescendant(aDescendent); end; { TYamlObject.TEnumerator } constructor TYamlObject.TEnumerator.Create(const aObject: TYamlObject); begin inherited Create; fIndex := -1; fObject := aObject; end; function TYamlObject.TEnumerator.GetCurrent: TYamlPair; begin {$IFNDEF FPC} Result := fObject.fMembers.List[fIndex]; {$ELSE} Result := fObject.fMembers.Items[fIndex]; {$ENDIF} end; function TYamlObject.TEnumerator.MoveNext: Boolean; begin Inc(fIndex); Result := fIndex < fObject.Count; end; { TYamlValue } function TYamlValue.Value: TFlexValue; begin Result := ''; end; { TYamlArray.TEnumerator } constructor TYamlArray.TEnumerator.Create(const aArray: TYamlArray); begin inherited Create; fIndex := -1; fArray := aArray; end; function TYamlArray.TEnumerator.GetCurrent: TYamlValue; begin {$IFNDEF FPC} Result := fArray.fElements.List[fIndex]; {$ELSE} Result := fArray.fElements.Items[fIndex]; {$ENDIF} end; function TYamlArray.TEnumerator.MoveNext: Boolean; begin Inc(fIndex); Result := fIndex < fArray.Count; end; { TYamlArray } procedure TYamlArray.AddDescendant(const aDescendant: TYamlAncestor); begin fElements.Add(TYamlValue(aDescendant)); end; constructor TYamlArray.Create; begin inherited Create; fElements := TList<TYamlValue>.Create; end; constructor TYamlArray.Create(const aFirstElem: TYamlValue); begin inherited Create; AddElement(aFirstElem); end; procedure TYamlArray.AddElement(const aElement: TYamlValue); begin if aElement <> nil then AddDescendant(aElement); end; function TYamlArray.AsString: string; var first : Boolean; element : TYamlValue; begin first := True; for element in fElements do begin if first then Result := Result + element.AsString else Result := Result + ',' + element.AsString; end; Result := Format('[%s]',[Result]); end; destructor TYamlArray.Destroy; var element: TYamlAncestor; i: Integer; begin if Assigned(fElements) then for i := 0 to fElements.Count - 1 do begin element := fElements[i]; if Assigned(element) and (element.Owned) then element.Free; end; if Assigned(fElements) then FreeAndNil(fElements); inherited Destroy; end; function TYamlArray.GetCount: Integer; begin Result := fElements.Count; end; function TYamlArray.GetEnumerator: TEnumerator; begin Result := TEnumerator.Create(Self); end; function TYamlArray.GetValue(const aIndex: Integer): TYamlValue; begin Result := fElements[aIndex]; end; function TYamlArray.ParseToYaml(aIndent : Integer; var vIsScalar : Boolean) : string; var element : TYamlValue; yaml : TYamlWriter; yvalue : TYamlAncestor; indent : string; isscalar : Boolean; begin Result := ''; yvalue := nil; yaml := TYamlWriter.Create; try indent := StringOfChar(' ',aIndent); if fElements.Count = 0 then begin vIsScalar := True; Exit('[]'); end; for element in fElements do begin yvalue := element; if yvalue is TYamlPair then yvalue := TYamlPair(yvalue).value; if yvalue.IsScalar then begin {$IFNDEF FPC} if Result = '' then Result := element.AsString else Result := Result + ', ' + element.AsString; {$ELSE} if Result = '' then Result := TYamlPair(element).Value.AsString else Result := Result + ', ' + TYamlPair(element).Value.AsString; {$ENDIF} end else if (yvalue is TYamlObject) then begin yaml.Write(indent + '- ' + (yvalue as TYamlObject).ParseToYaml(aIndent + NUM_INDENT).TrimLeft); end else if (yvalue is TYamlArray) then begin yaml.Write(Format('%s%s',[indent,(yvalue as TYamlArray).ParseToYaml(aIndent + NUM_INDENT,isscalar)])) end; yaml.Writeln(''); end; if (yvalue <> nil) and (yvalue.IsScalar) then begin Result := '[' + Result + ']'; vIsScalar := True; end else Result := yaml.Text; finally yaml.Free; end; end; { TYamlWriter } procedure TYamlWriter.Write(const aValue: string); begin fData := fData + aValue; end; procedure TYamlWriter.Writeln(const aValue: string); begin fData := fData + aValue + CRLF; end; constructor TYamlWriter.Create; begin fData := ''; end; { TYamlNull } function TYamlNull.IsNull: Boolean; begin Result := True; end; function TYamlNull.AsString: string; begin Result := 'null'; end; function TYamlNull.Value: TFlexValue; begin Result := nil; end; { TYamlBoolean } constructor TYamlBoolean.Create; begin inherited Create; fIsNull := True; end; constructor TYamlBoolean.Create(const aValue: Boolean); begin inherited Create; fIsNull := False; fValue := aValue; end; function TYamlBoolean.IsNull: Boolean; begin Result := fIsNull; end; function TYamlBoolean.IsScalar: Boolean; begin Result := True; end; function TYamlBoolean.AsString: string; begin Result := BoolToStr(fValue,True).ToLower; end; function TYamlBoolean.Value: TFlexValue; begin Result := fValue; end; { TYamlComment } function TYamlComment.AsString: string; begin Result := fValue; end; constructor TYamlComment.Create; begin inherited Create; fIsNull := True; end; constructor TYamlComment.Create(const aComment: string); begin inherited Create; fIsNull := False; fValue := aComment; end; function TYamlComment.IsNull: Boolean; begin Result := fIsNull; end; function TYamlComment.IsScalar: Boolean; begin Result := True; end; function TYamlComment.Value: TFlexValue; begin end; end.
unit Scenes; interface uses Classes; const scMenu = 0; scGame = 1; scFrame = 2; type TScene = class(TObject) procedure Render(); virtual; abstract; procedure Update(); virtual; abstract; end; type TScenes = class(TScene) private FScene: TScene; procedure SetScene(const Value: TScene); public procedure Render(); override; procedure Update(); override; property Scene: TScene read FScene write SetScene default nil; procedure Clear; end; var SceneManager: TScenes; CurrentScene: array of TScene; implementation uses gm_engine; { TScenes } procedure TScenes.Clear; begin Scene := nil; end; procedure TScenes.Render; begin if (Scene <> nil) then Scene.Render; end; procedure TScenes.Update; begin if (Scene <> nil) then Scene.Update; end; procedure TScenes.SetScene(const Value: TScene); begin FScene := Value; ClearStates; end; end.
unit TestForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) btnParseHtml: TButton; mmo1: TMemo; mmo2: TMemo; btnClear: TButton; procedure btnParseHtmlClick(Sender: TObject); procedure btnClearClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses HTMLParserAll3; procedure TForm1.btnClearClick(Sender: TObject); begin mmo1.Lines.Clear; end; procedure TForm1.btnParseHtmlClick(Sender: TObject); var tmpHtmlParser: PHtmlParser; tmpHtmlDoc: PHtmlDocDomNode; tmpDomNode: PHtmlDomNode; i: integer; begin mmo2.Lines.Clear; tmpHtmlDoc := nil; tmpHtmlParser := CheckoutHtmlParser; try tmpHtmlDoc := HtmlParserparseString(tmpHtmlParser, mmo1.Lines.Text); finally CheckInHtmlParser(tmpHtmlParser); end; if nil <> tmpHtmlDoc then begin //mmo2.Lines.Add(IntToStr(GlobalTestNodeCount)); HtmlDomNodeFree(PHtmlDomNode(tmpHtmlDoc)); end; //mmo2.Lines.Add(IntToStr(GlobalTestNodeCount)); mmo2.Lines.Add('----------------------------'); // for i := 0 to tmpHtmlDoc.Count - 1 do // begin // tmpDomNode := tmpHtmlDoc.Items[i]; // mmo2.Lines.Add(IntToStr(tmpDomNode.NodeType) + ' - ' + tmpDomNode.NodeName); // if HTMLDOM_NODE_TEXT = tmpDomNode.NodeType then // begin // mmo2.Lines.Add(IntToStr(tmpDomNode.NodeType) + ' - ' + tmpDomNode.NodeValue); // end; // end; mmo2.Lines.Add('----------------------------'); end; end.
unit Functions; interface uses SysUtils, Dialogs, Graphics, Classes, ExtCtrls; function ExtractFileNameWithoutExt(filename: string): string; procedure ClearImage(Image: TImage; BackgroundColor: TColor); function Explode(Separator, Text: String): TStringList; function Position(FullString, Search: String): Integer; function DotsAtBeginning(s: string): integer; function DotsAtEnd(s: string): integer; implementation function ExtractFileNameWithoutExt(filename: string): string; begin result := ExtractFileName(filename); result := copy(result, 1, Length(result)-Length(ExtractFileExt(result))); end; procedure ClearImage(Image: TImage; BackgroundColor: TColor); var OldPenColor, OldBrushColor: TColor; begin OldPenColor := Image.Canvas.Pen.Color; OldBrushColor := Image.Canvas.Brush.Color; Image.Canvas.Pen.Color := BackgroundColor; Image.Canvas.Brush.Color := BackgroundColor; Image.Canvas.Rectangle(0, 0, Image.Width, Image.Height); Image.Canvas.Pen.Color := OldPenColor; Image.Canvas.Brush.Color := OldBrushColor; end; function Explode(Separator, Text: String): TStringList; var pos: integer; tmp: string; begin result := TStringList.Create; while Length(Text) > 0 do begin pos := Functions.Position(Text, Separator); if pos = -1 then begin tmp := Text; Text := ''; end else begin tmp := copy(Text, 1, pos-1); Text := copy(Text, pos+1, Length(Text)-pos); end; result.Add(tmp); end; end; function Position(FullString, Search: String): Integer; var x: Integer; begin x := Length(StrPos(PChar(FullString), PChar(Search))); if x = 0 then result := -1 else result := Length(FullString) - x + 1; end; function DotsAtBeginning(s: string): integer; var i: integer; begin result := 0; for i := 1 to Length(s) do begin if s[i] = '.' then Inc(result) else Exit; end; end; function DotsAtEnd(s: string): integer; var i: integer; begin result := 0; for i := Length(s) downto 1 do begin if s[i] = '.' then Inc(result) else Exit; end; end; end.
{ This is a personal project that I give to community under this licence: Copyright 2016 Eric Buso (Alias Caine_dvp) 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. } {%BuildWorkingDir D:\Dev_Projects\WebLogAnalyser\tests\Release tests\Lazarus} {%RunWorkingDir D:\Dev_Projects\WebLogAnalyser\tests\Release tests\Lazarus} unit UDataEngine; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface Uses UCustomDataEngine,UCommons; type { TGeolocData } TGeolocData = class(TCustomDataEngine) Public constructor Create(Const DBName:String); function GetCountryName(Const IPAddress:String):String; function IsTheLastIPAddress(IPAddress:String):Boolean; Private FLastIPChecked : String; const //Alias des tables Geoloc BlockIPV4 ='GeoLite_block_IPv4'; CountryLocation= 'GeoLite_Country_Location' ; //Alias des noms de la table GeoLite_block_IPv4 IP1 ='IP1'; IP2 ='IP2'; IP3 ='IP3'; IP4 ='IP4'; CIDR='CIDR'; Geoname='geoname_id'; regCountryGeoname='registered_country_geoname_id'; repCountryGeoname='represented_country_geoname_id'; IsAnonymousProxy='is_anonymous_proxy'; IsSatelliteProvider='is_satellite_provider'; //Alias des noms de la table GeoLite_Country_Location: GeonameID='geoname_id'; LocaleCode='locale_code'; ContientCode='continent_code'; ContinentName='continent_name'; CountryIsoCode='country_iso_code'; CountryName='country_name'; end; TDataEngine = class(TCustomDataEngine) Public constructor Create(Const DBName:String); procedure InsertDomain( const Infos : TLogsInfo; var Error: integer); procedure InsertHuman ( const Infos : TLogsInfo; var Error: integer); procedure InsertRobot ( const Infos : TLogsInfo; var Error: integer); Private Const // Alias des noms de tables de la Bdd. Domain = 'SiteDomains' ; Human = 'Human_traffic' ; Robots = 'Robots_traffic' ; AgentInfos = 'UserAgentInfos' ; RobotsInfos= 'Robot_infos' ; //Alias des noms de colonnes de la Bdd. // Table 'Domain' DomainKey = 'DN_Key' ; DomainName = 'DomainName' ; // Table 'Human' IPKey ='IP_Key' ; IPAddress ='IP_Address' ; //DomainName foreign key (DN_KEY). Referrer = 'Referrer' ; DateTime = 'VisitDatetime'; TimeZone = 'TimeZone' ; FileR = 'FileRequest' ; FileS = 'FileSize' ; Protocol = 'Protocol' ; Code = 'Code' ; // 'UserAgentInfos' Country = 'Country' ; Browser = 'Browser' ; OS = 'OS' ; // Table 'Robots', cette table reprend la majorité des champs de la table 'human' BotName = 'BotName'; function ForeignKey(const Table : string ; const Column : string;const ForeignColumn: String; const ForeignFormat: TVarRec;Var ForeignValue: TVarRec ) : String; end; implementation Uses SysUtils,StrUtils,Windows; { TGeolocData } constructor TGeolocData.Create(const DBName: String); begin inherited Create(DBName); end; function TGeolocData.IsTheLastIPAddress(IPAddress: String): Boolean; begin Result := (AnsiCompareText(FLastIPChecked,IPAddress)=0); end; function TGeolocData.GetCountryName(const IPAddress: String): String; Var Cols: Array of TVarRec; CIDRMasks: Array[1..4] of Integer; SearchStr:String; //IPS sera accéder par reste de la division par 8. Donc commence à zéro. IPS: Array[1..4] of String; GeoNameSearch :String; calc,p,ICIDR,Mask,len,llen,I:Integer; const Masks: Array[0..7] of integer = (255,128,192,224,240,248,252,254); begin //Extraire les 4 parties de l'adresse IP FLastIPChecked := IPAddress; len := Length(IPAddress); p := Pos('.',IPAddress); llen := p; IPS[1] := Copy( IPAddress,0,p-1); p := PosEx('.',IPAddress,p+1); IPS[2] := Copy( IPAddress,llen+1,p-llen-1); llen:=p; p := PosEx('.',IPAddress,p+1); IPS[3] := Copy( IPAddress,llen+1,p-llen-1); IPS[4] := Copy( IPAddress,p+1,len-p); For ICIDR := 8 to 32 Do Begin //Remise à zéro des chaînes de recherches. FillMemory(PVOID(@CIDRMasks),4*sizeof(String),0); //Convertir la partie IP en entier puis appliquer le masque. p := ICIDR Div 8; llen := ICIDR mod 8; I := 0; //Construire la table des masque de CIDR. For I :=1 To P Do Begin Mask := StrToInt(IPS[I]); Mask := Mask And Masks[0]; //Construire la chaine de recherche Sql à partir des masques. CIDRMasks[I] := Mask; end; If (llen > 0) Then //Erreur ici: 2*2*8 pour CIDR 17! Begin Inc(I); Mask := StrToInt(IPS[I]); Mask := Mask And Masks[llen]; //Construire la chaine de recherche Sql à partir des masques. CIDRMasks[I] := Mask; End; Columns := Geoname; Tables := BlockIPV4; Where := IP1+'='+IntToStr(CIDRMasks[1])+' and '+IP2+'='+IntToStr(CIDRMasks[2])+' and '+IP3+'='+IntToStr(CIDRMasks[3])+' and '+IP4+'='+IntToStr(CIDRMasks[4])+' and '+CIDR+'='+IntToStr(ICIDR); Select; If RowCount =1 then Begin SetLength(Cols,1); Cols[0].vType := vtPChar; Fetch(Cols); GeoNameSearch := String(Rows[0][0].VPChar); Columns := CountryName; Tables := CountryLocation; Where := GeonameID +'='+GeoNameSearch; Select; If RowCount = 1 then Begin SetLength(Cols,1); Cols[0].vType := vtPchar; Fetch(Cols); Result := String(Rows[0][0].VPChar); End; exit; End; end; end; { TDataEngine } //function TDataEngine.ForeignKey(const Value: TVarRec; const Table, constructor TDataEngine.Create(const DBName: String); begin inherited Create(DBName); end; function TDataEngine.ForeignKey(const Table, Column: string;const ForeignColumn: String; const ForeignFormat: TVarRec;Var ForeignValue: TVarRec): String; Var StrValue : String; Value: string; Cols : Array[0..0] of TVarRec; begin Result := EmptyStr; Case ForeignFormat.VType of vtInteger: Value := IntToStr(ForeignFormat.VInteger); vtChar: Value := ForeignFormat.VChar; vtString: Value := (ForeignFormat.VString)^ ; vtPChar: Value := String(ForeignFormat.VPChar) ; End; Columns := ForeignColumn; Tables := Table; Where := ' ' + Column + '="'+Value+'"'; Select; Cols[0] := ForeignValue; Fetch(Cols); Case ForeignValue.VType Of vtInteger: Begin ForeignValue.VInteger := Rows[0][0].VInteger; Result := IntToStr(ForeignValue.VInteger); End; vtChar: Begin ForeignValue.VChar := Rows[0][0].VChar; Result := ForeignValue.VChar; End; vtPChar: Begin ForeignValue.VPChar := Rows[0][0].VPChar; Result := String(ForeignValue.VPChar) ; End; End; end; procedure TDataEngine.InsertDomain(const Infos: TLogsInfo; var Error: integer); begin If Exists(Infos.Domain,Domain,DomainName) Then Exit; Tables := Domain; Columns := DomainKey+','+DomainName; Values := 'NULL,"' + Infos.Domain +'"' ; InsertARow; Error := Self.Error; end; procedure TDataEngine.InsertHuman(const Infos: TLogsInfo; var Error: integer); var VRec: TVarRec; ADomainKey : String; ColFormat,ResFormat : TVarRec; begin ColFormat.vType := vtPChar; ColFormat.VPChar := PChar(Infos.Domain); // Les clés étrangères doivent toutes être transformées avant toute autre opération. // Transformer le nom de domain en clé étrangère. ResFormat.VType := vtInteger; ADomainKey := ForeignKey(Domain,DomainName,Self.DomainKey,ColFormat,ResFormat); Tables := Human ; Columns := IPAddress + ',' + DomainName +','+DateTime+','{+TimeZone + ','} + FileR +','+Referrer +','+ Country + ','+ Browser + ',' + OS; Values := '"' +Infos.IpAddress +'",'+ ADomainKey+',"'+Infos.DateTime+'","'+Infos.FileRequest +'","'+ Infos.Referrer+ '","'+Infos.Country+'","'+Infos.Browser+'","'+Infos.OS+'"'; //Insertion infos d'une visite. InsertARow; Error := Self.Error; end; procedure TDataEngine.InsertRobot(const Infos: TLogsInfo; var Error: integer); begin InsertARow; Error := Self.Error; end; end.
unit SelArtFec; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, DateUtils, Db, Mask, DBTables, JvExMask, JvExControls, JvDBLookup, JvToolEdit, ADODB; type TFSelArtFec = class(TForm) GroupBox1: TGroupBox; GroupBox2: TGroupBox; BitBtn1: TBitBtn; BitBtn2: TBitBtn; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; DArti: TDataSource; gDep: TGroupBox; DDepos: TDataSource; ArtDesde: TJvDBLookupCombo; ArtHasta: TJvDBLookupCombo; Deposito: TJvDBLookupCombo; FecIni: TJvDateEdit; FecFin: TJvDateEdit; TArti: TADODataSet; TArtiCODIGO: TStringField; TArtiRubro: TStringField; TArtiMarca: TStringField; TArtiDenomina: TStringField; TArtiUnitario: TStringField; TArtiCosto: TFloatField; TArtiVenta: TFloatField; TDepos: TADODataSet; procedure FormCreate(Sender: TObject); procedure ArtDesdeExit(Sender: TObject); procedure ArtHastaExit(Sender: TObject); procedure FecIniExit(Sender: TObject); procedure FecFinExit(Sender: TObject); private procedure SetearSesion; { Private declarations } public { Public declarations } end; var FSelArtFec: TFSelArtFec; implementation uses DataMod; {$R *.DFM} procedure TFSelArtFec.FormCreate(Sender: TObject); begin SetearSesion; TDepos.open; TArti.Open; ArtDesde.value := TArtiCODIGO.value; TArti.last; ArtHasta.value := TArtiCODIGO.value; FecIni.date := StartOfTheMonth( date-30 ); FecFin.date := date; end; procedure TFSelArtFec.ArtDesdeExit(Sender: TObject); begin if ArtDesde.value > ArtHasta.value then ArtHasta.value := ArtDesde.value; end; procedure TFSelArtFec.ArtHastaExit(Sender: TObject); begin if ArtHasta.value < ArtDesde.value then ArtDesde.value := ArtHasta.value; end; procedure TFSelArtFec.FecIniExit(Sender: TObject); begin if FecFin.date < FecIni.date then FecFin.date := FecIni.date; end; procedure TFSelArtFec.FecFinExit(Sender: TObject); begin if FecIni.date > FecFin.date then FecIni.date := FecFin.date; end; procedure TFSelArtFec.SetearSesion; begin end; end.
Unit H2Gauge; Interface Uses Messages,Windows, Classes,Controls, ExtCtrls, SysUtils,GR32_Image,GR32, gr32_layers,Graphics,JvThreadTimer,GR32_transforms; Type TH2Gauge = Class(TControl) Private fx, fy, fwidth, fheight:Integer; fvisible:Boolean; fpos:Integer; fbitmap:tbitmaplayer; fdrawmode:tdrawmode; falpha:Cardinal; fbmp:tbitmap32; fneedle:tbitmap32; fmin:Integer; fmax:Integer; fposition:Integer; Procedure Setvisible(value:Boolean); Procedure SetAlpha(value:Cardinal); Procedure SetDrawmode(value:tdrawmode); Procedure Setx(value:Integer); Procedure Sety(value:Integer); Procedure SetPosition(value:Integer); Procedure rotate(b:tbitmap32;Var dest:tbitmap32;angle:Single); Public Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Published Procedure LoadBackGround(filename:String); Procedure LoadNeedle(filename:String); Property Min:Integer Read fmin Write fmin; Property Max:Integer Read fmax Write fmax; Property Position:Integer Read fposition Write setposition; Property Alpha:Cardinal Read falpha Write setalpha; Property DrawMode:tdrawmode Read fdrawmode Write setdrawmode; Property X:Integer Read fx Write setx; Property Y:Integer Read fy Write sety; Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap; Property Visible:Boolean Read fvisible Write setvisible; End; Implementation Uses Unit1; Constructor TH2Gauge.Create(AOwner: TComponent); Var L: TFloatRect; alayer:tbitmaplayer; Begin Inherited Create(AOwner); fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers); fdrawmode:=dmblend; falpha:=255; fvisible:=True; fmin:=0; fmax:=100; fposition:=0; fx:=0; fpos:=0; fy:=0; fwidth:=150; fheight:=150; fbmp:=tbitmap32.Create; fbitmap.Bitmap.Width:=fwidth; fbitmap.Bitmap.Height:=fheight; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Tag:=0; fbitmap.Bitmap.DrawMode:=fdrawmode; fbitmap.Bitmap.MasterAlpha:=falpha; fvisible:=True; fneedle:=tbitmap32.Create; fneedle.DrawMode:=dmblend; fneedle.MasterAlpha:=255; End; Destructor TH2Gauge.Destroy; Begin //here fbitmap.Free; fbmp.Free; fneedle.free; Inherited Destroy; End; Procedure TH2Gauge.LoadBackGround(filename: String); Var au:Boolean; L: TFloatRect; Begin If fileexists(filename) Then Begin Try LoadPNGintoBitmap32(fbmp,filename,au); fwidth:=fbmp.Width; fheight:=fbmp.Height; fneedle.Width:=fwidth; fneedle.Height:=fheight; fbitmap.Bitmap.width:=fwidth; fbitmap.Bitmap.Height:=fheight; l.Left:=fx; l.Top :=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; Except End; End; End; Procedure TH2Gauge.LoadNeedle(filename: String); Var au:Boolean; Begin If fileexists(filename) Then Begin Try LoadPNGintoBitmap32(fneedle,filename,au); Except End; End; End; Procedure TH2Gauge.rotate(b: tbitmap32; Var dest: tbitmap32; angle: Single); Var T: TAffineTransformation; Begin T := TAffineTransformation.Create; T.Clear; T.SrcRect := FloatRect(0, 0, b.Width + 1, B.height + 1); T.Translate(-b.width / 2, -b.height / 2); T.Rotate(0, 0, angle); T.Translate(b.width / 2, b.height / 2); transform(dest,b,t); t.Free; End; Procedure TH2Gauge.SetAlpha(value: Cardinal); Begin falpha:=value; fbitmap.Bitmap.MasterAlpha:=falpha; fbmp.MasterAlpha:=falpha; fneedle.MasterAlpha:=falpha; End; Procedure TH2Gauge.SetDrawmode(value: tdrawmode); Begin fdrawmode:=value; fbitmap.Bitmap.DrawMode:=fdrawmode; fbmp.DrawMode:=fdrawmode; fneedle.DrawMode:=fdrawmode; End; Procedure TH2Gauge.SetPosition(value: Integer); Var deg:Single; mb: tbitmap32; Begin fposition:=value; deg:=360 / fmax; mb :=tbitmap32.Create; mb.DrawMode:=dmblend; mb.MasterAlpha:=falpha; mb.Width:=fbmp.Width; mb.height:=fbmp.Height; rotate(fneedle,mb,-fposition*deg); fbmp.DrawTo(fbitmap.Bitmap,0,0); mb.DrawTo(fbitmap.Bitmap,0,0); mb.free; End; Procedure TH2Gauge.Setvisible(value: Boolean); Begin fbitmap.Visible:=value; End; Procedure TH2Gauge.Setx(value: Integer); Var L: TFloatRect; Begin fx:=value; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; End; Procedure TH2Gauge.Sety(value: Integer); Var L: TFloatRect; Begin fy:=value; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; End; End.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clDnsFileHandler; interface {$I clVer.inc} {$IFDEF DELPHI6} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF} {$IFDEF DELPHI7} {$WARN UNSAFE_CODE OFF} {$WARN UNSAFE_TYPE OFF} {$WARN UNSAFE_CAST OFF} {$ENDIF} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, SyncObjs, Windows, {$ELSE} System.Classes, System.SysUtils, System.SyncObjs, Winapi.Windows, {$ENDIF} clUdpServer, clDnsServer, clDnsMessage; type TclDnsRecordPersister = class protected function CreateRecord: TclDnsRecord; virtual; abstract; public function LoadRecord(AParameters: TStrings): TclDnsRecord; virtual; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); virtual; end; TclDnsARecordPersister = class(TclDnsRecordPersister) protected function CreateRecord: TclDnsRecord; override; public function LoadRecord(AParameters: TStrings): TclDnsRecord; override; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); override; end; TclDnsAAAARecordPersister = class(TclDnsRecordPersister) protected function CreateRecord: TclDnsRecord; override; public function LoadRecord(AParameters: TStrings): TclDnsRecord; override; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); override; end; TclDnsNSRecordPersister = class(TclDnsRecordPersister) protected function CreateRecord: TclDnsRecord; override; public function LoadRecord(AParameters: TStrings): TclDnsRecord; override; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); override; end; TclDnsCNAMERecordPersister = class(TclDnsRecordPersister) protected function CreateRecord: TclDnsRecord; override; public function LoadRecord(AParameters: TStrings): TclDnsRecord; override; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); override; end; TclDnsSOARecordPersister = class(TclDnsRecordPersister) protected function CreateRecord: TclDnsRecord; override; public function LoadRecord(AParameters: TStrings): TclDnsRecord; override; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); override; end; TclDnsPTRRecordPersister = class(TclDnsRecordPersister) protected function CreateRecord: TclDnsRecord; override; public function LoadRecord(AParameters: TStrings): TclDnsRecord; override; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); override; end; TclDnsMXRecordPersister = class(TclDnsRecordPersister) protected function CreateRecord: TclDnsRecord; override; public function LoadRecord(AParameters: TStrings): TclDnsRecord; override; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); override; end; TclDnsTXTRecordPersister = class(TclDnsRecordPersister) protected function CreateRecord: TclDnsRecord; override; public function LoadRecord(AParameters: TStrings): TclDnsRecord; override; procedure SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); override; end; TclDnsRecordPersisterFactory = class protected function CreatePersister(ARecType: Integer): TclDnsRecordPersister; overload; virtual; function CreatePersister(ARecord: TclDnsRecord): TclDnsRecordPersister; overload; virtual; public function LoadRecord(const ASource: string): TclDnsRecord; function SaveRecord(ARecord: TclDnsRecord): string; end; TclDnsCachePersister = class private procedure LoadRecords(ARecords: TclDnsRecordList; ASource: TStrings; var AIndex: Integer); procedure SaveRecords(ARecords: TclDnsRecordList; ADestination: TStrings); public function Load(ASource: TStrings): TclDnsCacheEntry; virtual; procedure Save(ACache: TclDnsCacheEntry; ADestination: TStrings); virtual; end; TclDnsFileHandler = class; TclDnsZoneManager = class private FZonePath: string; FRecords: TclDnsRecordList; FOwnRecords: TclDnsRecordList; function GetRecords: TclDnsRecordList; public constructor Create; overload; constructor Create(ARecords: TclDnsRecordList); overload; destructor Destroy; override; class function GetZoneFileName(const AZoneName: string): string; class function GetZoneName(const AFileName: string): string; procedure Load(const AZoneName: string); procedure LoadFromFile(const AFileName: string); procedure Save(const AZoneName: string); procedure SaveToFile(const AFileName: string); procedure ListZones(AZoneNames: TStrings); property ZonePath: string read FZonePath write FZonePath; property Records: TclDnsRecordList read GetRecords; end; TclDnsFileHandler = class(TComponent) private FServer: TclDnsServer; FAccessor: TCriticalSection; FHandedZonesPath: string; FCachedZonesPath: string; FZoneManager: TclDnsZoneManager; procedure SetServer(const Value: TclDnsServer); procedure SetHandedZonesPath(const Value: string); procedure SetCachedZonesPath(const Value: string); procedure DoGetHandedRecords(Sender: TObject; AConnection: TclUdpUserConnection; const AName: string; ARecords: TclDnsRecordList); procedure DoGetCachedRecords(Sender: TObject; AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer; var ACacheEntry: TclDnsCacheEntry); procedure DoAddCachedRecords(Sender: TObject; AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer; ACacheEntry: TclDnsCacheEntry); procedure DoDeleteCachedRecords(Sender: TObject; AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer); function EncodeCacheFileName(const AName: string; ARecordType: Integer): string; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure CleanEventHandlers; virtual; procedure InitEventHandlers; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ZoneManager: TclDnsZoneManager read FZoneManager; published property Server: TclDnsServer read FServer write SetServer; property HandedZonesPath: string read FHandedZonesPath write SetHandedZonesPath; property CachedZonesPath: string read FCachedZonesPath write SetCachedZonesPath; end; const cDnzZoneFileExt = '.txt'; implementation uses clUtils; { TclDnsFileHandler } procedure TclDnsFileHandler.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation <> opRemove) then Exit; if (AComponent = FServer) then begin CleanEventHandlers(); FServer := nil; end; end; procedure TclDnsFileHandler.SetCachedZonesPath(const Value: string); begin FAccessor.Enter(); try FCachedZonesPath := Value; finally FAccessor.Leave(); end; end; procedure TclDnsFileHandler.SetHandedZonesPath(const Value: string); begin FAccessor.Enter(); try FHandedZonesPath := Value; finally FAccessor.Leave(); end; end; procedure TclDnsFileHandler.SetServer(const Value: TclDnsServer); begin if (FServer <> Value) then begin if (FServer <> nil) then begin FServer.RemoveFreeNotification(Self); CleanEventHandlers(); end; FServer := Value; if (FServer <> nil) then begin FServer.FreeNotification(Self); InitEventHandlers(); end; end; end; procedure TclDnsFileHandler.CleanEventHandlers; begin Server.OnGetHandedRecords := nil; Server.OnGetCachedRecords := nil; Server.OnAddCachedRecords := nil; Server.OnDeleteCachedRecords := nil; end; constructor TclDnsFileHandler.Create(AOwner: TComponent); begin inherited Create(AOwner); FZoneManager := TclDnsZoneManager.Create(); FAccessor := TCriticalSection.Create(); FHandedZonesPath := 'Handed'; FCachedZonesPath := 'Cached'; end; destructor TclDnsFileHandler.Destroy; begin FAccessor.Free(); FZoneManager.Free(); inherited Destroy(); end; procedure TclDnsFileHandler.DoAddCachedRecords(Sender: TObject; AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer; ACacheEntry: TclDnsCacheEntry); var fileName: string; data: TStrings; persister: TclDnsCachePersister; begin FAccessor.Enter(); try fileName := AddTrailingBackSlash(CachedZonesPath) + EncodeCacheFileName(AName, ARecordType); if not ForceFileDirectories(AddTrailingBackSlash(CachedZonesPath)) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; data := nil; persister := nil; try data := TStringList.Create(); persister := TclDnsCachePersister.Create(); persister.Save(ACacheEntry, data); TclStringsUtils.SaveStrings(data, fileName, ''); finally persister.Free(); data.Free(); end; finally FAccessor.Leave(); end; end; procedure TclDnsFileHandler.DoDeleteCachedRecords(Sender: TObject; AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer); var fileName: string; begin FAccessor.Enter(); try fileName := AddTrailingBackSlash(CachedZonesPath) + EncodeCacheFileName(AName, ARecordType); if (FileExists(fileName)) then begin DeleteFile(PChar(fileName)); end; finally FAccessor.Leave(); end; end; procedure TclDnsFileHandler.DoGetCachedRecords(Sender: TObject; AConnection: TclUdpUserConnection; const AName: string; ARecordType: Integer; var ACacheEntry: TclDnsCacheEntry); var fileName: string; data: TStrings; persister: TclDnsCachePersister; begin FAccessor.Enter(); try fileName := AddTrailingBackSlash(CachedZonesPath) + EncodeCacheFileName(AName, ARecordType); if (FileExists(fileName)) then begin data := nil; persister := nil; try data := TStringList.Create(); TclStringsUtils.LoadStrings(fileName, data, ''); persister := TclDnsCachePersister.Create(); ACacheEntry := persister.Load(data); finally persister.Free(); data.Free(); end; if (ACacheEntry <> nil) then begin ACacheEntry.CreatedOn := GetLocalFileTime(fileName); end; end; finally FAccessor.Leave(); end; end; procedure TclDnsFileHandler.DoGetHandedRecords(Sender: TObject; AConnection: TclUdpUserConnection; const AName: string; ARecords: TclDnsRecordList); var zoneManager: TclDnsZoneManager; begin zoneManager := TclDnsZoneManager.Create(ARecords); try zoneManager.ZonePath := HandedZonesPath; FAccessor.Enter(); try zoneManager.Load(AName); finally FAccessor.Leave(); end; finally zoneManager.Free(); end; end; function TclDnsFileHandler.EncodeCacheFileName(const AName: string; ARecordType: Integer): string; begin Result := GetRecordTypeStr(ARecordType) + '_' + TclDnsZoneManager.GetZoneFileName(AName); end; procedure TclDnsFileHandler.InitEventHandlers; begin Server.OnGetHandedRecords := DoGetHandedRecords; Server.OnGetCachedRecords := DoGetCachedRecords; Server.OnAddCachedRecords := DoAddCachedRecords; Server.OnDeleteCachedRecords := DoDeleteCachedRecords; end; { TclDnsRecordPersister } function TclDnsRecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; begin Result := CreateRecord(); try Result.Name := AParameters[0]; Result.TTL := DWORD(StrToInt64Def(AParameters[2], 0)); except Result.Free(); raise; end; end; procedure TclDnsRecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); begin ADestination.Add(ARecord.Name); ADestination.Add(GetRecordTypeStr(ARecord.RecordType)); ADestination.Add(IntToStr(ARecord.TTL)); end; { TclDnsARecordPersister } function TclDnsARecordPersister.CreateRecord: TclDnsRecord; begin Result := TclDnsARecord.Create(); end; function TclDnsARecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; begin if (AParameters.Count < 4) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := inherited LoadRecord(AParameters); TclDnsARecord(Result).IPAddress := AParameters[3]; end; procedure TclDnsARecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); begin inherited SaveRecord(ARecord, ADestination); ADestination.Add(TclDnsARecord(ARecord).IPAddress); end; { TclDnsNSRecordPersister } function TclDnsNSRecordPersister.CreateRecord: TclDnsRecord; begin Result := TclDnsNSRecord.Create(); end; function TclDnsNSRecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; begin if (AParameters.Count < 4) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := inherited LoadRecord(AParameters); TclDnsNSRecord(Result).NameServer := AParameters[3]; end; procedure TclDnsNSRecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); begin inherited SaveRecord(ARecord, ADestination); ADestination.Add(TclDnsNSRecord(ARecord).NameServer); end; { TclDnsCNAMERecordPersister } function TclDnsCNAMERecordPersister.CreateRecord: TclDnsRecord; begin Result := TclDnsCNAMERecord.Create(); end; function TclDnsCNAMERecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; begin if (AParameters.Count < 4) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := inherited LoadRecord(AParameters); TclDnsCNAMERecord(Result).PrimaryName := AParameters[3]; end; procedure TclDnsCNAMERecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); begin inherited SaveRecord(ARecord, ADestination); ADestination.Add(TclDnsCNAMERecord(ARecord).PrimaryName); end; { TclDnsSOARecordPersister } function TclDnsSOARecordPersister.CreateRecord: TclDnsRecord; begin Result := TclDnsSOARecord.Create(); end; function TclDnsSOARecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; var res: TclDnsSOARecord; begin if (AParameters.Count < 10) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := inherited LoadRecord(AParameters); res := TclDnsSOARecord(Result); res.PrimaryNameServer := AParameters[3]; res.ResponsibleMailbox := AParameters[4]; res.SerialNumber := StrToInt64Def(AParameters[5], 0); res.RefreshInterval := StrToInt64Def(AParameters[6], 0); res.RetryInterval := StrToInt64Def(AParameters[7], 0); res.ExpirationLimit := StrToInt64Def(AParameters[8], 0); res.MinimumTTL := StrToInt64Def(AParameters[9], 0); end; procedure TclDnsSOARecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); var soaRec: TclDnsSOARecord; begin inherited SaveRecord(ARecord, ADestination); soaRec := TclDnsSOARecord(ARecord); ADestination.Add(soaRec.PrimaryNameServer); ADestination.Add(soaRec.ResponsibleMailbox); ADestination.Add(IntToStr(soaRec.SerialNumber)); ADestination.Add(IntToStr(soaRec.RefreshInterval)); ADestination.Add(IntToStr(soaRec.RetryInterval)); ADestination.Add(IntToStr(soaRec.ExpirationLimit)); ADestination.Add(IntToStr(soaRec.MinimumTTL)); end; { TclDnsPTRRecordPersister } function TclDnsPTRRecordPersister.CreateRecord: TclDnsRecord; begin Result := TclDnsPTRRecord.Create(); end; function TclDnsPTRRecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; begin if (AParameters.Count < 4) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := inherited LoadRecord(AParameters); TclDnsPTRRecord(Result).DomainName := AParameters[3]; end; procedure TclDnsPTRRecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); begin inherited SaveRecord(ARecord, ADestination); ADestination.Add(TclDnsPTRRecord(ARecord).DomainName); end; { TclDnsMXRecordPersister } function TclDnsMXRecordPersister.CreateRecord: TclDnsRecord; begin Result := TclDnsMXRecord.Create(); end; function TclDnsMXRecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; var res: TclDnsMXRecord; begin if (AParameters.Count < 5) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := inherited LoadRecord(AParameters); res := TclDnsMXRecord(Result); res.Preference := StrToIntDef(AParameters[3], 1); res.MailServer := AParameters[4]; end; procedure TclDnsMXRecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); var mxRec: TclDnsMXRecord; begin inherited SaveRecord(ARecord, ADestination); mxRec := TclDnsMXRecord(ARecord); ADestination.Add(IntToStr(mxRec.Preference)); ADestination.Add(mxRec.MailServer); end; { TclDnsTXTRecordPersister } function TclDnsTXTRecordPersister.CreateRecord: TclDnsRecord; begin Result := TclDnsTXTRecord.Create(); end; function TclDnsTXTRecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; begin if (AParameters.Count < 4) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := inherited LoadRecord(AParameters); TclDnsTXTRecord(Result).Text := AParameters[3]; end; procedure TclDnsTXTRecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); begin inherited SaveRecord(ARecord, ADestination); ADestination.Add(TclDnsTXTRecord(ARecord).Text); end; { TclDnsRecordPersisterFactory } function TclDnsRecordPersisterFactory.CreatePersister(ARecType: Integer): TclDnsRecordPersister; begin if (DnsRecordTypes[rtARecord] = ARecType) then begin Result := TclDnsARecordPersister.Create(); end else if (DnsRecordTypes[rtNSRecord] = ARecType) then begin Result := TclDnsNSRecordPersister.Create(); end else if (DnsRecordTypes[rtCNAMERecord] = ARecType) then begin Result := TclDnsCNAMERecordPersister.Create(); end else if (DnsRecordTypes[rtSOARecord] = ARecType) then begin Result := TclDnsSOARecordPersister.Create(); end else if (DnsRecordTypes[rtPTRRecord] = ARecType) then begin Result := TclDnsPTRRecordPersister.Create(); end else if (DnsRecordTypes[rtMXRecord] = ARecType) then begin Result := TclDnsMXRecordPersister.Create(); end else if (DnsRecordTypes[rtTXTRecord] = ARecType) then begin Result := TclDnsTXTRecordPersister.Create(); end else if (DnsRecordTypes[rtAAAARecord] = ARecType) then begin Result := TclDnsAAAARecordPersister.Create(); end else begin raise EclDnsServerError.Create(DnsServerFailureCode); end; end; function TclDnsRecordPersisterFactory.CreatePersister(ARecord: TclDnsRecord): TclDnsRecordPersister; begin if (ARecord is TclDnsARecord) then begin Result := TclDnsARecordPersister.Create(); end else if (ARecord is TclDnsNSRecord) then begin Result := TclDnsNSRecordPersister.Create(); end else if (ARecord is TclDnsCNAMERecord) then begin Result := TclDnsCNAMERecordPersister.Create(); end else if (ARecord is TclDnsSOARecord) then begin Result := TclDnsSOARecordPersister.Create(); end else if (ARecord is TclDnsPTRRecord) then begin Result := TclDnsPTRRecordPersister.Create(); end else if (ARecord is TclDnsMXRecord) then begin Result := TclDnsMXRecordPersister.Create(); end else if (ARecord is TclDnsTXTRecord) then begin Result := TclDnsTXTRecordPersister.Create(); end else if (ARecord is TclDnsAAAARecord) then begin Result := TclDnsAAAARecordPersister.Create(); end else begin raise EclDnsServerError.Create(DnsServerFailureCode); end; end; function TclDnsRecordPersisterFactory.LoadRecord(const ASource: string): TclDnsRecord; var parameters: TStrings; persister: TclDnsRecordPersister; begin Result := nil;//TODO in newer versions of Delphi causes compilation hint, add conditional define. parameters := nil; persister := nil; try parameters := TStringList.Create(); ExtractQuotedWords(ASource, parameters); if (parameters.Count < 3) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; persister := CreatePersister(GetRecordTypeInt(UpperCase(parameters[1]))); Result := persister.LoadRecord(parameters); finally persister.Free(); parameters.Free(); end; end; function TclDnsRecordPersisterFactory.SaveRecord(ARecord: TclDnsRecord): string; var list: TStrings; persister: TclDnsRecordPersister; begin persister := nil; list := nil; try persister := CreatePersister(ARecord); list := TStringList.Create(); persister.SaveRecord(ARecord, list); Result := GetQuotedWordsString(list); finally list.Free(); persister.Free(); end; end; { TclDnsCachePersister } function TclDnsCachePersister.Load(ASource: TStrings): TclDnsCacheEntry; var index: Integer; begin if (ASource.Count < 2) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := TclDnsCacheEntry.Create(); try index := 0; Result.RecordType := GetRecordTypeInt(ASource[index]); Inc(index); Result.Name := ASource[index]; Inc(index); LoadRecords(Result.Answers, ASource, index); LoadRecords(Result.NameServers, ASource, index); LoadRecords(Result.AdditionalRecords, ASource, index); except Result.Free(); raise; end; end; procedure TclDnsCachePersister.LoadRecords(ARecords: TclDnsRecordList; ASource: TStrings; var AIndex: Integer); var count: Integer; factory: TclDnsRecordPersisterFactory; rec: TclDnsRecord; begin if (AIndex >= ASource.Count) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; count := StrToIntDef(ASource[AIndex], 0); Inc(AIndex); if ((AIndex + count) > ASource.Count) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; factory := TclDnsRecordPersisterFactory.Create(); try while (count > 0) do begin rec := factory.LoadRecord(ASource[AIndex]); ARecords.Add(rec); Inc(AIndex); Dec(count); end; finally factory.Free(); end; end; procedure TclDnsCachePersister.Save(ACache: TclDnsCacheEntry; ADestination: TStrings); begin ADestination.Clear(); ADestination.Add(GetRecordTypeStr(ACache.RecordType)); ADestination.Add(ACache.Name); SaveRecords(ACache.Answers, ADestination); SaveRecords(ACache.NameServers, ADestination); SaveRecords(ACache.AdditionalRecords, ADestination); end; procedure TclDnsCachePersister.SaveRecords(ARecords: TclDnsRecordList; ADestination: TStrings); var factory: TclDnsRecordPersisterFactory; i: Integer; s: string; begin ADestination.Add(IntToStr(ARecords.Count)); factory := TclDnsRecordPersisterFactory.Create(); try for i := 0 to ARecords.Count - 1 do begin s := factory.SaveRecord(ARecords[i]); ADestination.Add(s); end; finally factory.Free(); end; end; { TclDnsZoneManager } constructor TclDnsZoneManager.Create; begin inherited Create(); FRecords := nil; FOwnRecords := nil; end; constructor TclDnsZoneManager.Create(ARecords: TclDnsRecordList); begin inherited Create(); FRecords := ARecords; FOwnRecords := nil; end; destructor TclDnsZoneManager.Destroy; begin FOwnRecords.Free(); inherited Destroy(); end; function TclDnsZoneManager.GetRecords: TclDnsRecordList; begin Result := FRecords; if (Result = nil) then begin Result := FOwnRecords; if (Result = nil) then begin FOwnRecords := TclDnsRecordList.Create(); end; Result := FOwnRecords; end; end; class function TclDnsZoneManager.GetZoneFileName(const AZoneName: string): string; var i: Integer; c: Char; begin if (AZoneName = '') then begin raise EclDnsServerError.Create(DnsNameErrorCode); end; Result := ''; for i := 1 to Length(AZoneName) do begin c := AZoneName[i]; case (c) of '.': Result := Result + '_'; '_': Result := Result + '__' else Result := Result + c; end; end; Result := Result + cDnzZoneFileExt; end; class function TclDnsZoneManager.GetZoneName(const AFileName: string): string; var i, cnt: Integer; c: Char; begin if (AFileName = '') then begin raise EclDnsServerError.Create(DnsNameErrorCode); end; Result := ''; cnt := 0; for i := 1 to Length(AFileName) do begin c := AFileName[i]; if (c = '.') then begin Break; end; if (c = '_') then begin Inc(cnt); if (cnt = 2) then begin cnt := 0; Result := Result + '_'; end; end else if (cnt = 1) then begin cnt := 0; Result := Result + '.' + c; end else begin cnt := 0; Result := Result + c; end; end; end; procedure TclDnsZoneManager.ListZones(AZoneNames: TStrings); var searchRec: TSearchRec; begin AZoneNames.Clear(); if {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindFirst(AddTrailingBackSlash(ZonePath) + '*' + cDnzZoneFileExt, 0, searchRec) = 0 then begin repeat AZoneNames.Add(GetZoneName(searchRec.Name)); until ({$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindNext(searchRec) <> 0); {$IFDEF DELPHIXE2}System.{$ENDIF}SysUtils.FindClose(searchRec); end; end; procedure TclDnsZoneManager.Load(const AZoneName: string); var fileName: string; begin fileName := AddTrailingBackSlash(ZonePath) + GetZoneFileName(AZoneName); if FileExists(fileName) then begin LoadFromFile(fileName); end; end; procedure TclDnsZoneManager.LoadFromFile(const AFileName: string); var data: TStrings; factory: TclDnsRecordPersisterFactory; rec: TclDnsRecord; i: Integer; begin Records.Clear(); data := nil; factory := nil; try data := TStringList.Create(); factory := TclDnsRecordPersisterFactory.Create(); TclStringsUtils.LoadStrings(AFileName, data, ''); for i := 0 to data.Count - 1 do begin rec := factory.LoadRecord(data[i]); Records.Add(rec); end; finally factory.Free(); data.Free(); end; end; procedure TclDnsZoneManager.Save(const AZoneName: string); var fileName: string; begin if (Records.Count = 0) then Exit; ForceFileDirectories(AddTrailingBackSlash(ZonePath)); fileName := AddTrailingBackSlash(ZonePath) + GetZoneFileName(AZoneName); SaveToFile(fileName); end; procedure TclDnsZoneManager.SaveToFile(const AFileName: string); var data: TStrings; factory: TclDnsRecordPersisterFactory; i: Integer; begin if (Records.Count = 0) then Exit; data := nil; factory := nil; try data := TStringList.Create(); factory := TclDnsRecordPersisterFactory.Create(); for i := 0 to Records.Count - 1 do begin data.Add(factory.SaveRecord(Records[i])); end; TclStringsUtils.SaveStrings(data, AFileName, ''); finally factory.Free(); data.Free(); end; end; { TclDnsAAAARecordPersister } function TclDnsAAAARecordPersister.CreateRecord: TclDnsRecord; begin Result := TclDnsAAAARecord.Create(); end; function TclDnsAAAARecordPersister.LoadRecord(AParameters: TStrings): TclDnsRecord; begin if (AParameters.Count < 4) then begin raise EclDnsServerError.Create(DnsServerFailureCode); end; Result := inherited LoadRecord(AParameters); TclDnsAAAARecord(Result).IPv6Address := AParameters[3]; end; procedure TclDnsAAAARecordPersister.SaveRecord(ARecord: TclDnsRecord; ADestination: TStrings); begin inherited SaveRecord(ARecord, ADestination); ADestination.Add(TclDnsAAAARecord(ARecord).IPv6Address); end; end.
unit DataChain; interface uses Windows; type PChainNode = ^TChainNode; PChainNodes = ^TChainNodes; PChain = ^TChain; PLockChain = ^TLockChain; TChainNode = packed record PrevSibling : PChainNode; NextSibling : PChainNode; NodePointer : Pointer; end; TChainNodes = packed record PrevSibling : PChainNodes; NextSibling : PChainNodes; Nodes : array[0..255] of TChainNode; end; TChain = record NodeCount : integer; FirstNode : PChainNode; LastNode : PChainNode; FirstNodes : PChainNodes; LastNodes : PChainNodes; end; TLockChain = record InitStatus : Integer; Lock : TRTLCriticalSection; Chain : TChain; end; PChainPool = ^TChainPool; TChainPool = packed record InitStatus : Integer; Lock : TRTLCriticalSection; UsedChain : TChain; UnUsedChain : TChain; end; procedure InitializeChainNodes(AChainNodes: PChainNodes); procedure AddChainNode(AChain: PChain; AChainNode: PChainNode); procedure DeleteChainNode(AChain: PChain; AChainNode: PChainNode); function CheckOutLockChain: PLockChain; procedure CheckInLockChain(var ALockChain: PLockChain); procedure InitializeLockChain(ALockChain: PLockChain); procedure AddLockChainNode(ALockChain: PLockChain; AChainNode: PChainNode); procedure DeleteLockChainNode(ALockChain: PLockChain; AChainNode: PChainNode); function CheckOutChainPool: PChainPool; procedure CheckInChainPool(var AChainPool: PChainPool); procedure InitializeChainPool(AChainPool: PChainPool); function CheckOutPoolChainNode(AChainPool: PChainPool): PChainNode; procedure CheckInPoolChainNode(AChainPool: PChainPool; AChainNode: PChainNode); implementation procedure InternalAddChainNode(AChain: PChain; AChainNode: PChainNode); begin if nil = AChain then exit; if nil = AChainNode then exit; AChain.NodeCount := AChain.NodeCount + 1; if nil = AChain.FirstNode then AChain.FirstNode := AChainNode; if nil <> AChain.LastNode then begin AChainNode.PrevSibling := AChain.LastNode; AChain.LastNode.NextSibling := AChainNode; end; AChain.LastNode := AChainNode; end; procedure InternalDeleteChainNode(AChain: PChain; AChainNode: PChainNode); begin if nil = AChain then exit; if nil = AChainNode then exit; AChain.NodeCount := AChain.NodeCount - 1; if nil = AChainNode.PrevSibling then begin AChain.FirstNode := AChainNode.NextSibling; end else begin AChainNode.PrevSibling.NextSibling := AChainNode.NextSibling; end; if nil = AChainNode.NextSibling then begin AChain.LastNode := AChainNode.PrevSibling; end else begin AChainNode.NextSibling.PrevSibling := AChainNode.PrevSibling; end; AChainNode.PrevSibling := nil; AChainNode.NextSibling := nil; end; function CheckOutPoolChainNode(AChainPool: PChainPool): PChainNode; begin EnterCriticalSection(AChainPool.Lock); try Result := AChainPool.UnUsedChain.FirstNode; if nil <> Result then begin InternalDeleteChainNode(@AChainPool.UnUsedChain, Result); end; if nil = Result then begin Result := System.New(PChainNode); FillChar(Result^, SizeOf(TChainNode), 0); end; AddChainNode(@AChainPool.UsedChain, Result); finally LeaveCriticalSection(AChainPool.Lock); end; end; procedure CheckInPoolChainNode(AChainPool: PChainPool; AChainNode: PChainNode); begin if nil = AChainNode then exit; if nil = AChainPool then exit; EnterCriticalSection(AChainPool.Lock); try InternalDeleteChainNode(@AChainPool.UsedChain, AChainNode); InternalAddChainNode(@AChainPool.UnUsedChain, AChainNode); finally LeaveCriticalSection(AChainPool.Lock); end; end; procedure AddChainNode(AChain: PChain; AChainNode: PChainNode); begin InternalAddChainNode(AChain, AChainNode); end; procedure DeleteChainNode(AChain: PChain; AChainNode: PChainNode); begin InternalDeleteChainNode(AChain, AChainNode); end; procedure AddLockChainNode(ALockChain: PLockChain; AChainNode: PChainNode); begin EnterCriticalSection(ALockChain.Lock); try InternalAddChainNode(@ALockChain.Chain, AChainNode); finally LeaveCriticalSection(ALockChain.Lock); end; end; procedure DeleteLockChainNode(ALockChain: PLockChain; AChainNode: PChainNode); begin EnterCriticalSection(ALockChain.Lock); try InternalDeleteChainNode(@ALockChain.Chain, AChainNode); finally LeaveCriticalSection(ALockChain.Lock); end; end; procedure AddChainNodes(AChain: PChain; AChainNodes: PChainNodes); begin if nil = AChainNodes then exit; if nil = AChain.FirstNodes then AChain.FirstNodes := AChainNodes; if nil <> AChain.LastNodes then begin AChainNodes.PrevSibling := AChain.LastNodes; AChain.LastNodes.NextSibling := AChainNodes; end; AChain.LastNodes := AChainNodes; end; procedure DeleteChainNodes(AChain: PChain; AChainNodes: PChainNodes); begin if nil = AChainNodes.PrevSibling then begin AChain.FirstNodes := AChainNodes.NextSibling; end else begin AChainNodes.PrevSibling.NextSibling := AChainNodes.NextSibling; end; if nil = AChainNodes.NextSibling then begin AChain.LastNodes := AChainNodes.PrevSibling; end else begin AChainNodes.NextSibling.PrevSibling := AChainNodes.PrevSibling; end; AChainNodes.PrevSibling := nil; AChainNodes.NextSibling := nil; end; procedure InitializeChainNodes(AChainNodes: PChainNodes); var i: integer; begin for i := Low(AChainNodes.Nodes) to High(AChainNodes.Nodes) do begin if i < High(AChainNodes.Nodes) then begin AChainNodes.Nodes[i].NextSibling := @AChainNodes.Nodes[i + 1]; AChainNodes.Nodes[i + 1].PrevSibling := @AChainNodes.Nodes[i]; end; end; end; function CheckOutChainPool: PChainPool; begin Result := System.New(PChainPool); FillChar(Result^, SizeOf(TChainPool), 0); InitializeChainPool(Result); end; procedure InitializeChainPool(AChainPool: PChainPool); begin if 0 = AChainPool.InitStatus then begin Windows.InitializeCriticalSection(AChainPool.Lock); AChainPool.InitStatus := 1; end; end; procedure CheckInChainPool(var AChainPool: PChainPool); begin if nil = AChainPool then exit; Windows.DeleteCriticalSection(AChainPool.Lock); AChainPool.InitStatus := 0; end; function CheckOutLockChain: PLockChain; begin Result := System.New(PLockChain); FillChar(Result^, SizeOf(TLockChain), 0); InitializeLockChain(Result); end; procedure CheckInLockChain(var ALockChain: PLockChain); begin if nil = ALockChain then exit; Windows.DeleteCriticalSection(ALockChain.Lock); ALockChain.InitStatus := 0; end; procedure InitializeLockChain(ALockChain: PLockChain); begin if 0 = ALockChain.InitStatus then begin Windows.InitializeCriticalSection(ALockChain.Lock); ALockChain.InitStatus := 1; end; end; end.
{******************************************************************************* 作者: dmzn@163.com 2011-11-21 描述: 产品进货 *******************************************************************************} unit UFrameReportProductJH; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, Menus, StdCtrls, cxButtons, cxLabel, cxRadioGroup, Grids, UGridPainter, UGridExPainter, ExtCtrls, cxDropDownEdit, cxCalendar, cxMaskEdit, UImageButton; type TfFrameReportProductJH = class(TfFrameBase) PanelR: TPanel; PanelL: TPanel; LabelHint: TLabel; GridDetail: TDrawGridEx; GridProduct: TDrawGridEx; Splitter1: TSplitter; Panel2: TPanel; Label1: TLabel; EditTime: TcxComboBox; EditS: TcxDateEdit; EditE: TcxDateEdit; Panel1: TPanel; Label2: TLabel; BtnSearch: TImageButton; procedure BtnExitClick(Sender: TObject); procedure EditTimePropertiesEditValueChanged(Sender: TObject); procedure BtnSearchClick(Sender: TObject); private { Private declarations } FPainter: TGridPainter; FPainterEx: TGridExPainter; //绘图对象 FData: TList; //数据列表 procedure ClearData(const nFree: Boolean); //清理数据 procedure LoadProductData; procedure LoadProductList; //产品列表 function CountNumber(const nID: string): Integer; //统计数量 procedure OnBtnClick(Sender: TObject); //点击按钮 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; class function FrameID: integer; override; end; implementation {$R *.dfm} uses IniFiles, ULibFun, UDataModule, DB, UMgrControl, USysConst, USysDB, USysFun; type PDataItem = ^TDataItem; TDataItem = record FStyle: string; FName: string; FColor: string; FSize: string; FNumber: Integer; end; class function TfFrameReportProductJH.FrameID: integer; begin Result := cFI_FrameReportJH; end; procedure TfFrameReportProductJH.OnCreateFrame; var nIni: TIniFile; begin Name := MakeFrameName(FrameID); FData := TList.Create; FPainter := TGridPainter.Create(GridProduct); FPainterEx := TGridExPainter.Create(GridDetail); with FPainter do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('款式名称', 50); AddHeader('总进货', 50); AddHeader('详细查询', 50); end; with FPainterEx do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('颜色', 50, True); AddHeader('尺码', 50); AddHeader('共进货', 50); end; nIni := TIniFile.Create(gPath + sFormConfig); try LoadDrawGridConfig(Name, GridProduct, nIni); LoadDrawGridConfig(Name, GridDetail, nIni); PanelL.Width := nIni.ReadInteger(Name, 'PanelL', 120); Width := PanelL.Width + GetGridHeaderWidth(GridDetail); EditTime.ItemIndex := 0; BtnSearch.Top := EditTime.Top + Trunc((EditTime.Height - BtnSearch.Height) / 2); finally nIni.Free; end; end; procedure TfFrameReportProductJH.OnDestroyFrame; var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try SaveDrawGridConfig(Name, GridProduct, nIni); SaveDrawGridConfig(Name, GridDetail, nIni); nIni.WriteInteger(Name, 'PanelL', PanelL.Width); finally nIni.Free; end; FPainter.Free; FPainterEx.Free; ClearData(True); end; procedure TfFrameReportProductJH.BtnExitClick(Sender: TObject); begin Close; end; //Desc: 清理数据 procedure TfFrameReportProductJH.ClearData(const nFree: Boolean); var nIdx: Integer; begin for nIdx:=FData.Count - 1 downto 0 do begin Dispose(PDataItem(FData[nIdx])); FData.Delete(nIdx); end; if nFree then FData.Free; end; //Desc: 时间变动 procedure TfFrameReportProductJH.EditTimePropertiesEditValueChanged(Sender: TObject); var nS,nE: TDate; begin GetDateInterval(EditTime.ItemIndex, nS, nE); EditS.Date := nS; EditE.Date := nE; end; procedure TfFrameReportProductJH.BtnSearchClick(Sender: TObject); begin BtnSearch.Enabled := False; try LoadProductData; finally BtnSearch.Enabled := True; end; end; //------------------------------------------------------------------------------ //Desc: 载入产品列表 procedure TfFrameReportProductJH.LoadProductData; var nStr,nHint: string; nDS: TDataSet; nItem: PDataItem; begin nStr := 'Select Sum(D_Number) As D_InNum,pt.StyleID,StyleName,ColorName,' + 'SizeName From $DL dl ' + ' Left Join $OD od On od.O_ID=dl.D_Order ' + ' Left Join $PT pt On pt.ProductID=dl.D_Product ' + ' Left Join $ST st On st.StyleID=pt.StyleID ' + ' Left Join $CR cr On cr.ColorID=pt.ColorID ' + ' Left Join $SZ sz On sz.SizeID=pt.SizeID ' + 'Where O_TerminalId = ''$ID'' And (D_Date>=''$KS'' And D_Date<''$JS'') ' + 'Group By pt.StyleID,StyleName,ColorName,SizeName ' + 'Order By StyleName,ColorName,SizeName'; nStr := MacroValue(nStr, [MI('$DL', sTable_OrderDeal), MI('$PT', sTable_DL_Product), MI('$ST', sTable_DL_Style), MI('$CR', sTable_DL_Color), MI('$SZ', sTable_DL_Size), MI('$OD', sTable_Order), MI('$ID', gSysParam.FTerminalID), MI('$KS', Date2Str(EditS.Date)), MI('$JS', Date2Str(EditE.Date + 1))]); //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; ClearData(False); FPainter.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin First; while not Eof do begin New(nItem); FData.Add(nItem); with nItem^ do begin FStyle := FieldByName('StyleID').AsString; FName := FieldByName('StyleName').AsString; FColor := FieldByName('ColorName').AsString; FSize := FieldByName('SizeName').AsString; FNumber := FieldByName('D_InNum').AsInteger; end; Next; end; end; finally FDM.ReleaseDataSet(nDS); end; LoadProductList; end; //Desc: 载入产品列表到界面 procedure TfFrameReportProductJH.LoadProductList; var i,nIdx,nInt: Integer; nList: TStrings; nBtn: TImageButton; nData: TGridDataArray; begin nList := TStringList.Create; try nInt := 1; for nIdx:=0 to FData.Count - 1 do with PDataItem(FData[nIdx])^ do if nList.IndexOf(FStyle) < 0 then begin nList.Add(FStyle); SetLength(nData, 5); for i:=Low(nData) to High(nData) do begin nData[i].FText := ''; nData[i].FCtrls := nil; nData[i].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[1].FText := FName; nData[2].FText := IntToStr(CountNumber(FStyle)); with nData[3] do begin FCtrls := TList.Create; nBtn := TImageButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Parent := Self; ButtonID := 'btn_view_detail'; LoadButton(nBtn); OnClick := OnBtnClick; Tag := FPainter.DataCount; end; end; nData[4].FText := FStyle; FPainter.AddData(nData); end; finally nList.Free; end; end; //Desc: 统计指定款式的库存总量 function TfFrameReportProductJH.CountNumber(const nID: string): Integer; var nIdx: Integer; begin Result := 0; for nIdx:=FData.Count - 1 downto 0 do with PDataItem(FData[nIdx])^ do if FStyle = nID then Result := Result + FNumber; //xxxxx end; //Desc: 查看详情 procedure TfFrameReportProductJH.OnBtnClick(Sender: TObject); var nStr,nID: string; nIdx,nNum,nInt: Integer; nRow: TGridExDataArray; nCol: TGridExColDataArray; begin nNum := TComponent(Sender).Tag; nID := FPainter.Data[nNum][4].FText; LabelHint.Caption := FPainter.Data[nNum][1].FText + '进货详情'; nInt := AdjustLabelCaption(LabelHint, GridDetail); if nInt > LabelHint.Width then Width := PanelL.Width + nInt + 32; //标题超长自适应 nNum := 0; nStr := ''; FPainterEx.ClearData; for nIdx:=0 to FData.Count - 1 do with PDataItem(FData[nIdx])^ do if FStyle = nID then begin SetLength(nRow, 3); for nInt:=Low(nRow) to High(nRow) do begin nRow[nInt].FCtrls := nil; nRow[nInt].FAlign := taCenter; end; nRow[0].FText := FSize; nRow[1].FText := IntToStr(FNumber); FPainterEx.AddRowData(nRow); //添加行数据 if nStr = '' then nStr := FColor; //xxxxx if nStr = FColor then begin Inc(nNum); Continue; end; SetLength(nCol, 1); with nCol[0] do begin FCol := 0; FRows := nNum; FAlign := taCenter; FText := nStr; nNum := 1; nStr := FColor; end; FPainterEx.AddColData(nCol); end; //color if nNum > 0 then begin SetLength(nCol, 1); with nCol[0] do begin FCol := 0; FRows := nNum; FAlign := taCenter; FText := nStr; end; FPainterEx.AddColData(nCol); end; end; initialization gControlManager.RegCtrl(TfFrameReportProductJH, TfFrameReportProductJH.FrameID); end.
program tp1ej5y6; type celular = record codigo:integer; nombre:string; descripcion:string; marca:string; precio:real; stock_min:integer; stock_actual:integeR; end; archivoCelulares = file of celular; procedure imprimirCelular(cel:celular); begin with cel do begin Writeln('nombre:', nombre); Writeln('codigo:', codigo); Writeln('descripcion:', descripcion); Writeln('marca:', marca); Writeln('precio:', precio:4:2); Writeln('stock_min:', stock_min); Writeln('stock_actual:', stock_actual); writeln('--------'); end; end; procedure leerCelular(var cel:celular); begin with cel do begin Writeln('codigo:');ReadLn(codigo); if codigo <> -1 then begin Writeln('nombre:');readln(nombre); Writeln('descripcion:');readln(descripcion); Writeln('marca:');readln(marca); Writeln('precio:'); ReadLn(precio); Writeln('stock_min:');readln(stock_min); Writeln('stock_actual:');ReadLn(stock_actual); writeln('--------'); end; end; end; procedure crearBinarioDesdeTxt(var bin:archivoCelulares; var txt:Text); var cel:celular; begin reset(txt); Rewrite(bin); while not eof(txt) do begin with cel do begin readln(txt, codigo, precio, marca); readln(txt, stock_actual, stock_min, descripcion); readln(txt, nombre); end; write(bin, cel); end; close(txt); close(bin); end; procedure agregarCelular(var archivo:archivoCelulares); var cel:celular; begin reset(archivo); leerCelular(cel); while(cel.codigo <> -1) do begin seek(archivo, FileSize(archivo)); write(archivo, cel); leerCelular(cel); end; close(archivo); end; procedure imprimirCelulares(var archivo:archivoCelulares); var cel:celular; begin reset(archivo); while(not eof(archivo)) do begin read(archivo, cel); imprimirCelular(cel); end; close(archivo); end; procedure listarStockMenorAlMinimo(var archivo: archivoCelulares); var cel:celular; begin reset(archivo); while(not eof(archivo)) do begin read(archivo,cel); with cel do begin if (stock_actual < stock_min) then imprimirCelular(cel); end; end; close(archivo); end; procedure listarPorDescripcion(var archivo:archivoCelulares); var cadena:string; cel:celular; begin reset(archivo); Write('Ingrese la cadena que espera que tenga la descripcion: ');Readln(cadena); while(not eof(archivo)) do begin read(archivo,cel); if(cel.descripcion = cadena) then imprimirCelular(cel); end; close(archivo); end; procedure exportarATexto(var archivo:archivoCelulares; var txt: Text); var cel:celular; begin reset(archivo); rewrite(txt); while(not eof(archivo)) do begin read(archivo, cel); with cel do begin writeln(txt, codigo, ' ', precio:4:2, ' ', marca); writeln(txt, stock_actual, ' ', stock_min, ' ', descripcion); writeln(txt, nombre); end; end; close(archivo); close(txt); end; procedure modificarStock(var archivo:archivoCelulares); var cel:celular; nombre:string; encontro:boolean; begin reset(archivo); encontro := false; Write('Ingrese el nombre del celular que desea modificar: ');ReadLn(nombre); while (not eof(archivo) and not encontro) do begin read(archivo, cel); if(cel.nombre = nombre) then encontro := true; end; if encontro then begin write('Ingrese el nuevo stock: '); ReadLn(cel.stock_actual); seek(archivo, FilePos(archivo) - 1); write(archivo, cel); end else Writeln('No se encontro ningun celular con ese nombre'); close(archivo); end; procedure exportarSinStock(var archivo:archivoCelulares; var txt:Text); var cel:celular; begin reset(archivo); Rewrite(txt); while(not eof(archivo)) do begin read(archivo, cel); if cel.stock_actual = 0 then begin with cel do begin writeln(txt, codigo, ' ', precio:4:2, ' ', marca); writeln(txt, stock_actual, ' ', stock_min, ' ', descripcion); writeln(txt, nombre); end; end; end; Close(archivo); Close(txt); end; var celularesBin:archivoCelulares; celularesTxt:Text; sinStockTxt:Text; opcion:integer; begin Assign(celularesBin, 'celulares'); Assign(celularesTxt, 'celulares.txt'); Assign(sinStockTxt, 'SinStock.txt'); opcion := -1; while(opcion <> 0) do begin Writeln('Elija una de las siguientes opciones de la lista o 0 para salir: '); writeln('1. Crear registro de celulares a partir de archivo de texto.'); writeln('2. Listar en pantalla los datos de aquellos celulares que tengan un stock menor al stock mínimo.'); writeln('3. Listar en pantalla los celulares del archivo cuya descripción contenga una cadena de caracteres proporcionada por el usuario.'); writeln('4. Exportar el archivo creado en el inciso a) a un archivo de texto denominado “celulares.txt” con todos los celulares del mismo.'); writeln('5. Añadir uno o más celulares al final del archivo con sus datos ingresados por teclado.'); writeln('6. Modificar stock de un celular buscado por nombre.'); writeln('7. Exportar celulares sin stock a SinStock.txt.'); Readln(opcion); case opcion of 1: crearBinarioDesdeTxt(celularesBin, celularesTxt); 2: listarStockMenorAlMinimo(celularesBin); 3: listarPorDescripcion(celularesBin); 4: exportarATexto(celularesBin, celularesTxt); 5: agregarCelular(celularesBin); 6: modificarStock(celularesBin); 7: exportarSinStock(celularesBin, sinStockTxt); end; end; end.
unit evTablePainter; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Everest/evTablePainter.pas" // Начат: 06.06.2007 11:44 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::Everest::ParaList Painters::TevTablePainter // // Реализация интерфейса IevPainter для таблицы // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\Everest\evDefine.inc} interface uses evFramedParaListPainter, evCellsOffsets, nevRealTools, nevTools, nevBase ; type TevTablePainter = class(TevFramedParaListPainter, IevTablePainter) {* Реализация интерфейса IevPainter для таблицы } private // private fields f_CellsOffsets : TevCellsOffsets; private // private methods function CellsOffsets: TevCellsOffsets; protected // realized methods procedure CheckCell(const aPara: InevTag; aCheckType: TnevCheckType = nev_None); procedure CalcOffset; {* Пересчитать смещение для следующей ячейки } function WasPainted(const aPara: InevTag; anPID: Integer; aForLines: Boolean): Boolean; {* Проверка была ли отрисована начальная ячейка объединения. } {$If defined(nsTest)} function NeedLog: Boolean; override; {* Поддерживает ли табличный объект запись в лог для тестов. } {$IfEnd} //nsTest protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } function DoDraw: Boolean; override; {* Собственно процедура рисования параграфа. Для перекрытия в потомках. } procedure InitBottom(var theBottom: InevBasePoint; var theCellBottom: InevBasePoint); override; function BeforeDrawChild(const ChildPainter: IevPainter): Boolean; override; {* Вызывается перед рисованием каждого дочернего параграфа. } function GetTablePainter: IevTablePainter; override; procedure InitInnerBottom(const aChildInfo: TnevShapeInfo); override; function NeedsHackK235870994: Boolean; override; end;//TevTablePainter implementation uses k2Tags, evdTypes, SysUtils ; // start class TevTablePainter function TevTablePainter.CellsOffsets: TevCellsOffsets; //#UC START# *49CB6F2D03C8_48C9377502A0_var* //#UC END# *49CB6F2D03C8_48C9377502A0_var* begin //#UC START# *49CB6F2D03C8_48C9377502A0_impl* if f_CellsOffsets = nil then f_CellsOffsets := TevCellsOffsets.Create; Result := f_CellsOffsets; //#UC END# *49CB6F2D03C8_48C9377502A0_impl* end;//TevTablePainter.CellsOffsets procedure TevTablePainter.CheckCell(const aPara: InevTag; aCheckType: TnevCheckType = nev_None); //#UC START# *49CB6BE30032_48C9377502A0_var* //#UC END# *49CB6BE30032_48C9377502A0_var* begin //#UC START# *49CB6BE30032_48C9377502A0_impl* f_CellsOffsets.SetWidth(aPara.IntA[k2_tiWidth]); case TevMergeStatus(aPara.IntA[k2_tiMergeStatus]) of ev_msHead: begin f_CellsOffsets.CheckOffset(False); f_CellsOffsets.AddCellWidth; end; // ev_msHead ev_msNone: f_CellsOffsets.CheckOffset(False); ev_msContinue: if aCheckType <> nev_None then begin f_CellsOffsets.CheckOffset(False); if aCheckType = nev_NeedAdd then f_CellsOffsets.AddCellWidth; end; end; // case l_MergeStatus of //#UC END# *49CB6BE30032_48C9377502A0_impl* end;//TevTablePainter.CheckCell procedure TevTablePainter.CalcOffset; //#UC START# *49CB6C1A02DF_48C9377502A0_var* //#UC END# *49CB6C1A02DF_48C9377502A0_var* begin //#UC START# *49CB6C1A02DF_48C9377502A0_impl* CellsOffsets.RecalcOffset; //#UC END# *49CB6C1A02DF_48C9377502A0_impl* end;//TevTablePainter.CalcOffset function TevTablePainter.WasPainted(const aPara: InevTag; anPID: Integer; aForLines: Boolean): Boolean; //#UC START# *49CB6C2E02E2_48C9377502A0_var* //#UC END# *49CB6C2E02E2_48C9377502A0_var* begin //#UC START# *49CB6C2E02E2_48C9377502A0_impl* Result := TevMergeStatus(aPara.IntA[k2_tiMergeStatus]) = ev_msContinue; if Result then Result := (f_CellsOffsets <> nil) and not f_CellsOffsets.CheckParam; if not Result and aForLines then if Area.rCanvas.Printing and (TopAnchor.Inner <> nil) and TopAnchor.Inner.HasHeadPart then Result := TopAnchor.Inner.InnerHead(anPID) <> nil //#UC END# *49CB6C2E02E2_48C9377502A0_impl* end;//TevTablePainter.WasPainted {$If defined(nsTest)} function TevTablePainter.NeedLog: Boolean; //#UC START# *4D0203AA016F_48C9377502A0_var* //#UC END# *4D0203AA016F_48C9377502A0_var* begin //#UC START# *4D0203AA016F_48C9377502A0_impl* Result := True; //#UC END# *4D0203AA016F_48C9377502A0_impl* end;//TevTablePainter.NeedLog {$IfEnd} //nsTest procedure TevTablePainter.Cleanup; //#UC START# *479731C50290_48C9377502A0_var* //#UC END# *479731C50290_48C9377502A0_var* begin //#UC START# *479731C50290_48C9377502A0_impl* FreeAndNil(f_CellsOffsets); inherited; //#UC END# *479731C50290_48C9377502A0_impl* end;//TevTablePainter.Cleanup function TevTablePainter.DoDraw: Boolean; //#UC START# *4804BC2401C2_48C9377502A0_var* //#UC END# *4804BC2401C2_48C9377502A0_var* begin //#UC START# *4804BC2401C2_48C9377502A0_impl* (* if HackK235870994 then Result := true else*) Result := inherited DoDraw; //#UC END# *4804BC2401C2_48C9377502A0_impl* end;//TevTablePainter.DoDraw procedure TevTablePainter.InitBottom(var theBottom: InevBasePoint; var theCellBottom: InevBasePoint); //#UC START# *4804BC800172_48C9377502A0_var* var l_Inn : InevBasePoint; //#UC END# *4804BC800172_48C9377502A0_var* begin //#UC START# *4804BC800172_48C9377502A0_impl* l_Inn := theBottom.Inner; inherited InitBottom(theBottom, theCellBottom); if (l_Inn <> nil) AND l_Inn.AfterEnd and not theBottom.AfterEnd then if l_Inn.HasHeadPart and Area.rCanvas.Printing then begin theBottom.Inner := theBottom.Inner.Obj^.BaseLine4Print; theBottom.Inner.CopyHeadParts(l_Inn); end; // if l_Inn.HasHeadPart then //#UC END# *4804BC800172_48C9377502A0_impl* end;//TevTablePainter.InitBottom function TevTablePainter.BeforeDrawChild(const ChildPainter: IevPainter): Boolean; //#UC START# *481D6C56033A_48C9377502A0_var* //#UC END# *481D6C56033A_48C9377502A0_var* begin //#UC START# *481D6C56033A_48C9377502A0_impl* Result := inherited BeforeDrawChild(ChildPainter); CellsOffsets.ClearOffset; //#UC END# *481D6C56033A_48C9377502A0_impl* end;//TevTablePainter.BeforeDrawChild function TevTablePainter.GetTablePainter: IevTablePainter; //#UC START# *49DCA7F3011C_48C9377502A0_var* //#UC END# *49DCA7F3011C_48C9377502A0_var* begin //#UC START# *49DCA7F3011C_48C9377502A0_impl* Result := Self; //#UC END# *49DCA7F3011C_48C9377502A0_impl* end;//TevTablePainter.GetTablePainter procedure TevTablePainter.InitInnerBottom(const aChildInfo: TnevShapeInfo); //#UC START# *4C4570AE0113_48C9377502A0_var* var l_Inn : InevBasePoint; //#UC END# *4C4570AE0113_48C9377502A0_var* begin //#UC START# *4C4570AE0113_48C9377502A0_impl* if Area.rNeedBottom then l_Inn := BottomAnchor.Inner; inherited; if Area.rNeedBottom and (l_Inn <> nil) then if l_Inn.HasHeadPart then BottomAnchor.Inner.CopyHeadParts(l_Inn); //#UC END# *4C4570AE0113_48C9377502A0_impl* end;//TevTablePainter.InitInnerBottom function TevTablePainter.NeedsHackK235870994: Boolean; //#UC START# *4CAF3D530327_48C9377502A0_var* //#UC END# *4CAF3D530327_48C9377502A0_var* begin //#UC START# *4CAF3D530327_48C9377502A0_impl* Result := false{true}; //^ - не нужно это, только всё портит, вызывая полное // форматироание таблицы //#UC END# *4CAF3D530327_48C9377502A0_impl* end;//TevTablePainter.NeedsHackK235870994 end.
unit NtUtils.Svc; interface uses Winapi.WinNt, NtUtils.Exceptions, Winapi.Svc; type TScmHandle = Winapi.Svc.TScmHandle; TServiceConfig = record ServiceType: Cardinal; StartType: TServiceStartType; ErrorControl: TServiceErrorControl; TagId: Cardinal; BinaryPathName: String; LoadOrderGroup: String; ServiceStartName: String; DisplayName: String; end; // Open a handle to SCM function ScmxConnect(out hScm: TScmHandle; DesiredAccess: TAccessMask; ServerName: String = ''): TNtxStatus; // Close SCM/service handle function ScmxClose(var hObject: TScmHandle): Boolean; // Open a service function ScmxOpenService(out hSvc: TScmHandle; hScm: TScmHandle; ServiceName: String; DesiredAccess: TAccessMask): TNtxStatus; function ScmxOpenServiceLocal(out hSvc: TScmHandle; ServiceName: String; DesiredAccess: TAccessMask): TNtxStatus; // Create a service function ScmxCreateService(out hSvc: TScmHandle; hScm: TScmHandle; CommandLine, ServiceName, DisplayName: String; StartType: TServiceStartType = ServiceDemandStart): TNtxStatus; function ScmxCreateServiceLocal(out hSvc: TScmHandle; CommandLine, ServiceName, DisplayName: String; StartType: TServiceStartType = ServiceDemandStart) : TNtxStatus; // Start a service function ScmxStartService(hSvc: TScmHandle): TNtxStatus; overload; function ScmxStartService(hSvc: TScmHandle; Parameters: TArray<String>): TNtxStatus; overload; // Send a control to a service function ScmxControlService(hSvc: TScmHandle; Control: TServiceControl; out ServiceStatus: TServiceStatus): TNtxStatus; // Delete a service function ScmxDeleteService(hSvc: TScmHandle): TNtxStatus; // Query service config function ScmxQueryConfigService(hSvc: TScmHandle; out Config: TServiceConfig) : TNtxStatus; // Query service status and process information function ScmxQueryProcessStatusService(hSvc: TScmHandle; out Info: TServiceStatusProcess): TNtxStatus; implementation uses NtUtils.Access.Expected; function ScmxConnect(out hScm: TScmHandle; DesiredAccess: TAccessMask; ServerName: String): TNtxStatus; var pServerName: PWideChar; begin if ServerName <> '' then pServerName := PWideChar(ServerName) else pServerName := nil; Result.Location := 'OpenSCManagerW'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @ScmAccessType; hScm := OpenSCManagerW(pServerName, nil, DesiredAccess); Result.Win32Result := (hScm <> 0); end; function ScmxClose(var hObject: TScmHandle): Boolean; begin Result := CloseServiceHandle(hObject); hObject := 0; end; function ScmxOpenService(out hSvc: TScmHandle; hScm: TScmHandle; ServiceName: String; DesiredAccess: TAccessMask): TNtxStatus; begin Result.Location := 'OpenServiceW'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @ServiceAccessType; Result.LastCall.Expects(SC_MANAGER_CONNECT, @ScmAccessType); hSvc := OpenServiceW(hScm, PWideChar(ServiceName), DesiredAccess); Result.Win32Result := (hSvc <> 0); end; function ScmxOpenServiceLocal(out hSvc: TScmHandle; ServiceName: String; DesiredAccess: TAccessMask): TNtxStatus; var hScm: TScmHandle; begin Result := ScmxConnect(hScm, SC_MANAGER_CONNECT); if Result.IsSuccess then begin Result := ScmxOpenService(hSvc, hScm, ServiceName, DesiredAccess); ScmxClose(hScm); end; end; function ScmxCreateService(out hSvc: TScmHandle; hScm: TScmHandle; CommandLine, ServiceName, DisplayName: String; StartType: TServiceStartType): TNtxStatus; begin Result.Location := 'CreateServiceW'; Result.LastCall.Expects(SC_MANAGER_CREATE_SERVICE, @ScmAccessType); hSvc := CreateServiceW(hScm, PWideChar(ServiceName), PWideChar(DisplayName), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, StartType, ServiceErrorNormal, PWideChar(CommandLine), nil, nil, nil, nil, nil); Result.Win32Result := (hSvc <> 0); end; function ScmxCreateServiceLocal(out hSvc: TScmHandle; CommandLine, ServiceName, DisplayName: String; StartType: TServiceStartType): TNtxStatus; var hScm: TScmHandle; begin Result := ScmxConnect(hScm, SC_MANAGER_CREATE_SERVICE); if Result.IsSuccess then begin Result := ScmxCreateService(hSvc, hScm, CommandLine, ServiceName, DisplayName, StartType); ScmxClose(hScm); end; end; function ScmxStartService(hSvc: TScmHandle): TNtxStatus; overload; var Parameters: TArray<String>; begin SetLength(Parameters, 0); Result := ScmxStartService(hSvc, Parameters); end; function ScmxStartService(hSvc: TScmHandle; Parameters: TArray<String>): TNtxStatus; var i: Integer; Params: TArray<PWideChar>; begin SetLength(Params, Length(Parameters)); for i := 0 to High(Params) do Params[i] := PWideChar(Parameters[i]); Result.Location := 'StartServiceW'; Result.LastCall.Expects(SERVICE_START, @ServiceAccessType); Result.Win32Result := StartServiceW(hSvc, Length(Params), Params); end; function ScmxControlService(hSvc: TScmHandle; Control: TServiceControl; out ServiceStatus: TServiceStatus): TNtxStatus; begin Result.Location := 'ControlService'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(Control); Result.LastCall.InfoClassType := TypeInfo(TServiceControl); RtlxComputeServiceControlAccess(Result.LastCall, Control); Result.Win32Result := ControlService(hSvc, Control, ServiceStatus); end; function ScmxDeleteService(hSvc: TScmHandle): TNtxStatus; begin Result.Location := 'DeleteService'; Result.LastCall.Expects(_DELETE, @ServiceAccessType); Result.Win32Result := DeleteService(hSvc); end; function ScmxQueryConfigService(hSvc: TScmHandle; out Config: TServiceConfig) : TNtxStatus; var Buffer: PQueryServiceConfigW; BufferSize, Required: Cardinal; begin Result.Location := 'QueryServiceConfigW'; Result.LastCall.Expects(SERVICE_QUERY_CONFIG, @ServiceAccessType); BufferSize := 0; repeat Buffer := AllocMem(BufferSize); Required := 0; Result.Win32Result := QueryServiceConfigW(hSvc, Buffer, BufferSize, Required); if not Result.IsSuccess then FreeMem(Buffer); until not NtxExpandBuffer(Result, BufferSize, Required); if not Result.IsSuccess then Exit; Config.ServiceType := Buffer.ServiceType; Config.StartType := Buffer.StartType; Config.ErrorControl := Buffer.ErrorControl; Config.TagId := Buffer.TagId; Config.BinaryPathName := String(Buffer.BinaryPathName); Config.LoadOrderGroup := String(Buffer.LoadOrderGroup); Config.ServiceStartName := String(Buffer.ServiceStartName); Config.DisplayName := String(Buffer.DisplayName); FreeMem(Buffer); end; function ScmxQueryProcessStatusService(hSvc: TScmHandle; out Info: TServiceStatusProcess): TNtxStatus; var Required: Cardinal; begin Result.Location := 'QueryServiceStatusEx'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(ScStatusProcessInfo); Result.LastCall.InfoClassType := TypeInfo(TScStatusType); Result.LastCall.Expects(SERVICE_QUERY_STATUS, @ServiceAccessType); Result.Win32Result := QueryServiceStatusEx(hSvc, ScStatusProcessInfo, @Info, SizeOf(Info), Required); end; end.
unit HttpServerService.Logger; interface uses SysUtils, Quick.Logger.Intf, Quick.Logger, Quick.Logger.Provider.Console; type TQuickLogger = class(TInterfacedObject,ILogger) public procedure Init; procedure Info(const aMsg : string); overload; procedure Info(const aMsg : string; aValues : array of const); overload; procedure Succ(const aMsg : string); overload; procedure Succ(const aMsg : string; aParams : array of const); overload; procedure Done(const aMsg : string); overload; procedure Done(const aMsg : string; aValues : array of const); overload; procedure Warn(const aMsg : string); overload; procedure Warn(const aMsg : string; aValues : array of const); overload; procedure Error(const aMsg : string); overload; procedure Error(const aMsg : string; aValues : array of const); overload; procedure Critical(const aMsg : string); overload; procedure Critical(const aMsg : string; aValues : array of const); overload; procedure Trace(const aMsg : string); overload; procedure Trace(const aMsg : string; aValues : array of const); overload; procedure Debug(const aMsg : string); overload; procedure Debug(const aMsg : string; aValues : array of const); overload; procedure &Except(const aMsg : string; aValues : array of const); overload; procedure &Except(const aMsg, aException, aStackTrace : string); overload; procedure &Except(const aMsg : string; aValues: array of const; const aException, aStackTrace: string); overload; end; implementation { TQuickLogger } procedure TQuickLogger.Init; begin GlobalLogConsoleProvider.LogLevel := LOG_DEBUG; Logger.Providers.Add(GlobalLogConsoleProvider); GlobalLogConsoleProvider.Enabled := True; end; procedure TQuickLogger.Info(const aMsg: string); begin Logger.Info(aMsg); end; procedure TQuickLogger.Info(const aMsg: string; aValues: array of const); begin Logger.Info(aMsg,aValues); end; procedure TQuickLogger.Succ(const aMsg: string); begin Logger.Succ(aMsg); end; procedure TQuickLogger.Succ(const aMsg: string; aParams: array of const); begin Logger.Succ(aMsg,aParams); end; procedure TQuickLogger.Done(const aMsg: string); begin Logger.Done(aMsg); end; procedure TQuickLogger.Done(const aMsg: string; aValues: array of const); begin Logger.Done(aMsg,aValues); end; procedure TQuickLogger.Warn(const aMsg: string); begin Logger.Warn(aMsg); end; procedure TQuickLogger.Warn(const aMsg: string; aValues: array of const); begin Logger.Warn(aMsg,aValues); end; procedure TQuickLogger.Error(const aMsg: string); begin Logger.Error(aMsg); end; procedure TQuickLogger.Error(const aMsg: string; aValues: array of const); begin Logger.Error(aMsg,aValues); end; procedure TQuickLogger.Critical(const aMsg: string); begin Logger.Critical(aMsg); end; procedure TQuickLogger.Critical(const aMsg: string; aValues: array of const); begin Logger.Critical(aMsg,aValues); end; procedure TQuickLogger.Trace(const aMsg: string); begin Logger.Trace(aMsg); end; procedure TQuickLogger.Trace(const aMsg: string; aValues: array of const); begin Logger.Trace(aMsg,aValues); end; procedure TQuickLogger.Debug(const aMsg: string); begin Logger.Debug(aMsg); end; procedure TQuickLogger.Debug(const aMsg: string; aValues: array of const); begin Logger.Debug(aMsg,aValues); end; procedure TQuickLogger.&Except(const aMsg: string; aValues: array of const); begin Logger.&Except(aMsg,aValues); end; procedure TQuickLogger.&Except(const aMsg: string; aValues: array of const; const aException, aStackTrace: string); begin Logger.&Except(aMsg,aValues,aException,aStacktrace); end; procedure TQuickLogger.&Except(const aMsg, aException, aStackTrace: string); begin Logger.&Except(aMsg,aException,aStackTrace); end; end.
Unit H2ScrollText; Interface Uses Messages,Windows, Classes,Controls, ExtCtrls, SysUtils,GR32_Image,GR32, gr32_layers,Graphics; Type TH2Scrolltext = Class(TControl) Private fNewstr:String; fanimate:Boolean; ftimer:tTimer; finterval:Cardinal; fsep:String; fx, fy, fwidth, fheight:Integer; fvisible:Boolean; fitems:tstringlist; ffont:tfont; fpos: Integer; fbitmap:tbitmaplayer; fbmp: tbitmap32; fdrawmode:tdrawmode; falpha:Cardinal; Procedure SetFont(font:tfont); Procedure Setvisible(value:Boolean); Procedure SetAnimate(value:Boolean); Procedure SetNewStr(value:String); Procedure Ontimer(Sender:Tobject);Virtual; Public Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Published Procedure Clear; Procedure Start; Procedure Stop; Property Seperator:String Read fsep Write fsep; Property NewStr:String Write SetNewStr; Property Animate:Boolean Read fanimate Write setanimate; Property Interval:Cardinal Read finterval Write finterval; Property Font:tfont Read ffont Write setfont; Property Alpha:Cardinal Read falpha Write falpha; Property DrawMode:tdrawmode Read fdrawmode Write fdrawmode; Property X:Integer Read fx Write fx; Property Y:Integer Read fy Write fy; Property Width:Integer Read fwidth Write fwidth; Property Height:Integer Read fheight Write fheight; Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap; Property Visible:Boolean Read fvisible Write setvisible; Property OnMouseDown; Property OnMouseMove; Property OnMouseUp; Property OnClick; Property OnDblClick; End; Implementation { TH2Label } Procedure TH2Scrolltext.Clear; Begin fitems.Clear; fanimate:=False; ftimer.Enabled:=False; End; Constructor TH2Scrolltext.Create(AOwner: TComponent); Var L: TFloatRect; Begin Inherited Create(AOwner); fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers); ffont:=tfont.Create; ftimer:=ttimer.Create(aowner); ftimer.Enabled:=False; ftimer.Interval:=500; fsep:=' # '; ftimer.OnTimer:=ontimer; fanimate:=False; finterval:=500; fitems:=tstringlist.Create; fnewstr:=''; fdrawmode:=dmblend; falpha:=255; fvisible:=True; fx:=0; fpos:=0; fy:=0; fwidth:=100; fheight:=100; fbmp:=tbitmap32.Create; fbitmap.Bitmap.Width:=fwidth; fbitmap.Bitmap.Height:=fheight; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Tag:=0; fbitmap.Bitmap.DrawMode:=fdrawmode; fbitmap.Bitmap.MasterAlpha:=falpha; fvisible:=True; End; Destructor TH2Scrolltext.Destroy; Begin //here stop; ffont.Free; fbitmap.Free; ftimer.Free; fitems.Free; fbmp.Free; Inherited Destroy; End; Procedure TH2Scrolltext.Ontimer(Sender: Tobject); Begin ftimer.Enabled:=False; If fanimate Then Begin fpos:=fpos+1; fbmp.DrawTo(fBitmap.Bitmap,0,0,rect(fpos,0,fwidth+fpos,fHeight)); If fpos>=fbmp.Width Then fpos:=0; End; ftimer.Enabled:=True; End; Procedure TH2Scrolltext.SetAnimate(value: Boolean); Begin fanimate:=value; ftimer.Interval:=finterval; ftimer.Enabled:=fanimate; End; Procedure TH2Scrolltext.SetFont(font: tfont); Begin ffont.Assign(font); End; Procedure TH2Scrolltext.SetNewStr(value: String); Var w,i,j:Integer; Color: Longint; r, g, b: Byte; Begin ftimer.Enabled:=False; fpos:=0; fitems.add(value+fsep); fbmp.Clear($000000); fbmp.Width:=0; fbmp.Height:=fheight; fbmp.Font.Assign(ffont); Color := ColorToRGB(ffont.Color); r := Color; g := Color Shr 8; b := Color Shr 16; w:=0; For i:=0 To fitems.Count-1 Do Begin w:=fbmp.TextWidth(fitems[i])+w; End; fbmp.Width:=w+fwidth; j:=0; For i:=0 To fitems.Count-1 Do Begin fbmp.RenderText(fwidth+j,0,fitems[i],0,color32(r,g,b,falpha)); j:=j+fbmp.TextWidth(fitems[i]); End; ftimer.Enabled:=True; End; Procedure TH2Scrolltext.Setvisible(value: Boolean); Begin fbitmap.Visible:=value; End; Procedure TH2Scrolltext.Start; Var L: TFloatRect; Begin fbitmap.bitmap.width:=fwidth; fbitmap.bitmap.height:=fheight; l.Left:=fx; l.Right:=fx+fbitmap.Bitmap.Width; l.Top :=fy; l.Bottom:=fy+fbitmap.Bitmap.height; ftimer.Interval:=finterval; fbitmap.Location:=l; fanimate:=True; ftimer.Enabled:=True; End; Procedure TH2Scrolltext.Stop; Begin fanimate:=False; ftimer.Enabled:=False; End; End.
unit gtWinCrypt3; {$I jediapilib.inc} {$IFDEF WIN32} {$DEFINE DYNAMIC_LINK} {$ENDIF} interface uses gtJwaWinCrypt3, gtJwaWinType3; const advapi32 = 'crypt32.dll'; crypt32 = 'crypt32.dll'; // +========================================================================= // PFX (PKCS #12) function defintions and types // ========================================================================== // +------------------------------------------------------------------------- // PFXImportCertStore // // Import the PFX blob and return a store containing certificates // // If the password parameter is incorrect or any other problems decoding // the PFX blob are encountered, the function will return NULL and the // error code can be found from GetLastError(). // // The dwFlags parameter may be set to the following: // CRYPT_EXPORTABLE - specify that any imported keys should be marked as // exportable (see documentation on CryptImportKey) // CRYPT_USER_PROTECTED - (see documentation on CryptImportKey) // CRYPT_MACHINE_KEYSET - used to force the private key to be stored in the // the local machine and not the current user. // CRYPT_USER_KEYSET - used to force the private key to be stored in the // the current user and not the local machine, even if // the pfx blob specifies that it should go into local // machine. // -------------------------------------------------------------------------- function PFXImportCertStore(pPFX: PCRYPT_DATA_BLOB; szPassword: LPCWSTR; dwFlags: DWORD): HCERTSTORE; stdcall; {$EXTERNALSYM PFXImportCertStore} // dwFlags definitions for PFXImportCertStore // #define CRYPT_EXPORTABLE 0x00000001 // CryptImportKey dwFlags // #define CRYPT_USER_PROTECTED 0x00000002 // CryptImportKey dwFlags // #define CRYPT_MACHINE_KEYSET 0x00000020 // CryptAcquireContext dwFlags const CRYPT_USER_KEYSET = $00001000; PKCS12_IMPORT_RESERVED_MASK = $FFFF0000; // +------------------------------------------------------------------------- // PFXIsPFXBlob // // This function will try to decode the outer layer of the blob as a pfx // blob, and if that works it will return TRUE, it will return FALSE otherwise // // -------------------------------------------------------------------------- function PFXIsPFXBlob(pPFX: PCRYPT_DATA_BLOB): BOOL; stdcall {$EXTERNALSYM PFXIsPFXBlob} // +------------------------------------------------------------------------- // PFXVerifyPassword // // This function will attempt to decode the outer layer of the blob as a pfx // blob and decrypt with the given password. No data from the blob will be // imported. // // Return value is TRUE if password appears correct, FALSE otherwise. // // -------------------------------------------------------------------------- function PFXVerifyPassword(pPFX: PCRYPT_DATA_BLOB; szPassword: LPCWSTR; dwFlags: DWORD): BOOL; stdcall {$EXTERNALSYM PFXVerifyPassword} // +------------------------------------------------------------------------- // PFXExportCertStoreEx // // Export the certificates and private keys referenced in the passed-in store // // This API encodes the blob under a stronger algorithm. The resulting // PKCS12 blobs are incompatible with the earlier PFXExportCertStore API. // // The value passed in the password parameter will be used to encrypt and // verify the integrity of the PFX packet. If any problems encoding the store // are encountered, the function will return FALSE and the error code can // be found from GetLastError(). // // The dwFlags parameter may be set to any combination of // EXPORT_PRIVATE_KEYS // REPORT_NO_PRIVATE_KEY // REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY // // The encoded PFX blob is returned in *pPFX. If pPFX->pbData is NULL upon // input, this is a length only calculation, whereby, pPFX->cbData is updated // with the number of bytes required for the encoded blob. Otherwise, // the memory pointed to by pPFX->pbData is updated with the encoded bytes // and pPFX->cbData is updated with the encoded byte length. // -------------------------------------------------------------------------- function PFXExportCertStoreEx(hStore: HCERTSTORE; var pPFX: PCRYPT_DATA_BLOB; szPassword: LPCWSTR; pvReserved: LPVOID; dwFlags: DWORD): BOOL; stdcall; {$EXTERNALSYM PFXExportCertStoreEx} // dwFlags definitions for PFXExportCertStoreEx const REPORT_NO_PRIVATE_KEY = $0001; REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY = $0002; EXPORT_PRIVATE_KEYS = $0004; PKCS12_EXPORT_RESERVED_MASK = $FFFF0000; // +------------------------------------------------------------------------- // PFXExportCertStore // // Export the certificates and private keys referenced in the passed-in store // // This is an old API kept for compatibility with IE4 clients. New applications // should call the above PfxExportCertStoreEx for enhanced security. // -------------------------------------------------------------------------- function PFXExportCertStore(hStore: HCERTSTORE; var pPFX: PCRYPT_DATA_BLOB; szPassword: LPCWSTR; dwFlags: DWORD): BOOL; stdcall; {$EXTERNALSYM PFXExportCertStore} // dwFlags has the following defines const CRYPT_STRING_BASE64HEADER = $00000000; CRYPT_STRING_BASE64 = $00000001; CRYPT_STRING_BINARY = $00000002; CRYPT_STRING_BASE64REQUESTHEADER = $00000003; CRYPT_STRING_HEX = $00000004; CRYPT_STRING_HEXASCII = $00000005; CRYPT_STRING_BASE64_ANY = $00000006; CRYPT_STRING_ANY = $00000007; CRYPT_STRING_HEX_ANY = $00000008; CRYPT_STRING_BASE64X509CRLHEADER = $00000009; CRYPT_STRING_HEXADDR = $0000000A; CRYPT_STRING_HEXASCIIADDR = $0000000B; CRYPT_STRING_NOCR = DWORD($80000000); implementation {$IFDEF DYNAMIC_LINK} var _PFXImportCertStore: Pointer; function PFXImportCertStore; begin GetProcedureAddress(_PFXImportCertStore, advapi32, 'PFXImportCertStore'); asm MOV ESP, EBP POP EBP JMP [_PFXImportCertStore] end; end; var _PFXIsPFXBlob: Pointer; function PFXIsPFXBlob; begin GetProcedureAddress(_PFXIsPFXBlob, advapi32, 'PFXIsPFXBlob'); asm MOV ESP, EBP POP EBP JMP [_PFXIsPFXBlob] end; end; var _PFXVerifyPassword: Pointer; function PFXVerifyPassword; begin GetProcedureAddress(_PFXVerifyPassword, advapi32, 'PFXVerifyPassword'); asm MOV ESP, EBP POP EBP JMP [_PFXVerifyPassword] end; end; var _PFXExportCertStoreEx: Pointer; function PFXExportCertStoreEx; begin GetProcedureAddress(_PFXExportCertStoreEx, advapi32, 'PFXExportCertStoreEx'); asm MOV ESP, EBP POP EBP JMP [_PFXExportCertStoreEx] end; end; var _PFXExportCertStore: Pointer; function PFXExportCertStore; begin GetProcedureAddress(_PFXExportCertStore, advapi32, 'PFXExportCertStore'); asm MOV ESP, EBP POP EBP JMP [_PFXExportCertStore] end; end; {$ELSE} function PFXImportCertStore; external crypt32 name 'PFXImportCertStore'; function PFXIsPFXBlob; external crypt32 name 'PFXIsPFXBlob'; function PFXVerifyPassword; external crypt32 name 'PFXVerifyPassword'; function PFXExportCertStoreEx; external crypt32 name 'PFXExportCertStoreEx'; function PFXExportCertStore; external crypt32 name 'PFXExportCertStore'; {$ENDIF DYNAMIC_LINK} {$EXTERNALSYM CRYPT_USER_KEYSET} {$EXTERNALSYM PKCS12_IMPORT_RESERVED_MASK} {$EXTERNALSYM REPORT_NO_PRIVATE_KEY} {$EXTERNALSYM REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY} {$EXTERNALSYM EXPORT_PRIVATE_KEYS} {$EXTERNALSYM PKCS12_EXPORT_RESERVED_MASK} {$EXTERNALSYM CRYPT_STRING_BASE64HEADER} {$EXTERNALSYM CRYPT_STRING_BASE64} {$EXTERNALSYM CRYPT_STRING_BINARY} {$EXTERNALSYM CRYPT_STRING_BASE64REQUESTHEADER} {$EXTERNALSYM CRYPT_STRING_HEX} {$EXTERNALSYM CRYPT_STRING_HEXASCII} {$EXTERNALSYM CRYPT_STRING_BASE64_ANY} {$EXTERNALSYM CRYPT_STRING_ANY} {$EXTERNALSYM CRYPT_STRING_HEX_ANY} {$EXTERNALSYM CRYPT_STRING_BASE64X509CRLHEADER} {$EXTERNALSYM CRYPT_STRING_HEXADDR} {$EXTERNALSYM CRYPT_STRING_NOCR} {$EXTERNALSYM CRYPT_STRING_HEXASCIIADDR} end.
unit ViewUtils; interface uses Windows; const // Stretch Mode internal flags smiOperationMask = $FF00; smiOperationFit = $4000; smiOperationStretch = $8000; smiOperationZoom = $0000; smiOperationShrink = $0080; smiMaxAllowedZoom = $007F; // Don't go mad, just use these constants & functions: ------------------------------------- // Examples: StretchSize( smFitClientArea, OriginalSize, Area ); // StretchSize( smZoomBy(2), OriginalSize, Area ); // Fit smFitClientArea = smiOperationFit + $00; smFitWidth = smiOperationFit + $01; smFitHeight = smiOperationFit + $02; // Stretch smStretchClientArea = smiOperationStretch + $00; smStretchWidth = smiOperationStretch + $01; smStretchHeight = smiOperationStretch + $02; // Zoom & Shrink function smZoomBy( Times : integer ) : integer; function smShrinkBy( Times : integer ) : integer; function StretchSize( StretchMode : integer; OriginalSize : TPoint; const Area : TRect ) : TPoint; procedure Center( const Size : TPoint; const Area : TRect; var Rect : TRect ); implementation uses Rects; function smZoomBy( Times : integer ) : integer; begin assert( Times <= smiMaxAllowedZoom, 'Invalid zoom requested in ViewUtils.smZoomBy' ); Result := smiOperationZoom + Times; end; function smShrinkBy( Times : integer ) : integer; begin assert( Times <= smiMaxAllowedZoom, 'Invalid zoom requested in ViewUtils.smShrinkBy' ); Result := smiOperationShrink + Times; end; function StretchSize( StretchMode : integer; OriginalSize : TPoint; const Area : TRect ) : TPoint; var ClientSize : TPoint; begin ClientSize := RectSize( Area ); if StretchMode and smiOperationMask = smiOperationZoom then // Do Zoom/Shrink begin if StretchMode and smiOperationShrink <> 0 then begin Result.X := OriginalSize.X div ( StretchMode and smiMaxAllowedZoom ); Result.Y := OriginalSize.Y div ( StretchMode and smiMaxAllowedZoom ); end else begin Result.X := OriginalSize.X * ( StretchMode and smiMaxAllowedZoom ); Result.Y := OriginalSize.Y * ( StretchMode and smiMaxAllowedZoom ); end; end else case StretchMode of smFitWidth : begin Result.X := ClientSize.X; Result.Y := (OriginalSize.Y * ClientSize.X div OriginalSize.X) end; smFitHeight : begin Result.X := OriginalSize.X * ClientSize.Y div OriginalSize.Y; Result.Y := ClientSize.Y; end; smFitClientArea : if ClientSize.X * OriginalSize.Y < ClientSize.Y * OriginalSize.X then begin Result.X := ClientSize.X; Result.Y := OriginalSize.Y * ClientSize.X div OriginalSize.X; end else begin Result.X := OriginalSize.X * ClientSize.Y div OriginalSize.Y; Result.Y := ClientSize.Y; end; smStretchWidth : begin Result.X := ClientSize.X; Result.Y := OriginalSize.Y; end; smStretchHeight : begin Result.X := OriginalSize.X; Result.Y := ClientSize.Y; end; smStretchClientArea : begin Result.X := ClientSize.X; Result.Y := ClientSize.Y; end; else begin Result.X := OriginalSize.X; Result.Y := OriginalSize.Y; end; end; end; procedure Center( const Size : TPoint; const Area : TRect; var Rect : TRect ); var ClientSize : TPoint; begin // Place control in ClientArea's center ClientSize := RectSize( Area ); with Area do begin if Size.X < ClientSize.X then Rect.Left := ( ClientSize.X - Size.X ) div 2 + Left else Rect.Left := Left; if Size.Y < ClientSize.Y then Rect.Top := ( ClientSize.Y - Size.Y ) div 2 + Top else Rect.Top := Top; end; with Rect do begin Right := Left + Size.X; Bottom := Top + Size.Y; end; end; end.
unit Globals; interface Uses Windows, SysUtils, Forms, SQLAccess, GenUtils, WinUtils, TransferFields; Const TABLE_CLASSROOMS = 'tblClassRooms'; FIELD_ID = 'ID'; FIELD_NAME = 'sName'; var SQL : TSchSQLAccess; { Indexes } iiClassRooms : Integer; procedure LoadLastIndexes(); procedure Perform_ExecuteUpdate( cList : TSchGenericEntry; sTable, sWhere : String ); function Perform_ExecuteSQLQuery ( sQuery : String; bIsUpdate : Boolean ) : TSchGenericEntryList; procedure Perform_ExecuteSQLModify ( TableName, ValueName : String; EqualsTo : Integer; Entry : TSchGenericEntry ); function Perform_Connect( cs : TConnectSpec ) : Boolean; function DB_Busy() : boolean; implementation var __cList : TSchGenericEntry; __sTable : String; __sWhere : String; __sQuery : String; __bIsUpdate : Boolean; __TableName : String; __ValueName : String; __EqualsTo : Integer; __Entry : TSchGenericEntry; __Result : TSchGenericEntryList; __cs : TConnectSpec; __Could : Boolean; __Die : Boolean; { Threading ... } function DB_Busy() : boolean; begin Result := not __Die; end; function Thread_ExecuteUpdate( pParam : Pointer ) : LongInt; stdcall; forward; function Thread_ExecuteSQLQuery( pParam : Pointer ) : LongInt; stdcall; forward; function Thread_ExecuteSQLModify( pParam : Pointer ) : LongInt; stdcall; forward; function Thread_Connect( pParam : Pointer ) : LongInt; stdcall; forward; function Perform_Connect( cs : TConnectSpec ) : Boolean; var thId : Cardinal; begin __cs := cs; __Die := False; CreateThread( nil, 0, Addr( Thread_Connect ), nil, 0, thId); while (not __Die) do begin Sleep( 50 ); Application.ProcessMessages(); end; Result := __Could; end; procedure Perform_ExecuteUpdate( cList : TSchGenericEntry; sTable, sWhere : String ); var thId : Cardinal; begin __cList := cList; __sTable := sTable; __sWhere := sWhere; __Die := False; CreateThread( nil, 0, Addr( Thread_ExecuteUpdate ), nil, 0, thId); while (not __Die) do begin Sleep( 50 ); Application.ProcessMessages(); end; end; function Perform_ExecuteSQLQuery ( sQuery : String; bIsUpdate : Boolean ) : TSchGenericEntryList; var thId : Cardinal; begin __sQuery := sQuery; __bIsUpdate := bIsUpdate; __Die := False; CreateThread( nil, 0, Addr( Thread_ExecuteSQLQuery ), nil, 0, thId); while (not __Die) do begin Sleep( 50 ); Application.ProcessMessages(); end; Result := __Result; end; procedure Perform_ExecuteSQLModify ( TableName, ValueName : String; EqualsTo : Integer; Entry : TSchGenericEntry ); var thId : Cardinal; begin __TableName := TableName; __ValueName := ValueName; __EqualsTo := EqualsTo; __Entry := Entry; __Die := False; CreateThread( nil, 0, Addr( Thread_ExecuteSQLModify ), nil, 0, thId); while (not __Die) do begin Sleep( 50 ); Application.ProcessMessages(); end; end; { Threading ... } function Thread_ExecuteUpdate( pParam : Pointer ) : LongInt; stdcall; begin SQL.ExecuteUpdate( __cList, __sTable, __sWhere ); { ----------------- } __Die := True; { Notify Thread Death } Result := 0; end; function Thread_ExecuteSQLQuery( pParam : Pointer ) : LongInt; stdcall; begin __Result := SQL.ExecuteSQLQuery( __sQuery, __bIsUpdate ); { ----------------- } __Die := True; { Notify Thread Death } Result := 0; end; function Thread_ExecuteSQLModify( pParam : Pointer ) : LongInt; stdcall; begin SQL.ExecuteSQLModify ( __TableName, __ValueName, __EqualsTo, __Entry ); { ----------------- } __Die := True; { Notify Thread Death } Result := 0; end; function Thread_Connect( pParam : Pointer ) : LongInt; stdcall; begin __Could := SQL.Connect ( __cs ); { ----------------- } __Die := True; { Notify Thread Death } Result := 0; end; function LoadLastIndex( sTable : String ) : Integer; var el : TSchGenericEntryList; begin el := Perform_ExecuteSQLQuery( 'SELECT MAX('+ FIELD_ID +') FROM ' + sTable, False ); Result := 1; if el.Count = 1 then if el.Items[0].Count = 1 then if el.Items[0].Items[0].isInteger then begin Result := el.Items[0].Items[0].asInteger; end; el.Destroy(); end; procedure LoadLastIndexes(); begin iiClassRooms := LoadLastIndex( TABLE_CLASSROOMS ); end; initialization __Die := True; end.
unit pointer_constraints_unstable_v1_protocol; {$mode objfpc} {$H+} {$interfaces corba} interface uses Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol; type Pzwp_pointer_constraints_v1 = Pointer; Pzwp_locked_pointer_v1 = Pointer; Pzwp_confined_pointer_v1 = Pointer; const ZWP_POINTER_CONSTRAINTS_V1_ERROR_ALREADY_CONSTRAINED = 1; // pointer constraint already requested on that surface ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT = 1; // ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_PERSISTENT = 2; // type Pzwp_pointer_constraints_v1_listener = ^Tzwp_pointer_constraints_v1_listener; Tzwp_pointer_constraints_v1_listener = record end; Pzwp_locked_pointer_v1_listener = ^Tzwp_locked_pointer_v1_listener; Tzwp_locked_pointer_v1_listener = record locked : procedure(data: Pointer; AZwpLockedPointerV1: Pzwp_locked_pointer_v1); cdecl; unlocked : procedure(data: Pointer; AZwpLockedPointerV1: Pzwp_locked_pointer_v1); cdecl; end; Pzwp_confined_pointer_v1_listener = ^Tzwp_confined_pointer_v1_listener; Tzwp_confined_pointer_v1_listener = record confined : procedure(data: Pointer; AZwpConfinedPointerV1: Pzwp_confined_pointer_v1); cdecl; unconfined : procedure(data: Pointer; AZwpConfinedPointerV1: Pzwp_confined_pointer_v1); cdecl; end; TZwpPointerConstraintsV1 = class; TZwpLockedPointerV1 = class; TZwpConfinedPointerV1 = class; IZwpPointerConstraintsV1Listener = interface ['IZwpPointerConstraintsV1Listener'] end; IZwpLockedPointerV1Listener = interface ['IZwpLockedPointerV1Listener'] procedure zwp_locked_pointer_v1_locked(AZwpLockedPointerV1: TZwpLockedPointerV1); procedure zwp_locked_pointer_v1_unlocked(AZwpLockedPointerV1: TZwpLockedPointerV1); end; IZwpConfinedPointerV1Listener = interface ['IZwpConfinedPointerV1Listener'] procedure zwp_confined_pointer_v1_confined(AZwpConfinedPointerV1: TZwpConfinedPointerV1); procedure zwp_confined_pointer_v1_unconfined(AZwpConfinedPointerV1: TZwpConfinedPointerV1); end; TZwpPointerConstraintsV1 = class(TWLProxyObject) private const _DESTROY = 0; const _LOCK_POINTER = 1; const _CONFINE_POINTER = 2; public destructor Destroy; override; function LockPointer(ASurface: TWlSurface; APointer: TWlPointer; ARegion: TWlRegion; ALifetime: DWord; AProxyClass: TWLProxyObjectClass = nil {TZwpLockedPointerV1}): TZwpLockedPointerV1; function ConfinePointer(ASurface: TWlSurface; APointer: TWlPointer; ARegion: TWlRegion; ALifetime: DWord; AProxyClass: TWLProxyObjectClass = nil {TZwpConfinedPointerV1}): TZwpConfinedPointerV1; function AddListener(AIntf: IZwpPointerConstraintsV1Listener): LongInt; end; TZwpLockedPointerV1 = class(TWLProxyObject) private const _DESTROY = 0; const _SET_CURSOR_POSITION_HINT = 1; const _SET_REGION = 2; public destructor Destroy; override; procedure SetCursorPositionHint(ASurfaceX: Longint{24.8}; ASurfaceY: Longint{24.8}); procedure SetRegion(ARegion: TWlRegion); function AddListener(AIntf: IZwpLockedPointerV1Listener): LongInt; end; TZwpConfinedPointerV1 = class(TWLProxyObject) private const _DESTROY = 0; const _SET_REGION = 1; public destructor Destroy; override; procedure SetRegion(ARegion: TWlRegion); function AddListener(AIntf: IZwpConfinedPointerV1Listener): LongInt; end; var zwp_pointer_constraints_v1_interface: Twl_interface; zwp_locked_pointer_v1_interface: Twl_interface; zwp_confined_pointer_v1_interface: Twl_interface; implementation var vIntf_zwp_pointer_constraints_v1_Listener: Tzwp_pointer_constraints_v1_listener; vIntf_zwp_locked_pointer_v1_Listener: Tzwp_locked_pointer_v1_listener; vIntf_zwp_confined_pointer_v1_Listener: Tzwp_confined_pointer_v1_listener; destructor TZwpPointerConstraintsV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; function TZwpPointerConstraintsV1.LockPointer(ASurface: TWlSurface; APointer: TWlPointer; ARegion: TWlRegion; ALifetime: DWord; AProxyClass: TWLProxyObjectClass = nil {TZwpLockedPointerV1}): TZwpLockedPointerV1; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _LOCK_POINTER, @zwp_locked_pointer_v1_interface, nil, ASurface.Proxy, APointer.Proxy, ARegion.Proxy, ALifetime); if AProxyClass = nil then AProxyClass := TZwpLockedPointerV1; Result := TZwpLockedPointerV1(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZwpLockedPointerV1) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZwpLockedPointerV1]); end; function TZwpPointerConstraintsV1.ConfinePointer(ASurface: TWlSurface; APointer: TWlPointer; ARegion: TWlRegion; ALifetime: DWord; AProxyClass: TWLProxyObjectClass = nil {TZwpConfinedPointerV1}): TZwpConfinedPointerV1; var id: Pwl_proxy; begin id := wl_proxy_marshal_constructor(FProxy, _CONFINE_POINTER, @zwp_confined_pointer_v1_interface, nil, ASurface.Proxy, APointer.Proxy, ARegion.Proxy, ALifetime); if AProxyClass = nil then AProxyClass := TZwpConfinedPointerV1; Result := TZwpConfinedPointerV1(AProxyClass.Create(id)); if not AProxyClass.InheritsFrom(TZwpConfinedPointerV1) then Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZwpConfinedPointerV1]); end; function TZwpPointerConstraintsV1.AddListener(AIntf: IZwpPointerConstraintsV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_pointer_constraints_v1_Listener, @FUserDataRec); end; destructor TZwpLockedPointerV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; procedure TZwpLockedPointerV1.SetCursorPositionHint(ASurfaceX: Longint{24.8}; ASurfaceY: Longint{24.8}); begin wl_proxy_marshal(FProxy, _SET_CURSOR_POSITION_HINT, ASurfaceX, ASurfaceY); end; procedure TZwpLockedPointerV1.SetRegion(ARegion: TWlRegion); begin wl_proxy_marshal(FProxy, _SET_REGION, ARegion.Proxy); end; function TZwpLockedPointerV1.AddListener(AIntf: IZwpLockedPointerV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_locked_pointer_v1_Listener, @FUserDataRec); end; destructor TZwpConfinedPointerV1.Destroy; begin wl_proxy_marshal(FProxy, _DESTROY); inherited Destroy; end; procedure TZwpConfinedPointerV1.SetRegion(ARegion: TWlRegion); begin wl_proxy_marshal(FProxy, _SET_REGION, ARegion.Proxy); end; function TZwpConfinedPointerV1.AddListener(AIntf: IZwpConfinedPointerV1Listener): LongInt; begin FUserDataRec.ListenerUserData := Pointer(AIntf); Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_confined_pointer_v1_Listener, @FUserDataRec); end; procedure zwp_locked_pointer_v1_locked_Intf(AData: PWLUserData; Azwp_locked_pointer_v1: Pzwp_locked_pointer_v1); cdecl; var AIntf: IZwpLockedPointerV1Listener; begin if AData = nil then Exit; AIntf := IZwpLockedPointerV1Listener(AData^.ListenerUserData); AIntf.zwp_locked_pointer_v1_locked(TZwpLockedPointerV1(AData^.PascalObject)); end; procedure zwp_locked_pointer_v1_unlocked_Intf(AData: PWLUserData; Azwp_locked_pointer_v1: Pzwp_locked_pointer_v1); cdecl; var AIntf: IZwpLockedPointerV1Listener; begin if AData = nil then Exit; AIntf := IZwpLockedPointerV1Listener(AData^.ListenerUserData); AIntf.zwp_locked_pointer_v1_unlocked(TZwpLockedPointerV1(AData^.PascalObject)); end; procedure zwp_confined_pointer_v1_confined_Intf(AData: PWLUserData; Azwp_confined_pointer_v1: Pzwp_confined_pointer_v1); cdecl; var AIntf: IZwpConfinedPointerV1Listener; begin if AData = nil then Exit; AIntf := IZwpConfinedPointerV1Listener(AData^.ListenerUserData); AIntf.zwp_confined_pointer_v1_confined(TZwpConfinedPointerV1(AData^.PascalObject)); end; procedure zwp_confined_pointer_v1_unconfined_Intf(AData: PWLUserData; Azwp_confined_pointer_v1: Pzwp_confined_pointer_v1); cdecl; var AIntf: IZwpConfinedPointerV1Listener; begin if AData = nil then Exit; AIntf := IZwpConfinedPointerV1Listener(AData^.ListenerUserData); AIntf.zwp_confined_pointer_v1_unconfined(TZwpConfinedPointerV1(AData^.PascalObject)); end; const pInterfaces: array[0..19] of Pwl_interface = ( (nil), (nil), (nil), (nil), (nil), (nil), (nil), (nil), (@zwp_locked_pointer_v1_interface), (@wl_surface_interface), (@wl_pointer_interface), (@wl_region_interface), (nil), (@zwp_confined_pointer_v1_interface), (@wl_surface_interface), (@wl_pointer_interface), (@wl_region_interface), (nil), (@wl_region_interface), (@wl_region_interface) ); zwp_pointer_constraints_v1_requests: array[0..2] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'lock_pointer'; signature: 'noo?ou'; types: @pInterfaces[8]), (name: 'confine_pointer'; signature: 'noo?ou'; types: @pInterfaces[13]) ); zwp_locked_pointer_v1_requests: array[0..2] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'set_cursor_position_hint'; signature: 'ff'; types: @pInterfaces[0]), (name: 'set_region'; signature: '?o'; types: @pInterfaces[18]) ); zwp_locked_pointer_v1_events: array[0..1] of Twl_message = ( (name: 'locked'; signature: ''; types: @pInterfaces[0]), (name: 'unlocked'; signature: ''; types: @pInterfaces[0]) ); zwp_confined_pointer_v1_requests: array[0..1] of Twl_message = ( (name: 'destroy'; signature: ''; types: @pInterfaces[0]), (name: 'set_region'; signature: '?o'; types: @pInterfaces[19]) ); zwp_confined_pointer_v1_events: array[0..1] of Twl_message = ( (name: 'confined'; signature: ''; types: @pInterfaces[0]), (name: 'unconfined'; signature: ''; types: @pInterfaces[0]) ); initialization Pointer(vIntf_zwp_locked_pointer_v1_Listener.locked) := @zwp_locked_pointer_v1_locked_Intf; Pointer(vIntf_zwp_locked_pointer_v1_Listener.unlocked) := @zwp_locked_pointer_v1_unlocked_Intf; Pointer(vIntf_zwp_confined_pointer_v1_Listener.confined) := @zwp_confined_pointer_v1_confined_Intf; Pointer(vIntf_zwp_confined_pointer_v1_Listener.unconfined) := @zwp_confined_pointer_v1_unconfined_Intf; zwp_pointer_constraints_v1_interface.name := 'zwp_pointer_constraints_v1'; zwp_pointer_constraints_v1_interface.version := 1; zwp_pointer_constraints_v1_interface.method_count := 3; zwp_pointer_constraints_v1_interface.methods := @zwp_pointer_constraints_v1_requests; zwp_pointer_constraints_v1_interface.event_count := 0; zwp_pointer_constraints_v1_interface.events := nil; zwp_locked_pointer_v1_interface.name := 'zwp_locked_pointer_v1'; zwp_locked_pointer_v1_interface.version := 1; zwp_locked_pointer_v1_interface.method_count := 3; zwp_locked_pointer_v1_interface.methods := @zwp_locked_pointer_v1_requests; zwp_locked_pointer_v1_interface.event_count := 2; zwp_locked_pointer_v1_interface.events := @zwp_locked_pointer_v1_events; zwp_confined_pointer_v1_interface.name := 'zwp_confined_pointer_v1'; zwp_confined_pointer_v1_interface.version := 1; zwp_confined_pointer_v1_interface.method_count := 2; zwp_confined_pointer_v1_interface.methods := @zwp_confined_pointer_v1_requests; zwp_confined_pointer_v1_interface.event_count := 2; zwp_confined_pointer_v1_interface.events := @zwp_confined_pointer_v1_events; end.
unit MainFrm; interface uses System.Generics.Collections, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Button1: TButton; GroupBox1: TGroupBox; Label1: TLabel; edtName: TEdit; Label2: TLabel; edtAge: TEdit; Memo1: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; TPerson = record Name: string[20]; Age: Integer; end; var Form1: TForm1; const SOURCE_FILE = 'D:\Test\demo1.txt'; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var ReadDateFile, WriteDateFile: file of TPerson; var Person: TPerson; var Persons: TList<TPerson>; var i: Integer; begin Persons := TList<TPerson>.Create; //构造数据 //文件不存在 if not FileExists(SOURCE_FILE) then begin try AssignFile(WriteDateFile, SOURCE_FILE); Rewrite(WriteDateFile); Person.Name := edtName.Text; Person.Age := StrToInt(edtAge.Text); Write(WriteDateFile, Person); finally CloseFile(WriteDateFile); end; exit; end; try //先读 AssignFile(ReadDateFile, SOURCE_FILE); Reset(ReadDateFile); //循环读取所有数据 while not Eof(ReadDateFile) do begin Read(ReadDateFile, Person); Persons.Add(Person); end; //在原来数据的基础上添加上我们新的数据 Person.Name := edtName.Text; Person.Age := StrToInt(edtAge.Text); Persons.Add(Person); //写入 AssignFile(WriteDateFile, SOURCE_FILE); Rewrite(WriteDateFile); for i := 0 to (Persons.Count - 1) do begin Person := Persons[i]; Write(WriteDateFile, Person); end; finally CloseFile(ReadDateFile); CloseFile(WriteDateFile); end; end; procedure TForm1.Button2Click(Sender: TObject); var DataFile: file of TPerson; var Person: TPerson; begin Memo1.Clear; try AssignFile(DataFile, SOURCE_FILE); Reset(DataFile); //循环读取 while not Eof(DataFile) do begin Read(DataFile, Person); Memo1.Lines.Add('姓名:' + Person.Name + ',年龄:' + IntToStr(Person.Age)); end; finally CloseFile(DataFile); end; end; end.
unit MFichas.Model.Permissoes; interface uses System.SysUtils, System.Generics.Collections, MFichas.Model.Permissoes.Interfaces, MFichas.Model.Conexao.Interfaces, MFichas.Model.Conexao.Factory, MFichas.Model.Entidade.USUARIOPERMISSOES, MFichas.Controller.Types, ORMBR.Container.ObjectSet, ORMBR.Container.ObjectSet.Interfaces; type TModelPermissoes = class(TInterfacedObject, iModelPermissoes) private FList : TDictionary<String ,TTypeTipoUsuario>; FListPermissoes: TObjectList<TUSUARIOPERMISSOES>; FConn : iModelConexaoSQL; FDAO : IContainerObjectSet<TUSUARIOPERMISSOES>; class var FInstance: iModelPermissoes; constructor Create; procedure PreencherListaDePermissoes; public destructor Destroy; override; class function New: iModelPermissoes; function ListaDePermissoes: iModelPermissoesLista; function EditarPermissoes : iModelPermissoesEditar; function DAO : iContainerObjectSet<TUSUARIOPERMISSOES>; end; implementation { TModelPermissoes } uses MFichas.Model.Permissoes.Metodos.Lista, MFichas.Model.Permissoes.Metodos.Editar; constructor TModelPermissoes.Create; begin FList := TDictionary<String ,TTypeTipoUsuario>.Create; FConn := TModelConexaoFactory.New.ConexaoSQL; FDAO := TContainerObjectSet<TUSUARIOPERMISSOES>.Create(FConn.Conn); PreencherListaDePermissoes; end; function TModelPermissoes.DAO: iContainerObjectSet<TUSUARIOPERMISSOES>; begin Result := FDAO; end; destructor TModelPermissoes.Destroy; begin {$IFDEF MSWINDOWS} FreeAndNil(FList); if Assigned(FListPermissoes) then FreeAndNil(FListPermissoes); {$ELSE} FList.Free; FList.DisposeOf; if Assigned(FListPermissoes) then begin FListPermissoes.Free; FListPermissoes.DisposeOf; end; {$ENDIF} inherited; end; function TModelPermissoes.EditarPermissoes: iModelPermissoesEditar; begin Result := TModelPermissoesMetodosEditar.New(Self, FList); end; function TModelPermissoes.ListaDePermissoes: iModelPermissoesLista; begin Result := TModelPermissoesMetodosLista.New(Self, FList); end; class function TModelPermissoes.New: iModelPermissoes; begin if not Assigned(FInstance) then FInstance := Self.Create; Result := FInstance; end; procedure TModelPermissoes.PreencherListaDePermissoes; var I: Integer; begin FListPermissoes := FDAO.Find; for I := 0 to Pred(FListPermissoes.Count) do begin FList.Add( FListPermissoes[I].DESCRICAO, TTypeTipoUsuario(FListPermissoes[I].PERMISSAO) ); end; end; end.
unit CornerDet; {=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] 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; function CornerResponse(const Mat:T2DIntArray; GaussDev:Single; KSize:Integer): T2DFloatArray; function FindCornerPoints(const Mat:T2DIntArray; GaussDev:Single; KSize:Integer; Thresh:Single; Footprint:Integer): TPointArray; function FindCornerMidPoints(const Mat:T2DIntArray; GaussDev:Single; KSize:Integer; Thresh:Single; MinDist: Integer): TPointArray; //----------------------------------------------------------------------- implementation uses SysUtils, Imaging, PointList, MatrixMath, MatrixOps, PointTools, Math; (*=============================================================================| Convert Matrix to byte values (0-255) - pixel-values represents color-intensity |=============================================================================*) function Intesity(const Mat:T2DIntArray): T2DIntArray; var x,y,W,H,color:Integer; begin W := High(Mat[0]); H := High(Mat); SetLength(Result, H+1, W+1); for y:=0 to H do for x:=0 to W do begin color := Mat[y][x]; //Result[y][x] := ((Color and $FF) + ((Color shr 8) and $FF) + ((Color shr 16) and $FF)) div 3; Result[y][x] := Round((0.299 * (Color and $FF)) + (0.587 * ((Color shr 8) and $FF)) + (0.114 * ((Color shr 16) and $FF))); end; end; (*=============================================================================| 2D Convolution |=============================================================================*) function SobelConvolve(const Source:T2DIntArray; Mask:T2DIntArray): T2DIntArray; var W,H,x,y: Integer; begin W := High(source[0]); H := High(source); SetLength(Result, H+1,W+1); for y:=0 to H do Move(Source[y][0],Result[y][0], (W+1)*SizeOf(Int32)); W := W-1; H := H-1; for y:=1 to H do for x:=1 to W do Result[y,x] := ( (mask[0][0] * Source[y-1][x-1]) + (mask[1][0] * Source[y-1][x+0]) + (mask[2][0] * Source[y-1][x+1]) + (mask[0][1] * Source[y][x-1]) + (mask[1][1] * Source[y][x]) + (mask[2][1] * Source[y][x+1]) + (mask[0][2] * Source[y+1][x-1]) + (mask[1][2] * Source[y+1][x+0]) + (mask[2][2] * Source[y+1][x+1]) ); end; (*=============================================================================| Sobel operator |=============================================================================*) function Sobel(const Mat:T2DIntArray; Axis:Char): T2DIntArray; var xmask, ymask: T2DIntArray; begin SetLength(xmask, 3,3); xmask[0,0] := -1; xmask[0,1] := 0; xmask[0,2] := 1; xmask[1,0] := -2; xmask[1,1] := 0; xmask[1,2] := 2; xmask[2,0] := -1; xmask[2,1] := 0; xmask[2,2] := 1; SetLength(ymask, 3,3); ymask[0,0] := -1; ymask[0,1] := -2; ymask[0,2] := -1; ymask[1,0] := 0; ymask[1,1] := 0; ymask[1,2] := 0; ymask[2,0] := 1; ymask[2,1] := 2; ymask[2,2] := 1; if axis = 'y' then Result := SobelConvolve(Mat,ymask); if axis = 'x' then Result := SobelConvolve(Mat,xmask); end; (*=============================================================================| Gassuian blur and related functions |=============================================================================*) function GaussianBlur(ImArr:T2DIntArray; Radius:Int32; Sigma:Single): T2DIntArray; var x,y,wid,hei,xx,yy,offset,block:Int32; gauss:Single; tmp:T2DFloatArray; kernel:TFloatArray; begin block := Radius*2; Wid := High(ImArr[0]); Hei := High(ImArr); SetLength(Result, hei+1,wid+1); SetLength(tmp, hei+1,wid+1); kernel := GaussKernel1D(Radius, Sigma); // Compute our gaussian 1d kernel // y direction for y:=0 to hei do for x:=0 to wid do begin gauss := 0.0; for offset:=0 to block do begin xx := (x-Radius)+offset; if (xx < 0) then xx := 0 else if (xx > wid) then xx := wid; gauss += ImArr[y, xx] * kernel[offset]; end; tmp[y,x] := gauss; end; // x direction for y:=0 to hei do for x:=0 to wid do begin gauss := 0.0; for offset:=0 to block do begin yy := (y-Radius)+offset; if (yy < 0) then yy := 0 else if (yy > hei) then yy := hei; gauss += tmp[yy, x] * kernel[offset]; end; Result[y,x] := Round(gauss); end; end; function BoxBlur3(Mat:T2DIntArray): T2DFloatArray; var W,H,x,y:Int32; begin W := High(Mat[0]); H := High(Mat); SetLength(Result, H+1,W+1); for y:=0 to H do Move(Mat[y][0],Result[y][0], (W+1)*SizeOf(Int32)); Dec(W); Dec(H); for y:=1 to H do for x:=1 to W do Result[y][x] := ( Mat[y-1][x] + Mat[y+1][x] + Mat[y][x-1] + Mat[y][x+1] + Mat[y-1][x-1] + Mat[y+1][x+1] + Mat[y-1][x+1] + Mat[y+1][x-1] + Mat[y][x]) div 9; end; (*=============================================================================| Computing harris response of grayscale (0-255) matrix. |=============================================================================*) function CornerResponse(const Mat:T2DIntArray; GaussDev:Single; KSize:Integer): T2DFloatArray; var blur,imx,imy:T2DIntArray; wxx,wyy,wxy: T2DFloatArray; begin blur := GaussianBlur(Intesity(Mat), KSize, GaussDev); imx := Sobel(blur, 'x'); imy := Sobel(blur, 'y'); (*Wxx := ToSingle(GaussianBlur(imx*imx, 3.0, 1)); Wyy := ToSingle(GaussianBlur(imy*imy, 3.0, 1)); Wxy := ToSingle(GaussianBlur(imx*imy, 3.0, 1));*) Wxx := BoxBlur3(imx*imx); Wyy := BoxBlur3(imy*imy); Wxy := BoxBlur3(imx*imy); Result := ((Wxx*Wyy) - (Wxy*Wxy)) / (Wxx+Wyy); end; (*=============================================================================| Tries to extract the peak points of the neighborhood covering MinDist. |=============================================================================*) function FindCornerPoints(const Mat:T2DIntArray; GaussDev:Single; KSize:Integer; Thresh:Single; Footprint:Integer): TPointArray; var w,h,i,j,x,y,k: Integer; CurrentMax: Single; Response: T2DFloatArray; begin Response := CornerResponse(Mat, GaussDev, KSize); W := High(Response[0]); H := High(Response); SetLength(Result, (W+1)*(H+1)); Response := Normalize(Response, 0, 1.0); k := 0; for y:=footprint to H-footprint do for x:=footprint to W-footprint do begin CurrentMax := Response[y][x]; for i :=-footprint to footprint do for j:=-footprint to footprint do if (Response[y + i][x + j] > currentMax) then begin CurrentMax := 0; Break; end; if (CurrentMax > Thresh) then begin Result[k] := CoreTypes.Point(x, y); Inc(k); end; end; SetLength(Result, k); SetLength(Response, 0); end; (*=============================================================================| Clusters each group of points and returns the mean point of that group. |=============================================================================*) function FindCornerMidPoints(const Mat:T2DIntArray; GaussDev:Single; KSize:Integer; Thresh:Single; MinDist: Integer): TPointArray; var W,H,x,y:Integer; aMax,aTresh:Single; Mat2:T2DFloatArray; TPL:TPointList; ATPA:T2DPointArray; begin Mat2 := CornerResponse(Mat, GaussDev, KSize); aMax := Mat2[0][0]; W := High(Mat2[0]); H := High(Mat2); for y:=0 to H do for x:=0 to W do if Mat2[y][x] > aMax then aMax := Mat2[y][x]; aTresh := aMax * Thresh; TPL.Init(); for y:=0 to H do for x:=0 to W do if (Mat2[y][x] > aTresh) then TPL.Append(x,y); ATPA := ClusterTPA(TPL.Clone(), MinDist, True); SetLength(Result, Length(ATPA)); for x:=0 to High(ATPA) do Result[x] := TPACenter(ATPA[x], CA_MEAN, False); TPL.Free(); end; end.
unit hls_rvb; interface uses windows,wutil,SysUtils; type Thls = record h,l,s:word; end; {record Thls} {HLS->RGB} {ih:0..360, il:0..100, is:0..100 -> tcolorref} procedure ihls_to_tcolorref(ih,il,isat:integer; var acolor:tcolorref); {h:0..360, l:0..1, s:0..1 -> tcolorref} procedure hls_to_tcolorref(h,l,s:real; var acolor:tcolorref); {h:0..360, l:0..1, s:0..1 -> r:0..1, g:0..1, b:0..1} procedure HLS_to_RGB(h,l,s:real; var r,g,b:real); {h:0..360, l:0..1, s:0..1 -> cyan:0..1, magenta:0..1, jaune:0..1} procedure HLS_to_CMY(hue,Lumiere,saturation:real; var cyan,magenta,jaune:real); {h:0..360, l:0..1, s:0..1 -> r:0..1, g:0..1, b:0..1} function Get_HLS_RGB(h,l,s:real):TColorref; {RGB->HLS} {tcolorref -> h:0..360, l:0..1, s:0..1} procedure tcolorref_to_hls(acolor:tcolorref; var h,l,s:real); {r:0..1, g:0..1, b:0..1 -> h:0..360, l:0..1, s:0..1} procedure RGB_to_HLS(r,g,b:real; var h,l,s:real); function get_lumiere_from_tcolor(une_couleur:TColorref):real; {RGB->CMYB en pourcent 0.0 - 1.0} procedure RGB_to_CMYB(RGB_long:TcolorRef; VAR Real_Cyan,Real_Magenta,Real_Yellow,Real_black:real); {CMYB->RGB en pourcent 0.0 - 1.0} procedure CMYB_to_RGB(Real_Cyan,Real_Magenta,Real_Yellow,Real_black:real; var RGB_long:TcolorRef); procedure RGB_to_PChar(RGB_long:TcolorRef; Out_apc:pchar); implementation function rmax(a,b:real):real; begin if a>b then rmax:=a else rmax:=b; end; function rmin(a,b:real):real; begin if a<b then rmin:=a else rmin:=b; end; {ih:0..360, il:0..100, is:0..100 -> tcolorref} procedure ihls_to_tcolorref(ih,il,isat:integer; var acolor:tcolorref); begin hls_to_tcolorref(ih,(1.0*il)/100,(1.0*isat)/100,acolor); end; {ihls_to_tcolorref} {h:0..360, l:0..1, s:0..1 -> tcolorref} procedure hls_to_tcolorref(h,l,s:real; var acolor:tcolorref); var r,g,b:real; begin if h>=360 then h:=round(h) mod 360; HLS_to_RGB(h,l,s,r,g,b); acolor:=RGB(round(R*255),round(G*255),round(B*255)); end; {ihls_to_tcolorref} function Get_HLS_RGB(h,l,s:real):TColorref; var r,g,b:real; begin while h>360 do h:=h-360; HLS_to_RGB(h,l,s,r,g,b); Get_HLS_RGB:=RGB(round(R*255),round(G*255),round(B*255)); end; procedure HLS_to_CMY(hue,Lumiere,saturation:real; var cyan,magenta,jaune:real); const espace = 360; var teinte:integer; begin cyan:=hue/espace*Lumiere; teinte:=round(hue+120); teinte:=teinte mod 360; magenta:=teinte/espace*Lumiere; teinte:=round(hue+240); teinte:=teinte mod 360; jaune:=teinte/espace*Lumiere; if false then begin if hue<120 then begin cyan:=hue/120; magenta:=hue/(2*120); jaune:=0; end else if hue<240 then begin cyan:=(hue-120)/(2*120); magenta:=(hue-120)/120; jaune:=0; end else begin cyan:=0; magenta:=(hue-240)/(2*120); jaune:=(hue-240)/120; end; end; end; (* code C a partir d'une méthode découverte à la bibliothèque de la vilette by db*) procedure HLS_to_RGB(h,l,s:real; var r,g,b:real); var v,m,sv,fract,vsf,mid1,mid2:real; sextant:integer; begin if h=360 then h:=0 else h:=h/360; if l<=0.5 then v:=l*(1.0+s) else v:=l+s-l*s; if v<=0.0 then begin r:=0.0; g:=0.0; b:=0.0; end else begin m:=l+l-v; sv:=(v-m)/v; h:=h*6.0; sextant:=trunc(h); fract:=h-sextant; vsf:=v*sv*fract; mid1:=m+vsf; mid2:=v-vsf; case sextant of 0:begin r:=v; g:=mid1; b:=m end; 1:begin r:=mid2; g:=v; b:=m end; 2:begin r:=m; g:=v; b:=mid1 end; 3:begin r:=m; g:=mid2; b:=v end; 4:begin r:=mid1; g:=m; b:=v end; 5:begin r:=v; g:=m; b:=mid2 end; end; {case sextant} end; end; {HLS_to_RGB} (* code mixte pascal procedure HLS_to_RGB(hue,value,sat:real; var r,g,b:real); var MinCol:real; begin MinCol:=value*(1.0-sat); if hue<=120.0 then begin B:=MinCol; if hue<=60.0 then begin R:=Value; G:=MinCol+Hue*(Value-MinCol)/(120.0-Hue); end else begin G:=Value; R:=MinCol+(120.0-Hue)*(Value-MinCol)/Hue; end end else if hue<=240.0 then begin R:=MinCol; if hue<=180.0 then begin G:=Value; B:=MinCol+(Hue-120.0)*(Value-MinCol)/(240.0-Hue); end else begin B:=Value; G:=MinCol+(240.0-Hue)*(Value-MinCol)/(Hue-120.0); end end else begin G:=MinCol; if hue<=300.0 then begin B:=Value; R:=MinCol+(Hue-240.0)*(Value-MinCol)/(360.0-Hue); end else begin R:=Value; B:=MinCol+(360.0-Hue)*(Value-MinCol)/(Hue-240.0); end end; end; {HLS_to_RGB} *) (* code pascal procedure HLS_to_RGB(h,l,s:real; var r,g,b:real); var mini,maxi:real; function val(mini,maxi,nuance:real):real; begin if nuance<0 then nuance:=nuance+360; if nuance<60 then val:=mini+(maxi-mini)*nuance/60 else if nuance<180 then val:=maxi else if nuance<240 then val:=mini+(maxi-mini)*(240-nuance)/60 else val:=mini; end; begin {HLS_to_RGB} if l<=0.5 then maxi:=l*(1+s) else maxi:=l+s+l*s; mini:=2*l-maxi; r:=val(mini,maxi,h); g:=val(mini,maxi,h-120); b:=val(mini,maxi,h-240); end; {HLS_to_RGB} *) {tcolorref -> h:0..360, l:0..1, s:0..1} procedure tcolorref_to_hls(acolor:tcolorref; var h,l,s:real); begin RGB_to_HLS( 1.0*getrvalue(acolor)/255, 1.0*getgvalue(acolor)/255, 1.0*getbvalue(acolor)/255, h,l,s); end; {r:0..1, g:0..1, b:0..1 -> h:0..360, l:0..1, s:0..1} procedure RGB_to_HLS(r,g,b:real; var h,l,s:real); var v,m,vm,r2,g2,b2:real; begin v:=rmax(rmax(r,g),b); m:=rmin(rmin(r,g),b); l:=(m+v) / 2.0; h:=0; s:=0; if l<=0 then begin l:=0; exit; end; vm:=v-m; s:=vm; if s>0.0 then begin if l<0.5 then s:=s/(v+m) else s:=s/(2.0-v-m); end else exit; r2:=(v-r)/vm; g2:=(v-g)/vm; b2:=(v-b)/vm; if r=v then begin if g=m then h:=5.0+b2 else h:=1.0-g2 end else if g=v then begin if b=m then h:=1.0+r2 else h:=3.0-b2 end else begin if r=m then h:=3.0+g2 else h:=5.0-r2 end; h:=round(h*60) mod 360; {h:=h/6; h:=h*360;} end; {RGB_to_HLS} function get_lumiere_from_tcolor(une_couleur:TColorref):real; var hue,lum,sat:real; begin hls_rvb.tcolorref_to_hls(une_couleur,hue,lum,sat); get_lumiere_from_tcolor:=lum; end; (* procedure RGB_to_HLS(r,g,b:real; var h,l,s:real); var rr,gg,bb,mini,maxi,diff,tot:real; begin rr:=r; gg:=g; bb:=b; maxi:=rmax(rmax(rr,gg),bb); mini:=rmin(rmin(rr,gg),bb); if mini<>maxi then begin diff:=maxi-mini; rr:=(maxi-rr)/diff; gg:=(maxi-gg)/diff; bb:=(maxi-bb)/diff; end; tot:=maxi+mini; l:=tot/2; if maxi=mini then s:=0 else if l<=0.5 then s:=diff/tot else s:=diff/(2-tot); if s=0 then h:=0 else if r=maxi then h:=2+bb-gg else if g=maxi then h:=4+rr-bb else h:=6+gg-rr; h:=round(h*60) mod 360; end; {RGB_to_HLS} *) {RGB->CMYB en pourcent} procedure RGB_to_CMYB(RGB_long:TcolorRef; VAR Real_Cyan,Real_Magenta,Real_Yellow,Real_black:real); var rouge,vert,bleu:real; begin rouge:=GetRvalue(RGB_long); vert:=GetGvalue(RGB_long); bleu:=GetBvalue(RGB_long); Real_Cyan:=1.0-(rouge/255); Real_Magenta:=1.0-(vert/255); Real_Yellow:=1.0-(bleu/255); Real_black:=wutil.Real_min(wutil.Real_min(Real_Cyan,Real_Magenta),Real_Yellow); Real_Cyan:=Real_Cyan-Real_black; Real_Magenta:=Real_Magenta-Real_black; Real_Yellow:=Real_Yellow-Real_black; end; {RGB_to_CMYB} procedure CMYB_to_RGB(Real_Cyan,Real_Magenta,Real_Yellow,Real_black:real; var RGB_long:TcolorRef); begin Real_Cyan:= wutil.Real_min(1.0,Real_Cyan+Real_black); Real_Magenta:= wutil.Real_min(1.0,Real_Magenta+Real_black); Real_Yellow:= wutil.Real_min(1.0,Real_Yellow+Real_black); RGB_long:=rgb( round((1.0-Real_Cyan)*255), round((1.0-Real_Magenta)*255), round((1.0-Real_Yellow)*255)); end; {CMYB_to_RGB} procedure RGB_to_PChar(RGB_long:TcolorRef; Out_apc:pchar); var str:pc255; const k_2_blanc=' '; {$ifdef dis_neo} k_R='R '; k_V='G '; k_B='B '; {$else} k_R='R '; k_V='V '; k_B='B '; {$endif} begin wutil.Inttopchar(GetRValue(RGB_long),Str); Strcat(Strcat(Strcopy(Out_apc,k_R),Str),k_2_blanc); wutil.Inttopchar(GetGValue(RGB_long),Str); Strcat(Strcat(Strcat(Out_apc,k_V),Str),k_2_blanc); wutil.Inttopchar(GetBValue(RGB_long),Str); Strcat(Strcat(Strcat(Strcat(Out_apc,k_B),Str),k_2_blanc),k_2_blanc); end; (* var r,g,b:real; var h,l,s:real; begin writeln; writeln('0,0,1'); RGB_to_HLS(0,0,1,h,l,s); writeln('h=',h:3:2); writeln('l=',l:3:2); writeln('s=',s:3:2); writeln; writeln('HLS_to_RGB'); HLS_to_RGB(h,l,s,r,g,b); writeln('r=',r:3:2); writeln('g=',g:3:2); writeln('b=',b:3:2); *) end.
unit ULinkedInDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.TMSCloudBase, FMX.TMSCloudLinkedIn, FMX.TabControl, FMX.Layouts, FMX.ListBox, FMX.Objects, FMX.TMSCloudImage, FMX.Edit, FMX.Memo, IOUtils, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomLinkedIn; type TForm82 = class(TForm) ToolBar1: TToolBar; Button1: TButton; Button2: TButton; TMSFMXCloudLinkedIn1: TTMSFMXCloudLinkedIn; TMSFMXCloudImage1: TTMSFMXCloudImage; lbConnections: TListBox; Button3: TButton; Title: TEdit; Image: TEdit; Link: TEdit; Descr: TEdit; Button5: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Button4: TButton; Label6: TLabel; Edit1: TEdit; Button6: TButton; Label5: TLabel; Memo1: TMemo; Label7: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure TMSFMXCloudLinkedIn1ReceivedAccessToken(Sender: TObject); procedure Button6Click(Sender: TObject); procedure lbConnectionsChange(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } Connected: boolean; resultpage: integer; resultcount: integer; pagesize: integer; procedure ToggleControls; procedure DisplayProfile(Profile: TLinkedInProfile); end; var Form82: TForm82; implementation {$R *.fmx} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // LinkedInAppkey = 'xxxxxxxxx'; // LinkedInAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm82.Button1Click(Sender: TObject); var acc: boolean; begin TMSFMXCloudLinkedIn1.App.Key := LinkedInAppKey; TMSFMXCloudLinkedIn1.App.Secret := LinkedInAppSecret; if TMSFMXCloudLinkedIn1.App.Key <> '' then begin TMSFMXCloudLinkedIn1.PersistTokens.Key := TPath.GetDocumentsPath + '/linkedin.ini'; TMSFMXCloudLinkedIn1.PersistTokens.Section := 'tokens'; TMSFMXCloudLinkedIn1.LoadTokens; acc := TMSFMXCloudLinkedIn1.TestTokens; if not acc then begin TMSFMXCloudLinkedIn1.RefreshAccess; TMSFMXCloudLinkedIn1.DoAuth; end else begin connected := true; ToggleControls; end; end else ShowMessage('Please provide a valid application ID for the client component'); end; procedure TForm82.Button2Click(Sender: TObject); begin TMSFMXCloudLinkedIn1.ClearTokens; Connected := false; ToggleControls; end; procedure TForm82.Button3Click(Sender: TObject); var i: integer; begin TMSFMXCloudLinkedIn1.GetConnections; lbConnections.Items.Clear; for i := 0 to TMSFMXCloudLinkedIn1.Connections.Count - 1 do lbConnections.Items.AddObject(TMSFMXCloudLinkedIn1.Connections.Items[i].Profile.FirstName + ' ' + TMSFMXCloudLinkedIn1.Connections.Items[i].Profile.LastName, TMSFMXCloudLinkedIn1.Connections.Items[i]); end; procedure TForm82.Button4Click(Sender: TObject); begin TMSFMXCloudLinkedIn1.Activity(Edit1.Text) end; procedure TForm82.Button5Click(Sender: TObject); begin TMSFMXCloudLinkedIn1.Share(Title.Text, Descr.Text, Link.Text, Image.Text); end; procedure TForm82.Button6Click(Sender: TObject); var lp: TLinkedInProfile; begin TMSFMXCloudLinkedIn1.GetDefaultProfile; lp := TMSFMXCloudLinkedIn1.DefaultProfile; DisplayProfile(lp); TMSFMXCloudImage1.URL := lp.PictureURL; end; procedure TForm82.DisplayProfile(Profile: TLinkedInProfile); begin memo1.Lines.Text := 'FormattedName: ' + Profile.FormattedName + #13 + 'Headline: ' + Profile.Headline + #13 + 'Summary: ' + Profile.Summary + #13 + 'Email: ' + Profile.EmailAddress + #13 + 'PublicProfileURL: ' + Profile.PublicProfileURL + #13 + 'Location: ' + Profile.Location + #13 + 'CountryCode: ' + Profile.CountryCode; end; procedure TForm82.FormCreate(Sender: TObject); begin Connected := False; ToggleControls; end; procedure TForm82.lbConnectionsChange(Sender: TObject); var lp: TLinkedInProfile; cn: TLinkedInConnection; begin if Assigned(lbConnections.Selected) then begin cn := (lbConnections.Selected.Data as TLinkedInConnection); lp := TMSFMXCloudLinkedIn1.GetProfile(cn.Profile.ID); TMSFMXCloudImage1.URL := lp.PictureURL; DisplayProfile(lp); end; end; procedure TForm82.TMSFMXCloudLinkedIn1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudLinkedIn1.SaveTokens; Connected := true; ToggleControls; end; procedure TForm82.ToggleControls; begin Button1.Enabled := not Connected; Button2.Enabled := Connected; Button3.Enabled := Connected; Button4.Enabled := Connected; Button5.Enabled := Connected; Button6.Enabled := Connected; Edit1.Enabled := Connected; Title.Enabled := Connected; Link.Enabled := Connected; Memo1.Enabled := Connected; Image.Enabled := Connected; Descr.Enabled := Connected; lbConnections.Enabled := Connected; end; end.
unit BrowseFolders; // Copyright (c) 1997 Jorge Romero Gomez, Merchise. interface uses Windows, ShellAPI, ShlObj, SysUtils, Classes, Forms, PidlPath; function BrowseNetworkFolder( const BrowseTitle : string ) : string; function BrowseLocalFolder( const BrowseTitle : string ) : string; function BrowseFolder( const BrowseTitle : string ) : string; function BrowseFolderDialog( const BrowseTitle : string; RootFolder : PItemIDList; Options : integer ) : string; type TBrowseCallbackProc = function ( WinHandle : HWND; uMsg : uint; Param, lpData : LPARAM ) : integer; stdcall; // In case you need to specify a parent or a callback function: function BrowseFolderDialogEx( ParentHandle : HWND; const BrowseTitle : string; RootFolder : PItemIDList; Options : integer; Callback : TBrowseCallbackProc; lpData : uint ) : string; function BrowseNetworkFolderEx( ParentHandle : HWND; const BrowseTitle : string; Callback : TBrowseCallbackProc; lpData : uint ) : string; function BrowseLocalFolderEx( ParentHandle : HWND; const BrowseTitle : string; Callback : TBrowseCallbackProc; lpData : uint ) : string; function BrowseFolderEx( ParentHandle : HWND; const BrowseTitle : string; Callback : TBrowseCallbackProc; lpData : uint ) : string; implementation function BrowseFolderDialog( const BrowseTitle : string; RootFolder : PItemIDList; Options : integer ) : string; begin Result := BrowseFolderDialogEx( Screen.ActiveForm.Handle, BrowseTitle, RootFolder, Options, nil, 0 ); end; function BrowseNetworkFolder( const BrowseTitle : string ) : string; begin Result := BrowseNetworkFolderEx( Screen.ActiveForm.Handle, BrowseTitle, nil, 0 ); end; function BrowseLocalFolder( const BrowseTitle : string ) : string; begin Result := BrowseLocalFolderEx( Screen.ActiveForm.Handle, BrowseTitle, nil, 0 ); end; function BrowseFolder( const BrowseTitle : string ) : string; begin Result := BrowseFolderEx( Screen.ActiveForm.Handle, BrowseTitle, nil, 0 ); end; function BrowseFolderDialogEx( ParentHandle : HWND; const BrowseTitle : string; RootFolder : PItemIDList; Options : integer; Callback : TBrowseCallbackProc; lpData : uint ) : string; var BrowseInfo : TBrowseInfo; SelName : array [0..MAX_PATH] of char; begin with BrowseInfo do begin hwndOwner := ParentHandle; pidlRoot := RootFolder; pszDisplayName := SelName; lpszTitle := pchar( BrowseTitle ); ulFlags := Options; lpfn := Callback; lParam := lpData; end; Result := PidlToFilePath( SHBrowseForFolder( BrowseInfo ) ); end; function BrowseNetworkFolderEx( ParentHandle : HWND; const BrowseTitle : string; Callback : TBrowseCallbackProc; lpData : uint ) : string; var Root : PItemIDList; begin SHGetSpecialFolderLocation( ParentHandle, CSIDL_NETWORK, Root ); Result := BrowseFolderDialogEx( ParentHandle, BrowseTitle, Root, BIF_RETURNONLYFSDIRS, Callback, lpData ); end; function BrowseLocalFolderEx( ParentHandle : HWND; const BrowseTitle : string; Callback : TBrowseCallbackProc; lpData : uint ) : string; var Root : PItemIDList; begin SHGetSpecialFolderLocation( ParentHandle, CSIDL_DRIVES, Root ); Result := BrowseFolderDialogEx( ParentHandle, BrowseTitle, Root, BIF_RETURNONLYFSDIRS, Callback, lpData ); end; function BrowseFolderEx( ParentHandle : HWND; const BrowseTitle : string; Callback : TBrowseCallbackProc; lpData : uint ) : string; begin Result := BrowseFolderDialogEx( ParentHandle, BrowseTitle, nil, BIF_RETURNONLYFSDIRS, Callback, lpData ); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpAsn1EncodableVector; {$I ..\Include\CryptoLib.inc} interface uses Generics.Collections, ClpCryptoLibTypes, ClpIProxiedInterface, ClpIAsn1EncodableVector; type TAsn1EncodableVector = class(TInterfacedObject, IAsn1EncodableVector) strict private var Flist: TList<IAsn1Encodable>; function GetCount: Int32; function GetSelf(Index: Int32): IAsn1Encodable; public class function FromEnumerable(const e: TList<IAsn1Encodable>) : IAsn1EncodableVector; static; constructor Create(); overload; constructor Create(const v: array of IAsn1Encodable); overload; destructor Destroy(); override; procedure Add(const objs: array of IAsn1Encodable); procedure AddOptional(const objs: array of IAsn1Encodable); property Self[Index: Int32]: IAsn1Encodable read GetSelf; default; property Count: Int32 read GetCount; function GetEnumerable: TCryptoLibGenericArray<IAsn1Encodable>; virtual; end; implementation { TAsn1EncodableVector } procedure TAsn1EncodableVector.Add(const objs: array of IAsn1Encodable); var obj: IAsn1Encodable; begin for obj in objs do begin Flist.Add(obj); end; end; procedure TAsn1EncodableVector.AddOptional(const objs: array of IAsn1Encodable); var obj: IAsn1Encodable; begin if (System.Length(objs) <> 0) then begin for obj in objs do begin if (obj <> Nil) then begin Flist.Add(obj); end; end; end; end; constructor TAsn1EncodableVector.Create(const v: array of IAsn1Encodable); begin inherited Create(); Flist := TList<IAsn1Encodable>.Create(); Add(v); end; constructor TAsn1EncodableVector.Create(); begin inherited Create(); Flist := TList<IAsn1Encodable>.Create(); end; destructor TAsn1EncodableVector.Destroy; begin Flist.Free; inherited Destroy; end; class function TAsn1EncodableVector.FromEnumerable (const e: TList<IAsn1Encodable>): IAsn1EncodableVector; var v: IAsn1EncodableVector; obj: IAsn1Encodable; begin v := TAsn1EncodableVector.Create(); for obj in e do begin v.Add(obj); end; result := v; end; function TAsn1EncodableVector.GetCount: Int32; begin result := Flist.Count; end; function TAsn1EncodableVector.GetEnumerable : TCryptoLibGenericArray<IAsn1Encodable>; begin result := Flist.ToArray; end; function TAsn1EncodableVector.GetSelf(Index: Int32): IAsn1Encodable; begin result := Flist[index]; end; end.
program a4; {This program tests the shortest path algorithm from program strategy 10.16 Below you will find a test program, and some procedure headers. You must fill in the bodies of the procedures. Do not alter the test program or type definitions in any way. You are given a constant for INFINITY, which is defined to be the same as MAXINT. This is a constant that returns the largest possible number of type integer. This assumes that you will use low edge weight values. Stick to weights less than 100 and the output will also look nicer. NOTE - always comment every single local variable you use. } {************* CONSTANTS ******************} Const MAX = 100; {This is the maximum size of graph. You can make this bigger if you want.} INFINITY = MAXINT; {Use this anywhere you need "infinity") {************* TYPE DEFINITIONS *********************} Type {The type definitions below define an adjacency matrix graph representation that stores edge weights.} GraphSize = 0..MAX; VertexNumber = 1..MAX; AdjacencyRow = Array [VertexNumber] of integer; GraphRep = Array [VertexNumber] of AdjacencyRow; {ShortestPathArray is the type for the ShortestDistance variable that returns the result of Dijkstra's algorithm} ShortestPathArray = Array [VertexNumber] of integer; {************** The Procedures and Functions ********************} {procedure minimum(a,b) pre: a and b are integers post: returns the larger of a and b. NOTE - Pascal does not have a built in minimum function. Use this one if you need it.} function minimum(a,b: integer): integer; begin if a<b then minimum := a else minimum := b end; {procedure NewGraph(G,S) pre: S is the size of graph to create. post: G should be an adjacency matrix or adjacency list that corresponds to a graph with S vertices and no edges. If using an adjacency matrix, you must initialize the entire matrix. HINT: Remember that the distance from a vertex to itself is always 0.} procedure NewGraph(var G:GraphRep; S:GraphSize); begin Writeln('*** NewGraph not implemented yet.') end; {procedure AddEdge(G,S,Origin,Terminus,Weight) pre: G is a graph representation with S vertices. Origin, Terminus, and Weight define an edge to be added to G. post: G has the specified edge added. HINT - you might want to print an error message if Origin or Terminus are bigger than S.} procedure AddEdge(var G:GraphRep; S:GraphSize; Origin:VertexNumber; Terminus: VertexNumber; Weight: integer); begin Writeln('*** AddEdge not implemented yet.') end; {procedure ShortestPath(G,S,Origin,ShortestDistance) pre: G is a graph representation with S vertices. Origin is the start vertex. post: ShortestDistance is an array containing the shortest distances from Origin to each vertex. HINT - program strategy 10.16 uses set variables. This is possible in Pascal, but you can't really use them the way you need to here. I suggest implementing the set W as an array of booleans. Initialize them all to FALSE and then each time you want to put a new vertex in the set, change the corresponding value to TRUE. You also might want to keep a count of the number of vertices in W. HINT - Watch out for the two "W" variables in 10.16. They use a big W and a small w. You can't do that in Pascal. I suggest using "w" for the small one and "BigW" for the big one. Of course you are free to use whatever variable names you want, but the closer you stick to the book, the easier it will be to mark. HINT - Comment this well!} procedure ShortestPath(var G:GraphRep; S:GraphSize; Origin: VertexNumber; var ShortestDistance: ShortestPathArray); begin Writeln('*** ShortestPath not implemented yet.') end; (**************************** IDENTIFICATION **************************) (* Change this procedure to identify yourself *) procedure IdentifyMyself; begin writeln; writeln('***** Student Name: Jane Doe'); writeln('***** Student Number: 00000000'); writeln('***** Professor Name: June Roe'); writeln('***** Course Number: CSI0000'); writeln('***** T.A. Name: John Poe'); writeln('***** Tutorial Number: 0'); writeln; end; var G: GraphRep; {G and S define the graph} S: GraphSize; E, {Counts number of edges} Weight: integer; {Weight, Origin and Terminus are } Origin, Terminus, {for User input} row, col: VertexNumber; {Row and Col are for looping {through the adjacency matrix} answer: string; {Stores users' answers to questions} ShortestPaths: ShortestPathArray; {Stores the shortest paths} begin IdentifyMyself; {INITIALIZE G} write('What size of graph do you want (maximum size=',MAX,'): '); readln(S); writeln; NewGraph(G,S); writeln('Enter the edges one by one until you are finished.'); writeln('Quit by entering a zero for the origin vertex.'); E := 0; repeat writeln; write('Origin: '); readln(Origin); if Origin > 0 then begin write('Terminus: '); readln(Terminus); write('Weight: '); readln(Weight); AddEdge(G,S,Origin,Terminus,Weight); E := E+1 end until (Origin<=0); {DISPLAY G IF REQUESTED} writeln; writeln('Your graph has ',S,' vertices and ',E,' edges.'); writeln; write('Would you like to see the adjacency matrix (y/n)' ); readln(answer); writeln; if (answer[1] = 'y') or (answer[1] = 'Y') then for row := 1 to S do begin for col := 1 to S do if G[row,col]=INFINITY then write(' INF') else write(G[row,col]:4); writeln end; writeln; {RUN SHORTEST PATH IF REQUESTED } write('Would you like to run the shortest path algorithm? (y/n)'); readln(answer); writeln; if (answer[1] = 'y') or (answer[1] = 'Y') then begin write('What is the start vertex? (1..',S,'): '); readln(Origin); writeln; ShortestPath(G,S,Origin,ShortestPaths); writeln; writeln('Shortest paths from start vertex ',Origin,' are: '); for Terminus := 1 to S do write(Terminus:5,': ',ShortestPaths[Terminus]); writeln; end; {QUIT} writeln; writeln('Bye bye') end.
unit DefineSearchDateKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы DefineSearchDate } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Search\DefineSearchDateKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "DefineSearchDateKeywordsPack" MUID: (9C20258F4DBF) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses , vtPanel , vtLabel , vtDblClickDateEdit , vtRadioButton ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , DefineSearchDate_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_DefineSearchDate = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы DefineSearchDate ---- *Пример использования*: [code] 'aControl' форма::DefineSearchDate TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_DefineSearchDate Tkw_DefineSearchDate_Control_Panel1 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола Panel1 ---- *Пример использования*: [code] контрол::Panel1 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_Panel1 Tkw_DefineSearchDate_Control_Panel1_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола Panel1 ---- *Пример использования*: [code] контрол::Panel1:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_Panel1_Push Tkw_DefineSearchDate_Control_ElLabel1 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ElLabel1 ---- *Пример использования*: [code] контрол::ElLabel1 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_ElLabel1 Tkw_DefineSearchDate_Control_ElLabel1_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ElLabel1 ---- *Пример использования*: [code] контрол::ElLabel1:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_ElLabel1_Push Tkw_DefineSearchDate_Control_ElLabel2 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ElLabel2 ---- *Пример использования*: [code] контрол::ElLabel2 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_ElLabel2 Tkw_DefineSearchDate_Control_ElLabel2_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ElLabel2 ---- *Пример использования*: [code] контрол::ElLabel2:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_ElLabel2_Push Tkw_DefineSearchDate_Control_ElLabel3 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ElLabel3 ---- *Пример использования*: [code] контрол::ElLabel3 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_ElLabel3 Tkw_DefineSearchDate_Control_ElLabel3_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ElLabel3 ---- *Пример использования*: [code] контрол::ElLabel3:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_ElLabel3_Push Tkw_DefineSearchDate_Control_dD1EqD2 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола dD1EqD2 ---- *Пример использования*: [code] контрол::dD1EqD2 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD1EqD2 Tkw_DefineSearchDate_Control_dD1EqD2_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола dD1EqD2 ---- *Пример использования*: [code] контрол::dD1EqD2:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD1EqD2_Push Tkw_DefineSearchDate_Control_rbEq = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbEq ---- *Пример использования*: [code] контрол::rbEq TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_rbEq Tkw_DefineSearchDate_Control_rbEq_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbEq ---- *Пример использования*: [code] контрол::rbEq:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_rbEq_Push Tkw_DefineSearchDate_Control_rbInt = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbInt ---- *Пример использования*: [code] контрол::rbInt TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_rbInt Tkw_DefineSearchDate_Control_rbInt_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbInt ---- *Пример использования*: [code] контрол::rbInt:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_rbInt_Push Tkw_DefineSearchDate_Control_rbD2Only = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbD2Only ---- *Пример использования*: [code] контрол::rbD2Only TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_rbD2Only Tkw_DefineSearchDate_Control_rbD2Only_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbD2Only ---- *Пример использования*: [code] контрол::rbD2Only:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_rbD2Only_Push Tkw_DefineSearchDate_Control_dD1Only = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола dD1Only ---- *Пример использования*: [code] контрол::dD1Only TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD1Only Tkw_DefineSearchDate_Control_dD1Only_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола dD1Only ---- *Пример использования*: [code] контрол::dD1Only:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD1Only_Push Tkw_DefineSearchDate_Control_dD2Only = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола dD2Only ---- *Пример использования*: [code] контрол::dD2Only TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD2Only Tkw_DefineSearchDate_Control_dD2Only_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола dD2Only ---- *Пример использования*: [code] контрол::dD2Only:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD2Only_Push Tkw_DefineSearchDate_Control_dD1 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола dD1 ---- *Пример использования*: [code] контрол::dD1 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD1 Tkw_DefineSearchDate_Control_dD1_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола dD1 ---- *Пример использования*: [code] контрол::dD1:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD1_Push Tkw_DefineSearchDate_Control_rbD1Only = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола rbD1Only ---- *Пример использования*: [code] контрол::rbD1Only TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_rbD1Only Tkw_DefineSearchDate_Control_rbD1Only_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола rbD1Only ---- *Пример использования*: [code] контрол::rbD1Only:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_rbD1Only_Push Tkw_DefineSearchDate_Control_dD2 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола dD2 ---- *Пример использования*: [code] контрол::dD2 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD2 Tkw_DefineSearchDate_Control_dD2_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола dD2 ---- *Пример использования*: [code] контрол::dD2:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_DefineSearchDate_Control_dD2_Push TkwEnDefineSearchDatePanel1 = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.Panel1 } private function Panel1(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtPanel; {* Реализация слова скрипта .Ten_DefineSearchDate.Panel1 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDatePanel1 TkwEnDefineSearchDateElLabel1 = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.ElLabel1 } private function ElLabel1(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtLabel; {* Реализация слова скрипта .Ten_DefineSearchDate.ElLabel1 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateElLabel1 TkwEnDefineSearchDateElLabel2 = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.ElLabel2 } private function ElLabel2(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtLabel; {* Реализация слова скрипта .Ten_DefineSearchDate.ElLabel2 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateElLabel2 TkwEnDefineSearchDateElLabel3 = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.ElLabel3 } private function ElLabel3(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtLabel; {* Реализация слова скрипта .Ten_DefineSearchDate.ElLabel3 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateElLabel3 TkwEnDefineSearchDateDD1EqD2 = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.dD1EqD2 } private function dD1EqD2(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD1EqD2 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateDD1EqD2 TkwEnDefineSearchDateRbEq = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.rbEq } private function rbEq(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtRadioButton; {* Реализация слова скрипта .Ten_DefineSearchDate.rbEq } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateRbEq TkwEnDefineSearchDateRbInt = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.rbInt } private function rbInt(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtRadioButton; {* Реализация слова скрипта .Ten_DefineSearchDate.rbInt } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateRbInt TkwEnDefineSearchDateRbD2Only = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.rbD2Only } private function rbD2Only(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtRadioButton; {* Реализация слова скрипта .Ten_DefineSearchDate.rbD2Only } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateRbD2Only TkwEnDefineSearchDateDD1Only = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.dD1Only } private function dD1Only(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD1Only } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateDD1Only TkwEnDefineSearchDateDD2Only = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.dD2Only } private function dD2Only(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD2Only } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateDD2Only TkwEnDefineSearchDateDD1 = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.dD1 } private function dD1(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD1 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateDD1 TkwEnDefineSearchDateRbD1Only = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.rbD1Only } private function rbD1Only(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtRadioButton; {* Реализация слова скрипта .Ten_DefineSearchDate.rbD1Only } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateRbD1Only TkwEnDefineSearchDateDD2 = {final} class(TtfwPropertyLike) {* Слово скрипта .Ten_DefineSearchDate.dD2 } private function dD2(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD2 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEnDefineSearchDateDD2 function Tkw_Form_DefineSearchDate.GetString: AnsiString; begin Result := 'en_DefineSearchDate'; end;//Tkw_Form_DefineSearchDate.GetString class function Tkw_Form_DefineSearchDate.GetWordNameForRegister: AnsiString; begin Result := 'форма::DefineSearchDate'; end;//Tkw_Form_DefineSearchDate.GetWordNameForRegister function Tkw_DefineSearchDate_Control_Panel1.GetString: AnsiString; begin Result := 'Panel1'; end;//Tkw_DefineSearchDate_Control_Panel1.GetString class procedure Tkw_DefineSearchDate_Control_Panel1.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_DefineSearchDate_Control_Panel1.RegisterInEngine class function Tkw_DefineSearchDate_Control_Panel1.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Panel1'; end;//Tkw_DefineSearchDate_Control_Panel1.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_Panel1_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('Panel1'); inherited; end;//Tkw_DefineSearchDate_Control_Panel1_Push.DoDoIt class function Tkw_DefineSearchDate_Control_Panel1_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Panel1:push'; end;//Tkw_DefineSearchDate_Control_Panel1_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_ElLabel1.GetString: AnsiString; begin Result := 'ElLabel1'; end;//Tkw_DefineSearchDate_Control_ElLabel1.GetString class procedure Tkw_DefineSearchDate_Control_ElLabel1.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_DefineSearchDate_Control_ElLabel1.RegisterInEngine class function Tkw_DefineSearchDate_Control_ElLabel1.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElLabel1'; end;//Tkw_DefineSearchDate_Control_ElLabel1.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_ElLabel1_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ElLabel1'); inherited; end;//Tkw_DefineSearchDate_Control_ElLabel1_Push.DoDoIt class function Tkw_DefineSearchDate_Control_ElLabel1_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElLabel1:push'; end;//Tkw_DefineSearchDate_Control_ElLabel1_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_ElLabel2.GetString: AnsiString; begin Result := 'ElLabel2'; end;//Tkw_DefineSearchDate_Control_ElLabel2.GetString class procedure Tkw_DefineSearchDate_Control_ElLabel2.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_DefineSearchDate_Control_ElLabel2.RegisterInEngine class function Tkw_DefineSearchDate_Control_ElLabel2.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElLabel2'; end;//Tkw_DefineSearchDate_Control_ElLabel2.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_ElLabel2_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ElLabel2'); inherited; end;//Tkw_DefineSearchDate_Control_ElLabel2_Push.DoDoIt class function Tkw_DefineSearchDate_Control_ElLabel2_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElLabel2:push'; end;//Tkw_DefineSearchDate_Control_ElLabel2_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_ElLabel3.GetString: AnsiString; begin Result := 'ElLabel3'; end;//Tkw_DefineSearchDate_Control_ElLabel3.GetString class procedure Tkw_DefineSearchDate_Control_ElLabel3.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_DefineSearchDate_Control_ElLabel3.RegisterInEngine class function Tkw_DefineSearchDate_Control_ElLabel3.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElLabel3'; end;//Tkw_DefineSearchDate_Control_ElLabel3.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_ElLabel3_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ElLabel3'); inherited; end;//Tkw_DefineSearchDate_Control_ElLabel3_Push.DoDoIt class function Tkw_DefineSearchDate_Control_ElLabel3_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ElLabel3:push'; end;//Tkw_DefineSearchDate_Control_ElLabel3_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_dD1EqD2.GetString: AnsiString; begin Result := 'dD1EqD2'; end;//Tkw_DefineSearchDate_Control_dD1EqD2.GetString class procedure Tkw_DefineSearchDate_Control_dD1EqD2.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtDblClickDateEdit); end;//Tkw_DefineSearchDate_Control_dD1EqD2.RegisterInEngine class function Tkw_DefineSearchDate_Control_dD1EqD2.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD1EqD2'; end;//Tkw_DefineSearchDate_Control_dD1EqD2.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_dD1EqD2_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('dD1EqD2'); inherited; end;//Tkw_DefineSearchDate_Control_dD1EqD2_Push.DoDoIt class function Tkw_DefineSearchDate_Control_dD1EqD2_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD1EqD2:push'; end;//Tkw_DefineSearchDate_Control_dD1EqD2_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_rbEq.GetString: AnsiString; begin Result := 'rbEq'; end;//Tkw_DefineSearchDate_Control_rbEq.GetString class procedure Tkw_DefineSearchDate_Control_rbEq.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_DefineSearchDate_Control_rbEq.RegisterInEngine class function Tkw_DefineSearchDate_Control_rbEq.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbEq'; end;//Tkw_DefineSearchDate_Control_rbEq.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_rbEq_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbEq'); inherited; end;//Tkw_DefineSearchDate_Control_rbEq_Push.DoDoIt class function Tkw_DefineSearchDate_Control_rbEq_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbEq:push'; end;//Tkw_DefineSearchDate_Control_rbEq_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_rbInt.GetString: AnsiString; begin Result := 'rbInt'; end;//Tkw_DefineSearchDate_Control_rbInt.GetString class procedure Tkw_DefineSearchDate_Control_rbInt.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_DefineSearchDate_Control_rbInt.RegisterInEngine class function Tkw_DefineSearchDate_Control_rbInt.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbInt'; end;//Tkw_DefineSearchDate_Control_rbInt.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_rbInt_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbInt'); inherited; end;//Tkw_DefineSearchDate_Control_rbInt_Push.DoDoIt class function Tkw_DefineSearchDate_Control_rbInt_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbInt:push'; end;//Tkw_DefineSearchDate_Control_rbInt_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_rbD2Only.GetString: AnsiString; begin Result := 'rbD2Only'; end;//Tkw_DefineSearchDate_Control_rbD2Only.GetString class procedure Tkw_DefineSearchDate_Control_rbD2Only.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_DefineSearchDate_Control_rbD2Only.RegisterInEngine class function Tkw_DefineSearchDate_Control_rbD2Only.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbD2Only'; end;//Tkw_DefineSearchDate_Control_rbD2Only.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_rbD2Only_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbD2Only'); inherited; end;//Tkw_DefineSearchDate_Control_rbD2Only_Push.DoDoIt class function Tkw_DefineSearchDate_Control_rbD2Only_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbD2Only:push'; end;//Tkw_DefineSearchDate_Control_rbD2Only_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_dD1Only.GetString: AnsiString; begin Result := 'dD1Only'; end;//Tkw_DefineSearchDate_Control_dD1Only.GetString class procedure Tkw_DefineSearchDate_Control_dD1Only.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtDblClickDateEdit); end;//Tkw_DefineSearchDate_Control_dD1Only.RegisterInEngine class function Tkw_DefineSearchDate_Control_dD1Only.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD1Only'; end;//Tkw_DefineSearchDate_Control_dD1Only.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_dD1Only_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('dD1Only'); inherited; end;//Tkw_DefineSearchDate_Control_dD1Only_Push.DoDoIt class function Tkw_DefineSearchDate_Control_dD1Only_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD1Only:push'; end;//Tkw_DefineSearchDate_Control_dD1Only_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_dD2Only.GetString: AnsiString; begin Result := 'dD2Only'; end;//Tkw_DefineSearchDate_Control_dD2Only.GetString class procedure Tkw_DefineSearchDate_Control_dD2Only.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtDblClickDateEdit); end;//Tkw_DefineSearchDate_Control_dD2Only.RegisterInEngine class function Tkw_DefineSearchDate_Control_dD2Only.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD2Only'; end;//Tkw_DefineSearchDate_Control_dD2Only.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_dD2Only_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('dD2Only'); inherited; end;//Tkw_DefineSearchDate_Control_dD2Only_Push.DoDoIt class function Tkw_DefineSearchDate_Control_dD2Only_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD2Only:push'; end;//Tkw_DefineSearchDate_Control_dD2Only_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_dD1.GetString: AnsiString; begin Result := 'dD1'; end;//Tkw_DefineSearchDate_Control_dD1.GetString class procedure Tkw_DefineSearchDate_Control_dD1.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtDblClickDateEdit); end;//Tkw_DefineSearchDate_Control_dD1.RegisterInEngine class function Tkw_DefineSearchDate_Control_dD1.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD1'; end;//Tkw_DefineSearchDate_Control_dD1.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_dD1_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('dD1'); inherited; end;//Tkw_DefineSearchDate_Control_dD1_Push.DoDoIt class function Tkw_DefineSearchDate_Control_dD1_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD1:push'; end;//Tkw_DefineSearchDate_Control_dD1_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_rbD1Only.GetString: AnsiString; begin Result := 'rbD1Only'; end;//Tkw_DefineSearchDate_Control_rbD1Only.GetString class procedure Tkw_DefineSearchDate_Control_rbD1Only.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtRadioButton); end;//Tkw_DefineSearchDate_Control_rbD1Only.RegisterInEngine class function Tkw_DefineSearchDate_Control_rbD1Only.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbD1Only'; end;//Tkw_DefineSearchDate_Control_rbD1Only.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_rbD1Only_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('rbD1Only'); inherited; end;//Tkw_DefineSearchDate_Control_rbD1Only_Push.DoDoIt class function Tkw_DefineSearchDate_Control_rbD1Only_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::rbD1Only:push'; end;//Tkw_DefineSearchDate_Control_rbD1Only_Push.GetWordNameForRegister function Tkw_DefineSearchDate_Control_dD2.GetString: AnsiString; begin Result := 'dD2'; end;//Tkw_DefineSearchDate_Control_dD2.GetString class procedure Tkw_DefineSearchDate_Control_dD2.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtDblClickDateEdit); end;//Tkw_DefineSearchDate_Control_dD2.RegisterInEngine class function Tkw_DefineSearchDate_Control_dD2.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD2'; end;//Tkw_DefineSearchDate_Control_dD2.GetWordNameForRegister procedure Tkw_DefineSearchDate_Control_dD2_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('dD2'); inherited; end;//Tkw_DefineSearchDate_Control_dD2_Push.DoDoIt class function Tkw_DefineSearchDate_Control_dD2_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::dD2:push'; end;//Tkw_DefineSearchDate_Control_dD2_Push.GetWordNameForRegister function TkwEnDefineSearchDatePanel1.Panel1(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtPanel; {* Реализация слова скрипта .Ten_DefineSearchDate.Panel1 } begin Result := aen_DefineSearchDate.Panel1; end;//TkwEnDefineSearchDatePanel1.Panel1 class function TkwEnDefineSearchDatePanel1.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.Panel1'; end;//TkwEnDefineSearchDatePanel1.GetWordNameForRegister function TkwEnDefineSearchDatePanel1.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEnDefineSearchDatePanel1.GetResultTypeInfo function TkwEnDefineSearchDatePanel1.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDatePanel1.GetAllParamsCount function TkwEnDefineSearchDatePanel1.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDatePanel1.ParamsTypes procedure TkwEnDefineSearchDatePanel1.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Panel1', aCtx); end;//TkwEnDefineSearchDatePanel1.SetValuePrim procedure TkwEnDefineSearchDatePanel1.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Panel1(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDatePanel1.DoDoIt function TkwEnDefineSearchDateElLabel1.ElLabel1(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtLabel; {* Реализация слова скрипта .Ten_DefineSearchDate.ElLabel1 } begin Result := aen_DefineSearchDate.ElLabel1; end;//TkwEnDefineSearchDateElLabel1.ElLabel1 class function TkwEnDefineSearchDateElLabel1.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.ElLabel1'; end;//TkwEnDefineSearchDateElLabel1.GetWordNameForRegister function TkwEnDefineSearchDateElLabel1.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEnDefineSearchDateElLabel1.GetResultTypeInfo function TkwEnDefineSearchDateElLabel1.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateElLabel1.GetAllParamsCount function TkwEnDefineSearchDateElLabel1.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateElLabel1.ParamsTypes procedure TkwEnDefineSearchDateElLabel1.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ElLabel1', aCtx); end;//TkwEnDefineSearchDateElLabel1.SetValuePrim procedure TkwEnDefineSearchDateElLabel1.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ElLabel1(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateElLabel1.DoDoIt function TkwEnDefineSearchDateElLabel2.ElLabel2(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtLabel; {* Реализация слова скрипта .Ten_DefineSearchDate.ElLabel2 } begin Result := aen_DefineSearchDate.ElLabel2; end;//TkwEnDefineSearchDateElLabel2.ElLabel2 class function TkwEnDefineSearchDateElLabel2.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.ElLabel2'; end;//TkwEnDefineSearchDateElLabel2.GetWordNameForRegister function TkwEnDefineSearchDateElLabel2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEnDefineSearchDateElLabel2.GetResultTypeInfo function TkwEnDefineSearchDateElLabel2.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateElLabel2.GetAllParamsCount function TkwEnDefineSearchDateElLabel2.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateElLabel2.ParamsTypes procedure TkwEnDefineSearchDateElLabel2.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ElLabel2', aCtx); end;//TkwEnDefineSearchDateElLabel2.SetValuePrim procedure TkwEnDefineSearchDateElLabel2.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ElLabel2(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateElLabel2.DoDoIt function TkwEnDefineSearchDateElLabel3.ElLabel3(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtLabel; {* Реализация слова скрипта .Ten_DefineSearchDate.ElLabel3 } begin Result := aen_DefineSearchDate.ElLabel3; end;//TkwEnDefineSearchDateElLabel3.ElLabel3 class function TkwEnDefineSearchDateElLabel3.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.ElLabel3'; end;//TkwEnDefineSearchDateElLabel3.GetWordNameForRegister function TkwEnDefineSearchDateElLabel3.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwEnDefineSearchDateElLabel3.GetResultTypeInfo function TkwEnDefineSearchDateElLabel3.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateElLabel3.GetAllParamsCount function TkwEnDefineSearchDateElLabel3.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateElLabel3.ParamsTypes procedure TkwEnDefineSearchDateElLabel3.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ElLabel3', aCtx); end;//TkwEnDefineSearchDateElLabel3.SetValuePrim procedure TkwEnDefineSearchDateElLabel3.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ElLabel3(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateElLabel3.DoDoIt function TkwEnDefineSearchDateDD1EqD2.dD1EqD2(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD1EqD2 } begin Result := aen_DefineSearchDate.dD1EqD2; end;//TkwEnDefineSearchDateDD1EqD2.dD1EqD2 class function TkwEnDefineSearchDateDD1EqD2.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.dD1EqD2'; end;//TkwEnDefineSearchDateDD1EqD2.GetWordNameForRegister function TkwEnDefineSearchDateDD1EqD2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtDblClickDateEdit); end;//TkwEnDefineSearchDateDD1EqD2.GetResultTypeInfo function TkwEnDefineSearchDateDD1EqD2.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateDD1EqD2.GetAllParamsCount function TkwEnDefineSearchDateDD1EqD2.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateDD1EqD2.ParamsTypes procedure TkwEnDefineSearchDateDD1EqD2.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству dD1EqD2', aCtx); end;//TkwEnDefineSearchDateDD1EqD2.SetValuePrim procedure TkwEnDefineSearchDateDD1EqD2.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(dD1EqD2(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateDD1EqD2.DoDoIt function TkwEnDefineSearchDateRbEq.rbEq(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtRadioButton; {* Реализация слова скрипта .Ten_DefineSearchDate.rbEq } begin Result := aen_DefineSearchDate.rbEq; end;//TkwEnDefineSearchDateRbEq.rbEq class function TkwEnDefineSearchDateRbEq.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.rbEq'; end;//TkwEnDefineSearchDateRbEq.GetWordNameForRegister function TkwEnDefineSearchDateRbEq.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnDefineSearchDateRbEq.GetResultTypeInfo function TkwEnDefineSearchDateRbEq.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateRbEq.GetAllParamsCount function TkwEnDefineSearchDateRbEq.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateRbEq.ParamsTypes procedure TkwEnDefineSearchDateRbEq.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbEq', aCtx); end;//TkwEnDefineSearchDateRbEq.SetValuePrim procedure TkwEnDefineSearchDateRbEq.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbEq(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateRbEq.DoDoIt function TkwEnDefineSearchDateRbInt.rbInt(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtRadioButton; {* Реализация слова скрипта .Ten_DefineSearchDate.rbInt } begin Result := aen_DefineSearchDate.rbInt; end;//TkwEnDefineSearchDateRbInt.rbInt class function TkwEnDefineSearchDateRbInt.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.rbInt'; end;//TkwEnDefineSearchDateRbInt.GetWordNameForRegister function TkwEnDefineSearchDateRbInt.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnDefineSearchDateRbInt.GetResultTypeInfo function TkwEnDefineSearchDateRbInt.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateRbInt.GetAllParamsCount function TkwEnDefineSearchDateRbInt.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateRbInt.ParamsTypes procedure TkwEnDefineSearchDateRbInt.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbInt', aCtx); end;//TkwEnDefineSearchDateRbInt.SetValuePrim procedure TkwEnDefineSearchDateRbInt.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbInt(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateRbInt.DoDoIt function TkwEnDefineSearchDateRbD2Only.rbD2Only(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtRadioButton; {* Реализация слова скрипта .Ten_DefineSearchDate.rbD2Only } begin Result := aen_DefineSearchDate.rbD2Only; end;//TkwEnDefineSearchDateRbD2Only.rbD2Only class function TkwEnDefineSearchDateRbD2Only.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.rbD2Only'; end;//TkwEnDefineSearchDateRbD2Only.GetWordNameForRegister function TkwEnDefineSearchDateRbD2Only.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnDefineSearchDateRbD2Only.GetResultTypeInfo function TkwEnDefineSearchDateRbD2Only.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateRbD2Only.GetAllParamsCount function TkwEnDefineSearchDateRbD2Only.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateRbD2Only.ParamsTypes procedure TkwEnDefineSearchDateRbD2Only.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbD2Only', aCtx); end;//TkwEnDefineSearchDateRbD2Only.SetValuePrim procedure TkwEnDefineSearchDateRbD2Only.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbD2Only(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateRbD2Only.DoDoIt function TkwEnDefineSearchDateDD1Only.dD1Only(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD1Only } begin Result := aen_DefineSearchDate.dD1Only; end;//TkwEnDefineSearchDateDD1Only.dD1Only class function TkwEnDefineSearchDateDD1Only.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.dD1Only'; end;//TkwEnDefineSearchDateDD1Only.GetWordNameForRegister function TkwEnDefineSearchDateDD1Only.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtDblClickDateEdit); end;//TkwEnDefineSearchDateDD1Only.GetResultTypeInfo function TkwEnDefineSearchDateDD1Only.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateDD1Only.GetAllParamsCount function TkwEnDefineSearchDateDD1Only.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateDD1Only.ParamsTypes procedure TkwEnDefineSearchDateDD1Only.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству dD1Only', aCtx); end;//TkwEnDefineSearchDateDD1Only.SetValuePrim procedure TkwEnDefineSearchDateDD1Only.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(dD1Only(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateDD1Only.DoDoIt function TkwEnDefineSearchDateDD2Only.dD2Only(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD2Only } begin Result := aen_DefineSearchDate.dD2Only; end;//TkwEnDefineSearchDateDD2Only.dD2Only class function TkwEnDefineSearchDateDD2Only.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.dD2Only'; end;//TkwEnDefineSearchDateDD2Only.GetWordNameForRegister function TkwEnDefineSearchDateDD2Only.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtDblClickDateEdit); end;//TkwEnDefineSearchDateDD2Only.GetResultTypeInfo function TkwEnDefineSearchDateDD2Only.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateDD2Only.GetAllParamsCount function TkwEnDefineSearchDateDD2Only.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateDD2Only.ParamsTypes procedure TkwEnDefineSearchDateDD2Only.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству dD2Only', aCtx); end;//TkwEnDefineSearchDateDD2Only.SetValuePrim procedure TkwEnDefineSearchDateDD2Only.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(dD2Only(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateDD2Only.DoDoIt function TkwEnDefineSearchDateDD1.dD1(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD1 } begin Result := aen_DefineSearchDate.dD1; end;//TkwEnDefineSearchDateDD1.dD1 class function TkwEnDefineSearchDateDD1.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.dD1'; end;//TkwEnDefineSearchDateDD1.GetWordNameForRegister function TkwEnDefineSearchDateDD1.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtDblClickDateEdit); end;//TkwEnDefineSearchDateDD1.GetResultTypeInfo function TkwEnDefineSearchDateDD1.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateDD1.GetAllParamsCount function TkwEnDefineSearchDateDD1.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateDD1.ParamsTypes procedure TkwEnDefineSearchDateDD1.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству dD1', aCtx); end;//TkwEnDefineSearchDateDD1.SetValuePrim procedure TkwEnDefineSearchDateDD1.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(dD1(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateDD1.DoDoIt function TkwEnDefineSearchDateRbD1Only.rbD1Only(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtRadioButton; {* Реализация слова скрипта .Ten_DefineSearchDate.rbD1Only } begin Result := aen_DefineSearchDate.rbD1Only; end;//TkwEnDefineSearchDateRbD1Only.rbD1Only class function TkwEnDefineSearchDateRbD1Only.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.rbD1Only'; end;//TkwEnDefineSearchDateRbD1Only.GetWordNameForRegister function TkwEnDefineSearchDateRbD1Only.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtRadioButton); end;//TkwEnDefineSearchDateRbD1Only.GetResultTypeInfo function TkwEnDefineSearchDateRbD1Only.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateRbD1Only.GetAllParamsCount function TkwEnDefineSearchDateRbD1Only.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateRbD1Only.ParamsTypes procedure TkwEnDefineSearchDateRbD1Only.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству rbD1Only', aCtx); end;//TkwEnDefineSearchDateRbD1Only.SetValuePrim procedure TkwEnDefineSearchDateRbD1Only.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(rbD1Only(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateRbD1Only.DoDoIt function TkwEnDefineSearchDateDD2.dD2(const aCtx: TtfwContext; aen_DefineSearchDate: Ten_DefineSearchDate): TvtDblClickDateEdit; {* Реализация слова скрипта .Ten_DefineSearchDate.dD2 } begin Result := aen_DefineSearchDate.dD2; end;//TkwEnDefineSearchDateDD2.dD2 class function TkwEnDefineSearchDateDD2.GetWordNameForRegister: AnsiString; begin Result := '.Ten_DefineSearchDate.dD2'; end;//TkwEnDefineSearchDateDD2.GetWordNameForRegister function TkwEnDefineSearchDateDD2.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtDblClickDateEdit); end;//TkwEnDefineSearchDateDD2.GetResultTypeInfo function TkwEnDefineSearchDateDD2.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEnDefineSearchDateDD2.GetAllParamsCount function TkwEnDefineSearchDateDD2.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(Ten_DefineSearchDate)]); end;//TkwEnDefineSearchDateDD2.ParamsTypes procedure TkwEnDefineSearchDateDD2.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству dD2', aCtx); end;//TkwEnDefineSearchDateDD2.SetValuePrim procedure TkwEnDefineSearchDateDD2.DoDoIt(const aCtx: TtfwContext); var l_aen_DefineSearchDate: Ten_DefineSearchDate; begin try l_aen_DefineSearchDate := Ten_DefineSearchDate(aCtx.rEngine.PopObjAs(Ten_DefineSearchDate)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aen_DefineSearchDate: Ten_DefineSearchDate : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(dD2(aCtx, l_aen_DefineSearchDate)); end;//TkwEnDefineSearchDateDD2.DoDoIt initialization Tkw_Form_DefineSearchDate.RegisterInEngine; {* Регистрация Tkw_Form_DefineSearchDate } Tkw_DefineSearchDate_Control_Panel1.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_Panel1 } Tkw_DefineSearchDate_Control_Panel1_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_Panel1_Push } Tkw_DefineSearchDate_Control_ElLabel1.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_ElLabel1 } Tkw_DefineSearchDate_Control_ElLabel1_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_ElLabel1_Push } Tkw_DefineSearchDate_Control_ElLabel2.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_ElLabel2 } Tkw_DefineSearchDate_Control_ElLabel2_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_ElLabel2_Push } Tkw_DefineSearchDate_Control_ElLabel3.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_ElLabel3 } Tkw_DefineSearchDate_Control_ElLabel3_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_ElLabel3_Push } Tkw_DefineSearchDate_Control_dD1EqD2.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD1EqD2 } Tkw_DefineSearchDate_Control_dD1EqD2_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD1EqD2_Push } Tkw_DefineSearchDate_Control_rbEq.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_rbEq } Tkw_DefineSearchDate_Control_rbEq_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_rbEq_Push } Tkw_DefineSearchDate_Control_rbInt.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_rbInt } Tkw_DefineSearchDate_Control_rbInt_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_rbInt_Push } Tkw_DefineSearchDate_Control_rbD2Only.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_rbD2Only } Tkw_DefineSearchDate_Control_rbD2Only_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_rbD2Only_Push } Tkw_DefineSearchDate_Control_dD1Only.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD1Only } Tkw_DefineSearchDate_Control_dD1Only_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD1Only_Push } Tkw_DefineSearchDate_Control_dD2Only.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD2Only } Tkw_DefineSearchDate_Control_dD2Only_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD2Only_Push } Tkw_DefineSearchDate_Control_dD1.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD1 } Tkw_DefineSearchDate_Control_dD1_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD1_Push } Tkw_DefineSearchDate_Control_rbD1Only.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_rbD1Only } Tkw_DefineSearchDate_Control_rbD1Only_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_rbD1Only_Push } Tkw_DefineSearchDate_Control_dD2.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD2 } Tkw_DefineSearchDate_Control_dD2_Push.RegisterInEngine; {* Регистрация Tkw_DefineSearchDate_Control_dD2_Push } TkwEnDefineSearchDatePanel1.RegisterInEngine; {* Регистрация en_DefineSearchDate_Panel1 } TkwEnDefineSearchDateElLabel1.RegisterInEngine; {* Регистрация en_DefineSearchDate_ElLabel1 } TkwEnDefineSearchDateElLabel2.RegisterInEngine; {* Регистрация en_DefineSearchDate_ElLabel2 } TkwEnDefineSearchDateElLabel3.RegisterInEngine; {* Регистрация en_DefineSearchDate_ElLabel3 } TkwEnDefineSearchDateDD1EqD2.RegisterInEngine; {* Регистрация en_DefineSearchDate_dD1EqD2 } TkwEnDefineSearchDateRbEq.RegisterInEngine; {* Регистрация en_DefineSearchDate_rbEq } TkwEnDefineSearchDateRbInt.RegisterInEngine; {* Регистрация en_DefineSearchDate_rbInt } TkwEnDefineSearchDateRbD2Only.RegisterInEngine; {* Регистрация en_DefineSearchDate_rbD2Only } TkwEnDefineSearchDateDD1Only.RegisterInEngine; {* Регистрация en_DefineSearchDate_dD1Only } TkwEnDefineSearchDateDD2Only.RegisterInEngine; {* Регистрация en_DefineSearchDate_dD2Only } TkwEnDefineSearchDateDD1.RegisterInEngine; {* Регистрация en_DefineSearchDate_dD1 } TkwEnDefineSearchDateRbD1Only.RegisterInEngine; {* Регистрация en_DefineSearchDate_rbD1Only } TkwEnDefineSearchDateDD2.RegisterInEngine; {* Регистрация en_DefineSearchDate_dD2 } TtfwTypeRegistrator.RegisterType(TypeInfo(Ten_DefineSearchDate)); {* Регистрация типа Ten_DefineSearchDate } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtDblClickDateEdit)); {* Регистрация типа TvtDblClickDateEdit } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtRadioButton)); {* Регистрация типа TvtRadioButton } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.