text
stringlengths
14
6.51M
unit oCoverSheetParam_CPRS_Reminders; { ================================================================================ * * Application: CPRS - CoverSheet * Developer: doma.user@domain.ext * Site: Salt Lake City ISC * Date: 2015-12-04 * * Description: Inherited from TCoverSheetParam_CPRS. Special functions * for the CLinical Reminders display * * Notes: * ================================================================================ } interface uses System.Classes, System.SysUtils, Vcl.Controls, oCoverSheetParam_CPRS, iCoverSheetIntf; type TCoverSheetParam_CPRS_Reminders = class(TCoverSheetParam_CPRS, ICoverSheetParam) protected function getDetailRPC: string; override; function getInvert: boolean; override; function getMainRPC: string; override; function NewCoverSheetControl(aOwner: TComponent): TControl; override; public { Public declarations } end; implementation uses mCoverSheetDisplayPanel_CPRS_Reminders, uReminders, uCore; { TCoverSheetParam_CPRS_Reminders } function TCoverSheetParam_CPRS_Reminders.getDetailRPC: string; begin Result := 'ORQQPX REMINDER DETAIL'; end; function TCoverSheetParam_CPRS_Reminders.getInvert: boolean; begin Result := False; end; function TCoverSheetParam_CPRS_Reminders.getMainRPC: string; begin if InteractiveRemindersActive then begin Result := 'ORQQPXRM REMINDERS APPLICABLE'; setParam1(IntToStr(encounter.location)); end else begin Result := 'ORQQPX REMINDERS LIST'; setParam1(''); end; end; function TCoverSheetParam_CPRS_Reminders.NewCoverSheetControl(aOwner: TComponent): TControl; begin Result := TfraCoverSheetDisplayPanel_CPRS_Reminders.Create(aOwner); end; end.
{----------------------------------------------------------------------------} { Written by Nguyen Le Quang Duy } { Nguyen Quang Dieu High School, An Giang } {----------------------------------------------------------------------------} Program CRATE; Uses Math; Const maxN =300000; maxV =100000; Type TData =Record id,x,y :LongInt end; Var n :LongInt; A :Array[1..maxN] of TData; Ans :Array[1..maxN] of LongInt; BIT :Array[1..maxV] of LongInt; procedure Enter; var i :LongInt; begin Read(n); for i:=1 to n do with (A[i]) do begin Read(x,y); id:=i; end; A[0].x:=0; A[0].y:=0; A[0].id:=0; end; function Compare(U,V :TData) :Boolean; begin Exit((U.x<V.x) or ((U.x=V.x) and (U.y<V.y))); end; procedure QSort(l,r :LongInt); var i,j :LongInt; Key,Tmp :TData; begin if (l>=r) then Exit; i:=l; j:=r; Key:=A[(l+r) div 2]; repeat while (Compare(A[i],Key)) do Inc(i); while (Compare(Key,A[j])) do Dec(j); if (i<=j) then begin if (i<j) then begin Tmp:=A[i]; A[i]:=A[j]; A[j]:=Tmp; end; Inc(i); Dec(j); end; until (i>j); QSort(l,j); QSort(i,r); end; procedure UpdateBIT(i :LongInt); begin while (i<=maxV) do begin Inc(BIT[i]); Inc(i,i and (-i)); end; end; function SearchBIT(i :LongInt) :LongInt; var res :LongInt; begin res:=0; while (i>0) do begin Inc(res,BIT[i]); Dec(i,i and (-i)); end; Exit(res); end; procedure SolveBIT; var i,j,k :LongInt; begin FillChar(BIT,SizeOf(BIT),0); i:=1; repeat j:=i; while (j<n) and (A[j+1].x=A[i].x) and (A[j+1].y=A[i].y) do Inc(j); Ans[A[i].id]:=SearchBIT(A[i].y); for k:=i+1 to j do Ans[A[k].id]:=Ans[A[i].id]; for k:=i to j do UpdateBIT(A[k].y); i:=j+1; until (i>n); end; procedure PrintResult; var i :LongInt; begin for i:=1 to n do WriteLn(Ans[i]); end; Begin Assign(Input,''); Reset(Input); Assign(Output,''); Rewrite(Output); Enter; QSort(1,n); SolveBIT; PrintResult; Close(Input); Close(Output); End.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995,98 Inprise Corporation } { } {*******************************************************} unit DsgnIntf; interface {$N+,S-,R-} uses Windows, SysUtils, Classes, Graphics, Controls, Forms, TypInfo; type IEventInfos = interface ['{11667FF0-7590-11D1-9FBC-0020AF3D82DA}'] function GetCount: Integer; function GetEventValue(Index: Integer): string; function GetEventName(Index: Integer): string; procedure ClearEvent(Index: Integer); property Count: Integer read GetCount; end; IPersistent = interface ['{82330133-65D1-11D1-9FBB-0020AF3D82DA}'] {Java} procedure DestroyObject; function Equals(const Other: IPersistent): Boolean; function GetClassname: string; function GetEventInfos: IEventInfos; function GetNamePath: string; function GetOwner: IPersistent; function InheritsFrom(const Classname: string): Boolean; function IsComponent: Boolean; // object is stream createable function IsControl: Boolean; function IsWinControl: Boolean; property Classname: string read GetClassname; property Owner: IPersistent read GetOwner; property NamePath: string read GetNamePath; // property PersistentProps[Index: Integer]: IPersistent // property PersistentPropCount: Integer; property EventInfos: IEventInfos read GetEventInfos; end; IComponent = interface(IPersistent) ['{B2F6D681-5098-11D1-9FB5-0020AF3D82DA}'] {Java} function FindComponent(const Name: string): IComponent; function GetComponentCount: Integer; function GetComponents(Index: Integer): IComponent; function GetComponentState: TComponentState; function GetComponentStyle: TComponentStyle; function GetDesignInfo: TSmallPoint; function GetDesignOffset: TPoint; function GetDesignSize: TPoint; function GetName: string; function GetOwner: IComponent; function GetParent: IComponent; procedure SetDesignInfo(const Point: TSmallPoint); procedure SetDesignOffset(const Point: TPoint); procedure SetDesignSize(const Point: TPoint); procedure SetName(const Value: string); property ComponentCount: Integer read GetComponentCount; property Components[Index: Integer]: IComponent read GetComponents; property ComponentState: TComponentState read GetComponentState; property ComponentStyle: TComponentStyle read GetComponentStyle; property DesignInfo: TSmallPoint read GetDesignInfo write SetDesignInfo; property DesignOffset: TPoint read GetDesignOffset write SetDesignOffset; property DesignSize: TPoint read GetDesignSize write SetDesignSize; property Name: string read GetName write SetName; property Owner: IComponent read GetOwner; property Parent: IComponent read GetParent; end; IImplementation = interface ['{F9D448F2-50BC-11D1-9FB5-0020AF3D82DA}'] function GetInstance: TObject; end; function MakeIPersistent(Instance: TPersistent): IPersistent; function ExtractPersistent(const Intf: IPersistent): TPersistent; function TryExtractPersistent(const Intf: IPersistent): TPersistent; function MakeIComponent(Instance: TComponent): IComponent; function ExtractComponent(const Intf: IComponent): TComponent; function TryExtractComponent(const Intf: IComponent): TComponent; var MakeIPersistentProc: function (Instance: TPersistent): IPersistent = nil; MakeIComponentProc: function (Instance: TComponent): IComponent = nil; type { IDesignerSelections } { Used to transport the selected objects list in and out of the form designer. Replaces TComponentList in form designer interface. } IDesignerSelections = interface ['{82330134-65D1-11D1-9FBB-0020AF3D82DA}'] {Java} function Add(const Item: IPersistent): Integer; function Equals(const List: IDesignerSelections): Boolean; function Get(Index: Integer): IPersistent; function GetCount: Integer; property Count: Integer read GetCount; property Items[Index: Integer]: IPersistent read Get; default; end; function CreateSelectionList: IDesignerSelections; type TComponentList = class; IComponentList = interface ['{8ED8AD16-A241-11D1-AA94-00C04FB17A72}'] function GetComponentList: TComponentList; end; { TComponentList } { Used to transport VCL component selections between property editors } TComponentList = class(TInterfacedObject, IDesignerSelections, IComponentList) private FList: TList; { IDesignSelections } function IDesignerSelections.Add = Intf_Add; function Intf_Add(const Item: IPersistent): Integer; function IDesignerSelections.Equals = Intf_Equals; function Intf_Equals(const List: IDesignerSelections): Boolean; function IDesignerSelections.Get = Intf_Get; function Intf_Get(Index: Integer): IPersistent; function Get(Index: Integer): TPersistent; function GetCount: Integer; { IComponentList } function GetComponentList: TComponentList; public constructor Create; destructor Destroy; override; function Add(Item: TPersistent): Integer; function Equals(List: TComponentList): Boolean; property Count: Integer read GetCount; property Items[Index: Integer]: TPersistent read Get; default; end; { IFormDesigner } type IFormDesigner = interface(IDesigner) ['{ABBE7255-5495-11D1-9FB5-0020AF3D82DA}'] function CreateMethod(const Name: string; TypeData: PTypeData): TMethod; function GetMethodName(const Method: TMethod): string; procedure GetMethods(TypeData: PTypeData; Proc: TGetStrProc); function GetPrivateDirectory: string; procedure GetSelections(const List: IDesignerSelections); function MethodExists(const Name: string): Boolean; procedure RenameMethod(const CurName, NewName: string); procedure SelectComponent(Instance: TPersistent); procedure SetSelections(const List: IDesignerSelections); procedure ShowMethod(const Name: string); function UniqueName(const BaseName: string): string; procedure GetComponentNames(TypeData: PTypeData; Proc: TGetStrProc); function GetComponent(const Name: string): TComponent; function GetComponentName(Component: TComponent): string; function GetObject(const Name: string): TPersistent; function GetObjectName(Instance: TPersistent): string; procedure GetObjectNames(TypeData: PTypeData; Proc: TGetStrProc); function MethodFromAncestor(const Method: TMethod): Boolean; function CreateComponent(ComponentClass: TComponentClass; Parent: TComponent; Left, Top, Width, Height: Integer): TComponent; function IsComponentLinkable(Component: TComponent): Boolean; procedure MakeComponentLinkable(Component: TComponent); function GetRoot: TComponent; procedure Revert(Instance: TPersistent; PropInfo: PPropInfo); function GetIsDormant: Boolean; function HasInterface: Boolean; function HasInterfaceMember(const Name: string): Boolean; procedure AddToInterface(InvKind: Integer; const Name: string; VT: Word; const TypeInfo: string); procedure GetProjectModules(Proc: TGetModuleProc); function GetAncestorDesigner: IFormDesigner; function IsSourceReadOnly: Boolean; property IsDormant: Boolean read GetIsDormant; property AncestorDesigner: IFormDesigner read GetAncestorDesigner; end; { TPropertyEditor Edits a property of a component, or list of components, selected into the Object Inspector. The property editor is created based on the type of the property being edited as determined by the types registered by RegisterPropertyEditor. The Object Inspector uses the a TPropertyEditor for all modification to a property. GetName and GetValue are called to display the name and value of the property. SetValue is called whenever the user requests to change the value. Edit is called when the user double-clicks the property in the Object Inspector. GetValues is called when the drop-down list of a property is displayed. GetProperties is called when the property is expanded to show sub-properties. AllEqual is called to decide whether or not to display the value of the property when more than one component is selected. The following are methods that can be overriden to change the behavior of the property editor: Activate Called whenever the property becomes selected in the object inspector. This is potientially useful to allow certian property attributes to to only be determined whenever the property is selected in the object inspector. Only paSubProperties and paMultiSelect, returned from GetAttributes, need to be accurate before this method is called. AllEqual Called whenever there are more than one components selected. If this method returns true, GetValue is called, otherwise blank is displayed in the Object Inspector. This is called only when GetAttributes returns paMultiSelect. AutoFill Called to determine whether the values returned by GetValues can be selected incrementally in the Object Inspector. This is called only when GetAttributes returns paValueList. Edit Called when the '...' button is pressed or the property is double-clicked. This can, for example, bring up a dialog to allow the editing the component in some more meaningful fashion than by text (e.g. the Font property). GetAttributes Returns the information for use in the Object Inspector to be able to show the approprate tools. GetAttributes return a set of type TPropertyAttributes: paValueList: The property editor can return an enumerated list of values for the property. If GetValues calls Proc with values then this attribute should be set. This will cause the drop-down button to appear to the right of the property in the Object Inspector. paSortList: Object Inspector to sort the list returned by GetValues. paSubProperties: The property editor has sub-properties that will be displayed indented and below the current property in standard outline format. If GetProperties will generate property objects then this attribute should be set. paDialog: Indicates that the Edit method will bring up a dialog. This will cause the '...' button to be displayed to the right of the property in the Object Inspector. paMultiSelect: Allows the property to be displayed when more than one component is selected. Some properties are not approprate for multi-selection (e.g. the Name property). paAutoUpdate: Causes the SetValue method to be called on each change made to the editor instead of after the change has been approved (e.g. the Caption property). paReadOnly: Value is not allowed to change. paRevertable: Allows the property to be reverted to the original value. Things that shouldn't be reverted are nested properties (e.g. Fonts) and elements of a composite property such as set element values. GetComponent Returns the Index'th component being edited by this property editor. This is used to retieve the components. A property editor can only refer to multiple components when paMultiSelect is returned from GetAttributes. GetEditLimit Returns the number of character the user is allowed to enter for the value. The inplace editor of the object inspector will be have its text limited set to the return value. By default this limit is 255. GetName Returns a the name of the property. By default the value is retrieved from the type information with all underbars replaced by spaces. This should only be overriden if the name of the property is not the name that should appear in the Object Inspector. GetProperties Should be overriden to call PropertyProc for every sub-property (or nested property) of the property begin edited and passing a new TPropertyEdtior for each sub-property. By default, PropertyProc is not called and no sub-properties are assumed. TClassProperty will pass a new property editor for each published property in a class. TSetProperty passes a new editor for each element in the set. GetPropType Returns the type information pointer for the propertie(s) being edited. GetValue Returns the string value of the property. By default this returns '(unknown)'. This should be overriden to return the appropriate value. GetValues Called when paValueList is returned in GetAttributes. Should call Proc for every value that is acceptable for this property. TEnumProperty will pass every element in the enumeration. Initialize Called after the property editor has been created but before it is used. Many times property editors are created and because they are not a common property across the entire selection they are thrown away. Initialize is called after it is determined the property editor is going to be used by the object inspector and not just thrown away. SetValue(Value) Called to set the value of the property. The property editor should be able to translate the string and call one of the SetXxxValue methods. If the string is not in the correct format or not an allowed value, the property editor should generate an exception describing the problem. Set value can ignore all changes and allow all editing of the property be accomplished through the Edit method (e.g. the Picture property). Properties and methods useful in creating a new TPropertyEditor classes: Name property Returns the name of the property returned by GetName PrivateDirectory property It is either the .EXE or the "working directory" as specified in the registry under the key: "HKEY_CURRENT_USER\Software\Borland\Delphi\3.0\Globals\PrivateDir" If the property editor needs auxilury or state files (templates, examples, etc) they should be stored in this directory. Value property The current value, as a string, of the property as returned by GetValue. Modified Called to indicate the value of the property has been modified. Called automatically by the SetXxxValue methods. If you call a TProperty SetXxxValue method directly, you *must* call Modified as well. GetXxxValue Gets the value of the first property in the Properties property. Calls the appropriate TProperty GetXxxValue method to retrieve the value. SetXxxValue Sets the value of all the properties in the Properties property. Calls the approprate TProperty SetXxxxValue methods to set the value. } TPropertyAttribute = (paValueList, paSubProperties, paDialog, paMultiSelect, paAutoUpdate, paSortList, paReadOnly, paRevertable); TPropertyAttributes = set of TPropertyAttribute; TPropertyEditor = class; TInstProp = record Instance: TPersistent; PropInfo: PPropInfo; end; PInstPropList = ^TInstPropList; TInstPropList = array[0..1023] of TInstProp; TGetPropEditProc = procedure(Prop: TPropertyEditor) of object; TPropertyEditor = class private FDesigner: IFormDesigner; FPropList: PInstPropList; FPropCount: Integer; function GetPrivateDirectory: string; procedure SetPropEntry(Index: Integer; AInstance: TPersistent; APropInfo: PPropInfo); protected constructor Create(const ADesigner: IFormDesigner; APropCount: Integer); function GetPropInfo: PPropInfo; function GetFloatValue: Extended; function GetFloatValueAt(Index: Integer): Extended; function GetMethodValue: TMethod; function GetMethodValueAt(Index: Integer): TMethod; function GetOrdValue: Longint; function GetOrdValueAt(Index: Integer): Longint; function GetStrValue: string; function GetStrValueAt(Index: Integer): string; function GetVarValue: Variant; function GetVarValueAt(Index: Integer): Variant; procedure Modified; procedure SetFloatValue(Value: Extended); procedure SetMethodValue(const Value: TMethod); procedure SetOrdValue(Value: Longint); procedure SetStrValue(const Value: string); procedure SetVarValue(const Value: Variant); public destructor Destroy; override; procedure Activate; virtual; function AllEqual: Boolean; virtual; function AutoFill: Boolean; virtual; procedure Edit; virtual; function GetAttributes: TPropertyAttributes; virtual; function GetComponent(Index: Integer): TPersistent; function GetEditLimit: Integer; virtual; function GetName: string; virtual; procedure GetProperties(Proc: TGetPropEditProc); virtual; function GetPropType: PTypeInfo; function GetValue: string; virtual; procedure GetValues(Proc: TGetStrProc); virtual; procedure Initialize; virtual; procedure Revert; procedure SetValue(const Value: string); virtual; function ValueAvailable: Boolean; property Designer: IFormDesigner read FDesigner; property PrivateDirectory: string read GetPrivateDirectory; property PropCount: Integer read FPropCount; property Value: string read GetValue write SetValue; end; TPropertyEditorClass = class of TPropertyEditor; { TOrdinalProperty The base class of all ordinal property editors. It established that ordinal properties are all equal if the GetOrdValue all return the same value. } TOrdinalProperty = class(TPropertyEditor) function AllEqual: Boolean; override; function GetEditLimit: Integer; override; end; { TIntegerProperty Default editor for all Longint properties and all subtypes of the Longint type (i.e. Integer, Word, 1..10, etc.). Retricts the value entrered into the property to the range of the sub-type. } TIntegerProperty = class(TOrdinalProperty) public function GetValue: string; override; procedure SetValue(const Value: string); override; end; { TCharProperty Default editor for all Char properties and sub-types of Char (i.e. Char, 'A'..'Z', etc.). } TCharProperty = class(TOrdinalProperty) public function GetValue: string; override; procedure SetValue(const Value: string); override; end; { TEnumProperty The default property editor for all enumerated properties (e.g. TShape = (sCircle, sTriangle, sSquare), etc.). } TEnumProperty = class(TOrdinalProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; TBoolProperty = class(TEnumProperty) function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TFloatProperty The default property editor for all floating point types (e.g. Float, Single, Double, etc.) } TFloatProperty = class(TPropertyEditor) public function AllEqual: Boolean; override; function GetValue: string; override; procedure SetValue(const Value: string); override; end; { TStringProperty The default property editor for all strings and sub types (e.g. string, string[20], etc.). } TStringProperty = class(TPropertyEditor) public function AllEqual: Boolean; override; function GetEditLimit: Integer; override; function GetValue: string; override; procedure SetValue(const Value: string); override; end; { TNestedProperty A property editor that uses the parents Designer, PropList and PropCount. The constructor and destructor do not call inherited, but all derived classes should. This is useful for properties like the TSetElementProperty. } TNestedProperty = class(TPropertyEditor) public constructor Create(Parent: TPropertyEditor); virtual; destructor Destroy; override; end; { TSetElementProperty A property editor that edits an individual set element. GetName is changed to display the set element name instead of the property name and Get/SetValue is changed to reflect the individual element state. This editor is created by the TSetProperty editor. } TSetElementProperty = class(TNestedProperty) private FElement: Integer; protected constructor Create(Parent: TPropertyEditor; AElement: Integer); reintroduce; public function AllEqual: Boolean; override; function GetAttributes: TPropertyAttributes; override; function GetName: string; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TSetProperty Default property editor for all set properties. This editor does not edit the set directly but will display sub-properties for each element of the set. GetValue displays the value of the set in standard set syntax. } TSetProperty = class(TOrdinalProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetProperties(Proc: TGetPropEditProc); override; function GetValue: string; override; end; { TClassProperty Default property editor for all objects. Does not allow modifing the property but does display the class name of the object and will allow the editing of the object's properties as sub-properties of the property. } TClassProperty = class(TPropertyEditor) public function GetAttributes: TPropertyAttributes; override; procedure GetProperties(Proc: TGetPropEditProc); override; function GetValue: string; override; end; { TMethodProperty Property editor for all method properties. } TMethodProperty = class(TPropertyEditor) public function AllEqual: Boolean; override; procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetEditLimit: Integer; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const AValue: string); override; function GetFormMethodName: string; virtual; function GetTrimmedEventName: string; end; { TComponentProperty The default editor for TComponents. It does not allow editing of the properties of the component. It allow the user to set the value of this property to point to a component in the same form that is type compatible with the property being edited (e.g. the ActiveControl property). } TComponentProperty = class(TPropertyEditor) public function GetAttributes: TPropertyAttributes; override; function GetEditLimit: Integer; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TComponentNameProperty Property editor for the Name property. It restricts the name property from being displayed when more than one component is selected. } TComponentNameProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; function GetEditLimit: Integer; override; end; { TFontNameProperty Editor for the TFont.FontName property. Displays a drop-down list of all the fonts known by Windows.} TFontNameProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; { TFontCharsetProperty Editor for the TFont.Charset property. Displays a drop-down list of the character-set by Windows.} TFontCharsetProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TImeNameProperty Editor for the TImeName property. Displays a drop-down list of all the IME names known by Windows.} TImeNameProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; procedure GetValues(Proc: TGetStrProc); override; end; { TColorProperty Property editor for the TColor type. Displays the color as a clXXX value if one exists, otherwise displays the value as hex. Also allows the clXXX value to be picked from a list. } TColorProperty = class(TIntegerProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TCursorProperty Property editor for the TCursor type. Displays the color as a crXXX value if one exists, otherwise displays the value as hex. Also allows the clXXX value to be picked from a list. } TCursorProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TFontProperty Property editor the Font property. Brings up the font dialog as well as allowing the properties of the object to be edited. } TFontProperty = class(TClassProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { TModalResultProperty } TModalResultProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TShortCutProperty Property editor the the ShortCut property. Allows both typing in a short cut value or picking a short-cut value from a list. } TShortCutProperty = class(TOrdinalProperty) public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; end; { TMPFilenameProperty Property editor for the TMediaPlayer. Displays an File Open Dialog for the name of the media file.} TMPFilenameProperty = class(TStringProperty) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; end; { TTabOrderProperty Property editor for the TabOrder property. Prevents the property from being displayed when more than one component is selected. } TTabOrderProperty = class(TIntegerProperty) public function GetAttributes: TPropertyAttributes; override; end; { TCaptionProperty Property editor for the Caption and Text properties. Updates the value of the property for each change instead on when the property is approved. } TCaptionProperty = class(TStringProperty) public function GetAttributes: TPropertyAttributes; override; end; { TDateProperty Property editor for date portion of TDateTime type. } TDateProperty = class(TPropertyEditor) function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure SetValue(const Value: string); override; end; { TTimeProperty Property editor for time portion of TDateTime type. } TTimeProperty = class(TPropertyEditor) function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure SetValue(const Value: string); override; end; { TDateTimeProperty Edits both date and time data... simultaneously! } TDateTimeProperty = class(TPropertyEditor) function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure SetValue(const Value: string); override; end; EPropertyError = class(Exception); { TComponentEditor A component editor is created for each component that is selected in the form designer based on the component's type (see GetComponentEditor and RegisterComponentEditor). When the component is double-clicked the Edit method is called. When the context menu for the component is invoked the GetVerbCount and GetVerb methods are called to build the menu. If one of the verbs are selected ExecuteVerb is called. Paste is called whenever the component is pasted to the clipboard. You only need to create a component editor if you wish to add verbs to the context menu, change the default double-click behavior, or paste an additional clipboard format. The default component editor (TDefaultEditor) implements Edit to searchs the properties of the component and generates (or navigates to) the OnCreate, OnChanged, or OnClick event (whichever it finds first). Whenever the component modifies the component is *must* call Designer.Modified to inform the designer that the form has been modified. Create(AComponent, ADesigner) Called to create the component editor. AComponent is the component to be edited by the editor. ADesigner is an interface to the designer to find controls and create methods (this is not use often). Edit Called when the user double-clicks the component. The component editor can bring up a dialog in responce to this method, for example, or some kind of design expert. If GetVerbCount is greater than zero, edit will execute the first verb in the list (ExecuteVerb(0)). ExecuteVerb(Index) The Index'ed verb was selected by the use off the context menu. The meaning of this is determined by component editor. GetVerb The component editor should return a string that will be displayed in the context menu. It is the responsibility of the component editor to place the & character and the '...' characters as appropriate. GetVerbCount The number of valid indexs to GetVerb and Execute verb. The index assumed to be zero based (i.e. 0..GetVerbCount - 1). Copy Called when the component is being copyied to the clipboard. The component's filed image is already on the clipboard. This gives the component editor a chance to paste a different type of format which is ignored by the designer but might be recoginized by another application. } IComponentEditor = interface ['{ABBE7252-5495-11D1-9FB5-0020AF3D82DA}'] procedure Edit; procedure ExecuteVerb(Index: Integer); function GetIComponent: IComponent; function GetDesigner: IFormDesigner; function GetVerb(Index: Integer): string; function GetVerbCount: Integer; procedure Copy; end; TComponentEditor = class(TInterfacedObject, IComponentEditor) private FComponent: TComponent; FDesigner: IFormDesigner; public constructor Create(AComponent: TComponent; ADesigner: IFormDesigner); virtual; procedure Edit; virtual; procedure ExecuteVerb(Index: Integer); virtual; function GetIComponent: IComponent; function GetDesigner: IFormDesigner; function GetVerb(Index: Integer): string; virtual; function GetVerbCount: Integer; virtual; procedure Copy; virtual; property Component: TComponent read FComponent; property Designer: IFormDesigner read GetDesigner; end; TComponentEditorClass = class of TComponentEditor; IDefaultEditor = interface(IComponentEditor) ['{5484FAE1-5C60-11D1-9FB6-0020AF3D82DA}'] end; TDefaultEditor = class(TComponentEditor, IDefaultEditor) private FFirst: TPropertyEditor; FBest: TPropertyEditor; FContinue: Boolean; procedure CheckEdit(PropertyEditor: TPropertyEditor); protected procedure EditProperty(PropertyEditor: TPropertyEditor; var Continue, FreeEditor: Boolean); virtual; public procedure Edit; override; end; { Global variables initialized internally by the form designer } type TFreeCustomModulesProc = procedure (Group: Integer); var FreeCustomModulesProc: TFreeCustomModulesProc; { RegisterPropertyEditor Registers a new property editor for the given type. When a component is selected the Object Inspector will create a property editor for each of the component's properties. The property editor is created based on the type of the property. If, for example, the property type is an Integer, the property editor for Integer will be created (by default that would be TIntegerProperty). Most properties do not need specialized property editors. For example, if the property is an ordinal type the default property editor will restrict the range to the ordinal subtype range (e.g. a property of type TMyRange = 1..10 will only allow values between 1 and 10 to be entered into the property). Enumerated types will display a drop-down list of all the enumerated values (e.g. TShapes = (sCircle, sSquare, sTriangle) will be edited by a drop-down list containing only sCircle, sSquare and sTriangle). A property editor need only be created if default property editor or none of the existing property editors are sufficient to edit the property. This is typically because the property is an object. The properties are looked up newest to oldest. This allows and existing property editor replaced by a custom property editor. PropertyType The type information pointer returned by the TypeInfo built-in function (e.g. TypeInfo(TMyRange) or TypeInfo(TShapes)). ComponentClass Type type of the component to which to restrict this type editor. This parameter can be left nil which will mean this type editor applies to all properties of PropertyType. PropertyName The name of the property to which to restrict this type editor. This parameter is ignored if ComponentClass is nil. This paramter can be an empty string ('') which will mean that this editor applies to all properties of PropertyType in ComponentClass. EditorClass The class of the editor to be created whenever a property of the type passed in PropertyTypeInfo is displayed in the Object Inspector. The class will be created by calling EditorClass.Create. } procedure RegisterPropertyEditor(PropertyType: PTypeInfo; ComponentClass: TClass; const PropertyName: string; EditorClass: TPropertyEditorClass); type TPropertyMapperFunc = function(Obj: TPersistent; PropInfo: PPropInfo): TPropertyEditorClass; procedure RegisterPropertyMapper(Mapper: TPropertyMapperFunc); procedure GetComponentProperties(Components: TComponentList; Filter: TTypeKinds; Designer: IFormDesigner; Proc: TGetPropEditProc); procedure RegisterComponentEditor(ComponentClass: TComponentClass; ComponentEditor: TComponentEditorClass); function GetComponentEditor(Component: TComponent; Designer: IFormDesigner): TComponentEditor; { Custom modules } { A custom module allows containers that descend from classes other than TForm to be created and edited by the form designer. This is useful for other form like containers (e.g. a report designer) or for specialized forms (e.g. an ActiveForm) or for generic component containers (e.g. a TDataModule). It is assumed that the base class registered will call InitInheritedComponent in its constructor which will initialize the component from the associated DFM file stored in the programs resources. See the constructors of TDataModule and TForm for examples of how to write such a constructor. The following designer assumptions are made, depending on the base components ancestor, If ComponentBaseClass descends from TForm, it is designed by creating an instance of the component as the form. Allows designing TForm descendents and modifying their properties as well as the form properties If ComponentBaseClass descends from TWinControl (but not TForm), it is designed by creating an instance of the control, placing it into a design-time form. The form's client size is in the default size of the control. If ComponentBaseClass descends from TDataModule, it is designed by creating and instance of the class and creating a special non-visual container designer to edit the components and display the icons of the contained components. The module will appear in the project file with a colon and the base class name appended after the component name (e.g. MyDataModle: TDataModule). Note it is not legal to register anything that does not desend from one of the above. TCustomModule class This an instance of this class is created for each custom module that is loaded. This class is also destroyed whenever the module is unloaded. The Saving method is called prior to the file being saved. When the context menu for the module is invoked the GetVerbCount and GetVerb methods are called to build the menu. If one of the verbs are selected ExecuteVerb is called. ExecuteVerb(Index) The Index'ed verb was selected by the use off the context menu. The meaning of this is determined by custom module. GetAttributes Only used for TWinControl object to determine if the control is "client aligned" in the designer or if the object should sized independently from the designer. This is a set for future expansion. GetVerb(Index) The custom module should return a string that will be displayed in the context menu. It is the responsibility of the custom module to place the & character and the '...' characters as appropriate. GetVerbCount The number of valid indexs to GetVerb and Execute verb. The index assumed to be zero based (i.e. 0..GetVerbCount - 1). Saving Called prior to the module being saved. ValidateComponent(Component) ValidateCompoennt is called whenever a component is created by the user for the designer to contain. The intent is for this procedure to raise an exception with a descriptive message if the component is not applicable for the container. For example, a TComponent module should throw an exception if the component descends from TControl. Root This is the instance being designed.} type TCustomModuleAttribute = (cmaVirtualSize); TCustomModuleAttributes = set of TCustomModuleAttribute; TCustomModule = class private FRoot: IComponent; public constructor Create(ARoot: IComponent); virtual; procedure ExecuteVerb(Index: Integer); virtual; function GetAttributes: TCustomModuleAttributes; virtual; function GetVerb(Index: Integer): string; virtual; function GetVerbCount: Integer; virtual; procedure Saving; virtual; procedure ValidateComponent(Component: IComponent); virtual; property Root: IComponent read FRoot; end; TCustomModuleClass = class of TCustomModule; TRegisterCustomModuleProc = procedure (Group: Integer; ComponentBaseClass: TComponentClass; CustomModuleClass: TCustomModuleClass); procedure RegisterCustomModule(ComponentBaseClass: TComponentClass; CustomModuleClass: TCustomModuleClass); var RegisterCustomModuleProc: TRegisterCustomModuleProc; { Routines used by the form designer for package management } function NewEditorGroup: Integer; procedure FreeEditorGroup(Group: Integer); var // number of significant characters in identifiers MaxIdentLength: Byte = 63; implementation uses Menus, Dialogs, Consts, Registry; type TIntegerSet = set of 0..SizeOf(Integer) * 8 - 1; type PPropertyClassRec = ^TPropertyClassRec; TPropertyClassRec = record Group: Integer; PropertyType: PTypeInfo; PropertyName: string; ComponentClass: TClass; EditorClass: TPropertyEditorClass; end; type PPropertyMapperRec = ^TPropertyMapperRec; TPropertyMapperRec = record Group: Integer; Mapper: TPropertyMapperFunc; end; const PropClassMap: array[TTypeKind] of TPropertyEditorClass = ( nil, TIntegerProperty, TCharProperty, TEnumProperty, TFloatProperty, TStringProperty, TSetProperty, TClassProperty, TMethodProperty, TPropertyEditor, TStringProperty, TStringProperty, TPropertyEditor, nil, nil, nil, nil, nil); (* tkArray, tkRecord, kInterface, tkInt64, tkDynArray *) var PropertyClassList: TList = nil; EditorGroupList: TBits = nil; PropertyMapperList: TList = nil; const { context ids for the Font editor and the Color Editor, etc. } hcDFontEditor = 25000; hcDColorEditor = 25010; hcDMediaPlayerOpen = 25020; { TComponentList } constructor TComponentList.Create; begin inherited Create; FList := TList.Create; end; destructor TComponentList.Destroy; begin FList.Free; inherited Destroy; end; function TComponentList.Get(Index: Integer): TPersistent; begin Result := FList[Index]; end; function TComponentList.GetCount: Integer; begin Result := FList.Count; end; function TComponentList.Add(Item: TPersistent): Integer; begin Result := FList.Add(Item); end; function TComponentList.Equals(List: TComponentList): Boolean; var I: Integer; begin Result := False; if List.Count <> FList.Count then Exit; for I := 0 to List.Count - 1 do if List[I] <> FList[I] then Exit; Result := True; end; function TComponentList.Intf_Add(const Item: IPersistent): Integer; begin Result := Add(ExtractPersistent(Item)); end; function TComponentList.Intf_Equals(const List: IDesignerSelections): Boolean; var I: Integer; CompList: IComponentList; P1, P2: IPersistent; begin if List.QueryInterface(IComponentList, CompList) = 0 then Result := CompList.GetComponentList.Equals(Self) else begin Result := False; if List.Count <> FList.Count then Exit; for I := 0 to List.Count - 1 do begin P1 := Intf_Get(I); P2 := List[I]; if ((P1 = nil) and (P2 <> nil)) or (P2 = nil) or not P1.Equals(P2) then Exit; end; Result := True; end; end; function TComponentList.Intf_Get(Index: Integer): IPersistent; begin Result := MakeIPersistent(TPersistent(FList[Index])); end; function TComponentList.GetComponentList: TComponentList; begin Result := Self; end; { TPropertyEditor } constructor TPropertyEditor.Create(const ADesigner: IFormDesigner; APropCount: Integer); begin FDesigner := ADesigner; GetMem(FPropList, APropCount * SizeOf(TInstProp)); FPropCount := APropCount; end; destructor TPropertyEditor.Destroy; begin if FPropList <> nil then FreeMem(FPropList, FPropCount * SizeOf(TInstProp)); end; procedure TPropertyEditor.Activate; begin end; function TPropertyEditor.AllEqual: Boolean; begin Result := FPropCount = 1; end; procedure TPropertyEditor.Edit; type TGetStrFunc = function(const Value: string): Integer of object; var I: Integer; Values: TStringList; AddValue: TGetStrFunc; begin Values := TStringList.Create; Values.Sorted := paSortList in GetAttributes; try AddValue := Values.Add; GetValues(TGetStrProc(AddValue)); if Values.Count > 0 then begin I := Values.IndexOf(Value) + 1; if I = Values.Count then I := 0; Value := Values[I]; end; finally Values.Free; end; end; function TPropertyEditor.AutoFill: Boolean; begin Result := True; end; function TPropertyEditor.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paRevertable]; end; function TPropertyEditor.GetComponent(Index: Integer): TPersistent; begin Result := FPropList^[Index].Instance; end; function TPropertyEditor.GetFloatValue: Extended; begin Result := GetFloatValueAt(0); end; function TPropertyEditor.GetFloatValueAt(Index: Integer): Extended; begin with FPropList^[Index] do Result := GetFloatProp(Instance, PropInfo); end; function TPropertyEditor.GetMethodValue: TMethod; begin Result := GetMethodValueAt(0); end; function TPropertyEditor.GetMethodValueAt(Index: Integer): TMethod; begin with FPropList^[Index] do Result := GetMethodProp(Instance, PropInfo); end; function TPropertyEditor.GetEditLimit: Integer; begin Result := 255; end; function TPropertyEditor.GetName: string; begin Result := FPropList^[0].PropInfo^.Name; end; function TPropertyEditor.GetOrdValue: Longint; begin Result := GetOrdValueAt(0); end; function TPropertyEditor.GetOrdValueAt(Index: Integer): Longint; begin with FPropList^[Index] do Result := GetOrdProp(Instance, PropInfo); end; function TPropertyEditor.GetPrivateDirectory: string; begin Result := Designer.GetPrivateDirectory; end; procedure TPropertyEditor.GetProperties(Proc: TGetPropEditProc); begin end; function TPropertyEditor.GetPropInfo: PPropInfo; begin Result := FPropList^[0].PropInfo; end; function TPropertyEditor.GetPropType: PTypeInfo; begin Result := FPropList^[0].PropInfo^.PropType^; end; function TPropertyEditor.GetStrValue: string; begin Result := GetStrValueAt(0); end; function TPropertyEditor.GetStrValueAt(Index: Integer): string; begin with FPropList^[Index] do Result := GetStrProp(Instance, PropInfo); end; function TPropertyEditor.GetVarValue: Variant; begin Result := GetVarValueAt(0); end; function TPropertyEditor.GetVarValueAt(Index: Integer): Variant; begin with FPropList^[Index] do Result := GetVariantProp(Instance, PropInfo); end; function TPropertyEditor.GetValue: string; begin Result := srUnknown; end; procedure TPropertyEditor.GetValues(Proc: TGetStrProc); begin end; procedure TPropertyEditor.Initialize; begin end; procedure TPropertyEditor.Modified; begin Designer.Modified; end; procedure TPropertyEditor.SetFloatValue(Value: Extended); var I: Integer; begin for I := 0 to FPropCount - 1 do with FPropList^[I] do SetFloatProp(Instance, PropInfo, Value); Modified; end; procedure TPropertyEditor.SetMethodValue(const Value: TMethod); var I: Integer; begin for I := 0 to FPropCount - 1 do with FPropList^[I] do SetMethodProp(Instance, PropInfo, Value); Modified; end; procedure TPropertyEditor.SetOrdValue(Value: Longint); var I: Integer; begin for I := 0 to FPropCount - 1 do with FPropList^[I] do SetOrdProp(Instance, PropInfo, Value); Modified; end; procedure TPropertyEditor.SetPropEntry(Index: Integer; AInstance: TPersistent; APropInfo: PPropInfo); begin with FPropList^[Index] do begin Instance := AInstance; PropInfo := APropInfo; end; end; procedure TPropertyEditor.SetStrValue(const Value: string); var I: Integer; begin for I := 0 to FPropCount - 1 do with FPropList^[I] do SetStrProp(Instance, PropInfo, Value); Modified; end; procedure TPropertyEditor.SetVarValue(const Value: Variant); var I: Integer; begin for I := 0 to FPropCount - 1 do with FPropList^[I] do SetVariantProp(Instance, PropInfo, Value); Modified; end; procedure TPropertyEditor.Revert; var I: Integer; begin for I := 0 to FPropCount - 1 do with FPropList^[I] do Designer.Revert(Instance, PropInfo); end; procedure TPropertyEditor.SetValue(const Value: string); begin end; function TPropertyEditor.ValueAvailable: Boolean; var I: Integer; S: string; begin Result := True; for I := 0 to FPropCount - 1 do begin if (FPropList^[I].Instance is TComponent) and (csCheckPropAvail in TComponent(FPropList^[I].Instance).ComponentStyle) then begin try S := GetValue; AllEqual; except Result := False; end; Exit; end; end; end; { TOrdinalProperty } function TOrdinalProperty.AllEqual: Boolean; var I: Integer; V: Longint; begin Result := False; if PropCount > 1 then begin V := GetOrdValue; for I := 1 to PropCount - 1 do if GetOrdValueAt(I) <> V then Exit; end; Result := True; end; function TOrdinalProperty.GetEditLimit: Integer; begin Result := 63; end; { TIntegerProperty } function TIntegerProperty.GetValue: string; begin Result := IntToStr(GetOrdValue); end; procedure TIntegerProperty.SetValue(const Value: String); var L: Longint; begin L := StrToInt(Value); with GetTypeData(GetPropType)^ do if (L < MinValue) or (L > MaxValue) then {NOTE: C++ 'unsigned long', unlike Cardinals, stretch up to 4G } if not ((MinValue = 0) and (MaxValue = -1)) then raise EPropertyError.CreateFmt(SOutOfRange, [MinValue, MaxValue]); SetOrdValue(L); end; { TCharProperty } function TCharProperty.GetValue: string; var Ch: Char; begin Ch := Chr(GetOrdValue); if Ch in [#33..#127] then Result := Ch else FmtStr(Result, '#%d', [Ord(Ch)]); end; procedure TCharProperty.SetValue(const Value: string); var L: Longint; begin if Length(Value) = 0 then L := 0 else if Length(Value) = 1 then L := Ord(Value[1]) else if Value[1] = '#' then L := StrToInt(Copy(Value, 2, Maxint)) else raise EPropertyError.Create(SInvalidPropertyValue); with GetTypeData(GetPropType)^ do if (L < MinValue) or (L > MaxValue) then raise EPropertyError.CreateFmt(SOutOfRange, [MinValue, MaxValue]); SetOrdValue(L); end; { TEnumProperty } function TEnumProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList, paRevertable]; end; function TEnumProperty.GetValue: string; var L: Longint; begin L := GetOrdValue; with GetTypeData(GetPropType)^ do if (L < MinValue) or (L > MaxValue) then L := MaxValue; Result := GetEnumName(GetPropType, L); end; procedure TEnumProperty.GetValues(Proc: TGetStrProc); var I: Integer; EnumType: PTypeInfo; begin EnumType := GetPropType; with GetTypeData(EnumType)^ do for I := MinValue to MaxValue do Proc(GetEnumName(EnumType, I)); end; procedure TEnumProperty.SetValue(const Value: string); var I: Integer; begin I := GetEnumValue(GetPropType, Value); if I < 0 then raise EPropertyError.Create(SInvalidPropertyValue); SetOrdValue(I); end; { TBoolProperty } function TBoolProperty.GetValue: string; begin if GetOrdValue = 0 then Result := 'False' else Result := 'True'; end; procedure TBoolProperty.GetValues(Proc: TGetStrProc); begin Proc('False'); Proc('True'); end; procedure TBoolProperty.SetValue(const Value: string); var I: Integer; begin if CompareText(Value, 'False') = 0 then I := 0 else if CompareText(Value, 'True') = 0 then I := -1 else I := StrToInt(Value); SetOrdValue(I); end; { TFloatProperty } function TFloatProperty.AllEqual: Boolean; var I: Integer; V: Extended; begin Result := False; if PropCount > 1 then begin V := GetFloatValue; for I := 1 to PropCount - 1 do if GetFloatValueAt(I) <> V then Exit; end; Result := True; end; function TFloatProperty.GetValue: string; const Precisions: array[TFloatType] of Integer = (7, 15, 18, 18, 18); begin Result := FloatToStrF(GetFloatValue, ffGeneral, Precisions[GetTypeData(GetPropType)^.FloatType], 0); end; procedure TFloatProperty.SetValue(const Value: string); begin SetFloatValue(StrToFloat(Value)); end; { TStringProperty } function TStringProperty.AllEqual: Boolean; var I: Integer; V: string; begin Result := False; if PropCount > 1 then begin V := GetStrValue; for I := 1 to PropCount - 1 do if GetStrValueAt(I) <> V then Exit; end; Result := True; end; function TStringProperty.GetEditLimit: Integer; begin if GetPropType^.Kind = tkString then Result := GetTypeData(GetPropType)^.MaxLength else Result := 255; end; function TStringProperty.GetValue: string; begin Result := GetStrValue; end; procedure TStringProperty.SetValue(const Value: string); begin SetStrValue(Value); end; { TComponentNameProperty } function TComponentNameProperty.GetAttributes: TPropertyAttributes; begin Result := []; end; function TComponentNameProperty.GetEditLimit: Integer; begin Result := MaxIdentLength; end; { TNestedProperty } constructor TNestedProperty.Create(Parent: TPropertyEditor); begin FDesigner := Parent.Designer; FPropList := Parent.FPropList; FPropCount := Parent.PropCount; end; destructor TNestedProperty.Destroy; begin end; { TSetElementProperty } constructor TSetElementProperty.Create(Parent: TPropertyEditor; AElement: Integer); begin inherited Create(Parent); FElement := AElement; end; function TSetElementProperty.AllEqual: Boolean; var I: Integer; S: TIntegerSet; V: Boolean; begin Result := False; if PropCount > 1 then begin Integer(S) := GetOrdValue; V := FElement in S; for I := 1 to PropCount - 1 do begin Integer(S) := GetOrdValueAt(I); if (FElement in S) <> V then Exit; end; end; Result := True; end; function TSetElementProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList]; end; function TSetElementProperty.GetName: string; begin Result := GetEnumName(GetTypeData(GetPropType)^.CompType^, FElement); end; function TSetElementProperty.GetValue: string; var S: TIntegerSet; begin Integer(S) := GetOrdValue; Result := BooleanIdents[FElement in S]; end; procedure TSetElementProperty.GetValues(Proc: TGetStrProc); begin Proc(BooleanIdents[False]); Proc(BooleanIdents[True]); end; procedure TSetElementProperty.SetValue(const Value: string); var S: TIntegerSet; begin Integer(S) := GetOrdValue; if CompareText(Value, 'True') = 0 then Include(S, FElement) else Exclude(S, FElement); SetOrdValue(Integer(S)); end; { TSetProperty } function TSetProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paReadOnly, paRevertable]; end; procedure TSetProperty.GetProperties(Proc: TGetPropEditProc); var I: Integer; begin with GetTypeData(GetTypeData(GetPropType)^.CompType^)^ do for I := MinValue to MaxValue do Proc(TSetElementProperty.Create(Self, I)); end; function TSetProperty.GetValue: string; var S: TIntegerSet; TypeInfo: PTypeInfo; I: Integer; begin Integer(S) := GetOrdValue; TypeInfo := GetTypeData(GetPropType)^.CompType^; Result := '['; for I := 0 to SizeOf(Integer) * 8 - 1 do if I in S then begin if Length(Result) <> 1 then Result := Result + ','; Result := Result + GetEnumName(TypeInfo, I); end; Result := Result + ']'; end; { TClassProperty } function TClassProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paReadOnly]; end; procedure TClassProperty.GetProperties(Proc: TGetPropEditProc); var I: Integer; Components: TComponentList; begin Components := TComponentList.Create; try for I := 0 to PropCount - 1 do Components.Add(TComponent(GetOrdValueAt(I))); GetComponentProperties(Components, tkProperties, Designer, Proc); finally Components.Free; end; end; function TClassProperty.GetValue: string; begin FmtStr(Result, '(%s)', [GetPropType^.Name]); end; { TComponentProperty } function TComponentProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList, paRevertable]; end; function TComponentProperty.GetEditLimit: Integer; begin Result := 127; end; function TComponentProperty.GetValue: string; begin Result := Designer.GetComponentName(TComponent(GetOrdValue)); end; procedure TComponentProperty.GetValues(Proc: TGetStrProc); begin Designer.GetComponentNames(GetTypeData(GetPropType), Proc); end; procedure TComponentProperty.SetValue(const Value: string); var Component: TComponent; begin if Value = '' then Component := nil else begin Component := Designer.GetComponent(Value); if not (Component is GetTypeData(GetPropType)^.ClassType) then raise EPropertyError.Create(SInvalidPropertyValue); end; SetOrdValue(Longint(Component)); end; { TMethodProperty } function TMethodProperty.AllEqual: Boolean; var I: Integer; V, T: TMethod; begin Result := False; if PropCount > 1 then begin V := GetMethodValue; for I := 1 to PropCount - 1 do begin T := GetMethodValueAt(I); if (T.Code <> V.Code) or (T.Data <> V.Data) then Exit; end; end; Result := True; end; procedure TMethodProperty.Edit; var FormMethodName: string; begin FormMethodName := GetValue; if (FormMethodName = '') or Designer.MethodFromAncestor(GetMethodValue) then begin if FormMethodName = '' then FormMethodName := GetFormMethodName; if FormMethodName = '' then raise EPropertyError.Create(SCannotCreateName); SetMethodValue(Designer.CreateMethod(FormMethodName, GetTypeData(GetPropType))); end; Designer.ShowMethod(FormMethodName); end; function TMethodProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList, paRevertable]; end; function TMethodProperty.GetEditLimit: Integer; begin Result := MaxIdentLength; end; function TMethodProperty.GetFormMethodName: string; var I: Integer; begin if GetComponent(0) = Designer.Form then Result := 'Form' else begin Result := Designer.GetObjectName(GetComponent(0)); for I := Length(Result) downto 1 do if Result[I] in ['.','[',']'] then Delete(Result, I, 1); end; if Result = '' then raise EPropertyError.Create(SCannotCreateName); Result := Result + GetTrimmedEventName; end; function TMethodProperty.GetTrimmedEventName: string; begin Result := GetName; if (Length(Result) >= 2) and (Result[1] in ['O','o']) and (Result[2] in ['N','n']) then Delete(Result,1,2); end; function TMethodProperty.GetValue: string; begin Result := Designer.GetMethodName(GetMethodValue); end; procedure TMethodProperty.GetValues(Proc: TGetStrProc); begin Designer.GetMethods(GetTypeData(GetPropType), Proc); end; procedure TMethodProperty.SetValue(const AValue: string); var NewMethod: Boolean; CurValue: string; begin CurValue:= GetValue; if (CurValue <> '') and (AValue <> '') and ((CompareText(CurValue, AValue) = 0) or not Designer.MethodExists(AValue)) then Designer.RenameMethod(CurValue, AValue) else begin NewMethod := (AValue <> '') and not Designer.MethodExists(AValue); SetMethodValue(Designer.CreateMethod(AValue, GetTypeData(GetPropType))); if NewMethod then Designer.ShowMethod(AValue); end; end; { TFontNameProperty } function TFontNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList, paRevertable]; end; procedure TFontNameProperty.GetValues(Proc: TGetStrProc); var I: Integer; begin for I := 0 to Screen.Fonts.Count - 1 do Proc(Screen.Fonts[I]); end; { TFontCharsetProperty } function TFontCharsetProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSortList, paValueList]; end; function TFontCharsetProperty.GetValue: string; begin if not CharsetToIdent(TFontCharset(GetOrdValue), Result) then FmtStr(Result, '%d', [GetOrdValue]); end; procedure TFontCharsetProperty.GetValues(Proc: TGetStrProc); begin GetCharsetValues(Proc); end; procedure TFontCharsetProperty.SetValue(const Value: string); var NewValue: Longint; begin if IdentToCharset(Value, NewValue) then SetOrdValue(NewValue) else inherited SetValue(Value); end; { TImeNameProperty } function TImeNameProperty.GetAttributes: TPropertyAttributes; begin Result := [paValueList, paSortList, paMultiSelect]; end; procedure TImeNameProperty.GetValues(Proc: TGetStrProc); var I: Integer; begin for I := 0 to Screen.Imes.Count - 1 do Proc(Screen.Imes[I]); end; { TMPFilenameProperty } procedure TMPFilenameProperty.Edit; var MPFileOpen: TOpenDialog; begin MPFileOpen := TOpenDialog.Create(Application); MPFileOpen.Filename := GetValue; MPFileOpen.Filter := SMPOpenFilter; MPFileOpen.HelpContext := hcDMediaPlayerOpen; MPFileOpen.Options := MPFileOpen.Options + [ofShowHelp, ofPathMustExist, ofFileMustExist]; try if MPFileOpen.Execute then SetValue(MPFileOpen.Filename); finally MPFileOpen.Free; end; end; function TMPFilenameProperty.GetAttributes: TPropertyAttributes; begin Result := [paDialog, paRevertable]; end; { TColorProperty } procedure TColorProperty.Edit; var ColorDialog: TColorDialog; IniFile: TRegIniFile; procedure GetCustomColors; begin IniFile := TRegIniFile.Create('\Software\Borland\Delphi\3.0'); try IniFile.ReadSectionValues(SCustomColors, ColorDialog.CustomColors); except { Ignore errors reading values } end; end; procedure SaveCustomColors; var I, P: Integer; S: string; begin if IniFile <> nil then with ColorDialog do for I := 0 to CustomColors.Count - 1 do begin S := CustomColors.Strings[I]; P := Pos('=', S); if P <> 0 then begin S := Copy(S, 1, P - 1); IniFile.WriteString(SCustomColors, S, CustomColors.Values[S]); end; end; end; begin IniFile := nil; ColorDialog := TColorDialog.Create(Application); try GetCustomColors; ColorDialog.Color := GetOrdValue; ColorDialog.HelpContext := hcDColorEditor; ColorDialog.Options := [cdShowHelp]; if ColorDialog.Execute then SetOrdValue(ColorDialog.Color); SaveCustomColors; finally if IniFile <> nil then IniFile.Free; ColorDialog.Free; end; end; function TColorProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paDialog, paValueList, paRevertable]; end; function TColorProperty.GetValue: string; begin Result := ColorToString(TColor(GetOrdValue)); end; procedure TColorProperty.GetValues(Proc: TGetStrProc); begin GetColorValues(Proc); end; procedure TColorProperty.SetValue(const Value: string); var NewValue: Longint; begin if IdentToColor(Value, NewValue) then SetOrdValue(NewValue) else inherited SetValue(Value); end; { TCursorProperty } function TCursorProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paSortList, paRevertable]; end; function TCursorProperty.GetValue: string; begin Result := CursorToString(TCursor(GetOrdValue)); end; procedure TCursorProperty.GetValues(Proc: TGetStrProc); begin GetCursorValues(Proc); end; procedure TCursorProperty.SetValue(const Value: string); var NewValue: Longint; begin if IdentToCursor(Value, NewValue) then SetOrdValue(NewValue) else inherited SetValue(Value); end; { TFontProperty } procedure TFontProperty.Edit; var FontDialog: TFontDialog; begin FontDialog := TFontDialog.Create(Application); try FontDialog.Font := TFont(GetOrdValue); FontDialog.HelpContext := hcDFontEditor; FontDialog.Options := FontDialog.Options + [fdShowHelp, fdForceFontExist]; if FontDialog.Execute then SetOrdValue(Longint(FontDialog.Font)); finally FontDialog.Free; end; end; function TFontProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paSubProperties, paDialog, paReadOnly]; end; { TModalResultProperty } const ModalResults: array[mrNone..mrYesToAll] of string = ( 'mrNone', 'mrOk', 'mrCancel', 'mrAbort', 'mrRetry', 'mrIgnore', 'mrYes', 'mrNo', 'mrAll', 'mrNoToAll', 'mrYesToAll'); function TModalResultProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paRevertable]; end; function TModalResultProperty.GetValue: string; var CurValue: Longint; begin CurValue := GetOrdValue; case CurValue of Low(ModalResults)..High(ModalResults): Result := ModalResults[CurValue]; else Result := IntToStr(CurValue); end; end; procedure TModalResultProperty.GetValues(Proc: TGetStrProc); var I: Integer; begin for I := Low(ModalResults) to High(ModalResults) do Proc(ModalResults[I]); end; procedure TModalResultProperty.SetValue(const Value: string); var I: Integer; begin if Value = '' then begin SetOrdValue(0); Exit; end; for I := Low(ModalResults) to High(ModalResults) do if CompareText(ModalResults[I], Value) = 0 then begin SetOrdValue(I); Exit; end; inherited SetValue(Value); end; { TShortCutProperty } const ShortCuts: array[0..108] of TShortCut = ( scNone, Byte('A') or scCtrl, Byte('B') or scCtrl, Byte('C') or scCtrl, Byte('D') or scCtrl, Byte('E') or scCtrl, Byte('F') or scCtrl, Byte('G') or scCtrl, Byte('H') or scCtrl, Byte('I') or scCtrl, Byte('J') or scCtrl, Byte('K') or scCtrl, Byte('L') or scCtrl, Byte('M') or scCtrl, Byte('N') or scCtrl, Byte('O') or scCtrl, Byte('P') or scCtrl, Byte('Q') or scCtrl, Byte('R') or scCtrl, Byte('S') or scCtrl, Byte('T') or scCtrl, Byte('U') or scCtrl, Byte('V') or scCtrl, Byte('W') or scCtrl, Byte('X') or scCtrl, Byte('Y') or scCtrl, Byte('Z') or scCtrl, Byte('A') or scCtrl or scAlt, Byte('B') or scCtrl or scAlt, Byte('C') or scCtrl or scAlt, Byte('D') or scCtrl or scAlt, Byte('E') or scCtrl or scAlt, Byte('F') or scCtrl or scAlt, Byte('G') or scCtrl or scAlt, Byte('H') or scCtrl or scAlt, Byte('I') or scCtrl or scAlt, Byte('J') or scCtrl or scAlt, Byte('K') or scCtrl or scAlt, Byte('L') or scCtrl or scAlt, Byte('M') or scCtrl or scAlt, Byte('N') or scCtrl or scAlt, Byte('O') or scCtrl or scAlt, Byte('P') or scCtrl or scAlt, Byte('Q') or scCtrl or scAlt, Byte('R') or scCtrl or scAlt, Byte('S') or scCtrl or scAlt, Byte('T') or scCtrl or scAlt, Byte('U') or scCtrl or scAlt, Byte('V') or scCtrl or scAlt, Byte('W') or scCtrl or scAlt, Byte('X') or scCtrl or scAlt, Byte('Y') or scCtrl or scAlt, Byte('Z') or scCtrl or scAlt, VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12, VK_F1 or scCtrl, VK_F2 or scCtrl, VK_F3 or scCtrl, VK_F4 or scCtrl, VK_F5 or scCtrl, VK_F6 or scCtrl, VK_F7 or scCtrl, VK_F8 or scCtrl, VK_F9 or scCtrl, VK_F10 or scCtrl, VK_F11 or scCtrl, VK_F12 or scCtrl, VK_F1 or scShift, VK_F2 or scShift, VK_F3 or scShift, VK_F4 or scShift, VK_F5 or scShift, VK_F6 or scShift, VK_F7 or scShift, VK_F8 or scShift, VK_F9 or scShift, VK_F10 or scShift, VK_F11 or scShift, VK_F12 or scShift, VK_F1 or scShift or scCtrl, VK_F2 or scShift or scCtrl, VK_F3 or scShift or scCtrl, VK_F4 or scShift or scCtrl, VK_F5 or scShift or scCtrl, VK_F6 or scShift or scCtrl, VK_F7 or scShift or scCtrl, VK_F8 or scShift or scCtrl, VK_F9 or scShift or scCtrl, VK_F10 or scShift or scCtrl, VK_F11 or scShift or scCtrl, VK_F12 or scShift or scCtrl, VK_INSERT, VK_INSERT or scShift, VK_INSERT or scCtrl, VK_DELETE, VK_DELETE or scShift, VK_DELETE or scCtrl, VK_BACK or scAlt, VK_BACK or scShift or scAlt); function TShortCutProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paValueList, paRevertable]; end; function TShortCutProperty.GetValue: string; var CurValue: TShortCut; begin CurValue := GetOrdValue; if CurValue = scNone then Result := srNone else Result := ShortCutToText(CurValue); end; procedure TShortCutProperty.GetValues(Proc: TGetStrProc); var I: Integer; begin Proc(srNone); for I := 1 to High(ShortCuts) do Proc(ShortCutToText(ShortCuts[I])); end; procedure TShortCutProperty.SetValue(const Value: string); var NewValue: TShortCut; begin NewValue := 0; if (Value <> '') and (AnsiCompareText(Value, srNone) <> 0) then begin NewValue := TextToShortCut(Value); if NewValue = 0 then raise EPropertyError.Create(SInvalidPropertyValue); end; SetOrdValue(NewValue); end; { TTabOrderProperty } function TTabOrderProperty.GetAttributes: TPropertyAttributes; begin Result := []; end; { TCaptionProperty } function TCaptionProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paAutoUpdate, paRevertable]; end; { TDateProperty } function TDateProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paRevertable]; end; function TDateProperty.GetValue: string; var DT: TDateTime; begin DT := GetFloatValue; if DT = 0.0 then Result := '' else Result := DateToStr(DT); end; procedure TDateProperty.SetValue(const Value: string); var DT: TDateTime; begin if Value = '' then DT := 0.0 else DT := StrToDate(Value); SetFloatValue(DT); end; { TTimeProperty } function TTimeProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paRevertable]; end; function TTimeProperty.GetValue: string; var DT: TDateTime; begin DT := GetFloatValue; if DT = 0.0 then Result := '' else Result := TimeToStr(DT); end; procedure TTimeProperty.SetValue(const Value: string); var DT: TDateTime; begin if Value = '' then DT := 0.0 else DT := StrToTime(Value); SetFloatValue(DT); end; function TDateTimeProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paRevertable]; end; function TDateTimeProperty.GetValue: string; var DT: TDateTime; begin DT := GetFloatValue; if DT = 0.0 then Result := '' else Result := DateTimeToStr(DT); end; procedure TDateTimeProperty.SetValue(const Value: string); var DT: TDateTime; begin if Value = '' then DT := 0.0 else DT := StrToDateTime(Value); SetFloatValue(DT); end; { TPropInfoList } type TPropInfoList = class private FList: PPropList; FCount: Integer; FSize: Integer; function Get(Index: Integer): PPropInfo; public constructor Create(Instance: TPersistent; Filter: TTypeKinds); destructor Destroy; override; function Contains(P: PPropInfo): Boolean; procedure Delete(Index: Integer); procedure Intersect(List: TPropInfoList); property Count: Integer read FCount; property Items[Index: Integer]: PPropInfo read Get; default; end; constructor TPropInfoList.Create(Instance: TPersistent; Filter: TTypeKinds); begin FCount := GetPropList(Instance.ClassInfo, Filter, nil); FSize := FCount * SizeOf(Pointer); GetMem(FList, FSize); GetPropList(Instance.ClassInfo, Filter, FList); end; destructor TPropInfoList.Destroy; begin if FList <> nil then FreeMem(FList, FSize); end; function TPropInfoList.Contains(P: PPropInfo): Boolean; var I: Integer; begin for I := 0 to FCount - 1 do with FList^[I]^ do if (PropType^ = P^.PropType^) and (CompareText(Name, P^.Name) = 0) then begin Result := True; Exit; end; Result := False; end; procedure TPropInfoList.Delete(Index: Integer); begin Dec(FCount); if Index < FCount then Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(Pointer)); end; function TPropInfoList.Get(Index: Integer): PPropInfo; begin Result := FList^[Index]; end; procedure TPropInfoList.Intersect(List: TPropInfoList); var I: Integer; begin for I := FCount - 1 downto 0 do if not List.Contains(FList^[I]) then Delete(I); end; { GetComponentProperties } procedure RegisterPropertyEditor(PropertyType: PTypeInfo; ComponentClass: TClass; const PropertyName: string; EditorClass: TPropertyEditorClass); var P: PPropertyClassRec; begin if PropertyClassList = nil then PropertyClassList := TList.Create; New(P); P.Group := CurrentGroup; P.PropertyType := PropertyType; P.ComponentClass := ComponentClass; P.PropertyName := ''; if Assigned(ComponentClass) then P^.PropertyName := PropertyName; P.EditorClass := EditorClass; PropertyClassList.Insert(0, P); end; procedure RegisterPropertyMapper(Mapper: TPropertyMapperFunc); var P: PPropertyMapperRec; begin if PropertyMapperList = nil then PropertyMapperList := TList.Create; New(P); P^.Group := CurrentGroup; P^.Mapper := Mapper; PropertyMapperList.Insert(0, P); end; function GetEditorClass(PropInfo: PPropInfo; Obj: TPersistent): TPropertyEditorClass; var PropType: PTypeInfo; P, C: PPropertyClassRec; I: Integer; begin if PropertyMapperList <> nil then begin for I := 0 to PropertyMapperList.Count -1 do with PPropertyMapperRec(PropertyMapperList[I])^ do begin Result := Mapper(Obj, PropInfo); if Result <> nil then Exit; end; end; PropType := PropInfo^.PropType^; I := 0; C := nil; while I < PropertyClassList.Count do begin P := PropertyClassList[I]; if ((P^.PropertyType = PropType) or ((P^.PropertyType^.Kind = PropType.Kind) and (P^.PropertyType^.Name = PropType.Name) ) ) or ( (PropType^.Kind = tkClass) and (P^.PropertyType^.Kind = tkClass) and GetTypeData(PropType)^.ClassType.InheritsFrom(GetTypeData(P^.PropertyType)^.ClassType) ) then if ((P^.ComponentClass = nil) or (Obj.InheritsFrom(P^.ComponentClass))) and ((P^.PropertyName = '') or (CompareText(PropInfo^.Name, P^.PropertyName) = 0)) then if (C = nil) or // see if P is better match than C ((C^.ComponentClass = nil) and (P^.ComponentClass <> nil)) or ((C^.PropertyName = '') and (P^.PropertyName <> '')) or // P's proptype match is exact, but C's isn't ((C^.PropertyType <> PropType) and (P^.PropertyType = PropType)) or // P's proptype is more specific than C's proptype ((P^.PropertyType <> C^.PropertyType) and (P^.PropertyType^.Kind = tkClass) and (C^.PropertyType^.Kind = tkClass) and GetTypeData(P^.PropertyType)^.ClassType.InheritsFrom( GetTypeData(C^.PropertyType)^.ClassType)) or // P's component class is more specific than C's component class ((P^.ComponentClass <> nil) and (C^.ComponentClass <> nil) and (P^.ComponentClass <> C^.ComponentClass) and (P^.ComponentClass.InheritsFrom(C^.ComponentClass))) then C := P; Inc(I); end; if C <> nil then Result := C^.EditorClass else Result := PropClassMap[PropType^.Kind]; end; procedure GetComponentProperties(Components: TComponentList; Filter: TTypeKinds; Designer: IFormDesigner; Proc: TGetPropEditProc); var I, J, CompCount: Integer; CompType: TClass; Candidates: TPropInfoList; PropLists: TList; Editor: TPropertyEditor; EdClass: TPropertyEditorClass; PropInfo: PPropInfo; AddEditor: Boolean; Obj: TPersistent; begin if (Components = nil) or (Components.Count = 0) then Exit; CompCount := Components.Count; Obj := Components[0]; CompType := Components[0].ClassType; Candidates := TPropInfoList.Create(Components[0], Filter); try for I := Candidates.Count - 1 downto 0 do begin PropInfo := Candidates[I]; EdClass := GetEditorClass(PropInfo, Obj); if EdClass = nil then Candidates.Delete(I) else begin Editor := EdClass.Create(Designer, 1); try Editor.SetPropEntry(0, Components[0], PropInfo); Editor.Initialize; with PropInfo^ do if (GetProc = nil) or ((PropType^.Kind <> tkClass) and (SetProc = nil)) or ((CompCount > 1) and not (paMultiSelect in Editor.GetAttributes)) or not Editor.ValueAvailable then Candidates.Delete(I); finally Editor.Free; end; end; end; PropLists := TList.Create; try PropLists.Capacity := CompCount; for I := 0 to CompCount - 1 do PropLists.Add(TPropInfoList.Create(Components[I], Filter)); for I := 0 to CompCount - 1 do Candidates.Intersect(TPropInfoList(PropLists[I])); for I := 0 to CompCount - 1 do TPropInfoList(PropLists[I]).Intersect(Candidates); for I := 0 to Candidates.Count - 1 do begin EdClass := GetEditorClass(Candidates[I], Obj); if EdClass = nil then Continue; Editor := EdClass.Create(Designer, CompCount); try AddEditor := True; for J := 0 to CompCount - 1 do begin if (Components[J].ClassType <> CompType) and (GetEditorClass(TPropInfoList(PropLists[J])[I], Components[J]) <> Editor.ClassType) then begin AddEditor := False; Break; end; Editor.SetPropEntry(J, Components[J], TPropInfoList(PropLists[J])[I]); end; except Editor.Free; raise; end; if AddEditor then begin Editor.Initialize; if Editor.ValueAvailable then Proc(Editor) else Editor.Free; end else Editor.Free; end; finally for I := 0 to PropLists.Count - 1 do TPropInfoList(PropLists[I]).Free; PropLists.Free; end; finally Candidates.Free; end; end; { RegisterComponentEditor } type PComponentClassRec = ^TComponentClassRec; TComponentClassRec = record Group: Integer; ComponentClass: TComponentClass; EditorClass: TComponentEditorClass; end; var ComponentClassList: TList = nil; procedure RegisterComponentEditor(ComponentClass: TComponentClass; ComponentEditor: TComponentEditorClass); var P: PComponentClassRec; begin if ComponentClassList = nil then ComponentClassList := TList.Create; New(P); P.Group := CurrentGroup; P.ComponentClass := ComponentClass; P.EditorClass := ComponentEditor; ComponentClassList.Insert(0, P); end; { GetComponentEditor } function GetComponentEditor(Component: TComponent; Designer: IFormDesigner): TComponentEditor; var P: PComponentClassRec; I: Integer; ComponentClass: TComponentClass; EditorClass: TComponentEditorClass; begin ComponentClass := TComponentClass(TPersistent); EditorClass := TDefaultEditor; for I := 0 to ComponentClassList.Count-1 do begin P := ComponentClassList[I]; if (Component is P^.ComponentClass) and (P^.ComponentClass <> ComponentClass) and (P^.ComponentClass.InheritsFrom(ComponentClass)) then begin EditorClass := P^.EditorClass; ComponentClass := P^.ComponentClass; end; end; Result := EditorClass.Create(Component, Designer); end; function NewEditorGroup: Integer; begin if EditorGroupList = nil then EditorGroupList := TBits.Create; CurrentGroup := EditorGroupList.OpenBit; EditorGroupList[CurrentGroup] := True; Result := CurrentGroup; end; procedure FreeEditorGroup(Group: Integer); var I: Integer; P: PPropertyClassRec; C: PComponentClassRec; M: PPropertyMapperRec; begin I := PropertyClassList.Count - 1; while I > -1 do begin P := PropertyClassList[I]; if P.Group = Group then begin PropertyClassList.Delete(I); Dispose(P); end; Dec(I); end; I := ComponentClassList.Count - 1; while I > -1 do begin C := ComponentClassList[I]; if C.Group = Group then begin ComponentClassList.Delete(I); Dispose(C); end; Dec(I); end; if PropertyMapperList <> nil then for I := PropertyMapperList.Count-1 downto 0 do begin M := PropertyMapperList[I]; if M.Group = Group then begin PropertyMapperList.Delete(I); Dispose(M); end; end; if Assigned(FreeCustomModulesProc) then FreeCustomModulesProc(Group); if (Group >= 0) and (Group < EditorGroupList.Size) then EditorGroupList[Group] := False; end; { TComponentEditor } constructor TComponentEditor.Create(AComponent: TComponent; ADesigner: IFormDesigner); begin inherited Create; FComponent := AComponent; FDesigner := ADesigner; end; procedure TComponentEditor.Edit; begin if GetVerbCount > 0 then ExecuteVerb(0); end; function TComponentEditor.GetIComponent: IComponent; begin Result := MakeIComponent(FComponent); end; function TComponentEditor.GetDesigner: IFormDesigner; begin Result := FDesigner; end; function TComponentEditor.GetVerbCount: Integer; begin Result := 0; end; function TComponentEditor.GetVerb(Index: Integer): string; begin end; procedure TComponentEditor.ExecuteVerb(Index: Integer); begin end; procedure TComponentEditor.Copy; begin end; { TDefaultEditor } procedure TDefaultEditor.CheckEdit(PropertyEditor: TPropertyEditor); var FreeEditor: Boolean; begin FreeEditor := True; try if FContinue then EditProperty(PropertyEditor, FContinue, FreeEditor); finally if FreeEditor then PropertyEditor.Free; end; end; procedure TDefaultEditor.EditProperty(PropertyEditor: TPropertyEditor; var Continue, FreeEditor: Boolean); var PropName: string; BestName: string; procedure ReplaceBest; begin FBest.Free; FBest := PropertyEditor; if FFirst = FBest then FFirst := nil; FreeEditor := False; end; begin if not Assigned(FFirst) and (PropertyEditor is TMethodProperty) then begin FreeEditor := False; FFirst := PropertyEditor; end; PropName := PropertyEditor.GetName; BestName := ''; if Assigned(FBest) then BestName := FBest.GetName; if CompareText(PropName, 'ONCREATE') = 0 then ReplaceBest else if CompareText(BestName, 'ONCREATE') <> 0 then if CompareText(PropName, 'ONCHANGE') = 0 then ReplaceBest else if CompareText(BestName, 'ONCHANGE') <> 0 then if CompareText(PropName, 'ONCLICK') = 0 then ReplaceBest; end; procedure TDefaultEditor.Edit; var Components: TComponentList; begin Components := TComponentList.Create; try FContinue := True; Components.Add(Component); FFirst := nil; FBest := nil; try GetComponentProperties(Components, tkAny, Designer, CheckEdit); if FContinue then if Assigned(FBest) then FBest.Edit else if Assigned(FFirst) then FFirst.Edit; finally FFirst.Free; FBest.Free; end; finally Components.Free; end; end; { TCustomModule } constructor TCustomModule.Create(ARoot: IComponent); begin inherited Create; FRoot := ARoot; end; procedure TCustomModule.ExecuteVerb(Index: Integer); begin end; function TCustomModule.GetAttributes: TCustomModuleAttributes; begin Result := []; end; function TCustomModule.GetVerb(Index: Integer): string; begin Result := ''; end; function TCustomModule.GetVerbCount: Integer; begin Result := 0; end; procedure TCustomModule.Saving; begin end; procedure TCustomModule.ValidateComponent(Component: IComponent); begin end; procedure RegisterCustomModule(ComponentBaseClass: TComponentClass; CustomModuleClass: TCustomModuleClass); begin if Assigned(RegisterCustomModuleProc) then RegisterCustomModuleProc(CurrentGroup, ComponentBaseClass, CustomModuleClass); end; function MakeIPersistent(Instance: TPersistent): IPersistent; begin if Assigned(MakeIPersistentProc) then Result := MakeIPersistentProc(Instance); end; function ExtractPersistent(const Intf: IPersistent): TPersistent; begin if Intf = nil then Result := nil else Result := (Intf as IImplementation).GetInstance as TPersistent; end; function TryExtractPersistent(const Intf: IPersistent): TPersistent; var Temp: IImplementation; begin Result := nil; if (Intf <> nil) and (Intf.QueryInterface(IImplementation, Temp) = 0) and (Temp.GetInstance <> nil) and (Temp.GetInstance is TPersistent) then Result := TPersistent(Temp.GetInstance); end; function MakeIComponent(Instance: TComponent): IComponent; begin if Assigned(MakeIComponentProc) then Result := MakeIComponentProc(Instance); end; function ExtractComponent(const Intf: IComponent): TComponent; begin if Intf = nil then Result := nil else Result := (Intf as IImplementation).GetInstance as TComponent; end; function TryExtractComponent(const Intf: IComponent): TComponent; var Temp: TPersistent; begin Temp := TryExtractPersistent(Intf); if (Temp <> nil) and (Temp is TComponent) then Result := TComponent(Temp) else Result := nil; end; type { TSelectionList - implements IDesignerSelections } TSelectionList = class(TInterfacedObject, IDesignerSelections) private FList: IInterfaceList; public constructor Create; function Add(const Item: IPersistent): Integer; function Equals(const List: IDesignerSelections): Boolean; function Get(Index: Integer): IPersistent; function GetCount: Integer; end; constructor TSelectionList.Create; begin inherited Create; FList := TInterfaceList.Create; end; function TSelectionList.Add(const Item: IPersistent): Integer; begin Result := FList.Add(Item); end; function TSelectionList.Equals(const List: IDesignerSelections): Boolean; var I: Integer; begin Result := False; if List.Count <> FList.Count then Exit; for I := 0 to List.Count - 1 do if not List[I].Equals(IPersistent(FList[I])) then Exit; Result := True; end; function TSelectionList.Get(Index: Integer): IPersistent; begin Result := IPersistent(FList[Index]); end; function TSelectionList.GetCount: Integer; begin Result := FList.Count; end; function CreateSelectionList: IDesignerSelections; begin Result := TSelectionList.Create; end; initialization finalization EditorGroupList.Free; PropertyClassList.Free; ComponentClassList.Free; PropertyMapperList.Free; end.
{ TODO - changing caption at runtime gives sigsegv } unit MUIPanel; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Controls, MUICommon, LCLIntf; type { MUIPanel } TMUIPanel = class(TCustomControl) private FColorBackground, FColorBorder: TColor; FBorderWidth: integer; protected procedure Paint; override; procedure TextChanged; override; procedure SetColorBackground(AColor: TColor); procedure SetColorBorder(AColor: TColor); procedure SetBorderWidth(AWidth: Integer); public constructor Create(AOwner: TComponent); override; published property Align; property Caption; property Visible; property ColorBackground: TColor read FColorBackground write SetColorBackground; property ColorBorder: TColor read FColorBorder write SetColorBorder; property BorderWidth: Integer read FBorderWidth write SetBorderWidth; property Font; end; implementation { TMUIPanel } procedure TMUIPanel.SetBorderWidth(AWidth: Integer); begin FBorderWidth := AWidth; Invalidate; end; procedure TMUIPanel.TextChanged; begin Inherited; Invalidate; end; procedure TMUIPanel.SetColorBackground(AColor: TColor); begin FColorBackground := AColor; Invalidate; end; procedure TMUIPanel.SetColorBorder(AColor: TColor); begin FColorBorder := AColor; Invalidate; end; procedure TMUIPanel.Paint; begin inherited; // Background Canvas.Brush.Style := bsSolid; Canvas.Brush.Color := FColorBackground; Canvas.FillRect(ClientRect); // Border if(FBorderWidth > 0) then begin Canvas.Brush.Style := bsClear; Canvas.Pen.Color := FColorBorder; Canvas.Rectangle(ClientRect); end; // Text Canvas.Brush.Style := bsClear; Canvas.Font.Color := Font.Color; Canvas.TextOut((ClientWidth-Canvas.TextExtent(Caption).cx) div 2, (ClientHeight-Canvas.TextExtent(Caption).cy) div 2, Caption); end; constructor TMUIPanel.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [csAcceptsControls, csNoFocus, csSetCaption]; Width := 180; Height := 100; Caption := ''; Font.Color := MCOL_CONTAINER_FG; FColorBorder := MCOL_CONTAINER_BORDER; FColorBackground := MCOL_CONTAINER_BG; end; end.
unit Controller; interface uses Generator, PropertyStyle, TechnoType, Classes; type TController = class public class function propertyExists(const aPropertyName: string; const aGenerator: TGenerator): integer; overload; class function propertyExists(const aIndex: integer; const aGenerator: TGenerator): boolean; overload; class function addProperty(const aPropertyName: string; aPropertyStyle: TPropertyStyle; const aGenerator: TGenerator): boolean; class function updateProperty(const aIndex: integer; aNewPropertyStyle: TPropertyStyle; const aGenerator: TGenerator): boolean; class function deleteProperty(const aIndex: integer; const aGenerator: TGenerator): boolean; class function getPropertyStyleString(const aPropertyStyle: TPropertyStyle): string; class function getTechnoString(const aTechnoType: TTechnoType): string; class function getPropertyNameAndStyle(const aIndex: integer; const aGenerator: TGenerator; out aName: string; out aStyle: string): boolean; class function getClassGeneration(const aTechnoType: TTechnoType; const aGenerator: TGenerator): TStringList; end; implementation uses sysUtils, PropertyObj, GeneratorInterface, DelphiGenerator ,windows // for outputdebugstring ; { TController } class function TController.addProperty(const aPropertyName: string; aPropertyStyle: TPropertyStyle; const aGenerator: TGenerator): boolean; begin result := false; if (aPropertyName <> '') and (assigned(aGenerator)) then begin aGenerator.properties.Add(TProperty.Create(aPropertyName, aPropertyStyle)); result := true; end; end; class function TController.deleteProperty(const aIndex: integer; const aGenerator: TGenerator): boolean; var vProperty: TProperty; begin result := false; if propertyExists(aIndex, aGenerator) then begin vProperty := aGenerator.properties.Items[aIndex]; vProperty.Free; aGenerator.properties.Delete(aIndex); result := true; end; end; { procedure TestUseInterface(iInt: IInterface); var iClassGen: IClassGenerator; begin if supports(iInt, iClassGenerator, iClassGen) then begin outputdebugstring('use iClassGen'); iClassGen := nil; end; end; } class function TController.getClassGeneration( const aTechnoType: TTechnoType; const aGenerator: TGenerator): TStringList; var iClassGen: IClassGenerator; vDcg: TDelphiClassGenerator; begin result := nil; if assigned(aGenerator) then begin case aTechnoType of ttDelphi: begin vDcg := TDelphiClassGenerator.Create(aGenerator); iClassGen := vDcg; result := iClassGen.generate; //TestUseInterface(iClassGen); iClassGen := nil; vDcg.Free; end; ttCs: begin // to implement end; ttJava: begin // to implement end; end; end; end; class function TController.getPropertyNameAndStyle(const aIndex: integer; const aGenerator: TGenerator; out aName, aStyle: string): boolean; begin result := false; aName := ''; aStyle := ''; if propertyExists(aIndex, aGenerator) then begin aName := aGenerator.properties.Items[aIndex].name; aStyle := getPropertyStyleString(aGenerator.properties.Items[aIndex].style); result := true; end; end; class function TController.getPropertyStyleString( const aPropertyStyle: TPropertyStyle): string; begin case aPropertyStyle of psInteger: result := 'integer'; psString: result := 'string'; psBoolean: result := 'boolean'; psFloat: result := 'float'; psDouble: result := 'double'; psStringList: result := 'stringList'; end; end; class function TController.getTechnoString( const aTechnoType: TTechnoType): string; begin case aTechnoType of ttDelphi: result := 'Delphi'; ttCs: result := 'C#'; ttJava: result := 'Java'; end; end; class function TController.propertyExists(const aIndex: integer; const aGenerator: TGenerator): boolean; begin result := false; if assigned(aGenerator) and (aIndex > -1) and (aIndex < aGenerator.properties.Count) then result := true; end; class function TController.updateProperty(const aIndex: integer; aNewPropertyStyle: TPropertyStyle; const aGenerator: TGenerator): boolean; var vProperty: TProperty; begin result := false; if propertyExists(aIndex, aGenerator) then begin vProperty := aGenerator.properties.Items[aIndex]; vProperty.style := aNewPropertyStyle; result := true; end; end; class function TController.propertyExists(const aPropertyName: string; const aGenerator: TGenerator): integer; var i: Integer; begin result := -1; if assigned(aGenerator) and (aPropertyName <> '') then begin if assigned(aGenerator.properties) then begin for i := 0 to aGenerator.properties.Count - 1 do begin if uppercase(aGenerator.properties.Items[i].name) = uppercase(aPropertyName) then begin result := i; break; end; end; end; end; end; end.
namespace RemObjects.SDK.CodeGen4; type ResGenerator = public static class private const FirstEmptyResource: array[0..31] of Byte = [$00,$00,$00,$00,$20,$00,$00,$00,$FF,$FF,$00,$00,$FF,$FF,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00]; NAME_RODLFile = 'RODLFILE'; class method WriteLong(buf: array of Byte; var pos: Int32; Value: Int32); begin buf[pos] := Value and $FF; buf[pos+1] := (Value shr 8) and $FF; buf[pos+2] := (Value shr 16) and $FF; buf[pos+3] := (Value shr 24) and $FF; inc(pos,4); end; class method GenerateResBufferFromBuffer(Content: array of Byte; aName: String): array of Byte; begin var len_name := length(aName)*2+2; // aName + #0#0 if len_name mod 4 <> 0 then inc(len_name,2); // extra 0 for dword alignment var len := length(FirstEmptyResource) + 7*4 {sizeOf(Int32)}+ len_name+ length(Content); result := new array of Byte(len); for i: Int32 := 0 to length(FirstEmptyResource)-1 do result[i]:= FirstEmptyResource[i]; var pos: Int32 := length(FirstEmptyResource); var cnt_size: Int32 := length(Content); WriteLong(result, var pos, cnt_size); // Resource Size WriteLong(result, var pos, 32+length(aName)*2); // Header Size WriteLong(result, var pos, $000AFFFF); // RT_RCDATA for i: Int32 := 0 to length(aName)-1 do begin var ch := ord(aName[i]); result[pos] := ch and $FF; result[pos+1] := (ch shr 8) and $FF; inc(pos,2); end; inc(pos,2); // Null terminater if length(aName)*2+2 <> len_name then inc(pos,2); // extra 0 for dword alignment WriteLong(result, var pos, 0); // Data Version WriteLong(result, var pos, 0); // Flags + Language WriteLong(result, var pos, 0); // Resource Version WriteLong(result, var pos, 0); // Characteristics for i: Int32 := 0 to length(Content)-1 do result[pos+i]:= Content[i]; end; class method GenerateResBufferFromFile(RODLFileName: String): array of Byte; begin {$IFDEF FAKESUGAR} if not File.Exists(RODLFileName) then raise new Exception('file is not found: '+RODLFileName); var rodl := File.OpenRead(RODLFileName); {$ELSE} if not File.Exists(RODLFileName) then raise new Exception('file is not found: '+RODLFileName); var rodl := new FileHandle(RODLFileName, FileOpenMode.ReadOnly); {$ENDIF} var cont := new array of Byte(rodl.Length); rodl.Read(cont,0, rodl.Length); exit GenerateResBufferFromBuffer(cont, NAME_RODLFile); end; class method SaveBufferToFile(Content: array of Byte; ResFileName: String); begin {$IFDEF FAKESUGAR} var res := File.Create(ResFileName); {$ELSE} var res := new FileHandle(ResFileName,FileOpenMode.Create); {$ENDIF} res.Write(Content, 0, length(Content)); res.Flush; res.Close; end; public class method GenerateResFile(aBytes: array of Byte; aResFileName: String); begin var lBuffer := GenerateResBufferFromBuffer(aBytes, NAME_RODLFile); SaveBufferToFile(lBuffer, aResFileName) end; class method GenerateResFile(aRODLFileName: String; aResFileName: String); begin var lBuffer := GenerateResBufferFromFile(aRODLFileName); SaveBufferToFile(lBuffer, aResFileName) end; class method GenerateResFile(aRODL: RodlLibrary; aResFileName: String); begin var lContent := Encoding.UTF8.GetBytes(aRODL.ToString()); var lBuffer := GenerateResBufferFromBuffer(lContent, NAME_RODLFile); SaveBufferToFile(lBuffer, aResFileName) end; end; end.
unit class_result_3; interface implementation uses System; type TC1 = class FData: Int32; end; TC2 = class FC: TC1; constructor Create; function GetFC: TC1; end; constructor TC2.Create; begin FC := TC1.Create(); FC.FData := 55; end; function TC2.GetFC: TC1; begin Result := FC; end; var Obj: TC2; Data: Int32; procedure Test; begin Data := Obj.GetFC().FData; end; initialization Obj := TC2.Create(); Test(); finalization Assert(Data = 55); end.
unit FC.Trade.ResultPage; {$I Compiler.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ToolWin, TeEngine, Series, ExtCtrls, TeeProcs, Chart, ExtendControls, DB, MemoryDS, ActnList, Serialization, FC.fmUIDataStorage, FC.Definitions, StockChart.Definitions, FC.Trade.Statistics, Grids, DBGrids, MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid, Menus, ActnPopup, JvExComCtrls, JvComCtrls, StdCtrls,Application.Definitions, PlatformDefaultStyleActnCtrls; type TTradeMode = (tmTest,tmReal); TfrmStockTradeResult = class(TFrame,IActionTarget) acActions: TActionList; acGetStatistic: TAction; acExportOrders: TAction; taOrders: TMemoryDataSet; taOrdersNo: TIntegerField; taOrdersType: TStringField; taOrdersOpenTime: TDateTimeField; taOrdersOpenBarNo: TStringField; taOrdersOpenPrice: TCurrencyField; taOrdersCloseTime: TDateTimeField; taOrdersCloseBarNo: TStringField; taOrdersClosePrice: TCurrencyField; taOrdersProfitPt: TIntegerField; taOrdersProfit: TCurrencyField; taOrdersWorstPt: TIntegerField; taOrdersBestPt: TIntegerField; taOrdersBalance: TCurrencyField; taOrdersCloseComment: TStringField; dsOrder: TDataSource; taOrdersOrderID: TStringField; taOrdersQuality: TIntegerField; acChooseColumns: TAction; pmGrid: TPopupActionBar; ChooseColumns1: TMenuItem; acFitColumns: TAction; FitColumns1: TMenuItem; N1: TMenuItem; Hilightoncharts1: TMenuItem; acAutoScroll: TAction; miAutoScroll: TMenuItem; pcPages: TJvPageControl; tsOrderHistory: TTabSheet; tsGraph: TTabSheet; se: TChart; chartBalance: TFastLineSeries; Splitter1: TSplitter; tcTabs: TFlatTabControl; grOrders: TEditDBGrid; grOrderDetails: TEditDBGrid; taOrderDetails: TMemoryDataSet; taOrderDetailsNoInGroup: TIntegerField; taOrderDetailsOrderID: TStringField; taOrderDetailsText: TStringField; dsOrderDetails: TDataSource; taOrderDetailsWhen: TDateTimeField; taOrdersStopLoss: TCurrencyField; taOrdersTakeProfit: TCurrencyField; taOrdersTrailingStop: TCurrencyField; taOrdersDetailNo: TIntegerField; taOrdersPendingOpenPrice: TCurrencyField; taOrderDetailsPriceAsk: TCurrencyField; taOrderDetailsPriceBid: TCurrencyField; taOrdersOpenComment: TStringField; tsJournal: TTabSheet; grJournal: TEditDBGrid; taOrderDetailsOrderNo: TIntegerField; taOrdersSubsidencePt: TIntegerField; Panel1: TPanel; ToolBar1: TToolBar; buExportOrders: TToolButton; buGetStatistic: TToolButton; ToolButton2: TToolButton; buAutoScroll: TToolButton; laBalance: TLabel; taOrderDetailsNo: TIntegerField; tmFilterDetails: TTimer; ToolButton1: TToolButton; ToolButton3: TToolButton; acFilter: TAction; laElapsedTime: TLabel; Gotothebeginning1: TMenuItem; Gotoend1: TMenuItem; N3: TMenuItem; taOrdersNotes: TStringField; taOrdersColor: TIntegerField; taOrdersCreateTime: TDateTimeField; taOrderDetailsColor: TIntegerField; acHilightOnCharts: TAction; taOrdersState: TIntegerField; tsEquity: TTabSheet; chEquity: TChart; seEquity: TFastLineSeries; taOrdersLots: TFloatField; taOperationHistory: TMemoryDataSet; dsOperationHistory: TDataSource; tsOperationHistory: TTabSheet; grOperationHistory: TEditDBGrid; taOperationHistoryNo: TIntegerField; taOperationHistoryTime: TDateTimeField; taOperationHistoryOrderNo: TIntegerField; taOperationHistoryType: TStringField; taOperationHistoryLots: TFloatField; taOperationHistoryPrice: TCurrencyField; taOperationHistoryStopLoss: TCurrencyField; taOperationHistoryTakeProfit: TCurrencyField; taOperationHistoryProfit: TCurrencyField; taOperationHistoryBalance: TCurrencyField; procedure Gotoend1Click(Sender: TObject); procedure Gotothebeginning1Click(Sender: TObject); procedure grJournalDblClick(Sender: TObject); procedure acFilterExecute(Sender: TObject); procedure taOrdersOpenTimeGetText(Sender: TField; var Text: string; DisplayText: Boolean); procedure tmFilterDetailsTimer(Sender: TObject); procedure grOrderDetailsBeforeDrawColumnCell(Sender: TObject; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure pcPagesChange(Sender: TObject); procedure taOrderDetailsBeforeClose(DataSet: TDataSet); procedure taOrderDetailsAfterOpen(DataSet: TDataSet); procedure grOrdersChangeRecord(Sender: TObject); procedure taOrderDetailsFilterRecord(DataSet: TDataSet; var Accept: Boolean); procedure tcTabsChange(Sender: TObject); procedure acAutoScrollExecute(Sender: TObject); procedure acExportOrdersUpdate(Sender: TObject); procedure acFitColumnsExecute(Sender: TObject); procedure acChooseColumnsUpdate(Sender: TObject); procedure acChooseColumnsExecute(Sender: TObject); procedure grOrdersBeforeDrawColumnCell(Sender: TObject; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure taOrdersBeforeClose(DataSet: TDataSet); procedure taOrdersAfterOpen(DataSet: TDataSet); procedure grOrdersDblClick(Sender: TObject); procedure acGetStatisticUpdate(Sender: TObject); procedure acGetStatisticExecute(Sender: TObject); procedure acExportOrdersExecute(Sender: TObject); procedure taOperationHistoryBeforeClose(DataSet: TDataSet); procedure taOperationHistoryAfterOpen(DataSet: TDataSet); procedure grOperationHistoryDblClick(Sender: TObject); private FStatictic : TStockTradingStatistics; FLastRepaintTime : TDateTime; FOrderCount : integer; FCharts : array of IStockChart; FProject : IStockProject; FCurrentTrader : IStockTrader; FOrderDetailNo : integer; FStartTime : TDateTime; FMode : TTradeMode; FLogOrderDetails: boolean; FLastEquityTime : TDateTime; FLastEquity : TStockRealNumber; function GetAutoScroll: boolean; procedure SetAutoScroll(const Value: boolean); protected procedure OnOpenOrderInternal(aOrder: IStockOrder); virtual; procedure OnCloseOrderInternal(aOrder: IStockOrder); virtual; procedure AddDetails(const aOrder: IStockOrder; const aText: string; const aColor: TColor); overload; procedure AddDetails(const aBroker: IStockBroker; const aText: string; const aColor: TColor); overload; //Получить номер записи в таблице ордеров по ID ордера function OrderRecordByID(const aID: TGUID): integer; procedure Loaded; override; public procedure Init(const aCharts : array of IStockChart); procedure OnStart(const aBroker: IStockBroker; const aTrader:IStockTrader); virtual; procedure OnEnd; virtual; property LogOrderDetails: boolean read FLogOrderDetails write FLogOrderDetails; procedure BeginUpdate; procedure EndUpdate; procedure SaveData(const aDataWriter: IDataWriter); procedure LoadData(const aDataReader: IDataReader); procedure OnNewData(const aSender: IStockBroker; const aSymbol: string); virtual; procedure OnNewOrder(const aOrder: IStockOrder); virtual; procedure OnModifyOrder(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs); procedure OnNewMessage (const aBroker: IStockBroker; const aMessage: IStockBrokerMessage); overload; procedure OnNewMessage (const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage); overload; property Statictics : TStockTradingStatistics read FStatictic; property AutoScrollOrders: boolean read GetAutoScroll write SetAutoScroll; //Обработка событий procedure OnActionUpdate(aAction: TActionParams); procedure OnActionExecute(aAction: TActionParams); property Mode : TTradeMode read FMode write FMode; constructor Create(aOwner: TComponent); override; destructor Destroy; override; end; implementation uses Math,BaseUtils, DateUtils, SystemService, DBUtils, Export.Definitions,FC.DataUtils, StockChart.Definitions.Drawing, FC.Trade.StatisticsDialog,FC.Trade.FilterDialog, ufmDialog_B, JvEditor, ufmForm_B; {$R *.dfm} type //Прокси для сериализации документа TResultPageSerializationProxy = class (TNameValuePersistentObjectRefCounted) private FOwner: TfrmStockTradeResult; public procedure OnReadValue(const aReader: INameValueDataReader; const aName: string; var aHandled: boolean); override; procedure OnWriteValues(const aWriter: INameValueDataWriter); override; constructor Create(aOwner: TfrmStockTradeResult); end; { TResultPageSerializationProxy } constructor TResultPageSerializationProxy.Create(aOwner: TfrmStockTradeResult); begin inherited Create; FOwner:=aOwner; end; procedure TResultPageSerializationProxy.OnReadValue(const aReader: INameValueDataReader; const aName: string; var aHandled: boolean); var aD: double; S: string; begin inherited; if aName='DataSet' then begin //История ордеров FOwner.taOrders.EmptyTable; FOwner.taOrders.Open; aReader.ReadString(s); LoadDataFromString(FOwner.taOrders,s); aHandled:=true; end else if aName='Details' then begin FOwner.taOrderDetails.EmptyTable; FOwner.taOrderDetails.Open; aReader.ReadString(s); LoadDataFromString(FOwner.taOrderDetails,s); aHandled:=true; end else if aName='OperationHistory' then begin //История операций FOwner.taOperationHistory.EmptyTable; FOwner.taOperationHistory.Open; aReader.ReadString(s); LoadDataFromString(FOwner.taOperationHistory,s); aHandled:=true; end else if aName='Graphic' then begin //График баланса aReader.ReadListBegin; while not aReader.EndOfList do begin aReader.ReadDouble(aD); FOwner.chartBalance.AddY(aD); end; aReader.ReadListEnd; aHandled:=true; end else if aName='Selected Order' then begin aHandled:=true; aReader.ReadString(S); if FOwner.taOrders.Active then FOwner.taOrders.Locate(FOwner.taOrdersOrderID.FieldName,S,[]); end; end; procedure TResultPageSerializationProxy.OnWriteValues(const aWriter: INameValueDataWriter); var i: integer; aFiltered: boolean; begin inherited; //График баланса aWriter.DataWriter.WriteString('Graphic'); aWriter.DataWriter.WriteListBegin; for i := 0 to FOwner.chartBalance.YValues.Count - 1 do aWriter.DataWriter.WriteDouble(FOwner.chartBalance.YValues[i]); aWriter.DataWriter.WriteListEnd; //История ордеров if FOwner.taOrders.Active then begin aWriter.DataWriter.WriteString('DataSet'); aFiltered:=FOwner.taOrders.Filtered; FOwner.taOrders.DisableControls; FOwner.taOrders.Filtered:=false; try aWriter.DataWriter.WriteString(SaveDataSetToString(FOwner.taOrders)); finally FOwner.taOrders.Filtered:=aFiltered; FOwner.taOrders.EnableControls; end; end; if FOwner.taOrderDetails.Active then begin //Детализация ордеров //FOwner.dsOrderDetails.DataSet:=nil; aFiltered:=FOwner.taOrderDetails.Filtered; FOwner.taOrderDetails.Filtered:=false; try aWriter.DataWriter.WriteString('Details'); aWriter.DataWriter.WriteString(SaveDataSetToString(FOwner.taOrderDetails)); finally FOwner.taOrderDetails.Filtered:=aFiltered; end; end; if FOwner.taOperationHistory.Active then begin aFiltered:=FOwner.taOperationHistory.Filtered; FOwner.taOperationHistory.Filtered:=false; try aWriter.DataWriter.WriteString('OperationHistory'); aWriter.DataWriter.WriteString(SaveDataSetToString(FOwner.taOperationHistory)); finally FOwner.taOperationHistory.Filtered:=aFiltered; end; end; if FOwner.taOrders.Active then begin aWriter.WriteString('Selected Order',FOwner.taOrdersOrderID.AsString); end; end; { TfrmStockTradeResult } constructor TfrmStockTradeResult.Create(aOwner: TComponent); begin inherited; FLogOrderDetails:=true; FStatictic:=TStockTradingStatistics.Create; tcTabs.Flat:=true; tcTabs.DrawTopLine:=true; pcPages.ActivePageIndex:=0; tcTabs.TabIndex:=0; Workspace.MainFrame.AddActionTarget(self); pcPagesChange(nil); end; destructor TfrmStockTradeResult.Destroy; begin Workspace.MainFrame.RemoveActionTarget(self); if taOrders.Active then begin taOrdersBeforeClose(nil); //Не срабатывает автоматом taOrders.Close; end; if taOrderDetails.Active then begin taOrderDetailsBeforeClose(nil); //Не срабатывает автоматом taOrderDetails.Close; end; if taOperationHistory.Active then begin taOperationHistoryBeforeClose(nil); //Не срабатывает автоматом taOperationHistory.Close; end; Workspace.Storage(self).WriteString(grOrders,'Columns',grOrders.ColumnStates.StrDump); Workspace.Storage(self).WriteString(grOrderDetails,'Columns',grOrderDetails.ColumnStates.StrDump); inherited; FreeAndNil(FStatictic); end; procedure TfrmStockTradeResult.Init(const aCharts : array of IStockChart); var i: integer; s: string; begin SetLength(FCharts,Length(aCharts)); for i:=0 to High(aCharts) do FCharts[i]:=aCharts[i]; s:='#Bar('; for i:=0 to High(FCharts) do s:=s+FCharts[i].StockSymbol.GetTimeIntervalName+','; s:=StrTrimRight(s,[','])+')'; taOrdersOpenBarNo.DisplayLabel:=s; taOrdersCloseBarNo.DisplayLabel:=s; FProject:=aCharts[0].GetProject; pcPages.ActivePageIndex:=0; pcPagesChange(pcPages); end; procedure TfrmStockTradeResult.OnStart(const aBroker: IStockBroker; const aTrader:IStockTrader); begin FStartTime:=Now; FCurrentTrader:=aTrader; FreeAndNil(FStatictic); FStatictic:=TStockTradingStatistics.Create; taOrders.EmptyTable; taOrders.Open; chartBalance.Clear; seEquity.Clear; taOrderDetails.EmptyTable; taOrderDetails.Open; taOperationHistory.EmptyTable; taOperationHistory.Open; FOrderCount:=0; FLastEquityTime:=0; FLastEquity:=aBroker.GetEquity; laBalance.Caption:='Current balance: '+FormatCurr('0,.00',aBroker.GetBalance); if FMode=tmTest then laElapsedTime.Caption:='Elapsed Time: '+TimeToStr(0) else laElapsedTime.Caption:='Last tick: '; end; function TfrmStockTradeResult.OrderRecordByID(const aID: TGUID): integer; var i: integer; s: string; begin s:=GUIDToString(aID); for i := taOrders.RecordCount - 1 downto 0 do if V2S(taOrders.DirectGetFieldData(i,taOrdersOrderID))=s then begin result:=i; exit; end; raise EAlgoError.Create; end; procedure TfrmStockTradeResult.pcPagesChange(Sender: TObject); begin tcTabs.TabIndex:=pcPages.ActivePageIndex; if pcPages.ActivePage=tsJournal then begin taOrderDetails.Filtered:=false; taOrderDetailsOrderNo.Visible:=true; taOrderDetailsNoInGroup.Visible:=false; end else if pcPages.ActivePage=tsOrderHistory then begin taOrderDetails.Filtered:=true; taOrderDetailsOrderNo.Visible:=false; taOrderDetailsNoInGroup.Visible:=true; end; end; procedure TfrmStockTradeResult.SaveData(const aDataWriter: IDataWriter); var aProxy: IPersistentObject; begin aProxy:=TResultPageSerializationProxy.Create(self); aDataWriter.WriteObject(aProxy); end; procedure TfrmStockTradeResult.LoadData(const aDataReader: IDataReader); var aProxy: IPersistentObject; begin aProxy:=TResultPageSerializationProxy.Create(self); aDataReader.ReadObjectExisting(aProxy); end; procedure TfrmStockTradeResult.Loaded; begin inherited; grOrders.ColumnStates.StrDump:=Workspace.Storage(self).ReadString(grOrders,'Columns',''); grOrderDetails.ColumnStates.StrDump:=Workspace.Storage(self).ReadString(grOrderDetails,'Columns',''); end; procedure TfrmStockTradeResult.SetAutoScroll(const Value: boolean); begin acAutoScroll.Checked:=Value; end; procedure TfrmStockTradeResult.OnEnd; begin chartBalance.Repaint; chEquity.Repaint; if FMode=tmTest then laElapsedTime.Caption:='Elapsed Time: '+TimeToStr(Now-FStartTime); end; procedure TfrmStockTradeResult.OnModifyOrder(const aOrder: IStockOrder; const aModifyEventArgs: TStockOrderModifyEventArgs); var aRecNo: integer; s: string; begin if FMode=tmTest then laElapsedTime.Caption:='Elapsed Time: '+TimeToStr(Now-FStartTime); //Состояние ордеров и детализации может быть рассинхронизировано if (taOrderDetailsOrderID.Value<>taOrdersOrderID.Value) and (taOrderDetails.Filtered) then tmFilterDetailsTimer(nil); BeginUpdate; try //Open if aModifyEventArgs.ModifyType=omtOpen then begin OnOpenOrderInternal(aOrder); end //Close else if aModifyEventArgs.ModifyType=omtClose then begin OnCloseOrderInternal(aOrder); end //Modify else begin aRecNo:=OrderRecordByID(aOrder.GetID); if aModifyEventArgs.ModifyType=omtChangeStopLoss then begin if taOrders.DirectGetFieldData(aRecNo,taOrdersStopLoss)<>0 then begin if aModifyEventArgs.StopLossFromTrailingStop then s:='Stop Loss automatically changed from ' else s:='Stop Loss changed from '; s:=s+PriceToStr(aOrder,taOrders.DirectGetFieldData(aRecNo,taOrdersStopLoss))+' to '+ PriceToStr(aOrder,aOrder.GetStopLoss); end else begin if aModifyEventArgs.StopLossFromTrailingStop then s:='Stop Loss automatically set to ' else s:='Stop Loss set to '; s:=s+PriceToStr(aOrder,aOrder.GetStopLoss); end; AddDetails(aOrder,s,clDefault); end else if aModifyEventArgs.ModifyType=omtChangeTakeProfit then begin if taOrders.DirectGetFieldData(aRecNo,taOrdersTakeProfit)<>0 then s:='Take Profit changed from '+ PriceToStr(aOrder,taOrders.DirectGetFieldData(aRecNo,taOrdersTakeProfit))+' to '+ PriceToStr(aOrder,aOrder.GetTakeProfit) else s:='Take Profit set to '+PriceToStr(aOrder,aOrder.GetTakeProfit); AddDetails(aOrder,s,clDefault); end else if aModifyEventArgs.ModifyType=omtChangeTrailingStop then begin if taOrders.DirectGetFieldData(aRecNo,taOrdersTrailingStop)<>0 then s:='Trailing Stop changed from '+IntToStr(aOrder.GetBroker.PriceToPoint(aOrder.GetSymbol,taOrders.DirectGetFieldData(aRecNo,taOrdersTrailingStop)))+' pts to '+ IntToStr(aOrder.GetBroker.PriceToPoint(aOrder.GetSymbol,aOrder.GetTrailingStop))+ ' pts (Current profit = '+IntToStr(aOrder.GetBroker.PriceToPoint(aOrder.GetSymbol,aOrder.GetCurrentProfit))+' pts)' else s:='Trailing Stop set to '+IntToStr(aOrder.GetBroker.PriceToPoint(aOrder.GetSymbol,aOrder.GetTrailingStop))+ ' pts (Current profit = '+IntToStr(aOrder.GetBroker.PriceToPoint(aOrder.GetSymbol,aOrder.GetCurrentProfit))+' pts)'; AddDetails(aOrder,s,clDefault); end else if aModifyEventArgs.ModifyType=omtChangeOpenPrice then begin //Для открытия отложенного ордера нужно сразу указать и комментарий taOrders.DirectSetFieldData(aRecNo,taOrdersType,OrderKindNames[aOrder.GetKind]); taOrders.DirectSetFieldData(aRecNo,taOrdersStopLoss,aOrder.GetStopLoss); taOrders.DirectSetFieldData(aRecNo,taOrdersTakeProfit,aOrder.GetTakeProfit); taOrders.DirectSetFieldData(aRecNo,taOrdersTrailingStop,aOrder.GetTrailingStop); taOrders.DirectSetFieldData(aRecNo,taOrdersOpenComment,aOrder.GetOpenComment); taOrders.DirectSetFieldData(aRecNo,taOrdersLots,aOrder.GetLots); taOrders.DirectSetFieldData(aRecNo,taOrdersType,OrderKindNames[aOrder.GetKind]); taOrders.DirectSetFieldData(aRecNo,taOrdersState,aOrder.GetState); if taOrders.DirectGetFieldData(aRecNo,taOrdersPendingOpenPrice)<>0 then begin s:=Format('Pending Open Price changed from %s to %s (%s)', [PriceToStr(aOrder,taOrders.DirectGetFieldData(aRecNo,taOrdersPendingOpenPrice)), PriceToStr(aOrder,aOrder.GetPendingOpenPrice), OrderKindNames[aOrder.GetKind]]); end else begin s:=Format('Pending Open Price set to %s (%s)', [PriceToStr(aOrder,aOrder.GetPendingOpenPrice), OrderKindNames[aOrder.GetKind]]); end; AddDetails(aOrder,s,clDefault); taOrders.RecNo:=taOrders.RecNo; end else if aModifyEventArgs.ModifyType=omtPendingRevoke then begin s:='Order revoked'; taOrders.DirectSetFieldData(aRecNo,taOrdersState,aOrder.GetState); AddDetails(aOrder,s,clDefault); taOrders.RecNo:=taOrders.RecNo; end else if aModifyEventArgs.ModifyType=omtChangeNotes then begin taOrders.DirectSetFieldData(aRecNo,taOrdersNotes,aOrder.GetNotes); end else if aModifyEventArgs.ModifyType=omtChangeColor then begin taOrders.DirectSetFieldData(aRecNo,taOrdersColor,aOrder.GetColor); end else if aModifyEventArgs.ModifyType=omtPendingSuspend then begin if aOrder.IsPendingSuspended then s:='Pending Order Suspended' else s:='Pending Order Resumed'; AddDetails(aOrder,s,clDefault); end end; finally EndUpdate; end; end; procedure TfrmStockTradeResult.OnNewMessage(const aBroker: IStockBroker; const aMessage: IStockBrokerMessage); begin BeginUpdate; try if aMessage.Color=clDefault then AddDetails(aBroker,'Message: '+aMessage.Text,clWebCornSilk) else AddDetails(aBroker,'Message: '+aMessage.Text,aMessage.Color); finally EndUpdate; end; end; procedure TfrmStockTradeResult.OnNewMessage(const aSender: IStockBroker; const aOrder: IStockOrder; const aMessage: IStockBrokerMessage); begin BeginUpdate; try if aMessage.Color=clDefault then AddDetails(aOrder,'Message: '+aMessage.Text,clWebCornSilk) else AddDetails(aOrder,'Message: '+aMessage.Text,aMessage.Color); if AutoScrollOrders then taOrders.Locate(taOrdersOrderID.FieldName,GUIDToString(aOrder.GetID),[]); finally EndUpdate; end; end; procedure TfrmStockTradeResult.OnNewData(const aSender: IStockBroker; const aSymbol: string); var i: integer; aOrder: IStockOrder; aOrders: IStockOrderCollection; aRecNo: integer; aCurrTime : TDateTime; begin aCurrTime:=aSender.GetCurrentTime; if (Trunc(FLastEquityTime)<> Trunc(aCurrTime)) and (FLastEquityTime<>0) then seEquity.AddXY(Trunc(FLastEquityTime),FLastEquity); if FMode=tmReal then laElapsedTime.Caption:='Last tick: '+TimeToStr(aCurrTime); if (aSender.IsRealTime) and (Mode=tmReal) then begin aOrders:=aSender.GetOpenedOrders; for I := 0 to aOrders.Count-1 do begin aOrder:=aOrders[i]; aRecNo:=OrderRecordByID(aOrder.GetID); taOrders.DirectSetFieldData(aRecNo,taOrdersProfit,aOrder.GetCurrentProfit); taOrders.DirectSetFieldData(aRecNo,taOrdersProfitPt,aSender.PriceToPoint(aOrder.GetSymbol,aOrder.GetCurrentProfit)); taOrders.RecNo:=taOrders.RecNo; end; FLastEquityTime:=aCurrTime; FLastEquity:=aSender.GetEquity; end //Оптимизация. GetEquity считается на ходу, поэтому в тестах лучше не злоупотреблять else if (Trunc(FLastEquityTime)<> Trunc(aCurrTime)) or (MinutesBetween(aCurrTime,FLastEquityTime)>10) then begin FLastEquityTime:=aCurrTime; FLastEquity:=aSender.GetEquity; end; end; procedure TfrmStockTradeResult.OnNewOrder(const aOrder: IStockOrder); var aRecNo: integer; begin inc(FOrderCount); BeginUpdate; try aRecNo:=taOrders.DirectInsertRecord; taOrders.DirectSetFieldData(aRecNo,taOrdersNo,FOrderCount); taOrders.DirectSetFieldData(aRecNo,taOrdersOrderID,GUIDToString(aOrder.GetID)); taOrders.DirectSetFieldData(aRecNo,taOrdersDetailNo,1); taOrders.DirectSetFieldData(aRecNo,taOrdersCreateTime,aOrder.GetCreateTime); if aOrder.GetState<>osNothing then begin taOrders.DirectSetFieldData(aRecNo,taOrdersType,OrderKindNames[aOrder.GetKind]); taOrders.DirectSetFieldData(aRecNo,taOrdersStopLoss,aOrder.GetStopLoss); taOrders.DirectSetFieldData(aRecNo,taOrdersTakeProfit,aOrder.GetTakeProfit); taOrders.DirectSetFieldData(aRecNo,taOrdersTrailingStop,aOrder.GetTrailingStop); taOrders.DirectSetFieldData(aRecNo,taOrdersNotes,aOrder.GetNotes); end; if aOrder.GetState=osPending then taOrders.DirectSetFieldData(aRecNo,taOrdersPendingOpenPrice,aOrder.GetPendingOpenPrice) else taOrders.DirectSetFieldData(aRecNo,taOrdersPendingOpenPrice,0); if AutoScrollOrders then taOrders.RecNo:=aRecNo+1 else taOrders.RecNo:=taOrders.RecNo; //Обязательно нужно сделать, чтобы прошло Resync. Но просто Resync использовать нельзя! finally EndUpdate; //if taOrders.RecordCount=2 then //grOrders.Repaint; //Какая-та неразбериха с миганием на втором ордере end; end; procedure TfrmStockTradeResult.OnOpenOrderInternal(aOrder: IStockOrder); var j,aRecNo: integer; s: string; aOrderNo : integer; begin BeginUpdate; try aRecNo:=OrderRecordByID(aOrder.GetID); aOrderNo:=taOrders.DirectGetFieldData(aRecNo,taOrdersNo); s:=''; for j:=0 to High(FCharts) do s:=s+IntToStr(FCharts[j].FindBar(aOrder.GetOpenTime))+','; //taOrders.DirectSetFieldData(aRecNo,taOrdersOrderID.Value:=GUIDToString(aOrder.GetID); taOrders.DirectSetFieldData(aRecNo,taOrdersType,OrderKindNames[aOrder.GetKind]); taOrders.DirectSetFieldData(aRecNo,taOrdersLots,aOrder.GetLots); taOrders.DirectSetFieldData(aRecNo,taOrdersOpenTime,aOrder.GetOpenTime); taOrders.DirectSetFieldData(aRecNo,taOrdersOpenBarNo,StrTrimRight(s,[','])); taOrders.DirectSetFieldData(aRecNo,taOrdersOpenPrice,aOrder.GetOpenPrice); taOrders.DirectSetFieldData(aRecNo,taOrdersOpenComment,aOrder.GetOpenComment); taOrders.DirectSetFieldData(aRecNo,taOrdersState,aOrder.GetState); AddDetails(aOrder,'Open at '+PriceToStr(aOrder,aOrder.GetOpenPrice)+'. Comment: '+aOrder.GetOpenComment,$D8FADC); if AutoScrollOrders then taOrders.RecNo:=aRecNo+1 else taOrders.RecNo:=taOrders.RecNo; aRecNo:=taOperationHistory.DirectInsertRecord; taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryNo,taOperationHistory.RecordCount); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryTime,aOrder.GetOpenTime); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryType,OrderKindNames[aOrder.GetKind]); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryOrderNo,aOrderNo); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryLots,aOrder.GetLots); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryPrice,aOrder.GetOpenPrice); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryStopLoss,aOrder.GetStopLoss); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryTakeProfit,aOrder.GetTakeProfit); taOperationHistory.RecNo:=taOperationHistory.RecNo; //Обязательно нужно сделать, чтобы прошло Resync. Но просто Resync использовать нельзя! finally EndUpdate; end; end; procedure TfrmStockTradeResult.OnActionExecute(aAction: TActionParams); begin aAction.Handled:=(aAction.Action=UIDataStorage.acTradingMoveNextOrder) or (aAction.Action=UIDataStorage.acTradingMovePrevOrder); if (aAction.Handled) and (not aAction.TestOnly) then begin Assert(grOrders.DataLink.DataSet=taOrders); if aAction.Action=UIDataStorage.acTradingMoveNextOrder then begin taOrders.Next; while (taOrdersOpenTime.IsNull) and not taOrders.EOF do taOrders.Next; if not taOrders.Eof then grOrdersDblClick(nil); end else if aAction.Action=UIDataStorage.acTradingMovePrevOrder then begin grOrders.DataLink.DataSet.Prior; grOrdersDblClick(nil); end end; end; procedure TfrmStockTradeResult.OnActionUpdate(aAction: TActionParams); begin aAction.Handled:=(aAction.Action=UIDataStorage.acTradingMoveNextOrder) or (aAction.Action=UIDataStorage.acTradingMovePrevOrder); if aAction.Handled then begin if not grOrders.IsDBActive then aAction.Action.Enabled:=false else if aAction.Action=UIDataStorage.acTradingMoveNextOrder then aAction.Action.Enabled:=not grOrders.DataLink.DataSet.Eof else if aAction.Action=UIDataStorage.acTradingMovePrevOrder then aAction.Action.Enabled:=not grOrders.DataLink.DataSet.Bof; end; end; procedure TfrmStockTradeResult.OnCloseOrderInternal(aOrder: IStockOrder); var aProfit,aBestProfit,aWorstProfit: TStockRealNumber; aProfitPts,aBestProfitPts,aWorstProfitPts: integer; aDelta : TStockRealNumber; aBroker : IStockBroker; j: integer; s: string; aRecNo: integer; aOrderNo : integer; begin aBroker:=aOrder.GetBroker; aProfitPts:=aBroker.PriceToPoint(aOrder.GetSymbol,aOrder.GetCurrentProfit);//-CurrentSpreadPoints; aProfit:=aBroker.PriceToMoney(aOrder.GetSymbol,aOrder.GetCurrentProfit,aOrder.GetLots); aBestProfitPts:=aBroker.PriceToPoint(aOrder.GetSymbol,aOrder.GetBestProfit);//-CurrentSpreadPoints; aBestProfit:=aBroker.PriceToMoney(aOrder.GetSymbol,aOrder.GetBestProfit,aOrder.GetLots); aWorstProfitPts:=aBroker.PriceToPoint(aOrder.GetSymbol,aOrder.GetWorstProfit);//-CurrentSpreadPoints; aWorstProfit:=aBroker.PriceToMoney(aOrder.GetSymbol,aOrder.GetWorstProfit,aOrder.GetLots); aDelta:=FStatictic.Balance; FStatictic.AddValue(aProfit,aBestProfit,aWorstProfit,aProfitPts,aBestProfitPts,aWorstProfitPts); aDelta:=FStatictic.Balance-aDelta; chartBalance.AddY(FStatictic.Balance); s:='Current balance: '+FormatCurr('0,.00',aBroker.GetBalance)+ ' ('; if aDelta>0 then s:=s+'+'; s:=s+FormatCurr('0,.00',aDelta)+')'; laBalance.Caption:=s; BeginUpdate; try aRecNo:=OrderRecordByID(aOrder.GetID); aOrderNo:=taOrders.DirectGetFieldData(aRecNo,taOrdersNo); s:=''; for j:=0 to High(FCharts) do s:=s+IntToStr(FCharts[j].FindBar(aOrder.GetCloseTime))+','; taOrders.DirectSetFieldData(aRecNo,taOrdersCloseTime,aOrder.GetCloseTime); taOrders.DirectSetFieldData(aRecNo,taOrdersCloseBarNo,s); taOrders.DirectSetFieldData(aRecNo,taOrdersClosePrice,aOrder.GetClosePrice); taOrders.DirectSetFieldData(aRecNo,taOrdersProfitPt,aProfitPts); taOrders.DirectSetFieldData(aRecNo,taOrdersLots,aOrder.GetLots); taOrders.DirectSetFieldData(aRecNo,taOrdersProfit,aProfit); taOrders.DirectSetFieldData(aRecNo,taOrdersWorstPt,Round(aWorstProfitPts)); taOrders.DirectSetFieldData(aRecNo,taOrdersBestPt,Round(aBestProfitPts)); if aProfitPts>0 then taOrders.DirectSetFieldData(aRecNo,taOrdersQuality,Round(aProfit/aBestProfit*100)) else taOrders.DirectSetFieldData(aRecNo,taOrdersQuality,-1); taOrders.DirectSetFieldData(aRecNo,taOrdersSubsidencePt,aBroker.PriceToPoint(aOrder.GetSymbol,(aOrder.GetWorstPrice-aOrder.GetOpenPrice))); taOrders.DirectSetFieldData(aRecNo,taOrdersBalance, aBroker.GetBalance {FStatictic.Balance}); taOrders.DirectSetFieldData(aRecNo,taOrdersCloseComment,aOrder.GetCloseComment); taOrders.DirectSetFieldData(aRecNo,taOrdersState,aOrder.GetState); AddDetails(aOrder,'Close at '+PriceToStr(aOrder,aOrder.GetClosePrice)+'. Comment: '+aOrder.GetCloseComment,$BBF7C2); if AutoScrollOrders then taOrders.RecNo:=aRecNo+1 else taOrders.RecNo:=taOrders.RecNo; aRecNo:=taOperationHistory.DirectInsertRecord; taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryNo,taOperationHistory.RecordCount); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryTime,aOrder.GetCloseTime); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryType,'close'); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryOrderNo,aOrderNo); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryLots,aOrder.GetLots); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryPrice,aOrder.GetClosePrice); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryStopLoss,aOrder.GetStopLoss); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryTakeProfit,aOrder.GetTakeProfit); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryProfit,aProfit); taOperationHistory.DirectSetFieldData(aRecNo,taOperationHistoryBalance,aBroker.GetBalance); taOperationHistory.RecNo:=taOperationHistory.RecNo; //Обязательно нужно сделать, чтобы прошло Resync. Но просто Resync использовать нельзя! finally EndUpdate; end; if MilliSecondsBetween(Now,FLastRepaintTime)>200 then begin chartBalance.Repaint; chEquity.Repaint; for j:=0 to High(FCharts) do FCharts[j].Repaint; //Forms.Application.ProcessMessages; FLastRepaintTime:=Now; end; end; procedure TfrmStockTradeResult.acExportOrdersExecute(Sender: TObject); var aExportInfo: TExportInfo; aPropCollection: IStockTraderPropertyCollection; aExportString : TExportString; i: integer; aStatistic : TStringList; begin aExportInfo:=TExportInfo.Create; aPropCollection:=FCurrentTrader.GetProperties; aStatistic:=TStringList.Create; try //Default format aExportInfo.DefaultFormat.FontName:='Tahoma'; aExportInfo.DefaultFormat.FontSize:=7; aExportInfo.DefaultFormat.IgnoreFormat:=false; //Title aExportString:=TExportString.Create(FCurrentTrader.GetCategory+'\'+FCurrentTrader.GetName); aExportString.Format.IgnoreFormat:=false; aExportString.Format.FontSize:=12; aExportString.Format.FontStyle:=[efsBold,efsItalic]; aExportInfo.HeadStrings.Add(aExportString); //Properties aExportString:=TExportString.Create(#13#10'Properties'); aExportString.Format.IgnoreFormat:=false; aExportString.Format.FontSize:=10; aExportString.Format.FontStyle:=[efsBold]; aExportInfo.HeadStrings.Add(aExportString); for i:=0 to aPropCollection.Count-1 do begin aExportString:=TExportString.Create(aPropCollection.Items[i].GetCategory+'\'+ aPropCollection.Items[i].GetName+'='+ aPropCollection.Items[i].ValueAsText); aExportString.Format.IgnoreFormat:=false; aExportString.Format.FontSize:=10; aExportInfo.HeadStrings.Add(aExportString); end; //Statistic aExportString:=TExportString.Create(#13#10'Statistic'); aExportString.Format.IgnoreFormat:=false; aExportString.Format.FontSize:=10; aExportString.Format.FontStyle:=[efsBold]; aExportInfo.HeadStrings.Add(aExportString); FStatictic.ToStrings(aStatistic); for i:=0 to aStatistic.Count-1 do begin aExportString:=TExportString.Create(aStatistic[i]); aExportString.Format.IgnoreFormat:=false; aExportString.Format.FontSize:=10; aExportInfo.HeadStrings.Add(aExportString); end; //Orders aExportString:=TExportString.Create(#13#10'Order History'); aExportString.Format.IgnoreFormat:=false; aExportString.Format.FontSize:=10; aExportString.Format.FontStyle:=[efsBold]; aExportInfo.HeadStrings.Add(aExportString); ExporterManager.ExportOperator.DoExport(grOrders,aExportInfo); finally aExportInfo.Free; aStatistic.Free; end; end; procedure TfrmStockTradeResult.acExportOrdersUpdate(Sender: TObject); begin TAction(Sender).Enabled:=FCurrentTrader<>nil; end; procedure TfrmStockTradeResult.acGetStatisticExecute(Sender: TObject); var aList: TStringList; aDlg: TfmTradingStatisticDialog; i: integer; begin aList:=TStringList.Create; aDlg:=TfmTradingStatisticDialog.Create(nil); try FStatictic.ToStrings(aList); for i:=0 to aList.Count-1 do if aList[i]='' then aDlg.AddProperty('','') else aDlg.AddProperty(aList.Names[i], aList.ValueFromIndex[i]); aDlg.Trader:=FCurrentTrader; aDlg.ShowModal; finally aList.Free; aDlg.Free; end; end; procedure TfrmStockTradeResult.acGetStatisticUpdate(Sender: TObject); begin TAction(Sender).Enabled:=FCurrentTrader<>nil; end; procedure TfrmStockTradeResult.AddDetails(const aBroker: IStockBroker; const aText: string; const aColor: TColor); var aGUID: TGUID; aDetailRecNo: integer; begin if not LogOrderDetails then exit; taOrderDetails.DisableControls; try CreateGUID(aGUID); inc(FOrderDetailNo); aDetailRecNo:=taOrderDetails.DirectInsertRecord(); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsNo,FOrderDetailNo); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsText,aText); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsWhen,aBroker.GetCurrentTime); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsOrderID,''); if aColor<>clDefault then taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsColor,aColor); taOrderDetails.RecNo:=taOrderDetails.RecNo; //Обязательно нужно сделать, чтобы прошло Resync. Но просто Resync использовать нельзя! finally taOrderDetails.EnableControls; end; end; procedure TfrmStockTradeResult.AddDetails(const aOrder: IStockOrder; const aText: string; const aColor: TCOlor); var aGUID: TGUID; aRecNo: integer; aDetailRecNo: integer; begin if not LogOrderDetails then exit; aRecNo:=OrderRecordByID(aOrder.GetID); BeginUpdate; try CreateGUID(aGUID); inc(FOrderDetailNo); //Order Details aDetailRecNo:=taOrderDetails.DirectInsertRecord(); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsNo,FOrderDetailNo); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsText,aText); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsWhen,aOrder.GetBroker.GetCurrentTime); if aOrder.GetSymbol<>'' then begin taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsPriceAsk,aOrder.GetBroker.GetCurrentPrice(aOrder.GetSymbol, bpkAsk)); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsPriceBid,aOrder.GetBroker.GetCurrentPrice(aOrder.GetSymbol, bpkBid)); end; taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsOrderID,GUIDToString(aOrder.GetID)); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsNoInGroup,taOrders.DirectGetFieldData(aRecNo,taOrdersDetailNo)); taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsOrderNo,taOrders.DirectGetFieldData(aRecNo,taOrdersNo)); taOrderDetails.RecNo:=taOrderDetails.RecNo; //Обязательно нужно сделать, чтобы прошло Resync. Но просто Resync использовать нельзя! if aColor<>clDefault then taOrderDetails.DirectSetFieldData(aDetailRecNo,taOrderDetailsColor,aColor); //Orders taOrders.DirectSetFieldData(aRecNo,taOrdersTrailingStop,aOrder.GetTrailingStop); taOrders.DirectSetFieldData(aRecNo,taOrdersTakeProfit,aOrder.GetTakeProfit); taOrders.DirectSetFieldData(aRecNo,taOrdersStopLoss,aOrder.GetStopLoss); if aOrder.GetState=osPending then taOrders.DirectSetFieldData(aRecNo,taOrdersPendingOpenPrice,aOrder.GetPendingOpenPrice) else taOrders.DirectSetFieldData(aRecNo,taOrdersPendingOpenPrice,0); taOrders.DirectSetFieldData(aRecNo,taOrdersDetailNo,integer(taOrders.DirectGetFieldData(aRecNo,taOrdersDetailNo))+1); finally EndUpdate; end; end; procedure TfrmStockTradeResult.grOrdersDblClick(Sender: TObject); var aOpenTime,aCloseTime: TDateTime; aShiftState: TShiftState; begin aOpenTime:=taOrdersOpenTime.Value; aCloseTime:=taOrdersCloseTime.Value; if aCloseTime<=0 then aCloseTime:=aOpenTime+1/MinsPerDay; aShiftState:=KeyboardStateToShiftState; FProject.HilightOnCharts(aOpenTime,aCloseTime,not (ssShift in aShiftState)); end; procedure TfrmStockTradeResult.grOrdersChangeRecord(Sender: TObject); begin if (taOrderDetailsOrderID.Value<>taOrdersOrderID.Value) and (taOrderDetails.Filtered) then begin tmFilterDetails.Enabled:=false; tmFilterDetails.Enabled:=true; end; end; procedure TfrmStockTradeResult.EndUpdate; begin taOrders.EnableControls; taOrderDetails.EnableControls; taOperationHistory.EnableControls; end; function TfrmStockTradeResult.GetAutoScroll: boolean; begin result:=acAutoScroll.Checked; end; procedure TfrmStockTradeResult.Gotoend1Click(Sender: TObject); var aOpenTime,aCloseTime: TDateTime; aShiftState: TShiftState; begin aOpenTime:=taOrdersCloseTime.Value; aCloseTime:=aOpenTime+MinuteAsDateTime; aShiftState:=KeyboardStateToShiftState; FProject.HilightOnCharts(aOpenTime,aCloseTime,not (ssShift in aShiftState)); end; procedure TfrmStockTradeResult.Gotothebeginning1Click(Sender: TObject); var aOpenTime,aCloseTime: TDateTime; aShiftState: TShiftState; begin aOpenTime:=taOrdersOpenTime.Value; aCloseTime:=aOpenTime+MinuteAsDateTime; aShiftState:=KeyboardStateToShiftState; FProject.HilightOnCharts(aOpenTime,aCloseTime,not (ssShift in aShiftState)); end; procedure TfrmStockTradeResult.BeginUpdate; begin taOrders.DisableControls; taOrderDetails.DisableControls; taOperationHistory.DisableControls; end; procedure TfrmStockTradeResult.taOperationHistoryAfterOpen(DataSet: TDataSet); begin grOperationHistory.ColumnStates.LoadColumnStates; end; procedure TfrmStockTradeResult.taOperationHistoryBeforeClose(DataSet: TDataSet); begin grOperationHistory.ColumnStates.SaveColumnStates; end; procedure TfrmStockTradeResult.taOrderDetailsAfterOpen(DataSet: TDataSet); begin grOrderDetails.ColumnStates.LoadColumnStates; end; procedure TfrmStockTradeResult.taOrderDetailsBeforeClose(DataSet: TDataSet); begin grOrderDetails.ColumnStates.SaveColumnStates; end; procedure TfrmStockTradeResult.taOrderDetailsFilterRecord(DataSet: TDataSet; var Accept: Boolean); begin Accept:=taOrderDetailsOrderID.Value = taOrdersOrderID.Value; end; procedure TfrmStockTradeResult.taOrdersAfterOpen(DataSet: TDataSet); begin grOrders.ColumnStates.LoadColumnStates; end; procedure TfrmStockTradeResult.taOrdersBeforeClose(DataSet: TDataSet); begin grOrders.ColumnStates.SaveColumnStates; end; procedure TfrmStockTradeResult.taOrdersOpenTimeGetText(Sender: TField; var Text: string; DisplayText: Boolean); begin if not Sender.IsNull then Text:=DefaultFormatter.DateTimeToStr(Sender.AsDateTime,false,true,true); end; procedure TfrmStockTradeResult.tcTabsChange(Sender: TObject); begin pcPages.ActivePageIndex:=tcTabs.TabIndex; pcPagesChange(nil); //Автоматически не срабатываеть end; procedure TfrmStockTradeResult.tmFilterDetailsTimer(Sender: TObject); begin tmFilterDetails.Enabled:=false; if (taOrderDetails.Active) and (taOrderDetailsOrderID.Value<>taOrdersOrderID.Value) and (taOrderDetails.Filtered) then taOrderDetails.First; end; procedure TfrmStockTradeResult.grJournalDblClick(Sender: TObject); var aOpenTime,aCloseTime: TDateTime; aShiftState: TShiftState; begin aOpenTime:=taOrderDetailsWhen.Value; aCloseTime:=aOpenTime+1/MinsPerDay; aShiftState:=KeyboardStateToShiftState; FProject.HilightOnCharts(aOpenTime,aCloseTime,not (ssShift in aShiftState)); end; procedure TfrmStockTradeResult.grOperationHistoryDblClick(Sender: TObject); var aOpenTime,aCloseTime: TDateTime; aShiftState: TShiftState; begin aOpenTime:=taOperationHistoryTime.Value; aCloseTime:=aOpenTime+1/MinsPerDay; aShiftState:=KeyboardStateToShiftState; FProject.HilightOnCharts(aOpenTime,aCloseTime,not (ssShift in aShiftState)); end; procedure TfrmStockTradeResult.grOrderDetailsBeforeDrawColumnCell(Sender: TObject; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if not taOrderDetailsColor.IsNull then TEditDBGrid(Sender).Canvas.Brush.Color:=taOrderDetailsColor.Value; end; procedure TfrmStockTradeResult.grOrdersBeforeDrawColumnCell(Sender: TObject; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if Column.Field=taOrdersProfitPt then TEditDBGrid(Sender).Canvas.Brush.Color:=clWebGhostWhite else if not taOrdersColor.IsNull then begin TEditDBGrid(Sender).Canvas.Brush.Color:=taOrdersColor.AsInteger; end; if not taOrdersNo.IsNull then begin //Это ничего if taOrdersState.Value=integer(osNothing) then begin // TEditDBGrid(Sender).Canvas.Font.Color:=clGrayText; if Mode=tmReal then begin TEditDBGrid(Sender).Canvas.Brush.Color:=clWebLightgrey; end; end //Это Pending Order else if taOrdersState.Value=integer(osPending) then begin TEditDBGrid(Sender).Canvas.Font.Color:=clGrayText; if Mode=tmReal then begin TEditDBGrid(Sender).Canvas.Brush.Color:=clWebLightCyan; end; end //Это Opened Order else if taOrdersState.Value=integer(osOpened) then begin TEditDBGrid(Sender).Canvas.Font.Color:=clWebBrown; if Mode=tmReal then TEditDBGrid(Sender).Canvas.Brush.Color:=clWebLemonChiffon; end; end; end; procedure TfrmStockTradeResult.acAutoScrollExecute(Sender: TObject); begin TAction(Sender).Checked:= not TAction(Sender).Checked; end; procedure TfrmStockTradeResult.acChooseColumnsExecute(Sender: TObject); begin if grOrders.ShowColumnsDlg then begin grOrders.ColumnStates.SaveColumnStates; end; end; procedure TfrmStockTradeResult.acChooseColumnsUpdate(Sender: TObject); begin TAction(Sender).Enabled:=grOrders.IsDBActive; end; procedure TfrmStockTradeResult.acFilterExecute(Sender: TObject); var i: integer; aFilter: string; aFiltered: boolean; aFields: TStringList; begin aFiltered:= not acFilter.Checked; if aFiltered then begin with TfmFilterDialog.Create(nil) do try aFields:=TStringList.Create; try for i := 0 to taOrders.Fields.Count - 1 do aFields.Add(taOrders.Fields[i].FieldName); SetFields(aFields); finally aFields.Free; end; mmFilter.Lines.Text:=taOrders.Filter; if ShowModal<>mrOk then aFiltered:=false else aFilter:=mmFilter.Lines.Text; finally Free; end; end; try if aFiltered then taOrders.Filter:=aFilter; taOrders.Filtered:=aFiltered; except on E:Exception do begin Workspace.MainFrame.HandleException(E); taOrders.Filtered:=false; end; end; acFilter.Checked:=taOrders.Filtered; //wewerer end; procedure TfrmStockTradeResult.acFitColumnsExecute(Sender: TObject); begin grOrders.ColumnSizes.FitColumnsByContents; end; end.
unit Mock.Getter.VolumeBitmap; interface uses SysUtils, Windows, Generics.Collections, OSFile; const BitmapSizePerBuffer = 16384; type TBitmapBuffer = Array[0..BitmapSizePerBuffer - 1] of Cardinal; TBitmapPositionSize = record StartingLCN: LARGE_INTEGER; BitmapSize: LARGE_INTEGER; end; TVolumeBitmapBufferWithErrorCode = record PositionSize: TBitmapPositionSize; Buffer: TBitmapBuffer; LastError: Cardinal; end; TVolumeBitmapGetter = class(TOSFile) public function GetVolumeBitmap(StartingLCN: LARGE_INTEGER): TVolumeBitmapBufferWithErrorCode; class procedure CreateBitmapStorage; class procedure FreeBitmapStorage; class procedure AddAtBitmapStorage(BitmapBuffer: TBitmapBuffer); class procedure ClearBitmapStorage; class procedure SetLength(NewLength: Int64); private type TBitmapBufferStorage = TList<TBitmapBuffer>; private class var BitmapBufferLength: Int64; class var BitmapBufferStorage: TBitmapBufferStorage; end; implementation { TVolumeBitmapGetter } function TVolumeBitmapGetter.GetVolumeBitmap( StartingLCN: LARGE_INTEGER): TVolumeBitmapBufferWithErrorCode; var RemainingLength: Int64; begin RemainingLength := BitmapBufferLength - StartingLCN.QuadPart; result.PositionSize.StartingLCN := StartingLCN; result.PositionSize.BitmapSize.QuadPart := RemainingLength; result.Buffer := BitmapBufferStorage[StartingLCN.QuadPart div BitmapSizePerBuffer]; if RemainingLength > BitmapSizePerBuffer then result.LastError := ERROR_MORE_DATA else if RemainingLength >= 0 then result.LastError := ERROR_SUCCESS else result.LastError := ERROR_NO_MORE_ITEMS; end; class procedure TVolumeBitmapGetter.SetLength(NewLength: Int64); begin BitmapBufferLength := NewLength; end; class procedure TVolumeBitmapGetter.CreateBitmapStorage; begin BitmapBufferStorage := TBitmapBufferStorage.Create; end; class procedure TVolumeBitmapGetter.FreeBitmapStorage; begin FreeAndNil(BitmapBufferStorage); end; class procedure TVolumeBitmapGetter.AddAtBitmapStorage( BitmapBuffer: TBitmapBuffer); begin BitmapBufferStorage.Add(BitmapBuffer); end; class procedure TVolumeBitmapGetter.ClearBitmapStorage; begin BitmapBufferStorage.Clear; end; end.
unit Ntapi.ntdef; {$MINENUMSIZE 4} interface uses Winapi.WinNt; type NTSTATUS = Cardinal; KPRIORITY = Integer; TEventType = ( NotificationEvent, SynchronizationEvent ); TTimerType = ( NotificationTimer, SynchronizationTimer ); ANSI_STRING = record Length: Word; MaximumLength: Word; Buffer: PAnsiChar; procedure FromString(Value: AnsiString); end; PANSI_STRING = ^ANSI_STRING; UNICODE_STRING = record Length: Word; // bytes MaximumLength: Word; // bytes Buffer: PWideChar; function ToString: String; procedure FromString(Value: string); end; PUNICODE_STRING = ^UNICODE_STRING; TObjectAttributes = record Length: Cardinal; RootDirectory: THandle; ObjectName: PUNICODE_STRING; Attributes: Cardinal; SecurityDescriptor: PSecurityDescriptor; SecurityQualityOfService: PSecurityQualityOfService; end; PObjectAttributes = ^TObjectAttributes; TClientId = record UniqueProcess: NativeUInt; UniqueThread: NativeUInt; procedure Create(PID, TID: NativeUInt); inline; end; PClientId = ^TClientId; const ntdll = 'ntdll.dll'; OBJ_PROTECT_CLOSE = $00000001; OBJ_INHERIT = $00000002; OBJ_AUDIT_OBJECT_CLOSE = $00000004; OBJ_PERMANENT = $00000010; OBJ_EXCLUSIVE = $00000020; OBJ_CASE_INSENSITIVE = $00000040; OBJ_OPENIF = $00000080; OBJ_OPENLINK = $00000100; OBJ_KERNEL_HANDLE = $00000200; OBJ_FORCE_ACCESS_CHECK = $00000400; OBJ_IGNORE_IMPERSONATED_DEVICEMAP = $00000800; OBJ_DONT_REPARSE = $00001000; OBJ_KERNEL_EXCLUSIVE = $00010000; MAX_UNICODE_STRING_SIZE = SizeOf(UNICODE_STRING) + High(Word) + 1 + SizeOf(WideChar); function NT_SEVERITY(Status: NTSTATUS): Byte; inline; function NT_FACILITY(Status: NTSTATUS): Word; inline; function NT_SUCCESS(Status: NTSTATUS): Boolean; inline; function NT_INFORMATION(Status: NTSTATUS): Boolean; inline; function NT_WARNING(Status: NTSTATUS): Boolean; inline; function NT_ERROR(Status: NTSTATUS): Boolean; inline; function NTSTATUS_FROM_WIN32(Win32Error: Cardinal): NTSTATUS; inline; function NT_NTWIN32(Status: NTSTATUS): Boolean; inline; function WIN32_FROM_NTSTATUS(Status: NTSTATUS): Cardinal; inline; function Offset(P: Pointer; Size: NativeUInt): Pointer; function AlighUp(Length: Cardinal; Size: Cardinal = SizeOf(NativeUInt)) : Cardinal; procedure InitializeObjectAttributes(var ObjAttr: TObjectAttributes; ObjectName: PUNICODE_STRING = nil; Attributes: Cardinal = 0; RootDirectory: THandle = 0; QoS: PSecurityQualityOfService = nil); inline; procedure InitializaQoS(var QoS: TSecurityQualityOfService; ImpersonationLevel: TSecurityImpersonationLevel = SecurityImpersonation; EffectiveOnly: Boolean = False); inline; implementation uses Ntapi.ntstatus; function NT_SEVERITY(Status: NTSTATUS): Byte; begin Result := Status shr NT_SEVERITY_SHIFT; end; function NT_FACILITY(Status: NTSTATUS): Word; begin Result := (Status shr NT_FACILITY_SHIFT) and NT_FACILITY_MASK; end; // 00000000..7FFFFFFF function NT_SUCCESS(Status: NTSTATUS): Boolean; begin Result := Integer(Status) >= 0; end; // 40000000..7FFFFFFF function NT_INFORMATION(Status: NTSTATUS): Boolean; begin Result := (NT_SEVERITY(Status) = SEVERITY_INFORMATIONAL); end; // 80000000..BFFFFFFF function NT_WARNING(Status: NTSTATUS): Boolean; begin Result := (NT_SEVERITY(Status) = SEVERITY_WARNING); end; // C0000000..FFFFFFFF function NT_ERROR(Status: NTSTATUS): Boolean; begin Result := (NT_SEVERITY(Status) = SEVERITY_ERROR); end; function NTSTATUS_FROM_WIN32(Win32Error: Cardinal): NTSTATUS; inline; begin // Note: the result is a fake NTSTATUS which is only suitable for storing // the error code without collisions with well-known NTSTATUS values. // Before formatting error messages convert it back to Win32. // Template: C007xxxx Result := Cardinal(SEVERITY_ERROR shl NT_SEVERITY_SHIFT) or (FACILITY_NTWIN32 shl NT_FACILITY_SHIFT) or (Win32Error and $FFFF); end; function NT_NTWIN32(Status: NTSTATUS): Boolean; begin Result := (NT_FACILITY(Status) = FACILITY_NTWIN32); end; function WIN32_FROM_NTSTATUS(Status: NTSTATUS): Cardinal; begin Result := Status and $FFFF; end; function Offset(P: Pointer; Size: NativeUInt): Pointer; begin Result := Pointer(NativeUInt(P) + Size); end; function AlighUp(Length: Cardinal; Size: Cardinal = SizeOf(NativeUInt)) : Cardinal; begin Result := (Length + Size - 1) and not (Size - 1); end; procedure InitializeObjectAttributes(var ObjAttr: TObjectAttributes; ObjectName: PUNICODE_STRING; Attributes: Cardinal; RootDirectory: THandle; QoS: PSecurityQualityOfService); begin FillChar(ObjAttr, SizeOf(ObjAttr), 0); ObjAttr.Length := SizeOf(ObjAttr); ObjAttr.ObjectName := ObjectName; ObjAttr.Attributes := Attributes; ObjAttr.RootDirectory := RootDirectory; ObjAttr.SecurityQualityOfService := QoS; end; procedure InitializaQoS(var QoS: TSecurityQualityOfService; ImpersonationLevel: TSecurityImpersonationLevel; EffectiveOnly: Boolean); begin FillChar(QoS, SizeOf(QoS), 0); QoS.Length := SizeOf(QoS); QoS.ImpersonationLevel := ImpersonationLevel; QoS.EffectiveOnly := EffectiveOnly; end; { ANSI_STRING } procedure ANSI_STRING.FromString(Value: AnsiString); begin Self.Buffer := PAnsiChar(Value); Self.Length := System.Length(Value) * SizeOf(AnsiChar); Self.MaximumLength := Self.Length + SizeOf(AnsiChar); end; { UNICODE_STRING } procedure UNICODE_STRING.FromString(Value: String); begin Self.Buffer := PWideChar(Value); Self.Length := System.Length(Value) * SizeOf(WideChar); Self.MaximumLength := Self.Length + SizeOf(WideChar); end; function UNICODE_STRING.ToString: String; begin SetString(Result, Buffer, Length div SizeOf(WideChar)); end; { TClientId } procedure TClientId.Create(PID, TID: NativeUInt); begin UniqueProcess := PID; UniqueThread := TID; end; end.
unit UFrmInputBox; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TFrmInputBox = class(TForm) txtInput: TEdit; BtnOK: TButton; BtnCancel: TButton; lblCaption: TLabel; procedure FormShow(Sender: TObject); procedure BtnOKClick(Sender: TObject); procedure BtnCancelClick(Sender: TObject); private { Private declarations } public { Public declarations } Caption, Default, Result:String; Execution: Boolean; end; var FrmInputBox: TFrmInputBox; implementation {$R *.dfm} procedure TFrmInputBox.BtnCancelClick(Sender: TObject); begin Result := ''; Execution := false; Close; end; procedure TFrmInputBox.BtnOKClick(Sender: TObject); begin Result := txtInput.Text; Execution := true; Close; end; procedure TFrmInputBox.FormShow(Sender: TObject); begin lblCaption.Caption := Caption; txtInput.Text := Default; end; end.
{$R-} {$Q-} unit ncEncTwofish; // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} interface uses System.Classes, System.Sysutils, ncEnccrypt2, ncEncblockciphers; const INPUTWHITEN = 0; OUTPUTWHITEN = 4; NUMROUNDS = 16; ROUNDSUBKEYS = (OUTPUTWHITEN + 4); TOTALSUBKEYS = (ROUNDSUBKEYS + NUMROUNDS * 2); RS_GF_FDBK = $14D; MDS_GF_FDBK = $169; SK_STEP = $02020202; SK_BUMP = $01010101; SK_ROTL = 9; type TncEnc_twofish = class(TncEnc_blockcipher128) protected SubKeys: array [0 .. TOTALSUBKEYS - 1] of DWord; sbox: array [0 .. 3, 0 .. 255] of DWord; procedure InitKey(const Key; Size: longword); override; public class function GetAlgorithm: string; override; class function GetMaxKeySize: integer; override; class function SelfTest: boolean; override; procedure Burn; override; procedure EncryptECB(const InData; var OutData); override; procedure DecryptECB(const InData; var OutData); override; constructor Create(AOwner: TComponent); override; end; { ****************************************************************************** } { ****************************************************************************** } implementation uses ncEncryption; const p8x8: array [0 .. 1, 0 .. 255] of byte = (($A9, $67, $B3, $E8, $04, $FD, $A3, $76, $9A, $92, $80, $78, $E4, $DD, $D1, $38, $0D, $C6, $35, $98, $18, $F7, $EC, $6C, $43, $75, $37, $26, $FA, $13, $94, $48, $F2, $D0, $8B, $30, $84, $54, $DF, $23, $19, $5B, $3D, $59, $F3, $AE, $A2, $82, $63, $01, $83, $2E, $D9, $51, $9B, $7C, $A6, $EB, $A5, $BE, $16, $0C, $E3, $61, $C0, $8C, $3A, $F5, $73, $2C, $25, $0B, $BB, $4E, $89, $6B, $53, $6A, $B4, $F1, $E1, $E6, $BD, $45, $E2, $F4, $B6, $66, $CC, $95, $03, $56, $D4, $1C, $1E, $D7, $FB, $C3, $8E, $B5, $E9, $CF, $BF, $BA, $EA, $77, $39, $AF, $33, $C9, $62, $71, $81, $79, $09, $AD, $24, $CD, $F9, $D8, $E5, $C5, $B9, $4D, $44, $08, $86, $E7, $A1, $1D, $AA, $ED, $06, $70, $B2, $D2, $41, $7B, $A0, $11, $31, $C2, $27, $90, $20, $F6, $60, $FF, $96, $5C, $B1, $AB, $9E, $9C, $52, $1B, $5F, $93, $0A, $EF, $91, $85, $49, $EE, $2D, $4F, $8F, $3B, $47, $87, $6D, $46, $D6, $3E, $69, $64, $2A, $CE, $CB, $2F, $FC, $97, $05, $7A, $AC, $7F, $D5, $1A, $4B, $0E, $A7, $5A, $28, $14, $3F, $29, $88, $3C, $4C, $02, $B8, $DA, $B0, $17, $55, $1F, $8A, $7D, $57, $C7, $8D, $74, $B7, $C4, $9F, $72, $7E, $15, $22, $12, $58, $07, $99, $34, $6E, $50, $DE, $68, $65, $BC, $DB, $F8, $C8, $A8, $2B, $40, $DC, $FE, $32, $A4, $CA, $10, $21, $F0, $D3, $5D, $0F, $00, $6F, $9D, $36, $42, $4A, $5E, $C1, $E0), ($75, $F3, $C6, $F4, $DB, $7B, $FB, $C8, $4A, $D3, $E6, $6B, $45, $7D, $E8, $4B, $D6, $32, $D8, $FD, $37, $71, $F1, $E1, $30, $0F, $F8, $1B, $87, $FA, $06, $3F, $5E, $BA, $AE, $5B, $8A, $00, $BC, $9D, $6D, $C1, $B1, $0E, $80, $5D, $D2, $D5, $A0, $84, $07, $14, $B5, $90, $2C, $A3, $B2, $73, $4C, $54, $92, $74, $36, $51, $38, $B0, $BD, $5A, $FC, $60, $62, $96, $6C, $42, $F7, $10, $7C, $28, $27, $8C, $13, $95, $9C, $C7, $24, $46, $3B, $70, $CA, $E3, $85, $CB, $11, $D0, $93, $B8, $A6, $83, $20, $FF, $9F, $77, $C3, $CC, $03, $6F, $08, $BF, $40, $E7, $2B, $E2, $79, $0C, $AA, $82, $41, $3A, $EA, $B9, $E4, $9A, $A4, $97, $7E, $DA, $7A, $17, $66, $94, $A1, $1D, $3D, $F0, $DE, $B3, $0B, $72, $A7, $1C, $EF, $D1, $53, $3E, $8F, $33, $26, $5F, $EC, $76, $2A, $49, $81, $88, $EE, $21, $C4, $1A, $EB, $D9, $C5, $39, $99, $CD, $AD, $31, $8B, $01, $18, $23, $DD, $1F, $4E, $2D, $F9, $48, $4F, $F2, $65, $8E, $78, $5C, $58, $19, $8D, $E5, $98, $57, $67, $7F, $05, $64, $AF, $63, $B6, $FE, $F5, $B7, $3C, $A5, $CE, $E9, $68, $44, $E0, $4D, $43, $69, $29, $2E, $AC, $15, $59, $A8, $0A, $9E, $6E, $47, $DF, $34, $35, $6A, $CF, $DC, $22, $C9, $C0, $9B, $89, $D4, $ED, $AB, $12, $A2, $0D, $52, $BB, $02, $2F, $A9, $D7, $61, $1E, $B4, $50, $04, $F6, $C2, $16, $25, $86, $56, $55, $09, $BE, $91)); var MDS: array [0 .. 3, 0 .. 255] of DWord; MDSDone: boolean; class function TncEnc_twofish.GetAlgorithm: string; begin Result := 'Twofish'; end; class function TncEnc_twofish.GetMaxKeySize: integer; begin Result := 256; end; class function TncEnc_twofish.SelfTest: boolean; const Out128: array [0 .. 15] of byte = ($5D, $9D, $4E, $EF, $FA, $91, $51, $57, $55, $24, $F1, $15, $81, $5A, $12, $E0); Out192: array [0 .. 15] of byte = ($E7, $54, $49, $21, $2B, $EE, $F9, $F4, $A3, $90, $BD, $86, $0A, $64, $09, $41); Out256: array [0 .. 15] of byte = ($37, $FE, $26, $FF, $1C, $F6, $61, $75, $F5, $DD, $F4, $C3, $3B, $97, $A2, $05); var i: integer; Key: array [0 .. 31] of byte; Block: array [0 .. 15] of byte; Cipher: TncEnc_twofish; begin Cipher := TncEnc_twofish.Create(nil); FillChar(Key, Sizeof(Key), 0); FillChar(Block, Sizeof(Block), 0); for i := 1 to 49 do begin Cipher.Init(Key, 128, nil); Move(Block, Key, 16); Cipher.EncryptECB(Block, Block); Cipher.Burn; end; Result := boolean(CompareMem(@Block, @Out128, 16)); FillChar(Key, Sizeof(Key), 0); FillChar(Block, Sizeof(Block), 0); for i := 1 to 49 do begin Cipher.Init(Key, 192, nil); Move(Key[0], Key[16], 8); Move(Block, Key, 16); Cipher.EncryptECB(Block, Block); Cipher.Burn; end; Result := Result and boolean(CompareMem(@Block, @Out192, 16)); FillChar(Key, Sizeof(Key), 0); FillChar(Block, Sizeof(Block), 0); for i := 1 to 49 do begin Cipher.Init(Key, 256, nil); Move(Key[0], Key[16], 16); Move(Block, Key, 16); Cipher.EncryptECB(Block, Block); Cipher.Burn; end; Result := Result and boolean(CompareMem(@Block, @Out256, 16)); Cipher.Burn; Cipher.Free; end; function LFSR1(x: DWord): DWord; begin if (x and 1) <> 0 then Result := (x shr 1) xor (MDS_GF_FDBK div 2) else Result := (x shr 1); end; function LFSR2(x: DWord): DWord; begin if (x and 2) <> 0 then if (x and 1) <> 0 then Result := (x shr 2) xor (MDS_GF_FDBK div 2) xor (MDS_GF_FDBK div 4) else Result := (x shr 2) xor (MDS_GF_FDBK div 2) else if (x and 1) <> 0 then Result := (x shr 2) xor (MDS_GF_FDBK div 4) else Result := (x shr 2); end; function Mul_X(x: DWord): DWord; begin Result := x xor LFSR2(x); end; function Mul_Y(x: DWord): DWord; begin Result := x xor LFSR1(x) xor LFSR2(x); end; function RS_MDS_Encode(lK0, lK1: DWord): DWord; var lR, nJ, lG2, lG3: DWord; bB: byte; begin lR := lK1; for nJ := 0 to 3 do begin bB := lR shr 24; if (bB and $80) <> 0 then lG2 := ((bB shl 1) xor RS_GF_FDBK) and $FF else lG2 := (bB shl 1) and $FF; if (bB and 1) <> 0 then lG3 := ((bB shr 1) and $7F) xor (RS_GF_FDBK shr 1) xor lG2 else lG3 := ((bB shr 1) and $7F) xor lG2; lR := (lR shl 8) xor (lG3 shl 24) xor (lG2 shl 16) xor (lG3 shl 8) xor bB; end; lR := lR xor lK0; for nJ := 0 to 3 do begin bB := lR shr 24; if (bB and $80) <> 0 then lG2 := ((bB shl 1) xor RS_GF_FDBK) and $FF else lG2 := (bB shl 1) and $FF; if (bB and 1) <> 0 then lG3 := ((bB shr 1) and $7F) xor (RS_GF_FDBK shr 1) xor lG2 else lG3 := ((bB shr 1) and $7F) xor lG2; lR := (lR shl 8) xor (lG3 shl 24) xor (lG2 shl 16) xor (lG3 shl 8) xor bB; end; Result := lR; end; function f32(x: DWord; K32: PDWordArray; Len: DWord): DWord; var t0, t1, t2, t3: DWord; begin t0 := x and $FF; t1 := (x shr 8) and $FF; t2 := (x shr 16) and $FF; t3 := x shr 24; if Len = 256 then begin t0 := p8x8[1, t0] xor ((K32^[3]) and $FF); t1 := p8x8[0, t1] xor ((K32^[3] shr 8) and $FF); t2 := p8x8[0, t2] xor ((K32^[3] shr 16) and $FF); t3 := p8x8[1, t3] xor ((K32^[3] shr 24)); end; if Len >= 192 then begin t0 := p8x8[1, t0] xor ((K32^[2]) and $FF); t1 := p8x8[1, t1] xor ((K32^[2] shr 8) and $FF); t2 := p8x8[0, t2] xor ((K32^[2] shr 16) and $FF); t3 := p8x8[0, t3] xor ((K32^[2] shr 24)); end; Result := MDS[0, p8x8[0, p8x8[0, t0] xor ((K32^[1]) and $FF)] xor ((K32^[0]) and $FF) ] xor MDS[1, p8x8[0, p8x8[1, t1] xor ((K32^[1] shr 8) and $FF)] xor ((K32^[0] shr 8) and $FF) ] xor MDS[2, p8x8[1, p8x8[0, t2] xor ((K32^[1] shr 16) and $FF)] xor ((K32^[0] shr 16) and $FF) ] xor MDS[3, p8x8[1, p8x8[1, t3] xor ((K32^[1] shr 24))] xor ((K32^[0] shr 24))]; end; procedure Xor256(Dst, Src: PDWordArray; v: byte); var i, j: DWord; begin i := 0; j := v * $01010101; while i < 64 do begin Dst^[i] := Src^[i] xor j; Dst^[i + 1] := Src^[i + 1] xor j; Dst^[i + 2] := Src^[i + 2] xor j; Dst^[i + 3] := Src^[i + 3] xor j; Inc(i, 4); end; end; procedure TncEnc_twofish.InitKey(const Key; Size: longword); const subkeyCnt = ROUNDSUBKEYS + 2 * NUMROUNDS; var key32: array [0 .. 7] of DWord; k32e, k32o, sboxkeys: array [0 .. 3] of DWord; k64Cnt, i, j, A, B, q: DWord; L0, L1: array [0 .. 255] of byte; begin FillChar(key32, Sizeof(key32), 0); Move(Key, key32, Size div 8); if Size <= 128 then { pad the key to either 128bit, 192bit or 256bit } Size := 128 else if Size <= 192 then Size := 192 else Size := 256; k64Cnt := Size div 64; j := k64Cnt - 1; for i := 0 to j do begin k32e[i] := key32[2 * i]; k32o[i] := key32[2 * i + 1]; sboxkeys[j] := RS_MDS_Encode(k32e[i], k32o[i]); Dec(j); end; q := 0; for i := 0 to ((subkeyCnt div 2) - 1) do begin A := f32(q, @k32e, Size); B := f32(q + SK_BUMP, @k32o, Size); B := (B shl 8) or (B shr 24); SubKeys[2 * i] := A + B; B := A + 2 * B; SubKeys[2 * i + 1] := (B shl SK_ROTL) or (B shr (32 - SK_ROTL)); Inc(q, SK_STEP); end; case Size of 128: begin Xor256(@L0, @p8x8[0], (sboxkeys[1] and $FF)); A := (sboxkeys[0] and $FF); i := 0; while i < 256 do begin sbox[0 and 2, 2 * i + (0 and 1)] := MDS[0, p8x8[0, L0[i]] xor A]; sbox[0 and 2, 2 * i + (0 and 1) + 2] := MDS[0, p8x8[0, L0[i + 1]] xor A]; Inc(i, 2); end; Xor256(@L0, @p8x8[1], (sboxkeys[1] shr 8) and $FF); A := (sboxkeys[0] shr 8) and $FF; i := 0; while i < 256 do begin sbox[1 and 2, 2 * i + (1 and 1)] := MDS[1, p8x8[0, L0[i]] xor A]; sbox[1 and 2, 2 * i + (1 and 1) + 2] := MDS[1, p8x8[0, L0[i + 1]] xor A]; Inc(i, 2); end; Xor256(@L0, @p8x8[0], (sboxkeys[1] shr 16) and $FF); A := (sboxkeys[0] shr 16) and $FF; i := 0; while i < 256 do begin sbox[2 and 2, 2 * i + (2 and 1)] := MDS[2, p8x8[1, L0[i]] xor A]; sbox[2 and 2, 2 * i + (2 and 1) + 2] := MDS[2, p8x8[1, L0[i + 1]] xor A]; Inc(i, 2); end; Xor256(@L0, @p8x8[1], (sboxkeys[1] shr 24)); A := (sboxkeys[0] shr 24); i := 0; while i < 256 do begin sbox[3 and 2, 2 * i + (3 and 1)] := MDS[3, p8x8[1, L0[i]] xor A]; sbox[3 and 2, 2 * i + (3 and 1) + 2] := MDS[3, p8x8[1, L0[i + 1]] xor A]; Inc(i, 2); end; end; 192: begin Xor256(@L0, @p8x8[1], sboxkeys[2] and $FF); A := sboxkeys[0] and $FF; B := sboxkeys[1] and $FF; i := 0; while i < 256 do begin sbox[0 and 2, 2 * i + (0 and 1)] := MDS[0, p8x8[0, p8x8[0, L0[i]] xor B] xor A]; sbox[0 and 2, 2 * i + (0 and 1) + 2] := MDS[0, p8x8[0, p8x8[0, L0[i + 1]] xor B] xor A]; Inc(i, 2); end; Xor256(@L0, @p8x8[1], (sboxkeys[2] shr 8) and $FF); A := (sboxkeys[0] shr 8) and $FF; B := (sboxkeys[1] shr 8) and $FF; i := 0; while i < 256 do begin sbox[1 and 2, 2 * i + (1 and 1)] := MDS[1, p8x8[0, p8x8[1, L0[i]] xor B] xor A]; sbox[1 and 2, 2 * i + (1 and 1) + 2] := MDS[1, p8x8[0, p8x8[1, L0[i + 1]] xor B] xor A]; Inc(i, 2); end; Xor256(@L0, @p8x8[0], (sboxkeys[2] shr 16) and $FF); A := (sboxkeys[0] shr 16) and $FF; B := (sboxkeys[1] shr 16) and $FF; i := 0; while i < 256 do begin sbox[2 and 2, 2 * i + (2 and 1)] := MDS[2, p8x8[1, p8x8[0, L0[i]] xor B] xor A]; sbox[2 and 2, 2 * i + (2 and 1) + 2] := MDS[2, p8x8[1, p8x8[0, L0[i + 1]] xor B] xor A]; Inc(i, 2); end; Xor256(@L0, @p8x8[0], (sboxkeys[2] shr 24)); A := (sboxkeys[0] shr 24); B := (sboxkeys[1] shr 24); i := 0; while i < 256 do begin sbox[3 and 2, 2 * i + (3 and 1)] := MDS[3, p8x8[1, p8x8[1, L0[i]] xor B] xor A]; sbox[3 and 2, 2 * i + (3 and 1) + 2] := MDS[3, p8x8[1, p8x8[1, L0[i + 1]] xor B] xor A]; Inc(i, 2); end; end; 256: begin Xor256(@L1, @p8x8[1], (sboxkeys[3]) and $FF); i := 0; while i < 256 do begin L0[i] := p8x8[1, L1[i]]; L0[i + 1] := p8x8[1, L1[i + 1]]; Inc(i, 2); end; Xor256(@L0, @L0, (sboxkeys[2]) and $FF); A := (sboxkeys[0]) and $FF; B := (sboxkeys[1]) and $FF; i := 0; while i < 256 do begin sbox[0 and 2, 2 * i + (0 and 1)] := MDS[0, p8x8[0, p8x8[0, L0[i]] xor B] xor A]; sbox[0 and 2, 2 * i + (0 and 1) + 2] := MDS[0, p8x8[0, p8x8[0, L0[i + 1]] xor B] xor A]; Inc(i, 2); end; Xor256(@L1, @p8x8[0], (sboxkeys[3] shr 8) and $FF); i := 0; while i < 256 do begin L0[i] := p8x8[1, L1[i]]; L0[i + 1] := p8x8[1, L1[i + 1]]; Inc(i, 2); end; Xor256(@L0, @L0, (sboxkeys[2] shr 8) and $FF); A := (sboxkeys[0] shr 8) and $FF; B := (sboxkeys[1] shr 8) and $FF; i := 0; while i < 256 do begin sbox[1 and 2, 2 * i + (1 and 1)] := MDS[1, p8x8[0, p8x8[1, L0[i]] xor B] xor A]; sbox[1 and 2, 2 * i + (1 and 1) + 2] := MDS[1, p8x8[0, p8x8[1, L0[i + 1]] xor B] xor A]; Inc(i, 2); end; Xor256(@L1, @p8x8[0], (sboxkeys[3] shr 16) and $FF); i := 0; while i < 256 do begin L0[i] := p8x8[0, L1[i]]; L0[i + 1] := p8x8[0, L1[i + 1]]; Inc(i, 2); end; Xor256(@L0, @L0, (sboxkeys[2] shr 16) and $FF); A := (sboxkeys[0] shr 16) and $FF; B := (sboxkeys[1] shr 16) and $FF; i := 0; while i < 256 do begin sbox[2 and 2, 2 * i + (2 and 1)] := MDS[2, p8x8[1, p8x8[0, L0[i]] xor B] xor A]; sbox[2 and 2, 2 * i + (2 and 1) + 2] := MDS[2, p8x8[1, p8x8[0, L0[i + 1]] xor B] xor A]; Inc(i, 2); end; Xor256(@L1, @p8x8[1], (sboxkeys[3] shr 24)); i := 0; while i < 256 do begin L0[i] := p8x8[0, L1[i]]; L0[i + 1] := p8x8[0, L1[i + 1]]; Inc(i, 2); end; Xor256(@L0, @L0, (sboxkeys[2] shr 24)); A := (sboxkeys[0] shr 24); B := (sboxkeys[1] shr 24); i := 0; while i < 256 do begin sbox[3 and 2, 2 * i + (3 and 1)] := MDS[3, p8x8[1, p8x8[1, L0[i]] xor B] xor A]; sbox[3 and 2, 2 * i + (3 and 1) + 2] := MDS[3, p8x8[1, p8x8[1, L0[i + 1]] xor B] xor A]; Inc(i, 2); end; end; end; end; procedure TncEnc_twofish.Burn; begin FillChar(sbox, Sizeof(sbox), $FF); FillChar(SubKeys, Sizeof(SubKeys), $FF); inherited Burn; end; procedure TncEnc_twofish.EncryptECB(const InData; var OutData); var i: longword; t0, t1: DWord; x: array [0 .. 3] of DWord; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); x[0] := PDWord(@InData)^ xor SubKeys[INPUTWHITEN]; x[1] := PDWord(longword(@InData) + 4)^ xor SubKeys[INPUTWHITEN + 1]; x[2] := PDWord(longword(@InData) + 8)^ xor SubKeys[INPUTWHITEN + 2]; x[3] := PDWord(longword(@InData) + 12)^ xor SubKeys[INPUTWHITEN + 3]; i := 0; while i <= NUMROUNDS - 2 do begin t0 := sbox[0, (x[0] shl 1) and $1FE] xor sbox[0, ((x[0] shr 7) and $1FE) + 1] xor sbox[2, (x[0] shr 15) and $1FE] xor sbox[2, ((x[0] shr 23) and $1FE) + 1]; t1 := sbox[0, ((x[1] shr 23) and $1FE)] xor sbox[0, ((x[1] shl 1) and $1FE) + 1] xor sbox[2, ((x[1] shr 7) and $1FE) ] xor sbox[2, ((x[1] shr 15) and $1FE) + 1]; x[3] := (x[3] shl 1) or (x[3] shr 31); x[2] := x[2] xor (t0 + t1 + SubKeys[ROUNDSUBKEYS + 2 * i]); x[3] := x[3] xor (t0 + 2 * t1 + SubKeys[ROUNDSUBKEYS + 2 * i + 1]); x[2] := (x[2] shr 1) or (x[2] shl 31); t0 := sbox[0, (x[2] shl 1) and $1FE] xor sbox[0, ((x[2] shr 7) and $1FE) + 1] xor sbox[2, ((x[2] shr 15) and $1FE) ] xor sbox[2, ((x[2] shr 23) and $1FE) + 1]; t1 := sbox[0, ((x[3] shr 23) and $1FE)] xor sbox[0, ((x[3] shl 1) and $1FE) + 1] xor sbox[2, ((x[3] shr 7) and $1FE) ] xor sbox[2, ((x[3] shr 15) and $1FE) + 1]; x[1] := (x[1] shl 1) or (x[1] shr 31); x[0] := x[0] xor (t0 + t1 + SubKeys[ROUNDSUBKEYS + 2 * (i + 1)]); x[1] := x[1] xor (t0 + 2 * t1 + SubKeys[ROUNDSUBKEYS + 2 * (i + 1) + 1]); x[0] := (x[0] shr 1) or (x[0] shl 31); Inc(i, 2); end; PDWord(longword(@OutData) + 0)^ := x[2] xor SubKeys[OUTPUTWHITEN]; PDWord(longword(@OutData) + 4)^ := x[3] xor SubKeys[OUTPUTWHITEN + 1]; PDWord(longword(@OutData) + 8)^ := x[0] xor SubKeys[OUTPUTWHITEN + 2]; PDWord(longword(@OutData) + 12)^ := x[1] xor SubKeys[OUTPUTWHITEN + 3]; end; procedure TncEnc_twofish.DecryptECB(const InData; var OutData); var i: integer; t0, t1: DWord; x: array [0 .. 3] of DWord; begin if not fInitialized then raise EncEnc_blockcipher.Create('Cipher not initialized'); x[2] := PDWord(@InData)^ xor SubKeys[OUTPUTWHITEN]; x[3] := PDWord(longword(@InData) + 4)^ xor SubKeys[OUTPUTWHITEN + 1]; x[0] := PDWord(longword(@InData) + 8)^ xor SubKeys[OUTPUTWHITEN + 2]; x[1] := PDWord(longword(@InData) + 12)^ xor SubKeys[OUTPUTWHITEN + 3]; i := NUMROUNDS - 2; while i >= 0 do begin t0 := sbox[0, (x[2] shl 1) and $1FE] xor sbox[0, ((x[2] shr 7) and $1FE) + 1] xor sbox[2, ((x[2] shr 15) and $1FE) ] xor sbox[2, ((x[2] shr 23) and $1FE) + 1]; t1 := sbox[0, ((x[3] shr 23) and $1FE)] xor sbox[0, ((x[3] shl 1) and $1FE) + 1] xor sbox[2, ((x[3] shr 7) and $1FE) ] xor sbox[2, ((x[3] shr 15) and $1FE) + 1]; x[0] := (x[0] shl 1) or (x[0] shr 31); x[0] := x[0] xor (t0 + t1 + SubKeys[ROUNDSUBKEYS + 2 * (i + 1)]); x[1] := x[1] xor (t0 + 2 * t1 + SubKeys[ROUNDSUBKEYS + 2 * (i + 1) + 1]); x[1] := (x[1] shr 1) or (x[1] shl 31); t0 := sbox[0, (x[0] shl 1) and $1FE] xor sbox[0, ((x[0] shr 7) and $1FE) + 1] xor sbox[2, (x[0] shr 15) and $1FE] xor sbox[2, ((x[0] shr 23) and $1FE) + 1]; t1 := sbox[0, ((x[1] shr 23) and $1FE)] xor sbox[0, ((x[1] shl 1) and $1FE) + 1] xor sbox[2, ((x[1] shr 7) and $1FE) ] xor sbox[2, ((x[1] shr 15) and $1FE) + 1]; x[2] := (x[2] shl 1) or (x[2] shr 31); x[2] := x[2] xor (t0 + t1 + SubKeys[ROUNDSUBKEYS + 2 * i]); x[3] := x[3] xor (t0 + 2 * t1 + SubKeys[ROUNDSUBKEYS + 2 * i + 1]); x[3] := (x[3] shr 1) or (x[3] shl 31); Dec(i, 2); end; PDWord(longword(@OutData) + 0)^ := x[0] xor SubKeys[INPUTWHITEN]; PDWord(longword(@OutData) + 4)^ := x[1] xor SubKeys[INPUTWHITEN + 1]; PDWord(longword(@OutData) + 8)^ := x[2] xor SubKeys[INPUTWHITEN + 2]; PDWord(longword(@OutData) + 12)^ := x[3] xor SubKeys[INPUTWHITEN + 3]; end; procedure PreCompMDS; var m1, mx, my: array [0 .. 1] of DWord; nI: longword; begin for nI := 0 to 255 do begin m1[0] := p8x8[0, nI]; mx[0] := Mul_X(m1[0]); my[0] := Mul_Y(m1[0]); m1[1] := p8x8[1, nI]; mx[1] := Mul_X(m1[1]); my[1] := Mul_Y(m1[1]); MDS[0, nI] := (m1[1] shl 0) or (mx[1] shl 8) or (my[1] shl 16) or (my[1] shl 24); MDS[1, nI] := (my[0] shl 0) or (my[0] shl 8) or (mx[0] shl 16) or (m1[0] shl 24); MDS[2, nI] := (mx[1] shl 0) or (my[1] shl 8) or (m1[1] shl 16) or (my[1] shl 24); MDS[3, nI] := (mx[0] shl 0) or (m1[0] shl 8) or (my[0] shl 16) or (mx[0] shl 24); end; end; constructor TncEnc_twofish.Create(AOwner: TComponent); begin inherited Create(AOwner); if not MDSDone then begin PreCompMDS; MDSDone := true; end; end; initialization MDSDone := false; end.
{*************************************************************** * * Project : telnet * Unit Name: mainform * Purpose : * Version : 1.0 * Date : Wed 25 Apr 2001 - 01:36:35 * Author : <unknown> * History : * Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com> * ****************************************************************} unit mainform; interface uses {$IFDEF Linux} QGraphics, QControls, QForms, QDialogs, QComCtrls, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, {$ENDIF} windows, messages, spin, SysUtils, Classes, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdTelnet; type TfrmTelnetDemo = class(TForm) Memo1: TRichEdit; edtServer: TEdit; lblServer: TLabel; spnedtPort: TSpinEdit; lblPort: TLabel; btnConnect: TButton; btnDisconnect: TButton; sbrStatus: TStatusBar; IdTelnetDemo: TIdTelnet; procedure btnConnectClick(Sender: TObject); procedure btnDisconnectClick(Sender: TObject); procedure Memo1KeyPress(Sender: TObject; var Key: Char); procedure IdTelnetDemoDataAvailable(Buffer: string); procedure IdTelnetDemoConnected(Sender: TObject); procedure IdTelnetDemoConnect; private { Private declarations } public { Public declarations } end; var frmTelnetDemo: TfrmTelnetDemo; implementation {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} procedure TfrmTelnetDemo.btnConnectClick(Sender: TObject); begin IDTelnetDemo.Host := edtServer.Text; IDTelnetDemo.port := spnedtPort.Value; IdTelnetDemo.Connect; end; procedure TfrmTelnetDemo.btnDisconnectClick(Sender: TObject); begin IdTelnetDemo.Disconnect; end; procedure TfrmTelnetDemo.Memo1KeyPress(Sender: TObject; var Key: Char); begin {we simply send the key stroke to the server. It may echo it back to us} if IdTelnetDemo.Connected then IdTelnetDemo.SendCh(Key); Key := #0; end; procedure TfrmTelnetDemo.IdTelnetDemoDataAvailable(Buffer: string); {This routine comes directly from the ICS TNDEMO code. Thanks to Francois Piette It updates the memo control when we get data} const CR = #13; LF = #10; var Start, Stop: Integer; begin if Memo1.Lines.Count = 0 then Memo1.Lines.Add(''); Start := 1; Stop := Pos(CR, Buffer); if Stop = 0 then Stop := Length(Buffer) + 1; while Start <= Length(Buffer) do begin Memo1.Lines.Strings[Memo1.Lines.Count - 1] := Memo1.Lines.Strings[Memo1.Lines.Count - 1] + Copy(Buffer, Start, Stop - Start); if Buffer[Stop] = CR then begin Memo1.Lines.Add(''); {$IFNDEF Linux} SendMessage(Memo1.Handle, WM_KEYDOWN, VK_UP, 1); {$ENDIF} end; Start := Stop + 1; if Start > Length(Buffer) then Break; if Buffer[Start] = LF then Start := Start + 1; Stop := Start; while (Buffer[Stop] <> CR) and (Stop <= Length(Buffer)) do Stop := Stop + 1; end; end; procedure TfrmTelnetDemo.IdTelnetDemoConnected(Sender: TObject); begin sbrStatus.SimpleText := 'Connected'; end; procedure TfrmTelnetDemo.IdTelnetDemoConnect; begin sbrStatus.SimpleText := 'Connect'; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Web server application components } { } { Copyright (c) 2000, 2001 Borland Software Corporation } { } {*******************************************************} // Parse an HTTP header. unit HTTPParse; interface uses SysUtils, Classes; const toEOL = Char(5); toGET = Char(6); toHEAD = Char(7); toPUT = Char(8); toDELETE = Char(9); toPOST = Char(10); toPATCH = Char(11); toCOPY = Char(12); toUserAgent = Char(13); toAccept = Char(14); toContentType = Char(15); toContentLength = Char(16); toReferer = Char(17); toAuthorization = Char(18); toCacheControl = Char(19); toDate = Char(20); toFrom = Char(21); toHost = Char(22); toIfModified = Char(23); toContentEncoding = Char(24); toContentVersion= Char(25); toAllow = Char(26); toConnection = Char(27); toCookie = Char(28); toContentDisposition = Char(29); hcGET = $14F5; hcPUT = $4AF5; hcDELETE = $92B2; hcPOST = $361D; hcCacheControl = $4FF6; hcDate = $0EE6; hcFrom = $418F; hcHost = $3611; hcIfModified = $DDF0; hcAllow = $3D80; hcUserAgent = $E890; hcAccept = $1844; hcContentEncoding= $C586; hcContentVersion = $EDF4; hcContentType = $F0E0; hcContentLength = $B0C4; hcReferer = $CEA5; hcAuthorization = $ABCA; hcConnection = $0EDE; hcCookie = $27B3; hcContentDisposition = $CBEB; type { THTTPParser } THTTPParser = class(TObject) private FStream: TStream; FOrigin: Longint; FBuffer: PChar; FBufPtr: PChar; FBufEnd: PChar; FSourcePtr: PChar; FSourceEnd: PChar; FStringPtr: PChar; FSourceLine: Integer; FSaveChar: Char; FToken: Char; FHeaderField: Boolean; FTokenPtr: PChar; procedure ReadBuffer; procedure SkipBlanks; public constructor Create(Stream: TStream); destructor Destroy; override; procedure CheckToken(T: Char); procedure CheckTokenSymbol(const S: string); function CopyTo(Length: Integer): string; function CopyToEOL: string; function CopyToEOF: string; procedure Error(const Ident: string); procedure ErrorFmt(const Ident: string; const Args: array of const); procedure ErrorStr(const Message: string); procedure HexToBinary(Stream: TStream); function NextToken: Char; procedure SkipEOL; function SourcePos: Longint; function TokenFloat: Extended; function TokenInt: Longint; function TokenString: string; function TokenSymbolIs(const S: string): Boolean; function BufferRequest(Length: Integer): TStream; property SourceLine: Integer read FSourceLine; property Token: Char read FToken; property HeaderField: Boolean read FHeaderField write FHeaderField; property SourcePtr: PChar read FSourcePtr write FSourcePtr; property TokenPtr: PChar read FTokenPtr write FTokenPtr; property Stream: TStream read FStream; property SourceEnd: PChar read FSourceEnd; end; implementation uses RTLConsts; const ParseBufSize = 4096; { THTTPParser } constructor THTTPParser.Create(Stream: TStream); begin FStream := Stream; GetMem(FBuffer, ParseBufSize); FBuffer[0] := #0; FBufPtr := FBuffer; FBufEnd := FBuffer + ParseBufSize; FSourcePtr := FBuffer; FSourceEnd := FBuffer; FTokenPtr := FBuffer; FSourceLine := 1; FHeaderField := True; NextToken; end; function THTTPParser.BufferRequest(Length: Integer): TStream; const BufSize = 1000; var Buffer: array[0..BufSize-1] of byte; Count: Integer; L, R, T, C: Integer; P1, P2: PChar; begin // Get processed contents of parser buffer Result := TMemoryStream.Create; Count := FSourcePtr - FBuffer; Result.Write(Pointer(FBuffer)^, Count); // Find end of parser buffer if Length > 0 then begin P1 := FSourcePtr; P2 := P1; while (P2^ <> #0) do Inc(P2); while Length > 0 do begin if Length > BufSize then L := BufSize else L := Length; if P1 < P2 then begin // Read from parser buffer if L > P2 - P1 then R := P2 - P1 else R := L; Move(P1^, Buffer, R); L := R; P1 := P1 + R; end else begin T := 0; R := L; repeat C := FStream.Read(Buffer[T], R-T); T := T + C; until (C = 0) or (T = R); end; Result.Write(Buffer, L); Length := Length - R; end; end; Result.Seek(Count, soFromBeginning); FStream := Result; end; destructor THTTPParser.Destroy; begin if FBuffer <> nil then begin FStream.Seek(Longint(FTokenPtr) - Longint(FSourceEnd), 1); FreeMem(FBuffer, ParseBufSize); end; end; procedure THTTPParser.CheckToken(T: Char); begin if Token <> T then case T of toSymbol: Error(SIdentifierExpected); toString: Error(SStringExpected); toInteger, toFloat: Error(SNumberExpected); else ErrorFmt(SCharExpected, [T]); end; end; procedure THTTPParser.CheckTokenSymbol(const S: string); begin if not TokenSymbolIs(S) then ErrorFmt(SSymbolExpected, [S]); end; function THTTPParser.CopyTo(Length: Integer): string; var P: PChar; Temp: string; begin Result := ''; repeat P := FTokenPtr; while (Length > 0) and (P^ <> #0) do begin Inc(P); Dec(Length); end; SetString(Temp, FTokenPtr, P - FTokenPtr); Result := Result + Temp; if Length > 0 then ReadBuffer; until (Length = 0) or (Token = toEOF); FSourcePtr := P; end; function THTTPParser.CopyToEOL: string; var P: PChar; begin P := FTokenPtr; while not (P^ in [#13, #10, #0]) do Inc(P); SetString(Result, FTokenPtr, P - FTokenPtr); if P^ = #13 then Inc(P); FSourcePtr := P; if P^ <> #0 then NextToken else FToken := #0; end; function THTTPParser.CopyToEOF: string; var P: PChar; Temp: string; begin repeat P := FTokenPtr; while P^ <> #0 do Inc(P); FSourcePtr := P; ReadBuffer; SetString(Temp, FTokenPtr, P - FTokenPtr); Result := Result + Temp; NextToken; until Token = toEOF; end; procedure THTTPParser.Error(const Ident: string); begin ErrorStr(Ident); end; procedure THTTPParser.ErrorFmt(const Ident: string; const Args: array of const); begin ErrorStr(Format(Ident, Args)); end; procedure THTTPParser.ErrorStr(const Message: string); begin raise EParserError.CreateResFmt(@SParseError, [Message, FSourceLine]); end; procedure THTTPParser.HexToBinary(Stream: TStream); var Count: Integer; Buffer: array[0..255] of Char; begin SkipBlanks; while FSourcePtr^ <> '}' do begin Count := HexToBin(FSourcePtr, Buffer, SizeOf(Buffer)); if Count = 0 then Error(SInvalidBinary); Stream.Write(Buffer, Count); Inc(FSourcePtr, Count * 2); SkipBlanks; end; NextToken; end; const CharValue: array[Byte] of Byte = ( $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$00,$00,$00,$00,$00,$00, $00,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F, $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,$00,$00,$00,$00,$5F, $00,$41,$42,$43,$44,$45,$46,$47,$48,$49,$4A,$4B,$4C,$4D,$4E,$4F, $50,$51,$52,$53,$54,$55,$56,$57,$58,$59,$5A,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00, $00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00); function GetHashCode(Ident: PChar; Length: Integer): Word; asm PUSH ESI {$IFNDEF PIC} PUSH EBX XOR EBX,EBX {$ENDIF} MOV ESI, EAX XOR EAX, EAX XOR ECX, ECX @@1: MOV AL,[ESI] ROL CX,5 XOR CL,CharValue.Byte[EBX + EAX] INC ESI DEC EDX JNE @@1 MOV EAX,ECX {$IFNDEF PIC} POP EBX {$ENDIF} POP ESI end; type TSymbolEntry = record HashCode: Word; Symbol: PChar; Token: Char; end; const SymbolTable: array[0..20] of TSymbolEntry = ( (HashCode: hcGet; Symbol: 'GET'; Token: toGET), (HashCode: hcPut; Symbol: 'PUT'; Token: toPUT), (HashCode: hcDelete; Symbol: 'DELETE'; Token: toDELETE), (HashCode: hcPost; Symbol: 'POST'; Token: toPOST), (HashCode: hcCacheControl; Symbol: 'Cache-Control'; Token: toCacheControl), (HashCode: hcDate; Symbol: 'Date'; Token: toDate), (HashCode: hcFrom; Symbol: 'From'; Token: toFrom), (HashCode: hcHost; Symbol: 'Host'; Token: toHost), (HashCode: hcIfModified; Symbol: 'If-Modified-Since'; Token: toIfModified), (HashCode: hcAllow; Symbol: 'Allow'; Token: toAllow), (HashCode: hcUserAgent; Symbol: 'User-Agent'; Token: toUserAgent), (HashCode: hcAccept; Symbol: 'Accept'; Token: toAccept), (HashCode: hcContentEncoding; Symbol: 'Content-Encoding'; Token: toContentEncoding), (HashCode: hcContentVersion; Symbol: 'Content-Version'; Token: toContentVersion), (HashCode: hcContentType; Symbol: 'Content-Type'; Token: toContentType), (HashCode: hcContentLength; Symbol: 'Content-Length'; Token: toContentLength), (HashCode: hcReferer; Symbol: 'Referer'; Token: toReferer), (HashCode: hcConnection; Symbol: 'Connection'; Token: toConnection), (HashCode: hcCookie; Symbol: 'Cookie'; Token: toCookie), (HashCode: hcAuthorization; Symbol: 'Authorization'; Token: toAuthorization), (HashCode: hcContentDisposition; Symbol: 'Content-Disposition'; Token: toContentDisposition)); function LookupToken(Sym: PChar): Char; var HCode: Word; I: Integer; begin Result := toSymbol; HCode := GetHashCode(Sym, StrLen(Sym)); for I := Low(SymbolTable) to High(SymbolTable) do with SymbolTable[I] do if HCode = HashCode then if StrIComp(Symbol, Sym) = 0 then begin Result := Token; Break; end; end; function THTTPParser.NextToken: Char; var I: Integer; P, S: PChar; SaveChar: Char; TokenChars: set of Char; begin SkipBlanks; P := FSourcePtr; FTokenPtr := P; if FHeaderField then TokenChars := ['A'..'Z', 'a'..'z', '0'..'9', '_', '-'] else TokenChars := ['A'..'Z', 'a'..'z', '0'..'9', '_']; case P^ of 'A'..'Z', 'a'..'z', '_': begin Inc(P); while P^ in TokenChars do Inc(P); SaveChar := P^; try P^ := #0; Result := LookupToken(FTokenPtr); finally P^ := SaveChar; end; end; #10: begin Inc(P); Inc(FSourceLine); Result := toEOL; end; '#', '''': begin S := P; while True do case P^ of '#': begin Inc(P); I := 0; while P^ in ['0'..'9'] do begin I := I * 10 + (Ord(P^) - Ord('0')); Inc(P); end; S^ := Chr(I); Inc(S); end; '''': begin Inc(P); while True do begin case P^ of #0, #10, #13: Error(SInvalidString); '''': begin Inc(P); if P^ <> '''' then Break; end; end; S^ := P^; Inc(S); Inc(P); end; end; else Break; end; FStringPtr := S; Result := toString; end; '$': begin Inc(P); while P^ in ['0'..'9', 'A'..'F', 'a'..'f'] do Inc(P); Result := toInteger; end; '0'..'9': begin Inc(P); while P^ in ['0'..'9'] do Inc(P); Result := toInteger; while P^ in ['0'..'9', '.', 'e', 'E', '+'] do begin Inc(P); Result := toFloat; end; end; else Result := P^; if Result <> toEOF then Inc(P); end; FSourcePtr := P; FToken := Result; end; procedure THTTPParser.ReadBuffer; var Count: Integer; P: PChar; begin Inc(FOrigin, FSourcePtr - FBuffer); FSourceEnd[0] := FSaveChar; Count := FBufPtr - FSourcePtr; if Count <> 0 then Move(FSourcePtr[0], FBuffer[0], Count); FBufPtr := FBuffer + Count; Inc(FBufPtr, FStream.Read(FBufPtr[0], FBufEnd - FBufPtr)); FSourcePtr := FBuffer; FSourceEnd := FBufPtr; if FSourceEnd = FBufEnd then begin FSourceEnd := LineStart(FBuffer, FSourceEnd - 1); if FSourceEnd = FBuffer then Error(SLineTooLong); end; P := FBuffer; while P < FSourceEnd do begin Inc(P); end; FSaveChar := FSourceEnd[0]; FSourceEnd[0] := #0; end; procedure THTTPParser.SkipBlanks; begin while True do begin case FSourcePtr^ of #0: begin ReadBuffer; if FSourcePtr^ = #0 then Exit; Continue; end; #10: Exit; #33..#255: Exit; end; Inc(FSourcePtr); end; end; function THTTPParser.SourcePos: Longint; begin Result := FOrigin + (FTokenPtr - FBuffer); end; procedure THTTPParser.SkipEOL; begin if Token = toEOL then begin while FTokenPtr^ in [#13, #10] do Inc(FTokenPtr); FSourcePtr := FTokenPtr; if FSourcePtr^ <> #0 then NextToken else FToken := #0; end; end; function THTTPParser.TokenFloat: Extended; begin Result := StrToFloat(TokenString); end; function THTTPParser.TokenInt: Longint; begin Result := StrToInt(TokenString); end; function THTTPParser.TokenString: string; var L: Integer; begin if FToken = toString then L := FStringPtr - FTokenPtr else L := FSourcePtr - FTokenPtr; SetString(Result, FTokenPtr, L); end; function THTTPParser.TokenSymbolIs(const S: string): Boolean; begin Result := (Token = toSymbol) and (CompareText(S, TokenString) = 0); end; end.
unit ContrastUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls; type TContrastForm = class(TForm) EditContrast: TEdit; UpDownContrast: TUpDown; ButtonOK: TButton; ButtonCancel: TButton; Label1: TLabel; EditBright: TEdit; TrackBarBright: TTrackBar; UpDownBright: TUpDown; TrackBarContrast: TTrackBar; Label2: TLabel; procedure EditContrastChange(Sender: TObject); procedure ButtonOKClick(Sender: TObject); procedure TrackBarContrastChange(Sender: TObject); procedure ButtonCancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure TrackBarBrightChange(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure EditBrightChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var ContrastForm: TContrastForm; implementation {$R *.dfm} Uses MainUnit; type TRGBTripleArray = array[0..32768] of TRGBTriple; procedure Contrast(Bitmap: TBitmap; Value: Integer; Local: Boolean); function BLimit(B: Integer): Byte; begin if B < 0 then Result := 0 else if B > 255 then Result := 255 else Result := B; end; var Dest: pRGBTriple; x, y, mr, mg, mb, W, H, tr, tg, tb: Integer; vd: Double; begin if Value = 0 then Exit; W := Bitmap.Width - 1; H := Bitmap.Height - 1; if Local then begin mR := 128; mG := 128; mB := 128; end else begin tr := 0; tg := 0; tb := 0; for y := 0 to H do begin Dest := Bitmap.ScanLine[y]; for x := 0 to W do begin with Dest^ do begin Inc(tb, rgbtBlue); Inc(tg, rgbtGreen); Inc(tr, rgbtRed); end; Inc(Dest); end; end; mB := Trunc(tb / (W * H)); mG := Trunc(tg / (W * H)); mR := Trunc(tr / (W * H)); end; if Value > 0 then vd := 1 + (Value / 10) else vd := 1 - (Sqrt(-Value) / 10); for y := 0 to H do begin Dest := Bitmap.ScanLine[y]; for x := 0 to W do begin with Dest^ do begin rgbtBlue := BLimit(mB + Trunc((rgbtBlue - mB) * vd)); rgbtGreen := BLimit(mG + Trunc((rgbtGreen - mG) * vd)); rgbtRed := BLimit(mR + Trunc((rgbtRed - mR) * vd)); end; Inc(Dest); end; end; end; procedure bright(const Bitmap:TBitmap; const factor:Double); //изменение €ркости var i,j:integer; r,g,b:integer; Reihe: ^TRGBTriple; begin for i:=0 to Bitmap.Height-1 do begin Reihe:=Bitmap.ScanLine[i]; for j:=0 to Bitmap.Width-1 do begin r:=Round(Reihe^.rgbtRed*factor); g:=Round(Reihe^.rgbtGreen*factor); b:=Round(Reihe^.rgbtBlue*factor); if r>255 then r:=255; if g>255 then g:=255; if b>255 then b:=255; Reihe^.rgbtRed:=r; Reihe^.rgbtGreen:=g; Reihe^.rgbtBlue:=b; Inc(Reihe); end; end; bitmap.Assign(Bitmap); end; procedure TContrastForm.ButtonCancelClick(Sender: TObject); begin buffer.Assign(img); ContrastForm.Close; end; procedure TContrastForm.ButtonOKClick(Sender: TObject); begin img.Assign(buffer); ContrastForm.Close; end; procedure TContrastForm.EditBrightChange(Sender: TObject); begin buffer.Assign(img); TrackBarBright.Position:=StrToInt(EditBright.Text); Bright(buffer,TrackBarBright.Position); MainForm.PaintBox.Visible:=false; MainForm.PaintBox.Visible:=true; end; procedure TContrastForm.EditContrastChange(Sender: TObject); begin buffer.Assign(img); TrackBarContrast.Position:=StrToInt(EditContrast.Text); Contrast(buffer,TrackBarContrast.Position, false); MainForm.PaintBox.Visible:=false; MainForm.PaintBox.Visible:=true; end; procedure TContrastForm.FormClose(Sender: TObject; var Action: TCloseAction); begin buffer.Assign(img); end; procedure TContrastForm.FormKeyPress(Sender: TObject; var Key: Char); begin if key=#13 then ButtonOK.Click; if key=#27 then ButtonCancel.Click; end; procedure TContrastForm.TrackBarBrightChange(Sender: TObject); begin EditBright.Text:=IntToStr(TrackBarBright.Position); end; procedure TContrastForm.TrackBarContrastChange(Sender: TObject); begin EditContrast.Text:=IntToStr(TrackBarContrast.Position); end; end.
PROGRAM SplitProg; const splitChar = '/'; FUNCTION WithoutLastChar(s: string): string; BEGIN (* WithoutLastChar *) if Length(s) > 0 then SetLength(s, Length(s) - 1); WithoutLastChar := s; END; (* WithoutLastChar *) FUNCTION EqualsIgnoreCase(a, b: string): boolean; BEGIN (* EqualsIgnoreCase *) if Upcase(a) = Upcase(b) then begin EqualsIgnoreCase := true; end else begin EqualsIgnoreCase := false; end; (* IF *) END; (* EqualsIgnoreCase *) PROCEDURE ClearArray(var words: array of string); var i: integer; BEGIN (* ClearArray *) for i := Low(words) to High(words) do BEGIN words[i] := ''; END; (* FOR *) END; (* ClearArray *) PROCEDURE Split(s: string; var words: array of string; var nrOfWords: integer); var i, wordsPos: integer; BEGIN (* Split *) nrOfWords := 0; wordsPos := Low(words); for i := 1 to Length(s) do BEGIN if s[i] <> splitChar then BEGIN words[wordsPos] := words[wordsPos] + s[i]; end else if s[i] = splitChar then BEGIN if i <> 1 then begin if s[i - 1] <> splitChar then Inc(wordsPos); end; (* IF *) END; (* IF *) END; (* FOR *) nrOfWords := Length(words); END; (* Split *) var words: array[1..100] of string; nrWords, i: integer; s: string; BEGIN WriteLn('Is "Pascal" and "paScAL" equal? ', EqualsIgnoreCase('Pascal', 'paScAL')); WriteLn('Is "tESt" and "test" equal? ', EqualsIgnoreCase('tESt', 'test')); WriteLn('Is "test" and "test2" equal? ', EqualsIgnoreCase('test', 'test2')); WriteLn(); WriteLn('Hello World without last char: ', WithoutLastChar('Hello World')); WriteLn('Test without last char: ', WithoutLastChar('test')); WriteLn('Lorem ipsum without last char: ', WithoutLastChar('Lorem ipsum')); WriteLn(); REPEAT ClearArray(words); Write('Text: '); ReadLn(s); Split(s, words, nrWords); for i := 1 to nrWords do BEGIN if (Pos(splitChar, words[i]) = 0) AND (Length(words[i]) > 0) then WriteLn(i, ': ', words[i]); END; (* FOR *) UNTIL s = ''; (* SplitProg.exe < test.txt *) END.
// GLScriptDWS2 {: DelphiWebScriptII implementation for the GLScene scripting layer.<p> <b>History : </b><font size=-1><ul> <li>04/11/2004 - SG - Creation </ul></font> } unit GLScriptDWS2; interface uses Classes, SysUtils, XCollection, GLScriptBase, dws2Comp, dws2Exprs, dws2Symbols, GLManager; type // TGLDelphiWebScriptII // {: This class only adds manager registration logic to the TDelphiWebScriptII class to enable the XCollection items (ie. TGLScriptDWS2) retain it's assigned compiler from design to run -time. } TGLDelphiWebScriptII = class(TDelphiWebScriptII) public constructor Create(AOnwer : TComponent); override; destructor Destroy; override; end; // GLScriptDWS2 // {: Implements DelphiWebScriptII scripting functionality through the abstracted GLScriptBase . } TGLScriptDWS2 = class(TGLScriptBase) private { Private Declarations } FDWS2Program : TProgram; FCompiler : TGLDelphiWebScriptII; FCompilerName : String; protected { Protected Declarations } procedure SetCompiler(const Value : TGLDelphiWebScriptII); procedure ReadFromFiler(reader : TReader); override; procedure WriteToFiler(writer : TWriter); override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetState : TGLScriptState; override; public { Public Declarations } destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Compile; override; procedure Start; override; procedure Stop; override; procedure Execute; override; procedure Invalidate; override; function Call(aName : String; aParams : array of Variant) : Variant; override; class function FriendlyName : String; override; class function FriendlyDescription : String; override; class function ItemCategory : String; override; property DWS2Program : TProgram read FDWS2Program; published { Published Declarations } property Compiler : TGLDelphiWebScriptII read FCompiler write SetCompiler; end; procedure Register; // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- implementation // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- // --------------- // --------------- Miscellaneous --------------- // --------------- // Register // procedure Register; begin RegisterClasses([TGLDelphiWebScriptII, TGLScriptDWS2]); RegisterComponents('GLScene DWS2', [TGLDelphiWebScriptII]); end; // ---------- // ---------- TGLDelphiWebScriptII ---------- // ---------- // Create // constructor TGLDelphiWebScriptII.Create(AOnwer : TComponent); begin inherited; RegisterManager(Self); end; // Destroy // destructor TGLDelphiWebScriptII.Destroy; begin DeregisterManager(Self); inherited; end; // --------------- // --------------- TGLScriptDWS2 --------------- // --------------- // Destroy // destructor TGLScriptDWS2.Destroy; begin Invalidate; inherited; end; // Assign // procedure TGLScriptDWS2.Assign(Source: TPersistent); begin inherited; if Source is TGLScriptDWS2 then begin Compiler:=TGLScriptDWS2(Source).Compiler; end; end; // ReadFromFiler // procedure TGLScriptDWS2.ReadFromFiler(reader : TReader); var archiveVersion : Integer; begin inherited; archiveVersion:=reader.ReadInteger; Assert(archiveVersion = 0); with reader do begin FCompilerName:=ReadString; end; end; // WriteToFiler // procedure TGLScriptDWS2.WriteToFiler(writer : TWriter); begin inherited; writer.WriteInteger(0); // archiveVersion with writer do begin if Assigned(FCompiler) then WriteString(FCompiler.GetNamePath) else WriteString(''); end; end; // Loaded // procedure TGLScriptDWS2.Loaded; var temp : TComponent; begin inherited; if FCompilerName<>'' then begin temp:=FindManager(TGLDelphiWebScriptII, FCompilerName); if Assigned(temp) then Compiler:=TGLDelphiWebScriptII(temp); FCompilerName:=''; end; end; // Notification // procedure TGLScriptDWS2.Notification(AComponent: TComponent; Operation: TOperation); begin if (AComponent = Compiler) and (Operation = opRemove) then Compiler:=nil; end; // FriendlyName // class function TGLScriptDWS2.FriendlyName : String; begin Result:='GLScriptDWS2'; end; // FriendlyDescription // class function TGLScriptDWS2.FriendlyDescription : String; begin Result:='DelphiWebScriptII script'; end; // ItemCategory // class function TGLScriptDWS2.ItemCategory : String; begin Result:=''; end; // Compile // procedure TGLScriptDWS2.Compile; begin Invalidate; if Assigned(Compiler) then FDWS2Program:=Compiler.Compile(Text.Text) else raise Exception.Create('No compiler assigned!'); end; // Execute // procedure TGLScriptDWS2.Execute; begin if (State = ssUncompiled) then Compile else if (State = ssRunning) then Stop; if (State = ssCompiled) then FDWS2Program.Execute; end; // Invalidate // procedure TGLScriptDWS2.Invalidate; begin if (State <> ssUncompiled) or Assigned(FDWS2Program) then begin Stop; FreeAndNil(FDWS2Program); end; end; // Start // procedure TGLScriptDWS2.Start; begin if (State = ssUncompiled) then Compile; if (State = ssCompiled) then FDWS2Program.BeginProgram(False); end; // Stop // procedure TGLScriptDWS2.Stop; begin if (State = ssRunning) then FDWS2Program.EndProgram; end; // Call // function TGLScriptDWS2.Call(aName: String; aParams: array of Variant) : Variant; var Symbol : TSymbol; Output : IInfo; begin if (State <> ssRunning) then Start; if State = ssRunning then begin Symbol:=FDWS2Program.Table.FindSymbol(aName); if Assigned(Symbol) then begin if Symbol is TFuncSymbol then begin Output:=FDWS2Program.Info.Func[aName].Call(aParams); if Assigned(Output) then Result:=Output.Value; end else raise Exception.Create('Expected TFuncSymbol but found '+Symbol.ClassName+' for '+aName); end else raise Exception.Create('Symbol not found for '+aName); end; end; // SetCompiler // procedure TGLScriptDWS2.SetCompiler(const Value : TGLDelphiWebScriptII); begin if Value<>FCompiler then begin FCompiler:=Value; Invalidate; end; end; // GetState // function TGLScriptDWS2.GetState : TGLScriptState; begin Result:=ssUncompiled; if Assigned(FDWS2Program) then begin case FDWS2Program.ProgramState of psReadyToRun : Result:=ssCompiled; psRunning : Result:=ssRunning; else if FDWS2Program.Msgs.HasErrors then begin if FDWS2Program.Msgs.HasCompilerErrors then Result:=ssCompileErrors else if FDWS2Program.Msgs.HasExecutionErrors then Result:=ssRunningErrors; Errors.Text:=FDWS2Program.Msgs.AsInfo; end; end; end; end; // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- initialization // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- RegisterXCollectionItemClass(TGLScriptDWS2); // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- finalization // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- UnregisterXCollectionItemClass(TGLScriptDWS2); end.
unit ufQMultSele; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Layouts, FMX.ScrollBox, FMX.Memo, ksTypes, ksVirtualListView, uBusiObj, FMX.TabControl, FMX.ListBox, FMX.Ani; const cTabName = 'TabQMultiSele'; cHeaderTitle = 'Sample Survey Question'; cTag = uBusiObj.tnQMultiSele; type TfraQMultSele = class(TFrame) ToolBar1: TToolBar; btnCancel: TSpeedButton; btnDone: TSpeedButton; lblHeaderTItle: TLabel; Memo1: TMemo; Layout1: TLayout; ListBox1: TListBox; ListBoxItem1: TListBoxItem; ListBoxGroupFooter1: TListBoxGroupFooter; FloatAnimation1: TFloatAnimation; Button1: TButton; procedure btnCancelClick(Sender: TObject); procedure ListBoxItem1Click(Sender: TObject); procedure btnDoneClick(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } FOnNextBtnClick: ^TProc; //<TObject>; -in the future, this should contain the ID of the next question. FOnCloseTab: ^TProc; procedure AnimateTrans(AAnimateRule: TAnimateRule); public { Public declarations } procedure PopuUI; end; TTabOfFrame = class(TTabItem) strict private FOnNextBtnClick: TProc; //<TObject>; FOnCloseTab: TProc; //<TObject>; { FTabItemState: TTabItemState; //FOnBackBtnClick: TProc<TObject>; //FOnDoneBtnClick: TProc<TObject>; // TProc<TObject, TUpdateMade, integer>; FOnAfterSave: TProc<TUpdateMade, integer>; FOnAfterDeleted: TProc<TUpdateMade, integer>; FCarID: integer; FOnUOMPickList: TProc<TEdit>; FOnATPickList: TProc<TEdit>; } private // FRecID: integer; public FCallerTab: TTabItem; FFrameMain: TfraQMultSele; property OnNextBtnClick: TProc read FOnNextBtnClick write FOnNextBtnClick; property OnCloseTab: TProc read FOnCloseTab write FOnCloseTab; procedure CloseTab(AIsRelease: Boolean); constructor Create(AOwner: TComponent); // supply various params here. AReccordID: integer); // ; AUserRequest: TUserRequest destructor Destroy; override; procedure ShowTab(ACallerTab: TTabItem); //; AUserRequest: TUserIntentInit; ATID, ACarID: integer); { FFrameMain: TfraCarHistUpd; FFrameHdr: TfraCarHdr; //property OnBackBtnClick: TProc<TObject> read FOnBackBtnClick write FOnBackBtnClick; //property OnDoneBtnClick: TProc<TObject> read FOnDoneBtnClick write FOnDoneBtnClick; property OnAfterSave: TProc<TUpdateMade, Integer> read FOnAfterSave write FOnAfterSave; property OnAfterDelete: TProc<TUpdateMade, integer> read FOnAfterDeleted write FOnAfterDeleted; property OnUOMPickList: TProc<TEdit> read FOnUOMPickList write FOnUOMPickList; property OnATPickList: TProc<TEdit> read FOnATPickList write FOnATPicklist; function GetCarID: integer; function GetCurrTabItemState: TUserIntentCurrent; function GetRecID: integer; } end; implementation {$R *.fmx} { TTabOfFrame } procedure TTabOfFrame.CloseTab(AIsRelease: Boolean); begin TTabControl(Self.Owner).ActiveTab := FCallerTab; if Assigned(FOnCloseTab) then FOnCloseTab(); end; procedure TfraQMultSele.AnimateTrans(AAnimateRule: TAnimateRule); begin try if AAnimateRule = uBusiObj.TAnimateRule.arInit then begin Layout1.Align := TAlignLayout.None; Layout1.Position.X := Layout1.Width; end else if AAnimateRule = uBusiObj.TAnimateRule.arIn then begin //Layout1.Position.X := Layout1.Width; Layout1.AnimateFloat('Position.X', 0, 0.3, TAnimationType.InOut, TInterpolationType.Linear); end else if AAnimateRule = uBusiObj.TAnimateRule.arOut then begin // Layout1.Position.X := Layout1.Width; Layout1.AnimateFloat('Position.X', Layout1.Width, 0.2, TAnimationType.InOut, TInterpolationType.Linear); end; finally if AAnimateRule = uBusiObj.TAnimateRule.arIn then Layout1.Align := TAlignLayout.Client; end; end; procedure TfraQMultSele.btnCancelClick(Sender: TObject); begin { TThread.CreateAnonymousThread( procedure begin TThread.Synchronize(nil, procedure begin AnimateTrans(TAnimationType.Out); end ); end); } // AnimateTrans(TAnimationType.Out); //Application.ProcessMessages; //sleep(1000); TTabOfFrame(Owner).CloseTab(false); end; procedure TfraQMultSele.btnDoneClick(Sender: TObject); begin // AnimateTrans(TAnimationType.Out); end; procedure TfraQMultSele.Button1Click(Sender: TObject); begin if Assigned(FOnNextBtnClick^) then FOnNextBtnClick^(); end; procedure TfraQMultSele.ListBoxItem1Click(Sender: TObject); begin TListBoxItem(Sender).IsChecked := not TListBoxItem(Sender).IsChecked; { if TListBoxItem(Sender).ItemData.Accessory = TListBoxItemData.TAccessory.aCheckmark then TListBoxItem(Sender).ItemData.Accessory := TListBoxItemData.TAccessory.aNone else TListBoxItem(Sender).ItemData.Accessory := TListBoxItemData.TAccessory.aCheckmark; } end; procedure TfraQMultSele.PopuUI; procedure AddItem(AText: string); var lItem: TListBoxItem; begin lItem := TListBoxItem.Create(nil); lItem.Parent := ListBox1; lItem.Text := AText; lItem.Height := 41; lItem.OnClick := ListBoxItem1Click; lItem.Selectable := false; end; //var // lItem: TListBoxItem; begin ListBox1.BeginUpdate; try ListBox1.Items.clear; AddItem('Sunday'); AddItem('Monday'); AddItem('Tuesday'); AddItem('Wednesday'); AddItem('Thursday'); AddItem('Friday'); AddItem('Saturday'); AddItem('Any day we want'); finally ListBox1.EndUpdate; end; { lItem.Text := 'Sunday'; lItem.Height := 41; lItem.OnClick := ListBoxItem1Click; } // lItem.StyleLookup := 'CustomItem'; { ksVirtualListView1.BeginUpdate; try ksVirtualListView1.Items.Add('Sunday', '', '', atNone); ksVirtualListView1.Items.Add('Monday', '', '', atNone); ksVirtualListView1.Items.Add('Tuesday', '', '', atNone); ksVirtualListView1.Items.Add('Wednesday', '', '', atNone); ksVirtualListView1.Items.Add('Thursday', '', '', atNone); ksVirtualListView1.Items.Add('Friday', '', '', atNone); ksVirtualListView1.Items.Add('Saturday', '', '', atNone); ksVirtualListView1.Items.Add('No fix day', '', '', atNone); finally ksVirtualListView1.EndUpdate; end; } end; constructor TTabOfFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); Name := cTabName; Tag := Integer(cTag); // create main frame FFrameMain := TfraQMultSele.Create(Self); FFrameMain.Parent := Self; // FFrameMain.Layout1.Align := TAlignLayout.None; FFrameMain.Tag := Integer(cTag); //uBusiObj.tnUOMUpd); // define events FFrameMain.FOnNextBtnClick := @OnNextBtnClick; FFrameMain.FOnCloseTab := @OnCloseTab; { //FFrameMain.FOnBackBtnClick := @OnBackBtnClick; //FFrameMain.FOnDoneBtnClick := @OnDoneBtnClick; FFrameMain.FOnAfterDelete := @OnAfterDelete; FFrameMain.FOnUOMPickList := @OnUOMPickList; FFrameMain.FOnATPickList := @OnATPickList; // create header frame FFrameHdr := TfraCarHdr.Create(Self); FFrameHdr.Parent := FFrameMain.Layout1; //FFrameHdr.FOnHdrEditClick := @OnHdrEditClick; FFrameHdr.loEdit.Visible := false; FFrameHdr.lblCarName.Align := TAlignLayout.Contents; FFrameHdr.lblCarName.Margins.Left := 100; FFrameHdr.lblCarName.Margins.Top := 0; } end; destructor TTabOfFrame.Destroy; begin FFrameMain.Free; inherited; end; procedure TTabOfFrame.ShowTab(ACallerTab: TTabItem); // AUserRequest: TUserIntentInit; ATID, ACarID: integer); begin FCallerTab := ACallerTab; { FRecID := ATID; FCarID := ACarID; FTabItemState.UserIntentInit := AUserRequest; FTabItemState.UserIntentCurr := UserIntentInitToCurr(AUserRequest); } FFrameMain.AnimateTrans(TAnimateRule.arInit); TTabControl(Self.Owner).ActiveTab := Self; // if FTabItemState.UserIntentCurr = uicAdding then // FFrameMain.edtDescript.SetFocus; FFrameMain.AnimateTrans(TAnimateRule.arIn); end; end.
unit generic_procs_2; interface implementation function Inc1<T>(Value: T): T; begin Result := Value + 1; end; var G: Float32; I: Int32; procedure Test; begin I := 1; G := Inc1<Float32>(I); end; initialization Test(); finalization Assert(G = 2); end.
unit Getter.DeviceDriver; interface uses Windows, ActiveX, ComObj, Variants, SysUtils, Dialogs, OSFile.ForInternal, CommandSet.Factory, WMI; type TDeviceDriver = record Name: String; Provider: String; Date: String; InfName: String; Version: String; end; TDeviceDriverGetter = class sealed(TOSFileForInternal) public function GetDeviceDriver: TDeviceDriver; private DeviceDriver: TDeviceDriver; function GetStorageDeviceID(WMIObject: IDispatch): String; procedure TryToGetDeviceDriver; function GetSCSIControllerDeviceID(WMIObject: IDispatch; const StorageDeviceID: String): String; function GetDeviceDriverInformation(WMIObject: IDispatch; const ControllerDeviceID: String): TDeviceDriver; function GetIDEControllerDeviceID(WMIObject: IDispatch; const StorageDeviceID: String): String; end; implementation { TDeviceDriverGetter } function TDeviceDriverGetter.GetDeviceDriver: TDeviceDriver; begin FillChar(DeviceDriver, SizeOf(DeviceDriver), 0); try TryToGetDeviceDriver; except FillChar(DeviceDriver, SizeOf(DeviceDriver), 0); end; result := DeviceDriver; end; procedure TDeviceDriverGetter.TryToGetDeviceDriver; var WMIObject: IDispatch; StorageDeviceID: String; ControllerDeviceID: String; begin WMIObject := WMIConnection.GetWMIConnection; StorageDeviceID := GetStorageDeviceID(WMIObject); try ControllerDeviceID := GetSCSIControllerDeviceID(WMIObject, StorageDeviceID); except ControllerDeviceID := GetIDEControllerDeviceID(WMIObject, StorageDeviceID); end; DeviceDriver := GetDeviceDriverInformation(WMIObject, ControllerDeviceID); end; function TDeviceDriverGetter.GetStorageDeviceID(WMIObject: IDispatch): String; const PreQuery = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID='''; PostQuery = '''} WHERE ResultClass=Win32_PnPEntity'; OneDeviceInformationNeeded = 1; var ResultAsOleVariant: OleVariant; EnumVariant: IEnumVARIANT; CurrentDevice: OleVariant; DeviceReturned: Cardinal; begin ResultAsOleVariant := OleVariant(WMIObject).ExecQuery(PreQuery + GetPathOfFileAccessing + PostQuery); EnumVariant := IUnknown(ResultAsOleVariant._NewEnum) as IEnumVARIANT; EnumVariant.Next(OneDeviceInformationNeeded, CurrentDevice, DeviceReturned); result := CurrentDevice.DeviceID; end; function TDeviceDriverGetter.GetSCSIControllerDeviceID(WMIObject: IDispatch; const StorageDeviceID: String): String; const PreQuery = 'ASSOCIATORS OF {Win32_PnPEntity.DeviceID='''; PostQuery = '''} WHERE AssocClass=Win32_SCSIControllerDevice'; OneDeviceInformationNeeded = 1; var ResultAsOleVariant: OleVariant; EnumVariant: IEnumVARIANT; CurrentDevice: OleVariant; DeviceReturned: Cardinal; begin ResultAsOleVariant := OleVariant(WMIObject).ExecQuery(PreQuery + StorageDeviceID + PostQuery); EnumVariant := IUnknown(ResultAsOleVariant._NewEnum) as IEnumVARIANT; EnumVariant.Next(OneDeviceInformationNeeded, CurrentDevice, DeviceReturned); result := CurrentDevice.DeviceID; end; function TDeviceDriverGetter.GetIDEControllerDeviceID(WMIObject: IDispatch; const StorageDeviceID: String): String; const PreQuery = 'ASSOCIATORS OF {Win32_PnPEntity.DeviceID='''; PostQuery = '''} WHERE AssocClass=Win32_IDEControllerDevice'; OneDeviceInformationNeeded = 1; var ResultAsOleVariant: OleVariant; EnumVariant: IEnumVARIANT; CurrentDevice: OleVariant; DeviceReturned: Cardinal; begin ResultAsOleVariant := OleVariant(WMIObject).ExecQuery(PreQuery + StorageDeviceID + PostQuery); EnumVariant := IUnknown(ResultAsOleVariant._NewEnum) as IEnumVARIANT; EnumVariant.Next(OneDeviceInformationNeeded, CurrentDevice, DeviceReturned); result := CurrentDevice.DeviceID; end; function TDeviceDriverGetter.GetDeviceDriverInformation(WMIObject: IDispatch; const ControllerDeviceID: String): TDeviceDriver; const PreQuery = 'SELECT * FROM Win32_PnPSignedDriver WHERE DeviceID='''; PostQuery = ''''; OneDeviceInformationNeeded = 1; var ResultAsOleVariant: OleVariant; EnumVariant: IEnumVARIANT; CurrentDevice: OleVariant; DeviceReturned: Cardinal; Query: String; UnescapedControllerDeviceID: String; begin UnescapedControllerDeviceID := StringReplace(ControllerDeviceID, '\', '\\', [rfReplaceAll]); Query := PreQuery + UnescapedControllerDeviceID + PostQuery; ResultAsOleVariant := OleVariant(WMIObject).ExecQuery(Query); EnumVariant := IUnknown(ResultAsOleVariant._NewEnum) as IEnumVARIANT; EnumVariant.Next(OneDeviceInformationNeeded, CurrentDevice, DeviceReturned); result.Name := CurrentDevice.DeviceName; result.Provider := CurrentDevice.DriverProviderName; result.Date := Copy(CurrentDevice.DriverDate, 1, 8); result.InfName := CurrentDevice.InfName; result.Version := CurrentDevice.DriverVersion; end; end.
Function SDECtoHEX(a:integer):char; Begin case a of 0 : exit('0'); 1 : exit('1'); 2 : exit('2'); 3 : exit('3'); 4 : exit('4'); 5 : exit('5'); 6 : exit('6'); 7 : exit('7'); 8 : exit('8'); 9 : exit('9'); 10 : exit('A'); 11 : exit('B'); 12 : exit('C'); 13 : exit('D'); 14 : exit('E'); 15 : exit('F'); end; End; Function SHEXtoDec(a:char):integer; Begin case upcase(a) of '0' : exit(0); '1' : exit(1); '2' : exit(2); '3' : exit(3); '4' : exit(4); '5' : exit(5); '6' : exit(6); '7' : exit(7); '8' : exit(8); '9' : exit(9); 'A' : exit(10); 'B' : exit(11); 'C' : exit(12); 'D' : exit(13); 'E' : exit(14); 'F' : exit(15); end; End; { 十进制转二进制 } Function Hex_Conversion_10to2(s:longint):string; Begin Hex_Conversion_10to2:=''; while s>0 do begin Hex_Conversion_10to2:=numtochar(s mod 2)+ Hex_Conversion_10to2; s:=s div 2; end; while length(Hex_Conversion_10to2)<8 do Hex_Conversion_10to2:='0'+Hex_Conversion_10to2; End; { 二进制转十进制 } Function Hex_Conversion_2to10(s:string):longint; Var i:longint; Begin Hex_Conversion_2to10:=0; for i:=length(s) downto 1 do begin if s[i]='1' then Hex_Conversion_2to10:=Hex_Conversion_2to10+ 2 ** (length(s)-i) end; End; Function Base64_Encryption(s:ansistring):ansistring; Var st:ansistring; i :longint; TheBase64Alphabet : string; Begin TheBase64Alphabet:='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; Base64_Encryption:=''; st:=''; for i:=1 to length(s) do begin st:=st+Hex_Conversion_10to2( integer(s[i]) ); while length(st)>=6 do begin Base64_Encryption:=Base64_Encryption + TheBase64Alphabet[ Hex_Conversion_2to10('00'+copy(st,1,6)) +1]; delete(st,1,6); end; end; if length(st)=2 then begin Base64_Encryption:=Base64_Encryption + TheBase64Alphabet[ Hex_Conversion_2to10('00'+st+'0000') +1]+'=='; end; if length(st)=4 then begin Base64_Encryption:=Base64_Encryption + TheBase64Alphabet[ Hex_Conversion_2to10('00'+st+'00') +1]+'='; end; End; Function Base64_Decryption(s:ansistring):ansistring; Var st:ansistring; len:longint; i :longint; TheBase64Alphabet : string; Begin TheBase64Alphabet:='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; Base64_Decryption:=''; st:=''; len:=length(s); i:=1; while i<=len do begin if s[i]<>'=' then begin st:=st+copy( Hex_Conversion_10to2( pos(s[i],TheBase64Alphabet)-1 ),3,8); while length(st)>=8 do begin Base64_Decryption:=Base64_Decryption+ char(Hex_Conversion_2to10( copy(st,1,8))); delete(st,1,8); end; end else begin if i=len then begin Base64_Decryption:=Base64_Decryption+ char(Hex_Conversion_2to10( copy(st,1,6))); end; if i=len-1 then begin Base64_Decryption:=Base64_Decryption+ char(Hex_Conversion_2to10( copy(st,1,4))); i:=i+1; end; if i<len-1 then begin exit('FALSE'); end; end; inc(i); end; End; { 反转字符串 } Function CoolQ_Tools_Flip(s:ansistring):ansistring; Var i:longint; Begin CoolQ_Tools_Flip:=''; for i:=length(s) downto 1 do CoolQ_Tools_Flip:=CoolQ_Tools_Flip+s[i]; End; Function BinToNum(bin:ansistring):int64; Var i:longint; Begin BinToNum:=0; bin:=CoolQ_Tools_Flip(bin); for i:=1 to length(bin) do begin BinToNum:=BinToNum+256**(i-1)*integer(bin[i]); end; End; Function NumToBin(num:int64;len:longint):ansistring; Begin NumToBin:=''; while num>0 do begin NumToBin:=NumToChar(num mod 256)+NumToBin; num:=num div 256; end; while length(NumToBin)<len*3 do NumToBin:='00 '+NumToBin; End; Function BinToHex(bin:ansistring):ansistring; Var i:longint; Begin BinToHex:=''; for i:=1 to length(bin) do begin BinToHex:=BinToHex+SDECtoHEX(integer(bin[i])div 16)+SDECtoHEX(integer(bin[i])mod 16)+' '; end; End; { 下面是神奇的东西 } Function CoolQ_Tools_GetBin(Var i:longint; len:longint; s:ansistring):ansistring; Begin if len<=0 then exit(''); CoolQ_Tools_GetBin:=copy(s,i,len); i:=i+len; End; Function CoolQ_Tools_GetNum(Var i:longint; len:longint; s:ansistring):int64; Begin CoolQ_Tools_GetNum:=BinToNum(copy(S,i,len)); i:=i+len; End; Function CoolQ_Tools_GetStr(Var i:longint; s:ansistring):ansistring; Var len:longint; Begin len:=CoolQ_Tools_GetNum(i,2,s); exit(CoolQ_Tools_GetBin(i,len,s)); End;
unit uMontaSql; interface uses uDbObject, Data.DB, System.SysUtils, uConexao, Classes; // MySql const cDateFormatMySql = 'yyyy/MM/dd'; const cDateTimeFormatMySql = cDateFormatMySql + ' hh:mm:ss'; // SQLServer const cDateFormatSqlServer = 'yyyyMMdd'; const cDateTimeFormatSqlServer = cDateFormatMySql + ' hhmmss'; // Firebird const cDateFormatFirebird = 'ddMMyyyy'; const cDateTimeFormatFirebird = cDateFormatFirebird + ' hhmmss'; // Oracle const cDateFormatOracle = 'dd/MM/yyyy'; const cDateTimeFormatOracle = cDateFormatOracle + ' hh:mm:ss'; type TMontaSQL = class private {MySql} class function getSqlAllTablesMySql (ADataBase: string): string; class function getSqlAllColumnsMySql(ADataBase, ATable: string): string; {SQL Server} class function getSqlAllTablesSqlServer: string; class function getSqlAllColumnsSqlServer(ATable: string): string; public class function getSqlAllTables: String; class function getSqlAllColums(ATable: string): string; class function SqlInsert(TableName : string; CampoValores : array of Variant; CampoNome : Array Of String; CampoNullIfZero : array of boolean; aSaveDateTimeFormat : array of Boolean; aIncludeOnInsert : array of Boolean; aFloatPrecision : array of Integer; aDbObject : TDbObject ): String; class function SqlUpdate(TableName : string; Where : string; CampoValores : array of Variant; CampoNome : Array Of String; CampoNullIfZero : array of boolean; aSaveDateTimeFormat : array of Boolean; aFloatPrecision : array of Integer; aDbObject : TDbObject ): string; class function FormatDateSql (AData: TDateTime; ASaveDateTimeFormat: Boolean; ANullIfZero: Boolean): string; class function getValorSql (AField: TDbField; ASaveDateTimeFormat: Boolean; ANullIfZero: Boolean): string; end; implementation { TMontaSQL } class function TMontaSQL.FormatDateSql(AData: TDateTime; ASaveDateTimeFormat: Boolean; ANullIfZero: Boolean): string; begin if (AData = 0) and (ANullIfZero) then result := 'NULL' else begin case conexao.tipoConexao of tcMySql: begin if ASaveDateTimeFormat then result := FormatDateTime(cDateTimeFormatMySql, AData) else result := FormatDateTime(cDateFormatMySql, AData); end; tcSqlServer: begin if ASaveDateTimeFormat then result := FormatDateTime(cDateTimeFormatSqlServer, AData) else result := FormatDateTime(cDateFormatSqlServer, AData); end; tcFirebird: begin if ASaveDateTimeFormat then result := FormatDateTime(cDateTimeFormatFirebird, AData) else result := FormatDateTime(cDateFormatFirebird, AData); end; tcOracle: begin if ASaveDateTimeFormat then result := FormatDateTime(cDateTimeFormatOracle, AData) else Result := FormatDateTime(cDateFormatOracle, AData); end; end; result := QuotedStr(Result); end; end; class function TMontaSQL.getSqlAllColumnsMySql(ADataBase, ATable: string): string; begin with TStringList.Create do begin Add('SELECT '); Add(' COLUMN_NAME, '); Add(' DATA_TYPE, '); Add(' COLUMN_KEY, '); Add(' '); Add(' CASE IS_NULLABLE WHEN ''NO'' THEN 0 ELSE 1 END AS NULLABLE, '); Add(' CASE COLUMN_KEY WHEN ''PRI'' THEN 1 ELSE 0 END AS PRIMARYKEY,'); Add(' 1 AS NULLIFZERO, '); Add(' 0 AS READONLY '); Add('FROM '); Add(' INFORMATION_SCHEMA.COLUMNS '); Add('WHERE '); Add(' TABLE_SCHEMA = ' + QuotedStr(ADataBase) ); Add('AND TABLE_NAME = ' + QuotedStr(ATable) ); Add(' '); Add('ORDER BY '); Add(' ORDINAL_POSITION '); Result := Text; Free; end; end; class function TMontaSQL.getSqlAllColumnsSqlServer(ATable: string): string; begin with TStringList.Create do begin Add('SELECT '); Add(' COLUMN_NAME, '); Add(' DATA_TYPE, '); // Add(' COLUMN_KEY, '); Add(' '); Add(' CASE IS_NULLABLE WHEN ''NO'' THEN 0 ELSE 1 END AS NULLABLE, '); Add(' 0 AS PRIMARYKEY, '); Add(' 1 AS NULLIFZERO, '); Add(' 0 AS READONLY '); Add('FROM '); Add(' INFORMATION_SCHEMA.COLUMNS '); Add(' '); Add('WHERE '); Add(' TABLE_NAME = ' + QuotedStr(ATable)); Add(' '); Add('ORDER BY '); Add(' COLUMN_NAME '); Result := Text; SaveToFile('sqlserver.sql'); Free; end; end; class function TMontaSQL.getSqlAllColums(ATable: string): string; var dataBase: string; begin dataBase := conexao.alias; case conexao.tipoConexao of tcMySql : Result := getSqlAllColumnsMySql(dataBase, ATable); tcSqlServer : Result := getSqlAllColumnsSqlServer(ATable); end; end; class function TMontaSQL.getSqlAllTables: String; var dataBase: string; begin dataBase := conexao.alias; case conexao.tipoConexao of tcMySql : result := getSqlAllTablesMySql(dataBase); tcSqlServer : result := getSqlAllTablesSqlServer; end; end; class function TMontaSQL.getSqlAllTablesMySql(ADataBase: string): string; begin with TStringList.Create do begin Add('SELECT '); Add(' TABLE_NAME '); Add('FROM '); Add(' INFORMATION_SCHEMA.TABLES '); Add('WHERE '); Add(' TABLE_SCHEMA = ' + QuotedStr(ADataBase) ); Add('ORDER BY '); Add(' TABLE_NAME '); result := Text; Free; end; end; class function TMontaSQL.getSqlAllTablesSqlServer: string; begin with TStringList.Create do begin Add('SELECT '); Add(' NAME AS TABLE_NAME '); Add('FROM '); Add(' SYS.TABLES '); Add('ORDER BY '); Add(' NAME '); result := Text; Free; end; end; class function TMontaSQL.getValorSql(AField: TDbField; ASaveDateTimeFormat, ANullIfZero: Boolean): string; begin case AField.DataType of ftString : begin result := AField.AsString; if (Trim(result) = '') and (ANullIfZero) then result := 'NULL' else result := QuotedStr(result); end; ftSmallint, ftInteger, ftWord : begin result := IntToStr ( AField.AsInteger ); if (result = '0') and (ANullIfZero) then result := 'NULL' end; ftFloat, ftCurrency, ftBCD: begin result := FloatToStr(AField.AsFloat); if (result = '0') and (ANullIfZero) then result := 'NULL'; result := StringReplace(result, ',', '.', [rfReplaceAll]); end; ftDate, ftDateTime: begin result := FormatDateSql(AField.AsDateTime, ASaveDateTimeFormat, ANullIfZero); end; end; end; class function TMontaSQL.SqlInsert(TableName : string; CampoValores : array of Variant; CampoNome : array of String; CampoNullIfZero : array of Boolean; aSaveDateTimeFormat : array of Boolean; aIncludeOnInsert : array of Boolean; aFloatPrecision : array of Integer; aDbObject : TDbObject ): String; var sql: string; i : Integer; nome : string; valor : Variant; nullIfZero : Boolean; saveDateTime : Boolean; floatPrecision : Integer; valorSql : string; begin sql := 'INSERT INTO ' + TableName + ' ('; ////////////////////////////////////////////////////////////////////////////// /// Campos ////////////////////////////////////////////////////////////////////////////// for I := Low(CampoNome) to High(CampoNome) do begin nome := CampoNome[i]; if i = 0 then sql := sql + nome else sql := sql + ', ' + nome; end; ////////////////////////////////////////////////////////////////////////////// /// Valores ////////////////////////////////////////////////////////////////////////////// sql := sql + ') VALUES ('; for i := Low(CampoNome) to High(CampoNome) do begin nome := CampoNome[i]; valor := CampoValores[0][i]; nullIfZero := CampoNullIfZero[i]; saveDateTime := aSaveDateTimeFormat[i]; floatPrecision := aFloatPrecision[i]; valorSql := getValorSql(aDbObject.FieldByName(nome), saveDateTime, nullIfZero); if i = 0 then sql := sql + valorSql else sql := sql + ', ' + valorSql; end; sql := sql + ')'; result := sql; end; class function TMontaSQL.SqlUpdate(TableName : string; Where : string; CampoValores : array of Variant; CampoNome : Array Of String; CampoNullIfZero : array of boolean; aSaveDateTimeFormat : array of Boolean; aFloatPrecision : array of Integer; aDbObject : TDbObject ): string; var sql: string; i : Integer; nome : string; valor : Variant; nullIfZero : Boolean; saveDateTime : Boolean; floatPrecision : Integer; valorSql : string; bPassou : Boolean; begin bPassou := False; sql := 'UPDATE ' + TableName + ' SET '; ////////////////////////////////////////////////////////////////////////////// /// Campos ////////////////////////////////////////////////////////////////////////////// for I := Low(CampoNome) to High(CampoNome) do begin nome := CampoNome[i]; nullIfZero := CampoNullIfZero[i]; saveDateTime := aSaveDateTimeFormat[i]; if Trim(nome) <> '' then begin if not bPassou then begin sql := sql + nome + ' = ' + getValorSql(aDbObject.FieldByName(nome), saveDateTime, nullIfZero); bPassou := True; end else sql := sql + ', ' + nome + ' = ' + getValorSql(aDbObject.FieldByName(nome), saveDateTime, nullIfZero); end; end; if Trim(where) <> '' then sql := sql + ' WHERE ' + Where; result := sql; end; end.
unit uChoices; interface uses System.Generics.Collections, Vcl.CheckLst; procedure CreateSalesforceFileAssociation(); procedure CreateSalesforceFileEditAssociation(); function CancelSalesforceFileAssociation():String; var CorruptedData: Boolean = false; type TChoice = class description: String; kind: String; options: String; end; TSingleChoice = class (TChoice) correctAnswer: Byte; constructor Create( desc: String; answer: Byte; king: String; opts: String = '' ); end; TMultipleChoice = class (TChoice) correctAnswer: TList<Integer>; constructor Create( desc: String; answer: TList<Integer>; opts: String ); end; TChoicesUtil = class class function LoadFromFile(const FileName: String): TList<TChoice>; class function LoadFileEdit(const FileName: String): TList<TChoice>; class procedure SaveFile(choices: TList<TChoice>; const FileName: String); class function AddMultiChoice(choices: TList<TChoice>; d: String; a: TList<Integer>; o: String): Integer; class function AddSingleChoice(choices: TList<TChoice>; d: String; a: Byte; k: String; o: String = ''): Integer; class procedure ConvertIntegerListToCheckBoxList(il: TList<Integer>; c: TCheckListBox); class procedure CopyCheckboxList(source, dest: TCheckListBox); class function TryImportFromFile(const FileName: String): TList<TChoice>; class function TryImportFromHTMLFile(const FileName: String): TList<TChoice>; class function ConcatLists(choices: TList<TChoice>; choices2: TList<TChoice>): TList<TChoice>; end; implementation uses SysUtils, Classes, Windows, Registry; procedure CreateFileAssociation(Ext,ExtType,ExtDescript,FileIcon,FileOpen:string); var reg:TRegistry; begin reg := TRegistry.Create; reg.RootKey := HKEY_CLASSES_ROOT; reg.OpenKey(Ext,true); reg.WriteString('',ExtType); reg.CloseKey; reg.OpenKey(ExtType,true); reg.WriteString('',ExtDescript); reg.CloseKey; reg.OpenKey(ExtType+'\DefaultIcon',true); reg.WriteString('',FileIcon); reg.CloseKey; reg.OpenKey(ExtType+'\shell\open\command',true); reg.WriteString('',FileOpen); reg.CloseKey; reg.OpenKey(ExtType+'\shell\open in original order\command',true); reg.WriteString('',FileOpen + ' o'); reg.CloseKey; reg.Free end; procedure CreateFileEditAssociation(Ext,ExtType,ExtDescript,FileEdit:string); var reg:TRegistry; begin reg := TRegistry.Create; reg.RootKey := HKEY_CLASSES_ROOT; reg.OpenKey(Ext,true); reg.WriteString('',ExtType); reg.CloseKey; reg.OpenKey(ExtType,true); reg.WriteString('',ExtDescript); reg.CloseKey; reg.OpenKey(ExtType+'\shell\edit\command',true); reg.WriteString('',FileEdit); reg.CloseKey; reg.Free end; function boolToBin(b: Boolean):Char; begin if b then Result := '1' else Result := '0'; end; function CancelFileAssociation(Ext,ExtType,PathToProgram:string):String; var reg:TRegistry; extKeyExists,extTypeKeyExists,programValueExists, extKeyRemoved,extTypeKeyRemoved,programValueRemoved: Boolean; begin reg := TRegistry.Create; try reg.RootKey := HKEY_CLASSES_ROOT; extKeyExists := reg.KeyExists(Ext); extTypeKeyExists := reg.KeyExists(ExtType); extKeyRemoved := reg.DeleteKey(Ext); extTypeKeyRemoved := reg.DeleteKey(ExtType); reg.RootKey := HKEY_CURRENT_USER; reg.OpenKey('Software\Microsoft\Windows\ShellNoRoam\MUICache',false); programValueExists := reg.ValueExists(PathToProgram); programValueRemoved := reg.DeleteValue(PathToProgram); Result := boolToBin(extKeyExists)+boolToBin(extTypeKeyExists)+boolToBin(programValueExists) + boolToBin(extKeyRemoved)+boolToBin(extTypeKeyRemoved)+boolToBin(programValueRemoved); finally reg.Free end end; const SFExt = '.sf'; SF501Ext = '.501'; SFExtType = 'Salesforce Questionary'; SFExtDesc = 'File containing questions and answers to prepare for Salesforce Certification'; procedure CreateSalesforceFileAssociation(); begin //CreateFileAssociation( SFExt, SFExtType, SFExtDesc, ParamStr(0)+',1',ParamStr(0)+' "%1"' ); CreateFileAssociation( SFExt, SFExtType, SFExtDesc, ParamStr(0)+',0',ParamStr(0)+' "%1"' ); CreateFileAssociation( SF501Ext, SFExtType, SFExtDesc, ParamStr(0)+',0',ParamStr(0)+' "%1"' ); end; procedure CreateSalesforceFileEditAssociation(); begin CreateFileEditAssociation( SFExt, SFExtType, SFExtDesc, ParamStr(0)+' "%1"' ); CreateFileEditAssociation( SF501Ext, SFExtType, SFExtDesc, ParamStr(0)+' "%1"' ); end; function CancelSalesforceFileAssociation():String; begin Result := CancelFileAssociation( SFExt, SFExtType, ParamStr(0) ); Result := CancelFileAssociation( SF501Ext, SFExtType, ParamStr(0) ); end; { TSingleChoice } constructor TSingleChoice.Create(desc: String; answer: Byte; king: String; opts: String = ''); begin description := desc; correctAnswer := answer; kind := king; options := opts; end; { TMultipleChoice } constructor TMultipleChoice.Create(desc: String; answer: TList<Integer>; opts: String); begin description := desc; correctAnswer := answer; if answer = Nil then correctAnswer := TList<Integer>.Create(); kind := 'm'; options := opts; end; { TChoicesUtil } class function TChoicesUtil.AddMultiChoice(choices: TList<TChoice>; d: String; a: TList<Integer>; o: String): Integer; var c: TChoice; begin c := TMultipleChoice.Create( d, a, o); Result := choices.Add(c); end; class function TChoicesUtil.AddSingleChoice(choices: TList<TChoice>; d: String; a: Byte; k: String; o: String = ''): Integer; var c: TChoice; begin c := TSingleChoice.Create( d, a, k, o); Result := choices.Add(c); end; class function TChoicesUtil.ConcatLists(choices, choices2: TList<TChoice>): TList<TChoice>; var i: Integer; begin for i := 0 to choices2.Count - 1 do begin choices.Add( choices2[i] ); end; Result := choices; end; class procedure TChoicesUtil.ConvertIntegerListToCheckBoxList( il: TList<Integer>; c: TCheckListBox); var i: Integer; begin for i := 0 to c.Items.Count - 1 do begin c.Checked[i] := False; end; for i := 0 to il.Count - 1 do begin if (il[i] >=0) and (il[i] < c.Items.Count) then c.Checked[il[i]] := True else CorruptedData := True; end; end; class procedure TChoicesUtil.CopyCheckboxList(source, dest: TCheckListBox); var i: Integer; begin for i := 0 to Source.Items.Count - 1 do begin dest.Checked[i] := Source.Checked[i]; end; end; class function TChoicesUtil.LoadFromFile(const FileName: String): TList<TChoice>; var i, j, l, m, n: Integer; kind, d, desc, opts: String; il: TList<Integer>; f:TextFile; ext:string; begin ext := '.sf'; Result := TList<TChoice>.Create(); if fileexists(FileName) then begin assignfile(f,FileName); ext := LowerCase(ExtractFileExt(FileName)); reset(f); try readln(f, l); for i := 0 to l - 1 do begin readln(f, kind); readln(f, m); desc := ''; for j := 0 to m - 1 do begin readln(f, d); desc := desc + d + #13#10; end; opts := ''; if kind <> 'b' then begin readln(f, m); for j := 0 to m - 1 do begin readln(f, d); opts := opts + d + #13#10; end; end; if kind = 'm' then addMultiChoice(Result, desc, nil, opts) else addSingleChoice(Result, desc, 0, kind, opts); end; for i := 0 to l - 1 do begin if Result[i].kind = 'm' then begin il := TList<Integer>.Create(); readln(f, m); for j := 0 to m - 1 do begin read(f, n); il.add(n); end; readln(f); TMultipleChoice(Result[i]).correctAnswer := il; end else begin readln(f, n); TSingleChoice(Result[i]).correctAnswer := n; end; end; finally closeFile(f); end; end; end; class function TChoicesUtil.LoadFileEdit(const FileName: String): TList<TChoice>; var i, j, l, m, n: Integer; kind, d, desc, opts: String; il: TList<Integer>; f:TextFile; ext:string; success: Boolean; s: String; begin ext := '.sf'; Result := TList<TChoice>.Create(); if fileexists(FileName) then begin assignfile(f,FileName); ext := LowerCase(ExtractFileExt(FileName)); reset(f); try readln(f, l); for i := 0 to l - 1 do begin readln(f, kind); readln(f, m); desc := ''; for j := 0 to m - 1 do begin readln(f, d); desc := desc + d + #13#10; end; opts := ''; if kind <> 'b' then begin readln(f, m); for j := 0 to m - 1 do begin readln(f, d); opts := opts + d + #13#10; end; end; if kind = 'm' then addMultiChoice(Result, desc, nil, opts) else addSingleChoice(Result, desc, 0, kind, opts); end; for i := 0 to l - 1 do begin if Result[i].kind = 'm' then begin il := TList<Integer>.Create(); success := False; m := 0; repeat readln(f, s); try m := StrToInt( s ); success := True; except on E: Exception do if (Pos('is not a valid integer value', E.Message) > 0) and (s.Length > 0) then begin kind := s[1]; readln(f, m); desc := ''; for j := 0 to m - 1 do begin readln(f, d); desc := desc + d + #13#10; end; opts := ''; if kind <> 'b' then begin readln(f, m); for j := 0 to m - 1 do begin readln(f, d); opts := opts + d + #13#10; end; end; if kind = 'm' then addMultiChoice(Result, desc, nil, opts) else addSingleChoice(Result, desc, 0, kind, opts); ///readln(f, m); end else success := True; end; until (success); if m > 0 then begin for j := 0 to m - 1 do begin read(f, n); il.add(n); end; readln(f); end; TMultipleChoice(Result[i]).correctAnswer := il; end else begin readln(f, n); TSingleChoice(Result[i]).correctAnswer := n; end; end; finally closeFile(f); end; end; end; class procedure TChoicesUtil.SaveFile(choices: TList<TChoice>; const FileName: String); var i,j:Integer; fn:string; sl: TStringList; il: TList<Integer>; f:TextFile; ext:string; begin ext := '.sf'; fn := ChangeFileExt(FileName, ext); AssignFile(f, fn); rewrite(f); try writeln(f, choices.Count); sl := TStringList.Create; //il := TList<Integer>.Create; for i := 0 to choices.Count - 1 do begin writeln(f, choices[i].kind); sl.Text := choices[i].description; writeln(f, sl.Count); write(f, sl.Text); if choices[i].kind <> 'b' then begin sl.Text := choices[i].options; writeln(f, sl.Count); write(f, sl.Text); end; end; for i := 0 to choices.Count - 1 do begin if choices[i].kind = 'm' then begin il := TMultipleChoice(choices[i]).correctAnswer; writeln(f, il.Count); if il.Count > 0 then begin for j := 0 to il.Count - 1 do write(f, il[j], ' '); writeln(f); end; end else begin writeln(f, TSingleChoice(choices[i]).correctAnswer); end; end; finally closeFile(f); end; //caption:=fn end; function AnswerLikeString(d: String): Boolean; begin Result := (d = 'Ans.') or (d = 'Ans ') or (d = 'Ans,') or (d = 'Ans:'); end; function isBold(html: String): Boolean; //function isBold(html, s: String): Boolean; {var i, j: Integer; } begin {i := Pos('<b', html); j := Pos(s, html); ShowMessage(s); ShowMessage(html); ShowMessage(IntToStr(i)); ShowMessage(IntToStr(j));} Result := ( Pos('<b', html) > 0 );// and ( Pos('<b', html) < Pos(s, html) ); end; class function TChoicesUtil.TryImportFromFile(const FileName: String): TList<TChoice>; var j: Integer; s, kind, d, e, desc, opts, lowd: String; il: TList<Integer>; alpha, bool, squareBracket: Boolean; aChar: Char; f:TextFile; sl: TStringList; begin Result := TList<TChoice>.Create(); if fileexists(FileName) then begin assignfile(f,FileName); reset(f); try if eof(f) then raise Exception.Create('Empty File!'); readln(f, s); repeat desc := ''; if (pos('[', s) > 0) or (pos('(', s) = 1) then if (pos('[', s) > 0) and (pos('(', s) > 0) then squareBracket := (pos('[', s) < pos('(', s)) else squareBracket := (pos('[', s) > 0); if squareBracket then j := pos(']', s) else j := pos(')', s); if s[j + 1] = ' ' then desc := desc + Copy(s, j + 2, Length(s) - j) else desc := desc + Copy(s, j + 1, Length(s) - j); repeat if eof(f) then raise Exception.Create('Incomplete of broken File!'); readln(f, s); d := Copy(s, 1, 4); e := Copy(s, 1, 2); if not AnswerLikeString(d) and (e <> 'A.') and (e <> '1.') then desc := desc + ' ' + s + #13#10; until (e = 'A.') or ( e = '1.') or AnswerLikeString(d) or eof(f); bool := AnswerLikeString(d); alpha := s[1] = 'A'; if alpha then aChar := 'A' else aChar := '1'; opts := ''; opts := opts + s;// + #13#10; if not bool then repeat if eof(f) then raise Exception.Create('Incomplete of broken File!'); readln(f, s); d := Copy(s, 1, 3); if d <> 'Ans' then if (Ord(d[1]) - Ord(aChar) >= 0) and (Ord(d[1]) - Ord(aChar) < 27) and (d[2] = '.') then opts := opts + #13#10 + s else opts := opts + ' ' + s;// + #13#10; until (d = 'Ans') or eof(f); if (Pos('Ans: ', s) > 0) or (Pos('Ans; ', s) > 0) then d := Copy(s, 6, Length(s) - 5) else d := Copy(s, 5, Length(s) - 4); if bool then kind := 'b' else if Length(d) = 1 then kind := 's' else kind := 'm'; if kind = 'm' then begin il := TList<Integer>.Create(); lowd := LowerCase(d); if ( Pos('above all', lowd) > 0 ) or (Pos('all above', lowd) > 0 ) then begin sl := TStringList.Create(); sl.Text := opts; for j := 1 to sl.Count do begin il.add( j - 1); end end else for j := 1 to Length(d) do begin il.add( Ord(d[j]) - Ord(aChar)); end; addMultiChoice(Result, desc, il, opts) end else if kind = 's' then begin addSingleChoice(Result, desc, Ord(d[1]) - Ord(aChar), kind, opts); end else begin if LowerCase(d) = 'true' then j := 0 else j := 1; addSingleChoice(Result, desc, j, kind, opts); end; if not eof(f) then repeat if eof(f) then raise Exception.Create('Incomplete of broken File!'); readln(f, s); until (Trim(s) <> '') or eof(f); until eof(f); (*except on e:Exception do ; end;*) finally closeFile(f); end; end; // Application.Title:=fn; // caption:=fn; end; function StripHTML(S: string): string; var TagBegin, TagEnd, TagLength: integer; begin S := StringReplace(S, '&nbsp;', '', [rfReplaceAll]); TagBegin := Pos( '<', S); // search position of first < while (TagBegin > 0) do begin // while there is a < in S TagEnd := Pos('>', S); // find the matching > TagLength := TagEnd - TagBegin + 1; Delete(S, TagBegin, TagLength); // delete the tag TagBegin:= Pos( '<', S); // search for next < end; Result := S; // give the result end; function charSeparation(s:String; c:Char): Boolean; var v: Integer; begin Result := (Pos(c, s) > 0)and (Pos(c, s) < 5) and TryStrToInt( Copy(s, 1, Pos(c, s) - 1), v); end; function closingParenthisSeparation(s:String): Boolean; begin Result := charSeparation(s, ')'); end; function soundsLikeDotSeparation(s:String): Boolean; begin Result := charSeparation(s, '.'); end; function soundsLikeColonSeparation(s:String): Boolean; begin Result := charSeparation(s, ':'); end; function startLike(s:String): Boolean; var v: Integer; begin Result := (Copy(s, 1, 2) = 'Q.') or {((Pos(')', s) > 0)and (Pos(')', s) < 5) and TryStrToInt( Copy(s, 1, Pos(')', s) - 1), v)) or ((Pos('.', s) > 0)and (Pos('.', s) < 5) and TryStrToInt( Copy(s, 1, Pos('.', s) - 1), v)); //} closingParenthisSeparation(s) or soundsLikeDotSeparation(s) or soundsLikeColonSeparation(s) end; function firstAnswerLike(s:String): Boolean; begin if Length(s) < 2 then Result := False else Result := (s[1] = '*') or (( s[1] in ['a','A','1']) and (s[2] in ['.',')','-',':'])); end; class function TChoicesUtil.TryImportFromHTMLFile(const FileName: String): TList<TChoice>; var j, c: Integer; s, html, kind, d, e, desc, opts: String; il: TList<Integer>; alpha, bool, squareBracket, dotSeparation, colonSeparation, asterisk: Boolean; aChar, delimiter: Char; f:TextFile; sl: TStringList; begin Result := TList<TChoice>.Create(); if fileexists(FileName) then begin assignfile(f,FileName); reset(f); try if eof(f) then raise Exception.Create('Empty File!'); readln(f, s); repeat desc := ''; s := StripHTML(s); if (pos('[', s) > 0) or (pos('(', s) = 1) then if (pos('[', s) > 0) and (pos('(', s) > 0) then squareBracket := (pos('[', s) < pos('(', s)) else squareBracket := (pos('[', s) > 0) else dotSeparation := soundsLikeDotSeparation(s); if dotSeparation then j := pos('.', s) else begin colonSeparation := soundsLikeColonSeparation(s); if not dotSeparation and colonSeparation then j := pos(':', s) else if squareBracket then j := pos(']', s) else j := pos(')', s); end; if s[j + 1] = ' ' then desc := desc + Copy(s, j + 2, Length(s) - j) else desc := desc + Copy(s, j + 1, Length(s) - j); il := TList<Integer>.Create(); c := 0; repeat if eof(f) then raise Exception.Create('Incomplete of broken File!'); readln(f, s); if (Trim(StripHTML(s)) = '') then begin desc := desc + ' ' + #13#10; continue; end; {if not eof(f) and (Trim(StripHTML(s)) = '') then repeat if eof(f) then raise Exception.Create('Incomplete of broken File!'); readln(f, s); until AnswerLikeString(StripHTML(s)) or firstAnswerLike(StripHTML(s)) or eof(f); } html := s; s := StripHTML(s); d := Copy(s, 1, 4); e := Copy(s, 1, 2); if not AnswerLikeString(d) and not firstAnswerLike(s) then desc := desc + ' ' + s;// + #13#10; until firstAnswerLike(s) or AnswerLikeString(d) or eof(f); //if isBold(html, Copy(StripHTML(s), 1, 2) ) then bool := AnswerLikeString(d); asterisk := s[1] = '*'; //alpha := UpperCase(s[1]) = 'A'; aChar := s[1]; delimiter := s[2]; opts := ''; opts := opts + s;// + #13#10; if not bool then begin readln(f, s); if not eof(f) and (Trim(StripHTML(s)) = '') then repeat if eof(f) then raise Exception.Create('Incomplete of broken File!'); readln(f, s); until (StripHTML(s)[2] = delimiter ) or eof(f); repeat if isBold(html ) then il.add(c); Inc(c); html := s; s := StripHTML(s); {//if isBold(html, Copy(StripHTML(s), 1, 2)) then if isBold(html ) then il.add(c); } d := Copy(s, 1, 3); if asterisk then opts := opts + #13#10 + s else if not asterisk and (d <> 'Ans') then if (Ord(d[1]) - Ord(aChar) >= 0) and (Ord(d[1]) - Ord(aChar) < 10) and (d[2] = delimiter ) then opts := opts + #13#10 + s else opts := opts + ' ' + s;// + #13#10; readln(f, s); until (Trim(StripHTML(s)) = '') or startLike(StripHTML(s)) or (d = 'Ans') or eof(f); end; if Pos('<b', html) > 0 then il.add(c); if bool then kind := 'b'; if AnswerLikeString(d) then begin if (Pos('Ans: ', s) > 0) or (Pos('Ans; ', s) > 0) then d := Copy(s, 6, Length(s) - 5) else d := Copy(s, 5, Length(s) - 4); if Length(d) = 1 then kind := 's' else kind := 'm'; if kind = 'm' then begin if LowerCase(d) = 'above all' then begin sl := TStringList.Create(); sl.Text := opts; for j := 1 to sl.Count do begin il.add( j - 1); end end else for j := 1 to Length(d) do begin il.add( Ord(d[j]) - Ord(aChar)); end; addMultiChoice(Result, desc, il, opts) end else if kind = 's' then begin addSingleChoice(Result, desc, Ord(d[1]) - Ord(aChar), kind, opts); end else begin if LowerCase(d) = 'true' then j := 0 else j := 1; addSingleChoice(Result, desc, j, kind, opts); end; end else begin if il.Count = 1 then kind := 's' else kind := 'm'; if kind = 'm' then addMultiChoice(Result, desc, il, opts) else addSingleChoice(Result, desc, il[0], kind, opts); end; if not eof(f) and (Trim(StripHTML(s)) = '') then repeat if eof(f) then raise Exception.Create('Incomplete of broken File!'); readln(f, s); s := StripHTML(s); until startLike(s) or eof(f); until eof(f); (*except on e:Exception do ; end;*) finally closeFile(f); end; end; // Application.Title:=fn; // caption:=fn; end; end.
unit BCEditor.Editor.SpecialChars.EndOfLine; interface uses Classes, Graphics, BCEditor.Types; type TBCEditorSpecialCharsEndOfLine = class(TPersistent) strict private FColor: TColor; FOnChange: TNotifyEvent; FStyle: TBCEditorSpecialCharsEndOfLineStyle; FVisible: Boolean; procedure DoChange; procedure SetColor(const Value: TColor); procedure SetStyle(const Value: TBCEditorSpecialCharsEndOfLineStyle); procedure SetVisible(const Value: Boolean); public constructor Create; procedure Assign(Source: TPersistent); override; published property Color: TColor read FColor write SetColor default clBlack; property OnChange: TNotifyEvent read FOnChange write FOnChange; property Style: TBCEditorSpecialCharsEndOfLineStyle read FStyle write SetStyle default eolArrow; property Visible: Boolean read FVisible write SetVisible default False; end; implementation { TBCEditorSpecialCharsEndOfLine } constructor TBCEditorSpecialCharsEndOfLine.Create; begin inherited; FColor := clBlack; FStyle := eolArrow; FVisible := False; end; procedure TBCEditorSpecialCharsEndOfLine.Assign(Source: TPersistent); begin if Assigned(Source) and (Source is TBCEditorSpecialCharsEndOfLine) then with Source as TBCEditorSpecialCharsEndOfLine do begin Self.FColor := FColor; Self.FStyle := FStyle; Self.FVisible := FVisible; Self.DoChange; end else inherited Assign(Source); end; procedure TBCEditorSpecialCharsEndOfLine.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TBCEditorSpecialCharsEndOfLine.SetColor(const Value: TColor); begin if Value <> FColor then begin FColor := Value; DoChange; end; end; procedure TBCEditorSpecialCharsEndOfLine.SetStyle(const Value: TBCEditorSpecialCharsEndOfLineStyle); begin if Value <> FStyle then begin FStyle := Value; DoChange; end; end; procedure TBCEditorSpecialCharsEndOfLine.SetVisible(const Value: Boolean); begin if Value <> FVisible then begin FVisible := Value; DoChange; end; end; end.
unit ncThreads; // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // NetCom7 Package // Written by Demos Bill, 17 Nov 2009 // // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // To disable as much of RTTI as possible (Delphi 2009/2010), // Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position {$IF CompilerVersion >= 21.0} {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} {$ENDIF} {$WARN SYMBOL_PLATFORM OFF} interface uses {$IFDEF MSWINDOWS} WinApi.Windows, WinApi.ActiveX, {$ENDIF} System.Classes, System.SyncObjs, System.SysUtils; type TncThreadPriority = (ntpIdle, ntpLowest, ntpLower, ntpNormal, ntpHigher, ntpHighest, ntpTimeCritical); // The thread waits for the wakeup event to start processing // after the its ready event is set. // After processing is complete, it sets again the ready event and waits // again for the WakeUpEvent to be set. TncReadyThread = class(TThread) public WakeupEvent, ReadyEvent: TEvent; constructor Create; destructor Destroy; override; procedure Execute; override; procedure ProcessEvent; virtual; abstract; function IsReady: Boolean; function WaitForReady(aTimeOut: Cardinal = Infinite): TWaitResult; procedure Run; end; TncReadyThreadClass = class of TncReadyThread; // TncThreadPool is a thread pool of TncCommandExecThread that manages // to assign a job with AddJob to a waiting thread. // This Thread pool works as: // Request a ready thread from it, with RequestReadyThread // Set its data (normally this thread is a descendant of TncReadyThread with appropriate data fields // Call RunRequestedThread to tell it to run its ProcessEvent TncThreadPool = class private FGrowUpto: Integer; function GetGrowUpto: Integer; procedure SetGrowUpto(const Value: Integer); private ThreadClass: TncReadyThreadClass; procedure ShutDown; protected Threads: array of TncReadyThread; public Serialiser: TCriticalSection; constructor Create(aWorkerThreadClass: TncReadyThreadClass); destructor Destroy; override; function RequestReadyThread: TncReadyThread; procedure RunRequestedThread(aRequestedThread: TncReadyThread); procedure SetExecThreads(aThreadCount: Integer; aThreadPriority: TncThreadPriority); procedure SetThreadPriority(aPriority: TncThreadPriority); property GrowUpto: Integer read GetGrowUpto write SetGrowUpto; end; function GetNumberOfProcessors: Integer; inline; {$IFDEF MSWINDOWS} function FromNCThreadPriority(ancThreadPriority: TncThreadPriority): TThreadPriority; inline; function ToNCThreadPriority(aThreadPriority: TThreadPriority): TncThreadPriority; inline; {$ELSE} function FromNCThreadPriority(ancThreadPriority: TncThreadPriority): Integer; inline; function ToNCThreadPriority(aThreadPriority: Integer): TncThreadPriority; inline; {$ENDIF} implementation // ***************************************************************************** // Helper functions // ***************************************************************************** function GetNumberOfProcessors: Integer; {$IFDEF MSWINDOWS} var lpSystemInfo: TSystemInfo; i: Integer; begin Result := 0; try GetSystemInfo(lpSystemInfo); for i := 0 to lpSystemInfo.dwNumberOfProcessors - 1 do if lpSystemInfo.dwActiveProcessorMask or (1 shl i) <> 0 then Result := Result + 1; finally if Result < 1 then Result := 1; end; end; {$ELSE} begin Result := TThread.ProcessorCount; end; {$ENDIF} {$IFDEF MSWINDOWS} function FromNCThreadPriority(ancThreadPriority: TncThreadPriority): TThreadPriority; begin case ancThreadPriority of ntpIdle: Result := tpIdle; ntpLowest: Result := tpLowest; ntpLower: Result := tpLower; ntpHigher: Result := tpHigher; ntpHighest: Result := tpHighest; ntpTimeCritical: Result := tpTimeCritical; else Result := tpNormal; end; end; function ToNCThreadPriority(aThreadPriority: TThreadPriority): TncThreadPriority; begin case aThreadPriority of tpIdle: Result := ntpIdle; tpLowest: Result := ntpLowest; tpLower: Result := ntpLower; tpHigher: Result := ntpHigher; tpHighest: Result := ntpHighest; tpTimeCritical: Result := ntpTimeCritical; else Result := ntpNormal; end; end; {$ELSE} function FromNCThreadPriority(ancThreadPriority: TncThreadPriority): Integer; begin case ancThreadPriority of ntpIdle: Result := 19; ntpLowest: Result := 13; ntpLower: Result := 7; ntpHigher: Result := -7; ntpHighest: Result := -13; ntpTimeCritical: Result := -19; else Result := 0; end; end; function ToNCThreadPriority(aThreadPriority: Integer): TncThreadPriority; begin case aThreadPriority of 14 .. 19: Result := ntpIdle; 8 .. 13: Result := ntpLowest; 3 .. 7: Result := ntpLower; -7 .. -3: Result := ntpHigher; -13 .. -8: Result := ntpHighest; -19 .. -14: Result := ntpTimeCritical; else Result := ntpNormal; end; end; {$ENDIF} // ***************************************************************************** { TncReadyThread } // ***************************************************************************** constructor TncReadyThread.Create; begin WakeupEvent := TEvent.Create; ReadyEvent := TEvent.Create; inherited Create(False); end; destructor TncReadyThread.Destroy; begin ReadyEvent.Free; WakeupEvent.Free; inherited Destroy; end; procedure TncReadyThread.Execute; begin {$IFDEF MSWINDOWS} CoInitialize(nil); {$ENDIF} try while True do begin ReadyEvent.SetEvent; WakeupEvent.WaitFor(Infinite); ReadyEvent.ResetEvent; WakeupEvent.ResetEvent; // Next loop will wait again if Terminated then Break; // Exit main loop try ProcessEvent; except end; if Terminated then Break; // Exit main loop end; // Exiting main loop terminates thread ReadyEvent.SetEvent; finally {$IFDEF MSWINDOWS} CoUninitialize; {$ENDIF} end; end; function TncReadyThread.IsReady: Boolean; begin Result := ReadyEvent.WaitFor(0) = wrSignaled; end; function TncReadyThread.WaitForReady(aTimeOut: Cardinal = Infinite): TWaitResult; begin Result := ReadyEvent.WaitFor(aTimeOut); end; procedure TncReadyThread.Run; begin ReadyEvent.ResetEvent; WakeupEvent.SetEvent; end; // ***************************************************************************** { TncThreadPool } // ***************************************************************************** constructor TncThreadPool.Create(aWorkerThreadClass: TncReadyThreadClass); begin Serialiser := TCriticalSection.Create; ThreadClass := aWorkerThreadClass; FGrowUpto := 500; // can reach up to 500 threads by default end; destructor TncThreadPool.Destroy; begin ShutDown; Serialiser.Free; inherited; end; function TncThreadPool.RequestReadyThread: TncReadyThread; var i: Integer; begin // Keep repeating until a ready thread is found repeat for i := 0 to High(Threads) do begin if Threads[i].ReadyEvent.WaitFor(0) = wrSignaled then begin Threads[i].ReadyEvent.ResetEvent; Result := Threads[i]; Exit; end; end; // We will get here if no threads were ready if (Length(Threads) < FGrowUpto) then begin // Create a new thread to handle commands i := Length(Threads); SetLength(Threads, i + 1); // i now holds High(Threads) try Threads[i] := ThreadClass.Create; except // Cannot create any new thread // Set length back to what it was, and continue waiting until // any other thread is ready SetLength(Threads, i); Continue; end; Threads[i].Priority := Threads[0].Priority; if Threads[i].ReadyEvent.WaitFor(1000) = wrSignaled then begin Threads[i].ReadyEvent.ResetEvent; Result := Threads[i]; Exit; end; end else TThread.Yield; // Was Sleep(1); until False; end; // Between requesting a ready thread and executing it, we normally fill in // the thread's data (would be a descendant that we need to fill known data to work with) procedure TncThreadPool.RunRequestedThread(aRequestedThread: TncReadyThread); begin aRequestedThread.WakeupEvent.SetEvent; end; procedure TncThreadPool.SetExecThreads(aThreadCount: Integer; aThreadPriority: TncThreadPriority); var i: Integer; begin // Terminate any not needed threads if aThreadCount < Length(Threads) then begin for i := aThreadCount to High(Threads) do try Threads[i].Terminate; Threads[i].WakeupEvent.SetEvent; except end; for i := aThreadCount to high(Threads) do try Threads[i].WaitFor; Threads[i].Free; except end; end; // Reallocate thread count SetLength(Threads, aThreadCount); for i := 0 to high(Threads) do if Threads[i] = nil then begin Threads[i] := ThreadClass.Create; Threads[i].Priority := FromNCThreadPriority(aThreadPriority); end else Threads[i].Priority := FromNCThreadPriority(aThreadPriority); end; procedure TncThreadPool.SetThreadPriority(aPriority: TncThreadPriority); var i: Integer; begin for i := 0 to high(Threads) do try Threads[i].Priority := FromNCThreadPriority(aPriority); except // Sone android devices do not like this end; end; procedure TncThreadPool.ShutDown; var i: Integer; begin for i := 0 to high(Threads) do try Threads[i].Terminate; Threads[i].WakeupEvent.SetEvent; except end; for i := 0 to high(Threads) do try Threads[i].WaitFor; Threads[i].Free; except end; end; function TncThreadPool.GetGrowUpto: Integer; begin Serialiser.Acquire; try Result := FGrowUpto; finally Serialiser.Release; end; end; procedure TncThreadPool.SetGrowUpto(const Value: Integer); begin Serialiser.Acquire; try FGrowUpto := Value; finally Serialiser.Release; end; end; end.
{ Copyright (c) 2018-2019 Karoly Balogh <charlie@amigaspirit.hu> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. } {$MODE OBJFPC} unit mqttclass; interface uses classes, ctypes, mosquitto; type mqtt_logfunc = procedure(const msg: ansistring); function mqtt_init: boolean; overload; function mqtt_init(const verbose: boolean): boolean; overload; function mqtt_loglevel_to_str(const loglevel: cint): ansistring; procedure mqtt_setlogfunc(logfunc: mqtt_logfunc); type TMQTTOnMessageEvent = procedure(const payload: Pmosquitto_message) of object; TMQTTOnPublishEvent = procedure(const mid: cint) of object; TMQTTOnSubscribeEvent = procedure(mid: cint; qos_count: cint; const granted_qos: pcint) of object; TMQTTOnUnsubscribeEvent = procedure(mid: cint) of object; TMQTTOnConnectEvent = procedure(const rc: cint) of object; TMQTTOnDisconnectEvent = procedure(const rc: cint) of object; TMQTTOnLogEvent = procedure(const level: cint; const str: ansistring) of object; const MOSQ_LOG_NODEBUG = MOSQ_LOG_ALL - MOSQ_LOG_DEBUG; type TMQTTConnectionState = ( mqttNone, mqttConnecting, mqttConnected, mqttReconnecting, mqttDisconnected ); type TMQTTConfig = record ssl: boolean; ssl_cacertfile: ansistring; hostname: ansistring; port: word; username: ansistring; password: ansistring; keepalives: longint; reconnect_delay: longint; reconnect_backoff: boolean; client_id: ansistring; end; type { This junk uses FPC-supplied threading, because mosquitto for whatever retarded reason on Windows comes w/o threading enabled by default (CB) } TMQTTConnection = class(TThread) protected FName: string; FMosquitto: Pmosquitto; FConfig: TMQTTConfig; FOnMessage: TMQTTOnMessageEvent; FOnPublish: TMQTTOnPublishEvent; FOnSubscribe: TMQTTOnSubscribeEvent; FOnUnsubscribe: TMQTTOnUnsubscribeEvent; FOnConnect: TMQTTOnConnectEvent; FOnDisconnect: TMQTTOnDisconnectEvent; FOnLog: TMQTTOnLogEvent; FMQTTLogLevel: cint; { allowed log levels of the mqttclass } FMOSQLogLevel: cint; { allowed log levels of the underlying mosquitto lib } FAutoReconnect: boolean; FReconnectTimer: TDateTime; FReconnectPeriod: longint; FReconnectDelay: longint; FReconnectBackoff: boolean; FMQTTState: TMQTTConnectionState; FMQTTStateLock: TRTLCriticalSection; procedure SetupReconnectDelay; function ReconnectDelayExpired: boolean; function GetMQTTState: TMQTTConnectionState; procedure SetMQTTState(state: TMQTTConnectionState); procedure Execute; override; public constructor Create(const name: string; const config: TMQTTConfig); constructor Create(const name: string; const config: TMQTTConfig; const loglevel: cint); destructor Destroy; override; function Connect: cint; function Reconnect: cint; function Subscribe(var mid: cint; const sub: ansistring; qos: cint): cint; function Subscribe(const sub: ansistring; qos: cint): cint; function Publish(var mid: cint; const topic: ansistring; payloadlen: cint; var payload; qos: cint; retain: cbool): cint; function Publish(const topic: ansistring; payloadlen: cint; var payload; qos: cint; retain: cbool): cint; function Publish(var mid: cint; const topic: ansistring; const payload: ansistring; qos: cint; retain: cbool): cint; function Publish(const topic: ansistring; const payload: ansistring; qos: cint; retain: cbool): cint; procedure Log(const level: cint; const message: ansistring); property State: TMQTTConnectionState read GetMQTTState write SetMQTTState; property AutoReconnect: boolean read FAutoReconnect write FAutoReconnect; property OnMessage: TMQTTOnMessageEvent read FOnMessage write FOnMessage; property OnPublish: TMQTTOnPublishEvent read FOnPublish write FOnPublish; property OnSubscribe: TMQTTOnSubscribeEvent read FOnSubscribe write FOnSubscribe; property OnUnsubscribe: TMQTTOnUnsubscribeEvent read FOnUnsubscribe write FOnUnsubscribe; property OnConnect: TMQTTOnConnectEvent read FOnConnect write FOnConnect; property OnDisconnect: TMQTTOnDisconnectEvent read FOnDisconnect write FOnDisconnect; property OnLog: TMQTTOnLogEvent read FOnLog write FOnLog; property MQTTLogLevel: cint read FMQTTLogLevel write FMQTTLogLevel; property MOSQLogLevel: cint read FMOSQLogLevel write FMOSQLogLevel; end; implementation uses sysutils, dateutils; const DEFAULT_RECONNECT_PERIOD_MS = 100; DEFAULT_RECONNECT_DELAY_MS = 60 * 1000; var logger: mqtt_logfunc; procedure mqtt_on_message(mosq: Pmosquitto; obj: pointer; const message: Pmosquitto_message); cdecl; forward; procedure mqtt_on_publish(mosq: Pmosquitto; obj: pointer; mid: cint); cdecl; forward; procedure mqtt_on_subscribe(mosq: Pmosquitto; obj: pointer; mid: cint; qos_count: cint; const granted_qos: pcint); cdecl; forward; procedure mqtt_on_unsubscribe(mosq: Pmosquitto; obj: pointer; mid: cint); cdecl; forward; procedure mqtt_on_connect(mosq: Pmosquitto; obj: pointer; rc: cint); cdecl; forward; procedure mqtt_on_disconnect(mosq: Pmosquitto; obj: pointer; rc: cint); cdecl; forward; procedure mqtt_on_log(mosq: Pmosquitto; obj: pointer; level: cint; const str: pchar); cdecl; forward; procedure mqtt_setlogfunc(logfunc: mqtt_logfunc); begin logger:=logfunc; end; procedure mqtt_log(const msg: ansistring); begin writeln(msg); end; constructor TMQTTConnection.Create(const name: String; const config: TMQTTConfig); begin Create(name, config, MOSQ_LOG_ALL); end; constructor TMQTTConnection.Create(const name: String; const config: TMQTTConfig; const loglevel: cint); var rc: cint; begin inherited Create(true); FName:=name; FConfig:=config; FMosquitto:=mosquitto_new(PChar(@FConfig.client_id[1]), true, self); if FMosquitto=nil then raise Exception.Create('mosquitto instance creation failure'); FAutoReconnect:=true; InitCriticalSection(FMQTTStateLock); State:=mqttNone; MQTTLogLevel:=loglevel; MOSQLogLevel:=loglevel; FReconnectTimer:=Now; FReconnectPeriod:=DEFAULT_RECONNECT_PERIOD_MS; FReconnectDelay:=DEFAULT_RECONNECT_DELAY_MS; if FConfig.reconnect_delay <> 0 then FReconnectDelay:=FConfig.reconnect_delay * 1000 else FAutoReconnect:=false; FReconnectBackoff:=FConfig.reconnect_backoff; mosquitto_threaded_set(Fmosquitto, true); mosquitto_log_callback_set(FMosquitto, @mqtt_on_log); mosquitto_message_callback_set(FMosquitto, @mqtt_on_message); mosquitto_publish_callback_set(FMosquitto, @mqtt_on_publish); mosquitto_subscribe_callback_set(FMosquitto, @mqtt_on_subscribe); mosquitto_unsubscribe_callback_set(FMosquitto, @mqtt_on_unsubscribe); mosquitto_connect_callback_set(FMosquitto, @mqtt_on_connect); mosquitto_disconnect_callback_set(FMosquitto, @mqtt_on_disconnect); if FConfig.ssl then begin if (FConfig.ssl_cacertfile <> '') then begin Log(MOSQ_LOG_INFO,'TLS CERT: '+FConfig.ssl_cacertfile); rc:=mosquitto_tls_set(Fmosquitto, PChar(FConfig.ssl_cacertfile), nil, nil, nil, nil); if rc <> MOSQ_ERR_SUCCESS then begin Log(MOSQ_LOG_ERR,'TLS Setup: '+mosquitto_strerror(rc)); raise Exception.Create('TLS Setup: '+mosquitto_strerror(rc)); end; end else Log(MOSQ_LOG_WARNING,'SSL enabled, but no CERT file specified. Skipping TLS setup...'); end; if FConfig.username <> '' then mosquitto_username_pw_set(Fmosquitto, PChar(FConfig.username), PChar(FConfig.password)); Start; { ... the thread } end; destructor TMQTTConnection.Destroy; begin mosquitto_disconnect(FMosquitto); if not Suspended then begin Terminate; { ... the thread } WaitFor; end; mosquitto_destroy(FMosquitto); FMosquitto:=nil; DoneCriticalSection(FMQTTStateLock); inherited; end; function TMQTTConnection.Connect: cint; begin Log(MOSQ_LOG_INFO,'Connecting to ['+FConfig.hostname+':'+IntToStr(FConfig.port)+'] - SSL:'+BoolToStr(FConfig.SSL,true)); result:=mosquitto_connect_async(Fmosquitto, PChar(FConfig.hostname), FConfig.port, FConfig.keepalives); if result = MOSQ_ERR_SUCCESS then State:=mqttConnecting else begin State:=mqttDisconnected; Log(MOSQ_LOG_ERR,'Connection failed with: '+mosquitto_strerror(result)); end; end; function TMQTTConnection.Reconnect: cint; begin Log(MOSQ_LOG_INFO,'Reconnecting to ['+FConfig.hostname+':'+IntToStr(FConfig.port)+'] - SSL:'+BoolToStr(FConfig.SSL,true)); result:=mosquitto_reconnect_async(Fmosquitto); if result = MOSQ_ERR_SUCCESS then State:=mqttConnecting else begin State:=mqttDisconnected; Log(MOSQ_LOG_ERR,'Reconnection failed with: '+mosquitto_strerror(result)); end; end; function TMQTTConnection.Subscribe(var mid: cint; const sub: ansistring; qos: cint): cint; begin result:=mosquitto_subscribe(Fmosquitto, @mid, PChar(sub), qos); end; function TMQTTConnection.Subscribe(const sub: ansistring; qos: cint): cint; begin result:=mosquitto_subscribe(Fmosquitto, nil, PChar(sub), qos); end; function TMQTTConnection.Publish(var mid: cint; const topic: ansistring; payloadlen: cint; var payload; qos: cint; retain: cbool): cint; begin result:=mosquitto_publish(Fmosquitto, @mid, PChar(topic), payloadlen, @payload, qos, retain); end; function TMQTTConnection.Publish(const topic: ansistring; payloadlen: cint; var payload; qos: cint; retain: cbool): cint; begin result:=mosquitto_publish(Fmosquitto, nil, PChar(topic), payloadlen, @payload, qos, retain); end; function TMQTTConnection.Publish(var mid: cint; const topic: ansistring; const payload: ansistring; qos: cint; retain: cbool): cint; begin result:=mosquitto_publish(Fmosquitto, @mid, PChar(topic), length(payload), PChar(payload), qos, retain); end; function TMQTTConnection.Publish(const topic: ansistring; const payload: ansistring; qos: cint; retain: cbool): cint; begin result:=mosquitto_publish(Fmosquitto, nil, PChar(topic), length(payload), PChar(payload), qos, retain); end; procedure TMQTTConnection.Log(const level: cint; const message: ansistring); var tmp: ansistring; begin if (MQTTLogLevel and level) > 0 then begin writestr(tmp,'[MQTT] [',FName,'] ',mqtt_loglevel_to_str(level),' ',message); logger(tmp); end; end; function TMQTTConnection.GetMQTTState: TMQTTConnectionState; begin EnterCriticalSection(FMQTTStateLock); result:=FMQTTState; LeaveCriticalSection(FMQTTStateLock); end; procedure TMQTTConnection.SetMQTTState(state: TMQTTConnectionState); var tmp: ansistring; begin EnterCriticalSection(FMQTTStateLock); if FMQTTState <> state then begin writestr(tmp,'State change: ',FMQTTState,' -> ',state); Log(MOSQ_LOG_DEBUG,tmp); FMQTTState:=state; end; LeaveCriticalSection(FMQTTStateLock); end; procedure TMQTTConnection.SetupReconnectDelay; begin if FReconnectBackoff then begin { This is kind of a kludge, but I've got no better idea for a simple solution - if there was no reconnection attempt for the double of the reconnect delay, we reset the backoff on the next attempt. (CB) } if MillisecondsBetween(FReconnectTimer, Now) > (FReconnectDelay * 2) then FReconnectPeriod:=DEFAULT_RECONNECT_PERIOD_MS else FReconnectPeriod:=FReconnectPeriod * 2; end else FReconnectPeriod:=FReconnectDelay; if FReconnectPeriod > FReconnectDelay then FReconnectPeriod:=FReconnectDelay; FReconnectTimer:=Now; Log(MOSQ_LOG_INFO,'Next reconnection attempt in '+FloatToStr(FReconnectPeriod / 1000)+' seconds.'); end; function TMQTTConnection.ReconnectDelayExpired: boolean; begin result:=MillisecondsBetween(FReconnectTimer, Now) > FReconnectPeriod; end; procedure TMQTTConnection.Execute; begin try Log(MOSQ_LOG_DEBUG,'Entering subthread...'); { OK, so this piece has to manage the entire reconnecting logic, because libmosquitto only has the reconnection logic and state machine, if the code uses the totally blocking mosquitto_loop_forever(), which has a few quirks to say the least, plus due to its blocking nature, has a few interoperability issues with Pascal threading... (CB) } while not (Terminated and (State in [mqttDisconnected, mqttReconnecting, mqttNone ] )) do begin case State of mqttNone: Sleep(100); mqttDisconnected: if AutoReconnect then begin SetupReconnectDelay; State:=mqttReconnecting; end else begin Log(MOSQ_LOG_INFO,'Automatic reconnection disabled, going standby.'); State:=mqttNone; end; mqttReconnecting: begin if ReconnectDelayExpired then Reconnect else Sleep(100); end; mqttConnected, mqttConnecting: mosquitto_loop(Fmosquitto, 100, 1); end; end; State:=mqttNone; except { FIX ME: this really needs something better } Log(MOSQ_LOG_ERR,'Exception in subthread, leaving...'); end; Log(MOSQ_LOG_DEBUG,'Exiting subthread.'); end; function mqtt_loglevel_to_str(const loglevel: cint): ansistring; begin mqtt_loglevel_to_str:='UNKNOWN'; case loglevel of MOSQ_LOG_INFO: mqtt_loglevel_to_str:='INFO'; MOSQ_LOG_NOTICE: mqtt_loglevel_to_str:='NOTICE'; MOSQ_LOG_WARNING: mqtt_loglevel_to_str:='WARNING'; MOSQ_LOG_ERR: mqtt_loglevel_to_str:='ERROR'; MOSQ_LOG_DEBUG: mqtt_loglevel_to_str:='DEBUG'; end; end; procedure mqtt_on_message(mosq: Pmosquitto; obj: pointer; const message: Pmosquitto_message); cdecl; var Fmosquitto: TMQTTConnection absolute obj; begin if assigned(Fmosquitto) and assigned(FMosquitto.OnMessage) then Fmosquitto.OnMessage(message); end; procedure mqtt_on_publish(mosq: Pmosquitto; obj: pointer; mid: cint); cdecl; var Fmosquitto: TMQTTConnection absolute obj; begin if assigned(Fmosquitto) then with FMosquitto do begin Log(MOSQ_LOG_DEBUG,'Publish ID: '+IntToStr(mid)); if assigned(OnPublish) then OnPublish(mid); end; end; procedure mqtt_on_subscribe(mosq: Pmosquitto; obj: pointer; mid: cint; qos_count: cint; const granted_qos: pcint); cdecl; var FMosquitto: TMQTTConnection absolute obj; begin if assigned(FMosquitto) and assigned(FMosquitto.OnSubscribe) then Fmosquitto.OnSubscribe(mid, qos_count, granted_qos); end; procedure mqtt_on_unsubscribe(mosq: Pmosquitto; obj: pointer; mid: cint); cdecl; var Fmosquitto: TMQTTConnection absolute obj; begin if assigned(FMosquitto) and assigned(FMosquitto.OnUnsubscribe) then FMosquitto.OnUnsubscribe(mid); end; procedure mqtt_on_connect(mosq: Pmosquitto; obj: pointer; rc: cint); cdecl; var FMosquitto: TMQTTConnection absolute obj; begin if assigned(FMosquitto) then with FMosquitto do begin Log(MOSQ_LOG_INFO,'Broker connection: '+mosquitto_strerror(rc)); State:=mqttConnected; if assigned(OnConnect) then OnConnect(rc); end; end; procedure mqtt_on_disconnect(mosq: Pmosquitto; obj: pointer; rc: cint); cdecl; const disconnect_reason: array[boolean] of string[31] = ('Connection lost', 'Normal termination'); var Fmosquitto: TMQTTConnection absolute obj; begin if assigned(FMosquitto) then with FMosquitto do begin Log(MOSQ_LOG_INFO,'Broker disconnected: '+disconnect_reason[rc = 0]); State:=mqttDisconnected; if assigned(OnDisconnect) then OnDisconnect(rc); end; end; procedure mqtt_on_log(mosq: Pmosquitto; obj: pointer; level: cint; const str: pchar); cdecl; var Fmosquitto: TMQTTConnection absolute obj; tmp: ansistring; begin tmp:=''; if assigned(Fmosquitto) then with Fmosquitto do begin if (MOSQLogLevel and level) > 0 then begin writestr(tmp,'[MOSQUITTO] [',FName,'] ',mqtt_loglevel_to_str(level),' ',str); logger(tmp) end; if assigned(OnLog) then OnLog(level, str); end else begin writestr(tmp,'[MOSQUITTO] [UNNAMED] ',mqtt_loglevel_to_str(level),' ',str); logger(tmp); end; end; var libinited: boolean; function mqtt_init: boolean; begin result:=mqtt_init(true); end; function mqtt_init(const verbose: boolean): boolean; var major, minor, revision: cint; begin result:=libinited; if not libinited then begin if verbose then logger('[MOSQUITTO] mosquitto init failed.'); exit; end; if verbose then begin mosquitto_lib_version(@major,@minor,@revision); logger('[MQTT] Compiled against mosquitto header version '+IntToStr(LIBMOSQUITTO_MAJOR)+'.'+IntToStr(LIBMOSQUITTO_MINOR)+'.'+IntToStr(LIBMOSQUITTO_REVISION)); logger('[MQTT] Running against libmosquitto version '+IntToStr(major)+'.'+IntToStr(minor)+'.'+IntToStr(revision)); end; end; initialization libinited:=mosquitto_lib_init = MOSQ_ERR_SUCCESS; logger:=@mqtt_log; finalization if libinited then mosquitto_lib_cleanup; end.
unit CfeChunkMp4; interface uses Classes, SysUtils, CfeChunkCommon; type TMp4DefinedChunk = class(TDefinedChunk) public constructor Create; override; end; TMp4FixedDefinedChunk = class(TFixedDefinedChunk) public constructor Create; override; end; TMp4UnknownChunk = class(TUnknownChunk) public constructor Create; override; end; TMp4ContainerChunk = class(TChunkContainer) public constructor Create; override; end; TMp4FileTypeChunk = class(TMp4DefinedChunk) private FMajorBrand: TChunkName; FMinorVersion: Integer; FCompatibleBrands: array of TChunkName; function GetCompatibleBrandsAsString: String; public procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; class function GetClassChunkName: TChunkName; override; property MajorBrand: TChunkName read FMajorBrand; property MinorVersion: Integer read FMinorVersion; property CompatibleBrandsAsString: String read GetCompatibleBrandsAsString; end; TMp4FreeChunk = class(TMp4DefinedChunk) public class function GetClassChunkName: TChunkName; override; end; TMp4MoovChunk = class(TMp4ContainerChunk) public class function GetClassChunkName: TChunkName; override; public constructor Create; override; end; TMp4MovieHeader = record Version: Byte; Flags: array [0..2] of Byte; CreationTime: Cardinal; ModificationTime: Cardinal; TimeScale: Cardinal; Duration: Cardinal; PreferredRate: Cardinal; PreferredVolume: Word; Reserved: array [0..9] of Byte; MatrixStructure: array [0..8] of Integer; PreviewTime: Cardinal; PreviewDuration: Cardinal; PosterTime: Cardinal; SelectionTime: Cardinal; SelectionDuration: Cardinal; CurrentTime: Cardinal; NextTrackId: Cardinal; end; TMp4MovieHeaderChunk = class(TMp4FixedDefinedChunk) private FMovieHeader: TMp4MovieHeader; function GetCreationTime: TDateTime; function GetDuration: Single; function GetModificationTime: TDateTime; function GetPreferredRate: Single; function GetPreferredVolume: Single; function GetTimeScale: Single; public constructor Create; override; class function GetClassChunkName: TChunkName; override; class function GetClassChunkSize: Cardinal; override; property CreationTime: TDateTime read GetCreationTime; property ModificationTime: TDateTime read GetModificationTime; property TimeScale: Single read GetTimeScale; property Duration: Single read GetDuration; property PreferredRate: Single read GetPreferredRate; property PreferredVolume: Single read GetPreferredVolume; end; TMp4TrackChunk = class(TMp4DefinedChunk) public class function GetClassChunkName: TChunkName; override; procedure LoadFromStream(Stream: TStream); override; end; TFileMp4 = class(TChunkedFile) private FFileType: TMp4FileTypeChunk; procedure ReadUnknownChunk(Stream: TStream; ChunkName: TChunkName; ChunkSize: Cardinal); public constructor Create; override; destructor Destroy; override; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; class function GetClassChunkName: TChunkName; override; class function CanLoad(Stream: TStream): Boolean; end; implementation uses DateUtils; { TMp4DefinedChunk } constructor TMp4DefinedChunk.Create; begin inherited; FChunkFlags := [cfSizeFirst, cfReversedByteOrder, cfIncludeChunkInSize]; end; { TMp4UnknownChunk } constructor TMp4UnknownChunk.Create; begin inherited; FChunkFlags := [cfSizeFirst, cfReversedByteOrder, cfIncludeChunkInSize]; end; { TMp4FixedDefinedChunk } constructor TMp4FixedDefinedChunk.Create; begin inherited; FChunkFlags := [cfSizeFirst, cfReversedByteOrder, cfIncludeChunkInSize]; end; { TMp4ContainerChunk } constructor TMp4ContainerChunk.Create; begin inherited; FChunkFlags := [cfSizeFirst, cfReversedByteOrder, cfIncludeChunkInSize]; end; { TMp4FreeChunk } class function TMp4FreeChunk.GetClassChunkName: TChunkName; begin Result := 'free'; end; { TMp4FileTypeChunk } class function TMp4FileTypeChunk.GetClassChunkName: TChunkName; begin Result := 'ftyp'; end; function TMp4FileTypeChunk.GetCompatibleBrandsAsString: String; var Index: Integer; begin if Length(FCompatibleBrands) = 0 then Result := ''; Result := FCompatibleBrands[0]; for Index := 1 to High(FCompatibleBrands) do Result := Result + ', ' + FCompatibleBrands[Index]; end; procedure TMp4FileTypeChunk.LoadFromStream(Stream: TStream); var Index: Integer; CompatibleBrandCount: Integer; begin inherited; Stream.Read(FMajorBrand, 4); Stream.Read(FMinorVersion, 4); CompatibleBrandCount := (FChunkSize - 16) div SizeOf(Integer); SetLength(FCompatibleBrands, CompatibleBrandCount); for Index := 0 to CompatibleBrandCount - 1 do Stream.Read(FCompatibleBrands[Index], 4); end; procedure TMp4FileTypeChunk.SaveToStream(Stream: TStream); var Index: Integer; begin inherited; Stream.Write(FMajorBrand, 4); Stream.Write(FMinorVersion, 4); for Index := 0 to Length(FCompatibleBrands) - 1 do Stream.Write(FCompatibleBrands[Index], 4); end; { TMp4MoovChunk } constructor TMp4MoovChunk.Create; begin inherited; RegisterChunkClasses([TMp4MovieHeaderChunk, TMp4TrackChunk]); end; class function TMp4MoovChunk.GetClassChunkName: TChunkName; begin Result := 'moov'; end; { TMp4MovieHeaderChunk } constructor TMp4MovieHeaderChunk.Create; begin inherited; // set initial values with FMovieHeader do begin Version := 0; Flags[0] := 0; Flags[1] := 0; Flags[2] := 0; CreationTime := SecondsBetween(Now, EncodeDateTime(1904, 1, 1, 0, 0, 0, 0)); ModificationTime := SecondsBetween(Now, EncodeDateTime(1904, 1, 1, 0, 0, 0, 0)); TimeScale := $3E8; Duration := $57BC0; PreferredRate := $10000; PreferredVolume := $100; FillChar(Reserved[0], 10, 0); MatrixStructure[0] := $100; MatrixStructure[1] := 0; MatrixStructure[2] := 0; MatrixStructure[3] := 0; MatrixStructure[4] := $100; MatrixStructure[5] := 0; MatrixStructure[6] := 0; MatrixStructure[7] := 0; MatrixStructure[8] := $40; PreviewTime := 0; PreviewDuration := 0; PosterTime := 0; SelectionTime := 0; SelectionDuration := 0; CurrentTime := 0; NextTrackId := $2000000; end; StartAddress := @FMovieHeader; end; class function TMp4MovieHeaderChunk.GetClassChunkName: TChunkName; begin Result := 'mvhd'; end; class function TMp4MovieHeaderChunk.GetClassChunkSize: Cardinal; begin Result := SizeOf(TMp4MovieHeader); end; function TMp4MovieHeaderChunk.GetCreationTime: TDateTime; begin Result := IncSecond(EncodeDateTime(1904, 1, 1, 0, 0, 0, 0), FMovieHeader.CreationTime); end; function TMp4MovieHeaderChunk.GetDuration: Single; begin Result := FMovieHeader.Duration / FMovieHeader.TimeScale; end; function TMp4MovieHeaderChunk.GetModificationTime: TDateTime; begin Result := IncSecond(EncodeDateTime(1904, 1, 1, 0, 0, 0, 0), FMovieHeader.ModificationTime); end; function TMp4MovieHeaderChunk.GetPreferredRate: Single; begin Result := FMovieHeader.PreferredRate / $10000; end; function TMp4MovieHeaderChunk.GetPreferredVolume: Single; begin Result := FMovieHeader.PreferredVolume / $100; end; function TMp4MovieHeaderChunk.GetTimeScale: Single; begin Result := 1 / FMovieHeader.TimeScale; end; { TMp4TrackChunk } class function TMp4TrackChunk.GetClassChunkName: TChunkName; begin Result := 'trak'; end; procedure TMp4TrackChunk.LoadFromStream(Stream: TStream); begin inherited; Stream.Position := Stream.Position + ChunkSize; end; { TFileMp4 } constructor TFileMp4.Create; begin inherited; FChunkFlags := [cfSizeFirst, cfReversedByteOrder]; FFileType := TMp4FileTypeChunk.Create; end; destructor TFileMp4.Destroy; begin inherited; end; class function TFileMp4.CanLoad(Stream: TStream): Boolean; var ChunkSize: Cardinal; ChunkName: TChunkName; begin Result := Stream.Size >= 8; if Result then begin Stream.Read(ChunkSize, 4); Stream.Read(ChunkName, 4); Stream.Seek(-8, soFromCurrent); Result := ChunkName = GetClassChunkName; end; end; class function TFileMp4.GetClassChunkName: TChunkName; begin Result := 'ftyp'; end; procedure TFileMp4.ReadUnknownChunk(Stream: TStream; ChunkName: TChunkName; ChunkSize: Cardinal); var ChunkClass: TDefinedChunkClass; DefinedChunk: TDefinedChunk; UnknownChunk: TMp4UnknownChunk; begin ChunkClass := ChunkClassByChunkName(ChunkName); if Assigned(ChunkClass) then begin DefinedChunk := ChunkClass.Create; DefinedChunk.LoadFromStream(Stream); FChunkList.Add(DefinedChunk); end else begin UnknownChunk := TMp4UnknownChunk.Create; UnknownChunk.LoadFromStream(Stream); AddChunk(UnknownChunk); end; end; procedure TFileMp4.LoadFromStream(Stream: TStream); var ChunkSize: Cardinal; ChunkName: TChunkName; UnknownChunk: TMp4UnknownChunk; begin FFileType.LoadFromStream(Stream); AddChunk(FFileType); while Stream.Position + 8 <= Stream.Size do begin Stream.Read(ChunkSize, 4); Stream.Read(ChunkName, 4); Flip32(ChunkSize); Stream.Position := Stream.Position - 8; ReadUnknownChunk(Stream, ChunkName, ChunkSize); end; end; procedure TFileMp4.SaveToStream(Stream: TStream); begin FFileType.SaveToStream(Stream); end; initialization TFileMp4.RegisterChunks([TMp4FileTypeChunk, TMp4FreeChunk, TMp4MoovChunk, TMp4MovieHeaderChunk, TMp4TrackChunk]); end.
unit UGameDBManager; { 游戏数据管理类 可使用 CreateNewDataType 创建一个数据集对象 数据集对象内 可存放数据对象,对象的结构由用户自行定义 可使用 QueryDataByTypeId 查询一个数据集对象 } interface uses Windows,Classes,SyncObjs,UGameDataBase; type TGameDBManager = class private mList:TList; mCri:TCriticalSection; public constructor Create(); //创建数据对象 Function CreateNewDataType(_DataName:string;_DataType:Cardinal):TGameDataBase; //查询数据对象 Function QueryDataByTypeId(_DataType:Cardinal):TGameDataBase; end; var g_GameDB:TGameDBManager; implementation { TGameDBManager } constructor TGameDBManager.Create; begin mList:=TList.Create; mCri:=TCriticalSection.Create; end; function TGameDBManager.CreateNewDataType(_DataName: string; _DataType: Cardinal): TGameDataBase; var pNode:TGameDataBase; begin pNode:=TGameDataBase.Create(_DataName,_DataType); mCri.Enter; mList.Add(pNode); mCri.Leave; Result:=pNode; end; function TGameDBManager.QueryDataByTypeId(_DataType: Cardinal): TGameDataBase; var pNode:TGameDataBase; i:integer; begin Result:= Nil; mCri.Enter; if mList.Count > 0 then begin for i := 0 to mList.Count - 1 do begin pNode:=mList[i]; if pNode.DataType = _DataType then begin Result:= pNode; Break; end; end; end; mCri.Leave; end; initialization g_GameDB:=TGameDBManager.Create; end.
program strings; var a, b: string; begin a := 'Hello, '; b := a + 'world!'; writeln(b); writeln(length(b)); writeln(LowerCase(b)); writeln(UpCase(b)); SetLength(b, 5); writeln(b); end.
unit U_Association; interface uses U_Typeset, U_ListFunctions; procedure InitAssocField(var assoc_field : dynamic_array_str; len : longint); // What : Initiates the association field with '-', sets it's length // to the estimated number of elements. procedure AssocOne(buffer : string; var assoc_field : dynamic_array_str; var exact_elem : longint; num_elem : longint); // What : Finds the element in the association array if it is already associated // else associates it into the first blank space. // How : Goes the the array, checking if we are searching in the valid // range and if we reach the end of valid range (indicated by length/'-' signs) // we associate a new element (add it at first blank spot) and increment // the exact number of elements procedure AssociateElements(start : PItem; var assoc_field : dynamic_array_str; var exact_elem : longint; num_elem : longint); // What : fills the whole association field, finds all the elements and through // AssocOne it counts how many elements there exactly are (exact_el) // How : Goes through the list, each reactant char by char. When it finds // a whole elemenet (whole element ends with a number, an uppercase letter // or parentheses, it calls AssocOne thus associates it. function FindAssoc(assoc_field : dynamic_array_str; exact_elem : longint; elem : string) : longint; // What : Finds the association of an element, returns the positionin the array // if found and -1 if not found procedure TokenizeString(S : string; assoc_field : dynamic_array_str; exact_elem : longint; var StackL : PStack); // What : Tokenizes given string into the stack, for complete details see documentation on tokenizing. // How : Goes through the string char by char, looking for UpperCases, parentheses // numbers, makes the appropriate pushes into the stack. implementation { initialization of assoc field} procedure InitAssocField(var assoc_field : dynamic_array_str; len : longint); var i : longint; begin setlength(assoc_field,len); for i := 0 to len-1 do begin assoc_field[i] := '-'; end; writeln('OK _ ASSOC INIT'); end; procedure AssocOne(buffer : string; var assoc_field : dynamic_array_str; var exact_elem : longint; num_elem : longint); var i_f : longint; begin i_f := 0; while( (assoc_field[i_f] <> buffer) and // while we are searching in some data (and not '-'s) (assoc_field[i_f] <> '-')) do begin if i_f < num_elem then Inc(i_f) else begin i_f := -1; break; end; end; if ( (i_f <> -1) and (assoc_field[i_f] = '-') ) then begin // if we didnt find it, associate it at the end assoc_field[i_f] := buffer; Inc(exact_elem); // and we found a new element! end; end; procedure AssociateElements(start : PItem; var assoc_field : dynamic_array_str; var exact_elem : longint; num_elem : longint); var S,buffer : String; i : longint; i_lst : PItem; begin i_lst := start^.next; while i_lst <> nil do begin S := i_lst^.val; buffer := S[1]; if(IsUpper(S[1]) = false) then begin WriteLn('Reactant > ',S,' < does not begin with capital letter!'); WriteLn('Ending'); halt; end; for i := 2 to length(S) do begin if ((IsLower(S[i])) and (buffer <> '')) then begin buffer := buffer + S[i]; end else if ((IsUpper(S[i])) or (IsNumber(S[i])) or (S[i] = '(') or (S[i] = ')')) then begin if(buffer <> '') then begin AssocOne(buffer, assoc_field, exact_elem, num_elem); buffer := ''; end; if (IsUpper(S[i])) then buffer := S[i]; end; end; if (buffer <> '') then AssocOne(buffer, assoc_field, exact_elem, num_elem);; i_lst := i_lst^.next; end; end; { returns what number is assigned to 'elem', -1 if none } function FindAssoc(assoc_field : dynamic_array_str; exact_elem : longint; elem : string) : longint; var i : longint; begin for i := 0 to exact_elem do begin if(assoc_field[i] = elem) then begin FindAssoc := i; exit; end; end; FindAssoc := -1; end; { Tokenizes parameter s (string) into a stack at StackS (PStack) making it able to be counted into a matrix } procedure TokenizeString(S : string; assoc_field : dynamic_array_str; exact_elem : longint; var StackL : PStack); var tmp,NumOrStr,i,num_buf : longint; str_buf : string; {NumOrStr :: 0 - nothing, 1 - int, 2 - str, 3 - cislo za zavorkou} begin if(IsUpper(S[1])) then begin str_buf := S[1]; NumOrStr := 2 end else begin Writeln;Writeln('===============================================');Writeln; writeln(' Error? > ',S ,' < does not start with a capital letter!'); Writeln(' Ending.'); halt; end; num_buf := 0; for i:=2 to length(S) do begin {found lowercase and needed lowercase} if ( (IsLower(S[i])) and (NumOrStr = 2) ) then begin str_buf := str_buf + S[i]; end {found lowercase and needed number or bracket number!} else if ( (IsLower(S[i])) and (NumOrStr <> 2) ) then begin writeln('Element didnt start with capital!'); halt; end {found number and needed number} else if ( (IsNumber(S[i])) and ( (NumOrStr = 0) or (NumOrStr = 1) or (NumOrStr = 3) )) then begin num_buf := num_buf*10 + ord(S[i]) - ord('0'); end {found number, was reading string} {dump the string! and read number, and set reading} else if ( (IsNumber(S[i])) and (NumOrStr = 2)) then begin tmp := FindAssoc(assoc_field, exact_elem, str_buf); if(tmp <> -1) then PushEnd(tmp,StackL) else begin Write('I found element I havent previously, ERROR at ',S[i]); halt; end; NumOrStr := 1; str_buf := ''; num_buf := ord(S[i]) - ord('0'); end {found UpperCase, was doing nothing} {start reading string, set what I am doing} else if (IsUpper(S[i]) and (NumOrStr = 0)) then begin str_buf := S[i]; NumOrStr := 2; end {found UpperCase, was reading number} {set reding str, do buffer} {dump number, clear numbuf} else if (IsUpper(S[i]) and (NumOrStr = 1)) then begin NumOrStr := 2; str_buf := S[i]; num_buf := num_buf*(-1); PushEnd(num_buf,StackL); num_buf := 0; end {found Upper Case, was reading string } {dump the string, start new string} else if (IsUpper(S[i]) and (NumOrStr = 2)) then begin tmp := FindAssoc(assoc_field, exact_elem, str_buf); if(tmp <> -1) then PushEnd(tmp,StackL) else begin Write('I found element I havent previously, ERROR'); halt; end; str_buf := S[i]; end {found UpperCase, was reading BRACKET number} {dump number, DUMP FLAG, set mode, start string} else if (IsUpper(S[i]) and (NumOrStr = 3)) then begin if(num_buf = 0) then begin num_buf := -1; PushEnd(num_buf,StackL); end else begin num_buf := num_buf*(-1); PushEnd(num_buf,StackL); end; PushEnd(32000,StackL); NumOrStr := 2; num_buf := 0; str_buf := S[i]; end {found opening bracket, was doing nothing} {dump OPENFLAG, do nothing} else if ( (S[i] = '(') and (NumOrStr = 0) )then begin PushEnd(-32000,StackL); NumOrStr := 0; end {found opening bracket, was reading number} {dump numbuf and OPENFLAG, clear numbuf, do nothing} else if ( (S[i] = '(') and (NumOrStr = 1) )then begin num_buf := num_buf*(-1); PushEnd(num_buf,StackL); num_buf := 0; PushEnd(-32000,StackL); NumOrStr := 0; end {found opening bracket, was reading string} {dump string and OPENFLAG, clear strbuf, do nothing} else if ( (S[i] = '(') and (NumOrStr = 2) )then begin tmp := FindAssoc(assoc_field, exact_elem, str_buf); if(tmp <> -1) then PushEnd(tmp,StackL) else begin Write('I found element I havent previously, ERROR'); halt; end; PushEnd(-32000,StackL); NumOrStr := 0; str_buf := ''; end {found opening bracket, was reading BRACKET number} {dump number, DUMP FLAG, set mode} else if ((S[i] = '(') and (NumOrStr = 3)) then begin if(num_buf = 0) then begin num_buf := -1; PushEnd(num_buf,StackL); end else begin num_buf := num_buf*(-1); PushEnd(num_buf,StackL); end; PushEnd(32000,StackL); NumOrStr := 0; num_buf := 0; end {found close braket, was doing nothing} {enter mode 3 - reading number, then printing flag} else if ( (S[i] = ')') and (NumOrStr = 0) )then begin NumOrStr := 3; num_buf := 0; end {found closing bracket, was reading number} {dump number, clear numbuf, enter mode 3} else if ( (S[i] = ')') and (NumOrStr = 1) )then begin num_buf := num_buf*(-1); PushEnd(num_buf,StackL); num_buf := 0; NumOrStr := 3; end {found closing bracket, was reading string} {dump string, clear strbuf, enter mode 3} else if ( (S[i] = ')') and (NumOrStr = 2) )then begin tmp := FindAssoc(assoc_field, exact_elem, str_buf); if(tmp <> -1) then PushEnd(tmp,StackL) else begin Write('I found element I havent previously, ERROR'); halt; end; NumOrStr := 3; str_buf := ''; end {found closing bracket, was reading BRACKET number} {dump number, FLAG, then clear number and set mode 3} else if ( (S[i] = ')') and (NumOrStr = 3) )then begin if(num_buf = 0) then begin num_buf := -1; PushEnd(num_buf,StackL); end else begin num_buf := num_buf*(-1); PushEnd(num_buf,StackL); end; NumOrStr := 3; num_buf := 0; PushEnd(32000,StackL); end end; if(num_buf <> 0) then begin { some number left over} num_buf := num_buf*(-1); PushEnd(num_buf,StackL); num_buf := 0; if(NumOrStr = 3) then begin { is the number after brackets check} PushEnd(32000,StackL); end; NumOrStr := 0; end else if ((num_buf = 0) and (NumOrStr = 3)) then begin { -1 after brackets left over } PushEnd(-1,StackL); PushEnd(32000,StackL); NumOrStr := 0; end else if (str_buf <> '') then begin { string left over } tmp := FindAssoc(assoc_field, exact_elem, str_buf); if(tmp <> -1) then PushEnd(tmp,StackL) else begin Write('I found element at the end that I havent previously found, ERROR'); halt; end; str_buf := ''; NumOrStr := 0; end; { End of procedure, checks if num_buf, str_buf and NumOrStr are all as should - 0, empty and 0. Writeln('NumBuf je : ', num_buf); Writeln('StrBuf je : ,', str_buf,','); Writeln('NumOrStr je : ', NumOrStr); } end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, RstrFld, snake; type { TForm1 } TForm1 = class(TForm) BRasterFeld: TButton; procedure BRasterFeldClick(Sender: TObject); procedure FormPaint(Sender: TObject); procedure SpielSchleife(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); private { private declarations } public { public declarations } end; var Form1: TForm1; SpielFeld: TRasterFeld; KastenX, KastenY: integer; Rendern: boolean; Schlange: TSnake; implementation {$R *.lfm} { TForm1 } // Prozedur wird aufgerufen, sobald der Button gedrückt wird procedure TForm1.BRasterFeldClick(Sender: TObject); begin BRasterFeld.Visible := false; // Den Button nicht sichtbar machen SpielFeld := TRasterFeld.Erstelle(50, 12, 9, Self); // Das RasterFeld erstellen SpielFeld.FormAnFeldAnpassen(); // Die Größe der Form an die Größe des RasterFeldes anpassen SpielFeld.StarteSpielSchleife(1000 div 2, @SpielSchleife); // Startet die Spiel Schleife mit 2 Aufrufen pro Sekunden SpielFeld.StarteRenderSchleife(); // Startet die Render Schleife mit 60 fps Rendern := True; Schlange := TSnake.Create(0, 0, clRed, SpielFeld); end; var Runter: boolean; // Prozedur entspricht der Spiel Schleife und wird 2 Mal in einer Sekunde aufgerufen procedure TForm1.SpielSchleife(Sender: TObject); begin //KastenX := 200;//Random(SpielFeld.FeldBreite); //KastenY := 200;//Random(SpielFeld.FeldHoehe); if(Runter) then Schlange.Bewegung('runter') else Schlange.Bewegung('rechts'); Runter := not Runter; end; // In dieser Prozedur wird alles gerendert mit 60 fps procedure TForm1.FormPaint(Sender: TObject); begin if not Rendern then Exit; // Erst anfangen zu Rendern wenn der Button geklickt wurde SpielFeld.Loeschen(); Schlange.Rendern(); end; // Prozedur wird aufgerufen, sobald das Fenster geschlossen wird procedure TForm1.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin SpielFeld.StoppeSpielSchleife(); SpielFeld.StoppeRenderSchleife(); FreeAndNil(SpielFeld); // SpielFeld-Objekt aus dem Speicher (RAM) löschen end; end.
unit dlg_ProrataNewDetailUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Mask, Db, DBTables, Wwtable, wwdblook; type Tdlg_ProrataNewDetail = class(TForm) gb_ProrataYear: TGroupBox; Label5: TLabel; Label6: TLabel; ed_RollYear: TEdit; gb_OtherInformation: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; OKButton: TBitBtn; CancelButton: TBitBtn; cb_HomesteadCode: TComboBox; ed_Days: TEdit; ed_TaxRate: TEdit; ed_ExemptionAmount: TEdit; Label7: TLabel; cb_Levy: TComboBox; Label8: TLabel; ed_TaxAmount: TEdit; tb_LeviesToProrate: TTable; Label9: TLabel; ed_CalculationDays: TEdit; Label10: TLabel; procedure OKButtonClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ed_RollYearExit(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure ed_ExemptionAmountExit(Sender: TObject); private { Private declarations } public { Public declarations } EditMode, RollYear, GeneralTaxType, LevyDescription, HomesteadCode : String; Days, ExemptionAmount : LongInt; TaxRate, TaxAmount : Double; end; implementation {$R *.DFM} uses DataAccessUnit, GlblCnst, Utilitys, WinUtils; {=========================================================================} Procedure Tdlg_ProrataNewDetail.FormShow(Sender: TObject); var Levy : String; begin _OpenTable(tb_LeviesToProrate, '', '', '', NoProcessingType, []); with tb_LeviesToProrate do while not EOF do begin Levy := FieldByName('GeneralTaxType').AsString + '|' + FieldByName('Description').AsString; If _Compare(cb_Levy.Items.IndexOf(Levy), -1, coEqual) then cb_Levy.Items.Add(Levy); Next; end; {while not EOF do} If _Compare(EditMode, emEdit, coEqual) then begin Caption := 'Edit the prorata detail.'; ed_RollYear.Text := RollYear; MakeNonDataAwareEditReadOnly(ed_RollYear, False, ''); cb_Levy.SetFocus; cb_Levy.ItemIndex := cb_Levy.Items.IndexOf(GeneralTaxType + '|' + LevyDescription); cb_HomesteadCode.ItemIndex := cb_HomesteadCode.Items.IndexOf(HomesteadCode); ed_Days.Text := IntToStr(Days); ed_TaxRate.Text := FormatFloat(ExtendedDecimalDisplay_BlankZero, TaxRate); ed_ExemptionAmount.Text := IntToStr(ExemptionAmount); ed_TaxAmount.Text := FormatFloat(DecimalEditDisplay, TaxAmount); end; {If _Compare(EditMode, emEdit, coEqual)} end; {FormShow} {================================================================} Procedure Tdlg_ProrataNewDetail.FormKeyPress( Sender: TObject; var Key: Char); begin If (Key = #13) then begin Perform(WM_NextDlgCtl, 0, 0); Key := #0; end; {If (Key = #13)} end; {FormKeyPress} {=========================================================================} Procedure Tdlg_ProrataNewDetail.ed_RollYearExit(Sender: TObject); begin cb_Levy.SetFocus; end; {=========================================================================} Procedure Tdlg_ProrataNewDetail.ed_ExemptionAmountExit(Sender: TObject); var TaxAmount, TaxRate : Double; CalculationDays, ExemptionAmount, Days : LongInt; begin try Days := StrToInt(ed_Days.Text); except Days := 0; end; try CalculationDays := StrToInt(ed_CalculationDays.Text); except CalculationDays := 0; end; try TaxRate := Roundoff(StrToFloat(ed_TaxRate.Text), 6); except TaxRate := 0; end; try ExemptionAmount := StrToInt(ed_ExemptionAmount.Text); except ExemptionAmount := 0; end; If _Compare(ed_TaxAmount.Text, coBlank) then begin TaxAmount := (ExemptionAmount / 100) * TaxRate * (Days / CalculationDays); ed_TaxAmount.Text := FormatFloat(DecimalEditDisplay, TaxAmount); end; end; {ed_ExemptionAmountExit} {=========================================================================} Procedure Tdlg_ProrataNewDetail.OKButtonClick(Sender: TObject); var Levy : String; begin RollYear := ed_RollYear.Text; Levy := cb_Levy.Items[cb_Levy.ItemIndex]; GeneralTaxType := Copy(Levy, 1, (Pos('|', Levy) - 1)); LevyDescription := Copy(Levy, (Pos('|', Levy) + 1), 200); HomesteadCode := cb_HomesteadCode.Text; try Days := StrToInt(ed_Days.Text); except Days := 0; end; try TaxRate := Roundoff(StrToFloat(ed_TaxRate.Text), 6); except TaxRate := 0; end; try ExemptionAmount := StrToInt(ed_ExemptionAmount.Text); except ExemptionAmount := 0; end; try TaxAmount := Roundoff(StrToFloat(ed_TaxAmount.Text), 2); except TaxAmount := 0; end; ModalResult := mrOK; end; {OKButtonClick} {================================================================} Procedure Tdlg_ProrataNewDetail.FormClose( Sender: TObject; var Action: TCloseAction); begin _CloseTablesForForm(Self); Action := caFree; end; end.
unit FormKiesTabSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, cxControls, cxInplaceContainer, cxTL, uBibExcel; type TfrmKiesTabsheet = class(TForm) cxtrlTabsheets: TcxTreeList; cxtrlTabsheetscxTreeListColumn1: TcxTreeListColumn; procedure cxtrlTabsheetsDblClick(Sender: TObject); private FExcelSheet: TExcelFunctions; FChosenSheet: String; procedure SetExcelSheet(const Value: TExcelFunctions); { Private declarations } public { Public declarations } property ExcelSheet: TExcelFunctions read FExcelSheet write SetExcelSheet; property ChosenSheet: String read FChosenSheet write FChosenSheet; end; function KiesTabsheet(aExcelSheet:TExcelFunctions):String; implementation {$R *.DFM} {----------------------------------------------------------------------------- Procedure: KiesTabsheet Author: Harry Date: 12-apr-2012 Arguments: aExcelSheet:TExcelFunctions Result: None -----------------------------------------------------------------------------} function KiesTabsheet(aExcelSheet:TExcelFunctions):String; begin result := ''; with TfrmKiesTabsheet.Create(nil) do begin try ExcelSheet := aExcelSheet; if ShowModal = mrOk then begin result := ChosenSheet; end; finally Free; end; end; end; { TfrmKiesTabsheet } {----------------------------------------------------------------------------- Procedure: SetExcelSheet Author: Harry Date: 12-apr-2012 Arguments: const Value: TExcelFunctions Result: None -----------------------------------------------------------------------------} procedure TfrmKiesTabsheet.SetExcelSheet(const Value: TExcelFunctions); var i:integer; begin FExcelSheet := Value; for i:=1 to FExcelSheet.ExcelApp.ActiveWorkbook.Worksheets.Count do begin with cxtrlTabsheets.Add do begin Values[0] := FExcelSheet.ExcelApp.ActiveWorkbook.Worksheets[i].Name; end; end; end; procedure TfrmKiesTabsheet.cxtrlTabsheetsDblClick(Sender: TObject); begin ChosenSheet := cxtrlTabsheets.FocusedNode.Texts[0]; ModalResult := mrOk; end; end.
unit uTInject.FrmConfigNetWork; {$I cef.inc} interface uses {$IFDEF DELPHI16_UP} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.ExtCtrls; {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin, ExtCtrls; {$ENDIF} type TFrmConfigNetWork = class(TForm) GroupBox1: TGroupBox; ProxyTypeCbx: TComboBox; ProxyTypeLbl: TLabel; ProxyServerLbl: TLabel; ProxyServerEdt: TEdit; ProxyPortLbl: TLabel; ProxyPortEdt: TEdit; ProxyUsernameLbl: TLabel; ProxyUsernameEdt: TEdit; ProxyPasswordLbl: TLabel; ProxyPasswordEdt: TEdit; ProxyScriptURLEdt: TEdit; ProxyScriptURLLbl: TLabel; ProxyByPassListEdt: TEdit; ProxyByPassListLbl: TLabel; GroupBox2: TGroupBox; HeaderNameEdt: TEdit; HeaderNameLbl: TLabel; HeaderValueEdt: TEdit; HeaderValueLbl: TLabel; ProxySchemeCb: TComboBox; MaxConnectionsPerProxyLbl: TLabel; MaxConnectionsPerProxyEdt: TSpinEdit; Panel1: TPanel; BntOk: TButton; BntCancel: TButton; PrtocolLbl: TLabel; procedure FormCreate(Sender: TObject); procedure BntOkClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmConfigNetWork: TFrmConfigNetWork; implementation {$R *.dfm} uses uTInject.Constant, uTInject.Diversos, uTInject.languages, System.UITypes; procedure TFrmConfigNetWork.BntOkClick(Sender: TObject); begin if MessageDlg(Text_FrmConfigNetWork_QuestionSave, mtConfirmation, [mbYes, mbNo], 0) <> mrYes then Begin ProxyTypeCbx.SetFocus; Exit; End; ModalResult := mrOk; end; procedure TFrmConfigNetWork.FormCreate(Sender: TObject); begin Caption := Text_FrmConfigNetWork_Caption; ProxyTypeLbl.Caption := Text_FrmConfigNetWork_ProxyTypeLbl ; ProxyServerLbl.Caption := Text_FrmConfigNetWork_ProxyServerLbl ; PrtocolLbl.Caption := Text_FrmConfigNetWork_PrtocolLbl; ProxyPortLbl.Caption := Text_FrmConfigNetWork_ProxyPortLbl ; ProxyUsernameLbl.Caption := Text_FrmConfigNetWork_ProxyUsernameLbl ; ProxyPasswordLbl.Caption := Text_FrmConfigNetWork_ProxyPasswordLbl ; ProxyScriptURLLbl.Caption := Text_FrmConfigNetWork_ProxyScriptURLLbl ; ProxyByPassListLbl.Caption := Text_FrmConfigNetWork_ProxyByPassListLbl ; GroupBox2.Caption := Text_FrmConfigNetWork_GroupBox2; HeaderNameLbl.Caption := Text_FrmConfigNetWork_HeaderNameLbl ; HeaderValueLbl.Caption := Text_FrmConfigNetWork_HeaderValueLbl ; MaxConnectionsPerProxyLbl.Caption := Text_FrmConfigNetWork_MaxConnectionsPerProxyLbl ; BntOk.Caption := Text_FrmConfigNetWork_BntOK; BntCancel.Caption := Text_FrmConfigNetWork_BntCancel; end; end.
Unit UnExportacaoDados; Interface Uses Classes, DBTables, Tabela, SysUtils, UnDados,SQLExpr, StdCtrls, ComCtrls, unVersoes, UnProdutos, UnDadosProduto, UnCotacao, UnNotaFiscal; //classe localiza Type TRBLocalizaExportacaoDados = class private public constructor cria; end; //classe funcoes Type TRBFuncoesExportacaoDados = class(TRBLocalizaExportacaoDados) private Pedido, Tabela, TabelaMatriz, PedidoMatriz, CadastroMatriz : TSQl; VprLabelQtd, VprLabelProcesso : TLabel; VprBarraProgresso : TProgressBar; procedure LocalizaClientesNaoExportados(VpaTabela : TSQL); procedure LocalizaPedidosNaoExportados(VpaTabela : TSQL); procedure LocalizaNotasNaoExportadas(VpaTabela : TSQL); procedure LocalizaContasaReceberNaoExportado(VpaTabela : TSQL); procedure LocalizaMovComissoesNaoExportado(VpaTabela : TSQL); procedure LocalizaMovOrcamento(VpaTabela : TSQl;VpaCodFilial,VpaLanOrcamento : Integer); procedure LocalizaMovServicoOrcamento(VpaTabela : TSQl;VpaCodFilial,VpaLanOrcamento : Integer); procedure LocalizaMovNotas(VpaTabela : TSQL;VpaCodFilial,VpaSeqNota : Integer); procedure LocalizaMovContasAReceber(VpaTabela : TSQL;VpaCodFilial, VpaLanReceber : Integer); procedure LocalizaMovServicoNota(VpaTabela : TSQL;VpaCodFilial,VpaSeqNota : Integer); procedure AtualizaProcesso(VpaDesProcesso : string); function ExisteClienteMatriz(VpaCodCliente : Integer; VpaNumCNPJ, VpaNUMCPF : string):string; function ExistePedidoMatriz(VpaCodFilial, VpaLanOrcamento : Integer) : string; function ExisteNotaMatriz(VpaCodFilial, VpaSeqNota : Integer):string; function ExisteContasaReceberMatriz(VpaCodFilial,VpaLanReceber : Integer) :string; function ExisteComissaoMatriz(VpaCodFilial, VpaLanComissao : Integer) : string; function ExportaMovOrcamento(VpaDExportacao : TRBDExportacaoDados;VpaCodFilial, VpaNumpedido :Integer):string; function ExportaMovServicoOrcamento(VpaDExportacao : TRBDExportacaoDados;VpaCodFilial, VpaNumpedido :Integer):string; function ExportaMovNotasFiscais(VpaDExportacao : TRBDExportacaoDados;VpaCodFilial, VpaSeqNota :Integer):string; function ExportaMovContasaReceber(VpaDExportacao : TRBDExportacaoDados;VpaCodFilial, VpaLanReceber :Integer):string; function ExportaMovNotasFiscaisServico(VpaDExportacao : TRBDExportacaoDados;VpaCodFilial, VpaSeqNota :Integer):string; public constructor cria(VpaBaseDados, VpaBaseDadosMatriz : TSQLConnection;VpaLabelProcesso, VpaLabelQtd : TLabel;VpaBarraProgresso : TProgressBar); function ExportaCliente(VpaDExportacao : TRBDExportacaoDados):string; function ExportaPedido(VpaDExportacao : TRBDExportacaoDados):string; function ExportaNotaFiscal(VpaDExportacao : TRBDExportacaoDados):string; function ExportaContasaReceber(VpaDExportacao : TRBDExportacaoDados):string; function ExportaComissao(VpaDExportacao : TRBDExportacaoDados):string; end; implementation Uses FunSql,constantes, APrincipal; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos da classe TRBLocalizaExportacaoDados )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {********************************* cria a classe ********************************} constructor TRBLocalizaExportacaoDados.cria; begin inherited create; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( eventos da classe TRBFuncoesExportacaoDados )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {********************************* cria a classe ********************************} procedure TRBFuncoesExportacaoDados.AtualizaProcesso(VpaDesProcesso: string); begin VprLabelProcesso.Caption := VpaDesProcesso; VprLabelProcesso.Refresh; end; {********************************************************************************} constructor TRBFuncoesExportacaoDados.cria(VpaBaseDados, VpaBaseDadosMatriz : TSQLConnection;VpaLabelProcesso, VpaLabelQtd : TLabel;VpaBarraProgresso : TProgressBar); begin inherited create; Tabela := TSQL.Create(nil); Tabela.ASQlConnection := VpaBaseDados; Pedido := TSQL.Create(nil); Pedido.ASQlConnection := VpaBaseDados; TabelaMatriz := TSQL.create(nil); TabelaMatriz.ASQlConnection := VpaBaseDadosMatriz; CadastroMatriz := TSQL.create(nil); CadastroMatriz.ASQlConnection := VpaBaseDadosMatriz; PedidoMatriz := TSQL.create(nil); PedidoMatriz.ASQlConnection := VpaBaseDadosMatriz; VprLabelQtd := VpaLabelQtd; VprLabelProcesso := VpaLabelProcesso; VprBarraProgresso := VpaBarraProgresso; end; {********************************************************************************} function TRBFuncoesExportacaoDados.ExisteClienteMatriz( VpaCodCliente: Integer; VpaNumCNPJ, VpaNUMCPF: string): string; var VpfFiltroCNPJCPF : string; begin VpfFiltroCNPJCPF := ''; if VpaNumCNPJ <> '' then VpfFiltroCNPJCPF := ' or C_CGC_CLI = '''+VpaNumCNPJ+'''' else if VpaNUMCPF <> '' then VpfFiltroCNPJCPF := ' or C_CPF_CLI = '''+VpaNumCPF+''''; AdicionaSQLAbreTabela(TabelaMatriz,'Select I_COD_CLI from CADCLIENTES ' + ' Where I_COD_CLI = '+IntToStr(VpaCodCliente) + VpfFiltroCNPJCPF); if not TabelaMatriz.Eof then begin if TabelaMatriz.FieldByName('I_COD_CLI').AsInteger = VpaCodCliente then result := 'CODIGO CLIENTE DUPLICADO. O código "'+IntToStr(VpaCodCliente)+'" já esta sendo utilizado na fábrica para outro cliente' else result := 'CLIENTE JA CADASTRADO NA FABRICA. Esse cliente já existe cadastrado na fábrica com o código "'+TabelaMatriz.FieldByName('I_COD_CLI').AsString+'"'; end; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExisteComissaoMatriz(VpaCodFilial, VpaLanComissao: Integer): string; begin result := ''; AdicionaSQLAbreTabela(TabelaMatriz,'Select I_EMP_FIL FROM MOVCOMISSOES ' + ' Where I_EMP_FIL = '+IntToStr(VpaCodFilial) + ' AND I_LAN_CON = ' +IntToStr(VpaLanComissao)); if not TabelaMatriz.Eof then result := 'COMISSÃO DUPLICADA NA FABRICA!!!Já existe digitado na fábrica uma comissão com o mesmo sequencial.'; TabelaMatriz.Close; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExisteContasaReceberMatriz(VpaCodFilial, VpaLanReceber: Integer): string; begin result := ''; AdicionaSQLAbreTabela(TabelaMatriz,'Select I_EMP_FIL FROM CADCONTASARECEBER ' + ' Where I_EMP_FIL = ' +IntToStr(VpaCodFilial)+ ' AND I_LAN_REC = ' +IntToStr(VpaLanReceber)); if not TabelaMatriz.Eof then result := 'CONTAS A RECEBER DUPLICADO NA FABRICA!!!Ja existe digitado na fabrica um contas a receber com o mesmo sequencial'; TabelaMatriz.Close; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExisteNotaMatriz(VpaCodFilial, VpaSeqNota: Integer): string; begin result := ''; AdicionaSQLAbreTabela(TabelaMatriz,'Select I_EMP_FIL FROM CADNOTAFISCAIS ' + ' Where I_EMP_FIL = ' +IntToStr(VpaCodFilial)+ ' AND I_SEQ_NOT = ' +IntToStr(VpaSeqNota)); if not TabelaMatriz.Eof then result := 'NOTA FISCAL DUPLICADA NA FABRICA!!!Ja existe digitado na fabrica uma nota fiscal com o mesmo sequencial'; TabelaMatriz.Close; end; {********************************************************************************} function TRBFuncoesExportacaoDados.ExistePedidoMatriz(VpaCodFilial, VpaLanOrcamento: Integer): string; begin result := ''; AdicionaSQLAbreTabela(TabelaMatriz,'Select I_EMP_FIL from CADORCAMENTOS ' + ' Where I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' AND I_LAN_ORC = '+IntToStr(VpaLanOrcamento)); if not TabelaMatriz.eof then result := 'PEDIDO DUPLICADO NA FÁBRICA!!!Ja existe digitado na fabrica um pedido com o mesmo numero'; TabelaMatriz.Close; end; {********************************************************************************} function TRBFuncoesExportacaoDados.ExportaCliente(VpaDExportacao: TRBDExportacaoDados): string; Var VpfResultado : string; VpfLacoCampos : Integer; begin result := ''; VpfResultado := ''; LocalizaClientesnaoExportados(Tabela); VprBarraProgresso.Position := 0; VprBarraProgresso.Max := Tabela.RecordCount; AdicionaSQLAbreTabela(CadastroMatriz,'Select * from CADCLIENTES ' + ' Where I_COD_CLI = 0 '); while not Tabela.Eof do begin AtualizaProcesso('Verificando se o clientes existe cadastrado na Matriz'); VpfResultado := ExisteClienteMatriz(Tabela.FieldByName('I_COD_CLI').AsInteger,Tabela.FieldByName('C_CGC_CLI').AsString,Tabela.FieldByName('C_CPF_CLI').AsString); if VpfResultado = '' then begin AtualizaProcesso('Exportando dados do cliente'); CadastroMatriz.Insert; for VpfLacoCampos := 0 to Tabela.FieldCount - 1 do CadastroMatriz.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value := Tabela.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value; CadastroMatriz.FieldByName('C_FLA_EXP').AsString := 'S'; CadastroMatriz.FieldByName('D_DAT_ALT').AsDateTime := VpaDExportacao.DatExportacao; CadastroMatriz.FieldByName('D_DAT_EXP').AsDateTime := VpaDExportacao.DatExportacao; CadastroMatriz.Post; VpfResultado := CadastroMatriz.AMensagemErroGravacao; end; if VpfResultado <> '' then begin VpaDExportacao.AddErroExportacao('CLIENTES',Tabela.FieldByName('I_COD_CLI').AsString,VpfResultado); VpaDExportacao.ClientesNaoExportados.Add(Tabela.FieldByName('I_COD_CLI').AsString); end; if VpfResultado = '' then begin Tabela.Edit; Tabela.FieldByName('C_FLA_EXP').AsString := 'S'; Tabela.Post; VpaDExportacao.ClientesExportados.Add(Tabela.FieldByName('I_COD_CLI').AsString); end; VprBarraProgresso.Position := VprBarraProgresso.Position + 1; Tabela.Next; end; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExportaComissao(VpaDExportacao: TRBDExportacaoDados): string; Var VpfLacoCampos : Integer; VpfTransacao : TTransactionDesc; begin result := ''; LocalizaMovComissoesNaoExportado(Pedido); VprBarraProgresso.Position := 0; VprBarraProgresso.Max := Pedido.RecordCount; AdicionaSQLAbreTabela(PedidoMatriz,'Select * from MOVCOMISSOES ' + ' Where I_EMP_FIL = 0 AND I_LAN_CON = 0'); while not Pedido.Eof do begin VpfTransacao.IsolationLevel :=xilDIRTYREAD; FPrincipal.BaseDadosMatriz.StartTransaction(vpfTransacao); AtualizaProcesso('Verificando se o numero da comisão existe na Matriz'); result := ExisteComissaoMatriz(Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_LAN_CON').AsInteger); if result = '' then begin AtualizaProcesso('Verificando se o contas a receber da comisão existe na Matriz'); result := ExisteContasaReceberMatriz(Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_LAN_REC').AsInteger); //se o result vir preenchido é porque existe o contas a receber exportado. if result = '' then result := 'CONTAS A RECEBER DA COMISSÃO NÃO EXPORTADO PARA A FABRICA!!!O contas a receber dessa comissão não foi exportado para a fabrica' else result := ''; end; if result = '' then begin AtualizaProcesso('Exportando dados da comissão '+IntToStr(Pedido.FieldByName('I_LAN_CON').AsInteger)); PedidoMatriz.Insert; for VpfLacoCampos := 0 to Pedido.FieldCount - 1 do PedidoMatriz.FieldByName(Pedido.Fields[VpfLacoCampos].DisplayName).Value := Pedido.FieldByName(Pedido.Fields[VpfLacoCampos].DisplayName).Value; PedidoMatriz.FieldByName('C_FLA_EXP').AsString := 'S'; PedidoMatriz.FieldByName('D_ULT_ALT').AsDateTime := VpaDExportacao.DatExportacao; PedidoMatriz.FieldByName('D_DAT_EXP').AsDateTime := VpaDExportacao.DatExportacao; PedidoMatriz.Post; result := PedidoMatriz.AMensagemErroGravacao; end; if result <> '' then begin VpaDExportacao.AddErroExportacao('COMISSÃO',Pedido.FieldByName('I_EMP_FIL').AsString+'/'+Pedido.FieldByName('I_LAN_CON').AsString,result); end else if result = '' then begin FPrincipal.BaseDadosMatriz.Commit(VpfTransacao); Pedido.Edit; Pedido.FieldByName('C_FLA_EXP').AsString := 'S'; Pedido.Post; VpaDExportacao.ComissaoExportada.Add(Pedido.FieldByName('I_EMP_FIL').AsString+'/'+Pedido.FieldByName('I_LAN_CON').AsString); end else FPrincipal.BaseDadosMatriz.Rollback(VpfTransacao); VprBarraProgresso.Position := VprBarraProgresso.Position + 1; Pedido.Next; end; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExportaContasaReceber(VpaDExportacao: TRBDExportacaoDados): string; Var VpfResultado : string; VpfLacoCampos : Integer; VpfTransacao : TTransactionDesc; begin result := ''; VpfResultado := ''; LocalizaContasaReceberNaoExportado(Pedido); VprBarraProgresso.Position := 0; VprBarraProgresso.Max := Pedido.RecordCount; AdicionaSQLAbreTabela(PedidoMatriz,'Select * from CADCONTASARECEBER ' + ' Where I_EMP_FIL = 0 AND I_LAN_REC = 0'); while not Pedido.Eof do begin VpfTransacao.IsolationLevel :=xilDIRTYREAD; FPrincipal.BaseDadosMatriz.StartTransaction(vpfTransacao); AtualizaProcesso('Verificando se o numero do contas a receber existe na Matriz'); VpfResultado := ExisteContasaReceberMatriz (Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_LAN_REC').AsInteger); if VpfResultado = '' then begin if VpaDExportacao.ClientesNaoExportados.IndexOf(Pedido.FieldByName('I_COD_CLI').AsString) >=0 then VpfResultado := 'Cliente referente a esse contas a receber nao exportado'; end; if VpfResultado = '' then begin AtualizaProcesso('Exportando dados do corpo do contas a receber '+IntToStr(Pedido.FieldByName('I_LAN_REC').AsInteger)); PedidoMatriz.Insert; for VpfLacoCampos := 0 to Pedido.FieldCount - 1 do PedidoMatriz.FieldByName(Pedido.Fields[VpfLacoCampos].DisplayName).Value := Pedido.FieldByName(Pedido.Fields[VpfLacoCampos].DisplayName).Value; PedidoMatriz.FieldByName('C_FLA_EXP').AsString := 'S'; PedidoMatriz.FieldByName('D_ULT_ALT').AsDateTime := VpaDExportacao.DatExportacao; PedidoMatriz.FieldByName('D_DAT_EXP').AsDateTime := VpaDExportacao.DatExportacao; PedidoMatriz.Post; VpfResultado := PedidoMatriz.AMensagemErroGravacao; end; if VpfResultado <> '' then begin VpaDExportacao.AddErroExportacao('CONTAS A RECEBER CORPO',Pedido.FieldByName('I_EMP_FIL').AsString+'/'+Pedido.FieldByName('I_LAN_REC').AsString,VpfResultado); end else begin VpfResultado := ExportaMovContasaReceber(VpaDExportacao,Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_LAN_REC').AsInteger); end; if VpfResultado = '' then begin FPrincipal.BaseDadosMatriz.Commit(VpfTransacao); Pedido.Edit; Pedido.FieldByName('C_FLA_EXP').AsString := 'S'; Pedido.Post; VpaDExportacao.ContasaReceberExportados.Add(Pedido.FieldByName('I_EMP_FIL').AsString+'/'+Pedido.FieldByName('I_LAN_REC').AsString); end else FPrincipal.BaseDadosMatriz.Rollback(VpfTransacao); VprBarraProgresso.Position := VprBarraProgresso.Position + 1; Pedido.Next; end; end; {********************************************************************************} function TRBFuncoesExportacaoDados.ExportaMovContasaReceber(VpaDExportacao: TRBDExportacaoDados; VpaCodFilial,VpaLanReceber: Integer): string; var VpfLacoCampos : Integer; begin result := ''; LocalizaMovContasAReceber(Tabela,VpaCodFilial,VpaLanReceber); AdicionaSQLAbreTabela(CadastroMatriz,'Select * from MOVCONTASARECEBER ' + ' Where I_EMP_FIL = 0 AND I_LAN_REC = 0 AND I_NRO_PAR = 0'); while not Tabela.Eof do begin AtualizaProcesso('Exportando a parcela "'+Tabela.FieldByName('I_NRO_PAR').AsString+'" do contas a receber "'+IntToStr(VpaLanReceber)+'"'); CadastroMatriz.Insert; for VpfLacoCampos := 0 to Tabela.FieldCount - 1 do CadastroMatriz.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value := Tabela.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value; CadastroMatriz.Post; result := CadastroMatriz.AMensagemErroGravacao; if result <> '' then begin VpaDExportacao.AddErroExportacao('CONTAS A RECEBER ITEM',TABELA.FieldByName('I_EMP_FIL').AsString+'/'+Tabela.FieldByName('I_LAN_REC').AsString+'/'+Tabela.FieldByName('I_NRO_PAR').AsString,result); exit; end; Tabela.Next; end; CadastroMatriz.Close; Tabela.Close; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExportaMovNotasFiscais(VpaDExportacao: TRBDExportacaoDados; VpaCodFilial,VpaSeqNota: Integer): string; Var VpfLacoCampos : Integer; begin result := ''; LocalizaMovNotas(Tabela,VpaCodFilial,VpaSeqNota); AdicionaSQLAbreTabela(CadastroMatriz,'Select * from MOVNOTASFISCAIS ' + ' Where I_EMP_FIL = 0 AND I_SEQ_NOT = 0 AND I_SEQ_MOV = 0'); while not Tabela.Eof do begin AtualizaProcesso('Exportando o produto "'+Tabela.FieldByName('C_COD_PRO').AsString+'" da nota "'+IntToStr(VpaSeqNota)+'"'); CadastroMatriz.Insert; for VpfLacoCampos := 0 to Tabela.FieldCount - 1 do CadastroMatriz.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value := Tabela.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value; CadastroMatriz.Post; result := CadastroMatriz.AMensagemErroGravacao; if result <> '' then begin VpaDExportacao.AddErroExportacao('NOTA FISCAL ITEM',TABELA.FieldByName('I_EMP_FIL').AsString+'/'+Tabela.FieldByName('I_SEQ_NOT').AsString+'/'+Tabela.FieldByName('I_SEQ_MOV').AsString,result); exit; end; Tabela.Next; end; CadastroMatriz.Close; Tabela.Close; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExportaMovNotasFiscaisServico(VpaDExportacao: TRBDExportacaoDados; VpaCodFilial,VpaSeqNota: Integer): string; Var VpfLacoCampos : Integer; begin result := ''; LocalizaMovServicoNota(Tabela,VpaCodFilial,VpaSeqNota); AdicionaSQLAbreTabela(CadastroMatriz,'Select * from MOVSERVICONOTA ' + ' Where I_EMP_FIL = 0 AND I_SEQ_NOT = 0 AND I_SEQ_MOV = 0'); while not Tabela.Eof do begin AtualizaProcesso('Exportando o servico "'+Tabela.FieldByName('I_COD_SER').AsString+'" da nota "'+IntToStr(VpaSeqNota)+'"'); CadastroMatriz.Insert; for VpfLacoCampos := 0 to Tabela.FieldCount - 1 do CadastroMatriz.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value := Tabela.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value; CadastroMatriz.Post; result := CadastroMatriz.AMensagemErroGravacao; if result <> '' then begin VpaDExportacao.AddErroExportacao('NOTA FISCAL SERVICO',TABELA.FieldByName('I_EMP_FIL').AsString+'/'+Tabela.FieldByName('I_SEQ_NOT').AsString+'/'+Tabela.FieldByName('I_SEQ_MOV').AsString,result); exit; end; Tabela.Next; end; CadastroMatriz.Close; Tabela.Close; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExportaMovOrcamento(VpaDExportacao: TRBDExportacaoDados; VpaCodFilial,VpaNumpedido : Integer): string; Var VpfLacoCampos : Integer; begin result := ''; LocalizaMovOrcamento(Tabela,VpaCodFilial,VpaNumpedido); AdicionaSQLAbreTabela(CadastroMatriz,'Select * from MOVORCAMENTOS ' + ' Where I_EMP_FIL = 0 AND I_LAN_ORC = 0'); while not Tabela.Eof do begin AtualizaProcesso('Exportando o produto "'+Tabela.FieldByName('C_COD_PRO').AsString+'" do pedido "'+IntToStr(VpaNumpedido)+'"'); CadastroMatriz.Insert; for VpfLacoCampos := 0 to Tabela.FieldCount - 1 do CadastroMatriz.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value := Tabela.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value; CadastroMatriz.Post; result := CadastroMatriz.AMensagemErroGravacao; if result <> '' then begin VpaDExportacao.AddErroExportacao('PEDIDO ITEM',TABELA.FieldByName('I_EMP_FIL').AsString+'/'+Tabela.FieldByName('I_LAN_ORC').AsString+'/'+Tabela.FieldByName('I_SEQ_MOV').AsString,result); exit; end; Tabela.Next; end; CadastroMatriz.Close; Tabela.Close; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExportaMovServicoOrcamento(VpaDExportacao: TRBDExportacaoDados; VpaCodFilial,VpaNumpedido: Integer): string; Var VpfLacoCampos : Integer; begin result := ''; LocalizaMovServicoOrcamento(Tabela,VpaCodFilial,VpaNumpedido); AdicionaSQLAbreTabela(CadastroMatriz,'Select * from MOVSERVICOORCAMENTO ' + ' Where I_EMP_FIL = 0 AND I_LAN_ORC = 0 AND I_SEQ_MOV = 0'); while not Tabela.Eof do begin AtualizaProcesso('Exportando o serviço "'+Tabela.FieldByName('I_COD_SER').AsString+'" do pedido "'+IntToStr(VpaNumpedido)+'"'); CadastroMatriz.Insert; for VpfLacoCampos := 0 to Tabela.FieldCount - 1 do CadastroMatriz.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value := Tabela.FieldByName(Tabela.Fields[VpfLacoCampos].DisplayName).Value; CadastroMatriz.Post; result := CadastroMatriz.AMensagemErroGravacao; if result <> '' then begin VpaDExportacao.AddErroExportacao('SERVICO PEDIDO',TABELA.FieldByName('I_EMP_FIL').AsString+'/'+Tabela.FieldByName('I_LAN_ORC').AsString+'/'+Tabela.FieldByName('I_SEQ_MOV').AsString,result); exit; end; Tabela.Next; end; CadastroMatriz.Close; Tabela.Close; end; {******************************************************************************} function TRBFuncoesExportacaoDados.ExportaNotaFiscal(VpaDExportacao: TRBDExportacaoDados): string; Var VpfResultado : string; VpfLacoCampos : Integer; VpfTransacao : TTransactionDesc; VpfFunProdutosMatriz : TFuncoesProduto; VpfDNota : TRBDNotaFiscal; begin VpfFunProdutosMatriz := TFuncoesProduto.criar(nil,FPrincipal.BaseDadosMatriz); result := ''; VpfResultado := ''; LocalizaNotasNaoExportadas(Pedido); VprBarraProgresso.Position := 0; VprBarraProgresso.Max := Pedido.RecordCount; AdicionaSQLAbreTabela(PedidoMatriz,'Select * from CADNOTAFISCAIS ' + ' Where I_EMP_FIL = 0 AND I_SEQ_NOT = 0'); while not Pedido.Eof do begin VpfTransacao.IsolationLevel :=xilDIRTYREAD; FPrincipal.BaseDadosMatriz.StartTransaction(vpfTransacao); VpfDNota := TRBDNotaFiscal.cria; FunNotaFiscal.CarDNotaFiscal(VpfDNota,Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_SEQ_NOT').AsInteger); AtualizaProcesso('Verificando se o numero da nota existe digitado na Matriz'); VpfResultado := ExisteNotaMatriz (Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_SEQ_NOT').AsInteger); if VpfResultado = '' then begin if VpaDExportacao.ClientesNaoExportados.IndexOf(Pedido.FieldByName('I_COD_CLI').AsString) >=0 then VpfResultado := 'Cliente referente a essa nota nao exportado'; end; if VpfResultado = '' then begin AtualizaProcesso('Exportando dados do corpo da nota '+IntToStr(Pedido.FieldByName('I_NRO_NOT').AsInteger)); PedidoMatriz.Insert; for VpfLacoCampos := 0 to Pedido.FieldCount - 1 do PedidoMatriz.FieldByName(Pedido.Fields[VpfLacoCampos].DisplayName).Value := Pedido.FieldByName(Pedido.Fields[VpfLacoCampos].DisplayName).Value; PedidoMatriz.FieldByName('C_FLA_EXP').AsString := 'S'; PedidoMatriz.FieldByName('D_ULT_ALT').AsDateTime := VpaDExportacao.DatExportacao; PedidoMatriz.FieldByName('D_DAT_EXP').AsDateTime := VpaDExportacao.DatExportacao; PedidoMatriz.Post; VpfResultado := PedidoMatriz.AMensagemErroGravacao; end; if VpfResultado <> '' then begin VpaDExportacao.AddErroExportacao('NOTA FISCAL CORPO',Pedido.FieldByName('I_EMP_FIL').AsString+'/'+Pedido.FieldByName('I_SEQ_NOT').AsString,VpfResultado); end else begin VpfResultado := ExportaMovNotasFiscais(VpaDExportacao,Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_SEQ_NOT').AsInteger); if VpfResultado = '' then begin VpfResultado := ExportaMovNotasFiscaisServico(VpaDExportacao,Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_SEQ_NOT').AsInteger); if VpfResultado = '' then begin if (config.BaixarEstoqueECF) and (Pedido.FieldByName('C_NOT_CAN').AsString = 'N') then begin AtualizaProcesso('Atualizando estoque da nota '+Pedido.FieldByName('I_NRO_NOT').AsString); VpfResultado := FunNotaFiscal.BaixaEstoqueNota(VpfDNota,nil,VpfFunProdutosMatriz); end; end; end; end; if VpfResultado = '' then begin FPrincipal.BaseDadosMatriz.Commit(VpfTransacao); Pedido.Edit; Pedido.FieldByName('C_FLA_EXP').AsString := 'S'; Pedido.Post; VpaDExportacao.NotasExportadas.Add(Pedido.FieldByName('I_EMP_FIL').AsString+'/'+Pedido.FieldByName('I_NRO_NOT').AsString); end else FPrincipal.BaseDadosMatriz.Rollback(VpfTransacao); VprBarraProgresso.Position := VprBarraProgresso.Position + 1; VpfDNota.Free; Pedido.Next; end; VpfFunProdutosMatriz.Free; end; {********************************************************************************} function TRBFuncoesExportacaoDados.ExportaPedido(VpaDExportacao: TRBDExportacaoDados): string; Var VpfResultado : string; VpfLacoCampos : Integer; VpfTransacao : TTransactionDesc; VpfFunProdutosMatriz : TFuncoesProduto; VpfDCotacao : TRBDOrcamento; begin VpfFunProdutosMatriz := TFuncoesProduto.criar(nil,FPrincipal.BaseDadosMatriz); result := ''; VpfResultado := ''; LocalizaPedidosNaoExportados(Pedido); VprBarraProgresso.Position := 0; VprBarraProgresso.Max := Pedido.RecordCount; AdicionaSQLAbreTabela(PedidoMatriz,'Select * from CADORCAMENTOS ' + ' Where I_EMP_FIL = 0 AND I_LAN_ORC = 0'); while not Pedido.Eof do begin VpfDCotacao := TRBDOrcamento.cria; FunCotacao.CarDOrcamento(VpfDCotacao,Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_LAN_ORC').AsInteger); VpfTransacao.IsolationLevel :=xilDIRTYREAD; FPrincipal.BaseDadosMatriz.StartTransaction(vpfTransacao); AtualizaProcesso('Verificando se o numero do pedido existe digitado na Matriz'); VpfResultado := ExistePedidoMatriz (Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_LAN_ORC').AsInteger); if VpfResultado = '' then begin if VpaDExportacao.ClientesNaoExportados.IndexOf(Pedido.FieldByName('I_COD_CLI').AsString) >=0 then VpfResultado := 'Cliente referente ao pedido nao exportado'; end; if VpfResultado = '' then begin AtualizaProcesso('Exportando dados do corpo do pedido '+IntToStr(VpfDCotacao.LanOrcamento)); PedidoMatriz.Insert; for VpfLacoCampos := 0 to Pedido.FieldCount - 1 do PedidoMatriz.FieldByName(Pedido.Fields[VpfLacoCampos].DisplayName).Value := Pedido.FieldByName(Pedido.Fields[VpfLacoCampos].DisplayName).Value; PedidoMatriz.FieldByName('C_FLA_EXP').AsString := 'S'; PedidoMatriz.FieldByName('C_IND_IMP').AsString := 'N'; PedidoMatriz.FieldByName('D_ULT_ALT').AsDateTime := VpaDExportacao.DatExportacao; PedidoMatriz.FieldByName('D_DAT_EXP').AsDateTime := VpaDExportacao.DatExportacao; PedidoMatriz.Post; VpfResultado := PedidoMatriz.AMensagemErroGravacao; end; if VpfResultado <> '' then begin VpaDExportacao.AddErroExportacao('PEDIDO CORPO',Pedido.FieldByName('I_EMP_FIL').AsString+'/'+Pedido.FieldByName('I_LAN_ORC').AsString,VpfResultado); end else begin VpfResultado := ExportaMovOrcamento(VpaDExportacao,Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_LAN_ORC').AsInteger); if VpfResultado = '' then begin VpfResultado := ExportaMovServicoOrcamento(VpaDExportacao,Pedido.FieldByName('I_EMP_FIL').AsInteger,Pedido.FieldByName('I_LAN_ORC').AsInteger); if VpfResultado = '' then begin { if config.BaixarEstoqueCotacao then begin AtualizaProcesso('Atualizando estoque do pedido '+IntToStr(VpfDCotacao.LanOrcamento)); VpfResultado := FunCotacao.GeraEstoqueProdutos(VpfDCotacao,VpfFunProdutosMatriz); end;} end; end; end; if VpfResultado = '' then begin FPrincipal.BaseDadosMatriz.Commit(VpfTransacao); Pedido.Edit; Pedido.FieldByName('C_FLA_EXP').AsString := 'S'; Pedido.Post; VpaDExportacao.PedidosExportados.Add(Pedido.FieldByName('I_EMP_FIL').AsString+'/'+Pedido.FieldByName('I_LAN_ORC').AsString); end else FPrincipal.BaseDadosMatriz.Rollback(VpfTransacao); VprBarraProgresso.Position := VprBarraProgresso.Position + 1; VpfDCotacao.Free; Pedido.Next; end; VpfFunProdutosMatriz.Free; end; {********************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaClientesnaoExportados(VpaTabela: TSQL); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from CADCLIENTES ' + ' Where C_FLA_EXP = ''N'''); end; {******************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaContasaReceberNaoExportado(VpaTabela: TSQL); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from CADCONTASARECEBER ' + ' Where C_FLA_EXP = ''N'''+ ' ORDER BY I_EMP_FIL, I_LAN_REC'); end; {********************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaMovComissoesNaoExportado(VpaTabela: TSQL); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from MOVCOMISSOES ' + ' Where C_FLA_EXP = ''N''' + ' ORDER BY I_EMP_FIL, I_LAN_CON'); end; {******************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaMovContasAReceber(VpaTabela: TSQL; VpaCodFilial, VpaLanReceber : Integer); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from MOVCONTASARECEBER ' + ' Where I_EMP_FIL = ' + IntToStr(VpaCodFilial)+ ' and I_LAN_REC = ' + IntToStr(VpaLanReceber)+ ' order by I_NRO_PAR '); end; {******************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaMovNotas(VpaTabela: TSQL; VpaCodFilial, VpaSeqNota: Integer); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from MOVNOTASFISCAIS ' + ' Where I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' AND I_SEQ_NOT = '+IntToStr(VpaSeqNota)+ ' ORDER BY I_SEQ_MOV'); end; {******************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaMovOrcamento(VpaTabela: TSQl; VpaCodFilial, VpaLanOrcamento: Integer); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from MOVORCAMENTOS '+ ' WHERE I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' AND I_LAN_ORC = '+IntToStr(VpaLanOrcamento)+ ' ORDER BY I_SEQ_MOV' ); end; {******************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaMovServicoNota(VpaTabela: TSQL; VpaCodFilial, VpaSeqNota: Integer); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from MOVSERVICONOTA ' + ' Where I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' AND I_SEQ_NOT = '+IntToStr(VpaSeqNota)+ ' ORDER BY I_SEQ_MOV'); end; {******************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaMovServicoOrcamento(VpaTabela: TSQl; VpaCodFilial,VpaLanOrcamento: Integer); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from MOVSERVICOORCAMENTO '+ ' WHERE I_EMP_FIL = '+IntToStr(VpaCodFilial)+ ' AND I_LAN_ORC = '+IntToStr(VpaLanOrcamento)+ ' ORDER BY I_SEQ_MOV' ); end; {******************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaNotasNaoExportadas(VpaTabela: TSQL); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from CADNOTAFISCAIS ' + ' Where C_FLA_EXP = ''N''' + ' ORDER BY I_NRO_NOT '); end; {********************************************************************************} procedure TRBFuncoesExportacaoDados.LocalizaPedidosNaoExportados(VpaTabela: TSQL); begin AdicionaSQLAbreTabela(VpaTabela,'Select * from CADORCAMENTOS ' + ' Where C_FLA_EXP = ''N'''+ ' ORDER BY I_LAN_ORC '); end; end.
unit sarray_of_proc_1; interface implementation type TProc = procedure; var A: array [3] of TProc; G: Int32; procedure IncG; begin Inc(G); end; procedure Test; begin A[0] := IncG; A[1] := IncG; A[2] := IncG; A[0](); A[1](); A[2](); end; initialization Test(); finalization Assert(G = 3); end.
unit mTemplateFieldButton; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, uDlgComponents, VA508AccessibilityManager; type TfraTemplateFieldButton = class(TFrame, ICPRSDialogComponent) pnlBtn: TPanel; lblText: TLabel; pbFocus: TPaintBox; procedure pnlBtnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure pnlBtnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FrameEnter(Sender: TObject); procedure FrameExit(Sender: TObject); procedure pbFocusPaint(Sender: TObject); private FCPRSDialogData: ICPRSDialogComponent; FBtnDown: boolean; FItems: TStringList; FOnChange: TNotifyEvent; procedure ButtonKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ButtonKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); function GetButtonText: string; procedure SetButtonText(const Value: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ButtonText: string read GetButtonText write SetButtonText; property Items: TStringList read FItems; property OnChange: TNotifyEvent read FOnChange write FOnChange; property CPRSDialogData: ICPRSDialogComponent read FCPRSDialogData implements ICPRSDialogComponent; end; implementation {$R *.DFM} uses ORFn, VA508AccessibilityRouter, VAUtils; procedure TfraTemplateFieldButton.pnlBtnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var txt: string; i, idx: integer; begin if(not FBtnDown) then begin FBtnDown := TRUE; pnlBtn.BevelOuter := bvLowered; if(FItems.Count > 0) then begin txt := ButtonText; idx := FItems.Count-1; for i := 0 to FItems.Count-1 do begin if(txt = FItems[i]) then begin idx := i; break; end; end; inc(idx); if(idx >= FItems.Count) then idx := 0; ButtonText := FItems[idx]; if ScreenReaderSystemActive then begin txt := FItems[idx]; if Trim(txt) = '' then txt := 'blank'; GetScreenReader.Speak(txt); end; if assigned(FOnChange) then FOnChange(Self); end; SetFocus; end; end; procedure TfraTemplateFieldButton.pnlBtnMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if(FBtnDown) then begin FBtnDown := FALSE; pnlBtn.BevelOuter := bvRaised; end; end; type TWinControlFriend = class(TWinControl); procedure TfraTemplateFieldButton.FrameEnter(Sender: TObject); begin pbFocus.Invalidate; end; procedure TfraTemplateFieldButton.FrameExit(Sender: TObject); begin pbFocus.Invalidate; end; constructor TfraTemplateFieldButton.Create(AOwner: TComponent); begin inherited Create(AOwner); TabStop := TRUE; FItems := TStringList.Create; OnKeyDown := ButtonKeyDown; OnKeyUp := ButtonKeyUp; Font.Size := MainFontSize; FCPRSDialogData := TCPRSDialogComponent.Create(Self, 'multi value button'); end; procedure TfraTemplateFieldButton.ButtonKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_SPACE then pnlBtnMouseDown(Sender, mbLeft, [], 0, 0); end; procedure TfraTemplateFieldButton.ButtonKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin pnlBtnMouseUp(Sender, mbLeft, [], 0, 0); end; function TfraTemplateFieldButton.GetButtonText: string; begin Result := lblText.Caption; end; procedure TfraTemplateFieldButton.SetButtonText(const Value: string); begin lblText.Caption := Value; end; procedure TfraTemplateFieldButton.pbFocusPaint(Sender: TObject); var R: TRect; begin if(Focused) then begin R := Rect(1, 0, pnlBtn.Width - 3, pnlBtn.Height-2); pbFocus.Canvas.DrawFocusRect(R); end; end; destructor TfraTemplateFieldButton.Destroy; begin FItems.Free; FCPRSDialogData := nil; inherited; end; initialization SpecifyFormIsNotADialog(TfraTemplateFieldButton); end.
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ######### NOTICE: this comes from the SlavaNap source code. ########### Copyright 2001,2002 by SlavaNap development team Released under GNU General Public License Latest version is available at http://www.slavanap.org ********************************************************** Unit: class_cmdlist TNapCmd and TNapCmdList declarations *********************************************************} unit class_cmdlist; interface uses Windows, Classes2, SysUtils; type TNapCmd = record id : Integer; cmd : String; end; PNapCmd = ^TNapCmd; TNapCmdList = class(TMyList) function Add(Value: TNapCmd):Integer; procedure Insert(Index:Integer; Value: TNapCmd); procedure Clear; override; procedure Delete(Index: Integer); function AddCmd(id: Integer; cmd:String): Integer; function Cmd(index: Integer): TNapCmd; function Id(index: Integer): Integer; function Str(index: Integer): String; function FindByCmd(cmd: String; ignore_case: Boolean): Integer; function FindById(id: Integer): Integer; function FindItem(id: Integer; cmd: String): Integer; constructor Create; destructor Destroy; override; function GetLength: Integer; end; function CreateCmdList: TNapCmdList; implementation function CreateCmdList: TNapCmdList; begin Result:=TNapCmdList.Create; end; function CreateItem: PNapCmd; var data: PNapCmd; begin data:=AllocMem(sizeof(TNapCmd)); Pointer(data^.cmd):=nil; Result:=data; end; procedure FreeItem(item: PNapCmd); begin if Pointer(item^.cmd)<>nil then SetLength(item^.cmd,0); Finalize(item^); FreeMem(item,sizeof(TNapCmd)); end; procedure DeleteItem(item: PNapCmd); begin if Pointer(item^.cmd)<>nil then SetLength(item^.cmd,0); FreeItem(item); end; {* * * * * TNapCmdList * * * * *} function TNapCmdList.Add(Value: TNapCmd):Integer; var data:PNapCmd; begin data:=CreateItem; with data^ do begin cmd:=Value.cmd; id:=Value.id; end; Result:=inherited Add(data); end; procedure TNapCmdList.Insert(Index:Integer; Value: TNapCmd); var data:PNapCmd; begin data:=CreateItem; with data^ do begin cmd:=Value.cmd; id:=Value.id; end; inherited Insert(Index,data); end; procedure TNapCmdList.Clear; begin while count>0 do Delete(count-1); inherited Clear; end; procedure TNapCmdList.Delete(Index: Integer); begin if (Index<0) or (Index>=Count) then exit; if Items[Index]<>nil then DeleteItem(Items[Index]); Inherited Delete(index); end; function TNapCmdList.AddCmd(id: Integer; cmd:String): Integer; var data:TNapCmd; begin data.id:=id; data.cmd:=cmd; Result:=Add(data); end; function TNapCmdList.Cmd(index :Integer): TNapCmd; var data:TNapCmd; begin if (index>=0) and (index<count) then begin Result:=TNapCmd(Items[index]^); exit; end; data.id:=-1; data.cmd:=''; Result:=data; end; function TNapCmdList.Id(index: Integer): Integer; var data:PNapCmd; begin if (index>=0) and (index<count) then begin data:=PNapCmd(Items[index]); Result:=data^.id; exit; end; Result:=-1; end; function TNapCmdList.Str(index: Integer): String; var data:PNapCmd; begin if (index>=0) and (index<count) then begin data:=PNapCmd(Items[index]); Result:=data^.cmd; exit; end; Result:=''; end; function TNapCmdList.FindByCmd(cmd: String; ignore_case: Boolean): Integer; var i, len: Integer; begin len:=Length(cmd); if ignore_case then begin cmd:=lowercase(cmd); for i:=0 to count-1 do if Length(PNapCmd(Items[i])^.cmd)=len then if lowercase(PNapCmd(Items[i])^.cmd)=cmd then begin Result:=i; exit; end; Result:=-1; exit; end; for i:=0 to count-1 do if Length(PNapCmd(Items[i])^.cmd)=len then if PNapCmd(Items[i]).cmd=cmd then begin Result:=i; exit; end; Result:=-1; end; function TNapCmdList.FindById(id: Integer): Integer; var i: Integer; begin for i:=0 to count-1 do if PNapCmd(Items[i]).id=id then begin Result:=i; exit; end; Result:=-1; end; function TNapCmdList.FindItem(id: Integer; cmd: String): Integer; var i, len: Integer; begin len:=Length(cmd); for i:=0 to count-1 do if PNapCmd(Items[i])^.id=id then if Length(PNapCmd(Items[i])^.cmd)=len then if PNapCmd(Items[i]).cmd=cmd then begin Result:=i; exit; end; Result:=-1; end; constructor TNapCmdList.Create; begin inherited Create; end; destructor TNapCmdList.Destroy; begin Clear; inherited Destroy; end; function TNapCmdList.GetLength: Integer; var i,j: Integer; begin j:=0; for i:=0 to count-1 do inc(j,Length(PNapCmd(Items[i]).cmd)); Result:=j; end; end.
program carremagique; uses crt; (*BUT: cree un carre magique ENTREE: debut du carre magique SORTIE: le carre magique fini const n=5 //valeur maximum du tableau var carre=tableau[1..n,1..n] de entier i,j,nombre:entier procedure crea //creation du carre var i,j: entier debut debut pour i<-1 a n faire debut pour j<-1 a n faire carre[i,j]<-0 fin ecrire fin fin procedure placement //placement des nombre var i,j,T:entier debut j<- (n div 2) +1 i<-2 T<-0 fin procedure deplacement //deplacement des nombre var i,j,T,ancj,anci:integer debut repeter inc (T) carre[i,j]<-T ancj<-j dec (j) SI (j<1) alors j<-n anci<-i dec (i) SI (i<1) alors i<-n SI carre[i,j]<>0 alors debut i<-anci-1 SI i>n alors i<-1 j<-ancj finsi fin jusqu'a T=n*n fin fin debut car pour i<-1 a n faire debut pour j<-1 a n faire ecrire (carre[i,j]:5) ecrire fin lire fin *) const n=5; var cell:array[1..n,1..n] of integer; i,j,sum:integer; procedure car; var i,j,count,ancj,anci:integer; begin clrscr; begin begin for i:=1 to n do begin for j:=1 to n do cell[i,j]:=0; end; end; j:=(n div 2) +1; i:=2; count:=0; repeat inc(count); cell[i,j]:=count; ancj:=j; dec (j); if (j<1) then j:=n; anci:=i; dec (i); if (i<1) then i:=n; if cell[i,j]<>0 then begin i:=anci-1; if i>n then i:=1; j:=ancj; end; until count=n*n; end; end; begin car; for i:=1 to n do begin for j:=1 to n do write(cell[i,j]:5); writeln; end; readln; end.
unit BaseFamilyQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CustomComponentsQuery, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, ApplyQueryFrame, Vcl.StdCtrls, SearchComponentCategoryQuery, SearchProductParameterValuesQuery, SearchCategoryQuery, SearchFamily, DSWrap; type TBaseFamilyW = class(TCustomComponentsW) private FExternalID: TFieldWrap; public constructor Create(AOwner: TComponent); override; property ExternalID: TFieldWrap read FExternalID; end; TQueryBaseFamily = class(TQueryCustomComponents) private FBaseFamilyW: TBaseFamilyW; FqSearchCategory: TQuerySearchCategory; FqSearchFamily: TQuerySearchFamily; FQuerySearchComponentCategory: TQuerySearchComponentCategory; procedure DoBeforeOpen(Sender: TObject); function GetCategoryExternalID: string; function GetqSearchCategory: TQuerySearchCategory; function GetqSearchFamily: TQuerySearchFamily; function GetQuerySearchComponentCategory: TQuerySearchComponentCategory; { Private declarations } protected procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override; procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override; function CreateDSWrap: TDSWrap; override; procedure UpdateCategory(AIDComponent: Integer; const ASubGroup: String); property qSearchCategory: TQuerySearchCategory read GetqSearchCategory; property qSearchFamily: TQuerySearchFamily read GetqSearchFamily; property QuerySearchComponentCategory: TQuerySearchComponentCategory read GetQuerySearchComponentCategory; public constructor Create(AOwner: TComponent); override; property CategoryExternalID: string read GetCategoryExternalID; { Public declarations } end; implementation uses DBRecordHolder, System.Generics.Collections, DefaultParameters, NotifyEvents; {$R *.dfm} { TfrmQueryComponents } constructor TQueryBaseFamily.Create(AOwner: TComponent); var S: String; begin inherited Create(AOwner); S := FDSWrap.ClassName; FBaseFamilyW := FDSWrap as TBaseFamilyW; TNotifyEventWrap.Create(W.BeforeOpen, DoBeforeOpen, W.EventList); end; procedure TQueryBaseFamily.ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); begin Assert(ASender = FDQuery); if W.ID.F.AsInteger > 0 then begin // Удаляем компонент из всех категорий UpdateCategory(W.ID.F.AsInteger, ''); // Удаляем сам компонент qProducts.DeleteRecord(W.PK.AsInteger); end; inherited; end; procedure TQueryBaseFamily.ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); var ARH: TRecordHolder; ASubGroup: TField; begin Assert(ASender = FDQuery); ARH := TRecordHolder.Create(ASender); try // Обновляем те поля, которые есть у компонента qProducts.UpdateRecord(ARH); finally FreeAndNil(ARH); end; // Обрабатываем обновление значений параметров W.UpdateParamValue(W.PKFieldName); ASubGroup := FDQuery.FindField('SubGroup'); // Если в запросе выбираются внешние коды категорий if ASubGroup <> nil then begin // Обновляем категории нашего компонента UpdateCategory(W.PK.AsInteger, ASubGroup.AsString); end; inherited; end; function TQueryBaseFamily.CreateDSWrap: TDSWrap; begin Result := TBaseFamilyW.Create(FDQuery); end; procedure TQueryBaseFamily.DoBeforeOpen(Sender: TObject); begin // Заполняем код параметра "Производитель" FDQuery.ParamByName('ProducerParamSubParamID').AsInteger := TDefaultParameters.ProducerParamSubParamID; FDQuery.ParamByName('PackagePinsParamSubParamID').AsInteger := TDefaultParameters.PackagePinsParamSubParamID; FDQuery.ParamByName('DatasheetParamSubParamID').AsInteger := TDefaultParameters.DatasheetParamSubParamID; FDQuery.ParamByName('DiagramParamSubParamID').AsInteger := TDefaultParameters.DiagramParamSubParamID; FDQuery.ParamByName('DrawingParamSubParamID').AsInteger := TDefaultParameters.DrawingParamSubParamID; FDQuery.ParamByName('ImageParamSubParamID').AsInteger := TDefaultParameters.ImageParamSubParamID; end; function TQueryBaseFamily.GetCategoryExternalID: string; begin Assert(FDQuery.Active); if not FBaseFamilyW.ExternalID.F.AsString.IsEmpty then begin Result := FBaseFamilyW.ExternalID.F.AsString; Exit; end; Assert(not DetailParameterName.IsEmpty); qSearchCategory.SearchByID(FDQuery.ParamByName(DetailParameterName).AsInteger, 1); Result := qSearchCategory.W.ExternalID.F.AsString; end; function TQueryBaseFamily.GetqSearchCategory: TQuerySearchCategory; begin if FqSearchCategory = nil then FqSearchCategory := TQuerySearchCategory.Create(Self); Result := FqSearchCategory; end; function TQueryBaseFamily.GetqSearchFamily: TQuerySearchFamily; begin if FqSearchFamily = nil then FqSearchFamily := TQuerySearchFamily.Create(Self); Result := FqSearchFamily; end; function TQueryBaseFamily.GetQuerySearchComponentCategory : TQuerySearchComponentCategory; begin if FQuerySearchComponentCategory = nil then FQuerySearchComponentCategory := TQuerySearchComponentCategory.Create(Self); Result := FQuerySearchComponentCategory; end; procedure TQueryBaseFamily.UpdateCategory(AIDComponent: Integer; const ASubGroup: String); var rc: Integer; begin // Сначала удалим компонент из "лишних" категорий QuerySearchComponentCategory.SearchAndDelete(AIDComponent, ASubGroup); if not ASubGroup.IsEmpty then begin // Потом добавим компонент в нужные нам категории rc := qSearchCategory.SearchBySubgroup(ASubGroup); Assert(rc > 0); qSearchCategory.FDQuery.First; while not qSearchCategory.FDQuery.Eof do begin // Если компонент не находится в этой категории то добавляем его в эту категорию QuerySearchComponentCategory.LocateOrAddValue(AIDComponent, qSearchCategory.W.PK.Value); qSearchCategory.FDQuery.Next; end; end; end; constructor TBaseFamilyW.Create(AOwner: TComponent); begin inherited; FExternalID := TFieldWrap.Create(Self, 'ExternalID'); end; end.
unit ncaFrmConfig_EndLoja; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ncaFrmBaseOpcaoImgTxt, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.StdCtrls, cxButtons, cxLabel, dxGDIPlusClasses, Vcl.ExtCtrls, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDSimplePanel, ncaFrmMemoEnd; type TFrmConfig_EndLoja = class(TFrmBaseOpcaoImgTxt) panEnd: TLMDSimplePanel; lbPrompt: TcxLabel; procedure FormCreate(Sender: TObject); private FEnd : TFrmMemoEnd; { Private declarations } public { Public declarations } procedure Ler; override; procedure Salvar; override; function Alterou: Boolean; override; procedure Renumera; override; function NumItens: Integer; override; end; var FrmConfig_EndLoja: TFrmConfig_EndLoja; implementation {$R *.dfm} uses ncEndereco, ncClassesBase, ncaDM, ncGuidUtils; function TFrmConfig_EndLoja.Alterou: Boolean; begin Result := FEnd.DadosAnt.Alterou(FEnd.DadosAtu); end; procedure TFrmConfig_EndLoja.FormCreate(Sender: TObject); begin inherited; FEnd := TFrmMemoEnd.Create(Self); FEnd.EditOnClick := True; FEnd.MostrarRota := False; FEnd.M.Parent := panEnd; end; procedure TFrmConfig_EndLoja.Ler; begin inherited; if (gConfig.Endereco_Loja='') or (not Dados.AchaEnd(gConfig.End_Loja_Nativo)) then FEnd.Clear else FEnd.LoadFromDataset(Dados.tbEnd); end; function TFrmConfig_EndLoja.NumItens: Integer; begin Result := 1; end; procedure TFrmConfig_EndLoja.Renumera; begin inherited; RenumLB(lbPrompt, 0); end; procedure TFrmConfig_EndLoja.Salvar; begin inherited; with Dados do begin if AchaEnd(FEnd.DadosAtu.enID) then tbEnd.Edit else tbEnd.Append; FEnd.DadosAtu.SaveToDataset(tbEnd); tbEnd.Post; if gConfig.End_Loja_Nativo<>FEnd.DadosAtu.enID then gConfig.Endereco_Loja := TGuidEx.ToString(FEnd.DadosAtu.enID); end; end; end.
unit Form.Main; interface uses System.SysUtils, System.Variants, System.Classes, Winapi.Windows, Winapi.Messages, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ExtCtrls, Command.DiceRoll, Command.AsyncDiceRoll, Command.AsyncDiceRollExtra; type TForm1 = class(TForm) pnProgressBar: TPanel; ProgressBar1: TProgressBar; Memo1: TMemo; GroupBoxDiceRolls: TGroupBox; btnAsycDiceRollCmd: TButton; btnDiceRollCommand: TButton; Timer1: TTimer; btnAsycDiceRollCmdTwo: TButton; ProgressBar2: TProgressBar; ProgressBar3: TProgressBar; chkShowProgressPanel: TCheckBox; btnTermianteAllBackgroundJobs: TButton; lblProgress1: TLabel; lblProgress2: TLabel; lblProgress3: TLabel; procedure FormCreate(Sender: TObject); procedure btnAsycDiceRollCmdClick(Sender: TObject); procedure btnDiceRollCommandClick(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure btnAsycDiceRollCmdTwoClick(Sender: TObject); procedure chkShowProgressPanelClick(Sender: TObject); procedure btnTermianteAllBackgroundJobsClick(Sender: TObject); private fCommand: TDiceRollCommand; fAsyncCommand: TAsyncDiceRollCommand; fAsyncCommandEx: TAsyncDiceRollCommandEx; procedure DiceRoll_DoDisplayStepInfo; procedure DiceRoll_DoDisplaySummaryInfo; public end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := not(fCommand.IsBusy) and not(fAsyncCommand.IsBusy) and not(fAsyncCommandEx.IsBusy); if not CanClose then ShowMessage('Can''t close application - async command in progress'); end; procedure TForm1.FormCreate(Sender: TObject); begin Memo1.Clear; lblProgress1.Caption := ''; lblProgress2.Caption := ''; lblProgress3.Caption := ''; fCommand := TDiceRollCommand.Create(Self); fAsyncCommand := TAsyncDiceRollCommand.Create(Self); fAsyncCommandEx := TAsyncDiceRollCommandEx.Create(Self); ReportMemoryLeaksOnShutdown := True; end; procedure TForm1.chkShowProgressPanelClick(Sender: TObject); begin pnProgressBar.Visible := chkShowProgressPanel.Checked; end; procedure TForm1.Timer1Timer(Sender: TObject); begin btnDiceRollCommand.Enabled := not fCommand.IsBusy; btnAsycDiceRollCmd.Enabled := not fAsyncCommand.IsBusy; btnAsycDiceRollCmdTwo.Enabled := not fAsyncCommandEx.IsBusy; end; const NumberOfRolls: integer = 500; procedure TForm1.btnDiceRollCommandClick(Sender: TObject); begin fCommand.WithInjections([ProgressBar1, Memo1, lblProgress1, NumberOfRolls]).Execute; end; procedure TForm1.btnTermianteAllBackgroundJobsClick(Sender: TObject); begin fCommand.Terminate; fAsyncCommand.Terminate; fAsyncCommandEx.Terminate; end; procedure TForm1.btnAsycDiceRollCmdClick(Sender: TObject); begin fAsyncCommand.WithInjections([ProgressBar2, Memo1, lblProgress2, NumberOfRolls]).Execute; end; procedure TForm1.DiceRoll_DoDisplayStepInfo; begin ProgressBar3.Position := fAsyncCommandEx.Step; lblProgress3.Caption := Format('calculating %d/%d', [fAsyncCommandEx.Step, fAsyncCommandEx.RollsCount]); end; procedure TForm1.DiceRoll_DoDisplaySummaryInfo; var aDistribution: TArray<integer>; i: integer; begin aDistribution := fAsyncCommandEx.GetDistribution; Memo1.Lines.Add(Format('Elapsed time: %.1f seconds', [fAsyncCommandEx.GetElapsedTime.TotalSeconds])); Memo1.Lines.Add(Format('Dice results (%d-sided dice) (number of rolls: %d)', [fAsyncCommandEx.MaxDiceValue, fAsyncCommandEx.Step])); for i := 1 to High(aDistribution) do Memo1.Lines.Add(Format(' [%d] : %d', [i, aDistribution[i]])); end; procedure TForm1.btnAsycDiceRollCmdTwoClick(Sender: TObject); begin with fAsyncCommandEx do begin WithInjections([NumberOfRolls]); WithEventBeforeStart( procedure begin ProgressBar3.Position := 0; ProgressBar3.Max := fAsyncCommandEx.RollsCount; lblProgress3.Caption := ''; end); WithEventOnUpdate(DiceRoll_DoDisplayStepInfo); WithEventAfterFinish( procedure begin DiceRoll_DoDisplayStepInfo; DiceRoll_DoDisplaySummaryInfo; end); Execute; end; end; end.
unit Test.GBV; interface uses Windows, TestFrameWork, GMGlobals, GMBlockValues, Classes; type TGeomerBlockValuesForTest = class(TGeomerBlockValues) protected function NeedTrace(): bool; override; end; TGBVTest = class(TTestCase) private gbv: TGeomerBlockValues; TracePath: string; BlockExamplePath: string; protected procedure SetUp; override; procedure TearDown; override; published procedure Trace(); procedure StringForLog(); end; implementation uses Forms, DateUtils, SysUtils, GMConst; { TGBVTest } procedure TGBVTest.Trace(); var buf: array[0..100] of byte; i, fsize: int; fn: string; f: File; begin for i := 0 to 100 do buf[i] := 0; fn := TracePath + '0_0_1.gbv'; DeleteFile(fn); try gbv.ReadLongDataWithISCO(buf); Check(FileExists(fn), 'No File'); AssignFile(f, fn); Reset(f, 1); fsize := FileSize(f); CloseFile(f); Check(fsize = 90, 'FileSize ' + IntToStr(fsize) + ' <> 90'); finally DeleteFile(fn); end; end; procedure TGBVTest.SetUp; begin inherited; gbv := TGeomerBlockValuesForTest.Create(); TracePath := IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)) + 'trace\'; BlockExamplePath := IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName)) + 'examples\gbv\'; RemoveDir(TracePath); end; procedure TGBVTest.StringForLog; begin Check(gbv.ToString() <> 'TGeomerBlockValues'); end; procedure TGBVTest.TearDown; begin inherited; gbv.Free(); RemoveDir(TracePath); end; { TGeomerBlockValuesForTest } function TGeomerBlockValuesForTest.NeedTrace: bool; begin Result := true; end; initialization RegisterTest('GMIOPSrv/Classes/GBV', TGBVTest.Suite); end.
unit vr_promise; {$mode delphi}{$H+} {$I vrode.inc} interface uses Classes, SysUtils, vr_classes, Types, vr_utils, vr_fpclasses, vr_variant; type IPromise = interface; TVariantDynArray = array of IVariant; TPromiseResolveMethod = function(const AValue: IVariant; const AData: IVariant): IPromise of object; TPromiseResolveProc = function(const AValue: IVariant; const AData: IVariant): IPromise; TPromiseRejectMethod = function(const AReason: string; const AData: IVariant): IPromise of object; TPromiseRejectProc = function(const AReason: string; const AData: IVariant): IPromise; TPromiseFinallyProc = procedure(const AData: IVariant); TPromiseFinallyMethod = procedure(const AData: IVariant) of object; TPromiseState = ({psNone,} psPending, {psSealed,} psFulfilled, psRejected); { IPromise } IPromise = interface ['{B2303D03-5F01-4907-A80D-E39DC88767C3}'] function GetData: IVariant; function GetSettled: Boolean; function GetState: TPromiseState; function GetValue: IVariant; procedure SetData(const AValue: IVariant); function ThenP(const AOnFulfillment: TPromiseResolveProc; const AData: IVariant; const AOnRejection: TPromiseRejectProc = nil; const AInMainThread: Boolean = False): IPromise; function ThenM(const AOnFulfillment: TPromiseResolveMethod; const AData: IVariant; const AOnRejection: TPromiseRejectMethod = nil; const AInMainThread: Boolean = False): IPromise; function CatchP(const AOnRejection: TPromiseRejectProc; const AData: IVariant; const AInMainThread: Boolean = False): IPromise; function CatchM(const AOnRejection: TPromiseRejectMethod; const AData: IVariant; const AInMainThread: Boolean = False): IPromise; function FinallyP(const ACallbak: TPromiseFinallyProc; const AData: IVariant; const AInMainThread: Boolean = False): IPromise; function FinallyM(const ACallbak: TPromiseFinallyMethod; const AData: IVariant; const AInMainThread: Boolean = False): IPromise; function Wait(AWaitMSec: Cardinal = 3000): IVariant; property State: TPromiseState read GetState; property Settled: Boolean read GetSettled; property Value: IVariant read GetValue; property Data: IVariant read GetData write SetData; end; TResolverResolveMethod = procedure(const AValue: IVariant) of object; TResolverRejectMethod = procedure(const AReason: string) of object; TPromiseCreateProc = procedure(const AResolve: TResolverResolveMethod; const AData: IVariant; AReject: TResolverRejectMethod); TPromiseCreateMethod = procedure(const AResolve: TResolverResolveMethod; const AData: IVariant; AReject: TResolverRejectMethod) of object; //not overload to use Code Completion on AResolver (Ctrl+Shift+C) function PromiseP(const AResolver: TPromiseCreateProc; const AData: IVariant; const InMainThread: Boolean = False): IPromise; //overload; //inline; function PromiseM(const AResolver: TPromiseCreateMethod; const AData: IVariant; const InMainThread: Boolean = False): IPromise; //overload; //inline; type TPromiseDynArray = array of IPromise; TPromiseSettledInfo = record FullFilled: TVariantDynArray; Rejected: TStringDynArray; end; PPromiseSettledInfo = ^TPromiseSettledInfo; TPromiseSettledInfoArray = array of TPromiseSettledInfo; { TPromise } TPromise = class public class function New(const AData: IVariant): IPromise; class function Resolve(const AValue: IVariant): IPromise; class function Reject(const AReason: string): IPromise; class function DoChain(const APromise: IPromise; const ANewState: TPromiseState; const AValue: IVariant): IPromise; {* Wait for all promises to be resolved, or for any to be rejected. If the returned promise resolves, it is resolved with an aggregating array of the values from the resolved promises in the same order as defined in the iterable of multiple promises. If it rejects, it is rejected with the reason from the first promise in the iterable that was rejected. : IPromise.Value=IInterfaceList of IVariant *} class function All(const APromises: TPromiseDynArray): IPromise; {* Wait until all promises have settled (each may resolve, or reject). Returns a promise that resolves after all of the given promises have either resolved or rejected, with an array of objects that each describe the outcome of each promise. : Use PromiseSettledInfoFromVariant(IPromise.Value, Info) *} class function AllSettled(const APromises: TPromiseDynArray): IPromise; {* Wait until any of the promises is resolved or rejected. If the returned promise resolves, it is resolved with the value of the first promise in the iterable that resolved. If it rejects, it is rejected with the reason from the first promise that was rejected. *} class function Race(const APromises: TPromiseDynArray): IPromise; end; //use for IPromise.Value returned by TPromise.AllSettled function PromiseSettledInfoFromVariant(const v: IVariant): TPromiseSettledInfo; procedure PromiseSettledInfoToVariant(var v: IVariant; constref AInfo: TPromiseSettledInfo); implementation type TPromiseInternal = class; IPromiseInternal = interface ['{73497ABA-D609-4A0A-8699-ABA2A6E7DD7E}'] function GetPromise: TPromiseInternal; procedure Call(const APrevPromise: IPromise); end; { TPromiseInternal } TPromiseInternal = class(TInterfacedObject, IPromise, IPromiseInternal) private FData: IVariant; FState: TPromiseState; FLock: TRTLCriticalSection; FValue: IVariant; FThen: IPromise; function GetData: IVariant; function GetSettled: Boolean; function GetState: TPromiseState; function GetThenPromise: IPromise; function GetValue: IVariant; procedure SetData(const AValue: IVariant); procedure SetState(const AValue: TPromiseState); procedure SetThenPromise(const AValue: IPromise); procedure SetValue(const AValue: IVariant); protected function DoChain(const ANewState: TPromiseState; const AValue: IVariant): IPromise; property ThenPromise: IPromise read GetThenPromise write SetThenPromise; function ThenPromiseObject: TPromiseInternal; procedure DoCall(const {%H-}APrevPromise: TPromiseInternal); virtual; procedure ResolvePromise(const AValue: IVariant); procedure RejectPromise(const AReason: string); protected { IPromiseInternal } function GetPromise: TPromiseInternal; procedure Call(const APrevPromise: IPromise); public constructor Create(const AData: IVariant); virtual; destructor Destroy; override; procedure DoSettledLike(const APromise: TPromiseInternal); overload; procedure DoSettledLike(const APromise: IPromise); overload; { IPromise } function ThenP(const AOnFulfillment: TPromiseResolveProc; const AData: IVariant; const AOnRejection: TPromiseRejectProc; const AInMainThread: Boolean = False): IPromise; function ThenM(const AOnFulfillment: TPromiseResolveMethod; const AData: IVariant; const AOnRejection: TPromiseRejectMethod; const AInMainThread: Boolean = False): IPromise; function CatchP(const AOnRejection: TPromiseRejectProc; const AData: IVariant; const AInMainThread: Boolean = False): IPromise; function CatchM(const AOnRejection: TPromiseRejectMethod; const AData: IVariant; const AInMainThread: Boolean = False): IPromise; function FinallyP(const ACallbak: TPromiseFinallyProc; const AData: IVariant; const AInMainThread: Boolean = False): IPromise; function FinallyM(const ACallbak: TPromiseFinallyMethod; const AData: IVariant; const AInMainThread: Boolean = False): IPromise; function Wait(AWaitMSec: Cardinal = 3000): IVariant; property State: TPromiseState read GetState;// write SetState; property Settled: Boolean read GetSettled; property Value: IVariant read GetValue write SetValue; property Data: IVariant read GetData write SetData; end; { TPromiseResolver } TPromiseResolver = class(TPromiseInternal) private FResolverProc: TPromiseCreateProc; FResolverMethod: TPromiseCreateMethod; FInMainThread: Boolean; procedure Init(const AInMainThread: Boolean); private FSyncPromise: IPromise; procedure CallSync; procedure CallResolver; procedure OnExecuteThread(const Sender: TObject; const {%H-}AData: Pointer = nil); public constructor Create(const AResolver: TPromiseCreateProc; const AData: IVariant; const AInMainThread: Boolean = False); overload; constructor Create(const AResolver: TPromiseCreateMethod; const AData: IVariant; const AInMainThread: Boolean = False); overload; destructor Destroy; override; end; { TPromiseThen } TPromiseThen = class(TPromiseInternal) private FOnFulfillmentProc: TPromiseResolveProc; FOnRejectionProc: TPromiseRejectProc; FOnFulfillmentMethod: TPromiseResolveMethod; FOnRejectionMethod: TPromiseRejectMethod; FInMainThread: Boolean; FSyncValue: IVariant; FSyncResult: IPromise; procedure DoSyncResolve; procedure DoSyncReject; protected procedure DoCall(const APrevPromise: TPromiseInternal); override; public constructor Create(const AOnFulfillment: TPromiseResolveProc; const AData: IVariant; const AOnRejection: TPromiseRejectProc; const AInMainThread: Boolean = False); overload; constructor Create(const AOnFulfillment: TPromiseResolveMethod; const AData: IVariant; const AOnRejection: TPromiseRejectMethod; const AInMainThread: Boolean = False); overload; end; { TPromiseFinally } TPromiseFinally = class(TPromiseInternal) private FProc: TPromiseFinallyProc; FMethod: TPromiseFinallyMethod; FInMainThread: Boolean; procedure DoSyncCall; protected procedure DoCall(const APrevPromise: TPromiseInternal); override; public constructor Create(const ACallbak: TPromiseFinallyProc; const AData: IVariant; const AInMainThread: Boolean); overload; constructor Create(const ACallbak: TPromiseFinallyMethod; const AData: IVariant; const AInMainThread: Boolean); overload; end; TPromiseSettledVariant = TICustomVariant<TPromiseSettledInfo>; function PromiseSettledInfoFromVariant(const v: IVariant): TPromiseSettledInfo; var obj: TPromiseSettledVariant; begin if Supports(v, TPromiseSettledVariant, obj) then Result := obj.Data; end; procedure PromiseSettledInfoToVariant(var v: IVariant; constref AInfo: TPromiseSettledInfo); begin v := TPromiseSettledVariant.Create(AInfo); end; function PromiseP(const AResolver: TPromiseCreateProc; const AData: IVariant; const InMainThread: Boolean): IPromise; begin Result := TPromiseResolver.Create(AResolver, AData, InMainThread); end; function PromiseM(const AResolver: TPromiseCreateMethod; const AData: IVariant; const InMainThread: Boolean): IPromise; begin Result := TPromiseResolver.Create(AResolver, AData, InMainThread); end; { TPromiseFinally } procedure TPromiseFinally.DoSyncCall; begin try if Assigned(FProc) then FProc(FData) else if Assigned(FMethod) then FMethod(FData); except end; end; procedure TPromiseFinally.DoCall(const APrevPromise: TPromiseInternal); begin if FInMainThread and not IsMainThread then TThread.Synchronize(TThread.CurrentThread, DoSyncCall) else DoSyncCall; DoSettledLike(APrevPromise); end; constructor TPromiseFinally.Create(const ACallbak: TPromiseFinallyProc; const AData: IVariant; const AInMainThread: Boolean); begin Create(AData); FProc := ACallbak; FInMainThread := AInMainThread; end; constructor TPromiseFinally.Create(const ACallbak: TPromiseFinallyMethod; const AData: IVariant; const AInMainThread: Boolean); begin Create(AData); FMethod := ACallbak; FInMainThread := AInMainThread; end; { TPromiseThen } procedure TPromiseThen.DoSyncResolve; begin if Assigned(FOnFulfillmentProc) then FSyncResult := FOnFulfillmentProc(FSyncValue, FData) else if Assigned(FOnFulfillmentMethod) then FSyncResult := FOnFulfillmentMethod(FSyncValue, FData); end; procedure TPromiseThen.DoSyncReject; begin if Assigned(FOnRejectionProc) then FSyncResult := FOnRejectionProc(FSyncValue, FData) else if Assigned(FOnRejectionMethod) then FSyncResult := FOnRejectionMethod(FSyncValue, FData); end; procedure TPromiseThen.DoCall(const APrevPromise: TPromiseInternal); var sError: String; //vValue: IVariant; //Result: IPromise = nil; begin try FSyncResult := nil; FSyncValue := APrevPromise.Value; if APrevPromise.State = psRejected then begin if FInMainThread and not IsMainThread then TThread.Synchronize(TThread.CurrentThread, DoSyncReject) else DoSyncReject; end else if FInMainThread and not IsMainThread then TThread.Synchronize(TThread.CurrentThread, DoSyncResolve) else DoSyncResolve; //vValue := APrevPromise.Value; //if APrevPromise.State = psRejected then // begin // if Assigned(FOnRejectionProc) then // Result := FOnRejectionProc(vValue, FData) // else if Assigned(FOnRejectionMethod) then // Result := FOnRejectionMethod(vValue, FData); // end //else if Assigned(FOnFulfillmentProc) then // Result := FOnFulfillmentProc(vValue, FData) //else if Assigned(FOnFulfillmentMethod) then // Result := FOnFulfillmentMethod(vValue, FData); except on E: Exception do sError := E.Message; end; if FSyncResult = nil then FSyncResult := TPromise.Reject(IfThen(sError = '', 'Then handler return nil', sError)) else FSyncResult.Wait; DoSettledLike(FSyncResult); FSyncResult := nil; end; constructor TPromiseThen.Create(const AOnFulfillment: TPromiseResolveProc; const AData: IVariant; const AOnRejection: TPromiseRejectProc; const AInMainThread: Boolean); begin Create(AData); FOnFulfillmentProc := AOnFulfillment; FOnRejectionProc := AOnRejection; FInMainThread := AInMainThread; end; constructor TPromiseThen.Create(const AOnFulfillment: TPromiseResolveMethod; const AData: IVariant; const AOnRejection: TPromiseRejectMethod; const AInMainThread: Boolean); begin Create(AData); FOnFulfillmentMethod := AOnFulfillment; FOnRejectionMethod := AOnRejection; FInMainThread := AInMainThread; end; { TPromiseResolver } procedure TPromiseResolver.Init(const AInMainThread: Boolean); begin _AddRef;//in OnExecuteThread _Release FInMainThread := AInMainThread and (GetCurrentThreadId <> MainThreadID);// not IsMainThread(); if FInMainThread then OnExecuteThread(TThread.CurrentThread) else new_ThreadM(OnExecuteThread); end; constructor TPromiseResolver.Create(const AResolver: TPromiseCreateProc; const AData: IVariant; const AInMainThread: Boolean); begin Create(AData); FResolverProc := AResolver; Init(AInMainThread); end; constructor TPromiseResolver.Create(const AResolver: TPromiseCreateMethod; const AData: IVariant; const AInMainThread: Boolean); begin Create(AData); FResolverMethod := AResolver; Init(AInMainThread); end; destructor TPromiseResolver.Destroy; begin inherited Destroy; end; procedure TPromiseResolver.CallSync; var NextPromise: IPromise; begin NextPromise := (FSyncPromise as IPromiseInternal).GetPromise.FThen; if NextPromise <> nil then (NextPromise as IPromiseInternal).Call(FSyncPromise); end; procedure TPromiseResolver.CallResolver; begin if Assigned(FResolverProc) then FResolverProc(ResolvePromise, FData, RejectPromise) else if Assigned(FResolverMethod) then FResolverMethod(ResolvePromise, FData, RejectPromise); end; type TAccessThread = class(TThread) end; procedure TPromiseResolver.OnExecuteThread(const Sender: TObject; const AData: Pointer); var th: TAccessThread absolute Sender; //CurrPromise: TPromiseInternal; //NextPromise: TPromiseInternal = nil; CurrPromise, NextPromise: IPromise; begin try if FInMainThread then TThread.Synchronize(th, CallResolver) else CallResolver; if not Settled then begin //RejectPromise('Not settled'); _Release; Exit; end; CurrPromise := Self; NextPromise := FThen; while True do begin if NextPromise <> nil then begin if FInMainThread then begin FSyncPromise := CurrPromise; TThread.Synchronize(th, CallSync); end else (NextPromise as IPromiseInternal).Call(CurrPromise); CurrPromise := NextPromise; NextPromise := (NextPromise as IPromiseInternal).GetPromise.FThen; end else begin CurrPromise := nil; if frefcount = 1 then begin //th.Terminate; _Release;//in construnctor _AddRef Exit; end else Sleep(10); end; end; //CurrPromise := Self; //while True do // begin //ToDo ? merge with DoChain(); // if (NextPromise = nil) then // NextPromise := CurrPromise.ThenPromiseObject; // if NextPromise <> nil then // begin // NextPromise.DoCall(CurrPromise); // CurrPromise := NextPromise; // NextPromise := nil; // end // else if frefcount = 1 then // begin // //th.Terminate; // _Release;//in construnctor _AddRef // Exit; // end // else // Sleep(10); // end; except //on E: Exception do // RejectPromise(E.Message); end; end; { TPromise } class function TPromise.New(const AData: IVariant): IPromise; var Prom: TPromiseInternal; begin Result := TPromiseInternal.Create(nil); Prom := (Result as IPromiseInternal).GetPromise; Prom.Data := AData; end; class function TPromise.Resolve(const AValue: IVariant): IPromise; var Prom: TPromiseInternal; begin Result := TPromiseInternal.Create(nil); Prom := (Result as IPromiseInternal).GetPromise; Prom.FState := psFulfilled; Prom.FValue := AValue; end; class function TPromise.Reject(const AReason: string): IPromise; var Prom: TPromiseInternal; begin Result := TPromiseInternal.Create(nil); Prom := (Result as IPromiseInternal).GetPromise; Prom.FState := psRejected; Prom.FValue := AReason; end; class function TPromise.DoChain(const APromise: IPromise; const ANewState: TPromiseState; const AValue: IVariant): IPromise; begin Result := (APromise as IPromiseInternal).GetPromise.DoChain(ANewState, AValue); end; function _PromiseArrayToVariantList(const arr: TPromiseDynArray): IVariant; var i: Integer; lst: IInterfaceList; begin lst := TInterfaceList.Create; for i := 0 to Length(arr) - 1 do lst.Add(arr[i]); Result := lst; end; procedure _OnPromiseAll(const AResolve: TResolverResolveMethod; const AData: IVariant; AReject: TResolverRejectMethod); var lst: IInterfaceList; lstResult: IInterfaceList; i, Count: Integer; Prom: IPromise; vResult: IVariant; begin lst := IInterfaceList(AData.Intf); Count := lst.Count; lstResult := TInterfaceList.Create; for i := 0 to lst.Count - 1 do lstResult.Add(lst[i]); while True do begin if Count = 0 then Break; for i := 0 to lst.Count - 1 do if lstResult[i] = nil then begin Prom := IPromise(lst[i]); case Prom.State of psRejected: begin AReject(Prom.Value); Exit; end; psFulfilled: begin Dec(Count); lstResult[i] := Prom.Value; end; end; end; Sleep(10); end; vResult := lstResult; AResolve(vResult); end; class function TPromise.All(const APromises: TPromiseDynArray): IPromise; begin Result := PromiseP(_OnPromiseAll, _PromiseArrayToVariantList(APromises)); end; procedure _OnPromiseAllSettled(const AResolve: TResolverResolveMethod; const AData: IVariant; {%H-}AReject: TResolverRejectMethod); var lst: IInterfaceList; arrFlag: TBooleanDynArray; r: TPromiseSettledInfo; i, Count, n: Integer; Prom: IPromise; vResult: IVariant; begin lst := IInterfaceList(AData.Intf); Count := lst.Count; SetLength(arrFlag, Count); while True do begin if Count = 0 then Break; for i := 0 to lst.Count - 1 do if not arrFlag[i] then begin Prom := IPromise(lst[i]); case Prom.State of psRejected: begin arrFlag[i] := True; Dec(Count); n := Length({%H-}r.Rejected); SetLength(r.Rejected, n + 1); r.Rejected[n] := Prom.Value; end; psFulfilled: begin arrFlag[i] := True; Dec(Count); n := Length(r.FullFilled); SetLength(r.FullFilled, n + 1); r.FullFilled[n] := Prom.Value; end; end; end; Sleep(10); end; PromiseSettledInfoToVariant(vResult{%H-}, r); AResolve(vResult); end; class function TPromise.AllSettled(const APromises: TPromiseDynArray): IPromise; begin Result := PromiseP(_OnPromiseAllSettled, _PromiseArrayToVariantList(APromises)); end; procedure _OnPromiseRace(const AResolve: TResolverResolveMethod; const AData: IVariant; AReject: TResolverRejectMethod); var lst: IInterfaceList; Prom: IPromise; i: Integer; begin lst := IInterfaceList(AData.Intf); while True do begin for i := 0 to lst.Count - 1 do begin Prom := IPromise(lst[i]); case Prom.State of psRejected: begin AReject(Prom.Value); Exit; end; psFulfilled: begin AResolve(Prom.Value); Exit; end; end; end; Sleep(10); end; end; class function TPromise.Race(const APromises: TPromiseDynArray): IPromise; begin Result := PromiseP(_OnPromiseRace, _PromiseArrayToVariantList(APromises)); end; { TPromiseInternal } function TPromiseInternal.GetSettled: Boolean; begin EnterCriticalsection(FLock); try Result := FState in [psFulfilled, psRejected]; finally LeaveCriticalsection(FLock); end; end; function TPromiseInternal.GetData: IVariant; begin EnterCriticalsection(FLock); try Result := FData; finally LeaveCriticalsection(FLock); end; end; function TPromiseInternal.GetState: TPromiseState; begin EnterCriticalsection(FLock); try Result := FState; finally LeaveCriticalsection(FLock); end; end; function TPromiseInternal.GetThenPromise: IPromise; begin EnterCriticalsection(FLock); try Result := FThen; finally LeaveCriticalsection(FLock); end; end; function TPromiseInternal.GetValue: IVariant; begin EnterCriticalsection(FLock); try Result := FValue; finally LeaveCriticalsection(FLock); end; end; procedure TPromiseInternal.SetData(const AValue: IVariant); begin EnterCriticalsection(FLock); try FData := AValue; finally LeaveCriticalsection(FLock); end; end; procedure TPromiseInternal.SetThenPromise(const AValue: IPromise); begin EnterCriticalsection(FLock); try FThen := AValue; finally LeaveCriticalsection(FLock); end; end; procedure TPromiseInternal.SetValue(const AValue: IVariant); begin EnterCriticalsection(FLock); try FValue := AValue; finally LeaveCriticalsection(FLock); end; end; function TPromiseInternal.DoChain(const ANewState: TPromiseState; const AValue: IVariant): IPromise; var NextPromise: IPromise; begin Result := Self; if not Settled then begin if ANewState = psPending then Exit; SetState(ANewState); Value := AValue; end; NextPromise := FThen; while NextPromise <> nil do begin (NextPromise as IPromiseInternal).Call(Result); Result := NextPromise; if not Result.Settled then Exit; NextPromise := (NextPromise as IPromiseInternal).GetPromise.FThen; end; end; function TPromiseInternal.ThenPromiseObject: TPromiseInternal; begin EnterCriticalsection(FLock); try if FThen = nil then Result := nil else Result := (FThen as IPromiseInternal).GetPromise; finally LeaveCriticalsection(FLock); end; end; procedure TPromiseInternal.DoCall(const APrevPromise: TPromiseInternal); begin RejectPromise('Not implemented'); end; function TPromiseInternal.GetPromise: TPromiseInternal; begin Result := Self; end; procedure TPromiseInternal.Call(const APrevPromise: IPromise); begin DoCall((APrevPromise as IPromiseInternal).GetPromise); end; procedure TPromiseInternal.ResolvePromise(const AValue: IVariant); var Prom: IPromise; begin if Settled then Exit; if Supports(AValue.Intf, IPromise, Prom) and (Prom = IPromise(Self)) then raise Exception.Create('A promise cannot be resolved with itself'); //case VarType(AValue) of // var //end; SetState(psFulfilled); Value := AValue; //DoResolve(AValue, Self); end; procedure TPromiseInternal.RejectPromise(const AReason: string); begin if Settled then Exit; SetState(psRejected); Value := AReason; end; procedure TPromiseInternal.SetState(const AValue: TPromiseState); begin EnterCriticalsection(FLock); try FState := AValue; finally LeaveCriticalsection(FLock); end; end; constructor TPromiseInternal.Create(const AData: IVariant); begin FData := AData; InitCriticalSection(FLock); end; destructor TPromiseInternal.Destroy; begin EnterCriticalsection(FLock); try inherited Destroy; finally LeaveCriticalsection(FLock); DoneCriticalsection(FLock); end; end; procedure TPromiseInternal.DoSettledLike(const APromise: TPromiseInternal); begin if Settled then Exit; SetState(APromise.State); Value := APromise.FValue; end; procedure TPromiseInternal.DoSettledLike(const APromise: IPromise); begin DoSettledLike((APromise as IPromiseInternal).GetPromise); end; function TPromiseInternal.ThenP(const AOnFulfillment: TPromiseResolveProc; const AData: IVariant; const AOnRejection: TPromiseRejectProc; const AInMainThread: Boolean): IPromise; begin Result := TPromiseThen.Create(AOnFulfillment, AData, AOnRejection, AInMainThread); ThenPromise := Result; end; function TPromiseInternal.ThenM(const AOnFulfillment: TPromiseResolveMethod; const AData: IVariant; const AOnRejection: TPromiseRejectMethod; const AInMainThread: Boolean): IPromise; begin Result := TPromiseThen.Create(AOnFulfillment, AData, AOnRejection, AInMainThread); ThenPromise := Result; end; function TPromiseInternal.CatchP(const AOnRejection: TPromiseRejectProc; const AData: IVariant; const AInMainThread: Boolean): IPromise; begin Result := ThenP(nil, AData, AOnRejection, AInMainThread); end; function TPromiseInternal.CatchM(const AOnRejection: TPromiseRejectMethod; const AData: IVariant; const AInMainThread: Boolean): IPromise; begin Result := ThenM(nil, AData, AOnRejection, AInMainThread); end; function TPromiseInternal.FinallyP(const ACallbak: TPromiseFinallyProc; const AData: IVariant; const AInMainThread: Boolean): IPromise; begin Result := TPromiseFinally.Create(ACallbak, AData, AInMainThread); ThenPromise := Result; end; function TPromiseInternal.FinallyM(const ACallbak: TPromiseFinallyMethod; const AData: IVariant; const AInMainThread: Boolean): IPromise; begin Result := TPromiseFinally.Create(ACallbak, AData, AInMainThread); ThenPromise := Result; end; function TPromiseInternal.Wait(AWaitMSec: Cardinal): IVariant; var i: QWord; begin i := GetTickCount + AWaitMSec; while not Settled and (i > GetTickCount) do begin Sleep(10); if GetCurrentThreadId = MainThreadID then CheckSynchronize; end; Result := Value; end; end.
unit UFrmSaleBill; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrmBill, dxSkinsCore, dxSkinsdxBarPainter, dxSkinsDefaultPainters, dxBar, cxClasses, ImgList, cxGraphics, Grids, AdvObj, BaseGrid, AdvGrid, ExtCtrls, StdCtrls, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, cxDropDownEdit, cxCalendar, DB, uDataRecord, DBClient; type TFrmSaleBill = class(TFrmBill) lbl1: TLabel; edtClient: TcxButtonEdit; lbl2: TLabel; edtWorker: TcxButtonEdit; lbl3: TLabel; edtStock: TcxButtonEdit; lbl6: TLabel; edtRemark: TcxTextEdit; lbl4: TLabel; edtBillCode: TcxTextEdit; lbl5: TLabel; edtBillDate: TcxDateEdit; CdsTemp: TClientDataSet; procedure advstrngrd1CanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); procedure advstrngrd1GetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); procedure advstrngrd1GetEditorType(Sender: TObject; ACol, ARow: Integer; var AEditor: TEditorType); procedure FormShow(Sender: TObject); procedure advstrngrd1KeyPress(Sender: TObject; var Key: Char); procedure edtClientPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure FormDestroy(Sender: TObject); procedure edtStockPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure edtClientKeyPress(Sender: TObject; var Key: Char); procedure edtStockKeyPress(Sender: TObject; var Key: Char); procedure edtWorkerKeyPress(Sender: TObject; var Key: Char); procedure edtRemarkKeyPress(Sender: TObject; var Key: Char); procedure edtBillCodeKeyPress(Sender: TObject; var Key: Char); procedure edtBillDateKeyPress(Sender: TObject; var Key: Char); procedure BtnSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure BtnAddLineClick(Sender: TObject); procedure BtnInsertLineClick(Sender: TObject); procedure BtnDelLineClick(Sender: TObject); procedure advstrngrd1CellsChanged(Sender: TObject; R: TRect); private FStockGuid: string; FClientGuid: string; function GetBillCode: string; function DoBeforeSaveBill: Boolean; procedure DoSaveBillData; procedure DoSelectClient; procedure DoSelectStock; procedure DoSelectGoods; function DoCheckGoodsStock: Boolean; procedure InitForm; procedure AutoCalculate; procedure SetLineNo; public end; var FrmSaleBill: TFrmSaleBill; implementation uses dxForms, UMsgBox, uSysObj, UDBAccess, UPubFunLib, UFrmClientSelect, UFrmStockSelect, UFrmGoodsSelect, UDmBillBase; {$R *.dfm} procedure TFrmSaleBill.DoSelectClient; procedure SetClientValue(DataSet: TDataSet); begin edtClient.Text := DataSet.FindField('ClientName').AsString; FClientGuid := DataSet.FindField('Guid').AsString; edtWorker.SetFocus; end; begin if not Assigned(FrmClientSelect) then FrmClientSelect := TFrmClientSelect.Create(nil); with FrmClientSelect, DmBillBase do begin //DoDataFilter(Trim(edtClient.Text)); if CdsClient.Active and (CdsClient.RecordCount = 1) then begin SetClientValue(CdsClient); end else begin if ShowModal = mrOk then begin SetClientValue(CdsClient); end; end; end; end; procedure TFrmSaleBill.DoSelectStock; procedure SetClientValue(DataSet: TDataSet); begin edtStock.Text := DataSet.FindField('StockName').AsString; FStockGuid := DataSet.FindField('Guid').AsString; edtRemark.SetFocus; end; begin if not Assigned(FrmStockSelect) then FrmStockSelect := TFrmStockSelect.Create(nil); with FrmStockSelect, DmBillBase do begin //DoDataFilter(Trim(edtClient.Text)); if CdsStock.Active and (CdsStock.RecordCount = 1) then begin SetClientValue(CdsStock); end else begin if ShowModal = mrOk then begin SetClientValue(CdsStock); end; end; end; end; procedure TFrmSaleBill.DoSelectGoods; procedure SetClientValue(DataSet: TDataSet); var lRow: Integer; lValue: Double; begin lRow := advstrngrd1.Row; with advstrngrd1, DataSet do begin Cells[1, lRow] := FindField('GoodsID').AsString; Cells[2, lRow] := FindField('GoodsName').AsString; Cells[3, lRow] := FindField('GoodsType').AsString; Cells[4, lRow] := FindField('GoodsUnit').AsString; if Trim(Cells[5, lRow]) = '' then Cells[5, lRow] := '1'; Cells[6, lRow] := FindField('GoodsPrice').AsString; lValue := StrToFloatDef(Trim(advstrngrd1.Cells[5, lRow]), 0) * StrToFloatDef(Trim(advstrngrd1.Cells[6, lRow]), 0); advstrngrd1.Cells[7, lRow] := FormatFloat('0.##', lValue); Cells[9, lRow] := FindField('Guid').AsString; AutoCalculate; end; end; begin if not Assigned(FrmGoodsSelect) then FrmGoodsSelect := TFrmGoodsSelect.Create(nil); with FrmGoodsSelect, DmBillBase do begin //DoDataFilter(Trim(edtClient.Text)); if CdsGoods.Active and (CdsGoods.RecordCount = 1) then begin SetClientValue(CdsGoods); end else begin if ShowModal = mrOk then begin SetClientValue(CdsGoods); end; end; end; end; procedure TFrmSaleBill.advstrngrd1CanEditCell(Sender: TObject; ARow, ACol: Integer; var CanEdit: Boolean); begin inherited; case ACol of 1: CanEdit := Trim(advstrngrd1.Cells[1, ARow - 1]) <> ''; 5, 6, 7, 8: CanEdit := Trim(advstrngrd1.Cells[1, ARow]) <> ''; else CanEdit := False; end; end; procedure TFrmSaleBill.AutoCalculate; var I, lRowCount: Integer; lNum, lAmt: Double; begin lNum := 0; lAmt := 0; lRowCount := advstrngrd1.RowCount; for I := 1 to lRowCount - 2 do begin lNum := lNum + StrToFloatDef(Trim(advstrngrd1.Cells[5, I]), 0); lAmt := lAmt + StrToFloatDef(Trim(advstrngrd1.Cells[7, I]), 0); end; advstrngrd1.Cells[5, lRowCount - 1] := FormatFloat('0.####', lNum); advstrngrd1.Cells[7, lRowCount - 1] := FormatFloat('0.##', lAmt); end; procedure TFrmSaleBill.BtnAddLineClick(Sender: TObject); begin inherited; advstrngrd1.InsertRows(advstrngrd1.RowCount - 1, 1); advstrngrd1.Row := advstrngrd1.RowCount - 2; SetLineNo; end; procedure TFrmSaleBill.BtnCancelClick(Sender: TObject); begin InitForm; end; procedure TFrmSaleBill.BtnDelLineClick(Sender: TObject); var iRow: Integer; begin inherited; iRow := advstrngrd1.Row; if (iRow = 0) or (iRow = advstrngrd1.RowCount - 1) then Exit; if (iRow = 1) and (advstrngrd1.RowCount = 3) then advstrngrd1.Rows[1].Clear else begin advstrngrd1.RemoveRows(iRow, 1); if iRow = advstrngrd1.RowCount - 1 then advstrngrd1.Row := advstrngrd1.RowCount - 2; end; SetLineNo; AutoCalculate; advstrngrd1.Repaint; end; procedure TFrmSaleBill.BtnInsertLineClick(Sender: TObject); var iRow: Integer; begin inherited; iRow := advstrngrd1.Row; if (iRow = 0) then Exit; advstrngrd1.InsertRows(iRow, 1); SetLineNo; end; procedure TFrmSaleBill.BtnSaveClick(Sender: TObject); begin DoSaveBillData; end; procedure TFrmSaleBill.FormCreate(Sender: TObject); begin inherited; DmBillBase := TDmBillBase.Create(nil); if not DmBillBase.OpenDataSets then ShowMsg('读取初始化数据失败!'); end; procedure TFrmSaleBill.FormDestroy(Sender: TObject); begin if Assigned(FrmClientSelect) then FreeAndNil(FrmClientSelect); if Assigned(FrmStockSelect) then FreeAndNil(FrmStockSelect); if Assigned(FrmGoodsSelect) then FreeAndNil(FrmGoodsSelect); FreeAndNil(DmBillBase); inherited; end; procedure TFrmSaleBill.FormShow(Sender: TObject); begin inherited; InitForm; advstrngrd1.ColWidths[0] := 40; advstrngrd1.ColWidths[1] := 100; advstrngrd1.ColWidths[2] := 200; advstrngrd1.ColWidths[3] := 100; advstrngrd1.ColWidths[4] := 100; advstrngrd1.ColWidths[5] := 100; advstrngrd1.ColWidths[6] := 100; advstrngrd1.ColWidths[7] := 100; advstrngrd1.ColWidths[8] := 200; advstrngrd1.HideColumn(9); SetLineNo; end; function TFrmSaleBill.GetBillCode: string; var lStrSql: string; begin lStrSql := 'declare @MaxID varchar(3) '+ ' declare @Prefix varchar(10) '+ ' set @Prefix=''XS'' + replace(CONVERT(VARCHAR(10), getdate(), 120), ''-'', '''') '+ ' select @MaxID = CONVERT(VARCHAR(3), isnull(max(substring(ID, 11, 3)), 0) + 1) from SaleBillH '+ ' where substring(ID, 1, 10)=@Prefix '+ ' select @Prefix + REPLICATE(''0'', 3 - len(@MaxID)) + @MaxID'; Result := DBAccess.GetSQLStringValue(lStrSql); if Result = '' then begin ShowMsg('销售单号生成失败!'); Exit; end; end; procedure TFrmSaleBill.InitForm; var I: Integer; begin edtClient.SetFocus; edtBillCode.Text := GetBillCode; edtBillDate.Date := Date; edtClient.Text := ''; FClientGuid := ''; edtWorker.Text := Sys.WorkerInfo.WorkerName; edtStock.Text := ''; FStockGuid := ''; edtRemark.Text := ''; for I := 1 to advstrngrd1.RowCount - 2 do advstrngrd1.Rows[I].Clear; advstrngrd1.Cells[5, advstrngrd1.RowCount - 1] := ''; end; procedure TFrmSaleBill.SetLineNo; var I: Integer; begin for I := 1 to advstrngrd1.RowCount - 2 do advstrngrd1.Cells[0, I] := IntToStr(I); advstrngrd1.Cells[0, advstrngrd1.RowCount - 1] := '合计'; end; procedure TFrmSaleBill.advstrngrd1CellsChanged(Sender: TObject; R: TRect); var lValue: Double; ACol, ARow: Integer; begin inherited; ACol := advstrngrd1.Col; ARow := advstrngrd1.Row; if not (ACol in [5, 6, 7]) then Exit; case ACol of 5, 6: begin lValue := StrToFloatDef(Trim(advstrngrd1.Cells[5, ARow]), 0); advstrngrd1.Cells[5, ARow] := FormatFloat('0.####', lValue); lValue := StrToFloatDef(Trim(advstrngrd1.Cells[6, ARow]), 0); advstrngrd1.Cells[6, ARow] := FormatFloat('0.####', lValue); lValue := StrToFloatDef(Trim(advstrngrd1.Cells[5, ARow]), 0) * StrToFloatDef(Trim(advstrngrd1.Cells[6, ARow]), 0); advstrngrd1.Cells[7, ARow] := FormatFloat('0.##', lValue); end; 7: begin if (Trim(advstrngrd1.Cells[5, ARow]) = '') or ((Trim(advstrngrd1.Cells[7, ARow]) = '')) then advstrngrd1.Cells[6, ARow] := '' else begin lValue := StrToFloatDef(Trim(advstrngrd1.Cells[7, ARow]), 0) / StrToFloatDef(Trim(advstrngrd1.Cells[5, ARow]), 0); advstrngrd1.Cells[6, ARow] := FormatFloat('0.####', lValue); end; end; end; AutoCalculate; end; procedure TFrmSaleBill.advstrngrd1GetAlignment(Sender: TObject; ARow, ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment); begin inherited; if ARow > 0 then begin if ACol in [0, 4] then HAlign := taCenter else HAlign := taLeftJustify; end; end; procedure TFrmSaleBill.advstrngrd1GetEditorType(Sender: TObject; ACol, ARow: Integer; var AEditor: TEditorType); begin inherited; case ACol of 5, 6, 7: AEditor := edFloat; else AEditor := edNormal; end; end; procedure TFrmSaleBill.advstrngrd1KeyPress(Sender: TObject; var Key: Char); begin inherited; if Key = #13 then begin Key := #0; case advstrngrd1.Col of 1: begin DoSelectGoods; if Trim(advstrngrd1.Cells[1, advstrngrd1.Row]) <> '' then advstrngrd1.Col := advstrngrd1.Col + 4; end; 2..7: advstrngrd1.Col := advstrngrd1.Col + 1; 8: begin advstrngrd1.Col := 1; advstrngrd1.Row := advstrngrd1.Row + 1; end; end; end; end; procedure TFrmSaleBill.edtBillCodeKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then edtBillDate.SetFocus; end; procedure TFrmSaleBill.edtBillDateKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin advstrngrd1.SetFocus; advstrngrd1.Row := 1; advstrngrd1.Col := 1; end; end; procedure TFrmSaleBill.edtClientKeyPress(Sender: TObject; var Key: Char); begin // 如果文本框输入了内容,根据内容查询供货单位信息, // 如果只查到一个自动带出信息,否则弹出选择窗体 if Key =#13 then DoSelectClient; end; procedure TFrmSaleBill.edtClientPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin DoSelectClient; end; procedure TFrmSaleBill.edtRemarkKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then edtBillCode.SetFocus; end; procedure TFrmSaleBill.edtStockKeyPress(Sender: TObject; var Key: Char); begin if Key =#13 then DoSelectStock; end; procedure TFrmSaleBill.edtStockPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin DoSelectStock; end; procedure TFrmSaleBill.edtWorkerKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then edtStock.SetFocus; end; function TFrmSaleBill.DoCheckGoodsStock: Boolean; const GetGoodsStockSQL = 'select * from GoodsStock where StockGuid=''%s'''; var I: Integer; lNum, lStockNum: Double; lGoodsGuid, lGoodsName: string; lStrSql: string; begin Result := False; lStrSql := Format(GetGoodsStockSQL, [FStockGuid]); if not DBAccess.ReadDataSet(lStrSql, CdsTemp) then begin ShowMsg('获取商品库存信息失败!'); Exit; end; for I := 1 to advstrngrd1.RowCount - 2 do begin if Trim(advstrngrd1.Cells[1, I]) = '' then Continue; lGoodsName := advstrngrd1.Cells[2, I]; lGoodsGuid := advstrngrd1.Cells[9, I]; lNum := StrToFloatDef(advstrngrd1.Cells[5, I], 0); if CdsTemp.Locate('GoodsGuid', lGoodsGuid, [loCaseInsensitive]) then begin lStockNum := CdsTemp.FindField('TotalNum').AsFloat; if lNum > lStockNum then begin ShowMsg(Format('“%s”仓库的“%s”库存不足!', [Trim(edtStock.Text), lGoodsName])); Exit; end; end else begin ShowMsg(Format('“%s”仓库未找到“%s”的库存信息!', [Trim(edtStock.Text), lGoodsName])); Exit; end; end; Result := True; end; function TFrmSaleBill.DoBeforeSaveBill: Boolean; var I, iCount: Integer; begin Result := False; if Trim(edtClient.Text) = '' then begin edtClient.SetFocus; ShowMsg('购货单位不能为空!'); Exit; end; if Trim(edtWorker.Text) = '' then begin edtWorker.SetFocus; ShowMsg('经手人不能为空!'); Exit; end; if Trim(edtStock.Text) = '' then begin edtStock.SetFocus; ShowMsg('发货仓库不能为空!'); Exit; end; if Trim(edtBillCode.Text) = '' then begin edtBillCode.SetFocus; ShowMsg('单据编号不能为空!'); Exit; end; if Trim(edtBillDate.Text) = '' then begin edtBillDate.SetFocus; ShowMsg('单据日期不能为空!'); Exit; end; iCount := 0; for I := 1 to advstrngrd1.RowCount - 2 do begin if Trim(advstrngrd1.Cells[1, I]) <> '' then Inc(iCount); end; if iCount = 0 then begin ShowMsg('销售单明细信息至少需要包含一条完整信息!'); Exit; end; // 判断单号是否重复 iCount := DBAccess.GetSQLIntegerValue('select count(*) from SaleBillH where ID=' + QuotedStr(edtBillCode.Text)); if iCount = -1 then begin ShowMsg('检查销售单号是否重复失败!'); Exit; end; if iCount > 0 then begin ShowMsg('销售单号重复!'); Exit; end; // 此处判断库存是否充足 if not DoCheckGoodsStock then Exit; Result := True; end; procedure TFrmSaleBill.DoSaveBillData; const InsSaleBillHSQL = 'insert into SaleBillH(ID, SaleDate, ClientGuid, StockGuid, '+ ' TotalNum, TotalAmt, CreateMan, CreateTime, IsAffirm, AffirmMan, AffirmTime, Remark)'+ ' values(''%s'', ''%s'', ''%s'', ''%s'', %f, %f, ''%s'', getdate(), '+ ' 1, ''%s'', getdate(), ''%s'')'; InsSaleBillDSQL = 'insert into SaleBillD(Guid, SaleID, Line, GoodsGuid, Num, '+ ' Price, Amount, Remark) '+ ' values(''%s'', ''%s'', %d, ''%s'', %f, %f, %f,''%s'')'; UpdGoodsStockSQL = 'update GoodsStock set TotalNum=isnull(TotalNum, 0) - %f '+ ' where GoodsGuid=''%s'' and StockGuid=''%s'''; var lStrSql: string; lList: TStrings; I: Integer; lBillCode, lGoodsGuid, lGuid, lRemark: string; lTNum, lNum, lPrice, lTAmt, lAmt: Double; begin if not DoBeforeSaveBill then Exit; lList := TStringList.Create; try lBillCode := Trim(edtBillCode.Text); lTNum := 0; lTAmt := 0; // 增加明细表记录 for I := 1 to advstrngrd1.RowCount - 2 do begin if Trim(advstrngrd1.Cells[1, I]) <> '' then begin lGuid := CreateGuid; lNum := StrToFloat(Trim(advstrngrd1.Cells[5, I])); lPrice := StrToFloat(Trim(advstrngrd1.Cells[6, I])); lAmt := StrToFloat(Trim(advstrngrd1.Cells[7, I])); lRemark := Trim(advstrngrd1.Cells[8, I]); lGoodsGuid := Trim(advstrngrd1.Cells[9, I]); lStrSql := Format(InsSaleBillDSQL, [lGuid, lBillCode, I, lGoodsGuid, lNum, lPrice, lAmt, lRemark]); lList.Add(lStrSql); lStrSql := Format(UpdGoodsStockSQL, [lNum, lGoodsGuid, FStockGuid]); lList.Add(lStrSql); lTNum := lTNum + lNum; lTAmt := lTAmt + lAmt; end; end; lStrSql := Format(InsSaleBillHSQL, [lBillCode, DateToStr(edtBillDate.Date), FClientGuid, FStockGuid, lTNum, lTAmt, Sys.WorkerInfo.WorkerID, Sys.WorkerInfo.WorkerID, Trim(edtRemark.Text)]); lList.Add(lStrSql); if not DBAccess.ExecuteBatchSQL(lList) then begin ShowMsg('销售单保存失败!'); Exit; end; Self.InitForm; finally lList.Free; end; end; initialization dxFormManager.RegisterForm(TFrmSaleBill); end.
unit USettingsManager; interface uses SuperObject, SysUtils, WinApi.Windows, Classes, Generics.Collections, UFileUtilities, System.Win.Registry; type TMCPath = class path, name:String; end; var SMPPlayerName, SMPMinecraftPath, SMPJavaPath, SMPLaunchMode, SMPLast, SMPBackgroundPath, SMPSkinPath, SMPSkinName, SMPLanguage: String; SMPMaxMemory: Int64; SMPUseJava, SMPLoaded, SMPDebug, SMPShowBackground: Boolean; type TSettingsManager = class public class procedure Load; class procedure Save; end; function IntegerToString(i:Integer):string; function BooleanTOString(b:Boolean):string; function GetJavaPath:string; implementation //Returns Memory Size(MB) function GetMemorySize: Int64; var mse: TMemoryStatusEx; begin mse.dwLength := sizeof(TMemoryStatusEx); GlobalMemoryStatusEx(mse); exit(mse.ullTotalPhys div 1024 div 1024); end; function GetJavaPath:String; var reg, reg1, reg2: TRegistry; cv: String; begin reg := TRegistry.Create; reg.RootKey := HKEY_LOCAL_MACHINE; if reg.OpenKeyReadOnly('Software\JavaSoft\Java Runtime Environment') then cv := reg.ReadString('CurrentVersion'); reg1 := TRegistry.Create; reg1.RootKey := HKEY_LOCAL_MACHINE; if reg1.OpenKeyReadOnly('Software\JavaSoft\Java Runtime Environment\' + cv) then begin exit(reg1.ReadString('JavaHome') + '\bin'); end; if reg.OpenKeyReadOnly('Software\JavaSoft\Java Development Kit') then begin reg2 := TRegistry.Create; reg2.RootKey := HKEY_LOCAL_MACHINE; cv := reg2.ReadString('CurrentVersion'); if reg2.OpenKeyReadOnly('Software\JavaSoft\Java Development Kit\' + cv) then begin exit(reg2.ReadString('JavaHome') + '\bin'); end; end; reg.CloseKey; exit(''); end; function IntegerToString(i:Integer):string; begin Str(i, Result); end; function BooleanTOString(b:Boolean):string; begin if b then exit('true') else exit('false'); end; function DefaultMemory:string; var s:string; begin str(GetMemorySize div 2, s); exit(s); end; procedure tryGet(j:ISuperObject;name,default:String;var res:String); var jso: ISuperObject; begin jso := SOFindField(j, name); if jso = nil then res := default else res := jso.AsString; end; procedure tryGetBoolean(j:ISuperObject;name:string; default:Boolean; var res:Boolean); var jso: ISuperObject; begin jso := SOFindField(j, name); if jso = nil then res := default else res := jso.AsBoolean; end; procedure tryGetInteger(j:ISuperObject;name:string; default:Integer;var res:Integer); var jso: ISuperObject; begin jso := SOFindField(j, name); if jso = nil then res := default else res := jso.AsInteger; end; procedure tryGetInt64(j:ISuperObject;name:string; default:Int64;var res:Int64); var jso: ISuperObject; begin jso := SOFindField(j, name); if jso = nil then res := default else res := jso.AsInteger; end; class procedure TSettingsManager.Load; var t, jc:string; readfile:TextFile; jobj: ISuperObject; p:TMCPath; begin if FileExists(TFileUtilities.CurrentDir + 'settings.json') then begin AssignFile(ReadFile, TFileUtilities.CurrentDir + 'settings.json'); ReSet(ReadFile); jc := ''; while Not Eof(ReadFile) do begin ReadLn(ReadFile, t); jc := jc + t; end; Close(ReadFile); jobj := SO(jc); tryGet(jobj, 'PlayerName', 'Player007', SMPPlayerName); tryGet(jobj, 'MinecraftPath', TFileUtilities.CurrentDir + '.minecraft', SMPMinecraftPath); tryGet(jobj, 'LaunchMode', 'Normal', SMPLaunchMode); tryGet(jobj, 'JavaPath', GetJavaPath, SMPJavaPath); tryGet(jobj, 'Last', '', SMPLast); tryGet(jobj, 'BackgroundPath', '', SMPBackgroundPath); tryGet(jobj, 'SkinPath', '', SMPSkinPath); tryGet(jobj, 'SkinName', '', SMPSkinName); tryGet(jobj, 'Lang', 'zh_CN', SMPLanguage); tryGetInt64(jobj, 'MaxMemory', GetMemorySize div 2, SMPMaxMemory); tryGetBoolean(jobj, 'UseJava', false, SMPUseJava); tryGetBoolean(jobj, 'Debug', false, SMPDebug); tryGetBoolean(jobj, 'ShowBackground', false, SMPShowBackground); SMPLoaded := true; end else begin SMPPlayerName := 'Player007'; SMPMinecraftPath := TFileUtilities.CurrentDir + '.minecraft'; SMPMaxMemory := GetMemorySize div 2; SMPJavaPath := GetJavaPath; SMPUseJava := false; SMPDebug := false; SMPLast := ''; SMPLaunchMode := 'Normal'; SMPBackgroundPath := ''; SMPSkinPath := ''; SMPSkinName := ''; SMPLanguage := 'zh_CN'; SMPLoaded := true; TSettingsManager.Save; end; end; class procedure TSettingsManager.Save; var writefile:textfile; jobj: ISuperObject; content, path:String; begin if Not SMPLoaded then exit; path := TFileUtilities.CurrentDir; AssignFile(WriteFile, path + 'settings.json'); ReWrite(WriteFile); jobj := TSuperObject.Create; jobj['PlayerName'] := SO('"' + ParseSeparator(SMPPlayerName) + '"'); jobj['MinecraftPath'] := SO('"' + ParseSeparator(SMPMinecraftPath) + '"'); jobj['JavaPath'] := SO('"' + ParseSeparator(SMPJavaPath) + '"'); jobj['Last'] := SO('"' + ParseSeparator(SMPLast) + '"'); jobj['MaxMemory'] := SO(SMPMaxMemory); jobj['UseJava'] := SO(SMPUseJava); jobj['Debug'] := SO(SMPDebug); jobj['ShowBackground'] := SO(SMPShowBackground); jobj['LaunchMode'] := SO('"' + ParseSeparator(SMPLaunchMode) + '"'); jobj['BackgroundPath'] := SO('"' + ParseSeparator(SMPBackgroundPath) + '"'); jobj['SkinPath'] := SO('"' + ParseSeparator(SMPSkinPath) + '"'); jobj['SkinName'] := SO('"' + ParseSeparator(SMPSkinName) + '"'); jobj['Lang'] := SO('"' + ParseSeparator(SMPLanguage) + '"'); content:=jobj.AsJSon; Write(WriteFile,content); Close(WriteFile); end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.OracleDef; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf; type // TFDPhysOracleConnectionDefParams // Generated for: FireDAC Oracle driver TFDOracleAuthMode = (amNormal, amSysDBA, amSysOper, amSysASM, amSysBackup, amSysDG, amSysKM); TFDOracleCharacterSet = (cs_NLS_LANG_, csUTF8); TFDOracleBooleanFormat = (bfChoose, bfInteger, bfString); /// <summary> TFDPhysOracleConnectionDefParams class implements FireDAC Oracle driver specific connection definition class. </summary> TFDPhysOracleConnectionDefParams = class(TFDConnectionDefParams) private function GetDriverID: String; procedure SetDriverID(const AValue: String); function GetOSAuthent: Boolean; procedure SetOSAuthent(const AValue: Boolean); function GetAuthMode: TFDOracleAuthMode; procedure SetAuthMode(const AValue: TFDOracleAuthMode); function GetReadTimeout: Integer; procedure SetReadTimeout(const AValue: Integer); function GetWriteTimeout: Integer; procedure SetWriteTimeout(const AValue: Integer); function GetCharacterSet: TFDOracleCharacterSet; procedure SetCharacterSet(const AValue: TFDOracleCharacterSet); function GetBooleanFormat: TFDOracleBooleanFormat; procedure SetBooleanFormat(const AValue: TFDOracleBooleanFormat); function GetApplicationName: String; procedure SetApplicationName(const AValue: String); function GetOracleAdvanced: String; procedure SetOracleAdvanced(const AValue: String); function GetMetaDefSchema: String; procedure SetMetaDefSchema(const AValue: String); function GetMetaCurSchema: String; procedure SetMetaCurSchema(const AValue: String); published property DriverID: String read GetDriverID write SetDriverID stored False; property OSAuthent: Boolean read GetOSAuthent write SetOSAuthent stored False; property AuthMode: TFDOracleAuthMode read GetAuthMode write SetAuthMode stored False default amNormal; property ReadTimeout: Integer read GetReadTimeout write SetReadTimeout stored False; property WriteTimeout: Integer read GetWriteTimeout write SetWriteTimeout stored False; property CharacterSet: TFDOracleCharacterSet read GetCharacterSet write SetCharacterSet stored False default cs_NLS_LANG_; property BooleanFormat: TFDOracleBooleanFormat read GetBooleanFormat write SetBooleanFormat stored False default bfChoose; property ApplicationName: String read GetApplicationName write SetApplicationName stored False; property OracleAdvanced: String read GetOracleAdvanced write SetOracleAdvanced stored False; property MetaDefSchema: String read GetMetaDefSchema write SetMetaDefSchema stored False; property MetaCurSchema: String read GetMetaCurSchema write SetMetaCurSchema stored False; end; implementation uses FireDAC.Stan.Consts; // TFDPhysOracleConnectionDefParams // Generated for: FireDAC Oracle driver {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetDriverID: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_DriverID]; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetDriverID(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetOSAuthent: Boolean; begin Result := FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent]; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetOSAuthent(const AValue: Boolean); begin FDef.AsYesNo[S_FD_ConnParam_Common_OSAuthent] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetAuthMode: TFDOracleAuthMode; var s: String; begin s := FDef.AsString[S_FD_ConnParam_Oracle_AuthMode]; if CompareText(s, 'Normal') = 0 then Result := amNormal else if CompareText(s, 'SysDBA') = 0 then Result := amSysDBA else if CompareText(s, 'SysOper') = 0 then Result := amSysOper else if CompareText(s, 'SysASM') = 0 then Result := amSysASM else if CompareText(s, 'SysBackup') = 0 then Result := amSysBackup else if CompareText(s, 'SysDG') = 0 then Result := amSysDG else if CompareText(s, 'SysKM') = 0 then Result := amSysKM else Result := amNormal; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetAuthMode(const AValue: TFDOracleAuthMode); const C_AuthMode: array[TFDOracleAuthMode] of String = ('Normal', 'SysDBA', 'SysOper', 'SysASM', 'SysBackup', 'SysDG', 'SysKM'); begin FDef.AsString[S_FD_ConnParam_Oracle_AuthMode] := C_AuthMode[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetReadTimeout: Integer; begin Result := FDef.AsInteger[S_FD_ConnParam_Oracle_ReadTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetReadTimeout(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Oracle_ReadTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetWriteTimeout: Integer; begin Result := FDef.AsInteger[S_FD_ConnParam_Oracle_WriteTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetWriteTimeout(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_Oracle_WriteTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetCharacterSet: TFDOracleCharacterSet; var s: String; begin s := FDef.AsString[S_FD_ConnParam_Common_CharacterSet]; if CompareText(s, '<NLS_LANG>') = 0 then Result := cs_NLS_LANG_ else if CompareText(s, 'UTF8') = 0 then Result := csUTF8 else Result := cs_NLS_LANG_; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetCharacterSet(const AValue: TFDOracleCharacterSet); const C_CharacterSet: array[TFDOracleCharacterSet] of String = ('<NLS_LANG>', 'UTF8'); begin FDef.AsString[S_FD_ConnParam_Common_CharacterSet] := C_CharacterSet[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetBooleanFormat: TFDOracleBooleanFormat; var s: String; begin s := FDef.AsString[S_FD_ConnParam_Oracle_BooleanFormat]; if CompareText(s, 'Choose') = 0 then Result := bfChoose else if CompareText(s, 'Integer') = 0 then Result := bfInteger else if CompareText(s, 'String') = 0 then Result := bfString else Result := bfChoose; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetBooleanFormat(const AValue: TFDOracleBooleanFormat); const C_BooleanFormat: array[TFDOracleBooleanFormat] of String = ('Choose', 'Integer', 'String'); begin FDef.AsString[S_FD_ConnParam_Oracle_BooleanFormat] := C_BooleanFormat[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetApplicationName: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_ApplicationName]; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetApplicationName(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_ApplicationName] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetOracleAdvanced: String; begin Result := FDef.AsString[S_FD_ConnParam_Oracle_OracleAdvanced]; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetOracleAdvanced(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Oracle_OracleAdvanced] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetMetaDefSchema: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema]; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetMetaDefSchema(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaDefSchema] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysOracleConnectionDefParams.GetMetaCurSchema: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema]; end; {-------------------------------------------------------------------------------} procedure TFDPhysOracleConnectionDefParams.SetMetaCurSchema(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaCurSchema] := AValue; end; end.
unit ADAPT.UnitTests.Math.Delta; interface {$I ADAPT.inc} uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} DUnitX.TestFramework, ADAPT.Intf, ADAPT.Math.Delta.Intf; type [TestFixture] TADUTMathDelta = class(TObject) public [Test] procedure BasicIntegrity; [Test] procedure Extrapolation; [Test] procedure Interpolation; end; implementation uses ADAPT, ADAPT.Comparers, ADAPT.Math.Delta; type // Interfaces IADFloatDelta = IADDeltaValue<ADFloat>; { TADUTMathDelta } procedure TADUTMathDelta.BasicIntegrity; var LDelta: IADFloatDelta; LCurrentTime: ADFloat; begin // Get the current time as of Test Start. LCurrentTime := ADReferenceTime; // Create an empty Delta Value LDelta := ADDeltaFloat; // Set the Value for test start to 1.00 LDelta[LCurrentTime] := 1.00; // Set the Value for Start Time + 1 second to 2.00 LDelta[LCurrentTime + 1] := 2.00; // Verify the current exact values Assert.IsTrue(LDelta[LCurrentTime] = 1.00, Format('Value at %n should be 1.00 but instead got %n', [LCurrentTime, LDelta[LCurrentTime]])); Assert.IsTrue(LDelta[LCurrentTime + 1] = 2.00, Format('Value at %n should be 2.00 but instead got %n', [LCurrentTime + 1, LDelta[LCurrentTime + 1]])); end; procedure TADUTMathDelta.Extrapolation; var LDelta: IADFloatDelta; LCurrentTime: ADFloat; begin // Get the current time as of Test Start. LCurrentTime := ADReferenceTime; // Create an empty Delta Value LDelta := ADDeltaFloat; // Set the Value for test start to 1.00 LDelta[LCurrentTime] := 1.00; // Set the Value for Start Time + 1 second to 2.00 LDelta[LCurrentTime + 1] := 2.00; // Verify the current exact values Assert.IsTrue(LDelta[LCurrentTime] = 1.00, Format('Value at %n should be 1.00 but instead got %n', [LCurrentTime, LDelta[LCurrentTime]])); Assert.IsTrue(LDelta[LCurrentTime + 1] = 2.00, Format('Value at %n should be 2.00 but instead got %n', [LCurrentTime + 1, LDelta[LCurrentTime + 1]])); // Verify the value at LCurrentTime + 2 Assert.IsTrue(LDelta[LCurrentTime + 2] = 3.00, Format('Value at %n should be 3.00 but instead got %n', [LCurrentTime + 2, LDelta[LCurrentTime + 2]])); // Verify the value at LCurrentTime + 2.5 Assert.IsTrue(LDelta[LCurrentTime + 2.5] = 3.50, Format('Value at %n should be 3.50 but instead got %n', [LCurrentTime + 2.5, LDelta[LCurrentTime + 2.5]])); // Verify the value at LCurrentTime + 3 Assert.IsTrue(LDelta[LCurrentTime + 3] = 4.00, Format('Value at %n should be 4.00 but instead got %n', [LCurrentTime + 3, LDelta[LCurrentTime + 3]])); // Verify the value at LCurrentTime -1 Assert.IsTrue(LDelta[LCurrentTime - 1] = 0.00, Format('Value at %n should be 0.00 but instead got %n', [LCurrentTime - 1, LDelta[LCurrentTime - 1]])); // Verify the value at LCurrentTime -2 Assert.IsTrue(LDelta[LCurrentTime - 2] = -1.00, Format('Value at %n should be -1.00 but instead got %n', [LCurrentTime - 2, LDelta[LCurrentTime - 2]])); // Verify the value at LCurrentTime -2.5 Assert.IsTrue(LDelta[LCurrentTime - 2.5] = -1.50, Format('Value at %n should be -1.50 but instead got %n', [LCurrentTime - 2.5, LDelta[LCurrentTime - 2.5]])); // Verify the value at LCurrentTime -3 Assert.IsTrue(LDelta[LCurrentTime - 3] = -2.00, Format('Value at %n should be -2.00 but instead got %n', [LCurrentTime - 3, LDelta[LCurrentTime - 3]])); end; procedure TADUTMathDelta.Interpolation; var LDelta: IADFloatDelta; LCurrentTime: ADFloat; begin // Get the current time as of Test Start. LCurrentTime := ADReferenceTime; // Create an empty Delta Value LDelta := ADDeltaFloat; // Set the Value for test start to 1.00 LDelta[LCurrentTime] := 1.00; // Set the Value for Start Time + 1 second to 2.00 LDelta[LCurrentTime + 1] := 2.00; // Verify the value at LCurrentTime + 0.5; Assert.IsTrue(LDelta[LCurrentTime + 0.5] = 1.50, Format('Value at %n should be 1.50 but instead got %n', [LCurrentTime + 0.5, LDelta[LCurrentTime + 0.5]])); // Verify the value at LCurrentTime + 0.75; Assert.IsTrue(LDelta[LCurrentTime + 0.75] = 1.75, Format('Value at %n should be 1.75 but instead got %n', [LCurrentTime + 0.75, LDelta[LCurrentTime + 0.75]])); // Now let's add a new reference value. LDelta[LCurrentTime + 2] := 3.00; // Verify the value at LCurrentTime + 0.5; Assert.IsTrue(LDelta[LCurrentTime + 0.5] = 1.50, Format('Value at %n should be 1.50 but instead got %n', [LCurrentTime + 0.5, LDelta[LCurrentTime + 0.5]])); // Verify the value at LCurrentTime + 0.75; Assert.IsTrue(LDelta[LCurrentTime + 0.75] = 1.75, Format('Value at %n should be 1.75 but instead got %n', [LCurrentTime + 0.75, LDelta[LCurrentTime + 0.75]])); // Verify the value at LCurrentTime + 1.50; Assert.IsTrue(LDelta[LCurrentTime + 1.50] = 2.5, Format('Value at %n should be 2.5 but instead got %n', [LCurrentTime + 1.5, LDelta[LCurrentTime + 1.5]])); LDelta[LCurrentTime + 3] := 4.00; LDelta[LCurrentTime + 4] := 5.00; LDelta[LCurrentTime + 5] := 6.00; // Verify the value at LCurrentTime + 4.5; Assert.IsTrue(LDelta[LCurrentTime + 4.5] = 5.5, Format('Value at %n should be 5.5 but instead got %n', [LCurrentTime + 4.5, LDelta[LCurrentTime + 4.5]])); // Re-Verify the value at LCurrentTime + 0.5; Assert.IsTrue(LDelta[LCurrentTime + 0.5] = 1.50, Format('Value at %n should be 1.50 but instead got %n', [LCurrentTime + 0.5, LDelta[LCurrentTime + 0.5]])); // Verify the value at LCurrentTime - 1; Assert.IsTrue(LDelta[LCurrentTime - 1.00] = 0.00, Format('Value at %n should be 0.00 but instead got %n', [LCurrentTime - 1.00, LDelta[LCurrentTime - 1.00]])); end; end.
{ Serial communication port based on FTD2XX library. (C) Sergey Bodrov, 2012-2018 Properties: SerialNumber - FTDI device serial number DeviceDescription - FTDI device description string BaudRate - data exchange speed (300, 1200, 9600, 115384, 230769, 923076) DataBits - default 8 Parity - (N - None, O - Odd, E - Even, M - Mark or S - Space) default N StopBits - (1, 1.5, 2) default 1 MinDataBytes - minimal bytes count in buffer for triggering event OnDataAppear Methods: Open() - Opens port. As parameter it use port initialization string: InitStr = '<DeviceDescription>:<SerialNumber>:<PortInitStr>' Examples: 'USB Serial::' - first device of 'USB Serial' type ':FT425622:' - device with s/n FT425622 GetFtdiDeviceList() - list of available devices in format <DeviceDescription>:<SerialNumber><LineFeed> Events: OnModemStatus - Triggered when modem status changes (CTS, DTR, RI, DCD) } unit DataPortFTDI; interface uses {$ifndef FPC}Windows,{$endif} SysUtils, Classes, DataPort, DataPortUART, D2XXUnit; type { TFtdiClient - FTDI device reader/writer thread } TFtdiClient = class(TThread) private FRxData: AnsiString; FTxData: AnsiString; FTxLockCount: Integer; FLastErrorStr: string; FOnIncomingMsgEvent: TMsgEvent; FOnErrorEvent: TMsgEvent; FOnConnectEvent: TNotifyEvent; FDoConfig: Boolean; { how many bytes read for once, default 64k } FReadCount: Integer; FFtHandle: LongWord; FFtIOStatus: FT_Result; { bytes in receive queue } FFtRxQBytes: LongWord; { bytes in transmit queue } FFtTxQBytes: LongWord; { wakeup event status } FFtEventStatus: LongWord; { input buffer } FFtInBuffer: array[0..FT_In_Buffer_Index] of byte; { output buffer } //FFtOutBuffer: array[0..FT_Out_Buffer_Index] of byte; procedure SyncProc(); procedure SyncProcOnError(); procedure SyncProcOnConnect(); function SendStringInternal(const AData: AnsiString): Integer; function CheckFtError(APortStatus: FT_Result; AFunctionName: string = ''): Boolean; function GetFtErrorDescription(APortStatus: FT_Result): string; protected FParentDataPort: TDataPortUART; procedure Execute(); override; public //Serial: TBlockSerial; InitStr: string; CalledFromThread: Boolean; // port properties BaudRate: Integer; DataBits: Integer; Parity: AnsiChar; StopBits: TSerialStopBits; FlowControl: TSerialFlowControl; MinDataBytes: Integer; HalfDuplex: Boolean; constructor Create(AParent: TDataPortUART); reintroduce; property OnIncomingMsgEvent: TMsgEvent read FOnIncomingMsgEvent write FOnIncomingMsgEvent; property OnError: TMsgEvent read FOnErrorEvent write FOnErrorEvent; property OnConnect: TNotifyEvent read FOnConnectEvent write FOnConnectEvent; { Set port parameters (baud rate, data bits, etc..) } procedure Config(); function SendAnsiString(const AData: AnsiString): Boolean; { Get modem wires status (DSR,CTS,Ring,Carrier) } function ReadModemStatus(var AModemStatus: TModemStatus): Boolean; { Set DTR (Data Terminal Ready) signal } procedure SetDTR(AValue: Boolean); { Set RTS (Request to send) signal } procedure SetRTS(AValue: Boolean); { Get COM port name } function GetPortName(): string; end; { TDataPortFtdi } TDataPortFtdi = class(TDataPortUART) private FFtdiClient: TFtdiClient; FFtSerialNumber: string; FFtDeviceDescription: string; FFlowControl: TSerialFlowControl; FOnModemStatus: TNotifyEvent; function CloseClient(): Boolean; protected procedure SetBaudRate(AValue: Integer); override; procedure SetDataBits(AValue: Integer); override; procedure SetParity(AValue: AnsiChar); override; procedure SetStopBits(AValue: TSerialStopBits); override; procedure SetFlowControl(AValue: TSerialFlowControl); override; property FtdiClient: TFtdiClient read FFtdiClient; public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; { Open FTDI device for data transmission InitStr = '<DeviceDescription>:<SerialNumber>:<PortInitStr>' Examples: 'USB Serial:' - first device of 'USB Serial' type ':FT425622' - device with s/n FT425622 List of available devices can be acquired in GetFtdiDeviceList() } procedure Open(const AInitStr: string = ''); override; procedure Close(); override; function Push(const AData: AnsiString): Boolean; override; { list of available devices in format <DeviceDescription>:<SerialNumber><LineFeed> } class function GetFtdiDeviceList(): string; //class function GetFtdiDriverVersion(): string; { Get modem wires status (DSR,CTS,Ring,Carrier) } function GetModemStatus(): TModemStatus; override; { Set DTR (Data Terminal Ready) signal } procedure SetDTR(AValue: Boolean); override; { Set RTS (Request to send) signal } procedure SetRTS(AValue: Boolean); override; published property Active; { FTDI device serial number } property SerialNumber: string read FFtSerialNumber write FFtSerialNumber; { FTDI device description string } property DeviceDescription: string read FFtDeviceDescription write FFtDeviceDescription; { FlowControl - (sfcNone, sfcSend, sfcReady, sfcSoft) default sfcNone } property FlowControl: TSerialFlowControl read FFlowControl write SetFlowControl; property BaudRate; property DataBits; property MinDataBytes; property OnDataAppear; property OnError; property OnOpen; property OnClose; { Triggered when modem status changes (CTS, DTR, RI, DCD) } property OnModemStatus: TNotifyEvent read FOnModemStatus write FOnModemStatus; end; procedure Register; implementation const //TX_BUF_SIZE = 128; // safe size TX_BUF_SIZE = 512; // optimal size procedure Register; begin RegisterComponents('DataPort', [TDataPortFtdi]); end; { TFtdiClient } procedure TFtdiClient.Config(); begin FDoConfig := True; end; function TFtdiClient.CheckFtError(APortStatus: FT_Result; AFunctionName: string): Boolean; begin Result := True; if APortStatus <> FT_OK then begin Terminate(); FLastErrorStr := AFunctionName + ': ' + GetFtErrorDescription(APortStatus); Result := False; end; end; function TFtdiClient.SendStringInternal(const AData: AnsiString): Integer; var WriteResult: Integer; WritePos, WriteSize, TotalSize: Integer; begin Result := 0; TotalSize := Length(AData); if (TotalSize = 0) or Terminated then Exit; WritePos := 0; while (FFtIOStatus = FT_OK) and (Result < TotalSize) do begin // some FTDI chips or drivers can't receive many bytes at once WriteSize := TX_BUF_SIZE; //WriteSize := $FF; if (WritePos + WriteSize) > TotalSize then WriteSize := TotalSize - WritePos; FFtIOStatus := FT_GetStatus(FFtHandle, @FFtRxQBytes, @FFtTxQBytes, @FFtEventStatus); if FFtIOStatus = FT_OK then begin if FFtTxQBytes > TX_BUF_SIZE then Break; // Writes Write_Count Bytes from FT_Out_Buffer to the USB device // Function returns the number of bytes actually sent // In this example, Write_Count should be 64k bytes max if WriteSize > 0 then begin //Move(AData[WritePos+1], FFtOutBuffer, WriteSize); //FFtIOStatus := FT_Write(FFtHandle, @FFtOutBuffer, WriteSize, @WriteResult); if WritePos + WriteSize > Length(AData) then Break; WriteResult := 0; FFtIOStatus := FT_Write(FFtHandle, @AData[WritePos+1], WriteSize, @WriteResult); if FFtIOStatus = FT_OK then begin if WriteResult = 0 then WriteResult := WriteSize; Result := Result + WriteResult; if WriteResult <> WriteSize then Break; end else Break; WritePos := WritePos + WriteSize; end; end; end; CheckFtError(FFtIOStatus, 'FT_Write'); end; procedure TFtdiClient.Execute(); var FtBaudRate: LongWord; FtDataBits: byte; FtStopBits: byte; FtParity: byte; FtFlowControl: word; FtModemStatus: LongWord; FtModemStatusPrev: LongWord; PortStatus: FT_Result; DeviceString: AnsiString; s, ss: string; FtDeviceStringBuffer: array [1..50] of AnsiChar; ReadCount, ReadResult, WriteResult: Integer; ReadTimeout, WriteTimeout: LongWord; NeedSleep: Boolean; LockCount: Integer; begin // Default settings FLastErrorStr := ''; DeviceString := ''; FDoConfig := True; FFtHandle := FT_INVALID_HANDLE; FReadCount := SizeOf(FFtInBuffer); ReadTimeout := 100; WriteTimeout := 100; FtBaudRate := FT_BAUD_9600; FtDataBits := FT_DATA_BITS_8; FtParity := FT_PARITY_NONE; FtStopBits := FT_STOP_BITS_1; FtFlowControl := FT_FLOW_NONE; FtModemStatus := 0; FtModemStatusPrev := 0; if Terminated then Exit; // parse InitStr, open port FtDeviceStringBuffer[1] := #0; // remove warning ss := InitStr; DeviceString := ExtractFirstWord(ss, ':'); s := ExtractFirstWord(ss, ':'); // Serial num if Length(s) > 0 then begin FillChar(FtDeviceStringBuffer, SizeOf(FtDeviceStringBuffer), 0); Move(s[1], FtDeviceStringBuffer, Length(s)); PortStatus := FT_OpenEx(@FtDeviceStringBuffer, FT_OPEN_BY_SERIAL_NUMBER, @FFtHandle); end else if Length(DeviceString) > 0 then begin FillChar(FtDeviceStringBuffer, SizeOf(FtDeviceStringBuffer), 0); Move(DeviceString[1], FtDeviceStringBuffer, Length(DeviceString)); PortStatus := FT_OpenEx(@FtDeviceStringBuffer, FT_OPEN_BY_DESCRIPTION, @FFtHandle); end else PortStatus := FT_DEVICE_NOT_FOUND; if not CheckFtError(PortStatus, 'FT_OpenEx') then FFtHandle := FT_INVALID_HANDLE; // Device handle acquired, we must release it in any case try while not Terminated do begin NeedSleep := True; // configure port if FDoConfig then begin FDoConfig := False; if BaudRate <> 0 then FtBaudRate := BaudRate; if DataBits <> 0 then FtDataBits := Byte(DataBits); case Parity of 'N', 'n': FtParity := FT_PARITY_NONE; 'O', 'o': FtParity := FT_PARITY_ODD; 'E', 'e': FtParity := FT_PARITY_EVEN; 'M', 'm': FtParity := FT_PARITY_MARK; 'S', 's': FtParity := FT_PARITY_SPACE; end; case StopBits of stb1: FtStopBits := FT_STOP_BITS_1; stb15: FtStopBits := FT_STOP_BITS_15; stb2: FtStopBits := FT_STOP_BITS_2; end; case FlowControl of sfcNone: FtFlowControl := FT_FLOW_NONE; sfcSend: FtFlowControl := FT_FLOW_RTS_CTS; sfcReady: FtFlowControl := FT_FLOW_DTR_DSR; sfcSoft: FtFlowControl := FT_FLOW_XON_XOFF; end; // This function sends a reset command to the device. PortStatus := FT_ResetDevice(FFtHandle); if CheckFtError(PortStatus, 'FT_ResetDevice') then begin // set BaudRate PortStatus := FT_SetBaudRate(FFtHandle, FtBaudRate); if CheckFtError(PortStatus, 'FT_SetBaudRate') then begin // set data characteristics PortStatus := FT_SetDataCharacteristics(FFtHandle, FtDataBits, FtStopBits, FtParity); if CheckFtError(PortStatus, 'FT_SetDataCharacteristics') then begin // set flow control PortStatus := FT_SetFlowControl(FFtHandle, FtFlowControl, FT_XON_Value, FT_XOFF_Value); if CheckFtError(PortStatus, 'FT_SetFlowControl') then begin // This function sets the read and write timeouts (in milliseconds) for the device PortStatus := FT_SetTimeouts(FFtHandle, ReadTimeout, WriteTimeout); if CheckFtError(PortStatus, 'FT_SetTimeouts') then begin // This function purges receive and transmit buffers in the device. PortStatus := FT_Purge(FFtHandle, (FT_PURGE_RX + FT_PURGE_TX)); CheckFtError(PortStatus, 'FT_Purge'); PortStatus := FT_ResetDevice(FFtHandle); CheckFtError(PortStatus, 'FT_ResetDevice_2'); end; end; end; end; end; if PortStatus = FT_OK then begin if Assigned(FParentDataPort.OnOpen) then Synchronize(SyncProcOnConnect) else if Assigned(OnConnect) then OnConnect(Self); end else begin Terminate(); Continue; end; end; // update modem status if Assigned(FParentDataPort.OnModemStatus) then begin FFtIOStatus := FT_GetModemStatus(FFtHandle, @FtModemStatus); if CheckFtError(FFtIOStatus, 'FT_GetModemStatus') then begin if FtModemStatusPrev <> FtModemStatus then begin FtModemStatusPrev := FtModemStatus; Synchronize(SyncProc); end; end; end; // Reads Read_Count Bytes (or less) from the USB device to the FT_In_Buffer // Function returns the number of bytes actually received which may range from zero // to the actual number of bytes requested, depending on how many have been received // at the time of the request + the read timeout value. FRxData := ''; ReadCount := FReadCount; ReadResult := 0; {if (ReadCount = 1) then begin ReadResult := ReadCount; end; } FFtIOStatus := FT_GetStatus(FFtHandle, @FFtRxQBytes, @FFtTxQBytes, @FFtEventStatus); if CheckFtError(FFtIOStatus, 'FT_GetStatus') and (FFtRxQBytes > 0) then begin if ReadCount > FFtRxQBytes then ReadCount := FFtRxQBytes; FFtIOStatus := FT_Read(FFtHandle, @FFtInBuffer, ReadCount, @ReadResult); if CheckFtError(FFtIOStatus, 'FT_Read') and (ReadResult > 0) then begin // copy input buffer to string SetLength(FRxData, ReadResult); Move(FFtInBuffer, FRxData[1], ReadResult); if Assigned(FParentDataPort.OnDataAppear) then Synchronize(SyncProc) else if Assigned(OnIncomingMsgEvent) then OnIncomingMsgEvent(Self, FRxData); FRxData := ''; NeedSleep := False; end; end; // HalfDuplex mode write if HalfDuplex then begin // acquire lock LockCount := InterLockedIncrement(FTxLockCount); try if (LockCount = 1) then begin if Length(FTxData) > 0 then begin WriteResult := SendStringInternal(FTxData); Delete(FTxData, 1, WriteResult); NeedSleep := False; end; end; finally // release lock InterLockedDecrement(FTxLockCount); end; end; if NeedSleep then Sleep(1); end; finally if FFtHandle <> FT_INVALID_HANDLE then FT_Close(FFtHandle); FFtHandle := FT_INVALID_HANDLE; FFtIOStatus := FT_INVALID_HANDLE; end; if Assigned(FParentDataPort.OnError) then Synchronize(SyncProcOnError) else if Assigned(OnError) then OnError(Self, FLastErrorStr); OnIncomingMsgEvent := nil; OnError := nil; OnConnect := nil; end; constructor TFtdiClient.Create(AParent: TDataPortUART); begin inherited Create(True); FParentDataPort := AParent; BaudRate := 9600; end; function TFtdiClient.GetFtErrorDescription(APortStatus: FT_Result): string; begin Result := ''; if APortStatus = FT_OK then Exit; case APortStatus of FT_INVALID_HANDLE: Result := 'Invalid handle'; FT_DEVICE_NOT_FOUND: Result := 'Device not found'; FT_DEVICE_NOT_OPENED: Result := 'Device not opened'; FT_IO_ERROR: Result := 'General IO error'; FT_INSUFFICIENT_RESOURCES: Result := 'Insufficient resources'; FT_INVALID_PARAMETER: Result := 'Invalid parameter'; FT_INVALID_BAUD_RATE: Result := 'Invalid baud rate'; FT_DEVICE_NOT_OPENED_FOR_ERASE: Result := 'Device not opened for erase'; FT_DEVICE_NOT_OPENED_FOR_WRITE: Result := 'Device not opened for write'; FT_FAILED_TO_WRITE_DEVICE: Result := 'Failed to write'; FT_EEPROM_READ_FAILED: Result := 'EEPROM read failed'; FT_EEPROM_WRITE_FAILED: Result := 'EEPROM write failed'; FT_EEPROM_ERASE_FAILED: Result := 'EEPROM erase failed'; FT_EEPROM_NOT_PRESENT: Result := 'EEPROM not present'; FT_EEPROM_NOT_PROGRAMMED: Result := 'EEPROM not programmed'; FT_INVALID_ARGS: Result := 'Invalid arguments'; FT_OTHER_ERROR: Result := 'Other error'; else Result := 'Unknown error'; end; end; function TFtdiClient.SendAnsiString(const AData: AnsiString): Boolean; var WriteResult: Integer; AttemptCount, LockCount: Integer; begin Result := False; AttemptCount := 10; while AttemptCount > 0 do begin Dec(AttemptCount); LockCount := InterLockedIncrement(FTxLockCount); try if (LockCount = 1) then begin if HalfDuplex then begin FTxData := FTxData + AData; Result := True; end else begin WriteResult := SendStringInternal(AData); Result := (WriteResult = Length(AData)); end; AttemptCount := 0; end else Sleep(1); finally // release lock InterLockedDecrement(FTxLockCount); end; end; end; function TFtdiClient.ReadModemStatus(var AModemStatus: TModemStatus): Boolean; var ModemStat: LongWord; begin if FFtHandle <> FT_INVALID_HANDLE then begin Result := (FT_GetModemStatus(FFtHandle, @ModemStat) = FT_OK); if Result then begin AModemStatus.CTS := (ModemStat and FT_CTS) <> 0; AModemStatus.DSR := (ModemStat and FT_DSR) <> 0; AModemStatus.Ring := (ModemStat and FT_RI) <> 0; AModemStatus.Carrier := (ModemStat and FT_DCD) <> 0; end; end else Result := False; end; procedure TFtdiClient.SetDTR(AValue: Boolean); begin if FFtHandle <> FT_INVALID_HANDLE then begin if AValue then FT_SetDtr(FFtHandle) else FT_ClrDtr(FFtHandle); end; end; procedure TFtdiClient.SetRTS(AValue: Boolean); begin if FFtHandle <> FT_INVALID_HANDLE then begin if AValue then FT_SetRts(FFtHandle) else FT_ClrRts(FFtHandle); end; end; procedure TFtdiClient.SyncProc(); begin if not CalledFromThread then begin CalledFromThread := True; try if Assigned(OnIncomingMsgEvent) then OnIncomingMsgEvent(self, FRxData); finally CalledFromThread := False; end; end; end; procedure TFtdiClient.SyncProcOnError(); begin if not CalledFromThread then begin CalledFromThread := True; try if Assigned(OnError) then OnError(Self, FLastErrorStr); finally CalledFromThread := False; end; end; end; procedure TFtdiClient.SyncProcOnConnect(); begin if not CalledFromThread then begin CalledFromThread := True; try if Assigned(OnConnect) then OnConnect(Self); finally CalledFromThread := False; end; end; end; function TFtdiClient.GetPortName(): string; var ComPortNum: Longint; begin Result := ''; if (FFtHandle <> FT_INVALID_HANDLE) then begin FT_GetComPortNumber(FFtHandle, @ComPortNum); if ComPortNum <> -1 then Result := 'COM' + IntToStr(ComPortNum); end; end; { TDataPortFtdi } constructor TDataPortFtdi.Create(AOwner: TComponent); begin inherited Create(AOwner); FFlowControl := sfcNone; FFtdiClient := nil; end; destructor TDataPortFtdi.Destroy(); begin if Assigned(FFtdiClient) then begin FFtdiClient.OnIncomingMsgEvent := nil; FFtdiClient.OnError := nil; FFtdiClient.OnConnect := nil; FreeAndNil(FFtdiClient); end; inherited Destroy(); end; function TDataPortFtdi.CloseClient(): Boolean; begin Result := True; if Assigned(FFtdiClient) then begin Result := not FFtdiClient.CalledFromThread; if Result then begin FFtdiClient.OnIncomingMsgEvent := nil; FFtdiClient.OnError := nil; FFtdiClient.OnConnect := nil; FreeAndNil(FFtdiClient); end else FFtdiClient.Terminate(); end; end; procedure TDataPortFtdi.Open(const AInitStr: string); var ss: string; begin ss := AInitStr; // Set device description and serial number if ss <> '' then begin Self.FFtDeviceDescription := ExtractFirstWord(ss, ':'); Self.FFtSerialNumber := ExtractFirstWord(ss, ':'); end; inherited Open(ss); if CloseClient() then begin FFtdiClient := TFtdiClient.Create(Self); FFtdiClient.InitStr := FFtDeviceDescription + ':' + FFtSerialNumber; FFtdiClient.BaudRate := FBaudRate; FFtdiClient.DataBits := FDataBits; FFtdiClient.Parity := FParity; FFtdiClient.StopBits := FStopBits; FFtdiClient.FlowControl := FFlowControl; FFtdiClient.HalfDuplex := HalfDuplex; FFtdiClient.OnIncomingMsgEvent := OnIncomingMsgHandler; FFtdiClient.OnError := OnErrorHandler; FFtdiClient.OnConnect := OnConnectHandler; FFtdiClient.Suspended := False; // don't set FActive - will be set in OnConnect event after successfull connection end; end; procedure TDataPortFtdi.Close(); begin CloseClient(); inherited Close(); end; function TDataPortFtdi.Push(const AData: AnsiString): Boolean; begin Result := False; if Active and Assigned(FtdiClient) then begin Result := FtdiClient.SendAnsiString(AData); end; end; class function TDataPortFtdi.GetFtdiDeviceList(): string; var FtDeviceCount, DeviceIndex: LongWord; PortStatus: FT_Result; DeviceInfo: FT_Device_Info_Node; //FtDeviceInfoList: array of FT_Device_Info_Node; i: Integer; //sDevType: string; begin Result := ''; //PortStatus := FT_GetNumDevices(@FtDeviceCount, nil, FT_LIST_NUMBER_ONLY); //if PortStatus <> FT_OK then Exit; PortStatus := FT_CreateDeviceInfoList(@FtDeviceCount); if PortStatus <> FT_OK then Exit; //SetLength(FT_DeviceInfoList, FtDeviceCount); //PortStatus := FT_GetDeviceInfoList(FtDeviceInfoList, @FtDeviceCount); //if PortStatus <> FT_OK then Exit; for i := 1 to FtDeviceCount do begin DeviceIndex := i-1; DeviceInfo.Flags := 0; DeviceInfo.DeviceType := 0; DeviceInfo.ID := 0; DeviceInfo.LocID := 0; DeviceInfo.SerialNumber := ''; DeviceInfo.Description := ''; DeviceInfo.DeviceHandle := 0; PortStatus := FT_GetDeviceInfoDetail(DeviceIndex, @DeviceInfo.Flags, @DeviceInfo.DeviceType, @DeviceInfo.ID, @DeviceInfo.LocID, @DeviceInfo.SerialNumber, @DeviceInfo.Description, @DeviceInfo.DeviceHandle); if PortStatus = FT_OK then begin if (DeviceInfo.Flags and $1) > 0 then Continue; // device busy { //if (DeviceInfo.Flags and $2) > 0 then; // HighSpeed device case DeviceInfo.DeviceType of FT_DEVICE_232BM: sDevType := '232BM'; FT_DEVICE_232AM: sDevType := '232AM'; FT_DEVICE_100AX: sDevType := '100AX'; FT_DEVICE_UNKNOWN: sDevType := 'Unknown'; FT_DEVICE_2232C: sDevType := '2232C'; FT_DEVICE_232R: sDevType := '232R'; FT_DEVICE_2232H: sDevType := '2232H'; FT_DEVICE_4232H: sDevType := '4232H'; FT_DEVICE_232H: sDevType := '232H'; FT_DEVICE_X_SERIES: sDevType := 'X Series'; else sDevType := 'Unknown'; end; } if Length(Result) > 0 then Result := Result + sLineBreak; Result := Result + Trim(DeviceInfo.Description) + ':' + Trim(DeviceInfo.SerialNumber); end; end; end; function TDataPortFtdi.GetModemStatus(): TModemStatus; begin if Assigned(FtdiClient) then begin FtdiClient.ReadModemStatus(FModemStatus); end; Result := inherited GetModemStatus; end; procedure TDataPortFtdi.SetDTR(AValue: Boolean); begin if Assigned(FtdiClient) then FtdiClient.SetDTR(AValue); inherited SetDTR(AValue); end; procedure TDataPortFtdi.SetRTS(AValue: Boolean); begin if Assigned(FtdiClient) then FtdiClient.SetRTS(AValue); inherited SetRTS(AValue); end; (* class function TDataPortFtdi.GetFtdiDriverVersion(): string; var DrVersion: LongWord; begin Result := ''; {$ifdef WINDOWS} if not Active then Exit; if FT_GetDriverVersion(FtdiClient.FFtHandle, @DrVersion) = FT_OK then begin Result := IntToStr((DrVersion shr 16) and $FF) +'.'+IntToStr((DrVersion shr 8) and $FF) +'.'+IntToStr(DrVersion and $FF); end; {$endif} end; *) procedure TDataPortFtdi.SetBaudRate(AValue: Integer); begin inherited SetBaudRate(AValue); if Active then begin FtdiClient.BaudRate := FBaudRate; FtdiClient.Config(); end; end; procedure TDataPortFtdi.SetDataBits(AValue: Integer); begin inherited SetDataBits(AValue); if Active then begin FtdiClient.DataBits := FDataBits; FtdiClient.Config(); end; end; procedure TDataPortFtdi.SetFlowControl(AValue: TSerialFlowControl); begin FFlowControl := AValue; if Active then begin FtdiClient.FlowControl := FFlowControl; FtdiClient.Config(); end; end; procedure TDataPortFtdi.SetParity(AValue: AnsiChar); begin inherited SetParity(AValue); if Active then begin FtdiClient.Parity := FParity; FtdiClient.Config(); end; end; procedure TDataPortFtdi.SetStopBits(AValue: TSerialStopBits); begin inherited SetStopBits(AValue); if Active then begin FtdiClient.StopBits := FStopBits; FtdiClient.Config(); end; end; end.
unit ProductsSearchQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, ProductsBaseQuery, SearchInterfaceUnit, ApplyQueryFrame, StoreHouseListQuery, NotifyEvents, System.Generics.Collections, DSWrap, ProducersGroupUnit2; type TProductSearchW = class(TProductW) private FMode: TContentMode; public procedure AppendRows(AFieldName: string; AValues: TArray<String>); override; property Mode: TContentMode read FMode; end; TQueryProductsSearch = class(TQueryProductsBase) strict private private FClone: TFDMemTable; FGetModeClone: TFDMemTable; FOnBeginUpdate: TNotifyEventsEx; FOnEndUpdate: TNotifyEventsEx; const FEmptyAmount = 1; function GetCurrentMode: TContentMode; procedure DoAfterOpen(Sender: TObject); function GetIsClearEnabled: Boolean; function GetIsSearchEnabled: Boolean; function GetProductSearchW: TProductSearchW; { Private declarations } protected procedure ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override; procedure ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override; procedure ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); override; function CreateDSWrap: TDSWrap; override; procedure DoBeforePost(Sender: TObject); override; function GetHaveAnyChanges: Boolean; override; // procedure SetConditionSQL(const AConditionSQL, AMark: String; // ANotifyEventRef: TNotifyEventRef = nil); public constructor Create(AOwner: TComponent; AProducersGroup: TProducersGroup2); override; destructor Destroy; override; procedure AfterConstruction; override; procedure ClearSearchResult; procedure DoSearch(ALike: Boolean); procedure Search(AValues: TList<String>); overload; procedure SetSQLForSearch; property IsClearEnabled: Boolean read GetIsClearEnabled; property IsSearchEnabled: Boolean read GetIsSearchEnabled; property OnBeginUpdate: TNotifyEventsEx read FOnBeginUpdate; property OnEndUpdate: TNotifyEventsEx read FOnEndUpdate; property ProductSearchW: TProductSearchW read GetProductSearchW; { Public declarations } end; implementation {$R *.dfm} uses System.Math, RepositoryDataModule, System.StrUtils, StrHelper; constructor TQueryProductsSearch.Create(AOwner: TComponent; AProducersGroup: TProducersGroup2); begin inherited; // В режиме поиска - транзакции автоматом AutoTransaction := True; // Создаём два клона FGetModeClone := W.AddClone(Format('%s < %d', [W.PKFieldName, W.VirtualIDOffset])); FClone := W.AddClone(Format('%s <> null', [W.Value.FieldName])); TNotifyEventWrap.Create(W.AfterOpen, DoAfterOpen, W.EventList); FOnBeginUpdate := TNotifyEventsEx.Create(Self); FOnEndUpdate := TNotifyEventsEx.Create(Self); end; destructor TQueryProductsSearch.Destroy; begin FreeAndNil(FOnBeginUpdate); FreeAndNil(FOnEndUpdate); inherited; end; procedure TQueryProductsSearch.AfterConstruction; begin // Сохраняем первоначальный SQL inherited; SetSQLForSearch; end; procedure TQueryProductsSearch.ApplyDelete(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); begin if ProductSearchW.Mode = RecordsMode then inherited; end; procedure TQueryProductsSearch.ApplyInsert(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); begin // Ничего не делаем end; procedure TQueryProductsSearch.ApplyUpdate(ASender: TDataSet; ARequest: TFDUpdateRequest; var AAction: TFDErrorAction; AOptions: TFDUpdateRowOptions); begin if ProductSearchW.Mode = RecordsMode then inherited; end; function TQueryProductsSearch.GetCurrentMode: TContentMode; begin if (FDQuery.RecordCount = 0) or (FGetModeClone.RecordCount > 0) then Result := RecordsMode else Result := SearchMode; end; procedure TQueryProductsSearch.ClearSearchResult; begin SetSQLForSearch; W.RefreshQuery; end; function TQueryProductsSearch.CreateDSWrap: TDSWrap; begin Result := TProductSearchW.Create(FDQuery); end; procedure TQueryProductsSearch.DoAfterOpen(Sender: TObject); var I: Integer; begin W.SetFieldsRequired(False); W.SetFieldsReadOnly(False); // Добавляем пустую запись для поиска, если она необходима // AutoTransaction := True; for I := FDQuery.RecordCount to FEmptyAmount - 1 do begin FDQuery.Append; W.Value.F.AsString := ''; FDQuery.Post; FDQuery.ApplyUpdates(); FDQuery.CommitUpdates; end; FDQuery.First; // Вычисляем в какой режим мы перешли ProductSearchW.FMode := GetCurrentMode; // Выбираем нужный режим транзакции // AutoTransaction := ProductSearchW.Mode = SearchMode; end; procedure TQueryProductsSearch.DoBeforePost(Sender: TObject); begin // Предполагаем что при поиске // записи на склад не вставляются и проверка не нужна!!! if (FDQuery.State = dsEdit) and (GetCurrentMode = RecordsMode) then inherited; end; procedure TQueryProductsSearch.DoSearch(ALike: Boolean); var AConditionSQL: string; ANewSQL: string; m: TArray<String>; p: Integer; s: string; begin W.TryPost; // Формируем через запятую список из значений поля Value s := W.Value.AllValues; // Если поиск по пустой строке if s = '' then ALike := True; if ALike then begin AConditionSQL := ''; m := s.Split([',']); // Формируем несколько условий for s in m do begin AConditionSQL := IfThen(AConditionSQL.IsEmpty, '', ' or '); AConditionSQL := AConditionSQL + Format('%s like %s', [W.Value.FullName, QuotedStr(s + '%')]); end; // if not AConditionSQL.IsEmpty then // AConditionSQL := Format(' and (%s)', [AConditionSQL]); end else begin AConditionSQL := Format('instr('',''||:%s||'','', '',''||%s||'','') > 0', [W.Value.FieldName, W.Value.FullName]); // ' and (instr('',''||:Value||'','', '',''||p.Value||'','') > 0)'; end; if AConditionSQL <> '' then begin p := SQL.IndexOf('1=1'); Assert(p > 0); ANewSQL := SQL.Replace('1=1', AConditionSQL); p := ANewSQL.IndexOf('2=2'); Assert(p > 0); ANewSQL := ANewSQL.Replace('2=2', AConditionSQL); end; FDQuery.Close; FDQuery.SQL.Text := ANewSQL; if not ALike then begin SetParamTypeEx(W.Value.FieldName, s, ptInput, ftWideString); end; FDQuery.Open; end; // Есть-ли изменения не сохранённые в БД function TQueryProductsSearch.GetHaveAnyChanges: Boolean; begin Result := False; case ProductSearchW.Mode of RecordsMode: Result := inherited; SearchMode: Result := False; else Assert(False); end; end; function TQueryProductsSearch.GetIsClearEnabled: Boolean; begin Result := (ProductSearchW.Mode = RecordsMode); if not Result then begin Result := FClone.RecordCount > 0; end; end; function TQueryProductsSearch.GetIsSearchEnabled: Boolean; begin Result := (ProductSearchW.Mode = SearchMode) and (FClone.RecordCount > 0); end; function TQueryProductsSearch.GetProductSearchW: TProductSearchW; begin Result := W as TProductSearchW; end; procedure TQueryProductsSearch.Search(AValues: TList<String>); begin FOnBeginUpdate.CallEventHandlers(Self); try // Очищаем результат поиска ClearSearchResult; // Добавляем те записи, которые будем искать на складе ProductSearchW.AppendRows(W.Value.FieldName, AValues.ToArray); // Осуществляем поиск DoSearch(False); finally FOnEndUpdate.CallEventHandlers(Self); end; end; procedure TQueryProductsSearch.SetSQLForSearch; var p: Integer; begin // Меняем запрос чтобы изначально не выбиралось ни одной записи p := SQL.IndexOf('0=0'); Assert(p > 0); FDQuery.SQL.Text := SQL.Replace('0=0', Format('%s=0', [W.ID.FieldName])); end; procedure TProductSearchW.AppendRows(AFieldName: string; AValues: TArray<String>); begin if Length(AValues) = 0 then Exit; if Mode = SearchMode then begin // Удаляем пустую строку if Value.F.AsString.IsEmpty then DataSet.Delete; inherited; end; end; end.
unit U_ValidaCPF_CNPJ; interface uses System.SysUtils,StrUtils; type TValidaCPF_CNPJ = class public function ValidarCPF(numCPF: string): boolean; function isCNPJ(CNPJ: string) :boolean; end; implementation { TValidaCPF_CNPJ } function TValidaCPF_CNPJ.isCNPJ(CNPJ: string): boolean; var dig13, dig14: string; sm, i, r, peso: integer; begin // length - retorna o tamanho da string do CNPJ (CNPJ é um número formado por 14 dígitos) if ((CNPJ = '00000000000000') or (CNPJ = '11111111111111') or (CNPJ = '22222222222222') or (CNPJ = '33333333333333') or (CNPJ = '44444444444444') or (CNPJ = '55555555555555') or (CNPJ = '66666666666666') or (CNPJ = '77777777777777') or (CNPJ = '88888888888888') or (CNPJ = '99999999999999') or (length(CNPJ) <> 14)) then begin isCNPJ := false; exit; end; // "try" - protege o código para eventuais erros de conversão de tipo através da função "StrToInt" try { *-- Cálculo do 1o. Digito Verificador --* } sm := 0; peso := 2; for i := 12 downto 1 do begin // StrToInt converte o i-ésimo caractere do CNPJ em um número sm := sm + (StrToInt(CNPJ[i]) * peso); peso := peso + 1; if (peso = 10) then peso := 2; end; r := sm mod 11; if ((r = 0) or (r = 1)) then dig13 := '0' else str((11-r):1, dig13); // converte um número no respectivo caractere numérico { *-- Cálculo do 2o. Digito Verificador --* } sm := 0; peso := 2; for i := 13 downto 1 do begin sm := sm + (StrToInt(CNPJ[i]) * peso); peso := peso + 1; if (peso = 10) then peso := 2; end; r := sm mod 11; if ((r = 0) or (r = 1)) then dig14 := '0' else str((11-r):1, dig14); { Verifica se os digitos calculados conferem com os digitos informados. } if ((dig13 = CNPJ[13]) and (dig14 = CNPJ[14])) then isCNPJ := true else isCNPJ := false; except isCNPJ := false end; end; function TValidaCPF_CNPJ.ValidarCPF(numCPF: string): boolean; var cpf: string; x, total, dg1, dg2: Integer; ret: boolean; begin ret := True; for x := 1 to Length(numCPF) do if not (numCPF[x] in ['0'..'9', '-', '.', ' ']) then ret := False; if ret then begin ret := True; cpf := ''; for x := 1 to Length(numCPF) do if numCPF[x] in ['0'..'9'] then cpf := cpf + numCPF[x]; if Length(cpf) <> 11 then ret := False; if ret then begin //1° dígito total := 0; for x := 1 to 9 do total := total + (StrToInt(cpf[x]) * x); dg1 := total mod 11; if dg1 = 10 then dg1 := 0; //2° dígito total := 0; for x := 1 to 8 do total := total + (StrToInt(cpf[x + 1]) * (x)); total := total + (dg1 * 9); dg2 := total mod 11; if dg2 = 10 then dg2 := 0; //Validação final if (dg1 = StrToInt(cpf[10])) and (dg2 = StrToInt(cpf[11])) then ret := True else ret := False; //Inválidos case AnsiIndexStr(cpf,['00000000000','11111111111','22222222222','33333333333','44444444444', '55555555555','66666666666','77777777777','88888888888','99999999999']) of 0..9: ret := False; end; end else begin //Se não informado deixa passar if cpf = '' then ret := True; end; end; result := ret; end; end. (* interface type TfrmCadClientes = class(TForm) var frmCadClientes: TfrmCadClientes; implementation *)
unit uDataAccessLayer_a; interface type TAbstractDataRow = class protected function GetMetaField(AIdx: integer): TMdField; virtual; abstract; function GetIntValue(AIdx: integer): integer; virtual; abstract; ... function GetDateTimeValue(AIdx: integer): TDateTime; virtual; abstract; function GetIsNull(AIdx: integer): boolean; virtual; abstract; public procedure SetIntValue(AIdx: integer; AValue: integer); virtual; abstract; ... procedure SetDateTimeValue(AIdx: integer; AValue: TDateTime); virtual; abstract; procedure ClearField(AIdx: integer); virtual; abstract; property MetaField[AIdx: integer]: TMdField read getMetaField; property IntValue[AIdx: integer]: integer read getIntValue; ... property DateTimeValue[AIdx: integer]: TDateTime read getDateTimeValue; property IsNull[AIdx: integer]: boolean read getIsNull; end; TAbstractDataSet = class(TAbstractDataRow) public procedure Append; virtual; abstract; function GetKeyValue: TKeyVal; virtual; abstract; procedure SetRelation(AValue: TKeyVal); virtual; abstract; end; TAbstractWriter = class public function GetDataSet(ANode: PMdNode; var ADataSet: TAbstractDataSet): boolean; virtual; abstract; // alters data store structures according to metadata procedure updateDataStructure(ANewMetaDataRoot: PMdNode; AVerbosely: boolean); virtual; abstract; function GetHasData(ANode: PMdNode): boolean; virtual; abstract; end; implementation end.
unit vinverify; { '*************************************************************************** '** Written by: Richard Knechtel '** Ported to Delphi: by Greg Sherman on 9/24/2003 '** Contact: krs3@uswest.net / krs3@quest.net '** http://www.users.uswest.net/~krs3/ '** Date: 11/01/2000 '** '** Description: '** This function will calculate the Check Digit for a vehilces VIN number '** and verify that the passed VIN's check digit is valid. '** '** Parameters: '** This function requires a 17 character VIN number to be passed to it. '** It will return a Boolean value: '** If the VIN Check Digit is valid the functin will return TRUE. '** If the VIN Check Digit as not-valid the function will return FALSE. '** '** Notes: '** If the Check Digit is valid then the VIN number is valid. '** A Vehicle VIN number contains 17 characters. '** The 9th position in the VIN is the Check Digit. '** '*************************************************************************** '********* LICENSE ************************************/ '/* */ '/* This program is free software; you can redistribute */ '/* it and/or modify it under the terms of the GNU */ '/* General Public License as published by the Free */ '/* Software Foundation; either version 2 of the License,*/ '/* or (at your option) any later version. */ '/* */ '/* This program is distributed in the hope that it will */ '/* be useful, but WITHOUT ANY WARRANTY; without even */ '/* the implied warranty of MERCHANTABILITY or FITNESS */ '/* FOR A PARTICULAR PURPOSE. See the GNU General */ '/* Public License for more details. */ '/* */ '/* You should have received a copy of the GNU General */ '/* Public License along with this program; if not, */ '/* write to the */ '/* Free Software */ '/* Foundation, Inc., 675 Mass Ave, */ '/* Cambridge, MA 02139, USA. */ '/* */ '/********************************************************/ } interface function ValidVIN(VIN: String): Boolean; implementation uses SysUtils, miscroutines; function ValidVIN(VIN: String): Boolean; var strVIN: String; { String representation of VIN } strVINPos: Char; { Position of VIN character } Idx: Integer; { Index used to parse the position out of the VIN } lngSubTotal: integer;{ Sub Total used in multipling the "Numeric Factor" by the "Weight Factor" } lngTotal: integer; { Used to total the VIN } intCalcCD: Integer; { This is OUR calculated check digit - compare to 9th position in VIN } strCalcCD: String; { String verson of Check Digit } strVINCD: String; { This is the string version Check Digit from the passed VIN # } intNV: Integer; { Used to find "Numeric Value" } intWF: integer; { Used to find "Weight Factor" } begin lngSubTotal := 0; lngTotal := 0; {** Get a VIN Number to Work with } strVIN := Trim(VIN); For Idx := 1 To 17 do // Idx = The Position - a VIN Contains 17 characters. begin // We do not want to do anything with the 9th position // - It IS the Check Digit. If Idx <> 9 Then begin // First: a numerical value is assigned to letters in the VIN. // The letters I, O and Q are not allowed so on the positions // these letters the numerical sequence skips: strVINPos := strVIN[Idx]; IntNV := 0; IntWF := 0; Case strVINPos of '0' : intNV := 0; '1', 'A', 'J' : intNV := 1; '2', 'B', 'K', 'S' : intNV := 2; '3', 'C', 'L', 'T' : intNV := 3; '4', 'D', 'M', 'U' : intNV := 4; '5', 'E', 'N', 'V' : intNV := 5; '6', 'F','W' : intNV := 6; '7', 'G', 'P', 'X' : intNV := 7; '8', 'H','Y' : intNV := 8; '9', 'R', 'Z' : intNV := 9; end; { Second: a weight factor is assigned to all positions of the VIN, except of course for the 9th position, being the position of the check digit, as follows: } case Idx of // Idx = The Position 1, 11 : intWF := 8; 2, 12 : intWF := 7; 3, 13 : intWF := 6; 4, 14 : intWF := 5; 5, 15 : intWF := 4; 6, 16 : intWF := 3; 7, 17 : intWF := 2; 8 : intWF := 10; 10 : intWF := 9; end; { Then the Numbers and the Numercial Values of the letters in the VIN must be multiplied by their assigned Wieght Factor and the resulting products added up. } lngSubTotal := lngSubTotal + (intNV * intWF); lngTotal := lngSubTotal; end; { if } end; { for } {** Find the whole number remainder - (This is the Check Digit) } intCalcCD := lngTotal Mod 11; // Get the Calculated Check Digit strVINCD := VIN[9]; // Get the Passed VIN's Check Digit output(strVinCD); {** If the numerical remainder is 10 } {** then the Check Digit will be the Letter "X" } If intCalcCD = 10 Then strCalcCD := 'X' else strCalcCD := IntToStr(intCalcCD); {** Compare the calculated Check Digit with the Check Digit from the} {** Passed VIN # to see if they match.} If strCalcCD = strVINCD Then result := True { If Check Digit is valid return TRUE } else result := False; {** If Check Digit is not-valid return FALSE } end; end.
unit UComponentTray.SettingsDlg; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls; type TSettingsDlg = class(TForm) Button1: TButton; Button2: TButton; rgStyle: TRadioGroup; rgPosition: TRadioGroup; GroupBox1: TGroupBox; cbSplitterEnabled: TCheckBox; cbSplitterColor: TColorBox; private { Private 宣言 } public { Public 宣言 } end; function ShowSettingsDlg(var Style, Position: Integer; var SplitterEnabled: Boolean; var SplitterColor: TColor): Boolean; implementation {$R *.dfm} function ShowSettingsDlg(var Style, Position: Integer; var SplitterEnabled: Boolean; var SplitterColor: TColor): Boolean; var dlg: TSettingsDlg; begin dlg := TSettingsDlg.Create(nil); try dlg.rgStyle.ItemIndex := Style; dlg.rgPosition.ItemIndex := Position; dlg.cbSplitterEnabled.Checked := SplitterEnabled; dlg.cbSplitterColor.Selected := SplitterColor; Result := dlg.ShowModal = mrOk; if not Result then Exit; Style := dlg.rgStyle.ItemIndex; Position := dlg.rgPosition.ItemIndex; SplitterEnabled := dlg.cbSplitterEnabled.Checked; SplitterColor := dlg.cbSplitterColor.Selected; finally dlg.Free; end; end; end.
unit caActions; {$INCLUDE ca.inc} interface uses // Standard Delphi units  Windows, Classes, ActnList, StdCtrls, Forms, Controls, Dialogs, // ca units  caTypes, caUtils, caConsts, caForms; type TcaCloseFormEvent = procedure(Sender: TObject; SaveNeeded: Boolean) of object; //--------------------------------------------------------------------------- // TcaFormAction   //--------------------------------------------------------------------------- TcaFormAction = class(TAction) protected // Protected methods  function GetForm(Target: TObject): TForm; virtual; public // Public methods  function HandlesTarget(Target: TObject): Boolean; override; procedure UpdateTarget(Target: TObject); override; end; //--------------------------------------------------------------------------- // TcaCloseFormAction   //--------------------------------------------------------------------------- TcaCloseFormAction = class(TcaFormAction) private // Property fields  FCloseNeeded: Boolean; FHasChanged: Boolean; FOnBeforeCloseForm: TcaCloseFormEvent; // Event handlers  procedure FormCloseEvent(Sender: TObject; var Action: TCloseAction); protected // Protected methods  procedure DoBeforeCloseForm(SaveNeeded: Boolean); virtual; public // Public methods  procedure ExecuteTarget(Target: TObject); override; procedure UpdateTarget(Target: TObject); override; // Public properties  property HasChanged: Boolean read FHasChanged write FHasChanged; published // Published properties  property OnBeforeCloseForm: TcaCloseFormEvent read FOnBeforeCloseForm write FOnBeforeCloseForm; end; //--------------------------------------------------------------------------- // TcaStayOnTopFormAction   //--------------------------------------------------------------------------- TcaStayOnTopFormAction = class(TcaFormAction) public procedure ExecuteTarget(Target: TObject); override; end; //--------------------------------------------------------------------------- // TcaCheckAction   //--------------------------------------------------------------------------- TcaCheckAction = class(TAction) private // Private fields  FChecked: Boolean; public // Public methods  function HandlesTarget(Target: TObject): Boolean; override; procedure UpdateTarget(Target: TObject); override; // Properties  property Checked: Boolean read FChecked write FChecked; end; //--------------------------------------------------------------------------- // TcaDialogAction   //--------------------------------------------------------------------------- TcaDialogAction = class(TAction) private // Property fields  FDialog: TOpenDialog; FSucceeded: Boolean; protected // Protected methods  function CreateDialog: TOpenDialog; virtual; abstract; public // Create/Destroy  constructor Create(AOwner: TComponent); override; destructor Destroy; override; // Public methods  function Execute: Boolean; override; // Properties  property Dialog: TOpenDialog read FDialog; property Succeeded: Boolean read FSucceeded; end; //--------------------------------------------------------------------------- // TcaOpenDialogAction   //--------------------------------------------------------------------------- TcaOpenDialogAction = class(TcaDialogAction) protected // Protected methods  function CreateDialog: TOpenDialog; override; end; //--------------------------------------------------------------------------- // TcaSaveDialogAction   //--------------------------------------------------------------------------- TcaSaveDialogAction = class(TcaDialogAction) protected // Protected methods  function CreateDialog: TOpenDialog; override; end; implementation uses TypInfo; //--------------------------------------------------------------------------- // TcaFormAction   //--------------------------------------------------------------------------- // Public methods  function TcaFormAction.HandlesTarget(Target: TObject): Boolean; begin Result := Target is TForm; end; procedure TcaFormAction.UpdateTarget(Target: TObject); begin Enabled := Target <> nil; end; // Protected methods  function TcaFormAction.GetForm(Target: TObject): TForm; begin Result := Target as TForm; end; //--------------------------------------------------------------------------- // TcaCloseFormAction   //--------------------------------------------------------------------------- // Public methods  procedure TcaCloseFormAction.ExecuteTarget(Target: TObject); var Response: TcaMsgDialogResponse; SaveNeeded: Boolean; begin SaveNeeded := False; FCloseNeeded := True; if FHasChanged then begin Response := Utils.QuerySaveData(GetForm(Target).Handle); SaveNeeded := Response = mgYes; FCloseNeeded := Response <> mgCancel; end; if FCloseNeeded then begin DoBeforeCloseForm(SaveNeeded); GetForm(Target).OnClose := nil; GetForm(Target).Close; end; end; procedure TcaCloseFormAction.UpdateTarget(Target: TObject); begin inherited; if not Assigned(GetForm(Target).OnClose) then GetForm(Target).OnClose := FormCloseEvent; end; // Protected methods  procedure TcaCloseFormAction.DoBeforeCloseForm(SaveNeeded: Boolean); begin if Assigned(FOnBeforeCloseForm) then FOnBeforeCloseForm(Self, SaveNeeded); end; // Event handlers  procedure TcaCloseFormAction.FormCloseEvent(Sender: TObject; var Action: TCloseAction); begin ExecuteTarget(Sender); if not FCloseNeeded then Action := caNone; end; //--------------------------------------------------------------------------- // TcaStayOnTopFormAction   //--------------------------------------------------------------------------- procedure TcaStayOnTopFormAction.ExecuteTarget(Target: TObject); begin Checked := not Checked; FormUtils.SetStayOnTopState(GetForm(Target), Checked); end; //--------------------------------------------------------------------------- // TcaCheckAction   //--------------------------------------------------------------------------- function TcaCheckAction.HandlesTarget(Target: TObject): Boolean; begin Result := (Target is TControl) and IsPublishedProp(Target, cChecked) and (TControl(Target).Action = Self); if Result then FChecked := GetPropValue(Target, cChecked, False); end; procedure TcaCheckAction.UpdateTarget(Target: TObject); begin Enabled := Target <> nil; end; //--------------------------------------------------------------------------- // TcaDialogAction   //--------------------------------------------------------------------------- constructor TcaDialogAction.Create(AOwner: TComponent); begin inherited; FDialog := CreateDialog; end; destructor TcaDialogAction.Destroy; begin FDialog.Free; inherited; end; function TcaDialogAction.Execute: Boolean; begin FSucceeded := FDialog.Execute; Result := inherited Execute; end; //--------------------------------------------------------------------------- // TcaOpenDialogAction   //--------------------------------------------------------------------------- // Protected methods  function TcaOpenDialogAction.CreateDialog: TOpenDialog; begin Result := TOpenDialog.Create(nil); end; //--------------------------------------------------------------------------- // TcaSaveDialogAction   //--------------------------------------------------------------------------- function TcaSaveDialogAction.CreateDialog: TOpenDialog; begin Result := TSaveDialog.Create(nil); end; end.
unit AContatosProspect; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, ExtCtrls, PainelGradiente, StdCtrls, Buttons, Componentes1, Localizacao, Grids, CGrades, UnDados, UnProspect; type TFContatosProspect = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor3: TPanelColor; BGravar: TBitBtn; BCancelar: TBitBtn; BFechar: TBitBtn; PanelColor1: TPanelColor; SpeedButton1: TSpeedButton; Label1: TLabel; Label2: TLabel; EProspect: TEditLocaliza; Localiza: TConsultaPadrao; Grade: TRBStringGridColor; EProfissao: TEditLocaliza; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BFecharClick(Sender: TObject); procedure BCancelarClick(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure EProfissaoCadastrar(Sender: TObject); procedure EProfissaoRetorno(Retorno1, Retorno2: String); procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure GradeNovaLinha(Sender: TObject); procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure GradeKeyPress(Sender: TObject; var Key: Char); private VprCodProspect: Integer; VprAcao: Boolean; VprEmail : String; VprDContato: TRBDContatoProspect; VprContatos: TList; procedure CarTitulosGrade; function ExisteProfissao : boolean; procedure CarDContatoClasse; public function CadastraContatos(VpaCodProspect: Integer): Boolean; end; var FContatosProspect: TFContatosProspect; implementation uses APrincipal, FunString, UnClientes, Constantes, FunData, FunObjeto, ConstMsg, AProfissoes; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFContatosProspect.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprAcao:= False; VprContatos:= TList.Create; Grade.ADados:= VprContatos; CarTitulosGrade; end; { ******************* Quando o formulario e fechado ************************** } procedure TFContatosProspect.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } FreeTObjectsList(VprContatos); VprContatos.Free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFContatosProspect.CarTitulosGrade; begin Grade.Cells[1,0]:= 'Nome Contato'; Grade.Cells[2,0]:= 'Data Nascimento'; Grade.Cells[3,0]:= 'Telefone'; Grade.Cells[4,0]:= 'Celular'; Grade.Cells[5,0]:= 'E-Mail'; Grade.Cells[6,0]:= 'Código'; Grade.Cells[7,0]:= 'Profissão'; Grade.Cells[8,0]:= 'Observações'; Grade.Cells[9,0]:= 'Marketing'; end; {******************************************************************************} function TFContatosProspect.CadastraContatos(VpaCodProspect: Integer): Boolean; begin VprCodProspect:= VpaCodProspect; EProspect.AInteiro:= VpaCodProspect; EProspect.Atualiza; FunProspect.CarDContatoProspect(VpaCodProspect,VprContatos); Grade.CarregaGrade; ActiveControl:= Grade; Showmodal; Result:= VprAcao; end; {******************************************************************************} procedure TFContatosProspect.BFecharClick(Sender: TObject); begin Close; end; {******************************************************************************} procedure TFContatosProspect.BCancelarClick(Sender: TObject); begin Close; end; {******************************************************************************} procedure TFContatosProspect.BGravarClick(Sender: TObject); var VpfResultado: String; begin VpfResultado:= FunProspect.GravaDContatosProspect(VprCodProspect,VprContatos); if VpfResultado = '' then begin VprAcao:= True; Close; end else Aviso(VpfResultado); end; {******************************************************************************} procedure TFContatosProspect.GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDContato:= TRBDContatoProspect(VprContatos.Items[VpaLinha-1]); Grade.Cells[1,VpaLinha]:= VprDContato.NomContato; if VprDContato.DatNascimento > MontaData(1,1,1900) then Grade.Cells[2,VpaLinha]:= FormatDateTime('DD/MM/YYYY',VprDContato.DatNascimento) else Grade.Cells[2,VpaLinha]:= ''; Grade.Cells[3,VpaLinha]:= VprDContato.FonContato; Grade.Cells[4,VpaLinha]:= VprDContato.CelContato; Grade.Cells[5,VpaLinha]:= VprDContato.EMailContato; if VprDContato.CodProfissao <> 0 then Grade.Cells[6,VpaLinha]:= IntToStr(VprDContato.CodProfissao) else Grade.Cells[6,VpaLinha]:= ''; Grade.Cells[7,VpaLinha]:= VprDContato.NomProfissao; Grade.Cells[8,VpaLinha]:= VprDContato.DesObservacoes; Grade.Cells[9,VpaLinha]:= VprDContato.AceitaEMarketing; end; {******************************************************************************} procedure TFContatosProspect.GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos:= True; { //permitir cadastrar os prospect sem nome para colocar os contatos da newsletter if Grade.Cells[1,Grade.ALinha] = '' then begin Aviso('NOME DO CONTATO NÃO PREENCHIDO!!!'#13'É necessário preencher o nome do contato.'); VpaValidos:= False; Grade.Col:= 1; end else} if not ExisteProfissao then begin Aviso('PROFISSÃO INVÁLIDA!!!'#13'A profissão digitada não é válida.'); VpaValidos:= False; Grade.Col:= 6; end else if Grade.Cells[9,Grade.ALinha] = '' then begin Aviso('EMARKETING NÃO PREENCHIDO!!!'#13'É necessário preencher se o prospect aceita telemarketing.'); VpaValidos:= False; Grade.Col:= 1; end; if VpaValidos then CarDContatoClasse; end; {******************************************************************************} function TFContatosProspect.ExisteProfissao: boolean; begin result:= true; if Grade.Cells[6,Grade.ALinha] <> '' then begin result:= FunClientes.ExisteProfissao(StrToInt(Grade.Cells[6,Grade.ALinha])); if result then begin EProfissao.Text := Grade.Cells[6,Grade.ALinha]; EProfissao.Atualiza; end; end; end; {******************************************************************************} procedure TFContatosProspect.CarDContatoClasse; begin VprDContato.CodProspect:= VprCodProspect; VprDContato.CodUsuario:= Varia.CodigoUsuario; VprDContato.NomContato:= Grade.Cells[1,Grade.ALinha]; try VprDContato.DatNascimento:= StrToDate(Grade.Cells[2,Grade.ALinha]); except VprDContato.DatNascimento:= MontaData(1,1,1900); end; if DeletaChars(DeletaChars(DeletaChars(DeletaEspaco(Grade.Cells[3,Grade.ALinha]),'('),')'),'-') <> '' then VprDContato.FonContato:= Grade.Cells[3,Grade.ALinha] else VprDContato.FonContato:= ''; if DeletaChars(DeletaChars(DeletaChars(DeletaEspaco(Grade.Cells[4,Grade.ALinha]),'('),')'),'-') <> '' then VprDContato.CelContato:= Grade.Cells[4,Grade.ALinha] else VprDContato.CelContato:= ''; VprDContato.EMailContato:= Grade.Cells[5,Grade.ALinha]; if Grade.Cells[6,Grade.ALinha] <> '' then VprDContato.CodProfissao:= StrToInt(Grade.Cells[6,Grade.ALinha]) else VprDContato.CodProfissao:= 0; VprDContato.NomProfissao:= Grade.Cells[7,Grade.ALinha]; VprDContato.DesObservacoes:= Grade.Cells[8,Grade.ALinha]; VprDContato.AceitaEMarketing:= Grade.Cells[9,Grade.ALinha]; if Grade.AEstadoGrade in [egEdicao] then begin if (VprDContato.EmailContato <> VprEmail) then VprDContato.IndExportadoEficacia := false; end; end; {******************************************************************************} procedure TFContatosProspect.EProfissaoCadastrar(Sender: TObject); begin FProfissoes:= TFProfissoes.CriarSDI(self,'',FPrincipal.VerificaPermisao('FProfissoes')); FProfissoes.BotaoCadastrar1.Click; FProfissoes.showmodal; FProfissoes.free; Localiza.AtualizaConsulta; end; {******************************************************************************} procedure TFContatosProspect.EProfissaoRetorno(Retorno1, Retorno2: String); begin Grade.Cells[6,Grade.ALinha]:= Retorno1; Grade.Cells[7,Grade.ALinha]:= Retorno2; end; {******************************************************************************} procedure TFContatosProspect.GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); begin case ACol of 2: Value:= '!99\/99\/0000;1;'; 3, 4: Value:= '!\(00\)>#000-0000;1; '; 6: Value:= '00000;0; '; end; end; {******************************************************************************} procedure TFContatosProspect.GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of 114: case Grade.AColuna of 6: EProfissao.AAbreLocalizacao; end; end; end; {******************************************************************************} procedure TFContatosProspect.GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprContatos.Count > 0 then begin VprDContato:= TRBDContatoProspect(VprContatos.Items[VpaLinhaAtual-1]); VprEmail := VprDContato.EmailContato; end; end; {******************************************************************************} procedure TFContatosProspect.GradeNovaLinha(Sender: TObject); begin VprDContato:= TRBDContatoProspect.Cria; VprContatos.Add(VprDContato); VprDContato.AceitaEMarketing:= 'S'; Grade.Cells[9,Grade.ALinha]:= 'S'; end; {******************************************************************************} procedure TFContatosProspect.GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin if Grade.AEstadoGrade in [egEdicao, egInsercao] then begin if Grade.AColuna <> ACol then begin case Grade.AColuna of 6: if not ExisteProfissao then EProfissao.AAbreLocalizacao; end; end; end; end; {******************************************************************************} procedure TFContatosProspect.GradeKeyPress(Sender: TObject; var Key: Char); begin case Grade.Col of 5 : begin if key in [' ',',','/',';','ç','\','ã',':'] then key := #0; end; 9 : begin if not (Key in ['s','S','n','N',#8]) then Key:= #0 else if Key = 's' Then Key:= 'S' else if key = 'n' Then Key:= 'N'; end; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFContatosProspect]); end.
unit matrix; {$mode objfpc} {$modeswitch advancedrecords} {$h+} interface uses SysUtils, base; type TMatrix = record strict private function GetColumn(AColumn: longint): TVector; function GetCopy: TMatrix; function GetHermitian: TMatrix; function GetMinorColumn(AStartRow, AStartColumn, AColumn: longint): TVector; function GetRow(ARow: longint): TVector; function GetTranspose: TMatrix; function GetValue(ARow, AColumn: longint): double; procedure SetColumn(AColumn: longint; AValue: TVector); procedure SetRow(ARow: longint; AValue: TVector); procedure SetValue(ARow, AColumn: longint; AValue: double); public Data: array of double; Rows, Columns: longint; function Submatrix(AStartRow,AStartColumn: longint): TMatrix; function Submatrix(AStartRow,AStartColumn,ARows,AColumns: longint): TMatrix; function Extend(ARowS,AColumnS, ARowE,AColumnE: longint; AIdent: boolean): TMatrix; constructor Identity(ARows, AColumns: longint); constructor Identity(N: longint); constructor Create(ARows, AColumns: longint); constructor Create(ARows, AColumns: longint; const AValues: array of double); procedure SubScaled(ASrc, ADst: longint; AValue: double); procedure ScaleRow(ARow: longint; AValue: double); procedure Scale(AValue: double); function Dump: string; property Transpose: TMatrix read GetTranspose; property Hermitian: TMatrix read GetHermitian; property Copy: TMatrix read GetCopy; property Value[ARow, AColumn: longint]: double read GetValue write SetValue; default; property Row[ARow: longint]: TVector read GetRow write SetRow; property Column[AColumn: longint]: TVector read GetColumn write SetColumn; property MinorColumn[AStartRow,AStartColumn,AColumn: longint]: TVector read GetMinorColumn; end; operator explicit(const A: TVector): TMatrix; operator explicit(const A: TMatrix): TVector; operator -(const A: TMatrix): TMatrix; operator +(const A, B: TMatrix): TMatrix; operator -(const A, B: TMatrix): TMatrix; operator * (const A, B: TMatrix): TMatrix; operator * (const A: TMatrix; const B: double): TMatrix; operator * (const B: double; const A: TMatrix): TMatrix; procedure LUDecompose(const AMatrix: TMatrix; out AL, AU: TMatrix); procedure QRDecomposeGS(const AMatrix: TMatrix; out AQ, AR: TMatrix); // Gram-Schmidt procedure QRDecomposeHR(const AMatrix: TMatrix; out AQ, AR: TMatrix); // Householder reflection function ReduceHR(const AMatrix: TMatrix): TMatrix; // Reduction to tridiagonal by Householder reflection function CholeskyDecompose(const AMatrix: TMatrix): TMatrix; // Returns L where AMatrix=L*L.Transpose procedure ArnoldiIteration(const A: TMatrix; out H, Q: TMatrix); function SolveLU(const AL, AU, Ab: TMatrix): TMatrix; function InvertGJ(const A: TMatrix): TMatrix; function InvertLU(const AL, AU: TMatrix): TMatrix; function Determinant(const AMatrix: TMatrix): double; function DeterminantUnitary(const AMatrix: TMatrix): double; function DeterminantTriangular(const AMatrix: TMatrix): double; implementation uses Math, ops; operator explicit(const A: TVector): TMatrix; begin result:=TMatrix.Create(length(a), 1, a); end; operator explicit(const A: TMatrix): TVector; begin Assert((a.Rows = 1) or (a.Columns = 1)); Result := copy(a.Data); end; operator-(const A: TMatrix): TMatrix; var pa, pr: PDouble; i: longint; begin pa := @a.Data[0]; Result := TMatrix.Create(a.Rows, a.Columns); pr := @Result.Data[0]; for i := 0 to high(a.Data) do begin pr^ := -pa^; Inc(pa); Inc(pr); end; end; operator +(const A, B: TMatrix): TMatrix; var pa, pb, pr: PDouble; i: longint; begin Assert(a.Rows = b.Rows); Assert(a.Columns = b.Columns); pa := @a.Data[0]; pb := @b.Data[0]; Result := TMatrix.Create(a.Rows, a.Columns); pr := @Result.Data[0]; for i := 0 to high(a.Data) do begin pr^ := pa^ + pb^; Inc(pa); Inc(pb); Inc(pr); end; end; operator -(const A, B: TMatrix): TMatrix; var pa, pb, pr: PDouble; i: longint; begin Assert(a.Rows = b.Rows); Assert(a.Columns = b.Columns); pa := @a.Data[0]; pb := @b.Data[0]; Result := TMatrix.Create(a.Rows, a.Columns); pr := @Result.Data[0]; for i := 0 to high(a.Data) do begin pr^ := pa^ - pb^; Inc(pa); Inc(pb); Inc(pr); end; end; operator * (const A, B: TMatrix): TMatrix; var pa, pb, pr: PDouble; i, i2, i3: longint; sum: double; begin Assert(a.Columns = b.Rows); Result := TMatrix.Create(a.Rows, b.Columns); pr := @Result.Data[0]; for i := 0 to a.Rows - 1 do for i2 := 0 to b.Columns - 1 do begin sum := 0; pa := @a.Data[i * a.Columns]; pb := @b.Data[i2]; for i3 := 0 to a.Columns - 1 do begin sum := sum + pa^ * pb^; Inc(pa); Inc(pb, b.Columns); end; pr^ := sum; Inc(pr); end; end; operator*(const A: TMatrix; const B: double): TMatrix; begin result:=A.Copy; result.Scale(b); end; operator*(const B: double; const A: TMatrix): TMatrix; begin result:=A.Copy; result.Scale(b); end; procedure LUDecompose(const AMatrix: TMatrix; out AL, AU: TMatrix); var i, i2: longint; t: Double; Ln: TMatrix; begin assert(AMatrix.Columns = AMatrix.Rows, 'Only square matrices supported in LUDecompose'); AL := TMatrix.Identity(AMatrix.Rows); AU:=AMatrix; for i:=0 to AMatrix.Rows-2 do begin Ln:=TMatrix.Identity(AMatrix.Rows); t:=AU[i,i]; assert(t<>0, 'Zero entry in diagonal at iteration '+inttostr(i)); t:=1/t; for i2:=i+1 to AMatrix.Rows-1 do Ln[i2,i]:=-AU[i2,i]*t; AL:=Ln*AL; AU:=Ln*AU; end; for i:=0 to AL.Rows-2 do begin for i2:=i+1 to AL.Rows-1 do AL[i2,i]:=-AL[i2,i]; end; end; procedure QRDecomposeGS(const AMatrix: TMatrix; out AQ, AR: TMatrix); function Proj(e,a: TVector): TVector; begin result:=e*(Dot(e,a)/Dot(e,e)); end; var um: TMatrix; u, e, a: TVector; i, i2: longint; t: double; begin assert(AMatrix.Columns = AMatrix.Rows, 'Only square matrices supported in QRDecomposeGS'); um:=TMatrix.Create(AMatrix.Rows, AMatrix.Columns); e:=Zeros(AMatrix.Columns); for i:=0 to AMatrix.Columns-1 do begin a:=AMatrix.Column[i]; u:=a; for i2:=0 to i-1 do u:=u-proj(um.Column[i2],a); um.Column[i]:=u; t:=system.sqrt(dot(u,u)); assert(t<>0, 'Matrix is singular'); e[i]:=1/t; end; AQ:=TMatrix.Create(AMatrix.Rows, AMatrix.Columns); for i:=0 to AMatrix.Rows-1 do for i2:=0 to AMatrix.Columns-1 do AQ[i,i2]:=um[i,i2]*e[i2]; AR:=AQ.Transpose*AMatrix; end; function Sgn(d: double): double; begin if d<0 then exit(-1) else exit(1); end; procedure QRDecomposeHR(const AMatrix: TMatrix; out AQ, AR: TMatrix); var x, u, v: TVector; t, alpha: Double; Qn, A: TMatrix; i: longint; begin assert(AMatrix.Columns = AMatrix.Rows, 'Only square matrices supported in QRDecomposeHR'); AQ:=TMatrix.Identity(AMatrix.Rows); A:=AMatrix; for i:=0 to AMatrix.Rows-2 do begin x:=A.MinorColumn[i,i,0]; alpha:=-Sgn(x[1])*system.sqrt(dot(x,x)); u:=Zeros(length(x)); u[0]:=1; u:=x-alpha*u; t:=system.sqrt(dot(u,u)); if t=0 then continue; //if dot(x,x)=0 then continue; //assert(t<>0, 'Matrix is singular'); v:=u/t; Qn:=TMatrix.Identity(A.Rows-I) - (TMatrix.Create(length(v),1, 2*v)*TMatrix.Create(1,length(v),v)); Qn:=Qn.Extend(i,i,0,0, true); AQ:=AQ*Qn.Transpose; A:=Qn*A; end; AR:=AQ.Transpose*AMatrix; end; function ReduceHR(const AMatrix: TMatrix): TMatrix; var x, v: TVector; alpha: Double; Qn, A: TMatrix; i, i2, n: longint; r, rr: double; begin assert(AMatrix.Columns = AMatrix.Rows, 'Only square matrices supported in ReduceHR'); n:=AMatrix.Columns; A:=AMatrix; for i:=0 to n-2 do begin x:=A.MinorColumn[i,i,0]; x[0]:=0; alpha:=-Sgn(x[1])*system.sqrt(dot(x,x)); r:=system.sqrt(0.5*(system.sqr(alpha)-x[1]*alpha)); if r=0 then continue; rr:=1/(2*r); v:=zeros(length(x)); v[0]:=0; v[1]:=(x[1]-alpha)*rr; for i2:=2 to high(x) do v[i2]:=x[i2]*rr; Qn:=TMatrix.Identity(A.Rows-I) - (TMatrix.Create(length(v),1, 2*v)*TMatrix.Create(1,length(v),v)); Qn:=Qn.Extend(i,i,0,0, true); A:=Qn*A*Qn; end; result:=A; end; function CholeskyDecompose(const AMatrix: TMatrix): TMatrix; var Am: TMatrix; aii,t: Double; i, i2: longint; begin assert(AMatrix.Columns = AMatrix.Rows, 'Only square matrices supported in CholeskyDecompose'); am:=AMatrix.Copy; result:=TMatrix.Identity(AMatrix.Rows); for i:=0 to result.Rows-1 do begin t:=am[i,i]; assert(t<>0, 'Matrix is not invertible'); assert(t>0, 'Resulting matrix is not real'); aii:=system.sqrt(t); result[i,i]:=aii; aii:=1/aii; am.ScaleRow(i,system.sqr(aii)); for i2:=i+1 to result.rows-1 do begin t:=am[i2,i]; am.SubScaled(i,i2,t); result[i2,i]:=t*aii; end; end; end; procedure ArnoldiIteration(const A: TMatrix; out H, Q: TMatrix); var n, j: longint; b, v: TVector; begin b:=Rand(a.Rows); h:=TMatrix.Identity(a.Rows); q:=TMatrix.Identity(a.Rows); q.Column[0]:=b/Magnitude(b); for n:=1 to a.Rows-1 do begin v:=(A*TMatrix(q.Column[n-1])).data; for j:=0 to n-1 do begin h[j,n-1]:=Dot(q.Column[j],q.Column[n]); v:=v-h[j,n]*q.Column[j]; end; h[n,n-1]:=Magnitude(v); q.Column[n]:=v/h[n,n-1]; end; end; function InvertGJ(const A: TMatrix): TMatrix; var t: TMatrix; n, i, i2: LongInt; x: Double; begin assert(a.Columns = a.Rows, 'Only square matrices supported in InvertGJ'); n:=A.rows; t:=a.Copy; result:=TMatrix.Identity(n); for i:=0 to n-1 do begin x:=t[i,i]; result.ScaleRow(i,x); t.ScaleRow(i,x); for i2:=i+1 to n-1 do begin x:=t[i2,i]; result.SubScaled(i,i2,x); t.SubScaled(i,i2,x); end; end; for i:=n-1 downto 1 do begin for i2:=i-1 downto 0 do begin x:=t[i2,i]; result.SubScaled(i,i2,x); t.SubScaled(i,i2,x); end; end; end; function SolveLU(const AL, AU, Ab: TMatrix): TMatrix; var y: TMatrix; n, c, i, i2: LongInt; t: double; begin n:=AL.Rows; result:=TMatrix.Create(n,Ab.Columns); y:=TMatrix.Create(n,Ab.Columns); for c:=0 to ab.Columns-1 do begin for i:=0 to n-1 do begin t:=0; for i2:=0 to i-1 do t:=t+y[i2,0]*al[i,i2]; y[i,0]:=(ab[i,c]-t); end; for i:=n-1 downto 0 do begin t:=0; for i2:=n-1 downto i+1 do t:=t+result[i2,c]*au[i,i2]; result[i,c]:=(y[i,0]-t)/au[i,i]; end; end; end; function InvertLU(const AL, AU: TMatrix): TMatrix; var i,i2,n: LongInt; t: double; Y, b: TMatrix; begin assert(al.Columns = al.Rows, 'Only square matrices supported in InvertLU'); n:=al.rows; b:=TMatrix.Identity(n); result:=SolveLU(al, au, b); end; function Determinant(const AMatrix: TMatrix): double; var i,i2: longint; t: double; begin assert(AMatrix.Columns = AMatrix.Rows, 'Only square matrices supported in Determinant'); result:=0; for i:=0 to AMatrix.Columns-1 do begin t:=1; for i2:=0 to AMatrix.Rows-1 do t:=t*AMatrix[i2,(i+i2) mod AMatrix.Columns]; result:=result+t; t:=1; for i2:=0 to AMatrix.Rows-1 do t:=t*AMatrix[AMatrix.Rows-i2-1, (i+i2) mod AMatrix.Columns]; result:=result-t; end; end; function DeterminantUnitary(const AMatrix: TMatrix): double; begin result:=1; end; function DeterminantTriangular(const AMatrix: TMatrix): double; var i: longint; begin result:=1; for i:=0 to min(AMatrix.Rows,AMatrix.Columns)-1 do result:=result*AMatrix[i,i]; end; function TMatrix.GetColumn(AColumn: longint): TVector; var pd: PDouble; i: longint; begin Assert((AColumn<Columns) and (AColumn>=0), 'Invalid column index'); setlength(Result,Rows); pd:=@Data[AColumn]; for i:=0 to rows-1 do begin result[i]:=pd^; inc(pd,Columns); end; end; function TMatrix.GetCopy: TMatrix; begin result:=TMatrix.Create(Rows,Columns,system.Copy(Data)); end; function TMatrix.GetHermitian: TMatrix; var i, i2: longint; begin {$ifdef IsComplex} result:=TMatrix.Create(Columns,Rows); for i:=0 to rows-1 do for i2:=0 to Columns-1 do result[i2,i]:=cong(self[i,i2]); {$else} result:=Transpose; {$endif} end; function TMatrix.GetMinorColumn(AStartRow, AStartColumn, AColumn: longint): TVector; var pd: PDouble; i: longint; begin Assert((AStartRow<Rows) and (AStartRow>=0), 'Invalid start row index'); Assert((AStartColumn<Columns) and (AStartColumn>=0), 'Invalid start column index'); Assert((AColumn<(Columns-AStartColumn)) and (AColumn>=0), 'Invalid column index'); setlength(Result,Rows-AStartRow); pd:=@Data[AStartRow*Columns+AStartColumn+AColumn]; for i:=0 to rows-AStartRow-1 do begin result[i]:=pd^; inc(pd,Columns); end; end; function TMatrix.GetRow(ARow: longint): TVector; begin Assert((ARow<Rows) and (ARow>=0), 'Invalid row index'); setlength(Result,Columns); move(Data[Columns*ARow],result[0], Columns*sizeof(double)); end; function TMatrix.GetTranspose: TMatrix; var i, i2: longint; begin result:=TMatrix.Create(Columns,Rows); for i:=0 to rows-1 do for i2:=0 to Columns-1 do result[i2,i]:=self[i,i2]; end; function TMatrix.GetValue(ARow, AColumn: longint): double; begin Assert((AColumn<Columns) and (AColumn>=0), 'Invalid column index'); Assert((ARow<Rows) and (ARow>=0), 'Invalid row index'); result:=Data[AColumn+ARow*Columns]; end; procedure TMatrix.SetColumn(AColumn: longint; AValue: TVector); var pd: PDouble; i: longint; begin Assert((AColumn<Columns) and (AColumn>=0), 'Invalid column index'); pd:=@Data[AColumn]; for i:=0 to rows-1 do begin pd^:=AValue[i]; inc(pd,Columns); end; end; procedure TMatrix.SetRow(ARow: longint; AValue: TVector); begin Assert((ARow<Rows) and (ARow>=0), 'Invalid row index'); move(AValue[0], Data[Columns*ARow], Columns*sizeof(double)); end; procedure TMatrix.SetValue(ARow, AColumn: longint; AValue: double); begin Assert((AColumn<Columns) and (AColumn>=0), 'Invalid column index'); Assert((ARow<Rows) and (ARow>=0), 'Invalid row index'); Data[AColumn+ARow*Columns]:=AValue; end; function TMatrix.Submatrix(AStartRow, AStartColumn: longint): TMatrix; var i, i2: longint; begin Assert((AStartColumn<Columns) and (AStartColumn>=0), 'Invalid column index'); Assert((AStartRow<Rows) and (AStartRow>=0), 'Invalid row index'); result:=TMatrix.Create(Rows-AStartRow, Columns-AStartColumn); for i:=0 to result.Rows-1 do for i2:=0 to result.Columns-1 do result[i,i2]:=self[i+AStartRow,i2+AStartColumn]; end; function TMatrix.Submatrix(AStartRow, AStartColumn, ARows, AColumns: longint): TMatrix; var i, i2: longint; begin Assert((AStartColumn<Columns) and (AStartColumn>=0), 'Invalid column index'); Assert((AStartRow<Rows) and (AStartRow>=0), 'Invalid row index'); Assert((AStartColumn+AColumns)<=Columns, 'Invalid number of columns'); Assert((AStartRow+ARows)<=Rows, 'Invalid number of rows'); result:=TMatrix.Create(ARows, AColumns); for i:=0 to result.Rows-1 do for i2:=0 to result.Columns-1 do result[i,i2]:=self[i+AStartRow,i2+AStartColumn]; end; function TMatrix.Extend(ARowS, AColumnS, ARowE, AColumnE: longint; AIdent: boolean): TMatrix; var i, i2: longint; begin if AIdent then begin result:=TMatrix.Identity(ARowS+rows+ARowE); end else begin result:=TMatrix.Create(Rows+ARowS+ARowE, Columns+AColumnS+AColumnE); FillChar(result.Data[0], sizeof(double)*result.Rows*result.Columns, 0); end; for i:=0 to Rows-1 do for i2:=0 to Columns-1 do result[i+ARowS,i2+AColumnS]:=self[i,i2]; end; constructor TMatrix.Identity(ARows, AColumns: longint); var pd: PDouble; i, i2: longint; begin setlength(Data, ARows*AColumns); Rows := ARows; Columns := AColumns; pd := @Data[0]; for i := 0 to ARows - 1 do for i2 := 0 to AColumns - 1 do begin if i = i2 then pd^ := 1 else pd^ := 0; Inc(pd); end; end; constructor TMatrix.Identity(N: longint); var pd: PDouble; i, i2: longint; begin setlength(Data, n * n); Rows := n; Columns := n; pd := @Data[0]; for i := 0 to n - 1 do for i2 := 0 to n - 1 do begin if i = i2 then pd^ := 1 else pd^ := 0; Inc(pd); end; end; constructor TMatrix.Create(ARows, AColumns: longint); begin Data:=Zeros(ARows*AColumns); Rows := ARows; Columns := AColumns; end; constructor TMatrix.Create(ARows, AColumns: longint; const AValues: array of double); begin Rows := ARows; Columns := AColumns; setlength(Data, ARows * AColumns); move(AValues[0], Data[0], length(AValues) * sizeof(double)); end; procedure TMatrix.SubScaled(ASrc, ADst: longint; AValue: double); var pd, ps: PDouble; i: longint; begin ps := @Data[ASrc*Columns]; pd := @Data[ADst*Columns]; for i := 0 to Columns-1 do begin pd^ := pd^-ps^ * AValue; Inc(pd); Inc(ps); end; end; procedure TMatrix.ScaleRow(ARow: longint; AValue: double); var pd: PDouble; i: longint; begin pd := @Data[ARow*Columns]; for i := 0 to Columns-1 do begin pd^ := pd^ * AValue; Inc(pd); end; end; procedure TMatrix.Scale(AValue: double); var pd: PDouble; i: longint; begin pd := @Data[0]; for i := 0 to high(Data) do begin pd^ := pd^ * AValue; Inc(pd); end; end; function TMatrix.Dump: string; var m, i, i2: longint; x: double; begin x := max(Data); if x<0 then m := trunc(log10(-x)) + 6 else if x<>0 then m := trunc(log10(x)) + 5 else m := 1; Result := ''; for i2 := 0 to Rows - 1 do begin Result := Result + format(format('%%%D.2F', [m]), [Data[i2 * Columns + 0]]); for i := 1 to Columns - 1 do Result := Result + format(format(', %%%D.2F', [m]), [Data[i2 * Columns + i]]); if i2 <> (rows - 1) then Result := Result + lineending; end; end; end.
unit fDBConnect; {$mode objfpc} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, DBGrids, LCLType, Menus, IniFiles; type { TfrmDBConnect } TfrmDBConnect = class(TForm) btnConnect: TButton; btnDisconnect: TButton; btnNewLog: TButton; btnEditLog: TButton; btnDeleteLog: TButton; btnOpenLog: TButton; btnCancel: TButton; btnUtils: TButton; chkAutoOpen: TCheckBox; chkSaveToLocal: TCheckBox; chkAutoConn: TCheckBox; chkSavePass: TCheckBox; dbgrdLogs: TDBGrid; edtPass: TEdit; edtUser: TEdit; edtPort: TEdit; edtServer: TEdit; grbLogin: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; mnuRepair : TMenuItem; MenuItem5 : TMenuItem; mnuClearLog: TMenuItem; mnuImport: TMenuItem; mnuExport: TMenuItem; dlgOpen: TOpenDialog; Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; popUtils: TPopupMenu; dlgSave: TSaveDialog; tmrAutoConnect: TTimer; procedure btnCancelClick(Sender: TObject); procedure btnConnectClick(Sender: TObject); procedure btnDeleteLogClick(Sender: TObject); procedure btnDisconnectClick(Sender: TObject); procedure btnEditLogClick(Sender: TObject); procedure btnNewLogClick(Sender: TObject); procedure btnOpenLogClick(Sender: TObject); procedure btnUtilsClick(Sender: TObject); procedure chkSavePassChange(Sender: TObject); procedure chkSaveToLocalClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure mnuClearLogClick(Sender: TObject); procedure mnuExportClick(Sender: TObject); procedure mnuImportClick(Sender: TObject); procedure mnuRepairClick(Sender : TObject); procedure tmrAutoConnectTimer(Sender: TObject); private RemoteMySQL : Boolean; AskForDB : Boolean; procedure SaveLogin; procedure LoadLogin; procedure UpdateGridFields; procedure EnableButtons; procedure DisableButtons; procedure OpenDefaultLog; public OpenFromMenu : Boolean; end; var frmDBConnect: TfrmDBConnect; implementation uses dData, dUtils, fNewLog; { TfrmDBConnect } procedure TfrmDBConnect.EnableButtons; begin btnOpenLog.Enabled := True; btnNewLog.Enabled := True; btnEditLog.Enabled := True; btnDeleteLog.Enabled := True; btnUtils.Enabled := True end; procedure TfrmDBConnect.DisableButtons; begin btnOpenLog.Enabled := False; btnNewLog.Enabled := False; btnEditLog.Enabled := False; btnDeleteLog.Enabled := False; btnUtils.Enabled := False end; procedure TfrmDBConnect.UpdateGridFields; begin //dbgrdLogs.Columns[0].Visible := False; dbgrdLogs.Columns[0].Width := 50; dbgrdLogs.Columns[1].Width := 180; //dbgrdLogs.Columns[2].Visible := False; dbgrdLogs.Columns[0].DisplayName := 'Log nr'; dbgrdLogs.Columns[1].DisplayName := 'Log name' end; procedure TfrmDBConnect.SaveLogin; var ini : TIniFile; begin ini := TIniFile.Create(GetAppConfigDir(False)+'cqrlog_login.cfg'); try if not chkSaveToLocal.Checked then begin ini.WriteBool('Login','SaveToLocal',False); ini.WriteString('Login','Server',edtServer.Text); ini.WriteString('Login','Port',edtPort.Text); ini.WriteString('Logini','User',edtUser.Text); if chkSavePass.Checked then ini.WriteString('Login','Pass',edtPass.Text) else ini.WriteString('Login','Pass',''); ini.WriteBool('Login','SavePass',chkSavePass.Checked); ini.WriteBool('Login','AutoConnect',chkAutoConn.Checked) end else ini.WriteBool('Login','SaveToLocal',True) finally ini.Free end end; procedure TfrmDBConnect.LoadLogin; var ini : TIniFile; begin ini := TIniFile.Create(GetAppConfigDir(False)+'cqrlog_login.cfg'); try if ini.ReadBool('Login','SaveTolocal',True) then begin edtServer.Text := '127.0.0.1'; edtPort.Text := '65000'; edtUser.Text := 'cqrlog'; edtPass.Text := 'cqrlog'; tmrAutoConnect.Enabled := True; chkAutoConn.Checked := True; chkSaveToLocal.Checked := True; chkSaveToLocalClick(nil); RemoteMySQL := False end else begin chkSaveToLocal.Checked := False; grbLogin.Visible := True; edtServer.Text := ini.ReadString('Login','Server','127.0.0.1'); edtPort.Text := ini.ReadString('Login','Port','3306'); edtUser.Text := ini.ReadString('Logini','User',''); chkSavePass.Checked := ini.ReadBool('Login','SavePass',False); if chkSavePass.Checked then edtPass.Text := ini.ReadString('Login','Pass','') else edtPass.Text := ini.ReadString('Login','Pass',''); chkAutoConn.Checked := ini.ReadBool('Login','AutoConnect',False); chkSavePassChange(nil); if (chkAutoConn.Checked) and (chkAutoConn.Enabled) then tmrAutoConnect.Enabled := True; RemoteMySQL := True end; chkAutoOpen.Checked := ini.ReadBool('Login','AutoOpen',False); finally ini.Free end end; procedure TfrmDBConnect.FormClose(Sender: TObject; var CloseAction: TCloseAction ); var ini : TIniFile; begin SaveLogin; ini := TIniFile.Create(GetAppConfigDir(False)+'cqrlog_login.cfg'); try if WindowState = wsMaximized then ini.WriteBool(Name,'Max',True) else begin ini.WriteInteger(Name,'Height',Height); ini.WriteInteger(Name,'Width',Width); ini.WriteInteger(Name,'Top',Top); ini.WriteInteger(Name,'Left',Left); ini.WriteBool(Name,'Max',False) end finally ini.Free end end; procedure TfrmDBConnect.FormCreate(Sender: TObject); var ini : TIniFile; begin OpenFromMenu := False; ini := TIniFile.Create(GetAppConfigDir(False)+'cqrlog_login.cfg'); try AskForDB := not ini.ValueExists('Login','SaveToLocal') finally ini.Free end end; procedure TfrmDBConnect.btnConnectClick(Sender: TObject); begin SaveLogin; if dmData.OpenConnections(edtServer.Text,edtPort.Text,edtUser.Text,edtPass.Text) then begin dmData.CheckForDatabases; UpdateGridFields; EnableButtons; OpenDefaultLog end end; procedure TfrmDBConnect.btnDeleteLogClick(Sender: TObject); begin if dmData.qLogList.Fields[0].AsInteger = 1 then begin Application.MessageBox('You can not delete the first log!','Info ...',mb_ok + mb_IconInformation); exit end; if Application.MessageBox('Do you really want to delete this log?','Question ...', mb_YesNo + mb_IconQuestion) = idYes then begin if Application.MessageBox('LOG WILL BE _DELETED_. Are you sure?','Question ...', mb_YesNo + mb_IconQuestion) = idYes then begin dmData.DeleteLogDatabase(dmData.qLogList.Fields[0].AsInteger); UpdateGridFields end end end; procedure TfrmDBConnect.btnCancelClick(Sender: TObject); begin ModalResult := mrCancel end; procedure TfrmDBConnect.btnDisconnectClick(Sender: TObject); begin {if (dmData.MySQLVersion < 5.5) then begin if dmData.MainCon51.Connected then dmData.MainCon51.Connected := False end else begin if dmData.MainCon55.Connected then dmData.MainCon55.Connected := False end; } if dmData.MainCon.Connected then dmData.MainCon.Connected := False; DisableButtons end; procedure TfrmDBConnect.btnEditLogClick(Sender: TObject); begin frmNewLog := TfrmNewLog.Create(nil); try frmNewLog.Caption := 'Edit existing log ...'; frmNewLog.edtLogNR.Text := dmData.qLogList.Fields[0].AsString; frmNewLog.edtLogName.Text := dmData.qLogList.Fields[1].AsString; frmNewLog.edtLogNR.Enabled := False; frmNewLog.ShowModal; if frmNewLog.ModalResult = mrOK then begin dmData.EditDatabaseName(StrToInt(frmNewLog.edtLogNR.Text), frmNewLog.edtLogName.Text); UpdateGridFields end finally frmNewLog.Free end end; procedure TfrmDBConnect.btnNewLogClick(Sender: TObject); begin frmNewLog := TfrmNewLog.Create(nil); try frmNewLog.Caption := 'New log ...'; frmNewLog.ShowModal; if frmNewLog.ModalResult = mrOK then begin //if dmData.LogName <> '' then // dmData.CloseDatabases; dmData.CreateDatabase(StrToInt(frmNewLog.edtLogNR.Text), frmNewLog.edtLogName.Text); UpdateGridFields end finally frmNewLog.Free end end; procedure TfrmDBConnect.btnOpenLogClick(Sender: TObject); var ini : TIniFile; begin ini := TIniFile.Create(GetAppConfigDir(False)+'cqrlog_login.cfg'); try ini.WriteBool('Login','AutoOpen',chkAutoOpen.Checked); ini.WriteInteger('Login','LastLog',dmData.qLogList.Fields[0].AsInteger); if chkAutoOpen.Checked then ini.WriteInteger('Login','LastLog',dmData.qLogList.Fields[0].AsInteger) else ini.WriteInteger('Login','LastOpenedLog',dmData.qLogList.Fields[0].AsInteger) finally ini.Free end; if not OpenFromMenu then begin dmData.OpenDatabase(dmData.qLogList.Fields[0].AsInteger); dmData.LogName := dmData.qLogList.Fields[1].AsString end; ModalResult := mrOK end; procedure TfrmDBConnect.btnUtilsClick(Sender: TObject); var p : TPoint; begin p.x := 10; p.y := 10; p := btnUtils.ClientToScreen(p); popUtils.PopUp(p.x, p.y) end; procedure TfrmDBConnect.chkSavePassChange(Sender: TObject); begin if chkSavePass.Checked then chkAutoConn.Enabled := True else chkAutoConn.Enabled := False end; procedure TfrmDBConnect.chkSaveToLocalClick(Sender: TObject); begin if chkSaveToLocal.Checked then begin if RemoteMySQL then begin if Application.MessageBox('Local database is not running. Dou you want to start it?','Question',mb_YesNo+mb_IconQuestion) = idYes then begin dmData.StartMysqldProcess; Sleep(3000); btnConnectClick(nil) end else begin chkSaveToLocal.Checked := False; grbLogin.Visible := True; exit end end; grbLogin.Visible := False end else begin grbLogin.Visible := True end end; procedure TfrmDBConnect.FormShow(Sender: TObject); var ini : TIniFile; StartMysql : Boolean; begin ini := TIniFile.Create(GetAppConfigDir(False)+'cqrlog_login.cfg'); try if ini.ReadBool(Name,'Max',False) then WindowState := wsMaximized else begin Height := ini.ReadInteger(Name,'Height',Height); Width := ini.ReadInteger(Name,'Width',Width); Top := ini.ReadInteger(Name,'Top',20); Left := ini.ReadInteger(Name,'Left',20); end; StartMysql := ini.ReadBool('Login','SaveTolocal',False) finally ini.Free end; dbgrdLogs.DataSource := dmData.dsrLogList; if StartMysql then dmData.StartMysqldProcess; LoadLogin; if OpenFromMenu then begin UpdateGridFields; EnableButtons end; dlgOpen.InitialDir := dmData.AppHomeDir; dlgSave.InitialDir := dmData.AppHomeDir end; procedure TfrmDBConnect.mnuClearLogClick(Sender: TObject); var s : PChar; begin s := 'YOUR ENTIRE LOG WILL BE DELETED!'+LineEnding+LineEnding+ 'Do you want to CANCEL this operation?'; if Application.MessageBox(s,'Question ...', mb_YesNo + mb_IconQuestion) = idNo then begin //dmData.TruncateTables(dmData.qLogList.Fields[0].AsInteger); ShowMessage('Log is empty') end end; procedure TfrmDBConnect.mnuExportClick(Sender: TObject); var db : String; l : TStringList; begin if dlgSave.Execute then begin db := dmData.GetProperDBName(dmData.qLogList.Fields[0].AsInteger); dmData.Q.Close; if dmData.trQ.Active then dmData.trQ.Rollback; dmData.Q.SQL.Text := 'select config_file from '+db+'.cqrlog_config'; dmData.trQ.StartTransaction; l := TStringList.Create; try dmData.Q.Open; l.Text := dmData.Q.Fields[0].AsString; l.SaveToFile(dlgSave.FileName); ShowMessage('Config file saved to '+dlgSave.FileName) finally dmData.Q.Close; dmData.trQ.Rollback; l.Free end end end; procedure TfrmDBConnect.mnuImportClick(Sender: TObject); var db : String; l : TStringList; begin if dlgOpen.Execute then begin db := dmData.GetProperDBName(dmData.qLogList.Fields[0].AsInteger); dmData.Q.Close; if dmData.trQ.Active then dmData.trQ.Rollback; dmData.Q.SQL.Text := 'update '+db+'.cqrlog_config set config_file =:config_file'; dmData.trQ.StartTransaction; l := TStringList.Create; try try l.LoadFromFile(dlgOpen.FileName); dmData.Q.Params[0].AsString := l.Text; //if dmData.DebugLevel >=1 then Writeln(dmData.Q.SQL.Text); dmData.Q.ExecSQL except dmData.trQ.Rollback end; dmData.trQ.Commit; ShowMessage('Config file imported successfully') finally dmData.Q.Close; l.Free end end end; procedure TfrmDBConnect.mnuRepairClick(Sender : TObject); begin //dmData.RepairTables(dmData.qLogList.Fields[0].AsInteger); ShowMessage('Done, tables fixed') end; procedure TfrmDBConnect.tmrAutoConnectTimer(Sender: TObject); var Connect : Boolean = True; begin tmrAutoConnect.Enabled := False; if AskForDB then begin if Application.MessageBox('It seems you are trying to run this program for the first time, '+ 'are you going to save data to local machine?'#10#13'If you say Yes, '+ 'new databases will be created. This may take a while, please be patient.' ,'Question ...', mb_YesNo+mb_IconQuestion) = idYes then begin dmData.StartMysqldProcess; Sleep(3000) end else begin Connect := False; RemoteMySQL := True; chkSaveToLocal.Checked := False; chkSaveToLocalClick(nil); edtServer.SetFocus end end; if (not OpenFromMenu) and Connect then btnConnect.Click; if btnOpenLog.Enabled then btnOpenLog.SetFocus end; procedure TfrmDBConnect.OpenDefaultLog; var ini : TIniFile; AutoLog : Integer; AutoOpen : Boolean; LastLog : Integer; begin ini := TIniFile.Create(GetAppConfigDir(False)+'cqrlog_login.cfg'); try AutoOpen := ini.ReadBool('Login','AutoOpen',False); AutoLog := ini.ReadInteger('Login','LastLog',0); LastLog := ini.ReadInteger('Login','LastOpenedLog',0) finally ini.Free end; if AutoOpen then begin if dmData.qLogList.Locate('log_nr',AutoLog,[]) then btnOpenLog.Click end else begin dmData.qLogList.Locate('log_nr',LastLog,[]) end end; initialization {$I fDBConnect.lrs} end.
unit fPatientFlagMulti; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, fAutoSz, ORCtrls, ExtCtrls, ComCtrls, rMisc, fBase508Form, VA508AccessibilityManager; type {This object holds a List of Notes Linked to a PRF as Returned VIA the RPCBroker} TPRFNotes = class(TObject) private FPRFNoteList : TStringList; public //procedure to show the Notes in a ListView, requires a listview parameter procedure ShowActionsOnList(DisplayList : TCaptionListView); //procedure to load the notes, this will call the RPC procedure Load(TitleIEN : Int64; DFN : String); function getNoteIEN(index: integer): String; constructor create; destructor Destroy(); override; end; TfrmFlags = class(TfrmBase508Form) Panel1: TPanel; Splitter3: TSplitter; Splitter1: TSplitter; lblFlags: TLabel; lstFlagsCat2: TORListBox; memFlags: TRichEdit; pnlNotes: TPanel; lvPRF: TCaptionListView; lblNoteTitle: TLabel; Splitter2: TSplitter; pnlBottom: TORAutoPanel; btnClose: TButton; lstFlagsCat1: TORListBox; lblCat1: TLabel; TimerTextFlash: TTimer; procedure lstFlagsCat1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormDestroy(Sender: TObject); procedure lvPRFClick(Sender: TObject); procedure lvPRFKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure TimerTextFlashTimer(Sender: TObject); procedure lstFlagsCat2Click(Sender: TObject); private FFlagID: integer; FPRFNotes : TPRFNotes; FNoteTitle: String; procedure GetNotes(SelectedList : TORListBox); procedure MakeCat1FlagsStandOut; procedure LoadSelectedFlagData(SelectedList : TORListBox); procedure ActivateSpecificFlag; procedure PutFlagsOnLists(flags, Cat1List, Cat2List: TStrings); function GetListToActivate : TORListBox; public { Public declarations } end; const HIDDEN_COL = 'Press enter or space bar to view this note:'; //TIU GET LINKED PRF NOTES, return position constants NOTE_IEN_POS = 1; ACTION_POS = 2; NOTE_DATE_POS = 3; AUTHOR_POS = 4; //TIU GET PRF TITLE, return position constants NOTE_TITLE_IEN = 1; NOTE_TITLE = 2; procedure ShowFlags(FlagId: integer = 0); implementation uses uCore,uOrPtf,ORFn, ORNet, uConst, fRptBox, rCover; {$R *.dfm} procedure ShowFlags(FlagId: integer); var frmFlags: TfrmFlags; begin frmFlags := TFrmFlags.Create(Nil); try SetFormPosition(frmFlags); if HasFlag then begin with frmFlags do begin FFlagID := FlagId; PutFlagsOnLists(FlagList, lstFlagsCat1.Items, lstFlagsCat2.Items); end; frmFlags.memFlags.SelStart := 0; ResizeFormToFont(TForm(frmFlags)); frmFlags.ShowModal; end finally frmFlags.Release; end; end; procedure TfrmFlags.lstFlagsCat1Click(Sender: TObject); begin if lstFlagsCat1.ItemIndex >= 0 then begin with lstFlagsCat2 do Selected[ItemIndex] := False; LoadSelectedFlagData(lstFlagsCat1); end; end; procedure TfrmFlags.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; end; procedure TfrmFlags.FormShow(Sender: TObject); begin inherited; SetFormPosition(Self); if lstFlagsCat1.Count > 0 then MakeCat1FlagsStandOut; ActivateSpecificFlag; end; procedure TfrmFlags.FormCreate(Sender: TObject); begin inherited; FFlagID := 0; end; procedure TfrmFlags.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; SaveUserBounds(Self); end; procedure TfrmFlags.GetNotes(SelectedList : TORListBox); var NoteTitleIEN, FlagID : Int64; begin if FPRFNotes = nil then FPRFNotes := TPRFNotes.Create; FlagID := SelectedList.ItemID; CallV('TIU GET PRF TITLE', [Patient.DFN,FlagID]); FNoteTitle := Piece(RPCBrokerV.Results[0],U,NOTE_TITLE); lblNoteTitle.Caption := 'Signed, Linked Notes of Title: '+ FNoteTitle; NoteTitleIEN := StrToInt(Piece(RPCBrokerV.Results[0],U,NOTE_TITLE_IEN)); FPRFNotes.Load(NoteTitleIEN,Patient.DFN); FPRFNotes.ShowActionsOnList(lvPRF); with lvPRF do begin Columns.BeginUpdate; Columns.EndUpdate; end; end; { TPRFNotes } constructor TPRFNotes.create; begin inherited; FPRFNoteList := TStringList.create; end; destructor TPRFNotes.Destroy; begin FPRFNoteList.Free; inherited; end; function TPRFNotes.getNoteIEN(index: integer): String; begin Result := Piece(FPRFNoteList[index],U,NOTE_IEN_POS); end; procedure TPRFNotes.Load(TitleIEN: Int64; DFN: String); const REVERSE_CHRONO = 1; begin CallV('TIU GET LINKED PRF NOTES', [DFN,TitleIEN,REVERSE_CHRONO]); FastAssign(RPCBrokerV.Results, FPRFNoteList); end; procedure TPRFNotes.ShowActionsOnList(DisplayList: TCaptionListView); var i : integer; ListItem: TListItem; begin DisplayList.Clear; for i := 0 to FPRFNoteList.Count-1 do begin //Caption="Text for Screen Reader" SubItem1=Flag SubItem2=Date SubItem3=Action SubItem4=Note ListItem := DisplayList.Items.Add; ListItem.Caption := HIDDEN_COL; //Screen readers don't read the first column title on a listview. ListItem.SubItems.Add(Piece(FPRFNoteList[i],U,NOTE_DATE_POS)); ListItem.SubItems.Add(Piece(FPRFNoteList[i],U,ACTION_POS)); ListItem.SubItems.Add(Piece(FPRFNoteList[i],U,AUTHOR_POS)); end; end; procedure TfrmFlags.FormDestroy(Sender: TObject); begin FPRFNotes.Free; end; procedure TfrmFlags.lvPRFClick(Sender: TObject); begin if lvPRF.ItemIndex > -1 then begin NotifyOtherApps(NAE_REPORT, 'TIU^' + FPRFNotes.getNoteIEN(lvPRF.ItemIndex)); ReportBox(DetailPosting(FPRFNotes.getNoteIEN(lvPRF.ItemIndex)), FNoteTitle, True); end; end; procedure TfrmFlags.lvPRFKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_SPACE) or (Key = VK_RETURN) then lvPRFClick(Sender); end; procedure TfrmFlags.MakeCat1FlagsStandOut; Const FONT_INC = 4; clBrightOrange = TColor($3ABEF3); //Blue 58 Green 190 Red 243 begin lblCat1.Font.Size := lblCat1.Font.Size + FONT_INC; lstFlagsCat1.Font.Size := lstFlagsCat1.Font.Size + FONT_INC; lblCat1.Color := Get508CompliantColor(clBrightOrange); lstFlagsCat1.Color := Get508CompliantColor(clBrightOrange); lblCat1.Font.Color := Get508CompliantColor(clWhite); lstFlagsCat1.Font.Color := Get508CompliantColor(clWhite); TimerTextFlash.Enabled := true; end; procedure TfrmFlags.TimerTextFlashTimer(Sender: TObject); begin if lblCat1.Font.Color = Get508CompliantColor(clWhite) then lblCat1.Font.Color := Get508CompliantColor(clBlack) else lblCat1.Font.Color := Get508CompliantColor(clWhite); end; procedure TfrmFlags.LoadSelectedFlagData(SelectedList: TORListBox); var FlagArray: TStringList; begin FlagArray := TStringList.Create; GetActiveFlg(FlagArray, Patient.DFN, SelectedList.ItemID); if FlagArray.Count > 0 then QuickCopy(FlagArray, memFlags); memFlags.SelStart := 0; GetNotes(SelectedList); end; procedure TfrmFlags.lstFlagsCat2Click(Sender: TObject); begin if lstFlagsCat2.ItemIndex >= 0 then begin with lstFlagsCat1 do Selected[ItemIndex] := False; LoadSelectedFlagData(lstFlagsCat2); end; end; procedure TfrmFlags.ActivateSpecificFlag; var idx: integer; SelectedList : TORListBox; begin idx := 0; SelectedList := GetListToActivate; if FFlagID > 0 then idx := SelectedList.SelectByIEN(FFlagId); SelectedList.ItemIndex := idx; SelectedList.OnClick(Self); ActiveControl := memFlags; GetNotes(SelectedList); end; function TfrmFlags.GetListToActivate: TORListBox; begin Result := nil; if FFlagID > 0 then begin if lstFlagsCat1.SelectByIEN(FFlagId) > -1 then Result := lstFlagsCat1 else if lstFlagsCat2.SelectByIEN(FFlagId) > -1 then Result := lstFlagsCat2 end; if Result = nil then if lstFlagsCat1.Items.Count > 0 then Result := lstFlagsCat1 else Result := lstFlagsCat2; end; procedure TfrmFlags.PutFlagsOnLists(flags, Cat1List, Cat2List: TStrings); Const FLAG_TYPE_POS = 3; TRUE_STRING = '1'; var i, TypeOneCount, TypeTwoCount : integer; begin TypeOneCount := 0; TypeTwoCount := 0; for i := 0 to flags.Count-1 do begin if Piece(flags[i],U,FLAG_TYPE_POS) = TRUE_STRING then begin Cat1List.Add(flags[i]); Inc(TypeOneCount); end else begin Cat2List.Add(flags[i]); Inc(TypeTwoCount); end; end; If TypeOneCount > 0 then lblCat1.Caption := 'Category I Flags: ' + IntToStr(TypeOneCount) + ' Item(s)' else lblCat1.Caption := 'Category I Flags'; If TypeTwoCount > 0 then lblFlags.Caption := 'Category II Flags: ' + IntToStr(TypeTwoCount) + ' Item(s)' else lblFlags.Caption := 'Category II Flags'; end; end.
{=============================================================================== 数据库操作基类 ===============================================================================} unit xDBActionBase; interface uses xDBConn, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TDBActionBase = class private protected FQuery :TFDQuery; public constructor Create; virtual; destructor Destroy; override; property Query : TFDQuery read FQuery write FQuery; /// <summary> /// 执行SQL 语句 /// </summary> procedure ExecSQL; end; implementation { TDBAction } constructor TDBActionBase.Create; begin FQuery :=TFDQuery.Create(nil); FQuery.Connection := ADBConn.Connection; end; destructor TDBActionBase.Destroy; begin FQuery.Free; inherited; end; procedure TDBActionBase.ExecSQL; begin try FQuery.ExecSQL; except end; end; end.
unit SIBEABase; // SuperIB // Copyright © 1999 David S. Becker // dhbecker@jps.net // www.jps.net/dhbecker/superib // Revision History: // 1.54 8/5/1999 Fixed a bug which would cause access violations or // external exceptions on certain machines due to an // internal race condition in which threads were getting // freed before they were fully created. Also finally // got to the bottom of a problem which would cause // the component to lock up for some people. Basically // calls to Synchronize() would sometimes fail to execute // the intended code, effectively hanging the thread. As // it turns out, this is a problem in the classes unit of // the VCL. The RemoveThread function is calling // PostMessage when it really should be calling SendMessage. // Modifying the VCL is not a practical solution, so I've // managed to work around the issue. // // 1.53 7/14/1999 Fixed access violation in SIBEventBlock by finding // a new way to call the InterBase API function // isc_event_block which did not involve assembly. Also // fixed a problem which would cause events not to be // registered if you unregistered then re-registered events. // // 1.52 7/12/1999 Fixed a bug which would cause an access violation if // the TSIBbdeEventAlerter gets destroyed before the // TDatabase does. Also made a change to try and fix a // reported a random access violation which would occur // in the SIBEventBlock procedure if compiled in the $O+ // state. Thanks again to David Hildingsson! // // 1.51 7/10/1999 Fixed a bug in TSIBbdeEventAlerter which would // cause an access violation when assigning the // Database property at run time. Thanks to David // Hildingsson for finding this one. // // 1.50 7/8/1999 Major rearchitecture of the SuperIBEventAlerter // class structure and naming conventions. Created // TSIBbdeEventAlerter, TSIBfibEventAlerter, // TSIBiboEventAlerter. See the readme file for more info. // // 1.02 4/13/1999 If your TDatabase is not connected at design time, // it is possible to assign a non-InterBase database. // This would cause multiple cryptic exceptions to be // raised when RegisterEvents was called. Now checks // for a valid InterBase connection earlier in the // process and cleanly exits out of RegisterEvents // with a single exception. // // 1.01 3/29/1999 Wait loop would eat up all available CPU cycles if // nothing else was running. Special thanks go to // Chris Heberle for pointing this out and fixing it. // // 1.00 3/26/1999 Initial Release {$I FIBPlus.inc} {$T-} interface uses SysUtils, Classes,SyncObjs, SIBGlobals, SIBAPI,ibase,IB_Intf,IB_Externals; type TSIBEventThread = class; TSIBAlertEvent = procedure(Sender: TObject; EventName: string; EventCount: Longint) of object; { TSIBEventAlerter } TSIBEventAlerter = class(TComponent) protected { Private declarations } FClientLibrary:IIBClientLibrary; FOnEventAlert: TSIBAlertEvent; FEvents: TStrings; FThreads: TList; FNativeHandle: SIB_DBHandle; ThreadException: Boolean; FVCLSynchro:boolean; procedure SetEvents(Value: TStrings); function GetRegistered: Boolean; procedure SetRegistered(const Value: Boolean); protected { Protected declarations } procedure SetNativeHandle(const Value: SIB_DBHandle); virtual; function GetNativeHandle: SIB_DBHandle; virtual; procedure EventChange(Sender: TObject); virtual; procedure ThreadEnded(Sender: TObject); virtual; public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; procedure RegisterEvents; virtual; procedure UnRegisterEvents; virtual; property NativeHandle: SIB_DBHandle read GetNativeHandle write SetNativeHandle; property Registered: Boolean read GetRegistered write SetRegistered; published { Published declarations } property VCLSynchronize:boolean read FVCLSynchro write FVCLSynchro default True; property Events: TStrings read FEvents write SetEvents; property OnEventAlert: TSIBAlertEvent read FOnEventAlert write FOnEventAlert; end; { TSIBEventThread } TSIBEventThread = class(TThread) private { Private declarations } // IB API call parameters FClientLibrary:IIBClientLibrary; WhichEvent: Integer; ErrorBuffer: PAnsiChar; ErrorVector: SIB_PStatusVector; StatusVector: SIB_StatusVector; ResultStatus: SIB_Status; EventID: SIB_Long; DB: SIB_DBHandle; EventBuffer: PAnsiChar; EventBufferLen: SIB_Long; ResultBuffer: PAnsiChar; // Local use variables Signal: TSimpleEvent; EventsReceived, FirstTime: Boolean; EventGroup, EventCount: Integer; Parent: TSIBEventAlerter; FExceptObject: TObject; FExceptAddr: Pointer; FVCLSynchro:boolean; protected procedure Execute; override; procedure SignalEvent; virtual; procedure SignalTerminate; virtual; procedure RegisterEvents; virtual; procedure UnRegisterEvents; virtual; procedure QueueEvents; virtual; procedure ProcessEvents; virtual; function GetIBErrorString: string; virtual; procedure SIBQueEvents; virtual; procedure SIBInterpretError; virtual; procedure SIBEventCounts; virtual; procedure SIBFree; virtual; procedure SIBCancelEvents; virtual; procedure SIBEventBlock; virtual; procedure DoEvent; virtual; procedure DoHandleException; virtual; function HandleException: Boolean; virtual; procedure UpdateResultBuffer(Length: SIB_UShort; Updated: PAnsiChar); virtual; public constructor Create(ClientLibrary:IIBClientLibrary;Owner: TSIBEventAlerter; DBHandle: SIB_DBHandle; EventGrp: Integer; TermEvent: TNotifyEvent; aVCLSynchro:boolean); virtual; destructor Destroy; override; end; // You normally wouldn't register the TSIBEventAlerter base class directly, // but if you aren't using BDE, FIB, or IBO, then you can uncomment this // to use the component by accessing the raw InterBase handle. // procedure Register; implementation {$IFNDEF D_XE2} uses Windows; {$ENDIF} // You normally wouldn't register the TSIBEventAlerter base class directly, // but if you aren't using BDE, FIB, or IBO, then you can uncomment this // to use the component by accessing the raw InterBase handle. // procedure Register; // begin // RegisterComponents('SuperIB', [TSIBEventAlerter]); // end; // This is the callback generated by IB when an event occurs. It passes // a pointer of our choosing (in this case, a pointer to the event thread // which registered the callback) as well as an updated resultbuffer // this callback occurs in a separate thread created by IB, and therefore // we can't do anything that interacts with the VCL so we simply copy // the resultbuffer and set a flag to notify the event thread that // an event was received. By doing this we effectively bring this separate // thread back into our event thread, which then uses Synchronize() to // call the event handler in the main thread -- making it totally VCL safe! procedure EventCallback(P: Pointer; Length: SIB_UShort; Updated: PAnsiChar); cdecl; begin if (Assigned(P) and Assigned(Updated)) then begin TSIBEventThread(P).UpdateResultBuffer(Length, Updated); TSIBEventThread(P).SignalEvent; end; end; { TSIBEventThread } // stub for synchronizing with main thread procedure TSIBEventThread.SIBQueEvents; begin ResultStatus := SIB_QueEvents(FClientLibrary,@StatusVector, @DB, @EventID, EventBufferLen, PAnsiChar(EventBuffer), EventCallback ,Self ); end; // stub for synchronizing with main thread procedure TSIBEventThread.SIBInterpretError; begin ResultStatus :=FClientLibrary.isc_interprete( ErrorBuffer, PPISC_STATUS( @ErrorVector ) ); Set8087CW(Default8087CW); end; // stub for synchronizing with main thread procedure TSIBEventThread.SIBEventCounts; begin SIB_EventCounts(FClientLibrary,@StatusVector, EventBufferLen, EventBuffer, ResultBuffer); end; // stub for synchronizing with main thread procedure TSIBEventThread.SIBFree; begin SIB_Free(FClientLibrary,EventBuffer); EventBuffer := nil; SIB_Free(FClientLibrary,ResultBuffer); ResultBuffer := nil; end; // stub for synchronizing with main thread procedure TSIBEventThread.SIBCancelEvents; begin ResultStatus := SIB_CancelEvents(FClientLibrary,@StatusVector, @DB, @EventID); SIBFree end; // stub for synchronizing with main thread procedure TSIBEventThread.SIBEventBlock; var EBPArray : Array[1..SIB_MAX_EVENT_BLOCK] of PAnsiChar; EBPArrayStr : Array of AnsiString; i:integer; function EBP(Index: Integer): PAnsiChar; begin Inc(Index, (EventGroup * SIB_MAX_EVENT_BLOCK)); if (Index > Parent.FEvents.Count) then Result := nil else begin EBPArrayStr[Index-1]:=Ansistring(Parent.FEvents[Index - 1]); Result := PAnsiChar(EBPArrayStr[Index-1]); end; end; begin EventCount := (Parent.FEvents.Count - (EventGroup * SIB_MAX_EVENT_BLOCK)); if (EventCount > SIB_MAX_EVENT_BLOCK) then EventCount := SIB_MAX_EVENT_BLOCK; SetLength(EBPArrayStr,Parent.FEvents.Count); for i:=1 to SIB_MAX_EVENT_BLOCK do begin EBPArray[i]:=EBP(i); end; EventBufferLen := FClientLibrary.isc_event_block(@EventBuffer, @ResultBuffer, EventCount, EBPArray ); end; // stub for synchronizing with main thread procedure TSIBEventThread.DoEvent; begin Parent.FOnEventAlert(Parent, Parent.FEvents[((EventGroup * SIB_MAX_EVENT_BLOCK) + WhichEvent)], StatusVector[WhichEvent]) end; // called by the IB event callback to copy an update resultbuffer // into our own storage space procedure TSIBEventThread.UpdateResultBuffer(Length: SIB_UShort; Updated: PAnsiChar); begin Move(Updated[0], ResultBuffer[0], Length); end; function TSIBEventThread.GetIBErrorString: string; var Buffer: array[0..255] of AnsiChar; lastMsg: string; errCode: SIB_Status; begin Result := ''; if Terminated then Exit; ErrorBuffer := @Buffer; ErrorVector := @StatusVector; repeat Synchronize(SIBInterpretError); // SIBInterpretError; errCode := ResultStatus; if (Ansistring(lastMsg) <> Ansistring(Buffer)) then begin lastMsg := string(Buffer); if (Length(Result) <> 0) then Result := Result + #13#10; Result := Result + lastMsg; end; until (errCode = 0); end; // tell IB to queue up the events and begin reporting them // first time this is called generates a bogus notification // to initialize the result buffer procedure TSIBEventThread.QueueEvents; begin EventsReceived := False; if not Terminated then begin Signal.ResetEvent; if FVCLSynchro then Synchronize(SIBQueEvents) else SIBQueEvents; if (ResultStatus <> 0) then raise ESIBError.Create(GetIBErrorString); end; end; // call the event handler for any events received procedure TSIBEventThread.ProcessEvents; var i: Integer; begin // find out how many and which events occured if Terminated then Exit; // Synchronize(SIBEventCounts); if FVCLSynchro then Synchronize(SIBEventCounts) else SIBEventCounts; // the first time we come in here is a bogus initialization call, so don't // actually do anything if (Assigned(Parent.FOnEventAlert) and (not FirstTime)) then begin for i := 0 to (EventCount - 1) do begin // if this particular event occured, call the event handler if (StatusVector[i] <> 0) then begin WhichEvent := i; if FVCLSynchro then Synchronize(DoEvent) else DoEvent end; end; end; FirstTime := False; end; // tell IB to cancel the event notification and // release the various event buffers procedure TSIBEventThread.UnRegisterEvents; begin {$IFNDEF D6+} Synchronize(SIBCancelEvents); {$ELSE} // Synchronize(SIBCancelEvents); SIBCancelEvents; {$ENDIF} { if (ResultStatus <> 0) then raise ESIBError.Create(GetIBErrorString);} //^^^^May be shutdown error end; // setup the various event buffers with IB procedure TSIBEventThread.RegisterEvents; begin if Terminated then Exit; EventBuffer := nil; ResultBuffer := nil; EventBufferLen := 0; FirstTime := True; // figure out how many events are in the group we've been assigned EventCount := (Parent.FEvents.Count - (EventGroup * SIB_MAX_EVENT_BLOCK)); if (EventCount > SIB_MAX_EVENT_BLOCK) then EventCount := SIB_MAX_EVENT_BLOCK; SIBEventBlock; // For AutoRegistry end; // indicate than an event was received, and stop waiting procedure TSIBEventThread.SignalEvent; begin EventsReceived := True; Signal.SetEvent; end; // indicate termination desired, and stop waiting procedure TSIBEventThread.SignalTerminate; begin if not Terminated then begin Terminate; Signal.SetEvent; end; end; procedure TSIBEventThread.DoHandleException; begin SysUtils.ShowException(FExceptObject, FExceptAddr); end; function TSIBEventThread.HandleException: Boolean; begin // if a thread exception has already occurred, then // don't show another one if not Parent.ThreadException then begin Result := True; Parent.ThreadException := True; FExceptObject := ExceptObject; FExceptAddr := ExceptAddr; try if not (FExceptObject is EAbort) then if FVCLSynchro then Synchronize(DoHandleException) else DoHandleException; finally FExceptObject := nil; FExceptAddr := nil; end; end else Result := False; end; // set everything up with IB and sit in a loop // waiting for events to be received procedure TSIBEventThread.Execute; begin RegisterEvents; QueueEvents; try repeat // wait for an event to be signaled Signal.WaitFor(INFINITE); if EventsReceived then begin // handle any events that were received ProcessEvents; // queue the events QueueEvents; end; until Terminated; // thread completed OK ReturnValue := 0; except // thread had a problem, if we're the first // thread to report handle the problem, return // with an error code, otherwise return OK if HandleException then ReturnValue := 1 else ReturnValue := 0; end; end; constructor TSIBEventThread.Create(ClientLibrary:IIBClientLibrary;Owner: TSIBEventAlerter; DBHandle: SIB_DBHandle; EventGrp: Integer; TermEvent: TNotifyEvent;aVCLSynchro:boolean); begin inherited Create(True); FClientLibrary:=ClientLibrary; Signal := TSimpleEvent.Create; Parent := Owner; DB := DBHandle; EventGroup := EventGrp; OnTerminate := TermEvent; FreeOnTerminate := False; FVCLSynchro:=aVCLSynchro; Resume; end; destructor TSIBEventThread.Destroy; begin try UnRegisterEvents; except // thread had a problem, if we're the first // thread to report handle the problem, return // with an error code, otherwise return OK try if HandleException then ReturnValue := 1 else ReturnValue := 0; except end; end; Signal.Free; FClientLibrary:=nil; inherited Destroy; end; { TSIBEventAlerter } // are there any event threads running function TSIBEventAlerter.GetRegistered: Boolean; begin Result := (FThreads.Count > 0); end; // loop through all the running event threads and kill them procedure TSIBEventAlerter.UnRegisterEvents; var i: Integer; Temp: TSIBEventThread; begin if (FThreads.Count > 0) then begin for i := (FThreads.Count - 1) downto 0 do begin Temp := TSIBEventThread(FThreads[i]); FThreads.Delete(i); Temp.SignalTerminate; Temp.WaitFor; Temp.Free; end; end else raise ESIBError.Create(SIB_RS_NOT_REGISTERED); end; // calculate how many event threads we need to hold the events // and create them procedure TSIBEventAlerter.RegisterEvents; var i: Integer; DBH: SIB_DBHandle; begin if (FThreads.Count = 0) then begin DBH := NativeHandle; if (FEvents.Count > 0) then begin for i := 0 to ((FEvents.Count - 1) div SIB_MAX_EVENT_BLOCK) do FThreads.Add(TSIBEventThread.Create(FClientLibrary,Self, DBH, i, ThreadEnded,FVCLSynchro)); end; end else raise ESIBError.Create(SIB_RS_ALREADY_REGISTERED); end; // validates the event names being assigned procedure TSIBEventAlerter.EventChange(Sender: TObject); var i: Integer; TooLong, AnyEmpty, WasRegistered: Boolean; ErrorStr: string; begin ErrorStr := EmptyStr; WasRegistered := Registered; try if WasRegistered then UnRegisterEvents; TStringList(FEvents).OnChange := nil; try TooLong := False; AnyEmpty := False; // loop through all the Ansistring being assigned looking for errors for i := (FEvents.Count - 1) downto 0 do begin if (FEvents[i] = EmptyStr) then begin // can't have empty strings as events AnyEmpty := True; FEvents.Delete(i); end else if (Length(FEvents[i]) > (SIB_MAX_EVENT_LENGTH - 1)) then begin // can't have strings longer than EVENT_LENGTH TooLong := True; // FEvents[i] := Copy(FEvents[i], 1, (SIB_MAX_EVENT_LENGTH - 1)); end; end; // build the error message if AnyEmpty then ErrorStr := ErrorStr + SIB_RS_EMPTY_STRINGS; if TooLong then ErrorStr := ErrorStr + Format(SIB_RS_TOO_LONG, [(SIB_MAX_EVENT_LENGTH - 1)]); // and return it if (ErrorStr <> EmptyStr) then raise ESIBError.Create(ErrorStr); finally TStringList(FEvents).OnChange := EventChange; end; finally if WasRegistered then RegisterEvents; end; end; procedure TSIBEventAlerter.SetEvents(Value: TStrings); begin FEvents.Assign(Value); end; constructor TSIBEventAlerter.Create(Owner: TComponent); begin inherited Create(Owner); ThreadException := False; FOnEventAlert := nil; FNativeHandle := nil; FEvents := TStringList.Create; with TStringList(FEvents) do begin OnChange := EventChange; // assign the routine which validates the event lenghts Duplicates := dupIgnore; // don't allow duplicate events Sorted := True; end; FVCLSynchro:=True; FThreads := TList.Create; end; destructor TSIBEventAlerter.Destroy; begin try if Registered then UnRegisterEvents; except end; FThreads.Free; FEvents.Free; FClientLibrary:=nil; inherited Destroy; end; procedure TSIBEventAlerter.SetNativeHandle(const Value: SIB_DBHandle); var WasRegistered: Boolean; begin if (FNativeHandle <> Value) then begin WasRegistered := Registered; if WasRegistered then UnRegisterEvents; try FNativeHandle := Value; finally if WasRegistered then RegisterEvents; end; end; end; procedure TSIBEventAlerter.SetRegistered(const Value: Boolean); begin if Value then RegisterEvents else try UnRegisterEvents; except end end; procedure TSIBEventAlerter.ThreadEnded(Sender: TObject); var ThreadIdx: Integer; begin if (Sender is TSIBEventThread) then begin // Remove terminating thread from thread list ThreadIdx := FThreads.IndexOf(Sender); if (ThreadIdx > -1) then FThreads.Delete(ThreadIdx); // if any thread had an exception, then unregister everything if (TSIBEventThread(Sender).ReturnValue = 1) then begin if Registered then UnRegisterEvents; // Clear the thread exception ThreadException := False; end end; end; function TSIBEventAlerter.GetNativeHandle: SIB_DBHandle; begin Result := FNativeHandle; end; end.
var x1,x2,L: Real; begin Write('Введите x1: '); Readln(x1); Write('Введите x2: '); Readln(x2); L:=Abs(x1-x2); Writeln('Расстояние между x1 и x2 равно: ',L); end.
unit ChildCategoriesQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, SearchCategoryQuery, OrderQuery, DSWrap; type TChildCategoriesW = class(TOrderW) private FExternalID: TFieldWrap; FID: TFieldWrap; FParentExternalId: TFieldWrap; FParentID: TFieldWrap; FValue: TFieldWrap; public constructor Create(AOwner: TComponent); override; property ExternalID: TFieldWrap read FExternalID; property ID: TFieldWrap read FID; property ParentExternalId: TFieldWrap read FParentExternalId; property ParentID: TFieldWrap read FParentID; property Value: TFieldWrap read FValue; end; TQueryChildCategories = class(TQueryOrder) FDUpdateSQL: TFDUpdateSQL; private FqSearchCategory: TQuerySearchCategory; FW: TChildCategoriesW; function GetqSearchCategory: TQuerySearchCategory; { Private declarations } protected function CreateDSWrap: TDSWrap; override; procedure DoAfterOpen(Sender: TObject); property qSearchCategory: TQuerySearchCategory read GetqSearchCategory; public constructor Create(AOwner: TComponent); override; procedure AddCategory(const AValue: String); function CheckPossibility(const AParentID: Integer; const AValue: String): Boolean; function GetLevel: Integer; property W: TChildCategoriesW read FW; { Public declarations } end; implementation uses NotifyEvents; {$R *.dfm} constructor TQueryChildCategories.Create(AOwner: TComponent); begin inherited; FW := FDSWrap as TChildCategoriesW; DetailParameterName := W.ParentID.FieldName; TNotifyEventWrap.Create(W.AfterOpen, DoAfterOpen, W.EventList); end; procedure TQueryChildCategories.AddCategory(const AValue: String); var AExternalID: string; ALevel: Integer; AParentID: Integer; begin Assert(not AValue.IsEmpty); // Получаем идентификатор дочернего узла AParentID := FDQuery.ParamByName(DetailParameterName).AsInteger; ALevel := GetLevel; FDQuery.DisableControls; try W.TryPost; AExternalID := qSearchCategory.CalculateExternalId( AParentID, ALevel ); W.TryAppend; W.Value.F.AsString := AValue; W.ParentID.F.AsInteger := AParentID; W.ExternalID.F.AsString := AExternalID; W.TryPost; finally FDQuery.EnableControls; end; end; function TQueryChildCategories.CheckPossibility(const AParentID: Integer; const AValue: String): Boolean; begin Assert(FDQuery.Active); Result := qSearchCategory.SearchByParentAndValue(AParentID, AValue) = 0; end; function TQueryChildCategories.CreateDSWrap: TDSWrap; begin Result := TChildCategoriesW.Create(FDQuery); end; procedure TQueryChildCategories.DoAfterOpen(Sender: TObject); begin W.ParentExternalId.F.Required := False; // Порядок будет заполняться на стороне сервера OrderW.Ord.F.Required := False; end; function TQueryChildCategories.GetLevel: Integer; var AParentID: Integer; begin Assert(FDQuery.Active); Result := 1; // Получаем идентификатор дочернего узла AParentID := FDQuery.ParamByName(DetailParameterName).AsInteger; qSearchCategory.SearchByID(AParentID, 1); // Пока мы не добрались до корня дерева while not qSearchCategory.W.ParentID.F.IsNull do begin Inc(Result); qSearchCategory.SearchByID(qSearchCategory.W.ParentID.F.AsInteger, 1); end; end; function TQueryChildCategories.GetqSearchCategory: TQuerySearchCategory; begin if FqSearchCategory = nil then FqSearchCategory := TQuerySearchCategory.Create(Self); Result := FqSearchCategory; end; constructor TChildCategoriesW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FOrd := TFieldWrap.Create(Self, 'Ord'); FExternalID := TFieldWrap.Create(Self, 'ExternalID'); FParentExternalID := TFieldWrap.Create(Self, 'ParentExternalID'); FParentID := TFieldWrap.Create(Self, 'ParentID'); FValue := TFieldWrap.Create(Self, 'Value'); end; end.
unit Test.Devices.TR101.ReqCreator; interface uses Windows, TestFrameWork, GMGlobals, Test.Devices.UBZ, GMConst; type TTR101ReqCreatorTest = class(TUBZReqCreatorTest) protected function GetDevType(): int; override; procedure DoCheckRequests(); override; end; implementation { TTR101ReqCreatorTest } procedure TTR101ReqCreatorTest.DoCheckRequests; begin CheckReqHexString(0, '5, 3, 0, 2, 0, 6, 65, 8C'); CheckReqHexString(1, '5, 3, 0, 20, 0, 1, 84, 44'); CheckReqHexString(2, '5, 3, 0, 2E, 0, 1, E5, 87'); CheckReqHexString(3, '5, 3, 0, 3C, 0, 1, 45, 82'); CheckReqHexString(4, '5, 3, 0, 4A, 0, 1, A4, 58'); end; function TTR101ReqCreatorTest.GetDevType: int; begin Result := DEVTYPE_TR101; end; initialization RegisterTest('GMIOPSrv/Devices/TR101', TTR101ReqCreatorTest.Suite); end.
unit IdThreadSafe; interface uses Classes, SyncObjs; type TIdThreadSafe = class protected FCriticalSection: TCriticalSection; public constructor Create; virtual; destructor Destroy; override; procedure Lock; procedure Unlock; end; // Yes we know that integer operations are "atomic". However we do not like to rely on // internal compiler implementation. This is a safe and proper way to keep our code independent TIdThreadSafeInteger = class(TIdThreadSafe) protected FValue: Integer; // function GetValue: Integer; procedure SetValue(const AValue: Integer); public function Decrement: Integer; function Increment: Integer; // property Value: Integer read GetValue write SetValue; end; TIdThreadSafeCardinal = class(TIdThreadSafe) protected FValue: Cardinal; // function GetValue: Cardinal; procedure SetValue(const AValue: Cardinal); public function Decrement: Cardinal; function Increment: Cardinal; // property Value: Cardinal read GetValue write SetValue; end; TIdThreadSafeString = class(TIdThreadSafe) protected FValue: string; // function GetValue: string; procedure SetValue(const AValue: string); public procedure Append(const AValue: string); procedure Prepend(const AValue: string); // property Value: string read GetValue write SetValue; end; TIdThreadSafeStringList = class(TIdThreadSafe) protected FValue: TStringList; public constructor Create(const ASorted: Boolean = False); reintroduce; destructor Destroy; override; procedure Add(const AItem: string); procedure AddObject(const AItem: string; AObject: TObject); procedure Clear; function Lock: TStringList; reintroduce; function ObjectByItem(const AItem: string): TObject; procedure Remove(const AItem: string); procedure Unlock; reintroduce; end; TIdThreadSafeList = class(TThreadList) public function IsCountLessThan(const AValue: Cardinal): Boolean; End; implementation uses IdGlobal, // For FreeAndNil SysUtils; { TIdThreadSafe } constructor TIdThreadSafe.Create; begin inherited; FCriticalSection := TCriticalSection.Create; end; destructor TIdThreadSafe.Destroy; begin FreeAndNil(FCriticalSection); inherited; end; procedure TIdThreadSafe.Lock; begin FCriticalSection.Enter; end; procedure TIdThreadSafe.Unlock; begin FCriticalSection.Leave; end; { TIdThreadSafeInteger } function TIdThreadSafeInteger.Decrement: Integer; begin Lock; try Result := FValue; Dec(FValue); finally Unlock; end; end; function TIdThreadSafeInteger.GetValue: Integer; begin Lock; try Result := FValue; finally Unlock; end; end; function TIdThreadSafeInteger.Increment: Integer; begin Lock; try Result := FValue; Inc(FValue); finally Unlock; end; end; procedure TIdThreadSafeInteger.SetValue(const AValue: Integer); begin Lock; try FValue := AValue; finally Unlock; end; end; { TIdThreadSafeString } procedure TIdThreadSafeString.Append(const AValue: string); begin Lock; try FValue := FValue + AValue; finally Unlock; end; end; function TIdThreadSafeString.GetValue: string; begin Lock; try Result := FValue; finally Unlock; end; end; procedure TIdThreadSafeString.Prepend(const AValue: string); begin Lock; try FValue := AValue + FValue; finally Unlock; end; end; procedure TIdThreadSafeString.SetValue(const AValue: string); begin Lock; try FValue := AValue; finally Unlock; end; end; { TIdThreadSafeStringList } procedure TIdThreadSafeStringList.Add(const AItem: string); begin with Lock do try Add(AItem); finally Unlock; end; end; procedure TIdThreadSafeStringList.AddObject(const AItem: string; AObject: TObject); begin with Lock do try AddObject(AItem, AObject); finally Unlock; end; end; procedure TIdThreadSafeStringList.Clear; begin with Lock do try Clear; finally Unlock; end; end; constructor TIdThreadSafeStringList.Create(const ASorted: Boolean = False); begin inherited Create; FValue := TStringList.Create; FValue.Sorted := ASorted; end; destructor TIdThreadSafeStringList.Destroy; begin inherited Lock; try FreeAndNil(FValue); finally inherited Unlock; end; inherited; end; function TIdThreadSafeStringList.Lock: TStringList; begin inherited Lock; Result := FValue; end; function TIdThreadSafeStringList.ObjectByItem(const AItem: string): TObject; var i: Integer; begin Result := nil; with Lock do try i := IndexOf(AItem); if i > -1 then begin Result := Objects[i]; end; finally Unlock; end; end; procedure TIdThreadSafeStringList.Remove(const AItem: string); var i: Integer; begin with Lock do try i := IndexOf(AItem); if i > -1 then begin Delete(i); end; finally Unlock; end; end; procedure TIdThreadSafeStringList.Unlock; begin inherited Unlock; end; { TIdThreadSafeCardinal } function TIdThreadSafeCardinal.Decrement: Cardinal; begin Lock; try Result := FValue; Dec(FValue); finally Unlock; end; end; function TIdThreadSafeCardinal.GetValue: Cardinal; begin Lock; try Result := FValue; finally Unlock; end; end; function TIdThreadSafeCardinal.Increment: Cardinal; begin Lock; try Result := FValue; Inc(FValue); finally Unlock; end; end; procedure TIdThreadSafeCardinal.SetValue(const AValue: Cardinal); begin Lock; try FValue := AValue; finally Unlock; end; end; { TIdThreadSafeList } function TIdThreadSafeList.IsCountLessThan(const AValue: Cardinal): Boolean; Begin if Assigned(SELF) then begin try Result := Cardinal(LockList.Count) < AValue; finally UnlockList; end; end else begin Result := TRUE; // none always < end; End; end.
unit App.Core; interface uses System.SysUtils, System.Classes, App.Types, App.Abstractions, App.HandlerCore, BlockChain.Core, Net.Core, WebServer.HTTPCore, UI.Abstractions, UI.CommandLineParser, UI.ConsoleUI, UI.GUI, Wallet.Core; type TAppCore = class(TInterfacedObject, IAppCore) private isTerminate: boolean; UI: TBaseUI; BlockChain: TBlockChainCore; Net: TNetCore; WebServer: TWebServer; HandlerCore: THandlerCore; WalletCore: TWalletCore; { Procedures } procedure AppException(Sender: TObject); public procedure Terminate; procedure DoRun; procedure ShowMessage(AMessage: string); constructor Create; destructor Destroy; override; end; implementation { TAppCore } constructor TAppCore.Create; begin {$IFDEF CONSOLE} UI := TConsoleUI.Create; {$ENDIF} {$IFDEF GUI} UI := TGUI.Create; {$ENDIF} ApplicationHandleException := AppException; BlockChain := TBlockChainCore.Create; HandlerCore := THandlerCore.Create; Net := TNetCore.Create(HandlerCore); WebServer := TWebServer.Create(HandlerCore); WalletCore := TWalletCore.Create; HandlerCore.BlockChain := BlockChain; HandlerCore.UI := UI; HandlerCore.Net := Net; HandlerCore.WalletCore := WalletCore; HandlerCore.WebServer := WebServer; UI.ShowMessage := ShowMessage; UI.Handler := HandlerCore; end; procedure TAppCore.AppException(Sender: TObject); var O: TObject; begin O := ExceptObject; if O is Exception then begin if not(O is EAbort) then ShowMessage(Exception(O).Message) end else System.SysUtils.ShowException(O, ExceptAddr); end; destructor TAppCore.Destroy; begin UI.Free; inherited; end; procedure TAppCore.DoRun; begin TConsoleUI(UI).DoRun; end; procedure TAppCore.ShowMessage(AMessage: string); begin TThread.Synchronize(nil, procedure begin WriteLn(AMessage) end); end; procedure TAppCore.Terminate; begin isTerminate := True; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Data.Bind.JSON; interface implementation uses System.Bindings.EvalProtocol, System.Rtti, System.Bindings.Outputs, System.Classes, System.SysUtils, System.Bindings.Helper, System.JSON; const sIDJSONToString = 'JSONToString'; // Leave unit name blank so this unit will not be autmatically added to uses list (because we don't want a database dependency). sThisUnit = ''; // 'Data.Bind.JSON'; procedure RegisterOutputConversions; begin // Support assignment of TJSONValue to string TValueRefConverterFactory.RegisterConversion(TypeInfo(TJSONValue), TypeInfo(string), TConverterDescription.Create( procedure(const InValue: TValue; var OutValue: TValue) var LOutString: string; LValue: TJSONValue; begin if InValue.IsEmpty then LOutString := '' else begin if not InValue.TryAsType<TJSONValue>(LValue) then LOutString := '' else if LValue is TJSONString then // Return string without quotes LOutString := TJSONString(LValue).Value else LOutString := LValue.ToString; end; OutValue := TValue.From<string>(LOutString); end, sIDJSONToString, sIDJSONToString, sThisUnit, True, '', nil) ); end; procedure UnregisterOutputConversions; begin TValueRefConverterFactory.UnRegisterConversion( TypeInfo(TJSONValue), TypeInfo(string)); end; initialization RegisterOutputConversions; finalization UnregisterOutputConversions; end.
unit ufrmEditCreature; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, uDM; type TfrmEditCreature = class(TForm) btnSave: TBitBtn; edtName: TEdit; Label1: TLabel; Label2: TLabel; edtImage: TEdit; Label3: TLabel; edtMaxHP: TEdit; Label4: TLabel; edtCR: TEdit; Label5: TLabel; edtInit: TEdit; Label6: TLabel; edtStr: TEdit; Label7: TLabel; edtDex: TEdit; Label8: TLabel; edtCon: TEdit; Label9: TLabel; edtWis: TEdit; Label10: TLabel; edtInt: TEdit; Label11: TLabel; edtCha: TEdit; Label12: TLabel; edtXP: TEdit; procedure btnSaveClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FCreature : TCreature; public { Public declarations } Procedure SetCreature(aCreature : TCreature); Function GetCreature : TCreature; end; var frmEditCreature: TfrmEditCreature; implementation {$R *.dfm} procedure TfrmEditCreature.btnSaveClick(Sender: TObject); begin ModalResult := mrOK; end; procedure TfrmEditCreature.FormCreate(Sender: TObject); begin FCreature := TCreature.Create; end; procedure TfrmEditCreature.FormDestroy(Sender: TObject); begin FCreature.Free; end; function TfrmEditCreature.GetCreature: TCreature; begin FCreature.Name := edtName.Text; FCreature.image := edtImage.Text; FCreature.maxHealth := StrToIntDef(edtMaxHP.Text, 0); FCreature.initiative := StrToIntDef(edtInit.Text, 0); FCreature.cr := StrToCurrDef(edtCR.Text, 0); FCreature.xp := StrToIntDef(edtXP.Text, 0); FCreature.stats.str := StrToIntDef(edtStr.Text, 0); FCreature.stats.dex := StrToIntDef(edtDex.Text, 0); FCreature.stats.con := StrToIntDef(edtCon.Text, 0); FCreature.stats.int := StrToIntDef(edtInt.Text, 0); FCreature.stats.wis := StrToIntDef(edtWis.Text, 0); FCreature.stats.cha := StrToIntDef(edtCha.Text, 0); Result := FCreature; end; procedure TfrmEditCreature.SetCreature(aCreature: TCreature); begin FCreature := aCreature; edtName.Text := FCreature.Name; edtImage.Text := FCreature.image; edtMaxHP.Text := IntToStr(FCreature.maxHealth); edtInit.Text := IntToStr(FCreature.initiative); edtCR.Text := CurrToStr(FCreature.cr); edtXP.Text := IntToStr(FCreature.xp); edtStr.Text := IntToStr(FCreature.stats.str); edtDex.Text := IntToStr(FCreature.stats.dex); edtCon.Text := IntToStr(FCreature.stats.con); edtInt.Text := IntToStr(FCreature.stats.int); edtWis.Text := IntToStr(FCreature.stats.wis); edtCha.Text := IntToStr(FCreature.stats.cha); end; end.
//////////////////////////////////////////// // Кодировка и расчет CRC для приборов типа Взлет УРСВ //////////////////////////////////////////// unit Devices.Vzlet; interface uses Windows, GMGlobals, GMConst, Devices.ReqCreatorBase, GmSqlQuery, SysUtils; type TVzletURSVReqCreator = class(TDevReqCreator) private procedure AddVzletURSVToSendBuf_OneQuery(ID_Src, nChannel: int); public procedure AddRequests(); override; end; procedure Vzlet_CRC(var buf: array of Byte; Len: int); function Vzlet_CheckCRC(const buf: array of Byte; Len: int): bool; function Vzlet_Register_ID(ID_Src, nChannel: int): WORD; function Vzlet_Register_ReqType(ID_Src, nChannel: int): T485RequestType; implementation uses Devices.UBZ, ProgramLogFile; // Взлет УРСВ использует ту же самую CRC с полиномом $A001, что и УБЗ procedure Vzlet_CRC(var buf: array of Byte; Len: int); begin UBZ_CRC(buf, Len); end; function Vzlet_CheckCRC(const buf: array of Byte; Len: int): bool; begin Result := UBZ_CheckCRC(buf, Len); end; function Vzlet_Register_ID(ID_Src, nChannel: int): WORD; begin Result := 0; if ID_Src = SRC_AI then case nChannel of 1: Result := $C1A8; 2: Result := $C1AA; 3: Result := $C1AC; 4: Result := $C1AE; end; end; function Vzlet_Register_ReqType(ID_Src, nChannel: int): T485RequestType; begin Result := rqtNone; if ID_Src = SRC_AI then case nChannel of 1: Result := rqtVZLET_URSV_Q1; 2: Result := rqtVZLET_URSV_Q2; 3: Result := rqtVZLET_URSV_Q3; 4: Result := rqtVZLET_URSV_Q4; end; end; { TVzletURSVReqCreator } procedure TVzletURSVReqCreator.AddVzletURSVToSendBuf_OneQuery(ID_Src, nChannel: int); var buf: array[0..20] of byte; rqtp: T485RequestType; begin rqtp := Vzlet_Register_ReqType(ID_Src, nChannel); if rqtp = rqtNone then Exit; buf[0] := FReqDetails.DevNumber and $FF; buf[1] := 04; // запрос регистра WriteWORDInv(buf, 2, Vzlet_Register_ID(ID_Src, nChannel)); buf[4] := 0; buf[5] := 2; // число регистров Vzlet_CRC(buf, 6); AddBufRequestToSendBuf(buf, 8, rqtp); end; procedure TVzletURSVReqCreator.AddRequests; var q: TGMSqlQuery; begin q := TGMSqlQuery.Create(); try q.SQL.Text := 'select * from Params where ID_Device = ' + IntToStr(FReqDetails.ID_Device) + ' and ID_PT > 0 order by ID_Src, N_Src'; q.Open(); while not q.Eof do begin AddVzletURSVToSendBuf_OneQuery(q.FieldByName('ID_Src').AsInteger, q.FieldByName('N_Src').AsInteger ); q.Next(); end; except on e: Exception do ProgramLog().AddException('AddVzletURSVToSendBuf - ' + e.Message); end; q.Free(); end; end.
unit Code02.pslomski.DaylightTimeZone; interface { @theme: Delphi Challenge @subject: #02 Daylight Time Zone @author: Bogdan Polak @date: 2020-05-16 21:00 } { Zadaniem jest wydobycie z treści strony https://www.timeanddate.com/ informacji o tym czy w podanej strefie czasowej wykonuje się przesuniecie czasu podstawowego (zimowego) na czas letni. Daylight Saving Time Funkcja: * IsDaylightSaving - powinna sprawdzić to dla podanego roku (year) i dla podanego obszaru (area). Jeśli przesuniecie czasu jest aktywne to funkcje: * GetDaylightStart * GetDaylightEnd powinny zwrócić informacje w jakim dniu i o jakiej godzinie następuje przesuniecie czasu. Dla przykładu przy danych: - area: poland/warsaw - year: 2015 Powinna zostać wywołana strona: https://www.timeanddate.com/time/change/poland/warsaw?year=2015 i na podstawie analizy treści strony WWW należy zwrócić podane wyżej wyniki Aby nie powtarzać wielokrotnego pobierania danych dla tych samych stron należy przechować poprzednie wyniki, aby nie pobierać wielokrotnie tych samych danych. Uwaga! Wymagane jest użycie `TMyHttpGet.GetWebsiteContent` do pobrania zawartości strony Przykład wywołania: aHtmlPageContent := TMyHttpGet.GetWebsiteContent(‘http://delphi.pl/’); } function IsDaylightSaving(const area: string; year: word): boolean; function GetDaylightStart(const area: string; year: word): TDateTime; function GetDaylightEnd(const area: string; year: word): TDateTime; implementation uses System.SysUtils, Code02.HttpGet, TimeAndDate; function IsDaylightSaving(const area: string; year: word): boolean; begin Result := BuildTimeAndDateWebSite.IsDaylightSaving(area, year); end; function GetDaylightStart(const area: string; year: word): TDateTime; begin Result := BuildTimeAndDateWebSite.GetDaylightStart(area, year); end; function GetDaylightEnd(const area: string; year: word): TDateTime; begin Result := BuildTimeAndDateWebSite.GetDaylightEnd(area, year); end; end.
(******************************************************************************) (* This file contans the implementations of the low level procedures and *) (* functions. Those includes Little-Big endian converter, sign extension *) (* Bit swappers and low level memory access. *) (******************************************************************************) //## 8086 FLAGS LAYOUT //## F E D C B A 9 8 7 6 5 4 3 2 1 0 //##|_|_|_|_|O|D|I|T|S|Z|_|A|_|P|_|C| //## 68030 FLAGS LAYOUT //## |X|N|Z|V|C| (******************************************************************************) function cpu68k.lo16(data:longword):word; assembler; asm mov eax,data end; (******************************************************************************) function cpu68k.bfGETu(data:longword;offs,dep:byte):longword; assembler; asm mov eax,data mov cl,offs shl eax,cl mov ch,$20 sub ch,cl sub ch,dep add cl,ch shr eax,cl end; (******************************************************************************) function cpu68k.bfGETs(data:longword;offs,dep:byte):longword; assembler; asm mov eax,data mov cl,offs shl eax,cl mov ch,$20 sub ch,cl sub ch,dep add cl,ch sar eax,cl end; function cpu68k.addrcalc(addr1,addr2:pointer):longword; assembler; asm push ebx mov eax,addr1 mov ebx,addr2 sub eax,ebx pop ebx end; Procedure cpu68k.divu64(op1hig,op1low,op2low,op2hig:longword;var reslow,reshig:longword);assembler; asm push ebx push esi push edi push ebp mov ebx, op2low mov ebp, op2hig mov ecx, 40h xor edi, edi xor esi, esi @loc_4: shl eax, 1 rcl edx, 1 rcl esi, 1 rcl edi, 1 cmp edi, ebp jb @loc_2 ja @loc_1 cmp esi, ebx jb @loc_2 @loc_1: sub esi, ebx sbb edi, ebp inc eax @loc_2: loop @loc_4 @loc_3: pop ebp mov edi,reslow mov longword ptr[edi], eax mov edi,reshig mov longword ptr[edi], edx pop edi pop esi pop ebx end; (******************************************************************************) function cpu68k.ror8(var b:byte;count:byte):boolean;assembler; asm push cx mov al,byte ptr [b] mov cl,count ror al,cl mov byte ptr[b],al mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.ror16(var b:word;count:byte):boolean;assembler; asm push cx mov ax,word ptr [b] mov cl,count ror ax,cl mov word ptr[b],ax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.ror32(var b:longword;count:byte):boolean;assembler; asm push cx mov eax,longword ptr [b] mov cl,count ror eax,cl mov longword ptr[b],eax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rol8(var b:byte;count:byte):boolean;assembler; asm push cx mov al,byte ptr [b] mov cl,count rol al,cl mov byte ptr[b],al mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rol16(var b:word;count:byte):boolean;assembler; asm push cx mov ax,word ptr [b] mov cl,count rol ax,cl mov word ptr[b],ax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rol32(var b:longword;count:byte):boolean;assembler; asm push cx mov eax,longword ptr [b] mov cl,count rol eax,cl mov longword ptr[b],eax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.shr8(var b:byte;count:byte):boolean;assembler; asm push cx mov al,byte ptr [b] mov cl,count shr al,cl mov byte ptr[b],al mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.shr16(var b:word;count:byte):boolean;assembler; asm push cx mov ax,word ptr [b] mov cl,count shr ax,cl mov word ptr[b],ax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.shr32(var b:longword;count:byte):boolean;assembler; asm push cx mov eax,longword ptr [b] mov cl,count shr eax,cl mov longword ptr[b],eax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.shl8(var b:byte;count:byte):boolean;assembler; asm push cx mov al,byte ptr [b] mov cl,count shl al,cl mov byte ptr[b],al mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.shl16(var b:word;count:byte):boolean;assembler; asm push cx mov ax,word ptr [b] mov cl,count shl ax,cl mov word ptr[b],ax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.shl32(var b:longword;count:byte):boolean;assembler; asm push cx mov eax,longword ptr [b] mov cl,count shl eax,cl mov longword ptr[b],eax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.sar8(var b:byte;count:byte):boolean;assembler; asm push cx mov al,byte ptr [b] mov cl,count sar al,cl mov byte ptr[b],al mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.sar16(var b:word;count:byte):boolean;assembler; asm push cx mov ax,word ptr [b] mov cl,count sar ax,cl mov word ptr[b],ax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.sar32(var b:longword;count:byte):boolean;assembler; asm push cx mov eax,longword ptr [b] mov cl,count sar eax,cl mov longword ptr[b],eax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.sal8(var b:byte;count:byte):boolean;assembler; asm push cx mov al,byte ptr [b] mov cl,count sal al,cl mov byte ptr[b],al mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.sal16(var b:word;count:byte):boolean;assembler; asm push cx mov ax,word ptr [b] mov cl,count sal ax,cl mov word ptr[b],ax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.sal32(var b:longword;count:byte):boolean;assembler; asm push cx mov eax,longword ptr [b] mov cl,count sal eax,cl mov longword ptr[b],eax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rcr8(var b:byte;count,carry:byte):boolean;assembler; asm push cx mov al,carry or al,al clc jnz @NoCarry stc @NoCarry: mov al,byte ptr [b] mov cl,count rcr al,cl mov byte ptr[b],al mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rcr16(var w:word;count,carry:byte):boolean;assembler; asm push cx mov al,carry or al,al clc jnz @NoCarry stc @NoCarry: mov ax,word ptr [w] mov cl,count rcr al,cl mov word ptr[w],ax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rcr32(var l:longword;count,carry:byte):boolean;assembler; asm push cx mov al,carry or al,al clc jnz @NoCarry stc @NoCarry: mov eax,longword ptr [l] mov cl,count rcr al,cl mov longword ptr[l],eax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rcl8(var b:byte;count,carry:byte):boolean;assembler; asm push cx mov al,carry or al,al clc jnz @NoCarry stc @NoCarry: mov al,byte ptr [b] mov cl,count rcl al,cl mov byte ptr[b],al mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rcl16(var w:word;count,carry:byte):boolean;assembler; asm push cx mov al,carry or al,al clc jnz @NoCarry stc @NoCarry: mov ax,word ptr [w] mov cl,count rcl al,cl mov word ptr[w],ax mov al,0 jnc @fin inc al @fin: pop cx end; (******************************************************************************) function cpu68k.rcl32(var l:longword;count,carry:byte):boolean;assembler; asm push cx mov al,carry or al,al clc jnz @NoCarry stc @NoCarry: mov eax,longword ptr [l] mov cl,count rcl al,cl mov longword ptr[l],eax mov al,0 jnc @fin inc al @fin: pop cx end; (***********************************************************) function cpu68k.signext16(w:word):longword;assembler; asm push edx and edx,$0000ffff or dx,dx jns @no or edx,$ffff0000 @no: mov eax,edx pop edx end; (***********************************************************) function cpu68k.signext8(w:byte):longword;assembler; asm push edx and edx,$000000ff or dl,dl jns @no or edx,$ffffff00 @no: mov eax,edx pop edx end; (***********************************************************) function cpu68k.LBW(l:longword):longword;assembler; asm mov eax,l xchg al,ah end; (***********************************************************) function cpu68k.LBL(l:longword):longword;assembler; asm push ecx mov eax,l mov ecx,eax xchg al,ah shl eax,16 shr ecx,16 xchg cl,ch add eax,ecx pop ecx end; (***********************************************************) function cpu68k.regModSwap(n:byte):byte;assembler; asm mov al,n mov ah,al and al,$7 and ah,$38 shl al,3 shr ah,3 or al,ah end; (***********************************************************) function cpu68k.getbyte(address:longword;var page):byte;assembler; asm push esi push ecx mov esi,page mov ecx,address add esi,ecx lodsb pop ecx pop esi end; (***********************************************************) function cpu68k.getword(address:longword;var page):word;assembler; asm push esi push ecx cld mov esi,page mov ecx,address add esi,ecx lodsw xchg al,ah pop ecx pop esi end; (***********************************************************) function cpu68k.getlongword(address:longword;var page):longword;assembler; asm push esi push ecx cld mov esi,page mov ecx,address add esi,ecx lodsw xchg al,ah mov cx,ax shl ecx,16 lodsw xchg al,ah and eax,$ffff add eax,ecx pop ecx pop esi end; (***********************************************************) procedure cpu68k.putbyte(address:longword;val:byte;var page);assembler; asm push edi push ecx push eax mov al,val mov edi,page mov ecx,address add edi,ecx stosb pop eax pop ecx pop edi end; (***********************************************************) procedure cpu68k.putword(address:longword;val:word;var page);assembler; asm push edi push ecx push eax mov ax,val mov edi,page mov ecx,address add edi,ecx xchg al,ah stosw pop eax pop ecx pop edi end; (***********************************************************) procedure cpu68k.putlongword(address,val:longword;var page);assembler; asm push edi push ecx push eax mov eax,val mov edi,page mov ecx,address add edi,ecx mov cx,ax xchg cl,ch shl ecx,16 shr eax,16 xchg al,ah add eax,ecx stosd pop eax pop ecx pop edi end;
// GLDWS2Objects {: Base classes and logic for DelphiWebScriptII enabled objects in GLScene<p> <b>History : </b><font size=-1><ul> <li>04/11/2004 - SG - Moved TGLDelphiWebScriptII to GLScriptDWS2 unit. <li>06/04/2004 - SG - Creation </ul></font> } unit GLDWS2Objects; interface uses Classes, SysUtils, dws2Comp, dws2Exprs, dws2Symbols, GLScene, XCollection, GLScriptDWS2, GLBaseClasses, GLManager; type // TGLDWS2ActiveBehaviour // { A DelphiWebScriptII enabled behaviour. This behaviour also calls on the OnProgress and OnBeginProgram procedures in the script if they are found. Once compiled and executed the program remains active until killed, deactivated or the script is invalidated. } TGLDWS2ActiveBehaviour = class (TGLBehaviour) private FActive : Boolean; FScript : TStringList; FDWS2Program : TProgram; FCompiler : TGLDelphiWebScriptII; FCompilerName : String; procedure SetActive(const Value : Boolean); procedure SetScript(const Value : TStringList); procedure SetCompiler(const Value : TGLDelphiWebScriptII); procedure CompileProgram; procedure BeginProgram; procedure EndProgram; procedure KillProgram; protected procedure WriteToFiler(writer : TWriter); override; procedure ReadFromFiler(reader : TReader); override; procedure Loaded; override; public constructor Create(AOwner : TXCollection); override; destructor Destroy; override; class function FriendlyName : String; override; procedure DoProgress(const ProgressTimes : TProgressTimes); override; procedure InvalidateScript; property DWS2Program : TProgram read FDWS2Program; published property Active : Boolean read FActive write SetActive; property Script : TStringList read FScript write SetScript; property Compiler : TGLDelphiWebScriptII read FCompiler write SetCompiler; end; procedure Register; // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- implementation // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- // ---------- // ---------- Miscellaneous ---------- // ---------- procedure Register; begin RegisterClasses([TGLDWS2ActiveBehaviour]); end; // ---------- // ---------- TGLDWS2ActiveBehaviour ---------- // ---------- // Create // constructor TGLDWS2ActiveBehaviour.Create(AOwner: TXCollection); begin inherited; FScript:=TStringList.Create; end; // Destroy // destructor TGLDWS2ActiveBehaviour.Destroy; begin KillProgram; FScript.Free; inherited; end; // FriendlyName // class function TGLDWS2ActiveBehaviour.FriendlyName: String; begin Result:='DWS2 Active Script'; end; // DoProgress // procedure TGLDWS2ActiveBehaviour.DoProgress(const ProgressTimes: TProgressTimes); var Symbol : TSymbol; begin inherited; if Assigned(FDWS2Program) then begin if FDWS2Program.ProgramState = psRunning then begin Symbol:=DWS2Program.Table.FindSymbol('OnProgress'); if Assigned(Symbol) then if Symbol is TFuncSymbol then DWS2Program.Info.Func['OnProgress'].Call([ProgressTimes.newTime, ProgressTimes.deltaTime]); end; end; end; // Loaded // procedure TGLDWS2ActiveBehaviour.Loaded; var temp : TComponent; begin inherited; if FCompilerName<>'' then begin temp:=FindManager(TGLDelphiWebScriptII, FCompilerName); if Assigned(temp) then Compiler:=TGLDelphiWebScriptII(temp); FCompilerName:=''; CompileProgram; if Active then BeginProgram; end; end; // ReadFromFiler // procedure TGLDWS2ActiveBehaviour.ReadFromFiler(reader: TReader); begin inherited; with reader do begin Assert(ReadInteger = 0); // Archive version Active:=ReadBoolean; FCompilerName:=ReadString; Script.Text:=ReadString; end; end; // WriteToFiler // procedure TGLDWS2ActiveBehaviour.WriteToFiler(writer: TWriter); begin inherited; with writer do begin WriteInteger(0); // Archive version WriteBoolean(FActive); if Assigned(FCompiler) then WriteString(FCompiler.GetNamePath) else WriteString(''); WriteString(Script.Text); end; end; // CompileProgram // procedure TGLDWS2ActiveBehaviour.CompileProgram; begin if Assigned(Compiler) then begin KillProgram; FDWS2Program:=Compiler.Compile(Script.Text); if Active then BeginProgram; end; end; // BeginProgram // procedure TGLDWS2ActiveBehaviour.BeginProgram; var Symbol : TSymbol; ObjectID : Variant; Obj : TGLBaseSceneObject; begin if Assigned(DWS2Program) then begin if DWS2Program.ProgramState = psReadyToRun then begin DWS2Program.BeginProgram; if FDWS2Program.ProgramState = psRunning then begin Symbol:=DWS2Program.Table.FindSymbol('OnBeginProgram'); if Assigned(Symbol) then if Symbol is TFuncSymbol then begin Obj:=OwnerBaseSceneObject; if Assigned(Obj) then begin ObjectID:=DWS2Program.Info.RegisterExternalObject(Obj, False, False); DWS2Program.Info.Func['OnBeginProgram'].Call([ObjectID]); end; end; end; end; end; end; // EndProgram // procedure TGLDWS2ActiveBehaviour.EndProgram; begin if Assigned(DWS2Program) then begin if DWS2Program.ProgramState = psRunning then DWS2Program.EndProgram; end; end; // KillProgram // procedure TGLDWS2ActiveBehaviour.KillProgram; begin if Assigned(DWS2Program) then begin EndProgram; FreeAndNil(FDWS2Program); end; end; // InvalidateScript // procedure TGLDWS2ActiveBehaviour.InvalidateScript; begin KillProgram; CompileProgram; end; // SetActive // procedure TGLDWS2ActiveBehaviour.SetActive(const Value: Boolean); begin if Value<>FActive then begin EndProgram; FActive:=Value; if Active then BeginProgram; end; end; // SetScript // procedure TGLDWS2ActiveBehaviour.SetScript(const Value: TStringList); begin if Assigned(Value) then begin KillProgram; FScript.Assign(Value); if Assigned(Compiler) then begin CompileProgram; if Active then BeginProgram; end; end; end; // SetCompiler // procedure TGLDWS2ActiveBehaviour.SetCompiler(const Value: TGLDelphiWebScriptII); begin if Value<>FCompiler then begin if Assigned(FCompiler) then KillProgram; FCompiler:=Value; if Assigned(FCompiler) then begin RegisterManager(FCompiler); CompileProgram; if Active then BeginProgram; end; end; end; // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- initialization // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- RegisterXCollectionItemClass(TGLDWS2ActiveBehaviour); // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- finalization // -------------------------------------------------- // -------------------------------------------------- // -------------------------------------------------- UnregisterXCollectionItemClass(TGLDWS2ActiveBehaviour); end.
{ Copyright (c) 2005, Loginov Dmitry Sergeevich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } {*****************************************************************************} { } { Модуль LDSfunc содержит разнообразные функции, которые могут быть полезными } { при разработке приложений. В частности к ним относятся функции по копирован-} { ию и перемещению файлов и папок - здесь реализована возможность удобной } { визуализации хода копирования (как к TotalCommander). Также в этом модуле } { есть функция для поиска информации (текстовой, 16-ричной) в любых файлах } { Вы имеете полное право скопировать в свое приложение любой участок кода. } { Некоторые примеры были взяты из книжки Флёнова М. "Делфи глазами хакера" } { } { (c) Логинов Д.С., 2004-2005 } { http://matrix.kladovka.net.ru } { e-mail: loginov_d@inbox.ru } {*****************************************************************************} unit LDSfunc; interface uses Windows, SysUtils, // Нужен для осуществления файловых операций Classes, // Также нужен для операций над файлами ShlObj, ShellAPI, Graphics, Registry, ActiveX, ComObj, // Нужны для ярлыков WinSock; // Для определения IP-имени { ******************** Как пользоваться константами *************************} { Все числовые константы начинаются с префикса (например PATH_DESKTOP содержит префикс PATH_). Некоторые функции модуля в качестве одного из аргументов имеют переменую, обозначающую тип возвращаемой информации. Ее название тоже может имееть префикс. Например, если эта переменная называется PATH_TYPE, то вместо нее можно подставить любую константу, имеющую такой же префикс } Const // Переменные окружения Windows // нужны для извлечения системных путей PATH_DESKTOP = $0000; // Рабочий стол PATH_INTERNET = $0001; PATH_PROGRAMS = $0002; // "Все программы" PATH_CONTROLS = $0003; // ХЗ PATH_PRINTERS = $0004; PATH_PERSONAL = $0005; // Мои документы PATH_FAVORITES = $0006; // Избранное PATH_STARTUP = $0007; // Автозагрузка PATH_RECENT = $0008; // Ярлыки на недавние документы PATH_SENDTO = $0009; PATH_BITBUCKET = $000a; PATH_STARTMENU = $000b; // Меню "Пуск" PATH_DESKTOPDIRECTORY = $0010; // Рабочий стол PATH_DRIVES = $0011; PATH_NETWORK = $0012; PATH_NETHOOD = $0013; PATH_FONTS = $0014; PATH_TEMPLATES = $0015; PATH_COMMON_STARTMENU = $0016; PATH_COMMON_PROGRAMS = $0017; PATH_COMMON_STARTUP = $0018; PATH_COMMON_DESKTOPDIRECTORY = $0019; PATH_APPDATA = $001a; PATH_PRINTHOOD = $001b; PATH_ALTSTARTUP = $001d; PATH_COMMON_ALTSTARTUP = $001e; PATH_COMMON_FAVORITES = $001f; PATH_INTERNET_CACHE = $0020; PATH_COOKIES = $0021; PATH_HISTORY = $0022; PATH_TEMP = $0023; // My PATH_MYMUSIC_XP = $000d; PATH_MYGRAPHICS_XP = $0027; PATH_WINDOWS = $0024; // My PATH_SYSTEM = $0025; // My PATH_PROGRAMFILES = $0026; // My PATH_COMMONFILES = $002b; // My PATH_RESOURCES_XP = $0038; PATH_CURRENTUSER_XP = $0028; // Константы для извлечения информации о процессоре CP_SPEED = $0001; // скорость CP_Identifier = $0002; // Стандартное название CP_NameString = $0003; // Понятное название CP_Usage = $0004; // Загрузка (adCpuUsage.pas) CP_VendorIdentifier = $0005; // Производитель CP_MMXIdentifier = $0006; // Инф. о сопроцессоре CP_Count = $0007; // Кол-во процессоров (adCpuUsage) // Константы для извлечения информации о ОС OS_Version = $0001; OS_Platform = $0002; OS_Name = $0003; OS_Organization = $0004; OS_Owner = $0005; OS_SerNumber = $0006; OS_WinPath = $0007; OS_SysPath = $0008; OS_TempPath = $0009; OS_ProgramFilesPath = $000a; OS_IPName = $000b; // Константы для извлечения информации о памяти MEM_TotalPhys = $0001; // Всего физ. памяти MEM_AvailPhys = $0002; // Свободно физ. памяти MEM_NotAvailPhys = $0003; // Занять физ. памяти MEM_TotalPageFile = $0004; // Файл подкачки MEM_AvailPageFile = $0005; MEM_NotAvailPageFile = $0006; MEM_TotalVirtual = $0007; // Виртуальная память MEM_AvailVirtual = $0008; MEM_NotAvailVirtual = $0009; // Константы для извлечения информации о диске DI_TomLabel = $0001; DI_SerNumber = $0002; DI_FileSystem = $0003; DI_SectorsInClaster = $0004; DI_BytesInSector = $0005; DI_DiskSize = $0006; DI_DiskFreeSize = $0007; DI_DiskUsageSize = $0008; DI_MaximumLength = $0009; // Максимальная длина пути DI_TotalClasters = $000a; DI_FreeClasters = $000b; // Константы для извлечения информации о дисплее DS_BitsOnPixel = $0001; // Разрядность цвета DS_HorPixelSize = $0002; // Разреш. по горизонтали DS_VerPixelSize = $0003; // Разреш. по вертикали DS_Frequency = $0004; // Частота мерцаний (XP) DS_HorMMSize = $0005; // Ширина в миллиметрах DS_VerMMSize = $0006; // Высота в миллиметрах DS_PixelsOnInch_Hor = $0007; // Пикселей на дюйм DS_PixelsOnInch_Ver = $0008; // Пикселей на дюйм DS_ColorsInSysPalette = $0009; // Цветов в сис. палитре // Константы для загрузки параметров окна из ини-файла WP_WindowState = $0001; WP_Top = $0002; WP_Left = $0003; WP_Width = $0004; WP_Height = $0005; type { Вы можете объявить например следующую функцию: function DrawCopyProgress(Sour, Dest: String; CopyBytes, Size: DWORD; Speed: Real; FileNum, Files: Integer): Boolean; Аргументы следующие: - Sour - файл-источник, - Dest - файл-приемник, - CopyBytes - число скопированных байтов - Size - размер исходного файла, - Speed - скорость копирования, - FileNum - порядковый номер копируемого файла, - Files - общее число копируемых файлов Функция должна возвращать значение True. Если она вернет False, то процесс копирования будет прерван. В дальнейшем функцию DrawCopyProgress нужно указывать в качестве необязательного параметра к функциям копирования или перемещения файлов и папок} TCopyFileProgress = function(Sour, Dest: String; CopyBytes, Size: DWORD; Speed: Real; FileNum, Files: Integer): Boolean; { Работает аналогично TCopyFileProgress, но передает число просмотренных байт и размер файла. Используется при визуализации поиска в файле} TFindProgress = function(ByteNum, Bytes: Int64): Boolean; TLDSfunc = class(TObject) private LastSpeed: Real; function FileSetAttr(const FileName: string; Attr: Integer): Integer; function FileGetAttr(const FileName: string): Integer; function _GetDirList(DirName: String; var List: TStringList): DWORD; function _MixLists(var MasterList, DetailList: TStringList): DWORD; function _GetFileList(DirName: String; var List: TStringList): DWORD; function _GetFilesInfo(DirName: String; var CommonSize: Real): Integer; function _DelEmptyPath(DirName, LastDir: String): Boolean; procedure DoError(Msg: String); public (* Определяет размер файла в байтах *) function FileSize(FileName: String): Integer; (* Копирует файл с поддержкой визуализации копирования. Необязательные параметры менять не нужно - они используются другими функциями *) function FileCopy(Sour, Dest: String; VisProc: TCopyFileProgress = nil; FileNum: Integer = 1; Files: Integer = 1): Boolean; (* Перемещает файл с поддержкой визуализации копирования. Необязательные параметры менять не нужно - они используются другими функциями *) function FileMove(Sour, Dest: String; VisProc: TCopyFileProgress = nil; FileNum: Integer = 1; Files: Integer = 1): Boolean; (* Осуществляет поиск информации в файле FileName вы можете в качестве строки поиска задать HEX-последовательность или текст, например: 'aa bb ff'. TypeFind определяет тип поиска. При значении 1 ищется HEX-последовательность, при 2 ищется текст с учетом регистра, при 3 ищется текст без учета регистра. Возвращает адес начала искомой информации. Поддерживает визуализацию процесса поиска *) function FindHexStringInFile( FileName: String; // Имя файла HexString: String; // Строка поиска (HEX-последовательность или текст) StartByte: DWORD; // Откуда начинать поиск TypeFind: Byte; // Тип поиска Func: TFindProgress = nil): DWORD; (* Создает полный путь FullPath. Будут созданы все необходимые каталоги *) function CreateDir(FullPath: String; DirAttrib: DWORD = 0): Boolean; (* Копирование директории. Поддерживается визуализация процесса копирования *) function DirCopy(DirSour, DirDest: String; LogFileName: String; VisProc: TCopyFileProgress = nil): Boolean; (* Перемещение директории. Поддерживается визуализация процесса копирования *) function DirMove(DirSour, DirDest: String; LogFileName: String; VisProc: TCopyFileProgress = nil): Boolean; (* Удаление директории. Удаляются также все вложенные папки и файлы *) function DirDelete(DirName: String; LogFileName: String = ''): Boolean; (* Возвращает системный путь *) function GetSystemPath(Handle: THandle; PATH_type: WORD): String; (* Возвращает информацию о диске *) function GetDiskInfo(DiskName: String; DI_typeinfo: Byte): String; (* Возвращает информацию о состоянии памяти *) function GetMemoryInfo(MEM_typeinfo: Byte): DWORD; (* Возвращает информацию об операционной системы *) function GetOSInfo(OS_typeinfo: Byte; Default: String): String; (* Определяет реальную частоту процессора *) function GetCPUSpeed: Double; (* Возвращает информацию о процессоре *) function GetProcessorInfo(CP_typeinfo: Byte; CP_NUM: Byte; Default: String): String; (* Возвращает информацию о мониторе *) function GetDisplaySettings(DS_typeinfo: Byte): Integer; (* Меняет настройки монитора. Указывается нужный режим *) function ChangeDisplayMode(ModeNum: Integer): Boolean; (* Определяет номер режим дисплея с указанными параметрами. Если AutoFind=True то можно указать только интересующие параметры, а остальные задать нулевыми (они не изменятся) *) function GetDisplayModeNum( BitsColor: Byte; // Разрядность пискелей (4,8,16,32) Dis_Width, Dis_Height: Word; // Ширина и высота Dis_Freq: Word; // Частота AutoFind: Boolean ): Integer; (* Определяет размер свободного места на диске *) function GetFreeDiskSize(Root: String): Real; (* Определяет общий размер диска *) function GetTotalDiskSize(Root: String): Real; (* Универсальная процедура по созданию ярлыка *) procedure CreateShotCut(SourceFile, ShortCutName, SourceParams: String); (* Создает ярлык в папке ПРОГРАММЫ меню ПУСК *) procedure CreateShotCut_InPrograms(RelationPath, FullExeName, SourceParams: String; Handle: THandle); (* Создает ярлык на рабочем столе *) procedure CreateShotCut_OnDesktop(FullExeName, SourceParams: String; Handle: THandle); (* Изменяет форму любого визуального компонента, имеющего св-во Handle в соответствии с указанным bmp-файлом *) function CreateRgnFromBitmap(Handle: THandle; BmpFileName: TFileName): HRGN; (* Запуск файла на выполнение *) function ExecuteFile (WND: HWND; const FileName, // Имя запускаемого файла (с возможным путем доступа) Params, // Передаваемые параметры DefaultDir: string;// Текущая директория для запускаемой программы ShowCmd: Integer // Способ отображения окна запущенного файла ): THandle; (* Определение IP-имени данного компьютера *) function GetIPName: String; (* Генерация ХЭШ-кода текста по алгоритму МД-5 *) function md5(s: string):string; (* Правка HEX-строки *) function StringToHex(HexStr: String): String; (* Исключение замыкающего Backslash (чтобы Делфи не ругался) *) function ExcludeTrailingBackslash(const S: string): string; end; var LDSf: TLDSfunc; implementation { TLDSfunc } function TLDSfunc.CreateDir(FullPath: String; DirAttrib: DWORD = 0): Boolean; var List: TStringList; I, J, K, C: Integer; begin K := 0; C := 0; Result := False; if not DirectoryExists(FullPath[1] + ':\') then Exit; if Length(FullPath)<4 then Exit; if not(((FullPath[1]>='A') and (FullPath[1]<='Z')) or ((FullPath[1]>='a') and (FullPath[1]<='z'))) then Exit; if (FullPath[2]<>':') or (FullPath[3]<>'\') then Exit; FullPath := ExcludeTrailingBackslash(FullPath) + '\'; for I := 5 to Length(FullPath) do if FullPath[I] = '\' then Inc(C); // Теперь С хранить возможное количество путей для создания // Создаем список путей List :=TStringList.Create; for I:=0 to C-1 do // Перебор возможных путей begin List.Append(''); for J:=1 to Length(FullPath) do // Формируем путь begin if (FullPath[J] = '\') and (J>4) and (J>K) then begin K := J; Break; end; List.Strings[I] := List.Strings[I]+ FullPath[J]; end; end; // Все пути сформированы //Теперь в цикле создаем директории for I := 0 to C-1 do if not DirectoryExists(List.Strings[I]) then try MkDir(List.Strings[I]); except MessageBox(GetActiveWindow,PChar('Невозможно создать директорию "'+ List.Strings[I]+'"'+#13#10+ 'Проверьте наличие устройства "'+AnsiUpperCase(FullPath[1])+':\"'), 'Ошибка ввода/вывода',MB_OK or MB_ICONSTOP or MB_TOPMOST); Exit; end; List.Free; // Освобождаем память из-под объекта // Устанавливаем атрибуты конечной папки SetFileAttributes(PChar(FullPath), DirAttrib); Result := True; end; function TLDSfunc.DirCopy(DirSour, DirDest: String; LogFileName: String; VisProc: TCopyFileProgress = nil): Boolean; var DirList, //Хранит список всех возможных каталогов TempList: TStringList; C, K: DWORD; S: String; I, Files, FileNum: Integer; tf: TextFile; tk: DWORD; CommSize, Tmp: Real; begin Result := False; if not DirectoryExists(DirSour) then DoError('Директория-источник не найдена'); if not DirectoryExists(DirDest[1]+':\') then DoError('Накопитель-приемник не найдена'); tk := GetTickCount; // Записываем в ЛОГ-файл информацию о начале сессии if LogFileName <> '' then begin if not FileExists(LogFileName) then begin AssignFile(tf, LogFileName); ReWrite(tf); CloseFile(tf); end; try AssignFile(tf, LogFileName); Append(tf); Writeln(tf,'' ); Writeln(tf,'' ); Writeln(tf,'**** НАЧАЛО СЕССИИ КОПИРОВАНИЯ: '+DateTimeToStr(Now)+' ****'); Writeln(tf,'' ); except DoError('Ошибка при создании файла отчета'); end; end; DirList := TStringList.Create; TempList := TStringList.Create; if DirSour[Length(DirSour)] <> '\' then DirSour := DirSour+'\'; if DirDest[Length(DirDest)] <> '\' then DirDest := DirDest+'\'; // Создаем корневой каталог-приемник if not CreateDir(DirDest,0) then begin if LogFileName <> '' then CloseFile(tf); DoError('Не смог создать приемную директорию'); end; C:= _GetDirList(DirSour,DirList); // Получаем первый список каталогов I:=0; If C > 0 then While true do begin TempList.Clear; _GetDirList(DirList.Strings[I],TempList); _MixLists(DirList,TempList); If I = DirList.Count-1 then Break; Inc(I); end; // While DirList.Sort; FileNum := 0; Files := 0; CommSize := 0; if DirList.Count > 0 then for I := 0 to DirList.Count-1 do begin Files := Files + _GetFilesInfo(DirList[I], Tmp); CommSize := CommSize + Tmp; end; Files := Files + _GetFilesInfo(DirSour, Tmp); CommSize := CommSize + Tmp; if CommSize > GetFreeDiskSize(DirDest[1]) then begin if LogFileName <> '' then CloseFile(tf); DoError('Не хватает дисковой памяти для копирования директории'); end; // Создаем каталоги из списка на получателе if DirList.Count>0 then for I := 0 to DirList.Count-1 do begin S := Copy(DirList.Strings[I], Length(DirSour)+1, Length(DirList.Strings[I])-Length(DirSour)+1); // Cоздает нужный каталог if not CreateDir(DirDest+S,GetFileAttributes(PChar(DirList.Strings[I]))) then begin if LogFileName <> '' then CloseFile(tf); DoError('Не смог создать приемную директорию'); end; end; // Копируем файлы if DirList.Count>0 then for I := 0 to DirList.Count-1 do begin TempList.Clear; C:= _GetFileList(DirList.Strings[I],TempList); if C>0 then for K:=0 to C-1 do begin S := Copy(DirList.Strings[I], Length(DirSour)+1, Length(DirList.Strings[I])-Length(DirSour)+1); if LogFileName <> '' then Write(tf,TimeToStr(Time)+' --Copy-- '+ DirList.Strings[I]+'\'+TempList.Strings[K]+' --> '+ DirDest+S+'\'+TempList.Strings[K]); Inc(FileNum); try if not FileCopy(DirList.Strings[I]+'\'+TempList.Strings[K], DirDest+S+'\'+TempList.Strings[K], VisProc, FileNum, Files) then begin if LogFileName <> '' then CloseFile(tf); Exit; end; except if MessageBox(GetActiveWindow,'Произошла ошибка при работе с файлами'+ #13#10+'Продолжить со следующего файла?', 'Предупреждение', MB_YESNO or MB_ICONEXCLAMATION) = IDNO then begin if LogFileName <> '' then CloseFile(tf); Exit; end; end; if LogFileName <> '' then WriteLn(tf,' --OK-- '); end; end; // Теперь делаем, чтобы копировались файлы из самой выбранной папки C:= _GetFileList(DirSour,TempList); if C > 0 then for I := 0 to C-1 do begin S := DirDest+TempList.Strings[I]; // Куда копируем if LogFileName <> '' then Write(tf,TimeToStr(Time)+' --Copy-- '+ DirSour+TempList.Strings[I]+' --> '+ S); Inc(FileNum); try if not FileCopy(DirSour+TempList.Strings[I],S, VisProc, FileNum, Files) then begin if LogFileName <> '' then CloseFile(tf); Exit; end; except if MessageBox(GetActiveWindow,'Произошла ошибка при работе с файлами'+ #13#10+'Продолжить со следующего файла?', 'Предупреждение', MB_YESNO or MB_ICONEXCLAMATION) = IDNO then begin if LogFileName <> '' then CloseFile(tf); Exit; end; end; if LogFileName <> '' then WriteLn(tf,' --OK-- '); end; DirList.Free; TempList.Free; if LogFileName <> '' then begin WriteLn(tf,''); WriteLn(tf,'**** Время сессии: '+TimeToStr((Gettickcount-tk)* StrToTime('00:00:01')/1000)+ ' ****'); WriteLn(tf,''); CloseFile(tf); end; Result := True; end; procedure TLDSfunc.DoError(Msg: String); begin raise Exception.Create(Msg); end; function TLDSfunc.ExcludeTrailingBackslash(const S: string): string; begin Result := ExcludeTrailingPathDelimiter(S); end; function TLDSfunc.FileCopy(Sour, Dest: String; VisProc: TCopyFileProgress = nil; FileNum: Integer = 1; Files: Integer = 1): Boolean; var ArrayRead: Array[1..8192] Of Byte; FP_Read,FP_Write : TFileStream; fSize, I: Integer; sfHandle: HFile; fTime, CurIter: Integer; PartTime, Speed: Real; Tc, Delta: Cardinal; begin Result := False; if not DirectoryExists(ExtractFileDir(Dest)) then DoError('Директории не существует'); if not FileExists(Sour) then DoError('Файл не найден'); if Dest = Sour then begin Result := True; Exit; end; if FileExists(Dest) then begin FileSetAttr(Dest, 0); // Сбрасываем все атрибуты, чтобы можно было удалить DeleteFile(Dest); end; try FP_Read := TFileStream.Create(Sour,fmOpenRead); fSize := FP_Read.Size; FP_Write := TFileStream.Create(Dest,fmCreate); except DoError('Невозможно получить доступ к файлу.'+ ' Возможно он используется другим приложением'); Exit; end; CurIter := 0; Tc := GetTickCount; while FP_Read.Position < FSize do begin Inc(CurIter); // код для обработки сообщений закончен I := FSize-FP_Read.Position; if I >= 8192 then begin FP_Read.Read(ArrayRead,8192); FP_Write.Write(ArrayRead,8192); end else begin FP_Read.Read(ArrayRead,I); FP_Write.Write(ArrayRead,I); end; // Через каждые пол секунды выполняем визуализацию if (@VisProc <> nil) and ((GetTickCount - Tc > 500) or (FP_Read.Position = fSize)) then begin Delta := GetTickCount - Tc; PartTime := Delta / 1000; if Delta < 50 then Speed := LastSpeed else Speed := CurIter * 8192 / PartTime; LastSpeed := Speed; Tc := GetTickCount; CurIter := 0; if VisProc(Sour, Dest, FP_Read.Position, fSize, Speed, FileNum, Files) = False then begin FP_Read.Free; FP_Write.Free; if FileExists(Dest) then DeleteFile(Dest); Exit; end; end; end; FP_Read.Free; FP_Write.Free; // Устанавливает атрибуты sfHandle:=_lopen(PChar(Sour), OF_READ); fTime:=FileGetDate(sfHandle); _lclose(sfHandle); FileSetDate(Dest,fTime); FileSetAttr(Dest, FileGetAttr(Sour)); Result := True; end; function TLDSfunc.FileGetAttr(const FileName: string): Integer; begin Result := GetFileAttributes(PChar(FileName)); end; function TLDSfunc.FileMove(Sour, Dest: String; VisProc: TCopyFileProgress = nil; FileNum: Integer = 1; Files: Integer = 1): Boolean; var FullDest: String; begin Result := True; FullDest:= ExpandFileName(Dest); if Sour = FullDest then Exit; if not DirectoryExists(FullDest[1]+':\') then DoError('Имя приемника задано неверно'); if not FileExists(Sour) then DoError('Исходный файл не был найден'); // Если диск один, то можно переименовать старый файл if not RenameFile(Sour, FullDest) then begin FileCopy(Sour, FullDest, VisProc, FileNum, Files); FileSetAttr(Sour,0); DeleteFile(Sour); end; end; function TLDSfunc.FileSetAttr(const FileName: string; Attr: Integer): Integer; begin Result := 0; if not SetFileAttributes(PChar(FileName), Attr) then Result := GetLastError; end; function TLDSfunc.FileSize(FileName: String): Integer; var F: HFile; // Для расчета размера begin Result := 0; if not FileExists(FileName) then Exit; F:=_lopen(PChar(FileName), OF_READ); Result :=_llseek(F,0, FILE_END); _lclose(F); end; function TLDSfunc._GetDirList(DirName: String; var List: TStringList): DWORD; var FS: TSearchRec; Path: String; begin if DirName[Length(DirName)]<>'\' then DirName := DirName+'\'; Path := DirName+'*.*'; List.Clear; List.Sort; if FindFirst(Path, faAnyFile, FS)=0 then begin if (DirectoryExists(DirName+FS.Name)) and ((FS.Name<>'.') and (FS.Name<>'..')) then List.Append(DirName+FS.Name); while FindNext(FS)=0 do begin if (DirectoryExists(DirName+FS.Name)) and ((FS.Name<>'.') and (FS.Name<>'..')) then List.Append(DirName+FS.Name); end; FindClose(FS); end; Result := List.Count; end; function TLDSfunc._GetFilesInfo(DirName: String; var CommonSize: Real): Integer; var FS: TSearchRec; Path: String; begin if DirName[Length(DirName)]<>'\' then DirName := DirName+'\'; Path := DirName+'*.*'; Result := 0; CommonSize := 0; if FindFirst(Path, $00000020, FS)=0 then begin Inc(Result); CommonSize := CommonSize + FS.Size; while FindNext(FS)=0 do begin CommonSize := CommonSize + FS.Size; Inc(Result); end; FindClose(FS); end; end; function TLDSfunc._GetFileList(DirName: String; var List: TStringList): DWORD; var FS: TSearchRec; Path: String; begin if DirName[Length(DirName)]<>'\' then DirName := DirName+'\'; Path := DirName+'*.*'; List.Clear; if FindFirst(Path, $00000020, FS)=0 then begin List.Append(FS.Name); while FindNext(FS)=0 do begin List.Append(FS.Name); end; FindClose(FS); end; Result := List.Count; end; function TLDSfunc._MixLists(var MasterList, DetailList: TStringList): DWORD; var D, C: DWORD; begin C :=DetailList.Count; if C<>0 then for D := 0 to C-1 do MasterList.Append(DetailList.Strings[D]); Result := MasterList.Count; end; function TLDSfunc.GetDiskInfo(DiskName: String; DI_typeinfo: Byte): String; var lpRootPathName: PChar; lpVolumeNameBuffer: PChar; nVolumeNameSize: DWORD; lpVolumeSerialNumber: DWORD; lpMaximumComponentLength: DWORD; lpFileSystemFlags: DWORD; lpFileSystemNameBuffer: PChar; nFileSystemNameSize: DWORD; FSectorsPerCluster: DWORD; FBytesPerSector : DWORD; FFreeClusters : DWORD; FTotalClusters : DWORD; begin DiskName := DiskName[1]; if not DirectoryExists(DiskName+':\') then begin Result := '0'; Exit; end; lpVolumeSerialNumber := 0; lpMaximumComponentLength:= 0; lpFileSystemFlags := 0; GetMem(lpVolumeNameBuffer, MAX_PATH + 1); GetMem(lpFileSystemNameBuffer, MAX_PATH + 1); nVolumeNameSize := MAX_PATH + 1; nFileSystemNameSize := MAX_PATH + 1; lpRootPathName := PChar(DiskName+':\'); if GetVolumeInformation( lpRootPathName, lpVolumeNameBuffer, nVolumeNameSize, @lpVolumeSerialNumber, lpMaximumComponentLength, lpFileSystemFlags, lpFileSystemNameBuffer, nFileSystemNameSize ) then begin GetDiskFreeSpace( PChar(DiskName+':\'), FSectorsPerCluster, FBytesPerSector, FFreeClusters, FTotalClusters); case DI_typeinfo of DI_SerNumber: Result:=IntToHex(HIWord(lpVolumeSerialNumber), 4) + '-' + IntToHex(LOWord(lpVolumeSerialNumber), 4); DI_TomLabel: Result := lpVolumeNameBuffer; DI_FileSystem:Result := lpFileSystemNameBuffer; DI_SectorsInClaster:Result := IntToStr(FSectorsPerCluster); DI_BytesInSector: Result := IntToStr(FBytesPerSector); DI_MaximumLength: Result := IntToStr(lpMaximumComponentLength); DI_DiskFreeSize: Result := FloatToStr(GetFreeDiskSize(DiskName)); DI_DiskSize: Result := FloatToStr(GetTotalDiskSize(DiskName)); DI_DiskUsageSize: Result := FloatToStr(GetTotalDiskSize(DiskName)- GetFreeDiskSize(DiskName)); DI_TotalClasters: Result := IntToStr(FTotalClusters); DI_FreeClasters: Result := IntToStr(FFreeClusters); end; // Case end; // If FreeMem(lpVolumeNameBuffer); FreeMem(lpFileSystemNameBuffer); end; function TLDSfunc.GetFreeDiskSize(Root: String): Real; begin Result := 0; if not DirectoryExists(Root[1]+':\') then Exit; Root := UpperCase(Root); Result := DiskFree(Ord(Root[1]) - 64 ); end; function TLDSfunc.GetTotalDiskSize(Root: String): Real; begin Result := 0; if not DirectoryExists(Root[1]+':\') then Exit; Root := UpperCase(Root); Result := DiskSize(Ord(Root[1]) - 64 ); end; function TLDSfunc.DirMove(DirSour, DirDest, LogFileName: String; VisProc: TCopyFileProgress): Boolean; begin Result := False; if not DirectoryExists(DirSour) then Exit; if not DirectoryExists(DirDest[1]+':\') then Exit; if DirSour = DirDest then begin Result := True; Exit; end; if not CreateDir(DirDest,0) then Exit; // Создаем полный путь if not RemoveDir(DirDest) then Exit; // Удаляем последний каталог // Если указан существующий каталог, то функция пытается переместить файлы // в него, однако если в нем уже есть к.-л. файлы, то работа функции // прерывается (возвращается False) // Если источник и приемник находятся на одном диске, // то попытаемся переименовать источник в приемник if not RenameFile(DirSour, DirDest) then begin DirCopy(DirSour, DirDest,LogFileName, VisProc); DirDelete(DirSour, LogFileName); end; Result:=True; end; function TLDSfunc.DirDelete(DirName: String; LogFileName: String = ''): Boolean; var tf: TextFile; tk: DWORD; DirList, //Хранит список всех возможных каталогов TempList: TStringList; C, K: DWORD; I: Integer; begin Result := True; if not DirectoryExists(DirName) then Exit; tk := GetTickCount; // Записываем в ЛОГ-файл информацию о начале сессии if LogFileName <> '' then begin if not FileExists(LogFileName) then begin AssignFile(tf, LogFileName); ReWrite(tf); CloseFile(tf); end; AssignFile(tf, LogFileName); Append(tf); Writeln(tf,'' ); Writeln(tf,'' ); Writeln(tf,'**** НАЧАЛО СЕССИИ УДАЛЕНИЯ: '+DateTimeToStr(Now)+' ****'); Writeln(tf,'' ); end; // if DirList := TStringList.Create; TempList := TStringList.Create; if DirName[Length(DirName)] <> '\' then DirName := DirName+'\'; C:= _GetDirList(DirName,DirList); // Получаем первый список каталогов I:=0; If C > 0 then While true do begin TempList.Clear; _GetDirList(DirList.Strings[I],TempList); _MixLists(DirList,TempList); If I=DirList.Count-1 then Break; Inc(I); end; // While // Теперь нам известны все пути для удаления DirList.Sort; DirList.Append(ExcludeTrailingBackslash(DirName)); // Добавляем корневой каталог в конец списка // Начинаем удаление файлов из всех каталогов if DirList.Count>0 then for I := 0 to DirList.Count - 1 do begin // Получаем список файлов для текущего каталога C := _GetFileList(DirList.Strings[I], TempList); if C > 0 then for K := 0 to C-1 do begin if LogFileName <> '' then Write(tf,TimeToStr(Time)+' --Delete-- '+ DirList.Strings[I]+'\'+TempList.Strings[K]); SetFileAttributes(PChar(DirList.Strings[I]+'\'+TempList.Strings[K]),0); if DeleteFile(PChar(DirList.Strings[I]+'\'+TempList.Strings[K])) then if LogFileName <> '' then WriteLn(tf,' --OK--') else WriteLn(tf,' --NO--'); end; end; // Теперь удаляем сами каталоги if DirList.Count >0 then for I := 0 to DirList.Count-1 do begin // Здесь возникает проблема из-за того, что удалять каталоги // нужно по порядку - от дочернего к родительскому _DelEmptyPath(DirList.Strings[I], DirName) ; end; if LogFileName <> '' then begin WriteLn(tf,''); WriteLn(tf,'**** Время сессии: '+TimeToStr((Gettickcount-tk)* StrToTime('00:00:01')/1000)+ ' ****'); WriteLn(tf,''); CloseFile(tf); end; if DirectoryExists(DirName) then Result := False else Result := True; DirList.Free; TempList.Free; end; function TLDSfunc._DelEmptyPath(DirName, LastDir: String): Boolean; var DirList, TempList: TStringList; I: DWORD; begin Result := False; if not DirectoryExists(DirName) then Exit; DirName:=ExcludeTrailingBackslash(DirName)+'\'; LastDir:=ExcludeTrailingBackslash(LastDir)+'\'; DirList:= TStringList.Create; TempList:= TStringList.Create; if Length(DirName)<5 then Exit; if Length(LastDir)>Length(DirName) then Exit; for I := Length(DirName) downto Length(LastDir)+1 do begin if DirName[I]='\' then DirList.Append(Copy(DirName,1,I-1)); end; // Добавляем последнюю директорию DirList.Append(ExcludeTrailingBackslash(LastDir)); if DirList.Count > 0 then for I := 0 to DirList.Count - 1 do if _GetDirList(DirList.Strings[I], TempList) = 0 then begin FileSetAttr(DirList.Strings[I],0); RemoveDir(DirList.Strings[I]); end; Result := True; DirList.Free; TempList.Free; end; function TLDSfunc.GetMemoryInfo(MEM_typeinfo: Byte): DWORD; var MemInfo : TMemoryStatus; begin Result := 0; MemInfo.dwLength := Sizeof (MemInfo); GlobalMemoryStatus (MemInfo); Case MEM_typeinfo of MEM_TotalPhys: Result := MemInfo.dwTotalPhys; MEM_AvailPhys : Result := MemInfo.dwAvailPhys; MEM_NotAvailPhys : Result := MemInfo.dwTotalPhys-MemInfo.dwAvailPhys; MEM_TotalPageFile: Result := MemInfo.dwTotalPageFile; MEM_AvailPageFile : Result := MemInfo.dwAvailPageFile; MEM_NotAvailPageFile : Result := MemInfo.dwTotalPageFile-MemInfo.dwAvailPageFile; MEM_TotalVirtual: Result := MemInfo.dwTotalVirtual; MEM_AvailVirtual: Result := MemInfo.dwAvailVirtual; MEM_NotAvailVirtual : Result := MemInfo.dwTotalVirtual-MemInfo.dwAvailVirtual; end; end; function TLDSfunc.GetDisplaySettings(DS_typeinfo: Byte): Integer; var DC: HDC; begin Result := 0; DC := GetDC(0); // Канва Десктопа всегда 0 Case DS_typeinfo of DS_BitsOnPixel : Result := GetDeviceCaps(DC, BITSPIXEL); DS_HorPixelSize : Result := GetDeviceCaps(DC, HORZRES); DS_VerPixelSize : Result := GetDeviceCaps(DC, VERTRES); DS_Frequency : Result := GetDeviceCaps(DC, VREFRESH); DS_HorMMSize : Result := GetDeviceCaps(DC, HORZSIZE); DS_VerMMSize : Result := GetDeviceCaps(DC, VERTSIZE); DS_PixelsOnInch_Hor:Result := GetDeviceCaps(DC, LOGPIXELSX); DS_PixelsOnInch_Ver:Result := GetDeviceCaps(DC, LOGPIXELSY); DS_ColorsInSysPalette:Result:= GetDeviceCaps(DC, SIZEPALETTE); end; end; function TLDSfunc.ChangeDisplayMode(ModeNum: Integer): Boolean; var Mode: TDevMode; begin Result := False; if EnumDisplaySettings(nil, ModeNum, Mode) then begin Mode.dmFields := DM_BITSPERPEL or DM_PELSWIDTH or DM_PELSHEIGHT or DM_DISPLAYFLAGS or DM_DISPLAYFREQUENCY; ChangeDisplaySettings(Mode, CDS_UPDATEREGISTRY); Result := True; end; end; function TLDSfunc.GetDisplayModeNum(BitsColor: Byte; Dis_Width, Dis_Height, Dis_Freq: Word; AutoFind: Boolean): Integer; var modes: array[0..255] of TDevMode; I: Integer; begin Result := -1; if not AutoFind then if (BitsColor=0)or (Dis_Width=0)or(Dis_Height=0) or (Dis_Freq=0) then Exit; if AutoFind then begin if BitsColor = 0 then BitsColor:=GetDisplaySettings(DS_BitsOnPixel); if Dis_Width = 0 then Dis_Width:=GetDisplaySettings(DS_HorPixelSize); if Dis_Height = 0 then Dis_Height:=GetDisplaySettings(DS_VerPixelSize); end; I:=0; while EnumDisplaySettings(nil, I, Modes[I]) do begin if (BitsColor=modes[I].dmBitsPerPel) AND (Dis_Width=modes[I].dmPelsWidth) AND (Dis_Height=modes[I].dmPelsHeight) then if (AutoFind AND (Dis_Freq = 0)) or (Dis_Freq=modes[I].dmDisplayFrequency) then Result := I; Inc(I); end; end; function TLDSfunc.md5(s: string): string; var a:array[0..15] of byte; i:integer; LenHi, LenLo: longword; Index: DWord; HashBuffer: array[0..63] of byte; CurrentHash: array[0..3] of DWord; procedure Burn; begin LenHi:= 0; LenLo:= 0; Index:= 0; FillChar(HashBuffer,Sizeof(HashBuffer),0); FillChar(CurrentHash,Sizeof(CurrentHash),0); end; procedure Init; begin Burn; CurrentHash[0]:= $67452301; CurrentHash[1]:= $efcdab89; CurrentHash[2]:= $98badcfe; CurrentHash[3]:= $10325476; end; function LRot32(a, b: longword): longword; begin Result:= (a shl b) or (a shr (32-b)); end; procedure Compress; var Data: array[0..15] of dword; A, B, C, D: dword; begin Move(HashBuffer,Data,Sizeof(Data)); A:= CurrentHash[0]; B:= CurrentHash[1]; C:= CurrentHash[2]; D:= CurrentHash[3]; A:= B + LRot32(A + (D xor (B and (C xor D))) + Data[ 0] + $d76aa478,7); D:= A + LRot32(D + (C xor (A and (B xor C))) + Data[ 1] + $e8c7b756,12); C:= D + LRot32(C + (B xor (D and (A xor B))) + Data[ 2] + $242070db,17); B:= C + LRot32(B + (A xor (C and (D xor A))) + Data[ 3] + $c1bdceee,22); A:= B + LRot32(A + (D xor (B and (C xor D))) + Data[ 4] + $f57c0faf,7); D:= A + LRot32(D + (C xor (A and (B xor C))) + Data[ 5] + $4787c62a,12); C:= D + LRot32(C + (B xor (D and (A xor B))) + Data[ 6] + $a8304613,17); B:= C + LRot32(B + (A xor (C and (D xor A))) + Data[ 7] + $fd469501,22); A:= B + LRot32(A + (D xor (B and (C xor D))) + Data[ 8] + $698098d8,7); D:= A + LRot32(D + (C xor (A and (B xor C))) + Data[ 9] + $8b44f7af,12); C:= D + LRot32(C + (B xor (D and (A xor B))) + Data[10] + $ffff5bb1,17); B:= C + LRot32(B + (A xor (C and (D xor A))) + Data[11] + $895cd7be,22); A:= B + LRot32(A + (D xor (B and (C xor D))) + Data[12] + $6b901122,7); D:= A + LRot32(D + (C xor (A and (B xor C))) + Data[13] + $fd987193,12); C:= D + LRot32(C + (B xor (D and (A xor B))) + Data[14] + $a679438e,17); B:= C + LRot32(B + (A xor (C and (D xor A))) + Data[15] + $49b40821,22); A:= B + LRot32(A + (C xor (D and (B xor C))) + Data[ 1] + $f61e2562,5); D:= A + LRot32(D + (B xor (C and (A xor B))) + Data[ 6] + $c040b340,9); C:= D + LRot32(C + (A xor (B and (D xor A))) + Data[11] + $265e5a51,14); B:= C + LRot32(B + (D xor (A and (C xor D))) + Data[ 0] + $e9b6c7aa,20); A:= B + LRot32(A + (C xor (D and (B xor C))) + Data[ 5] + $d62f105d,5); D:= A + LRot32(D + (B xor (C and (A xor B))) + Data[10] + $02441453,9); C:= D + LRot32(C + (A xor (B and (D xor A))) + Data[15] + $d8a1e681,14); B:= C + LRot32(B + (D xor (A and (C xor D))) + Data[ 4] + $e7d3fbc8,20); A:= B + LRot32(A + (C xor (D and (B xor C))) + Data[ 9] + $21e1cde6,5); D:= A + LRot32(D + (B xor (C and (A xor B))) + Data[14] + $c33707d6,9); C:= D + LRot32(C + (A xor (B and (D xor A))) + Data[ 3] + $f4d50d87,14); B:= C + LRot32(B + (D xor (A and (C xor D))) + Data[ 8] + $455a14ed,20); A:= B + LRot32(A + (C xor (D and (B xor C))) + Data[13] + $a9e3e905,5); D:= A + LRot32(D + (B xor (C and (A xor B))) + Data[ 2] + $fcefa3f8,9); C:= D + LRot32(C + (A xor (B and (D xor A))) + Data[ 7] + $676f02d9,14); B:= C + LRot32(B + (D xor (A and (C xor D))) + Data[12] + $8d2a4c8a,20); A:= B + LRot32(A + (B xor C xor D) + Data[ 5] + $fffa3942,4); D:= A + LRot32(D + (A xor B xor C) + Data[ 8] + $8771f681,11); C:= D + LRot32(C + (D xor A xor B) + Data[11] + $6d9d6122,16); B:= C + LRot32(B + (C xor D xor A) + Data[14] + $fde5380c,23); A:= B + LRot32(A + (B xor C xor D) + Data[ 1] + $a4beea44,4); D:= A + LRot32(D + (A xor B xor C) + Data[ 4] + $4bdecfa9,11); C:= D + LRot32(C + (D xor A xor B) + Data[ 7] + $f6bb4b60,16); B:= C + LRot32(B + (C xor D xor A) + Data[10] + $bebfbc70,23); A:= B + LRot32(A + (B xor C xor D) + Data[13] + $289b7ec6,4); D:= A + LRot32(D + (A xor B xor C) + Data[ 0] + $eaa127fa,11); C:= D + LRot32(C + (D xor A xor B) + Data[ 3] + $d4ef3085,16); B:= C + LRot32(B + (C xor D xor A) + Data[ 6] + $04881d05,23); A:= B + LRot32(A + (B xor C xor D) + Data[ 9] + $d9d4d039,4); D:= A + LRot32(D + (A xor B xor C) + Data[12] + $e6db99e5,11); C:= D + LRot32(C + (D xor A xor B) + Data[15] + $1fa27cf8,16); B:= C + LRot32(B + (C xor D xor A) + Data[ 2] + $c4ac5665,23); A:= B + LRot32(A + (C xor (B or (not D))) + Data[ 0] + $f4292244,6); D:= A + LRot32(D + (B xor (A or (not C))) + Data[ 7] + $432aff97,10); C:= D + LRot32(C + (A xor (D or (not B))) + Data[14] + $ab9423a7,15); B:= C + LRot32(B + (D xor (C or (not A))) + Data[ 5] + $fc93a039,21); A:= B + LRot32(A + (C xor (B or (not D))) + Data[12] + $655b59c3,6); D:= A + LRot32(D + (B xor (A or (not C))) + Data[ 3] + $8f0ccc92,10); C:= D + LRot32(C + (A xor (D or (not B))) + Data[10] + $ffeff47d,15); B:= C + LRot32(B + (D xor (C or (not A))) + Data[ 1] + $85845dd1,21); A:= B + LRot32(A + (C xor (B or (not D))) + Data[ 8] + $6fa87e4f,6); D:= A + LRot32(D + (B xor (A or (not C))) + Data[15] + $fe2ce6e0,10); C:= D + LRot32(C + (A xor (D or (not B))) + Data[ 6] + $a3014314,15); B:= C + LRot32(B + (D xor (C or (not A))) + Data[13] + $4e0811a1,21); A:= B + LRot32(A + (C xor (B or (not D))) + Data[ 4] + $f7537e82,6); D:= A + LRot32(D + (B xor (A or (not C))) + Data[11] + $bd3af235,10); C:= D + LRot32(C + (A xor (D or (not B))) + Data[ 2] + $2ad7d2bb,15); B:= C + LRot32(B + (D xor (C or (not A))) + Data[ 9] + $eb86d391,21); Inc(CurrentHash[0],A); Inc(CurrentHash[1],B); Inc(CurrentHash[2],C); Inc(CurrentHash[3],D); Index:= 0; FillChar(HashBuffer,Sizeof(HashBuffer),0); end; procedure Update(const Buffer; Size: longword); var PBuf: ^byte; begin Inc(LenHi,Size shr 29); Inc(LenLo,Size*8); if LenLo< (Size*8) then Inc(LenHi); PBuf:= @Buffer; while Size> 0 do begin if (Sizeof(HashBuffer)-Index)<= DWord(Size) then begin Move(PBuf^,HashBuffer[Index],Sizeof(HashBuffer)-Index); Dec(Size,Sizeof(HashBuffer)-Index); Inc(PBuf,Sizeof(HashBuffer)-Index); Compress; end else begin Move(PBuf^,HashBuffer[Index],Size); Inc(Index,Size); Size:= 0; end; end; end; procedure Final(var Digest); begin HashBuffer[Index]:= $80; if Index>= 56 then Compress; PDWord(@HashBuffer[56])^:= LenLo; PDWord(@HashBuffer[60])^:= LenHi; Compress; Move(CurrentHash,Digest,Sizeof(CurrentHash)); Burn; end; begin Init; Update(s[1],Length(s)); Final(a); result:=''; for i:=0 to 15 do result:=result+IntToHex(a[i],2); Burn; end; procedure TLDSfunc.CreateShotCut(SourceFile, ShortCutName, SourceParams: String); var IUnk: IUnknown; ShellLink: IShellLink; ShellFile: IPersistFile; tmpShortCutName: string; WideStr: WideString; i: Integer; begin IUnk := CreateComObject(CLSID_ShellLink); ShellLink := IUnk as IShellLink; ShellFile := IUnk as IPersistFile; ShellLink.SetPath(PChar(SourceFile)); ShellLink.SetArguments(PChar(SourceParams)); ShellLink.SetWorkingDirectory(PChar(ExtractFilePath(SourceFile))); ShortCutName := ChangeFileExt(ShortCutName,'.lnk'); if fileexists(ShortCutName) then begin ShortCutName := copy(ShortCutName,1,length(ShortCutName)-4); i := 1; repeat tmpShortCutName := ShortCutName +'(' + inttostr(i)+ ').lnk'; inc(i); until not fileexists(tmpShortCutName); WideStr := tmpShortCutName; end else WideStr := ShortCutName; ShellFile.Save(PWChar(WideStr),False); end; procedure TLDSfunc.CreateShotCut_InPrograms(RelationPath, FullExeName, SourceParams: String; Handle: THandle); var WorkTable, LinkName:String; P:PItemIDList; C:array [0..1000] of char; begin if SHGetSpecialFolderLocation(Handle,CSIDL_PROGRAMS,p)=NOERROR then begin SHGetPathFromIDList(P,C); WorkTable:=StrPas(C)+'\'+RelationPath; end; if not DirectoryExists(WorkTable) then CreateDir(WorkTable,0); LinkName := ExtractFileName(FullExeName); LinkName := Copy(LinkName, 1, Length(LinkName)-Length(ExtractFileExt(LinkName))); LinkName := LinkName+'.lnk'; if FileExists(WorkTable+'\'+ExtractFileName(LinkName)) then DeleteFile(WorkTable+'\'+ExtractFileName(LinkName)); CreateShotCut(FullExeName, WorkTable+'\'+ExtractFileName(FullExeName), SourceParams); end; procedure TLDSfunc.CreateShotCut_OnDesktop(FullExeName, SourceParams: String; Handle: THandle); var WorkTable, LinkName:String; P:PItemIDList; C:array [0..1000] of char; begin if SHGetSpecialFolderLocation(Handle,CSIDL_DESKTOP,p)=NOERROR then begin SHGetPathFromIDList(P,C); WorkTable:=StrPas(C); end; LinkName := ExtractFileName(FullExeName); LinkName := Copy(LinkName, 1, Length(LinkName)-Length(ExtractFileExt(LinkName))); LinkName := LinkName+'.lnk'; if FileExists(WorkTable+'\'+ExtractFileName(LinkName)) then DeleteFile(WorkTable+'\'+ExtractFileName(LinkName)); CreateShotCut(FullExeName, WorkTable+'\'+ExtractFileName(FullExeName), SourceParams); end; function TLDSfunc.ExecuteFile(WND: HWND; const FileName, Params, DefaultDir: string; ShowCmd: Integer): THandle; var zFileName, zParams, zDir: array[0..79] of Char; begin Result := ShellExecute(WND,nil, StrPCopy(zFileName, FileName),StrPCopy(zParams, Params), StrPCopy(zDir, DefaultDir), ShowCmd); end; function TLDSfunc.CreateRgnFromBitmap(Handle: THandle; BmpFileName: TFileName): HRGN; var TransColor: TColor; i, j: Integer; i_width, i_height: Integer; i_left, i_right: Integer; rectRgn: HRGN; rgnBitmap: TBitmap; begin Result := 0; rgnBitmap:=TBitmap.Create; rgnBitmap.LoadFromFile(BmpFileName); i_width := rgnBitmap.Width; i_height := rgnBitmap.Height; transColor := rgnBitmap.Canvas.Pixels[0, 0]; for i := 0 to i_height - 1 do begin i_left := -1; for j := 0 to i_width - 1 do begin if i_left < 0 then begin if rgnBitmap.Canvas.Pixels[j, i] <> transColor then i_left := j; end else if rgnBitmap.Canvas.Pixels[j, i] = transColor then begin i_right := j; rectRgn := CreateRectRgn(i_left, i, i_right, i + 1); if Result = 0 then Result := rectRgn else begin CombineRgn(Result, Result, rectRgn, RGN_OR); DeleteObject(rectRgn); end; i_left := -1; end; end; if i_left >= 0 then begin rectRgn := CreateRectRgn(i_left, i, i_width, i + 1); if Result = 0 then Result := rectRgn else begin CombineRgn(Result, Result, rectRgn, RGN_OR); DeleteObject(rectRgn); end; end; end; rgnBitmap.Free; SetWindowRgn(Handle, Result, True); end; function TLDSfunc.GetOSInfo(OS_typeinfo: Byte; Default: String): String; var OSVersion: TOSVersionInfo; RegFile: TRegIniFile; begin Result := Default; RegFile:=TRegIniFile.Create('Software'); OSVersion.dwOSVersionInfoSize:=SIZEOF(OSVersion); if GetVersionEx(OSVersion) then begin if OS_typeinfo=OS_Version then // Получаем версию Result:= Format('%d.%d (%d.%s)',[OSVersion.dwMajorVersion, OSVersion.dwMinorVersion,(OSVersion.dwBuildNumber and $FFFF), OSVersion.szCSDVersion]); if OS_typeinfo=OS_Platform then // Получаем название платформы case OSVersion.dwPlatformID of VER_PLATFORM_WIN32s: Result := 'Windows 3.1'; VER_PLATFORM_WIN32_WINDOWS: Result := 'Windows 95';{для 98-го то-же самое} VER_PLATFORM_WIN32_NT: Result := 'Windows NT'; else Result := ''; end; end; RegFile.RootKey := HKEY_LOCAL_MACHINE; RegFile.OpenKey('SOFTWARE', false); RegFile.OpenKey('Microsoft', false); RegFile.OpenKey('Windows', false); case OS_typeinfo of OS_Name: Result:= RegFile.ReadString('CurrentVersion','ProductName',Default); OS_Organization: Result:= RegFile.ReadString('CurrentVersion', 'RegisteredOrganization',Default); OS_Owner: Result:=RegFile.ReadString('CurrentVersion','RegisteredOwner',Default); OS_SerNumber: Result :=RegFile.ReadString('CurrentVersion','ProductId',Default); OS_WinPath: Result:=GetSystemPath(0, PATH_WINDOWS); OS_SysPath: Result:=GetSystemPath(0, PATH_SYSTEM); OS_TempPath: Result:=GetSystemPath(0, PATH_TEMP); OS_ProgramFilesPath: Result:=GetSystemPath(0, PATH_PROGRAMFILES); OS_IPName: Result := GetIPName; end; RegFile.CloseKey; RegFile.Free; end; function TLDSfunc.GetSystemPath(Handle: THandle; PATH_type: WORD): String; var P:PItemIDList; C:array [0..1000] of char; PathArray:array [0..255] of char; begin if PATH_type = PATH_TEMP then begin FillChar(PathArray,SizeOf(PathArray),0); ExpandEnvironmentStrings('%TEMP%', PathArray, 255); Result := Format('%s',[PathArray])+'\'; Exit; end; if PATH_type = PATH_WINDOWS then begin FillChar(PathArray,SizeOf(PathArray),0); GetWindowsDirectory(PathArray,255); Result := Format('%s',[PathArray])+'\'; Exit; end; if PATH_type = PATH_SYSTEM then begin FillChar(PathArray,SizeOf(PathArray),0); GetSystemDirectory(PathArray,255); Result := Format('%s',[PathArray])+'\'; Exit; end; if (PATH_type = PATH_PROGRAMFILES) or(PATH_type = PATH_COMMONFILES) then begin FillChar(PathArray,SizeOf(PathArray),0); ExpandEnvironmentStrings('%ProgramFiles%', PathArray, 255); Result := Format('%s',[PathArray])+'\'; if Result[1] = '%' then begin FillChar(PathArray,SizeOf(PathArray),0); GetSystemDirectory(PathArray,255); Result := Format('%s',[PathArray]); Result := Result[1]+':\Program Files\'; end; if (PATH_type = PATH_COMMONFILES) then Result := Result+'Common Files\'; Exit; end; if SHGetSpecialFolderLocation(Handle,PATH_type,p)=NOERROR then begin SHGetPathFromIDList(P,C); if StrPas(C)<>'' then Result := StrPas(C)+'\' else Result:=''; end; end; function TLDSfunc.FindHexStringInFile(FileName, HexString: String; StartByte: DWORD; TypeFind: Byte; Func: TFindProgress = nil): DWORD; var FS: TFileStream; PosInFile: DWORD; BufferArray: Array[1..8192] of Byte; InputArray: Array[1..1000] of Byte; InputArrayAdd: Array[1..1000] of Byte; ReadSize: WORD; InputArrayLength: WORD; fSize, CurByte, I: DWORD; ToEnd: DWORD; StartByteToRead: DWORD; C: WORD; S1,S2: String; begin // Если TypeFind = 1, то будет HEX-последовательность // Если TypeFind = 2, то будет искать текст по точному совпадению // Если TypeFind = 3, то будет искать текст без учета регистра Result := $FFFFFFFF; // Такой будет результат в случае неудачи InputArrayLength := 0; if (FileName = '') or (TypeFind < 1) or (TypeFind > 3) then Exit; if not FileExists(FileName) then Exit; // Если ищем HEX-последовательность if TypeFind = 1 then begin HexString := StringToHex(HexString); if Length(HexString) mod 2 <> 0 then Delete(HexString,Length(HexString),1); if HexString='' then Exit; InputArrayLength := Length(HexString) div 2; for I := 1 to InputArrayLength do InputArray[I]:=StrToInt('$'+Copy(HexString, I * 2 - 1, 2)); end; // Если ищем текст с учетом регистра if (TypeFind = 2) then begin if HexString='' then Exit; InputArrayLength:=Length(HexString); for I:=1 to InputArrayLength do InputArray[I] := Ord(HexString[I]); end; // Если ищем текст без учета регистра if (TypeFind = 3) then begin if HexString='' then Exit; InputArrayLength:=Length(HexString); for I:=1 to InputArrayLength do begin S1 := AnsiUpperCase(HexString[I]); S2 := AnsiLowerCase(HexString[I]); InputArray[I] := Ord(S1[1]); InputArrayAdd[I] := Ord(S2[1]); end; end; // Мы перевели входящие данные в массив данных, что облегчит дальнейшую // обработку fSize:=FileSize(FileName); if fSize=0 then Exit; PosInFile := StartByte; C:=0; // Открывает указанный файл для чтения FS := TFileStream.Create(FileName, fmOpenRead,fmShareDenyWrite); FS.Seek(StartByte, soFromBeginning); while FS.Position < fSize do begin if (FS.Position - InputArrayLength > PosInFile) then begin StartByteToRead := FS.Position - InputArrayLength; FS.Seek(StartByteToRead, soFromBeginning); end; ToEnd := fSize-FS.Position; if ToEnd >= 8192 then ReadSize := 8192 else ReadSize := ToEnd; PosInFile := FS.Position; FS.Read(BufferArray, ReadSize); Inc(C); if C > 100 then begin C := 0; if @Func <> nil then if not Func(FS.Position, FS.Size) then Break; end; CurByte := 0; if TypeFind in [1, 2] then while CurByte < ReadSize do begin Inc(CurByte); if (BufferArray[CurByte] = InputArray[1]) then begin if InputArrayLength = 1 then begin Result := FS.Position - (ReadSize - CurByte) - 1; FS.Free; Exit; end; for I := 2 to InputArrayLength do begin if BufferArray[CurByte + I - 1] <> InputArray[I] then Break; if I=InputArrayLength then begin Result := FS.Position - (ReadSize - CurByte) - 1; FS.Free; Exit; end; end; end; end; if TypeFind = 3 then while CurByte < ReadSize do begin Inc(CurByte); if (BufferArray[CurByte] = InputArray[1]) or (BufferArray[CurByte] = InputArrayAdd[1]) then begin if InputArrayLength = 1 then begin Result := FS.Position-(ReadSize-CurByte)-1; FS.Free; Exit; end; for I := 2 to InputArrayLength do begin if (BufferArray[CurByte+I-1]<>InputArray[I]) and (BufferArray[CurByte+I-1]<>InputArrayAdd[I]) then Break; if I=InputArrayLength then begin Result := FS.Position - (ReadSize - CurByte) - 1; FS.Free; Exit; end; end; end; end; end; FS.Free; end; function TLDSfunc.StringToHex(HexStr: String): String; var I: WORD; HexSet: Set of '0'..'f' ; begin HexSet := ['0'..'9','a'..'f','A'..'F']; if HexStr = '' then Exit; // Отфильтровываем все знаки, оставляем только 16-ричные знаки for I:=1 to Length(HexStr) do if HexStr[I] in HexSet then Result := Result + HexStr[I]; end; function TLDSfunc.GetProcessorInfo(CP_typeinfo, CP_NUM: Byte; Default: String): String; var RegFile: TRegIniFile; begin Result := Default; if CP_typeinfo = CP_SPEED then begin Result := IntToStr(Round(GetCPUSpeed)); Exit; end; RegFile:=TRegIniFile.Create('Software'); RegFile.RootKey := HKEY_LOCAL_MACHINE; RegFile.OpenKey('hardware', false); RegFile.OpenKey('DESCRIPTION', false); RegFile.OpenKey('System', false); RegFile.OpenKey('CentralProcessor', false); case CP_typeinfo of CP_Identifier :Result := RegFile.ReadString(IntToStr(CP_NUM), 'Identifier', Default); CP_NameString :Result := RegFile.ReadString(IntToStr(CP_NUM), 'ProcessorNameString', Default); CP_VendorIdentifier :Result := RegFile.ReadString(IntToStr(CP_NUM), 'VendorIdentifier', Default); CP_MMXIdentifier :Result := RegFile.ReadString(IntToStr(CP_NUM), 'MMXIdentifier', Default); else Exit; end; RegFile.CloseKey; RegFile.Free; end; function TLDSfunc.GetCPUSpeed: Double; const DelayTime = 500; var TimerHi, TimerLo: DWORD; PriorityClass, Priority: Integer; begin PriorityClass := GetPriorityClass(GetCurrentProcess); Priority := GetThreadPriority(GetCurrentThread); SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL); Sleep(10); asm dw 310Fh mov TimerLo, eax mov TimerHi, edx end; Sleep(DelayTime); asm dw 310Fh sub eax, TimerLo sbb edx, TimerHi mov TimerLo, eax mov TimerHi, edx end; SetThreadPriority(GetCurrentThread, Priority); SetPriorityClass(GetCurrentProcess, PriorityClass); Result := TimerLo / (1000.0 * DelayTime); end; function TLDSfunc.GetIPName: String; var szHostName: array [0..255] of Char; wsdata : TWSAData; begin WSAStartup ($0101, wsdata); gethostname(szHostName, sizeof(szHostName)); Result := szHostName; WSACleanup; end; initialization LDSf := TLDSfunc.Create; finalization LDSf.Free; end.
unit SplashFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TSplashForm = class(TForm) Panel1: TPanel; Label1: TLabel; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; procedure ShowSplashForm(AOwner: TForm); procedure HideSplashForm; implementation {$R *.dfm} var GlobalSplashForm: TSplashForm; procedure ShowSplashForm(AOwner: TForm); begin GlobalSplashForm := TSplashForm.Create(AOwner); GlobalSplashForm.Show; GlobalSplashForm.Refresh; end; procedure HideSplashForm; begin FreeAndNil(GlobalSplashForm); end; procedure TSplashForm.FormCreate(Sender: TObject); begin BorderStyle := bsNone; // Форма без рамки Position := poOwnerFormCenter; // Форма отобразиться в середине формы-владельца FormStyle := fsStayOnTop; end; end.
unit uSendEmail; interface uses {$IF CompilerVersion > 22} Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, {$ELSE} Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, {$IFEND} CNClrLib.Control.EnumTypes, CNClrLib.Control.Base, CNClrLib.Component.OpenFileDialog, CNClrLib.Component.SmtpClient; type TfrmSendEmail = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; GroupBox1: TGroupBox; Label6: TLabel; Label7: TLabel; Label8: TLabel; btnSendEmail: TButton; txtFrom: TEdit; txtTo: TEdit; txtSubject: TEdit; rtxtMailBody: TRichEdit; txtAttachment: TEdit; btnBrowse: TButton; txtHost: TEdit; txtUser: TEdit; txtPassword: TEdit; CnOpenFileDialog1: TCnOpenFileDialog; CnSmtpClient1: TCnSmtpClient; txtPort: TEdit; Label9: TLabel; chkEnableSSL: TCheckBox; procedure btnBrowseClick(Sender: TObject); procedure btnSendEmailClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmSendEmail: TfrmSendEmail; implementation {$R *.dfm} procedure TfrmSendEmail.btnBrowseClick(Sender: TObject); begin CnOpenFileDialog1.FileName := txtAttachment.Text; if CnOpenFileDialog1.ShowDialog = TDialogResult.drOK then txtAttachment.Text := CnOpenFileDialog1.FileName; end; procedure TfrmSendEmail.btnSendEmailClick(Sender: TObject); var mmessage: _MailMessage; begin try // Init the smtp client and setting the network credentials CnSmtpClient1.Host := txtHost.Text; CnSmtpClient1.Port := StrToIntDef(txtPort.Text, 0); CnSmtpClient1.UserName := txtUser.Text; CnSmtpClient1.Password := txtPassword.Text; CnSmtpClient1.EnableSsl := chkEnableSSL.Checked; // Create MailMessage mmessage := TMailMessageActivator.CreateInstance(txtFrom.Text, txtTo.Text); mmessage.Subject := txtSubject.Text; mmessage.Body := rtxtMailBody.Text; if FileExists(txtAttachment.Text) then begin mmessage.Attachments.Add(TAttachmentActivator.CreateInstance(txtAttachment.Text)); end; CnSmtpClient1.Send(mmessage); TClrMessageBox.Show('The email is sent.', Caption, TMessageBoxButtons.mbbsOK, TMessageBoxIcon.mbiInformation); except on E: Exception do begin TClrMessageBox.Show(E.Message, Caption, TMessageBoxButtons.mbbsOK, TMessageBoxIcon.mbiError); end; end; end; end.
unit uDistribuidor; interface uses uCidade; type TDistribuidor = class private codigo: Integer; ativo: char; razaoSocial: String; fantasia: String; endereco: String; numero: String; bairro: String; complemento: String; telefone: String; cnpjcpf: String; ierg: String; email: String; tipo: char; cidade: TCidade; public // contrutor da classe constructor TDistribuidorCreate; // destrutor da classe destructor TDistribuidorDestroy; // metodo "procedimento" set do Objeto procedure setCodigo(param: Integer); procedure setAtivo(param: char); procedure setRazaoSocial(param: String); procedure setFantasia(param: String); procedure setEndereco(param: String); procedure setNumero(param: String); procedure setBairro(param: String); procedure setComplemento(param: String); procedure setTelefone(param: String); procedure setCnpjCpf(param: String); procedure setIeRg(param: String); procedure setEmail(param: String); procedure setTipo(param: char); procedure setCidade(param: TCidade); // metodo "funcoes" get do Objeto function getCodigo: Integer; function getAtivo: char; function getRazaoSocial: String; function getFantasia: String; function getEndereco: String; function getNumero: String; function getBairro: String; function getComplemento: String; function getTelefone: String; function getCnpjCpf: String; function getIeRg: String; function getEmail: String; function getTipo: char; function getCidade: TCidade; end; var distribuidor :TDistribuidor; implementation { TDistribuidor implemenetacao dos metodos Get e sey } function TDistribuidor.getAtivo: char; begin Result := ativo; end; function TDistribuidor.getBairro: String; begin Result := bairro; end; function TDistribuidor.getCidade: TCidade; begin Result := cidade; end; function TDistribuidor.getCnpjCpf: String; begin Result := cnpjcpf; end; function TDistribuidor.getCodigo: Integer; begin Result := codigo; end; function TDistribuidor.getComplemento: String; begin Result := complemento; end; function TDistribuidor.getEmail: String; begin Result := email; end; function TDistribuidor.getEndereco: String; begin Result := endereco; end; function TDistribuidor.getFantasia: String; begin Result := fantasia; end; function TDistribuidor.getIeRg: String; begin Result := ierg; end; function TDistribuidor.getNumero: String; begin Result := numero; end; function TDistribuidor.getRazaoSocial: String; begin Result := razaoSocial; end; function TDistribuidor.getTelefone: String; begin Result := telefone; end; function TDistribuidor.getTipo: char; begin Result := tipo; end; procedure TDistribuidor.setAtivo(param: char); begin ativo := param; end; procedure TDistribuidor.setBairro(param: String); begin bairro := param; end; procedure TDistribuidor.setCidade(param: TCidade); begin cidade := param; end; procedure TDistribuidor.setCnpjCpf(param: String); begin cnpjcpf := param; end; procedure TDistribuidor.setCodigo(param: Integer); begin codigo := param; end; procedure TDistribuidor.setComplemento(param: String); begin complemento := param; end; procedure TDistribuidor.setEmail(param: String); begin email := param; end; procedure TDistribuidor.setEndereco(param: String); begin endereco := param; end; procedure TDistribuidor.setFantasia(param: String); begin fantasia := param; end; procedure TDistribuidor.setIeRg(param: String); begin ierg := param; end; procedure TDistribuidor.setNumero(param: String); begin numero := param; end; procedure TDistribuidor.setRazaoSocial(param: String); begin razaoSocial := param; end; procedure TDistribuidor.setTelefone(param: String); begin telefone := param; end; procedure TDistribuidor.setTipo(param: char); begin tipo := param; end; constructor TDistribuidor.TDistribuidorCreate; begin codigo := 0; ativo := 'S'; razaoSocial := ''; fantasia := ''; endereco := ''; numero := ''; bairro := ''; complemento := ''; telefone := ''; cnpjcpf := ''; ierg := ''; email := ''; tipo := 'F'; cidade.TCidadeCreate; end; destructor TDistribuidor.TDistribuidorDestroy; begin cidade.TCidadeDestroy; FreeInstance; end; end.
unit BCEditor.Print; interface uses Windows, SysUtils, Classes, Graphics, Printers, BCEditor.Editor.Base, BCEditor.Types, BCEditor.Print.Types, BCEditor.Print.HeaderFooter, BCEditor.Print.PrinterInfo, BCEditor.Print.Margins, BCEditor.Utils, BCEditor.Highlighter, BCEditor.Editor.Selection, BCEditor.TextDrawer; type TBCEditorPageLine = class public FirstLine: Integer; end; TBCEditorPrint = class(TComponent) strict private FAbort: Boolean; FBlockBeginPosition: TBCEditorTextPosition; FBlockEndPosition: TBCEditorTextPosition; FCanvas: TCanvas; FCharWidth: Integer; FColors: Boolean; FCopies: Integer; FDefaultBackground: TColor; FDocumentTitle: string; FEditor: TBCBaseEditor; FFont: TFont; FFontDummy: TFont; FFontColor: TColor; FFooter: TBCEditorPrintFooter; FHeader: TBCEditorPrintHeader; FHighlight: Boolean; FHighlighter: TBCEditorHighlighter; FHighlighterRangesSet: Boolean; FLineHeight: Integer; FLineNumber: Integer; FLineNumbers: Boolean; FLineNumbersInMargin: Boolean; FLineOffset: Integer; FLines: TStrings; FMargins: TBCEditorPrintMargins; FMaxCol: Integer; FMaxLeftChar: Integer; FMaxWidth: Integer; FOldFont: TFont; FOnPrintLine: TBCEditorPrintLineEvent; FOnPrintStatus: TBCEditorPrintStatusEvent; FPageCount: Integer; FPageOffset: Integer; FPages: TList; FPagesCounted: Boolean; FPrinterInfo: TBCEditorPrinterInfo; FPrinting: Boolean; FSelectionAvailable: Boolean; FSelectedOnly: Boolean; FSelectionMode: TBCEditorSelectionMode; FTabWidth: Integer; FTextDrawer: TBCEditorTextDrawer; FTitle: string; FWrap: Boolean; FYPos: Integer; function ClipLineToRect(ALine: string): string; function GetPageCount: Integer; procedure CalculatePages; procedure HandleWrap(const Text: string; MaxWidth: Integer); procedure InitHighlighterRanges; procedure InitPrint; procedure PrintPage(Num: Integer); procedure RestoreCurrentFont; procedure SaveCurrentFont; procedure SetCharWidth(const Value: Integer); procedure SetEditor(const Value: TBCBaseEditor); procedure SetFont(const Value: TFont); procedure SetFooter(const Value: TBCEditorPrintFooter); procedure SetHeader(const Value: TBCEditorPrintHeader); procedure SetHighlighter(const Value: TBCEditorHighlighter); procedure SetLines(const Value: TStrings); procedure SetMargins(const Value: TBCEditorPrintMargins); procedure SetMaxLeftChar(const Value: Integer); procedure SetPixelsPerInch; procedure TextOut(const Text: string; AList: TList); procedure WriteLine(const Text: string); procedure WriteLineNumber; protected procedure PrintLine(LineNumber, PageNumber: Integer); virtual; procedure PrintStatus(Status: TBCEditorPrintStatus; PageNumber: Integer; var Abort: Boolean); virtual; property CharWidth: Integer read FCharWidth write SetCharWidth; property MaxLeftChar: Integer read FMaxLeftChar write SetMaxLeftChar; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure LoadFromStream(AStream: TStream); procedure Print; procedure PrintRange(StartPage, EndPage: Integer); procedure PrintToCanvas(ACanvas: TCanvas; PageNumber: Integer); procedure SaveToStream(AStream: TStream); procedure UpdatePages(ACanvas: TCanvas); property Editor: TBCBaseEditor read FEditor write SetEditor; property PageCount: Integer read GetPageCount; property PrinterInfo: TBCEditorPrinterInfo read FPrinterInfo; published property Color: TColor read FDefaultBackground write FDefaultBackground; property Colors: Boolean read FColors write FColors default False; property Copies: Integer read FCopies write FCopies; property DocumentTitle: string read FDocumentTitle write FDocumentTitle; property Font: TFont read FFont write SetFont; property Footer: TBCEditorPrintFooter read FFooter write SetFooter; property Header: TBCEditorPrintHeader read FHeader write SetHeader; property Highlight: Boolean read FHighlight write FHighlight default True; property Highlighter: TBCEditorHighlighter read FHighlighter write SetHighlighter; property LineNumbers: Boolean read FLineNumbers write FLineNumbers default False; property LineNumbersInMargin: Boolean read FLineNumbersInMargin write FLineNumbersInMargin default False; property LineOffset: Integer read FLineOffset write FLineOffset default 0; property Margins: TBCEditorPrintMargins read FMargins write SetMargins; property OnPrintLine: TBCEditorPrintLineEvent read FOnPrintLine write FOnPrintLine; property OnPrintStatus: TBCEditorPrintStatusEvent read FOnPrintStatus write FOnPrintStatus; property PageOffset: Integer read FPageOffset write FPageOffset default 0; property SelectedOnly: Boolean read FSelectedOnly write FSelectedOnly default False; property TabWidth: Integer read FTabWidth write FTabWidth; property Title: string read FTitle write FTitle; property Wrap: Boolean read FWrap write FWrap default True; end; implementation uses Math, BCEditor.Highlighter.Attributes, BCEditor.Consts; { TBCEditorPrint } constructor TBCEditorPrint.Create(AOwner: TComponent); begin inherited; FCopies := 1; FFooter := TBCEditorPrintFooter.Create; FHeader := TBCEditorPrintHeader.Create; FLines := TStringList.Create; FMargins := TBCEditorPrintMargins.Create; FPrinterInfo := TBCEditorPrinterInfo.Create; FFont := TFont.Create; FOldFont := TFont.Create; MaxLeftChar := 1024; FWrap := True; FHighlight := True; FColors := False; FLineNumbers := False; FLineOffset := 0; FPageOffset := 0; FLineNumbersInMargin := False; FPages := TList.Create; FTabWidth := 8; FDefaultBackground := clWhite; FFontDummy := TFont.Create; with FFontDummy do begin Name := 'Courier New'; Size := 10; end; FTextDrawer := TBCEditorTextDrawer.Create([fsBold], FFontDummy); end; destructor TBCEditorPrint.Destroy; var i: Integer; begin FFooter.Free; FHeader.Free; FLines.Free; FMargins.Free; FPrinterInfo.Free; FFont.Free; FOldFont.Free; for i := 0 to FPages.Count - 1 do TBCEditorPageLine(FPages[i]).Free; FPages.Free; FTextDrawer.Free; FFontDummy.Free; inherited; end; procedure TBCEditorPrint.SetLines(const Value: TStrings); var i, j: Integer; TabConvertProc: TBCEditorTabConvertProc; S: string; HasTabs: Boolean; begin TabConvertProc := GetTabConvertProc(FTabWidth); with FLines do begin BeginUpdate; try Clear; for i := 0 to Value.Count - 1 do begin S := TabConvertProc(Value[i], FTabWidth, HasTabs); j := Pos(BCEDITOR_TAB_CHAR, S); while j > 0 do begin S[j] := ' '; j := Pos(BCEDITOR_TAB_CHAR, S); end; Add(S); end; finally EndUpdate; end; end; FHighlighterRangesSet := False; FPagesCounted := False; end; procedure TBCEditorPrint.SetFont(const Value: TFont); begin FFont.Assign(Value); FPagesCounted := False; end; procedure TBCEditorPrint.SetCharWidth(const Value: Integer); begin if FCharWidth <> Value then FCharWidth := Value; end; procedure TBCEditorPrint.SetMaxLeftChar(const Value: Integer); begin if FMaxLeftChar <> Value then FMaxLeftChar := Value; end; procedure TBCEditorPrint.SetHighlighter(const Value: TBCEditorHighlighter); begin FHighlighter := Value; FHighlighterRangesSet := False; FPagesCounted := False; end; procedure TBCEditorPrint.InitPrint; var TempSize: Integer; TempTextMetrics: TTextMetric; begin FFontColor := FFont.Color; FCanvas.Font.Assign(FFont); if not FPrinting then begin SetPixelsPerInch; TempSize := FCanvas.Font.Size; FCanvas.Font.PixelsPerInch := FFont.PixelsPerInch; FCanvas.Font.Size := TempSize; end; FCanvas.Font.Style := [fsBold, fsItalic, fsUnderline, fsStrikeOut]; GetTextMetrics(FCanvas.Handle, TempTextMetrics); CharWidth := TempTextMetrics.tmAveCharWidth; FLineHeight := TempTextMetrics.tmHeight + TempTextMetrics.tmExternalLeading; FTextDrawer.SetBaseFont(FFont); FTextDrawer.Style := FFont.Style; FMargins.InitPage(FCanvas, 1, FPrinterInfo, FLineNumbers, FLineNumbersInMargin, FLines.Count - 1 + FLineOffset); CalculatePages; FHeader.InitPrint(FCanvas, FPageCount, FTitle, FMargins); FFooter.InitPrint(FCanvas, FPageCount, FTitle, FMargins); end; procedure TBCEditorPrint.SetPixelsPerInch; var TempSize: Integer; begin FHeader.SetPixelsPerInch(FPrinterInfo.YPixPerInch); FFooter.SetPixelsPerInch(FPrinterInfo.YPixPerInch); TempSize := FFont.Size; FFont.PixelsPerInch := FPrinterInfo.YPixPerInch; FFont.Size := TempSize; end; procedure TBCEditorPrint.InitHighlighterRanges; var i: Integer; begin if not FHighlighterRangesSet and Assigned(FHighlighter) and (FLines.Count > 0) then begin FHighlighter.ResetCurrentRange; FLines.Objects[0] := FHighlighter.GetCurrentRange; i := 1; while i < FLines.Count do begin FHighlighter.SetCurrentLine(FLines[i - 1]); FHighlighter.NextToEndOfLine; FLines.Objects[i] := FHighlighter.GetCurrentRange; Inc(i); end; FHighlighterRangesSet := True; end; end; procedure TBCEditorPrint.CalculatePages; var S, Text: string; i, j: Integer; LList: TList; YPos: Integer; PageLine: TBCEditorPageLine; StartLine, EndLine: Integer; SelectionStart, SelectionLength: Integer; procedure CountWrapped; var j: Integer; begin for j := 0 to LList.Count - 1 do YPos := YPos + FLineHeight; end; begin InitHighlighterRanges; for i := 0 to FPages.Count - 1 do TBCEditorPageLine(FPages[i]).Free; FPages.Clear; FMaxWidth := FMargins.PixelRight - FMargins.PixelLeft; S := ''; FMaxCol := 0; while TextWidth(FCanvas, S) < FMaxWidth do begin S := S + 'W'; FMaxCol := FMaxCol + 1; end; FMaxCol := FMaxCol - 1; S := StringOfChar('W', FMaxCol); FMaxWidth := TextWidth(FCanvas, S); FPageCount := 1; PageLine := TBCEditorPageLine.Create; PageLine.FirstLine := 0; FPages.Add(PageLine); YPos := FMargins.PixelTop; if SelectedOnly then begin StartLine := FBlockBeginPosition.Line - 1; EndLine := FBlockEndPosition.Line - 1; end else begin StartLine := 0; EndLine := FLines.Count - 1; end; for i := StartLine to EndLine do begin if not FSelectedOnly or (FSelectionMode = smLine) then Text := FLines[i] else begin if (FSelectionMode = smColumn) or (i = FBlockBeginPosition.Line - 1) then SelectionStart := FBlockBeginPosition.Char else SelectionStart := 1; if (FSelectionMode = smColumn) or (i = FBlockEndPosition.Line - 1) then SelectionLength := FBlockEndPosition.Char - SelectionStart else SelectionLength := MaxInt; Text := Copy(FLines[i], SelectionStart, SelectionLength); end; if YPos + FLineHeight > FMargins.PixelBottom then begin YPos := FMargins.PixelTop; FPageCount := FPageCount + 1; PageLine := TBCEditorPageLine.Create; PageLine.FirstLine := i; FPages.Add(PageLine); end; if Wrap and (TextWidth(FCanvas, Text) > FMaxWidth) then begin LList := TList.Create; try if WrapTextEx(Text, [' ', '-', BCEDITOR_TAB_CHAR, ','], FMaxCol, LList) then CountWrapped else begin if WrapTextEx(Text, [';', ')', '.'], FMaxCol, LList) then CountWrapped else while Length(Text) > 0 do begin S := Copy(Text, 1, FMaxCol); Delete(Text, 1, FMaxCol); if Length(Text) > 0 then YPos := YPos + FLineHeight; end; end; for j := 0 to LList.Count - 1 do TBCEditorWrapPosition(LList[j]).Free; finally LList.Free; end; end; YPos := YPos + FLineHeight; end; FPagesCounted := True; end; procedure TBCEditorPrint.WriteLineNumber; var S: string; begin SaveCurrentFont; S := IntToStr(FLineNumber + FLineOffset) + ': '; FCanvas.Brush.Color := FDefaultBackground; FCanvas.Font.Style := []; FCanvas.Font.Color := clBlack; FCanvas.TextOut(FMargins.PixelLeft - FCanvas.TextWidth(S), FYPos, S); RestoreCurrentFont; end; procedure TBCEditorPrint.HandleWrap(const Text: string; MaxWidth: Integer); var S: string; LList: TList; j: Integer; procedure WrapPrimitive; var i: Integer; WrapPos: TBCEditorWrapPosition; begin i := 1; while i <= Length(Text) do begin S := ''; while (Length(S) < FMaxCol) and (i <= Length(Text)) do begin S := S + Text[i]; i := i + 1; end; WrapPos := TBCEditorWrapPosition.Create; WrapPos.Index := i - 1; LList.Add(WrapPos); if (Length(S) - i) <= FMaxCol then Break; end; end; begin S := ''; LList := TList.Create; try if WrapTextEx(Text, [' ', '-', BCEDITOR_TAB_CHAR, ','], FMaxCol, LList) then TextOut(Text, LList) else begin if WrapTextEx(Text, [';', ')', '.'], FMaxCol, LList) then TextOut(Text, LList) else begin WrapPrimitive; TextOut(Text, LList) end; end; for j := 0 to LList.Count - 1 do TBCEditorWrapPosition(LList[j]).Free; finally LList.Free; end; end; procedure TBCEditorPrint.SaveCurrentFont; begin FOldFont.Assign(FCanvas.Font); end; procedure TBCEditorPrint.RestoreCurrentFont; begin FCanvas.Font.Assign(FOldFont); end; function TBCEditorPrint.ClipLineToRect(ALine: string): string; begin while FCanvas.TextWidth(ALine) > FMaxWidth do SetLength(ALine, Length(ALine) - 1); Result := ALine; end; procedure TBCEditorPrint.TextOut(const Text: string; AList: TList); var Token: string; TokenPos: Integer; Attr: TBCEditorHighlighterAttribute; AColor: TColor; TokenStart: Integer; LCount: Integer; Handled: Boolean; aStr: string; i, WrapPos, OldWrapPos: Integer; Lines: TStringList; ClipRect: TRect; procedure ClippedTextOut(X, Y: Integer; Text: string); begin Text := ClipLineToRect(Text); if Highlight and Assigned(FHighlighter) and (FLines.Count > 0) then begin SetBkMode(FCanvas.Handle, TRANSPARENT); FTextDrawer.ExtTextOut(X, Y, [], ClipRect, PChar(Text), Length(Text)); //ExtTextOutDistance); SetBkMode(FCanvas.Handle, OPAQUE); end else ExtTextOut(FCanvas.Handle, X, Y, 0, nil, PChar(Text), Length(Text), nil); end; procedure SplitToken; var aStr: string; Last: Integer; FirstPos: Integer; TokenEnd: Integer; begin Last := TokenPos; FirstPos := TokenPos; TokenEnd := TokenPos + Length(Token); while (LCount < AList.Count) and (TokenEnd > TBCEditorWrapPosition(AList[LCount]).Index) do begin aStr := Copy(Text, Last + 1, TBCEditorWrapPosition(AList[LCount]).Index - Last); Last := TBCEditorWrapPosition(AList[LCount]).Index; ClippedTextOut(FMargins.PixelLeft + FirstPos * FTextDrawer.CharWidth, FYPos, aStr); FirstPos := 0; LCount := LCount + 1; FYPos := FYPos + FLineHeight; end; aStr := Copy(Text, Last + 1, TokenEnd - Last); ClippedTextOut(FMargins.PixelLeft + FirstPos * FTextDrawer.CharWidth, FYPos, aStr); TokenStart := TokenPos + Length(Token) - Length(aStr); end; begin FTextDrawer.BeginDrawing(FCanvas.Handle); with FMargins do ClipRect := Rect(PixelLeft, PixelTop, PixelRight, PixelBottom); if Highlight and Assigned(FHighlighter) and (FLines.Count > 0) then begin SaveCurrentFont; FHighlighter.SetCurrentRange(FLines.Objects[FLineNumber - 1]); FHighlighter.SetCurrentLine(Text); Token := ''; TokenStart := 0; LCount := 0; while not FHighlighter.GetEndOfLine do begin Token := FHighlighter.GetToken; TokenPos := FHighlighter.GetTokenPosition; Attr := FHighlighter.GetTokenAttribute; if Assigned(Attr) then begin FCanvas.Font.Style := Attr.Style; if FColors then begin AColor := Attr.Foreground; if AColor = clNone then AColor := FFont.Color; FCanvas.Font.Color := AColor; AColor := Attr.Background; if AColor = clNone then AColor := FDefaultBackground; FCanvas.Brush.Color := AColor; end else begin FCanvas.Font.Color := FFontColor; FCanvas.Brush.Color := FDefaultBackground; end; end else begin FCanvas.Font.Color := FFontColor; FCanvas.Brush.Color := FDefaultBackground; end; Handled := False; if Assigned(AList) then if LCount < AList.Count then begin if TokenPos >= TBCEditorWrapPosition(AList[LCount]).Index then begin LCount := LCount + 1; TokenStart := TokenPos; FYPos := FYPos + FLineHeight; end else if TokenPos + Length(Token) > TBCEditorWrapPosition(AList[LCount]).Index then begin Handled := True; SplitToken; end; end; if not Handled then ClippedTextOut(FMargins.PixelLeft + (TokenPos - TokenStart) * FTextDrawer.CharWidth, FYPos, Token); FHighlighter.Next; end; RestoreCurrentFont; end else begin Lines := TStringList.Create; try OldWrapPos := 0; if Assigned(AList) then for i := 0 to AList.Count - 1 do begin WrapPos := TBCEditorWrapPosition(AList[i]).Index; if i = 0 then aStr := Copy(Text, 1, WrapPos) else aStr := Copy(Text, OldWrapPos + 1, WrapPos - OldWrapPos); Lines.Add(aStr); OldWrapPos := WrapPos; end; if Length(Text) > 0 then Lines.Add(Copy(Text, OldWrapPos + 1, MaxInt)); for i := 0 to Lines.Count - 1 do begin ClippedTextOut(FMargins.PixelLeft, FYPos, Lines[i]); if i < Lines.Count - 1 then FYPos := FYPos + FLineHeight; end; finally Lines.Free; end end; FTextDrawer.EndDrawing; end; procedure TBCEditorPrint.WriteLine(const Text: string); begin if FLineNumbers then WriteLineNumber; if Wrap and (FCanvas.TextWidth(Text) > FMaxWidth) then HandleWrap(Text, FMaxWidth) else TextOut(Text, nil); FYPos := FYPos + FLineHeight; end; procedure TBCEditorPrint.PrintPage(Num: Integer); var i, EndLine: Integer; SelectionStart, SelectionLen: Integer; begin PrintStatus(psNewPage, Num, FAbort); if not FAbort then begin FCanvas.Brush.Color := Color; with FMargins do FCanvas.FillRect(Rect(PixelLeft, PixelTop, PixelRight, PixelBottom)); FMargins.InitPage(FCanvas, Num, FPrinterInfo, FLineNumbers, FLineNumbersInMargin, FLines.Count - 1 + FLineOffset); FHeader.Print(FCanvas, Num + FPageOffset); if FPages.Count > 0 then begin FYPos := FMargins.PixelTop; if Num = FPageCount then EndLine := FLines.Count - 1 else EndLine := TBCEditorPageLine(FPages[Num]).FirstLine - 1; for i := TBCEditorPageLine(FPages[Num - 1]).FirstLine to EndLine do begin FLineNumber := i + 1; if (not FSelectedOnly or ((i >= FBlockBeginPosition.Line - 1) and (i <= FBlockEndPosition.Line - 1))) then begin if (not FSelectedOnly or (FSelectionMode = smLine)) then WriteLine(FLines[i]) else begin if (FSelectionMode = smColumn) or (i = FBlockBeginPosition.Line - 1) then SelectionStart := FBlockBeginPosition.Char else SelectionStart := 1; if (FSelectionMode = smColumn) or (i = FBlockEndPosition.Line - 1) then SelectionLen := FBlockEndPosition.Char - SelectionStart else SelectionLen := MaxInt; WriteLine(Copy(FLines[i], SelectionStart, SelectionLen)); end; PrintLine(i + 1, Num); end; end; end; FFooter.Print(FCanvas, Num + FPageOffset); end; end; procedure TBCEditorPrint.UpdatePages(ACanvas: TCanvas); begin FCanvas := ACanvas; FPrinterInfo.UpdatePrinter; InitPrint; end; procedure TBCEditorPrint.PrintToCanvas(ACanvas: TCanvas; PageNumber: Integer); begin FAbort := False; FPrinting := False; FCanvas := ACanvas; PrintPage(PageNumber); end; procedure TBCEditorPrint.Print; begin PrintRange(1, -1); end; procedure TBCEditorPrint.PrintRange(StartPage, EndPage: Integer); var i, j: Integer; begin if FSelectedOnly and not FSelectionAvailable then Exit; FPrinting := True; FAbort := False; if FDocumentTitle <> '' then Printer.Title := FDocumentTitle else Printer.Title := FTitle; Printer.BeginDoc; PrintStatus(psBegin, StartPage, FAbort); UpdatePages(Printer.Canvas); for j := 1 to Copies do begin i := StartPage; if EndPage < 0 then EndPage := FPageCount; while (i <= EndPage) and (not FAbort) do begin PrintPage(i); if ((i < EndPage) or (j < Copies)) and not FAbort then Printer.NewPage; i := i + 1; end; end; if not FAbort then PrintStatus(psEnd, EndPage, FAbort); Printer.EndDoc; FPrinting := False; end; procedure TBCEditorPrint.PrintLine(LineNumber, PageNumber: Integer); begin if Assigned(FOnPrintLine) then FOnPrintLine(Self, LineNumber, PageNumber); end; procedure TBCEditorPrint.PrintStatus(Status: TBCEditorPrintStatus; PageNumber: Integer; var Abort: Boolean); begin Abort := False; if Assigned(FOnPrintStatus) then FOnPrintStatus(Self, Status, PageNumber, Abort); if Abort then if FPrinting then Printer.Abort; end; function TBCEditorPrint.GetPageCount: Integer; var LCanvas: TCanvas; LHandle: HDC; begin Result := 0; if FPagesCounted then Result := FPageCount else begin LCanvas := TCanvas.Create; LHandle := GetDC(0); try if LHandle <> 0 then begin LCanvas.Handle := LHandle; UpdatePages(LCanvas); LCanvas.Handle := 0; Result := FPageCount; FPagesCounted := True; end; finally ReleaseDC(0, LHandle); LCanvas.Free; end; end; end; procedure TBCEditorPrint.SetEditor(const Value: TBCBaseEditor); begin FEditor := Value; Highlighter := Value.Highlighter; Font := Value.Font; CharWidth := Value.CharWidth; FTabWidth := Value.Tabs.Width; SetLines(Value.Lines); FSelectionAvailable := Value.SelectionAvailable; FBlockBeginPosition := Value.SelectionBeginPosition; FBlockEndPosition := Value.SelectionEndPosition; FSelectionMode := Value.Selection.Mode; end; procedure TBCEditorPrint.LoadFromStream(AStream: TStream); var LLength, BufferSize: Integer; Buffer: PChar; begin FHeader.LoadFromStream(AStream); FFooter.LoadFromStream(AStream); FMargins.LoadFromStream(AStream); with AStream do begin Read(LLength, SizeOf(LLength)); BufferSize := LLength * SizeOf(Char); GetMem(Buffer, BufferSize + SizeOf(Char)); try Read(Buffer^, BufferSize); Buffer[BufferSize div SizeOf(Char)] := BCEDITOR_NONE_CHAR; FTitle := Buffer; finally FreeMem(Buffer); end; Read(LLength, SizeOf(LLength)); BufferSize := LLength * SizeOf(Char); GetMem(Buffer, BufferSize + SizeOf(Char)); try Read(Buffer^, BufferSize); Buffer[BufferSize div SizeOf(Char)] := BCEDITOR_NONE_CHAR; FDocumentTitle := Buffer; finally FreeMem(Buffer); end; Read(FWrap, SizeOf(FWrap)); Read(FHighlight, SizeOf(FHighlight)); Read(FColors, SizeOf(FColors)); Read(FLineNumbers, SizeOf(FLineNumbers)); Read(FLineOffset, SizeOf(FLineOffset)); Read(FPageOffset, SizeOf(FPageOffset)); end; end; procedure TBCEditorPrint.SaveToStream(AStream: TStream); var LLength: Integer; begin FHeader.SaveToStream(AStream); FFooter.SaveToStream(AStream); FMargins.SaveToStream(AStream); with AStream do begin LLength := Length(FTitle); Write(LLength, SizeOf(LLength)); Write(PChar(FTitle)^, LLength * SizeOf(Char)); LLength := Length(FDocumentTitle); Write(LLength, SizeOf(LLength)); Write(PChar(FDocumentTitle)^, LLength * SizeOf(Char)); Write(FWrap, SizeOf(FWrap)); Write(FHighlight, SizeOf(FHighlight)); Write(FColors, SizeOf(FColors)); Write(FLineNumbers, SizeOf(FLineNumbers)); Write(FLineOffset, SizeOf(FLineOffset)); Write(FPageOffset, SizeOf(FPageOffset)); end; end; procedure TBCEditorPrint.SetFooter(const Value: TBCEditorPrintFooter); begin FFooter.Assign(Value); end; procedure TBCEditorPrint.SetHeader(const Value: TBCEditorPrintHeader); begin FHeader.Assign(Value); end; procedure TBCEditorPrint.SetMargins(const Value: TBCEditorPrintMargins); begin FMargins.Assign(Value); end; end.
UNIT Turtle; {$N+} interface VAR TurtlePace, TurtleX, TurtleY, TurtleTheta : SINGLE; PROCEDURE TurtleTurn(angle : SINGLE); PROCEDURE TurtleStep; FUNCTION TurtlePoint(X1,Y1,X2,Y2 : SINGLE) : SINGLE; implementation VAR HaPiRadian : SINGLE; PROCEDURE TurtleTurn(angle : SINGLE); BEGIN TurtleTheta := (TurtleTheta + angle); (* { ensure a valid angle } REPEAT IF TurtleTheta > 360.0 THEN TurtleTheta := TurtleTheta - 360.0 ELSE IF TurtleTheta < 0.0 THEN TurtleTheta := 360.0 + TurtleTheta; UNTIL (TurtleTheta < 360.0) AND NOT (TurtleTheta < 0.0) *) END; PROCEDURE TurtleStep; BEGIN TurtleX := TurtlePace * cos(TurtleTheta*HaPiRadian); TurtleY := TurtlePace * sin(TurtleTheta*HaPiRadian); END; FUNCTION TurtlePoint(X1,Y1,X2,Y2 : SINGLE) : SINGLE; VAR theta : SINGLE; BEGIN IF (x2-x1) = 0 THEN IF y2 > y1 THEN theta := 90.0 ELSE theta := 270.0 ELSE theta := TRUNC(ArcTan((y2-y1)/(x2-x1)) / HaPiRadian); TurtlePoint := theta; END; BEGIN HaPiRadian := Pi / 180.0; END.
unit MinStopsPlanner; interface uses Contnrs, MetroBase, Planner; type TMinStopsPlanner = class(TPlanner) protected FNetwork: TNetwork; public // construction/destruction constructor Create(ANetwork: TNetwork); // queries -------------------------------------------- function FindRoutes(A, B: TStationR; AOption: TSearchOption): TRouteSet; override; // pre: true // ret: set of optimal (according to AOption) routes from A to B function FindRoute(A, B: TStationR; AOption: TSearchOption): TRouteR; override; // pre: true // ret: a route from A to B with minimal number of stops end; implementation //=============================================================== // Auxiliary types type TStationState = (ssWhite, ssGrey, ssBlack); TStationData = class(TObject) FState: TStationState; FParent: TStationR; FLine: TLineR; FDir: TStationR; FDist: Integer; end; { TMinStopsPlanner } constructor TMinStopsPlanner.Create(ANetwork: TNetwork); begin inherited Create; FNetwork := ANetwork; end; function TMinStopsPlanner.FindRoute(A, B: TStationR; AOption: TSearchOption): TRouteR; var VRoute : TRouteRW; VSegment : TRouteSegmentR; VQueue : TObjectList; VS : TStationR; VL : TLineR; I, J : Integer; IndexOfNext : Integer; IndexOfPrev : Integer; Index : Integer; Repetitions : Integer; VDirection : TStationR; SearchTransferStation : TStationR; begin // initialization------------------------------------------------------------- (* forall U in SS - {S} do U.color := white; U.parent := nil; U.line := nil; U.dist := +¥ od; *) with FNetwork.GetStationSet do begin for I := 0 to Count - 1 do begin VS := GetStation(I); VS.Data := TStationData.Create; with VS.Data as TStationData do begin FState := ssWhite; FParent := nil; FLine := nil; FDist := MaxInt; end;{with} end;{for} end;{with} (* S.color := grey; S.parent := nil; S.line := nil; S.dist := 0; *) with A.Data as TStationData do begin FState := ssGrey; FDist := 0; end; (* Q := <S>; *) VQueue := TObjectList.Create(false); VQueue.Add(A); // main loop------------------------------------------------------------------ (* while (Q ? <>) and (T.color ? grey) do U, Q := first(Q), rest(Q); *) while (VQueue.Count <> 0) and ((B.Data as TStationData).FState <> ssGrey) do begin VS := VQueue.Items[0] as TStationR; VQueue.Delete(0); (* forall L in LL do if U occurs on L at some position I then *) with FNetwork.GetLineSet do begin for J := 0 to Count - 1 do begin VL := GetLine(J); if VL.HasStop(VS) then begin I := VL.IndexOf(VS); (* for possible successors V of U on L do V.color := grey; V.parent := U; V.line := L; V.dist := U.dist + 1; Q := Q ++ <V>; od; *) { Kijk of er een opvolger is } IndexOfNext := -1; if (I <> VL.Count - 1) then begin // I is niet het eind, er is een volgende IndexOfNext := I + 1; end else if VL.IsCircular then begin // I is wel het eind, maar circular, dus wel een volgende IndexOfNext := 0; end; { Kijk of er een voorganger is } IndexOfPrev := -1; if (VL.IsOneWay = False) then begin if (I <> 0) then begin // I is niet het begin, er is een vorige IndexOfPrev := I - 1; end else if VL.IsCircular then begin // I is wel het begin, maar circular, dus wel een vorige IndexOfPrev := VL.Count - 1; end;{if} end;{if} { Handel Voorganger en Opvolger van I af } Repetitions := 0; while Repetitions <> 2 do begin case Repetitions of 0: Index := IndexOfPrev; // for x := 1,2 do 1: Index := IndexOfNext; else Break; end;{case} if Index <> -1 then begin with ((VL.Stop(Index) as TStationR).Data as TStationData) do begin if (FState = ssWhite) then begin FState := ssGrey; FParent := VS; FLine := VL; FDist := (VS.Data as TStationData).FDist + 1; VQueue.Add(VL.Stop(Index)); end;{if} end;{with} end;{if} Inc(Repetitions); end;{while} end;{if} end;{for} end;{with} (* U.color := black *) (VS.Data as TStationData).FState := ssBlack; end;{while} (* {(Q = <>) or (T.color = grey)} *) { VQueue.Count = 0 or (B.Data as TStationData).FState = ssGrey } // construct route VRoute := TRouteRW.Create; (* if T.color <> grey then {T is not reachable from S} path := <> else {construct path by following parent pointers} *) if (B.Data as TStationData).FState = ssGrey then begin VS := B; while (VS <> A) do begin VL := (VS.Data as TStationData).FLine; SearchTransferStation := VS; { Zoek overstapstation } while (VL = (SearchTransferStation.Data as TStationData).FLine) do begin SearchTransferStation := (SearchTransferStation.Data as TStationData).FParent; end;{while} { SearchTransferStation.Data.FLine <> VL, overstapstation gevonden ALS = nil, beginstation gevonden } { Vind richting } with VL do begin if IndexOf(VS) <= IndexOf(SearchTransferStation) then VDirection := Stop(Count - 1) else VDirection := Stop(0); end;{with} { Maak route-segment } VSegment := TRouteSegmentR.Create(SearchTransferStation, VL, VDirection, VS); VRoute.Insert(0, VSegment); { Volgende } VS := SearchTransferStation; end;{while} end;{if} {TODO} // finalization with FNetwork.GetStationSet do for I := 0 to Count - 1 do GetStation(I).Data.Free; VQueue.Free; Result := VRoute; (* {initialization} forall g in N - {s} do g.color := white; g.parent := nil; g.dist := +¥ od; s.color := grey; s.parent := nil; s.dist := 0; Q := <s>; {main loop} while (Q ? <>) and (T.color ? grey) do U, Q := first(Q), rest(Q); "process U"; forall L in LL do if U occurs on L at some position I then for possible successors V of U on L do V.color := grey; V.parent := U; V.line := L; V.dist := U.dist + 1; Q := Q ++ <V>; od; fi; "process (U,V)"; od; U.color := black od; {(Q = <>) or (T.color = grey)} if T.color ? grey then {T is not reachable from S} path := <> else {construct path by following parent pointers} P := T; path := <T>; while P ? nil do path := <P.parent,P.line> ++ path; P := P.parent od fi {path is a shortest path from S to T} *) end; function TMinStopsPlanner.FindRoutes(A, B: TStationR; AOption: TSearchOption): TRouteSet; begin Result := TRouteSet.Create; Result.Add(FindRoute(A, B, AOption)); end; end.
unit FIToolkit.Config.Consts; interface uses System.SysUtils, System.Types, FIToolkit.Config.Types, FIToolkit.Localization; const { Common consts } STR_CFG_VALUE_ARR_DELIM_DEFAULT = ','; STR_CFG_VALUE_ARR_DELIM_REGEX = '<|>'; { FixInsight options consts } // <none> { Config data consts } CD_INT_SNIPPET_SIZE_MIN = 1; CD_INT_SNIPPET_SIZE_MAX = 101; { Default config values. Do not localize! } DEF_FIO_ARR_COMPILER_DEFINES : TStringDynArray = ['RELEASE', 'MSWINDOWS']; DEF_FIO_BOOL_SILENT = False; DEF_FIO_ENUM_OUTPUT_FORMAT = TFixInsightOutputFormat(fiofXML); DEF_FIO_STR_OUTPUT_FILENAME = 'FixInsightReport.xml'; DEF_FIO_STR_SETTINGS_FILENAME = String.Empty; DEF_CD_ARR_EXCLUDE_PROJECT_PATTERNS : TStringDynArray = ['Project[0-9]+\.dpr', '\\JCL\\', '\\JVCL\\']; DEF_CD_ARR_EXCLUDE_UNIT_PATTERNS : TStringDynArray = ['Unit[0-9]+\.pas', '\\JWA\\', '\\RegExpr.pas']; DEF_CD_BOOL_DEDUPLICATE = False; DEF_CD_BOOL_MAKE_ARCHIVE = False; DEF_CD_INT_NONZERO_EXIT_CODE_MSG_COUNT = 0; DEF_CD_INT_SNIPPET_SIZE = 21; DEF_CD_STR_OUTPUT_FILENAME = 'FIToolkitReport.html'; { FixInsight command line parameters. Do not localize! } STR_FIPARAM_PREFIX = '--'; STR_FIPARAM_VALUE_DELIM = '='; STR_FIPARAM_VALUES_DELIM = ';'; STR_FIPARAM_DEFINES = STR_FIPARAM_PREFIX + 'defines' + STR_FIPARAM_VALUE_DELIM; STR_FIPARAM_OUTPUT = STR_FIPARAM_PREFIX + 'output' + STR_FIPARAM_VALUE_DELIM; STR_FIPARAM_PROJECT = STR_FIPARAM_PREFIX + 'project' + STR_FIPARAM_VALUE_DELIM; STR_FIPARAM_SETTINGS = STR_FIPARAM_PREFIX + 'settings' + STR_FIPARAM_VALUE_DELIM; STR_FIPARAM_SILENT = STR_FIPARAM_PREFIX + 'silent'; STR_FIPARAM_XML = STR_FIPARAM_PREFIX + 'xml'; resourcestring {$IF LANGUAGE = LANG_EN_US} {$INCLUDE 'Locales\en-US.inc'} {$ELSEIF LANGUAGE = LANG_RU_RU} {$INCLUDE 'Locales\ru-RU.inc'} {$ELSE} {$MESSAGE FATAL 'No language defined!'} {$ENDIF} implementation end.
{ BiConnected Components DFS Method O(N2) Input: G: UnDirected simple graph N: Number of vertices Output: IsCut[I]: Vertex I is CutVertex CompNum: Number of components Comp[I]: Vertices in component I CompLen[I]: Size of component I Reference: Creative, p224 By Ali } program BiConnectedComponents; const MaxN = 100 + 2; var N: Integer; G: array[1 .. MaxN, 1 .. MaxN] of Integer; IsCut: array[1 .. MaxN] of Boolean; CompNum: Integer; Comp: array[1 .. MaxN, 1 .. MaxN] of Integer; CompLen: array[1 .. MaxN] of Integer; DfsNum: array[1 .. Maxn] of Integer; DfsN: Integer; Stack: array[1 .. MaxN] of Integer;{** Must be changed to 2dim if we want to have the edges of a comp.} SN: Integer; {Size of stack} procedure Push(V: Integer); begin Inc(SN); Stack[SN] := V; end; function Pop: Integer; begin if SN = 0 then Pop := -1 else begin Pop := Stack[SN]; Dec(SN); end; end; function BC(V: Integer; Parent: Integer) : Integer; var I, J, Hi, ChNum: Integer; begin DfsNum[V] := DfsN; Dec(DfsN); Push(V); ChNum := 0; Hi := DfsNum[v]; for I := 1 to N do {** insert (v, i) into Stack, each edge will be inserted twice.} if (G[V, I] <> 0) and (I <> Parent) then if DfsNum[I] = 0 then begin Inc(ChNum); J := BC(I, V); if J <= DFSNum[V] then begin if (Parent <> 0) or (ChNum > 1) then IsCut[V] := True; Inc(CompNum); CompLen[CompNum] := 0; repeat Inc(CompLen[CompNum]); Comp[CompNum, CompLen[CompNum]] := Pop; {** and pop all edges } until Comp[CompNum, CompLen[CompNum]] = V; Push(V); end; if Hi < J then Hi := J; end else if Hi < DFSNum[I] then Hi := DFSNum[I]; BC := Hi; end; procedure BiConnected; var I: Integer; begin FillChar(DfsNum, SizeOf(DfsNum), 0); FillChar(IsCut, SizeOf(IsCut), 0); SN := 0; CompNum := 0; DfsN := N; for I := 1 to N do if DfsNum[I] = 0 then BC(I, 0); {I == The root of the DFS tree} end; begin BiConnected; end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC monitor custom implementation } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$HPPEMIT LINKUNIT} unit FireDAC.Moni.Custom; interface uses System.Classes, FireDAC.Stan.Intf, FireDAC.Moni.Base; {$IFDEF FireDAC_MONITOR} type {-----------------------------------------------------------------------------} { TFDMoniCustomClientLink } {-----------------------------------------------------------------------------} [ComponentPlatformsAttribute(pidAllPlatforms)] TFDMoniCustomClientLink = class(TFDMoniClientLinkBase) private FCClient: IFDMoniCustomClient; function GetSynchronize: Boolean; procedure SetSynchronize(AValue: Boolean); protected function GetMoniClient: IFDMoniClient; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property CClient: IFDMoniCustomClient read FCClient; published property Tracing; property Synchronize: Boolean read GetSynchronize write SetSynchronize default False; end; {-----------------------------------------------------------------------------} { TFDMoniCustomClient } {-----------------------------------------------------------------------------} TFDMoniCustomClient = class(TFDMoniClientBase, IFDMoniCustomClient) private FLevel: Integer; FSynchronize: Boolean; protected // IFDMoniClient procedure Notify(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep; ASender: TObject; const AMsg: String; const AArgs: array of const); override; // IFDMoniCustomClient function GetSynchronize: Boolean; procedure SetSynchronize(AValue: Boolean); // other function DoTracingChanged: Boolean; override; procedure DoTraceMsg(const AClassName, AObjName, AMessage: String); virtual; public destructor Destroy; override; end; {$ENDIF} {-------------------------------------------------------------------------------} implementation {$IFDEF FireDAC_MONITOR} uses {$IFDEF MSWINDOWS} Winapi.Windows, {$ENDIF} System.SysUtils, System.Variants, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Factory, FireDAC.Stan.Error; {-------------------------------------------------------------------------------} { TFDMoniCustomClientMsg } {-------------------------------------------------------------------------------} type TFDMoniCustomClientMsg = class (TObject) private FClassName, FObjName, FMessage: String; FClient: IFDMoniCustomClient; protected procedure DoOutput; public constructor Create(const AClassName, AObjName, AMessage: String; const AClient: IFDMoniCustomClient); end; {-------------------------------------------------------------------------------} constructor TFDMoniCustomClientMsg.Create(const AClassName, AObjName, AMessage: String; const AClient: IFDMoniCustomClient); begin inherited Create; FClassName := AClassName; FObjName := AObjName; FMessage := AMessage; FClient := AClient; end; {-------------------------------------------------------------------------------} procedure TFDMoniCustomClientMsg.DoOutput; begin if FClient.OutputHandler <> nil then FClient.OutputHandler.HandleOutput(FClassName, FObjName, FMessage); Destroy; end; {-------------------------------------------------------------------------------} { TFDMoniCustomClient } {-------------------------------------------------------------------------------} destructor TFDMoniCustomClient.Destroy; begin SetTracing(False); inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDMoniCustomClient.GetSynchronize: Boolean; begin Result := FSynchronize; end; {-------------------------------------------------------------------------------} procedure TFDMoniCustomClient.SetSynchronize(AValue: Boolean); begin FSynchronize := AValue; end; {-------------------------------------------------------------------------------} function TFDMoniCustomClient.DoTracingChanged: Boolean; begin Result := True; end; {-------------------------------------------------------------------------------} procedure TFDMoniCustomClient.DoTraceMsg(const AClassName, AObjName, AMessage: String); begin // nothing end; {-------------------------------------------------------------------------------} function VarRec2Variant(AArg: PVarRec): Variant; begin case AArg^.VType of vtInteger: Result := AArg^.VInteger; vtBoolean: Result := AArg^.VBoolean; vtExtended: Result := AArg^.VExtended^; vtPointer: Result := NativeUInt(AArg^.VPointer); {$IFNDEF NEXTGEN} vtChar: Result := AArg^.VChar; vtString: Result := AArg^.VString^; vtAnsiString: Result := AnsiString(AArg^.VAnsiString); vtPChar: Result := AnsiString(AArg^.VPChar); {$ENDIF} vtWideChar: Result := AArg^.VWideChar; vtWideString: Result := {$IFDEF NEXTGEN} String {$ELSE} WideString {$ENDIF} (AArg^.VWideString); vtUnicodeString: Result := UnicodeString(AArg^.VUnicodeString); vtPWideChar: Result := String(AArg^.VPWideChar); vtCurrency: Result := AArg^.VCurrency^; vtInt64: Result := AArg^.VInt64^; vtObject: // special case - for NULL and Unassigned if Byte(NativeUInt(AArg^.VObject)) = 0 then Result := Null else if Byte(NativeUInt(AArg^.VObject)) = 1 then Result := Unassigned else ASSERT(False); else // vtClass, vtVariant, vtInterface ASSERT(False); end; end; {-------------------------------------------------------------------------------} procedure TFDMoniCustomClient.Notify(AKind: TFDMoniEventKind; AStep: TFDMoniEventStep; ASender: TObject; const AMsg: String; const AArgs: array of const); var s, sClassName, sName: String; i, iHigh, iLow: Integer; lQuotes: Boolean; oMsg: TFDMoniCustomClientMsg; begin if AStep = esEnd then Dec(FLevel); if GetTracing and (AKind in GetEventKinds) then begin s := StringOfChar(' ', FLevel * 4); case AStep of esStart: s := s + '>> '; esProgress: s := s + ' . '; esEnd: s := s + '<< '; end; s := s + AMsg; iHigh := High(AArgs); iLow := Low(AArgs); if iHigh - iLow + 1 >= 2 then begin s := s + ' ['; i := iLow; while i < iHigh do begin if i <> iLow then s := s + ', '; lQuotes := False; s := s + FDIdentToStr(VarRec2Variant(@AArgs[i]), lQuotes) + '=' + FDValToStr(VarRec2Variant(@AArgs[i + 1]), lQuotes); Inc(i, 2); end; s := s + ']'; end; GetObjectNames(ASender, sClassName, sName); DoTraceMsg(sClassName, sName, s); if GetOutputHandler <> nil then if not GetSynchronize or (TThread.CurrentThread.ThreadID = MainThreadID) then GetOutputHandler.HandleOutput(sClassName, sName, s) else begin oMsg := TFDMoniCustomClientMsg.Create(sClassName, sName, s, Self); TThread.Queue(nil, oMsg.DoOutput); end; end; if AStep = esStart then Inc(FLevel); end; {-------------------------------------------------------------------------------} { TFDMoniCustomClientLink } {-------------------------------------------------------------------------------} constructor TFDMoniCustomClientLink.Create(AOwner: TComponent); begin inherited Create(AOwner); FCClient := MoniClient as IFDMoniCustomClient; end; {-------------------------------------------------------------------------------} destructor TFDMoniCustomClientLink.Destroy; begin FCClient := nil; inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDMoniCustomClientLink.GetMoniClient: IFDMoniClient; var oCClient: IFDMoniCustomClient; begin FDCreateInterface(IFDMoniCustomClient, oCClient); Result := oCClient as IFDMoniClient; end; {-------------------------------------------------------------------------------} function TFDMoniCustomClientLink.GetSynchronize: Boolean; begin Result := FCClient.Synchronize; end; {-------------------------------------------------------------------------------} procedure TFDMoniCustomClientLink.SetSynchronize(AValue: Boolean); begin FCClient.Synchronize := AValue; end; {-------------------------------------------------------------------------------} var oFact: TFDFactory; initialization oFact := TFDSingletonFactory.Create(TFDMoniCustomClient, IFDMoniCustomClient); finalization FDReleaseFactory(oFact); {$ENDIF} end.
unit ACadastraEmailSuspect; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Buttons, Componentes1, ExtCtrls, PainelGradiente, Localizacao, UnDadosLocaliza, UnDados, UnProspect, DBKeyViolation; type TFCadastraEmailSuspect = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; BGravar: TBitBtn; BCancelar: TBitBtn; SpeedButton2: TSpeedButton; Label3: TLabel; ESuspect: TRBEditLocaliza; ENomSuspect: TEditColor; Label4: TLabel; BitBtn1: TBitBtn; EEmailsCadatrados: TMemoColor; Label1: TLabel; Bevel1: TBevel; Label2: TLabel; Label5: TLabel; LQtdCadastrados: TLabel; LQtdAutomaticos: TLabel; ESiteEmail: TMemoColor; ValidaGravacao1: TValidaGravacao; EDominios: TMemoColor; Label6: TLabel; OpenDialog: TOpenDialog; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure ESuspectRetorno(VpaColunas: TRBColunasLocaliza); procedure BCancelarClick(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure ESiteEmailKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BitBtn1Click(Sender: TObject); procedure ESuspectChange(Sender: TObject); private { Private declarations } VprAcao : Boolean; VprQtdEmailCadastrado, VprQtdEmailAutomatico : Integer; VprDProspect : TRBDProspect; procedure InicializaTela; function ImportaArquivoOutlook :string; public { Public declarations } end; var FCadastraEmailSuspect: TFCadastraEmailSuspect; implementation uses APrincipal, ConstMsg, FunString; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFCadastraEmailSuspect.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprDProspect := TRBDProspect.cria; VprQtdEmailCadastrado := 0; VprQtdEmailAutomatico := 0; ValidaGravacao1.execute; end; { ******************* Quando o formulario e fechado ************************** } procedure TFCadastraEmailSuspect.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } VprDProspect.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} function TFCadastraEmailSuspect.ImportaArquivoOutlook: string; var VpfLaco,VpfPosMailto : Integer; VpfArquivo : TStringList; VpfEmail,VpfResultado : String; VpfCharDelimitador : char; begin for VpfLaco := 0 to OpenDialog.Files.Count - 1 do begin VpfArquivo := TStringList.Create; VpfArquivo.LoadFromFile(OpenDialog.Files.Strings[VpfLaco]); VpfPosMailto := Pos('mailto',VpfArquivo.text); while VpfPosMailto > 0 do begin if VpfArquivo.Text[VpfPosMailto-1] = '[' then VpfCharDelimitador := ']' else if VpfArquivo.Text[VpfPosMailto-1] = '"' then VpfCharDelimitador := '"' else aviso('CharDelimitador não definido '+VpfArquivo.Text[VpfPosMailto-1]); VpfArquivo.Text := copy(VpfArquivo.Text,VpfPosMailto,length(VpfArquivo.Text)-VpfPosMailto); VpfEmail := CopiaAteChar(VpfArquivo.Text,VpfCharDelimitador); VpfEmail := DeleteAteChar(VpfEmail,':'); VpfArquivo.Text := DeleteAteChar(VpfArquivo.Text,VpfCharDelimitador); VprDProspect.CodProspect := ESuspect.AInteiro; VpfResultado := FunProspect.CadastraEmailEmailSuspect(VprDProspect,VpfEmail,EEmailsCadatrados,EDominios,VprQtdEmailCadastrado,VprQtdEmailAutomatico); if VpfResultado <> '' then begin aviso(VpfResultado); break; end; VpfPosMailto := Pos('mailto',VpfArquivo.text); LQtdCadastrados.Caption := IntToStr(VprQtdEmailCadastrado); LQtdCadastrados.Refresh; LQtdAutomaticos.Caption := IntToStr(VprQtdEmailAutomatico); LQtdAutomaticos.Refresh; end; VpfArquivo.Free; end; end; {******************************************************************************} procedure TFCadastraEmailSuspect.InicializaTela; begin ESiteEmail.Clear; if ESuspect.AInteiro <> 0 then ESiteEmail.SetFocus; end; {******************************************************************************} procedure TFCadastraEmailSuspect.ESuspectChange(Sender: TObject); begin ValidaGravacao1.execute; end; {******************************************************************************} procedure TFCadastraEmailSuspect.ESuspectRetorno( VpaColunas: TRBColunasLocaliza); begin ENomSuspect.Text := VpaColunas[1].AValorRetorno; end; {******************************************************************************} procedure TFCadastraEmailSuspect.BCancelarClick(Sender: TObject); begin VprAcao := false; close; end; {******************************************************************************} procedure TFCadastraEmailSuspect.BGravarClick(Sender: TObject); var VpfResultado : String; begin VprDProspect.CodProspect := ESuspect.AInteiro; VpfResultado := FunProspect.CadastraEmailEmailSuspect(VprDProspect,ESiteEmail.Text,EEmailsCadatrados,EDominios,VprQtdEmailCadastrado,VprQtdEmailAutomatico); if VpfResultado = '' then begin InicializaTela; LQtdCadastrados.Caption := IntToStr(VprQtdEmailCadastrado); LQtdAutomaticos.Caption := IntToStr(VprQtdEmailAutomatico); end else aviso(VpfResultado); end; {******************************************************************************} procedure TFCadastraEmailSuspect.BitBtn1Click(Sender: TObject); begin if ESuspect.AInteiro <> 0 then begin if OpenDialog.Execute then ImportaArquivoOutlook; end else aviso('SUSPECT NÃO PREENCHIDO!!!'#13'É necessário preencher o codigo do suspect que sera guardados os e-mails'); end; {******************************************************************************} procedure TFCadastraEmailSuspect.ESiteEmailKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = 13 then BGravar.Click; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFCadastraEmailSuspect]); end.
unit Eval; interface uses StackA; {stack of integer} function InFix2PostFix (L: string): string; function EvaluatePostFix (L: string): integer; function Evaluate (expr: string): integer; implementation function IsDigit (c: char): boolean; {returns TRUE if c is a digit} begin IsDigit := (c>='0') and (c<='9'); end; function OpPr (Op1, Op2: CHAR): boolean; {returns TRUE if Op1 has higher precedence than Op2 } const OP = 's%/*-+)(;'; { precedence list } begin if pos(Op1,OP)<=pos(Op2,OP) then OpPr:=true else OpPr:=false; end; function InFix2PostFix (L: string): string; {-- infix to postfix translator --} var i, j, unused: integer; O: string; S: TSTACK; begin InitStack(S,30); push(S, ord(';')); { precedes all operators } i := 0; {-- counter within L, the input string } j := 1; {-- counter within Out, the output string } O := ' '; repeat inc(i); if IsDigit(L[i]) then begin O[j] := ' '; j := j+1; while IsDigit(L[i]) do begin O[j] := L[i]; i := i+1; j := j+1; end; i := i-1; end else if L[i] = ')' then begin while chr(top(S)) <> '(' do begin {unstack} O[j] := chr(pop(S)); j := j+1; end; unused := pop(S); {-- pop the '(' } end else begin while OpPr(chr(top(S)), L[i]) and (L[i] <> '(') do begin O[j] := chr(pop(S)); j := j + 1; end; push(S, ord(L[i])); end; until i >= length(L); while not IsStackEmpty(S) do begin O[j] := chr(pop(S)); j := j + 1; end; SetLength(O,j-2); CleanUpStack(S); InFix2PostFix := O; end; function EvaluatePostFix (L: string): integer; {--- a postfix expression is evaluated ---} var i: integer; op1, op2: integer; S: TSTACK; begin InitStack(S,30); push(S,0); i := 0; repeat inc(i); if IsDigit(L[i]) then begin op1 := 0; while IsDigit(L[i]) do begin op1 := 10 * op1 + (ord(L[i]) - ord('0')); inc(i); end; dec(i); push(S, op1); end else if L[i] = ' ' then begin end else begin op2 := pop(S); op1 := pop(S); case L[i] of ' ': ; { do nothing } '+': push(S, op1 + op2); '*': push(S, op1 * op2); '-': push(S, op1 - op2); '/': push(S, op1 div op2); 's': begin push(S,op1); push(S,trunc(sin(op2))); end; end; end; until i >= length(L); op1 := pop(S); CleanUpStack(S); EvaluatePostFix := op1; end; function Evaluate (expr:string):integer; begin Evaluate := EvaluatePostFix(InFix2PostFix(expr)); end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, dglOpenGL, oglContext, oglShader, oglVector, oglMatrix; //image image.png (* Will man die Scene realistisch proportional darstellen, nimmt man eine Frustum-Matrix. Dies hat den Einfluss, das Objekte kleiner erscheinen, je weiter die Scene von einem weg ist. In der Realität ist dies auch so, das Objekte kleiner erscheinen, je weiter sie von einem weg sind. *) //lineal type { TForm1 } TForm1 = class(TForm) Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Timer1Timer(Sender: TObject); private ogc: TContext; Shader: TShader; // Shader Klasse procedure CreateScene; procedure InitScene; procedure ogcDrawScene(Sender: TObject); public end; var Form1: TForm1; implementation {$R *.lfm} type TCube = array[0..11] of Tmat3x3; const CubeVertex: TCube = (((-0.5, 0.5, 0.5), (-0.5, -0.5, 0.5), (0.5, -0.5, 0.5)), ((-0.5, 0.5, 0.5), (0.5, -0.5, 0.5), (0.5, 0.5, 0.5)), ((0.5, 0.5, 0.5), (0.5, -0.5, 0.5), (0.5, -0.5, -0.5)), ((0.5, 0.5, 0.5), (0.5, -0.5, -0.5), (0.5, 0.5, -0.5)), ((0.5, 0.5, -0.5), (0.5, -0.5, -0.5), (-0.5, -0.5, -0.5)), ((0.5, 0.5, -0.5), (-0.5, -0.5, -0.5), (-0.5, 0.5, -0.5)), ((-0.5, 0.5, -0.5), (-0.5, -0.5, -0.5), (-0.5, -0.5, 0.5)), ((-0.5, 0.5, -0.5), (-0.5, -0.5, 0.5), (-0.5, 0.5, 0.5)), // oben ((0.5, 0.5, 0.5), (0.5, 0.5, -0.5), (-0.5, 0.5, -0.5)), ((0.5, 0.5, 0.5), (-0.5, 0.5, -0.5), (-0.5, 0.5, 0.5)), // unten ((-0.5, -0.5, 0.5), (-0.5, -0.5, -0.5), (0.5, -0.5, -0.5)), ((-0.5, -0.5, 0.5), (0.5, -0.5, -0.5), (0.5, -0.5, 0.5))); CubeColor: TCube = (((1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 0.0)), ((1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 0.0)), ((0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0)), ((0.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 1.0, 0.0)), ((0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0)), ((0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0)), ((0.0, 1.0, 1.0), (0.0, 1.0, 1.0), (0.0, 1.0, 1.0)), ((0.0, 1.0, 1.0), (0.0, 1.0, 1.0), (0.0, 1.0, 1.0)), // oben ((1.0, 1.0, 0.0), (1.0, 1.0, 0.0), (1.0, 1.0, 0.0)), ((1.0, 1.0, 0.0), (1.0, 1.0, 0.0), (1.0, 1.0, 0.0)), // unten ((1.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 0.0, 1.0)), ((1.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 0.0, 1.0))); type TVB = record VAO, VBOvert, // VBO für Vektor. VBOcol: GLuint; // VBO für Farbe. end; const s = 2; l = 2 * s + 1; all = l * l * l; type TCubePos = record pos: TVector3f; end; var CubePosArray: array[0..all - 1] of TCubePos; var VBCube: TVB; FrustumMatrix, WorldMatrix, Matrix: TMatrix; Matrix_ID: GLint; { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin //remove+ Width := 340; Height := 240; //remove- ogc := TContext.Create(Self); ogc.OnPaint := @ogcDrawScene; CreateScene; InitScene; end; (* *) //code+ procedure TForm1.CreateScene; const w = 1.0; begin Matrix.Identity; FrustumMatrix.Frustum(-w, w, -w, w, 2.5, 1000.0); // FrustumMatrix.Perspective(45, 1.0, 2.5, 1000.0); // Alternativ WorldMatrix.Identity; WorldMatrix.Translate(0.0, 0.0, -200.0); // Die Scene in den sichtbaren Bereich verschieben. WorldMatrix.Scale(10.0); // Und der Grösse anpassen. //code- glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); Shader := TShader.Create([FileToStr('Vertexshader.glsl'), FileToStr('Fragmentshader.glsl')]); with Shader do begin UseProgram; Matrix_ID := UniformLocation('Matrix'); end; glGenVertexArrays(1, @VBCube.VAO); glGenBuffers(1, @VBCube.VBOvert); glGenBuffers(1, @VBCube.VBOcol); Timer1.Enabled := True; end; procedure TForm1.InitScene; const d = 1.8; var i:Integer; begin for i := 0 to all - 1 do begin CubePosArray[i].pos.x := ((i mod l)-s) * d; CubePosArray[i].pos.y := ((i div l) mod l-s) * d; CubePosArray[i].pos.z := (i div (l * l)-s) * d; end; glClearColor(0.6, 0.6, 0.4, 1.0); // Hintergrundfarbe glEnable(GL_BLEND); // Alphablending an glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Sortierung der Primitiven von hinten nach vorne. // --- Daten für Würfel glBindVertexArray(VBCube.VAO); // Vektor glBindBuffer(GL_ARRAY_BUFFER, VBCube.VBOvert); glBufferData(GL_ARRAY_BUFFER, sizeof(CubeVertex), @CubeVertex, GL_STATIC_DRAW); glEnableVertexAttribArray(10); // 10 ist die Location in inPos Shader. glVertexAttribPointer(10, 3, GL_FLOAT, False, 0, nil); // Farbe glBindBuffer(GL_ARRAY_BUFFER, VBCube.VBOcol); glBufferData(GL_ARRAY_BUFFER, sizeof(CubeColor), @CubeColor, GL_STATIC_DRAW); glEnableVertexAttribArray(11); // 11 ist die Location in inCol Shader. glVertexAttribPointer(11, 3, GL_FLOAT, False, 0, nil); end; (* Das Zeichnen ist das Selbe wie bei Ortho. *) procedure TForm1.ogcDrawScene(Sender: TObject); procedure QuickSort(var ia: array of TCubePos; ALo, AHi: integer); var Lo, Hi: integer; T, Pivot : TCubePos; begin Lo := ALo; Hi := AHi; Pivot := ia[(Lo + Hi) div 2]; repeat while ia[Lo].pos.z < Pivot.pos.z do begin Inc(Lo); end; while ia[Hi].pos.z > Pivot.pos.z do begin Dec(Hi); end; if Lo <= Hi then begin T := ia[Lo]; ia[Lo] := ia[Hi]; ia[Hi] := T; Inc(Lo); Dec(Hi); end; until Lo > Hi; if Hi > ALo then begin QuickSort(ia, ALo, Hi); end; if Lo < AHi then begin QuickSort(ia, Lo, AHi); end; end; var i: integer; begin glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); // Frame und Tiefen-Buffer löschen. glEnable(GL_CULL_FACE); glCullface(GL_BACK); Shader.UseProgram; glBindVertexArray(VBCube.VAO); QuickSort(CubePosArray, 0, all-1); //code+ // --- Zeichne Würfel for i := 0 to all - 1 do begin Matrix.Identity; Matrix.Translate(CubePosArray[i].pos); // Matrix verschieben. Matrix.Multiply(WorldMatrix, Matrix); // Matrixen multiplizieren. Matrix.Multiply(FrustumMatrix, Matrix); Matrix.Uniform(Matrix_ID); // Matrix dem Shader übergeben. glDrawArrays(GL_TRIANGLES, 0, Length(CubeVertex) * 3); // Zeichnet einen kleinen Würfel. end; //code- ogc.SwapBuffers; end; procedure TForm1.FormDestroy(Sender: TObject); begin Shader.Free; glDeleteVertexArrays(1, @VBCube.VAO); glDeleteBuffers(1, @VBCube.VBOvert); glDeleteBuffers(1, @VBCube.VBOcol); end; procedure TForm1.Timer1Timer(Sender: TObject); var i: Integer; begin for i := 0 to all - 1 do begin CubePosArray[i].pos.RotateA(0.0123); CubePosArray[i].pos.RotateB(0.0234); end; // WorldMatrix.RotateA(0.0123); // Drehe um X-Achse // WorldMatrix.RotateB(0.0234); // Drehe um Y-Achse ogc.Invalidate; end; //lineal (* <b>Vertex-Shader:</b> *) //includeglsl Vertexshader.glsl //lineal (* <b>Fragment-Shader</b> *) //includeglsl Fragmentshader.glsl end.
{ ID:asiapea1 PROG:ratios LANG:PASCAL } program ratios; const zero=1e-5; epsilon=1e-2; var lim,i,j:word; x:array[1..4]of word; b,t:array[1..3]of extended; a:array[1..3,1..3]of extended; // function can (x4:word):boolean; var x1,x2,x3:extended; begin x[4]:=x4; x3:=((a[1,3]*a[2,2]-a[1,2]*a[2,3])*(a[1,2]*b[1]-a[1,1]*b[2])-(a[1,2]*a[2,1]-a[1,1]*a[2,2])*(a[1,3]*b[2]-a[1,2]*b[3]))*x[4]/((a[1,3]*a[2,2]-a[1,2]*a[2,3])*(a[1,2]*a[3,1]-a[1,1]*a[3,2])-(a[1,2]*a[2,1]-a[1,1]*a[2,2])*(a[1,3]*a[3,2]-a[1,2]*a[3,3])); if abs(x3-round(x3))>epsilon then exit(false); x[3]:=round(x3); x2:=((a[1,3]*b[2]-a[1,2]*b[3])*x[4]-(a[1,3]*a[3,2]-a[1,2]*a[3,3])*x[3])/(a[1,3]*a[2,2]-a[1,2]*a[2,3]); if abs(x2-round(x2))>epsilon then exit(false); x[2]:=round(x2); x1:=(b[1]*x[4]-a[3,1]*x[3]-a[2,1]*x[2])/a[1,1]; if abs(x1-round(x1))>epsilon then exit(false); x[1]:=round(x1); exit(true); end; // begin assign(input,'ratios.in'); assign(output,'ratios.out'); reset(input); rewrite(output); for i:=1 to 3 do begin read(b[i]); if b[i]=0 then b[i]:=zero; end; readln; for i:=1 to 3 do begin for j:=1 to 3 do begin read(a[i,j]); if a[i,j]=0 then a[i,j]:=zero; end; readln; end; t[1]:=(a[1,1]*100+a[2,1]*100+a[3,1]*100)/b[1]; t[2]:=(a[1,2]*100+a[2,2]*100+a[3,2]*100)/b[2]; t[3]:=(a[1,3]*100+a[2,3]*100+a[3,3]*100)/b[3]; lim:=maxsmallint*2+1; for i:=1 to 3 do if trunc(t[i])<lim then lim:=trunc(t[i]); i:=1; while (i<=lim) and not can(i) do inc(i); if i>lim then writeln('NONE') else writeln(x[1],' ',x[2],' ',x[3],' ',x[4]); close(output); end.
{***************************************************************************} { Copyright 2021 Google LLC } { } { 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 } { } { https://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 EC; interface uses BitStr; const ECLevelAny = -1; ECLevelL = 1; ECLevelM = 0; ECLevelQ = 3; ECLevelH = 2; QRVersionAny = -1; type ECInfo = object Version: Byte; Level: Byte; ECWordsPerBlock: Byte; BlocksInGroup1: Byte; Block1Len: Byte; BlocksInGroup2: Byte; Block2Len: Byte; function TotalBlocks: Integer; function TotalDataWords: Integer; function TotalECWords: Integer; function TotalWords: Integer; function BlockOffset(block: Byte): Integer; function BlockLen(block: Byte): Integer; function ECBlockOffset(block: Byte): Integer; end; ECInfoPtr = ^ECInfo; const ECInfoTotal = 8*4; ECInfoTable: array[1..ECInfoTotal] of ECInfo = ( ( Version:1; Level:ECLevelL; EcWordsPerBlock:7; BlocksInGroup1: 1; Block1Len: 19; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:1; Level:ECLevelM; EcWordsPerBlock:10; BlocksInGroup1: 1; Block1Len: 16; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:1; Level:ECLevelQ; EcWordsPerBlock:13; BlocksInGroup1: 1; Block1Len: 13; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:1; Level:ECLevelH; EcWordsPerBlock:17; BlocksInGroup1: 1; Block1Len: 9; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:2; Level:ECLevelL; EcWordsPerBlock:10; BlocksInGroup1: 1; Block1Len: 34; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:2; Level:ECLevelM; EcWordsPerBlock:16; BlocksInGroup1: 1; Block1Len: 28; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:2; Level:ECLevelQ; EcWordsPerBlock:22; BlocksInGroup1: 1; Block1Len: 22; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:2; Level:ECLevelH; EcWordsPerBlock:28; BlocksInGroup1: 1; Block1Len: 16; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:3; Level:ECLevelL; EcWordsPerBlock:15; BlocksInGroup1: 1; Block1Len: 55; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:3; Level:ECLevelM; EcWordsPerBlock:26; BlocksInGroup1: 1; Block1Len: 44; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:3; Level:ECLevelQ; EcWordsPerBlock:18; BlocksInGroup1: 2; Block1Len: 17; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:3; Level:ECLevelH; EcWordsPerBlock:22; BlocksInGroup1: 2; Block1Len: 13; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:4; Level:ECLevelL; EcWordsPerBlock:20; BlocksInGroup1: 1; Block1Len: 80; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:4; Level:ECLevelM; EcWordsPerBlock:18; BlocksInGroup1: 2; Block1Len: 32; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:4; Level:ECLevelQ; EcWordsPerBlock:26; BlocksInGroup1: 2; Block1Len: 24; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:4; Level:ECLevelH; EcWordsPerBlock:16; BlocksInGroup1: 4; Block1Len: 9; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:5; Level:ECLevelL; EcWordsPerBlock:26; BlocksInGroup1: 1; Block1Len: 108; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:5; Level:ECLevelM; EcWordsPerBlock:24; BlocksInGroup1: 2; Block1Len: 43; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:5; Level:ECLevelQ; EcWordsPerBlock:18; BlocksInGroup1: 2; Block1Len: 15; BlocksInGroup2: 2; Block2Len: 16 ), ( Version:5; Level:ECLevelH; EcWordsPerBlock:22; BlocksInGroup1: 2; Block1Len: 11; BlocksInGroup2: 2; Block2Len: 12 ), ( Version:6; Level:ECLevelL; EcWordsPerBlock:18; BlocksInGroup1: 2; Block1Len: 68; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:6; Level:ECLevelM; EcWordsPerBlock:16; BlocksInGroup1: 4; Block1Len: 27; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:6; Level:ECLevelQ; EcWordsPerBlock:24; BlocksInGroup1: 4; Block1Len: 19; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:6; Level:ECLevelH; EcWordsPerBlock:28; BlocksInGroup1: 4; Block1Len: 15; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:7; Level:ECLevelL; EcWordsPerBlock:20; BlocksInGroup1: 2; Block1Len: 78; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:7; Level:ECLevelM; EcWordsPerBlock:18; BlocksInGroup1: 4; Block1Len: 31; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:7; Level:ECLevelQ; EcWordsPerBlock:18; BlocksInGroup1: 2; Block1Len: 14; BlocksInGroup2: 4; Block2Len: 15 ), ( Version:7; Level:ECLevelH; EcWordsPerBlock:26; BlocksInGroup1: 4; Block1Len: 13; BlocksInGroup2: 1; Block2Len: 14 ), ( Version:8; Level:ECLevelL; EcWordsPerBlock:24; BlocksInGroup1: 2; Block1Len: 97; BlocksInGroup2: 0; Block2Len: 0 ), ( Version:8; Level:ECLevelM; EcWordsPerBlock:22; BlocksInGroup1: 2; Block1Len: 38; BlocksInGroup2: 2; Block2Len: 39 ), ( Version:8; Level:ECLevelQ; EcWordsPerBlock:22; BlocksInGroup1: 4; Block1Len: 18; BlocksInGroup2: 2; Block2Len: 19 ), ( Version:8; Level:ECLevelH; EcWordsPerBlock:26; BlocksInGroup1: 4; Block1Len: 14; BlocksInGroup2: 2; Block2Len: 15 ) ); MaxECWords = 194; { 8-L } function FindECInfo(version, level: Integer; length: Integer): ECInfoPtr; procedure CalculateEC(buf: ByteBufferPtr; info: ECInfoPtr); implementation type ExpLogTableEntry = record Log, Exp: Word; end; ExpLogTable = Array[0..255] of ExpLogTableEntry; var ExpLog: ExpLogTable; tmpbuf: Array[0..MaxECWords] of Byte; g, msg: Array[0..255] of Byte; procedure InitExpLog; var i, exp: Word; begin exp := 1; ExpLog[0].Exp := exp; ExpLog[1].Log := 0; for i := 1 to 255 do begin exp := exp * 2; if exp >= 256 then exp := exp xor 285; ExpLog[i].Exp := exp; ExpLog[exp].Log := (i mod 255); end; end; function PolyMul(x, y: Byte): Byte; begin if (x <> 0) and (y <> 0) then begin PolyMul := ExpLog[(ExpLog[x].Log + ExpLog[y].Log) mod 255].Exp; end else PolyMul := 0; end; function ECInfo.TotalDataWords: Integer; begin TotalDataWords := BlocksInGroup1 * Block1Len + BlocksInGroup2 * Block2Len; end; function ECInfo.TotalBlocks: Integer; begin TotalBlocks := BlocksInGroup1 + BlocksInGroup2; end; function ECInfo.TotalECWords: Integer; begin TotalECWords := TotalBlocks * ECWordsPerBlock; end; function ECInfo.TotalWords: Integer; begin TotalWords := TotalECWords + TotalDataWords; end; function ECInfo.BlockOffset(block: Byte): Integer; begin if block < BlocksInGroup1 then BlockOffset := block * Block1Len else BlockOffset := BlocksInGroup1 * Block1Len + (block - BlocksInGroup1) * Block2Len; end; function ECInfo.BlockLen(block: Byte): Integer; begin if block < BlocksInGroup1 then BlockLen := Block1Len else BlockLen := Block2Len; end; function ECInfo.ECBlockOffset(block: Byte): Integer; begin ECBlockOffset := TotalDataWords + block * ECWordsPerBlock; end; procedure CalculateECBlock(buf: ByteBufferPtr; dataOffset, dataLen, ecOffset, ecLen: Word); var i, j, alpha: Word; { Generative and message polynomials } begin for i := 0 to SizeOf(g) - 1 do begin g[i] := 0; msg[i] := 0; end; { Create generative polynomial } g[0] := 1; g[1] := 1; for j := 1 to ecLen - 1 do begin alpha := ExpLog[j].Exp; for i := j+1 downto 1 do g[i] := PolyMul(alpha, g[i]) xor g[i-1]; g[0] := PolyMul(g[0], alpha); end; for j := dataLen - 1 downto 0 do msg[j + ecLen] := buf^[dataOffset + (dataLen - 1 - j)]; { msg mod g } for j := dataLen + ecLen - 1 downto ecLen do begin alpha := msg[j]; for i := ecLen downto 0 do msg[j - (ecLen - i)] := msg[j - (ecLen - i)] xor PolyMul(g[i], alpha); end; { copy back EC data } for i := ecLen - 1 downto 0 do buf^[ecOffset + ecLen - i - 1] := msg[i]; end; procedure CalculateEC(buf: ByteBufferPtr; info: ECInfoPtr); var i, col,ptr: Integer; begin { create a scratchpad copy to work with } for i := 0 to info^.TotalDataWords - 1 do tmpbuf[i] := buf^[i]; for i := 0 to info^.TotalBlocks - 1 do CalculateECBlock(@tmpbuf, info^.BlockOffset(i), info^.BlockLen(i), info^.ECBlockOffset(i), info^.ECWordsPerBlock); { interleave data } ptr := 0; col := 0; while ptr < info^.TotalDataWords do begin for i := 0 to info^.TotalBlocks - 1 do begin if col < info^.BlockLen(i) then begin buf^[ptr] := tmpbuf[info^.BlockOffset(i) + col]; ptr := ptr + 1; end; end; col := col + 1; end; { interleave EC } ptr := info^.TotalDataWords; col := 0; while ptr < info^.TotalWords do begin for i := 0 to info^.TotalBlocks - 1 do begin buf^[ptr] := tmpbuf[info^.ECBlockOffset(i) + col]; ptr := ptr + 1; end; col := col + 1; end; end; function FindECInfo(version, level, length: Integer): ECInfoPtr; var i: Integer; minTotal: Integer; info: ECInfoPtr; match: Boolean; begin info := Nil; minTotal := $7000; { some ridiculously high value } for i := 1 to ECInfoTotal do begin match := (version = QRVersionAny) or (ECInfoTable[i].version = version); match := match and ((level = ECLevelAny) or (ECInfoTable[i].level = level)); if match and (ECInfoTable[i].TotalDataWords >= length) and (ECInfoTable[i].TotalDataWords < minTotal) then begin minTotal := ECInfoTable[i].TotalDataWords; info := @ECInfoTable[i]; end; end; FindECInfo := info; end; begin InitExpLog; end.
unit config; {$DEFINE IP} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, DB, Wwdbgrid; type TConfig = class private FileName:string; Section:string; FItems,FDefaults:TStrings; procedure Update; public constructor Create(FileName:string; const DefaultValues:string); destructor Destroy; override; procedure Load(FileName:string=''); procedure Save(FileName:string=''); procedure setString(id:string; value:string); procedure setInteger(id:string; value:integer); procedure setBoolean(id:string; value:boolean); procedure setMem(id:string; value:string); function getString(id:string):string; overload; function getInteger(id:string; def:integer=0):integer; overload; function getBoolean(id:string; def:boolean=false):boolean; overload; function getMem(id:string):string; overload; procedure readBounds(id:string; Control:TControl); procedure writeBounds(id:string; Control:TControl); procedure writeFields(id:string; Dataset:TDataset); procedure readFields(id:string; Dataset:TDataset); procedure writeColumns(id:string; Grid:TwwDBGrid); procedure readColumns(id:string; Grid:TwwDBGrid); property Items:TStrings read FItems; property Defaults:TStrings read FDefaults; end; var CurrentConfig: TConfig; implementation uses DyUtils; constructor TConfig.Create(FileName:string; const DefaultValues:string); begin self.FileName:=FileName; Section:='config'; FDefaults:=TStringList.Create; FDefaults.Text:=DefaultValues; Fitems:=TStringList.Create; load; end; destructor TConfig.Destroy; begin save; Fitems.Free; FDefaults.Free; inherited; end; procedure TConfig.Update; var i:integer; key:string; begin for i:=0 to FDefaults.count-1 do begin key:=FDefaults.Names[i]; if FItems.Values[key]='' then FItems.Values[key]:=FDefaults.Values[key]; end; end; procedure TConfig.Load(FileName:string=''); begin if FileName='' then FileName:=self.FileName; if FileExists(FileName) then Fitems.LoadFromFile(FileName) else Fitems.Clear; Update; end; procedure TConfig.Save(FileName:string=''); var i:integer; key:string; begin for i:=0 to FDefaults.count-1 do begin key:=FDefaults.Names[i]; if FItems.Values[key]=FDefaults.Values[key] then FItems.Values[key]:=''; end; if FileName='' then FileName:=self.FileName; Fitems.SaveToFile(FileName); end; procedure TConfig.setString(id:string; value:string); begin Fitems.values[id]:=value; end; function TConfig.getString(id:string):string; begin result:=Fitems.values[id]; if result='' then result:=fdefaults.values[id]; end; procedure TConfig.setMem(id:string; value:string); begin Fitems.values[id]:=MemToStr(value); end; function TConfig.getMem(id:string):string; begin result:=Fitems.values[id]; if result='' then result:=fdefaults.values[id]; result:=StrToMem(result); end; procedure TConfig.setInteger(id:string; value:integer); begin setString(id,intToStr(value)); end; function TConfig.getInteger(id:string; def:integer=0):integer; var value:string; begin try value:=getString(id); if value='' then result:=def else result:=StrToInt(value); except result:=def end; end; procedure TConfig.setBoolean(id:string; value:boolean); begin if value then setString(id,'1') else setString(id,'0'); end; function TConfig.getBoolean(id:string; def:boolean=false):boolean; var value:string; begin try value:=getString(id); if value='' then result:=def else result:=StrToInt(value)<>0; except result:=def end; end; procedure TConfig.readBounds(id:string; Control:TControl); begin Control.Left:=getInteger(id+'.left',Control.Left); Control.Top:=getInteger(id+'.top',Control.Top); Control.Width:=getInteger(id+'.width',Control.Width); Control.Height:=getInteger(id+'.height',Control.Height); if Control.Width > Screen.Width then Control.Width := Screen.Width; if Control.Height > Screen.Height then Control.Height := Screen.Height; if Control.Left < 0 then Control.Left := 0 else if Control.Left > Control.Width then Control.Left := Control.Width - 5; if Control.Top < 0 then Control.Top := 0 else if Control.Top > Control.Height then Control.Top := Control.Height - 5; if (Control is TForm) then begin if getInteger(id+'.showcmd',SW_SHOW)=SW_SHOWMAXIMIZED then TForm(Control).WindowState:=wsMaximized; end; end; procedure TConfig.writeBounds(id:string; Control:TControl); var Placement:TWindowPlacement; begin Placement.Length:=SizeOf(Placement); if (Control is TForm) and GetWindowPlacement(TForm(Control).Handle,@Placement) then with Placement do begin setInteger(id+'.showcmd',ShowCmd); setInteger(id+'.left',rcNormalPosition.Left); setInteger(id+'.top',rcNormalPosition.Top); setInteger(id+'.width',rcNormalPosition.Right-rcNormalPosition.Left); setInteger(id+'.height',rcNormalPosition.Bottom-rcNormalPosition.Top); end else begin setInteger(id+'.left',Control.Left); setInteger(id+'.top',Control.Top); setInteger(id+'.width',Control.Width); setInteger(id+'.height',Control.Height); end; end; procedure TConfig.writeFields(id:string; Dataset:TDataset); var i:integer; S:string; begin with Dataset do for i:=0 to FieldCount-1 do if Fields[i].Visible then begin S:=id+'.'+Fields[i].FieldName; setInteger(S+'.DisplayWidth',Fields[i].DisplayWidth); setInteger(S+'.Index',Fields[i].Index); end; end; procedure TConfig.readFields(id:string; Dataset:TDataset); var i,N:integer; S:string; Pos:array of TField; begin SetLength(Pos,Dataset.FieldCount); with Dataset do begin for i:=0 to FieldCount-1 do try S:=id+'.'+Fields[i].FieldName; Fields[i].DisplayWidth:=getInteger(S+'.DisplayWidth',Fields[i].DisplayWidth); Fields[i].Visible:=getBoolean(S+'.Visible',Fields[i].Visible); N:=getInteger(S+'.Index',-1); if N>=0 then Pos[N]:=Fields[i]; except end; for i:=0 to FieldCount-1 do if Pos[i]<>nil then Pos[i].Index:=i; end; end; // не работает procedure TConfig.writeColumns(id:string; Grid:TwwDBGrid); var i: integer; S: string; begin with Grid do for i := 0 to Grid.GetColCount - 1 do begin S := id + '.' + Columns[i].FieldName; setInteger(S + '.DisplayWidth', Columns[i].DisplayWidth); //setInteger(S + '.Index', Columns[i].Index); end; end; // не работает procedure TConfig.readColumns(id:string; Grid:TwwDBGrid); var i: integer; S: string; begin with Grid do for i := 0 to GetColCount - 1 do begin S := id + '.' + Columns[i].FieldName; Columns[i].DisplayWidth := getInteger(S + '.DisplayWidth', Fields[i].DisplayWidth); end; end; end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.ActionSheet; interface {$SCOPEDENUMS ON} uses System.Classes, FMX.Platform, FMX.Types, FGX.ActionSheet.Types, FGX.Consts; type { TfgActionSheet } TfgCustomActionSheet = class(TFmxObject) public const DefaultUseUIGuidline = True; private FActions: TfgActionsCollections; FUseUIGuidline: Boolean; FTitle: string; FActionSheetService: IFGXActionSheetService; procedure SetActions(const Value: TfgActionsCollections); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Show; virtual; function Supported: Boolean; property ActionSheetService: IFGXActionSheetService read FActionSheetService; public property Actions: TfgActionsCollections read FActions write SetActions; property UseUIGuidline: Boolean read FUseUIGuidline write FUseUIGuidline default DefaultUseUIGuidline; property Title: string read FTitle write FTitle; end; [ComponentPlatformsAttribute(fgMobilePlatforms)] TfgActionSheet = class(TfgCustomActionSheet) published property Actions; property UseUIGuidline; property Title; end; implementation uses System.SysUtils, FGX.Asserts {$IFDEF IOS} , FGX.ActionSheet.iOS {$ENDIF} {$IFDEF ANDROID} , FGX.ActionSheet.Android {$ENDIF} ; { TActionSheet } constructor TfgCustomActionSheet.Create(AOwner: TComponent); begin inherited Create(AOwner); FActions := TfgActionsCollections.Create(Self); FUseUIGuidline := DefaultUseUIGuidline; TPlatformServices.Current.SupportsPlatformService(IFGXActionSheetService, FActionSheetService); end; destructor TfgCustomActionSheet.Destroy; begin FActionSheetService := nil; FreeAndNil(FActions); inherited Destroy; end; procedure TfgCustomActionSheet.SetActions(const Value: TfgActionsCollections); begin AssertIsNotNil(Value); FActions.Assign(Value); end; procedure TfgCustomActionSheet.Show; begin if Supported then FActionSheetService.Show(Title, Actions, UseUIGuidline); end; function TfgCustomActionSheet.Supported: Boolean; begin Result := ActionSheetService <> nil; end; initialization RegisterFmxClasses([TfgCustomActionSheet, TfgActionSheet]); {$IF Defined(IOS) OR Defined(ANDROID)} RegisterService; {$ENDIF} end.
unit Finance.StockPrice; interface uses Finance.interfaces, System.JSON, System.Generics.Collections; type TFinanceStockPrice = class(TInterfacedObject, iFinanceStockPrice) private FParent : iFinance; FCode : string; FName : string; FPrice : string; FChangePercent : string; public constructor Create(Parent : iFinance); destructor Destroy; override; function Code : string; function Name : string; function Price : string; function ChangePercent : string; function SetJSON( value : TJSONObject ) : iFinanceStockPrice; function &End : iFinance; end; implementation uses Injection; { TFinanceStockPrice } function TFinanceStockPrice.ChangePercent: string; begin Result := FChangePercent; end; function TFinanceStockPrice.Code: string; begin Result := FCode; end; constructor TFinanceStockPrice.Create(Parent: iFinance); begin TInjection.Weak(@FParent, Parent); end; destructor TFinanceStockPrice.Destroy; begin inherited; end; function TFinanceStockPrice.&End: iFinance; begin Result := FParent; end; function TFinanceStockPrice.Name: string; begin Result := FName; end; function TFinanceStockPrice.Price: string; begin Result := FPrice; end; function TFinanceStockPrice.SetJSON(value: TJSONObject): iFinanceStockPrice; begin Result := Self; FCode := value.Pairs[0].JsonString.Value; FName := value.Pairs[1].JsonValue.Value; FPrice := value.Pairs[10].JsonValue.Value; FChangePercent := value.Pairs[11].JsonValue.Value; end; end.
unit xDL645Thread; interface uses System.Types, xProtocolPacks, System.Classes, system.SysUtils, xDL645Type, xFunction, xMeterDataRect, xThreadBase, xProtocolPacksDl645, xProtocolPacksDL645_07, xProtocolPacksDL645_97, xProtocolDL645; type TDL645Thread = class(TThreadBase) private FProrocolType: TDL645_PROTOCOL_TYPE; FOnRev645Data: TGet645Data; FMeterAddr: string; FDL645_97BaudRate: string; FDL645_07BaudRate: string; FIsWairtForComm: Boolean; procedure SetProrocolType(const Value: TDL645_PROTOCOL_TYPE); /// <summary> /// 接收数据 /// </summary> procedure Rve645Data( A645data : TStringList ); virtual; protected procedure SetMeterAddr(const Value: string); virtual; public constructor Create(CreateSuspended: Boolean);override; destructor Destroy; override; /// <summary> /// 执行命令 /// </summary> /// <param name="ACmdType">命令类型</param> /// <param name="ADevice">命令对象</param> /// <param name="bWairtExecute">是否等待执行完命令才推出函数</param> procedure AddOrder( ACmdType: Integer; ADevice: TObject; bWairtExecute : Boolean = True); override; /// <summary> /// 协议类型 /// </summary> property ProrocolType : TDL645_PROTOCOL_TYPE read FProrocolType write SetProrocolType; /// <summary> /// DL645-2007波特率 默认2400 /// </summary> property DL645_07BaudRate : string read FDL645_07BaudRate write FDL645_07BaudRate; /// <summary> /// DL645-1997波特率 默认1200 /// </summary> property DL645_97BaudRate : string read FDL645_97BaudRate write FDL645_97BaudRate; /// <summary> /// 是否等待通讯完成才继续 /// </summary> property IsWairtForComm : Boolean read FIsWairtForComm write FIsWairtForComm; /// <summary> /// 通讯地址 /// </summary> property MeterAddr : string read FMeterAddr write SetMeterAddr; /// <summary> /// 读数据 /// </summary> procedure ReadMeterData( nSign, nLen : Int64; sFormt : string); /// <summary> /// 读后续数据 /// </summary> procedure ReadMeterDataNext( nSign, nLen : Int64; sFormt : string; nDataPackS : Integer); /// <summary> /// 读取给定时间的负荷记录块 /// </summary> procedure ReadLoadRecord(nSign, nLen : Int64; sFormt : string; dtTime: TDateTime; nNum:Integer); /// <summary> /// 广播校时 /// </summary> procedure ResetDateTime( dtDateTime : TDateTime ); /// <summary> /// 读通信地址 /// </summary> procedure ReadMeterAddr; /// <summary> /// 写数据 /// </summary> procedure WriteData( nSign:Int64; nLen : Integer; sFormt, sValue : string ); /// <summary> /// 写通讯地址 /// </summary> procedure WriteMeterAddr( nAddr : Int64 ); /// <summary> /// 冻结命令 /// </summary> procedure Freeze(dtDateTime: TDateTime; FreezeType: TDL645_07_FREEZE_TYPE); /// <summary> /// 改波特率 /// </summary> procedure ChangeBaudRate( nBaudRate : Integer ); /// <summary> /// 改密码 /// </summary> procedure ChangePWD( nNewPWD : Integer ); /// <summary> /// 最大需量清零 /// </summary> procedure ClearMaxDemand; /// <summary> /// 电表清零 /// </summary> procedure ClearData; /// <summary> /// 事件清零 /// </summary> procedure ClearEvent(nSign: Int64; AEventType: TDL645_07_CLEAREVENT_TYPE); /// <summary> /// 设置多功能口输出 /// </summary> procedure SetWOutType(AType : TMOUT_TYPE); /// <summary> /// 身份认证 /// </summary> procedure IdentityAuthentication( nSign:Int64; nLen : Integer; sFormt, sValue : string ); /// <summary> /// 费控操作 拉合闸 等 拉合闸 密文 20个字节 /// </summary> procedure OnOffControl( nLen : Integer; sValue : string ); /// <summary> /// 接收数据事件 /// </summary> property OnRev645Data : TGet645Data read FOnRev645Data write FOnRev645Data; end; implementation { TDL645Thread } procedure TDL645Thread.AddOrder(ACmdType: Integer; ADevice: TObject; bWairtExecute: Boolean); begin if Assigned(ADevice) and (ADevice is TDL645_DATA) then begin TDL645_DATA(ADevice).MeterProtocolType := FProrocolType; TDL645_DATA(ADevice).OrderType := ACmdType; end; inherited; end; procedure TDL645Thread.ChangeBaudRate(nBaudRate: Integer); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataSend := IntToStr(nBaudRate); ARevData.Address := FMeterAddr; AddOrder( C_645_CHANGE_BAUD_RATE, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ChangePWD(nNewPWD: Integer); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.MeterProtocolType := FProrocolType; ARevData.DataSend := IntToStr(nNewPWD); ARevData.Address := FMeterAddr; AddOrder( C_645_CHANGE_PWD, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ClearData; var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.Address := FMeterAddr; ARevData.MeterProtocolType := FProrocolType; AddOrder( C_645_CLEAR_RDATA, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ClearEvent(nSign: Int64; AEventType: TDL645_07_CLEAREVENT_TYPE); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.ClearEventTYPE := AEventType; ARevData.Address := FMeterAddr; ARevData.DataSign := nSign; AddOrder( C_645_CLEAR_REVENT, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ClearMaxDemand; var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.Address := FMeterAddr; AddOrder( C_645_CLEAR_MAX_DEMAND, ARevData, FIsWairtForComm); end; constructor TDL645Thread.Create(CreateSuspended: Boolean); begin inherited; FProtocol := TProtocolDL645.Create; SetProrocolType(dl645pt2007); TProtocolDL645(FProtocol).OnRev645Data := Rve645Data; FProtocol.OrderTimeOut := 2000; FMeterAddr := 'AAAAAAAAAAAA'; FDL645_97BaudRate:= '1200'; FDL645_07BaudRate:= '2400'; FIsWairtForComm := True; end; destructor TDL645Thread.Destroy; begin inherited; end; procedure TDL645Thread.Freeze(dtDateTime: TDateTime; FreezeType: TDL645_07_FREEZE_TYPE); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.FreezeType := FreezeType; ARevData.DateTimeValue := dtDateTime; ARevData.Address := FMeterAddr; AddOrder( C_645_FREEZE, ARevData, FIsWairtForComm); end; procedure TDL645Thread.IdentityAuthentication(nSign: Int64; nLen: Integer; sFormt, sValue: string); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataSign := nSign; ARevData.DataLen := nLen; ARevData.DataFormat := sFormt; ARevData.DataSend := sValue; ARevData.Address := FMeterAddr; AddOrder( C_645_IDENTITY, ARevData, FIsWairtForComm); end; procedure TDL645Thread.OnOffControl(nLen: Integer; sValue: string); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataLen := nLen; ARevData.DataSend := sValue; ARevData.Address := FMeterAddr; AddOrder( C_645_ONOFF_CONTROL, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ReadLoadRecord(nSign, nLen: Int64; sFormt: string; dtTime: TDateTime; nNum: Integer); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataSign := nSign; ARevData.DataLen := nLen; ARevData.DataFormat := sFormt; ARevData.Address := FMeterAddr; ARevData.DateTimeValue := dtTime; ARevData.BlockNum := nNum; if (ARevData.DateTimeValue > 1) and (ARevData.BlockNum > 0) then ARevData.ReadLoadRecord := 2; AddOrder( C_645_READ_DATA, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ReadMeterAddr; var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.OrderType := C_645_READ_ADDR; AddOrder( C_645_READ_ADDR, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ReadMeterData(nSign, nLen: Int64; sFormt: string); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataSign := nSign; ARevData.DataLen := nLen; ARevData.DataFormat := sFormt; ARevData.Address := FMeterAddr; AddOrder( C_645_READ_DATA, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ReadMeterDataNext(nSign, nLen: Int64; sFormt: string; nDataPackS: Integer); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataSign := nSign; ARevData.DataLen := nLen; ARevData.DataFormat := sFormt; ARevData.Address := FMeterAddr; ARevData.DataPackSN := nDataPackS; AddOrder( C_645_READ_NEXTDATA, ARevData, FIsWairtForComm); end; procedure TDL645Thread.ResetDateTime(dtDateTime: TDateTime); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DateTimeValue := dtDateTime; AddOrder( C_645_RESET_TIME, ARevData, FIsWairtForComm); end; procedure TDL645Thread.Rve645Data(A645data: TStringList); var i: Integer; sReply: string; begin for i := 0 to A645data.Count - 1 do begin if TDL645_DATA(A645data.Objects[i]).RePlyError = de645_07None then begin sReply := TDL645_DATA(A645data.Objects[i]).DataReply; if Pos('X', TDL645_DATA(A645data.Objects[i]).DataFormat) > 0 then begin TDL645_DATA(A645data.Objects[i]).DataReply := PacksToStr(StrToBCDPacks(sReply)); end else begin if sReply <> '' then begin TDL645_DATA(A645data.Objects[i]).DataReply := sReply; end; end; end; end; if Assigned(FOnRev645Data) then FOnRev645Data(A645data); end; procedure TDL645Thread.SetMeterAddr(const Value: string); var i: Integer; begin FMeterAddr := Value; if Length(FMeterAddr) > 12 then FMeterAddr := Copy(FMeterAddr, 1, 12) else if Length(FMeterAddr) < 12 then begin for i := Length(FMeterAddr) to 12 - 1 do FMeterAddr := '0' + FMeterAddr; end; end; procedure TDL645Thread.SetProrocolType(const Value: TDL645_PROTOCOL_TYPE); begin FProrocolType := Value; if Assigned(FProtocol) then TProtocolDL645(FProtocol).ProrocolType := FProrocolType; end; procedure TDL645Thread.SetWOutType(AType: TMOUT_TYPE); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataSend := IntToStr(Integer(AType)); ARevData.Address := FMeterAddr; AddOrder( C_SET_WOUT_TYPE, ARevData, FIsWairtForComm); end; procedure TDL645Thread.WriteData(nSign: Int64; nLen: Integer; sFormt, sValue: string); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataSign := nSign; ARevData.DataLen := nLen; ARevData.DataFormat := sFormt; ARevData.DataSend := sValue; ARevData.Address := FMeterAddr; AddOrder( C_645_WRITE_DATA, ARevData, FIsWairtForComm); end; procedure TDL645Thread.WriteMeterAddr(nAddr: Int64); var ARevData:TDL645_DATA; begin ARevData:= TDL645_DATA.Create; ARevData.DataSend := IntToStr(nAddr); ARevData.Address := FMeterAddr; AddOrder( C_645_WRITE_ADDR, ARevData, FIsWairtForComm); end; end.
unit ADAPT.UnitTests.Generics.Lists; interface {$I ADAPT.inc} uses {$IFDEF ADAPT_USE_EXPLICIT_UNIT_NAMES} System.Classes, System.SysUtils, {$ELSE} Classes, SysUtils, {$ENDIF ADAPT_USE_EXPLICIT_UNIT_NAMES} DUnitX.TestFramework, ADAPT.Intf, ADAPT.Collections.Intf; type [TestFixture] TADUTCollectionsArray = class(TObject) public [Test] procedure BasicIntegrity; [Test] procedure ReaderIntegrity; [Test] procedure SetCapacity; [Test] procedure SetItem; [Test] procedure Clear; [Test] procedure DeleteOne; [Test] procedure DeleteRange; [Test] procedure InsertMiddle; [Test] procedure InsertFirst; [Test] procedure InsertLast; end; [TestFixture] TADUTCollectionsExpander = class(TObject) end; [TestFixture] TADUTCollectionsExpanderGeometric = class(TObject) end; [TestFixture] TADUTCollectionsCompactor = class(TObject) end; [TestFixture] TADUTCollectionsList = class(TObject) [Test] procedure BasicIntegrity; [Test] procedure ReaderIntegrity; [Test] procedure SetItem; [Test] procedure Clear; [Test] procedure DeleteOne; [Test] procedure DeleteRange; [Test] procedure InsertMiddle; [Test] procedure InsertFirst; [Test] procedure InsertLast; [Test] procedure Sort; [Test] procedure SortRange; end; [TestFixture] TADUTCollectionsSortedList = class(TObject) [Test] procedure BasicIntegrity; [Test] procedure ReaderIntegrity; [Test] procedure Contains; [Test] procedure IndexOf; [Test] procedure Remove; end; [TestFixture] TADUTCollectionsCircularList = class(TObject) [Test] procedure BasicIntegrity; [Test] procedure ReaderIntegrity; [Test] procedure CircularIntegrity; end; [TestFixture] TADUTCollectionsMap = class(TObject) public [Test] procedure BasicIntegrity; end; [TestFixture] TADUTCollectionsCircularMap = class(TObject) public [Test] procedure BasicIntegrity; [Test] procedure CircularIntegrity; end; [TestFixture] TADUTCollectionsTree = class(TObject) public [Test] procedure BasicIntegrity; end; [TestFixture] TADUTCollectionsStackQueue = class(TObject) public [Test] procedure BasicIntegrity; end; implementation uses ADAPT, ADAPT.Collections, ADAPT.Comparers, ADAPT.Math.Delta; type // Specialized Interfaces IADStringArray = IADArray<String>; IADStringArrayReader = IADArrayReader<String>; IADStringList = IADList<String>; IADStringListReader = IADListReader<String>; IADStringCircularList = IADCircularList<String>; IADStringCircularListReader = IADCircularListReader<String>; IADStringSortedList = IADSortedList<String>; IADStringStringMap = IADMap<String, String>; IADStringTreeNodeReader = IADTreeNodeReader<String>; IADStringTreeNode = IADTreeNode<String>; // Specialized Classes TADStringArray = TADArray<String>; TADStringList = TADList<String>; TADStringSortedList = TADSortedList<String>; TADStringCircularList = TADCircularList<String>; TADStringStringMap = TADMap<String, String>; TADStringStringCircularMap = TADCircularMap<String, String>; TADStringTreeNode = TADTreeNode<String>; TMapTestItem = record Key: String; Value: String; end; const BASIC_ITEMS: Array[0..9] of String = ( 'Bob', 'Terry', 'Andy', 'Rick', 'Sarah', 'Ellen', 'Hugh', 'Jack', 'Marie', 'Ninette' ); BASIC_ITEMS_SORTED: Array[0..9] of String = ( 'Andy', 'Bob', 'Ellen', 'Hugh', 'Jack', 'Marie', 'Ninette', 'Rick', 'Sarah', 'Terry' ); BASIC_ITEMS_HALF_SORTED: Array[0..9] of String = ( 'Andy', 'Bob', 'Rick', 'Sarah', 'Terry', 'Ellen', 'Hugh', 'Jack', 'Marie', 'Ninette' ); MAP_ITEMS: Array[0..9] of TMapTestItem = ( (Key: 'Foo'; Value: 'Bar'), (Key: 'Donald'; Value: 'Duck'), (Key: 'Mickey'; Value: 'Mouse'), (Key: 'Winnie'; Value: 'Pooh'), (Key: 'Goof'; Value: 'Troop'), (Key: 'Tale'; Value: 'Spin'), (Key: 'Captain'; Value: 'Kangaroo'), (Key: 'Major'; Value: 'Tom'), (Key: 'Gummie'; Value: 'Bears'), (Key: 'Whacky'; Value: 'Races') ); MAP_ITEMS_SORTED: Array[0..9] of TMapTestItem = ( (Key: 'Captain'; Value: 'Kangaroo'), (Key: 'Donald'; Value: 'Duck'), (Key: 'Foo'; Value: 'Bar'), (Key: 'Goof'; Value: 'Troop'), (Key: 'Gummie'; Value: 'Bears'), (Key: 'Major'; Value: 'Tom'), (Key: 'Mickey'; Value: 'Mouse'), (Key: 'Tale'; Value: 'Spin'), (Key: 'Whacky'; Value: 'Races'), (Key: 'Winnie'; Value: 'Pooh') ); { TADUTCollectionsArray } procedure TADUTCollectionsArray.BasicIntegrity; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Test Capacity has been Initialized Assert.IsTrue(LArray.Capacity = 10, Format('Capacity Expected 10, got %d', [LArray.Capacity])); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Make sure they match! for I := 0 to LArray.Capacity - 1 do Assert.IsTrue(LArray.Items[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LArray.Items[I]])); end; procedure TADUTCollectionsArray.Clear; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Increase Capacity LArray.Capacity := 15; // Clear the Array LArray.Clear; // Capacity should return to 10 Assert.IsTrue(LArray.Capacity = 10, Format('Capacity Expected 10, got %d', [LArray.Capacity])); // There should be no items in the Array, so attempting to reference any should result in an Access Violation Exception. Assert.WillRaiseAny(procedure begin LArray[0]; end, 'Item 0 request should have raised an Exception, it did not! List must not be empty!'); end; procedure TADUTCollectionsArray.DeleteOne; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Test Capacity has been Initialized Assert.IsTrue(LArray.Capacity = 10, Format('Capacity Expected 10, got %d', [LArray.Capacity])); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Remove Item 5 LArray.Delete(5); // Item 5 should now equal Item 6 in the BASIC_ITEMS Array. Assert.IsTrue(LArray[5] = BASIC_ITEMS[6], Format('Array Item 5 should be "%s" but instead got "%s".', [BASIC_ITEMS[6], LArray[5]])); end; procedure TADUTCollectionsArray.DeleteRange; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Test Capacity has been Initialized Assert.IsTrue(LArray.Capacity = 10, Format('Capacity Expected 10, got %d', [LArray.Capacity])); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Remove Items 5 through 7 LArray.Delete(5, 2); // Item 5 should now equal Item 7 in the BASIC_ITEMS Array. Assert.IsTrue(LArray[5] = BASIC_ITEMS[7], Format('Array Item 5 should be "%s" but instead got "%s".', [BASIC_ITEMS[7], LArray[5]])); end; procedure TADUTCollectionsArray.InsertFirst; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Increase capacity to hold one more item LArray.Capacity := 11; // Insert a new Item at Index 0 LArray.Insert('Googar', 0); // Index 0 should be "Googar" Assert.IsTrue(LArray[0] = 'Googar', Format('Index 0 should be "Googar" but instead got "%s"', [LArray[0]])); // Index 1 through 10 should equal BASIC_ITEMS 0 through 9 for I := 1 to 10 do Assert.IsTrue(LArray.Items[I] = BASIC_ITEMS[I-1], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I-1], LArray.Items[I]])); end; procedure TADUTCollectionsArray.InsertLast; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Increase capacity to hold one more item LArray.Capacity := 11; // Insert a new Item at Index 10 LArray.Insert('Googar', 10); // Index 10 should be "Googar" Assert.IsTrue(LArray[10] = 'Googar', Format('Index 10 should be "Googar" but instead got "%s"', [LArray[10]])); // Index 0 through 9 should equal BASIC_ITEMS 0 through 9 for I := 0 to 9 do Assert.IsTrue(LArray.Items[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LArray.Items[I]])); end; procedure TADUTCollectionsArray.InsertMiddle; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Increase capacity to hold one more item LArray.Capacity := 11; // Insert a new Item at Index 5 LArray.Insert('Googar', 5); // Index 0 through 4 should match... for I := 0 to 4 do Assert.IsTrue(LArray.Items[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LArray.Items[I]])); // Index 5 should be "Googar" Assert.IsTrue(LArray[5] = 'Googar', Format('Index 5 should be "Googar" but instead got "%s"', [LArray[5]])); // Index 6 through 10 should equal BASIC_ITEMS 5 through 9 for I := 6 to 10 do Assert.IsTrue(LArray.Items[I] = BASIC_ITEMS[I-1], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I-1], LArray.Items[I]])); end; procedure TADUTCollectionsArray.ReaderIntegrity; var LArray: IADStringArray; LArrayReader: IADStringArrayReader; I: Integer; begin LArray := TADStringArray.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Obtain the Read-Only Interface Reference LArrayReader := LArray.Reader; // Make sure the items match for I := 0 to LArrayReader.Capacity - 1 do Assert.IsTrue(LArrayReader.Items[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LArrayReader.Items[I]])); end; procedure TADUTCollectionsArray.SetCapacity; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Test Capacity has been Initialized Assert.IsTrue(LArray.Capacity = 10, Format('Capacity Expected 10, got %d', [LArray.Capacity])); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Modify our Capacity LArray.Capacity := 15; // Test Capacity has been increased to 15 Assert.IsTrue(LArray.Capacity = 15, Format('Capacity Expected 15, got %d', [LArray.Capacity])); end; procedure TADUTCollectionsArray.SetItem; var LArray: IADStringArray; I: Integer; begin LArray := TADStringArray.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LArray.Items[I] := BASIC_ITEMS[I]; // Modify Item 5 LArray.Items[5] := 'Googar'; // Test Capacity has been increased to 15 Assert.IsTrue(LArray[5] = 'Googar', Format('Item 5 should be "Googar", got "%s"', [LArray[5]])); end; { TADUTCollectionsList } procedure TADUTCollectionsList.BasicIntegrity; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Make sure they match! for I := 0 to Length(BASIC_ITEMS) - 1 do Assert.IsTrue(LList[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LList[I]])); end; procedure TADUTCollectionsList.Clear; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do begin LList.Add(BASIC_ITEMS[I]); Assert.IsTrue(LList.Count = I + 1, Format('Count should be %d, instead got %d', [I + 1, LList.Count])); end; // Clear the List LList.Clear; // The Count should now be 0 Assert.IsTrue(LList.Count = 0, Format('Count should be 0, instead got %d', [LList.Count])); // There should be no items in the Array, so attempting to reference any should result in an Access Violation Exception. Assert.WillRaiseAny(procedure begin LList[0]; end, 'Item 0 request should have raised an Exception, it did not! List must not be empty!'); end; procedure TADUTCollectionsList.DeleteOne; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Remove Item 5 LList.Delete(5); // Item 5 should now equal Item 6 in the BASIC_ITEMS List. Assert.IsTrue(LList[5] = BASIC_ITEMS[6], Format('List Item 5 should be "%s" but instead got "%s".', [BASIC_ITEMS[6], LList[5]])); end; procedure TADUTCollectionsList.DeleteRange; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Remove Items 5 through 7 LList.DeleteRange(5, 2); // Item 5 should now equal Item 7 in the BASIC_ITEMS List. Assert.IsTrue(LList[5] = BASIC_ITEMS[7], Format('List Item 5 should be "%s" but instead got "%s".', [BASIC_ITEMS[7], LList[5]])); end; procedure TADUTCollectionsList.InsertFirst; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Insert a new Item at Index 0 LList.Insert('Googar', 0); // Index 0 should be "Googar" Assert.IsTrue(LList[0] = 'Googar', Format('Index 0 should be "Googar" but instead got "%s"', [LList[0]])); // Index 1 through 10 should equal BASIC_ITEMS 0 through 9 for I := 1 to 10 do Assert.IsTrue(LList[I] = BASIC_ITEMS[I-1], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I-1], LList[I]])); end; procedure TADUTCollectionsList.InsertLast; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Insert a new Item at Index 10 LList.Insert('Googar', 10); // Index 10 should be "Googar" Assert.IsTrue(LList[10] = 'Googar', Format('Index 10 should be "Googar" but instead got "%s"', [LList[10]])); // Index 0 through 9 should equal BASIC_ITEMS 0 through 9 for I := 0 to 9 do Assert.IsTrue(LList[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LList[I]])); end; procedure TADUTCollectionsList.InsertMiddle; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Insert a new Item at Index 5 LList.Insert('Googar', 5); // Index 0 through 4 should match... for I := 0 to 4 do Assert.IsTrue(LList[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LList[I]])); // Index 5 should be "Googar" Assert.IsTrue(LList[5] = 'Googar', Format('Index 5 should be "Googar" but instead got "%s"', [LList[5]])); // Index 6 through 10 should equal BASIC_ITEMS 5 through 9 for I := 6 to 10 do Assert.IsTrue(LList[I] = BASIC_ITEMS[I-1], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I-1], LList[I]])); end; procedure TADUTCollectionsList.ReaderIntegrity; var LList: IADStringList; LListReader: IADStringListReader; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Obtain the Reader Interface LListReader := LList.Reader; // Make sure they match! for I := 0 to Length(BASIC_ITEMS) - 1 do Assert.IsTrue(LListReader[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LListReader[I]])); end; procedure TADUTCollectionsList.SetItem; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Modify Item 5 LList.Items[5] := 'Googar'; // Test Capacity has been increased to 15 Assert.IsTrue(LList[5] = 'Googar', Format('Item 5 should be "Googar", got "%s"', [LList[5]])); end; procedure TADUTCollectionsList.Sort; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Sort the List LList.Sort(ADStringComparer); // Make sure they match! for I := 0 to Length(BASIC_ITEMS) - 1 do Assert.IsTrue(LList[I] = BASIC_ITEMS_SORTED[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS_SORTED[I], LList[I]])); end; procedure TADUTCollectionsList.SortRange; var LList: IADStringList; I: Integer; begin LList := TADStringList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Sort the List from Index 0 to Index 4 (half the list) LList.SortRange(ADStringComparer, 0, 4); // Make sure they match! for I := 0 to LList.Count - 1 do Assert.IsTrue(LList[I] = BASIC_ITEMS_HALF_SORTED[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS_HALF_SORTED[I], LList[I]])); end; { TADUTCollectionsSortedList } procedure TADUTCollectionsSortedList.BasicIntegrity; var LList: IADStringList; I: Integer; begin LList := TADStringSortedList.Create(ADStringComparer, 10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Make sure they match their PRE-SORTED COUNTERPARTS! for I := 0 to LList.Count - 1 do begin Log(TLogLevel.Information, Format('Sorted List Index %d = "%s"', [I, LList[I]])); Assert.IsTrue(LList[I] = BASIC_ITEMS_SORTED[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS_SORTED[I], LList[I]])); end; end; procedure TADUTCollectionsSortedList.Contains; var LSortedList: IADStringSortedList; I: Integer; begin LSortedList := TADStringSortedList.Create(ADStringComparer, 10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LSortedList.Add(BASIC_ITEMS[I]); // Should NOT contain "Googar" Assert.IsFalse(LSortedList.Contains('Googar'), 'List should NOT contain "Googar" but does.'); // Should contain "Bob" Assert.IsTrue(LSortedList.Contains('Bob'), 'List SHOULD contain "Bob" but does not.'); end; procedure TADUTCollectionsSortedList.IndexOf; var LSortedList: IADStringSortedList; I: Integer; begin LSortedList := TADStringSortedList.Create(ADStringComparer, 10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LSortedList.Add(BASIC_ITEMS[I]); // Should NOT contain "Googar" Assert.IsTrue(LSortedList.IndexOf('Googar') = -1, 'List should NOT contain "Googar" but does.'); // Should contain "Bob" Assert.IsTrue(LSortedList.IndexOf('Bob') = 1, 'List SHOULD contain "Bob" but does not.'); end; procedure TADUTCollectionsSortedList.ReaderIntegrity; var LList: IADStringList; LReader: IADStringListReader; I: Integer; begin LList := TADStringSortedList.Create(ADStringComparer, 10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Grab our Reader Interface LReader := LList.Reader; // Make sure they match their PRE-SORTED COUNTERPARTS! for I := 0 to LReader.Count - 1 do begin Log(TLogLevel.Information, Format('Sorted List Index %d = "%s"', [I, LReader[I]])); Assert.IsTrue(LReader[I] = BASIC_ITEMS_SORTED[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS_SORTED[I], LReader[I]])); end; end; procedure TADUTCollectionsSortedList.Remove; var LList: IADStringSortedList; I: Integer; begin LList := TADStringSortedList.Create(ADStringComparer, 10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Remove "Bob" LList.Remove('Bob'); // We know "Bob" sits at Index 1 // Ensure Item 0 matches Assert.IsTrue(LList[0] = BASIC_ITEMS_SORTED[0], 'Item 0 should match but does not.'); // Make sure the rest match their PRE-SORTED COUNTERPARTS! for I := 1 to Length(BASIC_ITEMS_SORTED) - 2 do Assert.IsTrue(LList[I] = BASIC_ITEMS_SORTED[I+1], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS_SORTED[I+1], LList[I]])); end; { TADUTCollectionsCircularList } procedure TADUTCollectionsCircularList.BasicIntegrity; var LList: IADStringList; I: Integer; begin LList := TADStringCircularList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Make sure they match! for I := 0 to Length(BASIC_ITEMS) - 1 do Assert.IsTrue(LList[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LList[I]])); end; procedure TADUTCollectionsCircularList.CircularIntegrity; var LList: IADStringList; I: Integer; begin LList := TADStringCircularList.Create(5); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Make sure they match the SECOND HALF of the BASIC_ITEMS Array! for I := 0 to LList.Count - 1 do Assert.IsTrue(LList[I] = BASIC_ITEMS[I+5], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I+5], LList[I]])); end; procedure TADUTCollectionsCircularList.ReaderIntegrity; var LList: IADStringList; LReader: IADStringCircularListReader; I: Integer; begin LList := TADStringCircularList.Create(10); // Add our Basic Test Items for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do LList.Add(BASIC_ITEMS[I]); // Get our Reader interface LReader := IADStringCircularListReader(LList.Reader); // Make sure they match! for I := 0 to Length(BASIC_ITEMS) - 1 do Assert.IsTrue(LReader[I] = BASIC_ITEMS[I], Format('Item at Index %d does not match. Expected "%s" but got "%s"', [I, BASIC_ITEMS[I], LReader[I]])); end; { TADUTCollectionsMap } procedure TADUTCollectionsMap.BasicIntegrity; var LMap: IADStringStringMap; LItem: IADKeyValuePair<String, String>; I: Integer; begin LMap := TADStringStringMap.Create(ADStringComparer); // Add the Test Items for I := Low(MAP_ITEMS) to High(MAP_ITEMS) do LMap.Add(MAP_ITEMS[I].Key, MAP_ITEMS[I].Value); // Verify they exist for I := 0 to LMap.Count - 1 do begin LItem := LMap.Pairs[I]; Assert.IsTrue((LItem.Key = MAP_ITEMS_SORTED[I].Key) and (LItem.Value = MAP_ITEMS_SORTED[I].Value), Format('Pair should be "%s", "%s" but instead got pair "%s", "%s".', [MAP_ITEMS_SORTED[I].Key, MAP_ITEMS_SORTED[I].Value, LItem.Key, LItem.Value])); end; end; { TADUTCollectionsCircularMap } procedure TADUTCollectionsCircularMap.BasicIntegrity; var LMap: IADStringStringMap; LItem: IADKeyValuePair<String, String>; I: Integer; begin LMap := TADStringStringCircularMap.Create(ADStringComparer); // Add the Test Items for I := Low(MAP_ITEMS) to High(MAP_ITEMS) do LMap.Add(MAP_ITEMS[I].Key, MAP_ITEMS[I].Value); // Verify they exist for I := 0 to LMap.Count - 1 do begin LItem := LMap.Pairs[I]; Assert.IsTrue((LItem.Key = MAP_ITEMS_SORTED[I].Key) and (LItem.Value = MAP_ITEMS_SORTED[I].Value), Format('Pair should be "%s", "%s" but instead got pair "%s", "%s".', [MAP_ITEMS_SORTED[I].Key, MAP_ITEMS_SORTED[I].Value, LItem.Key, LItem.Value])); end; end; procedure TADUTCollectionsCircularMap.CircularIntegrity; var LMap: IADStringStringMap; LItem: IADKeyValuePair<String, String>; I: Integer; begin LMap := TADStringStringCircularMap.Create(ADStringComparer, 5); // Add the Test Items for I := Low(MAP_ITEMS) to High(MAP_ITEMS) do LMap.Add(MAP_ITEMS[I].Key, MAP_ITEMS[I].Value); // Verify they exist for I := 0 to LMap.Count - 1 do begin LItem := LMap.Pairs[I]; Assert.IsTrue((LItem.Key = MAP_ITEMS_SORTED[I+5].Key) and (LItem.Value = MAP_ITEMS_SORTED[I+5].Value), Format('Pair should be "%s", "%s" but instead got pair "%s", "%s".', [MAP_ITEMS_SORTED[I+5].Key, MAP_ITEMS_SORTED[I+5].Value, LItem.Key, LItem.Value])); end; end; { TADUTCollectionsTree } procedure TADUTCollectionsTree.BasicIntegrity; var LNode: IADStringTreeNode; LNode2: IADStringTreeNode; begin LNode := TADStringTreeNode.Create('Foo'); LNode2 := TADStringTreeNode.Create(LNode, 'Bar'); // Test Values for both Nodes Assert.IsTrue(LNode.Value = 'Foo', Format('Node Value should be "Foo" but instead got "%s"', [LNode.Value])); Assert.IsTrue(LNode2.Value = 'Bar', Format('Node2 Value should be "Bar" but instead got "%s"', [LNode2.Value])); // Verify that we can access the value of the Child Node via its Parent Node. Assert.IsTrue(LNode[0].Value = 'Bar', Format('Node1 Child 0 Value should be "Bar" but instead got "%s"', [LNode[0].Value])); // Verify that the Parent of our Child Node is not nil Assert.IsTrue(LNode2.Parent <> nil, 'Node2 Parent should be Node, but is not!'); // Verify that we can access the value of the Parent Node via its Child Node. LNode2.Parent.Value := 'Haha'; Assert.IsTrue(LNode.Value = 'Haha', Format('Node Value should be "Haha" but instead got "%s"', [LNode.Value])); end; { TADUTCollectionsStackQueue } procedure TADUTCollectionsStackQueue.BasicIntegrity; var LStackQueue: IADStackQueue<String>; I: Integer; LConfirms: Array[0..9] of Boolean; LConfirmAll: Boolean; LSortedList: IADSortedList<String>; {$IFDEF PERFLOGGING} LStartTime: ADFloat; {$ENDIF PERLOGGING} begin Randomize; // Initialize LConfirms to False for I := Low(LConfirms) to High(LConfirms) do LConfirms[I] := False; // Create and populate a Sorted List (so we can easily confirm that values from the StackQueue are all present) LSortedList := TADSortedList<String>.Create(ADStringComparer, 10); LSortedList.AddItems(BASIC_ITEMS); // Create our StackQueue. LStackQueue := TADStackQueue<String>.Create; // Populate it with our Values. for I := Low(BASIC_ITEMS) to High(BASIC_ITEMS) do if (I mod 2 = 1) then LStackQueue.Queue(BASIC_ITEMS[I], Random(4) + 1) // Random Priority else LStackQueue.Stack(BASIC_ITEMS[I], Random(4) + 1); // Random Priority // Verify that Count = 10 Assert.IsTrue(LStackQueue.CountTotal = 10, Format('Stack/Queue should contain 10 items, instead contains %d.', [LStackQueue.CountTotal])); // Now that our StackQueue is populated, we need to Process it to ensure it Processes EVERY Value... {$IFDEF PERFLOGGING} LStartTime := ADReferenceTime; {$ENDIF PERFLOGGING} LStackQueue.ProcessStackQueue(procedure(const AItem: String) begin I := LSortedList.IndexOf(AItem); if I > -1 then LConfirms[I] := True; end); {$IFDEF PERFLOGGING} Log(TLogLevel.Warning, Format('%d Items took %f Seconds', [LStackQueue.CountTotal, ADReferenceTime - LStartTime])); {$ENDIF PERFLOGGING} LConfirmAll := True; // Optimistic for I := Low(LConfirms) to High(LConfirms) do if (not LConfirms[I]) then begin LConfirmAll := False; Break; end; Assert.IsTrue(LConfirmAll, 'Not all Values in the StackQueue could be verified.'); end; end.
unit DPTCoefficient; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Grids, Buttons, ExtCtrls; type TDPTCoefficientForm = class(TForm) sg1: TStringGrid; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; btn_edit: TBitBtn; btn_ok: TBitBtn; btn_cancel: TBitBtn; procedure btn_cancelClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure btn_okClick(Sender: TObject); procedure btn_editClick(Sender: TObject); private { Private declarations } procedure SetGridValue; procedure SaveGridValue; public { Public declarations } end; var DPTCoefficientForm: TDPTCoefficientForm; implementation uses MainDM, public_unit, SdCadMath; {$R *.dfm} procedure TDPTCoefficientForm.btn_cancelClick(Sender: TObject); begin self.Close; end; procedure TDPTCoefficientForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TDPTCoefficientForm.FormCreate(Sender: TObject); begin self.Left := trunc((screen.Width - self.Width)/2); self.Top := trunc((screen.Height - self.Height)/2); sg1.RowCount := 2; sg1.ColCount := 10; sg1.Cells[0,0]:='杆长↓击数→'; sg1.Cells[1,0]:='击数5'; sg1.Cells[2,0]:='击数10'; sg1.Cells[3,0]:='击数15'; sg1.Cells[4,0]:='击数20'; sg1.Cells[5,0]:='击数25'; sg1.Cells[6,0]:='击数30'; sg1.Cells[7,0]:='击数35'; sg1.Cells[8,0]:='击数40'; sg1.Cells[9,0]:='击数50'; sg1.ColWidths[0]:= 80; sg1.Options := [goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine,goEditing]; SetGridValue; end; procedure TDPTCoefficientForm.SaveGridValue; var aRow:integer; strUpdateSQL:string; begin for aRow:=1 to sg1.RowCount -1 do begin strUpdateSQL := 'Update dpt_coefficient SET '; strUpdateSQL := strUpdateSQL + 'n5='+sg1.Cells[1,aRow]+','; strUpdateSQL := strUpdateSQL + 'n10='+sg1.Cells[2,aRow]+','; strUpdateSQL := strUpdateSQL + 'n15='+sg1.Cells[3,aRow]+','; strUpdateSQL := strUpdateSQL + 'n20='+sg1.Cells[4,aRow]+','; strUpdateSQL := strUpdateSQL + 'n25='+sg1.Cells[5,aRow]+','; strUpdateSQL := strUpdateSQL + 'n30='+sg1.Cells[6,aRow]+','; strUpdateSQL := strUpdateSQL + 'n35='+sg1.Cells[7,aRow]+','; strUpdateSQL := strUpdateSQL + 'n40='+sg1.Cells[8,aRow]+','; strUpdateSQL := strUpdateSQL + 'n50='+sg1.Cells[9,aRow]; strUpdateSQL := strUpdateSQL + ' WHERE pole_len='+sg1.Cells[sg1.colcount,aRow]; Update_oneRecord(MainDataModule.qryDPTCoef,strUpdateSQL); end; end; procedure TDPTCoefficientForm.SetGridValue; var i,iFieldCount:integer; begin //qryDPTCoef with MainDataModule.qryDPTCoef do begin close; sql.Clear; sql.Add('SELECT * FROM dpt_coefficient'); open; iFieldCount := MainDataModule.qryDPTCoef.FieldCount; {for i := 1 to iFieldCount-1 do begin sFieldName := Fields[i].FieldName; System.Delete(sFieldName,1,1); sg1.Cells[i,0]:= '击数'+sFieldName; end;} while not eof do begin sg1.Cells[0,sg1.RowCount-1]:='杆长 '+ FieldByName('pole_len').AsString+'m'; sg1.Cells[sg1.ColCount,sg1.RowCount-1]:= FieldByName('pole_len').AsString; for i := 1 to iFieldCount-1 do sg1.Cells[i,sg1.RowCount-1] := Fields[i].AsString; sg1.RowCount := sg1.RowCount +2; sg1.RowCount := sg1.RowCount -1; next; end; close; sg1.RowCount := sg1.RowCount -1; end; end; procedure TDPTCoefficientForm.btn_okClick(Sender: TObject); begin SaveGridValue; sg1.Options :=[goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine]; end; //getDPTXiuZhengXiShu 返回重型圆锥动力触探锤击数修正系数 //N表示实测锤击数,L表示杆长,aType表示触探类型,aType=1是重型, // aType=2 是超重型。 function getDPTXiuZhengXiShu(N,L: double;aType:integer): double; var i,iFieldCount, iField, recNum, N0, N1, L0, L1, tmpL:integer; isExistN: boolean;//判断系数表里是否存在传入的击数 N_Exist: integer; //系数表里已存在的击数。 N_Max: integer; //系数表里已存在的最大击数。 tmpXiShu_N0, tmpXiShu_N1, //保存每一条记录中的两个击数对应的系数 XiShu_N0L0, XiShu_N0L1, XiShu_N1L0, XiShu_N1L1, tmpXiShu: double; //保存四个系数 sFieldName, //临时保存字段名 sTableName: string; //临时保存系数表的表名 begin N0:=0; L0:=0; N1:=0; XiShu_N0L0:=1; N_Exist:=0; N_Max:=0; XiShu_N1L0:=0; //qryDPTCoef case aType of 1: begin N_Max:= 50; sTableName := 'dpt_coefficient'; end; 2: begin N_Max:= 40; sTableName := 'dpt_supercoefficient'; end; end; isExistN:= false; with MainDataModule.qryDPTCoef do begin close; sql.Clear; sql.Add('SELECT * FROM ' + sTableName); open; iFieldCount := MainDataModule.qryDPTCoef.FieldCount; recNum:= 0; {开始找出击数N在数据库中的两边的值N0和N1, 如果刚好有这个N则转入下面的操作找杆长L0,L1和对应的修正系数} if N>=N_Max then begin N_Exist:= N_Max; isExistN := true; end else for i := 1 to iFieldCount-1 do begin sFieldName := Fields[i].FieldName; System.Delete(sFieldName,1,1); iField := strtoint(sFieldName); if iField=N then begin isExistN:= true; N_Exist:=iField; Break; end; if i=1 then begin N0:= iField; if N<iField then begin result:=1; close; exit; end; end; if N>iField then N0:= iField else begin N1:= iField; Break; end; end; //找杆长L0,L1和对应的修正系数 while not eof do begin Inc(recNum); tmpL := FieldByName('pole_len').AsInteger; if isExistN then begin tmpXiShu:= FieldByName('n' + inttostr(N_Exist)).AsFloat; if tmpL = L then begin result:= tmpXiShu; close; exit; end; if recNum=1 then begin L0:= tmpL; XiShu_N0L0:= tmpXiShu; if L<tmpL then begin result:= tmpXiShu; close; exit; end; end; if tmpL<L then begin L0:= tmpL; XiShu_N0L0:= tmpXiShu; end else begin L1:= tmpL; XiShu_N0L1:= tmpXiShu; result:= XianXingChaZhi(L0,XiShu_N0L0,L1,XiShu_N0L1,L); close; exit; end; end //end of if isExistN then else begin tmpXiShu_N0 := FieldByName('n'+inttostr(N0)).AsFloat; tmpXiShu_N1 := FieldByName('n'+inttostr(N1)).AsFloat; tmpL := FieldByName('pole_len').AsInteger; if L=tmpL then begin result:= XianXingChaZhi(N0,tmpXiShu_N0,N1,tmpXiShu_N1,N); close; exit; end; if recNum=1 then begin if L<tmpL then begin result:= tmpXiShu_N0; close; exit; end; XiShu_N0L0 := tmpXiShu_N0; XiShu_N1L0 := tmpXiShu_N1; L0 := tmpL; end else //else recNum>1 begin if L<tmpL then begin XiShu_N0L1:= tmpXiShu_N0; XiShu_N1L1 := tmpXiShu_N1; L1 := tmpL; result:= ShuangXianXingChaZhi(N0, L0, N1, L1, XiShu_N0L0,XiShu_N0L1,XiShu_N1L0,XiShu_N1L1,N,L); close; exit; end else begin XiShu_N0L0 := tmpXiShu_N0; XiShu_N1L0 := tmpXiShu_N1; L0 := tmpL; end; end; end; next; end; result:=1; close; end; end; procedure TDPTCoefficientForm.btn_editClick(Sender: TObject); begin sg1.Options :=[goFixedVertLine,goFixedHorzLine,goVertLine,goHorzLine,goEditing]; end; end.
{Программа: Bomberman } {Цель: создать игру Bomberman } {Переменные: CurrentTime, LastTime - время начала работы кадра, время конца работы кадра, DeltaTime - разница между LastTime и CurrentTime } {Программист: Агафонов Павел Алексеевич } {Проверил: Антипов Олег Владимирович } {Дата написания: 08.05.2020 } program Bomberman; uses GraphABC, GlobalVars, Menu, Help, Highscore, MapMenu, InputNames, MainGame, Editor, UIAssets, Renderer; var CurrentTime, LastTime : longint; DeltaTime : integer; {Процедура обработки отжатия клавиши клавиатуры } {Переменные: key - нажатая кнопка } procedure HandleKeyDown(key : integer); begin inputKeys[key] := true; LastChar := key; end; {Процедура обработки нажатия клавиши клавиатуры } {Переменные: key - нажатая кнопка } procedure HandleKeyUp(key : integer); begin inputKeys[key] := false; end; {Процедура обновления логики текущего состояния } {Переменные: dt - время между кадрами в мс } procedure Update(dt : integer); begin case _CurrentState of MenuState : begin UpdateMenu(dt); end; HelpState : begin UpdateHelp(dt); end; HighscoreState : begin UpdateHighscore(dt); end; ChooseMapState : begin UpdateMapMenu(dt); end; InputNamesState : begin UpdateInputNames(dt); end; MainGameState : begin UpdateMainGame(dt); end; EndHighState : begin UpdateNewHighscore(dt); end; EditorState : begin UpdateEditor(dt); end; end; end; {Процедура отрисовки текущего состояния } procedure Render(); begin case _CurrentState of MenuState : begin RenderMenu(); end; HelpState : begin RenderHelp(); end; HighscoreState : begin RenderHighscore(); end; ChooseMapState : begin RenderMapMenu(); end; InputNamesState : begin RenderInputNames(); end; MainGameState : begin RenderMainGame(); end; EndHighState : begin RenderNewHighscore(); end; EditorState : begin RenderEditor(); end; end; end; begin SetSmoothingOff(); Randomize(); InitAssets(); InitRenderer(); OnKeyDown := HandleKeyDown; OnKeyUp := HandleKeyUp; SetWindowIsFixedSize(true); LockDrawing(); LastChange := Milliseconds(); ChangeState(MenuState); Window.CenterOnScreen(); IsQuit := false; DeltaTime := 0; SetFontName('Consolas'); while (not IsQuit) do begin CurrentTime := Milliseconds(); Update(DeltaTime); Render(); Redraw(); LastTime := Milliseconds(); DeltaTime := LastTime - CurrentTime; if (DeltaTime <> 0) then SetWindowTitle('Bomberman (FPS:' + Trunc(1/DeltaTime * 1000) + ')'); if (17 - DeltaTime >= 0) then Sleep(17 - DeltaTime); end; UnlockDrawing(); Window.Clear(); Window.Close(); end.
unit AFormaPagamentoECF; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, Buttons, StdCtrls, Localizacao, Mask, numericos, DBKeyViolation, UnECF, ComCtrls, UnDadosCR, UnContasaReceber; type TFFormaPagamentoECF = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; PanelColor2: TPanelColor; EFormaPagamento: TEditLocaliza; ConsultaPadrao1: TConsultaPadrao; Label1: TLabel; LFormaPagamento: TLabel; SpeedButton1: TSpeedButton; EValPago: Tnumerico; Label3: TLabel; Label4: TLabel; EValTroco: Tnumerico; BOk: TBitBtn; BCancelar: TBitBtn; ValidaGravacao1: TValidaGravacao; Label5: TLabel; EValTotal: Tnumerico; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure EFormaPagamentoChange(Sender: TObject); procedure BOkClick(Sender: TObject); procedure BCancelarClick(Sender: TObject); procedure EValPagoChange(Sender: TObject); procedure EValPagoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } VprAcao : Boolean; FunECF : TRBFuncoesECF; VprBarraStatus : TStatusBar; function DadosValidos : String; public { Public declarations } function MostraFormaPagamento(VpaDFormaPagamento : TRBDFormaPagamento; Var VpaValPago :Double; VpaValTotal : Double;VpaFunECF : TRBFuncoesECF):boolean; end; var FFormaPagamentoECF: TFFormaPagamentoECF; implementation uses APrincipal, Constmsg; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFFormaPagamentoECF.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VprAcao := false; end; { ******************* Quando o formulario e fechado ************************** } procedure TFFormaPagamentoECF.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFFormaPagamentoECF.EFormaPagamentoChange(Sender: TObject); begin ValidaGravacao1.execute; end; {******************************************************************************} procedure TFFormaPagamentoECF.BOkClick(Sender: TObject); var VpfResultado : String; begin VpfResultado := DadosValidos; if VpfResultado <> '' then aviso(VpfREsultado) else begin VprAcao := true; close; end; end; {******************************************************************************} function TFFormaPagamentoECF.DadosValidos: String; begin if EValTroco.AValor < 0 then result := 'VALOR DO TROCO INVÁLIDO!!!'#13'O valor do troco não pode ser menor que 0(zero)'; end; {******************************************************************************} procedure TFFormaPagamentoECF.BCancelarClick(Sender: TObject); begin vprAcao := false; close; end; {******************************************************************************} function TFFormaPagamentoECF.MostraFormaPagamento(VpaDFormaPagamento : TRBDFormaPagamento; Var VpaValPago :Double; VpaValTotal : Double;VpaFunECF : TRBFuncoesECF):Boolean; begin FunECF := VpaFunECF; EValTotal.AValor := VpaValTotal; EFormaPagamento.AInteiro := VpaDFormaPagamento.CodForma; EFormaPagamento.Atualiza; Showmodal; result := VprAcao; if VprAcao then begin FunContasAReceber.CarDFormaPagamento(VpaDFormaPagamento,EFormaPagamento.AInteiro); VpaValPago := EValPago.AValor; end; end; {******************************************************************************} procedure TFFormaPagamentoECF.EValPagoChange(Sender: TObject); begin ValidaGravacao1.execute; if EValPago.Avalor <> 0 then EValTroco.AValor := EValPago.AValor - EValTotal.AValor else EValTroco.Clear; end; procedure TFFormaPagamentoECF.EValPagoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = 13 then FunECF.AbreGaveta; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFFormaPagamentoECF]); end.
unit uShipment; {$mode objfpc}{$H+} interface uses SynCommons, mORMot, uForwardDeclaration;//Classes, SysUtils; type // 1 TSQLItemIssuance = class(TSQLRecord) private fOrderId: TSQLOrderItemID; //fOrderItemSeq: Integer; fShipGroupSeq: Integer; fInventoryItem: Integer; fShipment: TSQLShipmentItemID; //fShipmentItemSeq: Integer; fFixedAsset: TSQLFixedAssetMaintID; //fMaintHistSeq: Integer; fIssuedDateTime: TDateTime; fIssuedByUserLogin: TSQLUserLoginID; fQuantity: Double; fCancelQuantity: Double; published property OrderId: TSQLOrderItemID read fOrderId write fOrderId; property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq; property InventoryItem: Integer read fInventoryItem write fInventoryItem; property Shipment: TSQLShipmentItemID read fShipment write fShipment; property FixedAsset: TSQLFixedAssetMaintID read fFixedAsset write fFixedAsset; property IssuedDateTime: TDateTime read fIssuedDateTime write fIssuedDateTime; property IssuedByUserLogin: TSQLUserLoginID read fIssuedByUserLogin write fIssuedByUserLogin; property Quantity: Double read fQuantity write fQuantity; property CancelQuantity: Double read fCancelQuantity write fCancelQuantity; end; // 2 TSQLItemIssuanceRole = class(TSQLRecord) private fItemIssuance: TSQLItemIssuanceID; fPartyRole: TSQLPartyRoleID; //partyId, roleTypeId published property ItemIssuance: TSQLItemIssuanceID read fItemIssuance write fItemIssuance; property PartyRole: TSQLPartyRoleID read fPartyRole write fPartyRole; end; // 3 TSQLPicklist = class(TSQLRecord) private fDescription: RawUTF8; fFacility: TSQLFacilityID; fShipmentMethodType: TSQLShipmentMethodTypeID; fStatus: TSQLStatusItemID; fPicklistDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedByUserLogin: TSQLUserLoginID; published property Description: RawUTF8 read fDescription write fDescription; property Facility: TSQLFacilityID read fFacility write fFacility; property ShipmentMethodType: TSQLShipmentMethodTypeID read fShipmentMethodType write fShipmentMethodType; property Status: TSQLStatusItemID read fStatus write fStatus; property PicklistDate: TDateTime read fPicklistDate write fPicklistDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 4 TSQLPicklistBin = class(TSQLRecord) private fPicklist: TSQLPicklistID; fBinLocationNumber: Integer; fPrimaryOrder: TSQLOrderHeaderID; fPrimaryShipGroupSeq: Integer; published property Picklist: TSQLPicklistID read fPicklist write fPicklist; property BinLocationNumber: Integer read fBinLocationNumber write fBinLocationNumber; property PrimaryOrder: TSQLOrderHeaderID read fPrimaryOrder write fPrimaryOrder; property PrimaryShipGroupSeq: Integer read fPrimaryShipGroupSeq write fPrimaryShipGroupSeq; end; // 5 TSQLPicklistItem = class(TSQLRecord) private fPicklistBin: TSQLPicklistBinID; fOrderId: TSQLOrderHeaderID; fOrderItemSeq: Integer; fShipGroupSeq: Integer; fInventoryItem: TSQLInventoryItemID; fStatusItem: TSQLStatusItemID; fQuantity: Double; published property PicklistBin: TSQLPicklistBinID read fPicklistBin write fPicklistBin; property OrderId: TSQLOrderHeaderID read fOrderId write fOrderId; property OrderItemSeq: Integer read fOrderItemSeq write fOrderItemSeq; property ShipGroupSeq: Integer read fShipGroupSeq write fShipGroupSeq; property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property StatusItem: TSQLStatusItemID read fStatusItem write fStatusItem; property Quantity: Double read fQuantity write fQuantity; end; // 6 TSQLPicklistRole = class(TSQLRecord) private fPicklist: TSQLPicklistID; fPartyRole: TSQLPartyRoleID; //partyId, roleTypeId fFromDate: TDateTime; fThruDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedByUserLogin: TSQLUserLoginID; published property Picklist: TSQLPicklistID read fPicklist write fPicklist; property PartyRole: TSQLPartyRoleID read fPartyRole write fPartyRole; property FromDate: TDateTime read fFromDate write fFromDate; property ThruDate: TDateTime read fThruDate write fThruDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 7 TSQLPicklistStatusHistory = class(TSQLRecord) private fPicklist: TSQLPicklistID; fChangeDate: TDateTime; fChangeUserLogin: TSQLUserLoginID; fStatus: TSQLStatusValidChangeID; //statusId, statusIdTo published property Picklist: TSQLPicklistID read fPicklist write fPicklist; property ChangeDate: TDateTime read fChangeDate write fChangeDate; property ChangeUserLogin: TSQLUserLoginID read fChangeUserLogin write fChangeUserLogin; property Status: TSQLStatusValidChangeID read fStatus write fStatus; end; // 8 TSQLRejectionReason = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; fDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read fDescription write fDescription; end; // 9 TSQLShipmentReceipt = class(TSQLRecord) private fInventoryItem: TSQLInventoryItemID; fProduct: TSQLProductID; fShipmentPackage: TSQLShipmentPackageID; //shipmentId, shipmentPackageSeqId fShipmentItem: TSQLShipmentItemID; //shipmentId, shipmentItemSeqId fOrderItem: TSQLOrderItemID; //orderId, orderItemSeqId fReturnItem: TSQLReturnItemID; //returnId, returnItemSeqId fRejectionReason: TSQLRejectionReasonID; fReceivedByUserLogin: TSQLUserLoginID; fDatetimeReceived: TDateTime; fItemDescription: RawUTF8; fQuantityAccepted: Double; fQuantityRejected: Double; published property InventoryItem: TSQLInventoryItemID read fInventoryItem write fInventoryItem; property Product: TSQLProductID read fProduct write fProduct; property ShipmentPackage: TSQLShipmentPackageID read fShipmentPackage write fShipmentPackage; property ShipmentItem: TSQLShipmentItemID read fShipmentItem write fShipmentItem; property OrderItem: TSQLOrderItemID read fOrderItem write fOrderItem; property ReturnItem: TSQLReturnItemID read fReturnItem write fReturnItem; property RejectionReason: TSQLRejectionReasonID read fRejectionReason write fRejectionReason; property ReceivedByUserLogin: TSQLUserLoginID read fReceivedByUserLogin write fReceivedByUserLogin; property DatetimeReceived: TDateTime read fDatetimeReceived write fDatetimeReceived; property ItemDescription: RawUTF8 read fItemDescription write fItemDescription; property QuantityAccepted: Double read fQuantityAccepted write fQuantityAccepted; property QuantityRejected: Double read fQuantityRejected write fQuantityRejected; end; // 10 TSQLShipmentReceiptRole = class(TSQLRecord) private fReceipt: TSQLShipmentReceiptID; fPartyRole: TSQLPartyRoleID; //partyId, roleTypeId published property Receipt: TSQLShipmentReceiptID read fReceipt write fReceipt; property PartyRole: TSQLPartyRoleID read fPartyRole write fPartyRole; end; // 11 TSQLCarrierShipmentMethod = class(TSQLRecord) private fShipmentMethodType: TSQLShipmentMethodTypeID; fPartyRole: TSQLPartyRoleID; //partyId, roleTypeId fSequenceNumber: Integer; fCarrierServiceCode: RawUTF8; published property ShipmentMethodType: TSQLShipmentMethodTypeID read fShipmentMethodType write fShipmentMethodType; property PartyRole: TSQLPartyRoleID read fPartyRole write fPartyRole; property SequenceNumber: Integer read fSequenceNumber write fSequenceNumber; property CarrierServiceCode: RawUTF8 read fCarrierServiceCode write fCarrierServiceCode; end; // 12 TSQLCarrierShipmentBoxType = class(TSQLRecord) private fShipmentBoxType: TSQLShipmentBoxTypeID; fParty: TSQLPartyID; fPackagingTypeCode: Integer; fOversizeCode: RawUTF8; published property ShipmentBoxType: TSQLShipmentBoxTypeID read fShipmentBoxType write fShipmentBoxType; property Party: TSQLPartyID read fParty write fParty; property PackagingTypeCode: Integer read fPackagingTypeCode write fPackagingTypeCode; property OversizeCode: RawUTF8 read fOversizeCode write fOversizeCode; end; // 13 TSQLDelivery = class(TSQLRecord) private fOriginFacility: TSQLFacilityID; fDestFacility: TSQLFacilityID; fActualStartDate: TDateTime; fActualArrivalDate: TDateTime; fEstimatedStartDate: TDateTime; fEstimatedArrivalDate: TDateTime; fFixedAsset: TSQLFixedAssetID; fStartMileage: Double; fEndMileage: Double; fFuelUsed: Double; published property OriginFacility: TSQLFacilityID read fOriginFacility write fOriginFacility; property DestFacility: TSQLFacilityID read fDestFacility write fDestFacility; property ActualStartDate: TDateTime read fActualStartDate write fActualStartDate; property ActualArrivalDate: TDateTime read fActualArrivalDate write fActualArrivalDate; property EstimatedStartDate: TDateTime read fEstimatedStartDate write fEstimatedStartDate; property EstimatedArrivalDate: TDateTime read fEstimatedArrivalDate write fEstimatedArrivalDate; property FixedAsset: TSQLFixedAssetID read fFixedAsset write fFixedAsset; property StartMileage: Double read fStartMileage write fStartMileage; property EndMileage: Double read fEndMileage write fEndMileage; property FuelUsed: Double read fFuelUsed write fFuelUsed; end; // 14 TSQLShipment = class(TSQLRecord) private fShipmentType: TSQLShipmentTypeID; fStatus: TSQLStatusItemID; fPrimaryOrder: TSQLOrderItemShipGroupID; //primaryOrderId, primaryShipGroupSeqId fPrimaryReturn: TSQLReturnHeaderID; fPicklistBin: TSQLPicklistBinID; fEstimatedReadyDate: TDateTime; fEstimatedShipDate: TDateTime; fEstimatedShipWorkEff: TSQLWorkEffortID; fEstimatedArrivalDate: TDateTime; fEstimatedArrivalWorkEff: TSQLWorkEffortID; fLatestCancelDate: TDateTime; fEstimatedShipCost: Currency; fCurrencyUom: TSQLUomID; fHandlingInstructions: RawUTF8; fOriginFacility: TSQLFacilityID; fDestinationFacility: TSQLFacilityID; fOriginContactMech: TSQLContactMechID; fOriginTelecomNumber: TSQLTelecomNumberID; fDestinationContactMech: TSQLContactMechID; fDestinationTelecomNumber: TSQLTelecomNumberID; fPartyTo: TSQLPartyID; fPartyFrom: TSQLPartyID; fAdditionalShippingCharge: Currency; fAddtlShippingChargeDesc: RawUTF8; fCreatedDate: TDateTime; fCreatedByUserLogin: TSQLUserLoginID; fLastModifiedDate: TDateTime; fLastModifiedByUserLogin: TSQLUserLoginID; published property ShipmentType: TSQLShipmentTypeID read fShipmentType write fShipmentType; property Status: TSQLStatusItemID read fStatus write fStatus; property PrimaryOrder: TSQLOrderItemShipGroupID read fPrimaryOrder write fPrimaryOrder; property PrimaryReturn: TSQLReturnHeaderID read fPrimaryReturn write fPrimaryReturn; property PicklistBin: TSQLPicklistBinID read fPicklistBin write fPicklistBin; property EstimatedReadyDate: TDateTime read fEstimatedReadyDate write fEstimatedReadyDate; property EstimatedShipDate: TDateTime read fEstimatedShipDate write fEstimatedShipDate; property EstimatedShipWorkEff: TSQLWorkEffortID read fEstimatedShipWorkEff write fEstimatedShipWorkEff; property EstimatedArrivalDate: TDateTime read fEstimatedArrivalDate write fEstimatedArrivalDate; property EstimatedArrivalWorkEff: TSQLWorkEffortID read fEstimatedArrivalWorkEff write fEstimatedArrivalWorkEff; property LatestCancelDate: TDateTime read fLatestCancelDate write fLatestCancelDate; property EstimatedShipCost: Currency read fEstimatedShipCost write fEstimatedShipCost; property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom; property HandlingInstructions: RawUTF8 read fHandlingInstructions write fHandlingInstructions; property OriginFacility: TSQLFacilityID read fOriginFacility write fOriginFacility; property DestinationFacility: TSQLFacilityID read fDestinationFacility write fDestinationFacility; property OriginContactMech: TSQLContactMechID read fOriginContactMech write fOriginContactMech; property OriginTelecomNumber: TSQLTelecomNumberID read fOriginTelecomNumber write fOriginTelecomNumber; property DestinationContactMech: TSQLContactMechID read fDestinationContactMech write fDestinationContactMech; property DestinationTelecomNumber: TSQLTelecomNumberID read fDestinationTelecomNumber write fDestinationTelecomNumber; property PartyTo: TSQLPartyID read fPartyTo write fPartyTo; property PartyFrom: TSQLPartyID read fPartyFrom write fPartyFrom; property AdditionalShippingCharge: Currency read fAdditionalShippingCharge write fAdditionalShippingCharge; property AddtlShippingChargeDesc: RawUTF8 read fAddtlShippingChargeDesc write fAddtlShippingChargeDesc; property CreatedDate: TDateTime read fCreatedDate write fCreatedDate; property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin; property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate; property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin; end; // 15 TSQLShipmentAttribute = class(TSQLRecord) private fShipment: TSQLShipmentID; fAttrName: TSQLInventoryItemTypeAttrID; fAttrValue: RawUTF8; fAttrDescription: RawUTF8; published property Shipment: TSQLShipmentID read fShipment write fShipment; property AttrName: TSQLInventoryItemTypeAttrID read fAttrName write fAttrName; property AttrValue: RawUTF8 read fAttrValue write fAttrValue; property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription; end; // 16 TSQLShipmentBoxType = class(TSQLRecord) private fDescription: RawUTF8; fDimensionUom: TSQLUomID; fBoxLength: Double; fBoxWidth: Double; fBoxHeight: Double; fWeightUom: TSQLUomID; fBoxWeight: Double; published property Description: RawUTF8 read fDescription write fDescription; property DimensionUom: TSQLUomID read fDimensionUom write fDimensionUom; property BoxLength: Double read fBoxLength write fBoxLength; property BoxWidth: Double read fBoxWidth write fBoxWidth; property BoxHeight: Double read fBoxHeight write fBoxHeight; property WeightUom: TSQLUomID read fWeightUom write fWeightUom; property BoxWeight: Double read fBoxWeight write fBoxWeight; end; // 17 TSQLShipmentContactMech = class(TSQLRecord) private fShipment: TSQLShipmentID; fShipmentContactMechType: TSQLShipmentContactMechTypeID; fContactMech: TSQLContactMechID; published property Shipment: TSQLShipmentID read fShipment write fShipment; property ShipmentContactMechType: TSQLShipmentContactMechTypeID read fShipmentContactMechType write fShipmentContactMechType; property ContactMech: TSQLContactMechID read fContactMech write fContactMech; end; // 18 TSQLShipmentContactMechType = class(TSQLRecord) private fEncode: RawUTF8; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 19 TSQLShipmentCostEstimate = class(TSQLRecord) private fCarrierShipmentMethod: TSQLCarrierShipmentMethodID; //shipmentMethodTypeId, carrierPartyId, carrierRoleTypeId fProductStoreShipMeth: TSQLProductStoreShipmentMethID; fProductStore: Integer; fPartyRole: TSQLPartyRoleID; //partyId, roleTypeId fGeoTo: TSQLGeoID; fGeoFrom: TSQLGeoID; fWeightBreak: TSQLQuantityBreakID; fWeightUom: TSQLUomID; fWeightUnitPrice: Currency; fQuantityBreak: TSQLQuantityBreakID; fQuantityUom: TSQLUomID; fQuantityUnitPrice: Currency; fPriceBreak: TSQLQuantityBreakID; fPriceUom: TSQLUomID; fPriceUnitPrice: Currency; fOrderFlatPrice: Currency; fOrderPricePercent: Double; fOrderItemFlatPrice: Currency; fShippingPricePercent: Double; fProductFeatureGroup: TSQLProductFeatureGroupID; fOversizeUnit: Double; fOversizePrice: Currency; fFeaturePercent: Double; fFeaturePrice: Currency; published property CarrierShipmentMethod: TSQLCarrierShipmentMethodID read fCarrierShipmentMethod write fCarrierShipmentMethod; property ProductStoreShipMeth: TSQLProductStoreShipmentMethID read fProductStoreShipMeth write fProductStoreShipMeth; property ProductStore: Integer read fProductStore write fProductStore; property PartyRole: TSQLPartyRoleID read fPartyRole write fPartyRole; property GeoTo: TSQLGeoID read fGeoTo write fGeoTo; property GeoFrom: TSQLGeoID read fGeoFrom write fGeoFrom; property WeightBreak: TSQLQuantityBreakID read fWeightBreak write fWeightBreak; property WeightUom: TSQLUomID read fWeightUom write fWeightUom; property WeightUnitPrice: Currency read fWeightUnitPrice write fWeightUnitPrice; property QuantityBreak: TSQLQuantityBreakID read fQuantityBreak write fQuantityBreak; property QuantityUom: TSQLUomID read fQuantityUom write fQuantityUom; property QuantityUnitPrice: Currency read fQuantityUnitPrice write fQuantityUnitPrice; property PriceBreak: TSQLQuantityBreakID read fPriceBreak write fPriceBreak; property PriceUom: TSQLUomID read fPriceUom write fPriceUom; property PriceUnitPrice: Currency read fPriceUnitPrice write fPriceUnitPrice; property OrderFlatPrice: Currency read fOrderFlatPrice write fOrderFlatPrice; property OrderPricePercent: Double read fOrderPricePercent write fOrderPricePercent; property OrderItemFlatPrice: Currency read fOrderItemFlatPrice write fOrderItemFlatPrice; property ShippingPricePercent: Double read fShippingPricePercent write fShippingPricePercent; property ProductFeatureGroup: TSQLProductFeatureGroupID read fProductFeatureGroup write fProductFeatureGroup; property OversizeUnit: Double read fOversizeUnit write fOversizeUnit; property OversizePrice: Currency read fOversizePrice write fOversizePrice; property FeaturePercent: Double read fFeaturePercent write fFeaturePercent; property FeaturePrice: Currency read fFeaturePrice write fFeaturePrice; end; // 20 TSQLShipmentGatewayConfigType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLShipmentGatewayConfigTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLShipmentGatewayConfigTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 21 TSQLShipmentGatewayConfig = class(TSQLRecord) private fEncode: RawUTF8; fShipmentGatewayConfTypeEncode: RawUTF8; fShipmentGatewayConfigType: TSQLShipmentGatewayConfigTypeID; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ShipmentGatewayConfTypeEncode: RawUTF8 read fShipmentGatewayConfTypeEncode write fShipmentGatewayConfTypeEncode; property ShipmentGatewayConfigType: TSQLShipmentGatewayConfigTypeID read fShipmentGatewayConfigType write fShipmentGatewayConfigType; property Description: RawUTF8 read FDescription write FDescription; end; // 22 TSQLShipmentGatewayDhl = class(TSQLRecord) private fShipmentGatewayConfigEncode: RawUTF8; fShipmentGatewayConfig: TSQLShipmentGatewayConfigID; fConnectUrl: RawUTF8; fConnectTimeout: Integer; fHeadVersion: RawUTF8; fHeadAction: RawUTF8; fAccessUser: Integer; fAccessPassword: RawUTF8; fAccessAccountNbr: RawUTF8; fAccessShippingKey: RawUTF8; fLabelImageFormat: RawUTF8; fRateEstimateTemplate: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property ShipmentGatewayConfigEncode: RawUTF8 read fShipmentGatewayConfigEncode write fShipmentGatewayConfigEncode; property ShipmentGatewayConfig: TSQLShipmentGatewayConfigID read fShipmentGatewayConfig write fShipmentGatewayConfig; property ConnectUrl: RawUTF8 read fConnectUrl write fConnectUrl; property ConnectTimeout: Integer read fConnectTimeout write fConnectTimeout; property HeadVersion: RawUTF8 read fHeadVersion write fHeadVersion; property HeadAction: RawUTF8 read fHeadAction write fHeadAction; property AccessUser: Integer read fAccessUser write fAccessUser; property AccessPassword: RawUTF8 read fAccessPassword write fAccessPassword; property AccessAccountNbr: RawUTF8 read fAccessAccountNbr write fAccessAccountNbr; property AccessShippingKey: RawUTF8 read fAccessShippingKey write fAccessShippingKey; property LabelImageFormat: RawUTF8 read fLabelImageFormat write fLabelImageFormat; property RateEstimateTemplate: RawUTF8 read fRateEstimateTemplate write fRateEstimateTemplate; end; // 23 TSQLShipmentGatewayFedex = class(TSQLRecord) private fShipmentGatewayConfigEncode: RawUTF8; fShipmentGatewayConfig: TSQLShipmentGatewayConfigID; fConnectUrl: RawUTF8; fConnectSoapUrl: RawUTF8; fConnectTimeout: Integer; fAccessAccountNbr: RawUTF8; fAccessMeterNumber: RawUTF8; fAccessUserKey: RawUTF8; fAccessUserPwd: RawUTF8; fLabelImageType: RawUTF8; fDefaultDropoffType: RawUTF8; fDefaultPackagingType: RawUTF8; fTemplateShipment: RawUTF8; fTemplateSubscription: RawUTF8; fRateEstimateTemplate: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property ShipmentGatewayConfigEncode: RawUTF8 read fShipmentGatewayConfigEncode write fShipmentGatewayConfigEncode; property ShipmentGatewayConfig: TSQLShipmentGatewayConfigID read fShipmentGatewayConfig write fShipmentGatewayConfig; property ConnectUrl: RawUTF8 read fConnectUrl write fConnectUrl; property ConnectSoapUrl: RawUTF8 read fConnectSoapUrl write fConnectSoapUrl; property ConnectTimeout: Integer read fConnectTimeout write fConnectTimeout; property AccessAccountNbr: RawUTF8 read fAccessAccountNbr write fAccessAccountNbr; property AccessMeterNumber: RawUTF8 read fAccessMeterNumber write fAccessMeterNumber; property AccessUserKey: RawUTF8 read fAccessUserKey write fAccessUserKey; property AccessUserPwd: RawUTF8 read fAccessUserPwd write fAccessUserPwd; property LabelImageType: RawUTF8 read fLabelImageType write fLabelImageType; property DefaultDropoffType: RawUTF8 read fDefaultDropoffType write fDefaultDropoffType; property DefaultPackagingType: RawUTF8 read fDefaultPackagingType write fDefaultPackagingType; property TemplateShipment: RawUTF8 read fTemplateShipment write fTemplateShipment; property TemplateSubscription: RawUTF8 read fTemplateSubscription write fTemplateSubscription; property RateEstimateTemplate: RawUTF8 read fRateEstimateTemplate write fRateEstimateTemplate; end; // 24 TSQLShipmentGatewayUps = class(TSQLRecord) private fShipmentGatewayConfigEncode: RawUTF8; fShipmentGatewayConfig: TSQLShipmentGatewayConfigID; fConnectUrl: RawUTF8; fConnectTimeout: Integer; fShipperNumber: RawUTF8; fBillShipperAccountNumber: RawUTF8; fAccessLicenseNumber: RawUTF8; fAccessUser: Integer; fAccessPassword: RawUTF8; fSaveCertInfo: RawUTF8; fSaveCertPath: RawUTF8; fShipperPickupType: RawUTF8; fCustomerClassification: RawUTF8; fMaxEstimateWeight: Double; fMinEstimateWeight: Double; fCodAllowCod: RawUTF8; fCodSurchargeAmount: Double; fCodSurchargeCurrencyUom: TSQLUomID; fCodSurchargeApplyToPackage: RawUTF8; fCodFundsCode: RawUTF8; fDefaultReturnLabelMemo: RawUTF8; fDefaultReturnLabelSubject: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property ShipmentGatewayConfigEncode: RawUTF8 read fShipmentGatewayConfigEncode write fShipmentGatewayConfigEncode; property ShipmentGatewayConfig: TSQLShipmentGatewayConfigID read fShipmentGatewayConfig write fShipmentGatewayConfig; property ConnectUrl: RawUTF8 read fConnectUrl write fConnectUrl; property ConnectTimeout: Integer read fConnectTimeout write fConnectTimeout; property ShipperNumber: RawUTF8 read fShipperNumber write fShipperNumber; property BillShipperAccountNumber: RawUTF8 read fBillShipperAccountNumber write fBillShipperAccountNumber; property AccessLicenseNumber: RawUTF8 read fAccessLicenseNumber write fAccessLicenseNumber; property AccessUser: Integer read fAccessUser write fAccessUser; property AccessPassword: RawUTF8 read fAccessPassword write fAccessPassword; property SaveCertInfo: RawUTF8 read fSaveCertInfo write fSaveCertInfo; property SaveCertPath: RawUTF8 read fSaveCertPath write fSaveCertPath; property ShipperPickupType: RawUTF8 read fShipperPickupType write fShipperPickupType; property CustomerClassification: RawUTF8 read fCustomerClassification write fCustomerClassification; property MaxEstimateWeight: Double read fMaxEstimateWeight write fMaxEstimateWeight; property MinEstimateWeight: Double read fMinEstimateWeight write fMinEstimateWeight; property CodAllowCod: RawUTF8 read fCodAllowCod write fCodAllowCod; property CodSurchargeAmount: Double read fCodSurchargeAmount write fCodSurchargeAmount; property CodSurchargeCurrencyUom: TSQLUomID read fCodSurchargeCurrencyUom write fCodSurchargeCurrencyUom; property CodSurchargeApplyToPackage: RawUTF8 read fCodSurchargeApplyToPackage write fCodSurchargeApplyToPackage; property CodFundsCode: RawUTF8 read fCodFundsCode write fCodFundsCode; property DefaultReturnLabelMemo: RawUTF8 read fDefaultReturnLabelMemo write fDefaultReturnLabelMemo; property DefaultReturnLabelSubject: RawUTF8 read fDefaultReturnLabelSubject write fDefaultReturnLabelSubject; end; // 25 TSQLShipmentGatewayUsps = class(TSQLRecord) private fShipmentGatewayConfigEncode: RawUTF8; fShipmentGatewayConfig: TSQLShipmentGatewayConfigID; fConnectUrl: RawUTF8; fConnectUrlLabels: RawUTF8; fConnectTimeout: Integer; fAccessUser: Integer; fAccessPassword: RawUTF8; fMaxEstimateWeight: Double; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property ShipmentGatewayConfigEncode: RawUTF8 read fShipmentGatewayConfigEncode write fShipmentGatewayConfigEncode; property ShipmentGatewayConfig: TSQLShipmentGatewayConfigID read fShipmentGatewayConfig write fShipmentGatewayConfig; property ConnectUrl: RawUTF8 read fConnectUrl write fConnectUrl; property ConnectUrlLabels: RawUTF8 read fConnectUrlLabels write fConnectUrlLabels; property ConnectTimeout: Integer read fConnectTimeout write fConnectTimeout; property AccessUser: Integer read fAccessUser write fAccessUser; property AccessPassword: RawUTF8 read fAccessPassword write fAccessPassword; property MaxEstimateWeight: Double read fMaxEstimateWeight write fMaxEstimateWeight; end; // 26 TSQLShipmentItem = class(TSQLRecord) private fShipment: TSQLShipmentID; fShipmentItemSeq: Integer; fProduct: TSQLProductID; fQuantity: Double; fShipmentContentDescription: RawUTF8; published property Shipment: TSQLShipmentID read fShipment write fShipment; property ShipmentItemSeq: Integer read fShipmentItemSeq write fShipmentItemSeq; property Product: TSQLProductID read fProduct write fProduct; property Quantity: Double read fQuantity write fQuantity; property ShipmentContentDescription: RawUTF8 read fShipmentContentDescription write fShipmentContentDescription; end; // 27 TSQLShipmentItemBilling = class(TSQLRecord) private fShipment: TSQLShipmentID; fShipmentItemSeq: Integer; fInvoiceItem: TSQLInvoiceItemID; //invoiceId, invoiceItemSeqId published property Shipment: TSQLShipmentID read fShipment write fShipment; property ShipmentItemSeq: Integer read fShipmentItemSeq write fShipmentItemSeq; property InvoiceItem: TSQLInvoiceItemID read fInvoiceItem write fInvoiceItem; end; // 28 TSQLShipmentItemFeature = class(TSQLRecord) private fShipment: TSQLShipmentID; fShipmentItemSeq: Integer; fProductFeature: TSQLProductFeatureID; published property Shipment: TSQLShipmentID read fShipment write fShipment; property ShipmentItemSeq: Integer read fShipmentItemSeq write fShipmentItemSeq; property ProductFeature: TSQLProductFeatureID read fProductFeature write fProductFeature; end; // 29 TSQLShipmentMethodType = class(TSQLRecord) private fName: RawUTF8; FDescription: RawUTF8; fSequenceNum: Integer; published property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; property SequenceNum: Integer read fSequenceNum write fSequenceNum; end; // 30 TSQLShipmentPackage = class(TSQLRecord) private fShipment: TSQLShipmentID; fShipmentPackageSeq: Integer; fShipmentBoxType: TSQLShipmentBoxTypeID; fDateCreated: TDateTime; fBoxLength: Double; fBoxHeight: Double; fBoxWidth: Double; fDimensionUom: TSQLUomID; fWeight: Double; fWeightUom: TSQLUomID; fInsuredValue: Currency; published property Shipment: TSQLShipmentID read fShipment write fShipment; property ShipmentPackageSeq: Integer read fShipmentPackageSeq write fShipmentPackageSeq; property ShipmentBoxType: TSQLShipmentBoxTypeID read fShipmentBoxType write fShipmentBoxType; property DateCreated: TDateTime read fDateCreated write fDateCreated; property BoxLength: Double read fBoxLength write fBoxLength; property BoxHeight: Double read fBoxHeight write fBoxHeight; property BoxWidth: Double read fBoxWidth write fBoxWidth; property DimensionUom: TSQLUomID read fDimensionUom write fDimensionUom; property Weight: Double read fWeight write fWeight; property WeightUom: TSQLUomID read fWeightUom write fWeightUom; property InsuredValue: Currency read fInsuredValue write fInsuredValue; end; // 31 TSQLShipmentPackageContent = class(TSQLRecord) private fShipment: TSQLShipmentID; fShipmentPackageSeq: Integer; fShipmentItemSeq: Integer; fQuantity: Double; fSubProduct: TSQLProductID; fSubProductQuantity: Double; published property Shipment: TSQLShipmentID read fShipment write fShipment; property ShipmentPackageSeq: Integer read fShipmentPackageSeq write fShipmentPackageSeq; property ShipmentItemSeq: Integer read fShipmentItemSeq write fShipmentItemSeq; property Quantity: Double read fQuantity write fQuantity; property SubProduct: TSQLProductID read fSubProduct write fSubProduct; property SubProductQuantity: Double read fSubProductQuantity write fSubProductQuantity; end; // 32 TSQLShipmentPackageRouteSeg = class(TSQLRecord) private fShipment: TSQLShipmentID; fShipmentPackageSeq: Integer; fShipmentRouteSegment: TSQLShipmentRouteSegmentID; fTrackingCode: RawUTF8; fBoxNumber: RawUTF8; fLabelImage: TSQLRawBlob; fLabelIntlSignImage: TSQLRawBlob; fLabelHtml: TSQLRawBlob; fLabelPrinted: Boolean; fInternationalInvoice: TSQLRawBlob; fPackageTransportCost: Currency; fPackageServiceCost: Currency; fPackageOtherCost: Currency; fCodAmount: Currency; fInsuredAmount: Currency; fCurrencyUom: TSQLUomID; published property Shipment: TSQLShipmentID read fShipment write fShipment; property ShipmentPackageSeq: Integer read fShipmentPackageSeq write fShipmentPackageSeq; property ShipmentRouteSegment: TSQLShipmentRouteSegmentID read fShipmentRouteSegment write fShipmentRouteSegment; property TrackingCode: RawUTF8 read fTrackingCode write fTrackingCode; property BoxNumber: RawUTF8 read fBoxNumber write fBoxNumber; property LabelImage: TSQLRawBlob read fLabelImage write fLabelImage; property LabelIntlSignImage: TSQLRawBlob read fLabelIntlSignImage write fLabelIntlSignImage; property LabelHtml: TSQLRawBlob read fLabelHtml write fLabelHtml; property LabelPrinted: Boolean read fLabelPrinted write fLabelPrinted; property InternationalInvoice: TSQLRawBlob read fInternationalInvoice write fInternationalInvoice; property PackageTransportCost: Currency read fPackageTransportCost write fPackageTransportCost; property PackageServiceCost: Currency read fPackageServiceCost write fPackageServiceCost; property PackageOtherCost: Currency read fPackageOtherCost write fPackageOtherCost; property CodAmount: Currency read fCodAmount write fCodAmount; property InsuredAmount: Currency read fInsuredAmount write fInsuredAmount; property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom; end; // 33 TSQLShipmentRouteSegment = class(TSQLRecord) private fShipment: TSQLShipmentID; fShipmentRouteSegment: Integer; fDelivery: TSQLDeliveryID; fOriginFacility: TSQLFacilityID; fDestFacility: TSQLFacilityID; fOriginContactMech: TSQLContactMechID; fOriginTelecomNumber: TSQLTelecomNumberID; fDestContactMech: TSQLContactMechID; fDestTelecomNumber: TSQLTelecomNumberID; fCarrierParty: TSQLPartyID; fShipmentMethodType: TSQLShipmentMethodTypeID; fCarrierServiceStatus: TSQLStatusItemID; fCarrierDeliveryZone: RawUTF8; fCarrierRestrictionCodes: RawUTF8; fCarrierRestrictionDesc: RawUTF8; fBillingWeight: Double; fBillingWeightUom: TSQLUomID; fActualTransportCost: Currency; fActualServiceCost: Currency; fActualOtherCost: Currency; fActualCost: Currency; fCurrencyUom: TSQLUomID; fActualStartDate: TDateTime; fActualArrivalDate: TDateTime; fEstimatedStartDate: TDateTime; fEstimatedArrivalDate: TDateTime; fTrackingIdNumber: RawUTF8; fTrackingDigest: TSQLRawBlob; fUpdatedByUserLogin: TSQLUserLoginID; fLastUpdatedDate: TDateTime; fHomeDeliveryType: Integer; fHomeDeliveryDate: TDateTime; fThirdPartyAccountNumber: Integer; fThirdPartyPostalCode: Integer; fThirdPartyCountryGeoCode: Integer; fUpsHighValueReport: TSQLRawBlob; published property Shipment: TSQLShipmentID read fShipment write fShipment; property ShipmentRouteSegment: Integer read fShipmentRouteSegment write fShipmentRouteSegment; property Delivery: TSQLDeliveryID read fDelivery write fDelivery; property OriginFacility: TSQLFacilityID read fOriginFacility write fOriginFacility; property DestFacility: TSQLFacilityID read fDestFacility write fDestFacility; property OriginContactMech: TSQLContactMechID read fOriginContactMech write fOriginContactMech; property OriginTelecomNumber: TSQLTelecomNumberID read fOriginTelecomNumber write fOriginTelecomNumber; property DestContactMech: TSQLContactMechID read fDestContactMech write fDestContactMech; property DestTelecomNumber: TSQLTelecomNumberID read fDestTelecomNumber write fDestTelecomNumber; property CarrierParty: TSQLPartyID read fCarrierParty write fCarrierParty; property ShipmentMethodType: TSQLShipmentMethodTypeID read fShipmentMethodType write fShipmentMethodType; property CarrierServiceStatus: TSQLStatusItemID read fCarrierServiceStatus write fCarrierServiceStatus; property CarrierDeliveryZone: RawUTF8 read fCarrierDeliveryZone write fCarrierDeliveryZone; property CarrierRestrictionCodes: RawUTF8 read fCarrierRestrictionCodes write fCarrierRestrictionCodes; property CarrierRestrictionDesc: RawUTF8 read fCarrierRestrictionDesc write fCarrierRestrictionDesc; property BillingWeight: Double read fBillingWeight write fBillingWeight; property BillingWeightUom: TSQLUomID read fBillingWeightUom write fBillingWeightUom; property ActualTransportCost: Currency read fActualTransportCost write fActualTransportCost; property ActualServiceCost: Currency read fActualServiceCost write fActualServiceCost; property ActualOtherCost: Currency read fActualOtherCost write fActualOtherCost; property ActualCost: Currency read fActualCost write fActualCost; property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom; property ActualStartDate: TDateTime read fActualStartDate write fActualStartDate; property ActualArrivalDate: TDateTime read fActualArrivalDate write fActualArrivalDate; property EstimatedStartDate: TDateTime read fEstimatedStartDate write fEstimatedStartDate; property EstimatedArrivalDate: TDateTime read fEstimatedArrivalDate write fEstimatedArrivalDate; property TrackingIdNumber: RawUTF8 read fTrackingIdNumber write fTrackingIdNumber; property TrackingDigest: TSQLRawBlob read fTrackingDigest write fTrackingDigest; property UpdatedByUserLogin: TSQLUserLoginID read fUpdatedByUserLogin write fUpdatedByUserLogin; property LastUpdatedDate: TDateTime read fLastUpdatedDate write fLastUpdatedDate; property HomeDeliveryType: Integer read fHomeDeliveryType write fHomeDeliveryType; property HomeDeliveryDate: TDateTime read fHomeDeliveryDate write fHomeDeliveryDate; property ThirdPartyAccountNumber: Integer read fThirdPartyAccountNumber write fThirdPartyAccountNumber; property ThirdPartyPostalCode: Integer read fThirdPartyPostalCode write fThirdPartyPostalCode; property ThirdPartyCountryGeoCode: Integer read fThirdPartyCountryGeoCode write fThirdPartyCountryGeoCode; property UpsHighValueReport: TSQLRawBlob read fUpsHighValueReport write fUpsHighValueReport; end; { // 34 TSQL = class(TSQLRecord) private published property read write ; property read write ; property read write ; property read write ; property read write ; end;} // 35 TSQLShipmentStatus = class(TSQLRecord) private fStatus: TSQLStatusItemID; fShipment: TSQLShipmentID; fStatusDate: TDateTime; fChangeByUserLogin: TSQLUserLoginID; published property Status: TSQLStatusItemID read fStatus write fStatus; property Shipment: TSQLShipmentID read fShipment write fShipment; property StatusDate: TDateTime read fStatusDate write fStatusDate; property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin; end; // 36 TSQLShipmentType = class(TSQLRecord) private fEncode: RawUTF8; fParentEncode: RawUTF8; fParent: TSQLShipmentTypeID; fHasTable: Boolean; fName: RawUTF8; FDescription: RawUTF8; public class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override; published property Encode: RawUTF8 read fEncode write fEncode; property ParentEncode: RawUTF8 read fParentEncode write fParentEncode; property Parent: TSQLShipmentTypeID read fParent write fParent; property HasTable: Boolean read fHasTable write fHasTable; property Name: RawUTF8 read fName write fName; property Description: RawUTF8 read FDescription write FDescription; end; // 37 TSQLShipmentTypeAttr = class(TSQLRecord) private fShipmentType: TSQLShipmentTypeID; fAttrName: RawUTF8; fDescription: RawUTF8; published property ShipmentType: TSQLShipmentTypeID read fShipmentType write fShipmentType; property AttrName: RawUTF8 read fAttrName write fAttrName; property Description: RawUTF8 read fDescription write fDescription; end; // 38 TSQLShippingDocument = class(TSQLRecord) private fDocument: TSQLDocumentID; fShipment: TSQLShipmentItemID; //shipmentId, shipmentItemSeqId fShipmentPackage: TSQLShipmentPackageID; //shipmentId, shipmentPackageSeqId fDescription: RawUTF8; published property Document: TSQLDocumentID read fDocument write fDocument; property Shipment: TSQLShipmentItemID read fShipment write fShipment; property ShipmentPackage: TSQLShipmentPackageID read fShipmentPackage write fShipmentPackage; property Description: RawUTF8 read fDescription write fDescription; end; implementation uses Classes, SysUtils; // 1 class procedure TSQLShipmentContactMechType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLShipmentContactMechType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLShipmentContactMechType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShipmentContactMechType.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 2 class procedure TSQLShipmentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLShipmentType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLShipmentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShipmentType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ShipmentType set Parent=(select c.id from ShipmentType c where c.Encode=ShipmentType.ParentEncode);'); finally Rec.Free; end; end; // 3 class procedure TSQLRejectionReason.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLRejectionReason; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLRejectionReason.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','RejectionReason.json']))); try while Rec.FillOne do Server.Add(Rec,true); finally Rec.Free; end; end; // 4 class procedure TSQLShipmentGatewayConfigType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLShipmentGatewayConfigType; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLShipmentGatewayConfigType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShipmentGatewayConfigType.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ShipmentGatewayConfigType set Parent=(select c.id from ShipmentGatewayConfigType c where c.Encode=ShipmentGatewayConfigType.ParentEncode);'); Server.Execute('update ShipmentGatewayConfig set ShipmentGatewayConfigType=(select c.id from ShipmentGatewayConfigType c where c.Encode=ShipmentGatewayConfig.ShipmentGatewayConfTypeEncode);'); finally Rec.Free; end; end; // 5 class procedure TSQLShipmentGatewayConfig.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLShipmentGatewayConfig; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLShipmentGatewayConfig.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShipmentGatewayConfig.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ShipmentGatewayConfig set ShipmentGatewayConfigType=(select c.id from ShipmentGatewayConfigType c where c.Encode=ShipmentGatewayConfig.ShipmentGatewayConfTypeEncode);'); Server.Execute('update ShipmentGatewayDhl set ShipmentGatewayConfig=(select c.id from ShipmentGatewayConfig c where c.Encode=ShipmentGatewayConfigEncode);'); finally Rec.Free; end; end; // 6 class procedure TSQLShipmentGatewayDhl.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLShipmentGatewayDhl; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLShipmentGatewayDhl.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShipmentGatewayDhl.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ShipmentGatewayDhl set ShipmentGatewayConfig=(select c.id from ShipmentGatewayConfig c where c.Encode=ShipmentGatewayConfigEncode);'); finally Rec.Free; end; end; // 7 class procedure TSQLShipmentGatewayFedex.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLShipmentGatewayFedex; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLShipmentGatewayFedex.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShipmentGatewayFedex.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ShipmentGatewayFedex set ShipmentGatewayConfig=(select c.id from ShipmentGatewayConfig c where c.Encode=ShipmentGatewayConfigEncode);'); finally Rec.Free; end; end; // 8 class procedure TSQLShipmentGatewayUps.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLShipmentGatewayUps; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLShipmentGatewayUps.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShipmentGatewayUps.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ShipmentGatewayUps set ShipmentGatewayConfig=(select c.id from ShipmentGatewayConfig c where c.Encode=ShipmentGatewayConfigEncode);'); finally Rec.Free; end; end; // 9 class procedure TSQLShipmentGatewayUsps.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); var Rec: TSQLShipmentGatewayUsps; begin inherited; if FieldName<>'' then exit; // create database only if void Rec := TSQLShipmentGatewayUsps.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ShipmentGatewayUsps.json']))); try while Rec.FillOne do Server.Add(Rec,true); Server.Execute('update ShipmentGatewayUsps set ShipmentGatewayConfig=(select c.id from ShipmentGatewayConfig c where c.Encode=ShipmentGatewayConfigEncode);'); finally Rec.Free; end; end; end.
unit frm_catalogoSeveridadHallazgos; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, frm_connection, global, ComCtrls, ToolWin, StdCtrls, ExtCtrls, DBCtrls, Mask, frm_barra, adodb, db, Menus, OleCtrls, frxClass, frxDBSet, ZAbstractRODataset, ZAbstractDataset, ZDataset, udbgrid, unitexcepciones, unittbotonespermisos, UnitValidaTexto, unitactivapop; type TfrmcatalogoSeveridadHallazgos = class(TForm) grid_severidad: TDBGrid; Label2: TLabel; frmBarra1: TfrmBarra; tsSeveridad: TDBEdit; PopupPrincipal: TPopupMenu; Insertar1: TMenuItem; Editar1: TMenuItem; N1: TMenuItem; Registrar1: TMenuItem; Can1: TMenuItem; N2: TMenuItem; Eliminar1: TMenuItem; Refresh1: TMenuItem; N4: TMenuItem; Cut1: TMenuItem; Copy1: TMenuItem; N3: TMenuItem; Salir1: TMenuItem; tzSeveridad: TZQuery; dsSeveridad: TDataSource; tzSeveridadiIdSeveridad: TIntegerField; tzSeveridadsSeveridad: TStringField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure grid_severidadCellClick(Column: TColumn); procedure tsIdPersonalKeyPress(Sender: TObject; var Key: Char); procedure frmBarra1btnAddClick(Sender: TObject); procedure frmBarra1btnEditClick(Sender: TObject); procedure frmBarra1btnPostClick(Sender: TObject); procedure frmBarra1btnCancelClick(Sender: TObject); procedure frmBarra1btnDeleteClick(Sender: TObject); procedure frmBarra1btnRefreshClick(Sender: TObject); procedure frmBarra1btnExitClick(Sender: TObject); procedure Insertar1Click(Sender: TObject); procedure Editar1Click(Sender: TObject); procedure Registrar1Click(Sender: TObject); procedure Can1Click(Sender: TObject); procedure Eliminar1Click(Sender: TObject); procedure Refresh1Click(Sender: TObject); procedure Salir1Click(Sender: TObject); procedure grid_severidadEnter(Sender: TObject); procedure grid_severidadKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure grid_severidadKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure tsIdsistemazKeyPress(Sender: TObject; var Key: Char); procedure tsSeveridadEnter(Sender: TObject); procedure tsSeveridadExit(Sender: TObject); procedure grid_severidadMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure grid_severidadMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure grid_severidadTitleClick(Column: TColumn); procedure Cut1Click(Sender: TObject); procedure Copy1Click(Sender: TObject); procedure tsSeveridadKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; var frmcatalogoSeveridadHallazgos : TfrmcatalogoSeveridadHallazgos; utgrid : ticdbgrid; sOldId : string; botonpermiso : tbotonespermisos; sOpcion : string; implementation uses frm_inteligent; {$R *.dfm} procedure TfrmcatalogoSeveridadHallazgos.FormClose(Sender: TObject; var Action: TCloseAction); begin action := cafree ; utgrid.Destroy; botonpermiso.Free; end; procedure TfrmcatalogoSeveridadHallazgos.FormShow(Sender: TObject); begin BotonPermiso := TBotonesPermisos.Create(Self, connection.zConnection, global_grupo, '', PopupPrincipal); OpcButton := '' ; frmbarra1.btnCancel.Click ; //tzMarcas := False ; tzSeveridad.Open ; grid_severidad.SetFocus; UtGrid:=TicdbGrid.create(grid_severidad); BotonPermiso.permisosBotones(frmBarra1); frmbarra1.btnPrinter.Enabled := False; tsSeveridad.Enabled := False ; end; procedure TfrmcatalogoSeveridadHallazgos.grid_severidadCellClick(Column: TColumn); begin If frmbarra1.btnCancel.Enabled = True then frmBarra1.btnCancel.Click ; end; procedure TfrmcatalogoSeveridadHallazgos.tsIdPersonalKeyPress(Sender: TObject; var Key: Char); begin // if key = #13 then // tsMarca.SetFocus ; end; procedure TfrmcatalogoSeveridadHallazgos.frmBarra1btnAddClick(Sender: TObject); begin frmBarra1.btnAddClick(Sender); Insertar1.Enabled := False ; Editar1.Enabled := False ; Registrar1.Enabled := True ; Can1.Enabled := True ; Eliminar1.Enabled := False ; Refresh1.Enabled := False ; Salir1.Enabled := False ; tzSeveridad.Append ; tzSeveridad.FieldValues['sSeveridad'] := '' ; activapop(frmcatalogoSeveridadHallazgos,popupprincipal); BotonPermiso.permisosBotones(frmBarra1); frmbarra1.btnPrinter.Enabled := False; grid_severidad.Enabled := False; tsSeveridad.Enabled := True; tsSeveridad.SetFocus end; procedure TfrmcatalogoSeveridadHallazgos.frmBarra1btnEditClick(Sender: TObject); begin If tzSeveridad.RecordCount > 0 Then Begin try frmBarra1.btnEditClick(Sender); Insertar1.Enabled := False ; Editar1.Enabled := False ; Registrar1.Enabled := True ; Can1.Enabled := True ; Eliminar1.Enabled := False ; Refresh1.Enabled := False ; Salir1.Enabled := False ; sOpcion := 'Edit'; sOldId := tzSeveridad.FieldValues['iIdSeveridad']; tzSeveridad.Edit ; grid_severidad.Enabled := False; tsSeveridad.Enabled := True ; tsSeveridad.SetFocus; activapop(frmcatalogoSeveridadHallazgos,popupprincipal) except on e : exception do begin UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'Catalogo de Severidad de Hallazgo de Inspeccion', 'Al agregar registro', 0); end; end; End; BotonPermiso.permisosBotones(frmBarra1); frmbarra1.btnPrinter.Enabled := False; end; procedure TfrmcatalogoSeveridadHallazgos.frmBarra1btnPostClick(Sender: TObject); var lEdicion : boolean; nombres, cadenas : TStringList; Clave : string; begin {Validaciones de campos} nombres:=TStringList.Create;cadenas:=TStringList.Create; nombres.Add('Descripcion'); cadenas.Add(tsSeveridad.Text); if not validaTexto(nombres, cadenas, 'Clave', tsSeveridad.Text) then begin MessageDlg(UnitValidaTexto.errorValidaTexto, mtInformation, [mbOk], 0); exit; end; {Continua insercion de datos..} lEdicion := tzSeveridad.state = dsEdit;//capturar la bandera para usarla luego del post Try tzSeveridad.Post ; Insertar1.Enabled := True ; Editar1.Enabled := True ; Registrar1.Enabled := False ; Can1.Enabled := False ; Eliminar1.Enabled := True ; Refresh1.Enabled := True ; Salir1.Enabled := True ; frmBarra1.btnPostClick(Sender); desactivapop(popupprincipal); except on e : exception do begin UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'Catalogo de Severidad de Hallazgo de Inspeccion', 'Al salvar registro', 0); frmBarra1.btnCancel.Click ; lEdicion := false; end; end; // if (lEdicion) and (sOldId <> tzSistematizacion.FieldValues['iIdsistematizacion']) then // begin // //El registro fue editado y su ID cambio, es necesario actualizar este ID en tablas dependientes // Connection.zCommand.Active := False ; // Connection.zCommand.SQL.Clear ; // Connection.zCommand.SQL.Add('UPDATE sistematizacion SET sIdMarca = :nuevo WHERE sIdMarca = :viejo'); // Connection.zCommand.Params.ParamByName('nuevo').value := tzSistematizacion.FieldValues['sIdMarca']; // Connection.zCommand.Params.ParamByName('viejo').value := sOldId; // try // Connection.zCommand.ExecSQL; // except // MessageDlg('Ocurrio un error al actualizar los registros de la tabla dependiente "marcas".', mtInformation, [mbOk], 0); // end; // end; BotonPermiso.permisosBotones(frmBarra1); frmbarra1.btnPrinter.Enabled := False; if sOpcion = 'Edit' then begin grid_severidad.Enabled := True; tsSeveridad.Enabled := False ; sOpcion := ''; end; end; procedure TfrmcatalogoSeveridadHallazgos.frmBarra1btnCancelClick(Sender: TObject); begin frmBarra1.btnCancelClick(Sender); tzSeveridad.Cancel ; tsSeveridad.Enabled:=false; Insertar1.Enabled := True ; Editar1.Enabled := True ; Registrar1.Enabled := False ; Can1.Enabled := False ; Eliminar1.Enabled := True ; Refresh1.Enabled := True ; Salir1.Enabled := True ; desactivapop(popupprincipal); BotonPermiso.permisosBotones(frmBarra1); frmbarra1.btnPrinter.Enabled := False; grid_severidad.Enabled := True; sOpcion := ''; end; procedure TfrmcatalogoSeveridadHallazgos.frmBarra1btnDeleteClick(Sender: TObject); begin If tzSeveridad.RecordCount > 0 then if MessageDlg('Desea eliminar el Registro Activo?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin try // Connection.QryBusca.Active := False ; // Connection.QryBusca.SQL.Clear ; // Connection.QryBusca.SQL.Add('Select sIdMarca from insumos Where sIdMarca =:Clave'); // Connection.QryBusca.Params.ParamByName('Clave').DataType := ftString ; // Connection.QryBusca.Params.ParamByName('Clave').Value := tzSistematizacion.FieldValues['sIdMarca'] ; // Connection.QryBusca.Open ; // If Connection.QryBusca.RecordCount > 0 Then // MessageDlg('No se puede Borrar el Registro por que esta asignado a un Material en la tabla Insumos', mtInformation, [mbOk], 0) // Else tzSeveridad.Delete ; except on e : exception do begin UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'Catalogo de Severidad de Hallazgo de Inspeccion', 'Al eliminar registro', 0); end; end end end; procedure TfrmcatalogoSeveridadHallazgos.frmBarra1btnRefreshClick(Sender: TObject); begin tzSeveridad.refresh ; end; procedure TfrmcatalogoSeveridadHallazgos.frmBarra1btnExitClick(Sender: TObject); begin frmBarra1.btnExitClick(Sender); Insertar1.Enabled := True ; Editar1.Enabled := True ; Registrar1.Enabled := False ; Can1.Enabled := False ; Eliminar1.Enabled := True ; Refresh1.Enabled := True ; Salir1.Enabled := True ; Close end; procedure TfrmcatalogoSeveridadHallazgos.Insertar1Click(Sender: TObject); begin frmBarra1.btnAdd.Click end; procedure TfrmcatalogoSeveridadHallazgos.Copy1Click(Sender: TObject); begin UtGrid.AddRowsFromClip; end; procedure TfrmcatalogoSeveridadHallazgos.Cut1Click(Sender: TObject); begin UtGrid.CopyRowsToClip; end; procedure TfrmcatalogoSeveridadHallazgos.Editar1Click(Sender: TObject); begin frmBarra1.btnEdit.Click end; procedure TfrmcatalogoSeveridadHallazgos.Registrar1Click(Sender: TObject); begin frmBarra1.btnPost.Click end; procedure TfrmcatalogoSeveridadHallazgos.Can1Click(Sender: TObject); begin frmBarra1.btnCancel.Click end; procedure TfrmcatalogoSeveridadHallazgos.Eliminar1Click(Sender: TObject); begin frmBarra1.btnDelete.Click end; procedure TfrmcatalogoSeveridadHallazgos.Refresh1Click(Sender: TObject); begin frmBarra1.btnRefresh.Click end; procedure TfrmcatalogoSeveridadHallazgos.Salir1Click(Sender: TObject); begin frmBarra1.btnExit.Click end; procedure TfrmcatalogoSeveridadHallazgos.grid_severidadEnter(Sender: TObject); begin If frmbarra1.btnCancel.Enabled = True then frmBarra1.btnCancel.Click ; end; procedure TfrmcatalogoSeveridadHallazgos.grid_severidadKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If frmbarra1.btnCancel.Enabled = True then frmBarra1.btnCancel.Click ; end; procedure TfrmcatalogoSeveridadHallazgos.grid_severidadKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin If frmbarra1.btnCancel.Enabled = True then frmBarra1.btnCancel.Click ; end; procedure TfrmcatalogoSeveridadHallazgos.grid_severidadMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin UtGrid.dbGridMouseMoveCoord(x,y); end; procedure TfrmcatalogoSeveridadHallazgos.grid_severidadMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin UtGrid.DbGridMouseUp(Sender,Button,Shift,X, Y); end; procedure TfrmcatalogoSeveridadHallazgos.grid_severidadTitleClick(Column: TColumn); begin UtGrid.DbGridTitleClick(Column); end; procedure TfrmcatalogoSeveridadHallazgos.tsIdsistemazKeyPress(Sender: TObject; var Key: Char); begin If Key = #13 Then tsSeveridad.SetFocus end; procedure TfrmcatalogoSeveridadHallazgos.tsSeveridadEnter(Sender: TObject); begin tsSeveridad.Color := global_color_entrada end; procedure TfrmcatalogoSeveridadHallazgos.tsSeveridadExit(Sender: TObject); begin tsSeveridad.Color := global_color_salida end; procedure TfrmcatalogoSeveridadHallazgos.tsSeveridadKeyPress(Sender: TObject; var Key: Char); begin tsSeveridad.SetFocus end; end.
{ Copyright (C) 1998-2018, written by Shkolnik Mike, Scalabium Software E-Mail: mshkolnik@scalabium.com mshkolnik@yahoo.com WEB: http://www.scalabium.com The TSMLanguage component allows to develop the multilanguage application without recompile. You can define the external files with translated strings and custom messages and in run-time to load it for modification of component properties. } unit SMLang; interface {$I SMVersion.inc} uses Classes, IniFiles, TypInfo, SysUtils; const cTabChar = '~'; type TLanguageEvent = procedure(Sender: TObject; AComponent: TComponent; PropertyName, OldValue: string; var NewValue: string) of object; {$IFDEF SM_ADD_ComponentPlatformsAttribute} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TSMLanguage = class(TComponent) private FAutoTranslate: Boolean; FResourceFile: string; FSeparator: string; FOnBeforeTranslation: TNotifyEvent; FOnAfterTranslation: TNotifyEvent; FOnTranslate: TLanguageEvent; function GetFirstPart(var AString: string): string; function IsLastPart(AString: string): Boolean; function GetProperty(AComponent: TComponent; sProperty: string): string; procedure SetProperty(AComponent: TComponent; sProperty, sValue: string); procedure TranslateProperty(sProperty, sTranslation: string); procedure SetResourceFile(Value: string); procedure SetStringsProperty(AComponent: TComponent; PropInfo: PPropInfo; sValues: string); protected procedure SetSeparator(const Value: string); public procedure SaveResources(AComponent: TComponent; AFileName: string); procedure LoadResources(AFileName: string); function TranslateUserMessage(Ident, sMessage: string): string; published property AutoTranslate: Boolean read FAutoTranslate write FAutoTranslate default False; property ResourceFile: string read FResourceFile write SetResourceFile; property StringsSeparator: string read FSeparator write SetSeparator; property OnBeforeTranslation: TNotifyEvent read FOnBeforeTranslation write FOnBeforeTranslation; property OnAfterTranslation: TNotifyEvent read FOnAfterTranslation write FOnAfterTranslation; property OnTranslate: TLanguageEvent read FOnTranslate write FOnTranslate; end; implementation uses Forms; const strSectionName = 'Translations'; { TSMLanguage } function TSMLanguage.GetFirstPart(var AString: string): string; var i: Integer; begin i := Pos('.', AString); if (i > 0) then begin Result := Copy(AString, 1, i-1); Delete(AString, 1, i); end else begin Result := AString; AString := ''; end; AString := Trim(AString); Result := Trim(Result); end; function TSMLanguage.IsLastPart(AString: string): Boolean; begin Result := (Pos('.', AString) = 0); end; function TSMLanguage.GetProperty(AComponent: TComponent; sProperty: string): string; var PropInfo: PPropInfo; begin PropInfo := GetPropInfo(AComponent.ClassInfo, sProperty); if (PropInfo <> nil) then if (PropInfo^.PropType^^.Kind in [tkString, tkLString, tkWString {$IFDEF SMForDelphi2009} , tkUString {$ENDIF} {, tkInteger}]) then Result := GetStrProp(AComponent, PropInfo); end; procedure TSMLanguage.SetProperty(AComponent: TComponent; sProperty, sValue: string); var PropInfo: PPropInfo; begin if (AComponent <> nil) then begin PropInfo := GetPropInfo(AComponent.ClassInfo, sProperty); if (PropInfo <> nil) then begin case PropInfo^.PropType^^.Kind of {$IFDEF SMForDelphi2009} tkUString, {$ENDIF} tkString, tkLString, tkWString: SetStrProp(AComponent, PropInfo, sValue); tkInteger: SetOrdProp(AComponent, PropInfo, StrToInt(sValue)) else SetStringsProperty(AComponent, PropInfo, sValue); end; end; end; end; function ConvertStrings(const s: string): string; begin Result := s end; procedure TSMLanguage.SaveResources(AComponent: TComponent; AFileName: string); var resFile: TIniFile; procedure ProcessComponent(AComp: TComponent; strParentName: string); var i, j, k: Integer; PropList: TPropList; PropInfo: PPropInfo; begin if not Assigned(AComp) or (AComp.Name = '') or (AComp = Self) then exit; i := GetPropList(AComp.ClassInfo, tkProperties, @PropList); for j := 0 to i-1 do begin if (PropList[j].Name = 'Name') then continue; PropInfo := GetPropInfo(AComp.ClassInfo, PropList[j].Name); if (PropInfo <> nil) then if (PropInfo^.PropType^^.Kind in [tkString, tkLString, tkWString {$IFDEF SMForDelphi2009} , tkUString {$ENDIF} {, tkInteger}]) then begin try resFile.WriteString(strSectionName, strParentName + AComp.Name + '.' + PropList[j].Name, GetStrProp(AComp, PropInfo)) except end end else if (PropInfo^.PropType^^.Kind = tkClass) then begin k := GetOrdProp(AComp, PropInfo); if (TObject(k) is TStrings) then resFile.WriteString(strSectionName, strParentName + AComp.Name + '.' + PropList[j].Name, ConvertStrings(TStrings(k).Text)) end; end; for i := 0 to AComp.ComponentCount-1 do ProcessComponent(AComp.Components[i], AComp.Name + '.'); end; begin if AFileName = '' then AFileName := ResourceFile; if FileExists(AFileName) then DeleteFile(AFileName); resFile := TIniFile.Create(AFileName); with resFile do try if Assigned(AComponent) then ProcessComponent(AComponent, '') else ProcessComponent(Self.Owner, ''); finally Free; end; end; procedure TSMLanguage.LoadResources(AFileName: string); var i: Integer; Properties: TStrings; begin if (Assigned(FOnBeforeTranslation)) then FOnBeforeTranslation(Self); if AFileName = '' then AFileName := ResourceFile; Properties := TStringList.Create; with TIniFile.Create(AFileName) do try ReadSectionValues(strSectionName, Properties); for i := 0 to Properties.Count-1 do if (Trim(Properties.Names[i]) <> '') then // TranslateProperty(Properties[i], ReadString(strSectionName, Properties[i], '')); TranslateProperty(Properties.Names[i], Properties.Values[Properties.Names[i]]); finally Free; end; Properties.Free; if (Assigned(FOnAfterTranslation)) then FOnAfterTranslation(Self); end; procedure TSMLanguage.TranslateProperty(sProperty, sTranslation: string); var AComponent: TComponent; i: Integer; begin sProperty := Trim(sProperty); AComponent := Application; i := Pos(cTabChar, sTranslation); while i > 0 do begin sTranslation := Copy(sTranslation, 1, i-1) + #9 + Copy(sTranslation, i+1, Length(sTranslation)-i); i := Pos(cTabChar, sTranslation); end; if (sProperty <> '') then while (not IsLastPart(sProperty)) do if Assigned(AComponent) then AComponent := AComponent.FindComponent(GetFirstPart(sProperty)) else exit; if ((AComponent <> nil) and (sTranslation <> '')) then begin if (Assigned(FOnTranslate)) then FOnTranslate(Self, AComponent, sProperty, GetProperty(AComponent, sProperty), sTranslation); SetProperty(AComponent, GetFirstPart(sProperty), sTranslation); end; end; procedure TSMLanguage.SetResourceFile(Value: string); begin if Value <> FResourceFile then begin FResourceFile := Value; if (not (csLoading in ComponentState)) and FAutoTranslate then LoadResources(''); end; end; function TSMLanguage.TranslateUserMessage(Ident, sMessage: string): string; begin with TIniFile.Create(ResourceFile) do try Result := ReadString('Custom', Ident, sMessage); finally Free; end; end; procedure TSMLanguage.SetStringsProperty(AComponent: TComponent; PropInfo: PPropInfo; sValues: string); var AStrings: TStringList; sBuffer: string; i: Integer; begin AStrings := TStringList.Create; i := Pos(FSeparator, sValues); while (i > 0) do begin sBuffer := Copy(sValues, 1, i-1); Delete(sValues, 1, i - 1 + Length(FSeparator)); i := Pos(FSeparator, sValues); AStrings.Add(Trim(sBuffer)); end; if (Length(Trim(sValues)) > 0) then AStrings.Add(Trim(sValues)); SetOrdProp(AComponent, PropInfo, LongInt(Pointer(AStrings))); AStrings.Free; end; procedure TSMLanguage.SetSeparator(const Value: string); begin if (Length(Trim(Value)) = 0) then FSeparator := #13#10 else FSeparator := Value; end; end.
unit Nathan.MapReturn.Tests; interface uses DUnitX.TestFramework, Nathan.MapFile.Core; type [TestFixture] TTestMapReturn = class(TObject) public [Test] procedure Test_ToString; end; implementation procedure TTestMapReturn.Test_ToString; var Cut: TMapReturn; Actual: string; begin // Arrange... Cut.Offset := 0; Cut.LineNumberFromAddr := $0020413C; Cut.ModuleStartFromAddr := $0020413C; Cut.ModuleNameFromAddr := 'Main'; Cut.ProcNameFromAddr := 'Main.TForm1.FormCreate'; Cut.SourceNameFromAddr := 'Main.pas'; Cut.LineNumberErrors := 1; // Act... Actual := Cut.ToString; // Assert... Assert.AreEqual('Offset: 0'#$D#$A'Codeline: 2113852'#$D#$A'Startaddress from Module: $0020413C'#$D#$A'Name of procedure from address: Main.TForm1.FormCreate'#$D#$A'Sourcename from address: Main.pas', Actual); end; initialization TDUnitX.RegisterTestFixture(TTestMapReturn); end.
{ basic jobs for multi-threading (C) 2014 ti_dic@hotmail.com License: modified LGPL with linking exception (like RTL, FCL and LCL) See the file COPYING.modifiedLGPL.txt, included in the Lazarus distribution, for details about the license. See also: https://wiki.lazarus.freepascal.org/FPC_modified_LGPL } unit mvJobs; {$mode objfpc}{$H+} interface uses Classes, SysUtils, mvJobQueue; type { TSimpleJob: job with only one task } TSimpleJob = class(TJob) private FRunning, FEnded: boolean; protected function pGetTask: integer; override; procedure pTaskStarted(aTask: integer); override; procedure pTaskEnded(aTask: integer; {%H-}aExcept: Exception); override; public function Running: boolean; override; end; TJobProc = procedure (Data: TObject; Job: TJob) of object; { TEventJob: job with only one task (callback an event) } TEventJob = class(TSimpleJob) private FData: TObject; FTask: TJobProc; FOwnData: Boolean; public constructor Create(aEvent: TJobProc; Data: TObject; OwnData: Boolean; JobName: String = ''); virtual; destructor Destroy; override; procedure ExecuteTask(aTask: integer; {%H-}FromWaiting: boolean); override; end; implementation { TEventJob } constructor TEventJob.Create(aEvent: TJobProc; Data: TObject; OwnData: Boolean; JobName: String = ''); begin Name := JobName; FTask := aEvent; if Assigned(Data) or OwnData then begin FData := Data; FOwnData := OwnData; end else begin FOwnData := false; FData := self; end; end; destructor TEventJob.Destroy; begin if FOwnData then if FData <> self then FData.Free; inherited Destroy; end; procedure TEventJob.ExecuteTask(aTask: integer; FromWaiting: boolean); begin if Assigned(FTask) then FTask(FData, self); end; { TSimpleJob } function TSimpleJob.pGetTask: integer; begin if FRunning or Cancelled then begin if not FRunning then Result := ALL_TASK_COMPLETED else Result := NO_MORE_TASK end else begin if FEnded then Result := ALL_TASK_COMPLETED else Result := 1; end; end; procedure TSimpleJob.pTaskStarted(aTask: integer); begin FEnded := false; FRunning := True; end; procedure TSimpleJob.pTaskEnded(aTask: integer; aExcept: Exception); begin FEnded := True; FRunning := False; end; function TSimpleJob.Running: boolean; begin Result := FRunning; end; end.