text stringlengths 14 6.51M |
|---|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit StructureViewAPI;
interface
uses Winapi.Windows, Winapi.CommCtrl, System.SysUtils, System.Classes, Vcl.Menus, Vcl.Controls, Winapi.ActiveX, ToolsAPI;
const
SourceCodeStructureType = 'SourceCode.StructureType';
ErrorsNodeType = 'Errors.NodeType';
DesignerStructureType = 'Designer.StructureType';
// These view selection options mirror some corresponding options on the
// Virtual tree-view used to implement the structure view
voLevelSelectConstraint = $0001; // Constrain selection to the same level as the selection anchor.
voMultiSelect = $0002; // Allow more than one node to be selected.
voRightClickSelect = $0004; // Allow selection, dragging etc. with the right mouse button.
voSiblingSelectConstraint = $0008; // constrain selection to nodes with same parent
type
{$MINENUMSIZE 4}
TOTAChildUpdateKind = (ckNodeAdded, ckNodeRemoved, ckChanged);
TOTADragState = (odsDragEnter, odsDragLeave, odsDragMove);
TOTADropMode = (odmNowhere, odmAbove, odmOnNode, odmBelow);
TOTANodePreservationMode = (onpNone, onpIntegrated, onpExternal);
{$MINENUMSIZE 1}
IOTAStructureContext = interface;
IOTAStructureNode = interface;
IOTAStructureNodeMenuItem = interface;
IOTAStructureNotifier = interface(IOTANotifier)
['{F158EF17-342C-46AA-BA06-5DCD544354BF}']
procedure StructureChanged(const Context: IOTAStructureContext);
procedure NodeEdited(const Node: IOTAStructureNode);
procedure NodeFocused(const Node: IOTAStructureNode);
procedure NodeSelected(const Node: IOTAStructureNode);
procedure DefaultNodeAction(const Node: IOTAStructureNode);
procedure VisibleChanged(Visible: WordBool);
end;
// The base methods that are required by the StructureView form
IOTABaseStructureView = interface(IDispatch)
['{04084727-3466-4220-9337-4F2A0CC17F87}']
procedure BeginUpdate; safecall;
procedure EndUpdate; safecall;
function GetStructureContext: IOTAStructureContext; safecall;
function GetStructureType: WideString; safecall;
procedure SetStructureContext(const AContext: IOTAStructureContext); safecall;
procedure StructureChanged(Deferred: WordBool); safecall;
procedure NodeSelected(const Node: IOTAStructureNode);
procedure NodeFocused(const Node: IOTAStructureNode);
procedure NodeEdited(const Node: IOTAStructureNode);
end;
IOTAStructureView = interface(IOTABaseStructureView)
['{A37053F0-8E22-47A2-8E99-1CFFFC392BEF}']
function AddNotifier(const Notifier: IOTAStructureNotifier): Integer; safecall;
procedure ChildNodeUpdated(const ParentNode, ChildNode: IOTAStructureNode;
AUpdateKind: TOTAChildUpdateKind); safecall;
procedure ClearSelection; safecall;
procedure FocusNode(const Node: IOTAStructureNode); safecall;
function GetFirstSelected: IOTAStructureNode; safecall;
function GetNextSelected(const ANode: IOTAStructureNode): IOTAStructureNode; safecall;
function GetSelectedCount: Integer; safecall;
function GetStructureType: WideString; safecall;
procedure RemoveNotifier(Index: Integer); safecall;
function RequestEdit(const Node: IOTAStructureNode; ForceEdit: WordBool): WordBool; safecall;
procedure SetStructureContext(const AContext: IOTAStructureContext); safecall;
procedure StructureChanged(Deferred: WordBool); safecall;
procedure SelectNode(const Node: IOTAStructureNode); safecall;
function AddBitmap(ABitmap: HBITMAP; StateImage: WordBool = False): Integer; safecall;
function AddIcon(AIcon: HICON; StateImage: WordBool = False): Integer; safecall;
function AddImageList(AImageList: HIMAGELIST; StateImage: WordBool = False): Integer; safecall;
function ViewShowing: WordBool; safecall;
end;
IOTAStructureView110 = interface(IOTAStructureView)
['{72C311FE-4C8A-44AD-9F1F-9A846FE617F2}']
function IsContextChanging: WordBool; safecall;
end;
IOTAStructureContext = interface(IDispatch)
['{67FD6512-C50F-4C83-8C2F-4E60340668D1}']
function Get_ContextIdent: WideString; safecall;
function Get_StructureType: WideString; safecall;
function Get_ViewOptions: Integer; safecall;
function Get_RootNodeCount: Integer; safecall;
function GetRootStructureNode(Index: Integer): IOTAStructureNode; safecall;
procedure NodeEdited(const Node: IOTAStructureNode); safecall;
procedure NodeFocused(const Node: IOTAStructureNode); safecall;
procedure NodeSelected(const Node: IOTAStructureNode); safecall;
procedure DefaultNodeAction(const Node: IOTAStructureNode); safecall;
function SameContext(const AContext: IOTAStructureContext): WordBool; safecall;
procedure InitPopupMenu(const Node: IOTAStructureNode;
const PopupMenu: IOTAStructureNodeMenuItem); safecall;
procedure AddRootNode(const ANode: IOTAStructureNode; Index: Integer); safecall;
procedure RemoveRootNode(const ANode: IOTAStructureNode); safecall;
property ContextIdent: WideString read Get_ContextIdent;
property StructureType: WideString read Get_StructureType;
property ViewOptions: Integer read Get_ViewOptions;
property RootNodeCount: Integer read Get_RootNodeCount;
end;
IOTAStructureContext110 = interface(IOTAStructureContext)
['{E60A76A6-8E44-4F67-85F3-06ED345BB2F4}']
procedure ContextActivated; safecall;
end;
IOTAStructureNodeStatePreserver = interface(IDispatch)
['{F6189580-87EE-4985-8866-7712D8DB4872}']
function Get_NodePreservationMode: TOTANodePreservationMode; safecall;
procedure PreserveNodeStates; safecall;
procedure RestoreNodeState(const Node: IOTAStructureNode); safecall;
property NodePreservationMode: TOTANodePreservationMode read Get_NodePreservationMode;
end;
IOTAStructureUpdateSynchronizer = interface(IDispatch)
['{D53E0F35-B178-4541-8CCD-24196466855D}']
procedure Lock; safecall;
function TryLock: WordBool; safecall;
procedure UnLock; safecall;
end;
INTAStructureContext = interface(IDispatch)
['{F413DD7C-532E-46EB-8238-C4FE5CDA9729}']
function GetStructureControl: TWinControl; safecall;
property StructureControl: TWinControl read GetStructureControl;
end;
IOTAStructureContextToolbar = interface(IDispatch)
['{55C848EB-2197-4B17-A9D0-696D3331B3CC}']
function Get_ButtonCount: Integer; safecall;
function GetButtonCaption(Index: Integer): WideString; safecall;
function GetButtonEnabled(Index: Integer): WordBool; safecall;
function GetButtonEnableDropDown(Index: Integer): WordBool; safecall;
function GetButtonHasDropDown(Index: Integer): WordBool; safecall;
function GetButtonHint(Index: Integer): WideString; safecall;
function GetButtonImageIndex(Index: Integer): Integer; safecall;
function GetButtonMenu(Index: Integer): IOTAStructureNodeMenuItem; safecall;
function GetButtonSeparator(Index: Integer): WordBool; safecall;
function GetButtonVisible(Index: Integer): WordBool; safecall;
procedure Invoke(Index: Integer); safecall;
property ButtonCount: Integer read Get_ButtonCount;
end;
IOTAStructureContextEditActions = interface(IDispatch)
['{EF0F0981-8E1B-468F-B063-4A5956EB4BDA}']
function EditAction(Action: Integer): WordBool; safecall;
function GetEditState: Integer; safecall;
end;
IOTAStructureContextKeyHandler = interface(IDispatch)
['{17A71EDB-A2FE-4358-ABD2-362011A8D547}']
procedure KeyDown(const Node: IOTAStructureNode; KeyState: Integer; var KeyCode: Word); safecall;
procedure KeyPressed(const Node: IOTAStructureNode; KeyState: Integer; var KeyChar: Word); safecall;
end;
IOTADragStructureContext = interface(IDispatch)
['{03DC0E9A-DED1-4E2A-BECE-328CB27D19B9}']
function DragAllowed(const Node: IOTAStructureNode): WordBool; safecall;
procedure DragDrop(const Node: IOTAStructureNode;
DataObject: OleVariant; const FormatArray: WideString;
X, Y: Integer; KeyState: Integer; Mode: TOTADropMode; var Effect: Integer); safecall;
function DragOver(const Node: IOTAStructureNode;
DataObject: OleVariant; State: TOTADragState;
X, Y: Integer; KeyState: Integer; Mode: TOTADropMode; var Effect: Integer): WordBool; safecall;
function GetDataObject: OleVariant; safecall;
end;
IOTAStructureNode = interface(IDispatch)
['{8A0802F5-C26C-4902-9D1F-8323F2F48F8C}']
function AddChildNode(const ANode: IOTAStructureNode; Index: Integer = -1): Integer; safecall;
function Get_Caption: WideString; safecall;
function Get_ChildCount: Integer; safecall;
function Get_Child(Index: Integer): IOTAStructureNode; safecall;
function Get_Expanded: WordBool; safecall;
procedure Set_Expanded(Value: WordBool); safecall;
function Get_Focused: WordBool; safecall;
procedure Set_Focused(Value: WordBool); safecall;
function Get_Hint: WideString; safecall;
function Get_ImageIndex: Integer; safecall;
function Get_Name: WideString; safecall;
function Get_Parent: IOTAStructureNode; safecall;
function Get_Selected: WordBool; safecall;
procedure Set_Selected(Value: WordBool); safecall;
function Get_StateIndex: Integer; safecall;
function Get_Data: Integer; safecall;
procedure Set_Data(Value: Integer); safecall;
procedure RemoveChildNode(Index: Integer); safecall;
property Caption: WideString read Get_Caption;
property ChildCount: Integer read Get_ChildCount;
property Child[Index: Integer]: IOTAStructureNode read Get_Child;
// The Data property is used by the structure view services to store certain
// payload information. DO NOT ATTEMPT TO USE THIS PROPERTY. Implementers
// of this interface should only store this value as purely opaque data.
property Data: Integer read Get_Data write Set_Data;
property Expanded: WordBool read Get_Expanded write Set_Expanded;
property Focused: WordBool read Get_Focused write Set_Focused;
property Hint: Widestring read Get_Hint;
property ImageIndex: Integer read Get_ImageIndex;
property Name: Widestring read Get_Name;
property Parent: IOTAStructureNode read Get_Parent;
property Selected: WordBool read Get_Selected write Set_Selected;
property StateIndex: Integer read Get_StateIndex;
end;
IOTASortableStructureNode = interface(IDispatch)
['{24451294-D128-47E6-A8A5-00C3547C2F9C}']
function Get_SortByIndex: WordBool; safecall;
function Get_ItemIndex: Integer; safecall;
property SortByIndex: WordBool read Get_SortByIndex;
property ItemIndex: Integer read Get_ItemIndex;
end;
IOTAEditableStructureNode = interface(IDispatch)
['{B2CF6C45-4151-4B1A-B56B-B23534BB053E}']
function Get_CanEdit: WordBool; safecall;
function Get_EditCaption: WideString; safecall;
procedure SetValue(const Value: WideString); safecall;
property EditCaption: WideString read Get_EditCaption;
property CanEdit: WordBool read Get_CanEdit;
end;
IOTANavigableStructureNode = interface(IDispatch)
['{81B1557A-E3F2-4E9C-AA69-CEBBA99D923F}']
function Navigate: Boolean; safecall;
end;
IOTADragStructureNode = interface(IDispatch)
['{679BCA19-150F-4CC5-9023-CE24F5580F5B}']
function DragAllowed: WordBool; safecall;
procedure DragDrop(DataObject: OleVariant; const FormatArray: WideString;
X, Y: Integer; KeyState: Integer; Mode: TOTADropMode; var Effect: Integer); safecall;
function DragOver(DataObject: OleVariant; State: TOTADragState;
X, Y: Integer; KeyState: Integer; Mode: TOTADropMode; var Effect: Integer): WordBool; safecall;
end;
IOTAStructureNodeMenuItem = interface(IDispatch)
['{7BF39892-F3D3-48F7-B5F3-664FDD438581}']
procedure DeleteItem(Index: Integer); safecall;
function Get_Caption: WideString; safecall;
function Get_Checked: WordBool; safecall;
function Get_Count: Integer; safecall;
function Get_Enabled: WordBool; safecall;
function Get_GroupIndex: Integer; safecall;
function Get_ImageIndex: Integer; safecall;
function Get_Item(Index: Integer): IOTAStructureNodeMenuItem; safecall;
function Get_Name: WideString; safecall;
function Get_RadioItem: WordBool; safecall;
function Get_ShortCut: Integer; safecall;
function Get_Visible: WordBool; safecall;
procedure InsertItem(Index: Integer; const Item: IOTAStructureNodeMenuItem); safecall;
procedure Invoke; safecall;
property Caption: WideString read Get_Caption;
property Checked: WordBool read Get_Checked;
property Count: Integer read Get_Count;
property Enabled: WordBool read Get_Enabled;
property GroupIndex: Integer read Get_GroupIndex;
property ImageIndex: Integer read Get_ImageIndex;
property Item[Index: Integer]: IOTAStructureNodeMenuItem read Get_Item;
property Name: WideString read Get_Name;
property RadioItem: WordBool read Get_RadioItem;
property ShortCut: Integer read Get_ShortCut;
property Visible: WordBool read Get_Visible;
end;
IOTAStructureNodePopup = interface(IDispatch)
['{FAA6133B-F03F-4A93-9E86-C50EAD7348E6}']
procedure InitPopupMenu(const PopupMenu: IOTAStructureNodeMenuItem); safecall;
end;
TStructureMenuItem = class(TMenuItem)
private
FStructureNodeMenuItem: IOTAStructureNodeMenuItem;
procedure SetStructureNodeMenuItem(const AStructureNodeMenuItem: IOTAStructureNodeMenuItem);
public
constructor Clone(AMenuItem: TMenuItem; DestroyOriginal: Boolean = True);
procedure Click; override;
property StructureNodeMenuItem: IOTAStructureNodeMenuItem
read FStructureNodeMenuItem write SetStructureNodeMenuItem;
end;
// !!!!Do NOT USE THIS INTERFACE EXECPT IN THIS UNIT!!!!
IInternalStructureMenuItem = interface(IInterface)
['{7CC9A6ED-7C94-4CEF-B524-2BC3132468F4}']
function GetMenuItem: TMenuItem;
end;
TStructureNodeMenuItem = class(TInterfacedObject, IDispatch, ISupportErrorInfo,
IOTAStructureNodeMenuItem, IInternalStructureMenuItem)
private
FMenuItem: TMenuItem;
protected
{ IDispatch }
function GetTypeInfoCount(out Count: Integer): HResult; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; overload; stdcall;
{ ISupportErrorInfo }
function InterfaceSupportsErrorInfo(const iid: TIID): HResult; stdcall;
{ IOTAStructureNodeMenuItem }
procedure DeleteItem(Index: Integer); safecall;
function Get_Caption: WideString; safecall;
function Get_Checked: WordBool; safecall;
function Get_Count: Integer; safecall;
function Get_Enabled: WordBool; safecall;
function Get_GroupIndex: Integer; safecall;
function Get_ImageIndex: Integer; safecall;
function Get_Item(Index: Integer): IOTAStructureNodeMenuItem; safecall;
function Get_Name: WideString; safecall;
function Get_RadioItem: WordBool; safecall;
function Get_ShortCut: Integer; safecall;
function Get_Visible: WordBool; safecall;
procedure InsertItem(Index: Integer; const Item: IOTAStructureNodeMenuItem); safecall;
procedure Invoke; overload; safecall;
{ IInternalMenuItem }
function GetMenuItem: TMenuItem;
public
constructor Create(AMenuItem: TMenuItem);
function SafeCallException(ExceptObject: TObject; ExceptAddr: Pointer): HResult; override;
end;
{ If an INTACustomEditorView also implements IOTACustomEditorViewStructure,
then the IOTACustomEditorViewStructure will be queried for the context to
use to populate the Structure view }
IOTACustomEditorViewStructure = interface(IInterface)
['{8B75C91B-7B4A-4FBB-93F0-3C8A09585982}']
function GetStructureContext: IOTAStructureContext;
function GetStructureType: WideString;
end;
{ If an INTACustomEditorSubView also implements IOTACustomEditorSubViewStructure,
then the IOTACustomEditorSubViewStructure will be queried for the context to
use to populate the Structure view }
IOTACustomEditorSubViewStructure = interface(IInterface)
['{E597AA89-3E34-449A-BDFC-0B3731200150}']
function GetStructureContext(const AContext: IInterface; AViewObject: TObject): IOTAStructureContext;
function GetStructureType(const AContext: IInterface; AViewObject: TObject): WideString;
end;
implementation
uses System.Win.ComObj;
{ TStructureNodeMenuItem }
constructor TStructureNodeMenuItem.Create(AMenuItem: TMenuItem);
begin
inherited Create;
FMenuItem := AMenuItem;
if FMenuItem is TStructureMenuItem then
TStructureMenuItem(FMenuItem).FStructureNodeMenuItem := Self;
end;
procedure TStructureNodeMenuItem.DeleteItem(Index: Integer);
begin
FMenuItem.Delete(Index);
end;
function TStructureNodeMenuItem.Get_Caption: WideString;
begin
Result := FMenuItem.Caption;
end;
function TStructureNodeMenuItem.Get_Checked: WordBool;
begin
Result := FMenuItem.Checked;
end;
function TStructureNodeMenuItem.Get_Count: Integer;
begin
Result := FMenuItem.Count;
end;
function TStructureNodeMenuItem.Get_Enabled: WordBool;
begin
Result := FMenuItem.Enabled;
end;
function TStructureNodeMenuItem.Get_ImageIndex: Integer;
begin
Result := FMenuItem.ImageIndex;
end;
function TStructureNodeMenuItem.Get_Item(Index: Integer): IOTAStructureNodeMenuItem;
var
MenuItem: TMenuItem;
begin
MenuItem := FMenuItem.Items[Index];
if not (MenuItem is TStructureMenuItem) then
MenuItem := TStructureMenuItem.Clone(MenuItem);
Result := TStructureMenuItem(MenuItem).StructureNodeMenuItem;
end;
function TStructureNodeMenuItem.Get_Name: WideString;
begin
Result := FMenuItem.Name;
end;
function TStructureNodeMenuItem.Get_ShortCut: Integer;
begin
Result := FMenuItem.ShortCut;
end;
function TStructureNodeMenuItem.Get_Visible: WordBool;
begin
Result := FMenuItem.Visible;
end;
function TStructureNodeMenuItem.GetIDsOfNames(const IID: TGUID;
Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult;
begin
Result := E_NOTIMPL;
end;
function TStructureNodeMenuItem.GetMenuItem: TMenuItem;
begin
Result := FMenuItem;
end;
function TStructureNodeMenuItem.GetTypeInfo(Index, LocaleID: Integer;
out TypeInfo): HResult;
begin
Result := E_NOTIMPL;
end;
function TStructureNodeMenuItem.GetTypeInfoCount(
out Count: Integer): HResult;
begin
Result := E_NOTIMPL;
end;
procedure TStructureNodeMenuItem.InsertItem(Index: Integer;
const Item: IOTAStructureNodeMenuItem);
var
MenuItem: TStructureMenuItem;
begin
MenuItem := TStructureMenuItem.Create(FMenuItem.Owner);
MenuItem.StructureNodeMenuItem := Item;
FMenuItem.Insert(Index, MenuItem);
end;
function TStructureNodeMenuItem.InterfaceSupportsErrorInfo(
const iid: TIID): HResult;
begin
Result := S_OK;
end;
function TStructureNodeMenuItem.Invoke(DispID: Integer; const IID: TGUID;
LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo,
ArgErr: Pointer): HResult;
begin
Result := E_NOTIMPL;
end;
procedure TStructureNodeMenuItem.Invoke;
begin
FMenuItem.Click;
end;
function TStructureNodeMenuItem.SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult;
begin
Result := HandleSafeCallException(ExceptObject, ExceptAddr, IUnknown, '', '');
end;
function TStructureNodeMenuItem.Get_GroupIndex: Integer;
begin
Result := FMenuItem.GroupIndex;
end;
function TStructureNodeMenuItem.Get_RadioItem: WordBool;
begin
Result := FMenuItem.RadioItem;
end;
{ TStructureMenuItem }
procedure TStructureMenuItem.Click;
var
InternalItem: IInternalStructureMenuItem;
begin
if (FStructureNodeMenuItem = nil) or
(Supports(FStructureNodeMenuItem, IInternalStructureMenuItem, InternalItem) and
(InternalItem.GetMenuItem = Self)) then
inherited Click
else
FStructureNodeMenuItem.Invoke;
end;
constructor TStructureMenuItem.Clone(AMenuItem: TMenuItem; DestroyOriginal: Boolean);
var
I: Integer;
LMenuItem: TMenuItem;
LName: string;
begin
inherited Create(AMenuItem.Owner);
TStructureNodeMenuItem.Create(Self);
if AMenuItem.Action <> nil then
Action := AMenuItem.Action
else
begin
Caption := AMenuItem.Caption;
ShortCut := AMenuItem.ShortCut;
Visible := AMenuItem.Visible;
Enabled := AMenuItem.Enabled;
Checked := AMenuItem.Checked;
ImageIndex := AMenuItem.ImageIndex;
end;
for I := AMenuItem.Count - 1 downto 0 do
begin
LMenuItem := AMenuItem[I];
AMenuItem.Delete(I);
Insert(0, LMenuItem);
end;
if AMenuItem.Parent <> nil then
AMenuItem.Parent.Insert(AMenuItem.Parent.IndexOf(AMenuItem), Self);
if DestroyOriginal then
begin
LName := AMenuItem.Name;
AMenuItem.Free;
Name := LName;
end;
end;
procedure TStructureMenuItem.SetStructureNodeMenuItem(const AStructureNodeMenuItem: IOTAStructureNodeMenuItem);
var
I: Integer;
MenuItem: TStructureMenuItem;
begin
FStructureNodeMenuItem := AStructureNodeMenuItem;
Caption := FStructureNodeMenuItem.Caption;
Visible := FStructureNodeMenuItem.Visible;
Enabled := FStructureNodeMenuItem.Enabled;
ImageIndex := FStructureNodeMenuItem.ImageIndex;
ShortCut := FStructureNodeMenuItem.ShortCut;
Name := FStructureNodeMenuItem.Name;
for I := 0 to FStructureNodeMenuItem.Count - 1 do
begin
MenuItem := TStructureMenuItem.Create(Owner);
MenuItem.StructureNodeMenuItem := FStructureNodeMenuItem.Item[I];
Add(MenuItem);
end;
end;
end.
|
{GENERAL METHODS USED BY TWAIN DELPHI}
{december 2001®, made by Gustavo Daud}
{This unit contains general methods used by Delphi}
{Twain component. Some of the methods bellow aren't}
{directly related to Twain, but are pieces needed}
{to implement the component.}
unit DelphiTwainUtils;
{$INCLUDE DELPHITWAIN.INC}
interface
uses
Twain;
type
{Kinds of directories to be obtained with GetCustomDirectory}
TDirectoryKind = (dkWindows, dkSystem, dkCurrent, dkApplication, dkTemp);
{Class to store a list of pointers}
TPointerList = class
private
{Stores pointer to the allocated data}
Data: Pointer;
{Contains number of additional items allocated every time}
{it needs more data to store}
fAdditionalBlock: Integer;
{Contains the number of items in the list}
fCount: Integer;
{Contains number of allocated items}
fAllocated: Integer;
{Allocate/deallocate memory to have enough memory}
{to hold the new number of items}
procedure SetAllocated(const Value: Integer);
{Sets the AdditionalBlock property}
procedure SetAdditionalBlock(const Value: Integer);
{Set the number of items in the list}
procedure SetCount(const Value: Integer);
function GetItem(Index: Integer): Pointer;
procedure PutItem(Index: Integer; const Value: Pointer);
public
{Add a new item}
procedure Add(Value: Pointer);
{Clear all the items in the list}
procedure Clear;
{Object being created or destroyed}
constructor Create;
destructor Destroy; override;
{Returns/sets an item value}
property Item[Index: Integer]: Pointer read GetItem write PutItem; default;
{Returns the number of items}
property Count: Integer read fCount write SetCount;
{Number of allocated items}
property Allocated: Integer read fAllocated write SetAllocated;
{Additional items to alloc when it needs more memory}
property AdditionalBlock: Integer read fAdditionalBlock write
SetAdditionalBlock;
end;
{Returns custom Microsoft Windows® directories}
function GetCustomDirectory(const DirectoryKind: TDirectoryKind): String;
{Returns the last error string from Microsoft Windows®}
function GetLastErrorText(): String;
{Returns if the directory exists}
function DirectoryExists(const Directory: String): Boolean;
{Returns if the file exists}
function FileExists(const FilePath: String): Boolean;
{Extracts the file directory part}
function ExtractDirectory(const FilePath: String): String;
{Convert from integer to string}
{$IFDEF DONTUSEVCL}function IntToStr(Value: Integer): String;{$ENDIF}
{$IFDEF DONTUSEVCL}function StrToIntDef(Value: String;
Default: Integer): Integer;{$ENDIF}
{$IFDEF DONTUSEVCL}function CompareMem(P1, P2: pChar;
Size: Integer): Boolean;{$ENDIF}
{Convert from twain Fix32 to extended}
function Fix32ToFloat(Value: TW_FIX32): Extended;
{Convert from extended to Fix32}
function FloatToFix32 (floater: extended): TW_FIX32;
implementation
{Units used bellow}
uses
Windows;
{$IFDEF DONTUSEVCL}
function CompareMem(P1, P2: pChar; Size: Integer): Boolean;
var
i: Integer;
begin
{Default result}
Result := TRUE;
{Search each byte}
FOR i := 1 TO Size DO
begin
{Compare booth bytes}
if P1^ <> P2^ then
begin
Result := FALSE;
Exit;
end; {if P1^ <> P2^}
{Move to next byte}
Inc(P1); Inc(P2);
end {FOR i}
end {function};
{$ENDIF}
{$IFDEF DONTUSEVCL}
function IntToStr(Value: Integer): String;
begin
Str(Value, Result);
end;
{$ENDIF}
{$IFDEF DONTUSEVCL}
function StrToIntDef(Value: String; Default: Integer): Integer;
var Code: Integer;
begin
{Try converting from string to integer}
Val(Value, Result, Code);
{If any error ocurred, returns default value}
if Code <> 0 then Result := Default;
end;
{$ENDIF}
{Convert from extended to Fix32}
function FloatToFix32 (floater: extended): TW_FIX32;
var
fracpart : extended;
begin
//Obtain numerical part by truncating the float number
Result.Whole := trunc(floater);
//Obtain fracional part by subtracting float number by
//numerical part. Also we make sure the number is not
//negative by multipling by -1 if it is negative
fracpart := floater - result.Whole;
if fracpart < 0 then fracpart := fracpart * -1;
//Multiply by 10 until there is no fracional part any longer
while FracPart - trunc(FracPart) <> 0 do fracpart := fracpart * 10;
//Return fracional part
Result.Frac := trunc(fracpart);
end;
{Convert from twain Fix32 to extended}
function Fix32ToFloat(Value: TW_FIX32): Extended;
begin
Result := Value.Whole + (Value.Frac / 65536.0);
end;
{Returns the last position for any of the characters in the parameter}
function LastPosition(const Text, characters: String): Integer;
var
x, y: Integer; {For loop variables}
begin
Result := Length(Text); {Initial result}
{Search each character in the text}
FOR x := 1 TO Length(Text) DO
begin
{Test for each character}
FOR y := 1 TO Length(characters) DO
if Text[x] = characters[y] then
Result := x;
end {for x}
end;
{Extracts the file directory}
function ExtractDirectory(const FilePath: String): String;
begin
{Searches for the last \ or : characters}
{ex: c:\windows\system32\yfile.ext or c:autoexec.bat}
Result := Copy(FilePath, 1, LastPosition(FilePath, '\:'));
end;
{Returns if the file exists}
function FileExists(const FilePath: String): Boolean;
var
FindData : TWin32FindData;
FindHandle: THandle;
begin
{Searches for the file}
FindHandle := FindFirstFile(PChar(FilePath), FindData);
Result := (FindHandle <> INVALID_HANDLE_VALUE);
{In case it found, closes the FindFirstFile handle}
if Result then FindClose(FindHandle);
end;
{Returns if the directory exists}
function DirectoryExists(const Directory: String): Boolean;
var
Attr: DWORD;
begin
{Calls GetFileAttributes to verify}
Attr := GetFileAttributes(PChar(Directory));
Result := (Attr <> $FFFFFFFF) and (Attr and FILE_ATTRIBUTE_DIRECTORY <> 0);
end;
{Makes an language identifier using the two ids}
function MAKELANGID(p, s: WORD): DWORD;
begin
Result := (s shl 10) or p;
end;
{Returns the last error string from Microsoft Windows®}
function GetLastErrorText(): String;
var
Buffer: Array[Byte] of Char;
Len : DWORD;
begin
{Calls format message to translate from the error code ID to}
{a text understandable error}
Len := Windows.FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or
FORMAT_MESSAGE_ARGUMENT_ARRAY, nil, GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), Buffer, sizeof(Buffer), nil);
{Remove this chars from the ending of the result}
while (Len > 0) and (Buffer[Len - 1] in [#0..#32, '.']) do Dec(Len);
{Fills result}
SetString(Result, Buffer, Len);
end;
{Includes a trailing backslash in the end of the directory; if necessary}
procedure IncludeTrailingBackslash(var Directory: String);
begin
{If there isn't already a backslash, add one}
if Directory[Length(Directory)] <> '\' then
Directory := Directory + '\'
end;
{Returns custom Microsoft Windows® directories}
function GetCustomDirectory(const DirectoryKind: TDirectoryKind): String;
const
{Default maximum size for directories}
DEF_DIRLEN = MAX_PATH;
{Calls appropriate method and returns necessary size}
function CallDirectoryMethod(Buffer: Pointer; Size: UINT): UINT;
begin
{Test the directory needed by the parameter}
case DirectoryKind of
{Windows directory}
dkWindows: Result := Windows.GetWindowsDirectory(Buffer, Size);
{System directory}
dkSystem : Result := Windows.GetSystemDirectory(Buffer, Size);
{Current directory}
dkCurrent: Result := Windows.GetCurrentDirectory(Size, Buffer);
{Application directory}
dkApplication: Result := Windows.GetModuleFileName(0, Buffer, Size);
{Temp directory}
dkTemp : Result := Windows.GetTempPath(Size, Buffer);
{Unknown directory}
else Result := 0;
end {case}
end;
var
DirectoryLen: UINT;
begin
{Set length of the resulting buffer to MAX_PATH to try to hold}
{windows directory}
SetLength(Result, DEF_DIRLEN + 1);
{Tries to obtain the windows directory and stores the size}
DirectoryLen := CallDirectoryMethod(@Result[1], DEF_DIRLEN);
{In case it was not enough to hold windows directory, enlarge}
if DirectoryLen > DEF_DIRLEN then
begin
{Try again, now with the right size}
SetLength(Result, DirectoryLen + 1);
CallDirectoryMethod(@Result[1], DirectoryLen);
end
else {Otherwise, adjust the result to excluded unused data}
SetLength(Result, DirectoryLen);
{In case the user searched for the application directory}
{extracts just the directory part}
if DirectoryKind = dkApplication then
Result := ExtractDirectory(Result);
{Add a trailing backslash to end of the directory name}
IncludeTrailingBackslash(Result);
end;
{ TPointerList object implementation }
{Add a new item}
procedure TPointerList.Add(Value: Pointer);
begin
{Increase number of items and update new item}
Count := Count + 1;
Item[Count - 1] := Value;
end;
{Clear all the items in the list}
procedure TPointerList.Clear;
begin
{Set number of items to 0 and initialize again allocated items}
Count := 0;
Allocated := AdditionalBlock;
end;
{TPointerList being created}
constructor TPointerList.Create;
begin
{Let ancestor receive the call}
inherited Create;
{Allocate a number of items}
fAdditionalBlock := 10;
fAllocated := fAdditionalBlock;
GetMem(Data, (fAllocated * sizeof(Pointer)));
end;
{TPointerList being destroyed}
destructor TPointerList.Destroy;
begin
{Deallocate data}
FreeMem(Data, (fAllocated * sizeof(Pointer)));
{Let ancestor receive and finish}
inherited Destroy;
end;
{Returns an item from the list}
function TPointerList.GetItem(Index: Integer): Pointer;
begin
{Check item bounds and return item}
if Index in [0..Count - 1] then
Longint(Result) := pLongint(Longint(Data) + (Index * sizeof(Pointer)))^
else Result := nil; {Otherwise returns nil}
end;
{Sets an item from the list}
procedure TPointerList.PutItem(Index: Integer; const Value: Pointer);
begin
{Check item bounds and sets item}
if Index in [0..Count - 1] then
pLongint(Longint(Data) + (Index * sizeof(Pointer)))^ := Longint(Value);
end;
{Sets the AdditionalBlock property}
procedure TPointerList.SetAdditionalBlock(const Value: Integer);
begin
{Value must be a positive number greater than 0}
if (Value > 0) then
fAdditionalBlock := Value;
end;
{Allocate/deallocate memory to have enough memory to hold}
{the new number of items}
procedure TPointerList.SetAllocated(const Value: Integer);
begin
{Must be always greater than 0 the number of allocated items}
{And it also should not be smaller than count}
if (Value > 0) and (Value <= Count) then
begin
{Just realloc memory and update property variable}
ReallocMem(Data, (Value * sizeof(Pointer)));
fAllocated := Value;
end {if (Value <> 0)}
end;
{Set the number of items in the list}
procedure TPointerList.SetCount(const Value: Integer);
begin
{Value must be 0 or greater}
if (Value >= 0) then
begin
{If there is no more memory to hold data, allocate some more}
while (Value > fAllocated) do
Allocated := Allocated + fAdditionalBlock;
{Update property}
fCount := Value;
end {if (Value >= 0)}
end;
end.
|
unit postgres_ext;
interface
uses Windows;
{ Pointers to basic pascal types, inserted by h2pas conversion program.}
Type
{$ifndef PLongint}
PLongint = ^Longint;
{$endif}
{$ifndef PSmallInt}
PSmallInt = ^SmallInt;
{$endif}
{$ifndef PByte}
PByte = ^Byte;
{$endif}
{$ifndef PWord}
PWord = ^Word;
{$endif}
{$ifndef DWord}
DWord = Longint;
{$endif}
{$ifndef PDWord}
PDWord = ^DWord;
{$endif}
{$ifndef PDouble}
PDouble = ^Double;
{$endif}
POid = ^Oid;
Oid = dword;
{ was #define dname def_expr }
function InvalidOid : Oid;
const
OID_MAX = MAXDWORD;
{ you will need to include <limits.h> to use the above #define }
{
* Identifiers of error message fields. Kept here to keep common
* between frontend and backend, and also to export them to libpq
* applications.
}
PG_DIAG_SEVERITY = 'S';
PG_DIAG_SQLSTATE = 'C';
PG_DIAG_MESSAGE_PRIMARY = 'M';
PG_DIAG_MESSAGE_DETAIL = 'D';
PG_DIAG_MESSAGE_HINT = 'H';
PG_DIAG_STATEMENT_POSITION = 'P';
PG_DIAG_INTERNAL_POSITION = 'p';
PG_DIAG_INTERNAL_QUERY = 'q';
PG_DIAG_CONTEXT = 'W';
PG_DIAG_SOURCE_FILE = 'F';
PG_DIAG_SOURCE_LINE = 'L';
PG_DIAG_SOURCE_FUNCTION = 'R';
implementation
{ was #define dname def_expr }
function InvalidOid : Oid;
begin
InvalidOid:=Oid(0);
end;
end.
|
unit LazUTF8Classes;
{
LLCL - FPC/Lazarus Light LCL
based upon
LVCL - Very LIGHT VCL
----------------------------
This file is a part of the Light LCL (LLCL).
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/.
This Source Code Form is "Incompatible With Secondary Licenses",
as defined by the Mozilla Public License, v. 2.0.
Copyright (c) 2015-2016 ChrisF
Based upon the Very LIGHT VCL (LVCL):
Copyright (c) 2008 Arnaud Bouchez - http://bouchez.info
Portions Copyright (c) 2001 Paul Toth - http://tothpaul.free.fr
Version 1.02:
Version 1.01:
Version 1.00:
* File creation.
* TFileStreamUTF8 class (simplified)
Notes:
- specific to FPC/Lazarus (not used with Delphi).
}
{$IFDEF FPC}
{$define LLCL_FPC_MODESECTION}
{$I LLCLFPCInc.inc} // For mode
{$undef LLCL_FPC_MODESECTION}
{$ENDIF}
{$I LLCLOptions.inc} // Options
//------------------------------------------------------------------------------
interface
uses
Classes;
type
TFileStreamUTF8 = class(TFileStream)
private
fFileNameUTF8: string;
public
constructor Create(const AFileName: string; Mode: Word);
property FileName: string read fFileNameUTF8;
end;
//------------------------------------------------------------------------------
implementation
uses
LazFileUtils;
{$IFDEF FPC}
{$PUSH} {$HINTS OFF}
{$ENDIF}
//------------------------------------------------------------------------------
constructor TFileStreamUTF8.Create(const AFileName: string; Mode: Word);
var AHandle: THandle;
begin
fFileNameUTF8 := AFileName;
if Mode=fmCreate then
AHandle := FileCreateUTF8(AFileName) else
AHandle := FileOpenUTF8(AFileName, Mode);
if AHandle=THandle(-1) then
raise EStreamError.Create(AFileName)
else
THandleStream(self).Create(AHandle);
end;
//------------------------------------------------------------------------------
{$IFDEF FPC}
{$POP}
{$ENDIF}
end.
|
{
"Fast Huge String manipulation and search classes" - Copyright (c) Danijel Tkalcec
@exclude
}
unit rtcFastStrings;
{$include rtcDefs.inc}
interface
uses
memStrIntList, SysUtils, Classes;
const
RTC_STROBJ_SHIFT = 4; // = 16
RTC_STROBJ_PACK = 1 shl RTC_STROBJ_SHIFT;
RTC_STROBJ_AND = RTC_STROBJ_PACK-1;
type
tRtcStrRec=packed record
str:string;
siz:integer;
end;
tRtcStrArr=array[0..RTC_STROBJ_PACK-1] of tRtcStrRec;
PRtcStrArr=^tRtcStrArr;
tRtcStrArray=array of PRtcStrArr;
TRtcHugeString=class
private
FData:tRtcStrArray;
FPack:PRtcStrArr;
FDataCnt,
FPackCnt,
FPackFree,
FPackLoc:integer;
FCount:integer;
FSize:int64;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Add(const s:String);
function Get:String;
property Size:int64 read FSize;
end;
tRtcStrObjRec=packed record
str:string;
obj:TObject;
end;
tRtcStrObjArr=array[0..RTC_STROBJ_PACK-1] of tRtcStrObjRec;
PRtcStrObjArr=^tRtcStrObjArr;
tRtcStrObjArray=array of PRtcStrObjArr;
tRtcFastStrObjList=class
private
FData:tRtcStrObjArray; // array of PRtcStrObjArr;
FPack:PRtcStrObjArr;
Tree:TStrIntList;
FDataCnt,
FPackCnt:integer;
FCnt:integer;
function GetName(const index: integer): string;
function GetValue(const index: integer): TObject;
procedure SetName(const index: integer; const _Value: string);
procedure SetValue(const index: integer; const _Value: TObject);
function GetCount: integer;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure DestroyObjects;
function Add(const Name:string; _Value:TObject=nil):integer;
function Find(const Name:string):integer;
property Objects[const index:integer]:TObject read GetValue write SetValue;
property Strings[const index:integer]:string read GetName write SetName;
property Count:integer read GetCount;
end;
implementation
{ TRtcHugeString }
constructor TRtcHugeString.Create;
begin
inherited;
SetLength(FData,0);
FDataCnt:=0;
New(FPack);
FillChar(FPack^,SizeOf(FPack^),0);
FPackCnt:=0;
FPackFree:=0;
FPackLoc:=0;
FCount:=0;
FSize:=0;
end;
destructor TRtcHugeString.Destroy;
begin
Clear;
Dispose(FPack);
inherited;
end;
procedure TRtcHugeString.Clear;
var
a,b:integer;
FPack2:PRtcStrArr;
begin
if FDataCnt>0 then
begin
for a:=0 to FDataCnt-1 do
begin
FPack2:=FData[a];
for b:=0 to RTC_STROBJ_PACK-1 do
FPack2^[b].str:='';
Dispose(FPack2);
end;
SetLength(FData,0);
FDataCnt:=0;
end;
if FPackCnt>0 then
begin
for b:=0 to FPackCnt-1 do
FPack^[b].str:='';
FPackCnt:=0;
FPackFree:=0;
FPackLoc:=0;
end;
FSize:=0;
FCount:=0;
end;
procedure TRtcHugeString.Add(const s: String);
var
len:integer;
begin
len:=length(s);
if len>0 then
begin
FSize:=FSize + len;
if FPackFree>=len then
begin
with FPack^[FPackCnt-1] do
begin
Move(s[1], str[FPackLoc], len);
Inc(siz, len);
end;
Inc(FPackLoc,len);
Dec(FPackFree,len);
end
else
begin
if FPackCnt>=RTC_STROBJ_PACK then
begin
if length(FData)<=FDataCnt then
SetLength(FData, FDataCnt + RTC_STROBJ_PACK);
FData[FDataCnt]:=FPack;
Inc(FDataCnt);
New(FPack);
FillChar(FPack^,SizeOf(FPack^),0);
FPackCnt:=0;
end;
if len>255 then
begin
with FPack^[FPackCnt] do
begin
str:=s;
siz:=len;
end;
FPackFree:=0;
FPackLoc:=0;
end
else
begin
with FPack^[FPackCnt] do
begin
SetLength(str, 290);
Move(s[1],str[1],len);
siz:=len;
end;
FPackFree:=290-len;
FPackLoc:=len+1;
end;
Inc(FPackCnt);
Inc(FCount);
end;
end;
end;
function TRtcHugeString.Get: String;
var
a,b,loc:integer;
FPack2:PRtcStrArr;
begin
if FCount>1 then
begin
SetLength(Result, FSize);
loc:=1;
for a:=0 to FDataCnt-1 do
begin
FPack2:=FData[a];
for b:=0 to RTC_STROBJ_PACK-1 do
with FPack2^[b] do
begin
Move(str[1], Result[loc], siz);
Inc(loc, siz);
end;
end;
for b:=0 to FPackCnt-1 do
with FPack^[b] do
begin
Move(str[1], Result[loc], siz);
Inc(loc, siz);
end;
if loc<>FSize+1 then
raise Exception.Create('Internal Huge String error.');
end
else if FCount>0 then
begin
with FPack^[0] do
begin
SetLength(Result, siz);
Move(str[1], Result[1], siz);
end;
end
else
Result:='';
end;
{ tRtcFastStrObjList }
constructor tRtcFastStrObjList.Create;
begin
inherited;
Tree:=tStrIntList.Create(RTC_STROBJ_PACK);
SetLength(FData,0);
New(FPack);
FillChar(FPack^,SizeOf(FPack^),0);
FCnt:=0;
FDataCnt:=0;
FPackCnt:=0;
end;
destructor tRtcFastStrObjList.Destroy;
begin
Clear;
Dispose(FPack);
Tree.Free;
inherited;
end;
procedure tRtcFastStrObjList.Clear;
var
a,b:integer;
FPack2:PRtcStrObjArr;
begin
if FPackCnt>0 then
begin
for b:=0 to FPackCnt-1 do
with FPack^[b] do
begin
str:='';
obj:=nil;
end;
FPackCnt:=0;
end;
if FDataCnt>0 then
begin
for a:=0 to FDataCnt-1 do
begin
FPack2:=FData[a];
for b:=0 to RTC_STROBJ_PACK-1 do
with FPack2^[b] do
begin
str:='';
obj:=nil;
end;
Dispose(FPack2);
end;
SetLength(FData,0);
FDataCnt:=0;
end;
Tree.removeall;
FCnt:=0;
end;
procedure tRtcFastStrObjList.DestroyObjects;
var
a,b:integer;
FPack2:PRtcStrObjArr;
begin
if FPackCnt>0 then
begin
for b:=0 to FPackCnt-1 do
with FPack^[b] do
begin
str:='';
if assigned(obj) then
begin
obj.Free;
obj:=nil;
end;
end;
FPackCnt:=0;
end;
if FDataCnt>0 then
begin
for a:=0 to FDataCnt-1 do
begin
FPack2:=FData[a];
for b:=0 to RTC_STROBJ_PACK-1 do
with FPack2^[b] do
begin
str:='';
if assigned(obj) then
begin
obj.Free;
obj:=nil;
end;
end;
Dispose(FPack2);
end;
SetLength(FData,0);
FDataCnt:=0;
end;
Tree.removeall;
FCnt:=0;
end;
function tRtcFastStrObjList.Add(const Name: string; _Value:TObject=nil): integer;
begin
if FPackCnt>=RTC_STROBJ_PACK then
begin
if length(FData)<=FDataCnt then
SetLength(FData, FDataCnt + RTC_STROBJ_PACK);
FData[FDataCnt]:=FPack;
Inc(FDataCnt);
New(FPack);
FillChar(FPack^,SizeOf(FPack^),0);
FPackCnt:=0;
end;
Tree.insert(UpperCase(Name), FCnt);
with FPack[FPackCnt] do
begin
str:=Name;
obj:=_Value;
end;
Inc(FPackCnt);
Inc(FCnt);
Result:=FCnt-1;
end;
function tRtcFastStrObjList.Find(const Name: string): integer;
begin
Result:=Tree.search(UpperCase(Name));
end;
function tRtcFastStrObjList.GetName(const index: integer): string;
begin
if index shr RTC_STROBJ_SHIFT<FDataCnt then
Result:=FData[index shr RTC_STROBJ_SHIFT]^[index and RTC_STROBJ_AND].str
else
Result:=FPack^[index and RTC_STROBJ_AND].str;
end;
function tRtcFastStrObjList.GetValue(const index: integer): TObject;
begin
if index shr RTC_STROBJ_SHIFT<FDataCnt then
Result:=FData[index shr RTC_STROBJ_SHIFT]^[index and RTC_STROBJ_AND].obj
else
Result:=FPack^[index and RTC_STROBJ_AND].obj;
end;
procedure tRtcFastStrObjList.SetName(const index: integer; const _Value: string);
begin
if index shr RTC_STROBJ_SHIFT<FDataCnt then
begin
with FData[index shr RTC_STROBJ_SHIFT]^[index and RTC_STROBJ_AND] do
begin
Tree.remove(UpperCase(str));
str:=_Value;
Tree.insert(UpperCase(_Value), index);
end;
end
else
begin
with FPack^[index and RTC_STROBJ_AND] do
begin
Tree.remove(UpperCase(str));
str:=_Value;
Tree.insert(UpperCase(_Value), index);
end;
end;
end;
procedure tRtcFastStrObjList.SetValue(const index: integer; const _Value: TObject);
begin
if index shr RTC_STROBJ_SHIFT<FDataCnt then
FData[index shr RTC_STROBJ_SHIFT]^[index and RTC_STROBJ_AND].obj:=_Value
else
FPack^[index and RTC_STROBJ_AND].obj:=_Value;
end;
function tRtcFastStrObjList.GetCount: integer;
begin
Result:=FCnt;
end;
end.
|
{*******************************************************************************
* *
* TkToolbar - Toolbar with form stack/transitions awareness *
* *
* https://github.com/gmurt/KernowSoftwareFMX *
* *
* Copyright 2017 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
unit ksToolBar;
interface
{$I ksComponents.inc}
uses Classes, FMX.StdCtrls, FMX.Graphics, ksTypes, FMX.Objects, FMX.Types,
System.UITypes, System.UIConsts, ksSpeedButton, ksFormTransition,
FMX.Controls.Presentation, FMX.Controls, System.Types;
type
// TksToolbar = class;
{IksToolbar = interface
['{42609FB8-4DE0-472F-B49C-A6CD636A530D}//]
//procedure SetTransition(ATransition: TksTransitionType);
//end;
[ComponentPlatformsAttribute(pidWin32 or pidWin64 or
{$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64
{$ELSE} pidiOSDevice {$ENDIF} or pidiOSSimulator or pidAndroid)]
TksToolbar = class(TPresentedControl)
private
FTintColor: TAlphaColor;
FFont: TFont;
FTextColor: TAlphaColor;
FText: string;
FMouseDown: Boolean;
FFormTransition: TksFormTransition;
FOnMenuButtonClick: TNotifyEvent;
FShowMenuButton: Boolean;
FOnBackButtonClick: TNotifyEvent;
FBackButtonEnabled: Boolean;
FShowBackButton: Boolean;
procedure Changed(Sender: TObject);
procedure BackButtonClicked;
procedure SetShowMenuButton(const Value: Boolean);
procedure SetTintColor(const Value: TAlphaColor);
procedure SetTextColor(const Value: TAlphaColor);
procedure SetText(const Value: string);
procedure SetFont(const Value: TFont);
function GetButtonOpacity: single;
procedure SetShowBackButton(const Value: Boolean);
protected
procedure Paint; override;
function GetDefaultSize: TSizeF; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure DoMouseLeave; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DisableBackButton;
procedure EnableBackButton;
published
property Font: TFont read FFont write SetFont;
property Text: string read FText write SetText;
property Size;
property TabOrder;
property TintColor: TAlphaColor read FTintColor write SetTintColor default claWhitesmoke;
property TextColor: TAlphaColor read FTextColor write SetTextColor default claBlack;
property ShowMenuButton: Boolean read FShowMenuButton write SetShowMenuButton default True;
property ShowBackButton: Boolean read FShowBackButton write SetShowBackButton default True;
property OnClick;
property OnMenuButtonClick: TNotifyEvent read FOnMenuButtonClick write FOnMenuButtonClick;
property OnBackButtonClick: TNotifyEvent read FOnBackButtonClick write FOnBackButtonClick;
end;
procedure Register;
implementation
uses Math, System.TypInfo, ksCommon, SysUtils, ksPickers,
Fmx.Forms, FMX.Platform;
procedure Register;
begin
RegisterComponents('Kernow Software FMX', [TksToolbar]);
end;
{ TksToolbar }
procedure TksToolbar.BackButtonClicked;
begin
PickerService.HidePickers;
HideKeyboard;
Application.ProcessMessages;
if FFormTransition.GetFormDepth(Root as TCommonCustomForm) = 0 then
begin
if (Assigned(FOnMenuButtonClick)) and (FShowMenuButton) then
FOnMenuButtonClick(Self);
end
else
begin
if (Assigned(FOnBackButtonClick))and (FShowBackButton) then
begin
FOnBackButtonClick(Self);
FFormTransition.Pop;
end
else
if (FShowBackButton) then
begin
FFormTransition.Pop;
end;
end;
end;
procedure TksToolbar.Changed(Sender: TObject);
begin
InvalidateRect(ClipRect);
end;
constructor TksToolbar.Create(AOwner: TComponent);
begin
inherited;
FFont := TFont.Create;
FFont.Size := 14;
Align := TAlignLayout.MostTop;
FFormTransition := TksFormTransition.Create(nil);
FTintColor := claWhitesmoke;
FTextColor := claBlack;
FMouseDown := False;
FFont.OnChanged := Changed;
FShowMenuButton := True;
FShowBackButton := True;
FBackButtonEnabled := True;
end;
destructor TksToolbar.Destroy;
begin
FreeAndNil(FFormTransition);
//FreeAndNil(FMenuBmp);
//FreeAndNil(FBackBmp);
FreeAndNil(FFont);
inherited;
end;
procedure TksToolbar.DisableBackButton;
begin
FBackButtonEnabled := False;
end;
procedure TksToolbar.DoMouseLeave;
begin
inherited;
FMouseDown := False;
InvalidateRect(ClipRect);
end;
procedure TksToolbar.EnableBackButton;
begin
FBackButtonEnabled := True;
end;
function TksToolbar.GetButtonOpacity: single;
begin
Result := 1;
if FMouseDown then
Result := 0.5;
end;
function TksToolbar.GetDefaultSize: TSizeF;
begin
Result := TSizeF.Create(120, 44);
end;
procedure TksToolbar.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
FMouseDown := X < 30;
if FMouseDown then
begin
if FBackButtonEnabled = False then
Exit;
InvalidateRect(ClipRect);
Application.ProcessMessages;
end;
end;
procedure TksToolbar.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
if FMouseDown then
begin
FMouseDown := False;
InvalidateRect(ClipRect);
Application.ProcessMessages;
TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
BackButtonClicked;
end);
end;
end;
procedure TksToolbar.Paint;
var
ABmp: TBitmap;
s: single;
begin
inherited;
if Locked then
Exit;
ABmp := nil;
s := GetScreenScale(False);
if (csDesigning in ComponentState) then
ABmp := AAccessories.GetAccessoryImage(TksAccessoryType.atDetails)
else
begin
if (FFormTransition.GetFormDepth(Root as TCommonCustomForm) = 0) then
begin
if (FShowMenuButton) then
ABmp := AAccessories.GetAccessoryImage(TksAccessoryType.atDetails);
end
else
if FShowBackButton then
ABmp := AAccessories.GetAccessoryImage(TksAccessoryType.atArrowLeft);
end;
Canvas.BeginScene;
try
Canvas.Fill.Color := FTintColor;
Canvas.Fill.Kind := TBrushKind.Solid;
Canvas.FillRect(ClipRect, 0, 0, AllCorners, 1);
Canvas.Font.Assign(FFont);
Canvas.Fill.Color := FTextColor;
Canvas.FillText(ClipRect, FText, False, 1, [], TTextAlign.Center);
(*{$IFDEF ANDROID}
if (FFormTransition.GetFormDepth(Root as TCommonCustomForm) = 0) and (FShowMenuButton) then
Canvas.FillText(Rect(0, 0, 50, Round(Height)), 'MENU', False, 1, [], TTextAlign.Center);
if (FFormTransition.GetFormDepth(Root as TCommonCustomForm) > 0) and (FShowBackButton) then
Canvas.FillText(Rect(0, 0, 50, Round(Height)), 'BACK', False, 1, [], TTextAlign.Center);
{$ELSE} *)
if ABmp <> nil then
begin
ReplaceOpaqueColor(ABmp, FTextColor);
Canvas.DrawBitmap(ABmp,
RectF(0, 0, ABmp.Width, ABmp.Height),
RectF(4, (Height/2)-((ABmp.Height/s)/2), 4+(ABmp.Width/s), (Height/2)+((ABmp.Height/s)/2)),
GetButtonOpacity);
end;
//{$ENDIF}
finally
Canvas.EndScene;
end;
end;
procedure TksToolbar.SetFont(const Value: TFont);
begin
FFont.Assign(Value);
end;
procedure TksToolbar.SetShowBackButton(const Value: Boolean);
begin
FShowBackButton := Value;
//InvalidateRect(ClipRect);
end;
procedure TksToolbar.SetShowMenuButton(const Value: Boolean);
begin
FShowMenuButton := Value;
//InvalidateRect(ClipRect);
end;
procedure TksToolbar.SetText(const Value: string);
begin
if FText <> Value then
begin
FText := Value;
InvalidateRect(ClipRect);
end;
end;
procedure TksToolbar.SetTextColor(const Value: TAlphaColor);
begin
FTextColor := Value;
end;
procedure TksToolbar.SetTintColor(const Value: TAlphaColor);
begin
if FTintColor <> Value then
begin
FTintColor := Value;
Repaint;
end;
end;
initialization
Classes.RegisterClass(TksToolbar);
end.
|
unit UnitSelectPorts;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin, ComCtrls, UnitConnection, UnitMain, Menus;
type
TFormSelectPorts = class(TForm)
lvPorts: TListView;
se1: TSpinEdit;
btn1: TButton;
chk1: TCheckBox;
edt1: TEdit;
pm1: TPopupMenu;
C1: TMenuItem;
se2: TSpinEdit;
lbl1: TLabel;
procedure btn1Click(Sender: TObject);
procedure C1Click(Sender: TObject);
procedure chk1Click(Sender: TObject);
procedure edt1Change(Sender: TObject);
private
{ Private declarations }
function GrabActivePortsList: string;
public
{ Public declarations }
procedure AddPort(Port: Word);
end;
var
FormSelectPorts: TFormSelectPorts;
implementation
uses
UnitConstants;
{$R *.dfm}
procedure TFormSelectPorts.AddPort(Port: Word);
var
PortList: TListItem;
begin
if OpenPort(Port) = False then
begin
MessageBox(Handle,
PChar('Failed to open port ' + IntToStr(Port) + '. This port is maybe in use.'),
PChar(PROGRAMNAME + ' ' + PROGRAMVERSION),
MB_OK or MB_ICONERROR or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST);
Exit;
end;
PortList := lvPorts.Items.Add;
PortList.Caption := IntToStr(Port);
PortList.ImageIndex := 0;
ActivePortList := GrabActivePortsList;
end;
function TFormSelectPorts.GrabActivePortsList: string;
var
i: Integer;
begin
Result := '';
for i := 0 to lvPorts.Items.Count - 1 do
Result := Result + lvPorts.Items.Item[i].Caption + '|';
end;
procedure TFormSelectPorts.btn1Click(Sender: TObject);
begin
if se1.Text <> '' then AddPort(se1.Value);
end;
procedure TFormSelectPorts.C1Click(Sender: TObject);
var
Port: Word;
begin
if not Assigned(lvPorts.Selected) then Exit;
Port := StrToInt(lvPorts.Selected.Caption);
try ClosePort(Port) except end;
lvPorts.Selected.Delete;
ActivePortList := GrabActivePortsList;
end;
procedure TFormSelectPorts.chk1Click(Sender: TObject);
begin
if chk1.Checked then edt1.PasswordChar := #0 else edt1.PasswordChar := '*';
end;
procedure TFormSelectPorts.edt1Change(Sender: TObject);
begin
ConnectionPassword := edt1.Text;
end;
end.
|
unit U_POWER_ANALYSIS;
interface
uses Classes, SysUtils, U_POWER_LIST_INFO, U_POWER_LIST_ACTION, Dialogs;
type
TIntArray = array of Integer;
type
TFloatArray = array of Double;
type
/// <summary>
/// 功率解析类
/// </summary>
TPowerAnalysis = class
private
FPowerAction : TPowerListAction;
/// <summary>
/// 三相四线所有Φ角度值列表
/// </summary>
FFourUIAngle : TIntArray;
FFourUUAngle : TIntArray;
/// <summary>
/// 三线三线所有Φ角度值列表
/// </summary>
FThreeUIAngle : TIntArray;
FThreeUUAngle : TIntArray;
/// <summary>
/// 获取最接近的标准角度
/// </summary>
function NearStdAngle(arAngle : TIntArray; dAngle: Double):Double;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 解析角度
/// </summary>
procedure AnalysisAngle(APower: TFourPower; dAngle: Double; var arAangle : TFloatArray);overload;
procedure AnalysisAngle(APower: TThreePower; dAngle: Double; var arAangle : TFloatArray);overload;
/// <summary>
/// 解析功率
/// </summary>
procedure AnalysisPower(APower: TFourPower; slErrors: TStringList;
dAngle: Double); overload;
procedure AnalysisPower(APower: TThreePower; slErrors: TStringList;
dAngle: Double); overload;
end;
implementation
{ TPowerAnalysis }
procedure TPowerAnalysis.AnalysisPower(APower: TFourPower;
slErrors: TStringList; dAngle: Double);
procedure SetStdPower(AStdP : TFourPower);
function SetUValue(dValue : Double) : Double;
begin
if dValue > 55 then
Result := 1
else
Result := -1;
end;
function SetIValue(dValue : Double) : Double;
begin
if dValue > 0.5 then
Result := 1
else
Result := -1;
end;
begin
AStdP.Assign(APower);
with AStdP do
begin
U1 := SetUValue(U1);
U2 := SetUValue(U2);
U3 := SetUValue(U3);
I1 := SetIValue(I1);
I2 := SetIValue(I2);
I3 := SetIValue(I3);
if (U1 <> -1) and (I1 <> -1) then
U1i1 := NearStdAngle(FFourUIAngle, U1i1-dAngle)
else
U1i1 := -1;
if (U2 <> -1) and (I2 <> -1) then
U2i2 := NearStdAngle(FFourUIAngle, U2i2-dAngle)
else
U2i2 := -1;
if (U3 <> -1) and (I3 <> -1) then
U3i3 := NearStdAngle(FFourUIAngle, U3i3-dAngle)
else
U3i3 := -1;
if (U1 <> -1) and (U2 <> -1) then
U1u2 := NearStdAngle(FFourUUAngle, U1u2)
else
U1u2 := -1;
if (U1 <> -1) and (U3 <> -1) then
U1u3 := NearStdAngle(FFourUUAngle, U1u3)
else
U1u3 := -1;
if (U2 <> -1) and (U3 <> -1) then
U2u3 := NearStdAngle(FFourUUAngle, U2u3)
else
U2u3 := -1;
end;
end;
var
AStdPower : TFourPower;
arAangle : TFloatArray;
i : Integer;
begin
if not Assigned(slErrors) then
Exit;
if not Assigned(APower) then
Exit;
slErrors.clear;
// 计算Φ角
if dAngle = -1 then
AnalysisAngle(APower, dAngle, arAangle)
else
begin
SetLength(arAangle, 1);
arAangle[0] := dAngle;
end;
AStdPower := TFourPower.Create;
for i := 0 to Length(arAangle) - 1 do
begin
dAngle := arAangle[i];
// 计算标准化功率
SetStdPower(AStdPower);
// 从数据库中查询错误列表
FPowerAction.GetErrorList(AStdPower, slErrors, dAngle);
end;
AStdPower.Free;
end;
procedure TPowerAnalysis.AnalysisAngle(APower: TFourPower; dAngle: Double;
var arAangle : TFloatArray);
function AngleExist(nValue : Double) : Boolean;
var
j : Integer;
begin
Result := False;
for j := 0 to Length(arAangle) - 1 do
begin
if arAangle[j] = nValue then
begin
Result := True;
Exit;
end;
end;
end;
var
i: Integer;
dValue1, dValue2, dValue3 : Double;
dValue : Double;
nCount : Integer;
begin
SetLength(arAangle, 0);
for i := 0 to 360 do
begin
nCount := 0;
if (APower.U1 > 30) and (APower.I1 > 0.3) then
dValue1 := NearStdAngle(FFourUIAngle, APower.U1i1 - i)
else
dValue1 := -2;
if (APower.U2 > 30) and (APower.I2 > 0.3) then
dValue2 := NearStdAngle(FFourUIAngle, APower.U2i2 - i)
else
dValue2 := -2;
if (APower.U3 > 30) and (APower.I3 > 0.3) then
dValue3 := NearStdAngle(FFourUIAngle, APower.U3i3 - i)
else
dValue3 := -2;
if (dValue1 <> -1) and (dValue2 <> -1) and (dValue3 <> -1) then
begin
dValue := 0;
if dValue1 <> -2 then
begin
dValue := dValue + APower.U1i1 - dValue1;
Inc(nCount);
end;
if dValue2 <> -2 then
begin
dValue := dValue + APower.U2i2 - dValue2;
Inc(nCount);
end;
if dValue3 <> -2 then
begin
dValue := dValue + APower.U3i3 - dValue3;
Inc(nCount);
end;
if nCount <> 0 then
begin
dValue := dValue / nCount;
if not AngleExist(dValue) then
begin
if (dValue >= -60) and (dValue <= 60) then
begin
SetLength(arAangle, Length(arAangle) + 1);
arAangle[Length(arAangle) - 1] := dValue;
end;
end;
end;
end;
end;
//var
// i: Integer;
// dMax, dMax1, dMax2, dMax3 : Double;
// nCount : Integer;
//begin
// dMax1 := 888;
// dMax2 := 888;
// dMax3 := 888;
// nCount := 0;
// dMax := 0;
//
// if (APower.U1 > 55) and (APower.I1 > 0.3) then
// for i := 0 to Length(FFourUIAngle) - 1 do
// if Abs(APower.U1i1 - FFourUIAngle[i]) < Abs(dMax1) then
// dMax1 := APower.U1i1 - FFourUIAngle[i];
//
// if (APower.U2 > 55) and (APower.I2 > 0.3) then
// for i := 0 to Length(FFourUIAngle) - 1 do
// if Abs(APower.U2i2 - FFourUIAngle[i]) < Abs(dMax2) then
// dMax2 := APower.U2i2 - FFourUIAngle[i];
//
// if (APower.U3 > 55) and (APower.I3 > 0.3) then
// for i := 0 to Length(FFourUIAngle) - 1 do
// if Abs(APower.U3i3 - FFourUIAngle[i]) < Abs(dMax3) then
// dMax3 := APower.U3i3 - FFourUIAngle[i];
//
// if dMax1 <> 888 then
// begin
// Inc(nCount);
// dMax := dMax + dMax1;
// end;
//
// if dMax2 <> 888 then
// begin
// Inc(nCount);
// dMax := dMax + dMax2;
// end;
//
// if dMax3 <> 888 then
// begin
// Inc(nCount);
// dMax := dMax + dMax3;
// end;
//
// if ncount <> 0 then
// dAngle := dMax/ncount
// else
// dAngle := 20;
end;
procedure TPowerAnalysis.AnalysisAngle(APower: TThreePower; dAngle: Double;
var arAangle : TFloatArray);
function AngleExist(nValue : Double) : Boolean;
var
j : Integer;
begin
Result := False;
for j := 0 to Length(arAangle) - 1 do
begin
if arAangle[j] = nValue then
begin
Result := True;
Exit;
end;
end;
end;
var
i: Integer;
dValue1, dValue2 : Double;
dValue : Double;
nCount : Integer;
begin
SetLength(arAangle, 0);
for i := 0 to 360 do
begin
nCount := 0;
if (APower.U12 > 30) and (APower.I1 > 0.3) then
dValue1 := NearStdAngle(FThreeUIAngle, APower.U12i1 - i)
else
dValue1 := -2;
if (APower.U32 > 30) and (APower.I3 > 0.3) then
dValue2 := NearStdAngle(FThreeUIAngle, APower.U32i3 - i)
else
dValue2 := -2;
if (dValue1 <> -1) and (dValue2 <> -1) then
begin
dValue := 0;
if dValue1 <> -2 then
begin
dValue := dValue + APower.U12i1 - dValue1;
Inc(nCount);
end;
if dValue2 <> -2 then
begin
dValue := dValue + APower.U32i3 - dValue2;
Inc(nCount);
end;
if nCount <> 0 then
begin
dValue := dValue / nCount;
if not AngleExist(dValue) then
begin
SetLength(arAangle, Length(arAangle) + 1);
arAangle[Length(arAangle) - 1] := dValue;
end;
end;
end;
end;
//var
// i: Integer;
// dMax, dMax1, dMax2 : Double;
// nCount : Integer;
//begin
// dMax1 := 888;
// dMax2 := 888;
// nCount := 0;
// dMax := 0;
//
// if (APower.U12 > 30) and (APower.I1 > 0.3) then
// for i := 0 to Length(FThreeUIAngle) - 1 do
// if Abs(APower.U12i1 - FThreeUIAngle[i]) < Abs(dMax1) then
// dMax1 := APower.U12i1 - FThreeUIAngle[i];
//
// if (APower.U32 > 30) and (APower.I3 > 0.3) then
// for i := 0 to Length(FThreeUIAngle) - 1 do
// if Abs(APower.U32i3 - FThreeUIAngle[i]) < Abs(dMax2) then
// dMax2 := APower.U32i3 - FThreeUIAngle[i];
//
// if dMax1 <> 888 then
// begin
// Inc(nCount);
// dMax := dMax + dMax1;
// end;
//
// if dMax2 <> 888 then
// begin
// Inc(nCount);
// dMax := dMax + dMax2;
// end;
//
// if ncount <> 0 then
// dAngle := dMax/ncount
// else
// dAngle := 20;
end;
procedure TPowerAnalysis.AnalysisPower(APower: TThreePower;
slErrors: TStringList; dAngle: Double);
procedure SetStdPower(AStdP : TThreePower);
function SetUValue(dValue : Double) : Double;
begin
if dValue > 30 then
Result := 1
else
Result := -1;
end;
function SetIValue(dValue : Double) : Double;
begin
if dValue > 0.5 then
Result := 1
else
Result := -1;
end;
begin
AStdP.Assign(APower);
with AStdP do
begin
U12 := SetUValue(U12);
U32 := SetUValue(U32);
I1 := SetIValue(I1);
I3 := SetIValue(I3);
if (U12 <> -1) and (I1 <> -1) then
U12i1 := NearStdAngle(FThreeUIAngle, U12i1-dAngle)
else
U12i1 := -1;
if (U32 <> -1) and (I3 <> -1) then
U32i3 := NearStdAngle(FThreeUIAngle, U32i3-dAngle)
else
U32i3 := -1;
if (U12 <> -1) and (U32 <> -1) then
U12u32 := NearStdAngle(FThreeUUAngle, U12u32)
else
U12u32 := -1;
end;
end;
var
AStdPower : TThreePower;
arAangle : TFloatArray;
i: Integer;
begin
if not Assigned(slErrors) then
Exit;
if not Assigned(APower) then
Exit;
slErrors.clear;
// 计算Φ角
if dAngle = -1 then
AnalysisAngle(APower, dAngle, arAangle)
else
begin
SetLength(arAangle, 1);
arAangle[0] := dAngle;
end;
AStdPower := TThreePower.Create;
for i := 0 to Length(arAangle) - 1 do
begin
dAngle := arAangle[i];
if (dAngle >= -30) and (dAngle <= 60) then
begin
// 计算标准化功率
SetStdPower(AStdPower);
// 从数据库中查询错误列表
FPowerAction.GetErrorList(AStdPower, slErrors, dAngle);
end;
end;
AStdPower.Free;
end;
constructor TPowerAnalysis.Create;
begin
FPowerAction := TPowerListAction.Create;
SetLength(FFourUIAngle, 6);
FFourUIAngle[0] := 300;
FFourUIAngle[1] := 240;
FFourUIAngle[2] := 180;
FFourUIAngle[3] := 120;
FFourUIAngle[4] := 60;
FFourUIAngle[5] := 0;
SetLength(FFourUUAngle, 2);
FFourUUAngle[0] := 240;
FFourUUAngle[1] := 120;
SetLength(FThreeUIAngle, 10);
FThreeUIAngle[0] := 330;
FThreeUIAngle[1] := 300;
FThreeUIAngle[2] := 270;
FThreeUIAngle[3] := 240;
FThreeUIAngle[4] := 210;
FThreeUIAngle[5] := 150;
FThreeUIAngle[6] := 120;
FThreeUIAngle[7] := 90;
FThreeUIAngle[8] := 60;
FThreeUIAngle[9] := 30;
SetLength(FThreeUUAngle, 8);
FThreeUUAngle[0] := 330;
FThreeUUAngle[1] := 300;
FThreeUUAngle[2] := 240;
FThreeUUAngle[3] := 180;
FThreeUUAngle[4] := 120;
FThreeUUAngle[5] := 60;
FThreeUUAngle[6] := 30;
FThreeUUAngle[7] := 0;
end;
destructor TPowerAnalysis.Destroy;
begin
FPowerAction.Free;
inherited;
end;
function TPowerAnalysis.NearStdAngle(arAngle : TIntArray; dAngle: Double): Double;
function GetValue(dV1, dV2 : Double) : Double;
begin
Result := dV1 - dV2;
if Result > 180 then
Result := 360- Result;
if Result < -180 then
Result := 360 + Result;
end;
var
i : Integer;
dTemp : Double;
nIndex : Integer;
begin
dTemp := 888;
nIndex := -1;
if dAngle < 0 then
dAngle := dAngle + 360
else if dAngle > 360 then
dAngle := dAngle - 360;
for i := 0 to Length(arAngle) - 1 do
begin
if Abs(GetValue(dAngle, arAngle[i])) < Abs(dTemp) then
begin
nIndex := i;
dTemp := GetValue(dAngle, arAngle[i]);
end;
end;
if Abs(dTemp) < 5 then
Result := arAngle[nIndex]
else
Result := -1;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.DSProxyWriter;
interface
uses Data.DBXPlatform, Datasnap.DSCommonProxy, System.Generics.Collections, System.Masks, System.SysUtils;
type
TDSProxyWriter = class;
TDSProxyWriterFactory = class
public
class function Instance: TDSProxyWriterFactory; static;
class procedure RegisterWriter(const Id: string; const WriterClass: TObjectClass); static;
class procedure UnregisterWriter(const Id: string); static;
class function HasWriter(const Id: UnicodeString): Boolean;
class function GetWriter(const Id: UnicodeString): TDSProxyWriter; static;
class function RegisteredWritersList: TDBXStringArray; static;
constructor Create;
destructor Destroy; override;
private
class var FSingleton: TDSProxyWriterFactory;
FRegisteredWriters: TDBXObjectStore;
end;
TDSProxyWriteFeature = (feConnectsWithDSRestConnection, feConnectsWithDBXConnection, feRESTClient, feDBXClient);
TDSProxyWriteFeatures = set of TDSProxyWriteFeature;
TDSProxyWriterProperties = record
UsesUnits: string;
DefaultExcludeClasses: string;
DefaultExcludeMethods: string;
DefaultEncoding: TEncoding;
Author: string;
Comment: string;
Language: string;
Features: TDSProxyWriteFeatures;
end;
TDSProxyFileDescription = record
ID: string;
DefaultFileExt: string;
end;
TDSProxyFileDescriptions = array of TDSProxyFileDescription;
TDSCustomProxyWriter = class;
TDSProxyWriter = class abstract(TFactoryObject)
public
function CreateProxyWriter: TDSCustomProxyWriter; virtual; abstract;
function Properties: TDSProxyWriterProperties; virtual; abstract;
function FileDescriptions: TDSProxyFileDescriptions; virtual; abstract;
end;
TDSCustomProxyWriter = class abstract
public
constructor Create;
destructor Destroy; override;
procedure WriteProxy; virtual;
protected
procedure WriteImplementation; virtual; abstract;
procedure WriteInterface; virtual; abstract;
procedure WriteFileHeader; virtual;
function GetTimeStamp: string; virtual;
procedure DerivedWrite(const Line: UnicodeString); virtual; abstract;
procedure DerivedWriteLine; virtual; abstract;
function GetAssignmentString: UnicodeString; virtual; abstract;
function IncludeClassName(const ClassName: UnicodeString): Boolean;
function IncludeMethodName(const MethodName: UnicodeString): Boolean;
function IncludeClass(const ProxyClass: TDSProxyClass): Boolean; virtual;
function IncludeMethod(const ProxyMethod: TDSProxyMethod): Boolean; virtual;
procedure WriteLine(const Line: UnicodeString); overload;
procedure Indent;
procedure Outdent;
procedure WriteLine; overload;
function IsKnownTableTypeName(const Name: UnicodeString): Boolean; virtual;
function IsKnownDBXValueTypeName(const Name: UnicodeString): Boolean; virtual;
function IsKnownJSONTypeName(const Name: UnicodeString): Boolean; virtual;
function GetDelphiTypeName(const Param: TDSProxyParameter): UnicodeString; virtual;
function GetGetter(const Param: TDSProxyParameter): UnicodeString;
function GetSetter(const Param: TDSProxyParameter): UnicodeString;
function GetCreateDataSetReader(const Param: TDSProxyParameter): UnicodeString; virtual; abstract;
function GetCreateParamsReader(const Param: TDSProxyParameter): UnicodeString; virtual; abstract;
strict private
FMetadata: TDSProxyMetadata;
FOwnsMetaData: Boolean;
private
procedure ClearMasks;
function InclusionTest(const Includes: TDBXStringArray; const Excludes: TDBXStringArray; const Name: UnicodeString): Boolean;
procedure SetMetaDataLoader(const Value: IDSProxyMetaDataLoader);
protected
FUnitFileName: UnicodeString;
FIndentString: UnicodeString;
FIndentIncrement: Integer;
FMetaDataLoader: IDSProxyMetaDataLoader;
private
FIndentSpaces: Integer;
FMasks: TObjectDictionary<string, TMask>;
FIncludeClasses: TDBXStringArray;
FExcludeClasses: TDBXStringArray;
FIncludeMethods: TDBXStringArray;
FExcludeMethods: TDBXStringArray;
FProxyWriters: TDictionary<string, IDSProxyWriter>;
function GetMetadata: TDSProxyMetadata;
procedure SetExcludeClasses(const Value: TDBXStringArray);
procedure SetExcludeMethods(const Value: TDBXStringArray);
procedure SetIncludeClasses(const Value: TDBXStringArray);
procedure SetIncludeMethods(const Value: TDBXStringArray);
public
property Metadata: TDSProxyMetadata read GetMetadata;
property MetaDataLoader: IDSProxyMetaDataLoader read FMetaDataLoader write SetMetaDataLoader;
property ProxyWriters: TDictionary<string, IDSProxyWriter> read FProxyWriters;
property UnitFileName: UnicodeString read FUnitFileName write FUnitFileName;
property IncludeClasses: TDBXStringArray read FIncludeClasses write SetIncludeClasses;
property ExcludeClasses: TDBXStringArray read FExcludeClasses write SetExcludeClasses;
property IncludeMethods: TDBXStringArray read FIncludeMethods write SetIncludeMethods;
property ExcludeMethods: TDBXStringArray read FExcludeMethods write SetExcludeMethods;
protected
property AssignmentString: UnicodeString read GetAssignmentString;
end;
const
// value from toolsapi.pas
sDSProxyDelphiLanguage = 'Delphi';
sDSProxyCppLanguage = 'C++';
sDSProxyJavaScriptLanguage = 'Java Script';
implementation
uses Data.DBXCommon, Datasnap.DSClientResStrs;
{ TDSClientProxyWriterFactory }
class function TDSProxyWriterFactory.Instance: TDSProxyWriterFactory;
begin
if FSingleton = nil then
FSingleton := TDSProxyWriterFactory.Create;
Result := FSingleton;
end;
class procedure TDSProxyWriterFactory.RegisterWriter(const Id: string; const WriterClass: TObjectClass);
var
LInstance: TDSProxyWriterFactory;
begin
LInstance := TDSProxyWriterFactory.Instance;
LInstance.FRegisteredWriters[Id] := TObject(WriterClass);
end;
class procedure TDSProxyWriterFactory.UnregisterWriter(const Id: string);
var
LInstance: TDSProxyWriterFactory;
I: Integer;
begin
LInstance := TDSProxyWriterFactory.Instance;
I := LInstance.FRegisteredWriters.IndexOf(Id);
if I >= 0 then
begin
LInstance.FRegisteredWriters.Delete(I);
if LInstance.FRegisteredWriters.Count = 0 then
Instance.Free;
end;
end;
class function TDSProxyWriterFactory.HasWriter(const Id: string): Boolean;
begin
Result := Instance.FRegisteredWriters[Id] <> nil;
end;
class function TDSProxyWriterFactory.GetWriter(const Id: string): TDSProxyWriter;
var
Clazz: TObjectClass;
begin
if Id = '' then
raise TDSProxyException.Create(SNoWriter);
if not HasWriter(Id) then
raise TDSProxyException.CreateFmt(SUnknownWriter, [Id]);
Clazz := TObjectClass(Instance.FRegisteredWriters[Id]);
if Clazz <> nil then
begin
try
Exit(TDSProxyWriter(Clazz.Create));
except
on E: Exception do
;
end;
Result := nil;
end
else
Result := nil;
end;
class function TDSProxyWriterFactory.RegisteredWritersList: TDBXStringArray;
var
List: TDBXStringArray;
I: Integer;
Keys: TDBXKeyEnumerator;
LInstance: TDSProxyWriterFactory;
begin
LInstance := TDSProxyWriterFactory.Instance;
if LInstance.FRegisteredWriters.Count > 0 then
begin
SetLength(List ,LInstance.FRegisteredWriters.Count);
I := 0;
Keys := LInstance.FRegisteredWriters.Keys;
try
while Keys.MoveNext do
List[IncrAfter(I)] := UnicodeString(Keys.Current);
finally
Keys.Free;
end;
end;
Result := List;
end;
constructor TDSProxyWriterFactory.Create;
begin
inherited Create;
FRegisteredWriters := TDBXObjectStore.Create;
end;
destructor TDSProxyWriterFactory.Destroy;
begin
FreeAndNil(FRegisteredWriters);
FSingleton := nil;
inherited Destroy;
end;
procedure TDSCustomProxyWriter.WriteFileHeader;
var
GeneratedMessage: UnicodeString;
Line: UnicodeString;
LTimeStamp: string;
begin
GeneratedMessage := '// ' + SGeneratedCode;
LTimeStamp := GetTimeStamp;
if Trim(LTimeStamp) <> '' then
LTimeStamp := '// ' + LTimeStamp;
Line := '// ';
WriteLine(Line);
WriteLine(GeneratedMessage);
if Trim(LTimeStamp) <> '' then
WriteLine(LTimeStamp);
WriteLine(Line);
WriteLine;
end;
procedure TDSCustomProxyWriter.ClearMasks;
begin
FMasks.Clear;
end;
constructor TDSCustomProxyWriter.Create;
begin
inherited Create;
FMasks := TObjectDictionary<string, TMask>.Create([doOwnsValues]);
FProxyWriters := TDictionary<string, IDSProxyWriter>.Create;
end;
function TDSCustomProxyWriter.InclusionTest(const Includes: TDBXStringArray; const Excludes: TDBXStringArray; const Name: UnicodeString): Boolean;
function IsMatch(const Pattern: string): Boolean;
var
Mask: TMask;
begin
if not FMasks.TryGetValue(Pattern, Mask) then
begin
Mask := TMask.Create(Trim(Pattern));
FMasks.Add(Pattern, Mask);
end;
Result := Mask.Matches(Name);
end;
var
Index: Integer;
begin
Result := True;
if Excludes <> nil then
begin
for Index := 0 to Length(Excludes) - 1 do
begin
if IsMatch(Excludes[Index]) then
begin
Result := False;
break;
end;
end;
end;
if Includes <> nil then
begin
for Index := 0 to Length(Includes) - 1 do
begin
if IsMatch(Includes[Index]) then
begin
Exit(True);
end;
end;
Result := False;
end;
end;
function TDSCustomProxyWriter.IncludeClassName(const ClassName: UnicodeString): Boolean;
begin
Result := InclusionTest(FIncludeClasses, FExcludeClasses, ClassName);
end;
function TDSCustomProxyWriter.IncludeMethodName(const MethodName: UnicodeString): Boolean;
begin
Result := InclusionTest(FIncludeMethods, FExcludeMethods, MethodName);
end;
procedure TDSCustomProxyWriter.WriteLine(const Line: UnicodeString);
begin
DerivedWrite(FIndentString + Line);
DerivedWriteLine;
end;
procedure TDSCustomProxyWriter.Indent;
var
Index: Integer;
begin
FIndentSpaces := FIndentSpaces + FIndentIncrement;
for Index := 0 to FIndentIncrement - 1 do
FIndentString := FIndentString + ' ';
end;
procedure TDSCustomProxyWriter.Outdent;
var
Index: Integer;
begin
FIndentSpaces := FIndentSpaces - FIndentIncrement;
FIndentString := '';
for Index := 0 to FIndentSpaces - 1 do
FIndentString := FIndentString + ' ';
end;
procedure TDSCustomProxyWriter.SetExcludeClasses(const Value: TDBXStringArray);
begin
ClearMasks;
FExcludeClasses := Value;
end;
procedure TDSCustomProxyWriter.SetExcludeMethods(const Value: TDBXStringArray);
begin
ClearMasks;
FExcludeMethods := Value;
end;
procedure TDSCustomProxyWriter.SetIncludeClasses(const Value: TDBXStringArray);
begin
ClearMasks;
FIncludeClasses := Value;
end;
procedure TDSCustomProxyWriter.SetIncludeMethods(const Value: TDBXStringArray);
begin
ClearMasks;
FIncludeMethods := Value;
end;
procedure TDSCustomProxyWriter.SetMetaDataLoader(
const Value: IDSProxyMetaDataLoader);
begin
FMetaDataLoader := Value;
end;
procedure TDSCustomProxyWriter.WriteLine;
begin
DerivedWriteLine;
end;
procedure TDSCustomProxyWriter.WriteProxy;
begin
WriteFileHeader;
WriteInterface;
WriteImplementation;
end;
function TDSCustomProxyWriter.IsKnownTableTypeName(const Name: UnicodeString): Boolean;
begin
if not StringIsNil(Name) then
begin
if (CompareText(Name, 'TDataSet') = 0) or (CompareText(Name, 'TParams') = 0) then
Exit(True);
end;
Result := False;
end;
function TDSCustomProxyWriter.IsKnownDBXValueTypeName(const Name: UnicodeString): Boolean;
begin
if not StringIsNil(Name) then
begin
if (CompareText(Copy(Name,0+1,4-(0)), 'TDBX') = 0) and (StringIndexOf(Name,'Value') = Length(Name) - 5) then
Exit(True);
end;
Result := False;
end;
function TDSCustomProxyWriter.IsKnownJSONTypeName(const Name: UnicodeString): Boolean;
begin
if not StringIsNil(Name) then
begin
if CompareText(Copy(Name,0+1,5-(0)), 'TJSON') = 0 then
Exit(True);
end;
Result := False;
end;
destructor TDSCustomProxyWriter.Destroy;
begin
FMasks.Free;
FProxyWriters.Free;
if FOwnsMetaData then
FMetadata.Free;
inherited;
end;
function TDSCustomProxyWriter.GetDelphiTypeName(const Param: TDSProxyParameter): UnicodeString;
var
Name: UnicodeString;
begin
Name := Param.TypeName;
if not StringIsNil(Name) then
Exit(Name);
case Param.DataType of
TDBXDataTypes.AnsiStringType:
Name := 'AnsiString';
TDBXDataTypes.BooleanType:
Name := 'Boolean';
TDBXDataTypes.Int8Type:
Name := 'ShortInt';
TDBXDataTypes.UInt8Type:
Name := 'Byte';
TDBXDataTypes.Int16Type:
Name := 'SmallInt';
TDBXDataTypes.UInt16Type:
Name := 'Word';
TDBXDataTypes.Int32Type:
Name := 'Integer';
TDBXDataTypes.Int64Type:
Name := 'Int64';
TDBXDataTypes.WideStringType:
Name := 'String';
TDBXDataTypes.SingleType:
Name := 'Single';
TDBXDataTypes.DoubleType:
Name := 'Double';
TDBXDataTypes.BcdType:
Name := 'TBcd';
TDBXDataTypes.TimeType:
Name := 'TDBXTime';
TDBXDataTypes.DatetimeType:
Name := 'TDateTime';
TDBXDataTypes.DateType:
Name := 'TDBXDate';
TDBXDataTypes.TimeStampType:
Name := 'TSQLTimeStamp';
TDBXDataTypes.TimeStampOffsetType:
Name := 'TSQLTimeStampOffset';
TDBXDataTypes.CurrencyType:
Name := 'Currency';
TDBXDataTypes.TableType:
if IsKnownTableTypeName(Param.TypeName) then
Name := Param.TypeName
else
Name := 'TDBXReader';
TDBXDataTypes.BinaryBlobType:
Name := 'TStream';
TDBXDataTypes.VariantType:
Name := 'Variant';
TDBXDataTypes.DbxConnectionType:
Name := 'TDBXConnection';
else
Name := '{UnknownType(' + IntToStr(Param.DataType) + ')}';
end;
Result := Name;
end;
function TDSCustomProxyWriter.GetGetter(const Param: TDSProxyParameter): UnicodeString;
var
Getter: UnicodeString;
begin
case Param.DataType of
TDBXDataTypes.AnsiStringType:
Getter := 'GetAnsiString';
TDBXDataTypes.BooleanType:
Getter := 'GetBoolean';
TDBXDataTypes.Int8Type:
Getter := 'GetInt8';
TDBXDataTypes.UInt8Type:
Getter := 'GetUInt8';
TDBXDataTypes.Int16Type:
Getter := 'GetInt16';
TDBXDataTypes.UInt16Type:
Getter := 'GetUInt16';
TDBXDataTypes.Int32Type:
Getter := 'GetInt32';
TDBXDataTypes.Int64Type:
Getter := 'GetInt64';
TDBXDataTypes.WideStringType:
Getter := 'GetWideString';
TDBXDataTypes.SingleType:
Getter := 'GetSingle';
TDBXDataTypes.DoubleType:
Getter := 'GetDouble';
TDBXDataTypes.BcdType:
Getter := 'GetBcd';
TDBXDataTypes.TimeType:
Getter := 'GetTime';
TDBXDataTypes.DatetimeType:
Getter := 'AsDateTime';
TDBXDataTypes.DateType:
Getter := 'GetDate';
TDBXDataTypes.TimeStampType:
Getter := 'GetTimeStamp';
TDBXDataTypes.TimeStampOffsetType:
Getter := 'GetTimeStampOffset';
TDBXDataTypes.CallbackType:
Getter := 'GetCallbackValue';
TDBXDataTypes.JsonValueType:
Getter := 'GetJSONValue';
TDBXDataTypes.CurrencyType:
Getter := 'AsCurrency';
TDBXDataTypes.TableType:
Getter := 'GetDBXReader';
TDBXDataTypes.BinaryBlobType:
Getter := 'GetStream';
TDBXDataTypes.VariantType:
Getter := 'AsVariant';
else
Getter := '{UnknownType(' + IntToStr(Param.DataType) + ')}';
end;
Result := Getter;
end;
function TDSCustomProxyWriter.GetMetadata: TDSProxyMetadata;
begin
if FMetaData = nil then
begin
FMetaData := TDSProxyMetadata.Create;
FOwnsMetaData := True;
if FMetaDataLoader <> nil then
FMetaDataLoader.Load(FMetaData);
end;
Result := FMetaData;
end;
function TDSCustomProxyWriter.GetSetter(const Param: TDSProxyParameter): UnicodeString;
var
Setter: UnicodeString;
HasOwnerOption: Boolean;
begin
HasOwnerOption := False;
case Param.DataType of
TDBXDataTypes.AnsiStringType:
Setter := 'SetAnsiString';
TDBXDataTypes.BooleanType:
Setter := 'SetBoolean';
TDBXDataTypes.Int8Type:
Setter := 'SetInt8';
TDBXDataTypes.UInt8Type:
Setter := 'SetUInt8';
TDBXDataTypes.Int16Type:
Setter := 'SetInt16';
TDBXDataTypes.UInt16Type:
Setter := 'SetUInt16';
TDBXDataTypes.Int32Type:
Setter := 'SetInt32';
TDBXDataTypes.Int64Type:
Setter := 'SetInt64';
TDBXDataTypes.WideStringType:
Setter := 'SetWideString';
TDBXDataTypes.SingleType:
Setter := 'SetSingle';
TDBXDataTypes.DoubleType:
Setter := 'SetDouble';
TDBXDataTypes.BcdType:
Setter := 'SetBcd';
TDBXDataTypes.TimeType:
Setter := 'SetTime';
TDBXDataTypes.DatetimeType:
Setter := 'AsDateTime';
TDBXDataTypes.DateType:
Setter := 'SetDate';
TDBXDataTypes.TimeStampType:
Setter := 'SetTimeStamp';
TDBXDataTypes.TimeStampOffsetType:
Setter := 'SetTimeStampOffset';
TDBXDataTypes.CallbackType:
Setter := 'SetCallbackValue';
TDBXDataTypes.JsonValueType:
begin
Setter := 'SetJSONValue';
HasOwnerOption := True;
end;
TDBXDataTypes.CurrencyType:
Setter := 'AsCurrency';
TDBXDataTypes.TableType:
begin
Setter := 'SetDBXReader';
HasOwnerOption := True;
end;
TDBXDataTypes.BinaryBlobType:
begin
Setter := 'SetStream';
HasOwnerOption := True;
end;
TDBXDataTypes.VariantType:
Setter := 'AsVariant';
else
Setter := '{UnknownType(' + IntToStr(Param.DataType) + ')}';
end;
if Setter[1+0] = 'S' then
begin
if (Param.DataType = TDBXDataTypes.TableType) and IsKnownTableTypeName(Param.TypeName) then
begin
if CompareText(Param.TypeName, 'TDataSet') = 0 then
Exit(Setter + GetCreateDataSetReader(Param))
else if CompareText(Param.TypeName, 'TParams') = 0 then
Exit(Setter + GetCreateParamsReader(Param));
end;
if IsKnownDBXValueTypeName(Param.TypeName) then
Exit(Setter + '(' + Param.ParameterName + '.Value.' + GetGetter(Param) + ')');
Setter := Setter + '(' + Param.ParameterName;
if HasOwnerOption then
Setter := Setter + ', FInstanceOwner)'
else
Setter := Setter + ')';
end
else
Setter := Setter + ' ' + AssignmentString + ' ' + Param.ParameterName;
Result := Setter;
end;
function TDSCustomProxyWriter.GetTimeStamp: string;
var
LNow: TDateTime;
begin
LNow := Now;
Result := FormatDateTime(FormatSettings.ShortDateFormat, LNow) + ' ' + FormatDateTime(FormatSettings.LongTimeFormat, LNow);
end;
function TDSCustomProxyWriter.IncludeClass(
const ProxyClass: TDSProxyClass): Boolean;
begin
Result := IncludeClassName(ProxyClass.ProxyClassName);
end;
function TDSCustomProxyWriter.IncludeMethod(
const ProxyMethod: TDSProxyMethod): Boolean;
begin
Result := INcludeMethodName(ProxyMethod.ProxyMethodName);
end;
end.
|
unit PrintView;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Quickrpt, StdCtrls, Spin, Buttons, ExtCtrls, QRPrntr, Db,
Tmax_DataSetText;
type
TViewForm = class(TForm)
Panel1: TPanel;
Bexit: TBitBtn;
SE_Zoom: TSpinEdit;
Bprint: TBitBtn;
SE_CurPage: TSpinEdit;
QRPreview: TQRPreview;
P_TotalPage: TPanel;
Panel4: TPanel;
Panel5: TPanel;
Panel3: TPanel;
T_Dml1: TTMaxDataSet;
procedure BexitClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure SE_ZoomChange(Sender: TObject);
procedure BprintClick(Sender: TObject);
procedure SE_CurPageChange(Sender: TObject);
procedure SE_CurPageKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FQr_QuickRep : TCustomQuickRep;
FMaxCount : integer;
FPosition : integer;
procedure SetMaxCount(Value : integer);
procedure SetPosition(Value : integer);
{ Private declarations }
public
constructor CreatePreview(AOwner : TComponent; aQuickRep : TCustomQuickRep); virtual;
property Qr_Report : TCustomQuickRep read FQr_QuickRep write FQr_QuickRep;
property MaxCount : Integer read FMaxCount write SetMaxCount;
property Position : Integer read FPosition write SetPosition;
{ Public declarations }
end;
var
ViewForm: TViewForm;
implementation
{$R *.DFM}
uses Pib30101, PIB30100;
constructor TViewForm.CreatePreview(AOwner : TComponent; aQuickRep : TCustomQuickRep);
begin
inherited Create(AOwner);
FMaxCount := 0;
FPosition := 0;
QR_Report := aQuickRep;
// WindowState := wsMaximized;
QRPreview.QRPrinter := aQuickRep.QRPrinter;
if QR_Report <> nil then Caption := '출력 미리보기 화면';
end;
procedure TViewForm.SetMaxCount(Value : integer);
begin
if FMaxCount <> Value then
begin
FMaxCount := Value;
// Pgr.Max := Value;
end;
end;
procedure TViewForm.SetPosition(Value : integer);
begin
if FPosition <> Value then
begin
FPosition := Value;
// Pgr.Position := Value;
end;
end;
procedure TViewForm.FormActivate(Sender: TObject);
begin
SE_Zoom.Value := 100;
QRPreview.Zoom := SE_Zoom.Value;
P_TotalPage.Caption := IntToStr(FM_Main.TPrint.RecordCount);
SE_CurPage.Value := 1;
QRPreview.PageNumber := SE_CurPage.Value;
if FM_Main.Vcertpryn = 'Y' then Bprint.Enabled := False
else Bprint.Enabled := True;
SE_CurPage.SetFocus;
end;
procedure TViewForm.BprintClick(Sender: TObject);
var Tem1 : String;
begin
Qrpreview.QRPrinter.Print;
Tem1 := 'UPDATE PIHCERT SET '+#13+
' CERTPRDATE='''+FM_Main.GSsysdate+''', '+#13+
' CERTPRYN =''Y'', '+#13+
' CERTPRCNT = (CERTPRCNT + 1) '+#13+
' WHERE EMPNO ='''+FM_Main.Ed_empno.Hint+''''+#13+
' AND CERTKIND ='''+FM_Main.Vcertkind+''' '+#13+
' AND CERTDATE ='''+FM_Main.Vcertdate+''' '+#13+
//2015.04.06.hjku..admin 추가.. 이지연씨 요청..
' AND ADMINYN ='''+FM_Main.Vadminyn +''' ';
with T_Dml1 do
begin
Close;
Sql.Clear;
Sql.Text := Tem1;
ServiceName := 'PIB3012A_dml';
//sql.savetofile('c:\test.sql');
if not Execute then
begin
Application.Messagebox('발행 내역 저장에 실패했습니다.','작업안내',mb_ok+ mb_IconStop);
system.exit;
end
else MessageBox(handle,'출력이 완료되었습니다 !!.','확 인',MB_OK or $0030);
Close;
end;
// Fm_Pib30101.InReport.Print;
Bprint.Enabled := False;
SE_CurPage.SetFocus;
end;
procedure TViewForm.BexitClick(Sender: TObject);
begin
FM_Main.LoadData1;
Close;
end;
procedure TViewForm.SE_ZoomChange(Sender: TObject);
begin
QRPreview.Zoom := SE_Zoom.Value;
end;
procedure TViewForm.SE_CurPageChange(Sender: TObject);
begin
if SE_CurPage.Value <=0 then System.Exit;
if SE_CurPage.Value > StrToIntDef(P_TotalPage.Caption,0) then
SE_CurPage.Value := StrToIntDef(P_TotalPage.Caption,0);
QRPreview.PageNumber := SE_CurPage.Value;
end;
procedure TViewForm.SE_CurPageKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
Case key of
VK_NEXT : SE_CurPage.Value := SE_CurPage.Value +1;
VK_PRIOR : SE_CurPage.Value := SE_CurPage.Value -1;
end;
end;
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ TSmithSeries Component }
{ Copyright (c) 2000-2004 Marjan Slatinek }
{*********************************************}
unit TeeSmith;
{$I TeeDefs.inc}
interface
uses {$IFDEF CLR}
Windows,
Classes,
Graphics,
{$ELSE}
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
{$ENDIF}
TeEngine, Chart, Series, TeCanvas, TeePolar;
type
TSmithSeries = class(TCircledSeries)
private
FCirclePen : TChartPen;
FImagSymbol : String;
FPointer : TSeriesPointer;
OldX,OldY : Integer;
function GetResistanceValues: TChartValueList;
function GetReactance: TChartValueList;
Function GetCPen:TChartPen;
Function GetRPen:TChartPen;
Function GetCLabels:Boolean;
Function GetRLabels:Boolean;
procedure SetResistanceValues(Value: TChartValueList);
procedure SetReactance(Value: TChartValueList);
procedure SetRPen(const Value: TChartPen);
procedure SetCPen(const Value: TChartPen);
procedure SetPointer(const Value: TSeriesPointer);
procedure SetCLabels(const Value: Boolean);
procedure SetRLabels(const Value: Boolean);
Procedure SetCirclePen(Const Value:TChartPen);
function GetCLabelsFont: TTeeFont;
function GetRLabelsFont: TTeeFont;
procedure SetCLabelsFont(const Value: TTeeFont);
procedure SetRLabelsFont(const Value: TTeeFont);
procedure SetImagSymbol(Const Value:String);
protected
procedure AddSampleValues(NumValues: Integer; OnlyMandatory:Boolean=False); override;
procedure DoBeforeDrawValues; override;
procedure DrawAllValues; override;
procedure DrawValue(ValueIndex: Integer); override;
class Function GetEditorClass:String; override;
function GetXCircleLabel(Const Reactance:Double):String;
procedure LinePrepareCanvas(ValueIndex:Integer);
Procedure PrepareForGallery(IsEnabled:Boolean); override; { 5.02 }
Procedure SetParentChart(Const Value:TCustomAxisPanel); override;
public
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
function AddPoint(Const Resist,React: Double; Const ALabel: String='';
AColor: TColor=clTeeColor): Integer;
function CalcXPos(ValueIndex: Integer): Integer; override;
function CalcYPos(ValueIndex: Integer): Integer; override;
function Clicked(X,Y:Integer):Integer;override;
procedure DrawRCircle(Const Value:Double; Z:Integer; ShowLabel:Boolean=True);
procedure DrawXCircle(Const Value:Double; Z:Integer; ShowLabel:Boolean=True);
procedure PosToZ(X,Y: Integer; var Resist,React: Double);
procedure ZToPos(Const Resist,React: Double; var X,Y: Integer);
published
property Active;
property CCirclePen:TChartPen read GetCPen write SetCPen;
property CircleBackColor;
property CircleGradient;
property CirclePen:TChartPen read FCirclePen write SetCirclePen;
property CLabels:Boolean read GetCLabels write SetCLabels;
property CLabelsFont:TTeeFont read GetCLabelsFont write SetCLabelsFont;
property ColorEachPoint;
property ImagSymbol:String read FImagSymbol write SetImagSymbol;
property ResistanceValues:TChartValueList read GetResistanceValues write SetResistanceValues;
property ReactanceValues:TChartValueList read GetReactance write SetReactance;
property Pen;
property Pointer:TSeriesPointer read FPointer write SetPointer;
property RCirclePen:TChartPen read GetRPen write SetRPen;
property RLabels:Boolean read GetRLabels write SetRLabels;
property RLabelsFont:TTeeFont read GetRLabelsFont write SetRLabelsFont;
end;
implementation
Uses {$IFDEF CLR}
SysUtils,
{$ENDIF}
TeeProCo, TeeConst;
{ TSmithSeries }
Constructor TSmithSeries.Create(AOwner: TComponent);
begin
inherited;
XValues.Name := TeeMsg_SmithResistance;
XValues.Order:= loNone; { 5.02 }
YValues.Name := TeeMsg_SmithReactance;
FPointer := TSeriesPointer.Create(Self);
FCirclePen := CreateChartPen;
FImagSymbol := 'i'; { 5.02 }
end;
Destructor TSmithSeries.Destroy;
begin
FCirclePen.Free;
FreeAndNil(FPointer);
inherited;
end;
procedure TSmithSeries.SetCLabels(Const Value: Boolean);
begin
if Assigned(GetVertAxis) then
GetVertAxis.Labels:=Value;
end;
procedure TSmithSeries.SetRLabels(Const Value: Boolean);
begin
if Assigned(GetHorizAxis) then
GetHorizAxis.Labels:=Value;
end;
procedure TSmithSeries.SetRPen(const Value: TChartPen);
begin
if Assigned(GetVertAxis) then
GetVertAxis.Grid.Assign(Value);
end;
procedure TSmithSeries.SetCPen(const Value: TChartPen);
begin
if Assigned(GetHorizAxis) then
GetHorizAxis.Grid.Assign(Value);
end;
procedure TSmithSeries.SetPointer(const Value: TSeriesPointer);
begin
FPointer.Assign(Value);
end;
function TSmithSeries.GetResistanceValues: TChartValueList;
begin
Result:=XValues;
end;
function TSmithSeries.GetReactance: TChartValueList;
begin
Result:=YValues;
end;
procedure TSmithSeries.SetResistanceValues(Value: TChartValueList);
begin
SetXValues(Value);
end;
procedure TSmithSeries.SetReactance(Value: TChartValueList);
begin
SetYValues(Value);
end;
procedure TSmithSeries.LinePrepareCanvas(ValueIndex:Integer);
begin
With ParentChart.Canvas do
begin
if Self.Pen.Visible then
begin
if ValueIndex=-1 then AssignVisiblePenColor(Self.Pen,SeriesColor)
else AssignVisiblePenColor(Self.Pen,ValueColor[ValueIndex]);
end
else Pen.Style:=psClear;
BackMode:=cbmTransparent;
end;
end;
{ impendance to Position}
{ (GRe,GIm)=(1-z)/(1+z) }
procedure TSmithSeries.ZToPos(Const Resist,React: Double; var X,Y: Integer);
var GRe : Double;
GIm : Double;
Norm2 : Double;
InvDen : Double;
begin
Norm2 := Sqr(Resist)+Sqr(React);
InvDen := 1/(Norm2+2*Resist+1);
GRe := (Norm2-1)*InvDen;
GIm := 2*React*InvDen;
X := CircleXCenter+Round(GRe*XRadius);
Y := CircleYCenter-Round(GIm*YRadius);
end;
{ Position to impendance}
{ (ZRe,ZIm)=(1+gamma)/(1-gamma) }
procedure TSmithSeries.PosToZ(X,Y: Integer; var Resist,React: Double);
var GRe : Double;
GIm : Double;
Norm2 : Double;
InvDen : Double;
begin
X := X-CircleXCenter;
Y := CircleYCenter-Y;
GRe := X/XRadius;
GIm := Y/YRadius;
Norm2 := Sqr(GRe)+Sqr(GIm);
InvDen := 1/(Norm2-2*GRe+1);
Resist := (1-Norm2)*InvDen;
React := 2*GIm*InvDen;
end;
Procedure TSmithSeries.DrawRCircle(Const Value:Double; Z:Integer;
ShowLabel: Boolean);
Procedure DrawrCircleLabel(rVal: Double; X,Y: Integer);
begin
if GetHorizAxis.Visible and ShowLabel then { 5.02 }
With ParentChart.Canvas do
begin
AssignFont(RLabelsFont);
TextAlign:=ta_Center;
BackMode:=cbmTransparent;
TextOut3D(X,Y,EndZ,FloatToStr(rVal));
end;
end;
Var tmp : Double;
HalfXSize : Integer;
HalfYSize : Integer;
begin
if Value<>-1 then
begin
{ Transform R }
tmp := 1/(1+Value);
HalfXSize := Round(tmp*XRadius);
HalfYSize := Round(tmp*YRadius);
{ Circles are always right aligned }
With ParentChart.Canvas do
EllipseWithZ(CircleRect.Right-2*HalfXSize,CircleYCenter-HalfYSize,
CircleRect.Right,CircleYCenter+HalfYSize,Z);
if ShowLabel then { 5.02 (was if RLabels) }
DrawRCircleLabel(Value,CircleRect.Right-2*HalfXSize,CircleYCenter);
end;
end;
procedure TSmithSeries.DrawValue(ValueIndex: Integer);
var X : Integer;
Y : Integer;
begin
ZToPos(XValues.Value[ValueIndex],YValues.Value[ValueIndex],X,Y);
LinePrepareCanvas(ValueIndeX);
With ParentChart.Canvas do
if ValueIndex=FirstValueIndex then MoveTo3D(X,Y,StartZ) { <-- first point }
else
if (X<>OldX) or (Y<>OldY) then LineTo3D(X,Y,StartZ);
OldX:=X;
OldY:=Y;
end;
type TPointerAccess=class(TSeriesPointer);
TAxisAccess=class(TChartAxis);
procedure TSmithSeries.DrawAllValues;
var t : Integer;
tmpColor : TColor;
begin
inherited;
With FPointer do
if Visible then
for t:=FirstValueIndex to LastValueIndex do
begin
tmpColor:=ValueColor[t];
FPointer.PrepareCanvas(ParentChart.Canvas,tmpColor);
Draw(CalcXPos(t),CalcYPos(t),tmpColor,Style);
end;
end;
Procedure TSmithSeries.SetParentChart(Const Value:TCustomAxisPanel);
Begin
inherited;
if Assigned(FPointer) and Assigned(Value) then
Pointer.ParentChart:=Value;
if Assigned(ParentChart) and (csDesigning in ParentChart.ComponentState) then
ParentChart.View3D:=False;
end;
procedure TSmithSeries.DrawXCircle(Const Value:Double; Z: Integer; ShowLabel: boolean);
Procedure DrawXCircleLabel(XVal: Double; X,Y: Integer);
var Angle : Double;
tmpHeight : Integer;
tmpWidth : Integer;
tmpSt : String;
begin
if GetVertAxis.Visible and ShowLabel then { 5.02 }
With ParentChart.Canvas do
begin
AssignFont(CLabelsFont);
tmpHeight:=FontHeight;
tmpSt:=GetxCircleLabel(XVal);
Angle := PointToAngle(X,Y)*57.29577;
if Angle>=360 then Angle:=Angle-360;
begin
if (Angle=0) or (Angle=180) then Dec(Y,tmpHeight div 2)
else
if (Angle>0) and (Angle<180) then Dec(Y,tmpHeight);
if (Angle=90) or (Angle=270) then TextAlign:=ta_Center
else
if (Angle>90) and (Angle<270) then TextAlign:=ta_Right
else TextAlign:=ta_Left;
tmpWidth:=TextWidth('0') div 2;
if Angle=0 then Inc(x,tmpWidth) else
if Angle=180 then Dec(x,tmpWidth);
BackMode:=cbmTransparent;
TextOut3D(X,Y,EndZ,tmpSt);
end;
end;
end;
var X1,X2,X3,X4,
Y1,Y2,Y3,Y4 : Integer;
HalfXSize,
HalfYSize : Integer;
InvValue : Double;
begin
if Value <> 0 then
With ParentChart.Canvas do
begin
InvValue := 1/Value;
ZToPos(0,Value,X4,Y4); // Endpos
if ShowLabel then DrawXCircleLabel(Value,X4,Y4);
ZToPos(100,Value,X3,Y3); // Startpos
// ellipse bounding points
HalfXSize := Round(InvValue*XRadius);
HalfYSize := Round(InvValue*YRadius);
X1 := CircleRect.Right - HalfXSize;
X2 := CircleRect.Right + HalfXSize;
Y1 := CircleYCenter;
Y2 := Y1-2*HalfYSize;
if (not ParentChart.View3D) or ParentChart.View3DOptions.Orthogonal then
Arc(X1,Y1,X2,Y2,X4,Y4,X3,Y3);
ZToPos(0,-Value,X4,Y4); // Endpos
if (not ParentChart.View3D) or ParentChart.View3DOptions.Orthogonal then
Arc(X1,Y1,X2,Y1+2*HalfYSize,X3,Y3,X4,Y4);
if ShowLabel then DrawXCircleLabel(-Value,X4,Y4);
end
else
begin { special case then reactance is zero }
X1 := CircleRect.Left;
X2 := CircleRect.Right;
Y1 := CircleYCenter;
ParentChart.Canvas.LineWithZ(X1,Y1,X2,Y1,MiddleZ);
if ShowLabel then DrawXCircleLabel(0,X1,Y1);
end;
end;
Procedure TSmithSeries.AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False);
var t : Integer;
begin
for t:=0 to NumValues-1 do
AddPoint( 6.5*t/NumValues,(RandomValue(t)+3.8)/NumValues);
end;
{ NOTE : the assumption is all points are normalized by Z0 }
function TSmithSeries.AddPoint(Const Resist,React: Double; Const ALabel: String; AColor: TColor): Integer;
begin
result:=AddXY(Resist,React,ALabel,AColor);
end;
function TSmithSeries.CalcXPos(ValueIndex: Integer): Integer;
var DummyY : Integer;
begin
ZToPos(XValues.Value[ValueIndex],YValues.Value[ValueIndex],Result,DummyY);
end;
function TSmithSeries.CalcYPos(ValueIndex: Integer): Integer;
var DummyX : Integer;
begin
ZToPos(XValues.Value[ValueIndex],YValues.Value[ValueIndex],DummyX,Result);
end;
Function TSmithSeries.Clicked(X,Y:Integer):Integer;
var t : Integer;
begin
if Assigned(ParentChart) then ParentChart.Canvas.Calculate2DPosition(X,Y,StartZ);
result:=inherited Clicked(X,Y);
if (result=TeeNoPointClicked) and
(FirstValueIndex>-1) and (LastValueIndex>-1) then
if FPointer.Visible then
for t:=FirstValueIndex to LastValueIndex do
if (Abs(CalcXPos(t)-X)<FPointer.HorizSize) and
(Abs(CalcYPos(t)-Y)<FPointer.VertSize) then
begin
result:=t;
break;
end;
end;
procedure TSmithSeries.DoBeforeDrawValues;
procedure DrawXCircleGrid;
const DefaultX: Array [0..11] of Double =
(0,0.1,0.3,0.5,0.8,1,1.5,2,3,5,7,10);
var i : Integer;
begin
with ParentChart.Canvas do
begin
Brush.Style:=bsClear;
AssignVisiblePen(CCirclePen);
BackMode:=cbmTransparent;
end;
for i := 0 to High(DefaultX) do DrawXCircle(DefaultX[i],MiddleZ,CLabels);
end;
procedure DrawRCircleGrid;
const DefaultR: Array [0..6] of Double =
(0,0.2,0.5,1,2,5,10);
var i : Integer;
begin
with ParentChart.Canvas do
begin
Brush.Style:=bsClear;
AssignVisiblePen(RCirclePen);
BackMode:=cbmTransparent;
end;
for i := 0 to High(DefaultR) do DrawRCircle(DefaultR[i],MiddleZ,RLabels);
end;
procedure DrawAxis;
begin
if GetVertAxis.Visible then DrawXCircleGrid;
if GetHorizAxis.Visible then DrawRCircleGrid;
end;
Procedure DrawCircle;
var tmpX,
tmpY : Integer;
begin
With ParentChart.Canvas do
Begin
if not Self.HasBackColor then Brush.Style:=bsClear
else
begin
Brush.Style:=bsSolid;
Brush.Color:=CalcCircleBackColor;
end;
AssignVisiblePen(CirclePen);
tmpX:=CircleWidth div 2;
tmpY:=CircleHeight div 2;
EllipseWithZ( CircleXCenter-tmpX,CircleYCenter-tmpY,
CircleXCenter+tmpX,CircleYCenter+tmpY, EndZ);
if CircleGradient.Visible then
DrawCircleGradient;
end;
end;
var t : Integer;
tmp : Integer;
First : Boolean;
Begin
First:=False;
With ParentChart do
for t:=0 to SeriesCount-1 do
if (Series[t].Active) and (Series[t] is Self.ClassType) then
begin
if Series[t]=Self then
begin
if Not First then
begin
if CLabels then
begin
With ChartRect do
begin
tmp:=Canvas.FontHeight+2;
Inc(Top,tmp);
Dec(Bottom,tmp);
tmp:=Canvas.TextWidth('360');
Inc(Left,tmp);
Dec(Right,tmp);
end;
end;
end;
break;
end;
First:=True;
end;
inherited;
First:=False;
With ParentChart do
for t:=0 to SeriesCount-1 do
if (Series[t].Active) and (Series[t] is Self.ClassType) then
begin
if Series[t]=Self then
begin
if not First then
begin
DrawCircle;
if Axes.Visible and Axes.Behind then
DrawAxis;
end;
break;
end;
First:=True;
end;
end;
class function TSmithSeries.GetEditorClass: String;
begin
result:='TSmithSeriesEdit';
end;
procedure TSmithSeries.SetCirclePen(Const Value: TChartPen);
begin
FCirclePen.Assign(Value);
end;
function TSmithSeries.GetXCircleLabel(Const Reactance: Double): String;
begin
Result:=FloatToStr(Reactance)+FImagSymbol;
end;
function TSmithSeries.GetCLabels: Boolean;
begin
if Assigned(GetVertAxis) then
result:=GetVertAxis.Labels
else
result:=True;
end;
function TSmithSeries.GetCPen: TChartPen;
begin
if Assigned(GetVertAxis) then
result:=GetVertAxis.Grid
else
result:=Pen; // workaround
end;
function TSmithSeries.GetRLabels: Boolean;
begin
if Assigned(GetHorizAxis) then
result:=GetHorizAxis.Labels
else
result:=True;
end;
function TSmithSeries.GetRPen: TChartPen;
begin
if Assigned(GetHorizAxis) then
result:=GetHorizAxis.Grid
else
result:=Pen; // workaround
end;
function TSmithSeries.GetCLabelsFont: TTeeFont;
begin
if Assigned(GetVertAxis) then
result:=GetVertAxis.LabelsFont
else
result:=Marks.Font; // workaround
end;
function TSmithSeries.GetRLabelsFont: TTeeFont;
begin
if Assigned(GetHorizAxis) then
result:=GetHorizAxis.LabelsFont
else
result:=Marks.Font; // workaround
end;
procedure TSmithSeries.SetCLabelsFont(const Value: TTeeFont);
begin
if Assigned(GetVertAxis) then
GetVertAxis.LabelsFont:=Value
end;
procedure TSmithSeries.SetRLabelsFont(const Value: TTeeFont);
begin
if Assigned(GetHorizAxis) then
GetHorizAxis.LabelsFont:=Value;
end;
procedure TSmithSeries.SetImagSymbol(const Value: String);
begin
SetStringProperty(FImagSymbol,Value);
end;
procedure TSmithSeries.PrepareForGallery(IsEnabled: Boolean); { 5.02 }
begin
inherited;
With ParentChart do
begin
Chart3DPercent:=5;
RightAxis.Labels:=False;
TopAxis.Labels:=False;
With View3DOptions do
begin
Orthogonal:=False;
Elevation:=360;
Zoom:=90;
end;
end;
end;
initialization
RegisterTeeSeries(TSmithSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GallerySmith,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended,2);
finalization
UnRegisterTeeSeries([TSmithSeries]);
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.DSLoginDlg;
{$P+,H+,X+}
interface
uses Datasnap.DSClientRest;
function LoginDialog(ASender: TObject; var ALoginProperties: TDSRestLoginProperties;
ATestConnectionMethod: TTestConnectionMethod): Boolean;
implementation
uses System.Classes, System.SysUtils;
function LoginDialog(ASender: TObject; var ALoginProperties: TDSRestLoginProperties; ATestConnectionMethod: TTestConnectionMethod): Boolean;
var
LUserName, LPassword: string;
LTestConnectionMethod: TTestConnectionMethod;
begin
LTestConnectionMethod := ATestConnectionMethod;
Result := TLoginCredentialService.GetLoginCredentials('',
function(const Username, Password, Domain: string): Boolean
begin
Result := True;
LUserName := Username;
LPassword := Password;
if Assigned(LTestConnectionMethod) then
LTestConnectionMethod;
end);
if Result then
begin
ALoginProperties.UserName := LUserName;
ALoginProperties.Password := LPassword;
end;
end;
initialization
if not Assigned(Datasnap.DSClientRest.DSRestLoginDialogProc) then
Datasnap.DSClientRest.DSRestLoginDialogProc := LoginDialog;
end.
|
unit NewButton;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Math, ExtCtrls ;
type
TBtnState =(Leave,Enter,Down,Up);
TNewButton = class(TGraphicControl)
private
FStep:integer;
FAnimateStep:integer;
FR,FG,FB,FR1,FG1,FB1,FR2,FG2,FB2:integer;
FBtnState:TBtnState;
FGlyph: TBitmap;
FCaption: String;
FColor:TColor;
FShowCaption: Boolean;
FModalResult: TModalResult;
FInterval:integer;
FFont:TFont;
FTimer:ttimer;
procedure SetInterval(value:integer);
procedure SetAnimateStep(Value:integer);
procedure SetColor(Value:TColor);
procedure TimerProc(Sender: TObject);
procedure SetGlyph(Value: TBitMap);
procedure SetCaption(Value:String);
procedure Resize(Sender: TObject);
procedure SetShowCaption(Value:Boolean);
procedure DrawCaption;
procedure SetFont(Value:TFont);
procedure DrawBtn(ACanvas:tcanvas);
protected
procedure paint;override;
procedure MouseEnter(var Msg: TMessage); message CM_MOUSEENTER;
procedure MouseLeave(var Msg: TMessage); message CM_MOUSELEAVE;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Glyph:TBitMap read FGlyph write SetGlyph;
property ModalResult: TModalResult read FModalResult write FModalResult default 0;
property Caption: String read FCaption write SetCaption;
property ShowCaption:Boolean read FShowCaption write SetShowCaption;
property Font:TFont read FFont write SetFont;
property AnimateRate:integer read Finterval write SetInterval;
property AnimateStep:integer read FAnimateStep write SetAnimateStep;
property Action;
property Anchors;
property Color:TColor read FColor write SetColor;
property Enabled;
property Hint;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Visible;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('WDN Soft', [TNewButton]);
end;
procedure TNewButton.DrawBtn(ACanvas:tcanvas);
var i,j:integer;
begin
acanvas.Brush.Style:=bssolid;
acanvas.Brush.Color:=clwhite;
acanvas.FillRect(acanvas.ClipRect );
for i:= 0 to height div 3 do
begin
acanvas.Brush.Color:=rgb(fr+(fr1-fr)*i*3 div height,
fg+(fg1-fg)*i*3 div height,
fb+(fb1-fb)*i*3 div height );
acanvas.FillRect(rect(0,i,width,i+1));
end;
for i:= height div 3 to height do
begin
acanvas.Brush.Color:=rgb(fr1+(fr2-fr1)*(i-height div 3)*3 div 2 div height,
fg1+(fg2-fg1)*(i-height div 3)*3 div 2 div height,
fb1+(fb2-fb1)*(i-height div 3)*3 div 2 div height );
acanvas.FillRect(rect(0,i,width,i+1));
end;
end;
constructor TNewButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 32;
Height := 32;
finterval:=50;
fanimatestep:=10;
fcolor:=clsilver;
setcolor(fcolor);
FGlyph:=tbitmap.Create;
FGlyph.Transparent:=true;
OnResize:=Resize;
ftimer:=ttimer.Create(nil);
ftimer.Interval:=finterval;
ftimer.OnTimer:=timerproc;
ftimer.Enabled:=false;
With Canvas.Font do
begin
Charset:=GB2312_CHARSET;
Color:= clWindowText;
Height:=-12;
Name:='����';
Pitch:=fpDefault;
Size:=9;
end;
FFont:=Canvas.Font;
end;
destructor TNewButton.Destroy;
begin
ftimer.Enabled:=false;
ftimer.Free;
FGlyph.Free;
inherited Destroy;
end;
procedure TNewButton.TimerProc;
var r1,g1,b1,r2,g2,b2:integer;
begin
if (fstep>=fanimatestep) and (fbtnstate=enter) then
begin
ftimer.Enabled:=false;
exit;
end;
if (fstep<=0 ) and (fbtnstate=leave) then
begin
ftimer.Enabled:=false;
exit;
end;
if fbtnstate=enter then
inc(fstep)
else if fbtnstate=leave then
dec(fstep);
r1:=127+127*fstep div fanimatestep;
g1:=127+127*fstep div fanimatestep;
b1:=127+127*fstep div fanimatestep;
r2:=127-127*fstep div fanimatestep;
g2:=127-127*fstep div fanimatestep;
b2:=127-127*fstep div fanimatestep;
canvas.Pen.Mode:=pmcopy;
canvas.Pen.Color:=rgb(r1,g1,b1);
canvas.MoveTo(0,height-1);
canvas.LineTo(0,0);
canvas.LineTo(width-1,0);
canvas.LineTo(width-2,1);
canvas.LineTo(1,1);
canvas.LineTo(1,height-2);
canvas.Pen.Color:=rgb(r2,g2,b2);
canvas.MoveTo(3,height-2);
canvas.LineTo(width-2,height-2);
canvas.LineTo(width-2,2);
canvas.LineTo(width-1,1);
canvas.LineTo(width-1,height-1);
canvas.LineTo(0,height-1);
end;
procedure TNewButton.paint;
const
XorColor = $00FFD8CE;
var x,y:integer;
r:trect;
bmp:tbitmap;
begin
r.Left:= (width-fglyph.Width) div 2;
r.Top:= (height-fglyph.Height)div 2;
r.Right:=r.Left +fglyph.Width;
r.Bottom:=r.Top +fglyph.Height;
with Canvas do
begin
if not fglyph.Empty then
begin
x:=(width-fglyph.Width ) div 2;
y:=(height-fglyph.Height ) div 2;
end;
if not Enabled then
begin
canvas.Brush.Color:=fcolor;
canvas.FillRect(canvas.ClipRect);
bmp:=tbitmap.Create;
bmp.Transparent:=true;
bmp.Width:=fglyph.Width;
bmp.Height:=fglyph.Height;
bmp.canvas.CopyMode:= cmnotsrccopy;
bmp.Canvas.CopyRect(bmp.Canvas.ClipRect,fglyph.Canvas,fglyph.Canvas.ClipRect );
if not fglyph.Empty then
canvas.Draw(r.Left,r.Top,bmp);
bmp.Free;
end
else
case fbtnstate of
enter:begin
drawbtn(canvas);
fglyph.Transparent:=true;
canvas.Draw(r.Left,r.Top,fglyph);
canvas.Brush.Color:=rgb(127,127,127);
canvas.FrameRect(canvas.ClipRect );
with canvas.ClipRect do
canvas.FrameRect(rect(left+1,top+1,right-1,bottom-1));
end;
leave:begin
drawbtn(canvas);
fglyph.Transparent:=true;
canvas.Draw(r.Left,r.Top,fglyph);
canvas.Brush.Color:=rgb(127,127,127);
canvas.FrameRect(canvas.ClipRect );
with canvas.ClipRect do
canvas.FrameRect(rect(left+1,top+1,right-1,bottom-1));
end;
down: begin
drawbtn(canvas);
fglyph.Transparent:=true;
canvas.Draw(r.Left+1,r.Top+1,fglyph);
canvas.Pen.Color:=clblack;
canvas.Pen.Mode:=pmcopy;
canvas.MoveTo(0,height-1);
canvas.LineTo(0,0);
canvas.LineTo(width-1,0);
canvas.LineTo(width-2,1);
canvas.LineTo(1,1);
canvas.LineTo(1,height-2);
canvas.Pen.Color:=clwhite;
canvas.MoveTo(3,height-2);
canvas.LineTo(width-2,height-2);
canvas.LineTo(width-2,2);
canvas.LineTo(width-1,1);
canvas.LineTo(width-1,height-1);
canvas.LineTo(0,height-1);
end;
up: begin
drawbtn(canvas);
fglyph.Transparent:=true;
canvas.Draw(r.Left,r.Top,fglyph);
canvas.Pen.Color:=clwhite;
canvas.Pen.Mode:=pmcopy;
canvas.MoveTo(0,height-1);
canvas.LineTo(0,0);
canvas.LineTo(width-1,0);
canvas.LineTo(width-2,1);
canvas.LineTo(1,1);
canvas.LineTo(1,height-2);
canvas.Pen.Color:=clblack;
canvas.MoveTo(3,height-2);
canvas.LineTo(width-2,height-2);
canvas.LineTo(width-2,2);
canvas.LineTo(width-1,1);
canvas.LineTo(width-1,height-1);
canvas.LineTo(0,height-1);
end;
end;
DrawCaption;
end;
end;
procedure TNewButton.SetColor(Value:TColor);
begin
fcolor:=value;
fr:= getrvalue(colortorgb(value) );
fg:= getgvalue(colortorgb(value) );
fb:= getbvalue(colortorgb(value) );
fr1:= fr+(255-fr)*2 div 3 ;
fg1:= fg+(255-fg)*2 div 3 ;
fb1:= fb+(255-fb)*2 div 3 ;
fr2:= fr div 2;
fg2:= fg div 2;
fb2:= fb div 2;
invalidate;
end;
procedure TNewButton.SetAnimateStep(Value:integer);
begin
if fanimatestep<>value then
begin
fanimatestep:=value;
end;
end;
procedure TNewButton.SetGlyph(Value:TBitMap);
begin
FGlyph.Assign(Value);
Invalidate;
end;
procedure TNewButton.SetInterval(Value:integer);
begin
FInterval:=value;
ftimer.Interval:=value;
end;
procedure TNewButton.SetCaption(Value:String);
begin
FCaption:=Value;
Invalidate;
end;
procedure TNewButton.SetShowCaption(Value:Boolean);
begin
FShowCaption:=Value;
Invalidate;
end;
procedure TNewButton.SetFont(Value:TFont);
begin
FFont:=Value;
Canvas.Font:=Value;
Invalidate;
end;
procedure TNewButton.Resize(Sender:TObject);
begin
Invalidate;
end;
procedure TNewButton.DrawCaption;
var
x,y:integer;
begin
if FShowCaption then
begin
if fbtnstate =down then
with Canvas do
begin
Brush.Style := bsClear;
x:=Round((Width-TextWidth(Caption))/2);
y:=Round((Height-TextHeight(Caption))/2);
TextOut(x+1,y+1,Caption);
end
else
with Canvas do
begin
Brush.Style := bsClear;
x:=Round((Width-TextWidth(Caption))/2);
y:=Round((Height-TextHeight(Caption))/2);
TextOut(x,y,Caption);
end;
end;
end;
procedure TNewButton.MouseEnter(var Msg:TMessage);
begin
if Enabled then
begin
fbtnstate:=enter;
ftimer.Enabled:=true;
//invalidate;
end;
end;
procedure TNewButton.MouseLeave(var Msg:TMessage);
begin
if Enabled then
begin
fbtnstate:=leave;
ftimer.Enabled:=true;
//Invalidate;
end;
end;
procedure TNewButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if Enabled and ( button = mbLeft) then
begin
fbtnstate:=down;
ftimer.Enabled:=false;
paint;
//invalidate;
end;
inherited;
end;
procedure TNewButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
if Enabled and ( button = mbLeft) then
begin
fbtnstate:= up;
ftimer.Enabled:=false;
paint;
//invalidate;
end;
inherited;
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Компоненты медиа-преобразования }
{ }
{ <Область> Мультимедиа }
{ }
{ <Задача> Преобразователь медиа-потока в формате BMP. Стабилизирует }
{ дрожание кадров }
{ Реализация. }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 21.01.2011 }
{ }
{ <Примечание> Отсутствует }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaProcessing.Stabilizer.RGB.Impl;
interface
uses SysUtils,Windows,Classes, Generics.Collections, SyncObjs,
MediaProcessing.Definitions,MediaProcessing.Global,MediaProcessing.Stabilizer.RGB,
CMSA,Collections.Aggregates;
type
//Собственно реализация медиа-процессора
TMediaProcessor_Stabilizer_Rgb_Impl =class (TMediaProcessor_Stabilizer_Rgb,IMediaProcessorImpl)
private
FResultBitmapDIB: TBytes;
FDF : TFrameDispFinder;
FXMovementStat: TAggregate;
FYMovementStat: TAggregate;
protected
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses Math,BitPlane,uBaseClasses;
{ TMediaProcessor_Stabilizer_Rgb_Impl }
constructor TMediaProcessor_Stabilizer_Rgb_Impl.Create;
begin
inherited;
FDF:=TFrameDispFinder.Create(0,0,100,100,12.5,7.5,FDF);
end;
destructor TMediaProcessor_Stabilizer_Rgb_Impl.Destroy;
begin
inherited;
FResultBitmapDIB:=nil;
FreeAndNil(FXMovementStat);
FreeAndNil(FYMovementStat);
FreeAndNil(FDF);
end;
procedure TMediaProcessor_Stabilizer_Rgb_Impl.LoadCustomProperties(
const aReader: IPropertiesReader);
begin
inherited;
FreeAndNil(FXMovementStat);
FreeAndNil(FYMovementStat);
if FDetectMovements then
begin
FXMovementStat:=TAggregate.Create(FDetectMovementsPeriod);
FYMovementStat:=TAggregate.Create(FDetectMovementsPeriod);
end;
end;
procedure TMediaProcessor_Stabilizer_Rgb_Impl.Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal);
var
// aStartTicks: cardinal;
aRes: CMSA_RESULT;
aBih: TBitmapInfoHeader;
aX,aY: single;
aMX,aMY: double;
aPlaneS,aPlaneD: TBitPlaneDesc;
begin
// aStartTicks:=GetTickCount;
TArgumentValidation.NotNil(aInData);
Assert(aInFormat.biMediaType=mtVideo);
Assert(aInFormat.biStreamType=stRGB);
aOutData:=nil;
aOutDataSize:=0;
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat:=aInFormat;
if (aInFormat.VideoBitCount<>24) then
begin
SetLastError(Format('Формат RGB должен имет глубину цвета 24 бита. Фактичесий формат - %d бит',[aInFormat.VideoBitCount]));
aOutFormat.Clear;
exit;
end;
aBih:=aInFormat.ToBitmapInfoHeader(aInDataSize);
aRes:=FDF.Process(aBih, aInData, aX,aY);
if aRes<>CMSARES_SUCCESS then
begin
SetLastError(CmsaGetErrorMessage(aRes));
exit;
end;
if (FXMovementStat<>nil) and (FXMovementStat.Period>0) then
begin
FXMovementStat.Add(aX);
if FXMovementStat.Count=FXMovementStat.Period then
begin
aMX:=FXMovementStat.GetAverage;
aX:=aX-aMX;
end;
end;
if (FYMovementStat<>nil) and (FYMovementStat.Period>0) then
begin
FYMovementStat.Add(aY);
if FYMovementStat.Count=FYMovementStat.Period then
begin
aMY:=FYMovementStat.GetAverage;
aY:=aY-aMY;
end;
end;
if cardinal(Length(FResultBitmapDIB))<aInDataSize then
begin
FResultBitmapDIB:=nil;
SetLength(FResultBitmapDIB,aInDataSize);
end;
aOutData:=FResultBitmapDIB;
aOutDataSize:=aInDataSize;
aOutFormat:=aInFormat;
//Вставляем картинку
aPlaneS.Init(aInData,aInDataSize,aInFormat.VideoWidth,aInFormat.VideoHeight,aInFormat.VideoBitCount);
aPlaneD.Init(aOutData,aOutDataSize,aOutFormat.VideoWidth,aOutFormat.VideoHeight,aOutFormat.VideoBitCount);
aPlaneS.CopyToBitPlane(aPlaneD,Round(aX),Round(aY),not FBuildImageOutOfBorders);
//CopyRGB(aPlaneS,aPlaneD,Round(0),Round(0));
end;
initialization
MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_Stabilizer_Rgb_Impl);
end.
|
unit uEngineResource;
{$ZEROBASEDSTRINGS OFF}
{.$DEFINE FORTEST}
// ***************************************
// 管理所有的资源文件(所有的图片资源,JSON文档信息)
// 任何一个Sprite都可以调用这个Unit来获取图片资源....
interface
uses
System.SysUtils,System.Classes,System.JSON,System.UITypes,
FMX.Graphics, FMX.Dialogs,
zipPackage;
Type
TEngineResManager = class
private
FAllSourceData : TZipRecord;
FConfigText : String;
FTmpData : TMemoryStream; // 定义一个Stream, 方便后面调用资源包里面的文件...
FJSONObject : TJSONObject; // 定义一个全局的JSONObject, 当场景不变化的时候, 可以一直使用...
public
Constructor Create;
Destructor Destroy;override;
procedure LoadConfig(ASrcPath:String);
procedure UpdateConfig(AConfigIndex : String);
procedure LoadResource(var OutBmp : TBitmap;ABmpName:String);overload;
procedure LoadResource(var OutList : TStringList; ATxtName:String);overload;
function GetJSONValue(AKey : String): String;
Function GetJSONArray(AKey : String) : TJSONArray;
Function ReadAllSprite(Var inStr : String) : Boolean; // 读取所有的精灵....
property ConfigText : String read FConfigText write FConfigText;
end;
const CONFIG_INDEX = 'config.txt';
// var
// G_EngineResManager : TEngineResManager;
implementation
uses
uConfiguration;
{ TEngineResManager }
constructor TEngineResManager.Create;
begin
FAllSourceData := TZipRecord.Create;
FTmpData := TMemoryStream.Create;
end;
destructor TEngineResManager.Destroy;
begin
FAllSourceData.DisposeOf;
FTmpData.DisposeOf;
if FJSONObject <> nil then
begin
FJSONObject.DisposeOf;
FJSONObject := nil;
end;
inherited;
end;
function TEngineResManager.GetJSONValue(AKey: String): String;
var
//JSONObject : TJSonObject;
S : String;
tmpValue : TJSONValue;
begin
S := ConfigText;
result := '';
if S = '' then
exit;
try
tmpValue := FJSONObject.Values[AKey];
if tmpValue <> nil then
begin
result := tmpValue.Value;
end;
finally
end;
end;
Function TEngineResManager.GetJSONArray(AKey: string) : TJSONArray;
begin
result := TJSONArray(FJSONObject.GetValue(AKey));
end;
Function TEngineResManager.ReadAllSprite(Var inStr : String) : Boolean;
var
tmpValue : TJSONValue;
tmpArray : TJSONArray;
i : Integer;
S : String;
begin
tmpArray := TJSONArray(FJSONObject.GetValue('Resource'));
for i := 0 to tmpArray.Size - 1 do
begin
S := (tmpArray.Get(I) as TJSONObject).ToString;
end;
// tmpValue := FJSONObject.Values['Resource'];
// if tmpValue <> nil then
// begin
//
// end;
end;
procedure TEngineResManager.UpdateConfig(AConfigIndex: String);
var
LList : TStringList;
begin
if not Assigned(FAllSourceData) then
raise Exception.Create('FAllSourceData is not assigned');
try
LList := TStringList.Create;
FTmpData.Clear;
FAllSourceData.LoadFileFromPackage(AConfigIndex, FTmpData);
FTmpData.Seek(LongInt(0),0);
LList.LoadFromStream(FTmpData);
FConfigText := LList.Text;
// 下面这段代码是测试用的...
{$IF defined(FORTEST) and defined(MSWINDOWS)}
LList.LoadFromFile(RES_PATH+AConfigIndex); // 修改4
FConfigText := LList.Text;
{$ENDIF}
finally
LList.DisposeOf;
end;
if FJSONObject <> nil then
FJSONObject.DisposeOf;
FJSONObject := TJSONObject.ParseJSONValue(FConfigText) as TJSonObject;
end;
procedure TEngineResManager.LoadConfig(ASrcPath:String);
begin
// 开始读取所有的资源文件....
if FileExists(ASrcPath) then
begin
try
UpPackage(ASrcPath, FAllSourceData);
finally
end;
end else
begin
ShowMessage('Error @TEngineResManager.LoadConfig : File not Exist');
end;
end;
procedure TEngineResManager.LoadResource(var OutList: TStringList;
ATxtName: String);
begin
if FAllSourceData.LoadFileFromPackage(ATxtName,FTmpData) then
begin
if Not Assigned(OutList) then
OutList := TStringList.Create else
OutList.Clear;
FTmpData.Seek(LongInt(0),soFromBeginning);
OutList.LoadFromStream(FTmpData);
end;
end;
procedure TEngineResManager.LoadResource(var OutBmp: TBitmap; ABmpName: String);
var
LTmp : TBitmap;
begin
if FAllSourceData.LoadFileFromPackage(ABmpName, FTmpData) then
begin
try
LTmp := TBitmap.Create;
LTmp.LoadFromStream(FTmpData);
OutBmp.Assign(LTmp);
finally
LTmp.DisposeOf;
end;
end else
begin
if FileExists(ABmpName) then
begin
try
LTmp := TBitmap.Create;
LTmp.LoadFromFile(ABmpName);
OutBmp.Assign(LTmp);
finally
LTmp.DisposeOf;
end;
end;
end;
end;
Initialization
// G_EngineResManager := TEngineResManager.Create;
Finalization
// G_EngineResManager.DisposeOf;
end.
|
{ 25/05/2007 10:35:31 (GMT+1:00) > [Akadamia] checked in }
{ 25/05/2007 10:34:36 (GMT+1:00) > [Akadamia] checked out /}
{ 14/02/2007 08:29:56 (GMT+0:00) > [Akadamia] checked in }
{ 14/02/2007 08:29:41 (GMT+0:00) > [Akadamia] checked out /}
{ 12/02/2007 10:17:14 (GMT+0:00) > [Akadamia] checked in }
{ 08/02/2007 14:07:44 (GMT+0:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: JIU
Author: ken.adam
Date: 15-Jan-2007
Purpose: Translation of Joystick Input example to Delphi
Use the "z" key to step through the events sent by the Joystick
including X,Y,Z axes, Slider and Hat switch
History:
-----------------------------------------------------------------------------}
unit JIU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
type
// Use enumerated types to create unique IDs as required
TGroupId = (Group0);
TInputId = (INPUT_Z,
INPUT_SLIDER,
INPUT_XAXIS,
INPUT_YAXIS,
INPUT_RZAXIS,
INPUT_HAT);
TEventID = (EVENT_Z,
EVENT_SLIDER,
EVENT_XAXIS,
EVENT_YAXIS,
EVENT_RZAXIS,
EVENT_HAT);
// The form
TJoystickInputForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Memo: TMemo;
StartPoll: TAction;
FileExit: TFileExit;
StartEvent: TAction;
procedure StartPollExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SimConnectMessage(var Message: TMessage); message
WM_USER_SIMCONNECT;
procedure StartEventExecute(Sender: TObject);
private
{ Private declarations }
RxCount: integer; // Count of Rx messages
Quit: boolean; // True when signalled to quit
hSimConnect: THandle; // Handle for the SimConection
Current: integer;
public
{ Public declarations }
procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer);
end;
var
JoystickInputForm: TJoystickInputForm;
implementation
resourcestring
StrRx6d = 'Rx: %6d';
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: MyDispatchProc
Wraps the call to the form method in a simple StdCall procedure
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer); stdcall;
begin
JoystickInputForm.DispatchHandler(pData, cbData, pContext);
end;
{-----------------------------------------------------------------------------
Procedure: DispatchHandler
Handle the Dispatched callbacks in a method of the form. Note that this is
used by both methods of handling the interface.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure TJoystickInputForm.DispatchHandler(pData: PSimConnectRecv; cbData:
DWORD;
pContext: Pointer);
var
hr: HRESULT;
Evt: PSimconnectRecvEvent;
OpenData: PSimConnectRecvOpen;
begin
// Maintain a display of the message count
Inc(RxCount);
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
// Only keep the last 200 lines in the Memo
while Memo.Lines.Count > 200 do
Memo.Lines.Delete(0);
// Handle the various types of message
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_OPEN:
begin
StatusBar.Panels[0].Text := 'Opened';
OpenData := PSimConnectRecvOpen(pData);
with OpenData^ do
begin
Memo.Lines.Add('');
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName,
dwApplicationVersionMajor, dwApplicationVersionMinor,
dwApplicationBuildMajor, dwApplicationBuildMinor]));
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect',
dwSimConnectVersionMajor, dwSimConnectVersionMinor,
dwSimConnectBuildMajor, dwSimConnectBuildMinor]));
Memo.Lines.Add('');
end;
end;
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventId(evt^.uEventID) of
EVENT_SLIDER:
Memo.Lines.Add(Format('Slider value:%d', [evt^.dwData]));
EVENT_XAXIS:
Memo.Lines.Add(Format('X Axis value:%d', [evt^.dwData]));
EVENT_YAXIS:
Memo.Lines.Add(Format('Y Axis value:%d', [evt^.dwData]));
EVENT_RZAXIS:
Memo.Lines.Add(Format('Rotate Z axis value:%d', [evt^.dwData]));
EVENT_HAT:
Memo.Lines.Add(Format('Hat value:%d', [evt^.dwData]));
EVENT_Z:
begin
Inc(Current);
if current = 6 then
current := 1;
case current of
1:
begin
Memo.Lines.Add('SLIDER is active');
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_SLIDER), Ord(SIMCONNECT_STATE_ON));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_XAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_YAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_RZAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_HAT),
Ord(SIMCONNECT_STATE_OFF));
end;
2:
begin
Memo.Lines.Add('X AXIS is active');
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_SLIDER), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_XAXIS), Ord(SIMCONNECT_STATE_ON));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_YAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_RZAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_HAT),
Ord(SIMCONNECT_STATE_OFF));
;
end;
3:
begin
Memo.Lines.Add('Y AXIS is active');
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_SLIDER), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_XAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_YAXIS), Ord(SIMCONNECT_STATE_ON));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_RZAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_HAT),
Ord(SIMCONNECT_STATE_OFF));
end;
4:
begin
Memo.Lines.Add('Z ROTATION is active');
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_SLIDER), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_XAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_YAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_RZAXIS), Ord(SIMCONNECT_STATE_ON));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_HAT),
Ord(SIMCONNECT_STATE_OFF));
end;
5:
begin
Memo.Lines.Add('HAT is active');
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_SLIDER), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_XAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_YAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_RZAXIS), Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect,
Ord(INPUT_HAT),
Ord(SIMCONNECT_STATE_ON));
end;
end;
end;
end;
end;
SIMCONNECT_RECV_ID_QUIT:
begin
Quit := True;
StatusBar.Panels[0].Text := 'FS X Quit';
end
else
Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID]));
end;
end;
{-----------------------------------------------------------------------------
Procedure: FormCloseQuery
Ensure that we can signal "Quit" to the busy wait loop
Author: ken.adam
Date: 11-Jan-2007
Arguments: Sender: TObject var CanClose: Boolean
Result: None
-----------------------------------------------------------------------------}
procedure TJoystickInputForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Quit := True;
CanClose := True;
end;
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TJoystickInputForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
begin
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
StartPoll.Enabled := False;
StartEvent.Enabled := False;
end;
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
Current := 0;
StatusBar.Panels[1].Text := Format(StrRx6d, [RxCount]);
end;
{-----------------------------------------------------------------------------
Procedure: SimConnectMessage
This uses CallDispatch, but could probably avoid the callback and use
SimConnect_GetNextDispatch instead.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
var Message: TMessage
-----------------------------------------------------------------------------}
procedure TJoystickInputForm.SimConnectMessage(var Message: TMessage);
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
end;
{-----------------------------------------------------------------------------
Procedure: StartEventExecute
Opens the connection for Event driven handling. If successful sets up the data
requests and hooks the system event "SimStart".
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TJoystickInputForm.StartEventExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', Handle,
WM_USER_SIMCONNECT, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Set up some private events
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_Z));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_SLIDER));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_XAXIS));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_YAXIS));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_RZAXIS));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_HAT));
// Add all the private events to a notifcation group
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_Z));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_SLIDER));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_XAXIS));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_YAXIS));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_RZAXIS));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_HAT));
// Set a high priority for the group
hr := SimConnect_SetNotificationGroupPriority(hSimConnect, Ord(GROUP0),
SIMCONNECT_GROUP_PRIORITY_HIGHEST);
// Map input events to the private client events
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_Z), 'z',
Ord(EVENT_Z));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_SLIDER),
'joystick:0:slider', Ord(EVENT_SLIDER));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_XAXIS),
'joystick:0:XAxis', Ord(EVENT_XAXIS));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_YAXIS),
'joystick:0:YAxis', Ord(EVENT_YAXIS));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_RZAXIS),
'joystick:0:RzAxis', Ord(EVENT_RZAXIS));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_HAT),
'joystick:0:POV', Ord(EVENT_HAT));
// Turn on the Z key
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_Z),
Ord(SIMCONNECT_STATE_ON));
hr := SimConnect_SetInputGroupPriority(hSimConnect, Ord(INPUT_Z),
SIMCONNECT_GROUP_PRIORITY_HIGHEST);
// Turn all the joystick events off
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_SLIDER),
Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_XAXIS),
Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_YAXIS),
Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_RZAXIS),
Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_HAT),
Ord(SIMCONNECT_STATE_OFF));
StartEvent.Enabled := False;
StartPoll.Enabled := False;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartPollExecute
Opens the connection for Polled access. If successful sets up the data
requests and hooks the system event "SimStart", and then loops indefinitely
on CallDispatch.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TJoystickInputForm.StartPollExecute(Sender: TObject);
var
hr: HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Set Data', 0, 0, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Set up some private events
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_Z));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_SLIDER));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_XAXIS));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_YAXIS));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_RZAXIS));
hr := SimConnect_MapClientEventToSimEvent(hSimConnect, Ord(EVENT_HAT));
// Add all the private events to a notifcation group
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_Z));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_SLIDER));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_XAXIS));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_YAXIS));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_RZAXIS));
hr := SimConnect_AddClientEventToNotificationGroup(hSimConnect, Ord(GROUP0),
Ord(EVENT_HAT));
// Set a high priority for the group
hr := SimConnect_SetNotificationGroupPriority(hSimConnect, Ord(GROUP0),
SIMCONNECT_GROUP_PRIORITY_HIGHEST);
// Map input events to the private client events
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_Z), 'z',
Ord(EVENT_Z));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_SLIDER),
'joystick:0:slider', Ord(EVENT_SLIDER));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_XAXIS),
'joystick:0:XAxis', Ord(EVENT_XAXIS));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_YAXIS),
'joystick:0:YAxis', Ord(EVENT_YAXIS));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_RZAXIS),
'joystick:0:RzAxis', Ord(EVENT_RZAXIS));
hr := SimConnect_MapInputEventToClientEvent(hSimConnect, Ord(INPUT_HAT),
'joystick:0:POV', Ord(EVENT_HAT));
// Turn on the Z key
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_Z),
Ord(SIMCONNECT_STATE_ON));
hr := SimConnect_SetInputGroupPriority(hSimConnect, Ord(INPUT_Z),
SIMCONNECT_GROUP_PRIORITY_HIGHEST);
// Turn all the joystick events off
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_SLIDER),
Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_XAXIS),
Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_YAXIS),
Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_RZAXIS),
Ord(SIMCONNECT_STATE_OFF));
hr := SimConnect_SetInputGroupState(hSimConnect, Ord(INPUT_HAT),
Ord(SIMCONNECT_STATE_OFF));
StartEvent.Enabled := False;
StartPoll.Enabled := False;
while not Quit do
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
Application.ProcessMessages;
Sleep(1);
end;
hr := SimConnect_Close(hSimConnect);
end;
end;
end.
|
unit UntDmREST;
interface
uses
System.SysUtils,
System.Classes,
System.JSON,
System.JSON.Readers,
System.NetEncoding,
System.JSON.Types,
System.Types,
IPPeerClient,
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Param,
FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf,
FireDAC.DApt.Intf,
FireDAC.Comp.DataSet,
FireDAC.Comp.Client,
Data.DB,
Data.Bind.Components,
Data.Bind.ObjectScope,
REST.Response.Adapter,
REST.Client,
REST.Types,
Constantes,
SmartPoint;
type
TDmREST = class(TDataModule)
rstClient: TRESTClient;
rstRequest: TRESTRequest;
rstResponse: TRESTResponse;
rstAdapter: TRESTResponseDataSetAdapter;
MemREST: TFDMemTable;
private
{ Private declarations }
procedure ClearToDefaults;
function Execute(const AServerMethod, AColecao: string; AElementos: TStrings): Boolean;overload;
function Execute(const AServerMethod, AColecao: string; AElementos: TStrings; AContent: TJSONArray;
ARequestMethod: TRESTRequestMethod): Boolean;overload;
public
{ Public declarations }
function Estabelecimentos(const AFiltro: string = ''; AValue: Integer = 0): Boolean;
function Categorias(const AEstabelecimento: Integer): Boolean;
function Cardapios(const ACategoria, AEstabelecimento: Integer): Boolean;
function Perfil(const AUsuario: string): Boolean;
function AtualizarPerfil(const APerfil: TJSONArray; const AID: Integer): Boolean;
function RegistrarUsuario(const AConteudo: TJSONArray): Boolean;
function Login(const AUsuario, ASenha: string): Boolean;
function EnviarPedido(const AConteudo: TJSONArray): Boolean;
function AtualizarStatusLocal (const AID_Usuario: Integer): Boolean;
function EnviarAlteracaoPedido(const AConteudo: TJSONArray; AID_Usuario, AID_PEDIDO_MOBILE: Integer): Boolean;
end;
var
DmREST: TDmREST;
implementation
uses
{$IFDEF WEB}
ServerController,
{$ENDIF}
UntDM;
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
{ TDmREST }
function TDmREST.Execute(const AServerMethod, AColecao: string;
AElementos: TStrings): Boolean;
var
I : Integer;
LParams : string;
begin
Result := False;
try
//Reset de componentes
ClearToDefaults;
MemREST.Active := False;
//RESTClient
rstClient.BaseURL := Format('%s%s', [C_BASEURL, AServerMethod]);
//RESTRequest
rstRequest.Method := rmGET;
{chave} {valor}
//SL.AddPair('estabelecimento', '1');
//SL.AddPair('cardapio', '4');
if (AElementos <> nil) and (AElementos.Count > 0) then
begin
for I := 0 to Pred(AElementos.Count) do
begin
rstRequest.Params.AddItem(
AElementos.Names[I],
AElementos.ValueFromIndex[I],
TRESTRequestParameterKind.pkURLSEGMENT
);
if LParams.Equals(EmptyStr)
then LParams := LParams + '{' + AElementos.Names[I] + '}'
else LParams := LParams + '/{' + AElementos.Names[I] + '}'
end;
//cardapios/{estabelecimento}{cardapio}
rstRequest.Resource := Format('%s/%s', [AColecao, LParams]);
end
else
rstRequest.Resource := AColecao;
rstRequest.Execute;
Result := True;
except on E:Exception do
begin
end;
end;
end;
procedure TDmRest.ClearToDefaults;
begin
rstRequest.ResetToDefaults;
rstClient.ResetToDefaults;
rstResponse.ResetToDefaults;
//FDMemTable1.EmptyDataSet;
//FDMemTable1.Active := False;
end;
function TDmREST.Login(const AUsuario, ASenha: string): Boolean;
var
LParams : TSmartPointer<TStringList>;
begin
Result := False;
LParams.Value.AddPair('nome_usuario', AUsuario);
LParams.Value.AddPair('senha', ASenha);
if Execute(C_METODOSGERAIS, C_LOGIN, LParams)
then Result := (rstResponse.StatusCode = 200)
else Result := False;
//ShowMessage('Erro de requisição');
end;
function TDmREST.AtualizarPerfil(const APerfil: TJSONArray;
const AID: Integer): Boolean;
var
LParams : TSmartPointer<TStringList>;
begin
Result := False;
try
LParams.Value.AddPair('id', AID.ToString);
Result := Execute(C_METODOSGERAIS, C_PERFIL, LParams, APerfil, rmPUT);
except on E:Exception do
begin
end;
end;
end;
function TDmREST.AtualizarStatusLocal(const AID_Usuario: Integer): Boolean;
const
_UPDATE = 'UPDATE PEDIDOS SET STATUS = :PSTATUS WHERE ID = :PID_PEDIDO_MOBILE AND ID_USUARIO = :PID_USUARIO';
var
LParams : TSmartPointer<TStringList>;
ArraySize : Integer;
vIndex : Integer;
begin
//
Result := False;
try
try
LParams.Value.AddPair('ID_USUARIO', AID_USUARIO.ToString);
if Execute(C_SmServicos, C_ATUALIZARSTATUS, LParams) then
begin
vIndex := -1;
MemREST.First;
ArraySize := MemREST.RecordCount;
DM.qryAuxiliar.Active := False;
DM.qryAuxiliar.SQL.Clear;
DM.qryAuxiliar.SQL.Text := _UPDATE;
DM.qryAuxiliar.Params.ArraySize := ArraySize;
while not MemREST.Eof do
begin
Inc(vIndex);
DM.qryAuxiliar.ParamByName('PSTATUS').AsStrings[vIndex] := MemREST.FieldByName('STATUS').AsString;
DM.qryAuxiliar.ParamByName('PID_PEDIDO_MOBILE').AsIntegers[vIndex] := MemREST.FieldByName('ID_PEDIDO_MOBILE').AsInteger;
DM.qryAuxiliar.ParamByName('PID_USUARIO').AsIntegers[vIndex] := MemREST.FieldByName('ID_USUARIO').AsInteger;
MemREST.Next;
end;
DM.qryAuxiliar.Execute(ArraySize, 0);
end;
except on E:Exception do
begin
end;
end;
finally
end;
end;
function TDmREST.Cardapios(const ACategoria, AEstabelecimento: Integer): Boolean;
var
LParams : TSmartPointer<TStringList>;
begin
Result := False;
try
try
LParams.Value.AddPair('id_categogia', ACategoria.ToString);
LParams.Value.AddPair('id_estabelecimento', AEstabelecimento.ToString);
if Execute(C_SmServicos, C_CARDAPIOS, LParams) then
begin
DM.MemCardapios.Active := False;
DM.MemCardapios.Active := True;
MemREST.First;
while not (MemREST.Eof) do
begin
DM.MemCardapios.Append;
DM.MemCardapios.FieldByName('ID').AsInteger := MemREST.FieldByName('ID').AsInteger;
DM.MemCardapios.FieldByName('ID_ESTABELECIMENTO').AsInteger := MemREST.FieldByName('ID_ESTABELECIMENTO').AsInteger;
DM.MemCardapios.FieldByName('ID_CATEGORIA').AsInteger := MemREST.FieldByName('ID_CATEGORIA').AsInteger;
DM.MemCardapios.FieldByName('NOME').AsString := MemREST.FieldByName('NOME').AsString;
DM.MemCardapios.FieldByName('INGREDIENTES').AsString := MemREST.FieldByName('INGREDIENTES').AsString;
DM.MemCardapios.FieldByName('PRECO').AsFloat := MemREST.FieldByName('PRECO').AsFloat;
DM.MemCardapios.Post;
MemREST.Next;
end;
Result := True;
end
else
Result := False;
MemREST.Active := False;
except on E:Exception do
begin
Result := False;
end;
end;
finally
end;
end;
function TDmREST.Categorias(const AEstabelecimento: Integer): Boolean;
var
LParams : TSmartPointer<TStringList>;
begin
Result := False;
try
try
LParams.Value.AddPair('id_estabelecimento', AEstabelecimento.ToString);
if Execute(C_SmServicos, C_CATEGORIAS, LParams) then
begin
DM.MemCategorias.Active := False;
DM.MemCategorias.Active := True;
MemREST.First;
while not (MemREST.Eof) do
begin
DM.MemCategorias.Append;
DM.MemCategorias.FieldByName('ID').AsInteger := MemREST.FieldByName('ID').AsInteger;
DM.MemCategorias.FieldByName('DESCRICAO').AsString := MemREST.FieldByName('DESCRICAO').AsString;
DM.MemCategorias.Post;
MemREST.Next;
end;
Result := True;
end
else
Result := False;
MemREST.Active := False;
except on E:Exception do
begin
Result := False;
end;
end;
finally
end;
end;
function TDmREST.EnviarAlteracaoPedido(const AConteudo: TJSONArray; AID_Usuario,
AID_PEDIDO_MOBILE: Integer): Boolean;
var
LParams : TSmartPointer<TStringList>;
begin
Result := False;
try
LParams.Value.AddPair('ID_USUARIO', AID_USUARIO.ToString);
LParams.Value.AddPair('ID_PEDIDO_MOBILE', AID_PEDIDO_MOBILE.ToString);
Result :=
Execute(C_SmServicos, C_PEDIDOS, LParams, AConteudo, rmPUT)
AND not (rstResponse.StatusCode = 202);
except on E:Exception do
begin
Result := False;
end;
end;
end;
function TDmREST.EnviarPedido(const AConteudo: TJSONArray): Boolean;
begin
Result := False;
try
Result := Execute(C_SmServicos, C_PEDIDOS, nil, AConteudo, rmPOST);
except on E:Exception do
begin
end;
end;
end;
function TDmREST.Estabelecimentos(const AFiltro: string = ''; AValue: Integer = 0): Boolean;
var
FotoStream : TStringStream;
Foto : TMemoryStream;
sReader : TStringReader;
jReader : TJsonTextReader;
sID : String;
LParams : TSmartPointer<TStringList>;
DMvREST : TDataModule;
dmDados : TDataModule;
begin
{$IFDEF WEB}
DmvREST := UserSession.DmRest;
dmDados := UserSession.DM;
{$ELSE}
DMvREST := DmRest;
dmDados := DM;
{$ENDIF}
Result := False;
try
try
if not (AFiltro.Equals(EmptyStr)) then
LParams.Value.AddPair(AFiltro, AValue.ToString);
if Execute(C_SmServicos, C_ESTABELECIMENTOS, LParams) then
begin
TDM(dmDados).MemRestaurantes.Active := False;
TDM(dmDados).MemRestaurantes.Active := True;
TDmREST(DMvREST).MemREST.First;
//TDM(dmDados).MemRestaurantes.CopyDataSet(TDmREST(DMvREST).MemREST);
//TDmREST(DMvREST).MemREST.Active := False;
while not (TDmREST(dmvREST).MemREST.Eof) do
begin
TDM(dmDados).MemRestaurantes.Append;
TDM(dmDados).MemRestaurantes.FieldByName('ID').AsInteger := TDmREST(dmvREST).MemREST.FieldByName('ID').AsInteger;
TDM(dmDados).MemRestaurantes.FieldByName('FANTASIA').AsString := TDmREST(dmvREST).MemREST.FieldByName('FANTASIA').AsString;
TDM(dmDados).MemRestaurantes.FieldByName('RAZAO_SOCIAL').AsString := TDmREST(dmvREST).MemREST.FieldByName('RAZAO_SOCIAL').AsString;
sReader := TStringReader.Create(rstResponse.Content);
jReader := TJsonTextReader.Create(sReader);
while jReader.Read do
begin
if jReader.TokenType = TJsonToken.PropertyName then
begin
if Pos('ID', UpperCase(jReader.Path)) > 0 then
begin
jReader.Read;
sID := jReader.Value.ToString;
end;
if (UpperCase(jReader.Value.ToString) = 'FOTO_LOGOTIPO') and
(sID = TDmREST(dmREST).MemREST.FieldByName('ID').AsInteger.ToString) then
begin
try
jReader.Read;
FotoStream := TStringStream.Create(jReader.Value.ToString);
FotoStream.Position := 0;
Foto := TMemoryStream.Create;
TNetEncoding.Base64.Decode(FotoStream, Foto);
TDM(dmDados).MemRestaurantesfoto_logotipo.LoadFromStream(Foto);
Break;
finally
FotoStream.DisposeOf;
Foto.DisposeOf;
end;
end
else
continue;
end;
end;
TDM(dmDados).MemRestaurantes.Post;
TDmREST(dmvREST).MemREST.Next;
end;
Result := True;
end
else
Result := False;
TDmREST(DMvREST).MemREST.Active := False;
except on E:Exception do
begin
Result := False;
end;
end;
finally
end;
end;
function TDmREST.Execute(const AServerMethod, AColecao: string;
AElementos: TStrings; AContent: TJSONArray;
ARequestMethod: TRESTRequestMethod): Boolean;
var
I : Integer;
LParams : string;
begin
Result := False;
try
//Reset de componentes
ClearToDefaults;
MemREST.Active := False;
//RESTClient
rstClient.BaseURL := Format('%s%s', [C_BASEURL, AServerMethod]);
//RESTRequest
rstRequest.Method := ARequestMethod;
{chave} {valor}
//SL.AddPair('estabelecimento', '1');
//SL.AddPair('cardapio', '4');
if (AElementos <> nil) and (AElementos.Count > 0) then
begin
for I := 0 to Pred(AElementos.Count) do
begin
rstRequest.Params.AddItem(
AElementos.Names[I],
AElementos.ValueFromIndex[I],
TRESTRequestParameterKind.pkURLSEGMENT
);
if LParams.Equals(EmptyStr)
then LParams := LParams + '{' + AElementos.Names[I] + '}'
else LParams := LParams + '/{' + AElementos.Names[I] + '}'
end;
//cardapios/{estabelecimento}{cardapio}
rstRequest.Resource := Format('%s/%s', [AColecao, LParams]);
end
else
rstRequest.Resource := AColecao;
rstRequest.Body.Add(AContent.ToString, ContentTypeFromString('application/json'));
rstRequest.Execute;
Result := True;
except on E:Exception do
begin
end;
end;
end;
function TDmREST.Perfil(const AUsuario: string): Boolean;
var
FotoStream : TStringStream;
Foto : TMemoryStream;
sReader : TStringReader;
jReader : TJsonTextReader;
sID : String;
LParams : TSmartPointer<TStringList>;
begin
Result := False;
try
try
LParams.Value.AddPair('nome_usuario', AUsuario);
if Execute(C_METODOSGERAIS, C_PERFIL, LParams) then
begin
DM.MemUsuario.Active := False;
DM.MemUsuario.Active := True;
MemREST.First;
while not (MemREST.Eof) do
begin
DM.MemUsuario.Append;
DM.MemUsuario.FieldByName('ID').AsInteger := MemREST.FieldByName('ID').AsInteger;
//DM.MemUsuario.FieldByName('ID_ENDERECO').AsInteger := MemREST.FieldByName('ID_ENDERECO').AsInteger;
DM.MemUsuario.FieldByName('NOME_COMPLETO').AsString := MemREST.FieldByName('NOME_COMPLETO').AsString;
DM.MemUsuario.FieldByName('NOME_USUARIO').AsString := MemREST.FieldByName('NOME_USUARIO').AsString;
DM.MemUsuario.FieldByName('EMAIL').AsString := MemREST.FieldByName('EMAIL').AsString;
DM.MemUsuario.FieldByName('CPFCNPJ').AsString := MemREST.FieldByName('CPFCNPJ').AsString;
DM.MemUsuario.FieldByName('SENHA').AsString := MemREST.FieldByName('SENHA').AsString;
sReader := TStringReader.Create(rstResponse.Content);
jReader := TJsonTextReader.Create(sReader);
while jReader.Read do
begin
if jReader.TokenType = TJsonToken.PropertyName then
begin
if (jReader.Path = '[0].id') then
begin
jReader.Read;
sID := jReader.Value.ToString;
end;
//Refatorado para o esquema acima.
//if Pos('ID', UpperCase(jReader.Path)) > 0 then
//begin
// jReader.Read;
// sID := jReader.Value.ToString;
//end;
if (UpperCase(jReader.Value.ToString) = 'FOTO') and
(sID = MemREST.FieldByName('ID').AsInteger.ToString) then
begin
try
jReader.Read;
FotoStream := TStringStream.Create(jReader.Value.ToString);
FotoStream.Position := 0;
Foto := TMemoryStream.Create;
TNetEncoding.Base64.Decode(FotoStream, Foto);
DM.memUsuariofoto.LoadFromStream(Foto);
Break;
finally
FotoStream.DisposeOf;
Foto.DisposeOf;
end;
end
else
continue;
end;
end;
DM.MemUsuario.Post;
MemREST.Next;
end;
Result := True;
end
else
Result := False;
MemREST.Active := False;
except on E:Exception do
begin
Result := False;
end;
end;
finally
end;
end;
function TDmREST.RegistrarUsuario(const AConteudo: TJSONArray): Boolean;
begin
Result := False;
try
Result := Execute(C_METODOSGERAIS, C_USUARIOS, nil, AConteudo, rmPOST);
except on E:Exception do
begin
end;
end;
end;
end.
|
unit ExtraChargeSimpleView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GridFrame, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit,
cxNavigator, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB,
cxDBData, dxBarBuiltInMenu, cxGridCustomPopupMenu, cxGridPopupMenu, Vcl.Menus,
System.Actions, Vcl.ActnList, dxBar, cxClasses, Vcl.ComCtrls, cxGridLevel,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridBandedTableView, cxGridDBBandedTableView, cxGrid, ExtraChargeQuery2,
dxDateRanges, cxDropDownEdit, NotifyEvents;
type
TViewExtraChargeSimple = class(TfrmGrid)
procedure cxGridDBBandedTableViewCellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift:
TShiftState; var AHandled: Boolean);
private
FOnClosePopup: TNotifyEventsEx;
FqExtraCharge: TQueryExtraCharge2;
function GetPopupWindow: TcxCustomEditPopupWindow;
procedure SetqExtraCharge(const Value: TQueryExtraCharge2);
{ Private declarations }
protected
procedure InitView(AView: TcxGridDBBandedTableView); override;
property PopupWindow: TcxCustomEditPopupWindow read GetPopupWindow;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property qExtraCharge: TQueryExtraCharge2 read FqExtraCharge
write SetqExtraCharge;
property OnClosePopup: TNotifyEventsEx read FOnClosePopup;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TViewExtraChargeSimple.Create(AOwner: TComponent);
begin
inherited;
FOnClosePopup := TNotifyEventsEx.Create(Self);
end;
destructor TViewExtraChargeSimple.Destroy;
begin
FreeAndNil(FOnClosePopup);
inherited;
end;
procedure TViewExtraChargeSimple.cxGridDBBandedTableViewCellClick(Sender:
TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
inherited;
PopupWindow.CloseUp;
FOnClosePopup.CallEventHandlers(Self);
end;
function TViewExtraChargeSimple.GetPopupWindow: TcxCustomEditPopupWindow;
var
PopupWindow: TCustomForm;
begin
PopupWindow := GetParentForm(Self);
Result := PopupWindow as TcxCustomEditPopupWindow;
end;
procedure TViewExtraChargeSimple.InitView(AView: TcxGridDBBandedTableView);
begin
AView.OptionsBehavior.ImmediateEditor := False;
AView.OptionsView.FocusRect := False;
AView.OptionsSelection.MultiSelect := False;
AView.OptionsSelection.CellMultiSelect := False;
AView.OptionsSelection.CellSelect := False;
// AView.Styles.Inactive := DMRepository.cxInactiveStyle;
end;
procedure TViewExtraChargeSimple.SetqExtraCharge(const Value
: TQueryExtraCharge2);
begin
if FqExtraCharge = Value then
Exit;
FqExtraCharge := Value;
if FqExtraCharge = nil then
begin
MainView.DataController.DataSource := nil;
Exit;
end;
MainView.DataController.DataSource := qExtraCharge.W.DataSource;
MainView.DataController.KeyFieldNames := qExtraCharge.W.PKFieldName;
MainView.DataController.CreateAllItems();
MyApplyBestFit;
end;
end.
|
unit UViewPort;
{$mode objfpc}{$H+}
interface
uses
Classes, Math, UGeometry;
type
TScrollBarType = (sbHorizontal, sbVertical);
TScrollUpdateEvent = procedure(AVisible: Boolean; APageSize,
APosition: Integer; AKind: TScrollBarType) of object;
{ TViewPort }
TViewPort = class
const
MaxScale = 20;
MinScale = 0.25;
private
FScale: Double;
FViewPosition: TFloatPoint;
FPortSize: TPoint;
FHorizontalSBPosition: Integer;
FVerticalSBPosition: Integer;
FScrollUpdateEvent: TScrollUpdateEvent;
procedure SetScale(AScale: Double);
public
property ViewPosition: TFloatPoint read FViewPosition
write FViewPosition;
property Scale: Double read FScale write SetScale;
property PortSize: TPoint read FPortSize write FPortSize;
property OnScrollUpdate: TScrollUpdateEvent read FScrollUpdateEvent
write FScrollUpdateEvent;
constructor Create;
function WorldToScreen(APoint: TFloatPoint): TPoint;
function WorldToScreen(APoints: TFloatPoints): TPoints; overload;
function WorldToScreen(AFloatRect: TFloatRect): TRect; overload;
function ScreenToWorld(APoint: TPoint): TFloatPoint;
function ScreenToWorld(ARect: TRect): TFloatRect; overload;
procedure ScaleTo(ARect: TFloatRect);
procedure SetScroll(APosition: Integer; AWSize, AMin: Double;
AKind: TScrollBarType);
procedure ScaleMouseWheel(APoint: TPoint; Delta: Integer);
end;
var
VP: TViewPort;
implementation
{ TViewPort }
procedure TViewPort.SetScale(AScale: Double);
begin
if (AScale <> FScale) and InRange(AScale, MinScale, MaxScale) then
FScale := AScale;
end;
constructor TViewPort.Create;
begin
FScale := 1;
FViewPosition := FloatPoint(0, 0);
end;
function TViewPort.WorldToScreen(APoint: TFloatPoint): TPoint;
begin
Result := Point((APoint - FViewPosition) * FScale + FPortSize / 2);
end;
function TViewPort.WorldToScreen(APoints: TFloatPoints): TPoints;
var i: integer;
begin
SetLength(Result, Length(APoints));
for i := 0 to High(APoints) do
begin
Result[i] := WorldToScreen(APoints[i]);
end;
end;
function TViewPort.WorldToScreen(AFloatRect: TFloatRect): TRect;
begin
Result := Rect(
WorldToScreen(FloatPoint(AFloatRect.Left, AFloatRect.Top)),
WorldToScreen(FloatPoint(AFloatRect.Right, AFloatRect.Bottom)));
end;
function TViewPort.ScreenToWorld(APoint: TPoint): TFloatPoint;
begin
Result := (APoint + FViewPosition * FScale - FPortSize / 2) / FScale;
end;
function TViewPort.ScreenToWorld(ARect: TRect): TFloatRect;
begin
Result := FloatRect(
ScreenToWorld(Point(ARect.Left, ARect.Top)),
ScreenToWorld(Point(ARect.Right, ARect.Bottom)));
end;
procedure TViewPort.ScaleTo(ARect: TFloatRect);
var scl: double;
begin
if (ARect.Left = ARect.Right) or (ARect.Top = ARect.Bottom) then
exit;
scl := Min(
FPortSize.X / abs(ARect.Left - ARect.Right),
FPortSize.Y / abs(ARect.Top - ARect.Bottom));
FScale := EnsureRange(scl, MinScale, MaxScale);
end;
procedure TViewPort.SetScroll(APosition: Integer; AWSize, AMin: Double;
AKind: TScrollBarType);
var
psshift: Double;
psize, pagesize: Integer;
visible: Boolean;
sbpos: ^Integer;
vpos: ^Double;
begin
if AKind = sbHorizontal then
begin
psize := FPortSize.X;
sbpos := @FHorizontalSBPosition;
vpos := @FViewPosition.X;
end
else
begin
psize := FPortSize.Y;
sbpos := @FVerticalSBPosition;
vpos := @FViewPosition.Y;
end;
psshift := psize / FScale / 2;
pagesize := round(psize * 10000 / (AWSize * FScale));
if pagesize >= 10000 then
visible := False
else
begin
visible := True;
{Updating scrollbar position when it is not moved, else updating view position}
if APosition = sbpos^ then
APosition := round((vpos^ - AMin - psshift) * 10000 / AWSize)
else
vpos^ := APosition * AWSize / 10000 + AMin + psshift;
sbpos^ := APosition;
end;
FScrollUpdateEvent(visible, pagesize, APosition, AKind);
end;
procedure TViewPort.ScaleMouseWheel(APoint: TPoint; Delta: Integer);
var mem: TFloatPoint;
begin
if not ((FScale <= MinScale) or (Delta > 0)) then
begin
mem := ScreenToWorld(APoint);
FViewPosition := ScreenToWorld(APoint);
FScale := Max(FScale / 1.25, MinScale);
FViewPosition += mem - ScreenToWorld(APoint);
end
else if not ((FScale >= MaxScale) or (Delta < 0)) then
begin
mem := ScreenToWorld(APoint);
FViewPosition := ScreenToWorld(APoint);
FScale := Min(FScale * 1.25, MaxScale);
FViewPosition += mem - ScreenToWorld(APoint);
end;
end;
end.
|
unit UPluginGroups;
interface
uses
SysUtils, Classes, Contnrs, UPluginClasses;
type
TPluginItem = class(TObject)
private
FPlugin: TPluginClass;
FPluginName: string;
public
property Plugin: TPluginClass read FPlugin write FPlugin;
property PluginName: string read FPluginName write FPluginName;
end;
TPluginGroup = class(TObject)
private
FObjectList: TObjectList;
function GetItem(Index: Integer): TPluginItem;
function GetItemCount: Integer;
public
constructor Create;
destructor Destroy; overload;
procedure AddItem(APluginClass: TPluginClass; APluginName: string);
function FindItem(APluginName: string): TPluginClass;
property Items[Index: Integer]: TPluginItem read GetItem;
property ItemCount: Integer read GetItemCount;
end;
function PluginGroup: TPluginGroup;
procedure RegisterPlugin(APluginClass: TPluginClass; APluginName: string);
implementation
var
FPluginList: TPluginGroup = nil;
function PluginGroup: TPluginGroup;
begin
if not Assigned(FPluginList) then
FPluginList := TPluginGroup.Create;
Result := FPluginList;
end;
procedure RegisterPlugin(APluginClass: TPluginClass; APluginName: string);
begin
PluginGroup.AddItem(APluginClass, APluginName);
end;
{ TPluginGroup }
procedure TPluginGroup.AddItem(APluginClass: TPluginClass; APluginName: string);
var
lPlugin: TPluginItem;
begin
lPlugin := TPluginItem.Create;
lPlugin.Plugin := APluginClass;
lPlugin.PluginName := APluginName;
FObjectList.Add(lPlugin);
end;
constructor TPluginGroup.Create;
begin
FObjectList := TObjectList.Create;
FObjectList.OwnsObjects := True;
end;
destructor TPluginGroup.Destroy;
begin
FObjectList.Free;
end;
function TPluginGroup.FindItem(APluginName: string): TPluginClass;
var
I: Integer;
begin
for I := 0 to ItemCount - 1 do
begin
if Items[I].PluginName = APluginName then
begin
Result := Items[I].Plugin;
Exit;
end;
end;
Result := nil;
end;
function TPluginGroup.GetItemCount: Integer;
begin
Result := FObjectList.Count;
end;
function TPluginGroup.GetItem(Index: Integer): TPluginItem;
begin
Result := TPluginItem(FObjectList(Index));
end;
initialization
finalization
FreeAndNil(FPluginList);
end.
|
unit uConnection;
interface
uses
SysUtils, ADODB, Classes, Dialogs, Windows;
const
connstrORA =
'Provider=MSDAORA.1;Password=%s;User ID=%s;Data Source=%s;Persist Security Info=True';
connstrMS =
//'Provider=SQLOLEDB.1;Password=%s;User ID=%s;Data Source=%s;Initial Catalog=IFRS;';
//'Provider=SQLNCLI10;Password=%s;User ID=%s;Data Source=%s;Initial Catalog=IFRS;';
'Provider=MSDASQL.1;Password=%s;User ID=%s;Data Source=%s;Persist Security Info=False';
type
TConnection = class
strict private
FConn: TADOConnection;
FConnected: boolean;
FLastError: string;
FOnChangeStatus: TNotifyEvent;
procedure SetConnected(const aValue: boolean);
procedure SetChangeStatus(aValue: TNotifyEvent);
public
Query: TADOQuery;
constructor Create(const aServer, aUser, aPass: string;
const aConnStr: string = connstrMS);
destructor Destroy; override;
procedure Connect;
procedure Disconnect;
property Connected: boolean read FConnected write SetConnected;
property LastError: string read FLastError;
property OnChangeStatus: TNotifyEvent read FOnChangeStatus write SetChangeStatus;
end;
implementation
{ TURConnection }
procedure TConnection.Connect;
begin
try
FConn.Connected := true;
FConnected := FConn.Connected;
if Assigned(FOnChangeStatus) then
OnChangeStatus(Self);
except
on E: Exception do
begin
FLastError := E.Message;
end;
end;
end;
constructor TConnection.Create(const aServer, aUser, aPass, aConnStr: string);
begin
inherited Create;
try
FConn := TADOConnection.Create(nil);
FConn.ConnectionString := Format(aConnStr, [aPass, aUser, aServer]);
FConn.LoginPrompt := false;
Query := TADOQuery.Create(nil);
Query.Connection := FConn;
except
on E: Exception do
begin
FLastError := E.Message;
end;
end;
end;
destructor TConnection.Destroy;
begin
Query.Close;
FConn.Close;
Query.Free;
FConn.Free;
inherited;
end;
procedure TConnection.Disconnect;
begin
try
FConn.Connected := false;
FConnected := FConn.Connected;
FOnChangeStatus(Self);
except
on E: Exception do
begin
FLastError := E.Message;
end;
end;
end;
procedure TConnection.SetChangeStatus(aValue: TNotifyEvent);
begin
FOnChangeStatus := aValue;
end;
procedure TConnection.SetConnected(const aValue: boolean);
begin
try
FConn.Connected := aValue;
FConnected := FConn.Connected;
FOnChangeStatus(Self);
except
on E: Exception do
begin
FConn.Connected := false;
FConnected := FConn.Connected;
FLastError:= E.Message;
end;
end;
end;
end.
|
unit CalcLogic;
interface
uses SysUtils;
type
TCalcLogic = class
public
function Add(a, b: integer): integer;
function Sub(a, b: integer): integer;
function Mul(a, b: integer): integer;
function Division(a, b: integer): integer;
end;
implementation
function TCalcLogic.Add(a, b: integer): integer;
begin
Result := a + b;
end;
function TCalcLogic.Sub(a, b: integer): integer;
begin
Result := a - b;
end;
function TCalcLogic.Mul(a, b: integer): integer;
begin
Result := a * b;
end;
function TCalcLogic.Division(a, b: integer): integer;
begin
try
Result := a div b;
except
on E: Exception do
raise;
end;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Базовый класс реаизации источника данных (IStockDataSource)
History:
-----------------------------------------------------------------------------}
unit FC.StockData.StockDataSource;
{$I Compiler.inc}
interface
uses Windows, Controls, SysUtils,Classes,Contnrs, DB,
StockChart.Definitions,
FC.Definitions,FC.Singletons,
FC.StockData.DataSourceToInputDataCollectionMediator;
type
//Базовый класс источников данных
TStockDataSource_B = class (TStockInterfacedObject,IStockDataSource)
private
FConnection: IStockDataSourceConnection;
FEventHandlers : TInterfaceList;
FStockSymbol : TStockSymbol;
FFinder : TStockDataSourceToInputDataCollectionMediator;
function GetEventHandler(index: integer): IStockDataSourceEventHandler;
protected
FPricePrecision : integer;
FPricesInPoint : integer;
function EventHandlerCount: integer;
property EventHandlers[index: integer]:IStockDataSourceEventHandler read GetEventHandler;
procedure RaiseChangeDataEvent(index: integer; aType: TStockDataModificationType);
public
//------ from IStockDataSource
function RecordCount: integer; virtual; abstract;
function IndexOf(const aDateTime:TDateTime): integer;
function FindBestMatched(const aDateTime:TDateTime): integer;
procedure ResetSearchCache;
procedure FetchAll; virtual;
//Непосредственно данные
function GetDataDateTime(index: integer): TDateTime; virtual; abstract;
function GetDataOpen(index: integer) : TStockRealNumber; virtual; abstract;
function GetDataHigh(index: integer) : TStockRealNumber; virtual; abstract;
function GetDataLow(index: integer) : TStockRealNumber; virtual; abstract;
function GetDataClose(index: integer) : TStockRealNumber; virtual; abstract;
function GetDataVolume(index: integer): integer; virtual; abstract;
//------------------------------
function Connection: IStockDataSourceConnection;
function StockSymbol:TStockSymbol;
function Tag: string; virtual;
//Кол-во точек после запятой
function GetPricePrecision: integer;
//Коэффициент трансформации из точки в цену, для EURUSD=10000, для USDJPY=100
function GetPricesInPoint: integer;
//Округление цены до PricePrecision
function RoundPrice(const aPrice: TSCRealNumber) : TSCRealNumber;
//Перевод цены в пункты (умножение на PricesInPoint)
function PriceToPoint(const aPrice: TSCRealNumber) : integer;
//Перевод пунктов в цену (деление на PricesInPoint)
function PointToPrice(const aPoint: integer) : TSCRealNumber;
procedure AddEventHandler(const aHandler: IStockDataSourceEventHandler);
procedure RemoveEventHandler(const aHandler: IStockDataSourceEventHandler);
constructor Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval);
destructor Destroy; override;
procedure AfterConstruction; override;
end;
//Класс для чтения данных из потока
TStockDataRecord = class
public
DataDateTime: TDateTime;
DataOpen : TStockRealNumber;
DataHigh : TStockRealNumber;
DataLow : TStockRealNumber;
DataClose : TStockRealNumber;
DataVolume : integer;
constructor Create(aDataDateTime: TDateTime;
aDataOpen : TStockRealNumber;
aDataHigh : TStockRealNumber;
aDataLow : TStockRealNumber;
aDataClose : TStockRealNumber;
aDataVolume : integer);
end;
{ TStockDataSourceMemory_B }
TStockDataSourceMemory_B = class (TStockDataSource_B)
protected
FRecordList: TObjectList; //of TStockDataRecord
function GetRecord(index: integer):TStockDataRecord; inline;
procedure OnLoadPortion(index:integer); virtual;
public
procedure FetchAll; override;
function Add(const aDataDateTime: TDateTime;
const aDataOpen, aDataHigh, aDataLow, aDataClose: TStockRealNumber;
aDataVolume: integer):TStockDataRecord;
//------ from IStockDataSource
function RecordCount: integer; override;
function GetDataDateTime(index: integer): TDateTime; override;
function GetDataOpen(index: integer) : TStockRealNumber;override;
function GetDataHigh(index: integer) : TStockRealNumber;override;
function GetDataLow(index: integer) : TStockRealNumber;override;
function GetDataClose(index: integer) : TStockRealNumber;override;
function GetDataVolume(index: integer): integer; override;
constructor Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval);
destructor Destroy; override;
end;
{ TStockDataSource_StreamToMemory }
TStockDataSource_StreamToMemory = class (TStockDataSourceMemory_B)
end;
EDataSourceException = class (EStockError);
function OnSortRecords(Item1, Item2: Pointer): Integer;
implementation
uses Math,BaseUtils,DateUtils,SystemService,FC.DataUtils, StockChart.Obj,
FC.StockData.StockDataSourceRegistry;
function OnSortRecords(Item1, Item2: Pointer): Integer;
begin
result:=sign(TStockDataRecord(Item1).DataDateTime-TStockDataRecord(Item2).DataDateTime);
end;
{ TStockDataSource_B }
procedure TStockDataSource_B.AddEventHandler(const aHandler: IStockDataSourceEventHandler);
begin
FEventHandlers.Add(aHandler);
end;
procedure TStockDataSource_B.RemoveEventHandler(const aHandler: IStockDataSourceEventHandler);
begin
FEventHandlers.Remove(aHandler);
end;
procedure TStockDataSource_B.ResetSearchCache;
begin
FFinder.ResetSearchCache;
end;
procedure TStockDataSource_B.AfterConstruction;
begin
inherited;
StockLoadedDataSourceRegistry.AddDataSource(self);
end;
function TStockDataSource_B.Connection: IStockDataSourceConnection;
begin
result:=FConnection;
end;
function TStockDataSourceMemory_B.Add(const aDataDateTime: TDateTime; const aDataOpen, aDataHigh, aDataLow,
aDataClose: TStockRealNumber; aDataVolume: integer): TStockDataRecord;
begin
result:=
TStockDataRecord.Create(
aDataDateTime,
aDataOpen,
aDataHigh,
aDataLow,
aDataClose,
aDataVolume);
FRecordList.Add(result);
end;
constructor TStockDataSourceMemory_B.Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval);
begin
inherited Create(aConnection, aSymbol,aInterval);
FRecordList:=TObjectList.Create;
end;
destructor TStockDataSourceMemory_B.Destroy;
begin
FreeAndNil(FRecordList);
inherited;
end;
procedure TStockDataSourceMemory_B.FetchAll;
begin
inherited;
if RecordCount>0 then
GetRecord(RecordCount-1);
end;
function TStockDataSource_B.GetEventHandler(index: integer): IStockDataSourceEventHandler;
begin
result:=FEventHandlers[index] as IStockDataSourceEventHandler;
end;
function TStockDataSource_B.GetPricePrecision: integer;
begin
result:=FPricePrecision;
end;
function TStockDataSource_B.GetPricesInPoint: integer;
begin
result:=FPricesInPoint;
end;
function TStockDataSource_B.EventHandlerCount: integer;
begin
result:=FEventHandlers.Count;
end;
procedure TStockDataSource_B.RaiseChangeDataEvent(index: integer; aType: TStockDataModificationType);
var
i: integer;
begin
for i:=0 to EventHandlerCount-1 do
EventHandlers[i].OnChangeData(self,index,aType);
end;
constructor TStockDataSource_B.Create(const aConnection: IStockDataSourceConnection; const aSymbol: string; aInterval: TStockTimeInterval);
begin
FStockSymbol:=TStockSymbol.Create(aSymbol,aInterval);
FEventHandlers:=TInterfaceList.Create;
FConnection:=aConnection;
//TODO
FPricesInPoint := TKnownSymbolRegistry.GetPricesInPoint(aSymbol); //Коэффициент
FPricePrecision := TKnownSymbolRegistry.GetPricePrecision(aSymbol); //Кол-во знаков после запятой
FFinder:=TStockDataSourceToInputDataCollectionMediator.Create(self,nil);
FFinder.BeginUpdate;
Assert(RefCount=2);
_Release; //Это потому что медиатор подвесился
end;
destructor TStockDataSource_B.Destroy;
begin
StockLoadedDataSourceRegistry.RemoveDataSource(self);
FreeAndNil(FEventHandlers);
FreeAndNil(FStockSymbol);
SetInvalidRefCount; //Из-за принудильного _Release в конструкторе
FreeAndNil(FFinder);
inherited;
end;
function TStockDataSource_B.IndexOf(const aDateTime: TDateTime): integer;
var
aStart,aStop: TDateTime;
begin
TStockDataUtils.AlignTime(aDateTime,FStockSymbol.TimeInterval,aStart,aStop);
Assert(SameDateTime(FStockSymbol.GetTimeIntervalValue/MinsPerDay,FFinder.GetGradation));
result:=FFinder.FindExactMatched(aStart);
end;
procedure TStockDataSource_B.FetchAll;
begin
end;
function TStockDataSource_B.FindBestMatched(const aDateTime: TDateTime): integer;
begin
result:=FFinder.FindBestMatched(aDateTime,0,RecordCount-1);
end;
function TStockDataSource_B.StockSymbol: TStockSymbol;
begin
result:=FStockSymbol;
end;
function TStockDataSource_B.Tag: string;
begin
result:='';
end;
//Округление цены до PricePrecision
function TStockDataSource_B.RoundPrice(const aPrice: TSCRealNumber) : TSCRealNumber;
begin
result:=RoundTo(aPrice,-FPricePrecision);
end;
//Перевод цены в пункты (умножение на PricesInPoint)
function TStockDataSource_B.PriceToPoint(const aPrice: TSCRealNumber) : integer;
begin
result:=Round(aPrice*FPricesInPoint);
end;
//Перевод пунктов в цену (деление на PricesInPoint)
function TStockDataSource_B.PointToPrice(const aPoint: integer) : TSCRealNumber;
begin
result:=aPoint/FPricesInPoint;
end;
{ TStockDataRecord }
constructor TStockDataRecord.Create(aDataDateTime: TDateTime; aDataOpen,
aDataHigh, aDataLow, aDataClose: TStockRealNumber; aDataVolume: integer);
begin
try
ASSERT(aDataOpen<=aDataHigh);
ASSERT(aDataClose<=aDataHigh);
ASSERT(aDataOpen>=aDataLow);
ASSERT(aDataClose>=aDataLow);
except
raise;
end;
DataDateTime:=TStockDataUtils.RefineTime(aDataDateTime);
DataOpen :=aDataOpen;
DataHigh :=aDataHigh;
DataLow :=aDataLow;
DataClose :=aDataClose;
DataVolume :=aDataVolume;
end;
{ TStockDataSourceMemory_B }
function TStockDataSourceMemory_B.GetDataClose(index: integer): TStockRealNumber;
begin
result:=GetRecord(index).DataClose;
end;
function TStockDataSourceMemory_B.GetDataDateTime(index: integer): TDateTime;
begin
result:=GetRecord(index).DataDateTime;
end;
function TStockDataSourceMemory_B.GetDataHigh(index: integer): TStockRealNumber;
begin
result:=GetRecord(index).DataHigh;
end;
function TStockDataSourceMemory_B.GetDataLow(index: integer): TStockRealNumber;
begin
result:=GetRecord(index).DataLow;
end;
function TStockDataSourceMemory_B.GetDataOpen(index: integer): TStockRealNumber;
begin
result:=GetRecord(index).DataOpen;
end;
function TStockDataSourceMemory_B.GetDataVolume(index: integer): integer;
begin
result:=GetRecord(index).DataVolume;
end;
function TStockDataSourceMemory_B.RecordCount: integer;
begin
result:=FRecordList.Count;
end;
function TStockDataSourceMemory_B.GetRecord(index: integer): TStockDataRecord;
begin
if index>=RecordCount then
raise EDataSourceException.Create('Index out of range');
if index<0 then
raise EDataSourceException.Create('Index out of range');
if index>=FRecordList.Count then
OnLoadPortion(index);
if index>=FRecordList.Count then
raise EAlgoError.Create;
result:=TStockDataRecord(FRecordList.List[index]);
end;
procedure TStockDataSourceMemory_B.OnLoadPortion(index: integer);
begin
raise EAlgoError.Create;
end;
end.
|
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
AppEvnts, ActnList, Menus, StdCtrls;
type
TMainForm = class(TForm)
ApplicationEvents: TApplicationEvents;
ActionList: TActionList;
Action: TAction;
MainMenu: TMainMenu;
MenuAction: TMenuItem;
MenuException: TMenuItem;
HintButton: TButton;
lbOnMessage: TListBox;
lblOnMessage: TLabel;
lbOther: TListBox;
lblOther: TLabel;
lbIdle: TListBox;
lblOnIdle: TLabel;
lbActionUpdate: TListBox;
lblOnActionUpdate: TLabel;
procedure ApplicationEventsActionExecute(Action: TBasicAction;
var Handled: Boolean);
procedure ApplicationEventsActionUpdate(Action: TBasicAction;
var Handled: Boolean);
procedure ApplicationEventsActivate(Sender: TObject);
procedure ApplicationEventsDeactivate(Sender: TObject);
procedure ApplicationEventsException(Sender: TObject; E: Exception);
function ApplicationEventsHelp(Command: Word; Data: Integer;
var CallHelp: Boolean): Boolean;
procedure ApplicationEventsHint(Sender: TObject);
procedure ApplicationEventsIdle(Sender: TObject; var Done: Boolean);
procedure ApplicationEventsMessage(var Msg: tagMSG;
var Handled: Boolean);
procedure ApplicationEventsMinimize(Sender: TObject);
procedure ApplicationEventsRestore(Sender: TObject);
procedure ApplicationEventsShortCut(var Msg: TWMKey;
var Handled: Boolean);
procedure ApplicationEventsShowHint(var HintStr: String;
var CanShow: Boolean; var HintInfo: THintInfo);
procedure ActionExecute(Sender: TObject);
procedure MenuExceptionClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
procedure TMainForm.ApplicationEventsActionExecute(Action: TBasicAction;
var Handled: Boolean);
begin
lbOther.Items.Add('Event OnActionExecute');
end;
procedure TMainForm.ApplicationEventsActionUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
lbActionUpdate.Items.Add('Event OnActionUpdate');
end;
procedure TMainForm.ApplicationEventsActivate(Sender: TObject);
begin
lbOther.Items.Add('Event OnActivate');
end;
procedure TMainForm.ApplicationEventsDeactivate(Sender: TObject);
begin
lbOther.Items.Add('Event OnDeactivate');
end;
procedure TMainForm.ApplicationEventsException(Sender: TObject;
E: Exception);
begin
lbOther.Items.Add('Event OnException: ' + E.Message);
end;
function TMainForm.ApplicationEventsHelp(Command: Word; Data: Integer;
var CallHelp: Boolean): Boolean;
begin
lbOther.Items.Add('Event OnHelp');
Result := False;
end;
procedure TMainForm.ApplicationEventsHint(Sender: TObject);
begin
lbOther.Items.Add('Event OnHint');
end;
procedure TMainForm.ApplicationEventsIdle(Sender: TObject;
var Done: Boolean);
begin
lbIdle.Items.Add('Event OnIdle');
end;
procedure TMainForm.ApplicationEventsMessage(var Msg: tagMSG;
var Handled: Boolean);
begin
lbOnMessage.Items.Add('X:=' + IntToStr(Msg.pt.x) + '|Y:=' + IntToStr(Msg.pt.y));
end;
procedure TMainForm.ApplicationEventsMinimize(Sender: TObject);
begin
lbOther.Items.Add('Event OnMinimize');
end;
procedure TMainForm.ApplicationEventsRestore(Sender: TObject);
begin
lbOther.Items.Add('Event OnRestore');
end;
procedure TMainForm.ApplicationEventsShortCut(var Msg: TWMKey;
var Handled: Boolean);
begin
lbOther.Items.Add('Event OnShortCut');
end;
procedure TMainForm.ApplicationEventsShowHint(var HintStr: String;
var CanShow: Boolean; var HintInfo: THintInfo);
begin
lbOther.Items.Add('Event OnShowHint');
end;
procedure TMainForm.ActionExecute(Sender: TObject);
begin
ShowMessage('Action executed');
end;
procedure TMainForm.MenuExceptionClick(Sender: TObject);
resourcestring
sExceptionRaised = 'This is an exception';
begin
raise Exception.Create(sExceptionRaised);
end;
end.
|
unit UnClienteListaRegistrosView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, DBGrids, StdCtrls, JvExControls, JvButton, DB,
JvTransparentButton, ExtCtrls,
{ Fluente }
Util, DataUtil, UnModelo, Componentes, UnAplicacao,
UnClienteListaRegistrosModelo, JvExDBGrids, JvDBGrid, JvDBUltimGrid,
JvComponentBase, JvBalloonHint;
type
TClienteListaRegistrosView = class(TForm, ITela)
Panel1: TPanel;
btnAdicionar: TJvTransparentButton;
JvTransparentButton2: TJvTransparentButton;
pnlFiltro: TPanel;
EdtCliente: TEdit;
gClientes: TJvDBUltimGrid;
procedure EdtClienteChange(Sender: TObject);
procedure gClientesDblClick(Sender: TObject);
procedure btnAdicionarClick(Sender: TObject);
private
FControlador: IResposta;
FClienteListaRegistrosModelo: TClienteListaRegistrosModelo;
public
function Descarregar: ITela;
function Controlador(const Controlador: IResposta): ITela;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
function ExibirTela: Integer;
end;
implementation
{$R *.dfm}
uses
{ helsonsant }
UnMenuView;
{ TClienteListaRegistrosView }
function TClienteListaRegistrosView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TClienteListaRegistrosView.Descarregar: ITela;
begin
Self.FControlador := nil;
Self.FClienteListaRegistrosModelo := nil;
Result := Self;
end;
function TClienteListaRegistrosView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TClienteListaRegistrosView.Modelo(const Modelo: TModelo): ITela;
begin
Self.FClienteListaRegistrosModelo := (Modelo as TClienteListaRegistrosModelo);
Result := Self;
end;
function TClienteListaRegistrosView.Preparar: ITela;
begin
Self.gClientes.DataSource := Self.FClienteListaRegistrosModelo.DataSource;
Result := Self;
end;
procedure TClienteListaRegistrosView.EdtClienteChange(Sender: TObject);
begin
if Self.EdtCliente.Text = '' then
Self.FClienteListaRegistrosModelo.Carregar
else
Self.FClienteListaRegistrosModelo.CarregarPor(
Criterio.Campo('cl_cod').como(Self.EdtCliente.Text).obter());
end;
procedure TClienteListaRegistrosView.gClientesDblClick(Sender: TObject);
var
_chamada: TChamada;
_dataSet: TDataSet;
begin
_dataSet := Self.FClienteListaRegistrosModelo.DataSet;
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(TMap.Create
.Gravar('acao', Ord(adrCarregar))
.Gravar('oid', _dataSet.FieldByName('cl_oid').AsString)
);
Self.FControlador.Responder(_chamada)
end;
procedure TClienteListaRegistrosView.btnAdicionarClick(Sender: TObject);
var
_chamada: TChamada;
_parametros: TMap;
begin
_parametros := Self.FClienteListaRegistrosModelo.Parametros;
_parametros
.Gravar('acao', 'incluir');
_chamada := TChamada.Create
.Chamador(Self)
.Parametros(_parametros);
Self.FControlador.Responder(_chamada);
end;
end.
|
unit TiledMap;
interface
uses
System.Classes,
Vcl.Imaging.PNGImage;
type
TTiledMap = class(TObject)
private type
TLayer = array of array of Integer;
private
FWidth: Integer;
FHeight: Integer;
FTileSize: Integer;
FOwner: TComponent;
FName: string;
FLevel: Integer;
public type
TLayerEnum = (lrTiles, lrObjects, lrItems, lrMonsters);
public type
TTiledObject = class(TObject)
private
public
Image: TPNGImage;
Name: string;
TileType: string;
Strength: Integer;
Dexterity: Integer;
Intellect: Integer;
Perception: Integer;
Protection: Integer;
Reach: Integer;
Level: Integer;
Exp: Integer;
Life: Integer;
MinDam: Integer;
MaxDam: Integer;
Radius: Integer;
Passable: Boolean;
Transparent: Boolean;
constructor Create;
destructor Destroy; override;
end;
public
FMap: array [TLayerEnum] of TLayer;
Firstgid: array [TLayerEnum] of Integer;
TiledObject: array of TTiledObject;
constructor Create(AOwner: TComponent);
destructor Destroy; override;
procedure LoadFromFile(const FileName: string);
property Width: Integer read FWidth;
property Height: Integer read FHeight;
property TileSize: Integer read FTileSize;
property Name: string read FName;
property Level: Integer read FLevel;
function GetTileType(const L: TLayerEnum; const X, Y: Integer): string;
end;
implementation
uses
System.SysUtils,
Math,
Utils,
Xml.XMLDoc,
Xml.XMLIntf,
System.IOUtils,
Dialogs,
Mods;
{ TTiledMap }
constructor TTiledMap.Create(AOwner: TComponent);
begin
FOwner := AOwner;
FWidth := 100;
FHeight := 100;
FTileSize := 32;
FLevel := 0;
FName := '';
end;
destructor TTiledMap.Destroy;
var
I: Integer;
begin
for I := 0 to High(TiledObject) do
FreeAndNil(TiledObject[I]);
inherited;
end;
function TTiledMap.GetTileType(const L: TLayerEnum; const X, Y: Integer): string;
begin
Result := '';
if (FMap[L][X][Y] > 0) then
Result := TiledObject[FMap[L][X][Y]].TileType;
end;
procedure TTiledMap.LoadFromFile(const FileName: string);
var
XMLDoc: TXMLDocument;
Node: IXMLNode;
S, LayerName: string;
Section: string;
I, Count, ID: Integer;
procedure LoadLayer(L: TLayerEnum);
var
X, Y: Integer;
SL: TStringList;
V: TArray<string>;
begin
SetLength(FMap[L], FWidth, FHeight);
Node := XMLDoc.DocumentElement.ChildNodes[I].ChildNodes['data'];
SL := TStringList.Create;
SL.Text := Trim(Node.Text);
for Y := 0 to FHeight - 1 do
begin
V := SL[Y].Split([',']);
for X := 0 to FWidth - 1 do
FMap[L][X][Y] := StrToIntDef(V[X], 0) - 1;
end;
FreeAndNil(SL);
end;
procedure LoadTileset(const FileName: string);
var
XMLDoc: TXMLDocument;
Node, NodeProps, NodeProp: IXMLNode;
I, J, Count, PropCount: Integer;
Name, Value, TileType: string;
begin
XMLDoc := TXMLDocument.Create(FOwner);
XMLDoc.LoadFromFile(FileName);
try
Count := XMLDoc.DocumentElement.ChildNodes.Count;
for I := 0 to Count - 1 do
begin
Section := TPath.GetFileNameWithoutExtension(FileName);
Node := XMLDoc.DocumentElement.ChildNodes[I];
if Node.NodeName = 'tile' then
begin
TileType := Trim(Node.Attributes['type']);
NodeProps := Node.ChildNodes['properties'];
PropCount := NodeProps.ChildNodes.Count;
Node := Node.ChildNodes['image'];
SetLength(TiledObject, ID + 1);
TiledObject[ID] := TTiledObject.Create;
TiledObject[ID].TileType := TileType;
TiledObject[ID].Image.LoadFromFile(GMods.GetPath('', Section + '\' + Trim(Node.Attributes['source'])));
for J := 0 to PropCount - 1 do
begin
NodeProp := NodeProps.ChildNodes[J];
Name := NodeProp.Attributes['name'];
Value := NodeProp.Attributes['value'];
if (Name = 'name') then
TiledObject[ID].Name := Trim(Value);
if (Section = 'tiles') then
begin
if (Name = 'passable') then
TiledObject[ID].Passable := StrToBoolDef(Value, False);
if (Name = 'transparent') then
TiledObject[ID].Transparent := StrToBoolDef(Value, False);
end;
if Section = 'objects' then
begin
if (Name = 'passable') then
TiledObject[ID].Passable := StrToBoolDef(Value, False);
if (Name = 'transparent') then
TiledObject[ID].Transparent := StrToBoolDef(Value, False);
end;
if Section = 'monsters' then
begin
if (Name = 'strength') then
TiledObject[ID].Strength := StrToIntDef(Value, 1);
if (Name = 'dexterity') then
TiledObject[ID].Dexterity := StrToIntDef(Value, 1);
if (Name = 'intellect') then
TiledObject[ID].Intellect := StrToIntDef(Value, 1);
if (Name = 'perception') then
TiledObject[ID].Perception := StrToIntDef(Value, 1);
if (Name = 'protection') then
TiledObject[ID].Protection := StrToIntDef(Value, 0);
if (Name = 'reach') then
TiledObject[ID].Reach := StrToIntDef(Value, 0);
if (Name = 'level') then
TiledObject[ID].Level := StrToIntDef(Value, 1);
if (Name = 'exp') then
TiledObject[ID].Exp := StrToIntDef(Value, 0);
if (Name = 'life') then
TiledObject[ID].Life := StrToIntDef(Value, 5);
if (Name = 'radius') then
TiledObject[ID].Radius := StrToIntDef(Value, 1);
if (Name = 'min_damage') then
TiledObject[ID].MinDam := EnsureRange(StrToIntDef(Value, 1), 1, 250);
if (Name = 'max_damage') then
TiledObject[ID].MaxDam := EnsureRange(StrToIntDef(Value, 2), 2, 255);
end;
end;
Inc(ID);
end;
end;
finally
FreeAndNil(XMLDoc);
end;
end;
procedure LoadProperties(Node: IXMLNode);
var
N: IXMLNode;
I: Integer;
Name, Value: string;
begin
for I := 0 to Node.ChildNodes.Count - 1 do
begin
N := Node.ChildNodes[I];
Name := Trim(N.Attributes['name']);
Value := Trim(N.Attributes['value']);
if Name = 'Name' then
FName := Trim(Value);
if Name = 'Level' then
FLevel := StrToIntDef(Value, 0);
end;
end;
begin
ID := 0;
XMLDoc := TXMLDocument.Create(FOwner);
XMLDoc.LoadFromFile(GMods.GetPath('maps', FileName));
try
FTileSize := StrToIntDef(XMLDoc.DocumentElement.Attributes['tilewidth'], 32);
FWidth := StrToIntDef(XMLDoc.DocumentElement.Attributes['width'], 100);
FHeight := StrToIntDef(XMLDoc.DocumentElement.Attributes['height'], 100);
Count := XMLDoc.DocumentElement.ChildNodes.Count;
for I := 0 to Count - 1 do
begin
Node := XMLDoc.DocumentElement.ChildNodes[I];
if Node.NodeName = 'properties' then
begin
LoadProperties(Node);
Continue;
end;
if Node.NodeName = 'tileset' then
begin
S := GMods.GetPath('maps', Trim(Node.Attributes['source']));
Section := TPath.GetFileNameWithoutExtension(S);
if Section = 'tiles' then
Firstgid[lrTiles] := StrToInt(Trim(Node.Attributes['firstgid']));
if Section = 'objects' then
Firstgid[lrObjects] := StrToInt(Trim(Node.Attributes['firstgid']));
if Section = 'items' then
Firstgid[lrItems] := StrToInt(Trim(Node.Attributes['firstgid']));
if Section = 'monsters' then
Firstgid[lrMonsters] := StrToInt(Trim(Node.Attributes['firstgid']));
LoadTileset(S);
Continue;
end;
if Node.NodeName = 'layer' then
begin
LayerName := Trim(Node.Attributes['name']);
if (LayerName = 'tiles') then
LoadLayer(lrTiles);
if (LayerName = 'objects') then
LoadLayer(lrObjects);
if (LayerName = 'items') then
LoadLayer(lrItems);
if (LayerName = 'monsters') then
LoadLayer(lrMonsters);
end;
end;
finally
FreeAndNil(XMLDoc);
end;
end;
{ TTiledMap.TTiledObject }
constructor TTiledMap.TTiledObject.Create;
begin
Image := TPNGImage.Create;
end;
destructor TTiledMap.TTiledObject.Destroy;
begin
FreeAndNil(Image);
inherited;
end;
end.
|
unit Optimizer.Indexer;
interface
uses
SysUtils,
OS.EnvironmentVariable, Optimizer.Template, Global.LanguageString,
OS.ProcessOpener, Registry.Helper;
type
TIndexerOptimizer = class(TOptimizationUnit)
public
function IsOptional: Boolean; override;
function IsCompatible: Boolean; override;
function IsApplied: Boolean; override;
function GetName: String; override;
procedure Apply; override;
procedure Undo; override;
end;
implementation
function TIndexerOptimizer.IsOptional: Boolean;
begin
exit(true);
end;
function TIndexerOptimizer.IsCompatible: Boolean;
begin
exit(true);
end;
function TIndexerOptimizer.IsApplied: Boolean;
begin
result := false;
if Win32MajorVersion = 6 then
begin
result :=
(NSTRegistry.GetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SYSTEM\CurrentControlSet\services\WSearch',
'Start')) = 4);
end
else if Win32MajorVersion = 5 then
begin
result :=
(NSTRegistry.GetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SYSTEM\CurrentControlSet\services\CiSvc',
'Start')) = 4);
end;
end;
function TIndexerOptimizer.GetName: String;
begin
exit(CapOptIndex[CurrLang]);
end;
procedure TIndexerOptimizer.Apply;
var
ProcOutput: String;
begin
if Win32MajorVersion = 6 then
begin
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SYSTEM\CurrentControlSet\services\WSearch', 'Start'), 4);
ProcOutput :=
string(ProcessOpener.OpenProcWithOutput(EnvironmentVariable.WinDrive,
'net stop WSearch'));
end
else if Win32MajorVersion = 5 then
begin
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SYSTEM\CurrentControlSet\services\CiSvc', 'Start'), 4);
ProcOutput :=
string(ProcessOpener.OpenProcWithOutput(EnvironmentVariable.WinDrive,
'net stop CiSvc'));
end;
end;
procedure TIndexerOptimizer.Undo;
var
ProcOutput: String;
begin
if Win32MajorVersion = 6 then
begin
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SYSTEM\CurrentControlSet\services\WSearch', 'Start'), 2);
ProcOutput :=
string(ProcessOpener.OpenProcWithOutput(EnvironmentVariable.WinDrive,
'net start WSearch'));
end
else if Win32MajorVersion = 5 then
begin
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew(
'LM', 'SYSTEM\CurrentControlSet\services\CiSvc', 'Start'), 2);
ProcOutput :=
string(ProcessOpener.OpenProcWithOutput(EnvironmentVariable.WinDrive,
'net start CiSvc'));
end;
end;
end.
|
// Copyright 2021 Darian Miller, Licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// More info: www.radprogrammer.com
unit radRTL.Base32Encoding;
interface
uses
System.SysUtils;
type
TBase32 = class
public const
Dictionary:AnsiString = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; // 32 characters, max Base2 of 5 digits '11111' (Base32 encoding uses 5-bit groups)
PadCharacter:Integer = 61; // Ord('=');
public
class function Encode(const pPlainText:string):string; overload;
class function Encode(const pPlainText:TBytes):TBytes; overload;
class function Encode(const pPlainText:Pointer; const pDataLength:Integer):TBytes; overload;
class function Decode(const pCipherText:string):string; overload;
class function Decode(const pCipherText:TBytes):TBytes; overload;
class function Decode(const pCipherText:Pointer; const pDataLength:Integer):TBytes; overload;
end;
implementation
uses
radRTL.BitUtils;
class function TBase32.Encode(const pPlainText:string):string;
begin
// always encode UTF8 by default to match most implementations in the wild
Result := TEncoding.UTF8.GetString(Encode(TEncoding.UTF8.GetBytes(pPlainText)));
end;
class function TBase32.Encode(const pPlainText:TBytes):TBytes;
var
vInputLength:Integer;
begin
SetLength(Result, 0);
vInputLength := Length(pPlainText);
if vInputLength > 0 then
begin
Result := Encode(@pPlainText[0], vInputLength);
end;
end;
class function TBase32.Encode(const pPlainText:Pointer; const pDataLength:Integer):TBytes;
var
vBuffer:Integer;
vBitsInBuffer:Integer;
vDictionaryIndex:Integer;
vFinalPadBits:Integer;
vSourcePosition:Integer;
vResultPosition:Integer;
i:Integer;
vPadCharacters:Integer;
begin
SetLength(Result, 0);
if pDataLength > 0 then
begin
// estimate max bytes to be used (excess trimmed below)
SetLength(Result, Trunc((pDataLength / 5) * 8) + 6 + 1); // 8 bytes out for every 5 in, +6 padding (at most), +1 for partial trailing bits if needed
vBuffer := PByteArray(pPlainText)[0];
vBitsInBuffer := 8;
vSourcePosition := 1;
vResultPosition := 0;
while ((vBitsInBuffer > 0) or (vSourcePosition < pDataLength)) do
begin
if (vBitsInBuffer < 5) then // fill buffer up to 5 bits at least for next (possibly final) character
begin
if (vSourcePosition < pDataLength) then
begin
// Combine the next byte with the unused bits of the last byte
vBuffer := (vBuffer shl 8) or PByteArray(pPlainText)[vSourcePosition];
vBitsInBuffer := vBitsInBuffer + 8;
vSourcePosition := vSourcePosition + 1;
end
else
begin
vFinalPadBits := 5 - vBitsInBuffer;
vBuffer := vBuffer shl vFinalPadBits;
vBitsInBuffer := vBitsInBuffer + vFinalPadBits;
end;
end;
// Map 5-bits collected in our buffer to a Base32 encoded character
vDictionaryIndex := $1F and (vBuffer shr (vBitsInBuffer - 5)); // $1F mask = 00011111 (last 5 are 1)
vBitsInBuffer := vBitsInBuffer - 5;
vBuffer := ExtractLastBits(vBuffer, vBitsInBuffer); // zero out bits we just mapped
Result[vResultPosition] := Ord(TBase32.Dictionary[vDictionaryIndex + 1]);
vResultPosition := vResultPosition + 1;
end;
// pad result based on the number of quantums received (should be same as: "Length(pPlainText)*BitsPerByte mod BitsPerQuantum of" 8:16:24:32:)
case pDataLength mod 5 of
1:
vPadCharacters := 6;
2:
vPadCharacters := 4;
3:
vPadCharacters := 3;
4:
vPadCharacters := 1;
else
vPadCharacters := 0;
end;
for i := 1 to vPadCharacters do
begin
Result[vResultPosition + i - 1] := TBase32.PadCharacter;
end;
// trim result to actual bytes used
SetLength(Result, vResultPosition + vPadCharacters);
end;
end;
class function TBase32.Decode(const pCipherText:string):string;
begin
// always decode UTF8 by default to match most implementations in the wild
Result := TEncoding.UTF8.GetString(Decode(TEncoding.UTF8.GetBytes(pCipherText)));
end;
class function TBase32.Decode(const pCipherText:TBytes):TBytes;
var
vInputLength:Integer;
begin
SetLength(Result, 0);
vInputLength := Length(pCipherText);
if vInputLength > 0 then
begin
Result := Decode(@pCipherText[0], vInputLength);
end;
end;
class function TBase32.Decode(const pCipherText:Pointer; const pDataLength:Integer):TBytes;
var
vBuffer:Integer;
vBitsInBuffer:Integer;
vDictionaryIndex:Integer;
vBase32Char:AnsiChar;
vSourcePosition:Integer;
vResultPosition:Integer;
begin
SetLength(Result, 0);
if pDataLength > 0 then
begin
// estimate max bytes to be used (excess trimmed below)
SetLength(Result, Trunc(pDataLength / 8 * 5)); // 5 bytes out for every 8 input
vSourcePosition := 0;
vBuffer := 0;
vBitsInBuffer := 0;
vResultPosition := 0;
repeat
vBase32Char := AnsiChar(PByteArray(pCipherText)[vSourcePosition]);
vDictionaryIndex := Pos(vBase32Char, TBase32.Dictionary); // todo: support case insensitive decoding?
if vDictionaryIndex = 0 then
begin
// todo: Consider failing on invalid characters with Exit(EmptyStr) or Exception
// For now, just skip all invalid characters.
// If removing this general skip, potentially add intentional skip for '=', ' ', #9, #10, #13, '-'
// And perhaps auto-correct commonly mistyped characters (e.g. replace '0' with 'O')
vSourcePosition := vSourcePosition + 1;
Continue;
end;
vDictionaryIndex := vDictionaryIndex - 1; // POS result is 1-based
vBuffer := vBuffer shl 5; // Expand buffer to add next 5-bit group
vBuffer := vBuffer or vDictionaryIndex; // combine the last bits collected and the next 5-bit group (Note to self: No mask needed on OR index as its known to be within range due to fixed dictionary size)
vBitsInBuffer := vBitsInBuffer + 5;
if vBitsInBuffer >= 8 then // Now able to fully extract an 8-bit decoded character from our bit buffer
begin
vBitsInBuffer := vBitsInBuffer - 8;
Result[vResultPosition] := vBuffer shr vBitsInBuffer; // shr to hide remaining buffered bits to be used in next iteration
vResultPosition := vResultPosition + 1;
vBuffer := ExtractLastBits(vBuffer, vBitsInBuffer); // zero out bits already extracted from buffer
end;
vSourcePosition := vSourcePosition + 1;
until vSourcePosition >= pDataLength; // NOTE: unused trailing bits, if any, are discarded (as is done in other common implementations)
// trim result to actual bytes used (strip off preallocated space for unused, skipped input characters)
SetLength(Result, vResultPosition);
end;
end;
(*
Note: https://stackoverflow.com/questions/37893325/difference-betweeen-rfc-3548-and-rfc-4648 (TLDR:minor edits)
sample reference code:
(Archived) https://github.com/google/google-authenticator (Blackberry/iOS)
(Archived) https://github.com/google/google-authenticator-android
https://github.com/google/google-authenticator-libpam/blob/0b02aadc28ac261b6c7f5785d2f7f36b3e199d97/src/base32_prog.c
https://github.com/freeotp/freeotp-android/blob/master/app/src/main/java/com/google/android/apps/authenticator/Base32String.java#L129
FreeOTP uses this repo for iOS: https://github.com/norio-nomura/Base32
base32 Alphabet values:
A 0
B 1
C 2
D 3
E 4
F 5
G 6
H 7
I 8
J 9
K 10
L 11
M 12
N 13
O 14
P 15
Q 16
R 17
S 18
T 19
U 20
V 21
W 22
X 23
Y 24
Z 25
2 26
3 27
4 28
5 29
6 30
7 31
*)
end.
|
{***********************************************************************
Unit gfx_colors.PAS v1.2 0801
(c) by Andreas Moser, amoser@amoser.de
gfx_colors is part of the gfx_library collection
You may use this sourcecode for your freewareproducts.
You may modify this source-code for your own use.
You may recompile this source-code for your own use.
All functions, procedures and classes may NOT be used in commercial
products without the permission of the author. For parts of this library
not written by me, you have to ask for permission by their
respective authors.
Disclaimer of warranty: "This software is supplied as is. The author
disclaims all warranties, expressed or implied, including, without
limitation, the warranties of merchantability and of fitness for any
purpose. The author assumes no liability for damages, direct or
consequential, which may result from the use of this software."
All brand and product names are marks or registered marks of their
respective companies.
Please report bugs to:
Andreas Moser amoser@amoser.de
Histogram and descriptive statistic algorythms are based on or taken from the sources written by
Earl F. Glynn, efg's computer lab
********************************************************************************}
unit gfx_colors;
interface
uses
Wintypes,
Messages,
ExtCtrls,
Windows,
Graphics,
gfx_basedef,
StdCtrls,
SysUtils;
{$R-}
// -----------------------------------------------------------------------------
//
// Statistics
//
// -----------------------------------------------------------------------------
const
NAN = MaxDouble / 2.0;
type
TDescriptiveStatistics =
class(TObject)
protected
FCount : INTEGER;
FMaxValue : DOUBLE;
FMinValue : DOUBLE;
FSum : DOUBLE;
FSumOfSquares: DOUBLE;
public
property Count : INTEGER read FCount;
property MaxValue: DOUBLE read FMaxValue;
property MinValue: DOUBLE read FMinValue;
property Sum : DOUBLE read FSum;
constructor Create;
procedure NextValue(const x: DOUBLE);
function MeanValue : DOUBLE;
function StandardDeviation: DOUBLE;
procedure ResetValues;
end;
// -----------------------------------------------------------------------------
//
// ColorQuantizer
//
// -----------------------------------------------------------------------------
type
TOctreeNode = class; // forward definition so TReducibleNodes can be declared
TReducibleNodes = array[0..7] OF TOctreeNode;
TOctreeNode =
class(TObject)
IsLeaf : BOOLEAN;
PixelCount : INTEGER;
RedSum : INTEGER;
GreenSum : INTEGER;
BlueSum : INTEGER;
Next : TOctreeNode;
Child : TReducibleNodes;
constructor Create (const Level : INTEGER;
const ColorBits : INTEGER;
var LeafCount : INTEGER;
var ReducibleNodes: TReducibleNodes);
destructor Destroy; override;
end;
TColorQuantizer =
class(TOBject)
private
FTree : TOctreeNode;
FLeafCount : INTEGER;
FReducibleNodes: TReducibleNodes;
FMaxColors : INTEGER;
FColorBits : INTEGER;
PROTECTED
procedure AddColor(var Node : TOctreeNode;
const r,g,b : BYTE;
const ColorBits : INTEGER;
const Level : INTEGER;
var LeafCount : INTEGER;
var ReducibleNodes: TReducibleNodes);
procedure DeleteTree(var Node: TOctreeNode);
procedure GetPaletteColors(const Node : TOctreeNode;
var RGBQuadarray: TRGBQuadarray;
var Index : INTEGER);
procedure ReduceTree(const ColorBits: INTEGER;
var LeafCount: INTEGER;
var ReducibleNodes: TReducibleNodes);
public
constructor Create(const MaxColors: INTEGER; const ColorBits: INTEGER);
destructor Destroy; override;
procedure GetColorTable(var RGBQuadarray: TRGBQuadarray);
function ProcessImage(const Handle: THandle): BOOLEAN;
property ColorCount: INTEGER READ FLeafCount;
end;
// -----------------------------------------------------------------------------
//
// ColorSpace
//
// -----------------------------------------------------------------------------
type
THistogram = array[0..255] of INTEGER;
TRGBStatistics =
class(TObject)
protected
FStatsRed : TDescriptiveStatistics;
FStatsGreen: TDescriptiveStatistics;
FStatsBlue : TDescriptiveStatistics;
function PixelCount: INTEGER;
public
property Count: INTEGER read PixelCount;
constructor Create;
destructor Destroy; override;
procedure NextRGBTriple(const rgb: TRGBTriple);
procedure ResetValues;
end;
{ ---------------------------------------------------------------- }
// Bitmaps
procedure PrintBitmap(Canvas: TCanvas; DestRect: TRect; Bitmap: TBitmap);
function GetBitmapDimensionsString(const Bitmap: TBitmap): string;
function GetColorPlaneString(const ColorPlane: TColorPlane): string;
function GetPixelformatString(const Pixelformat: TPixelformat): string;
// Image Processing
procedure GetImagePlane (const ColorPlane: TColorPlane;
const ColorOutput: BOOLEAN;
const OriginalBitmap: TBitmap;
var ProcessedBitmap: TBitmap);
// Bitmap Statistics
procedure GetBitmapStatistics(const Bitmap: TBitmap;
const ColorPlane: TColorPlane;
var Statistics: TDescriptiveStatistics);
procedure GetHistogram(const Bitmap: TBitmap;
const ColorPlane: TColorPlane;
var Histogram: THistogram);
procedure DrawHistogram(const ColorPlane: TColorPlane;
const Histogram: THistogram;
const aCanvas: TCanvas;
const LineColor:TColor; //** Added
const TextColor:TColor); //** Added
//------------------------------------------------------------
// Palette
//------------------------------------------------------------
const
clMoneyGreen = TColor($C0DCC0); // Color "8" RGB: 192 220 192
clSkyBlue = TColor($F0CAA6); // Color "9" RGB: 166 202 240
clCream = TColor($F0FBFF); // Color "246" RGB: 255 251 240
clMediumGray = TColor($A4A0A0); // Color "247" RGB: 160 160 164
NonDitherColors: array[0..19] OF TColor =
(clBlack, clMaroon, clGreen, clOlive, clNavy, clPurple, clTeal, clSilver,
clMoneyGreen, clSkyblue, clCream, clMediumGray,
clGray, clRed, clLime, clYellow, clBlue, clFuchsia, clAqua, clWhite);
const PaletteDataSize256 = SizeOf(TLogPalette)+(255*SizeOf(TPaletteEntry));
type
TGetBitmapCallback = procedure (const Counter: INTEGER;
var OK: BOOLEAN; var Bitmap: TBitmap);
const
PaletteVersion = $0300;
function GetColorDepth: INTEGER;
function GetPixelDepth: INTEGER;
function GetDesktopPalette: hPalette;
function GetGradientPalette(const red, green, blue: BOOLEAN): hPalette;
function CreateOptimizedPaletteforSingleBitmap(const Bitmap: TBitmap;
const ColorBits: INTEGER): hPalette;
function CreateOptimizedPaletteforManyBitmaps(const CallBack: TGetBitmapCallback;
const ColorBits: INTEGER): hPalette;
function IsPaletteDevice: BOOLEAN;
procedure LogicalPaletteToRGBQuad(const Start : WORD;
const Count : WORD;
var LogicalPalette: TPaletteEntries;
var RGBQuad : TRGBQuadarray);
function ReadAndCreatePaletteFromFractIntFile(const Filename: string): hPalette;
procedure WMQueryNewPalette(formcanvashandle:THandle; PaletteHandle: hPalette;
var Msg: TWMQueryNewPalette);
procedure WMPaletteChanged(formcanvashandle:THandle;formhandle:THandle; PaletteHandle: hPalette;
var Msg: TWMPaletteChanged);
function ReadPaletteFromFile(FileName:String):HPalette;
procedure ApplyPaletteToGraphic(Palette:Hpalette;Graphic:TGraphic;ChangePixelformat:Boolean;NewPixelformat:TPixelformat);
procedure ApplyPaletteToDC(DC:HDC;Palette:HPalette);
function LoadOptimizedPalette:HPalette;
procedure PaletteDefaults(PaletteEntries:TPaletteEntries);
procedure MakeGreyPalette(MaxLogPalette:TMaxLogPalette);
procedure MakeStandardPalette(MaxLogPalette:TMaxLogPalette);
var
PaletteColorCount: INTEGER;
const stdPalette:array[0..15,1..3] Of Byte = (
{Black} (0 ,0 ,0 ),
{Blue} (0 ,0 ,32),
{Green} (0 ,32 ,0 ),
{Cyan} (0 ,32 ,32),
{Red} (32 ,0 ,0 ),
{Magenta} (32 ,0 ,32),
{Brown} (32 ,32 ,0 ),
{Light Gray} (42 ,42 ,42),
{Dark Gray} (21 ,21 ,21),
{Light Blue} (0 ,0 ,63),
{Light Green} (0 ,63 ,0 ),
{Light Cyan} (0 ,63 ,63),
{Light Red} (63 ,0 ,0 ),
{Light Magenta} (63 ,0 ,63),
{Yellow} (63 ,63 ,0 ),
{Bright White} (63 ,63 ,63));
const optPal:array[0..255, 0..2] of byte =
((0,0,0 ), (128,0,0 ), (0,128,0 ), (128,128,0 ), (0,0,128 ),
(128,0,128 ), (0,128,128 ), (192,192,192), (52,66,82 ), (79,101,125 ),
(6,7,6 ), (7,21,8 ), (12,18,17 ), (24,11,10 ), (21,14,18 ),
(17,23,13 ), (21,18,16 ), (5,19,46 ), (20,38,17 ), (21,41,53 ),
(41,10,9 ), (39,23,12 ), (40,20,21 ), (55,11,12 ), (56,22,11 ),
(59,27,22 ), (49,43,19 ), (46,48,44 ), (4,26,80 ), (8,41,85 ),
(18,53,112 ), (40,52,75 ), (39,60,98 ), (51,69,13 ), (55,72,38 ),
(58,100,49 ), (23,72,81 ), (20,74,101 ), (56,75,80 ), (41,73,114 ),
(59,108,75 ), (51,100,122 ), (70,10,11 ), (72,24,10 ), (71,26,29 ),
(86,7,14 ), (87,11,16 ), (85,26,13 ), (87,26,20 ), (81,45,20 ),
(75,42,37 ), (71,44,57 ), (72,55,36 ), (74,58,54 ), (88,44,37 ),
(88,56,38 ), (88,60,56 ), (110,13,12 ), (119,26,39 ), (102,43,15 ),
(102,41,26 ), (100,55,15 ), (104,53,24 ), (121,39,17 ), (126,63,13 ),
(105,44,37 ), (107,40,53 ), (106,57,39 ), (104,58,52 ), (118,43,36 ),
(120,42,58 ), (121,52,39 ), (118,58,56 ), (72,55,65 ), (76,78,23 ),
(83,72,44 ), (79,104,44 ), (105,69,19 ), (108,70,38 ), (102,69,50 ),
(103,88,39 ), (109,82,52 ), (119,70,43 ), (121,74,55 ), (123,85,43 ),
(121,83,51 ), (115,96,27 ), (112,104,46 ), (84,76,71 ), (77,87,114 ),
(85,111,77 ), (82,108,116 ), (108,84,69 ), (109,89,111 ), (105,115,86 ),
(106,115,118), (38,59,128 ), (31,73,148 ), (48,84,144 ), (55,110,144 ),
(78,104,143 ), (83,112,164 ), (108,119,143), (99,121,173 ), (112,137,37 ),
(90,132,74 ), (83,137,100 ), (103,135,89 ), (112,141,112), (111,163,111),
(86,132,137 ), (80,134,171 ), (119,139,139), (109,140,176), (122,162,134),
(127,164,187), (126,140,194), (144,22,14 ), (142,28,41 ), (146,41,24 ),
(133,44,45 ), (136,37,62 ), (130,59,43 ), (136,57,52 ), (157,44,57 ),
(152,55,32 ), (152,60,60 ), (168,28,19 ), (169,40,28 ), (176,52,41 ),
(142,56,69 ), (171,57,71 ), (156,77,4 ), (139,79,54 ), (143,110,21 ),
(141,102,52 ), (163,85,14 ), (171,82,54 ), (171,113,13 ), (169,111,47 ),
(137,77,77 ), (135,74,85 ), (138,89,72 ), (130,95,92 ), (152,75,69 ),
(150,88,68 ), (144,103,73 ), (139,115,109), (170,87,75 ), (174,109,78 ),
(177,112,105), (198,26,24 ), (204,62,4 ), (204,41,37 ), (245,56,57 ),
(207,75,61 ), (205,122,12 ), (211,124,47 ), (224,94,24 ), (203,82,85 ),
(206,87,102 ), (199,115,86 ), (208,115,103), (246,80,77 ), (236,119,105),
(147,118,142), (143,122,167), (168,123,152), (231,118,130), (152,131,49 ),
(181,134,25 ), (182,144,35 ), (151,133,84 ), (149,140,115), (143,169,71 ),
(149,166,112), (174,137,87 ), (173,143,115), (179,170,111), (208,144,18 ),
(202,135,51 ), (215,168,27 ), (218,183,44 ), (237,153,10 ), (229,145,43 ),
(248,180,9 ), (203,134,89 ), (209,138,105), (208,168,83 ), (214,180,109),
(228,146,84 ), (231,146,117), (239,173,75 ), (240,170,124), (215,217,17 ),
(222,199,52 ), (251,205,6 ), (246,203,46 ), (234,230,10 ), (251,228,8 ),
(251,230,48 ), (251,246,43 ), (204,198,92 ), (214,197,107), (241,205,78 ),
(240,204,111), (251,231,80 ), (250,238,110), (143,147,144), (148,164,156),
(149,174,178), (177,146,142), (170,140,165), (177,168,148), (178,177,174),
(133,150,202), (145,176,210), (169,186,206), (168,183,226), (181,199,145),
(172,197,176), (180,201,205), (177,206,236), (208,142,138), (194,152,186),
(209,171,144), (210,177,173), (236,152,141), (239,171,139), (241,180,175),
(204,179,202), (224,182,212), (210,196,150), (213,201,176), (248,203,143),
(247,203,170), (248,232,143), (250,247,176), (210,203,205), (207,213,231),
(221,230,200), (202,229,240), (243,208,201), (228,215,232), (244,238,209),
(247,246,238), (162,177,196), (160,160,164), (128,128,128), (255,0,0 ),
(0,255,0 ), (255,255,0 ), (0,0,255 ), (255,0,255 ), (0,255,255 ),
(0,0,102 ));
//------------------------------------------------------------
// Splitting
//------------------------------------------------------------
procedure GetRedPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
procedure GetGreenPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
procedure GetBluePlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
procedure GetHuePlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
procedure GetSatPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
procedure GetValPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
procedure GetLigPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
implementation
//------------------------------------------------------------
// Statistics
//------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// Create
//
// -----------------------------------------------------------------------------
constructor TDescriptiveStatistics.Create;
begin
ResetValues
end {Create};
// -----------------------------------------------------------------------------
//
// NextValue
//
// -----------------------------------------------------------------------------
procedure TDescriptiveStatistics.NextValue (const x: DOUBLE);
begin
INC(FCount);
FSum := FSum + x;
FSumOfSquares := FSumOfSquares + x*x;
if x > FMaxValue
then FmaxValue := x;
if x < FMinValue
then FMinValue := x
end {NextNumber};
// -----------------------------------------------------------------------------
//
// MeanValue
//
// -----------------------------------------------------------------------------
function TDescriptiveStatistics.MeanValue: DOUBLE;
begin
if FCount = 0
then RESULT := NAN
else RESULT := FSum / FCount
end {MeanValue};
// -----------------------------------------------------------------------------
//
// StandardDeviation
//
// -----------------------------------------------------------------------------
function TDescriptiveStatistics.StandardDeviation: DOUBLE;
begin
if FCount < 2
then RESULT := NAN
else RESULT := SQRT( (FSumOfSquares - (FSum*FSum / FCount)) /
(FCount - 1) )
end {StandardDeviation};
// -----------------------------------------------------------------------------
//
// ResetValue
//
// -----------------------------------------------------------------------------
procedure TDescriptiveStatistics.ResetValues;
begin
FCount := 0;
FMinValue := MaxDouble;
FMaxValue := -MaxDouble;
FSum := 0.0;
FSumOfSquares := 0.0
end {ResetValues};
//------------------------------------------------------------
// Color Quantization
//------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// Create
//
// -----------------------------------------------------------------------------
constructor TOctreeNode.Create (const Level : INTEGER;
const ColorBits : INTEGER;
var LeafCount : INTEGER;
var ReducibleNodes: TReducibleNodes);
var
i: INTEGER;
begin
PixelCount := 0;
RedSum := 0;
GreenSum := 0;
BlueSum := 0;
for i := Low(Child) to High(Child) do
Child[i] := nil;
IsLeaf := (Level = ColorBits);
if IsLeaf
then begin
Next := nil;
INC(LeafCount);
end
else begin
Next := ReducibleNodes[Level];
ReducibleNodes[Level] := SELF
end
end {Create};
// -----------------------------------------------------------------------------
//
// Destroy
//
// -----------------------------------------------------------------------------
destructor TOctreeNode.Destroy;
var
i: INTEGER;
begin
for i := Low(Child) to High(Child) do
Child[i].Free
end {Destroy};
// -----------------------------------------------------------------------------
//
// Create
//
// -----------------------------------------------------------------------------
constructor TColorQuantizer.Create(const MaxColors: INTEGER; const ColorBits: INTEGER);
var
i: INTEGER;
begin
ASSERT (ColorBits <= 8);
FTree := nil;
FLeafCount := 0;
// Initialize all nodes even though only ColorBits+1 of them are needed
for i := Low(FReducibleNodes) to High(FReducibleNodes) do
FReducibleNodes[i] := nil;
FMaxColors := MaxColors;
FColorBits := ColorBits
end {Create};
// -----------------------------------------------------------------------------
//
// Destroy
//
// -----------------------------------------------------------------------------
destructor TColorQuantizer.Destroy;
begin
if FTree <> nil
then DeleteTree(FTree)
end {Destroy};
// -----------------------------------------------------------------------------
//
// GetColorTable
//
// -----------------------------------------------------------------------------
procedure TColorQuantizer.GetColorTable(var RGBQuadarray: TRGBQuadarray);
var
Index: INTEGER;
begin
Index := 0;
GetPaletteColors(FTree, RGBQuadarray, Index)
end {GetColorTable};
// -----------------------------------------------------------------------------
//
// ProcessImage
//
// -----------------------------------------------------------------------------
// Handles passed to ProcessImage should refer to DIB sections, not DDBs.
// In certain cases, specifically when it's called upon to process 1, 4, or
// 8-bit per pixel images on systems with palettized display adapters,
// ProcessImage can produce incorrect results if it's passed a handle to a
// DDB.
function TColorQuantizer.ProcessImage(const Handle: THandle): BOOLEAN;
const
MaxPixelCount = 1048576; // 2^20 shouldn't be much of a limit here
var
Bytes : INTEGER;
DIBSection: TDIBSection;
// Process 1, 4, or 8-bit DIB:
// The strategy here is to use GetDIBits to convert the image into
// a 24-bit DIB one scan line at a time. A pleasant side effect
// of using GetDIBits in this manner is that RLE-encoded 4-bit and
// 8-bit DIBs will be uncompressed.
// Implemented as in article, but doesn't work (yet) as I would expect.
procedure ProcessLowBitDIB;
var
BitmapInfo : TBitmapInfo;
DeviceContext: hDC;
i : INTEGER;
j : INTEGER;
ScanLine : pRGBarray;
begin
GetMem(ScanLine, 3*DIBSection.dsBmih.biWidth);
try
ZeroMemory(@BitmapInfo, SizeOf(BitmapInfo));
with BitmapInfo do
begin
bmiHeader.biSize := SizeOf(TBitmapInfo);
bmiHeader.biWidth := DIBSection.dsBmih.biWidth;
bmiHeader.biHeight := DIBSection.dsBmih.biHeight;
bmiHeader.biPlanes := 1;
bmiHeader.biBitCount := 24;
bmiHeader.biCompression := BI_RGB;
end;
DeviceContext := GetDC(0);
try
for j := 0 to DIBSection.dsBmih.biHeight-1 do
begin
GetDIBits (DeviceContext, Handle, j, 1, ScanLine, BitmapInfo, DIB_RGB_COLORS);
for i := 0 to DIBSection.dsBmih.biWidth-1 do
begin
with Scanline[i] do
AddColor(FTree, rgbtRed, rgbtGreen, rgbtBlue,
FColorBits, 0, FLeafCount, FReducibleNodes);
while FLeafCount > FMaxColors do
ReduceTree(FColorbits, FLeafCount, FReducibleNodes)
end
end
finally
ReleaseDC(0, DeviceContext);
end
finally
FreeMem(ScanLine)
end
end {ProcessLowBitDIB};
procedure Process16BitDIB;
begin
// Not yet implemented
end {Process16BitDIB};
procedure Process24BitDIB;
var
i : INTEGER;
j : INTEGER;
ScanLine: pRGBarray;
begin
Scanline := pRGBarray(DIBSection.dsBm.bmBits);
for j := 0 to DIBSection.dsBmih.biHeight-1 do
begin
for i := 0 to DIBSection.dsBmih.biWidth-1 do
begin
with Scanline[i] DO
AddColor(FTree, rgbtRed, rgbtGreen, rgbtBlue,
FColorBits, 0, FLeafCount, FReducibleNodes);
WHILE FLeafCount > FMaxColors DO
ReduceTree(FColorbits, FLeafCount, FReducibleNodes)
end;
ScanLine := pRGBarray(INTEGER(Scanline) + DIBSection.dsBm.bmWidthBytes);
end
end {Process24BitDIB};
procedure Process32BitDIB;
begin
// Not yet implemented
end {Process32BitDIB};
begin
RESULT := FALSE;
Bytes := GetObject(Handle, SizeOF(DIBSection), @DIBSection);
IF Bytes > 0 // Invalid Bitmap if Bytes = 0
THEN begin
// PadBytes := DIBSECTION.dsBm.bmWidthBytes -
// (((DIBSection.dsBmih.biWidth * DIBSection.dsBmih.biBitCount) + 7) DIV 8);
ASSERT (DIBSection.dsBmih.biHeight < MaxPixelCount);
ASSERT (DIBSection.dsBmih.biWidth < MaxPixelCount);
CASE DIBSection.dsBmih.biBitCount OF
1: ProcessLowBitDIB;
4: ProcessLowBitDIB;
8: ProcessLowBitDIB;
16: Process16bitDIB;
24: Process24bitDIB;
32: Process32bitDIB
else
// Do nothing. Default RESULT is already FALSE
end
end
end ;
// -----------------------------------------------------------------------------
//
// AddColor
//
// -----------------------------------------------------------------------------
procedure TColorQuantizer.AddColor(var Node : TOctreeNode;
const r,g,b : BYTE;
const ColorBits : INTEGER;
const Level : INTEGER;
var LeafCount : INTEGER;
var ReducibleNodes: TReducibleNodes);
const
Mask: array[0..7] OF BYTE = ($80, $40, $20, $10, $08, $04, $02, $01);
var
Index : INTEGER;
Shift : INTEGER;
begin
// If the node doesn't exist, create it.
IF Node = NIL
THEN Node := TOctreeNode.Create(Level, ColorBits, LeafCount, ReducibleNodes);
IF Node.IsLeaf
THEN begin
INC(Node.PixelCount);
INC(Node.RedSum, r);
INC(Node.GreenSum, g);
INC(Node.BlueSum, b)
end
else begin
// Recurse a level deeper if the node is not a leaf.
Shift := 7 - Level;
Index := (((r AND mask[Level]) SHR Shift) SHL 2) OR
(((g AND mask[Level]) SHR Shift) SHL 1) OR
((b AND mask[Level]) SHR Shift);
AddColor(Node.Child[Index], r, g, b, ColorBits, Level+1,
LeafCount, ReducibleNodes)
end
end ;
// -----------------------------------------------------------------------------
//
// DeleteTree
//
// -----------------------------------------------------------------------------
procedure TColorQuantizer.DeleteTree(var Node: TOctreeNode);
var
i : INTEGER;
begin
for i := Low(TReducibleNodes) TO High(TReducibleNodes) DO
begin
IF Node.Child[i] <> NIL
THEN DeleteTree(Node.Child[i]);
end;
Node.Free;
Node := NIL;
end;
// -----------------------------------------------------------------------------
//
// GetPaletteColors
//
// -----------------------------------------------------------------------------
procedure TColorQuantizer.GetPaletteColors(const Node : TOctreeNode;
var RGBQuadarray: TRGBQuadarray;
var Index : INTEGER);
var
i: INTEGER;
begin
if Assigned(Node) then IF Node.IsLeaf
THEN begin
with RGBQuadarray[Index] DO
begin
TRY
rgbRed := BYTE(Node.RedSum DIV Node.PixelCount);
rgbGreen := BYTE(Node.GreenSum DIV Node.PixelCount);
rgbBlue := BYTE(Node.BlueSum DIV Node.PixelCount)
EXCEPT
rgbRed := 0;
rgbGreen := 0;
rgbBlue := 0
end;
rgbReserved := 0
end;
INC(Index)
end
else begin
for i := Low(Node.Child) TO High(Node.Child) DO
begin
IF Node.Child[i] <> NIL
THEN GetPaletteColors(Node.Child[i], RGBQuadarray, Index)
end
end
end;
// -----------------------------------------------------------------------------
//
// ReduceTree
//
// -----------------------------------------------------------------------------
procedure TColorQuantizer.ReduceTree(const ColorBits: INTEGER;
var LeafCount: INTEGER;
var ReducibleNodes: TReducibleNodes);
var
BlueSum : INTEGER;
Children: INTEGER;
GreenSum: INTEGER;
i : INTEGER;
Node : TOctreeNode;
RedSum : INTEGER;
begin
// Find the deepest level containing at least one reducible node
i := Colorbits - 1;
WHILE (i > 0) AND (ReducibleNodes[i] = NIL) DO
DEC(i);
// Reduce the node most recently added to the list at level i.
Node := ReducibleNodes[i];
ReducibleNodes[i] := Node.Next;
RedSum := 0;
GreenSum := 0;
BlueSum := 0;
Children := 0;
for i := Low(ReducibleNodes) TO High(ReducibleNodes) DO
begin
IF Node.Child[i] <> NIL
THEN begin
INC(RedSum, Node.Child[i].RedSum);
INC(GreenSum, Node.Child[i].GreenSum);
INC(BlueSum, Node.Child[i].BlueSum);
INC(Node.PixelCount, Node.Child[i].PixelCount);
Node.Child[i].Free;
Node.Child[i] := NIL;
INC(Children)
end
end;
Node.IsLeaf := TRUE;
Node.RedSum := RedSum;
Node.GreenSum := GreenSum;
Node.BlueSum := BlueSum;
DEC(LeafCount, Children-1)
end;
//------------------------------------------------------------
// Colorspace
//------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// Create
//
// -----------------------------------------------------------------------------
constructor TRGBStatistics.Create;
begin
FStatsRed := TDescriptiveStatistics.Create;
FStatsGreen := TDescriptiveStatistics.Create;
FStatsBlue := TDescriptiveStatistics.Create;
FStatsRed.ResetValues;
FStatsGreen.ResetValues;
FStatsBlue.ResetValues
end;
// -----------------------------------------------------------------------------
//
// Destroy
//
// -----------------------------------------------------------------------------
destructor TRGBStatistics.Destroy;
begin
FStatsRed.Free;
FStatsGreen.Free;
FStatsBlue.Free
end;
// -----------------------------------------------------------------------------
//
// PixelCount
//
// -----------------------------------------------------------------------------
function TRGBStatistics.PixelCount;
begin
RESULT := FStatsRed.Count
end;
// -----------------------------------------------------------------------------
//
// NextRGBTriple
//
// -----------------------------------------------------------------------------
procedure TRGBStatistics.NextRGBTriple(const rgb: TRGBTriple);
begin
with rgb DO
begin
FStatsRed.NextValue(rgbtRed);
FStatsGreen.NextValue(rgbtGreen);
FStatsBlue.NextValue(rgbtBlue);
end
end;
// -----------------------------------------------------------------------------
//
// ResetValues
//
// -----------------------------------------------------------------------------
procedure TRGBStatistics.ResetValues;
begin
FStatsRed.ResetValues;
FStatsGreen.ResetValues;
FStatsBlue.ResetValues
end;
{== Bitmaps =======================================================}
// -----------------------------------------------------------------------------
//
// PrintBitmap
//
// -----------------------------------------------------------------------------
{Based on posting to borland.public.delphi.winapi by Rodney E Geraghty, 8/8/97.
Used to print bitmap on any Windows printer.}
procedure PrintBitmap(Canvas: TCanvas; DestRect: TRect; Bitmap: TBitmap);
var
BitmapHeader: pBitmapInfo;
BitmapImage : POINTER;
HeaderSize : DWOrd;
ImageSize : DWord;
begin
GetDIBSizes(Bitmap.Handle, HeaderSize, ImageSize);
GetMem(BitmapHeader, HeaderSize);
GetMem(BitmapImage, ImageSize);
TRY
GetDIB(Bitmap.Handle, Bitmap.Palette, BitmapHeader^, BitmapImage^);
StretchDIBits(Canvas.Handle,
DestRect.Left, DestRect.Top, {Destination Origin}
DestRect.Right - DestRect.Left, {Destination Width}
DestRect.Bottom - DestRect.Top, {Destination Height}
0, 0, {Source Origin}
Bitmap.Width, Bitmap.Height, {Source Width & Height}
BitmapImage,
TBitmapInfo(BitmapHeader^),
DIB_RGB_COLORS,
SRCCOPY)
FINALLY
FreeMem(BitmapHeader);
FreeMem(BitmapImage)
end
end;
// -----------------------------------------------------------------------------
//
// GetBitmapDimensionsString
//
// -----------------------------------------------------------------------------
function GetBitmapDimensionsString(const Bitmap: TBitmap): STRING;
begin
RESULT := IntToStr(Bitmap.Width) + ' by ' +
IntToStr(Bitmap.Height) + ' pixels by ' +
GetPixelformatString(Bitmap.Pixelformat) + ' color';
end;
// -----------------------------------------------------------------------------
//
// GetColorPlaneString
//
// -----------------------------------------------------------------------------
function GetColorPlaneString(const ColorPlane: TColorPlane): STRING;
begin
CASE ColorPlane OF
cpRGB: RESULT := 'RGB Composite';
cpRed: RESULT := 'Red';
cpGreen: RESULT := 'Green';
cpBlue: RESULT := 'Blue';
cpHueHSV: RESULT := 'Hue (HSV)';
cpSaturationHSV: RESULT := 'Saturation (HSV)';
cpValue: RESULT := 'Value (HSV)';
cpCyan: RESULT := 'Cyan';
cpMagenta: RESULT := 'Magenta';
cpYellow: RESULT := 'Yellow';
cpBlack: RESULT := 'Black (CMYK)';
cpIntensity: RESULT := 'RGB Intensity';
end
end;
// -----------------------------------------------------------------------------
//
// GetPixelFormatString
//
// -----------------------------------------------------------------------------
function GetPixelformatString(const Pixelformat: TPixelformat): STRING;
var
format: STRING;
begin
CASE Pixelformat OF
pfDevice: format := 'Device';
pf1bit: format := '1 bit';
pf4bit: format := '4 bit';
pf8bit: format := '8 bit';
pf15bit: format := '15 bit';
pf16bit: format := '16 bit';
pf24bit: format := '24 bit';
pf32bit: format := '32 bit'
else
format := 'Unknown';
end;
RESULT := format;
end;
{== Image Processing ==============================================}
// -----------------------------------------------------------------------------
//
// GetImagePlane
//
// -----------------------------------------------------------------------------
procedure GetImagePlane (const ColorPlane: TColorPlane;
const ColorOutput: BOOLEAN;
const OriginalBitmap: TBitmap;
var ProcessedBitmap: TBitmap);
var
HSV:THSVTriple;
CMYK:TCMYKQuad;
i : INTEGER;
Intensity : INTEGER;
j : INTEGER;
// L : INTEGER;
RowOriginal : pRGBarray;
RowProcessed: pRGBarray;
begin
IF OriginalBitmap.Pixelformat <> pf24bit
THEN RAISE EGraphicformat.Create('GetImageSpace: ' +
'Bitmap must be 24-bit color.');
{Step through each row of image.}
for j := OriginalBitmap.Height-1 downto 0 DO
begin
RowOriginal := pRGBarray(OriginalBitmap.Scanline[j]);
RowProcessed := pRGBarray(ProcessedBitmap.Scanline[j]);
for i := OriginalBitmap.Width-1 downto 0 DO
begin
CASE ColorPlane OF
cpRGB: IF ColorOutput
THEN AssignRGBTriple(RowProcessed[i], RowOriginal[i])
else begin
Intensity := RGBIntensity(RowOriginal[i]);
AssignRGBTriple(RowProcessed[i],
RGBTriple(Intensity, Intensity, Intensity))
end;
cpRed: IF ColorOutput
THEN AssignRGBTriple(RowProcessed[i],
RGBTriple(RowOriginal[i].rgbtRed, 0, 0))
else begin
Intensity := RowOriginal[i].rgbtRed;
AssignRGBTriple(RowProcessed[i],
RGBTriple(Intensity, Intensity, Intensity))
end;
cpGreen: IF ColorOutput
THEN AssignRGBTriple(RowProcessed[i],
RGBTriple(0, RowOriginal[i].rgbtGreen, 0))
else begin
Intensity := RowOriginal[i].rgbtGreen;
AssignRGBTriple(RowProcessed[i],
RGBTriple(Intensity, Intensity, Intensity))
end;
cpBlue: IF ColorOutput
THEN AssignRGBTriple(RowProcessed[i],
RGBTriple(0, 0, RowOriginal[i].rgbtBlue))
else begin
Intensity := RowOriginal[i].rgbtBlue;
AssignRGBTriple(RowProcessed[i],
RGBTriple(Intensity, Intensity, Intensity))
end;
cpHueHSV:
begin
RGBtoHSV(RowOriginal[i], HSV);
HSV.hsvHue := (255 * HSV.hsvHue) DIV 359;
{Shades of Hue}
AssignRGBTriple(RowProcessed[i], RGBTriple(HSV.hsvHue,HSV.hsvHue,HSV.hsvHue))
end;
cpSaturationHSV:
begin
RGBtoHSV(RowOriginal[i], HSV);
{Shades of Saturation}
AssignRGBTriple(RowProcessed[i], RGBTriple(HSV.hsvSaturation,HSV.hsvSaturation,HSV.hsvSaturation))
end;
cpValue:
begin
RGBtoHSV(RowOriginal[i], HSV);
{Shades of Value}
AssignRGBTriple(RowProcessed[i], RGBTriple(HSV.hsvValue,HSV.hsvValue,HSV.hsvValue))
end;
cpCyan:
begin
RGBtoCMYK(RowOriginal[i], CMYK);
{Shades of Value}
AssignRGBTriple(RowProcessed[i], RGBTriple(CMYK.cmykCyan,CMYK.cmykCyan,CMYK.cmykCyan))
end;
cpMagenta:
begin
RGBtoCMYK(RowOriginal[i], CMYK);
{Shades of Value}
AssignRGBTriple(RowProcessed[i], RGBTriple(CMYK.cmykMagenta,CMYK.cmykMagenta,CMYK.cmykMagenta))
end;
cpYellow:
begin
RGBtoCMYK(RowOriginal[i], CMYK);
{Shades of Value}
AssignRGBTriple(RowProcessed[i], RGBTriple(CMYK.cmykYellow,CMYK.cmykYellow,CMYK.cmykYellow))
end;
cpBlack:
begin
RGBtoCMYK(RowOriginal[i], CMYK);
{Shades of Value}
AssignRGBTriple(RowProcessed[i], RGBTriple(CMYK.cmykK,CMYK.cmykK,CMYK.cmykK))
end;
cpIntensity:
begin
Intensity := RGBIntensity(RowOriginal[i]);
{Shades of Saturation}
AssignRGBTriple(RowProcessed[i],
RGBTriple(Intensity, Intensity, Intensity))
end
end
end
end
end;
{== Image Statistics ==============================================}
// -----------------------------------------------------------------------------
//
// GetBitmapStatistics
//
// -----------------------------------------------------------------------------
procedure GetBitmapStatistics(const Bitmap: TBitmap;const ColorPlane: TColorPlane;
var Statistics: TDescriptiveStatistics);
var
CMYK: TCMYKQuad;
HSV : THSVTriple; {color coordinates}
i : INTEGER;
j : INTEGER;
Row : pRGBarray;
Value : INTEGER;
begin
IF Bitmap.Pixelformat <> pf24bit
THEN RAISE EGraphicformat.Create('GetBitmapStatistics: ' +
'Bitmap must be 24-bit color.');
value := 0; {avoid compiler warning about initialization}
{Step through each row of image.}
for j := Bitmap.Height-1 downto 0 DO
begin
Row := pRGBarray(Bitmap.Scanline[j]);
for i := Bitmap.Width-1 downto 0 DO
begin
CASE ColorPlane OF
cpRGB,
cpIntensity: value := RGBIntensity(Row[i]);
cpRed: value := Row[i].rgbtRed;
cpGreen: value := Row[i].rgbtGreen;
cpBlue: value := Row[i].rgbtBlue;
cpHueHSV:
begin
RGBtoHSV(Row[i], HSV);
value := HSV.hsvHue
end;
cpSaturationHSV:
begin
RGBtoHSV(Row[i], HSV);
value := HSV.hsvSaturation
end;
cpValue:
begin
RGBtoHSV(Row[i], HSV);
value := HSV.hsvValue
end;
cpCyan:
begin
RGBtoCMYK(Row[i], CMYK);
value := CMYK.cmykCyan
end
end;
Statistics.NextValue(value)
end
end
end;
// -----------------------------------------------------------------------------
//
// GetHistogram
//
// -----------------------------------------------------------------------------
procedure GetHistogram(const Bitmap : TBitmap;
const ColorPlane: TColorPlane;
var Histogram : THistogram);
var
CMYK: TCMYKQuad;
HSV : THSVTriple; {color coordinates}
i : INTEGER;
index : INTEGER;
j : INTEGER;
Row : pRGBarray;
Row8bit: pBytearray;
begin
IF (Bitmap.Pixelformat <> pf24bit) AND
(Bitmap.Pixelformat <> pf8bit)
THEN RAISE EGraphicformat.Create('GetHistogram: ' +
'Bitmap must be 8-bit or 24-bit.');
index := 0; {avoid compiler warning about initialization}
for i := Low(THistogram) TO High(THistogram) DO
Histogram[i] := 0;
IF Bitmap.Pixelformat = pf8bit
THEN begin
IF ColorPlane <> cp8bit
THEN RAISE EGraphicformat.Create('GetHistogram: ' +
'Attempting to extract color plane from 8-bit bitmap.');
for j := Bitmap.Height-1 downto 0 DO
begin
Row8bit := pBytearray(Bitmap.Scanline[j]);
for i := Bitmap.Width-1 downto 0 DO
begin
INC (Histogram[Row8bit[i]])
end
end
end
else begin
{Step through each row of image.}
for j := Bitmap.Height-1 downto 0 DO
begin
Row := pRGBarray(Bitmap.Scanline[j]);
for i := Bitmap.Width-1 downto 0 DO
begin
CASE ColorPlane OF
cpRGB,
cpIntensity: index := RGBIntensity(Row[i]);
cpRed: index := Row[i].rgbtRed;
cpGreen: index := Row[i].rgbtGreen;
cpBlue: index := Row[i].rgbtBlue;
cpHueHSV:
begin
RGBtoHSV(Row[i], HSV);
index := (255 * HSV.hsvHue) DIV 359
end;
cpSaturationHSV:
begin
RGBtoHSV(Row[i], HSV);
index := HSV.hsvSaturation
end;
cpValue:
begin
RGBtoHSV(Row[i], HSV);
index := HSV.hsvValue
end;
cpCyan:
begin
RGBtoCMYK(Row[i], CMYK);
index := CMYK.cmykCyan
end;
cpMagenta:
begin
RGBtoCMYK(Row[i], CMYK);
index := CMYK.cmykMagenta
end;
cpYellow:
begin
RGBtoCMYK(Row[i], CMYK);
index := CMYK.cmykYellow
end;
cpBlack:
begin
RGBtoCMYK(Row[i], CMYK);
index := CMYK.cmykK
end;
end;
INC (Histogram[index]);
end
end
end
end;
// -----------------------------------------------------------------------------
//
// DrawHistogram
//
// -----------------------------------------------------------------------------
procedure DrawHistogram(const ColorPlane: TColorPlane;
const Histogram : THistogram;
const aCanvas : TCanvas;
const LineColor:TColor; //<- LineColor added 19.04.98
const TextColor:TColor); //<- TextColor added 19.04.98
const
MajorTickSize = 8;
var
BarLength: INTEGER;
Delta : INTEGER;
dheight : Integer; //** Added
Color : TColor;
i : INTEGER;
j : INTEGER;
MaxValue : INTEGER;
MinValue : Integer; //** Added
RGBTriple: TRGBTRiple;
Width : INTEGER;
lMargin : Integer; //** Added
HSV: THSVTriple;
begin
Color := clBlack; {avoid compiler warning about initialization}
aCanvas.Pen.Style:=psSolid;
lMargin:=44; //** Added
dHeight := aCanvas.ClipRect.Bottom-(4+MajorTickSize+aCanvas.TextHeight('X')); //** Added
Width := aCanvas.ClipRect.Right;
MaxValue := xMaxIntValue(Histogram);
MinValue := xMinIntValue(Histogram);
{for now only paint on a canvas exactly 256 pixels wide. If
MaxValue is zero, array was not filled in correctly and is ignored.}
IF (Width = 256+lMargin) AND (MaxValue > 0)
THEN begin
for i := Low(THistogram) TO High(THistogram) DO
begin
CASE ColorPlane OF
cpRGB,
cpIntensity: Color := RGB(i, i, i);
cpRed: Color := RGB(i, 0, 0);
cpGreen: Color := RGB(0, i, 0);
cpBlue: Color := RGB(0, 0, i);
cpHueHSV:
begin
HSV.hsvHue:=(i*359) DIV 255;
HSV.hsvSaturation:=255;
HSV.hsvValue:=255;
HSVtoRGB(HSV, RGBTriple);
with RGBTriple DO
Color := RGB(rgbtRed, rgbtGreen, rgbtBlue)
end;
cpSaturationHSV:
Color := clBlack;
cpValue: Color := RGB(i, i, i);
end;
aCanvas.Pen.Color := Color;
BarLength := ROUND(dHeight*Histogram[i] / MaxValue);
aCanvas.MoveTo(i+lMargin, dHeight-1);
aCanvas.LineTo(i+lMargin, dHeight-1-BarLength)
// aCanvas.Pixels[i+lMargin, dHeight-1-BarLength]:=Color;
end;
aCanvas.Pen.Color := LineColor;
{Vertical Lines for visual estimation}
for i := 0 TO 25 DO
begin
aCanvas.MoveTo((10*i)+lMargin, dHeight-1);
IF i MOD 5 = 0
THEN Delta := MajorTickSize
else Delta := MajorTickSize DIV 2;
aCanvas.LineTo((10*i)+lMargin, dHeight+1+Delta);
end;
{Horizontal Lines}
for j := 0 TO 4 DO
begin
aCanvas.MoveTo(0+lMargin, j*dHeight DIV 5);
aCanvas.LineTo(Width-1, j*dHeight DIV 5);
end;
//** Added +
aCanvas.Font.Color:=TextColor;
aCanvas.Brush.Style := bsClear;
aCanvas.TextOut(lMargin-aCanvas.TextWidth(IntToStr(MaxValue))-2, 0, IntToStr(MaxValue));
aCanvas.TextOut(lMargin-aCanvas.TextWidth(IntToStr(MinValue))-2, dHeight, IntToStr(MinValue));
//** Added -
aCanvas.TextOut(2+lMargin, dHeight+aCanvas.TextHeight('X') - MajorTickSize+3, '0');
aCanvas.TextOut(Width-aCanvas.TextWidth('250 '),
dHeight+aCanvas.TextHeight('X') - MajorTickSize+3, '250')
end
end;
//------------------------------------------------------------
// Palette
//------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// GetColorDepth
//
// -----------------------------------------------------------------------------
// Adapted from Tommy Andersen's ColorDepth post to
// comp.lang.pascal.delphi.components.misc, 5 Oct 1997.
//
// According to Tim Robert's post "Bitmaps with > 256 Colors" to
// compl.lang.pascal.delphi.misc, 17 Apr 1997, "in a windows bitmap,
// one of either the bits-per-plane or the number of planes must be 1. In
// fact, the planar form is only supported at 4 bits per pixel. A 24-bit
// true color bitmap must have bits-per-pixel set to 24 and planes set to 1.
function GetColorDepth: INTEGER;
var
DeviceContext: hDC;
begin
// Get the screen's DC since memory DCs are not reliable
DeviceContext := GetDC(0);
TRY
RESULT := 1 SHL (GetDeviceCaps(DeviceContext, PLANES) *
GetDeviceCaps(DeviceContext, BITSPIXEL))
FINALLY
// Give back the screen DC
ReleaseDC(0, DeviceContext)
end;
end;
// -----------------------------------------------------------------------------
//
// GetPixelDepth
//
// -----------------------------------------------------------------------------
function GetPixelDepth: INTEGER;
var
DeviceContext: hDC;
begin
// Get the screen's DC since memory DCs are not reliable
DeviceContext := GetDC(0);
TRY
RESULT := GetDeviceCaps(DeviceContext, BITSPIXEL)
FINALLY
// Give back the screen DC
ReleaseDC(0, DeviceContext)
end;
end;
// -----------------------------------------------------------------------------
//
// GetDesktopPalette
//
// -----------------------------------------------------------------------------
// Adapted from PaletteFromDesktop function in "Delphi 2 Multimedia," Jarol,
// et al, 1996, Coriolis Group Books, p. 307. Unlike book version, use
// TMaxLogPalette and avoid allocating and freeing a pLogPalette area.
function GetDesktopPalette: hPalette;
var
LogicalPalette : TMaxLogPalette;
ScreendeviceContext: hDC;
ReturnCode : INTEGER;
begin
LogicalPalette.palVersion := PaletteVersion;
LogicalPalette.palNumEntries := 256;
ScreendeviceContext := GetDC(0);
TRY
// Get all 256 entries
ReturnCode := GetSystemPaletteEntries(ScreendeviceContext,
0, 255, LogicalPalette.palPalEntry)
FINALLY
ReleaseDC(0, ScreendeviceContext)
end;
IF ReturnCode >0
THEN RESULT := CreatePalette(pLogPalette(@LogicalPalette)^)
else RESULT := 0
end;
// -----------------------------------------------------------------------------
//
// GetGradientPalette
//
// -----------------------------------------------------------------------------
// Parameters identify which planes participate.
// Use all TRUE for shades of gray.
function GetGradientPalette(const red, green, blue: BOOLEAN): hPalette;
var
ScreendeviceContext: hDC;
i : INTEGER;
LogicalPalette : TMaxLogPalette;
function ScaleValue(const flag: BOOLEAN; const i: INTEGER): INTEGER;
begin
IF flag
THEN RESULT := MulDiv(i, 255, 235)
else RESULT := 0
end;
begin
LogicalPalette.palVersion := PaletteVersion;
LogicalPalette.palNumEntries := 256;
ScreendeviceContext := GetDC(0);
TRY
GetSystemPaletteEntries(ScreendeviceContext,
0, 10, LogicalPalette.palPalEntry[0]); // Maintain first 10
GetSystemPaletteEntries(ScreendeviceContext,
246, 10, LogicalPalette.palPalEntry[246]); // Maintain last 10
FINALLY
ReleaseDC(0, ScreendeviceContext)
end;
// Skip over first 10 and last 10 "fixed" entries
for i := 0 TO 255-20 DO
begin
// Skip over first 10 "fixed" entries in system palette
LogicalPalette.palPalEntry[10+i].peRed := ScaleValue(Red, i);
LogicalPalette.palPalEntry[10+i].peGreen := ScaleValue(Green, i);
LogicalPalette.palPalEntry[10+i].peBlue := ScaleValue(Blue, i);
LogicalPalette.palPalEntry[10+i].peFlags := pC_RESERVED;
end;
RESULT := CreatePalette(pLogPalette(@LogicalPalette)^)
end;
// -----------------------------------------------------------------------------
//
// CreateOptimizedPaletteForSingleBitmap
//
// -----------------------------------------------------------------------------
// Adapted from MSJ "Wicked Code" article, Oct 97, pp. 79-84
// Bitmap must be a DIB.
function CreateOptimizedPaletteforSingleBitmap(const Bitmap: TBitmap; const ColorBits: INTEGER): hPalette;
var
ColorQuantizer : TColorQuantizer;
ScreendeviceContext: hDC;
i : INTEGER;
LogicalPalette : TMaxLogPalette;
RGBQuadarray : TRGBQuadarray;
begin
LogicalPalette.palVersion := PaletteVersion;
LogicalPalette.palNumEntries := 256;
ScreendeviceContext := GetDC(0);
TRY
GetSystemPaletteEntries(ScreendeviceContext,
0,256, LogicalPalette.palPalEntry[0]); // Need first 10 and last 10
FINALLY
ReleaseDC(0, ScreendeviceContext)
end;
// Normally for 24-bit images, use ColorBits of 5 or 6. for 8-bit images
// use ColorBits = 8.
ColorQuantizer := TColorQuantizer.Create(236, ColorBits);
TRY
ColorQuantizer.ProcessImage(Bitmap.Handle);
ColorQuantizer.GetColorTable(RGBQuadarray);
// Skip over first 10 and last 10 "fixed" entries
for i := 0 TO 255-20 DO
begin
// Skip over first 10 "fixed" entries in system palette
LogicalPalette.palPalEntry[10+i].peRed := RGBQuadarray[i].rgbRed;
LogicalPalette.palPalEntry[10+i].peGreen := RGBQuadarray[i].rgbGreen;
LogicalPalette.palPalEntry[10+i].peBlue := RGBQuadarray[i].rgbBlue;
LogicalPalette.palPalEntry[10+i].peFlags := RGBQuadarray[i].rgbReserved
end;
RESULT := CreatePalette(pLogPalette(@LogicalPalette)^)
FINALLY
ColorQuantizer.Free
end
end;
// -----------------------------------------------------------------------------
//
// CreateOptimizedPaletteForManyBitmaps
//
// -----------------------------------------------------------------------------
// This separate function is for convenience in processing many bitmaps to
// obtain an optimized palette. The CallBack is called until a NIL pointer
// is returned.
function CreateOptimizedPaletteforManyBitmaps(const CallBack: TGetBitmapCallback;
const ColorBits: INTEGER): hPalette;
var
Bitmap : TBitmap;
ColorQuantizer : TColorQuantizer;
Counter : INTEGER;
i : INTEGER;
LogicalPalette : TMaxLogPalette;
OK : BOOLEAN;
RGBQuadarray : TRGBQuadarray;
ScreendeviceContext: hDC;
begin
LogicalPalette.palVersion := PaletteVersion;
LogicalPalette.palNumEntries := 256;
ScreendeviceContext := GetDC(0);
TRY
GetSystemPaletteEntries(ScreendeviceContext,
0,256, LogicalPalette.palPalEntry[0]); // Need first 10 and last 10
FINALLY
ReleaseDC(0, ScreendeviceContext)
end;
// Normally for 24-bit images, use ColorBits of 5 or 6. for 8-bit images
// use ColorBits = 8.
ColorQuantizer := TColorQuantizer.Create(236, ColorBits);
TRY
// Keep calling the callback for more bitmaps until a NIL pointer is
// returned. Use Counter and OK parameters is for convenience.
Counter := 1;
CallBack(Counter, OK, Bitmap);
WHILE (Bitmap <> NIL) DO
begin
IF OK
THEN ColorQuantizer.ProcessImage(Bitmap.Handle);
INC(Counter);
CallBack(Counter, OK, Bitmap)
end;
ColorQuantizer.GetColorTable(RGBQuadarray);
// Skip over first 10 and last 10 "fixed" entries
for i := 0 TO 255-20 DO
begin
// Skip over first 10 "fixed" entries in system palette
LogicalPalette.palPalEntry[10+i].peRed := RGBQuadarray[i].rgbRed;
LogicalPalette.palPalEntry[10+i].peGreen := RGBQuadarray[i].rgbGreen;
LogicalPalette.palPalEntry[10+i].peBlue := RGBQuadarray[i].rgbBlue;
LogicalPalette.palPalEntry[10+i].peFlags := RGBQuadarray[i].rgbReserved
end;
RESULT := CreatePalette(pLogPalette(@LogicalPalette)^)
FINALLY
ColorQuantizer.Free
end
end;
// -----------------------------------------------------------------------------
//
// IsPaletteDevice
//
// -----------------------------------------------------------------------------
// Adapted from Joe C. Hecht's BitTBitmapAsDIB post to
// borland.public.delphi.winapi, 12 Oct 1997.
function IsPaletteDevice: BOOLEAN;
var
DeviceContext: hDC;
begin
// Get the screen's DC since memory DCs are not reliable
DeviceContext := GetDC(0);
TRY
RESULT := GetDeviceCaps(DeviceContext, RASTERCAPS) AND RC_PALETTE = RC_PALETTE
FINALLY
// Give back the screen DC
ReleaseDC(0, DeviceContext)
end
end;
// -----------------------------------------------------------------------------
//
// LogicalPaletteToRGBQuad
//
// -----------------------------------------------------------------------------
procedure LogicalPaletteToRGBQuad(const Start : WORD;
const Count : WORD;
var LogicalPalette: TPaletteEntries;
var RGBQuad : TRGBQuadarray);
var
i: INTEGER;
begin
for i := Start TO Start+Count-1 DO
begin
RGBQuad[i].rgbRed := LogicalPalette[i].peRed;
RGBQuad[i].rgbGreen := LogicalPalette[i].peGreen;
RGBQuad[i].rgbBlue := LogicalPalette[i].peBlue;
RGBQuad[i].rgbReserved := LogicalPalette[i].peFlags
end
end;
// -----------------------------------------------------------------------------
//
// ReadAndCreatePaletteFromFractIntFile
//
// -----------------------------------------------------------------------------
// Adapted from "DibDemo" by John Biddiscombe, J.Biddiscombe@r1.ac.uk
function ReadAndCreatePaletteFromFractIntFile(const Filename : STRING): hPalette;
var
Blue : INTEGER;
Green : INTEGER;
ScreendeviceContext: hDC;
i : INTEGER;
LogicalPalette : TMaxLogPalette;
FractIntPalFile : TextFile;
Red : INTEGER;
begin
AssignFile(FractIntPalFile, Filename);
RESET(FractIntPalFile);
READLN(FractIntPalFile, PaletteColorCount);
IF PaletteColorCount > 236
THEN Palettecolorcount := 236;
LogicalPalette.palVersion := PaletteVersion;
LogicalPalette.palNumEntries := 256;
ScreendeviceContext := GetDC(0);
TRY
GetSystemPaletteEntries(ScreendeviceContext,
0, 10, LogicalPalette.palPalEntry[0]); // Maintain first 10
GetSystemPaletteEntries(ScreendeviceContext,
246, 10, LogicalPalette.palPalEntry[246]); // Maintain last 10
FINALLY
ReleaseDC(0, ScreendeviceContext)
end;
for i := 0 TO PaletteColorCount-1 DO
begin
READLN(FractIntPalFile, Red, Green, Blue);
// Skip over first 10 "fixed" entries in system palette
LogicalPalette.palPalEntry[10+i].peRed := Red;
LogicalPalette.palPalEntry[10+i].peGreen := Green;
LogicalPalette.palPalEntry[10+i].peBlue := Blue;
// Must be PC_RESERVED if AnimatePalette is to be used
LogicalPalette.palPalEntry[10+i].peFlags := PC_RESERVED;
end;
IF PaletteColorCount-1 < 235
THEN begin
for i := PaletteColorCount TO 235
DO begin
LogicalPalette.palPalEntry[10+i].peRed := LogicalPalette.palPalEntry[10+i-PaletteColorCount].peRed;
LogicalPalette.palPalEntry[10+i].peGreen := LogicalPalette.palPalEntry[10+i-PaletteColorCount].peGreen;
LogicalPalette.palPalEntry[10+i].peBlue := LogicalPalette.palPalEntry[10+i-PaletteColorCount].peBlue;
LogicalPalette.palPalEntry[10+i].peFlags := pc_Reserved;
end
end;
RESULT := CreatePalette(pLogPalette(@LogicalPalette)^);
CloseFile(FractIntPalFile);
end;
// -----------------------------------------------------------------------------
//
// WMQuereyNewPalette
//
// -----------------------------------------------------------------------------
// This message informs a window that it is about to receive the
// keyboard focus, giving the window the opportunity to realize its
// logical palette when it receives the focus.
procedure WMQueryNewPalette(formcanvashandle:THandle; PaletteHandle: hPalette;
var Msg: TWMQueryNewPalette);
var
DeviceContext: hDC;
Palette : hPalette;
ReturnCode : INTEGER;
begin
DeviceContext := formCanvasHandle;
// Select the specified palette into a device context.
// FALSE parameter forces logical palette to be copied into the device palette
// when the application is in the foreground.
Palette := SelectPalette(DeviceContext, PaletteHandle, FALSE);
// Map palette entries from the current logical palette to the system palette.
// Returned value is the number of entries in the logical palette mapped to
// the system palette.
ReturnCode := RealizePalette(DeviceContext);
// Restore the old palette into the device context.
SelectPalette(DeviceContext, Palette, FALSE);
// If new entries were mapped to the system palette, then invalidate the
// image so it gets repainted.
// IF ReturnCode > 0
// THEN form.Invalidate;
Msg.Result := ReturnCode
end;
// -----------------------------------------------------------------------------
//
// WMPaletteChanged
//
// -----------------------------------------------------------------------------
// This message is sent to all top-level and overlapped windows after the
// window with keyboard focus has realized its logical palette, thereby
// changing the system palette. This message enables a window that uses a
// color palette but does not have the keyboard focus to realize its logical
// palette and update its client area.
procedure WMPaletteChanged(formcanvashandle:THandle;formhandle:THandle; PaletteHandle: hPalette;
var Msg: TWMPaletteChanged);
var
DeviceContext: hDC;
Palette : hPalette;
begin
IF Msg.PalChg = formHandle
THEN begin
// To avoid creating an infinite loop, a window that receives this message
// must not realize its palette (unless it determines the window that
// caused the palette to change is not its own)
Msg.Result := 0
end
else begin
DeviceContext := formCanvasHandle;
// Select the specified palette into a device context.
// A TRUE parameter causes the logical palette to be mapped to the colors
// already in the physical palette in the best possible way.
Palette := SelectPalette(DeviceContext, PaletteHandle, TRUE);
// Map palette entries from the current logical palette to the system palette.
// Returned value is the number of entries in the logical palette mapped to
// the system palette.
RealizePalette(DeviceContext);
// UpdateColors is Microsoft's preferred way to refresh an on-screen Window
// if the system palette changes. UpdateColors updates the clinet area
// of the specified device contenxt by remapping the current colors in the
// client area to the currently realized logical palette. An inactive window
// with a realized logical palette may call UpdateColors as an alternative
// to redrawing its client area when the system palette changes.
UpdateColors(DeviceContext);
// Restore the old palette into the device context.
SelectPalette(DeviceContext, Palette, FALSE);
Msg.Result := 1;
end
end;
// -----------------------------------------------------------------------------
//
// ReadPaletteFromFile
//
// -----------------------------------------------------------------------------
function ReadPaletteFromFile(FileName:String):HPalette;
var F:TextFile;
s:String;
i:Integer;
fLogicalPalette:TMaxLogPalette;
fRGBQuadarray:TRGBQuadarray;
begin
AssignFile(F,FileName);
Reset(F);
ReadLn(F,s);
ReadLn(f,s);
ReadLn(f,s);
i:=0;
while not EOF(f) do
begin
ReadLn(f,s);
fRGBQuadarray[i].rgbRed:=StrToInt(Copy(s,1,Pos(' ',s)-1));
Delete(s,1,Pos(' ',s));
fRGBQuadarray[i].rgbGreen:=StrToInt(Copy(s,1,Pos(' ',s)-1));
Delete(s,1,Pos(' ',s));
fRGBQuadarray[i].rgbBlue:=StrToInt(s);
Inc(i,1);
fRGBQuadarray[i].rgbReserved:=0;
end;
fLogicalPalette.palVersion := PaletteVersion;
fLogicalPalette.palNumEntries := 256;
for i := 0 TO 255 DO
begin
fLogicalPalette.palPalEntry[i].peRed := fRGBQuadarray[i].rgbRed;
fLogicalPalette.palPalEntry[i].peGreen := fRGBQuadarray[i].rgbGreen;
fLogicalPalette.palPalEntry[i].peBlue := fRGBQuadarray[i].rgbBlue;
fLogicalPalette.palPalEntry[i].peFlags := fRGBQuadarray[i].rgbReserved
end;
Result := CreatePalette(pLogPalette(@fLogicalPalette)^);
end;
// -----------------------------------------------------------------------------
//
// LoadOptimizedPalette
//
// -----------------------------------------------------------------------------
function LoadOptimizedPalette:HPalette;
var i:Integer;
fLogicalPalette:TMaxLogPalette;
fRGBQuadarray:TRGBQuadarray;
begin
for i:=0 to 255 do
begin
fRGBQuadarray[i].rgbRed:=Optpal[i,0];
fRGBQuadarray[i].rgbGreen:=Optpal[i,1];
fRGBQuadarray[i].rgbBlue:=Optpal[i,2];
fRGBQuadarray[i].rgbReserved:=0;
end;
fLogicalPalette.palVersion := PaletteVersion;
fLogicalPalette.palNumEntries := 256;
for i := 10 TO 255-10 DO
begin
fLogicalPalette.palPalEntry[i].peRed := fRGBQuadarray[i].rgbRed;
fLogicalPalette.palPalEntry[i].peGreen := fRGBQuadarray[i].rgbGreen;
fLogicalPalette.palPalEntry[i].peBlue := fRGBQuadarray[i].rgbBlue;
fLogicalPalette.palPalEntry[i].peFlags := fRGBQuadarray[i].rgbReserved
end;
Result := CreatePalette(pLogPalette(@fLogicalPalette)^);
end;
// -----------------------------------------------------------------------------
//
// ApplyPaletteToGraphic
//
// -----------------------------------------------------------------------------
procedure ApplyPaletteToGraphic(Palette:Hpalette;Graphic:TGraphic;ChangePixelformat:Boolean;NewPixelformat:TPixelformat);
begin
if (Palette<>0) then
begin
{ if Graphic is TJPEGImage then
begin
TJPEGImage(Graphic).Pixelformat:=jf8Bit;
DeleteObject(TJPEGImage(Graphic).palette);
TJPEGImage(Graphic).Palette:=Palette;;
end else if Graphic is TBitmap then}
begin
TBitmap(Graphic).Pixelformat:=NewPixelformat;
DeleteObject(TBitmap(Graphic).ReleasePalette);
// TBitmap(Graphic).Palette:=Palette;
TBitmap(Graphic).Palette:=CopyPalette(Palette);
TBitmap(Graphic).Canvas.Refresh;
end;
end;
end;
// -----------------------------------------------------------------------------
//
// ApplyPaletteToDC
//
// -----------------------------------------------------------------------------
procedure ApplyPaletteToDC(DC:HDC;Palette:HPalette);
begin
if Palette<>0 then
begin
SelectPalette(DC, Palette, False);
RealizePalette(DC);
end;
end;
// -----------------------------------------------------------------------------
//
// PaletteDefaults
//
// -----------------------------------------------------------------------------
procedure PaletteDefaults(PaletteEntries:TPaletteEntries);
var
J:Integer;
begin
for J:=0 To 15 Do
begin
PaletteEntries[J].peRed:=StdPalette[J,1];
PaletteEntries[J].peGreen:=StdPalette[J,2];
PaletteEntries[J].peBlue:=StdPalette[J,3];
end;
end;
// -----------------------------------------------------------------------------
//
// MakeGreyPalette
//
// -----------------------------------------------------------------------------
procedure MakeGreyPalette(MaxLogPalette:TMaxLogPalette);
var
i:Integer;
begin
MaxLogPalette.palVersion:=PaletteVersion;
MaxLogPalette.palNumEntries:=256;
for i:=0 To 255 Do
begin
MaxLogPalette.palPalEntry[i].peRed :=i*63 Div 255;
MaxLogPalette.palPalEntry[i].peGreen :=i*63 Div 255;
MaxLogPalette.palPalEntry[i].peBlue :=i*63 Div 255;
MaxLogPalette.palPalEntry[i].peFlags :=0;
end;
end;
// -----------------------------------------------------------------------------
//
// MakeStandardPalette
//
// -----------------------------------------------------------------------------
procedure MakeStandardPalette(MaxLogPalette:TMaxLogPalette);
var
i:integer;
r,g,b:Word;
begin
MaxLogPalette.palVersion:=PaletteVersion;
MaxLogPalette.palNumEntries:=256;
i:=0;
for R:=0 to 7 do
begin
for G:=0 to 7 do
begin
for B:=0 to 3 do
begin
MaxLogPalette.palPalEntry[i].peRed :=(R+1)*8-1;
MaxLogPalette.palPalEntry[i].peGreen :=(G+1)*8-1;
MaxLogPalette.palPalEntry[i].peBlue :=(B+1)*16-1;
MaxLogPalette.palPalEntry[i].peFlags :=0;
Inc(i);
end;
end;
end;
end;
//------------------------------------------------------------
// Spliting
//------------------------------------------------------------
// -----------------------------------------------------------------------------
//
// GetPlane
//
// -----------------------------------------------------------------------------
procedure GetPlane(SrcBitmap,DestBitmap:TBitmap;Plane:Integer);
var
lig : Integer;
i : INTEGER;
j : INTEGER;
rowRGB : pRGBarray;
rowD : pRGBarray;
HSV : THSVTriple;
HSL : THSLTriple;
begin
SetBitmapsEql(SrcBitmap,DestBitmap);
for j := SrcBitmap.Height-1 downto 0 DO
begin
rowRGB := SrcBitmap.Scanline[j];
rowD := DestBitmap.Scanline[j];
for i := SrcBitmap.Width-1 downto 0 DO
begin
case Plane of
1:begin
rowD[i].rgbtRed := rowRGB[i].rgbtRed;
rowD[i].rgbtGreen := 0;
rowD[i].rgbtBlue := 0
end;
2:begin
rowD[i].rgbtRed := 0;
rowD[i].rgbtGreen := rowRGB[i].rgbtGreen;
rowD[i].rgbtBlue := 0
end;
3:begin
rowD[i].rgbtRed := 0;
rowD[i].rgbtGreen := 0;
rowD[i].rgbtBlue := rowRGB[i].rgbtBlue;
end;
4:begin
RGBtoHSV(rowRGB[i], HSV);
HSV.hsvHue := (HSV.hsvHue * 255) DIV 359;
rowD[i].rgbtRed := HSV.hsvHue;
rowD[i].rgbtGreen := HSV.hsvHue;
rowD[i].rgbtBlue := HSV.hsvHue;
end;
5:begin
RGBtoHSV(rowRGB[i], HSV);
rowD[i].rgbtRed := HSV.hsvSaturation;
rowD[i].rgbtGreen := HSV.hsvSaturation;
rowD[i].rgbtBlue := HSV.hsvSaturation;
end;
6:begin
RGBtoHSV(rowRGB[i], HSV);
rowD[i].rgbtRed := HSV.hsvValue;
rowD[i].rgbtGreen := HSV.hsvValue;
rowD[i].rgbtBlue := HSV.hsvValue;
end;
7:begin
RGBtoHSL(rowRGB[i], HSL);
rowD[i].rgbtRed := HSL.hslLightness ;
rowD[i].rgbtGreen := HSL.hslLightness;
rowD[i].rgbtBlue := HSL.hslLightness;
end;
end;
end;
end
end;
// -----------------------------------------------------------------------------
//
// GetRedPlane
//
// -----------------------------------------------------------------------------
procedure GetRedPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
begin
GetPlane(SrcBitmap,DestBitmap,1);
end;
// -----------------------------------------------------------------------------
//
// GetGreenPlane
//
// -----------------------------------------------------------------------------
procedure GetGreenPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
begin
GetPlane(SrcBitmap,DestBitmap,2);
end;
// -----------------------------------------------------------------------------
//
// GetBluePlane
//
// -----------------------------------------------------------------------------
procedure GetBluePlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
begin
GetPlane(SrcBitmap,DestBitmap,3);
end;
// -----------------------------------------------------------------------------
//
// GetHuePlane
//
// -----------------------------------------------------------------------------
procedure GetHuePlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
begin
GetPlane(SrcBitmap,DestBitmap,4);
end;
// -----------------------------------------------------------------------------
//
// GetSatPlane
//
// -----------------------------------------------------------------------------
procedure GetSatPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
begin
GetPlane(SrcBitmap,DestBitmap,5);
end;
// -----------------------------------------------------------------------------
//
// GetValPlane
//
// -----------------------------------------------------------------------------
procedure GetValPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
begin
GetPlane(SrcBitmap,DestBitmap,6);
end;
// -----------------------------------------------------------------------------
//
// GetLigPlane
//
// -----------------------------------------------------------------------------
procedure GetLigPlane(SrcBitmap:TBitmap;DestBitmap:TBitmap);
begin
GetPlane(SrcBitmap,DestBitmap,7);
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
// 字符串与流的加解密
//-----------------------------------------------------------------------------}
unit untEasyUtilCrypt;
interface
uses
Windows, Classes, SysUtils, Forms, Controls;
const
_KEYLength = 128;
MAXBC = (256 div 32);
MAXKC = (256 div 32);
MAXROUNDS = 14;
DIR_ENCRYPT = 0; { Are we encrpyting? }
DIR_DECRYPT = 1; { Are we decrpyting? }
MODE_ECB = 1; { Are we ciphering in ECB mode? }
MODE_CBC = 2; { Are we ciphering in CBC mode? }
MODE_CFB1 = 3; { Are we ciphering in 1-bit CFB mode? }
rTRUE = 1; { integer(true) }
rFALSE = 0; { integer(false) }
BITSPERBLOCK = 128; { Default number of bits in a cipher block }
{ Error Codes - CHANGE POSSIBLE: inclusion of additional error codes }
BAD_KEY_DIR = -1; { Key direction is invalid, e.g., unknown value }
BAD_KEY_MAT = -2; { Key material not of correct length }
BAD_KEY_INSTANCE = -3; { Key passed is not valid }
BAD_CIPHER_MODE = -4; { Params struct passed to cipherInit invalid }
BAD_CIPHER_STATE = -5; { Cipher in wrong state (e.g., not initialized) }
BAD_CIPHER_INSTANCE = -7;
{ CHANGE POSSIBLE: inclusion of algorithm specific defines }
MAX_KEY_SIZE = 64; { # of ASCII char's needed to represent a key }
MAX_IV_SIZE = (BITSPERBLOCK div 8); { # bytes needed to represent an IV }
type
word8 = byte; // unsigned 8-bit
word16 = word; // unsigned 16-bit
word32 = longword; // unsigned 32-bit
TByteArray = array [0..MaxInt div sizeof(Byte)-1] of Byte;
PByte = ^TByteArray;
TArrayK = array [0..4-1, 0..MAXKC-1] of word8;
PArrayK = ^TArrayK;
TArrayRK = array [0..MAXROUNDS+1-1, 0..4-1, 0..MAXBC-1] of word8;
TArrayBox= array [0..256-1] of word8;
{ The structure for key information }
PkeyInstance = ^keyInstance;
keyInstance = packed record
direction: Byte; { Key used for encrypting or decrypting? }
keyLen: integer; { Length of the key }
keyMaterial: array [0..MAX_KEY_SIZE+1-1] of Ansichar; { Raw key data in ASCII, e.g., user input or KAT values }
{ The following parameters are algorithm dependent, replace or add as necessary }
blockLen: integer; { block length }
keySched: TArrayRK; { key schedule }
end; {* keyInstance *}
TkeyInstance = keyInstance;
{ The structure for cipher information }
PcipherInstance = ^cipherInstance;
cipherInstance = packed record
mode: Byte; // MODE_ECB, MODE_CBC, or MODE_CFB1
IV: array [0..MAX_IV_SIZE-1] of Byte; // A possible Initialization Vector for ciphering
{ Add any algorithm specific parameters needed here }
blockLen: integer; // Sample: Handles non-128 bit block sizes (if available)
end; {* cipherInstance *}
TcipherInstance = cipherInstance;
TEasyCrypterClass = class of TEasyCustomCrypter;
TEasyCustomCrypter = class(TComponent)
private
FStream: TStream;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Decrypt(Source: TStream; const Key: AnsiString): Boolean; virtual; abstract;
procedure Crypt(Dest: TStream; const Key: AnsiString); virtual; abstract;
procedure CreaEasyream;
property Stream: TStream read FStream write FStream;
end;
TEasyCrypt = class(TEasyCustomCrypter)
private
function AskKey(const Key: AnsiString): AnsiString;
public
procedure Crypt(Dest: TStream; const Key: AnsiString); override;
function Decrypt(Source: TStream; const Key: AnsiString): Boolean; override;
end;
procedure EasyCryptStream(Source, Dest: TStream; const Key: AnsiString);
procedure EasyDecryptStream(Source, Dest: TStream; const Key: AnsiString);
function ExpandKey(sKey: AnsiString; iLength: integer): Ansistring;
function _makeKey(key: PkeyInstance; direction: Byte; keyLen: integer; keyMaterial: pAnsichar): integer;
function MakeKey(const Key: AnsiString): AnsiString;
{encode string}
function EnCryptString(const sMessage: AnsiString; sKeyMaterial: AnsiString): AnsiString;
{decode string}
function DeCryptString(const sMessage: AnsiString; sKeyMaterial: AnsiString): AnsiString;
{ Calculate the necessary round keys
The number of calculations depends on keyBits and blockBits }
function rijndaelKeySched(k: TArrayK; keyBits, blockBits: integer;
var W: TArrayRK): integer;
{ Encryption of one block. }
function rijndaelEncrypt(var a: TArrayK; keyBits, blockBits: integer; rk: TArrayRK): integer;
{ Encrypt only a certain number of rounds.
Only used in the Intermediate Value Known Answer Easy. }
function rijndaelEncryptRound(var a: TArrayK; keyBits, blockBits: integer;
rk: TArrayRK; var irounds: integer): integer;
{ Decryption of one block. }
function rijndaelDecrypt(var a: TArrayK; keyBits, blockBits: integer; rk: TArrayRK): integer;
{ Decrypt only a certain number of rounds.
Only used in the Intermediate Value Known Answer Easy.
Operations rearranged such that the intermediate values
of decryption correspond with the intermediate values
of encryption. }
function rijndaelDecryptRound(var a: TArrayK; keyBits, blockBits: integer;
rk: TArrayRK; var irounds: integer): integer;
{sergey has corrected it}
function blocksEnCrypt(cipher: PcipherInstance; key: PkeyInstance; input: PByte;
inputLen: integer; outBuffer: PByte): integer;
{sergey has corrected it}
function blocksDeCrypt(cipher: PcipherInstance; key: PkeyInstance; input: PByte;
inputLen: integer; outBuffer: PByte): integer;
implementation
{
Tables that are needed by the reference implementation.
The tables implement the S-box and its inverse, and also
some temporary tables needed for multiplying in the finite field GF(2^8)
}
const
Logtable: array [0..256-1] of word8 = (
0, 0, 25, 1, 50, 2, 26, 198, 75, 199, 27, 104, 51, 238, 223, 3,
100, 4, 224, 14, 52, 141, 129, 239, 76, 113, 8, 200, 248, 105, 28, 193,
125, 194, 29, 181, 249, 185, 39, 106, 77, 228, 166, 114, 154, 201, 9, 120,
101, 47, 138, 5, 33, 15, 225, 36, 18, 240, 130, 69, 53, 147, 218, 142,
150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56,
102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16,
126, 110, 72, 195, 163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186,
43, 121, 10, 21, 155, 159, 94, 202, 78, 212, 172, 229, 243, 115, 167, 87,
175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233, 213, 231, 230, 173, 232,
44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169, 81, 160,
127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183,
204, 187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157,
151, 178, 135, 144, 97, 190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209,
83, 57, 132, 60, 65, 162, 109, 71, 20, 42, 158, 93, 86, 242, 211, 171,
68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119, 153, 227, 165,
103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7 );
Alogtable: array [0..256-1] of word8 = (
1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53,
95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170,
229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49,
83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205,
76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136,
131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154,
181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163,
254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160,
251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65,
195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117,
159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128,
155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84,
252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202,
69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14,
18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23,
57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1 );
S: TArrayBox{array [0..256-1] of word8} = (
99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118,
202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192,
183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21,
4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117,
9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132,
83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207,
208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168,
81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210,
205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115,
96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219,
224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121,
231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8,
186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138,
112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158,
225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22 );
Si: TArrayBox{array [0..256-1] of word8} = (
82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251,
124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203,
84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78,
8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37,
114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146,
108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132,
144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6,
208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107,
58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115,
150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110,
71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27,
252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244,
31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95,
96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239,
160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97,
23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125 );
rcon: array [0..30-1] of word32 = (
$01,$02, $04, $08, $10, $20, $40, $80, $1b, $36, $6c,
$d8, $ab, $4d, $9a, $2f, $5e, $bc, $63, $c6, $97, $35,
$6a, $d4, $b3, $7d, $fa, $ef, $c5, $91 );
shifts: array [0..3-1, 0..4-1, 0..2-1] of word8 = (
((0, 0),(1, 3),(2, 2),(3, 1)),
((0, 0),(1, 5),(2, 4),(3, 3)),
((0, 0),(1, 7),(3, 5),(4, 4)));
function blocksEnCrypt(cipher: PcipherInstance; key: PkeyInstance;
input: PByte; inputLen: integer; outBuffer: PByte): integer;
var
i, j, t, numBlocks: integer;
block: TArrayK;
begin
{ check parameter consistency: }
if (not assigned(key)) or
(key.direction <> DIR_ENCRYPT) or
((key.keyLen <> 128) and (key.keyLen <> 192) and (key.keyLen <> 256)) then
begin
result:= BAD_KEY_MAT;
exit;
end;
if (not assigned(cipher)) or
((cipher.mode <> MODE_ECB) and (cipher.mode <> MODE_CBC) and (cipher.mode <> MODE_CFB1)) or
((cipher.blockLen <> 128) and (cipher.blockLen <> 192) and (cipher.blockLen <> 256)) then
begin
result:= BAD_CIPHER_STATE;
exit;
end;
numBlocks:= inputLen div cipher.blockLen;
case (cipher.mode) of
MODE_ECB:
for i:= 0 to numBlocks-1 do
begin
for j:= 0 to (cipher.blockLen div 32)-1 do
for t:= 0 to 4-1 do
{ parse input stream into rectangular array }
block[t][j]:= input[4*j+t] and $FF;
rijndaelEncrypt(block, key.keyLen, cipher.blockLen, key.keySched);
for j:= 0 to (cipher.blockLen div 32)-1 do
{ parse rectangular array into output ciphertext bytes }
for t:= 0 to 4-1 do
outBuffer[4*j+t]:= Byte(block[t][j]);
end;
MODE_CBC:
begin
for j:= 0 to (cipher.blockLen div 32)-1 do
for t:= 0 to 4-1 do
{ parse initial value into rectangular array }
block[t][j]:= cipher.IV[t+4*j] and $FF;
for i:= 0 to numBlocks-1 do
begin
for j:= 0 to (cipher.blockLen div 32)-1 do
for t:= 0 to 4-1 do
{ parse input stream into rectangular array and exor with
IV or the previous ciphertext }
// block[t][j]:= block[t][j] xor (input[4*j+t] and $FF); {!original!}
block[t][j]:= block[t][j] xor (input[(i*(cipher.blockLen div 8))+4*j+t] and $FF); {!sergey made it!}
rijndaelEncrypt(block, key.keyLen, cipher.blockLen, key.keySched);
for j:= 0 to (cipher.blockLen div 32)-1 do
{ parse rectangular array into output ciphertext bytes }
for t:= 0 to 4-1 do
// outBuffer[4*j+t]:= Byte(block[t][j]); {!original!}
outBuffer[(i*(cipher.blockLen div 8))+4*j+t]:= Byte(block[t][j]); {!sergey made it!}
end;
end;
else
begin
result:= BAD_CIPHER_STATE;
exit
end;
end;
result:= numBlocks*cipher.blockLen;
end;
function blocksDeCrypt(cipher: PcipherInstance; key: PkeyInstance; input: PByte;
inputLen: integer; outBuffer: PByte): integer;
var
i, j, t, numBlocks: integer;
block: TArrayK;
begin
if (not assigned(cipher)) or
(not assigned(key)) or
(key.direction = DIR_ENCRYPT) or
(cipher.blockLen <> key.blockLen) then
begin
result:= BAD_CIPHER_STATE;
exit;
end;
{ check parameter consistency: }
if (not assigned(key)) or
(key.direction <> DIR_DECRYPT) or
((key.keyLen <> 128) and (key.keyLen <> 192) and (key.keyLen <> 256)) then
begin
result:= BAD_KEY_MAT;
exit;
end;
if (not assigned(cipher)) or
((cipher.mode <> MODE_ECB) and (cipher.mode <> MODE_CBC) and (cipher.mode <> MODE_CFB1)) or
((cipher.blockLen <> 128) and (cipher.blockLen <> 192) and (cipher.blockLen <> 256)) then
begin
result:= BAD_CIPHER_STATE;
exit;
end;
numBlocks:= inputLen div cipher.blockLen;
case (cipher.mode) of
MODE_ECB:
for i:= 0 to numBlocks-1 do
begin
for j:= 0 to (cipher.blockLen div 32)-1 do
for t:= 0 to 4-1 do
{ parse input stream into rectangular array }
block[t][j]:= input[4*j+t] and $FF;
rijndaelDecrypt (block, key.keyLen, cipher.blockLen, key.keySched);
for j:= 0 to (cipher.blockLen div 32)-1 do
{ parse rectangular array into output ciphertext bytes }
for t:= 0 to 4-1 do
outBuffer[4*j+t]:= Byte(block[t][j]);
end;
MODE_CBC:
{! sergey has rearranged processing blocks and
corrected exclusive-ORing operation !}
begin
{ blocks after first }
for i:= numBlocks-1 downto 1 do
begin
for j:= 0 to (cipher.blockLen div 32)-1 do
for t:= 0 to 4-1 do
{ parse input stream into rectangular array }
block[t][j]:= input[(i*(cipher.blockLen div 8))+ 4*j+ t] and $FF;
rijndaelDecrypt(block, key.keyLen, cipher.blockLen, key.keySched);
for j:= 0 to (cipher.blockLen div 32)-1 do
{ exor previous ciphertext block and parse rectangular array
into output ciphertext bytes }
for t:= 0 to 4-1 do
outBuffer[(i*(cipher.blockLen div 8))+ 4*j+t]:= Byte(block[t][j] xor
input[(i-1)*(cipher.blockLen div 8)+ 4*j+ t]);
end;
{ first block }
for j:= 0 to (cipher.blockLen div 32)-1 do
for t:= 0 to 4-1 do
{ parse input stream into rectangular array }
block[t][j]:= input[4*j+t] and $FF;
rijndaelDecrypt(block, key.keyLen, cipher.blockLen, key.keySched);
for j:= 0 to (cipher.blockLen div 32)-1 do
{ exor the IV and parse rectangular array into output ciphertext bytes }
for t:= 0 to 4-1 do
outBuffer[4*j+t]:= Byte(block[t][j] xor cipher.IV[t+4*j]);
end;
else
begin
result:= BAD_CIPHER_STATE;
exit;
end;
end;
result:= numBlocks*cipher.blockLen;
end;
function iif(bExpression: boolean; iResTrue,iResFalse: integer): integer;
begin
if bExpression then
result:= iResTrue
else
result:= iResFalse;
end;
function mul(a, b: word8): word8;
{ multiply two elements of GF(2^m)
needed for MixColumn and InvMixColumn }
begin
if (a<>0) and (b<>0) then
result:= Alogtable[(Logtable[a] + Logtable[b]) mod 255]
else
result:= 0;
end;
procedure KeyAddition(var a: TArrayK; rk: PArrayK; BC:word8);
{ Exor corresponding text input and round key input bytes }
var
i, j: integer;
begin
for i:= 0 to 4-1 do
for j:= 0 to BC-1 do
a[i][j]:= a[i][j] xor rk[i][j];
end;
procedure ShiftRow(var a: TArrayK; d, BC: word8);
{ Row 0 remains unchanged
The other three rows are shifted a variable amount }
var
tmp: array [0..MAXBC-1] of word8;
i, j: integer;
begin
for i:= 1 to 4-1 do
begin
for j:= 0 to BC-1 do
tmp[j]:= a[i][(j + shifts[((BC - 4) shr 1)][i][d]) mod BC];
for j:= 0 to BC-1 do
a[i][j]:= tmp[j];
end;
end;
procedure Substitution(var a: TArrayK; const box: TArrayBox; BC: word8);
{ Replace every byte of the input by the byte at that place
in the nonlinear S-box }
var
i, j: integer;
begin
for i:= 0 to 4-1 do
for j:= 0 to BC-1 do
a[i][j]:= box[a[i][j]];
end;
procedure MixColumn(var a: TArrayK; BC: word8);
{ Mix the four bytes of every column in a linear way }
var
b: TArrayK;
i, j: integer;
begin
for j:= 0 to BC-1 do
for i:= 0 to 4-1 do
b[i][j]:= mul(2,a[i][j])
xor mul(3,a[(i + 1) mod 4][j])
xor a[(i + 2) mod 4][j]
xor a[(i + 3) mod 4][j];
for i:= 0 to 4-1 do
for j:= 0 to BC-1 do
a[i][j]:= b[i][j];
end;
procedure InvMixColumn(var a: TArrayK; BC: word8);
{ Mix the four bytes of every column in a linear way
This is the opposite operation of Mixcolumn }
var
b: TArrayK;
i, j: integer;
begin
for j:= 0 to BC-1 do
for i:= 0 to 4-1 do
b[i][j]:= mul($e,a[i][j])
xor mul($b,a[(i + 1) mod 4][j])
xor mul($d,a[(i + 2) mod 4][j])
xor mul($9,a[(i + 3) mod 4][j]);
for i:= 0 to 4-1 do
for j:= 0 to BC-1 do
a[i][j]:= b[i][j];
end;
function rijndaelKeySched(k: TArrayK; keyBits, blockBits: integer;
var W: TArrayRK): integer;
{ Calculate the necessary round keys
The number of calculations depends on keyBits and blockBits }
var
KC, BC, ROUNDS: integer;
i, j, t, rconpointer: integer;
tk: array [0..4-1, 0..MAXKC-1] of word8;
begin
rconpointer:= 0;
case (keyBits) of
128: KC:= 4;
192: KC:= 6;
256: KC:= 8;
else
begin
result:= -1;
exit;
end;
end;
case (blockBits) of
128: BC:= 4;
192: BC:= 6;
256: BC:= 8;
else
begin
result:= -2;
exit;
end;
end;
case iif(keyBits >= blockBits, keyBits, blockBits) of
128: ROUNDS:= 10;
192: ROUNDS:= 12;
256: ROUNDS:= 14;
else
begin
result:= -3; {* this cannot happen *}
exit;
end;
end;
for j:= 0 to KC-1 do
for i:= 0 to 4-1 do
tk[i][j]:= k[i][j];
{ copy values into round key array }
t:= 0;
j:= 0;
while ((j < KC) and (t < (ROUNDS+1)*BC)) do
begin
for i:= 0 to 4-1 do
W[t div BC][i][t mod BC]:= tk[i][j];
inc(j);
inc(t);
end;
while (t < (ROUNDS+1)*BC) do { while not enough round key material calculated }
begin
{ calculate new values }
for i:= 0 to 4-1 do
tk[i][0]:= tk[i][0] xor S[tk[(i+1) mod 4][KC-1]];
tk[0][0]:= tk[0][0] xor rcon[rconpointer];
inc(rconpointer);
if (KC <> 8) then
begin
for j:= 1 to KC-1 do
for i:= 0 to 4-1 do
tk[i][j]:= tk[i][j] xor tk[i][j-1];
end
else
begin
j:= 1;
while j < KC/2 do
begin
for i:= 0 to 4-1 do
tk[i][j]:= tk[i][j] xor tk[i][j-1];
inc(j);
end;
for i:= 0 to 4-1 do
tk[i][KC div 2]:= tk[i][KC div 2] xor S[tk[i][(KC div 2) - 1]];
j:= (KC div 2) + 1;
while j < KC do
begin
for i:= 0 to 4-1 do
tk[i][j]:= tk[i][j] xor tk[i][j-1];
inc(j);
end;
end;
{ copy values into round key array }
j:= 0;
while ((j < KC) and (t < (ROUNDS+1)*BC)) do
begin
for i:= 0 to 4-1 do
W[t div BC][i][t mod BC]:= tk[i][j];
inc(j);
inc(t);
end;
end;
result:= 0;
end;
function rijndaelEncrypt(var a: TArrayK; keyBits, blockBits: integer; rk: TArrayRK): integer;
{ Encryption of one block. }
var
r, BC, ROUNDS: integer;
begin
case (blockBits) of
128: BC:= 4;
192: BC:= 6;
256: BC:= 8;
else
begin
result:= -2;
exit;
end;
end;
case iif(keyBits >= blockBits, keyBits, blockBits) of
128: ROUNDS:= 10;
192: ROUNDS:= 12;
256: ROUNDS:= 14;
else
begin
result:= -3; { this cannot happen }
exit;
end;
end;
{ begin with a key addition }
KeyAddition(a,addr(rk[0]),BC);
{ ROUNDS-1 ordinary rounds }
for r:= 1 to ROUNDS-1 do
begin
Substitution(a,S,BC);
ShiftRow(a,0,BC);
MixColumn(a,BC);
KeyAddition(a,addr(rk[r]),BC);
end;
{ Last round is special: there is no MixColumn }
Substitution(a,S,BC);
ShiftRow(a,0,BC);
KeyAddition(a,addr(rk[ROUNDS]),BC);
result:= 0;
end;
function rijndaelEncryptRound(var a: TArrayK; keyBits, blockBits: integer;
rk: TArrayRK; var irounds: integer): integer;
{ Encrypt only a certain number of rounds.
Only used in the Intermediate Value Known Answer Easy. }
var
r, BC, ROUNDS: integer;
begin
case (blockBits) of
128: BC:= 4;
192: BC:= 6;
256: BC:= 8;
else
begin
result:= -2;
exit;
end;
end;
case iif(keyBits >= blockBits, keyBits, blockBits) of
128: ROUNDS:= 10;
192: ROUNDS:= 12;
256: ROUNDS:= 14;
else
begin
result:= -3; { this cannot happen }
exit;
end;
end;
{ make number of rounds sane }
if (irounds > ROUNDS) then
irounds:= ROUNDS;
{ begin with a key addition }
KeyAddition(a,addr(rk[0]),BC);
{ at most ROUNDS-1 ordinary rounds }
r:= 1;
while (r <= irounds) and (r < ROUNDS) do
begin
Substitution(a,S,BC);
ShiftRow(a,0,BC);
MixColumn(a,BC);
KeyAddition(a,addr(rk[r]),BC);
inc(r);
end;
{ if necessary, do the last, special, round: }
if (irounds = ROUNDS) then
begin
Substitution(a,S,BC);
ShiftRow(a,0,BC);
KeyAddition(a,addr(rk[ROUNDS]),BC);
end;
result:= 0;
end;
function rijndaelDecrypt(var a: TArrayK; keyBits, blockBits: integer; rk: TArrayRK): integer;
var
r, BC, ROUNDS: integer;
begin
case (blockBits) of
128: BC:= 4;
192: BC:= 6;
256: BC:= 8;
else
begin
result:= -2;
exit;
end;
end;
case iif(keyBits >= blockBits, keyBits, blockBits) of
128: ROUNDS:= 10;
192: ROUNDS:= 12;
256: ROUNDS:= 14;
else
begin
result:= -3; { this cannot happen }
exit;
end;
end;
{ To decrypt: apply the inverse operations of the encrypt routine,
in opposite order
(KeyAddition is an involution: it 's equal to its inverse)
(the inverse of Substitution with table S is Substitution with the inverse table of S)
(the inverse of Shiftrow is Shiftrow over a suitable distance) }
{ First the special round:
without InvMixColumn
with extra KeyAddition }
KeyAddition(a,addr(rk[ROUNDS]),BC);
Substitution(a,Si,BC);
ShiftRow(a,1,BC);
{ ROUNDS-1 ordinary rounds }
for r:= ROUNDS-1 downto 0+1 do
begin
KeyAddition(a,addr(rk[r]),BC);
InvMixColumn(a,BC);
Substitution(a,Si,BC);
ShiftRow(a,1,BC);
end;
{ End with the extra key addition }
KeyAddition(a,addr(rk[0]),BC);
result:= 0;
end;
function rijndaelDecryptRound(var a: TArrayK; keyBits, blockBits: integer;
rk: TArrayRK; var irounds: integer): integer;
{ Decrypt only a certain number of rounds.
Only used in the Intermediate Value Known Answer Easy.
Operations rearranged such that the intermediate values
of decryption correspond with the intermediate values
of encryption. }
var
r, BC, ROUNDS: integer;
begin
case (blockBits) of
128: BC:= 4;
192: BC:= 6;
256: BC:= 8;
else
begin
result:= -2;
exit;
end;
end;
case iif(keyBits >= blockBits, keyBits, blockBits) of
128: ROUNDS:= 10;
192: ROUNDS:= 12;
256: ROUNDS:= 14;
else
begin
result:= -3; { this cannot happen }
exit;
end;
end;
{ make number of rounds sane }
if (irounds > ROUNDS) then
irounds:= ROUNDS;
{ First the special round:
without InvMixColumn
with extra KeyAddition }
KeyAddition(a,addr(rk[ROUNDS]),BC);
Substitution(a,Si,BC);
ShiftRow(a,1,BC);
{ ROUNDS-1 ordinary rounds }
for r:= ROUNDS-1 downto irounds+1 do
begin
KeyAddition(a,addr(rk[r]),BC);
InvMixColumn(a,BC);
Substitution(a,Si,BC);
ShiftRow(a,1,BC);
end;
if (irounds = 0) then
{ End with the extra key addition }
KeyAddition(a,addr(rk[0]),BC);
result:= 0;
end;
function _makeKey(key: PkeyInstance; direction: Byte; keyLen: integer; keyMaterial: pAnsichar): integer;
var
k: TArrayK;
i, j, t: integer;
begin
if not assigned(key) then
begin
result:= BAD_KEY_INSTANCE;
exit;
end;
if ((direction = DIR_ENCRYPT) or (direction = DIR_DECRYPT)) then
key.direction:= direction
else
begin
result:= BAD_KEY_DIR;
exit;
end;
if ((keyLen = 128) or (keyLen = 192) or (keyLen = 256)) then
key.keyLen:= keyLen
else
begin
result:= BAD_KEY_MAT;
exit;
end;
if (keyMaterial^ <> #0) then
StrLCopy(key.keyMaterial, keyMaterial, keyLen div 4); // strncpy
j := 0;
{ initialize key schedule: }
for i:= 0 to (key.keyLen div 8)-1 do
begin
t:= integer(key.keyMaterial[2*i]);
if ((t >= ord('0')) and (t <= ord('9'))) then
j:= (t - ord('0')) shl 4
else
if ((t >= ord('a')) and (t <= ord('f'))) then
j:= (t - ord('a') + 10) shl 4
else
if ((t >= ord('A')) and (t <= ord('F'))) then
j:= (t - ord('A') + 10) shl 4
else
begin
result:= BAD_KEY_MAT;
exit;
end;
t:= integer(key.keyMaterial[2*i+1]);
if ((t >= ord('0')) and (t <= ord('9'))) then
j:= j xor (t - ord('0'))
else
if ((t >= ord('a')) and (t <= ord('f'))) then
j:= j xor (t - ord('a') + 10)
else
if ((t >= ord('A')) and (t <= ord('F'))) then
j:= j xor (t - ord('A') + 10)
else
begin
result:= BAD_KEY_MAT;
exit;
end;
k[i mod 4][i div 4]:= word8(j);
end;
rijndaelKeySched(k, key.keyLen, key.blockLen, key.keySched);
result:= rTRUE;
end;
function EnCryptString(const sMessage: AnsiString; sKeyMaterial: AnsiString): AnsiString;
var
sres: Ansistring;
blockLength,i: integer;
keyInst: TkeyInstance;
cipherInst: TcipherInstance;
begin
keyInst.blockLen:= BITSPERBLOCK;
sres:= ExpandKey(sKeyMaterial,_KEYLength);
if _makeKey(addr(keyInst), DIR_ENCRYPT, _KEYLength, pAnsichar(sres))<> rTRUE then
raise Exception.CreateFmt('Key error.',[-1]);
cipherInst.blockLen:= BITSPERBLOCK;
cipherInst.mode:= MODE_CBC;
FillChar(cipherInst.IV,sizeof(cipherInst.IV),0);
sres:= sMessage;
blockLength:= length(sres)*8;
if (blockLength mod BITSPERBLOCK)<> 0 then
begin
for i:= 1 to ((BITSPERBLOCK-(blockLength-(BITSPERBLOCK*(blockLength div BITSPERBLOCK)))) div 8) do
sres:= sres+ ' ';
blockLength:= length(sres)*8;
end;
if blocksEnCrypt(addr(cipherInst), addr(keyInst), addr(sres[1]), blockLength, addr(sres[1]))<> blockLength then
raise Exception.CreateFmt('EnCrypt error.',[-2]);
result:= sres;
end;
function DeCryptString(const sMessage: AnsiString; sKeyMaterial: AnsiString): AnsiString;
var
sres: AnsiString;
blockLength: integer;
keyInst: TkeyInstance;
cipherInst: TcipherInstance;
begin
keyInst.blockLen:= BITSPERBLOCK;
sres:= ExpandKey(sKeyMaterial,_KEYLength);
if _makeKey(addr(keyInst), DIR_DECRYPT, _KEYLength, pAnsichar(sres))<> rTRUE then
raise Exception.CreateFmt('Key error.',[-1]);
cipherInst.blockLen:= BITSPERBLOCK;
cipherInst.mode:= MODE_CBC;
FillChar(cipherInst.IV,sizeof(cipherInst.IV),0);
sres:= sMessage;
blockLength:= length(sres)*8;
if (blockLength= 0) or ((blockLength mod BITSPERBLOCK)<> 0) then
raise Exception.CreateFmt('Wrong message length.',[-4]);
if blocksDeCrypt(addr(cipherInst), addr(keyInst), addr(sres[1]), blockLength, addr(sres[1]))<> blockLength then
raise Exception.CreateFmt('DeCrypt error.',[-3]);
result:= AnsiString(trim(String(sres)));
end;
function ExpandKey(sKey: Ansistring; iLength: integer): AnsiString;
var
ikey: array [0..(_KEYLength div 8)-1] of byte;
i,t: integer;
sr: Ansistring;
begin
sr:= sKey;
FillChar(ikey,sizeof(ikey),0);
try
if (length(sr) mod 2)<> 0 then
sr:= sr+ '0';
t:= length(sr) div 2;
if t> (iLength div 8) then
t:= (iLength div 8);
for i:= 0 to t-1 do
ikey[i]:= strtoint('$'+String(sr[i*2+1]) + String(sr[i*2+2]));
except
end;
sr:= '';
for i:= 0 to (iLength div 8)-1 do
sr:= sr + AnsiString(IntToHex(ikey[i],2));
result:= sr;
end;
function MakeKey(const Key: AnsiString): AnsiString;
begin
Result := '';
if (Key <> '') then
begin
SetLength(Result, Length(Key) * 2);
BinToHex(PAnsiChar(@Key[1]), PAnsiChar(@Result[1]), Length(Key));
end;
Result := ExpandKey(Result, _KEYLength);
end;
procedure EasyCryptStream(Source, Dest: TStream; const Key: AnsiString);
var
s: AnsiString;
header: array [0..2] of byte;
begin
Source.Position := 0;
SetLength(s, Source.Size);
Source.Read(s[1], Source.Size);
s := EncryptString(s, MakeKey(Key));
header[0] := Ord('r');
header[1] := Ord('i');
header[2] := Ord('j');
Dest.Write(header, 3);
Dest.Write(s[1], Length(s));
end;
procedure EasyDecryptStream(Source, Dest: TStream; const Key: AnsiString);
var
s: AnsiString;
begin
SetLength(s, Source.Size);
Source.Read(s[1], Source.Size);
if (s <> '') and (s[1] = 'r') and (s[2] = 'i') and (s[3] = 'j') then
begin
Delete(s, 1, 3);
s := DecryptString(s, MakeKey(Key));
end;
Dest.Write(s[1], Length(s));
end;
{ TEasyCustomCrypter }
constructor TEasyCustomCrypter.Create(AOwner: TComponent);
begin
inherited;
// EasyCrypterClass := TEasyCrypterClass(ClassType);
end;
destructor TEasyCustomCrypter.Destroy;
begin
if FStream <> nil then
FStream.Free;
inherited;
end;
procedure TEasyCustomCrypter.CreaEasyream;
begin
FStream := TMemoryStream.Create;
end;
{ TEasyCrypt }
function TEasyCrypt.AskKey(const Key: AnsiString): AnsiString;
begin
Result := Key;
{if Result = '' then
with TfrmEasyCryptPassw.Create(Application) do
begin
if ShowModal = mrOk then
Result := AnsiString(PasswordE.Text);
Free;
end;}
end;
procedure TEasyCrypt.Crypt(Dest: TStream; const Key: AnsiString);
begin
EasyCryptStream(Stream, Dest, Key);
end;
function TEasyCrypt.Decrypt(Source: TStream; const Key: AnsiString): Boolean;
var
Signature: array[0..2] of Byte;
begin
Source.Read(Signature, 3);
Source.Seek(-3, soFromCurrent);
Result := (Signature[0] = Ord('r')) and (Signature[1] = Ord('i')) and (Signature[2] = Ord('j'));
if Result then
EasyDecryptStream(Source, Stream, AskKey(Key));
Stream.Position := 0;
end;
end.
|
unit SpaceToTab;
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is SpaceToTab, released May 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
{$I JcfGlobal.inc}
interface
{ AFS 4 Jan 2002
convert spaces tabs }
uses SwitchableVisitor;
type
TSpaceToTab = class(TSwitchableVisitor)
private
fsSpaces: string;
protected
function EnabledVisitSourceToken(const pcNode: TObject): boolean; override;
public
constructor Create; override;
function IsIncludedInSettings: boolean; override;
end;
implementation
uses
SysUtils,
{ local }
JcfStringUtils,
JcfSettings, SourceToken, Tokens, FormatFlags;
constructor TSpaceToTab.Create;
begin
inherited;
fsSpaces := string(StrRepeat(NativeSpace, JcfFormatSettings.Spaces.SpacesForTab));
FormatFlags := FormatFlags + [eAddSpace, eRemoveSpace];
end;
function TSpaceToTab.EnabledVisitSourceToken(const pcNode: TObject): Boolean;
var
lcSourceToken, lcNextToken: TSourceToken;
ls, lsTab: string;
begin
Result := False;
lcSourceToken := TSourceToken(pcNode);
{ work only on whitespace tokens.
Indent spaces also occur in multiline comments, but leave them alone }
if (lcSourceToken.TokenType <> ttWhiteSpace) then
exit;
{ Merge following space tokens
can't pass property as var parameter so ls local var is used }
ls := lcSourceToken.SourceCode;
lcNextToken := lcSourceToken.NextToken;
while (lcNextToken <> nil) and (lcNextToken.TokenType = ttWhiteSpace) do
begin
ls := ls + lcNextToken.SourceCode;
lcNextToken.SourceCode := '';
lcNextToken := lcNextToken.NextToken;
end;
lsTab := NativeTab;
StrReplace(ls, fsSpaces, lsTab, [rfReplaceAll]);
lcSourceToken.SourceCode := ls;
end;
function TSpaceToTab.IsIncludedInSettings: boolean;
begin
Result := JcfFormatSettings.Spaces.SpacesToTabs;
end;
end.
|
{ *******************************************************
Threading utilities for Delphi 2009 and above
Utilidad para programación concurrente.
*******************************************************
2012 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
******************************************************* }
unit ThreadUtils.SafeDataTypes;
{
SUMMARY:
- TThreadSafeQueue: Thread-safe implementation of first-in last-out queue.
- TThreadSafeStack: Thread-safe implementation of first-in first-out stack.
}
interface
uses
SyncObjs, ThreadUtils.Sync, System.Generics.Collections;
{ TThreadSafeQueue
PURPOUSE:
Thread-safe implementation of first-in last-out queue.
ENQUEUE:
Non-blocking primitive. Stores an item into the queue, so it becomes
non empty.
DEQUEUE:
Calling thread is locked while queue is empty, then an item is extracted
from the queue and returned. Threads are also unlocked by raising an
EAbandoned exception, which happens at instance destruction.
WAITFOR:
Calling thread is locked until queue is empty or an EAbandoned exception
is raised at instance destruction.
EXAMPLE:
while not Terminated do
try
item := q.dequeue(item)
<<do something with item>>
except
on EAbandoned do Terminate;
end;
}
type
TThreadSafeQueue<T> = class
private type
TQueueNode = class
Next: TQueueNode;
Item: T;
end;
private
FHead: TQueueNode;
FTail: TQueueNode;
CSTail: TCriticalSection;
CSHead: TCriticalSection;
NotEmpty: TPrecondition;
Empty: TPrecondition;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Enqueue(Item: T);
function Dequeue: T;
function isEmpty: boolean;
function WaitFor(Timeout: cardinal = INFINITE): TWaitResult;
end;
{ TThreadSafeStack
PURPOUSE:
Thread-safe implementation of first-in first-out stack.
PUSH:
Non-blocking primitive. Stores an item at the top of the queue,
so it becomes non empty.
POP:
Calling thread is locked while stack is empty, then, top item is extracted
from the stack and returned. Threads are also unlocked by raising an
EAbandoned exception, which happens at instance destruction.
WAITFOR:
Calling thread is locked until queue is empty or an EAbandoned exception
is raised at instance destruction.
EXAMPLE:
while not Terminated do
try
item := stack.pop(item)
<<do something with item>>
except
on EAbandoned do Terminate;
end;
}
type
TThreadSafeStack<T> = class
private
FImpl: TQueue<T>;
CS: TCriticalSection;
NotEmpty: TPrecondition;
Empty: TPrecondition;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Push(Item: T);
function Pop: T;
function isEmpty: boolean;
function WaitFor(Timeout: cardinal = INFINITE): TWaitResult;
end;
type
EAbandoned = class(ESyncObjectException);
implementation
uses
sysutils;
// -----------------------------------------------------------------------------
// TThreadSafeQueue
// -----------------------------------------------------------------------------
constructor TThreadSafeQueue<T>.Create;
begin
FHead := TQueueNode.Create;
FHead.Next := nil;
FTail := FHead;
CSHead := TCriticalSection.Create;
CSTail := TCriticalSection.Create;
NotEmpty := TPrecondition.Create(
function: boolean
begin
Result := (FHead.Next <> nil)
end);
Empty := TPrecondition.Create(
function: boolean
begin
Result := (FHead.Next = nil);
end);
end;
// -----------------------------------------------------------------------------
function TThreadSafeQueue<T>.isEmpty: boolean;
begin
Result := (FHead.Next = nil);
end;
// -----------------------------------------------------------------------------
destructor TThreadSafeQueue<T>.Destroy;
var
oldHead: TQueueNode;
begin
NotEmpty.Cancel; // unlock waiting threads
Empty.Cancel; // unlock waiting threads
// free allocated memory
Clear;
// free other objects
CSHead.Free;
// CSTail.Free;
NotEmpty.Free;
Empty.Free;
inherited;
end;
// -----------------------------------------------------------------------------
procedure TThreadSafeQueue<T>.Enqueue(Item: T);
var
NewNode: TQueueNode;
begin
NewNode := TQueueNode.Create;
NewNode.Item := Item;
NewNode.Next := nil;
CSTail.Acquire;
try
FTail.Next := NewNode;
FTail := NewNode;
finally
CSTail.Release;
end;
Empty.Update;
NotEmpty.Update;
end;
// -----------------------------------------------------------------------------
function TThreadSafeQueue<T>.Dequeue: T;
var
OldNode: TQueueNode;
begin
OldNode := nil;
CSHead.Acquire;
try
if (NotEmpty.WaitFor(CSHead) = wrSignaled) then
begin
OldNode := FHead;
FHead := FHead.Next;
Result := FHead.Item;
end;
finally
CSHead.Release;
end;
if (OldNode <> nil) then
begin
OldNode.Free;
NotEmpty.Update;
Empty.Update;
end
else
raise EAbandoned.Create('TThreadSafeQueue was abandoned');
end;
// -----------------------------------------------------------------------------
procedure TThreadSafeQueue<T>.Clear;
var
oldHead: TQueueNode;
begin
CSHead.Acquire;
try
while (FHead.Next <> nil) do
begin
oldHead := FHead;
FHead := FHead.Next;
oldHead.Free;
end;
finally
CSHead.Release;
end;
NotEmpty.Update;
Empty.Update;
end;
// -----------------------------------------------------------------------------
function TThreadSafeQueue<T>.WaitFor(Timeout: cardinal = INFINITE): TWaitResult;
begin
CSHead.Acquire;
try
Result := Empty.WaitFor(CSHead, Timeout);
if (Result <> wrSignaled) and (Result <> wrTimeout) then
raise EAbandoned.Create('TThreadSafeQueue was abandoned');
finally
CSHead.Release;
end;
end;
// -----------------------------------------------------------------------------
// TThreadSafeStack
// -----------------------------------------------------------------------------
constructor TThreadSafeStack<T>.Create;
begin
CS := TCriticalSection.Create;
FImpl := TQueue<T>.Create;
NotEmpty := TPrecondition.Create(
function: boolean
begin
Result := (FImpl.Count > 0)
end);
Empty := TPrecondition.Create(
function: boolean
begin
Result := (FImpl.Count = 0);
end);
end;
// -----------------------------------------------------------------------------
function TThreadSafeStack<T>.isEmpty: boolean;
begin
CS.Acquire;
Result := (FImpl.Count = 0);
CS.Release;
end;
// -----------------------------------------------------------------------------
destructor TThreadSafeStack<T>.Destroy;
begin
NotEmpty.Cancel;
Empty.Cancel;
FImpl.Free;
CS.Free;
NotEmpty.Free;
Empty.Free;
inherited;
end;
// -----------------------------------------------------------------------------
procedure TThreadSafeStack<T>.Push(Item: T);
begin
CS.Acquire;
try
FImpl.Enqueue(Item);
finally
CS.Release;
end;
Empty.Update;
NotEmpty.Update;
end;
// -----------------------------------------------------------------------------
function TThreadSafeStack<T>.Pop: T;
var
wr: TWaitResult;
begin
CS.Acquire;
try
wr := NotEmpty.WaitFor(CS);
if (wr = wrSignaled) then
Result := FImpl.Dequeue
finally
CS.Release;
end;
if (wr = wrSignaled) then
begin
NotEmpty.Update;
Empty.Update;
end
else
raise EAbandoned.Create('TThreadSafeStack was abandoned');
end;
// -----------------------------------------------------------------------------
procedure TThreadSafeStack<T>.Clear;
begin
CS.Acquire;
try
FImpl.Clear;
finally
CS.Release;
end;
NotEmpty.Update;
Empty.Update;
end;
// -----------------------------------------------------------------------------
function TThreadSafeStack<T>.WaitFor(Timeout: cardinal = INFINITE): TWaitResult;
begin
CS.Acquire;
try
Result := Empty.WaitFor(CS, Timeout);
if (Result <> wrSignaled) and (Result <> wrTimeout) then
raise EAbandoned.Create('TThreadSafeStack was abandoned');
finally
CS.Release;
end;
end;
// -----------------------------------------------------------------------------
end.
|
unit elcohttpclient;
interface
uses superobject, System.sysutils;
type
ERemoteError = class(Exception);
function GetResponse(method: string; params: ISuperobject): ISuperobject;
implementation
uses registry, System.Net.HttpClient, winapi.windows,
ujsonrpc, classes, System.Net.URLClient;
function _httpaddr: string;
var
key: TRegistry;
begin
key := TRegistry.Create(KEY_READ);
try
if not key.OpenKey('elco\http', False) then
raise Exception.Create('cant open elco\http');
result := key.ReadString('addr');
finally
key.CloseKey;
key.Free;
end;
end;
function formatMessagetype(mt: TJsonRpcObjectType): string;
begin
case mt of
jotInvalid:
exit('invalid');
jotRequest:
exit('request');
jotNotification:
exit('notification');
jotSuccess:
exit('success');
jotError:
exit('error');
end;
end;
function GetResponse(method: string; params: ISuperobject): ISuperobject;
var
HttpClient: THTTPClient;
requestStream: TStringStream;
response: IHTTPResponse;
headers: TNetHeaders;
JsonRpcParsedResponse: IJsonRpcParsed;
rx: ISuperObject;
begin
try
HttpClient := THTTPClient.Create();
SetLength(headers, 2);
headers[0].Name := 'Content-Type';
headers[0].Value := 'application/json';
headers[1].Name := 'Accept';
headers[1].Value := 'application/json';
requestStream := TStringStream.Create(TJsonRpcMessage.request(0, method,
params).AsJSon);
response := HttpClient.Post(_httpaddr + '/rpc', requestStream,
nil, headers);
if response.StatusCode <> 200 then
raise Exception.Create(Inttostr(response.StatusCode) + ': ' +
response.StatusText);
JsonRpcParsedResponse := TJsonRpcMessage.Parse
(response.ContentAsString);
if not Assigned(JsonRpcParsedResponse) then
raise Exception.Create(Format('%s%s: unexpected nil response',
[method, params.AsString]));
if not Assigned(JsonRpcParsedResponse.GetMessagePayload) then
raise Exception.Create
(Format('%s%s: unexpected nil message payload',
[method, params.AsString]));
rx := JsonRpcParsedResponse.GetMessagePayload.AsJsonObject;
if Assigned(rx['result']) then
begin
result := rx['result'];
exit;
end;
if Assigned(rx['error.message']) then
raise ERemoteError.Create(rx['error'].S['message']);
raise Exception.Create(Format('%s%s'#13'%s'#13'message type: %s',
[method, params.AsString, JsonRpcParsedResponse.GetMessagePayload,
formatMessagetype(JsonRpcParsedResponse.GetMessageType)]));
finally
HttpClient.Free;
requestStream.Free;
end;
end;
end.
|
{*
DialogLongMessage.pas/dfm
-------------------------
Begin: 2005/06/20
Last revision: $Date: 2011-09-30 19:12:57 $ $Author: areeves $
Version number: $Revision: 1.19 $
Project: APHI General Purpose Delphi Libary
Website: http://www.naadsm.org/opensource/delphi/
Author: Aaron Reeves <aaron.reeves@naadsm.org>
--------------------------------------------------
Copyright (C) 2005 - 2013 NAADSM Development Team
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.
---------------------------------------------------
Used by many of the sm_forms units to display errors or warnings and present information to the user.
Long multi-line messages can be displayed and the message contents can be copied to the clipboard.
}
(*
Documentation generation tags begin with {* or ///
Replacing these with (* or // foils the documentation generator
*)
unit DialogLongMessage;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ExtCtrls
;
type
{*
Unit for displaying messages at runtime, inherits from TForm.
Long multi-line messages can be displayed with scroll control and the
message contents can be copied to the clipboard.
}
TDialogLongMessage = class( TForm )
mmoLongMessage: TMemo;
pnlBase: TPanel;
pnlButtons: TPanel;
btnOK: TButton;
btnCopy: TButton;
pnlHeader: TPanel;
pnlLeftMargin: TPanel;
procedure FormCreate(Sender: TObject);
{ Closes the dialog. }
procedure btnOKClick(Sender: TObject);
{ Copies contents of the memo control to the clipboard. }
procedure btnCopyClick(Sender: TObject);
protected
_closeFormOnOK: boolean;
procedure initialize();
procedure translateUI();
public
constructor create( AOwner: TComponent ); overload; override;
{ Creates the form with the designated caption, header, and message. }
constructor create(
AOwner: TComponent;
cap: string = '';
header: string = '';
msg: string = ''
); reintroduce; overload;
{ Sets the text of the long message to display. }
procedure setMessage( msg: string );
procedure appendMessage( msg: string );
{ Sets the text of the header. }
procedure setHeader( header: string );
{ Clears the contents of the form. }
procedure clear();
procedure disableFormClose();
procedure enableFormClose();
procedure show( const alwaysOnTop: boolean );
property header: string write setHeader;
property msg: string write setMessage;
end
;
implementation
{$R *.dfm}
uses
ControlUtils,
MyStrUtils,
I88n
;
constructor TDialogLongMessage.create( AOwner: TComponent );
begin
inherited create( AOwner );
initialize();
end
;
{*
Creates the form with the designated form caption, header (in pnlHeader), and message.
@param AOwner Form that owns the message dialog
@param cap text to be displayed in the form caption area to identify the subject to the user
@param header A place to put a longer directive to the user than can be displayed in the caption
@param msg some multi-line message; perhaps the logged outcome from a process, or the contents of a text file
}
constructor TDialogLongMessage.create(
AOwner: TComponent;
cap: string = '';
header: string = '';
msg: string = ''
);
begin
inherited create( AOwner );
initialize();
if( 0 <> length( trim( cap ) ) ) then
self.Caption := cap
;
if( 0 <> length( trim( header ) ) ) then
setHeader( header )
;
if( 0 <> length( trim( msg ) ) ) then
setMessage( msg )
;
end
;
procedure TDialogLongMessage.initialize();
begin
translateUI();
horizCenterInside( pnlButtons, pnlBase );
_closeFormOnOK := false;
end
;
/// Specifies the captions, hints, and other component text phrases for translation
procedure TDialogLongMessage.translateUI();
begin
// This function was generated automatically by Caption Collector 0.6.0.
// Generation date: Mon Feb 25 15:29:38 2008
// File name: C:/Documents and Settings/apreeves/My Documents/NAADSM/Interface-Fremont/general_purpose_gui/DialogLongMessage.dfm
// File date: Tue Oct 10 08:22:48 2006
// Set Caption, Hint, Text, and Filter properties
with self do
begin
Caption := tr( 'Form1' );
btnOK.Caption := tr( 'OK' );
btnCopy.Caption := tr( 'Copy message' );
end
;
end
;
/// Initializes the dialog form when first created. Applications do not call FormCreate
procedure TDialogLongMessage.FormCreate(Sender: TObject);
begin
Assert(not Scaled, 'You should set Scaled property of Form to False!');
if Screen.PixelsPerInch <> 96 then
begin
ScaleBy( Screen.PixelsPerInch, 96 );
self.width := round( self.width * ( screen.pixelsPerInch / 96 ) );
self.height := round( self.height * ( screen.pixelsPerInch / 96 ) );
end
;
end
;
/// OnClick event that closes the dialog form.
procedure TDialogLongMessage.btnOKClick(Sender: TObject);
begin
if( _closeFormOnOK ) then
close()
else
hide()
;
end
;
/// Prevents the user from closing the form by disabling the OK button and the title bar close button
procedure TDialogLongMessage.disableFormClose();
var
AppSysMenu: THandle;
begin
// Clicking on OK will NOT delete the form. The form will only be hidden.
// It will not be possible to use the "close" button to delete the form, either.
_closeFormOnOK := false;
(*
btnOK.Enabled := false;
*)
// See http://www.greatis.com/delphicb/tips/lib/system-hideclose.html
AppSysMenu:=GetSystemMenu( Handle, False );
EnableMenuItem( AppSysMenu, SC_CLOSE, MF_BYCOMMAND or MF_GRAYED );
end
;
/// Enables closing the form by enabling the OK button and the title bar close button
procedure TDialogLongMessage.enableFormClose();
var
AppSysMenu: THandle;
begin
// Clicking on OK will delete the form.
// It will now be possible to use the "close" button to delete the form.
_closeFormOnOK := true;
(*
btnOK.Enabled := true;
*)
// See http://www.greatis.com/delphicb/tips/lib/system-hideclose.html
AppSysMenu := GetSystemMenu( Handle, False );
EnableMenuItem( AppSysMenu, SC_CLOSE, MF_BYCOMMAND or MF_ENABLED );
end
;
{*
Shows the dialog form in the event it had been hidden.
@param alwaysOnTop Makes the dialog window stay on top, even when another window has focus
}
procedure TDialogLongMessage.show( const alwaysOnTop: boolean );
begin
inherited show();
if( alwaysOnTop ) then
begin
//Possible values for placement-order handle:
// HWND_BOTTOM: Places the window at the bottom of the Z order.
// HWND_NOTOPMOST: Places the window above all non-topmost windows
// HWND_TOP: Places the window at the top of the Z order.
// HWND_TOPMOST: Places the window above all non-topmost windows.
// The window maintains its topmost position even when it is deactivated.
// See http://www.swissdelphicenter.ch/torry/showcode.php?id=6
SetWindowPos(
self.Handle, // handle to window
HWND_TOPMOST, // placement-order handle
self.Left, // horizontal position
self.Top, // vertical position
self.Width,
self.Height,
SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE // window-positioning options
);
end
;
end
;
/// Copies contents of the memo control to the clipboard.
procedure TDialogLongMessage.btnCopyClick(Sender: TObject);
begin
mmoLongMessage.SelectAll();
mmoLongMessage.CopyToClipboard();
end
;
/// Sets the text of the memo control.
procedure TDialogLongMessage.setMessage( msg: string );
begin
mmoLongMessage.Lines.Text := msg;
end
;
{*
Appends text to the memo control.
@param msg text to append to the dialog contents
}
procedure TDialogLongMessage.appendMessage( msg: string );
begin
mmoLongMessage.Lines.Append( msg );
end
;
/// Clears the contents of the dialog output text
procedure TDialogLongMessage.clear();
begin
mmoLongMessage.Clear();
end
;
/// Sets the text of the header ( the panel at the top of the form).
procedure TDialogLongMessage.setHeader( header: string );
var
str: string;
strList: TStringList;
lbl: TLabel;
i: integer;
vertPos: integer;
begin
str := prettyPrint( header, 70 );
strList := TStringList.Create();
strList.Text := str;
vertPos := 10;
for i := 0 to strList.Count - 1 do
begin
lbl := TLabel.Create( pnlHeader );
lbl.Parent := pnlHeader;
lbl.Caption := strList.Strings[i];
lbl.Top := vertPos;
lbl.Width := self.Canvas.TextWidth( strList.Strings[i] );
lbl.Height := self.Canvas.TextHeight( 'Ag' );
lbl.Left := ( pnlHeader.Width - lbl.Width ) div 2;
lbl.Show();
// lbl will be destroyed with the form
inc( vertPos, lbl.Height );
end
;
pnlHeader.Height := ( strList.Count * self.Canvas.TextHeight( 'Ag' ) ) + 20;
strList.Free();
end
;
end.
|
{**
* @Author: Du xinming
* @Contact: QQ<36511179>; Email<lndxm1979@163.com>
* @Version: 0.0
* @Date: 2018.10
* @Brief:
*}
unit org.utilities.buffer;
interface
uses
WinApi.Windows,
System.SysUtils,
System.Classes,
org.algorithms.queue;
type
TBuffer = class
public
function GetBuffer(Buffer: PAnsiChar; Len: DWORD): DWORD; virtual; abstract;
end;
TByteBuffer = class(TBuffer)
private
FAutoFree: Boolean;
FBuffer: PAnsiChar;
FLength: DWORD;
FAvailable: DWORD;
public
destructor Destroy; override;
procedure SetBuffer(Buffer: PAnsiChar; Len: DWORD; AutoFree: Boolean = True);
function GetBuffer(Buffer: PAnsiChar; Len: DWORD): DWORD; override;
end;
TFileBuffer = class(TBuffer)
private
FFileHandle: THandle;
FFileLength: Int64;
FFileAvailable: Int64;
public
destructor Destroy; override;
procedure SetBuffer(FileHandle: THandle; FileLength: Int64);
function GetBuffer(Buffer: PAnsiChar; Len: DWORD): DWORD; override;
end;
TStreamBuffer = class(TBuffer)
private
FStream: TStream;
public
destructor Destroy; override;
procedure SetBuffer(AStream: TStream);
function GetBuffer(Buffer: PAnsiChar; Len: DWORD): DWORD; override;
end;
TBufferPool = class
private
FBufferSize: UInt64;
FBaseAddress: UInt64;
FCurrAddress: UInt64;
FAvailableBuffers: TFlexibleQueue<Pointer>;
public
destructor Destroy; override;
procedure Initialize(ReserveBufferCount, InitBufferCount, BufferSize: UInt64);
function AllocateBuffer: Pointer;
procedure ReleaseBuffer(Buffer: Pointer);
property BufferSize: UInt64 read FBufferSize;
end;
implementation
{ TByteBuffer }
destructor TByteBuffer.Destroy;
begin
if FAutoFree then begin
FreeMem(FBuffer, FLength);
FBuffer := nil;
end;
FLength := 0;
FAvailable := 0;
inherited;
end;
function TByteBuffer.GetBuffer(Buffer: PAnsiChar; Len: DWORD): DWORD;
begin
Result := Len;
if FAvailable >= Len then begin
Move(FBuffer^, Buffer^, Len);
Inc(FBuffer, Len);
Dec(FAvailable, Len);
end
else begin
Result := FAvailable;
Move(FBuffer^, Buffer^, FAvailable);
Dec(FBuffer, FLength - FAvailable);
FAvailable := 0;
end;
end;
procedure TByteBuffer.SetBuffer(Buffer: PAnsiChar; Len: DWORD; AutoFree: Boolean);
begin
FAutoFree := AutoFree;
FBuffer := Buffer;
FLength := Len;
FAvailable := Len;
end;
{ TFileBuffer }
destructor TFileBuffer.Destroy;
begin
FileClose(FFileHandle);
inherited;
end;
function TFileBuffer.GetBuffer(Buffer: PAnsiChar; Len: DWORD): DWORD;
begin
Result := Len;
if FFileAvailable >= Len then begin
FileRead(FFileHandle, Buffer^, Len);
Dec(FFileAvailable, Len);
end
else begin
Result := FFileAvailable;
FileRead(FFileHandle, Buffer^, FFileAvailable);
FFileAvailable := 0;
end;
end;
procedure TFileBuffer.SetBuffer(FileHandle: THandle; FileLength: Int64);
begin
FFileHandle := FileHandle;
FileSeek(FFileHandle, 0, 0);
FFileLength := FileLength;
FFileAvailable := FileLength;
end;
{ TBufferPool }
function TBufferPool.AllocateBuffer: Pointer;
begin
Result := FAvailableBuffers.Dequeue();
if Result = nil then begin
Result := VirtualAlloc(Pointer(FCurrAddress), FBufferSize, MEM_COMMIT, PAGE_READWRITE);
if Result <> nil then
Inc(FCurrAddress, FBufferSize)
else
raise Exception.Create('no more buffer!!');
end;
end;
destructor TBufferPool.Destroy;
begin
VirtualFree(Pointer(FBaseAddress), 0, MEM_RELEASE);
FAvailableBuffers.Free();
inherited;
end;
procedure TBufferPool.Initialize(ReserveBufferCount, InitBufferCount, BufferSize: UInt64);
var
I: Integer;
Buffer: Pointer;
Address: Pointer;
begin
if BufferSize mod 4096 <> 0 then
raise Exception.Create('缓冲大小必须是4KB的整数倍');
FBufferSize := BufferSize;
FAvailableBuffers := TFlexibleQueue<Pointer>.Create(InitBufferCount);
Address := VirtualAlloc(nil, ReserveBufferCount * BufferSize, MEM_TOP_DOWN or MEM_RESERVE, PAGE_READWRITE);
if Address = nil then
raise Exception.CreateFmt('预定虚拟地址空间失败 LastErrorCode=%d', [GetLastError()]);
FBaseAddress := UInt64(Address);
FCurrAddress := FBaseAddress;
for I := 0 to InitBufferCount - 1 do begin
Buffer := VirtualAlloc(Pointer(FCurrAddress), BufferSize, MEM_COMMIT, PAGE_READWRITE);
Inc(FCurrAddress, BufferSize);
FAvailableBuffers.Enqueue(Buffer);
end;
end;
procedure TBufferPool.ReleaseBuffer(Buffer: Pointer);
begin
FAvailableBuffers.Enqueue(Buffer);
end;
{ TStreamBuffer }
destructor TStreamBuffer.Destroy;
begin
FStream.Free();
inherited;
end;
function TStreamBuffer.GetBuffer(Buffer: PAnsiChar; Len: DWORD): DWORD;
begin
Result := FStream.Read(Buffer^, Len);
end;
procedure TStreamBuffer.SetBuffer(AStream: TStream);
begin
FStream := AStream;
FStream.Seek(0, soBeginning);
end;
end.
|
unit Security.Matrix.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.Imaging.jpeg, System.StrUtils,
PngSpeedButton, PngFunctions
, Security.Matrix.Interfaces
;
type
TSecurityMatrixView = class(TForm, iMatrixView, iPrivateMatrixEvents, iMatrixViewEvents)
EditCreatedAt: TEdit;
EditEmail: TEdit;
EditID: TEdit;
EditName: TEdit;
ImageLogo: TImage;
ImageName: TImage;
ImageNameError: TImage;
ImageNewPassword: TImage;
LabelEmail: TLabel;
LabelID: TLabel;
LabelIPComputerCaption: TLabel;
LabelIPComputerValue: TLabel;
LabelIPServerCaption: TLabel;
LabelIPServerValue: TLabel;
LabelPassword: TLabel;
LabelTableStatus: TLabel;
Panel1: TPanel;
Panel2: TPanel;
PanelEmail: TPanel;
PanelFundo: TPanel;
PanelImageEmail: TPanel;
PanelImageNameError: TPanel;
PanelImagePassword: TPanel;
PanelName: TPanel;
PanelStatus: TPanel;
PanelStatusBackground: TPanel;
PanelStatusBackgroundClient: TPanel;
PanelStatusShapeBottom: TShape;
PanelStatusShapeLeft: TShape;
PanelStatusShapeRight: TShape;
PanelTitle: TPanel;
PanelTitleAppInfo: TPanel;
PanelTitleAppInfoUpdated: TPanel;
PanelTitleAppInfoUpdatedCaption: TLabel;
PanelTitleAppInfoUpdatedValue: TLabel;
PanelTitleAppInfoVersion: TPanel;
PanelTitleAppInfoVersionCaption: TLabel;
PanelTitleAppInfoVersionValue: TLabel;
PanelTitleBackgroung: TPanel;
PanelTitleDOT: TLabel;
PanelTitleLabelAutenticacao: TLabel;
PanelTitleLabelSigla: TLabel;
PanelToolbar: TPanel;
PngSpeedButtonCancelar: TPngSpeedButton;
PngSpeedButtonOk: TPngSpeedButton;
ShapeBodyLeft: TShape;
ShapeBodyRight: TShape;
ShapePanelTitleBottom: TShape;
ShapePanelTitleLeft: TShape;
ShapePanelTitleRight: TShape;
ShapePanelTitleTop: TShape;
ShapeToolbarBottom: TShape;
ShapeToolbarLeft: TShape;
ShapeToolbarRight: TShape;
ShapeToolbarTop: TShape;
CheckBoxActive: TCheckBox;
procedure PngSpeedButtonCancelarClick(Sender: TObject);
procedure PngSpeedButtonOkClick(Sender: TObject);
procedure EditNameChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
strict private
FID : Int64;
FUpdatedAt : TDateTime;
FNameMatrix : String;
FEmail : String;
FActive : Boolean;
FPassword : String;
FMatrixID : Integer;
FIsMatrix : Boolean;
FChangedMatrix: Boolean;
FOnMatrix: TMatrixNotifyEvent;
FOnResult: TResultNotifyEvent;
{ Strict private declarations }
procedure setID(Value: Int64);
function getID: Int64;
function getUpdatedAt: TDateTime;
procedure setUpdatedAt(const Value: TDateTime);
procedure setNameMatrix(Value: String);
function getNameMatrix: String;
procedure setEmail(Value: String);
function getEmail: String;
procedure setActive(Value: Boolean);
function getActive: Boolean;
procedure setPassword(Value: String);
function getPassword: String;
procedure setMatrixID(Value: Integer);
function getMatrixID: Integer;
procedure setIsMatrix(Value: Boolean);
function getIsMatrix: Boolean;
procedure setOnMatrix(const Value: TMatrixNotifyEvent);
function getOnMatrix: TMatrixNotifyEvent;
procedure setOnResult(const Value: TResultNotifyEvent);
function getOnResult: TResultNotifyEvent;
private
{ Private declarations }
procedure Validate;
procedure doMatrix;
procedure doResult;
public
{ Public declarations }
function Events: iMatrixViewEvents;
published
{ Published declarations - Properties }
property ID : Int64 read getID write setID;
property UpdatedAt : TDateTime read getUpdatedAt write setUpdatedAt;
property NameMatrix: String read getNameMatrix write setNameMatrix;
property Email : String read getEmail write setEmail;
property Active : Boolean read getActive write setActive;
property Password : String read getPassword write setPassword;
property MatrixID : Integer read getMatrixID write setMatrixID;
property IsMatrix : Boolean read getIsMatrix write setIsMatrix;
{ Published declarations - Events }
property OnMatrix: TMatrixNotifyEvent read getOnMatrix write setOnMatrix;
property OnResult: TResultNotifyEvent read getOnResult write setOnResult;
end;
var
SecurityMatrixView: TSecurityMatrixView;
implementation
uses
Security.Internal;
{$R *.dfm}
{ TSecurityMatrixView }
procedure TSecurityMatrixView.EditNameChange(Sender: TObject);
var
LNome: string;
begin
LNome := EditName.Text;
LNome := StringReplace(Trim(Internal.RemoveAcento(LNome)), ' ', '_', [rfReplaceAll, rfIgnoreCase]);
if SameStr(LNome, EmptyStr) then
LNome := 'nao_informado';
EditEmail.Text := LowerCase(LNome) + '@matrix&.com';
end;
procedure TSecurityMatrixView.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Application.RestoreTopMosts;
doResult;
end;
procedure TSecurityMatrixView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_RETURN:
begin
if ActiveControl = CheckBoxActive then
PngSpeedButtonOk.Click
else
SelectNext(ActiveControl, true, true);
Key := VK_CANCEL;
end;
end;
end;
function TSecurityMatrixView.Events: iMatrixViewEvents;
begin
Result := Self;
end;
{ Published declarations - Properties }
procedure TSecurityMatrixView.setID(Value: Int64);
begin
FID := Value;
EditID.Text := Value.ToString;
LabelTableStatus.Caption := IFThen(Value = 0, 'Criando', 'Editando');
end;
function TSecurityMatrixView.getID: Int64;
begin
Result := FID;
end;
procedure TSecurityMatrixView.setNameMatrix(Value: String);
begin
FNameMatrix := Value;
EditName.Text := FNameMatrix;
end;
function TSecurityMatrixView.getNameMatrix: String;
begin
Result := FNameMatrix;
end;
procedure TSecurityMatrixView.setEmail(Value: String);
begin
FEmail := Value;
EditEmail.Text := FEmail;
end;
function TSecurityMatrixView.getEmail: String;
begin
Result := FEmail;
end;
procedure TSecurityMatrixView.setActive(Value: Boolean);
begin
FActive := Value;
CheckBoxActive.Checked := FActive;
end;
function TSecurityMatrixView.getActive: Boolean;
begin
Result := FActive;
end;
procedure TSecurityMatrixView.setPassword(Value: String);
begin
FPassword := Value;
end;
function TSecurityMatrixView.getPassword: String;
begin
Result := FPassword;
end;
procedure TSecurityMatrixView.setUpdatedAt(const Value: TDateTime);
begin
FUpdatedAt := Value;
EditCreatedAt.Text := IFThen(FUpdatedAt = 0, '', FormatDateTime('dd.mm.yyyy HH:mm', FUpdatedAt));
end;
function TSecurityMatrixView.getUpdatedAt: TDateTime;
begin
Result := FUpdatedAt;
end;
procedure TSecurityMatrixView.setMatrixID(Value: Integer);
begin
FMatrixID := Value;
end;
function TSecurityMatrixView.getMatrixID: Integer;
begin
Result := FMatrixID;
end;
procedure TSecurityMatrixView.setIsMatrix(Value: Boolean);
begin
FIsMatrix := Value;
end;
function TSecurityMatrixView.getIsMatrix: Boolean;
begin
Result := FIsMatrix;
end;
{ Published declarations - Events }
procedure TSecurityMatrixView.setOnMatrix(const Value: TMatrixNotifyEvent);
begin
FOnMatrix := Value;
end;
function TSecurityMatrixView.getOnMatrix: TMatrixNotifyEvent;
begin
Result := FOnMatrix;
end;
procedure TSecurityMatrixView.setOnResult(const Value: TResultNotifyEvent);
begin
FOnResult := Value;
end;
function TSecurityMatrixView.getOnResult: TResultNotifyEvent;
begin
Result := FOnResult;
end;
procedure TSecurityMatrixView.Validate;
begin
// Validações
Internal.Validate(EditName, Internal.IsEmpty(EditName.Text), 'Informe o [Nome].', PanelImageNameError, ImageNameError);
end;
procedure TSecurityMatrixView.doMatrix;
var
LError: string;
LKey : string;
begin
SelectFirst;
Validate;
LKey := EditName.Text + EditEmail.Text + DateTimeToStr(now);
FNameMatrix := EditName.Text;
FEmail := EditEmail.Text;
FActive := CheckBoxActive.Checked;
FPassword := Internal.MD5(LKey);
FMatrixID := 0;
FIsMatrix := true;
LError := EmptyStr;
FChangedMatrix := False;
OnMatrix(ID, NameMatrix, Email, Active, Password, MatrixID, IsMatrix, LError, FChangedMatrix);
Internal.Die(LError);
if FChangedMatrix then
Close;
end;
procedure TSecurityMatrixView.doResult;
begin
try
if not Assigned(FOnResult) then
Exit;
FOnResult(FChangedMatrix);
finally
Application.NormalizeAllTopMosts;
BringToFront;
end;
end;
procedure TSecurityMatrixView.PngSpeedButtonOkClick(Sender: TObject);
begin
doMatrix;
end;
procedure TSecurityMatrixView.PngSpeedButtonCancelarClick(Sender: TObject);
begin
FChangedMatrix := False;
Close;
end;
end.
|
// *******************************************************
//
// playIoT Global Library
//
// Copyright(c) 2016 playIoT.
//
// jsf3rd@playiot.biz
//
//
// *******************************************************
unit JdcGlobal;
interface
uses
Classes, SysUtils, Windows, ZLib, IdGlobal, IOUtils, JclFileUtils, Vcl.ExtCtrls,
IdUDPClient, JclSysInfo, psAPI, IdContext, Vcl.StdCtrls, JclSvcCtrl, Vcl.ActnList,
Vcl.Dialogs, WinApi.Shellapi, UITypes;
type
IExecuteFunc<T> = Interface
['{48E4B912-AE21-4201-88E0-4835432FEE69}']
function Execute(AValue: String): T;
End;
IExecuteProc<T> = Interface
['{48E4B912-AE21-4201-88E0-4835432FEE69}']
procedure Execute(AValue: T);
End;
TMessageType = (msDebug, msInfo, msError, msWarning, msUnknown);
TLogProc = procedure(const AType: TMessageType; const ATitle: String;
const AMessage: String = '') of object;
TOnMessageEvent = procedure(const Sender: TObject; const AName: string;
const AMessage: string = '') of object;
TMsgOutput = (moDebugView, moLogFile, moCloudMessage);
TMsgOutputs = set of TMsgOutput;
TConnInfo = record
StringValue: string;
IntegerValue: integer;
constructor Create(AString: string; AInteger: integer);
function ToString: string;
function Equals(const ConnInfo: TConnInfo): boolean;
end;
TClientInfo = record
Version: string;
Url: string;
end;
TMemoLog = record
Memo: TMemo;
Msg: string;
Time: TDateTime;
constructor Create(AMemo: TMemo; AMsg: string);
end;
TGlobalAbstract = class abstract
protected
FProjectCode: string;
FAppCode: string;
FIsInitialized: boolean;
FIsFinalized: boolean;
FExeName: String;
FLogName: string;
FUseCloudLog: boolean;
FUseDebug: boolean;
FStartTime: TDateTime;
FLogServer: TConnInfo;
procedure SetExeName(const Value: String); virtual; abstract;
procedure _ApplicationMessage(const AType: string; const ATitle: string;
const AMessage: String; const AOutputs: TMsgOutputs = [moDebugView, moLogFile,
moCloudMessage]); virtual;
function GetErrorLogName: string; virtual;
function GetLogName: string; virtual;
procedure SetUseDebug(const Value: boolean); virtual;
public
constructor Create; virtual;
procedure Initialize; virtual;
procedure Finalize; virtual;
procedure ApplicationMessage(const AType: TMessageType; const ATitle: String;
const AMessage: String = ''); overload; virtual;
procedure ApplicationMessage(const AType: TMessageType; const ATitle: String;
const AFormat: String; const Args: array of const); overload;
property ExeName: String read FExeName write SetExeName;
property LogName: string read GetLogName;
property ErrorLogName: string read GetErrorLogName;
property LogServer: TConnInfo read FLogServer write FLogServer;
property UseDebug: boolean read FUseDebug write SetUseDebug;
const
MESSAGE_TYPE_INFO = 'INFO';
MESSAGE_TYPE_ERROR = 'ERROR';
MESSAGE_TYPE_DEBUG = 'DEBUG';
MESSAGE_TYPE_WARNING = 'WARNING';
MESSAGE_TYPE_UNKNOWN = 'UNKNOWN';
end;
// 로그 찍기..
procedure PrintLog(const AFile: string; AMessage: String = ''); overload;
procedure PrintLog(AMemo: TMemo; const AMsg: String = ''); overload;
procedure PrintDebug(const Format: string; const Args: array of const); overload;
procedure PrintDebug(const str: string); overload;
// 특정 자리수 이하 0 만들기
// Value : 값, Digit : 자리수
function TruncInt(Value: integer; Digit: integer): integer;
function CurrentProcessMemory: Cardinal;
function FileVersion(const FileName: String): String;
procedure CloudMessage(const ProjectCode, AppCode, TypeCode, ATitle, AMessage,
AVersion: String; const AServer: TConnInfo);
// 데이터 압축..
function CompressStream(Stream: TStream; OutStream: TStream; OnProgress: TNotifyEvent)
: boolean;
// 데이터 압축 해제..
function DeCompressStream(Stream: TStream; OutStream: TStream;
OnProgress: TNotifyEvent): boolean;
// 응답 검사..
function Contains(Contents: string; const str: array of const): boolean;
function IsGoodResponse(Text, Command: string; Response: array of const): boolean;
// Reverse 2Btyes..
function Rev2Bytes(w: WORD): WORD;
// Reverse 4Btyes..
function Rev4Bytes(Value: Int32): Int32;
// Reverse 4Btyes..
function Rev4BytesF(Value: Single): Single;
// Big endian
function WordToBytes(AValue: WORD): TIdBytes;
// Big endian
function DWordToBytes(AValue: DWORD): TIdBytes;
// little endian
function HexStrToWord(const ASource: string; const AIndex: integer = 1): WORD;
function HexStrToByte(const ASource: String; const AIndex: integer = 1): Byte;
function HexStrToBytes(const ASource: string; const AIndex: integer = 1): TIdBytes;
function IdBytesToHex(const AValue: TIdBytes; const ASpliter: String = ' '): String;
function BytesToHex(const AValue: TBytes; const ASpliter: String = ' '): String;
function IdBytesPos(const SubIdBytes, IdBytes: TIdBytes; const AIndex: integer = 0): integer;
function DefaultFormatSettings: TFormatSettings;
function StrDefault(str: string; Default: string): string;
// Thread Safe
procedure ThreadSafe(AMethod: TThreadMethod); overload;
procedure ThreadSafe(AThreadProc: TThreadProcedure); overload;
procedure FreeAndNilEx(var Obj; const AGlobal: TGlobalAbstract = nil);
function GetPeerInfo(AContext: TIdContext): string;
// 서비스 관리
procedure StartService(const ServiceName: String; var OldStatus: TJclServiceState;
StartAction: TAction);
procedure StopService(const ServiceName: String; var OldStatus: TJclServiceState;
StopAction: TAction; hnd: HWND);
procedure UpdateServiceStatus(const ServiceName: String; var OldStatus: TJclServiceState;
StartAction, StopAction: TAction; StatusEdit: TLabeledEdit);
function IntToBin(Value: Cardinal; Digits: integer): String;
const
LOCAL_SERVER = '\\localhost';
implementation
uses JdcGlobal.ClassHelper;
function IntToBin(Value: Cardinal; Digits: integer): String;
var
S: String;
begin
S := '';
While Digits > 0 do
begin
if Odd(Value) then
S := '1' + S
Else
S := '0' + S;
Value := Value shr 1;
Digits := Digits - 1;
end;
Result := S;
end;
procedure FreeAndNilEx(var Obj; const AGlobal: TGlobalAbstract);
begin
try
if Assigned(TObject(Obj)) then
FreeAndNil(Obj);
except
on E: Exception do
begin
if Assigned(AGlobal) then
AGlobal.ApplicationMessage(msError, 'FreeAndNilEx - ' + TObject(Obj).ClassName,
E.Message);
end;
end;
end;
procedure StartService(const ServiceName: String; var OldStatus: TJclServiceState;
StartAction: TAction);
begin
OldStatus := ssUnknown;
StartAction.Enabled := False;
if StartServiceByName(LOCAL_SERVER, ServiceName) then
Exit;
MessageDlg('서비스를 시작하지 못했습니다.', TMsgDlgType.mtWarning, [mbOK], 0);
StartAction.Enabled := true;
end;
procedure StopService(const ServiceName: String; var OldStatus: TJclServiceState;
StopAction: TAction; hnd: HWND);
begin
OldStatus := ssUnknown;
StopAction.Enabled := False;
if StopServiceByName(LOCAL_SERVER, ServiceName) then
Exit;
if MessageDlg('알림 : 서비스를 중지하지 못했습니다.' + #13#10 + '강제로 중지하시겠습니까?', TMsgDlgType.mtConfirmation,
[mbYes, mbNo], 0) = mrYes then
ShellExecute(hnd, 'open', 'taskkill', PWideChar(' -f -im ' + ServiceName + '.exe'),
nil, SW_HIDE);
end;
procedure UpdateServiceStatus(const ServiceName: String; var OldStatus: TJclServiceState;
StartAction, StopAction: TAction; StatusEdit: TLabeledEdit);
var
Status: TJclServiceState;
begin
Status := GetServiceStatusByName(LOCAL_SERVER, ServiceName);
if OldStatus = Status then
Exit;
OldStatus := Status;
StartAction.Enabled := False;
StopAction.Enabled := False;
case Status of
ssUnknown:
StatusEdit.Text := '알수없음(등록된 서비스가 없습니다).';
ssStopped:
begin
StatusEdit.Text := '중지됨.';
StartAction.Enabled := true;
end;
ssStartPending:
StatusEdit.Text := '시작 중...';
ssStopPending:
StatusEdit.Text := '멈추는 중...';
ssRunning:
begin
StatusEdit.Text := '시작됨.';
StopAction.Enabled := true;
end;
ssContinuePending:
StatusEdit.Text := '계속 중...';
ssPausePending:
StatusEdit.Text := '일시정지 중...';
ssPaused:
StatusEdit.Text := '일시정지됨.';
end;
end;
function GetPeerInfo(AContext: TIdContext): string;
begin
Result := AContext.Connection.Socket.Binding.PeerIP + ':' +
AContext.Connection.Socket.Binding.PeerPort.ToString;
end;
procedure ThreadSafe(AMethod: TThreadMethod); overload;
begin
if TThread.CurrentThread.ThreadID = MainThreadID then
AMethod
else
TThread.Queue(nil, AMethod);
end;
procedure ThreadSafe(AThreadProc: TThreadProcedure); overload;
begin
if TThread.CurrentThread.ThreadID = MainThreadID then
AThreadProc
else
TThread.Queue(nil, AThreadProc);
end;
function DefaultFormatSettings: TFormatSettings;
begin
{$WARN SYMBOL_PLATFORM OFF}
Result := TFormatSettings.Create(GetThreadLocale);
{$WARN SYMBOL_PLATFORM ON}
Result.ShortDateFormat := 'YYYY-MM-DD';
Result.LongDateFormat := 'YYYY-MM-DD';
Result.ShortTimeFormat := 'hh:mm:ss';
Result.LongTimeFormat := 'hh:mm:ss';
Result.DateSeparator := '-';
Result.TimeSeparator := ':';
end;
function IdBytesPos(const SubIdBytes, IdBytes: TIdBytes; const AIndex: integer = 0): integer;
var
Index: integer;
I: integer;
begin
Index := ByteIndex(SubIdBytes[0], IdBytes, AIndex);
if Index = -1 then
Exit(-1);
for I := 0 to Length(SubIdBytes) - 1 do
begin
if IdBytes[Index + I] <> SubIdBytes[I] then
Exit(IdBytesPos(SubIdBytes, IdBytes, Index + I));
end;
Result := Index;
end;
function IdBytesToHex(const AValue: TIdBytes; const ASpliter: String): String;
var
I: integer;
begin
Result := '';
for I := 0 to Length(AValue) - 1 do
begin
Result := Result + ByteToHex(AValue[I]) + ASpliter;
end;
end;
function BytesToHex(const AValue: TBytes; const ASpliter: String): String;
var
I: integer;
begin
Result := '';
for I := 0 to Length(AValue) - 1 do
begin
Result := Result + ByteToHex(AValue[I]) + ASpliter;
end;
end;
procedure PrintLog(AMemo: TMemo; const AMsg: String);
begin
if AMemo.Lines.Count > 5000 then
AMemo.Lines.Clear;
if AMsg.IsEmpty then
AMemo.Lines.Add('')
else
begin
AMemo.Lines.Add(FormatDateTime('YYYY-MM-DD HH:NN:SS.zzz, ', Now) + AMsg);
end;
end;
procedure PrintLog(const AFile: string; AMessage: String);
var
Stream: TStreamWriter;
FileName: String;
begin
FileName := AFile;
if FileExists(FileName) then
begin
if JclFileUtils.FileGetSize(FileName) > 1024 * 1024 * 5 then
begin
try
FileMove(AFile, ChangeFileExt(FileName, FormatDateTime('_YYYYMMDD_HHNNSS', Now) +
'.bak'), true);
except
on E: Exception do
FileName := ChangeFileExt(FileName, FormatDateTime('_YYYYMMDD', Now) + '.tmp');
end;
end;
end;
ThreadSafe(
procedure
begin
try
Stream := TFile.AppendText(FileName);
try
if AMessage.IsEmpty then
Stream.WriteLine
else
Stream.WriteLine(FormatDateTime('YYYY-MM-DD, HH:NN:SS.zzz, ', Now) + AMessage);
finally
FreeAndNil(Stream);
end;
except
on E: Exception do
begin
if ExtractFileExt(FileName) = '.tmp' then
begin
PrintDebug(E.Message + ', ' + AMessage);
Exit;
end
else
PrintLog(FileName + '.tmp', AMessage);
end;
end;
end);
end;
procedure PrintDebug(const Format: string; const Args: array of const); overload;
var
str: string;
begin
FmtStr(str, Format, Args);
PrintDebug(str);
end;
procedure PrintDebug(const str: string); overload;
begin
OutputDebugString(PChar('[JDC] ' + str));
end;
function TruncInt(Value: integer; Digit: integer): integer;
begin
Result := Trunc(Value / Digit);
Result := Trunc(Result * Digit);
end;
function CurrentProcessMemory: Cardinal;
var
MemCounters: TProcessMemoryCounters;
begin
MemCounters.cb := SizeOf(MemCounters);
if GetProcessMemoryInfo(GetCurrentProcess, @MemCounters, SizeOf(MemCounters)) then
Result := MemCounters.WorkingSetSize
else
Result := 0;
end;
function FileVersion(const FileName: String): String;
var
VerInfoSize: Cardinal;
VerValueSize: Cardinal;
Dummy: Cardinal;
PVerInfo: Pointer;
PVerValue: PVSFixedFileInfo;
begin
Result := '';
if not TFile.Exists(FileName) then
Exit;
VerInfoSize := GetFileVersionInfoSize(PChar(FileName), Dummy);
GetMem(PVerInfo, VerInfoSize);
try
if GetFileVersionInfo(PChar(FileName), 0, VerInfoSize, PVerInfo) then
if VerQueryValue(PVerInfo, '\', Pointer(PVerValue), VerValueSize) then
with PVerValue^ do
Result := Format('v%d.%d.%d', [HiWord(dwFileVersionMS),
// Major
LoWord(dwFileVersionMS), // Minor
HiWord(dwFileVersionLS) // Release
]);
finally
FreeMem(PVerInfo, VerInfoSize);
end;
end;
procedure CloudMessage(const ProjectCode, AppCode, TypeCode, ATitle, AMessage,
AVersion: String; const AServer: TConnInfo);
var
UDPClient: TIdUDPClient;
SysInfo, Msg, DiskInfo: String;
MBFactor, GBFactor: double;
_Title: string;
begin
{$IFDEF DEBUG}
{
PrintDebug('XCloudLog,<%s> [%s] %s=%s,Host=%s', [TypeCode, AppCode, _Title, Msg,
AServer.StringValue]);
Exit;
}
{$ENDIF}
MBFactor := 1024 * 1024;
GBFactor := MBFactor * 1024;
SysInfo :=
Format('OS=%s,MemUsage=%.2fMB,TotalMem=%.2fGB,FreeMem=%.2fGB,IPAddress=%s,Server=%s',
[GetOSVersionString, CurrentProcessMemory / MBFactor, GetTotalPhysicalMemory / GBFactor,
GetFreePhysicalMemory / GBFactor, GetIPAddress(GetLocalComputerName),
AServer.StringValue]);
DiskInfo := Format('C_Free=%.2fGB,C_Size=%.2fGB,D_Free=%.2fGB,D_Size=%.2fGB',
[DiskFree(3) / GBFactor, DiskSize(3) / GBFactor, DiskFree(4) / GBFactor,
DiskSize(4) / GBFactor]);
_Title := ATitle.Replace(' ', '_', [rfReplaceAll]);
Msg := AMessage.Replace('"', '''');
Msg := Format
('CloudLog,ProjectCode=%s,AppCode=%s,TypeCode=%s,ComputerName=%s,Title=%s Version="%s",LogMessage="%s",SysInfo="%s",DiskInfo="%s"',
[ProjectCode, AppCode, TypeCode, GetLocalComputerName, _Title, AVersion, Msg, SysInfo,
DiskInfo]);
Msg := Msg.Replace('\', '\\');
Msg := Msg.Replace(#13, ', ');
Msg := Msg.Replace(#10, '');
Msg := Msg.Replace(#9, ' '); // TAB
if AServer.StringValue.IsEmpty then
Exit;
UDPClient := TIdUDPClient.Create(nil);
try
try
UDPClient.Send(AServer.StringValue, AServer.IntegerValue, Msg, IndyTextEncoding_UTF8);
PrintDebug('CloudLog,<%s> [%s] %s=%s,Host=%s', [TypeCode, AppCode, _Title, Msg,
AServer.StringValue]);
except
on E: Exception do
PrintDebug('CloudLog,E=' + E.Message);
end;
finally
UDPClient.Free;
end;
end;
function CompressStream(Stream: TStream; OutStream: TStream; OnProgress: TNotifyEvent)
: boolean;
var
CS: TZCompressionStream;
begin
CS := TZCompressionStream.Create(OutStream); // 스트림 생성
try
if Assigned(OnProgress) then
CS.OnProgress := OnProgress;
CS.CopyFrom(Stream, Stream.Size); // 여기서 압축이 진행됨
// 테스트 결과 압축완료시 이벤트가 발생하지 않기 때문에
// 완료시 한번 더 이벤트를 불러준다.
if Assigned(OnProgress) then
OnProgress(CS);
Result := true;
finally
CS.Free;
end;
end;
function Contains(Contents: string; const str: array of const): boolean;
var
I: integer;
begin
Result := False;
for I := 0 to High(str) do
begin
if Pos(str[I].VPWideChar, Contents) = 0 then
Exit;
end;
Result := true;
end;
function IsGoodResponse(Text, Command: string; Response: array of const): boolean;
var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Text := Text;
Result := (SL.Strings[0] = Command) and (Contains(Text, Response));
finally
SL.Free;
end;
end;
function DeCompressStream(Stream: TStream; OutStream: TStream;
OnProgress: TNotifyEvent): boolean;
const
BuffSize = 65535; // 버퍼 사이즈
var
DS: TZDeCompressionStream;
Buff: PChar; // 임시 버퍼
ReadSize: integer; // 읽은 크기
begin
if Stream = OutStream then
// 입력 스트림과 출력스트림이 같으면 문제가 발생한다
raise Exception.Create('입력 스트림과 출력 스트림이 같습니다');
Stream.Position := 0;
// 스트림 커서 초기화
OutStream.Position := 0;
// 인풋 스트림을 옵션으로 객체 생성.
DS := TZDeCompressionStream.Create(Stream);
try
if Assigned(OnProgress) then
DS.OnProgress := OnProgress;
GetMem(Buff, BuffSize);
try
// 버퍼 사이즈만큼 읽어온다. Read함수를 부르면 압축이 풀리게 된다.
repeat
ReadSize := DS.Read(Buff^, BuffSize);
if ReadSize <> 0 then
OutStream.Write(Buff^, ReadSize);
until ReadSize < BuffSize;
if Assigned(OnProgress) then
OnProgress(DS);
// Compress와 같은이유
Result := true;
finally
FreeMem(Buff)
end;
finally
DS.Free;
end;
end;
function Rev2Bytes(w: WORD): WORD;
asm
XCHG AL, AH
end;
function Rev4Bytes(Value: Int32): Int32; assembler;
asm
MOV EAX, Value;
BSWAP EAX;
end;
function Rev4BytesF(Value: Single): Single; assembler;
var
tmp1: PInteger;
tmp2: PSingle;
begin
tmp1 := @Value;
tmp1^ := Rev4Bytes(tmp1^);
tmp2 := @tmp1^;
Result := tmp2^;
end;
function CheckHexStr(ASource: String): String;
begin
if (Length(ASource) mod 2) = 0 then
Result := ASource
else
Result := '0' + ASource;
end;
function HexStrToByte(const ASource: String; const AIndex: integer): Byte;
var
str: String;
tmp: TIdBytes;
begin
str := CheckHexStr(ASource);
if Length(str) < AIndex + 1 then
begin
Result := $00;
Exit;
end;
str := Copy(str, AIndex, 2);
tmp := HexStrToBytes(str);
CopyMemory(@Result, tmp, 1);
end;
function WordToBytes(AValue: WORD): TIdBytes;
begin
Result := ToBytes(Rev2Bytes(AValue));
end;
function DWordToBytes(AValue: DWORD): TIdBytes;
begin
Result := ToBytes(Rev4Bytes(AValue));
end;
function HexStrToWord(const ASource: string; const AIndex: integer): WORD;
var
str: string;
begin
str := CheckHexStr(ASource);
if Length(str) = 2 then
str := '00' + str;
if Length(str) < AIndex + 3 then
begin
Result := $00;
Exit;
end;
str := Copy(str, AIndex, 4);
{$IF CompilerVersion > 28} // Ver28 = XE7
Result := BytesToUInt16(HexStrToBytes(str));
{$ELSE}
Result := BytesToWord(HexStrToBytes(str));
{$ENDIF}
end;
function HexStrToBytes(const ASource: string; const AIndex: integer): TIdBytes;
var
I, j, n: integer;
c: char;
b: Byte;
str: string;
begin
str := CheckHexStr(ASource);
SetLength(Result, 0);
j := 0;
b := 0;
n := 0;
for I := AIndex to Length(str) do
begin
c := ASource[I];
case c of
'0' .. '9':
n := ord(c) - ord('0');
'A' .. 'F':
n := ord(c) - ord('A') + 10;
'a' .. 'f':
n := ord(c) - ord('a') + 10;
else
Continue;
end;
if j = 0 then
begin
b := n;
j := 1;
end
else
begin
b := (b shl 4) + n;
j := 0;
AppendBytes(Result, ToBytes(b));
end
end;
if j <> 0 then
raise Exception.Create('Input contains an odd number of hexadecimal digits.[' + ASource +
'/' + IntToStr(AIndex) + ']');
end;
{ TGlobalAbstract }
procedure TGlobalAbstract.ApplicationMessage(const AType: TMessageType; const ATitle: string;
const AMessage: String);
begin
if FIsFinalized then
Exit;
case AType of
msDebug:
_ApplicationMessage(MESSAGE_TYPE_DEBUG, ATitle, AMessage, [moDebugView, moLogFile]);
msInfo:
_ApplicationMessage(MESSAGE_TYPE_INFO, ATitle, AMessage);
msError:
_ApplicationMessage(MESSAGE_TYPE_ERROR, ATitle, AMessage);
msWarning:
_ApplicationMessage(MESSAGE_TYPE_WARNING, ATitle, AMessage);
else
_ApplicationMessage(MESSAGE_TYPE_UNKNOWN, ATitle, AMessage);
end;
end;
procedure TGlobalAbstract.ApplicationMessage(const AType: TMessageType; const ATitle: string;
const AFormat: String; const Args: array of const);
var
str: string;
begin
FmtStr(str, AFormat, Args);
ApplicationMessage(AType, ATitle, str);
end;
constructor TGlobalAbstract.Create;
begin
FProjectCode := 'MyProject';
FAppCode := 'MyApp';
FExeName := '';
FLogName := '';
FLogServer.StringValue := '';
FLogServer.IntegerValue := 8094;
FIsInitialized := False;
FIsFinalized := False;
FUseCloudLog := False;
FUseDebug := False;
end;
procedure TGlobalAbstract.Finalize;
begin
ApplicationMessage(msInfo, 'Stop', 'StartTime=' + FStartTime.ToString);
end;
function TGlobalAbstract.GetErrorLogName: string;
begin
Result := ChangeFileExt(FLogName, FormatDateTime('_YYYYMMDD', Now) + '.err');
end;
function TGlobalAbstract.GetLogName: string;
begin
Result := ChangeFileExt(FLogName, FormatDateTime('_YYYYMMDD', Now) + '.log');
end;
procedure TGlobalAbstract.Initialize;
begin
FStartTime := Now;
{$IFDEF WIN32}
ApplicationMessage(msInfo, 'Start', '(x86)' + FExeName);
{$ENDIF}
{$IFDEF WIN64}
ApplicationMessage(msInfo, 'Start', '(x64)' + FExeName);
{$ENDIF}
end;
procedure TGlobalAbstract.SetUseDebug(const Value: boolean);
begin
FUseDebug := Value;
end;
procedure TGlobalAbstract._ApplicationMessage(const AType: string; const ATitle: string;
const AMessage: String; const AOutputs: TMsgOutputs);
var
splitter: string;
begin
if AMessage.IsEmpty then
splitter := ''
else
splitter := ' - ';
if moDebugView in AOutputs then
PrintDebug('<%s> [%s] %s%s%s', [AType, FAppCode, ATitle, splitter, AMessage]);
if moLogFile in AOutputs then
PrintLog(FLogName, Format('<%s> %s%s%s', [AType, ATitle, splitter, AMessage]));
if (moCloudMessage in AOutputs) and FUseCloudLog then
CloudMessage(FProjectCode, FAppCode, AType, ATitle, AMessage, FileVersion(FExeName),
FLogServer);
end;
{ TConnInfo }
constructor TConnInfo.Create(AString: string; AInteger: integer);
begin
Self.StringValue := AString;
Self.IntegerValue := AInteger;
end;
function TConnInfo.Equals(const ConnInfo: TConnInfo): boolean;
begin
Result := Self.StringValue.Equals(ConnInfo.StringValue) and
(Self.IntegerValue = ConnInfo.IntegerValue);
end;
function TConnInfo.ToString: string;
begin
Result := Self.StringValue + ':' + Self.IntegerValue.ToString;
end;
function StrDefault(str: string; Default: string): string;
begin
if str.IsEmpty then
Result := Default
else
Result := str;
end;
{ TMemoLog }
constructor TMemoLog.Create(AMemo: TMemo; AMsg: string);
begin
Self.Memo := AMemo;
Self.Msg := AMsg;
Self.Time := Now;
end;
end.
|
unit XMLUtils;
interface
uses
SysUtils, MSXML_TLB, ORFn;
function Text2XML(const AText: string): string;
function FindXMLElement(Element: IXMLDOMNode; ElementTag: string): IXMLDOMNode;
function FindXMLAttributeValue(Element: IXMLDOMNode; AttributeTag: string): string;
function GetXMLWPText(Element: IXMLDOMNode): string;
implementation
type
TXMLChars = (xcAmp, xcGT, xcLT, xcApos, xcQuot); // Keep & first in list!
const
XMLCnvChr: array[TXMLChars] of string = ('&', '>', '<', '''', '"');
XMLCnvStr: array[TXMLChars] of string = ('&','>','<',''','"');
function Text2XML(const AText: string): string;
var
i: TXMLChars;
p: integer;
tmp: string;
begin
Result := AText;
for i := low(TXMLChars) to high(TXMLChars) do
begin
tmp := Result;
Result := '';
repeat
p := pos(XMLCnvChr[i],tmp);
if(p > 0) then
begin
Result := Result + copy(tmp,1,p-1) + XMLCnvStr[i];
delete(tmp,1,p);
end;
until(p=0);
Result := Result + tmp;
end;
end;
function FindXMLElement(Element: IXMLDOMNode; ElementTag: string): IXMLDOMNode;
var
Children: IXMLDOMNodeList;
Child: IXMLDOMNode;
i, count: integer;
begin
Result := nil;
Children := Element.Get_childNodes;
if assigned(Children) then
begin
count := Children.Get_length;
for i := 0 to count-1 do
begin
Child := Children.Get_item(i);
if assigned(Child) and (CompareText(Child.Get_nodeName, ElementTag) = 0) then
begin
Result := Child;
break;
end;
end;
end;
end;
function FindXMLAttributeValue(Element: IXMLDOMNode; AttributeTag: string): string;
var
Attributes: IXMLDOMNamedNodeMap;
Attribute: IXMLDOMNode;
i, count: integer;
begin
Result := '';
Attributes := Element.Get_attributes;
try
if assigned(Attributes) then
begin
count := Attributes.Get_Length;
for i := 0 to Count - 1 do
begin
Attribute := Attributes.Item[i];
if CompareText(Attribute.Get_NodeName, AttributeTag) = 0 then
begin
Result := Attribute.Get_Text;
break;
end;
end;
end;
finally
Attribute := nil;
Attributes := nil;
end;
end;
function GetXMLWPText(Element: IXMLDOMNode): string;
var
Children: IXMLDOMNodeList;
Child: IXMLDOMNode;
i, count: integer;
begin
Result := '';
Children := Element.Get_childNodes;
try
if assigned(Children) then
begin
count := Children.Length;
for i := 0 to Count - 1 do
begin
Child := Children.Item[i];
if CompareText(Child.NodeName, 'P') = 0 then
begin
if(Result <> '') then
Result := Result + CRLF;
Result := Result + Child.Get_Text;
end;
end;
end;
finally
Child := nil;
Children := nil;
end;
end;
end.
|
unit MIDI;
interface
uses System.Types, mmsystem;
type
TMIDIInstrument = (midiAcousticGrandPiano, midiBrightAcousticPiano,
midiElectricGrandPiano, midiHonkyTonkPiano,
midiRhodesPiano, midiChorusedPiano, midiHarpsichord,
midiClavinet, midiCelesta, midiGlockenspiel,
midiMusicBox, midiVibraphone, midiMarimba, midiXylophone,
midiTubularBells, midiDulcimer, midiHammondOrgan,
midiPercussiveOrgan, midiRockOrgan, midiChurchOrgan,
midiReedOrgan, midiAccordion, midiHarmonica,
midiTangoAccordion, midiAcousticGuitarNylon,
midiAcousticGuitarSteel, midiElectricGuitarJazz,
midiElectricGuitarClean, midiElectricGuitarMuted,
midiOverdrivenGuitar, midiDistortionGuitar,
midiGuitarHarmonics, midiAcousticBass, midiElectricBassFinger,
midiElectricBassPick, midiFretlessBass, midiSlapBass1,
midiSlapBass2, midiSynthBass1, midiSynthBass2, midiViolin,
midiViola, midiCello, midiContrabass, midiTremoloStrings,
midiPizzicatoStrings, midiOrchestralHarp, midiTimpani,
midiStringEnsemble1, midiStringEnsemble2, midiSynthStrings1,
midiSynthStrings2, midiChoirAahs, midiVoiceOohs,
midiSynthVoice, midiOrchestraHit, midiTrumpet, midiTrombone,
midiTuba, midiMutedTrumpet, midiFrenchHorn, midiBrassSection,
midiSynthBrass1, midiSynthBrass2, midiSopranoSax, midiAltoSax,
midiTenorSax, midiBaritoneSax, midiOboe, midiEnglishHorn,
midiBassoon, midiClarinet, midiPiccolo, midiFlute,
midiRecorder, midiPanFlute, midiBottleBlow, midiShakuhachi,
midiWhistle, midiOcarina, midiLead1Square,
midiLead2Sawtooth, midiLead3CalliopeLead, midiLead4ChiffLead,
midiLead5Charang, midiLead6Voice, midiLead7Fifths,
midiLead8BrassLead, midiPad1NewAge, midiPad2Warm,
midiPad3Polysynth, midiPad4Choir, midiPad5Bowed,
midiPad6Metallic, midiPad7Halo, midiPad8Sweep, midiEmpty0,
midiEmpty1, midiEmpty2, midiEmpty3, midiEmpty4, midiEmpty5,
midiEmpty6, midiEmpty7, midiEmpty8, midiEmpty9, midiEmpty10,
midiEmpty11, midiEmpty12, midiEmpty13, midiEmpty14,
midiEmpty15, midiEmpty16, midiEmpty17, midiEmpty18,
midiEmpty19, midiEmpty20, midiEmpty21, midiEmpty22,
midiEmpty23, midiGuitarFretNoise, midiBreathNoise,
midiSeashore, midiBirdTweet, midiTelephoneRing,
midiHelicopter, midiApplause, midiGunshot);
const MIDI_DRUMS_COUNT =27;
Type TMIDIMessage=integer; //DWORD
TMIDIDrum =Record
name:string;
note:byte;
end;
TMIDIDrums =Array[0..MIDI_DRUMS_COUNT-1] of TMIDIDrum ;
var
hDevMidiOut :HMIDIOUT;
MIDIDrums:TMIDIDrums= (
(name:'Bass Drum'; note:35) //1
,(name:'Kick Drum'; note:36) //2
,(name:'Snare Cross Stick'; note:37) //3
,(name:'Snare Drum'; note:38) //4
,(name:'Hand Clap'; note:39) //5
,(name:'Electric Snare Drum'; note:40) //6
,(name:'Floor Tom 2'; note:41) //7
,(name:'Hi-Hat Closed'; note:42) //8
,(name:'Floor Tom 1'; note:43) //9
,(name:'Hi-Hat Foot'; note:44) //10
,(name:'Low Tom'; note:45) //11
,(name:'Hi-Hat Open'; note:46) //12
,(name:'Low-Mid Tom'; note:47) //13
,(name:'High-Mid Tom'; note:48) //14
,(name:'Crash Cymbal'; note:49) //15
,(name:'High Tom'; note:50) //16
,(name:'Ride Cymbal'; note:51) //17
,(name:'China Cymbal'; note:52) //18
,(name:'Ride Bell'; note:53) //19
,(name:'Tambourine'; note:54) //20
,(name:'Splash cymbal'; note:55) //21
,(name:'Cowbell'; note:56) //22
,(name:'Crash Cymbal 2'; note:57) //23
,(name:'Vibraslap'; note:58) //24
,(name:'Ride Cymbal 2'; note:59) //25
,(name:'High Bongo'; note:60) //26
,(name:'Low Bongo'; note:61) //27
);
const
MIDI_NOTE_ON = $90;
MIDI_NOTE_OFF = $80;
MIDI_CHANGE_INSTRUMENT = $C0;
MIDI_DEVICE = 0;
MIDI_VEL = 108;
function MidiOutput_DeviceProps(DeviceID: integer):string;
function MidiOut_Open(DeviceID: integer):integer;
function MidiOut_Close():integer;
function MIDIEncodeMessage(Msg, Param1, Param2: integer): integer;
procedure SetCurrentInstrument(CurrentInstrument: TMIDIInstrument);
procedure NoteOn(NewNote, NewIntensity: byte);
procedure NoteOff(NewNote, NewIntensity: byte);
procedure SetPlaybackVolume(PlaybackVolume: cardinal);
function MidiOut_Test():integer;
implementation
uses SysUtils;
function MIDIEncodeMessage(Msg, Param1, Param2: integer): integer;
begin
result := Msg + (Param1 shl 8) + (Param2 shl 16);
end;
procedure SetCurrentInstrument(CurrentInstrument: TMIDIInstrument);
begin
midiOutShortMsg(hDevMidiOut, MIDIEncodeMessage(MIDI_CHANGE_INSTRUMENT, ord(CurrentInstrument), 0));
end;
procedure NoteOn(NewNote, NewIntensity: byte);
var midimsg: TMIDIMessage;
begin
midimsg:= MIDIEncodeMessage(MIDI_NOTE_ON, NewNote, NewIntensity);
midiOutShortMsg(hDevMidiOut,midimsg);
end;
procedure NoteOff(NewNote, NewIntensity: byte);
var midimsg: TMIDIMessage;
begin
midimsg := MIDIEncodeMessage(MIDI_NOTE_OFF, NewNote, NewIntensity);
midiOutShortMsg(hDevMidiOut, midimsg);
end;
procedure SetPlaybackVolume(PlaybackVolume: cardinal);
begin
midiOutSetVolume(hDevMidiOut, PlaybackVolume);
end;
Function GetManufacturerName(ID:WORD):String;
Var s :string;
begin
Case ID of
0:S:='Unknown manufacturer';
1:S:='Microsoft Corp.' ;
34:S:='Advanced Gravis' ;
else
S:= 'Unknown manufacturer'
end;
GetManufacturerName:=S;
end;
function MidiOutput_DeviceProps(DeviceID: integer):string;
var OutCaps:TMidiOutCaps;
S:String;
begin
midiOutGetDevCaps(DeviceID,PMidiOutCaps(Addr(OutCaps)),SizeOf(TMidiOutCaps));
{Manufacturer ID}
S:='Device ID: '+IntToStr(DeviceID);
S:=S+#10#13+'Manufacturer ID: '+GetManufacturerName(OutCaps.wMid) +'('+IntToStr(OutCaps.wMid)+')';
S:=S+#10#13+'Product ID: '+IntToStr(OutCaps.wPid); {product ID}
S:=S+#10#13+'Driver version: '+IntToStr(Hi(OutCaps.vDriverVersion))+'.'+IntToStr(Lo(OutCaps.vDriverVersion)); { version of the driver }
S:=S+#10#13+'Product name: '+OutCaps.szPname; { product name (NULL terminated string) }
{ type of device }
Case OutCaps.wTechnology of
MOD_MIDIPORT : S:= S+#10#13+'Device type:Output port';
MOD_SYNTH : S:= S+#10#13+'Device type:Generic internal synth';
MOD_SQSYNTH : S:= S+#10#13+'Device type:Square wave internal synth';
MOD_FMSYNTH : S:= S+#10#13+'Device type:FM internal synth';
MOD_MAPPER : S:= S+#10#13+'Device type:MIDI mapper';
else S:= S+#10#13+'Device type:UNKNOWN'
End;
S:=S+#10#13+'No of voices: ' +IntToStr(OutCaps.wVoices); { # of voices (internal synth only) }
S:=S+#10#13+'Max No of notes: '+IntToStr(OutCaps.wNotes); { max # of notes (internal synth only) }
S:=S+#10#13+'Channels used: ' +IntToStr(OutCaps.wChannelMask); { channels used (internal synth only) }
S:=S+#10#13+'Supports:'; { functionality supported by driver }
if (OutCaps.dwSupport and MIDICAPS_CACHE )<>0 then s:=S+#10#13+ ' Patch caching' ;
if (OutCaps.dwSupport and MIDICAPS_VOLUME )<>0 then s:=S+#10#13+ ' Volume control ' ;
if (OutCaps.dwSupport and MIDICAPS_LRVOLUME)<>0 then s:=S+#10#13+ ' Separate left and right volume control';
if (OutCaps.dwSupport and MIDICAPS_STREAM )<>0 then s:=S+#10#13+ ' midiStreamOut function ';
Result:=s;
end;
function MidiOut_Open(DeviceID: integer):integer;
begin
MidiOut_Open :=midiOutOpen(@hDevMidiOut, DeviceID, 0, 0, CALLBACK_NULL);
// Return value
//Returns MMSYSERR_NOERROR if successful or an error otherwise. Possible error values include the following.
// MIDIERR_NODEVICE //--No MIDI port was found. This error occurs only when the mapper is opened.
// MMSYSERR_ALLOCATED The specified resource is already allocated.
// MMSYSERR_BADDEVICEID The specified device identifier is out of range.
// MMSYSERR_INVALPARAM The specified pointer or structure is invalid.
// MMSYSERR_NOMEM The system is unable to allocate or lock memory.
//SetPlaybackVolume($FFFFFFFF);
end;
function MidiOut_Close():integer;
begin
midiOutClose(hDevMidiOut);
end;
function MidiOut_Test():integer;
begin
NoteOn ($3C,$7F);
sleep(50);
NoteOff ($3C,$0);
NoteOn ($3E,$7F);
sleep(50);
NoteOff ($3E,$0);
NoteOn ($40,$7F);
sleep(50);
NoteOff ($40,$0);
//midiOutShortMsg(hDevMidiOut, $007F3C90);
sleep(500);
//midiOutShortMsg(hDevMidiOut, $007F3C80);
end;
end.
|
unit fLabTests;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ORCtrls, StdCtrls, ExtCtrls, fBase508Form, VA508AccessibilityManager;
type
TfrmLabTests = class(TfrmBase508Form)
pnlLabTests: TORAutoPanel;
cmdOK: TButton;
cmdCancel: TButton;
lstList: TORListBox;
cboTests: TORComboBox;
cmdRemove: TButton;
cmdClear: TButton;
lblTests: TLabel;
lblList: TLabel;
cmdAdd: TButton;
procedure FormCreate(Sender: TObject);
procedure cboTestsNeedData(Sender: TObject; const StartFrom: string;
Direction, InsertAt: Integer);
procedure cmdOKClick(Sender: TObject);
procedure cmdClearClick(Sender: TObject);
procedure cmdRemoveClick(Sender: TObject);
procedure lstListClick(Sender: TObject);
procedure cboTestsChange(Sender: TObject);
procedure cboTestsEnter(Sender: TObject);
procedure cboTestsExit(Sender: TObject);
procedure cmdAddClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure SelectTests(FontSize: Integer);
implementation
uses fLabs, ORFn, rLabs, rMisc, VAUtils;
{$R *.DFM}
procedure SelectTests(FontSize: Integer);
var
frmLabTests: TfrmLabTests;
W, H: integer;
begin
frmLabTests := TfrmLabTests.Create(Application);
try
with frmLabTests do
begin
Font.Size := FontSize;
W := ClientWidth;
H := ClientHeight;
ResizeToFont(FontSize, W, H);
ClientWidth := W; pnlLabTests.Width := W;
ClientHeight := H; pnlLabTests.Height := H;
SetFormPosition(frmLabTests);
FastAssign(frmLabs.lstTests.Items, lstList.Items);
if lstList.Items.Count > 0 then lstList.ItemIndex := 0;
lstListClick(frmLabTests);
ShowModal;
end;
finally
frmLabTests.Release;
end;
end;
procedure TfrmLabTests.FormCreate(Sender: TObject);
begin
RedrawSuspend(cboTests.Handle);
cboTests.InitLongList('');
RedrawActivate(cboTests.Handle);
end;
procedure TfrmLabTests.cboTestsNeedData(Sender: TObject;
const StartFrom: string; Direction, InsertAt: Integer);
begin
cboTests.ForDataUse(AllTests(StartFrom, Direction));
end;
procedure TfrmLabTests.cmdOKClick(Sender: TObject);
begin
if lstList.Items.Count = 0 then
ShowMsg('No tests were selected.')
else
begin
FastAssign(lstList.Items, frmLabs.lstTests.Items);
Close;
end;
end;
procedure TfrmLabTests.cmdClearClick(Sender: TObject);
begin
lstList.Clear;
lstListClick(self);
end;
procedure TfrmLabTests.cmdRemoveClick(Sender: TObject);
var
newindex: integer;
begin
if lstList.Items.Count > 0 then
begin
if lstList.ItemIndex = (lstList.Items.Count -1 ) then
newindex := lstList.ItemIndex - 1
else
newindex := lstList.ItemIndex;
lstList.Items.Delete(lstList.ItemIndex);
if lstList.Items.Count > 0 then lstList.ItemIndex := newindex;
end;
lstListClick(self);
end;
procedure TfrmLabTests.lstListClick(Sender: TObject);
begin
if lstList.Items.Count = 0 then
begin
cmdClear.Enabled := false;
cmdRemove.Enabled := false;
end
else
begin
cmdClear.Enabled := true;
cmdRemove.Enabled := true;
end;
end;
procedure TfrmLabTests.cboTestsChange(Sender: TObject);
begin
cmdAdd.Enabled := cboTests.ItemIndex > -1;
end;
procedure TfrmLabTests.cboTestsEnter(Sender: TObject);
begin
cmdAdd.Default := true;
end;
procedure TfrmLabTests.cboTestsExit(Sender: TObject);
begin
cmdAdd.Default := false;
end;
procedure TfrmLabTests.cmdAddClick(Sender: TObject);
var
i, textindex: integer;
begin
textindex := lstList.Items.Count;
for i := 0 to lstList.Items.Count -1 do
if lstList.Items[i] = cboTests.Items[cboTests.ItemIndex] then textindex := i;
if textindex = lstList.Items.Count then lstList.Items.Add(cboTests.Items[cboTests.ItemIndex]);
lstList.ItemIndex := textindex;
lstListClick(self);
end;
procedure TfrmLabTests.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SaveUserBounds(Self);
end;
end.
|
unit BindDocUnit;
interface
uses
DocBindExcelDataModule;
type
TBindDoc = class(TObject)
protected
class procedure DoBindDocs(ADocBindExcelTable: TDocBindExcelTable); static;
public
class procedure LoadDocBindsFromExcelDocument(const AFileName
: string); static;
end;
implementation
uses AllFamilyQuery, System.SysUtils, ProgressBarForm, ProjectConst,
System.UITypes, CustomExcelTable, System.IOUtils, LoadFromExcelFileHelper,
CustomErrorForm;
class procedure TBindDoc.DoBindDocs(ADocBindExcelTable: TDocBindExcelTable);
var
i: Integer;
qAllFamily: TQueryAllFamily;
begin
qAllFamily := TQueryAllFamily.Create(nil);
try
// начинаем транзакцию, если она ещё не началась
if (not qAllFamily.FDQuery.Connection.InTransaction) then
qAllFamily.FDQuery.Connection.StartTransaction;
ADocBindExcelTable.First;
ADocBindExcelTable.CallOnProcessEvent;
i := 0;
while not ADocBindExcelTable.Eof do
begin
// Пытаемся найти семейство с таким идентификатором
qAllFamily.Load(['ID'], [ADocBindExcelTable.IDProduct.AsInteger]);
if qAllFamily.FDQuery.RecordCount = 1 then
begin
qAllFamily.W.TryEdit;
// Если спецификация задана
if not ADocBindExcelTable.Datasheet.AsString.IsEmpty then
begin
// Файл документации должен лежать в папке с именем производителя
qAllFamily.W.Datasheet.F.AsString :=
TPath.Combine(qAllFamily.W.Producer.F.AsString,
ADocBindExcelTable.Datasheet.AsString);
end;
// Если функциональная диаграмма задана
if not ADocBindExcelTable.Diagram.AsString.IsEmpty then
begin
qAllFamily.W.Diagram.F.AsString :=
TPath.Combine(qAllFamily.W.Producer.F.AsString,
ADocBindExcelTable.Diagram.AsString);
end;
qAllFamily.W.TryPost;
Inc(i);
// Уже много записей обновили в рамках одной транзакции
if i >= 1000 then
begin
i := 0;
qAllFamily.FDQuery.Connection.Commit;
qAllFamily.FDQuery.Connection.StartTransaction;
end;
end;
ADocBindExcelTable.Next;
ADocBindExcelTable.CallOnProcessEvent;
end;
qAllFamily.FDQuery.Connection.Commit;
finally
FreeAndNil(qAllFamily);
end;
end;
class procedure TBindDoc.LoadDocBindsFromExcelDocument(const AFileName: string);
// var
// ADocBindExcelDM: TDocBindExcelDM;
// AfrmError: TfrmError;
// OK: Boolean;
begin
Assert(not AFileName.IsEmpty);
TLoad.Create.LoadAndProcess(AFileName, TDocBindExcelDM, TfrmCustomError,
procedure(ASender: TObject)
begin
// Выполняем привязку
DoBindDocs(ASender as TDocBindExcelTable);
end);
end;
end.
|
unit CAM_CCM;
(*************************************************************************
DESCRIPTION : Camellia Counter with CBC-MAC (CCM) mode functions
REQUIREMENTS : TP5-7, D1-D7/D9-D12/D17-D18, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REMARKS : - The IV and buf fields of the contexts are used for temporary buffers
- Tag compare is constant time but if verification fails,
then plaintext is zero-filled
- Maximum header length is $FEFF
- Since CCM was designed for use in a packet processing
environment, there are no incremental functions. The ..Ex
functions can be used together with CAM_Init to save
key setup overhead if the same key is used more than once.
REFERENCES : [1] RFC 3610, 2003, D. Whiting et al., Counter with CBC-MAC (CCM)
http://tools.ietf.org/html/rfc1320
[2] RFC 5528, 2009, A. Kato et al., Camellia Counter Mode
and Camellia Counter with CBC-MAC Mode Algorithms
http://tools.ietf.org/html/rfc5528
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 21.05.09 we Initial version derived from AES-CCM
0.11 29.07.10 we Fix: Check ofs(dtp^) for 16 bit
0.12 01.09.15 we constant time compare in CAM_CCM_Dec_VeriEX
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009-2015 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
interface
uses
BTypes, CAM_Base;
function CAM_CCM_Enc_AuthEx(var ctx: TCAMContext;
var tag: TCAMBlock; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
{$ifdef CONST}const{$else}var{$endif} nonce; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length}
ptp: pointer; pLen: longint; {plaintext: address / length}
ctp: pointer {ciphertext: address}
): integer;
{$ifdef DLL} stdcall; {$endif}
{-CCM packet encrypt/authenticate without key setup}
function CAM_CCM_Enc_Auth(var tag: TCAMBlock; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
{$ifdef CONST}const{$else}var{$endif} Key; KBytes: word; {key and byte length of key}
{$ifdef CONST}const{$else}var{$endif} nonce; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length}
ptp: pointer; pLen: longint; {plaintext: address / length}
ctp: pointer {ciphertext: address}
): integer;
{$ifdef DLL} stdcall; {$endif}
{-All-in-one call for CCM packet encrypt/authenticate}
function CAM_CCM_Dec_VeriEX(var ctx: TCAMContext;
ptag: pointer; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
{$ifdef CONST}const{$else}var{$endif} nonce; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length}
ctp: pointer; cLen: longint; {ciphertext: address / length}
ptp: pointer {plaintext: address}
): integer;
{$ifdef DLL} stdcall; {$endif}
{-CCM packet decrypt/verify without key setup. If ptag^ verification fails, ptp^ is zero-filled!}
function CAM_CCM_Dec_Veri( ptag: pointer; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
{$ifdef CONST}const{$else}var{$endif} Key; KBytes: word; {key and byte length of key}
{$ifdef CONST}const{$else}var{$endif} nonce; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length}
ctp: pointer; cLen: longint; {ciphertext: address / length}
ptp: pointer {plaintext: address}
): integer;
{$ifdef DLL} stdcall; {$endif}
{-All-in-one CCM packet decrypt/verify. If ptag^ verification fails, ptp^ is zero-filled!}
implementation
{---------------------------------------------------------------------------}
function CAM_CCM_Core(var ctx: TCAMContext; enc_auth: boolean;
var tag: TCAMBlock; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
pnonce: pointer; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length, hLen <$FF00}
stp: pointer; sLen: longint; {source text: address / length}
dtp: pointer {dest. text: address}
): integer;
{-CCM core routine. Encrypt or decrypt (depending on enc_auth) source text}
{ to dest. text and calculate the CCM tag. Key setup must be done from caller}
var
ecc: TCAMBlock; {encrypted counter}
err: integer;
len: longint;
k, L: word;
b: byte;
pb: pByte;
procedure IncCTR(var CTR: TCAMBlock);
{-Increment CTR[15]..CTR[16-L]}
var
j: integer;
begin
for j:=15 downto 16-L do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
begin
{Check static ranges and conditions}
if (sLen>0) and ((stp=nil) or (dtp=nil)) then err := CAM_Err_NIL_Pointer
else if odd(tLen) or (tLen<4) or (tLen>16) then err := CAM_Err_CCM_Tag_length
else if (hLen>0) and (hdr=nil) then err := CAM_Err_NIL_Pointer
else if hLen>=$FF00 then err := CAM_Err_CCM_Hdr_length
else if (nLen<7) or (nLen>13) then err := CAM_Err_CCM_Nonce_length
{$ifdef BIT16}
else if (ofs(stp^)+sLen>$FFFF) or (ofs(dtp^)+sLen>$FFFF) then err := CAM_Err_CCM_Text_length
{$endif}
else err := 0;
CAM_CCM_Core := err;
if err<>0 then exit;
{calculate L value = max(number of bytes needed for sLen, 15-nLen)}
len := sLen;
L := 0;
while len>0 do begin
inc(L);
len := len shr 8;
end;
if nLen+L > 15 then begin
CAM_CCM_Core := CAM_Err_CCM_Nonce_length;
exit;
end;
{Force nLen+L=15. Since nLen<=13, L is at least L}
L := 15-nLen;
with ctx do begin
{compose B_0 = Flags | Nonce N | l(m)}
{octet 0: Flags = 64*HdrPresent | 8*((tLen-2) div 2 | (L-1)}
if hLen>0 then b := 64 else b := 0;
buf[0] := b or ((tLen-2) shl 2) or (L-1);
{octets 1..15-L is nonce}
pb := pnonce;
for k:=1 to 15-L do begin
buf[k] := pb^;
inc(Ptr2Inc(pb));
end;
{octets 16-L .. 15: l(m)}
len := sLen;
for k:=1 to L do begin
buf[16-k] := len and $FF;
len := len shr 8;
end;
CAM_Encrypt(ctx, buf, buf);
{process header}
if hLen > 0 then begin
{octets 0..1: encoding of hLen. Note: since we allow max $FEFF bytes}
{only these to octets are used. Generally up to 10 octets are needed.}
buf[0] := buf[0] xor (hLen shr 8);
buf[1] := buf[1] xor (hLen and $FF);
{now append the hdr data}
blen:= 2;
pb := hdr;
for k:=1 to hLen do begin
if blen=16 then begin
CAM_Encrypt(ctx, buf, buf);
blen := 0;
end;
buf[blen] := buf[blen] xor pb^;
inc(blen);
inc(Ptr2Inc(pb));
end;
if blen<>0 then CAM_Encrypt(ctx, buf, buf);
end;
{setup the ctr counter for source text processing}
pb := pnonce;
IV[0] := (L-1) and $FF;
for k:=1 to 15 do begin
if k<16-L then begin
IV[k] := pb^;
inc(Ptr2Inc(pb));
end
else IV[k] := 0;
end;
{process full source text blocks}
while sLen>=16 do begin
IncCTR(IV);
CAM_Encrypt(ctx,IV,ecc);
if enc_auth then begin
CAM_XorBlock(PCAMBlock(stp)^, buf, buf);
CAM_XorBlock(PCAMBlock(stp)^, ecc, PCAMBlock(dtp)^);
end
else begin
CAM_XorBlock(PCAMBlock(stp)^, ecc, PCAMBlock(dtp)^);
CAM_XorBlock(PCAMBlock(dtp)^, buf, buf);
end;
CAM_Encrypt(ctx, buf, buf);
inc(Ptr2Inc(stp), CAMBLKSIZE);
inc(Ptr2Inc(dtp), CAMBLKSIZE);
dec(sLen, CAMBLKSIZE);
end;
if sLen>0 then begin
{handle remaining bytes of source text}
IncCTR(IV);
CAM_Encrypt(ctx, IV, ecc);
for k:=0 to word(sLen-1) do begin
if enc_auth then begin
b := pByte(stp)^;
pByte(dtp)^ := b xor ecc[k];
end
else begin
b := pByte(stp)^ xor ecc[k];
pByte(dtp)^ := b;
end;
buf[k] := buf[k] xor b;
inc(Ptr2Inc(stp));
inc(Ptr2Inc(dtp));
end;
CAM_Encrypt(ctx, buf, buf);
end;
{setup ctr for the tag (zero the count)}
for k:=15 downto 16-L do IV[k] := 0;
CAM_Encrypt(ctx, IV, ecc);
{store the TAG}
CAM_XorBlock(buf, ecc, tag);
end;
end;
{---------------------------------------------------------------------------}
function CAM_CCM_Enc_AuthEx(var ctx: TCAMContext;
var tag: TCAMBlock; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
{$ifdef CONST}const{$else}var{$endif} nonce; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length}
ptp: pointer; pLen: longint; {plaintext: address / length}
ctp: pointer {ciphertext: address}
): integer;
{-CCM packet encrypt/authenticate without key setup}
begin
CAM_CCM_Enc_AuthEx := CAM_CCM_Core(ctx,true,tag,tLen,@nonce,nLen,hdr,hLen,ptp,pLen,ctp);
end;
{---------------------------------------------------------------------------}
function CAM_CCM_Enc_Auth(var tag: TCAMBlock; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
{$ifdef CONST}const{$else}var{$endif} Key; KBytes: word; {key and byte length of key}
{$ifdef CONST}const{$else}var{$endif} nonce; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length}
ptp: pointer; pLen: longint; {plaintext: address / length}
ctp: pointer {ciphertext: address}
): integer;
{-All-in-one call for CCM packet encrypt/authenticate}
var
ctx: TCAMContext;
err: integer;
begin
err := CAM_Init(Key, KBytes*8, ctx);
if err<>0 then CAM_CCM_Enc_Auth := err
else CAM_CCM_Enc_Auth := CAM_CCM_Core(ctx,true,tag,tLen,@nonce,nLen,hdr,hLen,ptp,pLen,ctp);
fillchar(ctx, sizeof(ctx), 0);
end;
{---------------------------------------------------------------------------}
function CAM_CCM_Dec_VeriEX(var ctx: TCAMContext;
ptag: pointer; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
{$ifdef CONST}const{$else}var{$endif} nonce; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length}
ctp: pointer; cLen: longint; {ciphertext: address / length}
ptp: pointer {plaintext: address}
): integer;
{-CCM packet decrypt/verify without key setup. If ptag^ verification fails, ptp^ is zero-filled!}
var
tag: TCAMBlock;
err,i: integer;
diff: byte;
begin
err := CAM_CCM_Core(ctx,false,tag,tLen,@nonce,nLen,hdr,hLen,ctp,cLen,ptp);
if err=0 then begin
diff := 0;
for i:=0 to pred(tLen) do begin
diff := diff or (pByte(ptag)^ xor tag[i]);
inc(Ptr2Inc(ptag));
end;
err := (((integer(diff)-1) shr 8) and 1)-1; {0 compare, -1 otherwise}
err := err and CAM_Err_CCM_Verify_Tag;
end;
fillchar(tag, sizeof(tag),0);
if err<>0 then fillchar(ptp^, cLen, 0);
CAM_CCM_Dec_VeriEx := err;
end;
{---------------------------------------------------------------------------}
function CAM_CCM_Dec_Veri( ptag: pointer; tLen : word; {Tag & length in [4,6,8,19,12,14,16]}
{$ifdef CONST}const{$else}var{$endif} Key; KBytes: word;{key and byte length of key}
{$ifdef CONST}const{$else}var{$endif} nonce; nLen: word; {nonce: address / length}
hdr: pointer; hLen: word; {header: address / length}
ctp: pointer; cLen: longint; {ciphertext: address / length}
ptp: pointer {plaintext: address}
): integer;
{-All-in-one CCM packet decrypt/verify. If ptag^ verification fails, ptp^ is zero-filled!}
var
ctx: TCAMContext;
err: integer;
begin
err := CAM_Init(Key, KBytes*8, ctx);
if err<>0 then CAM_CCM_Dec_Veri := err
else CAM_CCM_Dec_Veri := CAM_CCM_Dec_VeriEX(ctx,ptag,tLen,nonce,nLen,hdr,hLen,ctp,cLen,ptp);
fillchar(ctx, sizeof(ctx), 0);
end;
end.
|
PROGRAM Avg;
var x, s, n: integer;
BEGIN (* Avg *)
s := 0;
n := 0;
Read(x);
WHILE (x <> 0) DO BEGIN
s := s + x;
n := n + 1;
Read(x);
END; (* WHILE *)
IF (n>0) THEN BEGIN
WriteLn('Avg: ', s/n :5:3); //--> 5: Vorkommastellen, 3: nachkommastellen
END ELSE BEGIN
WriteLn('No data.');
END; (* IF *)
END. (* Avg *) |
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995, 2001 Borland Software Corp. }
{ }
{ Windows specific property editors }
{ }
{*******************************************************}
unit VCLEditors;
interface
uses
Messages, Types, Classes, Graphics, Menus, Controls, Forms, StdCtrls,
DesignIntf, DesignEditors, DesignMenus, ActnList;
{ Property Editors }
type
{ ICustomPropertyDrawing
Implementing this interface allows a property editor to take over the object
inspector's drawing of the name and the value. If paFullWidthName is returned
by IProperty.GetAttributes then only PropDrawName will be called. Default
implementation of both these methods are provided in DefaultPropDrawName
and DefaultPropDrawValue in this unit. }
ICustomPropertyDrawing = interface
['{E1A50419-1288-4B26-9EFA-6608A35F0824}']
procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
end;
{ ICustomPropertyDrawing
Implemention this interface allows a property editor to take over the drawing
of the drop down list box displayed by the property editor. This is only
meaningful to implement if the property editor returns paValueList from
IProperty.GetAttributes. The Value parameter is the result of
IProperty.GetValue. The implementations ListMeasureWidth and ListMeasureHeight
can be left blank since the var parameter is filled in to reasonable defaults
by the object inspector. A default implementation of ListDrawValue is supplied
in the DefaultPropertyListDrawValue procedure included in this unit }
ICustomPropertyListDrawing = interface
['{BE2B8CF7-DDCA-4D4B-BE26-2396B969F8E0}']
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
end;
{ TFontNameProperty
Editor for the TFont.FontName property. Displays a drop-down list of all
the fonts known by Windows. The following global variable will make
this property editor actually show examples of each of the fonts in the
drop down list. We would have enabled this by default but it takes
too many cycles on slower machines or those with a lot of fonts. Enable
it at your own risk. ;-}
var
FontNamePropertyDisplayFontNames: Boolean = False;
type
TFontNameProperty = class(TStringProperty, ICustomPropertyListDrawing)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
// ICustomPropertyListDrawing
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
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, ICustomPropertyDrawing,
ICustomPropertyListDrawing)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
{ ICustomPropertyListDrawing }
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
{ CustomPropertyDrawing }
procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
end;
{ TBrushStyleProperty
Property editor for TBrush's Style. Simply provides for custom render. }
TBrushStyleProperty = class(TEnumProperty, ICustomPropertyDrawing,
ICustomPropertyListDrawing)
public
{ ICustomPropertyListDrawing }
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
{ ICustomPropertyDrawing }
procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
end;
{ TPenStyleProperty
Property editor for TPen's Style. Simply provides for custom render. }
TPenStyleProperty = class(TEnumProperty, ICustomPropertyDrawing,
ICustomPropertyListDrawing)
public
{ ICustomPropertyListDrawing }
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
{ ICustomPropertyDrawing }
procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
end;
{ TCursorProperty
Property editor for the TCursor type. Displays the cursor as a clXXX value
if one exists, otherwise displays the value as hex. Also allows the
clXXX value to be picked from a list. }
TCursorProperty = class(TIntegerProperty, ICustomPropertyListDrawing)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
{ ICustomPropertyListDrawing }
procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas;
var AHeight: Integer);
procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas;
var AWidth: Integer);
procedure ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
end;
{ TFontProperty
Property editor for 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 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;
function GetDisplayValue(const Prop: IProperty): string;
procedure DefaultPropertyDrawName(Prop: TPropertyEditor; Canvas: TCanvas;
const Rect: TRect);
procedure DefaultPropertyDrawValue(Prop: TPropertyEditor; Canvas: TCanvas;
const Rect: TRect);
procedure DefaultPropertyListDrawValue(const Value: string; Canvas: TCanvas;
const Rect: TRect; Selected: Boolean);
type
{ ISelectionMessage }
{ If a selection editor implements this interface the form designer will ensure
all windows message are first sent through this interface before handling
them when the selection editor for the corresponding class is selected.
IsSelectionMessage - Filter for all messages processed by the designer when
this the implementing selection editor is active. Return True if the message
is handled by the selection editor which causes the designer to ignore
the message (as well as preventing the control from seeing the message)
or False, allowing the designer to process the message normally.
Sender the control that received the original message.
Message the message sent by windows to the control. }
ISelectionMessage = interface
['{58274878-BB87-406A-9220-904105C9E112}']
function IsSelectionMessage(Sender: TControl;
var Message: TMessage): Boolean;
end;
ISelectionMessageList = interface
['{C1360368-0099-4A7C-A4A8-7650503BA0C6}']
function Get(Index: Integer): ISelectionMessage;
function GetCount: Integer;
property Count: Integer read GetCount;
property Items[Index: Integer]: ISelectionMessage read Get; default;
end;
function SelectionMessageListOf(const SelectionEditorList: ISelectionEditorList): ISelectionMessageList;
{ Custom Module Types }
type
{ ICustomDesignForm
Allows a custom module to create a different form for use by the designer
as the base form.
CreateDesignForm - Create a descendent of TCustomForm for use by the
designer as the instance to design }
ICustomDesignForm = interface
['{787195AF-C234-49DC-881B-221B69C0137A}']
procedure CreateDesignerForm(const Designer: IDesigner; Root: TComponent;
out DesignForm: TCustomForm; out ComponentContainer: TWinControl);
end;
{ Clipboard utility functions }
var
CF_COMPONENTS: Word;
procedure CopyStreamToClipboard(S: TMemoryStream);
function GetClipboardStream: TMemoryStream;
{ EditAction utility functions }
function EditActionFor(AEditControl: TCustomEdit; Action: TEditAction): Boolean;
function GetEditStateFor(AEditControl: TCustomEdit): TEditState;
{ Registry Information }
var
BaseRegistryKey: string = '';
{ Action Registration }
type
TNotifyActionListChange = procedure;
var
NotifyActionListChange: TNotifyActionListChange = nil;
procedure RegActions(const ACategory: string;
const AClasses: array of TBasicActionClass; AResource: TComponentClass);
procedure UnRegActions(const Classes: array of TBasicActionClass);
procedure EnumActions(Proc: TEnumActionProc; Info: Pointer);
function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction;
implementation
uses Consts, RTLConsts, SysUtils, Windows, Math, Dialogs, Registry, TypInfo,
Clipbrd, ImgList, CommCtrl;
{ Registry Information }
type
TBasicActionRecord = record
ActionClass: TBasicActionClass;
GroupId: Integer;
end;
TActionClassArray = array of TBasicActionRecord;
TActionClassesEntry = record
Category: string;
Actions: TActionClassArray;
Resource: TComponentClass;
end;
TActionClassesArray = array of TActionClassesEntry;
var
DesignersList: TList = nil;
ActionClasses: TActionClassesArray = nil;
{ Action Registration }
type
THackAction = class(TCustomAction);
procedure RegActions(const ACategory: string;
const AClasses: array of TBasicActionClass; AResource: TComponentClass);
var
CategoryIndex, Len, I, J, NewClassCount: Integer;
NewClasses: array of TBasicActionClass;
Skip: Boolean;
S: string;
begin
{ Determine whether we're adding a new category, or adding to an existing one }
CategoryIndex := -1;
for I := Low(ActionClasses) to High(ActionClasses) do
if CompareText(ActionClasses[I].Category, ACategory) = 0 then
begin
CategoryIndex := I;
Break;
end;
{ Adding a new category }
if CategoryIndex = -1 then
begin
CategoryIndex := Length(ActionClasses);
SetLength(ActionClasses, CategoryIndex + 1);
end;
with ActionClasses[CategoryIndex] do
begin
SetLength(NewClasses, Length(AClasses));
{ Remove duplicate classes }
NewClassCount := 0;
for I := Low(AClasses) to High(AClasses) do
begin
Skip := False;
for J := Low(Actions) to High(Actions) do
if AClasses[I] = Actions[I].ActionClass then
begin
Skip := True;
Break;
end;
if not Skip then
begin
NewClasses[Low(NewClasses) + NewClassCount] := AClasses[I];
Inc(NewClassCount);
end;
end;
{ Pack NewClasses }
SetLength(NewClasses, NewClassCount);
SetString(S, PChar(ACategory), Length(ACategory));
Category := S;
Resource := AResource;
Len := Length(Actions);
SetLength(Actions, Len + Length(NewClasses));
for I := Low(NewClasses) to High(NewClasses) do
begin
RegisterNoIcon([NewClasses[I]]);
Classes.RegisterClass(NewClasses[I]);
with Actions[Len + I] do
begin
ActionClass := NewClasses[I];
GroupId := CurrentGroup;
end;
end;
end;
{ Notify all available designers of new TAction class }
if (DesignersList <> nil) and Assigned(NotifyActionListChange) then
NotifyActionListChange;
end;
procedure UnRegActions(const Classes: array of TBasicActionClass);//! far;
begin
end;
procedure UnregisterActionGroup(AGroupId: Integer);
var
I, J: Integer;
begin
for I := Low(ActionClasses) to High(ActionClasses) do
for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do
with ActionClasses[I].Actions[J] do
if GroupId = AGroupId then
begin
ActionClass := nil;
GroupId := -1;
end;
if Assigned(NotifyActionListChange) then
NotifyActionListChange;
end;
procedure EnumActions(Proc: TEnumActionProc; Info: Pointer);
var
I, J, Count: Integer;
ActionClass: TBasicActionClass;
begin
if ActionClasses <> nil then
for I := Low(ActionClasses) to High(ActionClasses) do
begin
Count := 0;
for J := Low(ActionClasses[I].Actions) to High(ActionClasses[I].Actions) do
begin
ActionClass := ActionClasses[I].Actions[J].ActionClass;
if ActionClass = nil then
Continue;
Proc(ActionClasses[I].Category, ActionClass, Info);
Inc(Count);
end;
if Count = 0 then
SetLength(ActionClasses[I].Actions, 0);
end;
end;
function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction;
var
I, J: Integer;
Res: TComponentClass;
Instance: TComponent;
Action: TBasicAction;
function FindComponentByClass(AOwner: TComponent; const AClassName: string): TComponent;
var
I: Integer;
begin
if (AClassName <> '') and (AOwner.ComponentCount > 0) then
for I := 0 to AOwner.ComponentCount - 1 do
begin
Result := AOwner.Components[I];
if CompareText(Result.ClassName, AClassName) = 0 then Exit;
end;
Result := nil;
end;
procedure CreateMaskedBmp(ImageList: TCustomImageList; ImageIndex: Integer;
var Image, Mask: Graphics.TBitmap);
begin
Image := Graphics.TBitmap.Create;
Mask := Graphics.TBitmap.Create;
try
with Image do
begin
Height := ImageList.Height;
Width := ImageList.Width;
end;
with Mask do
begin
Monochrome := True;
Height := ImageList.Height;
Width := ImageList.Width;
end;
ImageList_Draw(ImageList.Handle, ImageIndex, Image.Canvas.Handle, 0, 0, ILD_NORMAL);
ImageList_Draw(ImageList.Handle, ImageIndex, Mask.Canvas.Handle, 0, 0, ILD_MASK);
//! Result.MaskHandle := Mask.ReleaseHandle;
except
Image.Free;
Mask.Free;
Image := nil;
Mask := nil;
raise;
end;
end;
begin
Result := ActionClass.Create(AOwner);
{ Attempt to find the first action with the same class Type as ActionClass in
the Resource component's resource stream, and use its property values as
our defaults. }
Res := nil;
for I := Low(ActionClasses) to High(ActionClasses) do
with ActionClasses[I] do
for J := Low(Actions) to High(Actions) do
if Actions[J].ActionClass = ActionClass then
begin
Res := Resource;
Break;
end;
if Res <> nil then
begin
Instance := Res.Create(nil);
try
Action := FindComponentByClass(Instance, ActionClass.ClassName) as TBasicAction;
if Action <> nil then
begin
with Action as TCustomAction do
begin
TCustomAction(Result).Caption := Caption;
TCustomAction(Result).Checked := Checked;
TCustomAction(Result).Enabled := Enabled;
TCustomAction(Result).HelpContext := HelpContext;
TCustomAction(Result).Hint := Hint;
TCustomAction(Result).ImageIndex := ImageIndex;
TCustomAction(Result).ShortCut := ShortCut;
TCustomAction(Result).Visible := Visible;
if (ImageIndex > -1) and (ActionList <> nil) and
(ActionList.Images <> nil) then
begin
THackAction(Result).FImage.Free;
THackAction(Result).FMask.Free;
CreateMaskedBmp(ActionList.Images, ImageIndex,
Graphics.TBitmap(THackAction(Result).FImage),
Graphics.TBitmap(THackAction(Result).FMask));
end;
end;
end;
finally
Instance.Free;
end;
end;
end;
const
{ context ids for the Font editor and the Color Editor, etc. }
hcDFontEditor = 25000;
hcDColorEditor = 25010;
hcDMediaPlayerOpen = 25020;
function GetDisplayValue(const Prop: IProperty): string;
begin
Result := '';
if Assigned(Prop) and Prop.AllEqual then
Result := Prop.GetValue;
end;
procedure DefaultPropertyDrawName(Prop: TPropertyEditor; Canvas: TCanvas;
const Rect: TRect);
begin
Canvas.TextRect(Rect, Rect.Left + 1, Rect.Top + 1, Prop.GetName);
end;
procedure DefaultPropertyDrawValue(Prop: TPropertyEditor; Canvas: TCanvas;
const Rect: TRect);
begin
Canvas.TextRect(Rect, Rect.Left + 1, Rect.Top + 1, Prop.GetVisualValue);
end;
procedure DefaultPropertyListDrawValue(const Value: string; Canvas: TCanvas;
const Rect: TRect; Selected: Boolean);
begin
Canvas.TextRect(Rect, Rect.Left + 1, Rect.Top + 1, Value);
end;
{ TFontNameProperty }
{ Owner draw code has been commented out, see the interface section's for info. }
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;
procedure TFontNameProperty.ListDrawValue(const Value: string;
ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
var
OldFontName: string;
begin
if FontNamePropertyDisplayFontNames then
with ACanvas do
begin
// save off things
OldFontName := Font.Name;
// set things up and do work
Font.Name := Value;
TextRect(ARect, ARect.Left + 2, ARect.Top + 1, Value);
// restore things
Font.Name := OldFontName;
end
else
DefaultPropertyListDrawValue(Value, ACanvas, ARect, ASelected);
end;
procedure TFontNameProperty.ListMeasureHeight(const Value: string;
ACanvas: TCanvas; var AHeight: Integer);
var
OldFontName: string;
begin
if FontNamePropertyDisplayFontNames then
with ACanvas do
begin
// save off things
OldFontName := Font.Name;
// set things up and do work
Font.Name := Value;
AHeight := TextHeight(Value) + 2;
// restore things
Font.Name := OldFontName;
end;
end;
procedure TFontNameProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
var
OldFontName: string;
begin
if FontNamePropertyDisplayFontNames then
with ACanvas do
begin
// save off things
OldFontName := Font.Name;
// set things up and do work
Font.Name := Value;
AWidth := TextWidth(Value) + 4;
// restore things
Font.Name := OldFontName;
end;
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
if BaseRegistryKey = '' then Exit;
IniFile := TRegIniFile.Create(BaseRegistryKey);
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
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.PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
if GetVisualValue <> '' then
ListDrawValue(GetVisualValue, ACanvas, ARect, True{ASelected})
else
DefaultPropertyDrawValue(Self, ACanvas, ARect);
end;
procedure TColorProperty.ListDrawValue(const Value: string; ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
function ColorToBorderColor(AColor: TColor): TColor;
type
TColorQuad = record
Red,
Green,
Blue,
Alpha: Byte;
end;
begin
if (TColorQuad(AColor).Red > 192) or
(TColorQuad(AColor).Green > 192) or
(TColorQuad(AColor).Blue > 192) then
Result := clBlack
else if ASelected then
Result := clWhite
else
Result := AColor;
end;
var
Right: Integer;
OldPenColor, OldBrushColor: TColor;
begin
Right := (ARect.Bottom - ARect.Top) {* 2} + ARect.Left;
with ACanvas do
begin
// save off things
OldPenColor := Pen.Color;
OldBrushColor := Brush.Color;
// frame things
Pen.Color := Brush.Color;
Rectangle(ARect.Left, ARect.Top, Right, ARect.Bottom);
// set things up and do the work
Brush.Color := StringToColor(Value);
Pen.Color := ColorToBorderColor(ColorToRGB(Brush.Color));
Rectangle(ARect.Left + 1, ARect.Top + 1, Right - 1, ARect.Bottom - 1);
// restore the things we twiddled with
Brush.Color := OldBrushColor;
Pen.Color := OldPenColor;
DefaultPropertyListDrawValue(Value, ACanvas, Rect(Right, ARect.Top, ARect.Right,
ARect.Bottom), ASelected);
end;
end;
procedure TColorProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
begin
AWidth := AWidth + ACanvas.TextHeight('M') {* 2};
end;
procedure TColorProperty.SetValue(const Value: string);
var
NewValue: Longint;
begin
if IdentToColor(Value, NewValue) then
SetOrdValue(NewValue)
else
inherited SetValue(Value);
end;
procedure TColorProperty.ListMeasureHeight(const Value: string;
ACanvas: TCanvas; var AHeight: Integer);
begin
// No implemenation necessary
end;
procedure TColorProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
DefaultPropertyDrawName(Self, ACanvas, ARect);
end;
{ TBrushStyleProperty }
procedure TBrushStyleProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
if GetVisualValue <> '' then
ListDrawValue(GetVisualValue, ACanvas, ARect, ASelected)
else
DefaultPropertyDrawValue(Self, ACanvas, ARect);
end;
procedure TBrushStyleProperty.ListDrawValue(const Value: string;
ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
var
Right: Integer;
OldPenColor, OldBrushColor: TColor;
OldBrushStyle: TBrushStyle;
begin
Right := (ARect.Bottom - ARect.Top) {* 2} + ARect.Left;
with ACanvas do
begin
// save off things
OldPenColor := Pen.Color;
OldBrushColor := Brush.Color;
OldBrushStyle := Brush.Style;
// frame things
Pen.Color := Brush.Color;
Brush.Color := clWindow;
Rectangle(ARect.Left, ARect.Top, Right, ARect.Bottom);
// set things up
Pen.Color := clWindowText;
Brush.Style := TBrushStyle(GetEnumValue(GetPropInfo^.PropType^, Value));
// bsClear hack
if Brush.Style = bsClear then
begin
Brush.Color := clWindow;
Brush.Style := bsSolid;
end
else
Brush.Color := clWindowText;
// ok on with the show
Rectangle(ARect.Left + 1, ARect.Top + 1, Right - 1, ARect.Bottom - 1);
// restore the things we twiddled with
Brush.Color := OldBrushColor;
Brush.Style := OldBrushStyle;
Pen.Color := OldPenColor;
DefaultPropertyListDrawValue(Value, ACanvas, Rect(Right, ARect.Top,
ARect.Right, ARect.Bottom), ASelected);
end;
end;
procedure TBrushStyleProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
begin
AWidth := AWidth + ACanvas.TextHeight('A') {* 2};
end;
procedure TBrushStyleProperty.ListMeasureHeight(const Value: string;
ACanvas: TCanvas; var AHeight: Integer);
begin
// No implementation necessary
end;
procedure TBrushStyleProperty.PropDrawName(ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
begin
DefaultPropertyDrawName(Self, ACanvas, ARect);
end;
{ TPenStyleProperty }
procedure TPenStyleProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect;
ASelected: Boolean);
begin
if GetVisualValue <> '' then
ListDrawValue(GetVisualValue, ACanvas, ARect, ASelected)
else
DefaultPropertyDrawValue(Self, ACanvas, ARect);
end;
procedure TPenStyleProperty.ListDrawValue(const Value: string;
ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
var
Right, Top: Integer;
OldPenColor, OldBrushColor: TColor;
OldPenStyle: TPenStyle;
begin
Right := (ARect.Bottom - ARect.Top) * 2 + ARect.Left;
Top := (ARect.Bottom - ARect.Top) div 2 + ARect.Top;
with ACanvas do
begin
// save off things
OldPenColor := Pen.Color;
OldBrushColor := Brush.Color;
OldPenStyle := Pen.Style;
// frame things
Pen.Color := Brush.Color;
Rectangle(ARect.Left, ARect.Top, Right, ARect.Bottom);
// white out the background
Pen.Color := clWindowText;
Brush.Color := clWindow;
Rectangle(ARect.Left + 1, ARect.Top + 1, Right - 1, ARect.Bottom - 1);
// set thing up and do work
Pen.Color := clWindowText;
Pen.Style := TPenStyle(GetEnumValue(GetPropInfo^.PropType^, Value));
MoveTo(ARect.Left + 1, Top);
LineTo(Right - 1, Top);
MoveTo(ARect.Left + 1, Top + 1);
LineTo(Right - 1, Top + 1);
// restore the things we twiddled with
Brush.Color := OldBrushColor;
Pen.Style := OldPenStyle;
Pen.Color := OldPenColor;
DefaultPropertyListDrawValue(Value, ACanvas, Rect(Right, ARect.Top,
ARect.Right, ARect.Bottom), ASelected);
end;
end;
procedure TPenStyleProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
begin
AWidth := AWidth + ACanvas.TextHeight('X') * 2;
end;
procedure TPenStyleProperty.ListMeasureHeight(const Value: string;
ACanvas: TCanvas; var AHeight: Integer);
begin
// No implementation necessary
end;
procedure TPenStyleProperty.PropDrawName(ACanvas: TCanvas;
const ARect: TRect; ASelected: Boolean);
begin
DefaultPropertyDrawName(Self, ACanvas, ARect);
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;
procedure TCursorProperty.ListDrawValue(const Value: string;
ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean);
var
Right: Integer;
CursorIndex: Integer;
CursorHandle: THandle;
begin
Right := ARect.Left + GetSystemMetrics(SM_CXCURSOR) + 4;
with ACanvas do
begin
if not IdentToCursor(Value, CursorIndex) then
CursorIndex := StrToInt(Value);
ACanvas.FillRect(ARect);
CursorHandle := Screen.Cursors[CursorIndex];
if CursorHandle <> 0 then
DrawIconEx(ACanvas.Handle, ARect.Left + 2, ARect.Top + 2, CursorHandle,
0, 0, 0, 0, DI_NORMAL or DI_DEFAULTSIZE);
DefaultPropertyListDrawValue(Value, ACanvas, Rect(Right, ARect.Top,
ARect.Right, ARect.Bottom), ASelected);
end;
end;
procedure TCursorProperty.ListMeasureWidth(const Value: string;
ACanvas: TCanvas; var AWidth: Integer);
begin
AWidth := AWidth + GetSystemMetrics(SM_CXCURSOR) + 4;
end;
procedure TCursorProperty.ListMeasureHeight(const Value: string;
ACanvas: TCanvas; var AHeight: Integer);
begin
AHeight := Max(ACanvas.TextHeight('Wg'), GetSystemMetrics(SM_CYCURSOR) + 4);
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.CreateRes(@SInvalidPropertyValue);
end;
SetOrdValue(NewValue);
end;
{ TTabOrderProperty }
function TTabOrderProperty.GetAttributes: TPropertyAttributes;
begin
Result := [];
end;
{ TCaptionProperty }
function TCaptionProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paAutoUpdate, paRevertable];
end;
{ Clipboard routines }
procedure CopyStreamToClipboard(S: TMemoryStream);
var
T: TMemoryStream;
I: TValueType;
V: Integer;
procedure CopyToClipboard(Format: Word; S: TMemoryStream);
var
Handle: THandle;
Mem: Pointer;
begin
Handle := GlobalAlloc(GMEM_MOVEABLE, S.Size);
Mem := GlobalLock(Handle);
Move(S.Memory^, Mem^, S.Size);
GlobalUnlock(Handle);
Clipboard.SetAsHandle(Format, Handle);
end;
begin
Clipboard.Open;
try
CopyToClipboard(CF_COMPONENTS, S);
S.Position := 0;
T := TMemoryStream.Create;
try
repeat
S.Read(I, SizeOf(I));
S.Seek(-SizeOf(I), 1);
if I = vaNull then Break;
ObjectBinaryToText(S, T);
until False;
V := 0;
T.Write(V, 1);
CopyToClipboard(CF_TEXT, T);
finally
T.Free;
end;
finally
Clipboard.Close;
end;
end;
function GetClipboardStream: TMemoryStream;
var
S, T: TMemoryStream;
Handle: THandle;
Mem: Pointer;
Format: Word;
V: TValueType;
function AnotherObject(S: TStream): Boolean;
var
Buffer: array[0..255] of Char;
Position: Integer;
begin
Position := S.Position;
Buffer[S.Read(Buffer, SizeOf(Buffer))-1] := #0;
S.Position := Position;
Result := PossibleStream(Buffer);
end;
begin
Result := TMemoryStream.Create;
try
if Clipboard.HasFormat(CF_COMPONENTS) then
Format := CF_COMPONENTS else
Format := CF_TEXT;
Clipboard.Open;
try
Handle := Clipboard.GetAsHandle(Format);
Mem := GlobalLock(Handle);
try
Result.Write(Mem^, GlobalSize(Handle));
finally
GlobalUnlock(Handle);
end;
finally
Clipboard.Close;
end;
Result.Position := 0;
if Format = CF_TEXT then
begin
S := TMemoryStream.Create;
try
while AnotherObject(Result) do ObjectTextToBinary(Result, S);
V := vaNull;
S.Write(V, SizeOf(V));
T := Result;
Result := nil;
T.Free;
except
S.Free;
raise;
end;
Result := S;
Result.Position := 0;
end;
except
Result.Free;
raise;
end;
end;
type
TSelectionMessageList = class(TInterfacedObject, ISelectionMessageList)
private
FList: IInterfaceList;
protected
procedure Add(AEditor: ISelectionMessage);
public
constructor Create;
function Get(Index: Integer): ISelectionMessage;
function GetCount: Integer;
property Count: Integer read GetCount;
property Items[Index: Integer]: ISelectionMessage read Get; default;
end;
{ TSelectionMessageList }
procedure TSelectionMessageList.Add(AEditor: ISelectionMessage);
begin
FList.Add(AEditor);
end;
constructor TSelectionMessageList.Create;
begin
inherited;
FList := TInterfaceList.Create;
end;
function TSelectionMessageList.Get(Index: Integer): ISelectionMessage;
begin
Result := FList[Index] as ISelectionMessage;
end;
function TSelectionMessageList.GetCount: Integer;
begin
Result := FList.Count;
end;
function SelectionMessageListOf(const SelectionEditorList: ISelectionEditorList): ISelectionMessageList;
var
SelectionMessage: ISelectionMessage;
I: Integer;
R: TSelectionMessageList;
begin
R := TSelectionMessageList.Create;
for I := 0 to SelectionEditorList.Count - 1 do
if Supports(SelectionEditorList[I], ISelectionMessage, SelectionMessage) then
R.Add(SelectionMessage);
Result := R;
end;
{ EditAction utility functions }
function EditActionFor(AEditControl: TCustomEdit; Action: TEditAction): Boolean;
begin
Result := True;
case Action of
eaUndo: AEditControl.Undo;
eaCut: AEditControl.CutToClipboard;
eaCopy: AEditControl.CopyToClipboard;
eaDelete: AEditControl.ClearSelection;
eaPaste: AEditControl.PasteFromClipboard;
eaSelectAll: AEditControl.SelectAll;
else
Result := False;
end;
end;
function GetEditStateFor(AEditControl: TCustomEdit): TEditState;
begin
Result := [];
if AEditControl.CanUndo then
Include(Result, esCanUndo);
if AEditControl.SelLength > 0 then
begin
Include(Result, esCanCut);
Include(Result, esCanCopy);
Include(Result, esCanDelete);
end;
if Clipboard.HasFormat(CF_TEXT) then
Include(Result, esCanPaste);
if AEditControl.SelLength < Length(AEditControl.Text) then
Include(Result, esCanSelectAll);
end;
initialization
CF_COMPONENTS := RegisterClipboardFormat('Delphi Components');
NotifyGroupChange(UnregisterActionGroup);
finalization
UnNotifyGroupChange(UnregisterActionGroup);
end.
|
unit Vigilante.Compilacao.DI;
interface
uses
ContainerDI.Base.Impl, ContainerDI.Base;
type
TCompilacaoDI = class(TContainerDI)
public
class function New: IContainerDI;
procedure Build; override;
end;
implementation
uses
ContainerDI,
Vigilante.Compilacao.View,
Vigilante.View.URLDialog.Impl, Vigilante.View.CompilacaoURLDialog,
Vigilante.Compilacao.Service, Vigilante.Compilacao.Service.Impl,
Vigilante.Controller.Compilacao, Vigilante.Controller.Compilacao.Impl,
Vigilante.Compilacao.Observer, Vigilante.Compilacao.Observer.Impl,
Vigilante.Compilacao.Event, Vigilante.Compilacao.DomainEvent.Impl,
Vigilante.Compilacao.Repositorio, Vigilante.Infra.Compilacao.Repositorio.Impl,
Vigilante.Infra.Compilacao.Builder, Vigilante.Infra.Compilacao.Builder.Impl,
Vigilante.Infra.Compilacao.DataAdapter, Vigilante.Infra.Compilacao.JSONDataAdapter;
procedure TCompilacaoDI.Build;
begin
CDI.RegisterType<TCompilacaoService>.Implements<ICompilacaoService>;
CDI.RegisterType<TCompilacaoURLDialog>.Implements<ICompilacaoURLDialog>('ICompilacaoURLDialog');
CDI.RegisterType<TfrmCompilacaoView, TfrmCompilacaoView>;
CDI.RegisterType<TCompilacaoSubject>.Implements<ICompilacaoSubject>.AsSingleton;
CDI.RegisterType<TCompilacaoController>.Implements<ICompilacaoController>;
CDI.RegisterType<TCompilacaoDomainEvent>.Implements<ICompilacaoEvent>;
CDI.RegisterType<TCompilacaoJSONDataAdapter>.Implements<ICompilacaoAdapter>;
CDI.RegisterType<TCompilacaoBuilder>.Implements<ICompilacaoBuilder>;
CDI.RegisterType<TCompilacaoRepositorio>.Implements<ICompilacaoRepositorio>;
end;
class function TCompilacaoDI.New: IContainerDI;
begin
Result := Create;
end;
end.
|
unit caProcesses;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
Windows,
SysUtils,
Classes,
Contnrs,
Tlhelp32,
PSAPI,
Forms,
// ca units
caClasses,
caConsts,
caTypes,
caLog,
caUtils;
type
//---------------------------------------------------------------------------
// TcaProcess
//---------------------------------------------------------------------------
TcaProcessList = class;
TcaProcess = class(TObject)
private
// Property fields
FMemoryUsage: DWORD;
FModuleFileName: string;
FProcessID: Cardinal;
public
// Properties
property MemoryUsage: DWORD read FMemoryUsage write FMemoryUsage;
property ModuleFileName: string read FModuleFileName write FModuleFileName;
property ProcessID: Cardinal read FProcessID write FProcessID;
end;
//---------------------------------------------------------------------------
// IcaProcessList
//---------------------------------------------------------------------------
IcaProcessList = interface
['{83065397-15E1-42F9-A7DE-6DEF99A7C880}']
// Property methods
function GetProcess(Index: Integer): TcaProcess;
function GetProcessCount: Integer;
// Interface methods
function FindProcessByName(const AName: String; AAllowSubString: Boolean = False): TcaProcess;
function FindProcessID(AProcessID: Cardinal): TcaProcess;
function StopProcessByName(const AName: String; AAllowSubString: Boolean = False): Boolean;
procedure GetProcessNamesAsStrings(AList: TStrings; AShowMemory: Boolean);
procedure SortByProcessName;
procedure SortByAscendingMemory;
procedure SortByDescendingMemory;
procedure Update;
// Interface properties
property ProcessCount: Integer read GetProcessCount;
property Processes[Index: Integer]: TcaProcess read GetProcess; default;
end;
//---------------------------------------------------------------------------
// TcaProcessList
//---------------------------------------------------------------------------
TcaProcessList = class(TInterfacedObject, IcaProcessList)
private
// Private fields
FList: TObjectList;
// Property methods - IcaProcessList
function GetProcess(Index: Integer): TcaProcess;
function GetProcessCount: Integer;
// Private methods
procedure BuildList;
function StopProcessByID(AProcessID: Cardinal): Boolean;
public
// Create/Destroy
constructor Create;
destructor Destroy; override;
// Interface methods - IcaProcessList
function FindProcessByName(const AName: String; AAllowSubString: Boolean = False): TcaProcess;
function FindProcessID(AProcessID: Cardinal): TcaProcess;
function StopProcessByName(const AName: String; AAllowSubString: Boolean = False): Boolean;
procedure GetProcessNamesAsStrings(AList: TStrings; AShowMemory: Boolean);
procedure SortByProcessName;
procedure SortByAscendingMemory;
procedure SortByDescendingMemory;
procedure Update;
// Interface properties - IcaProcessList
property ProcessCount: Integer read GetProcessCount;
property Processes[Index: Integer]: TcaProcess read GetProcess; default;
end;
//---------------------------------------------------------------------------
// TcaWindow
//---------------------------------------------------------------------------
TcaWindow = class(TObject)
private
FHandle: HWND;
// property methods
function GetCaption: string;
function GetHeight: Integer;
function GetIconic: Boolean;
function GetLeft: Integer;
function GetParent: HWND;
function GetTop: Integer;
function GetVisible: Boolean;
function GetWidth: Integer;
function GetWindowClass: string;
// private methods
function Rect: TRect;
public
// properties
property Caption: string read GetCaption;
property Handle: HWND read FHandle write FHandle;
property Height: Integer read GetHeight;
property Iconic: Boolean read GetIconic;
property Left: Integer read GetLeft;
property Parent: HWND read GetParent;
property Top: Integer read GetTop;
property Visible: Boolean read GetVisible;
property Width: Integer read GetWidth;
property WindowClass: string read GetWindowClass;
end;
//---------------------------------------------------------------------------
// IcaWindows
//---------------------------------------------------------------------------
IcaWindows = interface
['{BC8869C1-B80B-42D4-8E70-7B945E2FCA72}']
// event property methods
function GetCount: Integer;
function GetItem(Index: Integer): TcaWindow;
function GetOnUpdate: TNotifyEvent;
procedure SetOnUpdate(const Value: TNotifyEvent);
// interface methods
function FindCaption(const ACaption: string): TcaWindow;
function FindHandle(AHandle: HWND): TcaWindow;
function FindWindowClass(const AWindowClass: string): TcaWindow;
procedure GetCaptionsAsStrings(AStrings: TStrings; AVisible: Boolean = True);
// properties
property Count: Integer read GetCount;
property Items[Index: Integer]: TcaWindow read GetItem; default;
// event properties
property OnUpdate: TNotifyEvent read GetOnUpdate write SetOnUpdate;
end;
//---------------------------------------------------------------------------
// TcaWindowsThread
//---------------------------------------------------------------------------
TcaWindowsThread = class(TThread)
private
// private fields
FInterval: Integer;
FUpdateProc: TThreadMethod;
protected
// protected methods
procedure Execute; override;
public
// create/destroy
constructor CreateThread(AUpdateProc: TThreadMethod; AInterval: Integer);
destructor Destroy; override;
end;
//---------------------------------------------------------------------------
// TcaWindows
//---------------------------------------------------------------------------
TcaWindows = class(TInterfacedObject, IcaWindows)
private
// private fields
FLastCaptions: string;
FWindows: TObjectList;
FThread: TcaWindowsThread;
FUpdating: Boolean;
// event property fields
FOnUpdate: TNotifyEvent;
// private methods
procedure Update;
// event property methods
function GetCount: Integer;
function GetItem(Index: Integer): TcaWindow;
function GetOnUpdate: TNotifyEvent;
procedure SetOnUpdate(const Value: TNotifyEvent);
protected
// protected methods
procedure DoUpdate; virtual;
// interface methods
function FindCaption(const ACaption: string): TcaWindow;
function FindHandle(AHandle: HWND): TcaWindow;
function FindWindowClass(const AWindowClass: string): TcaWindow;
procedure GetCaptionsAsStrings(AStrings: TStrings; AVisible: Boolean = True);
public
// create/destroy
constructor Create(AInterval: Integer);
destructor Destroy; override;
end;
//---------------------------------------------------------------------------
// IcaProcessLauncher
//---------------------------------------------------------------------------
TcaProcessThread = class;
TcaProcessOption = (poNoteExit, poForceExit);
TcaProcessOptions = set of TcaProcessOption;
TcaProcessIdleEvent = procedure(Sender: TObject; AProcessID: Cardinal) of object;
TcaProcessExitEvent = procedure(Sender: TObject; AExitCode: DWORD) of object;
IcaProcessLauncher = interface
['{0797722E-B50A-4D25-B152-487ED44C6F25}']
// Property methods
function GetActive: Boolean;
function GetAppCaption: string;
function GetAppName: string;
function GetCommandLine: string;
function GetFolder: string;
function GetIdle: Boolean;
function GetJustOneInstance: Boolean;
function GetProcessID: Cardinal;
function GetShowWindow: TcaShowWindow;
function GetThread: TcaProcessThread;
function GetWaitOptions: TcaProcessOptions;
procedure SetAppCaption(const Value: string);
procedure SetAppName(const Value: string);
procedure SetCommandLine(const Value: string);
procedure SetFolder(const Value: string);
procedure SetIdle(const Value: Boolean);
procedure SetJustOneInstance(const Value: Boolean);
procedure SetProcessID(const Value: Cardinal);
procedure SetShowWindow(const Value: TcaShowWindow);
procedure SetThread(const Value: TcaProcessThread);
procedure SetWaitOptions(const Value: TcaProcessOptions);
// Event property methods
function GetOnFinished: TcaProcessExitEvent;
function GetOnIdle: TcaProcessIdleEvent;
procedure SetOnFinished(const Value: TcaProcessExitEvent);
procedure SetOnIdle(const Value: TcaProcessIdleEvent);
// Interface methods
procedure DoFinished(ExitCode: DWORD);
procedure DoIdle;
procedure Execute;
procedure ReleaseApplication;
// Properties
property Active: Boolean read GetActive;
property AppCaption: string read GetAppCaption write SetAppCaption;
property AppName: string read GetAppName write SetAppName;
property CommandLine: string read GetCommandLine write SetCommandLine;
property Folder: string read GetFolder write SetFolder;
property Idle: Boolean read GetIdle write SetIdle;
property JustOneInstance: Boolean read GetJustOneInstance write SetJustOneInstance;
property ProcessID: Cardinal read GetProcessID write SetProcessID;
property ShowWindow: TcaShowWindow read GetShowWindow write SetShowWindow;
property Thread: TcaProcessThread read GetThread write SetThread;
property WaitOptions: TcaProcessOptions read GetWaitOptions write SetWaitOptions;
// Event properties
property OnFinished: TcaProcessExitEvent read GetOnFinished write SetOnFinished;
property OnIdle: TcaProcessIdleEvent read GetOnIdle write SetOnIdle;
end;
//---------------------------------------------------------------------------
// TcaProcessLauncher
//---------------------------------------------------------------------------
TcaProcessLauncher = class(TInterfacedObject, IcaProcessLauncher)
protected
// Private fields
FAppCaption: string;
FAppName: string;
FCommandLine: string;
FFolder: string;
FIdle: Boolean;
FJustOneInstance: Boolean;
FProcessID: Cardinal;
FShowWindow: TcaShowWindow;
FThread: TcaProcessThread;
FWaitOptions: TcaProcessOptions;
// Event property fields
FOnFinished: TcaProcessExitEvent;
FOnIdle: TcaProcessIdleEvent;
// Interface property methods - IcaProcessLauncher
function GetActive: Boolean;
function GetAppCaption: string;
function GetAppName: string;
function GetCommandLine: string;
function GetFolder: string;
function GetIdle: Boolean;
function GetJustOneInstance: Boolean;
function GetProcessID: Cardinal;
function GetShowWindow: TcaShowWindow;
function GetThread: TcaProcessThread;
function GetWaitOptions: TcaProcessOptions;
procedure SetAppCaption(const Value: string);
procedure SetAppName(const Value: string);
procedure SetCommandLine(const Value: string);
procedure SetFolder(const Value: string);
procedure SetIdle(const Value: Boolean);
procedure SetJustOneInstance(const Value: Boolean);
procedure SetProcessID(const Value: Cardinal);
procedure SetShowWindow(const Value: TcaShowWindow);
procedure SetThread(const Value: TcaProcessThread);
procedure SetWaitOptions(const Value: TcaProcessOptions);
// Event property methods - IcaProcessLauncher
function GetOnFinished: TcaProcessExitEvent;
function GetOnIdle: TcaProcessIdleEvent;
procedure SetOnFinished(const Value: TcaProcessExitEvent);
procedure SetOnIdle(const Value: TcaProcessIdleEvent);
// Private methods
function IsActive: Boolean;
protected
// Protected event triggers
procedure DoFinished(ExitCode: DWORD); virtual;
procedure DoIdle; virtual;
// Protected properties
property Thread: TcaProcessThread read FThread write FThread;
public
// Create/Destroy
constructor Create;
destructor Destroy; override;
// Interface methods - IcaProcessLauncher
procedure Execute;
procedure ReleaseApplication;
// Interface properties - IcaProcessLauncher
property Active: Boolean read GetActive;
property AppCaption: string read GetAppCaption write SetAppCaption;
property AppName: string read GetAppName write SetAppName;
property CommandLine: string read GetCommandLine write SetCommandLine;
property Folder: string read GetFolder write SetFolder;
property Idle: Boolean read GetIdle write SetIdle;
property JustOneInstance: Boolean read GetJustOneInstance write SetJustOneInstance;
property ProcessID: Cardinal read GetProcessID write SetProcessID;
property ShowWindow: TcaShowWindow read GetShowWindow write SetShowWindow;
property WaitOptions: TcaProcessOptions read GetWaitOptions write SetWaitOptions;
// Interface event properties - IcaProcessLauncher
property OnFinished: TcaProcessExitEvent read GetOnFinished write SetOnFinished;
property OnIdle: TcaProcessIdleEvent read GetOnIdle write SetOnIdle;
end;
//---------------------------------------------------------------------------
// TcaProcessThread
//---------------------------------------------------------------------------
TcaProcessThread = class(TThread)
private
// Private fields
FProcessInfo: TProcessInformation;
FProcessLauncher: IcaProcessLauncher;
// Private methods
procedure LaunchNewProcess;
// Event handlers
procedure ResetThread(Sender: TObject);
protected
// Protected methods
procedure Execute; override;
public
// Create/Destroy
constructor CreateThread(const AProcessLauncher: IcaProcessLauncher);
end;
function EnumerateWindows(hWnd: HWND; lParam: LPARAM): BOOL; stdcall;
implementation
uses Types;
//---------------------------------------------------------------------------
// TcaProcessList
//---------------------------------------------------------------------------
// Create/Destroy
constructor TcaProcessList.Create;
begin
inherited;
FList := TObjectList.Create(True);
Update;
end;
destructor TcaProcessList.Destroy;
begin
FList.Free;
inherited;
end;
// Public methods
function TcaProcessList.FindProcessByName(const AName: String; AAllowSubString: Boolean = False): TcaProcess;
var
Index: Integer;
Process: TcaProcess;
FoundProcess: Boolean;
begin
Result := nil;
for Index := 0 to GetProcessCount - 1 do
begin
Process := GetProcess(Index);
if AAllowSubString then
FoundProcess := Pos(LowerCase(AName), LowerCase(Process.ModuleFileName)) > 0
else
FoundProcess := LowerCase(Process.ModuleFileName) = LowerCase(AName);
if FoundProcess then
begin
Result := Process;
Break;
end;
end;
end;
function TcaProcessList.FindProcessID(AProcessID: Cardinal): TcaProcess;
var
Index: Integer;
Process: TcaProcess;
begin
Result := nil;
for Index := 0 to GetProcessCount - 1 do
begin
Process := GetProcess(Index);
if Process.ProcessID = AProcessID then
begin
Result := Process;
Break;
end;
end;
end;
procedure TcaProcessList.GetProcessNamesAsStrings(AList: TStrings; AShowMemory: Boolean);
var
Index: Integer;
Process: TcaProcess;
ListEntry: String;
begin
AList.Clear;
AList.BeginUpdate;
try
for Index := 0 to GetProcessCount - 1 do
begin
Process := GetProcess(Index);
ListEntry := Process.ModuleFileName;
if AShowMemory then
ListEntry := ListEntry + Format(' [%dK]', [Process.MemoryUsage div 1024]);
AList.Add(ListEntry);
end;
finally
AList.EndUpdate;
end;
end;
function AscendingMemorySortFunc(Item1, Item2: Pointer): Integer;
var
Process1: TcaProcess;
Process2: TcaProcess;
begin
Process1 := TcaProcess(Item1);
Process2 := TcaProcess(Item2);
Result := Process1.MemoryUsage - Process2.MemoryUsage;
end;
procedure TcaProcessList.SortByAscendingMemory;
begin
FList.Sort(AscendingMemorySortFunc);
end;
function DescendingMemorySortFunc(Item1, Item2: Pointer): Integer;
var
Process1: TcaProcess;
Process2: TcaProcess;
begin
Process1 := TcaProcess(Item1);
Process2 := TcaProcess(Item2);
Result := Process2.MemoryUsage - Process1.MemoryUsage;
end;
procedure TcaProcessList.SortByDescendingMemory;
begin
FList.Sort(DescendingMemorySortFunc);
end;
function ProcessNameSortFunc(Item1, Item2: Pointer): Integer;
var
Process1: TcaProcess;
Process2: TcaProcess;
begin
Process1 := TcaProcess(Item1);
Process2 := TcaProcess(Item2);
Result := AnsiCompareText(Process1.ModuleFileName, Process2.ModuleFileName);
end;
procedure TcaProcessList.SortByProcessName;
begin
FList.Sort(ProcessNameSortFunc);
end;
function TcaProcessList.StopProcessByID(AProcessID: Cardinal): Boolean;
var
ProcessHandle: THandle;
begin
ProcessHandle := OpenProcess(PROCESS_TERMINATE, LongBool(False), AProcessID);
Result := TerminateProcess(ProcessHandle, 0);
end;
function TcaProcessList.StopProcessByName(const AName: String; AAllowSubString: Boolean = False): Boolean;
var
Process: TcaProcess;
begin
Result := False;
Process := FindProcessByName(AName, AAllowSubString);
if Process <> nil then
Result := StopProcessByID(Process.ProcessID);
end;
procedure TcaProcessList.Update;
begin
BuildList;
end;
// Private methods
procedure TcaProcessList.BuildList;
function GetProcessMemoryUsage(APID: Cardinal): DWORD;
var
ProcessHandle: THandle;
PMC: TProcessMemoryCounters;
begin
Result := 0;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, aPID);
if ProcessHandle <> 0 then
try
PMC.cb:=SizeOf(PMC);
GetProcessMemoryInfo(ProcessHandle, @PMC, SizeOf(PMC));
Result := PMC.WorkingSetSize;
finally
CloseHandle(ProcessHandle);
end;
end;
procedure BuildListForNT4;
var
Handle: THandle;
Index: Integer;
ModuleFileName: array[0..MAX_PATH] of Char;
Needed: DWORD;
PIDs: array[0..1024] of DWORD;
Process: TcaProcess;
ProcessCount: Integer;
begin
if EnumProcesses(@PIDs, Sizeof(PIDs), Needed) then
begin
ProcessCount := (Needed div Sizeof(DWORD));
for Index := 0 to ProcessCount - 1 do
begin
if PIDs[Index] <> 0 then
begin
Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PIDs[Index]);
if Handle <> 0 then
begin
try
Process := TcaProcess.Create;
if GetModuleFileNameEx(Handle, 0, ModuleFileName, Sizeof(ModuleFileName)) = 0 then
begin
Process.ModuleFileName := '[System]';
Process.ProcessID := INVALID_HANDLE_VALUE;
end
else
begin
Process.ModuleFileName := ModuleFileName;
Process.ProcessID := PIDs[Index];
end;
finally
CloseHandle(Handle);
end;
Process.MemoryUsage := GetProcessMemoryUsage(PIDs[Index]);
FList.Add(Process);
end;
end;
end;
end;
end;
procedure BuildListFor9xAnd2000;
var
NextProc: Boolean;
ProcEntry: TProcessEntry32;
Process: TcaProcess;
SnapProcHandle: THandle;
begin
SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if SnapProcHandle <> THandle(-1) then
try
ProcEntry.dwSize := Sizeof(ProcEntry);
NextProc := Process32First(SnapProcHandle, ProcEntry);
while NextProc do
begin
Process := TcaProcess.Create;
Process.ModuleFileName := ProcEntry.szExeFile;
Process.ProcessID := ProcEntry.th32ProcessID;
Process.MemoryUsage := GetProcessMemoryUsage(Process.ProcessID);
FList.Add(Process);
NextProc := Process32Next(SnapProcHandle, ProcEntry);
end;
finally
CloseHandle(SnapProcHandle);
end;
end;
begin
FList.Clear;
if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion = 4) then
BuildListForNT4
else
BuildListFor9xAnd2000;
end;
// Property methods
function TcaProcessList.GetProcess(Index: Integer): TcaProcess;
begin
Result := TcaProcess(FList[Index]);
end;
function TcaProcessList.GetProcessCount: Integer;
begin
Result := FList.Count;
end;
//---------------------------------------------------------------------------
// TcaWindow
//---------------------------------------------------------------------------
// private methods
function TcaWindow.Rect: TRect;
var
Rect: TRect;
begin
Result := Types.Rect(0, 0, 0, 0);
if Windows.GetWindowRect(FHandle, Rect) then
Result := Rect;
end;
// property methods
function TcaWindow.GetCaption: string;
var
TextLen: Integer;
begin
TextLen := Succ(GetWindowTextLength(FHandle));
SetLength(Result, TextLen);
GetWindowText(FHandle, PChar(Result), TextLen);
end;
function TcaWindow.GetHeight: Integer;
begin
Result := Rect.Bottom - Rect.Top;
end;
function TcaWindow.GetIconic: Boolean;
begin
Result := IsIconic(FHandle);
end;
function TcaWindow.GetLeft: Integer;
begin
Result := Rect.Left;
end;
function TcaWindow.GetParent: HWND;
begin
Result := Windows.GetParent(FHandle);
end;
function TcaWindow.GetTop: Integer;
begin
Result := Rect.Top;
end;
function TcaWindow.GetVisible: Boolean;
begin
Result := IsWindowVisible(FHandle);
end;
function TcaWindow.GetWidth: Integer;
begin
Result := Rect.Right - Rect.Left;
end;
function TcaWindow.GetWindowClass: string;
begin
Result := Utils.GetWindowClass(FHandle);
end;
//---------------------------------------------------------------------------
// TcaWindowsThread
//---------------------------------------------------------------------------
// create/destroy
constructor TcaWindowsThread.CreateThread(AUpdateProc: TThreadMethod; AInterval: Integer);
begin
inherited Create(True);
FUpdateProc := AUpdateProc;
FInterval := AInterval;
FreeOnTerminate := True;
Resume;
end;
destructor TcaWindowsThread.Destroy;
begin
inherited;
end;
// protected methods
procedure TcaWindowsThread.Execute;
begin
while not Terminated do
begin
Synchronize(FUpdateProc);
Sleep(FInterval);
end;
end;
//---------------------------------------------------------------------------
// TcaWindows
//---------------------------------------------------------------------------
// create/destroy
constructor TcaWindows.Create(AInterval: Integer);
begin
inherited Create;
FWindows := TObjectList.Create(True);
FThread := TcaWindowsThread.CreateThread(Update, AInterval);
end;
destructor TcaWindows.Destroy;
begin
FThread.Terminate;
FWindows.Free;
inherited;
end;
// interface methods
function TcaWindows.FindCaption(const ACaption: string): TcaWindow;
var
Index: Integer;
Window: TcaWindow;
begin
while FUpdating do
Application.ProcessMessages;
Result := nil;
for Index := 0 to Pred(GetCount) do
begin
Window := GetItem(Index);
if Window.Caption = ACaption then
begin
Result := Window;
Break;
end;
end;
end;
function TcaWindows.FindHandle(AHandle: HWND): TcaWindow;
var
Index: Integer;
Window: TcaWindow;
begin
while FUpdating do
Application.ProcessMessages;
Result := nil;
for Index := 0 to Pred(GetCount) do
begin
Window := GetItem(Index);
if Window.Handle = AHandle then
begin
Result := Window;
Break;
end;
end;
end;
function TcaWindows.FindWindowClass(const AWindowClass: string): TcaWindow;
var
Index: Integer;
Window: TcaWindow;
begin
while FUpdating do
Application.ProcessMessages;
Result := nil;
for Index := 0 to Pred(GetCount) do
begin
Window := GetItem(Index);
if Window.WindowClass = AWindowClass then
begin
Result := Window;
Break;
end;
end;
end;
procedure TcaWindows.GetCaptionsAsStrings(AStrings: TStrings; AVisible: Boolean = True);
var
Index: Integer;
Window: TcaWindow;
begin
AStrings.BeginUpdate;
AStrings.Clear;
for Index := 0 to Pred(GetCount) do
begin
Window := GetItem(Index);
if (Window.Visible = AVisible) and (Trim(Window.Caption) <> '') then
AStrings.Add(Window.Caption);
end;
AStrings.EndUpdate;
end;
// protected methods
procedure TcaWindows.DoUpdate;
begin
if Assigned(FOnUpdate) then FOnUpdate(Self);
end;
// private methods
procedure TcaWindows.Update;
var
Captions: TStrings;
begin
FUpdating := True;
Captions := Auto(TStringList.Create).Instance;
FWindows.Clear;
EnumWindows(@EnumerateWindows, Integer(FWindows));
GetCaptionsAsStrings(Captions);
if Captions.Text <> FLastCaptions then
begin
DoUpdate;
FLastCaptions := Captions.Text;
end;
FUpdating := False;
end;
function EnumerateWindows(hWnd: HWND; lParam: LPARAM): BOOL;
var
AWindows: TObjectList;
Window: TcaWindow;
begin
AWindows := TObjectList(lParam);
Window := TcaWindow.Create;
Window.Handle := hWnd;
AWindows.Add(Window);
Result := True;
end;
// event property methods
function TcaWindows.GetCount: Integer;
begin
Result := FWindows.Count;
end;
function TcaWindows.GetItem(Index: Integer): TcaWindow;
begin
Result := TcaWindow(FWindows[Index]);
end;
// event property methods
function TcaWindows.GetOnUpdate: TNotifyEvent;
begin
Result := FOnUpdate;
end;
procedure TcaWindows.SetOnUpdate(const Value: TNotifyEvent);
begin
FOnUpdate := Value;
end;
//---------------------------------------------------------------------------
// TcaProcessLauncher
//---------------------------------------------------------------------------
// Create/Destroy
constructor TcaProcessLauncher.Create;
begin
inherited;
FShowWindow := swShowNormal;
FWaitOptions := [];
end;
destructor TcaProcessLauncher.Destroy;
begin
ReleaseApplication;
inherited;
end;
// Interface methods - IcaProcessLauncher
procedure TcaProcessLauncher.Execute;
begin
if not GetActive then
begin
FThread := TcaProcessThread.CreateThread(Self as IcaProcessLauncher);
if (FWaitOptions = []) then FThread := nil;
end;
end;
procedure TcaProcessLauncher.ReleaseApplication;
begin
if (FThread <> nil) then
try
FThread.DoTerminate;
except
on E: Exception do ;
end;
end;
// Protected event triggers
procedure TcaProcessLauncher.DoFinished(ExitCode: DWORD);
begin
if Assigned(FOnFinished) then FOnFinished(Self, ExitCode);
end;
procedure TcaProcessLauncher.DoIdle;
begin
if Assigned(FOnIdle) then FOnIdle(Self, FProcessID);
end;
// Private methods
function TcaProcessLauncher.IsActive: Boolean;
begin
Result := GetActive;
end;
// Interface properties - IcaProcessLauncher
function TcaProcessLauncher.GetActive: Boolean;
begin
if FWaitOptions = [] then
Result := False
else
Result := FThread <> nil;
end;
function TcaProcessLauncher.GetAppCaption: string;
begin
Result := FAppCaption;
end;
function TcaProcessLauncher.GetAppName: string;
begin
Result := FAppName;
end;
function TcaProcessLauncher.GetCommandLine: string;
begin
Result := FCommandLine;
end;
function TcaProcessLauncher.GetFolder: string;
begin
Result := FFolder;
end;
function TcaProcessLauncher.GetIdle: Boolean;
begin
Result := FIdle;
end;
function TcaProcessLauncher.GetJustOneInstance: Boolean;
begin
Result := FJustOneInstance;
end;
function TcaProcessLauncher.GetProcessID: Cardinal;
begin
Result := FProcessID;
end;
function TcaProcessLauncher.GetShowWindow: TcaShowWindow;
begin
Result := FShowWindow;
end;
function TcaProcessLauncher.GetThread: TcaProcessThread;
begin
Result := FThread;
end;
function TcaProcessLauncher.GetWaitOptions: TcaProcessOptions;
begin
Result := FWaitOptions;
end;
procedure TcaProcessLauncher.SetAppCaption(const Value: string);
begin
FAppCaption := Value;
end;
procedure TcaProcessLauncher.SetAppName(const Value: string);
begin
if not IsActive then FAppName := Trim(Value);
end;
procedure TcaProcessLauncher.SetCommandLine(const Value: string);
begin
if not IsActive then FCommandLine := Trim(Value);
end;
procedure TcaProcessLauncher.SetFolder(const Value: string);
begin
if not IsActive then FFolder := Trim(Value);
end;
procedure TcaProcessLauncher.SetIdle(const Value: Boolean);
begin
if not IsActive then FIdle := Value;
end;
procedure TcaProcessLauncher.SetJustOneInstance(const Value: Boolean);
begin
FJustOneInstance := Value;
end;
procedure TcaProcessLauncher.SetProcessID(const Value: Cardinal);
begin
FProcessID := Value;
end;
procedure TcaProcessLauncher.SetShowWindow(const Value: TcaShowWindow);
begin
if not IsActive then FShowWindow := Value;
end;
procedure TcaProcessLauncher.SetThread(const Value: TcaProcessThread);
begin
FThread := Value;
end;
procedure TcaProcessLauncher.SetWaitOptions(const Value: TcaProcessOptions);
begin
if not IsActive then FWaitOptions := Value;
end;
// Event property methods - IcaProcessLauncher
function TcaProcessLauncher.GetOnFinished: TcaProcessExitEvent;
begin
Result := FOnFinished;
end;
function TcaProcessLauncher.GetOnIdle: TcaProcessIdleEvent;
begin
Result := FOnIdle;
end;
procedure TcaProcessLauncher.SetOnFinished(const Value: TcaProcessExitEvent);
begin
FOnFinished := Value;
end;
procedure TcaProcessLauncher.SetOnIdle(const Value: TcaProcessIdleEvent);
begin
FOnIdle := Value;
end;
//---------------------------------------------------------------------------
// TcaProcessThread
//---------------------------------------------------------------------------
// Create/Destroy
constructor TcaProcessThread.CreateThread(const AProcessLauncher: IcaProcessLauncher);
begin
inherited Create(True);
FProcessLauncher := AProcessLauncher;
FreeOnTerminate := True;
OnTerminate := ResetThread;
Resume;
end;
// Protected methods
procedure TcaProcessThread.Execute;
var
AppWnd: HWND;
begin
inherited;
if FProcessLauncher.JustOneInstance then
begin
AppWnd := FindWindow(nil, PChar(FProcessLauncher.AppCaption));
if AppWnd <> 0 then
ShowWindow(AppWnd, SW_NORMAL)
else
LaunchNewProcess;
end
else
LaunchNewProcess;
end;
// Private methods
procedure TcaProcessThread.LaunchNewProcess;
var
ExitCode: DWORD;
ReturnCode: DWORD;
StartupInfo: TStartupInfo;
begin
ExitCode := 0;
// Set startup info
FillChar(StartupInfo, SizeOf(StartupInfo), 0);
StartupInfo.cb := SizeOf(TStartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := cShowWindowValues[FProcessLauncher.ShowWindow];
if CreateProcess(PChar(FProcessLauncher.CommandLine),
nil,
nil,
nil,
False,
CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
nil,
nil,
StartupInfo,
FProcessInfo) then
begin
// Fire event when launched process is idle, IOW ready to receive messages
ReturnCode := WaitForInputIdle(FProcessInfo.hProcess, INFINITE);
FProcessLauncher.Idle := ReturnCode = 0;
FProcessLauncher.ProcessID := FProcessInfo.dwProcessId;
FProcessLauncher.DoIdle;
// Wait if necessary
ReturnCode := WAIT_TIMEOUT;
while (ReturnCode <> WAIT_OBJECT_0) and (FProcessLauncher.WaitOptions <> []) do
ReturnCode := WaitForSingleObject(FProcessInfo.hProcess, 1000);
GetExitCodeProcess(FProcessInfo.hProcess , ExitCode);
// Notify process end
if (FProcessLauncher.WaitOptions * [poNoteExit]) <> [] then
FProcessLauncher.DoFinished(ExitCode);
end;
// Tidy up
if (FProcessLauncher.WaitOptions = []) then
begin
CloseHandle(FProcessInfo.hProcess);
CloseHandle(FProcessInfo.hThread);
FProcessInfo.hProcess := 0;
end;
ResetThread(nil);
end;
// Event handlers
procedure TcaProcessThread.ResetThread(Sender: TObject);
var
ExitCode: DWORD;
begin
if FProcessInfo.hProcess <> 0 then
begin
GetExitCodeProcess(FProcessInfo.hProcess, ExitCode);
if FProcessInfo.hProcess <> 0 then
begin
if ((FProcessLauncher.WaitOptions * [poForceExit]) <> []) then
TerminateProcess(FProcessInfo.hProcess, ExitCode);
CloseHandle(FProcessInfo.hProcess);
end;
if (FProcessInfo.hThread <> 0) then
CloseHandle(FProcessInfo.hThread);
FProcessInfo.hProcess := 0;
end;
FProcessLauncher.Thread := nil;
end;
end.
|
unit uSetOfExemplo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, typinfo;
type
TDiasSemana = (Domingo, Segunda, Terca, Quarta, Quinta, Sexta, Sabado);
TAlfabeto = (a, b, c, d, e, f);
TConjunto = set of TAlfabeto;
TCLetras = set of char;
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Label1: TLabel;
Button4: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
conjunto1, conjunto2, conjuntoResultado: TCLetras;
resultado:boolean;
begin
conjunto1:=['a','b','c'];
conjunto2:=['a','m','c'];
//--OPERAÇÕES--//
//Operação: + UNIAO retorna um CONJUNTO cujos elementos estao contidos em quanquer dos elementos.
conjuntoResultado:= conjunto1+conjunto2;
//Operação: - DIFERENÇA retorna um CONJUNTO cujos elementos estao contidos no primeiro E NAO no segundo.
conjuntoResultado:= conjunto1-conjunto2; //so retorna B, pq o B nao esta no segundo.
conjuntoResultado:= conjunto2-conjunto1; //so retorna M, pq o sendo conj.2 o primeiro M nao esta no segundo conj.1.
//Operação: * INTERCEÇÃO retorna um CONJUNTO cujos elementos estao obrigatoriamente nos dois elementos.
conjuntoResultado:= conjunto1*conjunto2; //retorna 'a' e 'c'.
//Operação: <= SUBCONJUNTO (esta contido) retorna true/false se o primeiro conjunto é ou não um subconjunto do segundo.
/// isto é se todo e qualquer elemento do primeiro está no segundo conjunto.
resultado:= conjunto1<=conjunto2; //retorna false pq tem que ter TODOS os elemntos do primeiro no segundo.
showmessage(BoolToStr(resultado));
//Operação: >= SUPERCONJUNT0 (contem) retorna true/false se o primeiro conjunto é ou não um superconjunto do segundo.
/// isto é se todo e qualquer elemento do segundo está presente no primeiro conjunto.
resultado:= conjunto1>=conjunto2; //retorna false pq tem que ter TODOS os elemntos do segundo no primeiro.
showmessage(BoolToStr(resultado));
//Operação: = IGUALDADE retorna true/false retorna true se todo o elemento do primeiro esta no segundo e vice e versa.
resultado:= conjunto1=conjunto2;
//Operação: <> DESIGUALDADE retorna true/false retorna true se ao menos um do elemento do primeiro não estiver no segundo e vice e versa.
resultado:= conjunto1=conjunto2;
//Operação: = IN retorna true/false retorna true se o operador esta presente no conjunto2.
resultado:= conjunto1=conjunto2;
//Exemplo IN.
if 'a' in conjunto1 then begin
showmessage('vogais E estao dentro de consoantes');
end else begin
showmessage('NAO esta E dentro de consoantes');
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
const
FIM_DE_SEMANA : Set of TDiasSemana = [Sabado, Domingo];
var
DiasExpediente : Set of TDiasSemana;
begin
if Segunda in FIM_DE_SEMANA then
ShowMessage('Folga!')
else
ShowMessage('Dia de trabalhar');
//ou
DiasExpediente := [Segunda..Sexta];
if Domingo in DiasExpediente then
ShowMessage('É dia de trabalhar')
else
ShowMessage('Folga!');
end;
procedure TForm1.Button3Click(Sender: TObject);
var
I: TAlfabeto;
ConjB: TConjunto;
begin
ConjB := [d, b, f];
//Varre alfabeto.
for I := Low(I) to High(I) do begin
//verifica se I esta no conjuntoB
if I in ConjB then begin
//Trata se I estar no conjunto.
Showmessage('o Valor: '+GetEnumName(TypeInfo(TAlfabeto),integer(I))+ ' - esta no conjunto B!');
end;
end;
end;
procedure TForm1.Button4Click(Sender: TObject);
function StringInSet(const S: String; const StringSet: array of String): Boolean;
var
I: Integer;
begin
Result := False;
for I := Low(StringSet) to High(StringSet) do
begin
if S = StringSet[I] then
begin
Result := True;
Break;
end;
end;
end;
var
consoantes: array of string;
begin
SetLength(consoantes, 50);
consoantes[0] := 'a';
consoantes[1] := 'b';
consoantes[2] := 'c';
showmessage(BoolToStr(StringInSet('b',consoantes)));
end;
end.
|
Unit BaseObject_f_ID;
Interface
Uses
BaseObject_c_FunctionResult,
BaseObject_c_ID;
//
Function BaseObjectIDCreate(Var xxBaseObjectID: TBaseObjectID): TBaseObjectFunctionResult;
Function BaseObjectIDToHexString(xxBaseObjectID: TBaseObjectID): String;
Implementation
Uses
BaseObject_f_File,
SysUtils;
//
Function BaseObjectIDCreate(Var xxBaseObjectID: TBaseObjectID): TBaseObjectFunctionResult;
Var
fiBaseObjectFile: File;
stBaseObjectFileName: String;
xxBaseObjectIDTmp: TBaseObjectID;
Begin
If (boBaseObjectCatalogDefined) Then
Begin
Repeat
Randomize();
xxBaseObjectIDTmp := Random(High(Integer));
Randomize();
xxBaseObjectIDTmp := (xxBaseObjectIDTmp Shl 8) Xor TBaseObjectID(Random(High(Integer)));
Randomize();
xxBaseObjectIDTmp := (xxBaseObjectIDTmp Shl 8) Xor TBaseObjectID(Random(High(Integer)));
Randomize();
xxBaseObjectIDTmp := (xxBaseObjectIDTmp Shl 8) Xor TBaseObjectID(Random(High(Integer)));
stBaseObjectFileName := BaseObjectFileFileNameGet(xxBaseObjectIDTmp);
Until (Not FileExists(stBaseObjectFileName));
AssignFile(fiBaseObjectFile, stBaseObjectFileName);
ReWrite(fiBaseObjectFile, 1);
CloseFile(fiBaseObjectFile);
xxBaseObjectID := xxBaseObjectIDTmp;
result := coBaseObjectFunctionResult_Ok;
End
Else
Begin
result := coBaseObjectFunctionResult_BaseCatalogNotDefined;
End;
End;
//
Function BaseObjectIDToHexString(xxBaseObjectID: TBaseObjectID): String;
Var
byIndex: Byte;
Begin
byIndex := SizeOf(TBaseObjectID) * 2;
SetLength(result, byIndex);
While (byIndex <> 0) Do
Begin
result[byIndex] := coBaseObjectIDHexToChar[xxBaseObjectID And $F];
xxBaseObjectID := xxBaseObjectID Shr 4;
byIndex := byIndex - 1;
result[byIndex] := coBaseObjectIDHexToChar[xxBaseObjectID And $F];
xxBaseObjectID := xxBaseObjectID Shr 4;
byIndex := byIndex - 1;
End;
End;
End.
|
{
@abstract(@code(google.maps.LatLngBounds) class from Google Maps API.)
@author(Xavier Martinez (cadetill) <cadetill@gmail.com>)
@created(October 1, 2015)
@lastmod(October 1, 2015)
The GMLatLngBounds contains the implementation of TGMLatLngBounds class that encapsulate the @code(google.maps.LatLngBounds) class from Google Maps API.
}
unit GMLatLngBounds;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
GMClasses, GMSets, GMLatLng;
type
{ -------------------------------------------------------------------------- }
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.txt)
TGMLatLngBounds = class(TGMPersistentStr, IGMControlChanges)
private
FLang: TGMLang;
FNE: TGMLatLng;
FSW: TGMLatLng;
protected
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.GetOwnerLang.txt)
function GetOwnerLang: TGMLang; override;
// @exclude
function GetAPIUrl: string; override;
// @include(..\docs\GMClasses.IGMControlChanges.PropertyChanged.txt)
procedure PropertyChanged(Prop: TPersistent; PropName: string);
public
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Create_1.txt)
constructor Create(SWLat: Real = 0; SWLng: Real = 0; NELat: Real = 0; NELng: Real = 0; Lang: TGMLang = lnEnglish); reintroduce; overload; virtual;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Create_2.txt)
constructor Create(SW, NE: TGMLatLng; Lang: TGMLang = lnEnglish); reintroduce; overload; virtual;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Create_3.txt)
constructor Create(AOwner: TPersistent; SWLat: Real = 0; SWLng: Real = 0; NELat: Real = 0; NELng: Real = 0); reintroduce; overload; virtual;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Create_4.txt)
constructor Create(AOwner: TPersistent; SW, NE: TGMLatLng); reintroduce; overload; virtual;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Destroy.txt)
destructor Destroy; override;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Assign.txt)
procedure Assign(Source: TPersistent); override;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Extend.txt)
procedure Extend(LatLng: TGMLatLng); (*1 *)
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Union.txt)
procedure Union(Other: TGMLatLngBounds); (*1 *)
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.GetCenter.txt)
procedure GetCenter(LatLng: TGMLatLng); (*1 *)
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.ToSpan.txt)
procedure ToSpan(LatLng: TGMLatLng); (*1 *)
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Contains.txt)
function Contains(LatLng: TGMLatLng): Boolean; (*1 *)
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.IsEqual.txt)
function IsEqual(Other: TGMLatLngBounds): Boolean;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.Intersects.txt)
function Intersects(Other: TGMLatLngBounds): Boolean; (*1 *)
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.IsEmpty.txt)
function IsEmpty: Boolean;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.ToStr.txt)
function ToStr(Precision: Integer = 6): string;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.ToUrlValue.txt)
function ToUrlValue(Precision: Integer = 6): string;
// @include(..\docs\GMClasses.IGMToStr.PropToString.txt)
function PropToString: string; override;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.APIUrl.txt)
property APIUrl;
published
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.SW.txt)
property SW: TGMLatLng read FSW write FSW;
// @include(..\docs\GMLatLngBounds.TGMLatLngBounds.NE.txt)
property NE: TGMLatLng read FNE write FNE;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.SysUtils;
{$ELSE}
SysUtils;
{$ENDIF}
{ TGMLatLngBounds }
constructor TGMLatLngBounds.Create(SW, NE: TGMLatLng; Lang: TGMLang);
begin
inherited Create(nil);
FSW := TGMLatLng.Create(SW.Lat, SW.Lng, False, Lang);
FNE := TGMLatLng.Create(NE.Lat, NE.Lng, False, Lang);
FLang := Lang;
end;
constructor TGMLatLngBounds.Create(SWLat, SWLng, NELat, NELng: Real;
Lang: TGMLang);
begin
inherited Create(nil);
FSW := TGMLatLng.Create(SWLat, SWLng, False, Lang);
FNE := TGMLatLng.Create(NELat, NELng, False, Lang);
FLang := Lang;
end;
procedure TGMLatLngBounds.Assign(Source: TPersistent);
begin
inherited;
if Source is TGMLatLngBounds then
begin
SW.Assign(TGMLatLngBounds(Source).SW);
NE.Assign(TGMLatLngBounds(Source).NE);
end;
end;
function TGMLatLngBounds.Contains(LatLng: TGMLatLng): Boolean;
const
StrParams = '%s,%s,%s,%s,%s,%s';
var
Params: string;
Intf: IGMExecJS;
begin
if not Assigned(GetOwner()) then
raise EGMWithoutOwner.Create(GetOwnerLang); // Owner not assigned.
if not Supports(GetOwner(), IGMExecJS, Intf) then
raise EGMOwnerWithoutJS.Create(GetOwnerLang); // The object (or its owner) does not support JavaScript calls.
if not Assigned(LatLng) then
raise EGMUnassignedObject.Create(['LatLng'], GetOwnerLang); // Unassigned %s object.
Params := Format(StrParams, [LatLng.LatToStr,
LatLng.LngToStr,
FSW.LatToStr,
FSW.LngToStr,
FNE.LatToStr,
FNE.LngToStr
]);
Intf.ExecuteJavaScript('LLB_Contains', Params);
begin
Result := True;
// FSW.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLat), Precision);
// FSW.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLng), Precision);
// FNE.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELat), Precision);
// FNE.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELng), Precision);
end
end;
constructor TGMLatLngBounds.Create(AOwner: TPersistent; SW, NE: TGMLatLng);
begin
inherited Create(AOwner);
FSW := TGMLatLng.Create(Self, SW.Lat, SW.Lng, False);
FNE := TGMLatLng.Create(Self, NE.Lat, NE.Lng, False);
FLang := lnUnknown;
end;
destructor TGMLatLngBounds.Destroy;
begin
if Assigned(FSW) then FreeAndNil(FSW);
if Assigned(FNE) then FreeAndNil(FNE);
inherited;
end;
procedure TGMLatLngBounds.Extend(LatLng: TGMLatLng);
const
StrParams = '%s,%s,%s,%s,%s,%s';
var
Params: string;
Intf: IGMExecJS;
begin
if not Assigned(GetOwner()) then
raise EGMWithoutOwner.Create(GetOwnerLang); // Owner not assigned.
if not Supports(GetOwner(), IGMExecJS, Intf) then
raise EGMOwnerWithoutJS.Create(GetOwnerLang); // The object (or its owner) does not support JavaScript calls.
if not Assigned(LatLng) then
raise EGMUnassignedObject.Create(['LatLng'], GetOwnerLang); // Unassigned %s object.
Params := Format(StrParams, [LatLng.LatToStr,
LatLng.LngToStr,
FSW.LatToStr,
FSW.LngToStr,
FNE.LatToStr,
FNE.LngToStr
]);
Intf.ExecuteJavaScript('LLB_Extend', Params);
begin
// FSW.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLat), Precision);
// FSW.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLng), Precision);
// FNE.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELat), Precision);
// FNE.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELng), Precision);
end
end;
function TGMLatLngBounds.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/javascript/reference#LatLngBounds';
end;
procedure TGMLatLngBounds.GetCenter(LatLng: TGMLatLng);
const
StrParams = '%s,%s,%s,%s';
var
Params: string;
Intf: IGMExecJS;
begin
if not Assigned(GetOwner()) then
raise EGMWithoutOwner.Create(GetOwnerLang); // Owner not assigned.
if not Supports(GetOwner(), IGMExecJS, Intf) then
raise EGMOwnerWithoutJS.Create(GetOwnerLang); // The object (or its owner) does not support JavaScript calls.
Params := Format(StrParams, [FSW.LatToStr,
FSW.LngToStr,
FNE.LatToStr,
FNE.LngToStr
]);
Intf.ExecuteJavaScript('LLB_Center', Params);
begin
// FSW.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLat), Precision);
// FSW.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLng), Precision);
// FNE.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELat), Precision);
// FNE.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELng), Precision);
end
end;
function TGMLatLngBounds.GetOwnerLang: TGMLang;
begin
Result := FLang;
if FLang = lnUnknown then
inherited;
end;
function TGMLatLngBounds.Intersects(Other: TGMLatLngBounds): Boolean;
var
Intf: IGMExecJS;
begin
if not Assigned(GetOwner()) then
raise EGMWithoutOwner.Create(GetOwnerLang); // Owner not assigned.
if not Supports(GetOwner(), IGMExecJS, Intf) then
raise EGMOwnerWithoutJS.Create(GetOwnerLang); // The object (or its owner) does not support JavaScript calls.
if not Assigned(Other) then
raise EGMUnassignedObject.Create(['Other'], GetOwnerLang); // Unassigned %s object.
Intf.ExecuteJavaScript('LLB_Intersects', '');
begin
// FSW.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLat), Precision);
// FSW.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLng), Precision);
// FNE.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELat), Precision);
// FNE.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELng), Precision);
end
end;
function TGMLatLngBounds.IsEmpty: Boolean;
begin
Result := FSW.IsEqual(FNE);
end;
function TGMLatLngBounds.IsEqual(Other: TGMLatLngBounds): Boolean;
begin
Result := FNE.IsEqual(Other.NE) and FSW.IsEqual(Other.SW);
end;
procedure TGMLatLngBounds.PropertyChanged(Prop: TPersistent; PropName: string);
begin
ControlChanges(PropName);
end;
function TGMLatLngBounds.PropToString: string;
const
Str = '%s,%s';
begin
Result := inherited PropToString;
if Result <> '' then Result := Result + ',';
Result := Result +
Format(Str, [FNE.PropToString,
FSW.PropToString
]);
end;
procedure TGMLatLngBounds.ToSpan(LatLng: TGMLatLng);
var
Intf: IGMExecJS;
begin
if not Assigned(GetOwner()) then
raise EGMWithoutOwner.Create(GetOwnerLang); // Owner not assigned.
if not Supports(GetOwner(), IGMExecJS, Intf) then
raise EGMOwnerWithoutJS.Create(GetOwnerLang); // The object (or its owner) does not support JavaScript calls.
Intf.ExecuteJavaScript('LLB_Span', '');
begin
// FSW.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLat), Precision);
// FSW.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLng), Precision);
// FNE.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELat), Precision);
// FNE.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELng), Precision);
end
end;
function TGMLatLngBounds.ToStr(Precision: Integer): string;
const
Str = '(%s, %s)';
begin
Result := Format(Str, [FSW.ToStr(Precision), FNE.ToStr(Precision)]);
end;
function TGMLatLngBounds.ToUrlValue(Precision: Integer): string;
const
Str = '%s,%s';
begin
Result := Format(Str, [FSW.ToUrlValue(Precision), FNE.ToUrlValue(Precision)]);
end;
procedure TGMLatLngBounds.Union(Other: TGMLatLngBounds);
const
StrParams = '%s,%s,%s,%s,%s,%s,%s,%s';
var
Params: string;
Intf: IGMExecJS;
begin
if not Assigned(GetOwner()) then
raise EGMWithoutOwner.Create(GetOwnerLang); // Owner not assigned.
if not Supports(GetOwner(), IGMExecJS, Intf) then
raise EGMOwnerWithoutJS.Create(GetOwnerLang); // The object (or its owner) does not support JavaScript calls.
if not Assigned(Other) then
raise EGMUnassignedObject.Create(['Other'], GetOwnerLang); // Unassigned %s object.
Params := Format(StrParams, [Other.SW.LatToStr,
Other.SW.LngToStr,
Other.NE.LatToStr,
Other.NE.LngToStr,
FSW.LatToStr,
FSW.LngToStr,
FNE.LatToStr,
FNE.LngToStr
]);
Intf.ExecuteJavaScript('LLB_Union', Params);
begin
// FSW.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLat), Precision);
// FSW.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormSWLng), Precision);
// FNE.Lat := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELat), Precision);
// FNE.Lng := ControlPrecision(FWC.GetFloatField(LatLngBoundsForm, LatLngBoundsFormNELng), Precision);
end
end;
constructor TGMLatLngBounds.Create(AOwner: TPersistent; SWLat, SWLng, NELat,
NELng: Real);
begin
inherited Create(AOwner);
FSW := TGMLatLng.Create(Self, SWLat, SWLng, False);
FNE := TGMLatLng.Create(Self, NELat, NELng, False);
FLang := lnUnknown;
end;
end.
|
unit CORBAClientForm;
{
The CorbaConnection Component's Repository ID property is used to
connect to the Server. Please make sure that the Server is either
running or registered with OAD (using OADUtil).
Note that Delphi does not require the complete Repository ID. Both
the short form, 'CORBAServer/DemoCORBA' or the long form,
'IDL:CORBAServer/DemoCORBAFactory:1.0' are valid.
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Grids, DBGrids, DBCtrls, Db, DBClient, CorbaCon, Buttons,
StdCtrls, ActnList;
type
TDemoClientFrm = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
CustomerNavigator: TDBNavigator;
OrdersNavigator: TDBNavigator;
CustomerGrid: TDBGrid;
OrdersGrid: TDBGrid;
Splitter1: TSplitter;
DemoConnection: TCorbaConnection;
CustomerCDS: TClientDataSet;
OrdersCDS: TClientDataSet;
OrdersSource: TDataSource;
CustomerSource: TDataSource;
CustomerCDSCustNo: TFloatField;
CustomerCDSCompany: TStringField;
CustomerCDSAddr1: TStringField;
CustomerCDSAddr2: TStringField;
CustomerCDSCity: TStringField;
CustomerCDSState: TStringField;
CustomerCDSZip: TStringField;
CustomerCDSCountry: TStringField;
CustomerCDSPhone: TStringField;
CustomerCDSFAX: TStringField;
CustomerCDSTaxRate: TFloatField;
CustomerCDSContact: TStringField;
CustomerCDSLastInvoiceDate: TDateTimeField;
CustomerCDSOrderTable: TDataSetField;
CustomerAppUpdBtn: TSpeedButton;
Customer: TLabel;
Orders: TLabel;
ActionList: TActionList;
ApplyUpdates: TAction;
procedure FormCreate(Sender: TObject);
procedure ApplyUpdatesExecute(Sender: TObject);
procedure ApplyUpdatesUpdate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DemoClientFrm: TDemoClientFrm;
implementation
{$R *.DFM}
procedure TDemoClientFrm.FormCreate(Sender: TObject);
begin
try
DemoConnection.Connected := True;
CustomerCDS.Open;
OrdersCDS.Open;
except
on E:Exception do
ShowMessage(E.Message+': Server should be running.');
end;
end;
procedure TDemoClientFrm.ApplyUpdatesExecute(Sender: TObject);
begin
CustomerCDS.ApplyUpdates(-1);
end;
procedure TDemoClientFrm.ApplyUpdatesUpdate(Sender: TObject);
begin
ApplyUpdates.Enabled := CustomerCDS.ChangeCount > 0;
end;
end.
|
unit Unitres;
interface
uses
SysUtils, Classes,Graphics ;
type
TBase = class
private
x: integer;
y: Integer;
bitmap: TBitmap;
{ Private declarations }
public
constructor Create(x0,y0 : Integer ; bitmap0 : TBitmap);//создание изображения с этими значениями
procedure setX(x0:Integer);//значение х
procedure setY(y0:Integer);//значение у
procedure setBitmap(bitmap0:TBitmap);//значение изображения
function getX: Integer;//взять х
function getY: Integer;//взять у
function getBitmap: TBitmap;//взять изображение
{ Public declarations }
end;
TApple = class(TBase)//объект яблоко
end;
THead = class(TBase)//объект голова
end;
TTail = class(TBase)//объект хвост
end;
implementation
{$R *.dfm}
{ TBase }
//создание начального изображения
constructor TBase.Create(x0, y0: Integer; bitmap0: TBitmap);
begin
x:=x0;
y:=y0;
bitmap:=bitmap0;
end;
//результат при взятии картинки
function TBase.getBitmap: TBitmap;
begin
Result:=bitmap;
end;
//результат при взятии х
function TBase.getX: Integer;
begin
Result:=x;
end;
//результат при взятии у
function TBase.getY: Integer;
begin
Result:=y;
end;
//присвоение значений для картики
procedure TBase.setBitmap(bitmap0: TBitmap);
begin
bitmap:=bitmap0;
end;
//присвоение значений для х
procedure TBase.setX(x0: Integer);
begin
x:=x0;
end;
//присвоение значений для у
procedure TBase.setY(y0: Integer);
begin
y:=y0;
end;
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
uPiThread;
type
TfmMain = class(TForm)
cbCalculate: TCheckBox;
Label1: TLabel;
Label2: TLabel;
laBuiltIn: TLabel;
laValue: TLabel;
laIterNum: TLabel;
procedure FormCreate(Sender: TObject);
procedure cbCalculateClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PiThread : TPiThread;
procedure UpdatePi;
end;
var
fmMain: TfmMain;
implementation
{$R *.dfm}
procedure TfmMain.UpdatePi;
begin
if IsIconic( Application.Handle ) then Exit;
LaValue.Caption := FloatToStrF( GlobalPi, ffFixed, 18, 18 );
laIterNum.Caption := IntToStr( GlobalCounter ) + ' iterations';
end;
procedure TfmMain.FormCreate(Sender: TObject);
begin
laBuiltIn.Caption := FloatToStrF( Pi, ffFixed, 18, 18 );
end;
procedure TfmMain.cbCalculateClick(Sender: TObject);
begin
if cbCalculate.Checked then
begin
PiThread := TPiThread.Create( True );
PiThread.FreeOnTerminate := True;
PiThread.Priority := tpLower;
PiThread.Resume;
end
else
begin
if Assigned( PiThread ) then PiThread.Terminate;
end;
end;
end.
|
//******************************************************************************
//*** SCRIPT VCL FUNCTIONS ***
//*** ***
//*** (c) Massimo Magnano 2006 ***
//*** ***
//*** ***
//******************************************************************************
// File : Script_System.pas (rev. 1.1)
//
// Description : Access from scripts to all classes derived form TObject.
// Useful function for property of kind "set"
//
//******************************************************************************
// Known Limitations :
// Because VCL is not compiled whith the directives METHODINFO and TYPEINFO activated
// in the bases classes there is two different behaviour
// 1) in Classes derived from TComponent all the methods (public and published) can be called
// 2) in Classes derived from TObject only published methods can be called,
// so if you need to call public methods of your class this must be derived from TObjectDispatch.
// The alternative is to declare a method with the same parameters and result in the
// ScriptObject derived class (registered with "RegisterClass") that simply call the
// method in InstanceObj.
// This alternative must be used when VCL Objects must be accessed from script side.
//
//
// TO-DO :
// Eventi degli oggetti (una classe per ogni evento + lista con il nome della funzione lua)
// Gestione delle property di Tipo Record Vedi cos'è PFieldTable
// + Metodo x avere le property publiche??? invece di usare SetElement
// * Gestione di TComponent.<componentname> come se fosse una property tkClass
// ++ Migliorare la gestione delle property che sono degli array (se possibile???)
// * Migliorare la registrazione delle classi, andare sempre alla ricerca dell' ancestor
// COMMENTARE IL CODICE MENTRO ME LO RICORDO
unit Script_System;
{$J+}
interface
uses Classes, Controls, TypInfo, SysUtils, ScriptableObject, Variants,
ObjAuto, ObjComAuto, MGList;
type
{$METHODINFO ON}
//{$TYPEINFO ON} use this if you want only published methods
TScriptObject = class(TObjectDispatch)
protected
rInstanceObj :TObject;
Owned :Boolean;
class function GetPublicPropertyAccessClass :TClass; virtual;
public
constructor Create(AInstanceObj :TObject; AOwned :Boolean);
destructor Destroy; override;
function CallMethod(MethodName :String; const Args : array of variant;
NeedResult: Boolean): Variant;
function GetMethodInfos(MethodName :String;
var MethodInfo: PMethodInfoHeader; var ReturnInfo: PReturnInfo;
var ParamInfos: TParamInfos):Boolean;
//WARNING : if you want parameters when creating an Object you must write
// a function with the following form that create the object.
// You must change every parameter or result of type TClass, TObject
// with type integer (ObjComAuto do not support this types?????)
//
function ScriptCreate(ObjClass :Integer) :Integer; overload; virtual;
function GetDefaultArrayProp :String; virtual;
function GetArrayPropType(Name :String; index :Variant) :PTypeInfo; virtual;
function GetArrayProp(Name :String; index :Variant) :Variant; virtual;
procedure SetArrayProp(Name :String; index :Variant; Value :Variant); virtual;
//If the ElementType is tkSet or tkEnumeration (except the boolean) you may return the Value
// in GetElement as a String
function GetElementType(Name :String) :PTypeInfo; virtual;
function GetElement(Name :String) :Variant; virtual;
procedure SetElement(Name :String; Value :Variant); virtual;
function GetPublicPropInfo(Name :String) :PPropInfo;
function GetPublicPropValue(Name :String; AsString :Boolean) :Variant;
procedure SetPublicPropValue(Name :String; Value :Variant);
property InstanceObj :TObject read rInstanceObj;
end;
//{$TYPEINFO OFF}
{$METHODINFO OFF}
TScriptObjectClass = class of TScriptObject;
const
TypeInfoArray : TTypeInfo = (Kind : tkArray; Name :'');
TypeInfoClass : TTypeInfo = (Kind : tkClass; Name :'');
type
//This List associate an Object Class with a ScriptObject Class
TScriptClassesListData = record
ObjClass :TClass;
LuaClass :TScriptObjectClass;
end;
PScriptClassesListData =^TScriptClassesListData;
TScriptClassesList = class(TMGList)
protected
InternalData :TScriptClassesListData;
function allocData :Pointer; override;
procedure deallocData(pData :Pointer); override;
function internalFind(ObjClassName :String) :PScriptClassesListData; overload;
function internalFind(ObjClass :TClass) :PScriptClassesListData; overload;
public
function Add(ObjClass :TClass; LuaClass :TScriptObjectClass=nil) :PScriptClassesListData; overload;
function FindAncestor(ObjClass :TClass) :TScriptObjectClass;
function Find(ObjClassName :String) :PScriptClassesListData; overload;
function Find(ObjClass :TClass) :PScriptClassesListData; overload;
end;
//This List associate an Existing Object Instance with a Name in the Lua script
TScriptExistingObjListData = record
Obj :TObject;
Name :String;
end;
PScriptExistingObjListData =^TScriptExistingObjListData;
TScriptExistingObjList = class(TMGList)
protected
function allocData :Pointer; override;
procedure deallocData(pData :Pointer); override;
public
function Add(Obj :TObject; Name :String) :PScriptExistingObjListData; overload;
function Find(Name :String) :PScriptExistingObjListData; overload;
end;
Var
ScriptClassesList :TScriptClassesList =nil;
ScriptExistingObjList :TScriptExistingObjList =nil;
procedure RegisterClass(ObjClass :TClass; LuaClass :TScriptObjectClass=nil);
procedure RegisterObject(Obj :TObject; Name :String; LuaClass :TScriptObjectClass=nil);
procedure MySetPropValue(Instance: TObject; PropInfo: PPropInfo; const Value: Variant);
function SetToString(TypeInfo: PTypeInfo; Value: Integer; Brackets: Boolean): string;
function SetNextWord(var P: PChar): string;
function StringToSet(EnumInfo: PTypeInfo; const Value: string): Integer;
implementation
procedure MySetPropValue(Instance: TObject; PropInfo: PPropInfo;
const Value: Variant);
begin
//SetPropValue raise an exception when i try to set a class property...
// even if it's value is a simple Integer (infact GetPropValue return it as Integer)
if PropInfo^.PropType^.Kind = tkClass
then SetOrdProp(Instance, PropInfo, Value)
else SetPropValue(Instance, PropInfo, Value);
end;
constructor TScriptObject.Create(AInstanceObj :TObject; AOwned :Boolean);
begin
(* if AInstanceObj=nil
then AInstanceObj :=Self;
*) inherited Create(AInstanceObj, AOwned);
rInstanceObj :=AInstanceObj;
Owned :=AOwned;
end;
destructor TScriptObject.Destroy;
begin
if Owned then rInstanceObj.Free;
inherited Destroy;
end;
function TScriptObject.ScriptCreate(ObjClass :Integer) :Integer;
begin
Result :=Integer(TClass(ObjClass).Create);
end;
//stessa cosa x CallMethodLexicalOrder
function TScriptObject.CallMethod(MethodName :String; const Args : array of variant;
NeedResult: Boolean): Variant;
Var
scripter :TScriptableObject;
pRes :PVariant;
begin
Result :=NULL;
scripter :=nil;
try
//Try with My Methods
scripter :=TScriptableObject.Create(Self, false);
pRes :=scripter.CallMethod(scripter.NameToDispID(MethodName), Args, NeedResult);
if (pRes<>nil)
then Result :=pRes^;
scripter.Free;
except
scripter.Free;
Result :=NULL;
try
//Try with InstanceObj Methods
scripter :=TScriptableObject.Create(rInstanceObj, false);
pRes :=scripter.CallMethod(scripter.NameToDispID(MethodName), Args, NeedResult);
if (pRes<>nil)
then Result :=pRes^;
scripter.Free;
except
scripter.Free;
Result :=NULL;
end;
end;
end;
function TScriptObject.GetPublicPropInfo(Name :String) :PPropInfo;
Var
_parent :TScriptObjectClass;
PubProClass :TClass;
begin
_parent :=TScriptObjectClass(Self.ClassType);
repeat
PubProClass :=_parent.GetPublicPropertyAccessClass;
if (PubProClass<>nil)
then Result :=TypInfo.GetPropInfo(PubProClass, Name, tkProperties)
else Result :=nil;
if (Result=nil)
then _parent := TScriptObjectClass(_parent.ClassParent);
//IF the Property is not public in this Class, try in ancestors.
// This method avoid to redeclare property as published in every TXXXAccess class,
// for example :
// TLuaControl <- TLuaWinControl
// TControl <- TWinControl
// Without this method, in TLuaWinControl, you might declare every public property
// of TWinControl including every public property of TControl.
// With this method, in TLuaWinControl, you can declare only public property of TWinControl
until (_parent=TObjectDispatch) or (Result<>nil);
end;
(*
begin
Result :=TypInfo.GetPropInfo(GetPublicPropertyAccessClass, Name, tkProperties);
end;
*)
function TScriptObject.GetPublicPropValue(Name :String; AsString :Boolean) :Variant;
Var
PropInfo :PPropInfo;
begin
PropInfo :=GetPublicPropInfo(Name);
if (PropInfo<>nil)
then Result :=GetPropValue(rInstanceObj, PropInfo, AsString);
end;
procedure TScriptObject.SetPublicPropValue(Name :String; Value :Variant);
Var
PropInfo :PPropInfo;
begin
PropInfo :=GetPublicPropInfo(Name);
if (PropInfo<>nil)
then MySetPropValue(rInstanceObj, PropInfo, Value);
end;
function TScriptObject.GetMethodInfos(MethodName: String;
var MethodInfo: PMethodInfoHeader; var ReturnInfo: PReturnInfo;
var ParamInfos: TParamInfos): Boolean;
Var
scripter :TScriptableObject;
pRes :PVariant;
begin
Result :=false;
scripter :=nil;
try
//Try with My Methods
scripter :=TScriptableObject.Create(Self, false);
Result :=scripter.GetMethodInfos(MethodName, MethodInfo, ReturnInfo, ParamInfos);
if not(Result)
then begin
scripter.Free;
//Try with InstanceObj Methods
scripter :=TScriptableObject.Create(rInstanceObj, false);
Result :=scripter.GetMethodInfos(MethodName, MethodInfo, ReturnInfo, ParamInfos);
scripter.Free;
end;
except
scripter.Free;
Result :=false;
end;
end;
function TScriptObject.GetElementType(Name: String): PTypeInfo;
begin
Result :=nil;
end;
procedure TScriptObject.SetArrayProp(Name: String; index, Value: Variant);
begin
end;
class function TScriptObject.GetPublicPropertyAccessClass: TClass;
begin
Result :=nil;
end;
function TScriptObject.GetDefaultArrayProp: String;
begin
Result :='';
end;
function TScriptObject.GetElement(Name: String): Variant;
begin
Result :=NULL;
end;
function TScriptObject.GetArrayPropType(Name: String;
index: Variant): PTypeInfo;
begin
Result :=nil;
end;
procedure TScriptObject.SetElement(Name: String; Value: Variant);
begin
end;
function TScriptObject.GetArrayProp(Name: String; index: Variant): Variant;
begin
Result :=NULL;
end;
//==============================================================================
//
function TScriptClassesList.allocData :Pointer;
begin
GetMem(Result, sizeof(TScriptClassesListData));
fillchar(Result^, sizeof(TScriptClassesListData), 0);
end;
procedure TScriptClassesList.deallocData(pData :Pointer);
begin
FreeMem(pData, sizeof(TScriptClassesListData));
end;
function TScriptClassesList.Add(ObjClass :TClass; LuaClass :TScriptObjectClass=nil) :PScriptClassesListData;
begin
Result :=internalFind(ObjClass.ClassName);
if (Result=nil)
then Result :=Self.Add;
if (Result<>nil)
then begin
Result^.ObjClass :=ObjClass;
(*if (LuaClass=nil)
then Result^.LuaClass :=TScriptObject
else*) Result^.LuaClass :=LuaClass;
end;
end;
function TScriptClassesList.FindAncestor(ObjClass :TClass) :TScriptObjectClass;
Var
_parent :TClass;
Data :PScriptClassesListData;
begin
_parent :=ObjClass.ClassParent;
Data :=nil;
while (_parent<>nil) and (Data=nil) do
begin
Data :=internalFind(_parent);
if (Data<>nil)
then Result :=Data^.LuaClass
else _parent := _parent.ClassParent;
end;
if (Data=nil)
then Result :=TScriptObject;
end;
function TScriptClassesList.internalFind(ObjClassName :String) :PScriptClassesListData;
function CompByClassName(Tag :Integer; ptData1, ptData2 :Pointer) :Boolean;
begin
Result := String(PChar(ptData1)) = Uppercase(PScriptClassesListData(ptData2)^.ObjClass.Classname);
end;
begin
Result :=Self.ExtFind(PChar(Uppercase(ObjClassName)), 0, @CompByClassName);
end;
function TScriptClassesList.internalFind(ObjClass :TClass) :PScriptClassesListData;
function CompByClass(Tag :Integer; ptData1, ptData2 :Pointer) :Boolean;
begin
Result := TClass(ptData1) = PScriptClassesListData(ptData2)^.ObjClass;
end;
begin
Result :=Self.ExtFind(ObjClass, 0, @CompByClass);
end;
function TScriptClassesList.Find(ObjClass :TClass) :PScriptClassesListData;
begin
Result :=Self.internalFind(ObjClass);
if (Result<>nil)
then begin
if (Result^.LuaClass=nil) //The Class is registered, but have no LuaClass,
//try to find a registered ancestor class
then Result^.LuaClass :=FindAncestor(Result^.ObjClass);
end
else begin
//The Class is not registered, try to find a registered ancestor class
InternalData.ObjClass :=ObjClass;
InternalData.LuaClass :=FindAncestor(ObjClass);
if (InternalData.LuaClass<>nil)
then Result :=@InternalData
else Result :=nil;
end;
end;
function TScriptClassesList.Find(ObjClassName :String) :PScriptClassesListData;
begin
Result :=Self.internalFind(ObjClassName);
if (Result<>nil)
then begin
if (Result^.LuaClass=nil) //The Class is registered, but have no LuaClass,
//try to find a registered ancestor class
then Result^.LuaClass :=FindAncestor(Result^.ObjClass);
end
else begin
try
Result :=Self.internalFind(FindClass(ObjClassName));
except
Result :=nil;
end;
if (Result<>nil)
then begin
if (Result^.LuaClass=nil) //The Class is registered in VCL, but have no LuaClass,
//try to find a registered ancestor class
then Result^.LuaClass :=FindAncestor(Result^.ObjClass);
end
end;
end;
//==============================================================================
//
function TScriptExistingObjList.allocData :Pointer;
begin
GetMem(Result, sizeof(TScriptExistingObjListData));
fillchar(Result^, sizeof(TScriptExistingObjListData), 0);
end;
procedure TScriptExistingObjList.deallocData(pData :Pointer);
begin
PScriptExistingObjListData(pData)^.Name :='';
FreeMem(pData, sizeof(TScriptExistingObjListData));
end;
function TScriptExistingObjList.Add(Obj :TObject; Name :String) :PScriptExistingObjListData;
begin
Result :=Find(Name);
if (Result=nil)
then Result :=Self.Add;
if (Result<>nil)
then begin
Result^.Obj :=Obj;
Result^.Name :=Uppercase(Name);
end;
end;
function TScriptExistingObjList.Find(Name :String) :PScriptExistingObjListData;
function CompByClass(Tag :Integer; ptData1, ptData2 :Pointer) :Boolean;
begin
Result := String(PChar(ptData1)) = PScriptExistingObjListData(ptData2)^.Name;
end;
begin
Result :=Self.ExtFind(PChar(Uppercase(Name)), 0, @CompByClass);
end;
function SetToString(TypeInfo: PTypeInfo; Value: Integer; Brackets: Boolean): string;
var
S: TIntegerSet;
I: Integer;
EnumInfo :PTypeInfo;
begin
Result := '';
Integer(S) := Value;
EnumInfo := GetTypeData(TypeInfo)^.CompType^;
for I := 0 to SizeOf(Integer) * 8 - 1 do
if I in S then
begin
if Result <> '' then
Result := Result + ',';
Result := Result + GetEnumName(EnumInfo, I);
end;
if Brackets then
Result := '[' + Result + ']';
end;
// grab the next enum name
function SetNextWord(var P: PChar): string;
var
i: Integer;
begin
i := 0;
// scan til whitespace
while not (P[i] in [',', ' ', #0,']']) do
Inc(i);
SetString(Result, P, i);
// skip whitespace
while P[i] in [',', ' ',']'] do
Inc(i);
Inc(P, i);
end;
function StringToSet(EnumInfo: PTypeInfo; const Value: string): Integer;
var
P: PChar;
EnumName: string;
EnumValue: Longint;
begin
Result := 0;
if Value = '' then Exit;
P := PChar(Value);
// skip leading bracket and whitespace
while P^ in ['[',' '] do
Inc(P);
EnumName := SetNextWord(P);
while EnumName <> '' do
begin
EnumValue := GetEnumValue(EnumInfo, EnumName);
if EnumValue < 0 then
raise EPropertyConvertError.CreateFmt('Invalid Property Element %s', [EnumName]);
Include(TIntegerSet(Result), EnumValue);
EnumName := SetNextWord(P);
end;
end;
procedure RegisterClass(ObjClass :TClass; LuaClass :TScriptObjectClass=nil);
begin
ScriptClassesList.Add(ObjClass, LuaClass);
end;
procedure RegisterObject(Obj :TObject; Name :String; LuaClass :TScriptObjectClass=nil);
begin
ScriptExistingObjList.Add(Obj, Name);
ScriptClassesList.Add(Obj.ClassType, LuaClass);
end;
initialization
ScriptClassesList :=TScriptClassesList.Create;
ScriptExistingObjList :=TScriptExistingObjList.Create;
finalization
ScriptClassesList.Free;
ScriptExistingObjList.Free;
end.
|
unit udemutil;
interface
Uses Classes,Graphics,Dialogs;
Function EditColor(AOwner:TComponent; AColor:TColor):TColor;
implementation
Function EditColor(AOwner:TComponent; AColor:TColor):TColor;
Begin
With TColorDialog.Create(AOwner) do
try
Color:=AColor;
if Execute then AColor:=Color;
finally
Free;
end;
result:=AColor;
end;
end.
|
unit Crypto.RSA;
interface
uses
System.SysUtils,
RSA.main;
function RSAGenPrivateKey: TBytes;
function RSAGetPublicKey(const PrivateKey: TBytes): TBytes;
function RSAEncrypt(const PrivateKey,Data: TBytes): TBytes;
function RSADecrypt(const PublicKey,Data: TBytes): TBytes;
implementation
const
KeySize = 512;
function RSAGenPrivateKey: TBytes;
var Pri: TPrivateKey;
begin
GenPrivKey(KeySize,Pri);
PrivKeyToBytes_lt(Pri,Result);
FinalizePrivKey(Pri);
end;
function RSAGetPublicKey(const PrivateKey: TBytes): TBytes;
var
Pri: TPrivateKey;
Pub: TPublicKey;
begin
if Length(PrivateKey)=0 then Exit(nil);
BytesToPrivKey_lt(PrivateKey,Pri);
GenPubKey(Pri,Pub);
PubKeyToBytes(Pub,Result);
FinalizePrivKey(Pri);
FinalizePubKey(Pub);
end;
function RSAEncrypt(const PrivateKey,Data: TBytes): TBytes;
var Pri: TPrivateKey;
begin
if Length(PrivateKey)=0 then Exit(nil);
BytesToPrivKey_lt(PrivateKey,Pri);
RSAPrKEncrypt(Pri,Data,Result);
FinalizePrivKey(Pri);
end;
function RSADecrypt(const PublicKey,Data: TBytes): TBytes;
var Pub: TPublicKey;
begin
if Length(PublicKey)=0 then Exit(nil);
BytesToPubKey(PublicKey,Pub);
RSAPbKDecrypt(Pub,Data,Result);
FinalizePubKey(Pub);
end;
end.
|
unit BodyTypesGroupUnit2;
interface
uses
QueryGroupUnit2, System.Classes, NotifyEvents, BodyKindsQuery,
BodyTypesQuery2, ProducersQuery, BodyTypesSimpleQuery,
BodyTypesExcelDataModule, SearchBodyVariationQuery, BodyKindsColorQuery;
type
TBodyTypesGroup2 = class(TQueryGroup2)
private
FqBodyKinds: TQueryBodyKinds;
FqBodyKindsColor: TQryBodyKindsColor;
FqBodyTypes2: TQueryBodyTypes2;
FqProducers: TQueryProducers;
FqSearchBodyVariation: TQrySearchBodyVariation;
FQueryBodyTypesSimple: TQueryBodyTypesSimple;
procedure DoAfterDelete(Sender: TObject);
function GetqBodyKinds: TQueryBodyKinds;
function GetqBodyKindsColor: TQryBodyKindsColor;
function GetqBodyTypes2: TQueryBodyTypes2;
function GetqProducers: TQueryProducers;
function GetqSearchBodyVariation: TQrySearchBodyVariation;
function GetQueryBodyTypesSimple: TQueryBodyTypesSimple;
protected
property qSearchBodyVariation: TQrySearchBodyVariation
read GetqSearchBodyVariation;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure LoadDataFromExcelTable(ABodyTypesExcelTable: TBodyTypesExcelTable;
AIDProducer: Integer);
procedure Re_Open(AShowDuplicate: Boolean);
procedure Rollback; override;
function Search(ABodyVariation: String): Boolean;
property qBodyKinds: TQueryBodyKinds read GetqBodyKinds;
property qBodyKindsColor: TQryBodyKindsColor read GetqBodyKindsColor;
property qBodyTypes2: TQueryBodyTypes2 read GetqBodyTypes2;
property qProducers: TQueryProducers read GetqProducers;
property QueryBodyTypesSimple: TQueryBodyTypesSimple
read GetQueryBodyTypesSimple;
end;
implementation
uses
Data.DB, System.Generics.Collections, System.SysUtils, FireDAC.Comp.DataSet;
constructor TBodyTypesGroup2.Create(AOwner: TComponent);
begin
inherited;
QList.Add(qBodyKinds);
QList.Add(qBodyTypes2);
Assert(ComponentCount > 0);
// Для каскадного удаления
TNotifyEventWrap.Create(qBodyKinds.W.AfterDelete, DoAfterDelete, EventList);
end;
destructor TBodyTypesGroup2.Destroy;
begin
Assert(ComponentCount > 0);;
inherited;
end;
procedure TBodyTypesGroup2.DoAfterDelete(Sender: TObject);
begin
Assert(qBodyKinds.W.DeletedPKValue > 0);
// На сервере типы корпусов уже каскадно удалились
// Каскадно удаляем типы корпусов с клиента
qBodyTypes2.W.CascadeDelete(qBodyKinds.W.DeletedPKValue,
qBodyTypes2.W.IDBodyKind.FieldName, True);
end;
function TBodyTypesGroup2.GetqBodyKinds: TQueryBodyKinds;
begin
if FqBodyKinds = nil then
FqBodyKinds := TQueryBodyKinds.Create(Self);
Result := FqBodyKinds;
end;
function TBodyTypesGroup2.GetqBodyKindsColor: TQryBodyKindsColor;
begin
if FqBodyKindsColor = nil then
FqBodyKindsColor := TQryBodyKindsColor.Create(Self);
Result := FqBodyKindsColor;
end;
function TBodyTypesGroup2.GetqBodyTypes2: TQueryBodyTypes2;
begin
if FqBodyTypes2 = nil then
FqBodyTypes2 := TQueryBodyTypes2.Create(Self);
Result := FqBodyTypes2;
end;
function TBodyTypesGroup2.GetqProducers: TQueryProducers;
begin
if FqProducers = nil then
FqProducers := TQueryProducers.Create(Self);
Result := FqProducers;
end;
function TBodyTypesGroup2.GetqSearchBodyVariation: TQrySearchBodyVariation;
begin
if FqSearchBodyVariation = nil then
FqSearchBodyVariation := TQrySearchBodyVariation.Create(Self);
Result := FqSearchBodyVariation;
end;
function TBodyTypesGroup2.GetQueryBodyTypesSimple: TQueryBodyTypesSimple;
begin
if FQueryBodyTypesSimple = nil then
begin
FQueryBodyTypesSimple := TQueryBodyTypesSimple.Create(Self);
end;
Result := FQueryBodyTypesSimple;
end;
procedure TBodyTypesGroup2.LoadDataFromExcelTable(ABodyTypesExcelTable
: TBodyTypesExcelTable; AIDProducer: Integer);
var
AField: TField;
AProducerID: Integer;
F: TField;
begin
ABodyTypesExcelTable.DisableControls;
try
QueryBodyTypesSimple.W.RefreshQuery;
ABodyTypesExcelTable.First;
ABodyTypesExcelTable.CallOnProcessEvent;
QueryBodyTypesSimple.ClearUpdateRecCount;
while not ABodyTypesExcelTable.Eof do
begin
if AIDProducer > 0 then
AProducerID := AIDProducer
else
AProducerID := (ABodyTypesExcelTable as TBodyTypesExcelTable2)
.IDProducer.AsInteger;
// ищем или добавляем корень - вид корпуса
qBodyKinds.W.LocateOrAppend(ABodyTypesExcelTable.BodyKind.AsString);
QueryBodyTypesSimple.W.TryAppend;
QueryBodyTypesSimple.W.IDProducer.F.AsInteger := AProducerID;
QueryBodyTypesSimple.W.IDBodyKind.F.Value := qBodyKinds.W.PK.Value;
QueryBodyTypesSimple.W.Variations.F.AsString :=
ABodyTypesExcelTable.Variation.AsString;
QueryBodyTypesSimple.W.JEDEC.F.AsString :=
ABodyTypesExcelTable.JEDEC.AsString;
QueryBodyTypesSimple.W.Options.F.AsString :=
ABodyTypesExcelTable.Options.AsString;
for AField in ABodyTypesExcelTable.Fields do
begin
F := QueryBodyTypesSimple.FDQuery.FindField(AField.FieldName);
if F <> nil then
F.Value := AField.Value;
end;
QueryBodyTypesSimple.W.TryPost;
QueryBodyTypesSimple.IncUpdateRecCount;
ABodyTypesExcelTable.Next;
ABodyTypesExcelTable.CallOnProcessEvent;
end;
// Финальный коммит
QueryBodyTypesSimple.FDQuery.Connection.Commit;
// Обновляем данные в сгруппированном запросе
qBodyTypes2.W.RefreshQuery;
finally
ABodyTypesExcelTable.EnableControls;
end;
end;
procedure TBodyTypesGroup2.Re_Open(AShowDuplicate: Boolean);
begin
qBodyTypes2.W.TryPost;
qBodyKinds.W.TryPost;
SaveBookmark;
qBodyTypes2.ShowDuplicate := AShowDuplicate;
qBodyKinds.ShowDuplicate := AShowDuplicate;
RestoreBookmark;
end;
procedure TBodyTypesGroup2.Rollback;
begin
inherited;
qBodyTypes2.RefreshLinkedData;
end;
function TBodyTypesGroup2.Search(ABodyVariation: String): Boolean;
begin
Assert(not ABodyVariation.IsEmpty);
Result := False;
// Если нашли такой вариант корпуса
if qSearchBodyVariation.SearchVariation(ABodyVariation) > 0 then
begin
// Запрещаем всем компонентам отображать данные
// Иначе cxGrid ведёт себя неадекватно
qBodyTypes2.W.DataSource.Enabled := False;
qBodyKinds.W.DataSource.Enabled := False;
try
qBodyTypes2.W.IDS.Locate(qSearchBodyVariation.W.IDS.F.AsString, [], True);
qBodyKinds.W.ID.Locate(qBodyTypes2.W.IDBodyKind.F.AsInteger, [], True);
finally
// Разрешаем всем компонентам отображать данные
qBodyKinds.W.DataSource.Enabled := True;
qBodyTypes2.W.DataSource.Enabled := True;
end;
Result := True;
end;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_DetourLocalBoundary;
interface
uses RN_DetourNavMeshQuery, RN_DetourNavMeshHelper;
type
TdtLocalBoundary = class
private
const
MAX_LOCAL_SEGS = 8;
MAX_LOCAL_POLYS = 16;
type
PSegment = ^TSegment;
TSegment = record
s: array [0..5] of Single; ///< Segment start/end
d: Single; ///< Distance for pruning.
end;
var
m_center: array [0..2] of Single;
m_segs: array [0..MAX_LOCAL_SEGS-1] of TSegment;
m_nsegs: Integer;
m_polys: array [0..MAX_LOCAL_POLYS-1] of TdtPolyRef;
m_npolys: Integer;
procedure addSegment(const dist: Single; const s: PSingle);
public
constructor Create;
destructor Destroy; override;
procedure reset();
procedure update(ref: TdtPolyRef; const pos: PSingle; const collisionQueryRange: Single;
navquery: TdtNavMeshQuery; const filter: TdtQueryFilter);
function isValid(navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
function getCenter(): PSingle; { return m_center; }
function getSegmentCount(): Integer; { return m_nsegs; }
function getSegment(i: Integer): PSingle; { return m_segs[i].s; }
end;
implementation
uses Math, RN_DetourCommon, RN_DetourNavMesh;
constructor TdtLocalBoundary.Create;
begin
inherited;
dtVset(@m_center[0], MaxSingle,MaxSingle,MaxSingle);
end;
destructor TdtLocalBoundary.Destroy;
begin
inherited;
end;
procedure TdtLocalBoundary.reset();
begin
dtVset(@m_center[0], MaxSingle,MaxSingle,MaxSingle);
m_npolys := 0;
m_nsegs := 0;
end;
procedure TdtLocalBoundary.addSegment(const dist: Single; const s: PSingle);
var seg: PSegment; i,tgt,n: Integer;
begin
// Insert neighbour based on the distance.
seg := nil;
if (m_nsegs = 0) then
begin
// First, trivial accept.
seg := @m_segs[0];
end
else if (dist >= m_segs[m_nsegs-1].d) then
begin
// Further than the last segment, skip.
if (m_nsegs >= MAX_LOCAL_SEGS) then
Exit;
// Last, trivial accept.
seg := @m_segs[m_nsegs];
end
else
begin
// Insert inbetween.
for i := 0 to m_nsegs - 1 do
if (dist <= m_segs[i].d) then
break;
tgt := i+1;
n := dtMin(m_nsegs-i, MAX_LOCAL_SEGS-tgt);
Assert(tgt+n <= MAX_LOCAL_SEGS);
if (n > 0) then
Move(m_segs[i], m_segs[tgt], sizeof(TSegment)*n);
seg := @m_segs[i];
end;
seg.d := dist;
Move(s^, seg.s[0], sizeof(Single)*6);
if (m_nsegs < MAX_LOCAL_SEGS) then
Inc(m_nsegs);
end;
procedure TdtLocalBoundary.update(ref: TdtPolyRef; const pos: PSingle; const collisionQueryRange: Single;
navquery: TdtNavMeshQuery; const filter: TdtQueryFilter);
const MAX_SEGS_PER_POLY = DT_VERTS_PER_POLYGON*3;
var segs: array [0..MAX_SEGS_PER_POLY*6-1] of Single; nsegs,j,k: Integer; s: PSingle; tseg, distSqr: Single;
begin
if (ref = 0) then
begin
dtVset(@m_center[0], MaxSingle,MaxSingle,MaxSingle);
m_nsegs := 0;
m_npolys := 0;
Exit;
end;
dtVcopy(@m_center[0], pos);
// First query non-overlapping polygons.
navquery.findLocalNeighbourhood(ref, pos, collisionQueryRange,
filter, @m_polys[0], nil, @m_npolys, MAX_LOCAL_POLYS);
// Secondly, store all polygon edges.
m_nsegs := 0;
nsegs := 0;
for j := 0 to m_npolys - 1 do
begin
navquery.getPolyWallSegments(m_polys[j], filter, @segs[0], nil, @nsegs, MAX_SEGS_PER_POLY);
for k := 0 to nsegs - 1 do
begin
s := @segs[k*6];
// Skip too distant segments.
distSqr := dtDistancePtSegSqr2D(pos, s, s+3, @tseg);
if (distSqr > Sqr(collisionQueryRange)) then
continue;
addSegment(distSqr, s);
end;
end;
end;
function TdtLocalBoundary.isValid(navquery: TdtNavMeshQuery; const filter: TdtQueryFilter): Boolean;
var i: Integer;
begin
if (m_npolys = 0) then
Exit(false);
// Check that all polygons still pass query filter.
for i := 0 to m_npolys - 1 do
begin
if (not navquery.isValidPolyRef(m_polys[i], filter)) then
Exit(false);
end;
Result := true;
end;
function TdtLocalBoundary.getCenter(): PSingle; begin Result := @m_center[0]; end;
function TdtLocalBoundary.getSegmentCount(): Integer; begin Result := m_nsegs; end;
function TdtLocalBoundary.getSegment(i: Integer): PSingle; begin Result := @m_segs[i].s[0]; end;
end.
|
unit PassForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,
Vcl.WinXCtrls;
type
Tfrm_Password = class(TForm)
RelativePanel1: TRelativePanel;
edit_Password: TEdit;
bbt_OK: TBitBtn;
bbt_Cancel: TBitBtn;
Label1: TLabel;
cb_ShowHidePassword: TCheckBox;
procedure cb_ShowHidePasswordClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
fHidePass: Boolean;
fPW : string;
public
{ Public declarations }
function Execute: boolean;
property HidePass: boolean read fHidePass write fHidePass;
property PW: string read fPW write fPW;
end;
var
frm_Password: Tfrm_Password;
implementation
{$R *.dfm}
procedure Tfrm_Password.cb_ShowHidePasswordClick(Sender: TObject);
begin
if cb_ShowHidePassword.checked then
edit_Password.PasswordChar := '*'
else
edit_Password.PasswordChar := #0;
end;
function Tfrm_Password.Execute: boolean;
begin
Result := (ShowModal = mrOK);
// PW := edit_Password.Text;
end;
procedure Tfrm_Password.FormShow(Sender: TObject);
begin
cb_ShowHidePassword.Checked := HidePass;
cb_ShowHidePasswordClick(Sender);
end;
end.
|
{
InternetExpress sample component.
TReadFileClientDataSet is a custom TClientDataSet that
does not write the client data set file to disk when the
data set is closed. The inetxcenter sample application
uses a client data set file for read only data.
}
unit ReadFileClientDataSet;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBClient;
type
TReadFileClientDataSet = class(TClientDataSet)
private
{ Private declarations }
protected
{ Protected declarations }
procedure CloseCursor; override;
public
{ Public declarations }
published
{ Published declarations }
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('InternetExpress', [TReadFileClientDataSet]);
end;
{ TReadFileClientDataSet }
procedure TReadFileClientDataSet.CloseCursor;
var
SaveFileName: string;
begin
// Prevent client data set file from being saved to disk.
SaveFileName := FileName;
FileName := '';
try
inherited CloseCursor;
finally
FileName := SaveFileName;
end;
end;
end.
|
unit Ex7Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, MTUtils, ComCtrls;
type
TMyThread = class(TThread)
private
FResult: Int64;
FCurrValue: Integer;
procedure SetProgressParams;
procedure SetProgressCurrValue;
public
MaxValue: Integer;
procedure Execute; override;
end;
TForm1 = class(TForm)
btnRunInParallelThread: TButton;
ProgressBar1: TProgressBar;
Label1: TLabel;
labResult: TLabel;
edMaxValue: TEdit;
procedure btnRunInParallelThreadClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
FMyThread: TMyThread;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnRunInParallelThreadClick(Sender: TObject);
begin
// Уничтожаем запущенный поток
if Assigned(FMyThread) then
FreeAndNil(FMyThread);
// Создаём поток в спящем состоянии
FMyThread := TMyThread.Create(True);
// Запоминаем длину ряда в поле MaxValue
FMyThread.MaxValue := StrToIntDef(edMaxValue.Text, 0);
// Пробуждаем поток для выполнения вычислений
FMyThread.Resume;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FMyThread.Free;
end;
{ TMyThread }
procedure TMyThread.Execute;
var
Res: Int64;
CurrVal: Integer;
begin
// Выставляем параметры компонента ProgressBar1
Synchronize(SetProgressParams);
// Выполняем некоторые вычисления
Res := 0;
CurrVal := 0;
while CurrVal < MaxValue do
begin
if Terminated then Break;
Inc(CurrVal);
Res := Res + CurrVal;
if CurrVal mod 10000 = 0 then
begin // Обновление прогресса выполняется только 1 раз из 10000
FCurrValue := CurrVal;
FResult := Res;
Synchronize(SetProgressCurrValue);
end;
end;
// Обновляем прогресс в конце вычислений
FCurrValue := CurrVal;
FResult := Res;
Synchronize(SetProgressCurrValue);
end;
procedure TMyThread.SetProgressCurrValue;
begin
Form1.ProgressBar1.Position := FCurrValue;
Form1.labResult.Caption := IntToStr(FResult);
end;
procedure TMyThread.SetProgressParams;
begin
Form1.ProgressBar1.Max := MaxValue;
Form1.ProgressBar1.Position := 0;
Form1.labResult.Caption := '0';
end;
end.
|
unit ltrapitypes;
interface
uses SysUtils;
const
COMMENT_LENGTH =256;
ADC_CALIBRATION_NUMBER =256;
DAC_CALIBRATION_NUMBER =256;
type
{$A4}
SERNUMtext=array[0..15]of AnsiChar;
TLTR_CRATE_INFO=record
CrateType:byte;
CrateInterface:byte;
end;
TLTR_DESCRIPTION_MODULE=record
CompanyName:array[0..16-1]of AnsiChar; //
DeviceName:array[0..16-1]of AnsiChar; // название изделия
SerialNumber:array[0..16-1]of AnsiChar; // серийный номер изделия
Revision:byte; // ревизия изделия
Comment:array[0..256-1]of AnsiChar; //
end;
// описание процессора и програмного обеспечения
TLTR_DESCRIPTION_CPU=record
Active:byte; // флаг достоверности остальных полей структуры
Name:array[0..15]of AnsiChar; // название
ClockRate:double; //
FirmwareVersion:LongWord; //
Comment:array[0..COMMENT_LENGTH-1]of AnsiChar; //
end;
// описание плис
TLTR_DESCRIPTION_FPGA=record
Active:byte; // флаг достоверности остальных полей структуры
Name:array[0..15]of AnsiChar; // название
ClockRate:double; //
FirmwareVersion:LongWord; //
Comment:array[0..COMMENT_LENGTH-1]of AnsiChar; //
end;
// описание ацп
TLTR_DESCRIPTION_ADC=record
Active:byte; // флаг достоверности остальных полей структуры
Name:array[0..15]of AnsiChar; // название
Calibration:array[0..ADC_CALIBRATION_NUMBER-1]of double;// корректировочные коэффициенты
Comment:array[0..COMMENT_LENGTH-1]of AnsiChar; //
end;
TLTR_DESCRIPTION_DAC=record
Active:byte; // флаг достоверности остальных полей структуры
Name:array[0..15]of AnsiChar; // название
Calibration:array[0..ADC_CALIBRATION_NUMBER-1]of double;// корректировочные коэффициенты
Comment:array[0..COMMENT_LENGTH-1]of AnsiChar; //
end;
// описание h-мезанинов
TLTR_DESCRIPTION_MEZZANINE=record
Active:byte; // флаг достоверности остальных полей структуры
Name:array[0..15]of AnsiChar;
SerialNumber:array[0..15]of AnsiChar; // серийный номер изделия
Revision:Byte; // ревизия изделия
Calibration:array[0..3]of double; // корректировочные коэффициенты
Comment:array[0..COMMENT_LENGTH-1]of AnsiChar; // комментарий
end;
// описание цифрового вв
TLTR_DESCRIPTION_DIGITAL_IO=record
Active:byte; // флаг достоверности остальных полей структуры
Name:array[0..15]of AnsiChar; // название ???????
InChannels:word; // число каналов
OutChannels:word; // число каналов
Comment:array[0..COMMENT_LENGTH-1]of AnsiChar; // комментарий
end;
// описание интерфейсных модулей
TLTR_DESCRIPTION_INTERFACE=record
Active:BYTE; // флаг достоверности остальных полей структуры
Name:array[0..15]of AnsiChar; // название
Comment:array[0..COMMENT_LENGTH-1]of AnsiChar; //
end;
// элемент списка IP-крейтов
TLTR_CRATE_IP_ENTRY=record
ip_addr:LongWord; // IP адрес (host-endian)
flags:LongWord; // флаги режимов (CRATE_IP_FLAG_...)
serial_number:array[0..15]of AnsiChar; // серийный номер (если крейт подключен)
is_dynamic:byte; // 0 = задан пользователем, 1 = найден автоматически
status:byte; // состояние (CRATE_IP_STATUS_...)
end;
{$IFNDEF LTRAPI_DISABLE_COMPAT_DEFS}
TIPCRATE_ENTRY = TLTR_CRATE_IP_ENTRY;
TCRATE_INFO = TLTR_CRATE_INFO;
TDESCRIPTION_MODULE = TLTR_DESCRIPTION_MODULE;
TDESCRIPTION_CPU = TLTR_DESCRIPTION_CPU;
TDESCRIPTION_FPGA = TLTR_DESCRIPTION_FPGA;
TDESCRIPTION_ADC = TLTR_DESCRIPTION_ADC;
TDESCRIPTION_DAC = TLTR_DESCRIPTION_DAC;
TDESCRIPTION_MEZZANINE = TLTR_DESCRIPTION_MEZZANINE;
TDESCRIPTION_DIGITAL_IO = TLTR_DESCRIPTION_DIGITAL_IO;
TDESCRIPTION_INTERFACE = TLTR_DESCRIPTION_INTERFACE;
{$ENDIF}
{$A+}
implementation
end.
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Bitcoin Core developers
// Copyright (c) 2020-2020 Skybuck Flying
// Copyright (c) 2020-2020 The Delphicoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Bitcoin file: src/coins.h
// Bitcoin file: src/coins.cpp
// Bitcoin commit hash: f656165e9c0d09e654efabd56e6581638e35c26c
unit Unit_TCoinsView;
interface
/** Abstract view on the open txout dataset. */
class CCoinsView
{
public:
/** Retrieve the Coin (unspent transaction output) for a given outpoint.
* Returns true only when an unspent coin was found, which is returned in coin.
* When false is returned, coin's value is unspecified.
*/
virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const;
//! Just check whether a given outpoint is unspent.
virtual bool HaveCoin(const COutPoint &outpoint) const;
//! Retrieve the block hash whose state this CCoinsView currently represents
virtual uint256 GetBestBlock() const;
//! Retrieve the range of blocks that may have been only partially written.
//! If the database is in a consistent state, the result is the empty vector.
//! Otherwise, a two-element vector is returned consisting of the new and
//! the old block hash, in that order.
virtual std::vector<uint256> GetHeadBlocks() const;
//! Do a bulk modification (multiple Coin changes + BestBlock change).
//! The passed mapCoins can be modified.
virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock);
//! Get a cursor to iterate over the whole state
virtual CCoinsViewCursor *Cursor() const;
//! As we use CCoinsViews polymorphically, have a virtual destructor
virtual ~CCoinsView() {}
//! Estimate database size (0 if not implemented)
virtual size_t EstimateSize() const { return 0; }
};
implementation
bool CCoinsView::GetCoin(const COutPoint &outpoint, Coin &coin) const { return false; }
uint256 CCoinsView::GetBestBlock() const { return uint256(); }
std::vector<uint256> CCoinsView::GetHeadBlocks() const { return std::vector<uint256>(); }
bool CCoinsView::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return false; }
bool CCoinsView::HaveCoin(const COutPoint &outpoint) const
{
Coin coin;
return GetCoin(outpoint, coin);
}
end.
|
(* Morse: MM, 2020-04-09 *)
(* ------ *)
(* A Program do encode and decode morse messages *)
(* ========================================================================= *)
PROGRAM Morse;
USES
MorseTreeUnit;
CONST
WORD_SEPARATOR = ';';
SENTENCE_SEPATATOR = '$';
PROCEDURE CheckIOError(message: STRING);
VAR error: INTEGER;
BEGIN (* CheckIOError *)
error := IOResult;
IF (error <> 0) THEN BEGIN
WriteLn('ERROR: ', message, '(Code: ', error, ')');
HALT;
END; (* IF *)
END; (* CheckIOError *)
PROCEDURE Replace(VAR s: STRING; toReplace, replaceBy: CHAR);
VAR i: INTEGER;
BEGIN (* Replace *)
FOR i := 1 TO Length(s) DO BEGIN
IF (s[i] = toReplace) THEN
s[i] := replaceBy;
END; (* FOR *)
END; (* Replace *)
PROCEDURE ToMorseCode(t: Tree; VAR line: STRING);
VAR s: STRING;
i: INTEGER;
n: NodePtr;
BEGIN (* ToMorseCode *)
line := Upcase(line);
s := '';
FOR i := 1 TO Length(line) DO BEGIN
IF (line[i] = ' ') THEN BEGIN
s := Copy(s, 1, Length(s) - 1) + WORD_SEPARATOR;
END ELSE IF (line[i] = '.') THEN BEGIN
s := Copy(s, 1, Length(s) - 1) + SENTENCE_SEPATATOR;
END ELSE BEGIN
n := FindNode(t, line[i]);
s := s + n^.fullCode + ' ';
END; (* IF *)
END; (* FOR *)
line := s;
END; (* ToMorseCode *)
PROCEDURE FromMorseCode(t: Tree; VAR line: STRING);
VAR s, code: STRING;
i, j: INTEGER;
n: NodePtr;
BEGIN (* FromMorseCode *)
s := '';
i := 1;
REPEAT
j := 0;
WHILE ((line[i + j] <> ' ') AND (line[i + j] <> WORD_SEPARATOR) AND (line[i + j] <> SENTENCE_SEPATATOR)) DO BEGIN
Inc(j);
END; (* WHILE *)
code := Copy(line, i, j);
n := FindNodeByCode(t, code, 1);
s := s + n^.letter;
IF (line[i + j] <> ' ') THEN
s := s + line[i + j];
i := i + j + 1;
UNTIL (i >= Length(line)); (* REPEAT *)
Replace(s, WORD_SEPARATOR, ' ');
Replace(s, SENTENCE_SEPATATOR, '.');
line := s;
END; (* FromMorseCode *)
VAR stdOutput: TEXT;
morseFile: TEXT;
inputFileName, outputFileName: STRING;
line, code: STRING;
t: Tree;
BEGIN (* Morse *)
t := NewNode('$', 'Placeholder');
stdOutput := output;
Assign(morseFile, 'morsecode.txt');
{$I-}
Reset(morseFile);
CheckIOError('Cannot open morsecode file. Does it exist?');
{$I+}
REPEAT
ReadLn(morseFile, line);
code := Copy(line, 3, Length(line) - 2);
Insert(t, NewNode(line[1], code));
UNTIL (Eof(morseFile)); (* REPEAT *)
IF (ParamCount <> 3) THEN BEGIN
WriteLn('Error: Unknown number of Parameters.');
WriteLn('Usage: Morse.exe (-m | -t) <input.txt> <output.txt>');
HALT;
END; (* IF *)
inputFileName := ParamStr(2);
Assign(input, inputFileName);
{$I-}
Reset(input);
CheckIOError('Cannot open input file');
{$I+}
outputFileName := ParamStr(3);
Assign(output, outputFileName);
{$I-}
Rewrite(output);
CheckIOError('Cannot write to output file.');
{$I+}
IF (ParamStr(1) = '-m') THEN BEGIN
REPEAT
ReadLn(input, line);
ToMorseCode(t, line);
WriteLn(output, line);
UNTIL (Eof(input)); (* REPEAT *)
END ELSE IF (ParamStr(1) = '-t') THEN BEGIN
REPEAT
ReadLn(input, line);
FromMorseCode(t, line);
WriteLn(output, line);
UNTIL (Eof(input)); (* REPEAT *)
END ELSE BEGIN
WriteLn('Error: Unknown Parameter ', ParamStr(1));
WriteLn('Usage: Morse.exe (-m | -t) <input.txt> <output.txt>');
HALT;
END; (* IF *)
Close(input);
Close(output);
Close(morseFile);
DisposeTree(t);
output := stdOutput;
WriteLn('Done!');
END. (* Morse *) |
unit BarrasGantt;
interface
Uses
Windows, Forms, SysUtils, Classes, ZDataset, DB, ExtCtrls, Graphics, Grids,
DBGrids, StdCtrls, Menus, Tabs, DateUtils, Frm_Propiedades, Messages, global,
Controls ;
Type
{ Estructura para información de las barras }
TBarra = Class
Tipo: String;
NumeroActividad: String;
Duracion: Real;
FechaInicio: Real;
FechaTermino: Real;
Color: Integer;
X1,Y1,X2,Y2: Integer; // Coordenadas de posicionamiento en pantalla de la barra
InScreen: Boolean;
Private
Constructor Create;
Destructor Destroy;
End;
TDatos = Class
GeneralKey: String;
ItemKey: String;
NumeroActividad: String;
TipoActividad: String;
Wbs: String;
WbsAnterior: String;
Inicio: String;
Termino: String;
ColBarra: String;
Constructor Create;
End;
{ Estructura de elementos contenedores de barras }
TGraficaGantt = Class
Private
Dibujar: Boolean;
TimerCursor: TTimer;
FirstInScreen: String;
LastBarMouse: String;
TipoBarra: Integer;
IsDown: Boolean;
ListaBarras: TStringList;
Segmentos: TStringList;
QueryGen: TZQuery;
QueryData: TZQuery;
IntNumItems: Integer;
Grafico: TPaintBox;
InicioGraph, TerminoGraph: Real; // Fecha de inicio y término de área de gráfica
Imagen: TImage;
Forma: TForm;
TabSet: TTabSet;
Scroll: TScrollBar;
Grid: TStringGrid;
PintaCal: Boolean;
Porcentaje: Real;
AlturaBarra: Integer;
MargenBarra: Integer;
pAncho: Integer;
pTab: Word;
DatosBefore: TBarra;
//ncWbs: String; // Nombre del campo del wbs
//ncWbsAnterior: String; // Nombre del campo del Wbs anterior
ncDuracion: String; // Nombre del campo de duración de actividad
ncColor: String; // Nombre del campo del color de la barra
Dif: Byte; // Porcentaje de degradado de las barras (0 = Color solido y 255 = Desde color original hasta blanco)
pHoriz: Boolean; // Dibujar líneas de división horizontales
pVert: Boolean; // Dibujar líneas de división verticales
cFondo: Integer; // Color del fondo de la gráfica
cActividad: Integer; // Color general de las barras de actividad
cPaquete: Integer; // Color general de las barras de paquete
Especificos: Boolean; // ¿Se deben usar los colores especificos de cada barra?
MargenFecha: Integer; // Espacio entre limite de espacio y fecha de calendario
FormatoCal: Byte; // Número de formato de calendario (Variable 'Formato')
IniSem: Byte; // Día de inicio de semana para sus respectivos cortes (1 = Lunes... 7 = Domingo)
PosX, PosY: Integer; // Última posición del mouse
NewPosX1, NewPosY1: Integer; // Posición original de inicio de la barra seleccionada por el mouse
NewPosX2, NewPosY2: Integer; // Posición original de termino de la barra seleccionada por el mouse
FirstCol: Integer; // Primera columna dibujada en el grid para referenciar evento único de generación de barras
totalregistros : integer; // contador de registros desplegados en el grid
Procedure LoadGenData(Query: TObject; Llave: String);
Public
Constructor Create;
Destructor Destroy;
Procedure OnTimer(Sender: TObject);
Procedure SetQuery(Query: TZQuery; Llave: String); overload;
Procedure SetQuery(Query: TZReadOnlyQuery; Llave: String); overload;
Procedure LoadData(Query: TZQuery; TipoActividad, NumeroActividad, Llave, LLaveAnterior, Inicio, Termino, Duracion, ColorBarra: String); overload;
Procedure LoadData(Query: TZReadOnlyQuery; TipoActividad, NumeroActividad, Llave, LlaveAnterior, Inicio, Termino, Duracion, ColorBarra: String); overload;
Procedure UploadBar(Query: TObject; TipoActividad, NumeroActividad, Llave, LlaveAnterior, Inicio, Termino, Duracion, ColorBarra: String);
Procedure SetGraphic(GanttForm: TForm; GanttGrid: TObject; GanttCanvas: TPaintBox; GanttTabSet: TTabSet; GanttScroll: TScrollBar);
Procedure DrawCalendar;
Procedure DrawBar(Rect: TRect; pWbs: String);
Procedure SetScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
Procedure SetTab(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
Procedure BarraChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
Procedure DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
Procedure BeforeChangeData(DataSet: TDataSet);
Procedure AfterChangeData(DataSet: TDataSet);
Procedure MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
Procedure Mouseleave(Sender: TObject);
Procedure MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Procedure MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Procedure ActualizaPaquetes(DataSet: TDataSet);
Property NumItems: Integer Read IntNumItems;
End;
implementation
Uses
Dialogs, Utilerias;
(*
Nota de Rangel:
Estos valores constantes son los valores que deben de ir en la ventana de opciones de la gráfica la cual
se va a activar con la cejilla identificada por '...' en la parte baja de la gráfica.
Se pueden modificar a criterio para que se pueda apreciar su funcionamiento, solo resta analizar en que
parte de la base de datos deberá ser grabada ya que no sé si estos valores deben ser registrados en las
tablas a nivel de contrato o bien a nivel contrato-usuario; es decir que cada usuario pudiera tener una
diferente visualización de las gráficas pudiendo modificarlas de manera independiente o bien que cuando
un usuario modifique la visualización de la gráfica todos los usuarios la vean de la misma manera.
*)
Const
gDefault = 1; // Iniciar la visualización de esta gráfica en modo 3 (Mensual)
ValMarFecha = 2; // Ancho de margenes para fechas entre su bloque de espacios
valEspec = False; // Valor de color especifico de barras en verdadero
Var
Formato: Array[1..14] Of String;
Datos: TDatos;
Constructor TDatos.Create;
begin
GeneralKey := '';
ItemKey := '';
end;
Constructor TBarra.Create;
begin
// Inicializar los valores de la barra para que sirvan de verificador cuando se trate de ejecutar el
// evento afterchangedata sin haber pasado por el evento beforechangedata...
Tipo := '';
Duracion := 0;
FechaInicio := 0;
FechaTermino := 0;
Color := 0;
X1 := 0;
Y1 := 0;
X2 := 0;
Y2 := 0;
InScreen := False;
end;
Destructor TBarra.Destroy;
begin
// Solo por procedimiento, ya que el objeto estará disponible durante toda la vida de esta ventana
Tipo := '';
Duracion := 0;
FechaInicio := 0;
FechaTermino := 0;
Color := 0;
end;
Procedure TGraficaGantt.OnTimer(Sender: TObject);
Var
Cuantos: Integer;
Begin
Cuantos := -1;
if PosX < 0 then
Begin
Cuantos := Trunc(PosX / 10);
if Cuantos = 0 then Cuantos := -1; // Mínimo debe avanzar de uno en uno
End;
if PosX > Grafico.Width then
Begin
Cuantos := Trunc((PosX - Grafico.Width) / 10);
if Cuantos = 0 then Cuantos := 1; // Mínimo debe avanzar de uno en uno
End;
// Si se ha desbordado el mouse se debe modificar la gráfica
if Cuantos <> -1 then
Begin
Scroll.Position := Scroll.Position + Cuantos;
SetScroll(Scroll,scLineUp,Cuantos);
End;
End;
Procedure TGraficaGantt.SetScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
Begin
case ScrollCode of
scLineUp:
Begin
if ScrollPos <= InicioGraph then
TScrollBar(Sender).Min := TScrollBar(Sender).Min - TScrollBar(Sender).SmallChange;
if ScrollPos >= TerminoGraph then
TScrollBar(Sender).Max := TScrollBar(Sender).Max - TScrollBar(Sender).SmallChange;
End;
scLineDown:
Begin
if ScrollPos <= InicioGraph then
TScrollBar(Sender).Min := TScrollBar(Sender).Min + TScrollBar(Sender).SmallChange;
if ScrollPos >= TerminoGraph then
TScrollBar(Sender).Max := TScrollBar(Sender).Max + TScrollBar(Sender).SmallChange;
End;
scPageUp:
Begin
if ScrollPos <= InicioGraph then
TScrollBar(Sender).Min := TScrollBar(Sender).Min - TScrollBar(Sender).LargeChange;
if ScrollPos >= TerminoGraph then
TScrollBar(Sender).Max := TScrollBar(Sender).Max - TScrollBar(Sender).LargeChange;
End;
scPageDown:
Begin
if ScrollPos <= InicioGraph then
TScrollBar(Sender).Min := TScrollBar(Sender).Min + TScrollBar(Sender).LargeChange;
if ScrollPos >= TerminoGraph then
TScrollBar(Sender).Max := TScrollBar(Sender).Max + TScrollBar(Sender).LargeChange;
End;
scPosition: ;
scTrack: ;
scTop: ;
scBottom: ;
scEndScroll: ;
end;
PintaCal := True;
Grid.Repaint;
End;
Procedure TGraficaGantt.LoadGenData(Query: TObject; Llave: String);
Var
Procede: Boolean;
Begin
QueryGen := TZQuery(Query);
Datos.GeneralKey := Llave;
Procede := True;
QueryGen.DisableControls; // Deshabilitar los controls ligados a este query
// Verificar que el query esté abierto
if Not QueryGen.Active then
Raise Exception.CreateFmt('El query especificado está cerrado o ya no está disponible : ''%s''', [TZQuery(Query).Name]);
// Recorrer todo el query indicado para cargar todos sus elementos al vector de control
Try
QueryGen.First; // Verficiar si está disponible el query
Except
Procede := False;
End;
if Procede then
Begin
While Not QueryGen.Eof Do
Begin
ListaBarras.Add(QueryGen.FieldValues[Llave]);
QueryGen.Next;
End;
IntNumItems := ListaBarras.Count; // Mover numero de items a variable de control
End;
QueryGen.First;
QueryGen.EnableControls; // Habilitar nuevamente los controles ligados a este query
End;
Constructor TGraficaGantt.Create;
Var
T: Byte;
Begin
TimerCursor := TTimer.Create(Nil);
TimerCursor.Enabled := False;
TimerCursor.Interval := 1;
TimerCursor.OnTimer := Ontimer;
IsDown := False; // El mouse no se encuentra pulsado
PosX := -1;
PosX := -1;
ListaBarras := TStringList.Create; // Inicializar objeto para almacenamiento de partidas
Segmentos := TStringList.Create;
QueryData := TZQuery.Create(Nil);
Imagen := TImage.Create(Nil);
Scroll := TScrollBar.Create(Nil);
DatosBefore := TBarra.Create;
IntNumItems := 0;
Porcentaje := 1;
//ncWbs := '';
ncDuracion := '';
ncColor := '';
Dibujar := True;
FirstCol := -1; // No se ha pintado ningúna celda en el grid
Imagen.Left := 0;
Imagen.Top := 0;
Imagen.Width := Screen.Width;
Imagen.Height := Screen.Height;
Datos := TDatos.Create;
Formato[1] := 'dddd dd mmmm yyyy';
Formato[2] := 'dddd dd mmmm yy';
Formato[3] := 'dddd dd/mm/yyyy';
Formato[4] := 'dddd dd/mm/yy';
Formato[5] := 'dddd dd/mm';
Formato[6] := 'dddd dd';
Formato[7] := 'dd/mmmm/yyyy';
Formato[8] := 'dd/mmmm/yy';
Formato[9] := 'dd/mmmm';
Formato[10] := 'dd/mm/yyyy';
Formato[11] := 'dd/mm/yy';
Formato[12] := 'dd mmmm';
Formato[13] := 'dd/mm';
Formato[14] := 'dd';
// Estos datos se debe guardar en alguna parte para que no se tengan que estar solicitando simpre que se inicie la ventana
Dif := 126; // Degradado para barras
pHoriz := True; // Dibujar líneas de división horizontales
pVert := False; // Dibujar líneas de división verticales
cFondo := clMoneyGreen; // Color del fondo de la gráfica
cActividad := clBlue; // Color de barras de actividad en azul
cPaquete := 0; // Color de barras de paquetes en negro
FormatoCal := 3; // Número de formato de calendario (Variable 'Formato')
IniSem := 7; // Día de inicio de semana para sus respectivos cortes (1 = Lunes... 7 = Domingo)
Especificos := ValEspec; // Utilizar colores especificos por default
MargenFecha := ValMarFecha;
End;
Destructor TGraficaGantt.Destroy;
Begin
FreeAndNil(TimerCursor);
IntNumItems := -1; // Numero de items sin valor
FreeAndNil(ListaBarras); // Liberar memoria de lista de barras
FreeAndNil(Segmentos);
QueryData.Destroy;
Imagen.Destroy; // Desocupar la memoria
Scroll.Destroy;
DatosBefore.Destroy; // Eliminar la información existente de cualquier before pendiente
End;
Procedure TGraficaGantt.SetQuery(Query: TZQuery; Llave: String);
Begin
// Barrer todos los elementos indicados por el query y cargarlos en memoria
LoadGenData(Query, Llave);
End;
Procedure TGraficaGantt.SetQuery(Query: TZReadonlyQuery; Llave: String);
Begin
// Barrer todos los elementos indicados por el query y cargarlos en memoria
LoadGenData(Query, Llave);
End;
Procedure TGraficaGantt.Mouseleave(Sender: TObject);
begin
Screen.Cursor := crDefault;
end;
Procedure TGraficaGantt.MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
Var
Indice: Integer;
Continua: Boolean;
ParFormato: String;
Begin
// Guardar la última posición por la cual se va desplazando el cursor del mouse
if (TipoBarra = 1) Or (TipoBarra = 2) then
NewPosX1 := NewPosX1 + (X - PosX);
if (TipoBarra = 2) Or (TipoBarra = 3) then
NewPosX2 := NewPosX2 + (X - PosX);
PosX := X;
PosY := Y;
// Verifica si se encuentra seleccionada una barra de actividad con el mouse y el botón del mouse se encuentra pulsado
if (LastBarMouse <> '') And (IsDown) then
Begin
// Eliminar la barra original y substituirla por la nueva
Grafico.Canvas.Brush.Color := cFondo;
Grafico.Canvas.Pen.Color := cFondo;
Grafico.Canvas.Rectangle(0,NewPosY1,Grafico.Width,NewPosY2 + 1);
Grafico.Canvas.Brush.Color := clRed;
Grafico.Canvas.Pen.Color := clRed;
// Verificar de donde se tomó la barra al hacer click
case TipoBarra of
1: Grafico.Canvas.Rectangle(NewPosX1,NewPosY1,TBarra(Segmentos.Objects[Segmentos.IndexOf(LastBarMouse)]).X2, NewPosY2); // Cambiar inicio
2: Grafico.Canvas.Rectangle(NewPosX1,NewPosY1,NewPosX2,NewPosY2); // Cambiar terminación
3: Grafico.Canvas.Rectangle(TBarra(Segmentos.Objects[Segmentos.IndexOf(LastBarMouse)]).X1,NewPosY1,NewPosX2,NewPosY2); // Mover la barra completa
end;
End
Else
Begin
Grafico.Hint := '';
Grafico.ShowHint := False;
LastBarMouse := '';
// Verificar en que parte se está pasando el mouse
TipoBarra := -1;
Indice := Segmentos.IndexOf(FirstInScreen + ':1');
if Indice >= 0 then
Begin
Continua := True;
while (TBarra(Segmentos.Objects[Indice]).InScreen) And (Continua) And (Indice + 1 < Segmentos.Count) do
Begin
Continua := (Not ((X >= (TBarra(Segmentos.Objects[Indice]).X1)) And (X <= (TBarra(Segmentos.Objects[Indice]).X2)) And (Y >= (TBarra(Segmentos.Objects[Indice]).Y1)) And (Y <= (TBarra(Segmentos.Objects[Indice]).Y2))));
if Continua then
Inc(Indice);
End;
if (Continua) and (Segmentos.Count = Indice + 1) then
Continua := (Not ((X >= (TBarra(Segmentos.Objects[Indice]).X1)) And (X <= (TBarra(Segmentos.Objects[Indice]).X2)) And (Y >= (TBarra(Segmentos.Objects[Indice]).Y1)) And (Y <= (TBarra(Segmentos.Objects[Indice]).Y2))));
if Not Continua then
Begin
{ Area de ajustes
Mostrar la fecha y hora final a las 24 horas del día anterior para que coinsida con lo mostado en el grid
debido a que inteligent no maneja horario }
ParFormato := FormatDateTime('dd/mm/yyyy',TBarra(Segmentos.Objects[Indice]).FechaTermino - 1);
ParFormato := ParFormato + ' 24:00';
Grafico.Hint := TBarra(Segmentos.Objects[Indice]).Tipo + ': ' + TBarra(Segmentos.Objects[Indice]).NumeroActividad + #13 + 'Del ' + FormatDateTime('dd/mm/yyyy hh:mm',TBarra(Segmentos.Objects[Indice]).FechaInicio) + #13 + 'Al ' + ParFormato;
Grafico.ShowHint := True;
if TBarra(Segmentos.Objects[Indice]).Tipo = 'Paquete' then TipoBarra := 0 else TipoBarra := 1; // Tipo de mouse
if TipoBarra = 1 then
Begin
// Verificar la posición exacta del mouse
TipoBarra := 0;
if X < TBarra(Segmentos.Objects[Indice]).X1 + 4 then TipoBarra := 1;
if X > TBarra(Segmentos.Objects[Indice]).X2 - 4 then TipoBarra := 3;
if TipoBarra = 0 then TipoBarra := 2;
LastBarMouse := Segmentos[Indice];
End;
End;
End;
{ Modificar el puntero del mouse de acuerdo a los objetos en la gráfica }
case TipoBarra of
1: Screen.Cursor := crSizeWe;
2: Screen.Cursor := crSize;
3: Screen.Cursor := crSizeWe;
Else Screen.Cursor := crDefault;
end;
End;
End;
Procedure TGraficaGantt.MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Var
nLlave, Posicion, WbsSel: String;
Respaldo: TBitMap;
Begin
// Verificar si el apuntador del mouse se encuentra sobre una barra
if LastBarMouse <> '' then
Begin
IsDown := True;
// Mover las coordenadas de la barra a las variables de reposicionamiento
NewPosX1 := TBarra(Segmentos.Objects[Segmentos.IndexOf(LastBarMouse)]).X1;
NewPosY1 := TBarra(Segmentos.Objects[Segmentos.IndexOf(LastBarMouse)]).Y1;
NewPosX2 := TBarra(Segmentos.Objects[Segmentos.IndexOf(LastBarMouse)]).X2;
NewPosY2 := TBarra(Segmentos.Objects[Segmentos.IndexOf(LastBarMouse)]).Y2;
WbsSel := Segmentos[Segmentos.IndexOf(LastBarMouse)];
WbsSel := Copy(WbsSel,1,Pos(':',WbsSel) - 1);
PosX := X;
PosY := Y;
// Ocultar el movimiento del grid
Respaldo := TBitMap.Create;
Respaldo.Width := Grid.Width;
Respaldo.Height := Grid.Height;
BitBlt(Respaldo.Canvas.Handle,0,0,Grid.Width,Grid.Height,GetDC(GetDeskTopWindow),Forma.Left + (GetSystemMetrics(SM_CYEDGE) * 2),Forma.Top + GetSystemMetrics(SM_CYCAPTION) + (GetSystemMetrics(SM_CYEDGE) * 2),srcCopy);
Grid.Visible := False;
BitBlt(TForm(Forma).Canvas.Handle,0,0,Grid.Width,Grid.Height,Respaldo.Canvas.Handle,0,0,srcCopy);
// Seleccionar el registro correspondiente a la barra clickada
QueryGen.DisableControls;
Posicion := QueryGen.Bookmark;
while (QueryGen.FieldByName(Datos.Wbs).AsString <> FirstInScreen) And (QueryGen.FieldByName(Datos.Wbs).AsString <> WbsSel) And (Not QueryGen.Bof) do
QueryGen.Prior;
if QueryGen.Bof then
QueryGen.First;
// Recorrer hasta localizar el registro seleccionado
while (QueryGen.FieldByName(Datos.Wbs).AsString <> WbsSel) And (Not QueryGen.Eof) do
QueryGen.Next;
if QueryGen.Eof then
QueryGen.Bookmark := Posicion;
QueryGen.EnableControls;
Grid.Visible := True;
FreeAndNil(Respaldo);
// Activar el timer del cursor
TimerCursor.Enabled := True;
End;
End;
Procedure TGraficaGantt.MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Var
Duracion, Inicio, Termino: Real;
Indice: Integer;
nLlave, Posicion: String;
Respaldo: TBitMap;
Begin
TimerCursor.Enabled := False; // Desactivar el timer del cursor
// Registrar el cambio de la barra
Indice := Segmentos.IndexOf(LastBarMouse);
if Indice >= 0 then
Begin
Inicio := TBarra(Segmentos.Objects[Indice]).FechaInicio;
Termino := TBarra(Segmentos.Objects[Indice]).FechaTermino;
case TipoBarra of
1: Inicio := Trunc((NewPosX1 / pAncho) + Scroll.Position);
2: Begin
Duracion := TBarra(Segmentos.Objects[Indice]).FechaTermino - TBarra(Segmentos.Objects[Indice]).FechaInicio;
Inicio := Trunc((NewPosX1 / pAncho) + Scroll.Position);
Termino := Inicio + Duracion;
End;
3: Termino := Trunc((NewPosX2 / pAncho) + Scroll.Position);
end;
// Verificar si no se enciman las fechas
if Inicio < Termino then
Begin
if (Inicio <> QueryData.FieldByName(Datos.Inicio).AsFloat) Or ((Termino - 1) <> QueryData.FieldByName(Datos.Termino).AsFloat) then
Begin
TBarra(Segmentos.Objects[Indice]).FechaInicio := Inicio;
TBarra(Segmentos.Objects[Indice]).FechaTermino := Termino;
Try
QueryData.Edit;
QueryData.FieldByName(ncDuracion).AsFloat := Termino - Inicio;
QueryData.FieldByName(Datos.Inicio).AsFloat := Inicio;
QueryData.FieldByName(Datos.Termino).AsFloat := Termino - 1;
QueryData.UpdateRecord;
QueryData.Post;
ActualizaPaquetes(QueryData);
Except
Raise Exception.CreateFmt('El query especificado está cerrado o ya no está disponible : ''%s''', [TZQuery(QueryData).Name]);
End;
End;
End;
End;
IsDown := False;
LastBarMouse := '';
PosX := X;
PosY := Y;
Grid.Repaint;
End;
Procedure TGraficaGantt.SetGraphic(GanttForm: TForm; GanttGrid: TObject; GanttCanvas: TPaintBox; GanttTabSet: TTabSet; GanttScroll: TScrollBar);
Begin
// Establecer al área gráfica en la cual se requiere que se muestre la gráfica de gantt
Forma := GanttForm;
Grid := TStringGrid(GanttGrid); // Grid que tiene la estructura espejo para el diseño de grafica
TabSet := TTabSet.Create(Nil);
totalregistros := 0;
Grafico := GanttCanvas; // Área de gráfica
TabSet := GanttTabSet; // Selector de formato de gráfica
Scroll := GanttScroll; // Objeto que realiza el scroll horizontal de la imagen
{ Asignar el evento onchange del tabset }
if Not Assigned(TabSet.OnChange) then
TabSet.OnChange := BarraChange;
TabSet.Tabs.Add('Dia');
TabSet.Tabs.Add('Semana');
TabSet.Tabs.Add('Quincena');
TabSet.Tabs.Add('Mes');
TabSet.Tabs.Add('Año');
TabSet.Tabs.Add('Opciones...');
TabSet.SelectedColor := clYellow;
TabSet.TabIndex := gDefault;
MargenBarra := Trunc(Grid.RowHeights[0] / 3); // Espacio entre barras
AlturaBarra := Trunc(Grid.RowHeights[0] - MargenBarra); // Tamaño total de la barra
Grafico.ShowHint := True;
if Not Assigned(GanttCanvas.OnMouseMove) then
GanttCanvas.OnMouseleave := Mouseleave;
{ Asignar evento de movimiento de mouse }
if Not Assigned(GanttCanvas.OnMouseMove) then
GanttCanvas.OnMouseMove := MouseMove;
{ Asignar evento de presionar un botón del mouse }
if Not Assigned(GanttCanvas.OnMouseDown) then
GanttCanvas.OnMouseDown := MouseDown;
{ Asignar evento de soltar el botón presionado del mouse }
if Not Assigned(GanttCanvas.OnMouseUp) then
GanttCanvas.OnMouseUp := MouseUp;
{ Asignar evento de activación de scrollbar }
if Not Assigned(GanttScroll.OnScroll) then
GanttScroll.OnScroll := SetScroll;
{ Asignar el evento para dibujar las celdas del query }
if Not Assigned(TDbGrid(GanttGrid).OnDrawColumnCell) then
TDbGrid(GanttGrid).OnDrawColumnCell := DrawColumnCell;
End;
Procedure TGraficaGantt.UploadBar(Query: TObject; TipoActividad, NumeroActividad, Llave, LlaveAnterior, Inicio, Termino, Duracion, ColorBarra: String);
Var
Cta, Indice: Integer;
OldWbs: String;
begin
// Respaldar los nombres de los campos que se cargan al objeto de las barras
Datos.Wbs := Llave;
Datos.WbsAnterior := LlaveAnterior;
ncDuracion := Duracion;
ncColor := ColorBarra;
Datos.NumeroActividad := NumeroActividad;
Datos.TipoActividad := TipoActividad;
Datos.Inicio := Inicio;
Datos.Termino := Termino;
Datos.ColBarra := ColorBarra;
// Recorrer todas las barras y ligarlas con sus generales
QueryData := TZQuery(Query);
QueryData.DisableControls;
QueryData.First;
Cta := 0;
InicioGraph := 0;
TerminoGraph := 0;
OldWbs := '';
while Not TZQuery(Query).Eof do
Begin
if (InicioGraph = 0) Or (InicioGraph > QueryData.FieldByName(Inicio).AsFloat) then InicioGraph := QueryData.FieldByName(Inicio).AsFloat;
if TerminoGraph < QueryData.FieldByName(Termino).AsFloat then TerminoGraph := QueryData.FieldByName(Termino).AsFloat;
// Meter la información de las barras
if (OldWbs = '') Or (OldWbs <> QueryData.FieldByName(Llave).asstring) then
Cta := 0;
Inc(Cta);
Indice := Segmentos.AddObject(QueryData.FieldByName(Llave).asstring + ':' + IntToStr(Cta), TBarra.Create);
TBarra(Segmentos.Objects[Indice]).NumeroActividad := QueryData.FieldByName(NumeroActividad).AsString;
TBarra(Segmentos.Objects[Indice]).Tipo := QueryData.FieldByName(TipoActividad).AsString;
TBarra(Segmentos.Objects[Indice]).FechaInicio := QueryData.FieldByName(Inicio).AsFloat;
TBarra(Segmentos.Objects[Indice]).FechaTermino := QueryData.FieldByName(Termino).AsFloat + 1; // Fecha final hasta las 24 horas porque no tienen periodos parciales de dias
TBarra(Segmentos.Objects[Indice]).Color := QueryData.FieldVAlues[ColorBarra];
OldWbs := TZQuery(Query).FieldByName(Llave).asstring;
TZQuery(Query).Next;
End;
{ Área de ajustes:
- Se debe considerar que el INTELLIGENT no maneja horas por consiguiente
se deben ajustar todas las fechas finales para que terminen a las 24horas
ya que tal como están terminan el día que indican a las 0horas, lo cual
es igual al día anterior a las 24horas, perdiendose un día en este proceso }
TerminoGraph := Trunc(TerminoGraph + 1);
// Ajustar el inicio para que empieze a las 0 horas
InicioGraph := Trunc(InicioGraph);
Scroll.Max := Trunc(TerminoGraph); // Barra por default con máximo hasta la última fecha de proceso
Scroll.Position := Trunc(InicioGraph); // Posición de la barra al inicio del periodo
Scroll.Min := Trunc(InicioGraph); // Rango mínimo de la barra
Scroll.SmallChange := 1; // Cambio de rango por día
Scroll.LargeChange := Trunc((QueryData.RecordCount * 0.01) + 0.99); // 1% del total de registros, si es menor a 1 se ajusta a este
QueryData.First;
QueryData.EnableControls; // Deshabilitar los controls ligados a este query
end;
Procedure TGraficaGantt.LoadData(Query: TZQuery; TipoActividad, NumeroActividad, Llave, LlaveAnterior, Inicio, Termino, Duracion, ColorBarra: String);
Begin
// Cargar todas las barras correspondientes a la lista general
UpLoadBar(Query, TipoActividad, NumeroActividad, Llave, LlaveAnterior, Inicio, Termino, Duracion, ColorBarra);
End;
Procedure TGraficaGantt.LoadData(Query: TZReadOnlyQuery; TipoActividad, NumeroActividad, Llave, LlaveAnterior, Inicio, Termino, Duracion, ColorBarra: String);
Begin
// Cargar todas las barras correspondientes a la lista general
UpLoadBar(Query, TipoActividad, NumeroActividad, Llave, LlaveAnterior, Inicio, Termino, Duracion, ColorBarra);
End;
Procedure TGraficaGantt.DrawCalendar;
Var
Rect: TRect;
Cuenta: Real;
myFecha: TDateTime;
Texto: String;
Espacio: Integer;
IniDesp: Integer;
Procede: Boolean;
OldFecha: Real;
P: Word;
IniFecha, ParSeg: Real;
Ciclos: Byte;
I, Arriba, NumB: Integer;
NumSeg: Word;
SegBloque: Real;
Begin
FirstCol := -1; // Inicializar la primera columna no ha sido pintada en una nueva generación de la gráfica
Imagen.Width := Grafico.Width; // Imagen debe contener el mismo ancho que el área visual de gráfico
Imagen.Height := TStringGrid(Grid).Height; // El gráfico debe tener el mismo alto que el grid
// Área de calendario
Rect.Left := 0;
Rect.Top := 0;
Rect.Right := Imagen.Width;
Rect.Bottom := TStringGrid(Grid).RowHeights[0] + 2;
Imagen.Canvas.Brush.Color := TStringGrid(Grid).FixedColor;
Imagen.Canvas.Pen.Color := clSilver;
Imagen.Canvas.Rectangle(Rect);
// Margen del área
Imagen.Canvas.Pen.Color := clInfoBK;
Imagen.Canvas.Brush.Color := clInfoBK;
Imagen.Canvas.Rectangle(1,1,Imagen.Width - 1, 2);
Imagen.Canvas.Pen.Color := clBlack;
Imagen.Canvas.MoveTo(2,Grid.RowHeights[0] + 1);
Imagen.Canvas.LineTo(Imagen.Width - 2, Grid.RowHeights[0] + 1);
// Determinar el inicio del periodo actual
IniDesp := 0;
NumB := 1;
IniFecha := Scroll.Position;
if inifecha <= 1 then
inifecha := date;
case pTab of
1:
Begin
// Determinar el número de ciclos que se deben realizar para ajustar al día de inicio de la semana
If DayOfTheWeek(IniFecha) < IniSem then
Ciclos := 7 - (IniSem - DayOfTheWeek(IniFecha))
Else
Ciclos := DayOfTheWeek(IniFecha) - IniSem;
IniDesp := (pAncho * Ciclos) * -1; // Posición exacta de inicio de semana (fuera de visual o no)
IniFecha := IniFecha - Ciclos; // Un número de días hacia atras hasta el inicio de semana
NumB := 7;
End;
2:
Begin
// Determinar el número de ciclos que se deben realizar para ajustar al día de inicio de la quincena
if (DayOfTheMonth(IniFecha) > 0) And (DayOfTheMonth(IniFecha) < 16) then
Ciclos := DayOfTheMonth(IniFecha) - 1
Else
Ciclos := DayOfTheMonth(IniFecha) - 15;
IniDesp := (pAncho * Ciclos) * -1;
IniFecha := IniFecha - Ciclos;
NumB := 13;
End;
3:
Begin
// Determinar el número de ciclos que se deben realizar para ajustar al día de inicio del mes
Ciclos := DayOfTheMonth(IniFecha) - 1;
IniDesp := (pAncho * Ciclos) * -1;
IniFecha := IniFecha - Ciclos;
NumB := 28;
End;
4:
Begin
// Determinar el número de ciclos que se deben realizar para ajustar al primer día del año
Ciclos := DayOfTheYear(IniFecha) - 1;
IniDesp := (pAncho * Ciclos) * -1;
IniFecha := IniFecha - Ciclos;
NumB := 365;
End;
end;
// Colocar le calendario de acuerdo al scrollbar
Cuenta := IniDesp;
myFecha := IniFecha;
OldFecha := myFecha;
Imagen.Canvas.Font.Size := 7;
Imagen.Canvas.Font.Color := clBlack;
while Trunc(Cuenta) <= Grafico.Width do
Begin
// Definir si se ha de colocar la división de acuerdo al formato de gráfica seleccionado por el usuario
case pTab of
0: // Diaria
Begin
Procede := True;
NumSeg := 4; // Dividir los boques en 4 numeros de segmentos
SegBloque := pAncho / NumSeg; // Ancho de segmentos por bloque
End;
1: // Semanal
Begin
Procede := (DayOfTheWeek(myFecha) = IniSem); // Proceder al inicio de nueva semana o al iniciar la gráfica
NumSeg := 7;
SegBloque := pAncho;
End;
2: // Quincenal
Begin
Procede := (DayOfTheMonth(myFecha) = 1) Or (DayOfTheMonth(myFecha) = 16);
if DayOfTheMonth(myFecha) < 16 then
NumSeg := 15
Else
NumSeg := 16 - (31 - DaysInMonth(myFecha));
SegBloque := pAncho;
End;
3: // Mensual
Begin
Procede := (MonthOf(OldFecha) <> MonthOf(myFecha)) Or (OldFecha = myFecha);
NumSeg := DaysInMonth(myFecha);
SegBloque := pAncho;
End;
4: // Anual
Begin
Procede := (YearOf(OldFecha) <> YearOf(myFecha)) Or (OldFecha = myFecha);
NumSeg := 12;
SegBloque := 0;
End;
5:
Begin
Procede := False; // No hacer nada...
End;
end;
If Procede Then
Begin
Texto := FormatDateTime(Formato[FormatoCal], myFecha); // Obtener cadena de fecha
// Determinar espaciado requerido para centrar el texto solo en caso de dias, meses y años
if (pTab = 0) Or (pTab = 3) Or (pTab = 4) then
Begin
Espacio := Imagen.Canvas.TextWidth(Texto);
Espacio := Trunc((pAncho + MargenFecha - Espacio) / 2);
if Espacio < 0 then Espacio := 0;
End
Else Espacio := 0;
// Colocar el texto de la fecha
Imagen.Canvas.Brush.Color := Grid.FixedColor;
Imagen.Canvas.Pen.Color := clBlack;
Imagen.Canvas.TextOut(Trunc(Cuenta) + Espacio + MargenFecha,3,Texto);
// Colocar lineas de división de bloque
ParSeg := 0;
Imagen.Canvas.Pen.Color := clBlack;
Imagen.Canvas.Brush.Color := clBlack;
for P := 1 to NumSeg - 1 do
Begin
// Ojo, si es grafica anual el número de segmentos por bloque es según los dias del mes
if pTab = 4 then
SegBloque := DaysInMonth(IniFecha);
ParSeg := ParSeg + SegBloque;
// Verificar si es necesario detectar el inicio de semana (solo para gráficas quincenales y mensuales)
Arriba := 1;
if (pTab = 2) Or (pTab = 3) then
Begin
if (DayOfTheWeek(myFecha + P) = IniSem) Or (DayOfTheWeek(myFecha + P - 1) = IniSem) then
Arriba := (-1);
End;
if pTab = 4 then
Begin
if MonthOf(OldFecha) <> MonthOf(myFecha) then
Arriba := (-1);
End;
// Mostrar las líneas de división
if pvert then
begin
if totalregistros >= querydata.RecordCount then
begin
Imagen.Canvas.MoveTo(Trunc(Cuenta + ParSeg),Grid.RowHeights[0] + Arriba);
Imagen.Canvas.LineTo(Trunc(Cuenta + ParSeg),((Grid.RowHeights[0] + 1) * (totalregistros + 1 )));
end
else
begin
Imagen.Canvas.MoveTo(Trunc(Cuenta + ParSeg),Grid.RowHeights[0] + Arriba);
Imagen.Canvas.LineTo(Trunc(Cuenta + ParSeg),((Grid.RowHeights[0] + 1) * ( trunc(Grafico.Height / (Grid.RowHeights[0] + 1)))));
end;
end
else
begin
Imagen.Canvas.MoveTo(Trunc(Cuenta + ParSeg),Grid.RowHeights[0] + Arriba);
Imagen.Canvas.LineTo(Trunc(Cuenta + ParSeg),(Grid.RowHeights[0] + 1) + 5 );
end;
End;
if pvert then
begin
if totalregistros >= querydata.RecordCount then
begin
Imagen.Canvas.Pen.Color := clInfoBk;
Imagen.Canvas.MoveTo(Trunc(Cuenta) - 1, 1);
Imagen.Canvas.LineTo(Trunc(Cuenta) - 1, ((Grid.RowHeights[0] + 1) * (totalregistros + 1)));
Imagen.Canvas.Pen.Color := clSilver;
Imagen.Canvas.MoveTo(Trunc(Cuenta), 2);
Imagen.Canvas.LineTo(Trunc(Cuenta), ((Grid.RowHeights[0] + 1) * (totalregistros + 1)));
end
else
begin
Imagen.Canvas.Pen.Color := clInfoBk;
Imagen.Canvas.MoveTo(Trunc(Cuenta) - 1, 1);
Imagen.Canvas.LineTo(Trunc(Cuenta) - 1, ((Grid.RowHeights[0] + 1) * ( trunc(Grafico.Height / (Grid.RowHeights[0] + 1)))));
Imagen.Canvas.Pen.Color := clSilver;
Imagen.Canvas.MoveTo(Trunc(Cuenta), 2);
Imagen.Canvas.LineTo(Trunc(Cuenta), ((Grid.RowHeights[0] + 1) * ( trunc(Grafico.Height / (Grid.RowHeights[0] + 1)))));
end;
end
else
begin
Imagen.Canvas.Pen.Color := clInfoBk;
Imagen.Canvas.MoveTo(Trunc(Cuenta) - 1, 1);
Imagen.Canvas.LineTo(Trunc(Cuenta) - 1, (Grid.RowHeights[0] + 1) + 5);
Imagen.Canvas.Pen.Color := clSilver;
Imagen.Canvas.MoveTo(Trunc(Cuenta), 2);
Imagen.Canvas.LineTo(Trunc(Cuenta), (Grid.RowHeights[0] + 1) + 5);
end;
// showmessage(inttostr(totalregistros));
End;
Cuenta := Cuenta + pAncho; // Avanzar al límite del bloque el cual marca el inicio del nuevo
OldFecha := myFecha;
myFecha := myFecha + 1;
End;
End;
Procedure TGraficaGantt.DrawBar(Rect: TRect; pWbs: String);
Var
Cta: Integer;
Sigue: Boolean;
Datos: TBarra;
Duracion: Real;
P, Indice, gInicio, Color, Altura, AltoB: Integer;
Puntos: TPoint;
ri,gi,bi: integer; // (Red, Green, Blue) del color inicial indicado para la barra
rf,gf,bf: integer; // (Red, Green, Blue) del color final para la barra (Blanco)
pr,pg,pb: double; // (Red, gree, blue) Parametros para degradado
r,g,b: integer;
Y: integer;
Incre: Byte;
ScreenRect: TRect;
Begin
if Dibujar then
Begin
// Registrar la primera actividad que se muestra en pantalla
if Grid.RowHeights[0] + 1 = Rect.Top then
Begin
// Eliminar toda la información previa de visualización
Indice := Segmentos.IndexOf(FirstInScreen + ':1');
totalregistros := 0;
Imagen.Canvas.Pen.Color := clInfoBK;
Imagen.Canvas.Brush.Color := clInfoBK;
Imagen.Canvas.Rectangle(0,0,Imagen.Width , imagen.Height );
if Indice >= 0 then
while TBarra(Segmentos.Objects[Indice]).InScreen do
Begin
TBarra(Segmentos.Objects[Indice]).X1 := 0;
TBarra(Segmentos.Objects[Indice]).Y1 := 0;
TBarra(Segmentos.Objects[Indice]).X2 := 0;
TBarra(Segmentos.Objects[Indice]).Y2 := 0;
TBarra(Segmentos.Objects[Indice]).InScreen := False;
End;
FirstInScreen := pWbs;
End;
// Verificar si está presente la barra de desplazamiento vertical
Incre := 0;
if (TStringGrid(Grid).Scrollbars = ssBoth) Or (TStringGrid(Grid).Scrollbars = ssHorizontal) then
Incre := TStringGrid(Grid).RowHeights[0];
{ Imagen.Width := Grafico.Width;
Imagen.Height := Grafico.Height;
}
// Borrar la información anterior
Imagen.Canvas.Brush.Color := cFondo;
// Revisar si se deben mostrar las lineas de división horizontales
If pHoriz Then
Imagen.Canvas.Pen.Color := clSilver // Mostrar división horizontal
Else
Imagen.Canvas.Pen.Color := cFondo; // No mostrar división horizontal
Imagen.Canvas.Brush.Style := bsSolid;
Imagen.Canvas.Rectangle(0, Rect.Top, Grafico.Width, Rect.Top + MargenBarra + AlturaBarra + 2);
// Localizar la información de los segmentos de esta wbs
Cta := 1;
Sigue := True;
while Sigue do
Begin
Indice := Segmentos.IndexOf(pWbs + ':' + IntToStr(Cta));
Sigue := Indice <> -1;
if Sigue then
Begin
Imagen.Canvas.Brush.Color := clRed;
Imagen.Canvas.Pen.Color := clBlack;
Datos := TBarra(Segmentos.Objects[Indice]); // Obtener información del segmento de barra
// Calcular las coordenadas de la barra
Duracion := Datos.FechaTermino - Datos.FechaInicio;
GInicio := ((Trunc(Datos.FechaInicio - Scroll.Position)) * pAncho);
// Definir la barra con los colores prestablecidos
// especificos := false;
// if datos.color <> 0 then // define si existe un color determinado en la barra o si se aplicaran los colores predeterminados, siendo el valor 0 el color predeterminado
// especificos := true;
if Especificos and (datos.color <> 0) then
Begin
Imagen.Canvas.Brush.Color := escolor(Datos.Color);
Imagen.Canvas.Pen.Color := escolor(Datos.Color);
End
Else
Begin
If Datos.Tipo = 'Actividad' Then
Begin
Imagen.Canvas.Brush.Color := cActividad;
Imagen.Canvas.Pen.Color := cActividad;
End
Else
Begin
Imagen.Canvas.Brush.Color := cPaquete;
Imagen.Canvas.Pen.Color := cPaquete;
End;
End;
// Verificar tipo de barra para calcular alto de barra
if Datos.Tipo = 'Actividad' then
Begin
// Poner las barras de actividades en forma degradada
AltoB := AlturaBarra;
// Tomar los valores iniciales desde el registro de la barra
ri := GetRValue(Imagen.Canvas.Brush.Color);
gi := GetGValue(Imagen.Canvas.Brush.Color);
bi := GetBValue(Imagen.Canvas.Brush.Color);
// Determinar los valores finales del degradado (La variable Dif permite cambiar el porcentaje de degradado)
if ri + Dif > 255 then rf := 255 else rf := ri + Dif;
if gi + Dif > 255 then gf := 255 else gf := gi + Dif;
if bi + Dif > 255 then bf := 255 else bf := bi + Dif;
// Determinar el punto o color intermedio del degradado en base al los colores iniciales y finales
pr := (rf - ri) / (AltoB / 2);
pg := (gf - gi) / (AltoB / 2);
pb := (bf - bi) / (AltoB / 2);
// Pintar con líneas la barra por dos mitades
for Y := 0 to (AltoB div 2) do
begin
// Tomar colores para la línea
r := ri + round(pr * Y);
g := gi + round(pg * Y);
b := bi + round(pb * Y);
Imagen.Canvas.Pen.Color := RGB(r,g,b); // Establecer color para esta línea
// Pintar la parte superior
Imagen.Canvas.MoveTo(GInicio,Rect.Top + MargenBarra + Y);
Imagen.Canvas.LineTo(GInicio + Trunc(Duracion * pAncho),Rect.Top + MargenBarra + Y);
// Pintar la parte inferior
Imagen.Canvas.MoveTo(GInicio,Rect.Top + MargenBarra + AltoB - Y);
Imagen.Canvas.LineTo(GInicio + Trunc(Duracion * pAncho),Rect.Top + MargenBarra + AltoB - Y);
End;
End
else
Begin
// Poner las barras de paquetes en forma sólida
AltoB := Trunc(AlturaBarra / 2);
Imagen.Canvas.Rectangle(GInicio, Rect.Top + MargenBarra, GInicio + Trunc(Duracion * pAncho), Rect.Top + MargenBarra + AltoB);
//Imagen.Canvas.RoundRect(GInicio, Rect.Top + MargenBarra, GInicio + Trunc(Duracion * pAncho), Rect.Top + MargenBarra + AltoB,6,6);
End;
// Colocar los indicadores de inicio y terminación de paquetes entregables
if Datos.Tipo <> 'Actividad' then
Begin
{ Apuntador izquierdo} Imagen.Canvas.Polygon([Point(GInicio,Rect.Top + MargenBarra), Point(GInicio + AlturaBarra,Rect.Top + MargenBarra {+ AltoB}), Point(GInicio,Rect.Top + MargenBarra + AlturaBarra {- Trunc(MargenBarra / 2)})]);
{ Apuntador derecho} Imagen.Canvas.Polygon([Point((GInicio + Trunc(Duracion * pAncho)) - AlturaBarra, Rect.Top + MargenBarra {+ AltoB}), Point((GInicio + Trunc(Duracion * pAncho)), Rect.Top + MargenBarra {+ AltoB}), Point((GInicio + Trunc(Duracion * pAncho)), Rect.Top + MargenBarra + AlturaBarra)]);
End;
// Registrar información de la posición de la barra
TBarra(Segmentos.Objects[Indice]).InScreen := True;
TBarra(Segmentos.Objects[Indice]).X1 := gInicio;
TBarra(Segmentos.Objects[Indice]).Y1 := Rect.Top + MargenBarra;
TBarra(Segmentos.Objects[Indice]).X2 := GInicio + Trunc(Duracion * pAncho);
TBarra(Segmentos.Objects[Indice]).Y2 := Rect.Top + MargenBarra + AltoB;
End;
Inc(Cta);
End;
// Verificar si ya se cargó toda la gráfica
SystemParametersInfo(SPI_GETWORKAREA, 0, @ScreenRect, 0);
totalregistros := totalregistros + 1;
if (Rect.Bottom + Incre + (Rect.Bottom - Rect.Top) > Grafico.Height) or (totalregistros >= querydata.RecordCount) {Or ((Forma.Top + Rect.Bottom + (Rect.Bottom - Rect.Top) + (ScreenRect.Bottom - ScreenRect.Top) > Screen.Height) and (Not (Rect.Bottom + Incre + (Rect.Bottom - Rect.Top) > Grafico.Height)))} then
// if (totalregistros >= int(Grafico.Height / (Grid.RowHeights[0] + 1))) or (querydata.RecordCount = totalregistros ) then {Or ((Forma.Top + Rect.Bottom + (Rect.Bottom - Rect.Top) + (ScreenRect.Bottom - ScreenRect.Top) > Screen.Height) and (Not (Rect.Bottom + Incre + (Rect.Bottom - Rect.Top) > Grafico.Height)))}
Begin
DrawCalendar;
BitBlt(Grafico.Canvas.Handle,0,0,Imagen.Width,Imagen.Height,Imagen.Canvas.Handle,0,0,SRCCOPY); // Mover la imagen diseñada hacia el área grafica
totalregistros := 0;
End;
End;
End;
Procedure TGraficaGantt.SetTab(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
var
t: Integer;
Begin
// Analizar que número de tab se seleccionó
case NewTab of
0: // Gráfica diária
Begin
pAncho := 100;
pTab := NewTab;
End;
1: // Semanal
Begin
pAncho := 19;
pTab := NewTab;
End;
2: // Quincenal
Begin
pAncho := 12;
pTab := NewTab;
End;
3: // Mensual
Begin
pAncho := 7;
pTab := NewTab;
End;
4: // Anual
Begin
pAncho := 1;
pTab := NewTab;
End;
5:
Begin
for t := 1 to 14 do
FrmPropiedades.pFormato[T] := FormatDateTime(Formato[T],25345);
FrmPropiedades.pTipoGrafica := gDefault;
FrmPropiedades.pHorizontal := pHoriz;
FrmPropiedades.pVertical := pvert;
FrmPropiedades.pColorFondo := cFondo;
FrmPropiedades.pColorActividad := cActividad;
FrmPropiedades.pColorPaquete := cPaquete;
FrmPropiedades.pEspecifico := Especificos;
FrmPropiedades.pMargenFecha := MargenFecha;
FrmPropiedades.pInicioSemana := IniSem;
FrmPropiedades.pDegradado := Dif;
FrmPropiedades.pSelCal := FormatoCal - 1;
// Calcular la posición de acuerdo a pantalla del tabset para posicionar la ventana
// FrmPropiedades.Top := Forma.Top + TabSet.Top + GetSystemMetrics(SM_CXEDGE) + GetSystemMetrics(SM_CXBORDER) + GetSystemMetrics(SM_CYCAPTION) - FrmPropiedades.Height;
// FrmPropiedades.Left := Forma.Left + GetSystemMetrics(SM_CYEDGE) + GetSystemMetrics(SM_CYBORDER) + Grafico.Left;
FrmPropiedades.ShowModal;
if FrmPropiedades.cSalida then
Begin
Dif := FrmPropiedades.pDegradado;
pHoriz := FrmPropiedades.pHorizontal;
pVert := FrmPropiedades.pVertical;
cFondo := FrmPropiedades.pColorFondo;
cActividad := FrmPropiedades.pColorActividad;
cPaquete := FrmPropiedades.pColorPaquete;
Especificos := FrmPropiedades.pEspecifico;
MargenFecha := FrmPropiedades.pMargenFecha;
IniSem := FrmPropiedades.pInicioSemana;
FormatoCal := FrmPropiedades.pSelCal + 1;
End;
AllowChange := False; // Prohibir la selección de esta cejilla
End;
end;
Grid.Repaint; // Volver a pintar despues de las modificaciones
End;
Procedure TGraficaGantt.BarraChange(Sender: TObject; NewTab: Integer; var AllowChange: Boolean);
Begin
SetTab(Sender, NewTab, AllowChange);
End;
procedure TGraficaGantt.DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
if FirstCol < 0 then
FirstCol := DataCol;
if DataCol = FirstCol then
DrawBar(Rect, QueryGen.FieldByName(Datos.Wbs).AsString);
end;
Procedure TGraficaGantt.BeforeChangeData(DataSet: TDataSet);
Begin
// Verificar que la modificación provenga del query secundario
if DataSet.Name <> QueryData.Name then
Raise Exception.CreateFmt('Solo es posible validar en este modulo las modificaciones realizadas en el query secundario (%s) debido a que solo los registros del query secundario son registrados para la presentación de las barras de la grafica de gantt.', [QueryData.Name]);
// Cargar los datos originales del dataset al objeto destinado para ello
DatosBefore.Tipo := DataSet.FieldByName(Datos.TipoActividad).AsString;
DatosBefore.Duracion := DataSet.FieldByName(ncDuracion).AsFloat;
DatosBefore.FechaInicio := DataSet.FieldByName(Datos.Inicio).AsFloat;
DatosBefore.FechaTermino := DataSet.FieldByName(Datos.Termino).AsFloat;
DatosBefore.Color := DataSet.FieldByName(ncColor).AsInteger;
End;
Procedure TGraficaGantt.AfterChangeData(DataSet: TDataSet);
Var
C, Indice: Integer;
Continua: Boolean;
fInicio, fTermino: Real;
WbsAnterior, IniTipo: String;
tQuery: TZQuery;
vInicio, vTermino: Real;
Begin
if Dibujar then
Begin
// Verificar que la modificación provenga del query secundario
if DataSet.Name <> QueryData.Name then
Raise Exception.CreateFmt('Solo es posible validar en este modulo las modificaciones realizadas en el query secundario (%s) debido a que solo los registros del query secundario son registrados para la presentación de las barras de la grafica de gantt.', [QueryData.Name]);
{***********************************************************************
Inicia rutina de verificación de datos por EDICIÓN de registro
***********************************************************************}
If QueryGen.State = dsEdit Then
Begin
// Validar antes de ejecutar el afterchangedata que se haya ejecutado previamente el beforechangedata
if DatosBefore.FechaInicio = 0 then
Raise Exception.CreateFmt('Error de secuencia de comandos. Los datos utilizados para validar una modificación de registro deben provenir del query secundario (%s)', [QueryData.Name]);
if DatosBefore.color <> DataSet.FieldByName(datos.colbarra).AsFloat then
begin
C := 1;
Continua := True;
while (C < Segmentos.Count) do
Begin
Indice := Segmentos.IndexOf(DataSet.FieldByName(Datos.Wbs).AsString + ':' + IntToStr(C));
If Indice >= 0 then
// Datos localizados, analizar si se trata de los que se están buscando
TBarra(Segmentos.Objects[Indice]).Color := DataSet.FieldByName(ncColor).AsInteger;
Inc(C);
End;
end;
// Si existen datos de compración analizar que se hayan hecho cambios
if (DatosBefore.Duracion <> DataSet.FieldByName(ncDuracion).AsFloat) Or (DatosBefore.FechaInicio <> DataSet.FieldByName(Datos.Inicio).AsFloat) Or (DatosBefore.FechaTermino <> DataSet.FieldByName(Datos.Termino).AsFloat) then
Begin
If DatosBefore.Duracion <> DataSet.FieldByName(ncDuracion).AsFloat Then
DataSet.FieldByName(Datos.Termino).AsFloat := (DataSet.FieldByName(Datos.Inicio).AsFloat + DataSet.FieldByName(ncDuracion).AsFloat) - 1
Else
DataSet.FieldByName(ncDuracion).AsFloat := (DataSet.FieldByName(Datos.Termino).AsFloat - DataSet.FieldByName(Datos.Inicio).AsFloat) + 1;
// Verificar que no se esté intentando modificar un paquete de actividades en las fechas de inicio y terminación
if (DataSet.FieldByName(Datos.TipoActividad).AsString <> 'Paquete') then
Begin
// Ante la modificación de un campo de fecha se debe localizar el elemento en la memoria para cambiar los datos originales por los nuevos
C := 1;
Continua := True;
while (C < Segmentos.Count) And (Continua) do
Begin
Indice := Segmentos.IndexOf(DataSet.FieldByName(Datos.Wbs).AsString + ':' + IntToStr(C));
If Indice >= 0 then
// Datos localizados, analizar si se trata de los que se están buscando
Continua := Not ((TBarra(Segmentos.Objects[Indice]).FechaInicio = DatosBefore.FechaInicio) And (TBarra(Segmentos.Objects[Indice]).FechaTermino = DAtosBefore.FechaTermino + 1))
Else
Begin
Continua := False; // Se han terminado los elementos correspondientes a este Wbs, termina el ciclo sin localizar datos
C := -1; // Indicar de ausencia de datos buscados
End;
If Continua Then Inc(C);
End;
// Modificar los datos dentro de la memoria de la gráfica
if C > 0 then
Begin
TBarra(Segmentos.Objects[Indice]).Tipo := DataSet.FieldByName(Datos.TipoActividad).AsString;
TBarra(Segmentos.Objects[Indice]).Duracion := DataSet.FieldByName(ncDuracion).AsFloat;
TBarra(Segmentos.Objects[Indice]).FechaInicio := DataSet.FieldByName(Datos.Inicio).AsFloat;
{ ********* AJUSTE POR FALTA DE HORARIO EN CAMPOS DE FECHA FINAL
Agregar un día a la fecha final porque no cuentan con horas }
TBarra(Segmentos.Objects[Indice]).FechaTermino := DataSet.FieldByName(Datos.Termino).AsFloat + 1;
TBarra(Segmentos.Objects[Indice]).Color := DataSet.FieldByName(ncColor).AsInteger;
ActualizaPaquetes(DataSet); // Actualizar periodos de paquetes en caso de ser necesario
End;
End
Else
Begin
DataSet.FieldByName(ncDuracion).AsFloat := DatosBefore.Duracion;
DataSet.FieldByName(Datos.Inicio).AsFloat := DatosBefore.FechaInicio;
DataSet.FieldByName(Datos.Termino).AsFloat := DatosBefore.FechaTermino;
{ShowMessage('No es posible modificar la fecha de inicio y/o terminación de un paquete de actividades.' + #13 + #13 + 'El periodo de un paquete de actividades se modifica en base a los periodos de las actividades que el paquete contenga.');}
End;
End;
End // Termina rutina de validación de datos por edición de registro
Else
Begin
{**********************************************************************
Validación de registros de datos por INSERCIÓN
********************************************************************** }
Indice := Segmentos.AddObject(QueryData.FieldByName(Datos.GeneralKey).asstring + ':1', TBarra.Create);
TBarra(Segmentos.Objects[Indice]).NumeroActividad := DataSet.FieldByName(Datos.NumeroActividad).AsString;
TBarra(Segmentos.Objects[Indice]).Tipo := DataSet.FieldByName(Datos.TipoActividad).AsString;
TBarra(Segmentos.Objects[Indice]).FechaInicio := DataSet.FieldByName(Datos.Inicio).AsFloat;
TBarra(Segmentos.Objects[Indice]).FechaTermino := DataSet.FieldByName(Datos.Termino).AsFloat + 1; // Fecha final hasta las 24 horas porque no tienen periodos parciales de dias
TBarra(Segmentos.Objects[Indice]).Color := DataSet.FieldVAlues[Datos.ColBarra];
ActualizaPaquetes(DataSet); // Actualizar periodos de paquetes en caso de ser necesario
End;
End;
End;
Procedure TGraficaGantt.ActualizaPaquetes(DataSet: TDataSet);
Var
tQuery: TZQuery;
WbsAnterior: String;
vInicio, vTermino: Real;
Indice: Integer;
Begin
// Verificar si esta modificación afecta a barras concentradoras
tQuery := TZQuery.Create(Nil);
tQuery.Connection := QueryGen.Connection;
// Obtener una copia de la información del programa
tQuery.SQL.Text := QueryGen.SQL.Text;
tquery.Params.ParamByName('contrato').DataType := ftstring;
tquery.Params.ParamByName('contrato').Value := Global_Contrato;
tquery.Params.ParamByName('convenio').DataType := ftstring;
tquery.Params.ParamByName('convenio').Value := Global_Convenio;
tQuery.Open;
// showmessage(QueryGen.SQL.Text);
// showmessage(inttostr(tquery.RecordCount));
WbsAnterior := Dataset.FieldByName(Datos.WbsAnterior).AsString;
while (WbsAnterior <> '0') and (WbsAnterior <> '') do
Begin
// Filtrar las partidas de los paquetes afectados
tQuery.Filter := Datos.WbsAnterior + ' = ' + QuotedStr(WbsAnterior);
// showmessage(tQuery.Filter);
tQuery.Filtered := True;
tQuery.First;
vInicio := Dataset.FieldByName(Datos.Inicio).AsFloat;
vTermino := DataSet.FieldByName(Datos.Termino).AsFloat;
While Not tQuery.Eof Do
Begin
if tQuery.FieldByName(Datos.Wbs).AsString <> DataSet.FieldByName(Datos.Wbs).AsString then
Begin
If (vInicio = 0) Or (vInicio > tQuery.FieldByName(Datos.Inicio).AsFloat) then vInicio := tQuery.FieldByName(Datos.Inicio).AsFloat;
If vTermino < tQuery.FieldByName(Datos.Termino).AsFloat then vTermino := tQuery.FieldByName(Datos.Termino).AsFloat;
End;
tQuery.Next;
End;
tQuery.Filtered := False;
if vInicio <> 0 then
Begin
// Localizar el paquete
tQuery.Locate(Datos.Wbs,WbsAnterior,[]);
if tQuery.Found then
Begin
if (tQuery.FieldByName(Datos.Inicio).AsFloat <> vInicio) Or (tQuery.FieldByName(Datos.Termino).AsFloat <> vTermino) then
Begin
// Modificar los datos en caso de ser necesario
tQuery.Edit;
tQuery.FieldByName(ncDuracion).AsFloat := (vTermino - vInicio) + 1;
tQuery.FieldByName(Datos.Inicio).AsFloat := vInicio;
tQuery.FieldByName(Datos.Termino).AsFloat := vTermino;
tQuery.UpdateRecord;
tQuery.Post;
// Actualizar los vectores de memoria
Indice := Segmentos.IndexOf(tQuery.FieldByName(Datos.Wbs).AsString + ':1');
If Indice >= 0 then
Begin
TBarra(Segmentos.Objects[Indice]).FechaInicio := vInicio;
{ ********* AJUSTE POR FALTA DE HORARIO EN CAMPOS DE FECHA FINAL
Agregar un día a la fecha final porque no cuentan con horas }
TBarra(Segmentos.Objects[Indice]).FechaTermino := vTermino + 1;
End;
End;
WbsAnterior := tQuery.FieldByName(Datos.WbsAnterior).AsString; // Continuar con los paquetes hacia arriba
End
Else
WbsAnterior := '';
End;
End;
QueryGen.Refresh;
tQuery.Close;
FreeAndNil(tQuery);
Grid.Repaint; // Volver a dibujar la gráfica despues de las modificaciones*)
End;
end.
|
{ $Id: UnitTestExtensions.pas 7 2008-04-24 11:59:47Z judc $ }
{: DUnit: An XTreme testing framework for Delphi programs.
@author The DUnit Group.
@version $Revision: 7 $
}
(*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is DUnit.
*
* The Initial Developers of the Original Code are Kent Beck, Erich Gamma,
* and Juancarlo Aņez.
* Portions created The Initial Developers are Copyright (C) 1999-2000.
* Portions created by The DUnit Group are Copyright (C) 2000-2003.
* All rights reserved.
*
* Contributor(s):
* Kent Beck <kentbeck@csi.com>
* Erich Gamma <Erich_Gamma@oti.com>
* Juanco Aņez <juanco@users.sourceforge.net>
* Chris Morris <chrismo@users.sourceforge.net>
* Jeff Moore <JeffMoore@users.sourceforge.net>
* Kenneth Semeijn <kennethsem@users.sourceforge.net>
* Kris Golko <neuromancer@users.sourceforge.net>
* The DUnit group at SourceForge <http://dunit.sourceforge.net>
*
*)
unit UnitTestExtensions;
interface
uses
TestFramework,
TestExtensions;
const
COUNT_MAX = 5;
type
ITestStub = interface(ITest)
function GetCounter: integer;
end;
TTestStub = class(TTestCase, ITestStub)
protected
FCounter: integer;
public
function GetCounter: integer;
published
{$IFDEF CLR}[Test]{$ENDIF}
procedure test;
end;
TTestSetupStub = class(TTestSetup)
protected
procedure SetUp; override;
procedure TearDown; override;
public
SetUpCalled: boolean;
TearDownCalled: boolean;
end;
TTestStubTest = class(TTestCase)
private
FTestResult: TTestResult;
FTestStub: ITestStub;
protected
procedure SetUp; override;
procedure TearDown; override;
end;
TTestSetupTest = class(TTestStubTest)
private
FSetupTest: TTestSetupStub;
FTest: ITest;
protected
procedure SetUp; override;
procedure TearDown; override;
published
{$IFDEF CLR}[Test]{$ENDIF}
procedure TestSetupTest;
{$IFDEF CLR}[Test]{$ENDIF}
procedure TestDecoratedEnabling;
end;
TTestSetupStubExceptionInSetup = class(TTestSetupStub)
protected
procedure SetUp; override;
end;
TTestTestSetupExceptionInSetup = class(TTestStubTest)
private
FSetupTest: TTestSetupStub;
FTest: ITest;
protected
procedure SetUp; override;
procedure TearDown; override;
published
{$IFDEF CLR}[Test]{$ENDIF}
procedure testNoExecutionOfTests;
end;
TTestSetupStubExceptionInTearDown = class(TTestSetupStub)
protected
procedure TearDown; override;
end;
TTestTestSetupExceptionInTearDown = class(TTestStubTest)
private
FSetupTest: TTestSetupStub;
FTest: ITest;
protected
procedure SetUp; override;
procedure TearDown; override;
published
{$IFDEF CLR}[Test]{$ENDIF}
procedure testExecutionOfTests;
end;
TTestRepeatedTest = class(TTestStubTest)
private
FIterations: integer;
FRepTest: ITest;
protected
procedure SetUp; override;
procedure TearDown; override;
published
{$IFDEF CLR}[Test]{$ENDIF}
procedure testRepeatedTest;
{$IFDEF CLR}[Test]{$ENDIF}
procedure testWithCounting;
procedure testWithCountingHaltOnTestFailed;
end;
TCountCase = class(TTestCase)
private
FCounter : Integer;
FTotal : Integer;
FLast : Integer;
protected
procedure SetUp; override;
published
{$IFDEF CLR}[Test]{$ENDIF}
procedure CountTest; virtual;
end;
TCountCaseFails = class(TTestCase)
private
FCounter : Integer;
FTotal : Integer;
FLast : Integer;
protected
procedure SetUp; override;
published
{$IFDEF CLR}[Test]{$ENDIF}
procedure CountTestFails; virtual;
end;
{ TMemoryTest tests }
{$IFNDEF CLR}
TTestMemoryTest = class(TTestStubTest)
protected
FObject : TObject;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure testEmptyTest; virtual;
end;
TTestMemoryTestWithCheckError = class(TTestMemoryTest)
published
procedure testEmptyTest; override;
end;
TTestMemoryTestNotFreeing = class(TTestStubTest)
protected
FObject : TObject;
public
procedure SetUp; override;
procedure TearDown; override;
published
{$IFDEF CLR}[Test]{$ENDIF}
procedure testEmptyTest;
end;
TBaseMemoryTest = class(TTestStubTest)
private
FMemTest: ITest;
public
procedure SetUp; override;
procedure TearDown; override;
end;
TMemoryTestNoLeak = class(TBaseMemoryTest)
public
procedure SetUp; override;
published
procedure testNoLeak;
end;
TMemoryTestLeak = class(TBaseMemoryTest)
public
procedure SetUp; override;
published
procedure testLeak;
end;
TMemoryTestNoLeakReportingWithCheckError = class(TBaseMemoryTest)
public
procedure SetUp; override;
published
procedure testNoLeakWithCheckError;
end;
{$ENDIF}
implementation
uses
{$IFNDEF CONSOLE}
{$IFNDEF CLR}
UnitTestGUITesting,
{$ENDIF}
{$ENDIF}
UnitTestFramework,
SysUtils;
{ TTestStub }
function TTestStub.GetCounter: integer;
begin
Result := FCounter;
end;
procedure TTestStub.test;
begin
check(true);
Inc(FCounter);
end;
{ TTestSetupStub }
procedure TTestSetupStub.SetUp;
begin
SetUpCalled := true;
end;
procedure TTestSetupStub.TearDown;
begin
TearDownCalled := true;
end;
{ TTestStubTest }
procedure TTestStubTest.SetUp;
begin
inherited;
FTestStub := TTestStub.Create('test');
FTestResult := TTestResult.Create;
end;
procedure TTestStubTest.TearDown;
begin
FTestResult.Free;
FTestStub := nil;
inherited;
end;
{ TTestSetupTest }
procedure TTestSetupTest.SetUp;
begin
inherited;
FSetupTest := TTestSetupStub.Create(FTestStub);
FTest := FSetupTest;
end;
procedure TTestSetupTest.TearDown;
begin
inherited;
FTest := nil;
FSetupTest := nil;
end;
procedure TTestSetupTest.TestDecoratedEnabling;
var
childEnabled :boolean;
begin
childEnabled := FSetupTest.Test.Enabled;
FSetupTest.Enabled := true;
check(FSetupTest.Enabled);
check(childEnabled = FSetupTest.Test.Enabled);
FSetupTest.Enabled := false;
check(not FSetupTest.Enabled);
check(childEnabled = FSetupTest.Test.Enabled);
end;
procedure TTestSetupTest.TestSetupTest;
begin
{ call the interface to ensure proper inheritence in TTestSetup.
To make this test fail, remove the override directive from
TTestSetup.Run. }
ITestDecorator(FSetupTest).Run(FTestResult);
check(FTestResult.wasSuccessful);
check(FSetupTest.SetUpCalled);
check(FSetupTest.TearDownCalled);
end;
{ TTestRepeatedTest }
procedure TTestRepeatedTest.SetUp;
begin
inherited;
FIterations := COUNT_MAX;
FRepTest := TRepeatedTest.Create(FTestStub, FIterations);
end;
procedure TTestRepeatedTest.TearDown;
begin
FRepTest := nil;
FRepTest := nil;
inherited;
end;
procedure TTestRepeatedTest.testRepeatedTest;
begin
check(FRepTest.CountTestCases = COUNT_MAX);
check(FTestStub.getEnabled);
FRepTest.Run(FTestResult);
check(FTestResult.wasSuccessful);
check(FTestStub.GetCounter = COUNT_MAX);
end;
procedure TTestRepeatedTest.testWithCounting;
var
CountCase :ITest;
AREsult :TTestResult;
begin
CountCase := TRepeatedTest.Create(TCountCase.Create('CountTest'), COUNT_MAX);
AResult := CountCase.Run;
try
check(AResult.runCount = COUNT_MAX, 'wrong runCount, was ' + IntToStr(AResult.runCount) );
check(AResult.failureCount = 0, 'wrong failureCount, was ' + IntToStr(AResult.failureCount) );
check(AResult.errorCount = 0, 'wrong errorCount, was ' + IntToStr(AResult.errorCount) );
finally
AResult.Free
end
end;
{ TCountCase }
procedure TCountCase.CountTest;
begin
Inc(FCounter);
check(FCounter = 1, 'must be one, or SetUp was not called');
Inc(FTotal);
check(FTotal >= 1, 'total should be at least one');
check(FTotal = (FLast+1), 'total should be increment');
FLast := FTotal;
end;
procedure TCountCase.SetUp;
begin
FCounter := 0;
end;
procedure TTestRepeatedTest.testWithCountingHaltOnTestFailed;
var
CountCase :IRepeatedTest;
AResult :TTestResult;
begin
CountCase := TRepeatedTest.Create(TCountCaseFails.Create('CountTestFails'), COUNT_MAX);
CountCase.HaltOnError := True;
AResult := (CountCase as ITest).Run;
try
check(AResult.runCount = 1, 'wrong runCount, was ' + IntToStr(AResult.runCount) );
check(AResult.failureCount = 1, 'wrong failureCount, was ' + IntToStr(AResult.failureCount) );
check(AResult.errorCount = 0, 'wrong errorCount, was ' + IntToStr(AResult.errorCount) );
finally
AResult.Free
end
end;
{ TCountCaseFails }
procedure TCountCaseFails.CountTestFails;
begin
Inc(FCounter);
check(FCounter = 1, 'must be one, or SetUp was not called');
Inc(FTotal);
check(FTotal >= 1, 'total should be at least one');
check(FTotal = (FLast+1), 'total should be increment');
FLast := FTotal;
Check(False, 'Forced Fail');
end;
procedure TCountCaseFails.SetUp;
begin
FCounter := 0;
end;
{ TTestMemoryTest }
{$IFNDEF CLR}
procedure TTestMemoryTest.SetUp;
begin
inherited;
FObject := TObject.Create;
end;
procedure TTestMemoryTest.TearDown;
begin
FObject.Free;
FObject := nil;
// Now the memory leak should be 0
inherited;
end;
procedure TTestMemoryTest.testEmptyTest;
begin
CheckNotNull(FObject);
end;
{ TTestMemoryTestNotFreeing }
procedure TTestMemoryTestNotFreeing.SetUp;
begin
inherited;
FObject := TObject.Create;
end;
procedure TTestMemoryTestNotFreeing.TearDown;
begin
inherited;
// Don't free object
// Now the memory leak shouldnot be 0
end;
procedure TTestMemoryTestNotFreeing.testEmptyTest;
begin
CheckNotNull(FObject);
end;
{ TBaseMemoryTest }
procedure TBaseMemoryTest.SetUp;
begin
inherited;
FMemTest := nil
end;
procedure TBaseMemoryTest.TearDown;
begin
FMemTest := nil;
inherited;
end;
{ TMemoryTestNoLeak }
procedure TMemoryTestNoLeak.SetUp;
begin
inherited;
FMemTest := TMemoryTest.Create(TTestMemoryTest.Suite);
end;
procedure TMemoryTestNoLeak.testNoLeak;
begin
check(FTestStub.getEnabled);
FMemTest.Run(FTestResult);
if not FTestResult.wasSuccessful then
begin
if FTestResult.ErrorCount > 0 then
Fail('Memory tested testcase failed: '
+ FTestResult.Errors[0].ThrownExceptionMessage
);
if FTestResult.FailureCount > 0 then
Fail('Memory tested testcase failed: '
+ FTestResult.Failures[0].ThrownExceptionMessage
);
end;
end;
{ TMemoryTestLeak }
procedure TMemoryTestLeak.SetUp;
begin
inherited;
FMemTest := TMemoryTest.Create(TTestMemoryTestNotFreeing.Suite);
end;
procedure TMemoryTestLeak.testLeak;
begin
try
check(FTestStub.getEnabled);
FMemTest.Run(FTestResult);
finally
// Errors will happen on non Window platform
// Where no GetHeapStatus.TotalAllocated function exists.
check(not FTestResult.wasSuccessful, 'Test was successful, should not be successful.');
CheckEquals(0, FTestResult.errorCount, 'Wrong errorCount');
CheckEquals(1, FTestResult.failureCount, 'Wrong failureCount');
end;
end;
{ TMemoryTestNoLeakReportingWithCheckError }
procedure TMemoryTestNoLeakReportingWithCheckError.SetUp;
begin
inherited;
FMemTest := TMemoryTest.Create(TTestMemoryTestWithCheckError.Suite);
end;
procedure TMemoryTestNoLeakReportingWithCheckError.testNoLeakWithCheckError;
begin
check(FTestStub.getEnabled, 'not enabled');
FMemTest.Run(FTestResult);
check(FTestResult.FailureCount + FTestResult.ErrorCount = 1,
'Memory test added 1 error or failure');
end;
{ TTestMemoryTestWithCheckError }
procedure TTestMemoryTestWithCheckError.testEmptyTest;
begin
inherited;
// Deliberate error
Check(false);
end;
{$ENDIF}
{ TTestSetupExeptionInSetup }
procedure TTestSetupStubExceptionInSetup.SetUp;
begin
inherited;
raise EUnitTestException.Create('Exception in SetUp');
end;
{ TTestSetupExeptionInTearDown }
procedure TTestSetupStubExceptionInTearDown.TearDown;
begin
inherited;
raise EUnitTestException.Create('Exception in TearDown');
end;
{ TTestExceptionInSetup }
procedure TTestTestSetupExceptionInSetup.SetUp;
begin
inherited;
FSetupTest := TTestSetupStubExceptionInSetup.Create(FTestStub);
FTest := FSetupTest;
end;
procedure TTestTestSetupExceptionInSetup.TearDown;
begin
inherited;
FTest := nil;
FSetupTest := nil;
end;
procedure TTestTestSetupExceptionInSetup.testNoExecutionOfTests;
begin
ITestDecorator(FSetupTest).Run(FTestResult);
check(not FTestResult.WasSuccessful, 'Test was successful');
CheckEquals(FTestResult.RunCount, 0, 'Tests ran with Exception in SetUp');
check(FSetupTest.SetUpCalled, 'SetUp not called');
check(FSetupTest.TearDownCalled, 'TearDown not called');
end;
{ TTestExceptionInTearDown }
procedure TTestTestSetupExceptionInTearDown.SetUp;
begin
inherited;
FSetupTest := TTestSetupStubExceptionInTearDown.Create(FTestStub);
FTest := FSetupTest;
end;
procedure TTestTestSetupExceptionInTearDown.TearDown;
begin
inherited;
FTest := nil;
FSetupTest := nil;
end;
procedure TTestTestSetupExceptionInTearDown.testExecutionOfTests;
begin
ITestDecorator(FSetupTest).Run(FTestResult);
check(not FTestResult.WasSuccessful, 'Test was successful');
CheckEquals(FTestResult.RunCount, 1, 'Tests did not run');
check(FSetupTest.SetUpCalled, 'SetUp not called');
check(FSetupTest.TearDownCalled, 'TearDown not called');
end;
initialization
RegisterTests('TestExtensions Suite',
[ TTestRepeatedTest.Suite,
TTestSetupTest.Suite,
TTestTestSetupExceptionInSetup.Suite,
TTestTestSetupExceptionInTearDown.Suite,
TRepeatedTest.Create(TCountCase.Create('CountTest'), COUNT_MAX)
]);
{$IFNDEF CLR}
{$IFDEF CONSOLE}
// These memory tests do not work with the GUI
RegisterTests('TMemoryTest decorator test',
[
TMemoryTestNoLeak.Suite,
TMemoryTestLeak.Suite,
TMemoryTestNoLeakReportingWithCheckError.Suite,
TMemoryTest.Create(UnitTestFramework.TTestTest.Suite)
{$IFNDEF LINUX}
{$IFNDEF CONSOLE}
{$IFNDEF CLR}
, TMemoryTest.Create(UnitTestGUITesting.TGUITestRunnerTests.Suite)
{$ENDIF}
{$ENDIF}
{$ENDIF}
]);
{$ENDIF}
{$ENDIF}
end.
|
unit WHookInt;
interface
uses
Windows, Messages, SysUtils;
function SetHook(WinHandle: HWND; MsgToSend: Integer): Boolean; stdcall; export;
function FreeHook: Boolean; stdcall; export;
function MsgFilterFuncKbd(Code: Integer; wParam, lParam: Longint): Longint stdcall; export;
function MsgFilterFuncMou(Code: Integer; wParam, lParam: Longint): Longint stdcall; export;
function MsgFilterFuncMouLL(Code: Integer; wParam, lParam: Longint): Longint stdcall; export;
function SetDialogHandle(Value: HWND): Boolean; stdcall; export;
function SetMapWindowHandle(Value: HWND): Boolean; stdcall; export;
implementation
const
WH_KEYBOARD_LL = 13;
WH_MOUSE_LL = 14;
type
{ Structure used by WH_KEYBOARD_LL }
PKBDLLHookStruct = ^TKBDLLHookStruct;
{$EXTERNALSYM tagKBDLLHOOKSTRUCT}
tagKBDLLHOOKSTRUCT = packed record
vkCode: DWORD;
scanCode: DWORD;
flags: DWORD;
time: DWORD;
dwExtraInfo: PULONG;
end;
TKBDLLHookStruct = tagKBDLLHOOKSTRUCT;
{$EXTERNALSYM KBDLLHOOKSTRUCT}
KBDLLHOOKSTRUCT = tagKBDLLHOOKSTRUCT;
ULONG_PTR = ^DWORD;
POINT = packed record
x,y: longint;
end;
// Low Level Mouse Hook Info Struct
// http://msdn.microsoft.com/en-us/ms644970.aspx
MSLLHOOKSTRUCT = packed record
pt: POINT;
mouseData: DWORD;
flags: DWORD;
time: DWORD;
dwExtraInfo: ULONG_PTR;
end;
PMSLLHOOKSTRUCT = ^MSLLHOOKSTRUCT;
// Memory map file stuff
{
The CreateFileMapping function creates unnamed file-mapping object
for the specified file.
}
function CreateMMF(Name: string; Size: Integer): THandle;
begin
Result := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0, Size, PChar(Name));
if Result <> 0 then
begin
if GetLastError = ERROR_ALREADY_EXISTS then
begin
CloseHandle(Result);
Result := 0;
end;
end;
end;
{ The OpenFileMapping function opens a named file-mapping object. }
function OpenMMF(Name: string): THandle;
begin
Result := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PChar(Name));
// The return value is an open handle to the specified file-mapping object.
end;
{
The MapViewOfFile function maps a view of a file into
the address space of the calling process.
}
function MapMMF(MMFHandle: THandle): Pointer;
begin
Result := MapViewOfFile(MMFHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0);
end;
{
The UnmapViewOfFile function unmaps a mapped view of a file
from the calling process's address space.
}
function UnMapMMF(P: Pointer): Boolean;
begin
Result := UnmapViewOfFile(P);
end;
function CloseMMF(MMFHandle: THandle): Boolean;
begin
Result := CloseHandle(MMFHandle);
end;
// Actual hook stuff
type
TPMsg = ^TMsg;
const
VK_D = $44;
VK_E = $45;
VK_F = $46;
VK_M = $4D;
VK_R = $52;
MMFName = 'HIDMacrosSharedMem';
type
PMMFData = ^TMMFData;
TMMFData = record
WinHandle: HWND;
MsgToSend: Integer;
DialogHandle: HWND;
MapWindowHandle: HWND;
end;
// global variables, only valid in the process which installs the hook.
var
MMFHandle: THandle;
MMFData: PMMFData;
lHookKbd: HHOOK;
lHookMou: HHOOK;
function UnMapAndCloseMMF: Boolean;
begin
Result := False;
if UnMapMMF(MMFData) then
begin
MMFData := nil;
if CloseMMF(MMFHandle) then
begin
MMFHandle := 0;
Result := True;
end;
end;
end;
{
The SetWindowsHookEx function installs an application-defined
hook procedure into a hook chain.
WH_GETMESSAGE Installs a hook procedure that monitors messages
posted to a message queue.
For more information, see the GetMsgProc hook procedure.
}
function SetHook(WinHandle: HWND; MsgToSend: Integer): Boolean; stdcall;
begin
Result := False;
if (MMFData = nil) and (MMFHandle = 0) then
begin
MMFHandle := CreateMMF(MMFName, SizeOf(TMMFData));
if MMFHandle <> 0 then
begin
MMFData := MapMMF(MMFHandle);
if MMFData <> nil then
begin
MMFData.WinHandle := WinHandle;
MMFData.MsgToSend := MsgToSend;
MMFData.DialogHandle := 0;
MMFData.MapWindowHandle := 0;
lHookKbd := SetWindowsHookEx(WH_KEYBOARD, MsgFilterFuncKbd, HInstance, 0);
lHookMou := SetWindowsHookEx(WH_MOUSE, MsgFilterFuncMou, HInstance, 0);
// low level hooking, not used now
//lHookKbd := SetWindowsHookEx(WH_KEYBOARD_LL, MsgFilterFuncKbdLL, HInstance, 0);
//lHookMou := SetWindowsHookEx(WH_MOUSE_LL, MsgFilterFuncMouLL, HInstance, 0);
if (lHookKbd = 0) or (lHookMou = 0) then
begin
FreeHook; // free is something was ok
end
else
Result := True;
end
else
begin
CloseMMF(MMFHandle);
MMFHandle := 0;
end;
end;
end;
end;
{
The UnhookWindowsHookEx function removes the hook procedure installed
in a hook chain by the SetWindowsHookEx function.
}
function FreeHook: Boolean; stdcall;
var b1, b2, b3: Boolean;
begin
Result := False;
b1 := True;
b2 := True;
if (lHookKbd <> 0) then
b1 := UnHookWindowsHookEx(lHookKbd);
if (lHookMou <> 0) then
b2 := UnHookWindowsHookEx(lHookMou);
if (MMFData <> nil) and (MMFHandle <> 0) then
begin
b3 := UnMapAndCloseMMF;
Result := b1 and b2 and b3;
end;
end;
(*
GetMsgProc(
nCode: Integer; {the hook code}
wParam: WPARAM; {message removal flag}
lParam: LPARAM {a pointer to a TMsg structure}
): LRESULT; {this function should always return zero}
{ See help on ==> GetMsgProc}
*)
function MsgFilterFuncKbd(Code: Integer; wParam, lParam: Longint): Longint;
var
MMFHandle: THandle;
MMFData: PMMFData;
Kill: boolean;
locData: TMMFData;
dataFetched : boolean;
what2do : Integer;
MessageId: Word;
// ext_code: Cardinal;
begin
if (Code < 0) or (Code <> HC_ACTION) then
begin
Result := CallNextHookEx(lHookKbd {ignored in API}, Code, wParam, lParam);
exit;
end;
Result := 0;
dataFetched := False;
MMFHandle := OpenMMF(MMFName);
if MMFHandle <> 0 then
begin
MMFData := MapMMF(MMFHandle);
if MMFData <> nil then
begin
locData := MMFData^;
dataFetched := True;
UnMapMMF(MMFData);
end;
CloseMMF(MMFHandle);
end;
if (dataFetched) then
begin
Kill := False;
if (locData.WinHandle <> 0) and (locData.MsgToSend > 0) then
begin
//OutputDebugString('DLL: Would ask HIDmacros what to do for KEYBOARD.');
if (lParam and $80000000 > 0) then
MessageId := WM_KEYUP
else
MessageId := WM_KEYDOWN;
what2do := SendMessage(locData.WinHandle, locData.MsgToSend, MessageId , wParam);
if (what2do = -1) then
Kill := True;
end;
if Kill then
Result := 1
else
Result := CallNextHookEx(lHookKbd {ignored in API}, Code, wParam, lParam);
end;
end;
function MsgFilterFuncKbdLL(Code: Integer; wParam, lParam: Longint): Longint;
var
MMFHandle: THandle;
MMFData: PMMFData;
Kill: boolean;
locData: TMMFData;
dataFetched : boolean;
what2do : Integer;
// ext_code: Cardinal;
begin
Result := 0;
dataFetched := False;
MMFHandle := OpenMMF(MMFName);
if MMFHandle <> 0 then
begin
MMFData := MapMMF(MMFHandle);
if MMFData <> nil then
begin
locData := MMFData^;
dataFetched := True;
UnMapMMF(MMFData);
end;
CloseMMF(MMFHandle);
end;
if (dataFetched) then
begin
if (Code < 0) or (Code <> HC_ACTION) then
{
The CallNextHookEx function passes the hook information to the
next hook procedure in the current hook chain.
}
Result := CallNextHookEx(lHookKbd {ignored in API}, Code, wParam, lParam)
else
begin
Kill := False;
if (locData.WinHandle <> 0) and (locData.MsgToSend > 0) then
begin
//OutputDebugString('DLL: Would ask HIDmacros what to do for KEYBOARD.');
what2do := SendMessage(locData.WinHandle, locData.MsgToSend, wParam , PKBDLLHookStruct(lParam)^.vkCode);
if (what2do = -1) then
Kill := True;
end;
if Kill then
Result := 1
else
Result := CallNextHookEx(lHookKbd {ignored in API}, Code, wParam, lParam);
end;
end;
end;
function MsgFilterFuncMou(Code: Integer; wParam, lParam: Longint): Longint;
var
MMFHandle: THandle;
MMFData: PMMFData;
Kill: boolean;
locData: TMMFData;
dataFetched : boolean;
what2do: Integer;
// ext_code: Cardinal;
begin
Result := 0;
dataFetched := False;
MMFHandle := OpenMMF(MMFName);
if MMFHandle <> 0 then
begin
MMFData := MapMMF(MMFHandle);
if MMFData <> nil then
begin
locData := MMFData^;
dataFetched := True;
UnMapMMF(MMFData);
end;
CloseMMF(MMFHandle);
end;
if (dataFetched) then
begin
if (Code < 0) or (Code <> HC_ACTION) then
Result := CallNextHookEx(lHookMou {ignored in API}, Code, wParam, lParam)
else
begin
Kill := False;
if (locData.WinHandle <> 0) and (locData.MsgToSend > 0)
and (
(wParam = WM_LBUTTONDOWN) or
(wParam = WM_LBUTTONUP) or
(wParam = WM_MBUTTONDOWN) or
(wParam = WM_MBUTTONUP) or
(wParam = WM_RBUTTONDOWN) or
(wParam = WM_RBUTTONUP) or
(wParam = WM_MOUSEWHEEL) or
(wParam = WM_NCLBUTTONDOWN) or
(wParam = WM_NCLBUTTONUP) or
(wParam = WM_NCMBUTTONDOWN) or
(wParam = WM_NCMBUTTONUP) or
(wParam = WM_NCRBUTTONDOWN) or
(wParam = WM_NCRBUTTONUP)
)
then
begin
//if GetAncestor(PMSLLHOOKSTRUCT(lParam)^.hwnd, GA_ROOT) = locData.WinHandle then
// this would be for LL to have Wheel direction, but I wouldn't have
// target window handle then. Would have to calculate it from mouse pos
// so rather ignore direction
if (GetAncestor(PMouseHookStruct(lParam)^.hwnd, GA_ROOT) = locData.WinHandle) or
((locData.DialogHandle > 0) and (GetAncestor(PMouseHookStruct(lParam)^.hwnd, GA_ROOT) = locData.DialogHandle)) or
((locData.MapWindowHandle > 0) and (GetAncestor(PMouseHookStruct(lParam)^.hwnd, GA_ROOT) = locData.MapWindowHandle))
then
begin
//OutputDebugString('DLL: Just info message to HIDMacros window.');
SendMessage(locData.WinHandle, locData.MsgToSend, wParam , 1);
end
else
begin
//OutputDebugString('DLL: Would ask HIDmacros what to do for MOUSE.');
what2do := SendMessage(locData.WinHandle, locData.MsgToSend, wParam , 0);
if (what2do = -1) then
Kill := True;
end;
end;
if Kill then
Result := 1
else
Result := CallNextHookEx(lHookMou {ignored in API}, Code, wParam, lParam);
end;
end;
end;
function MsgFilterFuncMouLL(Code: Integer; wParam, lParam: Longint): Longint;
var
MMFHandle: THandle;
MMFData: PMMFData;
Kill: boolean;
locData: TMMFData;
dataFetched : boolean;
what2do: Integer;
// ext_code: Cardinal;
begin
Result := 0;
dataFetched := False;
MMFHandle := OpenMMF(MMFName);
if MMFHandle <> 0 then
begin
MMFData := MapMMF(MMFHandle);
if MMFData <> nil then
begin
locData := MMFData^;
dataFetched := True;
UnMapMMF(MMFData);
end;
CloseMMF(MMFHandle);
end;
if (dataFetched) then
begin
if (Code < 0) or (Code <> HC_ACTION) then
Result := CallNextHookEx(lHookMou {ignored in API}, Code, wParam, lParam)
else
begin
Kill := False;
if (locData.WinHandle <> 0) and (locData.MsgToSend > 0)
and (
(wParam = WM_LBUTTONDOWN) or
(wParam = WM_LBUTTONUP) or
(wParam = WM_MBUTTONDOWN) or
(wParam = WM_MBUTTONUP) or
(wParam = WM_RBUTTONDOWN) or
(wParam = WM_RBUTTONUP) or
(wParam = WM_MOUSEWHEEL) or
(wParam = WM_NCLBUTTONDOWN) or
(wParam = WM_NCLBUTTONUP) or
(wParam = WM_NCMBUTTONDOWN) or
(wParam = WM_NCMBUTTONUP) or
(wParam = WM_NCRBUTTONDOWN) or
(wParam = WM_NCRBUTTONUP)
)
then
begin
//if GetAncestor(PMSLLHOOKSTRUCT(lParam)^.hwnd, GA_ROOT) = locData.WinHandle then
// this would be for LL to have Wheel direction, but I wouldn't have
// target window handle then. Would have to calculate it from mouse pos
// so rather ignore direction
//if GetAncestor(PMouseHookStruct(lParam)^.hwnd, GA_ROOT) = locData.WinHandle then
// OutputDebugString('DLL: No user message when message goes to HIDMacros window.')
//else
begin
//OutputDebugString('DLL: Would ask HIDmacros what to do for MOUSE.');
what2do := SendMessage(locData.WinHandle, locData.MsgToSend, wParam , 0);
if (what2do = -1) then
Kill := True;
end;
end;
if Kill then
Result := 1
else
Result := CallNextHookEx(lHookMou {ignored in API}, Code, wParam, lParam);
end;
end;
end;
function SetDialogHandle(Value: HWND): Boolean;
var
MMFHandle: THandle;
MMFData: PMMFData;
begin
Result := False;
MMFHandle := OpenMMF(MMFName);
if MMFHandle <> 0 then
begin
MMFData := MapMMF(MMFHandle);
if MMFData <> nil then
begin
MMFData^.DialogHandle := Value;
UnMapMMF(MMFData);
Result := True;
end;
CloseMMF(MMFHandle);
end;
end;
function SetMapWindowHandle(Value: HWND): Boolean;
var
MMFHandle: THandle;
MMFData: PMMFData;
begin
Result := False;
MMFHandle := OpenMMF(MMFName);
if MMFHandle <> 0 then
begin
MMFData := MapMMF(MMFHandle);
if MMFData <> nil then
begin
MMFData^.MapWindowHandle := Value;
UnMapMMF(MMFData);
Result := True;
end;
CloseMMF(MMFHandle);
end;
end;
initialization
begin
MMFHandle := 0;
MMFData := nil;
end;
finalization
FreeHook;
end.
|
unit FormatDateSQLiteU;
interface
uses
System.SysUtils;
type FormatDateSQLite=class
public
function FormatDate(datef:TDate):string;
end;
implementation
{ StringUtils }
{ FormatDateSQLite }
function FormatDateSQLite.FormatDate(datef: TDate): string;
var Present: TDateTime;
Year, Month, Day, Hour, Min, Sec, MSec: Word;
mois,jour : string;
begin
Present:= Now;
DecodeDate(Present, Year, Month, Day);
if Month>9 then
begin
mois:= IntToStr(Month);
end else
begin
mois:='0'+IntToStr(Month);
end;
if Day>9 then
begin
jour:= IntToStr(Day);
end else
begin
jour:='0'+IntToStr(Day);
end;
result:=IntToStr(Year)+'-'+mois+'-'+jour;
end;
end.
|
unit EdParamToFields;
interface
{$i ..\FIBPlus.inc}
uses
Windows, Messages, SysUtils,
Classes,
{$IFDEF D_XE2}
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls,
Vcl.StdCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls,
{$ENDIF}
DB, uFIBEditorForm
{$IFDEF D6+}
,Variants
{$ENDIF}
;
type
TfrmEdParamToFields = class(TFIBEditorCustomForm)
Memo1: TMemo;
Panel1: TPanel;
Button1: TButton;
Button2: TButton;
Panel2: TPanel;
lstFields: TListBox;
Splitter1: TSplitter;
lstParams: TListBox;
Splitter2: TSplitter;
Button3: TButton;
Button4: TButton;
Panel3: TPanel;
Label1: TLabel;
Label2: TLabel;
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Splitter1Moved(Sender: TObject);
private
FDataSet :TDataSet;
public
{ Public declarations }
end;
var
frmEdParamToFields: TfrmEdParamToFields;
function ShowEdParamToFields(DataSet:TDataSet;CurValues:TStrings):boolean;
implementation
uses pFIBInterfaces, RTTIRoutines;
{$R *.dfm}
function ShowEdParamToFields(DataSet:TDataSet;CurValues:TStrings):boolean;
var i:integer;
ids:IFIBDataSet;
begin
if not ObjSupports(DataSet,IFIBDataSet,ids) then
begin
Result:=False;
Exit;
end;
frmEdParamToFields:= TfrmEdParamToFields.Create(Application);
with frmEdParamToFields do
try
Caption:=DataSet.Name+':Params to Fields Links (Values for NewRecord)';
FDataSet:=DataSet;
Memo1.Lines.Assign(CurValues);
for i:=0 to DataSet.FieldCount-1 do
lstFields.Items.Add(DataSet.Fields[i].FieldName);
for i:=0 to ids.ParamCount-1 do
// lstParams.Items.Add(DataSet.Params[i].Name);
lstParams.Items.Add(ids.ParamName(i));
if lstFields.Items.Count>0 then
lstFields.ItemIndex:=0;
if lstParams.Items.Count>0 then
lstParams.ItemIndex:=0;
Result:=ShowModal=mrOK;
if Result then
CurValues.Assign(Memo1.Lines)
finally
Free
end;
end;
procedure TfrmEdParamToFields.Button3Click(Sender: TObject);
begin
if (lstFields.Items.Count>0) and (lstParams.Items.Count>0) then
Memo1.Lines.Values[lstFields.Items[lstFields.ItemIndex]]:=
lstParams.Items[lstParams.ItemIndex]
;
end;
procedure TfrmEdParamToFields.Button4Click(Sender: TObject);
var
ids:IFIBDataSet;
begin
ObjSupports(FDataSet,IFIBDataSet,ids);
ids.ParseParamToFieldsLinks(Memo1.Lines);
end;
procedure TfrmEdParamToFields.Splitter1Moved(Sender: TObject);
begin
Label2.Left:=lstFields.Width+1
end;
end.
|
unit NtUtils.Security.Sid;
interface
uses
Winapi.WinNt, Winapi.securitybaseapi, NtUtils.Exceptions;
type
ISid = interface
function Sid: PSid;
function EqualsTo(Sid2: PSid): Boolean;
function Parent: ISid;
function Child(Rid: Cardinal): ISid;
function SDDL: String;
function IdentifyerAuthority: PSidIdentifierAuthority;
function Rid: Cardinal;
function SubAuthorities: Byte;
function SubAuthority(Index: Integer): Cardinal;
end;
TSid = class(TInterfacedObject, ISid)
protected
FSid: PSid;
constructor CreateOwned(OwnedSid: PSid; Dummy: Integer = 0);
public
constructor Create(const IdentifyerAuthority: TSidIdentifierAuthority;
SubAuthouritiesArray: TArray<Cardinal> = nil);
constructor CreateCopy(SourceSid: PSid);
constructor CreateNew(const IdentifyerAuthority: TSidIdentifierAuthority;
SubAuthorities: Byte; SubAuthourity0: Cardinal = 0;
SubAuthourity1: Cardinal = 0; SubAuthourity2: Cardinal = 0;
SubAuthourity3: Cardinal = 0; SubAuthourity4: Cardinal = 0);
destructor Destroy; override;
function Sid: PSid;
function EqualsTo(Sid2: PSid): Boolean;
function Parent: ISid;
function Child(Rid: Cardinal): ISid;
function SDDL: String;
function IdentifyerAuthority: PSidIdentifierAuthority;
function Rid: Cardinal;
function SubAuthorities: Byte;
function SubAuthority(Index: Integer): Cardinal;
end;
TGroup = record
SecurityIdentifier: ISid;
Attributes: Cardinal; // SE_GROUP_*
end;
// Validate the buffer and capture a copy as an ISid
function RtlxCaptureCopySid(Buffer: PSid; out Sid: ISid): TNtxStatus;
// Convert a SID to its SDDL representation
function RtlxConvertSidToString(Sid: PSid): String;
// Convert SDDL string to SID
function RtlxConvertStringToSid(SDDL: String; out Sid: ISid): TNtxStatus;
function RtlxStringToSidConverter(const SDDL: String; out Sid: ISid): Boolean;
// Construct a well-known SID
function SddlxGetWellKnownSid(WellKnownSidType: TWellKnownSidType;
out Sid: ISid): TNtxStatus;
implementation
uses
Ntapi.ntdef, Ntapi.ntrtl, Ntapi.ntstatus, Winapi.WinBase, Winapi.Sddl,
DelphiUtils.Strings, System.SysUtils;
{ TSid }
function TSid.Child(Rid: Cardinal): ISid;
var
Buffer: PSid;
Status: NTSTATUS;
i: Integer;
begin
Buffer := AllocMem(RtlLengthRequiredSid(SubAuthorities + 1));
// Copy identifier authority
Status := RtlInitializeSid(Buffer, RtlIdentifierAuthoritySid(FSid),
SubAuthorities + 1);
if not NT_SUCCESS(Status) then
begin
FreeMem(Buffer);
NtxAssert(Status, 'RtlInitializeSid');
end;
// Copy existing sub authorities
for i := 0 to SubAuthorities - 1 do
RtlSubAuthoritySid(Buffer, i)^ := RtlSubAuthoritySid(FSid, i)^;
// Set the last sub authority to the RID
RtlSubAuthoritySid(Buffer, SubAuthorities)^ := Rid;
Result := TSid.CreateOwned(Buffer);
end;
constructor TSid.Create(const IdentifyerAuthority: TSidIdentifierAuthority;
SubAuthouritiesArray: TArray<Cardinal>);
var
Status: NTSTATUS;
i: Integer;
begin
FSid := AllocMem(RtlLengthRequiredSid(Length(SubAuthouritiesArray)));
Status := RtlInitializeSid(FSid, @IdentifyerAuthority, SubAuthorities);
if not NT_SUCCESS(Status) then
begin
FreeMem(FSid);
NtxAssert(Status, 'RtlInitializeSid');
end;
for i := 0 to High(SubAuthouritiesArray) do
RtlSubAuthoritySid(FSid, i)^ := SubAuthouritiesArray[i];
end;
constructor TSid.CreateCopy(SourceSid: PSid);
var
Status: NTSTATUS;
begin
if not RtlValidSid(SourceSid) then
NtxAssert(STATUS_INVALID_SID, 'RtlValidSid');
FSid := AllocMem(RtlLengthSid(SourceSid));
Status := RtlCopySid(RtlLengthSid(SourceSid), FSid, SourceSid);
if not NT_SUCCESS(Status) then
begin
FreeMem(FSid);
NtxAssert(Status, 'RtlCopySid');
end;
end;
constructor TSid.CreateNew(const IdentifyerAuthority: TSidIdentifierAuthority;
SubAuthorities: Byte; SubAuthourity0, SubAuthourity1, SubAuthourity2,
SubAuthourity3, SubAuthourity4: Cardinal);
var
Status: NTSTATUS;
begin
FSid := AllocMem(RtlLengthRequiredSid(SubAuthorities));
Status := RtlInitializeSid(FSid, @IdentifyerAuthority, SubAuthorities);
if not NT_SUCCESS(Status) then
begin
FreeMem(FSid);
NtxAssert(Status, 'RtlInitializeSid');
end;
if SubAuthorities > 0 then
RtlSubAuthoritySid(FSid, 0)^ := SubAuthourity0;
if SubAuthorities > 1 then
RtlSubAuthoritySid(FSid, 1)^ := SubAuthourity1;
if SubAuthorities > 2 then
RtlSubAuthoritySid(FSid, 2)^ := SubAuthourity2;
if SubAuthorities > 3 then
RtlSubAuthoritySid(FSid, 3)^ := SubAuthourity3;
if SubAuthorities > 4 then
RtlSubAuthoritySid(FSid, 4)^ := SubAuthourity4;
end;
constructor TSid.CreateOwned(OwnedSid: PSid; Dummy: Integer);
begin
FSid := OwnedSid;
end;
destructor TSid.Destroy;
begin
FreeMem(FSid);
inherited;
end;
function TSid.EqualsTo(Sid2: PSid): Boolean;
begin
Result := RtlEqualSid(FSid, Sid2);
end;
function TSid.IdentifyerAuthority: PSidIdentifierAuthority;
begin
Result := RtlIdentifierAuthoritySid(FSid);
end;
function TSid.Parent: ISid;
var
Status: NTSTATUS;
Buffer: PSid;
i: Integer;
begin
// The rule is simple: we drop the last sub-authority and create a new SID.
Assert(SubAuthorities > 0);
Buffer := AllocMem(RtlLengthRequiredSid(SubAuthorities - 1));
// Copy identifier authority
Status := RtlInitializeSid(Buffer, RtlIdentifierAuthoritySid(FSid),
SubAuthorities - 1);
if not NT_SUCCESS(Status) then
begin
FreeMem(Buffer);
NtxAssert(Status, 'RtlInitializeSid');
end;
// Copy sub authorities
for i := 0 to RtlSubAuthorityCountSid(Buffer)^ - 1 do
RtlSubAuthoritySid(Buffer, i)^ := RtlSubAuthoritySid(FSid, i)^;
Result := TSid.CreateOwned(Buffer);
end;
function TSid.Rid: Cardinal;
begin
if SubAuthorities > 0 then
Result := SubAuthority(SubAuthorities - 1)
else
Result := 0;
end;
function TSid.SDDL: String;
begin
Result := RtlxConvertSidToString(FSid);
end;
function TSid.Sid: PSid;
begin
Result := FSid;
end;
function TSid.SubAuthorities: Byte;
begin
Result := RtlSubAuthorityCountSid(FSid)^;
end;
function TSid.SubAuthority(Index: Integer): Cardinal;
begin
if (Index >= 0) and (Index < SubAuthorities) then
Result := RtlSubAuthoritySid(FSid, Index)^
else
Result := 0;
end;
{ Functions }
function RtlxCaptureCopySid(Buffer: PSid; out Sid: ISid): TNtxStatus;
begin
if Assigned(Buffer) and RtlValidSid(Buffer) then
begin
Sid := TSid.CreateCopy(Buffer);
Result.Status := STATUS_SUCCESS;
end
else
begin
Result.Location := 'RtlValidSid';
Result.Status := STATUS_INVALID_SID;
end;
end;
function RtlxpApplySddlOverrides(SID: PSid; var SDDL: String): Boolean;
begin
Result := False;
// We override convertion of some SIDs to strings for the sake of readability.
// The result is still a parsable SDDL string.
case RtlIdentifierAuthoritySid(SID).ToInt64 of
// Integrity: S-1-16-x
SECURITY_MANDATORY_LABEL_AUTHORITY_ID:
if RtlSubAuthorityCountSid(SID)^ = 1 then
begin
SDDL := 'S-1-16-' + IntToHexEx(RtlSubAuthoritySid(SID, 0)^, 4);
Result := True;
end;
end;
end;
function RtlxConvertSidToString(Sid: PSid): String;
var
SDDL: UNICODE_STRING;
Buffer: array [0 .. SECURITY_MAX_SID_STRING_CHARACTERS - 1] of WideChar;
begin
Result := '';
if RtlxpApplySddlOverrides(SID, Result) then
Exit;
SDDL.Length := 0;
SDDL.MaximumLength := SizeOf(Buffer);
SDDL.Buffer := Buffer;
if NT_SUCCESS(RtlConvertSidToUnicodeString(SDDL, Sid, False)) then
Result := SDDL.ToString
else
Result := '';
end;
function RtlxConvertStringToSid(SDDL: String; out Sid: ISid): TNtxStatus;
var
Buffer: PSid;
IdAuthorityUInt64: UInt64;
IdAuthority: TSidIdentifierAuthority;
begin
// Despite the fact that RtlConvertSidToUnicodeString can convert SIDs with
// zero sub authorities to SDDL, ConvertStringSidToSidW (for some reason)
// can't convert them back. Fix this behaviour by parsing them manually.
// Expected formats for an SID with 0 sub authorities:
// S-1-(\d+) | S-1-(0x[A-F\d]+)
// where the value fits into a 6-byte (48-bit) buffer
if SDDL.StartsWith('S-1-', True) and
TryStrToUInt64Ex(Copy(SDDL, Length('S-1-') + 1, Length(SDDL)),
IdAuthorityUInt64) and (IdAuthorityUInt64 < UInt64(1) shl 48) then
begin
IdAuthority.FromInt64(IdAuthorityUInt64);
Sid := TSid.CreateNew(IdAuthority, 0);
end
else
begin
// Usual SDDL conversion
Result.Location := 'ConvertStringSidToSidW';
Result.Win32Result := ConvertStringSidToSidW(PWideChar(SDDL), Buffer);
if Result.IsSuccess then
begin
Result := RtlxCaptureCopySid(Buffer, Sid);
LocalFree(Buffer);
end;
end;
end;
function RtlxStringToSidConverter(const SDDL: String; out Sid: ISid): Boolean;
begin
// Use this function with TArrayHelper.Convert<String, ISID>
Result := RtlxConvertStringToSid(SDDL, Sid).IsSuccess;
end;
function SddlxGetWellKnownSid(WellKnownSidType: TWellKnownSidType;
out Sid: ISid): TNtxStatus;
var
Buffer: PSid;
BufferSize: Cardinal;
begin
BufferSize := 0;
Result.Location := 'CreateWellKnownSid';
Result.Win32Result := CreateWellKnownSid(WellKnownSidType, nil, nil,
BufferSize);
if not NtxTryCheckBuffer(Result.Status, BufferSize) then
Exit;
Buffer := AllocMem(BufferSize);
Result.Win32Result := CreateWellKnownSid(WellKnownSidType, nil, Buffer,
BufferSize);
if Result.IsSuccess then
Sid := TSid.CreateOwned(Buffer)
else
FreeMem(Buffer);
end;
end.
|
unit rConsults;
interface
uses SysUtils, Classes, ORNet, ORFn, rCore, uCore, TRPCB, dialogs, uConsults, rTIU, uTIU;
type
TUnresolvedConsults = record
UnresolvedConsultsExist: boolean;
ShowNagScreen: boolean;
end;
{Consult Titles }
function DfltConsultTitle: integer;
function DfltConsultTitleName: string;
function DfltClinProcTitle: integer;
function DfltClinProcTitleName: string;
function IdentifyConsultsClass: integer;
function IdentifyClinProcClass: integer;
procedure ListConsultTitlesShort(Dest: TStrings);
procedure ListClinProcTitlesShort(Dest: TStrings);
function SubSetOfConsultTitles(aResults: TStrings; const StartFrom: string; Direction: Integer; IDNoteTitlesOnly: boolean): Integer;
function SubSetOfClinProcTitles(aResults: TStrings; const StartFrom: string; Direction: Integer; IDNoteTitlesOnly: boolean): Integer;
procedure ResetConsultTitles;
procedure ResetClinProcTitles;
{ Data Retrieval }
procedure GetConsultsList(Dest: TStrings; Early, Late: double;
Service, Status: string; SortAscending: Boolean);
procedure LoadConsultDetail(Dest: TStrings; IEN: integer) ;
function GetCurrentContext: TSelectContext;
procedure SaveCurrentContext(AContext: TSelectContext) ;
procedure DisplayResults(Dest: TStrings; IEN: integer) ;
procedure GetConsultRec(IEN: integer) ;
function ShowSF513(ConsultIEN: integer): TStrings ;
procedure PrintSF513ToDevice(AConsult: Integer; const ADevice: string; ChartCopy: string;
var ErrMsg: string);
function GetFormattedSF513(AConsult: Integer; ChartCopy: string): TStrings;
function UnresolvedConsultsExist: boolean;
procedure GetUnresolvedConsultsInfo;
{list box fillers}
function SubSetOfStatus: TStrings;
function SubSetOfUrgencies(ConsultIEN: integer): TStrings;
function LoadServiceList(Purpose: integer): TStrings ; overload ;
function LoadServiceList(ShowSynonyms: Boolean; StartService, Purpose: integer; ConsultIEN: integer = -1): TStrings ; overload;
function LoadServiceListWithSynonyms(Purpose: integer): TStrings ; overload;
function LoadServiceListWithSynonyms(Purpose, ConsultIEN: integer): TStrings ; overload;
function SubSetOfServices(const StartFrom: string; Direction: Integer): TStrings;
function FindConsult(ConsultIEN: integer): string ;
{user access level functions}
function ConsultServiceUser(ServiceIEN: integer; DUZ: int64): boolean ;
function GetActionMenuLevel(ConsultIEN: integer): TMenuAccessRec ;
{consult result functions}
function GetAssignableMedResults(ConsultIEN: integer): TStrings;
function GetRemovableMedResults(ConsultIEN: integer): TStrings;
function GetDetailedMedicineResults(ResultID: string): TStrings;
procedure AttachMedicineResult(ConsultIEN: integer; ResultID: string; DateTime: TFMDateTime; ResponsiblePerson: int64; AlertTo: string);
procedure RemoveMedicineResult(ConsultIEN: integer; ResultID: string; DateTime: TFMDateTime; ResponsiblePerson: int64);
{Consult Request Actions}
procedure ReceiveConsult(Dest: TStrings; IEN: integer; ReceivedBy: int64; RcptDate: TFMDateTime; Comments: TStrings);
procedure ScheduleConsult(Dest: TStrings; IEN: integer; ScheduledBy: Int64; SchdDate: TFMDateTime; Alert: integer;
AlertTo: string; Comments: TStrings);
procedure DiscontinueConsult(Dest: TStrings; IEN: integer; DiscontinuedBy: int64;
DiscontinueDate: TFMDateTime; Comments: TStrings);
procedure DenyConsult(Dest: TStrings; IEN: integer; DeniedBy: int64;
DenialDate: TFMDateTime; Comments: TStrings);
procedure ForwardConsult(Dest: TStrings; IEN, ToService: integer; Forwarder, AttentionOf: int64;
Urgency: integer; ActionDate: TFMDateTime; Comments: TStrings);
procedure AddComment(Dest: TStrings; IEN: integer; Comments: TStrings; ActionDate: TFMDateTime; Alert: integer;
AlertTo: string) ;
procedure SigFindings(Dest: TStrings; IEN: integer; SigFindingsFlag: string; Comments: TStrings; ActionDate: TFMDateTime;Alert: integer;
AlertTo: string) ;
procedure AdminComplete(Dest: TStrings; IEN: integer; SigFindingsFlag: string; Comments: TStrings;
RespProv: Int64; ActionDate: TFMDateTime; Alert: integer; AlertTo: string) ;
{ Consults Ordering Calls }
function ODForConsults: TStrings;
function ODForProcedures: TStrings;
function ConsultMessage(AnIEN: Integer): string;
function LoadConsultsQuickList: TStrings ;
function GetProcedureServices(ProcIEN: integer): TStrings;
function ConsultCanBeResubmitted(ConsultIEN: integer): string;
function LoadConsultForEdit(ConsultIEN: integer): TEditResubmitRec;
function ResubmitConsult(EditResubmitRec: TEditResubmitRec): string;
function SubSetOfProcedures(const StartFrom: string; Direction: Integer): TStrings;
function GetDefaultReasonForRequest(Service: string; Resolve: Boolean): TStrings;
function ReasonForRequestEditable(Service: string): string;
function GetNewDialog(OrderType: string): string;
function GetServiceIEN(ORIEN: string): string;
function GetProcedureIEN(ORIEN: string): string;
function GetConsultOrderIEN(ConsultIEN: integer): string;
function GetServicePrerequisites(Service: string): TStrings;
procedure GetProvDxMode(var ProvDx: TProvisionalDiagnosis; SvcIEN: string);
function IsProstheticsService(SvcIen: int64) : string;
function GetServiceUserLevel(ServiceIEN, UserDUZ: integer): String ;
{ Clinical Procedures Specific}
function GetSavedCPFields(NoteIEN: integer): TEditNoteRec;
var
uConsultsClass: integer;
uConsultTitles: TConsultTitles;
uClinProcClass: integer;
uClinProcTitles: TClinProcTitles;
uUnresolvedConsults: TUnresolvedConsults;
implementation
uses rODBase;
var
uLastOrderedIEN: Integer;
uLastOrderMsg: string;
{ -------------------------- Consult Titles --------------------------------- }
function IdentifyConsultsClass: integer;
begin
if uConsultsClass = 0 then
uConsultsClass := StrToIntDef(sCallV('TIU IDENTIFY CONSULTS CLASS',[nil]), 0) ;
Result := uConsultsClass;
end;
procedure LoadConsultTitles;
{ private - called one time to set up the uConsultTitles object }
var
x: string;
begin
if uConsultTitles <> nil then Exit;
CallV('TIU PERSONAL TITLE LIST', [User.DUZ, IdentifyConsultsClass]);
RPCBrokerV.Results.Insert(0, '~SHORT LIST'); // insert so can call ExtractItems
uConsultTitles := TConsultTitles.Create;
ExtractItems(uConsultTitles.ShortList, RPCBrokerV.Results, 'SHORT LIST');
x := ExtractDefault(RPCBrokerV.Results, 'SHORT LIST');
uConsultTitles.DfltTitle := StrToIntDef(Piece(x, U, 1), 0);
uConsultTitles.DfltTitleName := Piece(x, U, 2);
end;
procedure ResetConsultTitles;
begin
if uConsultTitles <> nil then
begin
uConsultTitles.Free;
uConsultTitles := nil;
LoadConsultTitles;
end;
end;
function DfltConsultTitle: integer;
{ returns the user defined default Consult title (if any) }
begin
if uConsultTitles = nil then LoadConsultTitles;
Result := uConsultTitles.DfltTitle;
end;
function DfltConsultTitleName: string;
{ returns the name of the user defined default progress note title (if any) }
begin
if uConsultTitles = nil then LoadConsultTitles;
Result := uConsultTitles.DfltTitleName;
end;
procedure ListConsultTitlesShort(Dest: TStrings);
{ returns the user defined list (short list) of Consult titles }
begin
if uConsultTitles = nil then LoadConsultTitles;
Dest.AddStrings(uConsultTitles.ShortList);
if uConsultTitles.ShortList.Count > 0 then
begin
Dest.Add('0^________________________________________________________________________');
Dest.Add('0^ ');
end;
end;
function SubSetOfConsultTitles(aResults: TStrings; const StartFrom: string; Direction: Integer; IDNoteTitlesOnly: boolean): Integer;
{ returns a pointer to a list of consults progress note titles (for use in a long list box)}
begin
CallVistA('TIU LONG LIST CONSULT TITLES', [StartFrom, Direction], aResults);
Result := aResults.Count;
end;
{ -------------------------- Clinical Procedures Titles --------------------------------- }
function IdentifyClinProcClass: integer;
begin
if uClinProcClass = 0 then
uClinProcClass := StrToIntDef(sCallV('TIU IDENTIFY CLINPROC CLASS',[nil]), 0) ;
Result := uClinProcClass;
end;
procedure LoadClinProcTitles;
{ private - called one time to set up the uConsultTitles object }
var
x: string;
begin
if uClinProcTitles <> nil then Exit;
CallV('TIU PERSONAL TITLE LIST', [User.DUZ, IdentifyClinProcClass]);
RPCBrokerV.Results.Insert(0, '~SHORT LIST'); // insert so can call ExtractItems
uClinProcTitles := TClinProcTitles.Create;
ExtractItems(uClinProcTitles.ShortList, RPCBrokerV.Results, 'SHORT LIST');
x := ExtractDefault(RPCBrokerV.Results, 'SHORT LIST');
uClinProcTitles.DfltTitle := StrToIntDef(Piece(x, U, 1), 0);
uClinProcTitles.DfltTitleName := Piece(x, U, 2);
end;
procedure ResetClinProcTitles;
begin
if uClinProcTitles <> nil then
begin
uClinProcTitles.Free;
uClinProcTitles := nil;
LoadClinProcTitles;
end;
end;
function DfltClinProcTitle: integer;
{ returns the user defined default ClinProc title (if any) }
begin
if uClinProcTitles = nil then LoadClinProcTitles;
Result := uClinProcTitles.DfltTitle;
end;
function DfltClinProcTitleName: string;
{ returns the name of the user defined default progress note title (if any) }
begin
if uClinProcTitles = nil then LoadClinProcTitles;
Result := uClinProcTitles.DfltTitleName;
end;
procedure ListClinProcTitlesShort(Dest: TStrings);
{ returns the user defined list (short list) of ClinProc titles }
begin
if uClinProcTitles = nil then LoadClinProcTitles;
Dest.AddStrings(uClinProcTitles.ShortList);
if uClinProcTitles.ShortList.Count > 0 then
begin
Dest.Add('0^________________________________________________________________________');
Dest.Add('0^ ');
end;
end;
function SubSetOfClinProcTitles(aResults: TStrings; const StartFrom: string; Direction: Integer; IDNoteTitlesOnly: boolean): Integer;
{ returns a pointer to a list of clinical procedures titles (for use in a long list box)}
begin
CallVistA('TIU LONG LIST CLINPROC TITLES', [StartFrom, Direction], aResults);
result := aResults.Count;
end;
{--------------- data retrieval ------------------------------------------}
procedure GetConsultsList(Dest: TStrings; Early, Late: double;
Service, Status: string; SortAscending: Boolean);
{ returns a list of consults for a patient, based on selected dates, service, status, or ALL}
var
i: Integer;
x, date1, date2: string;
begin
if Early <= 0 then date1 := '' else date1 := FloatToStr(Early) ;
if Late <= 0 then date2 := '' else date2 := FloatToStr(Late) ;
CallV('ORQQCN LIST', [Patient.DFN, date1, date2, Service, Status]);
with RPCBrokerV do
begin
if Copy(Results[0],1,1) <> '<' then
begin
SortByPiece(TStringList(Results), U, 2);
if not SortAscending then InvertStringList(TStringList(Results));
//SetListFMDateTime('mmm dd,yy', TStringList(Results), U, 2);
for i := 0 to Results.Count - 1 do
begin
x := MakeConsultListItem(Results[i]);
Results[i] := x;
end;
FastAssign(Results, Dest);
end
else
begin
Dest.Clear ;
Dest.Add('-1^No Matches') ;
end ;
end;
end;
procedure LoadConsultDetail(Dest: TStrings; IEN: integer) ;
{ returns the detail of a consult }
begin
CallV('ORQQCN DETAIL', [IEN]);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure DisplayResults(Dest: TStrings; IEN: integer) ;
{ returns the results for a consult }
begin
CallV('ORQQCN MED RESULTS', [IEN]);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure GetConsultRec(IEN: integer);
{returns zero node from file 123, plus a list of all related TIU documents, if any}
const
SHOW_ADDENDA = True;
var
alist: TStrings;
x: string ;
i: integer;
{ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
{ Pieces: EntDt^Pat^OrIFN^PtLoc^ToSvc^From^ReqDt^Typ^Urg^Place^Attn^Sts^LstAct^SndPrv^Rslt^
16 17 18 19 20 21 22
^EntMode^ReqTyp^InOut^SigFnd^TIUPtr^OrdFac^FrgnCslt}
begin
FillChar(ConsultRec, SizeOf(ConsultRec), 0);
CallV('ORQQCN GET CONSULT', [IEN, SHOW_ADDENDA]);
ConsultRec.IEN := IEN ;
alist := TStringList.Create ;
try
FastAssign(RPCBrokerV.Results, aList);
x := alist[0] ;
if Piece(x,u,1) <> '-1' then
with ConsultRec do
begin
EntryDate := MakeFMDateTime(Piece(x, U, 1));
ORFileNumber := StrToIntDef(Piece(x, U, 3),0);
PatientLocation := StrToIntDef(Piece(x, U, 4),0);
OrderingFacility := StrToIntDef(Piece(x, U, 21),0);
ForeignConsultFileNum := StrToIntDef(Piece(x, U, 22),0);
ToService := StrToIntDef(Piece(x, U, 5),0);
From := StrToIntDef(Piece(x, U, 6),0);
RequestDate := MakeFMDateTime(Piece(x, U, 7));
ConsultProcedure := Piece(x, U, 8) ;
Urgency := StrToIntDef(Piece(x, U, 9),0);
PlaceOfConsult := StrToIntDef(Piece(x, U, 10),0);
Attention := StrToInt64Def(Piece(x, U, 11),0);
ORStatus := StrToIntDef(Piece(x, U, 12),0);
LastAction := StrToIntDef(Piece(x, U, 13),0);
SendingProvider := StrToInt64Def(Piece(Piece(x, U, 14),';',1),0);
SendingProviderName := Piece(Piece(x, U, 14),';',2) ;
Result := Piece(x, U, 15) ;
ModeOfEntry := Piece(x, U, 16) ;
RequestType := StrToIntDef(Piece(x, U, 17),0);
InOut := Piece(x, U, 18) ;
Findings := Piece(x, U, 19) ;
TIUResultNarrative := StrToIntDef(Piece(x, U, 20),0);
ClinicallyIndicatedDate := StrToFloatDef(Piece(x, U, 98), 0);
//ProvDiagnosis := Piece(x, U, 23); NO!!!!! Up to 180 Characters!!!!
alist.delete(0) ;
TIUDocuments := TStringList.Create ;
MedResults := TStringList.Create;
if alist.count > 0 then
begin
SortByPiece(TStringList(alist), U, 3);
for i := 0 to alist.Count - 1 do
if Copy(Piece(Piece(alist[i], U, 1), ';', 2), 1, 4) = 'MCAR' then
MedResults.Add(alist[i])
else
TIUDocuments.Add(alist[i]);
end;
end {ConsultRec}
else
ConsultRec.EntryDate := -1 ;
finally
alist.free ;
end ;
end ;
{---------------- list box fillers -----------------------------------}
function SubSetOfStatus: TStrings;
{ returns a pointer to a list of stati (for use in a list box) }
begin
CallV('ORQQCN STATUS', [nil]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function SubSetOfUrgencies(ConsultIEN: integer): TStrings;
{ returns a pointer to a list of urgencies }
begin
CallV('ORQQCN URGENCIES',[ConsultIEN]) ;
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function FindConsult(ConsultIEN: integer): string ;
var
x: string;
begin
x := sCallV('ORQQCN FIND CONSULT',[ConsultIEN]);
Result := MakeConsultListItem(x);
end;
{-----------------consult result functions-----------------------------------}
function GetAssignableMedResults(ConsultIEN: integer): TStrings;
begin
CallV('ORQQCN ASSIGNABLE MED RESULTS', [ConsultIEN]);
Result := RPCBrokerV.Results;
end;
function GetRemovableMedResults(ConsultIEN: integer): TStrings;
begin
CallV('ORQQCN REMOVABLE MED RESULTS', [ConsultIEN]);
Result := RPCBrokerV.Results;
end;
function GetDetailedMedicineResults(ResultID: string): TStrings;
begin
CallV('ORQQCN GET MED RESULT DETAILS', [ResultID]);
Result := RPCBrokerV.Results;
end;
procedure AttachMedicineResult(ConsultIEN: integer; ResultID: string; DateTime: TFMDateTime; ResponsiblePerson: int64; AlertTo: string);
begin
CallV('ORQQCN ATTACH MED RESULTS', [ConsultIEN, ResultID, DateTime, ResponsiblePerson, AlertTo]);
end;
procedure RemoveMedicineResult(ConsultIEN: integer; ResultID: string; DateTime: TFMDateTime; ResponsiblePerson: int64);
begin
CallV('ORQQCN REMOVE MED RESULTS', [ConsultIEN, ResultID, DateTime, ResponsiblePerson]);
end;
{-------------- user access level functions ---------------------------------}
function ConsultServiceUser(ServiceIEN: integer; DUZ: int64): boolean ;
var
i: integer ;
begin
Result := False ;
CallV('ORWU GENERIC', ['',1,'^GMR(123.5,'+IntToStr(ServiceIEN)+',123.3,"B")']) ;
for i:=0 to RPCBrokerV.Results.Count-1 do
if StrToInt64(Piece(RPCBrokerV.Results[i],u,2))=DUZ then result := True ;
end ;
function GetActionMenuLevel(ConsultIEN: integer): TMenuAccessRec ;
var
x: string;
begin
x := sCallV('ORQQCN SET ACT MENUS', [ConsultIEN]) ;
Result.UserLevel := StrToIntDef(Piece(x, U, 1), 1);
Result.AllowMedResulting := (Piece(x, U, 4) = '1');
Result.AllowMedDissociate := (Piece(x, U, 5) = '1');
Result.AllowResubmit := (Piece(x, U, 6) = '1') and (Piece(ConsultCanBeResubmitted(ConsultIEN), U, 1) <> '0');
Result.ClinProcFlag := StrToIntDef(Piece(x, U, 7), CP_NOT_CLINPROC);
Result.IsClinicalProcedure := (Result.ClinProcFlag > CP_NOT_CLINPROC);
end ;
{------------------- Consult request actions -------------------------------}
procedure ReceiveConsult(Dest: TStrings; IEN: integer; ReceivedBy: int64; RcptDate: TFMDateTime; Comments: TStrings);
begin
CallV('ORQQCN RECEIVE', [IEN, ReceivedBy, RcptDate, Comments]);
FastAssign(RPCBrokerV.Results, Dest); {1^Error message' or '0'}
end;
procedure ScheduleConsult(Dest: TStrings; IEN: integer; ScheduledBy: Int64; SchdDate: TFMDateTime; Alert: integer;
AlertTo: string; Comments: TStrings);
begin
CallV('ORQQCN2 SCHEDULE CONSULT', [IEN, ScheduledBy, SchdDate, Alert, AlertTo, Comments]);
FastAssign(RPCBrokerV.Results, Dest); {1^Error message' or '0'}
end;
procedure DenyConsult(Dest: TStrings; IEN: integer; DeniedBy: int64;
DenialDate: TFMDateTime; Comments: TStrings);
begin
CallV('ORQQCN DISCONTINUE', [IEN, DeniedBy, DenialDate,'DY',Comments]);
FastAssign(RPCBrokerV.Results, Dest); {1^Error message' or '0'}
end;
procedure DiscontinueConsult(Dest: TStrings; IEN: integer; DiscontinuedBy: int64;
DiscontinueDate: TFMDateTime; Comments: TStrings);
begin
CallV('ORQQCN DISCONTINUE', [IEN, DiscontinuedBy, DiscontinueDate,'DC',Comments]);
FastAssign(RPCBrokerV.Results, Dest); {1^Error message' or '0'}
end;
procedure ForwardConsult(Dest: TStrings; IEN, ToService: integer; Forwarder, AttentionOf: int64; Urgency: integer;
ActionDate: TFMDateTime; Comments: TStrings);
begin
CallV('ORQQCN FORWARD', [IEN, ToService, Forwarder, AttentionOf, Urgency, ActionDate, Comments]);
FastAssign(RPCBrokerV.Results, Dest); {1^Error message' or '0'}
end ;
procedure AddComment(Dest: TStrings; IEN: integer; Comments: TStrings; ActionDate: TFMDateTime; Alert: integer;
AlertTo: string) ;
begin
CallV('ORQQCN ADDCMT', [IEN, Comments, Alert, AlertTo, ActionDate]);
FastAssign(RPCBrokerV.Results, Dest); {1^Error message' or '0'}
end ;
procedure AdminComplete(Dest: TStrings; IEN: integer; SigFindingsFlag: string; Comments: TStrings;
RespProv: Int64; ActionDate: TFMDateTime; Alert: integer; AlertTo: string) ;
begin
CallV('ORQQCN ADMIN COMPLETE', [IEN, SigFindingsFlag, Comments, RespProv, Alert, AlertTo, ActionDate]);
FastAssign(RPCBrokerV.Results, Dest); {1^Error message' or '0'}
end ;
procedure SigFindings(Dest: TStrings; IEN: integer; SigFindingsFlag: string; Comments: TStrings; ActionDate: TFMDateTime; Alert: integer;
AlertTo: string) ;
begin
CallV('ORQQCN SIGFIND', [IEN, SigFindingsFlag, Comments, Alert, AlertTo, ActionDate]);
FastAssign(RPCBrokerV.Results, Dest); {1^Error message' or '0'}
end ;
//================== Ordering functions ===================================
function ODForConsults: TStrings;
{ Returns init values for consults dialog. The results must be used immediately. }
begin
CallV('ORWDCN32 DEF', ['C']);
Result := RPCBrokerV.Results;
end;
function ODForProcedures: TStrings;
{ Returns init values for procedures dialog. The results must be used immediately. }
begin
CallV('ORWDCN32 DEF', ['P']);
Result := RPCBrokerV.Results;
end;
function SubSetOfProcedures(const StartFrom: string; Direction: Integer): TStrings;
begin
begin
CallV('ORWDCN32 PROCEDURES', [StartFrom, Direction]);
Result := RPCBrokerV.Results;
end;
end;
function LoadServiceList(Purpose: integer): TStrings ;
// Purpose: 0=display all services, 1=forward or order from possible services
begin
Callv('ORQQCN SVCTREE',[Purpose]) ;
MixedCaseList(RPCBrokerV.Results) ;
Result := RPCBrokerV.Results;
end ;
function LoadServiceList(ShowSynonyms: Boolean; StartService, Purpose: Integer; ConsultIEN: integer = -1): TStrings ;
// Param 1 = Starting service (1=All Services)
// Param 2 = Purpose: 0=display all services, 1=forward or order from possible services
// Param 3 = Show synonyms
// Param 4 = Consult IEN
begin
if ConsultIEN > -1 then
Callv('ORQQCN SVC W/SYNONYMS',[StartService, Purpose, ShowSynonyms, ConsultIEN])
else
Callv('ORQQCN SVC W/SYNONYMS',[StartService, Purpose, ShowSynonyms]) ;
MixedCaseList(RPCBrokerV.Results) ;
Result := RPCBrokerV.Results;
end ;
function LoadServiceListWithSynonyms(Purpose: integer): TStrings ;
// Param 1 = Starting service (1=All Services)
// Param 2 = Purpose: 0=display all services, 1=forward or order from possible services
// Param 3 = Show synonyms
begin
Callv('ORQQCN SVC W/SYNONYMS',[1, Purpose, True]) ;
MixedCaseList(RPCBrokerV.Results) ;
Result := RPCBrokerV.Results;
end ;
function LoadServiceListWithSynonyms(Purpose, ConsultIEN: integer): TStrings ;
// Param 1 = Starting service (1=All Services)
// Param 2 = Purpose: 0=display all services, 1=forward or order from possible services
// Param 3 = Show synonyms
// Param 4 = Consult IEN
begin
Callv('ORQQCN SVC W/SYNONYMS',[1, Purpose, True, ConsultIEN]) ;
MixedCaseList(RPCBrokerV.Results) ;
Result := RPCBrokerV.Results;
end ;
function SubSetOfServices(const StartFrom: string; Direction: Integer): TStrings;
// used only on consults order dialog for service long combo box, which needs to include quick orders
begin
CallV('ORQQCN SVCLIST', [StartFrom, Direction]);
Result := RPCBrokerV.Results;
end;
function LoadConsultsQuickList: TStrings ;
begin
Callv('ORWDXQ GETQLST',['CSLT', 'Q']) ;
Result := RPCBrokerV.Results;
end ;
function ShowSF513(ConsultIEN: integer): TStrings ;
var
x: string;
i: integer;
begin
CallV('ORQQCN SHOW SF513',[ConsultIEN]) ;
if RPCBrokerV.Results.Count > 0 then
begin
x := RPCBrokerV.Results[0];
i := Pos('-', x);
x := Copy(x, i, 999);
RPCBrokerV.Results[0] := x;
end;
Result := RPCBrokerV.Results;
end ;
procedure PrintSF513ToDevice(AConsult: Integer; const ADevice: string; ChartCopy: string;
var ErrMsg: string);
{ prints a SF 513 on the selected device }
begin
ErrMsg := sCallV('ORQQCN PRINT SF513', [AConsult, ChartCopy, ADevice]);
// if Piece(ErrMsg, U, 1) = '0' then ErrMsg := '' else ErrMsg := Piece(ErrMsg, U, 2);
end;
function GetFormattedSF513(AConsult: Integer; ChartCopy: string): TStrings;
begin
CallV('ORQQCN SF513 WINDOWS PRINT',[AConsult, ChartCopy]);
Result := RPCBrokerV.Results;
end;
function UnresolvedConsultsExist: boolean;
begin
Result := (sCallV('ORQQCN UNRESOLVED', [Patient.DFN]) = '1');
end;
procedure GetUnresolvedConsultsInfo;
var
x: string;
begin
x := sCallV('ORQQCN UNRESOLVED', [Patient.DFN]);
with uUnresolvedConsults do
begin
UnresolvedConsultsExist := (Piece(x, U, 1) = '1');
ShowNagScreen := (Piece(x, U, 2) = '1');
end;
end;
function ConsultMessage(AnIEN: Integer): string;
begin
if AnIEN = uLastOrderedIEN then Result := uLastOrderMsg else
begin
Result := sCallV('ORWDCN32 ORDRMSG', [AnIEN]);
uLastOrderedIEN := AnIEN;
uLastOrderMsg := Result;
end;
end;
function GetProcedureIEN(ORIEN: string): string;
begin
Result := sCallV('ORQQCN GET PROC IEN', [ORIEN]);
end;
function GetProcedureServices(ProcIEN: integer): TStrings;
begin
CallV('ORQQCN GET PROC SVCS',[ProcIEN]) ;
Result := RPCBrokerV.Results;
end;
function ConsultCanBeResubmitted(ConsultIEN: integer): string;
begin
Result := sCallV('ORQQCN CANEDIT', [ConsultIEN]);
end;
function LoadConsultForEdit(ConsultIEN: integer): TEditResubmitRec;
var
Dest: TStringList;
EditRec: TEditResubmitRec;
begin
Dest := TStringList.Create;
try
tCallV(Dest, 'ORQQCN LOAD FOR EDIT',[ConsultIEN]) ;
with EditRec do
begin
Changed := False;
IEN := ConsultIEN;
ToService := StrToIntDef(Piece(ExtractDefault(Dest, 'SERVICE'), U, 2), 0);
RequestType := Piece(ExtractDefault(Dest, 'TYPE'), U, 3);
OrderableItem := StrToIntDef(Piece(ExtractDefault(Dest, 'PROCEDURE'), U, 1), 0);
ConsultProc := Piece(ExtractDefault(Dest, 'PROCEDURE'), U, 3);
ConsultProcName := Piece(ExtractDefault(Dest, 'PROCEDURE'), U, 2);
Urgency := StrToIntDef(Piece(ExtractDefault(Dest, 'URGENCY'), U, 3), 0);
UrgencyName := Piece(ExtractDefault(Dest, 'URGENCY'), U, 2);
ClinicallyIndicatedDate := StrToFloatDef(Piece(ExtractDefault(Dest, 'CLINICALLY'), U, 2), 0);
Place := Piece(ExtractDefault(Dest, 'PLACE'), U, 1);
PlaceName := Piece(ExtractDefault(Dest, 'PLACE'), U, 2);
Attention := StrToInt64Def(Piece(ExtractDefault(Dest, 'ATTENTION'), U, 1), 0);
AttnName := Piece(ExtractDefault(Dest, 'ATTENTION'), U, 2);
InpOutp := Piece(ExtractDefault(Dest, 'CATEGORY'), U, 1);
ProvDiagnosis := Piece(ExtractDefault(Dest, 'DIAGNOSIS'), U, 1);
ProvDxCode := Piece(ExtractDefault(Dest, 'DIAGNOSIS'), U, 2);
ProvDxCodeInactive := (Piece(ExtractDefault(Dest, 'DIAGNOSIS'), U, 3) = '1');
RequestReason := TStringList.Create;
ExtractText(RequestReason, Dest, 'REASON');
LimitStringLength(RequestReason, 74);
DenyComments := TStringList.Create;
ExtractText(DenyComments, Dest, 'DENY COMMENT');
OtherComments := TStringList.Create;
ExtractText(OtherComments, Dest, 'ADDED COMMENT');
NewComments := TStringList.Create;
end;
Result := EditRec;
finally
Dest.Free;
end;
end;
function ResubmitConsult(EditResubmitRec: TEditResubmitRec): string;
var
i: integer;
begin
LockBroker;
try
with RPCBrokerV, EditResubmitRec do
begin
ClearParameters := True;
RemoteProcedure := 'ORQQCN RESUBMIT';
Param[0].PType := literal;
Param[0].Value := IntToStr(IEN);
Param[1].PType := list;
with Param[1] do
begin
if ToService > 0 then
Mult['1'] := 'GMRCSS^' + IntToStr(ToService);
if ConsultProc <> '' then
Mult['2'] := 'GMRCPROC^' + ConsultProc ;
if Urgency > 0 then
Mult['3'] := 'GMRCURG^' + IntToStr(Urgency);
if Length(Place) > 0 then
Mult['4'] := 'GMRCPL^' + Place;
if Attention > 0 then
Mult['5'] := 'GMRCATN^' + IntToStr(Attention)
else if Attention = -1 then
Mult['5'] := 'GMRCATN^' + '@';
if RequestType <> '' then
Mult['6'] := 'GMRCRQT^' + RequestType;
if Length(InpOutP) > 0 then
Mult['7'] := 'GMRCION^' + InpOutp;
if Length(ProvDiagnosis) > 0 then
Mult['8'] := 'GMRCDIAG^' + ProvDiagnosis + U + ProvDxCode;
if RequestReason.Count > 0 then
begin
Mult['9'] := 'GMRCRFQ^20';
for i := 0 to RequestReason.Count - 1 do
Mult['9,' + IntToStr(i+1)] := RequestReason.Strings[i];
end;
if NewComments.Count > 0 then
begin
Mult['10'] := 'COMMENT^';
for i := 0 to NewComments.Count - 1 do
Mult['10,' + IntToStr(i+1)] := NewComments.Strings[i];
end;
if ClinicallyIndicatedDate > 0 then
Mult['11'] := 'GMRCERDT^' + FloatToStr(ClinicallyIndicatedDate); //wat renamed v28
end;
CallBroker;
Result := '0';
//Result := Results[0];
end;
finally
UnlockBroker;
end;
end;
function GetCurrentContext: TSelectContext;
var
x: string;
AContext: TSelectContext;
begin
x := sCallV('ORQQCN2 GET CONTEXT', [User.DUZ]) ;
with AContext do
begin
Changed := True;
BeginDate := Piece(x, ';', 1);
EndDate := Piece(x, ';', 2);
Status := Piece(x, ';', 3);
Service := Piece(x, ';', 4);
GroupBy := Piece(x, ';', 5);
Ascending := (Piece(x, ';', 6) = '1');
end;
Result := AContext;
end;
procedure SaveCurrentContext(AContext: TSelectContext) ;
var
x: string;
begin
with AContext do
begin
SetPiece(x, ';', 1, BeginDate);
SetPiece(x, ';', 2, EndDate);
SetPiece(x, ';', 3, Status);
SetPiece(x, ';', 4, Service);
SetPiece(x, ';', 5, GroupBy);
SetPiece(x, ';', 6, BOOLCHAR[Ascending]);
end;
CallV('ORQQCN2 SAVE CONTEXT', [x]);
end;
function GetDefaultReasonForRequest(Service: string; Resolve: Boolean): TStrings;
begin
CallV('ORQQCN DEFAULT REQUEST REASON',[Service, Patient.DFN, Resolve]) ;
Result := RPCBrokerV.Results;
end;
function ReasonForRequestEditable(Service: string): string;
begin
Result := sCallV('ORQQCN EDIT DEFAULT REASON', [Service]);
end;
function GetServicePrerequisites(Service: string): TStrings;
begin
CallV('ORQQCN2 GET PREREQUISITE',[Service, Patient.DFN]) ;
Result := RPCBrokerV.Results;
end;
function GetNewDialog(OrderType: string): string;
{ get dialog for new consults}
begin
Result := sCallV('ORWDCN32 NEWDLG', [OrderType, Encounter.Location]);
end;
function GetServiceIEN(ORIEN: string): string;
begin
Result := sCallV('ORQQCN GET SERVICE IEN', [ORIEN]);
end;
procedure GetProvDxMode(var ProvDx: TProvisionalDiagnosis; SvcIEN: string);
var
x: string;
begin
x := sCallV('ORQQCN PROVDX', [SvcIEN]);
ProvDx.Reqd := Piece(x, U, 1);
ProvDx.PromptMode := Piece(x, U, 2);
end;
function GetConsultOrderIEN(ConsultIEN: integer): string;
begin
Result := sCallV('ORQQCN GET ORDER NUMBER', [ConsultIEN]);
end;
function GetSavedCPFields(NoteIEN: integer): TEditNoteRec;
var
x: string;
AnEditRec: TEditNoteRec;
begin
x := sCallV('ORWTIU GET SAVED CP FIELDS', [NoteIEN]);
with AnEditRec do
begin
Author := StrToInt64Def(Piece(x, U, 1), 0);
Cosigner := StrToInt64Def(Piece(x, U, 2), 0);
ClinProcSummCode := StrToIntDef(Piece(x, U, 3), 0);
ClinProcDateTime := StrToFMDateTime(Piece(x, U, 4));
Title := StrToIntDef(Piece(x, U, 5), 0);
DateTime := StrToFloatDef(Piece(x, U, 6), 0);
end;
Result := AnEditRec;
end;
function IsProstheticsService(SvcIen : int64) : string; //wat v28
begin
Result := sCallV('ORQQCN ISPROSVC', [SvcIen]);
end;
function GetServiceUserLevel(ServiceIEN, UserDUZ: integer): String ;
// Param 1 = IEN of service
// Param 2 = Users DUZ (currently can be null)
begin
Result := sCallV('ORQQCN GET USER AUTH',[ServiceIEN]) ;
end;
initialization
uLastOrderedIEN := 0;
uLastOrderMsg := '';
uConsultsClass := 0;
uClinProcClass := 0;
finalization
if uConsultTitles <> nil then uConsultTitles.Free;
if uClinProcTitles <> nil then uClinProcTitles.Free;
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;
VL: TLineR;
VS, VR, VP, VH: TStationR;
I, J: Integer;
begin
// initialization
with FNetwork.GetStationSet do
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;
FDir := nil;
FDist := Maxint;
end{with};
end{for};
with A.Data as TStationData do
begin
FState := ssGrey;
FParent := nil;
FLine := nil;
FDir := nil;
FDist := 0;
end;
VQueue := TObjectList.Create(false);
VQueue.Add(A);
// main loop
while (VQueue.Count > 0) and ((B.Data as TStationData).FState <> ssGrey) do
begin
VS := VQueue.Items[0] as TStationR;
VQueue.Delete(0);
with FNetwork.GetLineSet do
for I := 0 to Count - 1 do
begin
VL := GetLine(I);
J := VL.IndexOf(VS);
if J <> -1 then
begin {station VS occurs on line VL; trace its successors on VL}
if J < VL.Count - 1 then
begin {trace following stop on line}
VR := VL.Stop(J + 1);
with VR.Data as TStationData do
if FState = ssWhite then
begin
FState := ssGrey;
FParent := VS;
FLine := VL;
FDir := VL.Stop(VL.Count - 1);
FDist := (VS.Data as TStationData).FDist + 1;
VQueue.Add(VR)
end{if};
end{if};
if 0 < J then
begin {trace preceding stop on line}
VR := VL.Stop(J - 1);
with VR.Data as TStationData do
if FState = ssWhite then
begin
FState := ssGrey;
FParent := VS;
FLine := VL;
FDir := VL.Stop(0);
FDist := (VS.Data as TStationData).FDist + 1;
VQueue.Add(VR)
end{if};
end{if};
end{if};
end{for};
(VS.Data as TStationData).FState := ssBlack;
end{while};
// construct route
VRoute := TRouteRW.Create;
if (B.Data as TStationData).FState = ssGrey then
begin {B is reachable; add route segments to VRoute}
VP := B;
while VP <> nil do
begin
VH := (VP.Data as TStationData).FParent;
while (VH <> nil) and
((VH.Data as TStationData).FLine = (VP.Data as TStationData).FLine)
do VH := (VH.Data as TStationData).FParent;
if VH <> nil then
begin
VSegment :=
TRouteSegmentR.Create(
VH,
(VP.Data as TStationData).FLine,
(VP.Data as TStationData).FDir,
VP);
VRoute.Insert(0, VSegment);
end{if};
VP := VH
end{while};
end{if};
// finalization
with FNetwork.GetStationSet do
for I := 0 to Count - 1 do
GetStation(I).Data.Free;
VQueue.Free;
Result := VRoute;
end;
function TMinStopsPlanner.FindRoutes(A, B: TStationR;
AOption: TSearchOption): TRouteSet;
begin
Result := TRouteSet.Create;
Result.Add(FindRoute(A, B, AOption));
end;
end.
|
unit uZeichnerFarben;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils, uZeichnerBase, fgl, uFarben;
type TZeichnerFarben = class(TZeichnerBase)
private
FFarben: TFarben;
procedure aktionSchrittMtLinie(list: TStringList);
public
constructor Create(zeichenPara: TZeichenParameter); override;
destructor Destroy; override;
end;
implementation
uses uMatrizen,dglOpenGL;
procedure schritt(l:Real;Spur:BOOLEAN;r:Real;g:Real;b:Real);
begin
if Spur then
begin
glMatrixMode(GL_ModelView);
UebergangsmatrixObjekt_Kamera_Laden;
glColor3f(r,g,b);
glLineWidth(0.01);
glBegin(GL_LINES);
glVertex3f(0,0,0);glVertex3f(0,l,0);
glEnd;
end;
ObjInEigenKOSVerschieben(0,l,0)
end;
procedure TZeichnerFarben.aktionSchrittMtLinie(list: TStringList);
var m,colorIdx: Cardinal; farbe: TFarbe;
begin
colorIdx := StrToInt(list[0]); m := 50;
farbe := FFarben.gibFarbe(colorIdx);
schritt(1/m,true,farbe.r,farbe.g,farbe.b);
end;
constructor TZeichnerFarben.Create(zeichenPara: TZeichenParameter);
begin
inherited;
FName := 'ZeichnerFarben';
FFarben.initColor;
FVersandTabelle.AddOrSetData('F',aktionSchrittMtLinie);
end;
destructor TZeichnerFarben.Destroy;
begin
FreeAndNil(FName);
inherited;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.Touch.GestureConsts;
interface
resourcestring
// RTS engine
SAddIStylusAsyncPluginError = 'Unable to add IStylusAsyncPlugin: %s';
SAddIStylusSyncPluginError = 'Unable to add IStylusSyncPlugin: %s';
SRemoveIStylusAsyncPluginError = 'Unable to remove IStylusAsyncPlugin: %s';
SRemoveIStylusSyncPluginError = 'Unable to remove IStylusSyncPlugin: %s';
SStylusHandleError = 'Unable to get or set window handle: %s';
SStylusEnableError = 'Unable to enable or disable IRealTimeStylus: %s';
SEnableRecognizerError = 'Unable to enable or disable IGestureRecognizer: %s';
SInitialGesturePointError = 'Unable to retrieve initial gesture point';
SSetStylusGestureError = 'Unable to set stylus gestures: %s';
// TGesturePreview
SStartPoint = 'Start point';
SStartPoints = 'Start points';
// TGestureListView
SNameColumn = 'Name';
// TGestureManager
SInvalidStreamFormat = 'Invalid stream format';
SControlNotFound = 'Control not found';
STooManyRegisteredGestures = 'Too many registered gestures';
SRegisteredGestureNotFound = 'The following registered gestures were not found:'#13#10#13#10'%s';
SDuplicateRegisteredGestureName = 'A registered gesture named %s already exists';
SDuplicateRecordedGestureName = 'A recorded gesture named %s already exists';
SInvalidGestureID = 'Invalid gesture ID (%d)';
SInvalidGestureName = 'Invalid gesture name (%s)';
// TGestureCollectionItem
SDuplicateGestureName = 'Duplicate gesture name: %s';
implementation
end.
|
unit ExPolygon1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
//GLS
GLScene, GLObjects, GLGeomObjects, GLTexture, GLMultiPolygon,
GLVectorGeometry, GLWin32Viewer, GLCrossPlatform, GLMaterial,
GLCoordinates, GLBaseClasses;
type
TVektor = record
x,y,z : Double;
end;
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
GLLightSource1: TGLLightSource;
GLLightSource2: TGLLightSource;
Container: TGLDummyCube;
CameraTarget: TGLDummyCube;
Camera: TGLCamera;
GLMaterialLibrary1: TGLMaterialLibrary;
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure FormShow(Sender: TObject);
private
mx,my : Integer;
FPlane : array[0..5] of TGLMultiPolygon;
FDY: Double;
FDX: Double;
FDZ: Double;
function GetPlane(Side: Integer): TGLMultiPolygon;
procedure SetDX(const Value: Double);
procedure SetDY(const Value: Double);
procedure SetDZ(const Value: Double);
procedure CreatePanel;
procedure AddMaterial(Obj:TGLSceneObject);
procedure ReDraw;
function TransformToPlane(Side:Integer; x,y,z:Double):TVektor; overload;
function TransformToPlane(Side:Integer; v:TVektor):TVektor; overload;
public
{ Public-Deklarationen }
procedure MakeHole(Side:Integer; X,Y,Z,D,T:Double; Phi:Double=0; Rho:Double=0);
property Plane[Side:Integer]:TGLMultiPolygon read GetPlane;
property DX:Double read FDX write SetDX;
property DY:Double read FDY write SetDY;
property DZ:Double read FDZ write SetDZ;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
function Vektor(x,y,z:Double):TVektor;
begin
result.x := x;
result.y := y;
result.z := z;
end;
const
cOpposite : array[0..5] of Integer = (5,3,4,1,2,0);
procedure TForm1.MakeHole(Side: Integer; X, Y, Z, D, T, Phi, Rho: Double);
var
R : Double;
Dum : TGLDummyCube;
Cyl : TGLCylinder;
through : Boolean;
begin
Dum := TGLDummyCube.Create(nil);
Dum.Position.x := X;
Dum.Position.y := Y;
Dum.Position.z := Z;
case Side of
0 : Dum.PitchAngle := -90;
1 : Dum.RollAngle := 90;
2 : Dum.RollAngle := 180;
3 : Dum.RollAngle := 270;
4 : Dum.RollAngle := 0;
5 : Dum.PitchAngle := 90;
end;
Dum.PitchAngle := Dum.PitchAngle + Rho;
Dum.RollAngle := Dum.RollAngle + Phi;
R := 0.5*D;
through := true;
case Side of
0 : if (Z-T)<=0 then T := Z else through := false;
1 : if (X+T)>=DX then T := DX-X else through := false;
2 : if (Y+T)>=DY then T := DY-Y else through := false;
3 : if (X-T)<=0 then T := X else through := false;
4 : if (Y-T)<=0 then T := Y else through := false;
5 : if (Z+T)>=DZ then T := DZ-Z else through := false;
end;
Cyl := TGLCylinder.Create(nil);
AddMaterial(Cyl);
Cyl.Position.x := 0;
Cyl.Position.y := - 0.5*T;
Cyl.Position.z := 0;
Cyl.Height := T;
Cyl.BottomRadius := R;
Cyl.TopRadius := R;
Cyl.NormalDirection := ndInside;
if through then Cyl.Parts := [cySides]
else Cyl.Parts := [cySides,cyBottom];
Dum.AddChild(Cyl);
Container.AddChild(Dum);
Plane[Side].Contours.Add.Nodes.AddXYArc(R/cos(Phi*c180divPi),R,0,360,16, AffineVectorMake(X,Y,0));
if through then
Plane[cOpposite[Side]].Contours.Add.Nodes.AddXYArc(R/cos(Phi*c180divPi),R,0,360,16, AffineVectorMake(X,Y,0));
end;
procedure TForm1.CreatePanel;
var
I : Integer;
function MakePlane(X,Y,Z,P,T,W,H:Double):TGLMultiPolygon;
begin
result := TGLMultiPolygon.Create(nil);
result.Material.MaterialLibrary := GLMaterialLibrary1;
result.Material.LibMaterialName := 'MatSurface';
result.Parts := [ppTop];
result.AddNode(0,0,0,0);
result.AddNode(0,W,0,0);
result.AddNode(0,W,H,0);
result.AddNode(0,0,H,0);
result.Position.x := X;
result.Position.y := Y;
result.Position.z := Z;
result.PitchAngle := P;
result.TurnAngle := T;
end;
begin
Container.DeleteChildren;
FPlane[2] := MakePlane( 0, 0, 0, -90, 0,DX,DZ);
FPlane[3] := MakePlane(DX, 0, 0, -90, 90,DY,DZ);
FPlane[4] := MakePlane(DX,DY, 0, -90,180,DX,DZ);
FPlane[1] := MakePlane( 0,DY, 0, -90,270,DY,DZ);
FPlane[5] := MakePlane( 0,DY, 0,-180, 0,DX,DY);
FPlane[0] := MakePlane( 0, 0,DZ, 0, 0,DX,DY);
for I:=0 to 5 do Container.AddChild(FPlane[I]);
end;
function TForm1.GetPlane(Side: Integer): TGLMultiPolygon;
begin
result := FPlane[Side];
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x; my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift<>[] then
Camera.MoveAroundTarget(my-y, mx-x);
mx:=x; my:=y;
end;
procedure TForm1.SetDX(const Value: Double);
begin
FDX := Value;
Container.Position.X := -0.5*Value;
end;
procedure TForm1.SetDY(const Value: Double);
begin
FDY := Value;
Container.Position.Y := -0.5*Value;
end;
procedure TForm1.SetDZ(const Value: Double);
begin
FDZ := Value;
Container.Position.Z := -0.5*Value;
end;
procedure TForm1.AddMaterial(Obj: TGLSceneObject);
begin
Obj.Material.MaterialLibrary := GLMaterialLibrary1;
Obj.Material.LibMaterialName := 'MatInner';
end;
procedure TForm1.ReDraw;
begin
DX := 600;
DY := 400;
DZ := 19;
CreatePanel;
MakeHole(0,0.5*DX,0.5*DY,DZ,50,DZ);
end;
procedure TForm1.FormShow(Sender: TObject);
begin
Redraw;
end;
function TForm1.TransformToPlane(Side: Integer; x, y, z: Double): TVektor;
begin
case Side of
0 : result := Vektor(x,y,z-DZ);
1 : result := Vektor(DY-y,z,x);
2 : result := Vektor(x,z,-y);
3 : result := Vektor(y,z,DX-x);
4 : result := Vektor(DX-x,z,DY-y);
5 : result := Vektor(x,DY-y,z);
else result := Vektor(x,y,z);
end;
end;
function TForm1.TransformToPlane(Side: Integer; v: TVektor): TVektor;
begin
result := TransformToPlane(Side,v.x,v.y,v.z);
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ XML Data File to XML Schema Translator }
{ }
{ Copyright (c) 2001-2002 Borland Software Corporation }
{ }
{*******************************************************}
unit XMLDataToSchema;
interface
uses Variants, SysUtils, Classes, xmldom, XMLDoc, XMLIntf, XMLSchema;
type
{ TXMLDataTranslator }
TXMLDataImporter = class(TXMLSchemaTranslator)
private
FXMLDoc: IXMLDocument;
protected
function AddComplexType(const Node: IXMLNode): DOMString;
function GetDataType(const Node: IXMLNode): DOMString;
function IsComplexType(const Node: IXMLNode): Boolean;
procedure Translate(const FileName: WideString; const SchemaDef: IXMLSchemaDef); override;
procedure ValidateExistingType(const ExistingType: IXMLComplexTypeDef;
const Node: IXMLNode);
{ Data member access }
property XMLDoc: IXMLDocument read FXMLDoc;
end;
const
SXMLDataExtension = '.xml';
implementation
uses XMLSchemaTags, XMLConst;
const
TypeSuffix = 'Type';
var
TranslatorFactory: IXMLSchemaTranslatorFactory;
{ TXMLDataImporter }
function TXMLDataImporter.GetDataType(const Node: IXMLNode): DOMString;
const
Digits = ['0'..'9'];
var
Len, I: Integer;
Value: string;
begin
{ Basic routine to try and determine the data type of a node's value.
Currently only tries to detect integers and decimals }
if (Node.NodeType = ntAttribute) or Node.IsTextElement then
Value := VarToStr(Node.NodeValue);
if Value = '' then
begin
Result := xsdString;
Exit;
end;
Len := Length(Value);
Result := '';
for I := 1 to Len do
if not (Value[I] in (Digits + [DecimalSeparator])) then
begin
Result := xsdString;
Exit;
end else if Value[I] = DecimalSeparator then
Result := xsdDecimal;
if Result = '' then
Result := xsdInteger;
end;
function TXMLDataImporter.IsComplexType(const Node: IXMLNode): Boolean;
var
I: Integer;
begin
Result := Node.AttributeNodes.Count > 0;
if not Result then
for I := 0 to Node.ChildNodes.Count - 1 do
if Node.ChildNodes[I].NodeType = ntElement then
begin
Result := True;
Break;
end;
end;
function TXMLDataImporter.AddComplexType(const Node: IXMLNode): DOMString;
function MakeTypeName(const Name: string): DOMString;
var
TypePos: Integer;
begin
TypePos := Pos(TypeSuffix, Name);
if (TypePos = 0) or (TypePos <> (Length(Name) + 1 - Length(TypeSuffix))) then
Result := Name + TypeSuffix
else
Result := Name;
end;
procedure ProcessChildNodes(ComplexTypeDef: IXMLComplexTypeDef);
var
I: Integer;
BaseName, ChildType: DOMString;
ChildNode: IXMLNode;
ElementDef: IXMLElementDef;
begin
with ComplexTypeDef do
for I := 0 to Node.ChildNodes.Count - 1 do
begin
ChildNode := Node.ChildNodes[I];
if ChildNode.NodeType = ntElement then
begin
BaseName := ExtractLocalName(ChildNode.NodeName);
ElementDef := ElementDefs.Find(BaseName);
if not Assigned(ElementDef) then
begin
if IsComplexType(ChildNode) then
ChildType := AddComplexType(ChildNode) else
ChildType := GetDataType(ChildNode);
ElementDefs.Add(BaseName, ChildType);
end else
begin
ElementDef.MaxOccurs := SUnbounded;
{ Determine if this node is different than any we've already seen }
if ElementDef.DataType.IsComplex then
ValidateExistingType(ElementDef.DataType as IXMLComplexTypeDef,
ChildNode);
end;
end;
end;
end;
procedure ProcessAttributes(ComplexTypeDef: IXMLComplexTypeDef);
var
I: Integer;
BaseName: DOMString;
AttributeNode: IXMLNode;
begin
with ComplexTypeDef do
for I := 0 to Node.AttributeNodes.Count - 1 do
begin
AttributeNode := Node.AttributeNodes[I];
BaseName := ExtractLocalName(AttributeNode.NodeName);
{ Ignore 'xmlns' and any other reserved xml attributes }
if Pos('xml', attributeNode.Prefix) <> 1 then
if AttributeDefs.IndexOfItem(BaseName) = -1 then
AttributeDefs.Add(BaseName, GetDataType(AttributeNode));
end;
end;
var
NewType, ExistingType: IXMLComplexTypeDef;
begin
Result := MakeTypeName(ExtractLocalName(Node.NodeName));
ExistingType := SchemaDef.ComplexTypes.Find(Result);
if ExistingType = nil then
begin
if not Node.IsTextElement then
begin
NewType := SchemaDef.ComplexTypes.Add(Result);
ProcessChildNodes(NewType);
end else
NewType := SchemaDef.ComplexTypes.Add(Result, xsdString, dmSimpleRestriction, cmEmpty);
ProcessAttributes(NewType);
end else
ValidateExistingType(ExistingType, Node);
end;
procedure TXMLDataImporter.ValidateExistingType(
const ExistingType: IXMLComplexTypeDef; const Node: IXMLNode);
var
I, J: Integer;
BaseName, ChildType: DOMString;
AttrNode, ChildNode: IXMLNode;
AttrDef: IXMLAttributeDef;
ElementDef: IXMLElementDef;
begin
if not Node.IsTextElement then
for I := 0 to Node.ChildNodes.Count - 1 do
begin
ChildNode := Node.ChildNodes[I];
if ChildNode.NodeType <> ntElement then continue;
BaseName := ExtractLocalName(ChildNode.NodeName);
ElementDef := ExistingType.ElementDefs.Find(BaseName);
{ If element didn't occur previously, then add it now }
if not Assigned(ElementDef) then
begin
if IsComplexType(ChildNode) then
ChildType := AddComplexType(ChildNode) else
ChildType := GetDataType(ChildNode);
ExistingType.ElementDefs.Add(BaseName, ChildType);
end else
begin
{ Check if the element is repeated in this node, if it wasn't previously }
if ElementDef.MaxOccurs <> SUnbounded then
for J := I + 1 to Node.ChildNodes.Count - 1 do
if Node.GetChildNodes[J].NodeName = ChildNode.NodeName then
begin
ElementDef.MaxOccurs := SUnbounded;
Break;
end;
{ Validate the children of this node as well }
if ElementDef.DataType.IsComplex then
ValidateExistingType(ElementDef.DataType as IXMLComplexTypeDef, ChildNode);
end;
end;
{ If an attribute didn't occur previously, then add it now }
for I := 0 to Node.AttributeNodes.Count - 1 do
begin
AttrNode := Node.AttributeNodes[I];
BaseName := ExtractLocalName(AttrNode.NodeName);
AttrDef := ExistingType.AttributeDefs.Find(BaseName);
if not Assigned(AttrDef) then
ExistingType.AttributeDefs.Add(BaseName, GetDataType(AttrNode));
end;
{ If an existing element doesn't appear here, then mark it as optional }
for I := 0 to ExistingType.ElementDefs.Count - 1 do
begin
ElementDef := ExistingType.ElementDefs[I];
if (ElementDef.MinOccurs <> '0') and
(Node.ChildNodes.FindNode(ElementDef.Name) = nil) then
ElementDef.MinOccurs := '0';
end;
end;
procedure TXMLDataImporter.Translate(const FileName: WideString;
const SchemaDef: IXMLSchemaDef);
begin
inherited;
FXMLDoc := LoadXMLDocument(FileName);
if Assigned(XMLDoc.DocumentElement) then
begin
if XMLDoc.DocumentElement.NamespaceURI <> '' then
with XMLDoc.DocumentElement do
SchemaDef.SetTargetNamespace(NamespaceURI, Prefix);
if IsComplexType(XMLDoc.DocumentElement) then
begin
SchemaDef.ElementDefs.Add(ExtractLocalName(XMLDoc.DocumentElement.NodeName),
XMLDoc.DocumentElement.NodeName+TypeSuffix);
AddComplexType(XMLDoc.DocumentElement);
end;
end;
end;
initialization
TranslatorFactory := TXMLSchemaTranslatorFactory.Create(TXMLDataImporter, nil,
SXMLDataExtension, SXMLDataTransDesc);
RegisterSchemaTranslator(TranslatorFactory);
finalization
UnRegisterSchemaTranslator(TranslatorFactory);
end.
|
{*********************************************}
{ TeeChart Delphi Component Library }
{ Logarithmic Labels Demo }
{ Copyright (c) 1996 by David Berneda }
{ All rights reserved }
{*********************************************}
unit LogLab;
{$P-}
interface
{ This form shows how custom Axis labels can be specified }
{ The Chart.OnGetNextAxisLabel event is used to supply the axis with
custom label positions and values. }
uses
WinProcs, WinTypes, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, TeeProcs, TeEngine, Chart, Series, StdCtrls, Buttons;
type
TLogLabelsForm = class(TForm)
Chart1: TChart;
Series1: TFastLineSeries;
Panel1: TPanel;
BitBtn2: TBitBtn;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.DFM}
procedure TLogLabelsForm.FormCreate(Sender: TObject);
begin
{ Axis settings }
Chart1.BottomAxis.Logarithmic:=True;
Chart1.BottomAxis.TickOnLabelsOnly:=True;
Chart1.BottomAxis.SetMinMax( 10.0, 1000);
Chart1.LeftAxis.Logarithmic:=True;
Chart1.LeftAxis.TickOnLabelsOnly:=True;
Chart1.LeftAxis.SetMinMax( 10.0, 1000);
{ adding XY values to Series1 }
Series1.XValues.DateTime:=False;
Series1.AddXY( 100, 100, '', clTeeColor );
Series1.AddXY( 500, 200, '', clTeeColor );
Series1.AddXY( 800, 300, '', clTeeColor );
Series1.AddXY( 200, 200, '', clTeeColor );
end;
end.
|
unit UnitCuentaCredito;
interface
uses System.SysUtils, System.Variants,
System.Classes, Data.DB;
type
TCuentaCredito = class
public
estadoCuenta : string;
deudaTotal : currency;
idClienteCuenta : integer;
idCuentaCredito : integer;
numeroDeCuenta : string;
currentDate: TDateTime;
procedure actualizarEstado(estado: string);
procedure obtenerId(numeroCuenta: string);
procedure registrarRecargo(monto: currency);
procedure sumarRecargoAcuenta(monto: currency);
function getPagos : integer;
function getIntereses : Currency;
end;
var
cuentaCredito: TCuentaCredito;
pagos : integer;
intereses : currency;
implementation
uses DataAccesModule, FireDAC.Stan.Param, DataModuleDani;
{ TCuentaCredito }
procedure TCuentaCredito.actualizarEstado(estado: string);
begin
obtenerId(numeroDeCuenta);
with DataAccesModule.DataAccesModule_.updateCuentaCredito do
begin
Open;
Refresh;
if FindKey([idCuentaCredito]) then
begin
Edit;
FieldByName('estadoCuenta').AsString := estado;
Post;
end;
end;
end;
procedure TCuentaCredito.obtenerId(numeroCuenta: string);
begin
with DataAccesModule_.getIdCuentaCreditoNumeroCuenta do
begin
Prepare;
ParamByName('numeroDeCuenta').AsString:= numeroCuenta;
Open;
Refresh;
First;
while not EOF do
begin
idCuentaCredito := FieldByName('id_cuenta_credito').AsInteger;
Next;
end;
end;
end;
//REGISTRAR RECARO
procedure TCuentaCredito.registrarRecargo(monto: Currency);
begin
currentDate := Now;
with DataAccesModule_.crearRecargo do
begin
Open;
Refresh;
Insert;
FieldByName('fecha').AsDateTime := currentDate;
FieldByName('monto').AsCurrency := monto;
FieldByName('idCuentaCredito').AsInteger := cuentaCredito.idCuentaCredito;
Post;
end;
//sumarRecargoAcuenta(monto);
end;
// SUMAR RECARGO A CUENTA
procedure TCuentaCredito.sumarRecargoAcuenta(monto: currency);
begin
with DataAccesModule.DataAccesModule_.updateCuentaCredito do
begin
Open;
Refresh;
if FindKey([idCuentaCredito]) then
begin
Edit;
deudaTotal := FieldByName('deudaTotal').AsCurrency;
deudaTotal := deudaTotal + monto;
FieldByName('deudaTotal').AsCurrency := deudaTotal;
Post;
end;
end;
end;
function TCuentaCredito.getIntereses: Currency;
begin
intereses := 0.0;
with DataModuleDaniBD.CuentainteresesTable do
begin
Prepare;
ParamByName('idCuentaCredito').AsInteger := idCuentaCredito;
Open;
Refresh;
First;
while not EOF do
begin
intereses := FieldByName('totalInteresesAcumulados').AsCurrency;
Next;
end;
end;
Result := intereses;
end;
function TCuentaCredito.getPagos: integer;
begin
pagos := 0;
with DataModuleDaniBD.PagoTable do
begin
Prepare;
ParamByName('idCuentaCredito').AsInteger := idCuentaCredito;
Open;
Refresh;
First;
while not EOF do
begin
pagos := pagos + 1;
Next;
end;
end;
Result := pagos;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
charge=class
private
_q:Real ;
_pos:TPoint;
//1-point,2-sphere,3-cylinder,4-plane
_OBJTYPE: Integer ;
_r:Integer ;
_height:integer ;
_width:Integer ;
_checked:BOOLean;
_color:TColor;
public
// constructor new(q:Real;pos:TPoint;r:Integer);overload ;
// constructor new(q:Real;pos:TPoint;r:Integer;height:Integer);overload;
constructor new(q:Real;pos:TPoint;r:Integer;height:Integer;width:Integer);
// constructor new(q:Real;pos:TPoint;r:Integer;height:integer);overload;
end;
space=class
private
charges:array of charge;
_cntcharger:Integer;
_gridp:Integer ;
_canvas:TCanvas;
public
constructor new(canvas:TCanvas;gridp:Integer);
{
procedure AddCharge() ;
procedure removeCharge() ;
procedure draw() ;
procedure movecharge() ;
procedure drawgrid() ;
}
end;
TForm1 = class(TForm)
pb1: TPaintBox;
edtq: TLabeledEdit;
btnaccpt: TButton;
edtr: TLabeledEdit;
edth: TLabeledEdit;
edtw: TLabeledEdit;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
c1:charge;
implementation
{$R *.dfm}
constructor charge.new(q:Real;pos:TPoint;r:Integer;height:Integer;width:Integer);
begin
self._q:=q ;
self._pos:=Pos ;
if (q<0) then
Self._color:=clBlue
else Self._color:=clred;
if (not(r>=0)and (height>=0) and (width>=0)) then
begin
if ((width>=0) and (r<0)) then
begin
Self._objtype:=4
end
else
if (height>=0) then
Self._OBJTYPE:=3
else
Self._OBJTYPE :=2
end
else Self._objtype:=0;
Self._checked:=False;
end;
end.
end;
end. |
unit Authentication;
interface
uses Storage;
type
/// <summary>
/// Класс хранящий информацию о текущем пользователе
/// </summary>
/// <remarks>
/// </remarks>
TUser = class
strict private
class var FLocal: boolean;
class var FLocalMaxAtempt: Byte;
private
FSession: String;
FLogin: String;
procedure SetLocal(const Value: Boolean);
function GetLocal: Boolean;
procedure SetLocalMaxAtempt(const Value: Byte = 10);
function GetLocalMaxAtempt: Byte;
public
property Session: String read FSession;
Property Local: Boolean read GetLocal Write SetLocal;
Property LocalMaxAtempt: Byte read GetLocalMaxAtempt Write SetLocalMaxAtempt;
property Login: String read FLogin;
constructor Create(ASession: String; ALocal: Boolean = false);
end;
/// <summary>
/// Класс аутентификации пользователя
/// </summary>
/// <remarks>
/// </remarks>
TAuthentication = class
/// <summary>
/// Проверка логина и пароля. В случае успеха возвращает данные о пользователе.
/// </summary>
class function CheckLogin(pStorage: IStorage;
const pUserName, pPassword: string; var pUser: TUser;
ANeedShowException: Boolean = True): boolean;
class function spCheckPhoneAuthentSMS (pStorage: IStorage;const pSession, pPhoneAuthent: string; ANeedShowException: Boolean = True): boolean;
end;
implementation
uses iniFiles, Xml.XMLDoc, UtilConst, SysUtils, IdIPWatch, Xml.XmlIntf, CommonData, WinAPI.Windows,
vcl.Forms, vcl.Dialogs, dsdAction, DialogPswSms;
{------------------------------------------------------------------------------}
function GetIniFile(out AIniFileName: String):boolean;
const
FileName: String = '\Boutique.ini';
var
dir: string;
f: TIniFile;
Begin
result := False;
dir := ExtractFilePath(Application.exeName)+'ini';
AIniFileName := dir + FileName;
//
if not DirectoryExists(dir) AND not ForceDirectories(dir) then
Begin
ShowMessage('Пользователь не может получить доступ к файлу настроек:'+#13
+ AIniFileName+#13
+ 'Дальнейшая работа программы невозможна.'+#13
+ 'Обратитесь к администратору.');
exit;
End;
//
if not FileExists (AIniFileName) then
Begin
f := TiniFile.Create(AIniFileName);
try
try
F.WriteString('Common','BoutiqueName','');
Except
ShowMessage('Пользователь не может получить доступ к файлу настроек:'+#13
+ AIniFileName+#13
+ 'Дальнейшая работа программы невозможна.'+#13
+ 'Обратитесь к администратору.');
exit;
end;
finally
f.Free;
end;
end;
//
result := True;
End;
{------------------------------------------------------------------------------}
constructor TUser.Create(ASession: String; ALocal: Boolean = false);
begin
FSession := ASession;
FLocal := ALocal;
FLogin := '';
end;
{------------------------------------------------------------------------------}
class function TAuthentication.spCheckPhoneAuthentSMS (pStorage: IStorage;const pSession, pPhoneAuthent: string; ANeedShowException: Boolean = True): boolean;
var SendSMSAction : TdsdSendSMSCPAAction;
var N: IXMLNode;
pXML : String;
begin
Result:= pPhoneAuthent = '';
// выход
if Result = TRUE then exit;
//
pXML :=
'<xml Session = "' + pSession + '" >' +
'<gpSelect_Object_User_bySMS OutputType="otResult">' +
'<inPhoneAuthent DataType="ftString" Value="%s" />' +
'</gpSelect_Object_User_bySMS>' +
'</xml>';
try
SendSMSAction:= TdsdSendSMSCPAAction.Create(nil);
N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [pPhoneAuthent]), False, 4, ANeedShowException)).DocumentElement;
//
if Assigned(N) then Result:= N.GetAttribute(AnsiLowerCase('Message_sms')) <> '' else Result:= false;
//
if Assigned(N) and (Result = TRUE) then
begin
try
// Send SMS
SendSMSAction.Host.Value := N.GetAttribute(AnsiLowerCase('ServiceName_Sms'));
SendSMSAction.Login.Value := N.GetAttribute(AnsiLowerCase('Login_sms'));
SendSMSAction.Password.Value:= N.GetAttribute(AnsiLowerCase('Password_sms'));
SendSMSAction.Message.Value := N.GetAttribute(AnsiLowerCase('Message_sms'));
SendSMSAction.Phones.Value := N.GetAttribute(AnsiLowerCase('PhoneNum_sms'));
Result:= SendSMSAction.Execute;
//Result:= true;
if not Result then begin ShowMessage('Ошибка при отправке СМС на номер <'+pPhoneAuthent+'>.Работа с программой заблокирована.');exit;end;
except
Result:= false;
exit;
end;
//
// Check Enter SMS
with TDialogPswSmsForm.Create(nil) do
begin
Result:= Execute (pStorage, pSession) <> '';
Free;
end;
end;
finally
SendSMSAction.Free;
end;
end;
{------------------------------------------------------------------------------}
class function TAuthentication.CheckLogin(pStorage: IStorage;
const pUserName, pPassword: string; var pUser: TUser;
ANeedShowException: Boolean = True): boolean;
var IP_str:string;
N: IXMLNode;
pXML : String;
BoutiqueName, IniFileName, S: String;
f: TIniFile;
isBoutique, isProject : Boolean;
begin
//ловим ProjectTest.exe
S:= ExtractFileName(ParamStr(0));
//
isBoutique:= (AnsiUpperCase(gc_ProgramName) = AnsiUpperCase('Boutique.exe'))
or(AnsiUpperCase(gc_ProgramName) = AnsiUpperCase('Boutique_Demo.exe'));
//
isProject:= (AnsiUpperCase(gc_ProgramName) = AnsiUpperCase('Project.exe'))
and (UpperCase(S) <> UpperCase('ProjectTest.exe'))
;
{создаем XML вызова процедуры на сервере}
if isBoutique = TRUE
then begin
//
if GetIniFile (IniFileName) then
try BoutiqueName:= '';
f := TiniFile.Create(IniFileName);
BoutiqueName:= f.ReadString('Common','BoutiqueName','');
finally
f.Free;
end
else begin
result:=false;
exit;
end;
// для Бутиков - еще 1 параметр
pXML :=
'<xml Session = "" >' +
'<gpCheckLogin OutputType="otResult">' +
'<inUserLogin DataType="ftString" Value="%s" />' +
'<inUserPassword DataType="ftString" Value="%s" />' +
'<inIP DataType="ftString" Value="%s" />' +
'<inBoutiqueName DataType="ftString" Value="%s" />' +
'</gpCheckLogin>' +
'</xml>';
end
else
// для Project - еще 1 параметр - Телефон для аутентификации
if isProject = TRUE
then
pXML :=
'<xml Session = "" >' +
'<gpCheckLogin OutputType="otResult">' +
'<inUserLogin DataType="ftString" Value="%s" />' +
'<inUserPassword DataType="ftString" Value="%s" />' +
'<inIP DataType="ftString" Value="%s" />' +
'<ioPhoneAuthent DataType="ftString" Value="%s" />' +
'</gpCheckLogin>' +
'</xml>'
else
pXML :=
'<xml Session = "" >' +
'<gpCheckLogin OutputType="otResult">' +
'<inUserLogin DataType="ftString" Value="%s" />' +
'<inUserPassword DataType="ftString" Value="%s" />' +
'<inIP DataType="ftString" Value="%s" />' +
'</gpCheckLogin>' +
'</xml>';
with TIdIPWatch.Create(nil) do
begin
Active:=true;
IP_str:=LocalIP;
Free;
end;
if isBoutique = TRUE
then
// для Бутиков - еще 1 параметр
N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [pUserName, pPassword, IP_str, BoutiqueName]), False, 4, ANeedShowException)).DocumentElement
else if isProject = TRUE
then
// для Project - еще 1 параметр - Телефон для аутентификации
N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [pUserName, pPassword, IP_str, BoutiqueName]), False, 4, ANeedShowException)).DocumentElement
else
N := LoadXMLData(pStorage.ExecuteProc(Format(pXML, [pUserName, pPassword, IP_str]), False, 4, ANeedShowException)).DocumentElement;
//
result := TRUE;
//
if Assigned(N) then
begin
// сформировали смс, проверили что он корректный
if isProject = TRUE then result := spCheckPhoneAuthentSMS(pStorage, N.GetAttribute(AnsiLowerCase(gcSession)), N.GetAttribute(AnsiLowerCase('ioPhoneAuthent')), ANeedShowException);
//
pUser := TUser.Create(N.GetAttribute(AnsiLowerCase(gcSession)));
pUser.FLogin := pUserName;
end;
//
if result = FALSE then pUser:= nil;
//
result := (pUser <> nil);
end;
function TUser.GetLocal: Boolean;
begin
Result := TUser.FLocal;
end;
procedure TUser.SetLocal(const Value: Boolean);
var
I : Integer;
F: TForm;
begin
TUser.FLocal := Value;
for I := 0 to Screen.FormCount - 1 do
Begin
try
F := Screen.Forms[I];
if assigned(F) AND (F.Handle <> 0) AND (F.ClassNameIs('TMainCashForm') or F.ClassNameIs('TMainCashForm2')) then
PostMessage(F.Handle, UM_LOCAL_CONNECTION,0,0);
Except
end;
End;
end;
function TUser.GetLocalMaxAtempt: Byte;
begin
Result := TUser.FLocalMaxAtempt;
end;
procedure TUser.SetLocalMaxAtempt(const Value: Byte = 10);
begin
TUser.FLocalMaxAtempt := Value;
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the GNU General Public License
Version 2.0 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.gnu.org/copyleft/gpl.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Michael Elsdörfer.
All Rights Reserved.
$Id$
You may retrieve the latest version of this file at the Corporeal
Website, located at http://www.elsdoerfer.info/corporeal
Known Issues:
-----------------------------------------------------------------------------}
unit PWStoreModel;
interface
uses
SysUtils, Classes,
DCPrijndael, DCPsha512;
type
// A single username/password combination
TPWItem = class
private
FID: Cardinal;
FNotes: string;
FTitle: string;
FPassword: string;
FURL: string;
FUsername: string;
FCreationTime: TDateTime;
function GetID: Cardinal;
procedure SetNotes(const Value: string);
procedure SetPassword(const Value: string);
procedure SetTitle(const Value: string);
procedure SetURL(const Value: string);
procedure SetUsername(const Value: string);
procedure SetCreationTime(const Value: TDateTime);
public
constructor Create(ItemID: Cardinal); virtual;
destructor Destroy; override;
public
property ID: Cardinal read GetID;
property Title: string read FTitle write SetTitle;
property Username: string read FUsername write SetUsername;
property Password: string read FPassword write SetPassword;
property URL: string read FURL write SetURL;
property Notes: string read FNotes write SetNotes;
property CreationTime: TDateTime read FCreationTime write SetCreationTime;
end;
// In order to synchronize between multiple computers, we log each and
// every operation.
TPWStoreOperationType = (soAdd, soUpdate, soDelete);
TPWStoreOperation = record
Index: Integer; // must be unique, each index = one revision
Item: TPWItem;
&Type: TPWStoreOperationType;
end;
PPWStoreOperation = ^TPWStoreOperation;
TPWStoreOperationLog = class
private
FOperationLog: TList;
protected
procedure Clear;
procedure Add(Operation: TPWStoreOperationType; Item: TPWItem);
public
constructor Create; virtual;
destructor Destroy; override;
end;
// Stores a list of password items
TPWItemStore = class
private
function GetItems(Index: Integer): TPWItem;
procedure SetItems(Index: Integer; const Value: TPWItem);
function GetCount: Integer;
private
FItems: TList;
FLastAutoID: Cardinal;
FStoreFileStream: TFileStream;
protected
function NextID: Cardinal;
procedure CloseOpenFilestream;
public
constructor Create; virtual;
destructor Destroy; override;
public
procedure Clear;
procedure Close;
function Add: TPWItem;
function Remove(Item: TPWItem): Integer;
procedure SaveToFile(AFilename, APassword: string);
procedure LoadFromFile(AFilename, APassword: string);
public
property Count: Integer read GetCount;
property Items[Index: Integer]: TPWItem read GetItems write SetItems;
end;
implementation
const
PWDB_HEADER = AnsiString('PWDB');
var
PWDB_VERSION: Integer = 1;
{ TPWItem }
constructor TPWItem.Create(ItemID: Cardinal);
begin
FID := ItemID;
FCreationTime := 0;
end;
destructor TPWItem.Destroy;
begin
inherited;
end;
function TPWItem.GetID: Cardinal;
begin
Result := FID;
end;
procedure TPWItem.SetCreationTime(const Value: TDateTime);
begin
FCreationTime := Value;
end;
procedure TPWItem.SetNotes(const Value: string);
begin
FNotes := Value;
end;
procedure TPWItem.SetPassword(const Value: string);
begin
FPassword := Value;
end;
procedure TPWItem.SetTitle(const Value: string);
begin
FTitle := Value;
end;
procedure TPWItem.SetURL(const Value: string);
begin
FURL := Value;
end;
procedure TPWItem.SetUsername(const Value: string);
begin
FUsername := Value;
end;
{ TPWItemStore }
function TPWItemStore.Add: TPWItem;
begin
Result := TPWItem.Create(NextID);
Result.CreationTime := Now;
FItems.Add(Result);
end;
procedure TPWItemStore.Clear;
var
I: Integer;
begin
try
for I := 0 to Count - 1 do
Items[I].Free;
finally
FItems.Clear;
end;
end;
procedure TPWItemStore.Close;
begin
try
Clear;
finally
CloseOpenFilestream;
end;
end;
procedure TPWItemStore.CloseOpenFilestream;
begin
if FStoreFileStream <> nil then
begin
FreeAndNil(FStoreFileStream);
FStoreFileStream := nil;
end;
end;
constructor TPWItemStore.Create;
begin
FItems := TList.Create;
FLastAutoID := 0;
FStoreFileStream := nil;
end;
destructor TPWItemStore.Destroy;
begin
try
Clear;
finally
FItems.Free;
end;
CloseOpenFilestream;
inherited;
end;
function TPWItemStore.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TPWItemStore.GetItems(Index: Integer): TPWItem;
begin
Result := FItems[Index];
end;
procedure TPWItemStore.LoadFromFile(AFilename, APassword: string);
var
MemoryStream: TMemoryStream;
AESCipher: TDCP_rijndael;
I, NumItems: Integer;
function ReadString(const Length: Integer = 0): AnsiString;
var
Lng: Integer;
begin
// no length specified, read from stream
if Length = 0 then
MemoryStream.ReadBuffer(Lng, SizeOf(Lng))
else
Lng := Length;
// read string
SetLength(Result, Lng);
MemoryStream.ReadBuffer(Result[1], Lng);
end;
function ReadInteger: Integer;
begin
MemoryStream.ReadBuffer(Result, SizeOf(Result));
end;
function ReadFloat: Double;
begin
MemoryStream.ReadBuffer(Result, SizeOf(Result));
end;
begin
// clear all the current items
Clear;
// open the file and decrypt to memory stream
CloseOpenFilestream;
try
FStoreFileStream := TFileStream.Create(AFilename, fmOpenReadWrite or fmShareExclusive);
MemoryStream := TMemoryStream.Create;
AESCipher := TDCP_rijndael.Create(nil);
try
// XXX: Traditionally, the password was an AnsiString; we need to
// keep it that way to continue to decrypt existing stores.
AESCipher.InitStr(AnsiString(APassword), TDCP_sha512);
AESCipher.DecryptStream(FStoreFileStream, MemoryStream, FStoreFileStream.Size);
MemoryStream.Position := 0;
// read header
if ReadString(Length(PWDB_HEADER)) <> PWDB_HEADER then
raise Exception.Create('Invalid header (might be wrong key)');
if ReadInteger <> PWDB_VERSION then
raise Exception.Create('Invalid file version');
// read all the items
NumItems := ReadInteger;
for I := 0 to NumItems - 1 do
with Add do
begin
// TODO: Historically, we wrote AnsiStrings; Upgrade to unicode.
Title := string(ReadString);
Username := string(ReadString);
Password := string(ReadString);
URL := string(ReadString);
Notes := string(ReadString);
CreationTime := ReadFloat;
end;
// read binlog
finally
MemoryStream.Free;
AESCipher.Free;
// do not close FStoreFileStream, keep the file open
end;
except
on E: Exception do
begin
// if there was an error, make sure we close the file
CloseOpenFilestream;
// re-raise the exception
raise;
end;
end;
end;
function TPWItemStore.NextID: Cardinal;
begin
Inc(FLastAutoID);
Result := FLastAutoID;
end;
function TPWItemStore.Remove(Item: TPWItem): Integer;
begin
Result := FItems.Remove(Item);
if Result >= 0 then Item.Free;
end;
procedure TPWItemStore.SaveToFile(AFilename, APassword: string);
var
MemoryStream: TMemoryStream;
AESCipher: TDCP_rijndael;
I: Integer;
procedure WriteString(AStr: AnsiString);
var
Lng: Integer;
begin
Lng := Length(Astr);
MemoryStream.WriteBuffer(Lng, SizeOf(Lng));
MemoryStream.WriteBuffer(AStr[1], Length(AStr));
end;
procedure WriteInteger(AInt: Integer);
begin
MemoryStream.WriteBuffer(AInt, SizeOf(AInt));
end;
procedure WriteFloat(AFloat: Double);
begin
MemoryStream.WriteBuffer(AFloat, SizeOf(AFloat));
end;
begin
// put together everything in memory first
MemoryStream := TMemoryStream.Create;
try
// write header
MemoryStream.WriteBuffer(PWDB_HEADER[1], Length(PWDB_HEADER));
MemoryStream.WriteBuffer(PWDB_VERSION, SizeOf(PWDB_VERSION));
// write all the items
WriteInteger(Count);
for I := 0 to Count - 1 do
begin
WriteString(AnsiString(Items[I].Title));
WriteString(AnsiString(Items[I].Username));
WriteString(AnsiString(Items[I].Password));
WriteString(AnsiString(Items[I].URL));
WriteString(AnsiString(Items[I].Notes));
WriteFloat(Double(Items[I].CreationTime));
end;
// write binlog
// now encrypt everything and output to file stream
AESCipher := TDCP_rijndael.Create(nil);
// use existing file stream, or create a new one
if FStoreFileStream = nil then
FStoreFileStream := TFileStream.Create(AFilename, fmCreate or fmShareExclusive)
else begin
FStoreFileStream.Size := 0;
FStoreFileStream.Position := 0;
end;
try
MemoryStream.Position := 0;
AESCipher.InitStr(AnsiString(APassword), TDCP_sha512);
AESCipher.EncryptStream(MemoryStream, FStoreFileStream, MemoryStream.Size)
finally
AESCipher.Free;
// keep filestream open
end;
finally
MemoryStream.Free;
end;
end;
procedure TPWItemStore.SetItems(Index: Integer; const Value: TPWItem);
begin
FItems[Index] := Value;
end;
{ TPWStoreOperationLog }
procedure TPWStoreOperationLog.Add(Operation: TPWStoreOperationType;
Item: TPWItem);
var
NewOp: PPWStoreOperation;
begin
New(NewOp);
NewOp.Index := 0;
NewOp.Item := Item;
NewOp.&Type := Operation;
FOperationLog.Add(NewOp);
end;
procedure TPWStoreOperationLog.Clear;
var
I: Integer;
begin
for I := 0 to FOperationLog.Count - 1 do
Dispose(FOperationLog[I]);
FOperationLog.Clear;
end;
constructor TPWStoreOperationLog.Create;
begin
FOperationLog := TList.Create;
end;
destructor TPWStoreOperationLog.Destroy;
begin
Clear;
FOperationLog.Free;
inherited;
end;
end.
|
{Copyright (C) 2006 Benito van der Zander
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
}
{** @abstract(You can use this unit to configure and create internet connections.)
Currently it only supports HTTP/S connections, but this might change in future (e.g. to also support ftp)}
unit internetaccess;
{$I ../internettoolsconfig.inc}
{$WARN 5043 off : Symbol "$1" is deprecated}
interface
uses
Classes, SysUtils, bbutils;
type
PInternetConfig=^TInternetConfig;
{** @abstract(Internet configuration)
Not all options are supported by all backends. Compatibility matrix:
@table(
@rowHead( @cell(option) @cell(wininet (w32)) @cell(synapse) @cell(OkHttp for Android) @cell((Android) Apache HttpComponents) )
@row( @cell(useragent) @cell(yes) @cell(yes) @cell(yes) @cell(yes) )
@row( @cell(tryDefaultConfig) @cell(yes) @cell(no) @cell(no) @cell(no) )
@row( @cell(http proxy) @cell(yes) @cell(yes) @cell(no) @cell(yes) )
@row( @cell(https proxy) @cell(yes) @cell(should use http proxy) @cell(no) @cell(should use http proxy) )
@row( @cell(socks proxy) @cell(yes) @cell(yes) @cell(no) @cell(no) )
@row( @cell(proxy user/pass) @cell(same auth for all proxies)@cell(separate for http and socks)@cell(no)@cell(no) )
@row( @cell(checkSSLCertificates) @cell(yes) @cell(yes) @cell(no, depends on Android) @cell(no, depends on Android) )
@row( @cell(cafile/capath) @cell(no, uses system CA) @cell(yes) @cell(no) @cell(no) )
)
You can always set more options on the internalHandle returned by TInternetAccess.
}
TInternetConfig=record
userAgent: string; //**< the user agent used when connecting
tryDefaultConfig: boolean; //**< should the system default configuration be used
useProxy: Boolean; //**< should a proxy be used
proxyHTTPName, proxyHTTPPort: string; //**< proxy used for HTTP
proxyHTTPSName, proxyHTTPSPort: string; //**< proxy used for HTTPS
proxySOCKSName, proxySOCKSPort: string; //**< socks proxy
proxyUsername, proxyPassword: string;
connectionCheckPage: string; //**< url we should open to check if an internet connection exists (e.g. http://google.de)
checkSSLCertificates: boolean; //**< If ssl certificates should be checked in HTTPS connections
CAFile, CAPath: string; //**< CA certificates when using OpenSSL
logToPath: string;
procedure setProxy(proxy: string);
procedure searchCertificates;
function equalsUserAgent(const otherConfig: TInternetConfig): boolean;
function equalsProxy(const otherConfig: TInternetConfig): boolean;
end;
{ TDecodedUrl }
TDecodedUrlParts = set of (dupProtocol, dupUsername, dupPassword, dupHost, dupPort, dupPath, dupParams, dupLinkTarget);
const
DecodedUrlPartsALL = [dupProtocol, dupUsername, dupPassword, dupHost, dupPort, dupPath, dupParams, dupLinkTarget];
type
//** @abstract(A record storing a decoded url.)
//** Use decodeUrl to create it.@br
//** It only splits the string into parts, so parts that are url encoded (username, password, path, params, linktarget) will still be url encoded. @br
//** path, params, linktarget include their delimiter, so an empty string denotes the absence of these parts.
TDecodedUrl = record
protocol, username, password, host, port, path, params, linktarget: string;
function combined(use: TDecodedUrlParts = DecodedUrlPartsALL): string;
function combinedExclude(doNotUse: TDecodedUrlParts = []): string; inline;
function resolved(rel: string): TDecodedUrl;
function serverConnectionOnly: TDecodedUrl;
procedure prepareSelfForRequest(const lastConnectedURL: TDecodedUrl);
end;
TInternetAccessDataBlock = TPCharView;
TMIMEMultipartSubData = record
data: string;
headers: TStringArray;
function getFormDataName: string;
end;
PMIMEMultipartSubData = ^TMIMEMultipartSubData;
//**encodes the data corresponding to RFC 1341 (preliminary)
TMIMEMultipartData = record
data: array of TMIMEMultipartSubData;
function getFormDataIndex(const name: string): integer;
procedure add(const sdata: string; const headers: string = '');
procedure addFormData(const name, sdata: string; headers: string = '');
//procedure TMIMEMultipartData.addFormData(const name, sdata: string; headers: TStringArray);
procedure addFormDataFile(const name, filename: string; headers: string = '');
procedure addFormData(const name, sdata, filename, contenttype, headers: string);
function compose(out boundary: string; boundaryHint: string = '---------------------------1212jhjg2ypsdofx0235p2z5as09'): string;
procedure parse(sdata, boundary: string);
procedure clear;
const HeaderSeparator = #13#10;
//const ALLOWED_BOUNDARY_CHARS: string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ''''()+,-./:=?'; //all allowed
const ALLOWED_BOUNDARY_CHARS: string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-'; //might be preferable to use those only
class function buildHeaders(const name, filename, contenttype, headers: string): TStringArray; static;
class function insertMissingNameToHeaders(const name: string; headers: TStringArray): TStringArray; static;
class function nameFromHeader(const header: string): string; static;
class function indexOfHeader(const sl: TStringArray; name: string): sizeint; static;
class function HeaderForBoundary(const boundary: string): string; static;
end;
THeaderKind = (iahUnknown, iahContentType, iahContentDisposition, iahAccept, iahReferer, iahLocation, iahSetCookie, iahCookie, iahUserAgent);
THTTPHeaderList = class(TStringList)
public
constructor Create;
function getHeaderValue(kind: THeaderKind): string;
function getHeaderValue(header: string): string; //**< Reads a certain HTTP header received by the last @noAutoLink(request)
function getContentDispositionFileNameTry(out filename: string): Boolean;
procedure add(const name, value: string);
property headerValues[header: string]: string read GetheaderValue; default;
protected
class function parseCharacterSetEncodedHeaderRFC5987AsUtf8Try(value: TPCharView; out utf8: string): Boolean; static;
class function parseContentDispositionFileNameTry(const contentDisposition: string; out filename: string): Boolean; static;
end;
TCookieFlags = set of (cfHostOnly, cfSecure {, cfHttpOnly});
TCookieManager = record
cookies: array of record
domain, path, name, value: string;
flags: TCookieFlags;
end;
procedure clear;
procedure setCookie(domain, path: string; const name,value:string; flags: TCookieFlags);
procedure parseHeadersForCookies(const source: TDecodedUrl; headers: THTTPHeaderList; allowUnsecureXidelExtensions: boolean = false);
function makeCookieHeader(const target: TDecodedUrl):string;
function makeCookieHeaderValueOnly(const target: TDecodedUrl):string;
function serializeCookies: string;
procedure loadFromFile(const fn: string);
procedure saveToFile(const fn: string);
end;
TInternetAccess = class;
TTransferContentInflater = class;
TInternetAccessReaction = (iarAccept, iarFollowRedirectGET, iarFollowRedirectKeepMethod, iarRetry, iarReject);
//if headerKind is iahUnknown header contains the entire header line name: value, otherwise only the value
THeaderEnumCallback = procedure (data: pointer; headerKindHint: THeaderKind; const name, value: string);
//**Event to monitor the progress of a download (measured in bytes)
TProgressEvent=procedure (sender: TObject; progress,maxprogress: longint) of object;
//**Event to intercept transfers end/start
TTransferClearEvent = procedure() of object;
TTransferBlockWriteEvent = TStreamLikeWriteNativeInt;
TTransfer = record
//in
method: string;
url: string;
decodedUrl: TDecodedUrl;
data: TPCharView;
ownerAccess: TInternetAccess;
//during transfer
writeBlockCallback: TTransferBlockWriteEvent;
inflater: TTransferContentInflater;
currentSize, contentLength: sizeint;
//out
HTTPResultCode: longint;
HTTPErrorDetails: string;
receivedHTTPHeaders: THTTPHeaderList;
procedure beginTransfer(onClear: TTransferClearEvent; onReceivedBlock: TTransferBlockWriteEvent; const amethod: string; const aurl: TDecodedUrl; const adata: TInternetAccessDataBlock);
procedure writeBlock(const Buffer; Count: Longint);
procedure endTransfer;
end;
TTransferStartEvent=procedure (sender: TObject; const method: string; const url: TDecodedUrl; const data: TInternetAccessDataBlock) of object;
TTransferReactEvent=procedure (sender: TInternetAccess; var transfer: TTransfer; var reaction: TInternetAccessReaction) of object;
TTransferEndEvent=procedure (sender: TObject; var transfer: TTransfer) of object;
TTransferContentInflater = class
//constructor create(); virtual; abstract;
//procedure writeCompressedBlock(const Buffer; Count: Longint); virtual; abstract;
class procedure injectDecoder(var transfer: TTransfer; const encoding: string); virtual; abstract;
procedure endTransfer; virtual; abstract;
end;
TTransferInflaterClass = class of TTransferContentInflater;
//**URL Encoding encodes every special character @code(#$AB) by @code(%AB). This model describes which characters are special:
TUrlEncodingModel = (
ueHTMLForm, //**< Encode for application/x-www-form-urlencoded as defined in HTML 5 standard
ueHTMLMultipartFieldName, //**< Encode for multipart/form-data field names as defined in HTML 5 standard
ueURLPath, //**< Encode for the path part of an URL
ueURLQuery, //**< Encode for the query part of an URL
ueXPathURI, //**< Encode for the XPath/XQuery function fn:encode-for-uri as defined in the XPath standard
ueXPathHTML4, //**< Encode for the XPath/XQuery function fn:escape-html-uri as defined in the XPath standard (they quote the the HTML4 standard)
ueXPathFromIRI);//**< Encode for the XPath/XQuery function fn:iri-to-uri as defined in the XPath standard
//**@abstract(Abstract base class for connections)
//**This class defines the interface methods for HTTP requests, like @link(get), post or request.@br
//**If a method fails, it will raise a EInternetException@br@br
//**Since this is an abstract class, you cannot use it directly, but need to use one of the implementing child classes
//**TW32InternetAccess, TSynapseInternetAccess, TAndroidInternetAccess or TMockInternetAccess. @br
//**The recommended usage is to assign one of the child classes to defaultInternetAccessClass and
//**then create an actual internet access class with @code(defaultInternetAccessClass.create()). @br
//**Then it is trivial to swap between different implementations on different platforms, and the depending units
//**(e.g. simpleinternet or xquery ) will use the implementation you have choosen. Default options will be taken from the global defaultInternetConfig record.
TInternetAccess=class
private
FOnTransferEnd: TTransferEndEvent;
FOnTransferReact: TTransferReactEvent;
FOnTransferStart: TTransferStartEvent;
FOnProgress:TProgressEvent;
procedure setLastUrl(AValue: string);
protected
fconfig: TInternetConfig;
procedure setConfig(internetConfig: PInternetConfig); virtual;
function getConfig: PInternetConfig;
protected
//active transfer
lastTransfer: TTransfer;
//**Override this if you want to sub class it
procedure doTransferUnchecked(var transfer: TTransfer);virtual;abstract;
procedure doTransferChecked(onClear: TTransferClearEvent; onReceivedBlock: TTransferBlockWriteEvent; method: string; url: TDecodedUrl; data: TInternetAccessDataBlock; remainingRedirects: integer);
function getLastErrorDetails(): string;
function getLastHTTPHeaders: THTTPHeaderList;
function getLastHTTPResultCode: longint;
function getLastUrl: string;
//utility functions to minimize platform dependent code
procedure enumerateAdditionalHeaders(const atransfer: TTransfer; callback: THeaderEnumCallback; callbackData: pointer);
public
class function parseHeaderLineKind(const line: string): THeaderKind; static;
protected
class function parseHeaderLineValue(const line: string): string; static;
class function parseHeaderLineName(const line: string): string; static;
class function makeHeaderLine(const name, value: string): string; static;
class function makeHeaderLine(const kind: THeaderKind; const value: string): string; static;
class function makeHeaderName(const kind: THeaderKind): string; static;
//constructor, since .create is "abstract" and can not be called
public
//in
additionalHeaders: THTTPHeaderList; //**< Defines additional headers that should be send to the server
ContentTypeForData: string; //**< Defines the Content-Type that is used to transmit data. Usually @code(application/x-www-form-urlencoded) or @code(multipart/form-data; boundary=...). @br This is overriden by a Content-Type set in additionalHeaders.
multipartFormData: TMIMEMultipartData;
function getFinalMultipartFormData: string;
public
//out
property lastHTTPResultCode: longint read getlastHTTPResultCode; //**< HTTP Status code of the last @noAutoLink(request)
property lastUrl: string read getLastUrl write setLastUrl; //**< Last retrieved URL
property lastHTTPHeaders: THTTPHeaderList read getLastHTTPHeaders; //**< HTTP headers received by the last @noAutoLink(request)
function getLastContentType: string; //**< Same as getLastHTTPHeader('Content-Type') but easier to remember and without magic string
public
//** Cookies receive from/to-send the server
cookies: TCookieManager;
property config: PInternetConfig read getConfig write setConfig;
constructor create();virtual;
constructor create(const internetConfig: TInternetConfig);virtual;
destructor Destroy; override;
//**post the (raw) data to the given url and returns the resulting document
//**as string
function post(const totalUrl, data:string):string;
//**post the (raw) data to the url given as three parts and returns the page as string
function post(const protocol,host,url: string; data:string):string;
//**get the url as stream
procedure get(const totalUrl: string; stream:TStream);
//**get the url as string
function get(const totalUrl: string):string;
//**get the url as stream
procedure get(const protocol,host,url: string; stream:TStream);
//**get the url as string
function get(const protocol,host,url: string):string;
//**performs a HTTP @noAutoLink(request)
function request(const method, fullUrl, data:string):string;
//**performs a HTTP @noAutoLink(request)
function request(method, protocol,host,url, data:string):string;
//**performs a HTTP @noAutoLink(request)
function request(method: string; url: TDecodedUrl; data:string):string;
//**performs a HTTP @noAutoLink(request)
procedure request(const method: string; const url: TDecodedUrl; const uploadData:string; outStream: TStream);
//**performs a HTTP @noAutoLink(request)
procedure request(const method: string; const url: TDecodedUrl; const uploadData: TInternetAccessDataBlock; const onClear: TTransferClearEvent; const onReceivedBlock: TTransferBlockWriteEvent);
//**checks if an internet connection exists
function existsConnection():boolean; virtual; deprecated;
//**call this to open a connection (very unreliable). It will return true on success
function needConnection():boolean; virtual; deprecated;
//**Should close all connections (doesn''t work)
procedure closeOpenedConnections(); virtual; deprecated;
//**Encodes the passed string in the url encoded format
class function urlEncodeData(const data: string; encodingModel: TUrlEncodingModel = ueHTMLForm): string; static;
//**Encodes all var=... pairs of data in the url encoded format
class function urlEncodeData(data: TStringList; encodingModel: TUrlEncodingModel = ueHTMLForm): string; static;
//**parses a string like 200=accept,400=abort,300=redirect
class function reactFromCodeString(const codes: string; actualCode: integer; var reaction: TInternetAccessReaction): string; static;
function internalHandle: TObject; virtual; abstract;
published
property OnTransferStart: TTransferStartEvent read FOnTransferStart write FOnTransferStart;
property OnTransferReact: TTransferReactEvent read FOnTransferReact write FOnTransferReact;
property OnTransferEnd: TTransferEndEvent read FOnTransferEnd write FOnTransferEnd;
property OnProgress: TProgressEvent read FOnProgress write FOnProgress;
end;
{ EInternetException }
EInternetException=class(Exception)
details:string;
errorCode: integer;
constructor create(amessage: string);
constructor create(amessage: string; aerrorCode: integer);
end;
TInternetAccessClass=class of TInternetAccess;
//procedure decodeURL(const totalURL: string; out protocol, host, url: string);
//** Splits a url into parts
//** @param(normalize performs some normalizations (e.g. foo//bar -> foo/bar))
function decodeURL(const totalURL: string; normalize: boolean = true): TDecodedUrl;
function decodeURL(const protocol, host, url: string; normalize: boolean = true): TDecodedUrl;
type TRetrieveType = (rtEmpty, rtRemoteURL, rtFile, rtXML, rtJSON);
(***
Guesses the type of a given string@br@br
E.g. for 'http://' it returns rtRemoteURL, for '/tmp' rtFile and for '<abc/>' rtXML.@br
Internally used by simpleinternet.retrieve to determine how to actually @noAutoLink(retrieve) the data.
*)
function guessType(const data: string): TRetrieveType;
var defaultInternetConfiguration: TInternetConfig; //**< default configuration, used by all internet access classes
defaultInternetAccessClass:TInternetAccessClass = nil; //**< default internet access. This controls which internet library the program will use.
defaultTransferInflater: TTransferInflaterClass;
const ContentTypeUrlEncoded: string = 'application/x-www-form-urlencoded';
const ContentTypeMultipart: string = 'multipart/form-data'; //; boundary=
const ContentTypeTextPlain: string = 'text/plain'; //; boundary=
//**Make a HTTP GET request to a certain url.
function httpRequest(url: string): string; overload;
//**Make a HTTP POST request to a certain url, sending the data in rawpostdata unmodified to the server.
function httpRequest(url: string; rawpostdata: string): string; overload;
//**Make a HTTP POST request to a certain url, sending the data in postdata to the server, after url encoding all name=value pairs of it.
function httpRequest(url: string; postdata: TStringList): string; overload;
//**Make a HTTP request to a certain url, sending the data in rawdata unmodified to the server.
function httpRequest(const method, url, rawdata: string): string; overload;
//**This provides a thread-safe default internet
function defaultInternet: TInternetAccess;
//**If you use the procedural interface from different threads, you have to call freeThreadVars
//**before the thread terminates to prevent memory leaks @br
procedure freeThreadVars;
implementation
uses bbrandomnumbergenerator;
//==============================================================================
// TInternetAccess
//==============================================================================
(*procedure decodeURL(const totalURL: string; out protocol, host, url: string);
var slash,points: integer;
port:string;
begin
url:=totalURL;
protocol:=copy(url,1,pos('://',url)-1);
delete(url,1,length(protocol)+3);
slash:=pos('/',url);
if slash = 0 then slash := length(url) + 1;
points:=pos(':',url);
if (points=0) or (points>slash) then points:=slash
else begin
port:=copy(url,points+1,slash-points-1);
case strToInt(port) of
80,8080: begin
if protocol<>'http' then
raise EInternetException.create('Protocol value ('+port+') doesn''t match protocol name ('+protocol+')'#13#10'URL: '+totalURL);
if port<>'80' then
points:=slash; //keep non standard port
end;
443: if protocol<>'https' then
raise EInternetException.create('Protocol value (443) doesn''t match protocol name ('+protocol+')'#13#10'URL: '+totalURL);
else raise EInternetException.create('Unknown port in '+totalURL);
end;
end;
host:=copy(url,1,points-1);
delete(url,1,slash-1);
if url = '' then url := '/';
end; *)
function decodeURL(const totalURL: string; normalize: boolean): TDecodedUrl;
var url: String;
userPos: SizeInt;
slashPos: SizeInt;
p: SizeInt;
paramPos: SizeInt;
targetPos: SizeInt;
nextSep: SizeInt;
temp: String;
begin
result.protocol:='http';
result.port:='';
result.username:=''; //if these values are not initialized here, they might get a random value
result.password:='';
result.path:='';
result.params:='';
result.linktarget:='';
url:=totalURL;
if pos('://', url) > 0 then
result.protocol := strSplitGet('://', url);
userPos := pos('@', url);
slashPos := pos('/', url);
paramPos := pos('?', url);
targetPos := pos('#', url);
nextSep := length(url)+1;
if ((slashPos <> 0) and (slashPos < nextSep)) then nextSep:=slashPos;
if ((paramPos <> 0) and (paramPos < nextSep)) then nextSep:=paramPos;
if ((targetPos <> 0) and (targetPos < nextSep)) then nextSep:=targetPos;
if (userPos > 0) and ((userPos < nextSep) or (nextSep = 0)) then begin //username:password@...
nextSep -= userPos;
result.username := strSplitGet('@', url);
if strContains(result.username, ':') then begin
temp:=strSplitGet(':', result.username);
result.password:=result.username;
result.username:=temp;
end;
end;
result.host := copy(url, 1, nextSep-1);
url := strCopyFrom(url, nextSep);
if strBeginsWith(result.host, '[') then begin //[::1 IPV6 address]
delete(result.host, 1, 1);
p := pos(']', result.host);
if p > 0 then begin
result.port:=strCopyFrom(result.host, p+1);
result.host:=copy(result.host, 1, p-1);
if strBeginsWith(result.port, ':') then delete(result.port, 1, 1);
end;
end else begin //host:port
p := pos(':', result.host);
if p > 0 then begin
result.port:=strCopyFrom(result.host, p+1);
result.host:=copy(result.host, 1, p-1);
end;
end;
if paramPos > 0 then begin
result.path := strSplitGet('?', url);
if targetPos > 0 then begin
result.params := '?' + strSplitGet('#', url);
result.linktarget:='#'+url;
end else result.params := '?' + url;
end else if targetPos > 0 then begin
result.path := strSplitGet('#', url);
result.linktarget:='#'+url;
end else result.path := url;
if normalize then begin
p := 2;
while (p <= length(result.path)) do
if (result.path[p] = '/') and (result.path[p-1] = '/') then delete(result.path, p, 1)
else p += 1;
end;
end;
function decodeURL(const protocol, host, url: string; normalize: boolean): TDecodedUrl;
var
temp: String;
begin
temp := '';
if not strBeginsWith(url, '/') then temp := '/';
result := decodeURL(protocol + '://' + host + temp + url, normalize);
end;
function guessType(const data: string): TRetrieveType;
var trimmed: string;
begin
trimmed:=TrimLeft(data);
if trimmed = '' then exit(rtEmpty);
if striBeginsWith(trimmed, 'http://') or striBeginsWith(trimmed, 'https://') then
exit(rtRemoteURL);
if striBeginsWith(trimmed, 'file://') then
exit(rtFile);
if trimmed[1] = '<' then
exit(rtXML);
if trimmed[1] in ['[', '{'] then
exit(rtJSON);
exit(rtFile);
end;
procedure saveableURL(var url:string);
var temp:integer;
begin
for temp:=1 to length(url) do
if url[temp] in ['/','?','&',':','\','*','"','<','>','|'] then
url[temp]:='#';
end;
procedure writeString(dir,url,value: string);
var tempdebug:TFileStream;
begin
saveAbleURL(url);
url:=copy(url,1,200); //cut it of, or it won't work on old Windows with large data
url:=dir+url;
try
if fileexists(url) then
tempdebug:=TFileStream.create(url+'_____'+inttostr(random(99999999)),fmCreate)
else
tempdebug:=TFileStream.create(Utf8ToAnsi(url),fmCreate);
if value<>'' then
tempdebug.writebuffer(value[1],length(value))
else
tempdebug.Write('empty',5);
tempdebug.free;
except
end;
end;
function TMIMEMultipartSubData.getFormDataName: string;
var
j: Integer;
begin
for j := 0 to high(headers) do
if striBeginsWith(headers[j], 'Content-Disposition:') then
exit(striBetween(headers[j], 'name="', '"')); //todo: decoding
result := '';
end;
{ TMIMEMultipartData }
procedure TMIMEMultipartData.addFormData(const name, sdata: string; headers: string);
begin
headers := 'Content-Disposition: form-data; name="'+name+'"' + #13#10 + headers; //todo: name may encoded with [RFC2045]/rfc2047
add(sdata, headers);
end;
{procedure TMIMEMultipartData.addFormData(const name, sdata: string; headers: TStringArray);
begin
add(sdata, strJoin(insertMissingNameToHeaders(name, headers), HeaderSeparator));
end;}
procedure TMIMEMultipartData.addFormDataFile(const name, filename: string; headers: string);
begin
headers := 'Content-Disposition: form-data; name="'+name+'"; filename="'+filename+'"' + #13#10 + headers; //todo: name may encoded with [RFC2045]/rfc2047; filename may be approximated or encoded with 2045
add(strLoadFromFileUTF8(filename), headers);
end;
procedure TMIMEMultipartData.addFormData(const name, sdata, filename, contenttype, headers: string);
var
splittedHeaders: TStringArray;
disposition: String;
begin
splittedHeaders := strSplit(headers, #13#10, false);
if (indexOfHeader(splittedHeaders, 'Content-Type') < 0) and (contenttype <> '') then
arrayInsert(splittedHeaders, 0, 'Content-Type: ' + contenttype);
if indexOfHeader(splittedHeaders, 'Content-Disposition') < 0 then begin
disposition := 'Content-Disposition: form-data; name="'+name+'"';
if filename <> '' then disposition += '; filename="'+filename+'"'; //todo: name may encoded with [RFC2045]/rfc2047; filename may be approximated or encoded with 2045
arrayInsert(splittedHeaders, 0, disposition);
end;
SetLength(data, length(data) + 1);
data[high(data)].headers := splittedHeaders;
data[high(data)].data := sdata;
end;
function TMIMEMultipartData.getFormDataIndex(const name: string): integer;
var
i,j: Integer;
begin
for i := 0 to high(data) do
for j := 0 to high(data[i].headers) do
if striBeginsWith(data[i].headers[j], 'Content-Disposition:') then
if name = striBetween(data[i].headers[j], 'name="', '"') then
exit(i);
exit(-1);
end;
procedure TMIMEMultipartData.add(const sdata: string; const headers: string);
begin
SetLength(data, length(data) + 1);
data[high(data)].headers := strSplit(headers, #13#10, false);
data[high(data)].data := sdata;
end;
function TMIMEMultipartData.compose(out boundary: string; boundaryHint: string): string;
var joinedHeaders: TStringArray = nil;
encodedData: TStringArray = nil;
i: Integer;
ok: Boolean;
rng: TRandomNumberGenerator;
rnginitialized: boolean = false;
function randomLetter: char;
var seed: qword = qword($3456789012345678);
temp: qword = 0;
begin
if not rnginitialized then begin
if length(boundaryHint) >= sizeof(temp) then move(boundaryHint[length(boundaryHint) - sizeof(temp) + 1], temp, sizeof(temp));
seed := seed xor temp;
rng.randomize(seed);
rnginitialized := true;
end;
result := ALLOWED_BOUNDARY_CHARS[ rng.next(length(ALLOWED_BOUNDARY_CHARS)) + 1 ];
end;
begin
SetLength(joinedHeaders, length(data));
SetLength(encodedData, length(data));
for i := 0 to high(data) do begin
joinedHeaders[i] := trim(strJoin(data[i].headers, #13#10)); //trim to remove additional #13#10 at the end
{ todo: this actually breaks it.
firefox only sets content-type for file, nothing else
if indexOfHeader(data[i].headers, 'Content-Type') < 0 then begin
if joinedHeaders[i] <> '' then joinedHeaders[i] += #13#10;
joinedHeaders[i] += 'Content-Type: application/octet-stream'; //todo: use text for plain text
end;
if indexOfHeader(data[i].headers, 'Content-transfer-encoding') < 0 then begin
if joinedHeaders[i] <> '' then joinedHeaders[i] += #13#10;
joinedHeaders[i] += 'Content-transfer-encoding: binary'; //todo: binary is not allowed for mails (use base64, or 8-bit with line wrapping)
end; }
encodedData[i] := data[i].data;
end;
rng := default(TRandomNumberGenerator);
boundary := boundaryHint;
repeat
repeat
ok := true;
for i := 0 to high(data) do begin
ok := ok and not strContains(joinedHeaders[i], boundary) and not strContains(encodedData[i], boundary);
if not ok then break;
end;
if not ok then
boundary += randomLetter;
until ok or (length(boundary) >= 70 {max length});
if not ok then
if length(boundaryHint) <= 16 then boundary := boundaryHint
else boundary := copy(boundaryHint, 1, 8) + strCopyFrom(boundaryHint, length(boundaryHint) - 7); //if boundary hint has max length, we can only use a (random) part
until ok;
result := '';
for i := 0 to high(data) do begin
result += #13#10'--' +boundary + #13#10;
result += joinedHeaders[i] + #13#10;
result += #13#10; //separator
result += encodedData[i];
end;
result += #13#10'--' + boundary + '--'#13#10;
end;
procedure TMIMEMultipartData.parse(sdata, boundary: string);
var
p,q,r: Integer;
begin
boundary := #13#10'--'+boundary;
p := 1;
q := strIndexOf(sdata, boundary, p) + length(boundary);
while (q + 2 <= length(sdata)) and strBeginsWith(@sdata[q], #13#10) do begin
r := strIndexOf(sdata, #13#10#13#10, q);
SetLength(data, length(data) + 1);
data[high(data)].headers := strSplit(strSlice(sdata, q+2, r-1), #13#10, false);
p := r + 4;
q := strIndexOf(sdata, boundary, p);
data[high(data)].data := strSlice(sdata, p, q- 1);
q += length(boundary);
end;
end;
procedure TMIMEMultipartData.clear;
begin
setlength(data, 0);
end;
class function TMIMEMultipartData.buildHeaders(const name, filename, contenttype, headers: string): TStringArray;
var
splittedHeaders: TStringArray;
disposition: String;
begin
splittedHeaders := strSplit(headers, HeaderSeparator, false);
if (contenttype <> '') and (indexOfHeader(splittedHeaders, 'Content-Type') < 0) then
arrayInsert(splittedHeaders, 0, 'Content-Type: ' + contenttype);
if indexOfHeader(splittedHeaders, 'Content-Disposition') < 0 then begin
disposition := 'Content-Disposition: form-data; name="'+name+'"';
if filename <> '' then disposition += '; filename="'+filename+'"'; //todo: name may encoded with [RFC2045]/rfc2047; filename may be approximated or encoded with 2045
arrayInsert(splittedHeaders, 0, disposition);
end;
result := splittedHeaders;
end;
class function TMIMEMultipartData.insertMissingNameToHeaders(const name: string; headers: TStringArray): TStringArray;
begin
result := headers;
if indexOfHeader(result, 'Content-Disposition') < 0 then
arrayInsert(result, 0, 'Content-Disposition: form-data; name="'+name+'"');
end;
class function TMIMEMultipartData.nameFromHeader(const header: string): string;
begin
result := strBefore(header, ':');
end;
class function TMIMEMultipartData.indexOfHeader(const sl: TStringArray; name: string): sizeint;
var
i: sizeint;
begin
name := trim(name) + ':';
for i:=0 to high(sl) do
if striBeginsWith(sl[i], name) then
exit(i);
exit(-1);
end;
class function TMIMEMultipartData.HeaderForBoundary(const boundary: string): string;
begin
result := 'Content-Type: ' + ContentTypeMultipart + '; boundary=' + boundary;
end;
{ EInternetException }
constructor EInternetException.create(amessage: string);
begin
inherited Create(amessage);
errorCode:=-1;
end;
constructor EInternetException.create(amessage: string; aerrorCode: integer);
begin
inherited Create(amessage);
Self.errorCode:=aerrorCode;
end;
{ TDecodedUrl }
function TDecodedUrl.combined(use: TDecodedUrlParts): string;
begin
result := '';
if (dupProtocol in use) and (protocol <> '') then result += protocol+'://';
if (dupUsername in use) and (username <> '') then begin
result += username;
if (dupPassword in use) and (password <> '') then result += ':'+password;
Result+='@';
end;
if dupHost in use then begin
if strContains(host, ':') then result += '['+host+']'
else result += host;
if (dupPort in use) and (port <> '') then result += ':'+port;
end;
if dupPath in use then result += path;
if dupParams in use then result += params;
if dupLinkTarget in use then result += linktarget;
end;
function TDecodedUrl.combinedExclude(doNotUse: TDecodedUrlParts): string;
begin
result := combined(DecodedUrlPartsALL - doNotUse);
end;
function TDecodedUrl.resolved(rel: string): TDecodedUrl;
begin
if strIsAbsoluteURI(rel) then result := decodeURL(rel)
else result := decodeURL(strResolveURI(rel, combined));
end;
function TDecodedUrl.serverConnectionOnly: TDecodedUrl;
begin
result.protocol := protocol;
result.username := username;
result.password := password;
result.host := host;
result.port := port;
end;
procedure TDecodedUrl.prepareSelfForRequest(const lastConnectedURL: TDecodedUrl);
begin
if path = '' then path:='/';
if (lastConnectedUrl.username <> '') and (lastConnectedUrl.password <> '')
and (username = '') and (password = '')
and (lastConnectedUrl.host = host) and (lastConnectedUrl.port = port) and (lastConnectedUrl.protocol = protocol) then begin
//remember username/password from last connection (=> allows to follows urls within passwort protected areas)
username := lastConnectedUrl.username;
password := lastConnectedUrl.password;
end;
linktarget := '';
end;
{ TInternetConfig }
type TProxyOptionKind = (pkHTTPorHTTPS, pkHTTP, pkHTTPS, pkSocks);
procedure TInternetConfig.setProxy(proxy: string);
var
url: TDecodedUrl;
view, v, viewKind: TStringView;
kind: TProxyOptionKind;
begin
view := proxy.view;
view.trim();
if view.IsEmpty then begin
useProxy:=false;
exit;
end;
proxyUsername:='';
proxyPassword:='';
for v in view.splitFindToArray(' ') do begin
kind := pkHTTPorHTTPS;
if v.splitRightOfFind(viewKind, '=') then begin
if viewKind = 'socks' then kind := pkSocks
else if viewKind = 'http' then kind := pkHTTP
else if viewKind = 'https' then kind := pkHTTPS;
end;
url := decodeURL(v.ToString);
with url do begin
if ( (username <> '') or (password <> '') ) and (proxyUsername = '') and (proxyPassword = '') then begin
proxyUsername:=strUnescapeHex(username, '%');
proxyPassword:=strUnescapeHex(password, '%');
end;
if kind in [pkHTTP, pkHTTPS, pkHTTPorHTTPS] then begin
if port = '' then port := '8080';
if kind in [pkHTTP, pkHTTPorHTTPS] then begin
proxyHTTPName := host;
proxyHTTPPort := port;
end;
if kind in [pkHTTPS, pkHTTPorHTTPS] then begin
proxyHTTPSName := host;
proxyHTTPSPort := port;
end;
end;
if kind = pkSocks then begin
proxySOCKSName := host;
proxySOCKSPort := port;
end;
end;
end;
useProxy:=true;
{ writeln('h:' ,proxyHTTPName,' ',proxyHTTPPort);
writeln('t:' ,proxyHTTPSName,' ',proxyHTTPSPort);
writeln('s:' ,proxySocksName,' ',proxySocksPort);}
end;
procedure TInternetConfig.searchCertificates;
//see https://serverfault.com/questions/62496/ssl-certificate-location-on-unix-linux
const SystemCAFiles: array[1..2{$ifndef windows}+7{$endif}] of string = (
{$ifndef windows}
'/etc/ssl/certs/ca-certificates.crt', // Debian/Ubuntu/Gentoo etc.
'/etc/pki/tls/certs/ca-bundle.crt', // Fedora/RHEL 6
'/etc/ssl/ca-bundle.pem', // OpenSUSE
'/etc/pki/tls/cacert.pem', // OpenELEC
'/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem', // CentOS/RHEL 7
'/etc/ssl/cert.pem', // Alpine Linux
'/usr/local/ssl/cert.pem', // OpenSSL default
{$endif}
'cacert.pem',
'ca-bundle.crt'
);
{$ifndef windows}
const SystemCAPaths: array[1..7] of string = (
'/etc/ssl/certs', // SLES10/SLES11, https://golang.org/issue/12139
'/system/etc/security/cacerts', // Android
'/usr/local/share/certs', // FreeBSD
'/etc/pki/tls/certs', // Fedora/RHEL
'/etc/openssl/certs', // NetBSD
'/var/ssl/certs', // AIX
'/usr/local/ssl/certs' // OpenSSL default
);
{$endif}
var
i: Integer;
temp: AnsiString;
{$ifdef windows}
programPath: String;
{$endif}
begin
temp := GetEnvironmentVariable('SSL_CERT_FILE');
if (temp <> '') and (FileExists(temp)) then CAFile := temp;
temp := GetEnvironmentVariable('SSL_CERT_DIR');
if (temp <> '') and (DirectoryExists(temp)) then CAPath := temp;
{$ifdef android}
temp := GetEnvironmentVariable('PREFIX');
if (CAFile = '') and FileExists(temp + '/etc/tls/cert.pem') then CAFile := temp + '/etc/tls/cert.pem';
if (CAPath = '') and DirectoryExists(temp + '/etc/tls/certs') then CAPath := temp + '/etc/tls/certs';
{$endif}
{$ifdef windows}
programPath:=IncludeTrailingBackslash(ExtractFilePath(ParamStr(0)));
for i := low(SystemCAFiles) to high(SystemCAFiles) do begin
if CAFile <> '' then break;
if FileExists(programPath + SystemCAFiles[i]) then CAFile := programPath + SystemCAFiles[i];
end;
{$endif}
for i := low(SystemCAFiles) to high(SystemCAFiles) do begin
if CAFile <> '' then break;
if FileExists(SystemCAFiles[i]) then CAFile := SystemCAFiles[i];
end;
{$ifndef windows}
for i := low(SystemCAPaths) to high(SystemCAPaths) do begin
if CAPath <> '' then break;
if DirectoryExists(SystemCAPaths[i]) then CAPath := SystemCAPaths[i];
end;
{$endif}
end;
function TInternetConfig.equalsUserAgent(const otherConfig: TInternetConfig): boolean;
begin
result := userAgent = otherConfig.userAgent;
end;
function TInternetConfig.equalsProxy(const otherConfig: TInternetConfig): boolean;
begin
if useProxy <> otherConfig.useProxy then exit(false);
if not useProxy then exit(true);
result := (proxyHTTPName = otherConfig.proxyHTTPName) and (proxyHTTPPort = otherConfig.proxyHTTPPort)
and (proxyHTTPSName = otherConfig.proxyHTTPSName) and (proxyHTTPSPort = otherConfig.proxyHTTPSPort)
and (proxySOCKSName = otherConfig.proxySOCKSName) and (proxySOCKSPort = otherConfig.proxySOCKSPort)
and (proxyUsername = otherConfig.proxyUsername) and (proxyPassword = otherConfig.proxyPassword)
end;
procedure TTransfer.beginTransfer(onClear: TTransferClearEvent; onReceivedBlock: TTransferBlockWriteEvent;
const amethod: string; const aurl: TDecodedUrl; const adata: TInternetAccessDataBlock);
begin
onClear();
method := amethod;
decodedUrl := aurl;
url := aurl.combinedExclude([dupUsername, dupPassword, dupLinkTarget]);
data := adata;
//during transfer
writeBlockCallback := onReceivedBlock;
FreeAndNil(inflater); //should be freed in endTransfer, but might have failed because of exceptions during transfer
currentSize := 0;
contentLength := -1; //only used for progress event
//out
HTTPResultCode := -1;
HTTPErrorDetails := '';
receivedHTTPHeaders.Clear;
//do not call OnTransferStart, since that event is triggered once for each request, while this function is called for the each request and again for each redirection;
end;
procedure TTransfer.writeBlock(const Buffer; Count: Longint);
procedure checkForContentEncoding;
var encoding: string;
begin
encoding := receivedHTTPHeaders['content-encoding'];
if encoding = '' then exit;
defaultTransferInflater.injectDecoder(self, encoding);
end;
begin
if (currentSize = 0) and (count > 0) and (defaultTransferInflater <> nil) then
checkForContentEncoding;
currentSize := currentSize + Count;
writeBlockCallback(buffer, count);
if Assigned(ownerAccess.FOnProgress) then begin
if contentLength < 0 then
contentLength := StrToIntDef(receivedHTTPHeaders['content-length'], 0);
ownerAccess.FOnProgress(ownerAccess, currentSize, contentLength);
end;
end;
procedure TTransfer.endTransfer;
begin
if assigned(inflater) then begin
inflater.endTransfer;
FreeAndNil(inflater);
end;
if Assigned(ownerAccess.FOnProgress) then begin
if (currentSize < contentLength) then ownerAccess.FOnProgress(ownerAccess, currentSize, contentLength)
else if contentLength = -1 then ownerAccess.FOnProgress(ownerAccess, 0, 0);
end;
end;
function TInternetAccess.request(method, protocol, host, url, data: string): string;
begin
result := request(method, decodeURL(protocol, host, url), data);
end;
function TInternetAccess.request(const method, fullUrl, data: string): string;
begin
result := request(method, decodeURL(fullUrl), data);
end;
function TInternetAccess.request(method: string; url: TDecodedUrl; data: string): string;
var builder: TStrBuilder;
begin
builder.init(@result);
request(method, url, data.pcharView, TTransferClearEvent(@builder.clear), TTransferBlockWriteEvent(@builder.appendBuffer));
builder.final;
if fconfig.logToPath<>'' then
writeString(fconfig.logToPath, url.combined+'<-DATA:'+data,result);
end;
procedure clearStream(self: TStream);
begin
self.Position := 0;
self.Size := 0;
end;
procedure writeStream(self: TStream; const buffer; size: NativeInt);
begin
self.WriteBuffer(buffer, size);
end;
procedure TInternetAccess.request(const method: string; const url: TDecodedUrl; const uploadData: string; outStream: TStream);
begin
request(method, url, uploadData.pcharView, TTransferClearEvent(makeMethod(@clearStream, outStream)), TTransferBlockWriteEvent(makeMethod(@writeStream, outStream)));
end;
procedure TInternetAccess.request(const method: string; const url: TDecodedUrl; const uploadData: TInternetAccessDataBlock;
const onClear: TTransferClearEvent; const onReceivedBlock: TTransferBlockWriteEvent);
begin
doTransferChecked(onClear, onReceivedBlock, method, url, uploadData, 10);
end;
function TInternetAccess.getLastHTTPHeaders: THTTPHeaderList;
begin
result := lastTransfer.receivedHTTPHeaders;
end;
function TInternetAccess.getLastHTTPResultCode: longint;
begin
result := lastTransfer.HTTPResultCode;
end;
function TInternetAccess.getLastUrl: string;
begin
result := lastTransfer.url;
end;
procedure TInternetAccess.setLastUrl(AValue: string);
begin
lastTransfer.url := AValue;
lastTransfer.decodedUrl := decodeURL(avalue);
end;
procedure TInternetAccess.setConfig(internetConfig: PInternetConfig);
begin
fconfig := internetConfig^;
end;
function TInternetAccess.getConfig: PInternetConfig;
begin
result := @fconfig
end;
procedure TInternetAccess.doTransferChecked(onClear: TTransferClearEvent; onReceivedBlock: TTransferBlockWriteEvent;
method: string; url: TDecodedUrl; data: TInternetAccessDataBlock; remainingRedirects: integer);
var
reaction: TInternetAccessReaction;
message: String;
transfer: TTransfer;
begin
if assigned(FOnTransferStart) then
FOnTransferStart(self, method, url, data);
url.prepareSelfForRequest(lastTransfer.decodedUrl);
transfer := lastTransfer;
method := UpperCase(method);
reaction := iarReject;
while reaction <> iarAccept do begin
url.path := urlEncodeData(url.path, ueURLPath); //remove forbidden characters from url. mostly for Apache HTTPClient, it throws an exception if it they remain
url.params := urlEncodeData(url.params, ueURLQuery);
transfer.beginTransfer(onClear, onReceivedBlock, method, url, data );
doTransferUnchecked(transfer);
transfer.endTransfer;
reaction := iarReject;
case transfer.HTTPResultCode of
200..299: reaction := iarAccept;
301,302,303: if remainingRedirects > 0 then
if striEqual(method, 'POST') then reaction := iarFollowRedirectGET
else reaction := iarFollowRedirectKeepMethod;
304..308: if remainingRedirects > 0 then reaction := iarFollowRedirectKeepMethod;
else reaction := iarReject;
end;
if Assigned(OnTransferReact) then OnTransferReact(self, transfer, reaction);
case reaction of
iarAccept: ; //see above
iarFollowRedirectGET, iarFollowRedirectKeepMethod: begin
if reaction = iarFollowRedirectGET then begin
method := 'GET';
data := default(TInternetAccessDataBlock);
end;
cookies.parseHeadersForCookies(url, transfer.receivedHTTPHeaders); //parse for old url
url := url.resolved(transfer.receivedHTTPHeaders.getHeaderValue(iahLocation));
dec(remainingRedirects);
continue;
end;
iarRetry: ; //do nothing
else begin
message := IntToStr(transfer.HTTPResultCode) + ' ' + transfer.HTTPErrorDetails;
if transfer.HTTPResultCode <= 0 then message := 'Internet Error: ' + message
else message := 'Internet/HTTP Error: ' + message;
raise EInternetException.Create(message + LineEnding + 'when talking to: '+url.combined, transfer.HTTPResultCode);
end;
end;
cookies.parseHeadersForCookies(url, transfer.receivedHTTPHeaders);
end;
lastTransfer := transfer;
//url.username:=''; url.password:=''; url.linktarget:=''; //keep this secret
//lastTransfer.decodedUrl := url;
if assigned(FOnTransferEnd) then
FOnTransferEnd(self, lastTransfer);
end;
function TInternetAccess.getLastErrorDetails(): string;
begin
result := lastTransfer.HTTPErrorDetails;
end;
procedure TCookieManager.clear;
begin
SetLength(cookies, 0);
end;
procedure TCookieManager.setCookie(domain, path: string; const name, value: string; flags: TCookieFlags);
var i:longint;
begin
domain := lowercase(domain);
for i:=0 to high(cookies) do //todo: use a map
if strEqual(cookies[i].name, name) //case-sensitive according to RFC6265 (likely insensitive in RFC 2109, but that is obsolete)
and strEqual(cookies[i].domain, domain) //case-insensitive, but domain is assumed to be normalized as it is not send to the server
and strEqual(cookies[i].path, path) //case-sensitive
then begin
cookies[i].value:=value;
cookies[i].flags:=flags;
exit;
end;
setlength(cookies,length(cookies)+1);
cookies[high(cookies)].domain:=domain;
cookies[high(cookies)].path:=path;
cookies[high(cookies)].name:=name;
cookies[high(cookies)].value:=value;
cookies[high(cookies)].flags:=flags;
end;
//Returns the highest private domain (e.g. www.example.com -> example.com )
//todo: do not count points, but use a list of tlds (so it will works with co.uk)
function isPublicDomain(const domain: string): boolean;
begin
result := not strContains(domain, '.');
end;
function normalizeDomain(const s: string): string;
begin
result := lowercase(s); //should this do xn-- punycoding?
end;
//str is a sub domain of domain
function domainMatches(const str, domain: string): boolean;
//RFC 6265: A string domain-matches a given domain string if at ...
begin
if strEqual(str, domain) then exit(true);
result := strEndsWith(str, domain) and (length(str) > length(domain)) and (str[length(str) - length(domain)] = '.') {and str is not an ip};
end;
//str is a subdirectory of path
function pathMatches(str: string; const path: string): boolean;
begin
if strEqual(str, path) then exit(true);
if not strBeginsWith(str, '/') then str := '/' + str;
str := strUnescapeHex(str, '%');
if strBeginsWith(str, path) then begin
if strEndsWith(path, '/')
or (length(str) = length(path))
or ((length(str) > length(path)) and (str[length(path)+1] = '/' ) ) then
exit(true);
end;
result := false;
end;
procedure TCookieManager.parseHeadersForCookies(const source: TDecodedUrl; headers: THTTPHeaderList; allowUnsecureXidelExtensions: boolean);
const WSP = [' ',#9];
var i:longint;
header:string;
ci, headerlen: Integer;
function parseNameValuePair(out name, value: string; needEqualSign: boolean): boolean;
var
nameStart, nameEnd: integer;
valueStart, valueEnd: integer;
begin
while (i <= headerlen) and (header[i] in WSP) do i+=1;
nameStart := i;
while (i <= headerlen) and not (header[i] in ['=', ';']) do i+=1;
nameEnd := i - 1;
while (nameEnd > nameStart) and (header[nameEnd] in WSP) do dec(nameEnd);
name:=copy(header,nameStart,nameEnd - nameStart + 1);
if (i > headerlen) or (header[i] <> '=') then begin
value := '';
exit(not needEqualSign);
end;
inc(i);
while (i <= headerlen) and (header[i] in WSP) do i+=1;
valueStart := i;
while (i <= headerlen) and (header[i] <> ';') do i+=1;
valueEnd := i - 1;
while (valueEnd > valueStart) and (header[valueEnd] in WSP) do dec(valueEnd);
value:=copy(header,valueStart,valueEnd - valueStart + 1 );
result := true;
end;
var name, value, domain, path, tName, tValue: string;
flags: TCookieFlags;
lastSlash: LongInt;
begin
for ci := 0 to headers.Count - 1 do
case TInternetAccess.parseHeaderLineKind(headers.Strings[ci]) of
iahSetCookie: begin
header := TInternetAccess.parseHeaderLineValue(headers.Strings[ci]);
headerlen := length(header);
i := 1;
if not parseNameValuePair(name, value, true) then continue;
domain := '';
path := '';
flags := [];
while i < headerlen do begin
inc(i);
if not parseNameValuePair(tname, tvalue, false) then break;
case lowercase(tname) of
//'expires': ;
//'max-age': ;
'domain': begin
if strBeginsWith(tvalue, '.') then delete(tvalue, 1, 1);
domain := normalizeDomain(tvalue);
end;
'path': if strBeginsWith(tvalue, '/') then path := tvalue;
'secure': Include(flags, cfSecure);
//'httponly': Include(flags, cfHttpOnly);
'hostonly': if allowUnsecureXidelExtensions then include(flags, cfHostOnly);
end;
end;
if domain <> '' then begin
//exclude(flags, cfHostOnly);
if not allowUnsecureXidelExtensions then
if not domainMatches(normalizeDomain(source.host), domain) or isPublicDomain(domain) then continue; //only allow for super domains and private ones
end else begin;
include(flags, cfHostOnly);
domain := normalizeDomain(source.host);
end;
if path = '' then begin
path := source.path;
if not strBeginsWith(path, '/') then path := '/'
else begin
lastSlash := strLastIndexOf(path, '/');
if lastSlash = 1 then path := '/'
else path := copy(path, 1, lastSlash - 1);
end;
end;
setCookie(domain, strUnescapeHex(path, '%'), name, value, flags);
end;
else;
end;
end;
function TCookieManager.makeCookieHeader(const target: TDecodedUrl): string;
begin
result:='';
if length(cookies)=0 then exit;
result := TInternetAccess.makeHeaderLine(iahCookie, makeCookieHeaderValueOnly(target));
end;
function TCookieManager.makeCookieHeaderValueOnly(const target: TDecodedUrl): string;
var
i: Integer;
domain: String;
builder: TStrBuilder;
begin
result:='';
if length(cookies)=0 then exit;
domain := normalizeDomain(target.host);
builder.init(@result);
for i := 0 to high(cookies) do
if (strEqual(cookies[i].domain, domain)
or (not (cfHostOnly in cookies[i].flags) and domainMatches(domain, cookies[i].domain))) //also send of super domain
and (pathMatches(target.path, cookies[i].path))
and (not (cfSecure in cookies[i].flags) or ( striEqual(target.protocol, 'https') ) )
then begin
if builder.count <> 0 then builder.append('; ');
builder.append(cookies[i].name);
builder.append('=');
builder.append(cookies[i].value);
end;
builder.final;
end;
function TCookieManager.serializeCookies: string;
var builder: TStrBuilder;
i: Integer;
begin
result:='';
with builder do begin
init(@result);
for i := 0 to high(cookies) do with cookies[i] do begin
append('Set-Cookie: ');
append(name);
append('=');
append(value);
append('; Domain=');
append(domain);
append('; Path=');
append( TInternetAccess.urlEncodeData(path, ueURLPath));
if cfHostOnly in flags then append('; HostOnly');
if cfSecure in flags then append('; Secure');
append(#13#10);
end;
final;
end;
end;
procedure TCookieManager.loadFromFile(const fn: string);
var temp: THTTPHeaderList;
tempurl: TDecodedUrl;
begin
temp := THTTPHeaderList.Create;
try
temp.LoadFromFile(fn);
tempurl := decodeURL('file:///'); //this is not actually used in parseHeadersForCookies
parseHeadersForCookies(tempurl, temp, true);
finally
temp.free;
end;
end;
procedure TCookieManager.saveToFile(const fn: string);
begin
strSaveToFileUTF8(fn, serializeCookies);
end;
class function TInternetAccess.parseHeaderLineKind(const line: string): THeaderKind;
function check(const s: string): boolean;
var
i: Integer;
begin
result := false;
if striBeginsWith(line, s) then begin
for i := length(s) + 1 to length(line) do
case line[i] of
' ',#9,#10,#13: ;
':': exit(true);
else exit(false);
end;
end;
end;
begin
result := iahUnknown;
if line = '' then exit();
case line[1] of
'c', 'C': if check('content-type') then exit(iahContentType)
else if check('cookie') then exit(iahCookie)
else if check('content-disposition') then exit(iahContentDisposition);
'a', 'A': if check('accept') then exit(iahAccept);
'l', 'L': if check('location') then exit(iahLocation);
'r', 'R': if check('referer') then exit(iahReferer);
's', 'S': if check('set-cookie') then exit(iahSetCookie);
'u', 'U': if check('user-agent') then exit(iahUserAgent);
end;
end;
class function TInternetAccess.parseHeaderLineValue(const line: string): string;
begin
result := trim(strCopyFrom(line, pos(':', line)+1))
end;
class function TInternetAccess.parseHeaderLineName(const line: string): string;
begin
result := copy(line, 1, pos(':', line) - 1);
end;
class function TInternetAccess.makeHeaderLine(const name, value: string): string;
begin
result := name + ': ' + value;
end;
class function TInternetAccess.makeHeaderLine(const kind: THeaderKind; const value: string): string;
begin
result := makeHeaderName(kind) + ': '+value;
end;
class function TInternetAccess.makeHeaderName(const kind: THeaderKind): string;
begin
case kind of
iahContentType: result := 'Content-Type';
iahContentDisposition: result := 'Content-Disposition';
iahAccept: result := 'Accept';
iahReferer: result := 'Referer';
iahLocation: result := 'Location';
iahSetCookie: result := 'Set-Cookie';
iahCookie: result := 'Cookie';
iahUserAgent: result := 'User-Agent';
else raise EInternetException.create('Internal error: Unknown header line kind');
end;
end;
procedure TInternetAccess.enumerateAdditionalHeaders(const atransfer: TTransfer; callback: THeaderEnumCallback; callbackData: pointer);
procedure callKnownKind(kind: THeaderKind; value: string);
begin
callback(callbackData, kind, makeHeaderName(kind), value);
end;
var
hadHeader: array[THeaderKind] of Boolean = (false, false, false, false, false, false, false, false, false);
i: Integer;
kind: THeaderKind;
temp: String;
begin
for i := 0 to additionalHeaders.Count - 1 do begin
kind := parseHeaderLineKind(additionalHeaders.Strings[i]);
hadHeader[kind] := true;
callback(callbackData, kind, parseHeaderLineName(additionalHeaders.Strings[i]), parseHeaderLineValue(additionalHeaders.Strings[i]));
end;
if (not hadHeader[iahReferer]) and (lastUrl <> '') then callKnownKind( iahReferer, lastUrl );
if (not hadHeader[iahAccept]) then callKnownKind( iahAccept, 'text/html,application/xhtml+xml,application/xml,text/*,*/*' );
if (not hadHeader[iahCookie]) and (length(cookies.cookies) > 0) then begin
temp := cookies.makeCookieHeaderValueOnly(atransfer.decodedUrl);
if temp <> '' then callKnownKind( iahCookie, temp);
end;
if (not hadHeader[iahContentType]) and (not atransfer.data.isEmpty) then callKnownKind(iahContentType, ContentTypeForData);
//if (not hadHeader[iahUserAgent]) then callKnownKind( iahUserAgent, internetConfig^.userAgent ); no central handling of agent, it is too different between the APIs
end;
function TInternetAccess.getFinalMultipartFormData: string;
var
boundary: String;
begin
boundary := '';
result := multipartFormData.compose(boundary);
ContentTypeForData := ContentTypeMultipart + '; boundary=' + boundary;
multipartFormData.clear;
end;
constructor THTTPHeaderList.Create;
begin
inherited;
NameValueSeparator := ':';
end;
function THTTPHeaderList.getHeaderValue(kind: THeaderKind): string;
var
i: Integer;
begin
for i:= 0 to count - 1 do
if TInternetAccess.parseHeaderLineKind(Strings[i]) = kind then
exit(TInternetAccess.parseHeaderLineValue(Strings[i]));
exit('');
end;
function THTTPHeaderList.getHeaderValue(header: string): string;
var
i: Integer;
begin
header := header + ':';
for i:= 0 to count - 1 do
if striBeginsWith(Strings[i], header) then
exit(trim(strCopyFrom(Strings[i], length(header) + 1)));
exit('');
end;
function THTTPHeaderList.getContentDispositionFileNameTry(out filename: string): Boolean;
begin
result := parseContentDispositionFileNameTry(getHeaderValue(iahContentDisposition), filename);
end;
procedure THTTPHeaderList.add(const name, value: string);
begin
add(name + ': '+value);
end;
class function THTTPHeaderList.parseCharacterSetEncodedHeaderRFC5987AsUtf8Try(value: TPCharView; out utf8: string): Boolean;
var
enc, country: TPCharView;
codepage: TSystemCodePage;
begin
result := value.splitRightOfFind(enc, '''');
result := result and value.splitRightOfFind(country, '''');
if not result then exit;
codepage := strEncodingFromName(enc.ToString);
if codepage = CP_NONE then exit(false);
utf8 := strConvert(strUnescapeHex(value.ToString, '%'), codepage, cp_acp);
end;
class function THTTPHeaderList.parseContentDispositionFileNameTry(const contentDisposition: string; out filename: string): Boolean;
var
directive, temp: String;
directives: sysutils.TStringArray;
name, value: TPCharView;
begin
result := false;
filename := '';
if contentDisposition.IsEmpty then exit;
if not (contentDisposition[1] in ['a'..'z','A'..'Z']) then exit; //should be attachment or inline; but allow unknown, future types
directives := contentDisposition.Split(';');
for directive in directives do begin
if not directive.pcharView.splitAtFind(name, '=', value) then continue;
name.trim();
value.trim();
if name = 'filename*' then begin
result := true;
if parseCharacterSetEncodedHeaderRFC5987AsUtf8Try(value, temp) then begin
filename := temp;
exit(true);
end;
end else if name = 'filename' then begin
if value.beginsWith('"') and value.endsWith('"') then begin
value.leftOfLast(1);
value.rightOfFirst(1);
end;
filename := value.ToString;
result := true;
end;
end;
end;
function TInternetAccess.getLastContentType: string;
begin
result := lastHTTPHeaders.getHeaderValue(iahContentType);
end;
constructor TInternetAccess.create();
begin
create(defaultInternetConfiguration);
end;
constructor TInternetAccess.create(const internetConfig: TInternetConfig);
begin
if ClassType = TInternetAccess then
raise eabstracterror.create('Abstract internet class created (TInternetAccess)');
additionalHeaders := THTTPHeaderList.Create;
lastTransfer.receivedHTTPHeaders := THTTPHeaderList.Create;
lastTransfer.ownerAccess := self;
ContentTypeForData := ContentTypeUrlEncoded;
setConfig(@internetConfig);
if fconfig.userAgent='' then begin
fconfig.userAgent:='Mozilla/5.0 (compatible)';
setConfig(@fconfig);
end;
end;
destructor TInternetAccess.Destroy;
begin
FreeAndNil(lastTransfer.receivedHTTPHeaders); //created by init
additionalHeaders.Free;
FreeAndNil(lastTransfer.inflater); //should be freed in endTransfer, but might have failed because of exceptions during transfer
inherited Destroy;
end;
function TInternetAccess.post(const totalUrl, data: string): string;
begin
result := request('POST', totalUrl, data);
end;
function TInternetAccess.post(const protocol, host, url: string; data: string): string;
begin
result:=request('POST',protocol,host,url,data);
end;
procedure TInternetAccess.get(const totalUrl: string; stream: TStream);
begin
request('GET', decodeURL(totalUrl), '', stream);
end;
function TInternetAccess.get(const totalUrl: string): string;
begin
result:=request('GET', totalUrl, '');
end;
procedure TInternetAccess.get(const protocol, host, url: string; stream: TStream);
begin
request('GET', decodeURL(protocol, host, url), '', stream);
end;
function TInternetAccess.get(const protocol, host, url: string): string;
begin
result:=request('GET', protocol, host, url, '');
end;
function TInternetAccess.existsConnection(): boolean;
begin
result:=false;
try
if fconfig.connectionCheckPage = '' then
result:=get('https','www.google.de','/')<>''
else
result:=get('https',fconfig.connectionCheckPage,'/')<>'';
except
end;
end;
function TInternetAccess.needConnection(): boolean;
begin
result:=existsConnection();
end;
procedure TInternetAccess.closeOpenedConnections();
begin
end;
class function TInternetAccess.urlEncodeData(const data: string; encodingModel: TUrlEncodingModel): string;
const allowedUnreserved = ['0'..'9', 'A'..'Z', 'a'..'z', '-', '_', '.', '!', '~', '*', '''', '(', ')', '%'];
allowedPath = allowedUnreserved + [':','@','&','=','+','$',',', ';','/'];
allowedURI = allowedUnreserved + [';','/','?',':','@','&','=','+','$',',','[',']'];
allChars = [#0..#255];
const ENCODE_TABLE: array[TUrlEncodingModel] of TCharSet = (
allChars - [#$20, #$2A, #$2D, #$2E, #$30..#$39, #$41..#$5A, #$5F, #$61..#$7A],
//Multipart name encoding:
//this is written in the HTML5 standard.
//this is nothing like the browser behaviour. Firefox converts " to \" and line break to space
[#$A, #$D, #$22],
allChars - allowedPath,
allChars - allowedURI,
allChars - ['a'..'z', 'A'..'Z', '0'..'9', '-', '_', '.', '~'],
allChars - [#32..#126],
allChars - ([#$20..#$7E] - ['<','>','"',' ','{','}','|','\','^','`'])
);
var
i: Integer;
begin
result:=strEscapeToHex(data, ENCODE_TABLE[encodingModel], '%');
if encodingModel = ueHTMLForm then begin
for i := 1 to length(result) do
if result[i] = ' ' then result[i] := '+';
end;
end;
class function TInternetAccess.urlEncodeData(data: TStringList; encodingModel: TUrlEncodingModel): string;
var
i: Integer;
begin
Result:='';
for i:=0 to data.Count-1 do begin
if result <> '' then result+='&';
result+=urlEncodeData(data.Names[i], encodingModel)+'='+urlEncodeData(data.ValueFromIndex[i], encodingModel);
end;
end;
class function TInternetAccess.reactFromCodeString(const codes: string; actualCode: integer;var reaction: TInternetAccessReaction): string;
function matches(filter: string; value: string): boolean;
var
i: Integer;
begin
if length(filter) <> length(value) then exit(false);
for i := 1 to length(filter) do
if (filter[i] <> 'x') and (filter[i] <> value[i]) then
exit(false);
result := true;
end;
var
errors: TStringArray;
cur: TStringArray;
i: Integer;
begin
result := '';
errors := strSplit(codes, ',');
for i:=0 to high(errors) do begin
cur := strSplit(errors[i], '=');
if matches(trim(cur[0]), inttostr(actualCode)) then begin
result := trim(cur[1]);
case result of
'accept', 'ignore', 'skip': reaction := iarAccept;
'retry': reaction := iarRetry;
'redirect': reaction := iarFollowRedirectGET;
'redirect-data': reaction := iarFollowRedirectKeepMethod;
'abort': reaction := iarReject
end;
exit;
end;
end;
end;
threadvar theDefaultInternet: TInternetAccess;
function httpRequest(url: string): string;
begin
result:=defaultInternet.get(url);
end;
function httpRequest(url: string; rawpostdata: string): string;
begin
result:=defaultInternet.post(url, rawpostdata);
end;
function httpRequest(url: string; postdata: TStringList): string;
begin
result := httpRequest(url, TInternetAccess.urlEncodeData(postdata, ueHTMLForm));
end;
function httpRequest(const method, url, rawdata: string): string;
begin
result := defaultInternet.request(method, url, rawdata);
end;
function defaultInternet: TInternetAccess;
begin
if theDefaultInternet <> nil then exit(theDefaultInternet);
if defaultInternetAccessClass = nil then
raise Exception.Create('You need to set defaultInternetAccessClass to choose between synapse, wininet or android. Or you can add one of the units synapseinternetaccess, okhttpinternetaccecss or w32internetaccess to your uses clauses (if that unit actually will be compiled depends on the active defines).');
theDefaultInternet := defaultInternetAccessClass.create;
result := theDefaultInternet;
end;
procedure freeThreadVars;
begin
FreeAndNil(theDefaultInternet);
end;
initialization
defaultInternetConfiguration.checkSSLCertificates := true;
defaultInternetConfiguration.tryDefaultConfig := true;
finalization
freeThreadVars;
end.
|
unit TestDirectPartitionTrimmer;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework,
Mock.Getter.TrimBasics.Factory,
Mock.Getter.VolumeBitmap,
Mock.DeviceTrimmer,
Thread.Trim.Helper.Partition.Direct;
type
// Test methods for class TPartitionTrimmer
TestTDirectPartitionTrimmer = class(TTestCase)
strict private
FPartitionTrimmer: TDirectPartitionTrimmer;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBasicTrim;
end;
implementation
procedure TestTDirectPartitionTrimmer.SetUp;
begin
TVolumeBitmapGetter.CreateBitmapStorage;
TDeviceTrimmer.CreateTrimOperationLogger;
FPartitionTrimmer := TDirectPartitionTrimmer.Create('');
end;
procedure TestTDirectPartitionTrimmer.TearDown;
begin
FPartitionTrimmer.Free;
FPartitionTrimmer := nil;
TVolumeBitmapGetter.FreeBitmapStorage;
TDeviceTrimmer.FreeTrimOperationLogger;
end;
procedure TestTDirectPartitionTrimmer.TestBasicTrim;
const
NullSyncronization: Mock.Getter.TrimBasics.Factory.TTrimSynchronization =
(IsUIInteractionNeeded: False);
var
BasicTest: TBitmapBuffer;
Result: TTrimOperationList;
begin
TVolumeBitmapGetter.SetLength(8);
BasicTest[0] := $65; //0110 0101
TVolumeBitmapGetter.AddAtBitmapStorage(BasicTest);
FPartitionTrimmer.TrimPartition(NullSyncronization);
Result := TDeviceTrimmer.GetTrimOperationLogger;
CheckEquals(3, Result.Count, 'Result.Count');
CheckEquals(1, Result[0].StartLBA, 'Result[0].StartLBA');
CheckEquals(1, Result[0].LengthInLBA, 'Result[0].LengthInLBA');
CheckEquals(3, Result[1].StartLBA, 'Result[1].StartLBA');
CheckEquals(2, Result[1].LengthInLBA, 'Result[1].LengthInLBA');
CheckEquals(7, Result[2].StartLBA, 'Result[2].StartLBA');
CheckEquals(1, Result[2].LengthInLBA, 'Result[2].LengthInLBA');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTDirectPartitionTrimmer.Suite);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.DlgPushChannelsU;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.Generics.Collections, FMX.ListView.Types, FMX.StdCtrls, FMX.ListView,
FMX.ListView.Appearances, System.JSON, FMX.Controls.Presentation,
FMX.ListView.Adapters.Base, FMX.Layouts;
type
TDlgPushChannels = class(TForm)
GroupBox2: TGroupBox;
CheckBoxAllChannels: TCheckBox;
ListView1: TListView;
ButtonOK: TButton;
ButtonCancel: TButton;
Layout1: TLayout;
procedure ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
procedure CheckBoxAllChannelsChange(Sender: TObject);
private
FChannels: TArray<string>;
FChecking: Boolean;
procedure SetChannels(const Value: TArray<string>);
procedure UpdateCheckAll;
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Channels: TArray<string> write SetChannels;
procedure Load(const AJSON: TJSONObject);
procedure Save(const AJSON: TJSONObject);
end;
var
DlgPushChannels: TDlgPushChannels;
implementation
{$R *.fmx}
{ TDlgPushChannels }
procedure TDlgPushChannels.CheckBoxAllChannelsChange(Sender: TObject);
begin
if not FChecking then
ListView1.Items.CheckAll(CheckBoxAllChannels.IsChecked);
end;
constructor TDlgPushChannels.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TDlgPushChannels.Destroy;
begin
inherited;
end;
procedure TDlgPushChannels.ListView1ItemClick(const Sender: TObject;
const AItem: TListViewItem);
begin
UpdateCheckAll;
end;
procedure TDlgPushChannels.Load(const AJSON: TJSONObject);
var
LChannels: TJSONArray;
LValue: TJSONValue;
LDictionary: TDictionary<string, Integer>;
S: string;
I: Integer;
begin
LDictionary := TDictionary<string, Integer>.Create;
try
for S in FChannels do
LDictionary.Add(S, LDictionary.Count);
if AJSON.TryGetValue<TJSONArray>('channels', LChannels) then
for LValue in LChannels do
if LDictionary.TryGetValue(LValue.Value, I) then
ListView1.Items[I].Checked := True;
UpdateCheckAll;
finally
LDictionary.Free;
end;
end;
procedure TDlgPushChannels.UpdateCheckAll;
begin
FChecking := True;
try
CheckBoxAllChannels.IsChecked := ListView1.Items.CheckedCount = ListView1.
Items.Count;
finally
FChecking := False;
end;
end;
procedure TDlgPushChannels.Save(const AJSON: TJSONObject);
var
LJSONChannels: TJSONArray;
LItem: TListViewItem;
begin
AJSON.RemovePair('channels');
LJSONChannels := TJSONArray.Create;
for LItem in ListView1.Items do
if LItem.Checked then
LJSONChannels.Add(FChannels[LItem.Index]);
AJSON.AddPair('channels', LJSONChannels);
end;
procedure TDlgPushChannels.SetChannels(const Value: TArray<string>);
var
S: string;
begin
FChannels := Value;
for S in FChannels do
ListView1.Items.Add.Text := S;
end;
end.
|
{PROGRAM hello (output);
Write 'Hello, world.' ten times
VAR
i : integer;
BEGIN hello
FOR i := 1 TO 10 DO BEGIN
writeln('Hello, world.');
END;
END hello}
0 1 20 000000000045 0 2
|
unit UISearchController;
interface
type
ISearchController = interface
procedure Close;
procedure Search(Value : String);
procedure Add;
procedure Update(Id : String);
procedure Delete(Id : String);
procedure UpdateFilters;
end;
implementation
end.
|
{
@html(<b>)
ISAPI Server Connection
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
Introducing the @html(<b>) @Link(TRtcISAPIServer) @html(</b>) component: @html(<br>)
Server connection component for ISAPI communication using HTTP requests.
}
unit rtcISAPISrv;
{$INCLUDE rtcDefs.inc}
interface
uses
Windows, Classes, isapi2,
rtcSyncObjs,
rtcInfo,
rtcConn,
rtcFastStrings,
rtcDataSrv,
rtcISAPIApp;
type
{ @Abstract(ISAPI Server Connection component)
Methods to check first:
@html(<br>)
@Link(TRtcDataServer.Request), @Link(TRtcConnection.Read) - Read client request
@html(<br>)
@Link(TRtcDataServer.Response), @Link(TRtcISAPIServer.WriteHeader), @Link(TRtcISAPIServer.Write) - Write result to client
@html(<br><br>)
Events to check first:
@html(<br>)
@Link(TRtcServer.OnListenStart) - Module Loaded
@html(<br>)
@Link(TRtcConnection.OnConnect) - new Client connected
@html(<br>)
@Link(TRtcConnection.OnDataReceived) - Data available from client (check @Link(TRtcDataServer.Request))
@html(<br>)
@Link(TRtcConnection.OnDataSent) - Data sent to client (buffer now empty)
@html(<br>)
@Link(TRtcConnection.OnDisconnect) - one Client disconnected
@html(<br>)
@Link(TRtcServer.OnListenStop) - Module Unloading
@html(<br><br>)
Check @Link(TRtcDataServer), @Link(TRtcServer) and @Link(TRtcConnection) for more info.
}
TRtcISAPIServer = class(TRtcDataServer)
private
FCS:TRtcCritSec;
ConnPool:TList;
FWritten:boolean;
FWriteBuffer:TRtcHugeString;
FForce1Thread: boolean;
function GetConnection:TRtcISAPIServer;
procedure PutConnection(conn:TRtcISAPIServer);
procedure FreeConnection(conn:TRtcISAPIServer);
procedure CloseAllConnections;
protected
// @exclude
procedure CopyFrom(Dup: TRtcServer); override;
// @exclude
procedure SetParams; override;
// @exclude
function CreateProvider:TObject; override;
// @exclude
procedure TriggerDataSent; override;
// @exclude
procedure TriggerDataReceived; override;
// @exclude
procedure TriggerDataOut; override;
// @exclude
procedure SetRequest(const Value: TRtcServerRequest); override;
// @exclude
procedure SetResponse(const Value: TRtcServerResponse); override;
public
// This will always return TRUE for TRtcISAPIServer.
function isExtension:boolean; override;
// @exclude
procedure ExecuteRequest(var ECB: TEXTENSION_CONTROL_BLOCK);
// @exclude
class procedure Load;
// @exclude
class procedure UnLoad;
// @exclude
class function HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD;
// @exclude
constructor Create(AOwner: TComponent); override;
// @exclude
destructor Destroy; override;
// Constructor
class function New:TRtcISAPIServer;
{ Flush all buffered data.
@html(<br>)
When using 'Write' without calling 'WriteHeader' before, all data
prepared by calling 'Write' will be buffered until your event
returns to its caller (automatically upon your event completion) or
when you first call 'Flush'. Flush will check if Response.ContentLength is set
and if not, will set the content length to the number of bytes buffered.
@html(<br>)
Flush does nothing if WriteHeader was called for this response.
@exclude}
procedure Flush; override;
// You can call WriteHeader to send the Response header out.
procedure WriteHeader(SendNow:boolean=True); overload; override;
{ You can call WriteHeader with empty 'HeaderText' parameter to
tell the component that you do not want any HTTP header to be sent. }
procedure WriteHeader(const HeaderText: string; SendNow:boolean=True); overload; override;
// Use Write to send the Content (document body) out.
procedure Write(const s:string=''); override;
published
{ Set "ForceSingleThread" to TRUE if you want your ISAPI extension to handle
ONLY one request at a time. This is useful *ONLY* if you don't know how to
write thread-safe code and are experiencing problems with your ISAPI extension.
Setting this property to TRUE will force all clients to "stand in a line"
and wait for their turn. If your ISAPI has to serve large files, it won't
be capable of handling more than 1 client at a time, since most clients
will disconnect themselves after a specific time-out period. }
property ForceSingleThread:boolean read FForce1Thread write FForce1Thread default False;
end;
implementation
uses
SysUtils,
rtcConnProv,
rtcISAPISrvProv; // ISAPI Server Provider
type
TMyProvider = TRtcISAPIServerProvider;
var
MainISAPIServer:TRtcISAPIServer=nil;
MainISAPICS:TRtcCritSec=nil;
{ TRtcISAPIServer }
constructor TRtcISAPIServer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
// Make the first instance a global instance
if not assigned(MainISAPIServer) then
begin
MainISAPIServer:=self;
MainISAPICS:=TRtcCritSec.Create;
end;
FCS:=TRtcCritSec.Create;
FWriteBuffer:=TRtcHugeString.Create;
FWritten:=False;
FForce1Thread:=False;
end;
destructor TRtcISAPIServer.Destroy;
begin
// If this is the global instance, remove pointer
if self=MainISAPIServer then
begin
MainISAPIServer:=nil;
MainISAPICS.Free;
MainISAPICS:=nil;
end;
CloseAllConnections;
FCS.Free;
FWriteBuffer.Free;
inherited;
end;
function TRtcISAPIServer.GetConnection:TRtcISAPIServer;
begin
if FForce1Thread then
MainISAPICS.Enter;
try
Result:=nil;
FCS.Enter;
try
if assigned(ConnPool) then
begin
if ConnPool.Count > 0 then
begin
Result:= ConnPool.items[ConnPool.Count-1];
ConnPool.Delete(ConnPool.Count-1);
end;
end;
finally
FCS.Leave;
end;
{ Now we either have the connection,
or we need to create one. }
if Result=nil then
begin
TriggerConnectionAccepting;
Result:=TRtcISAPIServer(self.copyOf);
end;
except
if FForce1Thread then
MainISAPICS.Leave;
raise;
end;
end;
procedure TRtcISAPIServer.PutConnection(conn:TRtcISAPIServer);
begin
try
FCS.Enter;
try
if not assigned(ConnPool) then
ConnPool:=TList.Create;
ConnPool.Add(conn);
finally
FCS.Leave;
end;
finally
if FForce1Thread then
MainISAPICS.Leave;
end;
end;
procedure TRtcISAPIServer.FreeConnection(conn:TRtcISAPIServer);
begin
try
Conn.Release;
finally
if FForce1Thread then
MainISAPICS.Leave;
end;
end;
procedure TRtcISAPIServer.CloseAllConnections;
var
i :integer;
mycon :TRtcISAPIServer;
begin
FCS.Enter;
try
if assigned(ConnPool) then
begin
for i:= 0 to ConnPool.count - 1 do
begin
mycon:= TRtcISAPIServer(ConnPool.items[i]);
mycon.Release;
end;
ConnPool.Clear;
ConnPool.Free;
ConnPool:=nil;
end;
finally
FCS.Leave;
end;
end;
class function TRtcISAPIServer.New: TRtcISAPIServer;
begin
Result:=Create(nil);
end;
function TRtcISAPIServer.CreateProvider:TObject;
begin
if not assigned(Con) then
begin
Con:=TMyProvider.Create;
SetTriggers;
end;
Result:=Con;
end;
procedure TRtcISAPIServer.CopyFrom(Dup: TRtcServer);
begin
inherited CopyFrom(Dup);
end;
procedure TRtcISAPIServer.SetParams;
begin
inherited;
if assigned(Con) then
begin
TMyProvider(Con).Request:=Request;
TMyProvider(Con).Response:=Response;
end;
end;
procedure TRtcISAPIServer.WriteHeader(SendNow:boolean=True);
begin
if assigned(Con) and (State<>conInactive) then
begin
if Response.Sending then
raise Exception.Create('Error! Sending multiple headers for one request.');
Timeout.DataSending;
TMyProvider(Con).WriteHeader;
end;
end;
procedure TRtcISAPIServer.WriteHeader(const HeaderText: string; SendNow:boolean=True);
begin
if assigned(Con) and (State<>conInactive) then
begin
if Response.Sending then
raise Exception.Create('Error! Sending multiple headers for one request.');
Timeout.DataSending;
TMyProvider(Con).WriteHeader(HeaderText);
end;
end;
procedure TRtcISAPIServer.Write(const s: string='');
begin
if assigned(Con) and (State<>conInactive) then
begin
if Response.Sent then
raise Exception.Create('Error! Answer allready sent for this request.');
if Response.Sending then
begin
{ Header is out }
if Response['Content-Length']<>'' then
if Response.ContentLength - Response.ContentOut < length(s) then
raise Exception.Create('Error! Sending more data out than specified in header.');
{ Data size is known or unimportant.
We can just write the string out, without buffering }
Con.Write(s);
end
else
begin
if (Response['CONTENT-LENGTH']<>'') and not FWritten then // Direct writing if header was sent out.
begin
{ Content length defined and no data buffered,
send out header prior to sending first content bytes }
WriteHeader;
if Response.ContentLength - Response.ContentOut < length(s) then
raise Exception.Create('Error! Sending more data out than specified in header.');
Con.Write(s);
end
else
begin
{ Header is not out.
Buffer all Write() operations,
so we can determine content size and write it all out in a flush. }
FWritten:=True;
FWriteBuffer.Add(s);
end;
end;
end;
end;
procedure TRtcISAPIServer.Flush;
var
Temp:string;
begin
if not FWritten then
Exit
else
FWritten:=False; // so we don't re-enter this method.
if assigned(Con) and (State<>conInactive) then
begin
Timeout.DataSending;
if Response.Sent then
raise Exception.Create('Error! Answer allready sent for this request.');
if not Response.Sending then
begin
if Response['CONTENT-LENGTH']='' then // length not specified
Response.ContentLength:=FWriteBuffer.Size;
TMyProvider(Con).WriteHeader;
end;
if FWriteBuffer.Size>0 then
begin
Temp:= FWriteBuffer.Get;
FWriteBuffer.Clear;
Con.Write(Temp);
Temp:='';
end;
end;
end;
procedure TRtcISAPIServer.TriggerDataReceived;
begin
inherited;
Flush;
end;
procedure TRtcISAPIServer.TriggerDataSent;
begin
if FWriteCount>0 then
Timeout.DataSent;
EnterEvent;
try
if FWriteCount>0 then
begin
CallDataSent;
Flush;
if Response.Done then
if Request.Close then
Disconnect; // make sure we close the connection, as requested by the client.
end;
if not isClosing then
begin
CallReadyToSend;
Flush;
if (FWriteCount>0) and Response.Done then
if Request.Close then
Disconnect; // make sure we close the connection, as requested by the client.
end;
finally
LeaveEvent;
end;
end;
procedure TRtcISAPIServer.TriggerDataOut;
begin
inherited;
Flush;
end;
procedure TRtcISAPIServer.SetRequest(const Value: TRtcServerRequest);
begin
inherited SetRequest(Value);
if assigned(Con) then
TMyProvider(Con).Request:=Request;
end;
procedure TRtcISAPIServer.SetResponse(const Value: TRtcServerResponse);
begin
inherited SetResponse(Value);
if assigned(Con) then
TMyProvider(Con).Response:=Response;
end;
class function TRtcISAPIServer.HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD;
var
Server:TRtcISAPIServer;
begin
if assigned(MainISAPIServer) then
begin
Result:=HSE_STATUS_SUCCESS;
Server:=MainISAPIServer.GetConnection;
try
Server.EnterEvent;
try
Server.ExecuteRequest(ECB);
if not Server.Response.Sent then
raise Exception.Create('Response not sent! Need to send complete response from ISAPI.'); // Result:=HSE_STATUS_PENDING;
finally
Server.LeaveEvent;
end;
except
on E:Exception do
begin
{ If an exception happens, we do not want to keep the object.
This is to avoid future problems with this object,
since it could now be in a "limb" state. }
MainISAPIServer.FreeConnection(Server);
raise;
end;
end;
MainISAPIServer.PutConnection(Server);
end
else
raise Exception.Create('No ISAPI Server component found.');
end;
procedure TRtcISAPIServer.ExecuteRequest(var ECB: TEXTENSION_CONTROL_BLOCK);
begin
TMyProvider(Con).Connect(ECB);
TMyProvider(Con).ExecuteRequest;
end;
class procedure TRtcISAPIServer.Load;
begin
if assigned(MainISAPIServer) then
MainISAPIServer.Listen;
end;
class procedure TRtcISAPIServer.UnLoad;
begin
if assigned(MainISAPIServer) then
MainISAPIServer.StopListen;
end;
function TRtcISAPIServer.isExtension: boolean;
begin
Result:=True;
end;
function GetModuleName(Module: HMODULE): string;
var
ModName: array[0..MAX_PATH] of Char;
begin
SetString(Result, ModName, GetModuleFileName(Module, ModName, SizeOf(ModName)));
end;
initialization
AppFileName:=ExpandUNCFileName(GetModuleName(HInstance));
end.
|
unit uLivroModel;
interface
uses
uEnumerado, FireDAC.Comp.Client;
type
TLivroModel = class
private
FAcao: TAcao;
FCodigo: string;
FTitulo: string;
FAutor: string;
FAno: Integer;
FLocalizacao: integer;
procedure SetAcao(const Value: TAcao);
procedure SetAno(const Value: Integer);
procedure SetAutor(const Value: string);
procedure SetCodigo(const Value: string);
procedure SetLocalizacao(const Value: integer);
procedure SetTitulo(const Value: string);
public
function Obter: TFDQuery;
function Buscar: TFDQuery;
function Salvar: Boolean;
function ObterNome: String;
function ObterDados: TFDQuery;
function BuscaAvancada: TFDQuery;
property Codigo: string read FCodigo write SetCodigo;
property Titulo: string read FTitulo write SetTitulo;
property Autor: string read FAutor write SetAutor;
property Ano: Integer read FAno write SetAno;
property Localizacao: integer read FLocalizacao write SetLocalizacao;
property Acao: TAcao read FAcao write SetAcao;
end;
implementation
{ TLivro }
uses uLivroDao;
function TLivroModel.Obter: TFDQuery;
var
Dao: TLivroDao;
begin
Dao := TLivroDao.Create;
try
Result := Dao.Obter;
finally
Dao.Free;
end;
end;
function TLivroModel.Salvar: Boolean;
var
Dao: TLivroDao;
begin
Result := False;
Dao := TLivroDao.Create;
try
case FAcao of
uEnumerado.tacIncluir:
Result := Dao.Incluir(Self);
uEnumerado.tacAlterar:
Result := Dao.Alterar(Self);
uEnumerado.tacExcluir:
Result := Dao.Excluir(Self);
end;
finally
Dao.Free;
end;
end;
procedure TLivroModel.SetAcao(const Value: TAcao);
begin
FAcao := Value;
end;
procedure TLivroModel.SetAno(const Value: Integer);
begin
FAno := Value;
end;
procedure TLivroModel.SetAutor(const Value: string);
begin
FAutor := Value;
end;
procedure TLivroModel.SetCodigo(const Value: string);
begin
FCodigo := Value;
end;
procedure TLivroModel.SetLocalizacao(const Value: Integer);
begin
FLocalizacao := Value;
end;
procedure TLivroModel.SetTitulo(const Value: string);
begin
FTitulo := Value;
end;
function TLivroModel.ObterNome(): String;
var
VQry: TFDQuery;
Dao: TLivroDao;
begin
Dao := TLivroDao.Create;
try
VQry := Dao.ObterDados(Self);
Result := VQry.FieldByName('Titulo').AsString;
finally
Dao.Free;
end;
end;
function TLivroModel.Buscar(): TFDQuery;
var
Dao: TLivroDao;
begin
Dao := TLivroDao.Create;
try
Result := Dao.Buscar(Self);
finally
Dao.Free;
end;
end;
function TLivroModel.BuscaAvancada(): TFDQuery;
var
Dao: TLivroDao;
begin
Dao := TLivroDao.Create;
try
Result := Dao.BuscaAvancado(Self);
finally
Dao.Free;
end;
end;
function TLivroModel.ObterDados(): TFDQuery;
var
Dao: TLivroDao;
begin
Dao := TLivroDao.Create;
try
Result := Dao.ObterDados(Self);
finally
Dao.Free;
end;
end;
end.
|
unit U_Hex;
interface
Uses Forms,ADODB,Dialogs,Messages,
Windows, SysUtils, Variants, Classes, Graphics, Controls,
DB, StdCtrls, Grids, DBGrids, Buttons, ExtCtrls,Clipbrd,StrUtils;
procedure ShowMsgB(Msg: String);
function ReadAndCheckHexFile(strFileName:string):string;//合法返回数据串,不合法返回串'-1'
function LoadHexFile(strFileName:string;var pBuf:array of Byte;var pLen:Integer):Boolean;//成功返回True,失败返回False
function LoadBinFile(strFileName:string;var pBuf:array of Byte;var pLen:Integer):Boolean;//成功返回True,失败返回False
function CutFFFromEnd(pBuf:PByte;len:Integer):Integer;
implementation
function CutFFFromEnd(pBuf:PByte;len:Integer):Integer;
var i:Integer;
begin
Inc(pBuf,len-1);
for i:=len-1 downto 0 do
begin
if pBuf^<>$ff then Break;
if (i<len-1)and(i mod 1024 = 0) then
begin
Inc(len,-1024);
end;
Inc(pBuf,-1);
end;
Result := len;
end;
procedure ShowMsgB(Msg: String);
begin
MessageBox(Application.Handle, pchar(Msg),pchar('提示!'), MB_OK + MB_ICONWARNING);
end;
function ReadAndCheckHexFile(strFileName:string):string;//合法返回数据串,不合法返回串'-1'
var FText:TextFile;
i,LenInt,old_inttype,inttype,oldLenInt:integer;
new_addr,old_addr,sline,HexStr,xcsender:string;//new_seg_addr,old_seg_addr,
label endto;
begin
old_addr := '0';
new_addr := '0';
LenInt := 0;
oldLenInt := 0;
xcsender := '';
//new_seg_addr:='1';
//old_seg_addr:='2';i:=0;
AssignFile(FText,strFileName);//打开外部盘点单文件
Reset(FText);
Application.ProcessMessages;
while not eof( Ftext) do
begin
inc(i);
ReadLn(Ftext,sline);
//每行记录合法性
//第一个字符应为冒号":"
//if leftstr(sline,1)<>':' then
if copy(sline,1,1)<>':' then
begin
if length(sline)=0 then
begin
ShowMsgB(strFileName+'文件中含有空行!');
result:='-1';CloseFile(FText);exit;
end;
ShowMsgB(strFileName+'文件中内容非法!');
result:='-1';CloseFile(FText);exit;
end;
//冒号后开始
new_addr:= copy(sline,4,4);//new_addr:= midstr(sline,4,4);//地址;
LenInt := strtoint('$'+copy(sline,2,2)); //LenInt := strtoint('$'+midstr(sline,2,2));//[长度域]一个字节
HexStr := copy(sline,10,LenInt*2);//HexStr := midstr(sline,10,LenInt*2);//[数据域]
inttype := strtoint('$'+copy(sline,8,2));//inttype := strtoint('$'+midstr(sline,8,2));//文件类型
//if (LenInt=0) and (inttype<>0) then
if (LenInt=0) or (inttype<>0) then
begin
//outputdebugstring(pchar('goto endto'));
goto endto;
end;
//if (strtoint('$'+new_addr)<>strtoint('$'+old_addr)+oldLenInt) and (old_addr<>'0') then
if (strtoint('$'+new_addr)<>strtoint('$'+old_addr)+oldLenInt) and (old_addr<>'0') and (old_inttype<>$02)and (inttype<>$02) then // and (old_seg_addr=new_seg_addr)
begin
//outputdebugstring(pchar('地址不连续:'+'第'+inttostr(i)+'行'+sline));
ShowMsgB('文件中内容非法!地址不连续!');
result:='-1';CloseFile(FText);exit;
end;
//outputdebugstring(pchar(sline));
xcsender := xcsender + HexStr;
endto:
//outputdebugstring(pchar('endto:'));
oldLenInt := LenInt;
old_addr := new_addr;
//old_seg_addr:=new_seg_addr;
old_inttype:=inttype;
//result:=result+sline;//RichEdit1.Lines.Add(sline); //保存字符串
end; //while not eof( Ftext) do
CloseFile(FText);
result:=xcsender;
end;
function LoadBinFile(strFileName:string;var pBuf:array of Byte;var pLen:Integer):Boolean;//成功返回True,失败返回False
var FileStream:TFileStream;
p:PByte;
nRead:Integer;
buf:array[0..127] of Byte;
begin
p := @pBuf[Low(pBuf)];
Result := False;
FileStream := TFileStream.Create(strFileName,fmOpenRead);
FileStream.Position := 0;
while True do
begin
nRead := FileStream.Read(buf,SizeOf(buf));
if nRead>0 then
begin
MoveMemory(p, @buf[0], nRead);
Inc(p,nRead);
end
else
Break;
end;
pLen := Integer(p) - Integer(@pBuf[Low(pBuf)]);
Result := True;
FileStream.Free;
end;
function LoadHexFile(strFileName:string;var pBuf:array of Byte;var pLen:Integer):Boolean;//成功返回True,失败返回False
var FText:TextFile;
i,LenInt,old_inttype,inttype,oldLenInt:integer;
new_addr,old_addr,sline,HexStr,xcsender:string;//new_seg_addr,old_seg_addr,
p:PByte;
label endto;
begin
p := @pBuf[Low(pBuf)];
Result := False;
old_addr := '0';
new_addr := '0';
LenInt := 0;
oldLenInt := 0;
//new_seg_addr:='1';
//old_seg_addr:='2';i:=0;
AssignFile(FText,strFileName);//打开外部盘点单文件
Reset(FText);
Application.ProcessMessages;
while not eof( Ftext) do
begin
//inc(i);
ReadLn(Ftext,sline);
//每行记录合法性
//第一个字符应为冒号":"
//if leftstr(sline,1)<>':' then
if copy(sline,1,1)<>':' then
begin
if length(sline)=0 then
begin
ShowMsgB(strFileName+'文件中含有空行!');
CloseFile(FText);exit;
end;
ShowMsgB(strFileName+'文件中内容非法!');
CloseFile(FText);exit;
end;
//冒号后开始
new_addr:= copy(sline,4,4);//new_addr:= midstr(sline,4,4);//地址;
LenInt := strtoint('$'+copy(sline,2,2)); //LenInt := strtoint('$'+midstr(sline,2,2));//[长度域]一个字节
HexStr := copy(sline,10,LenInt*2);//HexStr := midstr(sline,10,LenInt*2);//[数据域]
inttype := strtoint('$'+copy(sline,8,2));//inttype := strtoint('$'+midstr(sline,8,2));//文件类型
//if (LenInt=0) and (inttype<>0) then
if (LenInt=0) or (inttype<>0) then
begin
//outputdebugstring(pchar('goto endto'));
goto endto;
end;
//if (strtoint('$'+new_addr)<>strtoint('$'+old_addr)+oldLenInt) and (old_addr<>'0') then
{
if (strtoint('$'+new_addr)<>strtoint('$'+old_addr)+oldLenInt) and (old_addr<>'0') and (old_inttype<>$02)and (inttype<>$02) then // and (old_seg_addr=new_seg_addr)
begin
//outputdebugstring(pchar('地址不连续:'+'第'+inttostr(i)+'行'+sline));
ShowMsgB('文件中内容非法!地址不连续!');
CloseFile(FText);exit;
end;
}
//outputdebugstring(pchar(sline));
//xcsender := xcsender + HexStr;
pLen := Length(HexStr) div 2;
for i:=1 to pLen do
begin
p^ := StrToInt('x'+Copy(HexStr,i*2-1,2));
Inc(p);
//outputdebugstring(pchar( IntToStr(Integer(p) - Integer(@pBuf[Low(pBuf)]))));
end;
endto:
//outputdebugstring(pchar('endto:'));
oldLenInt := LenInt;
old_addr := new_addr;
//old_seg_addr:=new_seg_addr;
old_inttype:=inttype;
//result:=result+sline;//RichEdit1.Lines.Add(sline); //保存字符串
end; //while not eof( Ftext) do
CloseFile(FText);
//result:=xcsender;
pLen := Integer(p) - Integer(@pBuf[Low(pBuf)]);
Result := True;
end;
end.
|
unit UfrmConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IniFiles, Buttons;
type
TfrmConfig = class(TForm)
lblBD: TLabel;
edtBD: TEdit;
lblSenha: TLabel;
edtSenha: TEdit;
btnGravar: TBitBtn;
lblEmpresa: TLabel;
edtEmpresa: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
procedure btnGravarClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmConfig: TfrmConfig;
ArqIni: TIniFile;
_caminho: string;
implementation
uses UFuncoes, UfrmPrincipal;
{$R *.dfm}
procedure TfrmConfig.btnGravarClick(Sender: TObject);
begin
_caminho := ExtractFileDir(Application.ExeName);
try
ArqIni := TIniFile.Create(_caminho + '\Config.ini');
ArqIni.WriteString('Geral','BDados',edtBD.Text);
if edtSenha.Text = 'masterkey' then
ArqIni.WriteString('Geral','Senha','A87F9B7E987C82A609');
ArqIni.WriteInteger('Geral', 'EmpresaId', StrToInt(edtEmpresa.Text));
finally
ArqIni.Free;
end;
ShowMessage('Arquivo gravado! Feche o aplicativo e abra novamente.');
Log('Arquivo de configuração criado. Aplicativo será finalizado.');
Log('Finalizado o aplicativo!');
Application.Terminate;
end;
procedure TfrmConfig.FormCreate(Sender: TObject);
var
empresaId: Integer;
begin
frmPrincipal.StatusBar.Panels[0].Text := 'Iniciando o form de configuração...';
Log(frmPrincipal.StatusBar.Panels[0].Text);
_caminho := ExtractFileDir(Application.ExeName);
ArqIni := TIniFile.Create(_caminho + '\Config.ini');
edtBD.Text := ArqIni.ReadString('Geral', 'BDados', '127.0.0.1:pfwin');
edtSenha.Text := ArqIni.ReadString('Geral', 'Senha', 'masterkey');
if edtSenha.Text = 'A87F9B7E987C82A609' then
edtSenha.Text := 'masterkey';
empresaId := ArqIni.ReadInteger('Geral', 'EmpresaId', 0);
edtEmpresa.Text := IntToStr(empresaId);
ArqIni.Free;
end;
end.
|
unit AHistoricoTelemarketingProspect;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
ExtCtrls, PainelGradiente, Componentes1, StdCtrls, Buttons, Localizacao,
ComCtrls, Db, DBTables, DBCtrls, Tabela, Grids, DBGrids, DBKeyViolation,
Mask, numericos, Menus, DBClient;
type
TFHistoricoTelemarketingProspect = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
BFechar: TBitBtn;
PanelColor2: TPanelColor;
Label1: TLabel;
Label5: TLabel;
SpeedButton4: TSpeedButton;
Label4: TLabel;
BUsuario: TSpeedButton;
Label3: TLabel;
SpeedButton2: TSpeedButton;
CPeriodo: TCheckBox;
EDatInicio: TCalendario;
EDatFim: TCalendario;
ECodProspect: TEditLocaliza;
ECodUsuario: TEditLocaliza;
ECodHistorico: TEditLocaliza;
Localiza: TConsultaPadrao;
Label2: TLabel;
LNomUsuario: TLabel;
Label7: TLabel;
PanelColor3: TPanelColor;
LIGACOES: TSQL;
DataLIGACOES: TDataSource;
Grade: TGridIndice;
EObservacoes: TDBMemoColor;
Splitter1: TSplitter;
LIGACOESSEQTELE: TFMTBCDField;
LIGACOESDATLIGACAO: TSQLTimeStampField;
LIGACOESDESFALADOCOM: TWideStringField;
LIGACOESDESOBSERVACAO: TWideStringField;
LIGACOESDATTEMPOLIGACAO: TSQLTimeStampField;
LIGACOESCODPROSPECT: TFMTBCDField;
LIGACOESNOMPROSPECT: TWideStringField;
LIGACOESC_NOM_USU: TWideStringField;
LIGACOESDESHISTORICO: TWideStringField;
PanelColor4: TPanelColor;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
CAtualizarTotais: TCheckBox;
EQtdLigacoes: Tnumerico;
ETempoTotal: TEditColor;
ETempoMedio: TEditColor;
Aux: TSQL;
PopupMenu1: TPopupMenu;
TelemarketingReceptivo1: TMenuItem;
LIGACOESTIPO: TWideStringField;
Label6: TLabel;
BVendedor: TSpeedButton;
LVendedor: TLabel;
EVendedor: TRBEditLocaliza;
LIGACOESVENDEDORCADASTRO: TWideStringField;
LIGACOESVENDEDORHISTORICO: TWideStringField;
N1: TMenuItem;
Agendar1: TMenuItem;
Label11: TLabel;
SpeedButton1: TSpeedButton;
LCidade: TLabel;
ECidade: TEditLocaliza;
LIGACOESCIDADE: TWideStringField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EDatInicioCloseUp(Sender: TObject);
procedure BFecharClick(Sender: TObject);
procedure CAtualizarTotaisClick(Sender: TObject);
procedure TelemarketingReceptivo1Click(Sender: TObject);
procedure GradeOrdem(Ordem: string);
procedure Agendar1Click(Sender: TObject);
procedure ECidadeFimConsulta(Sender: TObject);
procedure ECidadeRetorno(Retorno1, Retorno2: string);
private
VprOrdem,
VprEstadoFiltro: String;
procedure InicializaTela;
procedure AtualizaConsulta;
procedure AdicionaFiltros(VpaSelect: TStrings);
procedure AdicionaFiltroCliente(VpaComandoSql : TStrings);
function RQtdLigacoes(var VpaTempoTotal, VpaMedia: Integer): Integer;
procedure ConfiguraPermissaoUsuario;
public
end;
var
FHistoricoTelemarketingProspect: TFHistoricoTelemarketingProspect;
implementation
uses
APrincipal, FunString, FunNumeros, FunSQL, FunData, Constantes,
ANovoTelemarketingProspect, ANovoTeleMarketing, ANovoAgendamento;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFHistoricoTelemarketingProspect.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
ConfiguraPermissaoUsuario;
VprOrdem:= ' ORDER BY 2';
InicializaTela;
AtualizaConsulta;
end;
procedure TFHistoricoTelemarketingProspect.GradeOrdem(Ordem: string);
begin
VprOrdem := Ordem;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFHistoricoTelemarketingProspect.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.InicializaTela;
begin
EDatInicio.DateTime:= PrimeiroDiaMes(Date);
EDatFim.DateTime:= UltimoDiaMes(Date);
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.AdicionaFiltros(VpaSelect: TStrings);
begin
if CPeriodo.Checked then
VpaSelect.Add(SQLTextoDataEntreAAAAMMDD('TRUNC(TEL.DATLIGACAO)',EDatInicio.DateTime,EDatFim.Datetime,True));
if ECodProspect.AInteiro <> 0 then
VpaSelect.Add(' AND TEL.CODPROSPECT = '+ECodProspect.Text);
if ECodUsuario.Ainteiro <> 0 then
VpaSelect.Add(' AND TEL.CODUSUARIO = '+ECodUsuario.Text);
if EVendedor.Ainteiro <> 0 then
VpaSelect.Add(' AND TEL.CODVENDEDOR = '+EVendedor.Text);
if ECodHistorico.AInteiro <> 0 then
VpaSelect.Add(' AND TEL.CODHISTORICO = '+ECodHistorico.Text);
if ECidade.AInteiro <> 0 then
VpaSelect.add(' and PRO.DESCIDADE = '''+LCidade.Caption+'''');
if VprEstadoFiltro <> '' then
VpaSelect.Add(' and PRO.DESUF = '''+ VprEstadoFiltro+ '''');
end;
procedure TFHistoricoTelemarketingProspect.Agendar1Click(Sender: TObject);
begin
if LIGACOESTIPO.AsString = 'PROSPECT' then
begin
FNovoAgedamento := TFNovoAgedamento.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoAgedamento'));
FNovoAgedamento.AgendaPeloTelemarketing(LIGACOESCODPROSPECT.AsInteger,varia.CodigoUsuario);
FNovoAgedamento.free;
end;
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.AdicionaFiltroCliente(VpaComandoSql : TStrings);
begin
if ECodProspect.AInteiro <> 0 then
VpaComandoSql.Add(' AND TEL.CODCLIENTE = 0');
if EVendedor.AInteiro <> 0 then
VpaComandoSql.Add(' AND TEL.CODVENDEDOR = '+EVendedor.Text);
if CPeriodo.Checked then
VpaComandoSql.add(SQLTextoDataEntreAAAAMMDD('TRUNC(TEL.DATLIGACAO)',EDatInicio.DateTime,EDatFim.Datetime,true));
if ECodUsuario.Ainteiro <> 0 then
VpaComandoSql.add(' and TEL.CODUSUARIO = '+ECodUsuario.Text);
if ECodHistorico.AInteiro <> 0 then
VpaComandoSql.add(' and TEL.CODHISTORICO = '+ECodHistorico.Text);
if ECidade.AInteiro <> 0 then
VpaComandoSql.add(' and CLI.C_CID_CLI = '''+LCidade.Caption+'''');
if VprEstadoFiltro <> '' then
VpaComandoSql.Add(' and CLI.C_EST_CLI = '''+ VprEstadoFiltro+'''');
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.AtualizaConsulta;
begin
LIGACOES.close;
LIGACOES.SQL.Clear;
LIGACOES.SQL.Add('SELECT'+
' ''SUSPECT'' TIPO,TEL.SEQTELE, TEL.DATLIGACAO, TEL.DESFALADOCOM,'+
' TEL.DESOBSERVACAO, TEL.DATTEMPOLIGACAO, TEL.CODPROSPECT,'+
' PRO.NOMPROSPECT, PRO.DESCIDADE CIDADE,'+
' USU.C_NOM_USU,'+
' HIS.DESHISTORICO, '+
' VEC.C_NOM_VEN VENDEDORCADASTRO, ' +
' VEH.C_NOM_VEN VENDEDORHISTORICO ' +
' FROM '+
' TELEMARKETINGPROSPECT TEL, PROSPECT PRO, CADUSUARIOS USU, HISTORICOLIGACAO HIS, CADVENDEDORES VEC, CADVENDEDORES VEH '+
' WHERE'+
' TEL.CODPROSPECT = PRO.CODPROSPECT'+
' AND TEL.CODUSUARIO = USU.I_COD_USU'+
' AND ' +SQLTextoRightJoin('PRO.CODVENDEDOR','VEC.I_COD_VEN')+
' AND ' +SQLTextoRightJoin('TEL.CODVENDEDOR','VEH.I_COD_VEN')+
' AND TEL.CODHISTORICO = HIS.CODHISTORICO');
AdicionaFiltros(LIGACOES.SQL);
Ligacoes.SQL.ADD('union '+
' select ''PROSPECT'' TIPO,TEL.SEQTELE, TEL.DATLIGACAO,TEL.DESFALADOCOM, TEL.DESOBSERVACAO, TEL.DATTEMPOLIGACAO, TEL.CODCLIENTE, '+
' CLI.C_NOM_CLI, CLI.C_CID_CLI CIDADE, '+
' USU.C_NOM_USU, '+
' HIS.DESHISTORICO, '+
' VEC.C_NOM_VEN VENDEDORCADASTRO, ' +
' VEH.C_NOM_VEN VENDEDORHISTORICO ' +
' from TELEMARKETING TEL, CADCLIENTES CLI, CADUSUARIOS USU, HISTORICOLIGACAO HIS, CADVENDEDORES VEC, CADVENDEDORES VEH '+
' Where TEL.CODCLIENTE = CLI.I_COD_CLI '+
' and TEL.CODUSUARIO = USU.I_COD_USU '+
' AND ' +SQLTextoRightJoin('CLI.I_COD_VEN','VEC.I_COD_VEN')+
' AND ' +SQLTextoRightJoin('TEL.CODVENDEDOR','VEH.I_COD_VEN')+
' and TEL.CODHISTORICO = HIS.CODHISTORICO ');
AdicionaFiltroCliente(LIGACOES.sql);
LIGACOES.SQL.Add(VprOrdem);
LIGACOES.Open;
Grade.ALinhaSQLOrderBy:= LIGACOES.SQL.Count-1;
CAtualizarTotaisClick(CAtualizarTotais);
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.ECidadeFimConsulta(Sender: TObject);
begin
AtualizaConsulta;
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.ECidadeRetorno(Retorno1,
Retorno2: string);
begin
VprEstadoFiltro:= Retorno1;
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.EDatInicioCloseUp(Sender: TObject);
begin
AtualizaConsulta;
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.BFecharClick(Sender: TObject);
begin
Close;
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.CAtualizarTotaisClick(Sender: TObject);
var
VpfTempoTotal, VpfMedia: Integer;
begin
if CAtualizarTotais.Checked then
begin
EQtdLigacoes.AValor:= RQtdLigacoes(VpfTempoTotal,VpfMedia);
ETempoTotal.Text:= FormatDateTime('HH:MM:SS',VpfTempoTotal);
ETempoMedio.Text:= FormatDateTime('HH:MM:SS',VpfMedia);
end
else
begin
EQtdLigacoes.AValor:= 0;
ETempoTotal.Text:= FormatDateTime('HH:MM:SS',0);
ETempoMedio.Text:= FormatDateTime('HH:MM:SS',0);
end;
end;
{******************************************************************************}
function TFHistoricoTelemarketingProspect.RQtdLigacoes(var VpaTempoTotal, VpaMedia: Integer): Integer;
begin
Aux.Close;
Aux.SQL.Clear;
Aux.SQL.Add('SELECT COUNT(*) QTD,'+
' SUM(QTDSEGUNDOSLIGACAO) TEMPO,'+
' AVG(QTDSEGUNDOSLIGACAO) MEDIA'+
' FROM TELEMARKETINGPROSPECT TEL, PROSPECT PRO'+
' WHERE TEL.SEQTELE = TEL.SEQTELE' +
' AND TEL.CODPROSPECT = PRO.CODPROSPECT');
Adicionafiltros(Aux.SQL);
Aux.Open;
Result:= Aux.FieldByName('QTD').AsInteger;
VpaTempoTotal:= Aux.FieldByName('TEMPO').AsInteger;
VpaMedia:= Aux.FieldByName('MEDIA').AsInteger;
Aux.Close;
Aux.SQL.Clear;
Aux.SQL.Add('SELECT COUNT(*) QTD,'+
' SUM(QTDSEGUNDOSLIGACAO) TEMPO,'+
' AVG(QTDSEGUNDOSLIGACAO) MEDIA'+
' FROM TELEMARKETING TEL, CADCLIENTES CLI'+
' WHERE TEL.SEQTELE = TEL.SEQTELE' +
' AND TEL.CODCLIENTE = CLI.I_COD_CLI ');
AdicionaFiltroCliente(Aux.SQL);
Aux.open;
Result:= result + Aux.FieldByName('QTD').AsInteger;
Aux.Close;
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.ConfiguraPermissaoUsuario;
begin
if (puSomenteClientesdoVendedor in varia.PermissoesUsuario) then
begin
EVendedor.AInteiro := Varia.CodVendedor;
EVendedor.Atualiza;
EVendedor.Enabled := false;
BVendedor.Enabled := false;
LVendedor.Enabled := false;
end;
end;
{******************************************************************************}
procedure TFHistoricoTelemarketingProspect.TelemarketingReceptivo1Click(
Sender: TObject);
begin
if not LIGACOESCODPROSPECT.AsInteger <> 0 then
begin
if LIGACOESTIPO.AsString = 'SUSPECT' then
BEGIN
FNovoTeleMarketingProspect:= TFNovoTeleMarketingProspect.CriarSDI(Application,'',True);
FNovoTeleMarketingProspect.TeleMarketingProspect(LIGACOESCODPROSPECT.AsInteger);
FNovoTeleMarketingProspect.Free;
END
else
if LIGACOESTIPO.AsString = 'PROSPECT' then
begin
FNovoTeleMarketing := TFNovoTeleMarketing.CriarSDI(self,'',true);
FNovoTeleMarketing.TeleMarketingCliente(LIGACOESCODPROSPECT.AsInteger);
FNovoTeleMarketing.Free;
end;
end;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFHistoricoTelemarketingProspect]);
end.
|
unit ServersUtils;
interface
type
TServerData = record
name, adress: string;
id, players, slots: integer;
status: boolean;
end;
procedure AddServer(data: TServerData);
function GetServer(ID:integer):TServerData;
var
Servers: array of TServerData;
implementation
procedure AddServer(data: TServerData);
begin
SetLength(Servers, Length(Servers) + 1);
Servers[Length(Servers) - 1] := data;
end;
function GetServer(ID: integer): TServerData;
begin
Result := Servers[ID];
end;
end.
|
{: GLHiddenLineShader<p>
A shader that renders hidden (back-faced) lines differently from visible
(front) lines. Polygon offset is used to displace fragments depths a little
so that there is no z-fighting in rendering the same geometry multiple times.<p>
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>22/04/10 - Yar - Fixes after GLState revision
<li>05/03/10 - DanB - More state added to TGLStateCache
<li>06/06/07 - DaStr - Added $I GLScene.inc
Added GLColor to uses (BugtrackerID = 1732211)
<li>25/02/07 - DaStr - Moved registration to GLSceneRegister.pas
<li>25/09/04 - NelC - Fixed bug of disabled blend (thx Carlos)
<li>05/02/04 - NelC - Fixed memory leak in TGLHiddenLineShader.Destroy (thx Achim Hammes)
<li>13/12/03 - NelC - Added SurfaceLit, ShadeModel
<li>05/12/03 - NelC - Added ForceMaterial
<li>03/12/03 - NelC - Creation. Modified from the HiddenLineShader in
the multipass demo.
</ul></font>
}
unit GLHiddenLineShader;
interface
{$I GLScene.inc}
uses
System.Classes,
GLMaterial, OpenGLTokens, GLCrossPlatform, GLScene, GLColor,
GLBaseClasses, GLRenderContextInfo, GLState, GLContext;
type
TGLLineSettings = class(TGLUpdateAbleObject)
private
{ Private Declarations }
FColor: TGLColor;
FWidth: Single;
FPattern: TGLushort;
FForceMaterial: Boolean;
procedure SetPattern(const value: TGLushort);
procedure SetColor(const v: TGLColor);
procedure SetWidth(const Value: Single);
procedure SetForceMaterial(v: boolean);
public
{ Public Declarations }
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Apply(var rci: TRenderContextInfo);
procedure UnApply(var rci: TRenderContextInfo);
published
{ Published Declarations }
property Width: Single read FWidth write SetWidth;
property Color: TGLColor read FColor write SetColor;
property Pattern: TGLushort read FPattern write SetPattern default $FFFF;
{: Set ForceMaterial to true to enforce the application of the line settings
for objects that sets their own color, line width and pattern. }
property ForceMaterial: Boolean read FForceMaterial write SetForceMaterial
default false;
end;
TGLHiddenLineShader = class(TGLShader)
private
FPassCount: integer;
FLineSmooth: Boolean;
FSolid: Boolean;
FBackGroundColor: TGLColor;
FFrontLine: TGLLineSettings;
FBackLine: TGLLineSettings;
FLighting: Boolean;
FShadeModel: TGLShadeModel;
procedure SetlineSmooth(v: boolean);
procedure SetSolid(v: boolean);
procedure SetBackgroundColor(AColor: TGLColor);
procedure SetLighting(v: boolean);
procedure SetShadeModel(const val: TGLShadeModel);
protected
procedure DoApply(var rci: TRenderContextInfo; Sender: TObject); override;
function DoUnApply(var rci: TRenderContextInfo): Boolean; override;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published Declarations }
property FrontLine: TGLLineSettings read FFrontLine write FFrontLine;
property BackLine: TGLLineSettings read FBackLine write FBackLine;
{: Line smoothing control }
property LineSmooth: Boolean read FlineSmooth write SetlineSmooth default
false;
{: Solid controls if you can see through the front-line wireframe. }
property Solid: Boolean read FSolid write SetSolid default false;
{: Color used for solid fill. }
property BackgroundColor: TGLColor read FBackgroundColor write
SetBackgroundColor;
{: When Solid is True, determines if lighting or background color is used. }
property SurfaceLit: Boolean read FLighting write SetLighting default true;
{: Shade model.<p>
Default is "Smooth".<p> }
property ShadeModel: TGLShadeModel read FShadeModel write SetShadeModel
default smDefault;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------
// ------------------ TGLLineSettings ------------------
// ------------------
// Create
//
constructor TGLLineSettings.Create(AOwner: TPersistent);
begin
inherited;
FColor := TGLColor.Create(Self);
FColor.Initialize(clrGray20);
FWidth := 2;
Pattern := $FFFF;
ForceMaterial := false;
end;
// Destroy
//
destructor TGLLineSettings.Destroy;
begin
FColor.Free;
inherited;
end;
// SetPattern
//
procedure TGLLineSettings.SetPattern(const value: TGLushort);
begin
if FPattern <> value then
begin
FPattern := Value;
NotifyChange(self);
end;
end;
// SetColor
//
procedure TGLLineSettings.SetColor(const v: TGLColor);
begin
FColor.Color := v.Color;
NotifyChange(Self);
end;
// SetWidth
//
procedure TGLLineSettings.SetWidth(const Value: Single);
begin
FWidth := Value;
NotifyChange(Self);
end;
var
IgnoreMatSave: boolean;
// Apply
//
procedure TGLLineSettings.Apply(var rci: TRenderContextInfo);
begin
rci.GLStates.LineWidth := Width;
GL.Color4fv(Color.AsAddress);
if Pattern <> $FFFF then
begin
rci.GLStates.Enable(stLineStipple);
rci.GLStates.LineStippleFactor := 1;
rci.GLStates.LineStipplePattern := Pattern;
end
else
rci.GLStates.Disable(stLineStipple);
if ForceMaterial then
begin
IgnoreMatSave := rci.ignoreMaterials;
rci.ignoreMaterials := true;
end;
end;
// UnApply
//
procedure TGLLineSettings.UnApply(var rci: TRenderContextInfo);
begin
if ForceMaterial then
rci.ignoreMaterials := IgnoreMatSave;
end;
// SetForceMaterial
//
procedure TGLLineSettings.SetForceMaterial(v: boolean);
begin
if FForceMaterial <> v then
begin
FForceMaterial := v;
NotifyChange(self);
end;
end;
// ------------------
// ------------------ TGLHiddenLineShader ------------------
// ------------------
// Create
//
constructor TGLHiddenLineShader.Create(AOwner: TComponent);
begin
inherited;
FFrontLine := TGLLineSettings.Create(self);
FBackLine := TGLLineSettings.Create(self);
FSolid := false;
FBackgroundColor := TGLColor.Create(Self);
FBackgroundColor.Initialize(clrBtnFace);
FLineSmooth := False;
FLighting := true;
FShadeModel := smDefault;
end;
// Destroy
//
destructor TGLHiddenLineShader.Destroy;
begin
FFrontLine.Free;
FBackLine.Free;
FBackgroundColor.Free;
inherited;
end;
// DoApply
//
procedure TGLHiddenLineShader.DoApply(var rci: TRenderContextInfo; Sender:
TObject);
begin
FPassCount := 1;
if solid then
with rci.GLStates do
begin
// draw filled front faces in first pass
PolygonMode := pmFill;
CullFaceMode := cmBack;
if FLighting then
begin
case ShadeModel of
smDefault, smSmooth: GL.ShadeModel(GL_SMOOTH);
smFlat: GL.ShadeModel(GL_FLAT);
end
end
else
begin
Disable(stLighting);
GL.Color4fv(FBackgroundColor.AsAddress); // use background color
end;
// enable and adjust polygon offset
Enable(stPolygonOffsetFill);
end
else
with rci.GLStates do
begin
Disable(stLighting);
// draw back lines in first pass
FBackLine.Apply(rci);
CullFaceMode := cmFront;
PolygonMode := pmLines;
// enable and adjust polygon offset
Enable(stPolygonOffsetLine);
end;
rci.GLStates.SetPolygonOffset(1, 2);
end;
// DoUnApply
//
function TGLHiddenLineShader.DoUnApply(var rci: TRenderContextInfo): Boolean;
procedure SetLineSmoothBlend;
begin
with rci.GLStates do
begin
LineStippleFactor := 1;
LineStipplePattern := $FFFF;
if LineSmooth then
begin
LineSmoothHint := hintNicest;
Enable(stLineSmooth);
end
else
Disable(stLineSmooth);
if LineSmooth or (FBackLine.FColor.Alpha < 1)
or (FFrontLine.FColor.Alpha < 1) then
begin
Enable(stBlend);
SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha);
end
else
Disable(stBlend);
end;
end;
begin
case FPassCount of
1:
with rci.GLStates do begin
// draw front line in 2nd pass
FPassCount := 2;
FBackLine.UnApply(rci);
FFrontLine.Apply(rci);
SetLineSmoothBlend;
if solid and FLighting then
Disable(stLighting);
PolygonMode := pmLines;
CullFaceMode := cmBack;
if solid then
rci.GLStates.Disable(stPolygonOffsetFill)
else
rci.GLStates.Disable(stPolygonOffsetLine);
Result := True;
end;
2:
begin
FFrontLine.UnApply(rci);
rci.GLStates.PolygonMode := pmFill;
Result := false;
end;
else
Assert(False);
Result := False;
end;
end;
// SetBackgroundColor
//
procedure TGLHiddenLineShader.SetBackgroundColor(AColor: TGLColor);
begin
FBackgroundColor.Color := AColor.Color;
NotifyChange(Self);
end;
// SetlineSmooth
//
procedure TGLHiddenLineShader.SetlineSmooth(v: boolean);
begin
if FlineSmooth <> v then
begin
FlineSmooth := v;
NotifyChange(self);
end;
end;
// SetLighting
//
procedure TGLHiddenLineShader.SetLighting(v: boolean);
begin
if FLighting <> v then
begin
FLighting := v;
NotifyChange(self);
end;
end;
// SetSolid
//
procedure TGLHiddenLineShader.SetSolid(v: boolean);
begin
if FSolid <> v then
begin
FSolid := v;
NotifyChange(self);
end;
end;
// SetShadeModel
//
procedure TGLHiddenLineShader.SetShadeModel(const val: TGLShadeModel);
begin
if FShadeModel <> val then
begin
FShadeModel := val;
NotifyChange(Self);
end;
end;
end.
|
///////////////////////////////////////////////////////////////////////////
// //
// Copyright © 1997-1998, NetMasters, L.L.C //
// - All rights reserved worldwide. - //
// Portions may be Copyright © Inprise. //
// //
// UUEncode/Decode/MIME Demo Unit 1: (UNIT1.PAS) //
// //
// DESCRIPTION: //
// //
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY //
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE //
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR //
// PURPOSE. //
// //
///////////////////////////////////////////////////////////////////////////
//
// Revision History
//
// //
///////////////////////////////////////////////////////////////////////////
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
NMUUE, StdCtrls, ComCtrls, Buttons;
type
TForm1 = class(TForm)
Edit1: TEdit;
Label1: TLabel;
NMUUE1: TNMUUProcessor;
Edit2: TEdit;
Label2: TLabel;
Button1: TButton;
GroupBox1: TGroupBox;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
GroupBox2: TGroupBox;
RadioButton3: TRadioButton;
RadioButton4: TRadioButton;
StatusBar1: TStatusBar;
SpeedButton1: TSpeedButton;
OpenDialog1: TOpenDialog;
procedure Button1Click(Sender: TObject);
procedure NMUUE1BeginDecode(Sender: TObject);
procedure NMUUE1BeginEncode(Sender: TObject);
procedure NMUUE1EndDecode(Sender: TObject);
procedure NMUUE1EndEncode(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
InStream,
OutStream: TFileStream;
begin
InStream := TFileStream.Create(Edit1.Text, fmOpenRead);
OutStream := TFileStream.Create(Edit2.Text, fmCreate);
try
If RadioButton4.Checked then
NMUUE1.Method := uuMIME
else
NMUUE1.Method := uuCode;
NMUUE1.InputStream := InStream;
// NMUUE1.InputStream.CopyFrom(InStream,InStream.Size);
NMUUE1.OutputStream := OutStream;
If RadioButton1.Checked then
NMUUE1.Encode
else
NMUUE1.Decode;
finally
InStream.Free;
OutStream.Free;
end;
end;
procedure TForm1.NMUUE1BeginDecode(Sender: TObject);
begin
StatusBar1.SimpleText := 'Decoding stream';
end;
procedure TForm1.NMUUE1BeginEncode(Sender: TObject);
begin
StatusBar1.SimpleText := 'encoding stream';
end;
procedure TForm1.NMUUE1EndDecode(Sender: TObject);
begin
StatusBar1.SimpleText := 'Completed decoding stream';
end;
procedure TForm1.NMUUE1EndEncode(Sender: TObject);
begin
StatusBar1.SimpleText := 'Completed encoding stream';
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
If OpenDialog1.Execute then
Edit1.Text := OpenDialog1.FileName;
end;
end.
|
// ====================================================================
//
// Unit uWarrior.pas
//
// This class contains the main properties from the player/character
//
// Esta classe contém as propriedades principais do jogador/personagem
//
// ====================================================================
unit uWarrior;
interface
uses
{ExtCtrls,} Classes, SysUtils;
type
// Enumeration with the possible player classes
// Enumeration com as possíveis classes do usuário
TWarriorClass = (wcDeprived,
wcSorcerer,
wcCleric,
wcThief,
wcBandit,
wcKnight,
wcHunter,
wcPyromancer,
wcWarrior,
wcWanderer,
wcNone);
// Warrior class
// Classe Warrior
TWarrior = class
private
{FStatusGetterTimer: TTimer;
FStaminaHPGetterTimer: TTimer;}
FWarriorClass: TWarriorClass;
FLevel: Integer;
FVitality: Integer;
FAttunement: Integer;
FEndurance: Integer;
FStrength: Integer;
FDexterity: Integer;
FResistance: Integer;
FIntelligence: Integer;
FFaith: Integer;
FMaxHP: Integer;
FHP: Integer;
FMaxStamina: Integer;
FActualStamina: Integer;
FName: String;
//FWarriorClassName: String;
// Getters and Setters
function GetWarriorClass: TWarriorClass;
procedure SetWarriorClass(const AWarriorClass: TWarriorClass);
function GetLevel: Integer;
procedure SetLevel(const ALevel: Integer);
function GetVitality: Integer;
procedure SetVitality(const AVitality: Integer);
function GetAttunement: Integer;
procedure SetAttunement(const AAttunement: Integer);
function GetEndurance: Integer;
procedure SetEndurance(const AEndurance: Integer);
function GetStrength: Integer;
procedure SetStrength(const AStrength: Integer);
function GetDexterity: Integer;
procedure SetDexterity(const ADexterity: Integer);
function GetResistance: Integer;
procedure SetResistance(const AResistance: Integer);
function GetIntelligence: Integer;
procedure SetIntelligence(const AIntelligence: Integer);
function GetFaith: Integer;
procedure SetFaith(const AFaith: Integer);
function GetHP: Integer;
procedure SetHP(const AHP: Integer);
function GetMaxHP: Integer;
procedure SetMaxHP(const AMaxHP: Integer);
function GetMaxStamina: Integer;
procedure SetMaxStamina(const AMaxStamina: Integer);
function GetActualStamina: Integer;
procedure SetActualStamina(const AActualStamina: Integer);
function GetName: String;
procedure SetName(const AName: String);
function GetWarriorClassName: String;
//procedure SetWarriorClassName(const AWarriorClassName: String);
//procedure OnTimerUpdateStatus(Sender: TObject);
//procedure OnTimerUpdateStaminaHP(Sender: TObject);
public
// They are public because there's no need of make some get and set for them. It just contains the offsets
// Essas "propriedades" estão públicas porque não há a necessidade de implementar get and set, visto que são apenas offsets
FPointer: Cardinal;
FInfoPointer: Cardinal;
FLevelOffsets: array [0..10] of Cardinal;
FVitalityOffsets: array [0..10] of Cardinal;
FAttunementOffsets: array [0..10] of Cardinal;
FEnduranceOffsets: array [0..10] of Cardinal;
FStrengthOffsets: array [0..10] of Cardinal;
FDexterityOffsets: array [0..10] of Cardinal;
FResistanceOffsets: array [0..10] of Cardinal;
FIntelligenceOffsets: array [0..10] of Cardinal;
FFaithOffsets: array [0..10] of Cardinal;
FMaxStaminaOffsets: array[0..10] of Cardinal;
FMaxHPOffSets: array[0..10] of Cardinal;
FActualStaminaOffsets: array [0..10] of Cardinal;
FActualHPOffsets: array [0..10] of Cardinal;
constructor Create; virtual;
procedure UpdateStatus; virtual;
procedure UpdateStaminaHPStatus; virtual;
property WarriorClass: TWarriorClass read GetWarriorClass write SetWarriorClass;
property Level: Integer read GetLevel write SetLevel;
property Vitality: Integer read GetVitality write SetVitality;
property Attunement: Integer read GetAttunement write SetAttunement;
property Endurance: Integer read GetEndurance write SetEndurance;
property Strength: Integer read GetStrength write SetStrength;
property Dexterity: Integer read GetDexterity write SetDexterity;
property Resistance: Integer read GetResistance write SetResistance;
property Intelligence: Integer read GetIntelligence write SetIntelligence;
property Faith: Integer read GetFaith write SetFaith;
property HP: Integer read GetHP write SetHP;
property MaxHP: Integer read GetMaxHP write SetMaxHP;
property MaxStamina: Integer read GetMaxStamina write SetMaxStamina;
property ActualStamina: Integer read GetActualStamina write SetActualStamina;
property Name: String read GetName write SetName;
property WarriorClassName: String read GetWarriorClassName;// write SetWarriorClassName;
end;
implementation
uses
uDSProcessMgmt;
{ TWarrior }
constructor TWarrior.Create;
begin
Self.WarriorClass := wcNone;
{ FStatusGetterTimer := TTimer.Create(nil);
FStaminaHPGetterTimer := TTimer.Create(nil);
FStatusGetterTimer.Interval := 2000;
FStaminaHPGetterTimer.Interval := 3;
FStatusGetterTimer.OnTimer := OnTimerUpdateStatus;
FStaminaHPGetterTimer.OnTimer := OnTimerUpdateStaminaHP;
FStatusGetterTimer.Enabled := True;
FStaminaHPGetterTimer.Enabled := True; }
UpdateStatus;
//UpdateStaminaHPStatus;
end;
// Just getters and setters below
// Apenas getters e setters abaixo
function TWarrior.GetActualStamina: Integer;
begin
Result := FActualStamina;
end;
function TWarrior.GetAttunement: Integer;
begin
Result := FAttunement;
end;
function TWarrior.GetDexterity: Integer;
begin
Result := FDexterity;
end;
function TWarrior.GetEndurance: Integer;
begin
Result := FEndurance;
end;
function TWarrior.GetFaith: Integer;
begin
Result := FFaith;
end;
function TWarrior.GetHP: Integer;
begin
Result := FHP;
end;
function TWarrior.GetIntelligence: Integer;
begin
Result := FIntelligence;
end;
function TWarrior.GetLevel: Integer;
begin
Result := FLevel;
end;
function TWarrior.GetMaxHP: Integer;
begin
Result := FMaxHP;
end;
function TWarrior.GetMaxStamina: Integer;
begin
Result := FMaxStamina;
end;
function TWarrior.GetName: String;
begin
Result := FName;
end;
function TWarrior.GetResistance: Integer;
begin
Result := FResistance;
end;
function TWarrior.GetStrength: Integer;
begin
Result := FStrength;
end;
function TWarrior.GetVitality: Integer;
begin
Result := FVitality;
end;
function TWarrior.GetWarriorClass: TWarriorClass;
begin
Result := FWarriorClass;
end;
function TWarrior.GetWarriorClassName: String;
begin
Result := EmptyStr;
case Self.WarriorClass of
wcWarrior: Result := 'Warrior';
wcKnight: Result := 'Knight';
wcWanderer: Result := 'Wanderer';
wcThief: Result := 'Thief';
wcBandit: Result := 'Bandit';
wcHunter: Result := 'Hunter';
wcSorcerer: Result := 'Sorcerer';
wcPyromancer: Result := 'Pyromancer';
wcCleric: Result := 'Cleric';
wcDeprived: Result := 'Deprived';
else
Result := EmptyStr;
end;
end;
{procedure TWarrior.OnTimerUpdateStaminaHP(Sender: TObject);
begin
UpdateStaminaHPStatus;
end;
procedure TWarrior.OnTimerUpdateStatus(Sender: TObject);
begin
UpdateStatus;
end;}
procedure TWarrior.SetActualStamina(const AActualStamina: Integer);
begin
FActualStamina := AActualStamina;
end;
procedure TWarrior.SetAttunement(const AAttunement: Integer);
begin
FAttunement := AAttunement;
end;
procedure TWarrior.SetDexterity(const ADexterity: Integer);
begin
FDexterity := ADexterity;
end;
procedure TWarrior.SetEndurance(const AEndurance: Integer);
begin
FEndurance := AEndurance;
end;
procedure TWarrior.SetFaith(const AFaith: Integer);
begin
FFaith := AFaith;
end;
procedure TWarrior.SetHP(const AHP: Integer);
begin
FHP := AHP;
end;
procedure TWarrior.SetIntelligence(const AIntelligence: Integer);
begin
FIntelligence := AIntelligence;
end;
procedure TWarrior.SetLevel(const ALevel: Integer);
begin
FLevel := ALevel;
end;
procedure TWarrior.SetMaxHP(const AMaxHP: Integer);
begin
FMaxHP := AMaxHP;
end;
procedure TWarrior.SetMaxStamina(const AMaxStamina: Integer);
begin
FMaxStamina := AMaxStamina;
end;
procedure TWarrior.SetName(const AName: String);
begin
FName := AName;
end;
procedure TWarrior.SetResistance(const AResistance: Integer);
begin
FResistance := AResistance;
end;
procedure TWarrior.SetStrength(const AStrength: Integer);
begin
FStrength := AStrength;
end;
procedure TWarrior.SetVitality(const AVitality: Integer);
begin
FVitality := AVitality;
end;
procedure TWarrior.SetWarriorClass(const AWarriorClass: TWarriorClass);
begin
FWarriorClass := AWarriorClass;
end;
procedure TWarrior.UpdateStaminaHPStatus;
begin
uDSProcessMgmt.UpdateStaminaHPStatus(Self);
end;
// This procedure calls the DS Process Management for read the Dark Souls Memory data, and update the var Warrior (as parameter)
// Esta procedure chama o DS Process Management para ler os dados da memória do Dark Souls e atualiza a classe (tipo var no parãmetro)
procedure TWarrior.UpdateStatus;
begin
uDSProcessMgmt.UpdateStatus(Self);
UpdateStaminaHPStatus;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{*******************************************************}
{ TTimeSpan data type implementation }
{*******************************************************}
unit System.TimeSpan;
interface
{$IFNDEF CPUX86}
{$WARN LOST_EXTENDED_PRECISION OFF}
{$ENDIF !CPUX86}
type
TTimeSpan = record
private
FTicks: Int64;
strict private
function GetDays: Integer;
function GetHours: Integer;
function GetMinutes: Integer;
function GetSeconds: Integer;
function GetMilliseconds: Integer;
function GetTotalDays: Double;
function GetTotalHours: Double;
function GetTotalMinutes: Double;
function GetTotalSeconds: Double;
function GetTotalMilliseconds: Double;
function ToString: string;
class function GetScaledInterval(Value: Double; Scale: Integer): TTimeSpan; static;
class constructor Create;
strict private class var
FMinValue: TTimeSpan{ = (FTicks: -9223372036854775808)};
FMaxValue: TTimeSpan{ = (FTicks: $7FFFFFFFFFFFFFFF)};
FZero: TTimeSpan;
strict private const
MillisecondsPerTick = 0.0001;
SecondsPerTick = 1e-07;
MinutesPerTick = 1.6666666666666667E-09;
HoursPerTick = 2.7777777777777777E-11;
DaysPerTick = 1.1574074074074074E-12;
MillisPerSecond = 1000;
MillisPerMinute = 60 * MillisPerSecond;
MillisPerHour = 60 * MillisPerMinute;
MillisPerDay = 24 * MillisPerHour;
MaxSeconds = 922337203685;
MinSeconds = -922337203685;
MaxMilliseconds = 922337203685477;
MinMilliseconds = -922337203685477;
public const
TicksPerMillisecond = 10000;
TicksPerSecond = 1000 * Int64(TicksPerMillisecond);
TicksPerMinute = 60 * Int64(TicksPerSecond);
TicksPerHour = 60 * Int64(TicksPerMinute);
TicksPerDay = 24 * TIcksPerHour;
public
constructor Create(ATicks: Int64); overload;
constructor Create(Hours, Minutes, Seconds: Integer); overload;
constructor Create(Days, Hours, Minutes, Seconds: Integer); overload;
constructor Create(Days, Hours, Minutes, Seconds, Milliseconds: Integer); overload;
function Add(const TS: TTimeSpan): TTimeSpan; overload;
function Duration: TTimeSpan;
function Negate: TTimeSpan;
function Subtract(const TS: TTimeSpan): TTimeSpan; overload;
class function FromDays(Value: Double): TTimeSpan; static;
class function FromHours(Value: Double): TTimeSpan; static;
class function FromMinutes(Value: Double): TTimeSpan; static;
class function FromSeconds(Value: Double): TTimeSpan; static;
class function FromMilliseconds(Value: Double): TTimeSpan; static;
class function FromTicks(Value: Int64): TTimeSpan; static;
class function Subtract(const D1, D2: TDateTime): TTimeSpan; overload; static;
class function Parse(const S: string): TTimeSpan; static;
class function TryParse(const S: string; out Value: TTimeSpan): Boolean; static;
class operator Add(const Left, Right: TTimeSpan): TTimeSpan;
class operator Add(const Left: TTimeSpan; Right: TDateTime): TDateTime;
class operator Add(const Left: TDateTime; Right: TTimeSpan): TDateTime;
class operator Subtract(const Left, Right: TTimeSpan): TTimeSpan;
class operator Subtract(const Left: TDateTime; Right: TTimeSpan): TDateTime;
class operator Equal(const Left, Right: TTimeSpan): Boolean;
class operator NotEqual(const Left, Right: TTimeSpan): Boolean;
class operator GreaterThan(const Left, Right: TTimeSpan): Boolean;
class operator GreaterThanOrEqual(const Left, Right: TTimeSpan): Boolean;
class operator LessThan(const Left, Right: TTimeSpan): Boolean;
class operator LessThanOrEqual(const Left, Right: TTimeSpan): Boolean;
class operator Negative(const Value: TTimeSpan): TTimeSpan;
class operator Positive(const Value: TTimeSpan): TTimeSpan;
class operator Implicit(const Value: TTimeSpan): string;
class operator Explicit(const Value: TTimeSpan): string;
property Ticks: Int64 read FTicks;
property Days: Integer read GetDays;
property Hours: Integer read GetHours;
property Minutes: Integer read GetMinutes;
property Seconds: Integer read GetSeconds;
property Milliseconds: Integer read GetMilliseconds;
property TotalDays: Double read GetTotalDays;
property TotalHours: Double read GetTotalHours;
property TotalMinutes: Double read GetTotalMinutes;
property TotalSeconds: Double read GetTotalSeconds;
property TotalMilliseconds: Double read GetTotalMilliseconds;
class property MinValue: TTimeSpan read FMinValue;
class property MaxValue: TTimeSpan read FMaxValue;
class property Zero: TTimeSpan read FZero;
end;
implementation
uses System.RTLConsts, System.SysUtils, System.Math;
type
TTimeSpanParser = record
public type
TParseError = (peNone, peFormat, peOverflow, peOverflowHMS);
private
FStr: string;
FPos: Integer;
public
function CurrentChar: Char; inline;
function NextChar: Char; inline;
function NextNonDigit: Char;
function Convert(const S: string): Int64;
function TryConvert(const S: string; out Value: Int64): TParseError;
function NextInt(MaxValue: Integer; out Value: Integer): TParseError;
function ConvertTime(out Time: Int64): TParseError;
procedure SkipWhite;
end;
{ TTimeSpanParser }
function TTimeSpanParser.CurrentChar: Char;
begin
if FPos <= Length(FStr) then
Result := FStr[FPos]
else
Result := #0;
end;
function TTimeSpanParser.NextChar: Char;
begin
if FPos <= Length(FStr) then
Inc(FPos);
Result := CurrentChar;
end;
function TTimeSpanParser.NextNonDigit: Char;
var
I: Integer;
begin
for I := FPos to Length(FStr) do
begin
Result := FStr[I];
if (Result < '0') or (Result > '9') then // do not localize
Exit;
end;
Result := #0;
end;
function TTimeSpanParser.Convert(const S: string): Int64;
begin
Result := 0;
case TryConvert(S, Result) of
peFormat:
raise Exception.Create(sInvalidTimespanFormat);
peOverflow:
raise EIntOverflow.Create(sTimespanTooLong);
peOverflowHMS:
raise EIntOverflow.Create(sTimespanElementTooLong);
end;
end;
function TTimeSpanParser.NextInt(MaxValue: Integer; out Value: Integer): TParseError;
var
StartPos: Integer;
Ch: Char;
begin
Value := 0;
StartPos := FPos;
Ch := CurrentChar;
while (Ch >= '0') and (Ch <= '9') do // do not localize
begin
if Value and $F0000000 <> 0 then
Exit(peOverflow);
Value := Value * 10 + (Ord(Ch) - $30);
if Value < 0 then
Exit(peOverflow);
Ch := NextChar;
end;
if FPos = StartPos then
Exit(peFormat);
if Value > MaxValue then
Exit(peOverflow);
Result := peNone;
end;
function TTimeSpanParser.ConvertTime(out Time: Int64): TParseError;
var
Part: Integer;
Ch: Char;
begin
Time := 0;
Result := NextInt(23, Part);
if Result <> peNone then
begin
if Result = peOverflow then
Result := peOverflowHMS;
Exit;
end;
Time := Part * TTimeSpan.TicksPerHour;
if CurrentChar <> ':' then
Exit(peFormat);
NextChar;
Result := NextInt(59, Part);
if Result <> peNone then
begin
if Result = peOverflow then
Result := peOverflowHMS;
Exit;
end;
Time := Time + Part * TTimeSpan.TicksPerMinute;
if CurrentChar = ':' then
begin
if NextChar <> '.' then
begin
Result := NextInt(59, Part);
if Result <> peNone then
begin
if Result = peOverflow then
Result := peOverflowHMS;
Exit;
end;
Time := Time + Part * TTimeSpan.TicksPerSecond;
end;
if CurrentChar = '.' then
begin
Ch := NextChar;
Part := TTimeSpan.TicksPerSecond;
while (Part > 1) and ((Ch >= '0') and (Ch <= '9')) do // do not localize
begin
Part := Part div 10;
Time := Time + (Ord(Ch) - $30) * Part;
Ch := NextChar;
end;
end;
end;
Result := peNone;
end;
procedure TTimeSpanParser.SkipWhite;
var
Ch: Char;
begin
Ch := CurrentChar;
while (Ch= ' ') or (Ch = #9) do
Ch := NextChar;
end;
function TTimeSpanParser.TryConvert(const S: string; out Value: Int64): TParseError;
var
Ticks, TimeVal: Int64;
Days: Integer;
IsNegative: Boolean;
begin
Ticks := 0;
Value := 0;
FStr := S;
FPos := 0;
NextChar;
SkipWhite;
IsNegative := False;
if CurrentChar = '-' then
begin
IsNegative := True;
NextChar;
end;
if NextNonDigit = ':' then
begin
Result := ConvertTime(Ticks);
if Result <> peNone then
Exit;
end else
begin
Result := NextInt($a2e3ff, Days);
if Result <> peNone then
Exit;
Ticks := Days * TTimeSpan.TicksPerDay;
if CurrentChar = '.' then
begin
NextChar;
Result := ConvertTime(TimeVal);
if Result <> peNone then
Exit;
Ticks := Ticks + TimeVal;
end;
end;
if IsNegative then
begin
Ticks := -Ticks;
if Ticks > 0 then
Exit(peOverflow);
end else if Ticks < 0 then
Exit(peOverflow);
SkipWhite;
if FPos <= Length(FStr) then
Exit(peFormat);
Value := Ticks;
Result := peNone;
end;
{ TTimeSpan }
constructor TTimeSpan.Create(ATicks: Int64);
begin
FTicks := ATicks;
end;
constructor TTimeSpan.Create(Hours, Minutes, Seconds: Integer);
begin
FTicks := Int64(Hours) * 3600 + Int64(Minutes) * 60 + Seconds;
if (FTicks > MaxSeconds) or (FTicks < MinSeconds) then
raise EArgumentOutOfRangeException.Create(sTimespanTooLong);
FTicks := FTicks * TicksPerSecond;
end;
constructor TTimeSpan.Create(Days, Hours, Minutes, Seconds: Integer);
begin
Create(Days, Hours, Minutes, Seconds, 0);
end;
constructor TTimeSpan.Create(Days, Hours, Minutes, Seconds, Milliseconds: Integer);
var
LTicks: Int64;
begin
LTicks := (Int64(Days) * 3600 * 24 + Int64(Hours) * 3600 + Int64(Minutes) * 60 + Seconds) * 1000 + Milliseconds;
if (LTicks > MaxMilliseconds) or (LTicks < MinMilliseconds) then
raise EArgumentOutOfRangeException.Create(sTimespanTooLong);
FTicks := LTicks * TicksPerMillisecond;
end;
function TTimeSpan.Add(const TS: TTimeSpan): TTimeSpan;
var
NewTicks: Int64;
begin
NewTicks := FTicks + TS.FTicks;
if ((FTicks shr 63) = (TS.FTicks shr 63)) and ((FTicks shr 63) <> (NewTicks shr 63)) then
raise EArgumentOutOfRangeException.Create(sTimespanTooLong);
Result := TTimeSpan.Create(NewTicks);
end;
class operator TTimeSpan.Add(const Left, Right: TTimeSpan): TTimeSpan;
begin
Result := Left.Add(Right);
end;
class operator TTimeSpan.Add(const Left: TDateTime; Right: TTimeSpan): TDateTime;
begin
Result := TimeStampToDateTime(MSecsToTimeStamp(TimeStampToMSecs(DateTimeToTimeStamp(Left)) + Trunc(Right.TotalMilliseconds)));
end;
class operator TTimeSpan.Add(const Left: TTimeSpan; Right: TDateTime): TDateTime;
begin
Result := Right + Left;
end;
function TTimeSpan.Duration: TTimeSpan;
begin
if FTicks = MinValue.FTicks then
raise EIntOverflow.Create(sInvalidTimespanDuration);
if FTicks < 0 then
Result := TTimeSpan.Create(-FTicks)
else
Result := TTimeSpan.Create(FTicks);
end;
class operator TTimeSpan.Equal(const Left, Right: TTimeSpan): Boolean;
begin
Result := Left.FTicks = Right.FTicks;
end;
class operator TTimeSpan.Explicit(const Value: TTimeSpan): string;
begin
Result := Value.ToString;
end;
class function TTimeSpan.FromDays(Value: Double): TTimeSpan;
begin
Result := GetScaledInterval(Value, MillisPerDay);
end;
class function TTimeSpan.FromHours(Value: Double): TTimeSpan;
begin
Result := GetScaledInterval(Value, MillisPerHour);
end;
class function TTimeSpan.FromMilliseconds(Value: Double): TTimeSpan;
begin
Result := GetScaledInterval(Value, 1);
end;
class function TTimeSpan.FromMinutes(Value: Double): TTimeSpan;
begin
Result := GetScaledInterval(Value, MillisPerMinute);
end;
class function TTimeSpan.FromSeconds(Value: Double): TTimeSpan;
begin
Result := GetScaledInterval(Value, MillisPerSecond);
end;
class function TTimeSpan.FromTicks(Value: Int64): TTimeSpan;
begin
Result := TTimeSpan.Create(Value);
end;
function TTimeSpan.GetDays: Integer;
begin
Result := Integer(FTicks div TicksPerDay);
end;
function TTimeSpan.GetHours: Integer;
begin
Result := Integer((FTicks div TicksPerHour) mod 24);
end;
function TTimeSpan.GetMilliseconds: Integer;
begin
Result := Integer((FTicks div TicksPerMillisecond) mod 1000);
end;
function TTimeSpan.GetMinutes: Integer;
begin
Result := Integer((FTicks div TicksPerMinute) mod 60);
end;
function TTimeSpan.GetSeconds: Integer;
begin
Result := Integer((FTicks div TicksPerSecond) mod 60);
end;
function TTimeSpan.GetTotalDays: Double;
begin
Result := FTicks * DaysPerTick;
end;
function TTimeSpan.GetTotalHours: Double;
begin
Result := FTicks * HoursPerTick;
end;
function TTimeSpan.GetTotalMilliseconds: Double;
begin
Result := FTicks * MillisecondsPerTick;
if Result > MaxMilliseconds then
Result := MaxMilliseconds
else if Result < MinMilliseconds then
Result := MinMilliseconds;
end;
function TTimeSpan.GetTotalMinutes: Double;
begin
Result := FTicks * MinutesPerTick;
end;
function TTimeSpan.GetTotalSeconds: Double;
begin
Result := FTicks * SecondsPerTick;
end;
class operator TTimeSpan.GreaterThan(const Left, Right: TTimeSpan): Boolean;
begin
Result := Left.FTicks > Right.FTicks;
end;
class operator TTimeSpan.GreaterThanOrEqual(const Left, Right: TTimeSpan): Boolean;
begin
Result := Left.FTicks >= Right.FTicks;
end;
class operator TTimeSpan.Implicit(const Value: TTimeSpan): string;
begin
Result := Value.ToString;
end;
class constructor TTimeSpan.Create;
begin
FMinValue.FTicks := -9223372036854775808;
FMaxValue.FTicks := $7FFFFFFFFFFFFFFF;
end;
class function TTimeSpan.GetScaledInterval(Value: Double; Scale: Integer): TTimeSpan;
var
NewVal: Double;
begin
if IsNan(Value) then
raise EArgumentException.Create(sTimespanValueCannotBeNan);
NewVal := Value * Scale;
if Value >= 0.0 then
NewVal := NewVal + 0.5
else
NewVal := NewVal - 0.5;
if (NewVal > MaxMilliseconds) or (NewVal < MinMilliseconds) then
raise EArgumentOutOfRangeException.Create(sTimespanTooLong);
Result := TTimeSpan.Create(Trunc(NewVal) * TicksPerMillisecond);
end;
class operator TTimeSpan.LessThan(const Left, Right: TTimeSpan): Boolean;
begin
Result := Left.FTicks < Right.FTicks;
end;
class operator TTimeSpan.LessThanOrEqual(const Left, Right: TTimeSpan): Boolean;
begin
Result := Left.FTicks <= Right.FTicks;
end;
function TTimeSpan.Negate: TTimeSpan;
begin
if FTicks = MinValue.FTicks then
raise EIntOverflow.Create(sCannotNegateTimespan);
Result := TTimeSpan.Create(-FTicks);
end;
class operator TTimeSpan.Negative(const Value: TTimeSpan): TTimeSpan;
begin
Result := Value.Negate;
end;
class operator TTimeSpan.NotEqual(const Left, Right: TTimeSpan): Boolean;
begin
Result := Left.FTicks <> Right.FTicks;
end;
class function TTimeSpan.Parse(const S: string): TTimeSpan;
var
TimeSpanParser: TTimeSpanParser;
begin
Result := TTimeSpan.Create(TimeSpanParser.Convert(S));
end;
class operator TTimeSpan.Positive(const Value: TTimeSpan): TTimeSpan;
begin
Result := Value;
end;
class operator TTimeSpan.Subtract(const Left, Right: TTimeSpan): TTimeSpan;
begin
Result := Left.Subtract(Right);
end;
function TTimeSpan.Subtract(const TS: TTimeSpan): TTimeSpan;
var
NewTicks: Int64;
begin
NewTicks := FTicks - TS.FTicks;
if ((FTicks shr 63) <> (TS.FTicks shr 63)) and ((FTicks shr 63) <> (NewTicks shr 63)) then
raise EArgumentOutOfRangeException.Create(sTimespanTooLong);
Result := TTimeSpan.Create(NewTicks);
end;
function TTimeSpan.ToString: string;
var
Fmt: string;
Days, SubSecondTicks: Integer;
LTicks: Int64;
begin
Fmt := '%1:.2d:%2:.2d:%3:.2d'; // do not localize
Days := FTicks div TicksPerDay;
LTicks := FTicks mod TicksPerDay;
if FTicks < 0 then
LTicks := -LTicks;
if Days <> 0 then
Fmt := '%0:d.' + Fmt; // do not localize
SubSecondTicks := LTicks mod TicksPerSecond;
if SubSecondTicks <> 0 then
Fmt := Fmt + '.%4:.7d'; // do not localize
Result := Format(Fmt,
[Days,
(LTicks div TicksPerHour) mod 24,
(LTicks div TicksPerMinute) mod 60,
(LTicks div TicksPerSecond) mod 60,
SubSecondTicks]);
end;
class function TTimeSpan.TryParse(const S: string; out Value: TTimeSpan): Boolean;
var
LTicks: Int64;
TimeSpanParser: TTimeSpanParser;
begin
if TimeSpanParser.TryConvert(S, LTicks) = peNone then
begin
Value := TTimeSpan.Create(LTicks);
Result := True;
end else
begin
Value := Zero;
Result := False;
end;
end;
class function TTimeSpan.Subtract(const D1, D2: TDateTime): TTimeSpan;
begin
Result := TTimeSpan.Create(Trunc(TimeStampToMSecs(DateTimeToTimeStamp(D1)) - TimeStampToMSecs(DateTimeToTimeStamp(D2))) * TicksPerMillisecond);
end;
class operator TTimeSpan.Subtract(const Left: TDateTime; Right: TTimeSpan): TDateTime;
begin
Result := TimeStampToDateTime(MSecsToTimeStamp(TimeStampToMSecs(DateTimeToTimeStamp(Left)) - Trunc(Right.TotalMilliseconds)));
end;
(*$HPPEMIT END 'namespace System { ' *)
(*$HPPEMIT END 'namespace Timespan { ' *)
(*$HPPEMIT END ' inline TTimeSpan operator+(const TTimeSpan &Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_Addition(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline System::TDateTime operator+(const TTimeSpan &Left, System::TDateTime Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_Addition(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline System::TDateTime operator+(const System::TDateTime Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_Addition(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline TTimeSpan operator-(const TTimeSpan &Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_Subtraction(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline System::TDateTime operator-(const System::TDateTime Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_Subtraction(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline bool operator ==(const TTimeSpan &Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_Equality(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline bool operator !=(const TTimeSpan &Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_Inequality(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline bool operator >(const TTimeSpan &Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_GreaterThan(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline bool operator >=(const TTimeSpan &Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_GreaterThanOrEqual(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline bool operator <(const TTimeSpan &Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_LessThan(Left,Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END ' inline bool operator <=(const TTimeSpan &Left, const TTimeSpan &Right) ' *)
(*$HPPEMIT END ' { ' *)
(*$HPPEMIT END ' return TTimeSpan::_op_LessThanOrEqual(Left, Right); ' *)
(*$HPPEMIT END ' } ' *)
(*$HPPEMIT END '} ' *)
(*$HPPEMIT END '} ' *)
end.
|
unit TestTypes;
interface
type
TDateTimeRec = record
Year, Month, Day,
Hour, Minute, Second : Word;
class operator Implicit(ADateTimeRec : TDateTimeRec) : TDateTime;
end;
implementation
uses
System.DateUtils;
{ TDateTimeRec }
class operator TDateTimeRec.Implicit(ADateTimeRec : TDateTimeRec) : TDateTime;
begin
with ADateTimeRec do
Result := EncodeDateTime(Year, Month, Day, Hour, Minute, Second, 0);
end;
end.
|
{ rxCRC unit
Copyright (C) 2005-2020 Lagunov Aleksey alexs@yandex.ru and Lazarus team
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit rxCRC;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
function rxCRC8(Buffer:String;Polynom,Initial:Cardinal):Cardinal; overload;
function rxCRC8(Buffer:PByteArray; BufferLen:Cardinal; Polynom,Initial:Cardinal):Cardinal; overload;
implementation
{autor - hansotten
http://forum.lazarus.freepascal.org/index.php?topic=31532.msg202338#msg202338
}
function rxCRC8(Buffer:String;Polynom,Initial:Cardinal):Cardinal;
var
i,j : Integer;
begin
{ Result:=Initial;
for i:=1 to Length(Buffer) do
begin
Result:=Result xor Ord(buffer[i]);
for j:=0 to 7 do
begin
if (Result and $80)<>0 then
Result:=(Result shl 1) xor Polynom
else
Result:=Result shl 1;
end;
end;
Result:=Result and $ff;}
if Length(Buffer) > 0 then
Result:=rxCRC8(@Buffer[1], Length(Buffer), Polynom, Initial)
else
Result:=Initial;
end;
function rxCRC8(Buffer: PByteArray; BufferLen: Cardinal; Polynom, Initial: Cardinal
): Cardinal;
var
i,j : Integer;
begin
Result:=Initial;
for i:=0 to BufferLen-1 do
begin
Result:=Result xor Buffer^[i];
for j:=0 to 7 do
begin
if (Result and $80)<>0 then
Result:=(Result shl 1) xor Polynom
else
Result:=Result shl 1;
end;
end;
Result:=Result and $ff;
end;
end.
|
unit uDelphiLexer;
interface
uses
uLexer, uText, Character;
const
ltDfmIdentifier = 1;
ltDfmStrin = 2;
ltDfmNumber = 3;
ltDfmEqual = 6; // =
ltDfmLT = 7; // <
ltDfmGT = 8; // >
ltDfmLeftBracket = 9; // (
ltDfmRightBracket = 10; // )
ltDfmColon = 11; // :
ltDfmLeftSqBracket = 12; // [
ltDfmRightSqBracket = 13; // ]
// Key words
ltDfm_object = 100;
ltDfm_end = 101;
ltDfm_inherited = 102;
ltDfm_item = 103;
type
TDfmLexer = class(TNativeLexer)
procedure ReadIdentifier;
procedure ReadNumber;
constructor Create(const AText: IText);
function GetLexeme: TLexeme; override;
private
end;
implementation
{ TDfmLexer }
constructor TDfmLexer.Create(const AText: IText);
begin
end;
function TDfmLexer.GetLexeme: TLexeme;
begin
Result.LexemeType := cLexemeTypeEnd;
Result.Pos := FText.Pos;
Result.Data := '';
FText.SkipWhiteChar;
if FText.Eof then
Exit;
if FText.Ch.IsLetter then
ReadIdentifier
else
if FText.Ch.IsDigit then
ReadNumber
else
case FText.Ch of
'=': Result.LexemeType := ltDfmEqual;
'<': Result.LexemeType := ltDfmLT;
'>': Result.LexemeType := ltDfmGT;
'(': Result.LexemeType := ltDfmLeftBracket;
')': Result.LexemeType := ltDfmRightBracket;
':': Result.LexemeType := ltDfmColon;
'[': Result.LexemeType := ltDfmLeftSqBracket;
']': Result.LexemeType := ltDfmRightSqBracket;
else
end;
end;
procedure TDfmLexer.ReadIdentifier;
begin
end;
procedure TDfmLexer.ReadNumber;
begin
end;
end.
|
//
// uSettings for GLSViewer
//
unit uSettings;
interface
uses
Winapi.Windows, Winapi.Messages,
System.Win.Registry, System.IniFiles, System.SysUtils,
Vcl.Forms, Vcl.Graphics, Vcl.ActnList,
//
GNUGettext;
procedure InitGeneralRegistry;
//-------------------------------------------------------------------------
implementation
// ------------------------------------------------------------------------
uses
uGlobals;
procedure InitGeneralRegistry;
var
RegIni: TRegistryIniFile;
FileVersion: cardinal;
begin
GeneralSection := RegGLSViewer + 'General';
FileVersion := GetFileVersion(Application.ExeName);
ExePath := ExtractFilePath(Application.ExeName);
RegIni := TRegistryIniFile.Create(GeneralSection);
try
with RegIni do
begin
if not RegIni.SectionExists(GeneralSection) then
begin
WriteString(GeneralSection, 'ExePath', ExePath); //Don't translate the strings
WriteInteger(GeneralSection, 'FileVersion', FileVersion);
WriteString(GeneralSection, 'License', 'MPL');
WriteInteger(GeneralSection, 'Language', LANG_ENGLISH); //9, Default installation
Language := LANG_ENGLISH;
end
else
begin
ExePath := ReadString(GeneralSection, 'ExePath', ExePath);
Language := ReadInteger(GeneralSection, 'Language', LANG_ENGLISH);
//9, LANG_ENGLISH - Default
end;
end;
finally
RegIni.Free;
end;
if RegIni.ValueExists(GeneralSection,'SplashStart') then
SplashStart := RegIni.ReadBool(GeneralSection,'SplashStart',False)
else
SplashStart := True;
if RegIni.ValueExists(GeneralSection,'TipOfTheDay') then
TipOfTheDay := RegIni.ReadBool(GeneralSection,'TipOfTheDay', True)
else
TipOfTheDay := False;
end;
initialization
InitGeneralRegistry;
end.
|
{
*******************************************************************************************************************
SpiderForm: Contains TSpiderForm component which used to generate HTML form
Author: Motaz Abdel Azeem
email: motaz@code.sd
Home page: http://code.sd
License: LGPL
Last modifie: 23.Dec.2012
Jul/2010 - Modified by Luiz Américo
* Remove LCL dependency
Jul/2010 - Modified byHéctor S. Ponce
* Add check box
16.July.2010 adding AddHTML, LabelCSS in AddText by Cem Zafer Demirsoy
*******************************************************************************************************************
}
unit SpiderForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TInputType = (itText, itPassword, itButton, itSubmit, itTextArea, itFile, itHidden, itCheckbox);
{ TSpiderForm }
TSpiderForm = class(TComponent)
private
fMethod: string;
fAction: string;
fExtraParam: string;
fPutInTable: Boolean;
fRowOpened: Boolean;
fConentList: TStringList;
{ Private declarations }
protected
{ Protected declarations }
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure AddText(AText: string; LabelCSS: string = ''; CloseRow: Boolean = False);
procedure AddInputExt(InputType: TInputType; const InputName: string; const InputValue: string = ''; const ExtraParam: string = '';
NewLine: Boolean = True; CloseRow: Boolean = True; TextBefor: String = ''; TextAfter: string = '');
procedure AddHTML(AHTMLText: string);
procedure AddInput(InputType: TInputType; const InputName: string; const InputValue: string = ''; const ExtraParam: string = '';
NewLine: Boolean = True);
function Contents: string;
procedure Clear;
procedure NewRow;
procedure CloseRow;
{ Public declarations }
published
property Method: string read fMethod write fMethod;
property Action: string read fAction write fAction;
property PutInTable: Boolean read fPutInTable write fPutInTable;
property ExtraParam: string read fExtraParam write fExtraParam;
{ Published declarations }
end;
implementation
{ TSpiderForm }
constructor TSpiderForm.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
fConentList:= TStringList.Create;
Method:= 'POST';
fPutInTable:= True;
fRowOpened:= False;
end;
destructor TSpiderForm.Destroy;
begin
fConentList.Free;
inherited Destroy;
end;
procedure TSpiderForm.AddText(AText: string; LabelCSS: string; CloseRow: Boolean = False
);
var
TR, TD, STD, STR: string;
LB, LBT: string;
begin
if fPutInTable then
begin
if not fRowOpened then
begin
TR:= '<TR>';
fRowOpened:= True;
end;
TD:= '<TD>';
STD:= '</TD>';
if CloseRow then
begin
STR:= '</TR>';
fRowOpened:= False;
end
else
STR:= '';
end;
LB:= '';
LBT:= '';
if LabelCSS <> '' then
begin
LB:= '<LABEL ' + LabelCSS + '>';
LBT:= '</LABEL>';
end;
fConentList.Add(TR + TD + LB + AText + LBT + STD + STR);
end;
procedure TSpiderForm.AddInputExt(InputType: TInputType; const InputName: string;
const InputValue: string; const ExtraParam: string; NewLine: Boolean;
CloseRow: Boolean = True; TextBefor: String = ''; TextAfter: string = '');
var
TR, STR, TD, STD, NameAttr: string;
begin
if fPutInTable then
begin
if not fRowOpened then
begin
TR:= '<TR>';
fRowOpened:= True;
end
else
TR:= '';
TD:= '<TD>';
STD:= '</TD>';
if CloseRow then
begin
STR:= '</TR>';
fRowOpened:= False;
end
else
STR:= '';
end;
if InputName <> '' then
NameAttr := ' name="' + InputName + '"'
else
NameAttr := '';
fConentList.Add(TR + TD + TextBefor);
case InputType of
itText: fConentList.Add('<input type="text"'+ NameAttr + ' value="' + InputValue + '" ' + ExtraParam + ' />' );
itPassword: fConentList.Add('<input type="password"' + NameAttr + ' value="' + InputValue + '" ' + ExtraParam + ' />' );
itButton: fConentList.Add('<input type="button"' + NameAttr + ' value="' + InputValue + '" ' + ExtraParam + '/>');
itSubmit: fConentList.Add('<input type="submit"' + NameAttr + ' value="' + InputValue + '" ' + ExtraParam + ' />');
itTextArea: fConentList.Add('<textarea' + NameAttr + ' ' + ExtraParam + '>' + InputValue + '</textarea>');
itFile: fConentList.Add('<input type="file"' + NameAttr + ' value="' + InputValue + '" ' + ExtraParam + ' />');
itHidden: fConentList.Add('<input type="hidden"' + NameAttr + ' value="' + InputValue + '" ' + ExtraParam + ' />');
itCheckbox: fConentList.Add('<input type="checkbox" name="' + InputName + '" value="'+ InputValue + '" ' +
ExtraParam + ' /> ');
end;
fConentList.Add(TextAfter + STD + STR);
if (not fPutInTable) and NewLine then
fConentList.Add('<br />');
end;
procedure TSpiderForm.AddHTML(AHTMLText: string);
begin
fConentList.Add(AHTMLText);
end;
procedure TSpiderForm.AddInput(InputType: TInputType; const InputName: string;
const InputValue: string; const ExtraParam: string; NewLine: Boolean);
begin
AddInputExt(InputType, InputName, InputValue, ExtraParam, NewLine);
end;
function TSpiderForm.Contents: string;
begin
if fPutInTable then
begin
fConentList.Insert(0, '<table>');
fConentList.Add('</table>');
end;
Result:= '<form method="' + fMethod + '" action="' + fAction + '" ' + fExtraParam + ' >' + #10 +
fConentList.Text + '</form>';
end;
procedure TSpiderForm.Clear;
begin
fConentList.Clear;
fRowOpened:= False;
end;
procedure TSpiderForm.NewRow;
begin
if fPutInTable then
begin
fConentList.Add('<tr>');
fRowOpened:= True;
end;
end;
procedure TSpiderForm.CloseRow;
begin
if fPutInTable then
begin
fConentList.Add('</tr>');
fRowOpened:= False;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.