text stringlengths 14 6.51M |
|---|
unit Dmitry.PathProviders.MyComputer;
interface
uses
System.StrUtils,
System.SysUtils,
Winapi.Windows,
Winapi.ShellApi,
Vcl.Graphics,
Dmitry.Memory,
Dmitry.Utils.Files,
Dmitry.Utils.System,
Dmitry.Utils.ShellIcons,
Dmitry.PathProviders;
const
cNetworkPath = 'Network';
type
THomeItem = class(TPathItem)
protected
function GetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
public
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
constructor Create; override;
end;
TDriveItem = class(TPathItem)
protected
function InternalGetParent: TPathItem; override;
function InternalCreateNewInstance: TPathItem; override;
function GetIsDirectory: Boolean; override;
public
function LoadImage(Options, ImageSize: Integer): Boolean; override;
constructor CreateFromPath(APath: string; Options, ImageSize: Integer); override;
end;
type
TMyComputerProvider = class(TPathProvider)
protected
function InternalFillChildList(Sender: TObject; Item: TPathItem; List: TPathItemCollection;
Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean; override;
public
function Supports(Item: TPathItem): Boolean; override;
function Supports(Path: string): Boolean; override;
function SupportsFeature(Feature: string): Boolean; override;
function CreateFromPath(Path: string): TPathItem; override;
end;
function ExtractPathExPath(Path: string): string;
function IsPathEx(Path: string): Boolean;
implementation
function IsPathEx(Path: string): Boolean;
var
P1, P2: Integer;
begin
P1 := Pos('::', Path);
P2 := Pos('://', Path);
Result := (P1 > 0) and (P2 > 0) and (P2 > P1);
end;
function ExtractPathExPath(Path: string): string;
begin
if IsPathEx(Path) then
Result := Copy(Path, 1, Pos('::', Path) - 1)
else
Result := Path;
end;
{ TMyComputerProvider }
function TMyComputerProvider.CreateFromPath(Path: string): TPathItem;
begin
Result := nil;
if Path = '' then
Result := THomeItem.Create;
end;
function TMyComputerProvider.InternalFillChildList(Sender: TObject;
Item: TPathItem; List: TPathItemCollection; Options, ImageSize: Integer; PacketSize: Integer; CallBack: TLoadListCallBack): Boolean;
const
DRIVE_REMOVABLE = 2;
DRIVE_FIXED = 3;
DRIVE_REMOTE = 4;
DRIVE_CDROM = 5;
var
I: Integer;
DI: TDriveItem;
Drive: string;
DriveType : UINT;
OldMode: Cardinal;
Cancel: Boolean;
begin
Cancel := False;
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
for I := Ord('C') to Ord('Z') do
begin
DriveType := GetDriveType(PChar(Chr(I) + ':\'));
if (DriveType = DRIVE_REMOVABLE) or (DriveType = DRIVE_FIXED) or
(DriveType = DRIVE_REMOTE) or (DriveType = DRIVE_CDROM) or (DriveType = DRIVE_RAMDISK) then
begin
Drive := Chr(I) + ':\';
DI := TDriveItem.CreateFromPath(Drive, Options, ImageSize);
List.Add(DI);
if List.Count mod PacketSize = 0 then
begin
if Assigned(CallBack) then
CallBack(Sender, Item, List, Cancel);
if Cancel then
Break;
end;
end;
end;
if Assigned(CallBack) then
CallBack(Sender, Item, List, Cancel);
finally
SetErrorMode(OldMode);
end;
Result := True;
end;
function TMyComputerProvider.Supports(Item: TPathItem): Boolean;
begin
Result := Item is THomeItem;
Result := Result or Supports(Item.Path);
end;
function TMyComputerProvider.Supports(Path: string): Boolean;
begin
Result := Path = '';
end;
function TMyComputerProvider.SupportsFeature(Feature: string): Boolean;
begin
Result := Feature = PATH_FEATURE_CHILD_LIST;
end;
{ TDriveItem }
constructor TDriveItem.CreateFromPath(APath: string; Options, ImageSize: Integer);
var
DS: TDriveState;
begin
inherited;
FImage := nil;
FParent := nil;
FDisplayName := 'unknown drive';
if Length(APath) > 0 then
begin
DS := DriveState(AnsiString(APath)[1]);
if Options and PATH_LOAD_FAST > 0 then
FDisplayName := UpCase(APath[1]) + ':\'
else
begin
if (DS = DS_DISK_WITH_FILES) or (DS = DS_EMPTY_DISK) then
FDisplayName := GetCDVolumeLabelEx(UpCase(APath[1])) + ' (' + APath[1] + ':)'
else
FDisplayName := MrsGetFileType(UpCase(APath[1]) + ':\') + ' (' + APath[1] + ':)';
end;
if Options and PATH_LOAD_NO_IMAGE = 0 then
LoadImage(Options, ImageSize);
end;
if Options and PATH_LOAD_CHECK_CHILDREN > 0 then
FCanHaveChildren := IsDirectoryHasDirectories(Path);
end;
function TDriveItem.LoadImage(Options, ImageSize: Integer): Boolean;
var
Icon: HIcon;
begin
Result := False;
F(FImage);
Icon := ExtractShellIcon(FPath, ImageSize);
if Icon <> 0 then
begin
FImage := TPathImage.Create(Icon);
Result := True;
end;
end;
function TDriveItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function TDriveItem.InternalCreateNewInstance: TPathItem;
begin
Result := TDriveItem.Create;
end;
function TDriveItem.InternalGetParent: TPathItem;
begin
Result := THomeItem.Create;
end;
{ THomeItem }
constructor THomeItem.Create;
begin
inherited;
FDisplayName := 'My Computer';
UpdateText;
end;
constructor THomeItem.CreateFromPath(APath: string; Options,
ImageSize: Integer);
begin
inherited;
FDisplayName := 'My Computer';
UpdateText;
if (ImageSize > 0) and (Options and PATH_LOAD_NO_IMAGE = 0) then
LoadImage(Options, ImageSize);
end;
function THomeItem.GetIsDirectory: Boolean;
begin
Result := True;
end;
function THomeItem.GetParent: TPathItem;
begin
Result := nil;
end;
function THomeItem.InternalCreateNewInstance: TPathItem;
begin
Result := THomeItem.Create;
end;
function THomeItem.LoadImage(Options, ImageSize: Integer): Boolean;
begin
F(FImage);
UpdateImage(ImageSize);
Result := True;
end;
initialization
PathProviderManager.RegisterProvider(TMyComputerProvider.Create);
end.
|
{
Unit Name : MILAssociate.pas
Component Name : TMILAssociate
Author : Larry J. Rutledge ( lrutledge@jps.net )
Created : August 4, 1998
Last Modified : N/A
Description : This component makes creating Windows file associations
a simple, painless process. After registering the
application, all that is required is a call to Associate
or UnAssociate to add or remove file associations.
Instructions : To use the component, drop it onto a form and assign values
to all the properties. Then in code call the RegisterApp
method. This process puts an entry in the Windows Registry
for the application that allows associations to be created.
To associate an extension with the application identified in
the component properties, call the Associate method and pass
it the extension to associate.
Important Note : No notes for this component
History : Version Date Author Description
------- ---------- ------ --------------------------
1.0.0 08/04/1998 LJR Created initial component.
Proposed
Revisions : No currently proposed revisions
}
unit MILAssociate;
interface
uses
Classes, Dialogs, Forms, Registry, ShlObj, SysUtils, Windows;
const
_TITLE = 'TMILAssociate';
_VERSION = '1.0.0';
_AUTHOR = 'Larry J. Rutledge';
_COPYRIGHT = '© Copyright 1998, Millennial Software';
type
{ TMILAssociate - The actual component class }
TMILAssociate = class(TComponent)
private
FKeyName : String;
FPathToApp : String;
FIconPath : String;
FIcon : Integer;
FShellCmd : String;
FShell : String;
FTypeName : String;
FNew : Boolean;
FQuick : Boolean;
shellReg : TRegistry;
procedure SetKeyName(Value : String);
procedure SetPathToApp(Value : String);
procedure SetIconPath(Value : String);
procedure SetIcon(Value : Integer);
procedure SetShellCmd(Value : String);
procedure SetShell(Value : String);
procedure SetTypeName(Value : String);
procedure SetNew(Value : Boolean);
procedure SetQuick(Value : Boolean);
function GetKeyName : String;
function GetPathToApp : String;
function GetIconPath : String;
function GetIcon : Integer;
function GetShellCmd : String;
function GetShell : String;
function GetTypeName : String;
function GetNew : Boolean;
function GetQuick : Boolean;
protected
function qualifyExt(Ext : String) : String;
function AddSlash(Path : String) : String;
function StripPeriod(Ext : String) : String;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure RegisterApp;
procedure UnRegisterApp;
procedure Associate(Extension : String);
procedure UnAssociate(Extension : String);
function Enumerate : TStringList;
published
property KeyName : String read GetKeyName write SetKeyName;
property PathToApp : String read GetPathToApp write SetPathToApp;
property IconPath : String read GetIconPath write SetIconPath;
property Icon : Integer read GetIcon write SetIcon default 0;
property ShellCmd : String read GetShellCmd write SetShellCmd;
property Shell : String read GetShell write SetShell;
property TypeName : String read GetTypeName write SetTypeName;
property ShowInNew : Boolean read GetNew write SetNew default False;
property QuickView : Boolean read GetQuick write SetQuick default False;
end;
procedure Register;
implementation
{---------------------------------------------------------}
{ TIconPathProperty - IconPath Property Editor methods }
{---------------------------------------------------------}
{---------------------------------------------------------}
{ TMILAssociate - The component implementation )
{---------------------------------------------------------}
constructor TMILAssociate.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FIcon := 0;
FNew := False;
FQuick := False;
FShellCmd := 'Open';
end;
destructor TMILAssociate.Destroy;
begin
inherited Destroy;
end;
procedure TMILAssociate.SetKeyName(Value : String);
begin
if FKeyName <> Value then
begin
FKeyName := Value;
end;
end;
procedure TMILAssociate.SetPathToApp(Value : String);
begin
if FPathToApp <> Value then
begin
FPathToApp := Value;
end;
end;
procedure TMILAssociate.SetIconPath(Value : String);
begin
if FIconPath <> Value then
begin
FIconPath := Value;
end;
end;
procedure TMILAssociate.SetIcon(Value : Integer);
begin
if FIcon <> Value then
begin
FIcon := Value;
end;
end;
procedure TMILAssociate.SetShellCmd(Value : String);
begin
if FShellCmd <> Value then
begin
FShellCmd := Value;
end;
end;
procedure TMILAssociate.SetShell(Value : String);
begin
if FShell <> Value then
begin
FShell := Value;
end;
end;
procedure TMILAssociate.SetTypeName(Value : String);
begin
if FTypeName <> Value then
begin
FTypeName := Value;
end;
end;
procedure TMILAssociate.SetNew(Value : Boolean);
begin
if FNew <> Value then
begin
FNew := Value;
end;
end;
procedure TMILAssociate.SetQuick(Value : Boolean);
begin
if FQuick <> Value then
begin
FQuick := Value;
end;
end;
function TMILAssociate.GetKeyName : String;
begin
Result := FKeyName;
end;
function TMILAssociate.GetPathToApp : String;
begin
Result := FPathToApp;
end;
function TMILAssociate.GetIconPath : String;
begin
Result := FIconPath;
end;
function TMILAssociate.GetIcon : Integer;
begin
Result := FIcon;
end;
function TMILAssociate.GetShellCmd : String;
begin
Result := FShellCmd;
end;
function TMILAssociate.GetShell : String;
begin
Result := FShell;
end;
function TMILAssociate.GetTypeName : String;
begin
Result := FTypeName;
end;
function TMILAssociate.GetNew : Boolean;
begin
Result := FNew;
end;
function TMILAssociate.GetQuick : Boolean;
begin
Result := FQuick;
end;
(******************************************************************************)
(* QualifyExt - Takes a file extension as a parameter and returns a file *)
(* extension with a leading period (.) *)
(******************************************************************************)
function TMILAssociate.qualifyExt(Ext : String) : String;
begin
if Pos('.', Ext) > 1 then
Result := Copy(Ext, Pos('.', Ext), Length(Ext))
else
if Ext[1] <> '.' then
Result := '.' + Ext
else
Result := Ext;
end;
(******************************************************************************)
(* AddSlash - Takes a path as a parameter and returns a path with a *)
(* leading slash (\) *)
(******************************************************************************)
function TMILAssociate.AddSlash(Path : String) : String;
begin
if Path[Length(Path)] <> '\' then
Result := Path + '\'
else
Result := Path;
end;
(******************************************************************************)
(* StripPeriod - Takes a file extension as a parameter and returns a file *)
(* extension without a leading period (.) *)
(******************************************************************************)
function TMILAssociate.StripPeriod(Ext : String) : String;
begin
if Ext[1] = '.' then
Result := Copy(Ext, 2, Length(Ext))
else
Result := Ext;
end;
(******************************************************************************)
(* RegisterApp - Registers the application identified by the properties in *)
(* the Windows registry. *)
(******************************************************************************)
procedure TMILAssociate.RegisterApp;
begin
shellReg := TRegistry.Create;
shellReg.RootKey := HKEY_CLASSES_ROOT;
shellReg.OpenKey(FKeyName, True);
shellReg.WriteString('', FTypeName);
shellReg.CloseKey;
shellReg.OpenKey(FKeyName + '\DefaultIcon', True);
shellReg.WriteString('', FIconPath + ',' + IntToStr(FIcon));
shellReg.CloseKey;
shellReg.OpenKey(FKeyName + '\Shell\' + FShellCmd + '\Command', True);
shellReg.WriteString('', FShell);
if FQuick then
begin
shellReg.CloseKey;
shellReg.OpenKey(FKeyName + '\QuickView', True);
shellReg.WriteString('', '*');
end else
begin
shellReg.CloseKey;
shellReg.DeleteKey(FKeyName + '\QuickView');
end;
shellReg.CloseKey;
shellReg.Free;
// Update system to notify of association change
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, PChar(''), PChar(''));
end;
(******************************************************************************)
(* UnRegisterApp - UnRegisters the application identified by the properties *)
(* in the Windows registry. *)
(******************************************************************************)
procedure TMILAssociate.UnRegisterApp;
begin
shellReg := TRegistry.Create;
shellReg.RootKey := HKEY_CLASSES_ROOT;
shellReg.DeleteKey(FKeyName + '\Shell');
shellReg.DeleteKey(FKeyName + '\QuickView');
shellReg.DeleteKey(FKeyName + '\DefaultIcon');
shellReg.DeleteKey(FKeyName);
shellReg.Free;
// Update system to notify of association change
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, PChar(''), PChar(''));
end;
(******************************************************************************)
(* Associate - Associates the specified file extension with the currently*)
(* identified application. Also stores old association in the*)
(* event that the association needs to be restored. *)
(******************************************************************************)
procedure TMILAssociate.Associate(Extension : String);
var
Ext : String;
begin
shellReg := TRegistry.Create;
shellReg.RootKey := HKEY_CLASSES_ROOT;
Ext := qualifyExt(Extension);
if FALSE (*shellReg.KeyExists(Ext)*) then
begin
(*
shellReg.OpenKey(Ext, True);
WorkStr := shellReg.ReadString('');
if FNew then
begin
shellReg.OpenKey('ShellNew', True);
shellReg.WriteString('NullFile', '');
end else
begin
shellReg.CloseKey;
shellReg.DeleteKey(WorkStr + '\ShellNew');
end;
shellReg.CloseKey;
if shellReg.KeyExists(WorkStr) then
begin
shellReg.CloseKey;
shellReg.OpenKey(WorkStr, False);
// if shellReg.ReadString('') = '' then
shellReg.WriteString('', FTypeName);
shellReg.CloseKey;
shellReg.OpenKey(WorkStr + '\DefaultIcon', TRUE);
// shellReg.WriteString('OldAssociation', shellReg.ReadString(''));
shellReg.WriteString('', 'blabla');
// shellReg.WriteString('', FIconPath + ',' + IntToStr(FIcon));
// shellReg.CloseKey;
shellReg.OpenKey(WorkStr + '\Shell\' + FShellCmd + '\Command', True);
// shellReg.WriteString('OldAssociation', shellReg.ReadString(''));
shellReg.WriteString('', FShell);
if FQuick then
begin
shellReg.CloseKey;
shellReg.OpenKey(WorkStr + '\QuickView', True);
shellReg.WriteString('', '*');
end else
begin
shellReg.CloseKey;
shellReg.DeleteKey(WorkStr + '\QuickView');
end;
end else
begin
shellReg.CloseKey;
shellReg.OpenKey(WorkStr, True);
shellReg.WriteString('', FTypeName);
shellReg.CloseKey;
shellReg.OpenKey(WorkStr + '\DefaultIcon', True);
shellReg.WriteString('', FIconPath + ',' + IntToStr(FIcon));
shellReg.CloseKey;
shellReg.OpenKey(WorkStr + '\Shell\' + FShellCmd + '\Command', True);
shellReg.WriteString('', FShell);
if FQuick then
begin
shellReg.CloseKey;
shellReg.OpenKey(WorkStr + '\QuickView', True);
shellReg.WriteString('', '*');
end;
end;
*)
end else
begin
shellReg.OpenKey(Ext, True);
shellReg.WriteString('', FTypeName);
shellReg.WriteString('Content Type', 'text/plain');
if FNew then
begin
shellReg.OpenKey('ShellNew', True);
shellReg.WriteString('NullFile', '');
end;
shellReg.CloseKey;
shellReg.OpenKey(FTypeName, True);
shellReg.WriteString('', FTypeName);
shellReg.CloseKey;
shellReg.OpenKey(FTypeName+'\DefaultIcon', True);
shellReg.WriteString('', FIconPath + ',' + IntToStr(FIcon));
shellReg.CloseKey;
shellReg.OpenKey(FTypeName+'\Shell\' + FShellCmd + '\Command', True);
shellReg.WriteString('', FShell);
if FQuick then
begin
shellReg.CloseKey;
shellReg.OpenKey(FTypeName+'\QuickView', True);
shellReg.WriteString('', '*');
end;
end;
shellReg.CloseKey;
shellReg.Free;
// Update system to notify of association change
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, PChar(''), PChar(''));
end;
(******************************************************************************)
(* UnAssociate - If an old association was stored for the specified file *)
(* file extension, it is restored. *)
(******************************************************************************)
procedure TMILAssociate.UnAssociate(Extension : String);
var
Ext : String;
WorkStr : String;
begin
shellReg := TRegistry.Create;
shellReg.RootKey := HKEY_CLASSES_ROOT;
Ext := StripPeriod(qualifyExt(Extension));
if shellReg.KeyExists('.' + Ext) then
begin
shellReg.OpenKey('.' + Ext, False);
WorkStr := shellReg.ReadString('');
shellReg.CloseKey;
shellReg.DeleteKey('.' + Ext);
end;
shellReg.CloseKey;
shellReg.Free;
// Update system to notify of association change
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, PChar(''), PChar(''));
end;
(******************************************************************************)
(* Enumerate - Returns a list of extensions currently associated with *)
(* currently identified application. *)
(******************************************************************************)
function TMILAssociate.Enumerate : TStringList;
var
KeyList,
ResultList : TStringList;
iCount,
jCount : Integer;
WorkStr,
WorkStr2 : String;
s :string;
begin
KeyList := TStringList.Create;
ResultList := TStringList.Create;
shellReg := TRegistry.Create;
shellReg.RootKey := HKEY_CLASSES_ROOT;
shellReg.OpenKey('', False);
shellReg.GetKeyNames(KeyList);
for iCount := 0 to KeyList.Count - 1 do
begin
if Copy(KeyList.Strings[iCount], 1, 1) <> '.' then
begin
shellReg.CloseKey;
shellReg.OpenKey(KeyList.Strings[iCount] + '\Shell\Open\Command', False);
WorkStr := LowerCase(shellReg.ReadString(''));
s:=LowerCase(ExtractFileName(FShell));
if Pos(s, WorkStr) > 0 then
begin
for jCount := 0 to KeyList.Count - 1 do
begin
if Copy(KeyList.Strings[jCount], 1, 1) = '.' then
begin
shellReg.CloseKey;
shellReg.OpenKey(KeyList.Strings[jCount], False);
WorkStr2 := shellReg.ReadString('');
if WorkStr2 = KeyList.Strings[iCount] then
ResultList.Add(KeyList.Strings[jCount]);
end;
end;
end;
end;
end;
KeyList.Clear;
KeyList.Free;
shellReg.CloseKey;
shellReg.Free;
Result := ResultList;
end;
procedure Register;
begin
RegisterComponents('Add-On''s', [TMILAssociate]);
end;
end.
|
unit uOperationProgress;
interface
uses
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ComCtrls,
uMemoryEx,
uDBForm;
type
TFormOperationProgress = class(TDBForm)
PrbProgress: TProgressBar;
BtnCancel: TButton;
LbInfo: TLabel;
procedure FormCreate(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
private
{ Private declarations }
FClosed: Boolean;
procedure LoadLanguage;
procedure SetLabel(Text: string);
protected
{ Protected declarations }
procedure CreateParams(var Params: TCreateParams); override;
function GetFormID: string; override;
public
{ Public declarations }
end;
type
TOperationProgress = class(TObject)
private
FForm: TFormOperationProgress;
function GetMax: Integer;
function GetPosition: Integer;
function GetText: string;
procedure SetClosed(const Value: Boolean);
procedure SetMax(const Value: Integer);
procedure SetPosition(const Value: Integer);
procedure SetText(const Value: string);
function GetClosed: Boolean;
public
constructor Create(Owner: TDBForm);
destructor Destroy; override;
procedure Show;
property Max: Integer read GetMax write SetMax;
property Position: Integer read GetPosition write SetPosition;
property Text: string read GetText write SetText;
property Closed: Boolean read GetClosed write SetClosed;
end;
implementation
{$R *.dfm}
{ TFormOperationProgress }
procedure TFormOperationProgress.BtnCancelClick(Sender: TObject);
begin
BtnCancel.Enabled := True;
FClosed := True;
end;
procedure TFormOperationProgress.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.ExStyle := Params.ExStyle and not WS_EX_TOOLWINDOW or WS_EX_APPWINDOW;
end;
procedure TFormOperationProgress.FormCreate(Sender: TObject);
begin
FClosed := False;
LoadLanguage;
end;
function TFormOperationProgress.GetFormID: string;
begin
Result := 'OperationProgress';
end;
procedure TFormOperationProgress.LoadLanguage;
begin
BeginTranslate;
try
Caption := L('Please wait...');
BtnCancel.Caption := L('Cancel');
finally
EndTranslate;
end;
end;
procedure TFormOperationProgress.SetLabel(Text: string);
begin
LbInfo.Caption := Text;
PrbProgress.Top := LbInfo.Top + LbInfo.Height + 5;
BtnCancel.Top := PrbProgress.Top + PrbProgress.Height + 5;
ClientHeight := BtnCancel.Top + BtnCancel.Height + 5;
end;
{ TOperationProgress }
constructor TOperationProgress.Create(Owner: TDBForm);
begin
FForm := TFormOperationProgress.Create(Owner);
end;
destructor TOperationProgress.Destroy;
begin
R(FForm);
inherited;
end;
function TOperationProgress.GetClosed: Boolean;
begin
Result := FForm.FClosed;
end;
function TOperationProgress.GetMax: Integer;
begin
Result := FForm.PrbProgress.Max;
end;
function TOperationProgress.GetPosition: Integer;
begin
Result := FForm.PrbProgress.Position;
end;
function TOperationProgress.GetText: string;
begin
Result := FForm.LbInfo.Caption;
end;
procedure TOperationProgress.SetClosed(const Value: Boolean);
begin
FForm.FClosed := Value;
end;
procedure TOperationProgress.SetMax(const Value: Integer);
begin
FForm.PrbProgress.Max := Value;
end;
procedure TOperationProgress.SetPosition(const Value: Integer);
begin
FForm.PrbProgress.Position := Value;
FForm.Repaint;
Application.ProcessMessages;
end;
procedure TOperationProgress.SetText(const Value: string);
begin
FForm.SetLabel(Value);
end;
procedure TOperationProgress.Show;
begin
FForm.Show;
end;
end.
|
unit Form.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, Vcl.ExtCtrls,
Data.Proxy.Book;
type
TForm1 = class(TForm)
FDConnection1: TFDConnection;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
Button1: TButton;
ListBox1: TListBox;
GroupBox1: TGroupBox;
Splitter1: TSplitter;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ListBox1Click(Sender: TObject);
private
BookProxy: TBookProxy;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
Data.DataProxy;
procedure TForm1.FormCreate(Sender: TObject);
var
ds: TDataSet;
begin
BookProxy := TBookProxy.Create(Self);
FDConnection1.ExecSQL('SELECT ISBN, Title, Authors, Status, ' +
'ReleseDate, Pages, Price, Currency, Imported, Description FROM Books', ds);
BookProxy.ConnectWithDataSet(ds);
BookProxy.Open;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
BookProxy.ForEach(
procedure(dsp: TDataSetProxy)
begin
ListBox1.Items.Add(BookProxy.ISBN.Value + ' ' + BookProxy.ToString);
end);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Button2.Caption := BookProxy.CountNumberOfMoreExpensiveBooks.ToString;
end;
procedure TForm1.ListBox1Click(Sender: TObject);
var
idx: Integer;
line: string;
ISBN: string;
begin
idx := ListBox1.ItemIndex;
if (idx >= 0) then
begin
line := ListBox1.Items[idx];
ISBN := line.Substring(0,14);
BookProxy.LocateISBN(ISBN);
Caption := BookProxy.Title.Value;
end;
end;
end.
|
{$I-,Q-,R-,S-}
{28¦ Diga Cheese Korea 2002
----------------------------------------------------------------------
Había una vez un pedazo grande de queso, vivía en él un ácaro del
queso llamada Amelia Acaro del Queso. Amelia estaba realmente contenta
porque ella estaba rodeada por los más deliciosos quesos que ella pudo
haber comido. Sin embargo, ella sentía que había algo que le faltaba a
su vida.
Una mañana, meintras soñaba con quesos fue interrumpida por un ruido
que jamás había oido. Pero ella inmediatamente se da cuenta que esto
era el sonido de un ácaro de queso macho rullendo en el mismo pedazo
de queso! (determinando el género del ácaro del queso justo por el
sonido de esta rodeadura no es un método fácil, pero todos los ácaros
de queso lo pueden hacer. Esto es porque sus padres lo hacen).
Nada puede detener a Amelia ahora. Ella tenía que conocer lo más
pronto posible al ácaro. Por lo tanto ella tiene que encontrar el
camino más rápido para llegar al otro ácaro. Amelia puede roer
complemante un 1 mm de queso en diez segundos. Para reunirse con el
otro ácaro por el camino directo puede no ser rápido. El queso en que
Amelia vive está lleno de huecos. Estos huecos, los cuales son
burbujas de aire atrapados en el queso son esféricos para la mayor
parte. Pero ocasionalmente estos huecos esféricos se superponen,
creando huecos compuestos de todos los tipos. Pasando a través de un
hueco en el queso Amelia toma un tiempo esencialmente cero, dado que
ella puede volar desde un extremo al otro instántaneamente. Así ella
puede aprovechar viajar a través de huecos para llegar al otro ácaro
rápidamente.
Para este problema, usted escribirá un programa que dado la
localización de ambos ácaros y los huecos en el queso, determinar el
menor tiempo que se toma Amelia para alcanzar al otro ácaro. Para
resolver este problema, usted puede asumir que el queso tiene un largo
infinito. Esto es porque el queso es tan largo como nunca permita que
Amelia abandone el queso al alcanzar el otro ácaro (especialmente
puesto que el ácaro de queso comilón pueda comersela a ella). Usted
también puede asumir que el otro ácaro espera ansiosamente el arribo
de Amelia y no se moverá mientras que Amelia está en el camino.
Entrada
La entrada es mediante el fichero texto ACARO.IN con la descripción
siguiente:
. La primera línea contiene un simple entero N (0 <= N <= 100) , el
número de huecos en el queso. En las siguientes N líneas hay 4
enteros separados por un espacio en blanco cada uno Xi, Yi, Zi y Ri.
Estos describen el centro (Xi, Yi, Zi) y el radio Ri (Ri > 0) de los
huecos. Todos los valores están expresados en milímetros. La
descripción concluye con dos líneas conteniendo 3 enteros cada una.
La primera línea contiene los valores Xa, Ya y Za; la posicióm de
Amelia en el queso, la segunda línea contiene los valores Xb, Yb y
Zb las posiciones del otro ácaro.
Salida
La salida es hacia el fichero texto ACARO.OUT con una sola línea con
un solo valor entero que representa el menor tiempo en segundos que
toma Amelia en llegar al otro ácaro, redondeado al entero cercano.
Ejemplos de Entrada y Salida:
Ejemplo #1 Ejemplo #2
+------------+ +-----------+ +----------+ +-----------+
¦ ACARO.IN ¦ ¦ ACARO.OUT ¦ ¦ ACARO.IN ¦ ¦ ACARO.OUT ¦
+------------¦ +-----------¦ +----------¦ +-----------¦
¦ 1 ¦ ¦ 100 ¦ ¦ 1 ¦ ¦ 20 ¦
¦ 20 20 20 1 ¦ +-----------+ ¦ 5 0 0 4 ¦ +-----------+
¦ 0 0 0 ¦ ¦ 0 0 0 ¦
¦ 0 0 10 ¦ ¦ 10 0 0 ¦
+------------+ +----------+
}
{ Dijkstra }
const
max = 102;
var
fe,fs : text;
n,i,j,x : longint;
k : real;
tab : array[1..max,1..4] of integer;
cost : array[1..max,1..max] of real;
d : array[0..max] of real;
procedure open;
begin
assign(fe,'acaro.in'); reset(fe);
assign(fs,'acaro.out'); rewrite(fs);
readln(fe,n);
for i:=2 to n+1 do
readln(fe,tab[i,1],tab[i,2],tab[i,3],tab[i,4]);
readln(fe,tab[1,1],tab[1,2],tab[1,3]);
n:=n+2;
readln(fe,tab[n,1],tab[n,2],tab[n,3]);
close(fe);
end;
function dist(x,y,z,k,x1,y1,z1,k1 : real) : real;
var
r1,r2,r3,best : real;
begin
r1:=abs(x-x1); r2:=abs(y-y1); r3:=abs(z-z1);
best:=sqrt(sqr(r1)+sqr(r2)+sqr(r3));
best:=best-k-k1;
if best > 0 then dist:=best
else dist:=0;
end;
procedure calc;
begin
for i:=1 to n do
for j:=1 to i-1 do
begin
k:=dist(tab[i,1],tab[i,2],tab[i,3],tab[i,4],tab[j,1],tab[j,2],tab[j,3],tab[j,4]);
cost[i,j]:=k;
cost[j,i]:=k;
end;
end;
procedure dikstra(ini : longint);
var
x : longint;
s : array[1..max] of boolean;
begin
fillchar(s,sizeof(s),false);
d[ini]:=0; s[ini]:=true;
for i:=1 to n-1 do
begin
x:=0;
for j:=1 to n do
begin
if (not s[j]) and (d[j] < d[x]) then
x:=j;
end;
s[x]:=true;
for j:=1 to n do
begin
k:=cost[x,j] + d[x];
if d[j] > k then
d[j]:=k;
end;
end;
end;
procedure work;
begin
calc;
d[0]:=maxlongint;
for i:=1 to n do
d[i]:=cost[1,i];
dikstra(1);
end;
procedure closer;
begin
writeln(fs,d[n]*10:0:0);
close(fs);
end;
begin
open;
work;
closer;
end. |
{ -------------------------------------------------------------------------------
Unit Name: contourtypes
Author: HochwimmerA (aaron@graphic-edge.co.nz)
Purpose: classes to display x,y,z data points in GLSCene via Proxy Objects
History:
------------------------------------------------------------------------------- }
unit cContourTypes;
interface
uses
System.Classes, System.SysUtils, Data.DB,
GLScene, Graphics, GLGeomObjects, GLObjects, GLVectorgeometry,
GLVectorTypes, GLTexture, cColourSpectrum, GLMaterial, GLColor, GLState;
type
TContourPointCollection = class;
TVectorField = class;
TVectorPoint = class(TObject)
private
fArrow: TGLArrowLine;
fBookMark: TBookMark;
fX: double;
fY: double;
fZ: double;
fMagnitude: double;
fParent: TVectorField;
public
constructor Create(aParent: TVectorField);
destructor Destroy; override;
property Arrow: TGLArrowLine read fArrow write fArrow;
property Bookmark: TBookMark read fBookMark write fBookMark;
property Magnitude: double read fMagnitude write fMagnitude;
property X: double read fX write fX;
property Y: double read fY write fY;
property Z: double read fZ write fZ;
end;
TContourPoint = class(TObject)
private
fBookMark: TBookMark;
fParent: TContourPointCollection;
fPoint: TGLProxyObject;
fX: double;
fY: double;
fZ: double;
fValue: double;
fIsNull: boolean;
fPointLabel: string;
public
constructor Create(aParent: TContourPointCollection);
destructor Destroy; override;
procedure DisplayPoint(position: TVector);
property Bookmark: TBookMark read fBookMark write fBookMark;
property Parent: TContourPointCollection read fParent write fParent;
property IsNull: boolean read fIsNull write fIsNull;
property Point: TGLProxyObject read fPoint write fPoint;
property PointLabel: string read fPointLabel write fPointLabel;
property Value: double read fValue write fValue;
property X: double read fX write fX;
property Y: double read fY write fY;
property Z: double read fZ write fZ;
end;
TVectorField = class(TObject)
private
fDummyCube: TGLDummyCube;
fColPalette: TColourSpectrum;
fMaxArrowHeadHeight: single;
fMaxArrowHeadRadius: single;
fMaxArrowLength: single;
fMaxArrowRadius: single;
fMinArrowHeadHeight: single;
fMinArrowHeadRadius: single;
fMinArrowLength: single;
fMinArrowRadius: single;
fScaleX: single;
fScaleY: single;
fScaleZ: single;
fSlices: integer;
fStacks: integer;
fPointList: TStringList;
fZeroMin: boolean;
protected
function GetMaxMag: double;
function GetMinMag: double;
procedure SetScaleX(iScale: single);
procedure SetScaleY(iScale: single);
procedure SetScaleZ(iScale: single);
procedure SetSlices(iSlices: integer);
procedure SetStacks(iStacks: integer);
public
constructor Create(aDummyCube: TGLDummyCube);
destructor Destroy; override;
procedure ClearAll;
procedure CalcBounds(var dleft, dright, dBack, dForward, dBottom,
dtop: double);
procedure Insert(xp, yp, zp, mag, ux, uy, uz: double; sLabel: string;
aBookMark: TBookMark);
procedure RenderField;
property ColPalette: TColourSpectrum read fColPalette write fColPalette;
property DummyCube: TGLDummyCube read fDummyCube write fDummyCube;
property MaxArrowHeadHeight: single read fMaxArrowHeadHeight
write fMaxArrowHeadHeight;
property MaxArrowHeadRadius: single read fMaxArrowHeadRadius
write fMaxArrowHeadRadius;
property MaxArrowLength: single read fMaxArrowLength write fMaxArrowLength;
property MaxArrowRadius: single read fMaxArrowRadius write fMaxArrowRadius;
property MaxMag: double read GetMaxMag;
property MinArrowHeadHeight: single read fMinArrowHeadHeight
write fMinArrowHeadHeight;
property MinArrowHeadRadius: single read fMinArrowHeadRadius
write fMinArrowHeadRadius;
property MinArrowLength: single read fMinArrowLength write fMinArrowLength;
property MinArrowRadius: single read fMinArrowRadius write fMinArrowRadius;
property MinMag: double read GetMinMag;
property PointList: TStringList read fPointList;
property ScaleX: single read fScaleX write SetScaleX;
property ScaleY: single read fScaleY write SetScaleY;
property ScaleZ: single read fScaleZ Write SetScaleZ;
property Slices: integer read fSlices write SetSlices;
property Stacks: integer read fStacks write SetStacks;
property ZeroMin: boolean read fZeroMin write fZeroMin;
end;
TContourPointCollection = class(TObject)
private
fPointList: TStringList;
fColour: TColor;
fShown: boolean;
fPointType: string;
fRadius: double;
fSlices: integer;
fStacks: integer;
fWireFrame: boolean;
fScaleX: single;
fScaleY: single;
fScaleZ: single;
fMaster: TGLSphere;
fDummyCube: TGLDummyCube;
protected
function GetCount: integer;
function GetMinValue: double;
function GetMaxValue: double;
procedure SetRadius(aRadius: double);
procedure SetColour(aColour: TColor);
procedure SetShown(bShown: boolean);
procedure SetSlices(iSlices: integer);
procedure SetStacks(iStacks: integer);
procedure SetWireFrame(bWireFrame: boolean);
procedure SetScaleX(iScale: single);
procedure SetScaleY(iScale: single);
procedure SetScaleZ(iScale: single);
public
constructor Create(aDummyCube: TGLDummyCube; aMaster: TGLSphere);
destructor Destroy; override;
procedure ClearAll;
procedure CalcBounds(var dleft, dright, dBack, dForward, dBottom,
dtop: double);
procedure Insert(dx, dy, dz, val: double; bIsNull: boolean; sLabel: string;
aBookMark: TBookMark);
property PointType: string read fPointType write fPointType;
property Count: integer read GetCount;
property MinValue: double read GetMinValue;
property MaxValue: double read GetMaxValue;
property Shown: boolean read fShown write SetShown;
property Radius: double read fRadius write SetRadius;
property Slices: integer read fSlices write SetSlices;
property Stacks: integer read fStacks write SetStacks;
property WireFrame: boolean read fWireFrame write SetWireFrame;
property Colour: TColor read fColour write SetColour; // windows color
property PointList: TStringList read fPointList write fPointList;
property ScaleX: single read fScaleX write SetScaleX;
property ScaleY: single read fScaleY write SetScaleY;
property ScaleZ: single read fScaleZ Write SetScaleZ;
{ ** these properties are assigned in the Create Method }
property Master: TGLSphere read fMaster write fMaster;
property DummyCube: TGLDummyCube read fDummyCube write fDummyCube;
end;
implementation
uses
cUtilities;
// =============================================================================
// TVECTORPOINT Implementation
// =============================================================================
// ----- TVectorPoint.Create ---------------------------------------------------
constructor TVectorPoint.Create(aParent: TVectorField);
begin
inherited Create;
fParent := aParent;
fArrow := TGLArrowLine(fParent.DummyCube.AddNewChild(TGLArrowLine));
end;
// ----- TVectorPoint.Destroy --------------------------------------------------
destructor TVectorPoint.Destroy;
begin
fArrow.Free;
inherited Destroy;
end;
// =============================================================================
// TCONTOURPOINT Implementation
// =============================================================================
// ----- TContourPoint.Create --------------------------------------------------
constructor TContourPoint.Create(aParent: TContourPointCollection);
begin
inherited Create;
fParent := aParent;
fPoint := TGLProxyObject(Parent.DummyCube.AddNewChild(TGLProxyObject));
end;
// ------ TContourPoint.Destroy ------------------------------------------------
destructor TContourPoint.Destroy;
begin
fPoint.Free;
inherited Destroy;
end;
// ------ TContourPoint.DisplayPoint -------------------------------------------
procedure TContourPoint.DisplayPoint(position: TVector);
begin
Point.Visible := Parent.Shown;
Point.position.AsVector := position;
end;
{ ** TContourPointCollection Implementation ==================================== }
// ------ TContourPointCollection.Create ---------------------------------------
constructor TContourPointCollection.Create(aDummyCube: TGLDummyCube;
aMaster: TGLSphere);
begin
inherited Create;
fDummyCube := aDummyCube;
fMaster := aMaster;
fRadius := 0.05; // metres
fColour := clRed;
fMaster.Visible := false;
fPointList := TStringList.Create;
fWireFrame := false;
fSlices := 6;
fStacks := 6;
fShown := true;
fScaleX := 1.0;
fScaleY := 1.0;
fScaleZ := 1.0;
fPointType := 'Point';
end;
// ------ TContourPointCollection.Destroy --------------------------------------
destructor TContourPointCollection.Destroy;
begin
ClearAll;
PointList.Free;
inherited Destroy;
end;
// ----- TContourPointCollection.GetCount --------------------------------------
function TContourPointCollection.GetCount: integer;
begin
result := PointList.Count;
end;
// ----- TContourPointCollection.GetMinValue -----------------------------------
function TContourPointCollection.GetMinValue: double;
var
i: integer;
dMin: double;
begin
dMin := 1E30;
for i := 0 to PointList.Count - 1 do
begin
if TContourPoint(PointList.Objects[i]).IsNull then
continue;
if TContourPoint(PointList.Objects[i]).Value < dMin then
dMin := TContourPoint(PointList.Objects[i]).Value;
end;
result := dMin;
end;
// ----- TContourPointCollection.GetMaxValue -----------------------------------
function TContourPointCollection.GetMaxValue: double;
var
i: integer;
dMax: double;
begin
dMax := -1E30;
for i := 0 to PointList.Count - 1 do
begin
if TContourPoint(PointList.Objects[i]).IsNull then
continue;
if TContourPoint(PointList.Objects[i]).Value > dMax then
dMax := TContourPoint(PointList.Objects[i]).Value;
end;
result := dMax;
end;
// ----- TContourPointCollection.SetRadius -------------------------------------
procedure TContourPointCollection.SetRadius(aRadius: double);
begin
fRadius := aRadius;
fMaster.Radius := fRadius;
end;
// ------ TContourPointsCollection.SetWireFrame --------------------------------
procedure TContourPointCollection.SetWireFrame(bWireFrame: boolean);
begin
fWireFrame := bWireFrame;
if bWireFrame then
fMaster.Material.PolygonMode := pmLines
else
fMaster.Material.PolygonMode := pmFill;
fMaster.StructureChanged;
end;
// ----- TContourPointCollection.SetScaleX -------------------------------------
procedure TContourPointCollection.SetScaleX(iScale: single);
var
i: integer;
begin
fScaleX := iScale;
for i := 0 to PointList.Count - 1 do
begin
with TContourPoint(PointList.Objects[i]) do
Point.position.X := (iScale * X);
end;
end;
// ----- TContourPointCollection.SetScaleY -------------------------------------
procedure TContourPointCollection.SetScaleY(iScale: single);
var
i: integer;
begin
fScaleY := iScale;
for i := 0 to PointList.Count - 1 do
begin
with TContourPoint(PointList.Objects[i]) do
Point.position.Y := (iScale * Y);
end;
end;
// ----- TContourPointCollection.SetScaleZ -------------------------------------
procedure TContourPointCollection.SetScaleZ(iScale: single);
var
i: integer;
begin
fScaleZ := iScale;
for i := 0 to PointList.Count - 1 do
begin
with TContourPoint(PointList.Objects[i]) do
Point.position.Z := (iScale * Z);
end;
end;
// ------ TContourPointCollection.SetSlices ------------------------------------
procedure TContourPointCollection.SetSlices(iSlices: integer);
begin
fSlices := iSlices;
fMaster.Slices := iSlices;
end;
// ----- TContourPointCollection.SetStacks -------------------------------------
procedure TContourPointCollection.SetStacks(iStacks: integer);
begin
fStacks := iStacks;
fMaster.Stacks := iStacks;
end;
// ----- TContourPointCollection.SetColour -------------------------------------
procedure TContourPointCollection.SetColour(aColour: TColor);
begin
fColour := aColour;
fMaster.Material.FrontProperties.Emission.AsWinColor := aColour;
fMaster.StructureChanged;
end;
// ------ TContourPointCollection.SetShown -------------------------------------
procedure TContourPointCollection.SetShown(bShown: boolean);
var
i: integer;
begin
fShown := bShown;
for i := 0 to PointList.Count - 1 do
begin
with TContourPoint(PointList.Objects[i]) do
Point.Visible := bShown
end;
end;
// ------ TContourPointCollection.ClearAll -------------------------------------
procedure TContourPointCollection.ClearAll;
begin
while PointList.Count > 0 do
begin
PointList.Objects[0].Free;
PointList.Delete(0);
end
end;
// ------ TContourPointCollection.CalcBounds -----------------------------------
procedure TContourPointCollection.CalcBounds(var dleft, dright, dBack, dForward,
dBottom, dtop: double);
var
i: integer;
begin
dleft := 1E30;
dright := -1E30;
dBack := 1E30;
dForward := -1E30;
dtop := -1E30;
dBottom := 1E30;
for i := 0 to PointList.Count - 1 do
begin
with TContourPoint(PointList.Objects[i]) do
begin
if X < dleft then
dleft := X;
if X > dright then
dright := X;
if Y < dBack then
dBack := Y;
if Y > dForward then
dForward := Y;
if Z < dBottom then
dBottom := Z;
if Z > dtop then
dtop := Z;
end;
end;
end;
// ------ TContourPointCollection.Insert ---------------------------------------
procedure TContourPointCollection.Insert(dx, dy, dz, val: double;
bIsNull: boolean; sLabel: string; aBookMark: TBookMark);
var
iIndex, iPos: integer;
sGoodLabel, sName: string;
v: TVector;
begin
{ ** assumes we only add all at once }
iPos := PointList.Count;
{ ** get a safe name for the data point }
sGoodLabel := GetSafeName(sLabel);
sName := PointType + '_' + sGoodLabel + '_' + IntToStr(iPos);
{ ** to ensure no duplicates }
while (PointList.IndexOf(sName) <> -1) do
sName := PointType + '_' + sGoodLabel + '_' + IntToStr(iPos + 1);
PointList.AddObject(sName, TContourPoint.Create(self));
iIndex := PointList.IndexOf(sName);
with TContourPoint(PointList.Objects[iIndex]) do
begin
Point.Name := sName;
Point.MasterObject := Master;
Point.Up := Master.Up;
Point.Direction := Master.Direction;
Point.ProxyOptions := [pooObjects];
Bookmark := aBookMark;
PointLabel := sLabel;
X := dx;
Y := dy;
Z := dz;
Value := val;
IsNull := bIsNull;
SetVector(v, X * fScaleX, Y * fScaleY, Z * fScaleZ);
DisplayPoint(v);
end;
end;
// =============================================================================
// TVECTORFIELD Implementation
// =============================================================================
// ----- TVectorField.GetMaxMag ------------------------------------------------
function TVectorField.GetMaxMag: double;
var
i: integer;
begin
// sweep through and determine magnitudes
for i := 0 to fPointList.Count - 1 do
begin
with TVectorPoint(fPointList.Objects[i]) do
begin
if i = 0 then
result := Magnitude
else
begin
if (result < Magnitude) then
result := Magnitude;
end;
end;
end;
end;
// ----- TVectorField.GetMinMag ------------------------------------------------
function TVectorField.GetMinMag: double;
var
i: integer;
begin
if ZeroMin then
result := 0.0
else
begin
// sweep through and determine magnitudes
for i := 0 to fPointList.Count - 1 do
begin
with TVectorPoint(fPointList.Objects[i]) do
begin
if i = 0 then
result := Magnitude
else
begin
if (result > Magnitude) then
result := Magnitude;
end;
end;
end;
end;
end;
// ----- TVectorField.SetScaleX ------------------------------------------------
procedure TVectorField.SetScaleX(iScale: single);
var
i: integer;
begin
fScaleX := iScale;
// don't scale point but rather the position
for i := 0 to fPointList.Count - 1 do
begin
with TVectorPoint(fPointList.Objects[i]) do
Arrow.position.X := (iScale * fX);
end;
end;
// ----- TVectorField.SetScaleY ------------------------------------------------
procedure TVectorField.SetScaleY(iScale: single);
var
i: integer;
begin
fScaleY := iScale;
// don't scale point but rather the position
for i := 0 to fPointList.Count - 1 do
begin
with TVectorPoint(fPointList.Objects[i]) do
Arrow.position.Y := (iScale * fY);
end;
end;
// ----- TVectorField.SetScaleZ ------------------------------------------------
procedure TVectorField.SetScaleZ(iScale: single);
var
i: integer;
begin
fScaleZ := iScale;
// don't scale point but rather the position
for i := 0 to fPointList.Count - 1 do
begin
with TVectorPoint(fPointList.Objects[i]) do
Arrow.position.Z := (iScale * fZ);
end;
end;
// ----- TVectorField.SetSlices ------------------------------------------------
procedure TVectorField.SetSlices(iSlices: integer);
var
i: integer;
begin
fSlices := iSlices;
for i := 0 to fPointList.Count - 1 do
with TVectorPoint(fPointList.Objects[i]) do
Arrow.Slices := iSlices;
end;
// ----- TVectorField.SetStacks ------------------------------------------------
procedure TVectorField.SetStacks(iStacks: integer);
var
i: integer;
begin
fStacks := iStacks;
for i := 0 to fPointList.Count - 1 do
with TVectorPoint(fPointList.Objects[i]) do
Arrow.Stacks := iStacks;
end;
// ------ TVectorField.Create --------------------------------------------------
constructor TVectorField.Create(aDummyCube: TGLDummyCube);
begin
inherited Create;
fDummyCube := aDummyCube;
fMaxArrowLength := 1.0;
fMinArrowLength := 0.0;
fMaxArrowHeadHeight := 0.5;
fMinArrowHeadHeight := 0.0;
fMaxArrowHeadRadius := 0.2;
fMinArrowHeadRadius := 0.0;
fMaxArrowRadius := 0.1;
fMinArrowRadius := 0.0;
fZeroMin := false;
fScaleX := 1.0;
fScaleY := 1.0;
fScaleZ := 1.0;
fSlices := 4;
fStacks := 1;
fPointList := TStringList.Create;
end;
// ------ TVectorField.Destroy -------------------------------------------------
destructor TVectorField.Destroy;
begin
fPointList.Free;
inherited Destroy;
end;
// ------ TVectorField.ClearAll ------------------------------------------------
procedure TVectorField.ClearAll;
begin
while fPointList.Count > 0 do
begin
fPointList.Objects[0].Free;
fPointList.Delete(0);
end
end;
// ------ TVectorField.CalcBounds -----------------------------------
procedure TVectorField.CalcBounds(var dleft, dright, dBack, dForward, dBottom,
dtop: double);
var
i: integer;
begin
dleft := 1E30;
dright := -1E30;
dBack := 1E30;
dForward := -1E30;
dtop := -1E30;
dBottom := 1E30;
for i := 0 to PointList.Count - 1 do
begin
with TVectorPoint(PointList.Objects[i]) do
begin
if X < dleft then
dleft := X;
if X > dright then
dright := X;
if Y < dBack then
dBack := Y;
if Y > dForward then
dForward := Y;
if Z < dBottom then
dBottom := Z;
if Z > dtop then
dtop := Z;
end;
end;
end;
// ----- TVectorField.Insert ---------------------------------------------------
procedure TVectorField.Insert(xp, yp, zp, mag, ux, uy, uz: double;
sLabel: string; aBookMark: TBookMark);
var
iIndex, iPos: integer;
sGoodLabel, sName: string;
pos, direct: TVector;
begin
iPos := fPointList.Count;
sGoodLabel := GetSafeName(sLabel);
sName := 'vect' + sGoodLabel + '_' + IntToStr(iPos);
{ ** to ensure no duplicates }
while (fPointList.IndexOf(sName) <> -1) do
sName := 'vect' + sGoodLabel + '_' + IntToStr(iPos + 1);
fPointList.AddObject(sName, TVectorPoint.Create(self));
iIndex := fPointList.IndexOf(sName);
with TVectorPoint(fPointList.Objects[iIndex]) do
begin
X := xp;
Y := yp;
Z := zp;
Magnitude := mag;
Arrow.Visible := false;
Arrow.Name := sName;
SetVector(direct, ux, uy, uz);
Arrow.Direction.AsVector := direct;
Bookmark := aBookMark;
SetVector(pos, fScaleX * xp, fScaleY * yp, fScaleZ * zp);
Arrow.position.AsVector := pos;
end;
end;
// ----- TVectorField.RenderField ----------------------------------------------
procedure TVectorField.RenderField;
var
i: integer;
dRatio: double;
col: TColorVector;
begin
// should have an option to set this manually:
ColPalette.MinValue := MinMag;
ColPalette.MaxValue := MaxMag;
for i := 0 to fPointList.Count - 1 do
begin
with TVectorPoint(fPointList.Objects[i]) do
begin
dRatio := (Magnitude - ColPalette.MinValue) /
(ColPalette.MaxValue - ColPalette.MinValue);
case ColPalette.SpectrumMode of
// single colour
0:
col := ColPalette.GetColourVector(Magnitude, true);
// simple minimum/maximum
1:
col := ColPalette.GetColourVector(Magnitude, true);
// rainbow and inverse rainbow spectrum
2, 3:
col := ColPalette.GetColourVector(Magnitude,
(ColPalette.SpectrumMode = 2));
// using a palette
4, 5:
col := ColPalette.GetColourVector(Magnitude,
(ColPalette.SpectrumMode = 4))
end;
// range from Minimum properties to maximum properties
Arrow.Material.FrontProperties.Emission.Color := col;
Arrow.Height := MinArrowLength + dRatio *
(MaxArrowLength - MinArrowLength);
Arrow.TopRadius := MinArrowRadius + dRatio *
(MaxArrowRadius - MinArrowRadius);
Arrow.BottomRadius := Arrow.TopRadius;
Arrow.TopArrowHeadHeight := MinArrowHeadHeight + dRatio *
(MaxArrowHeadHeight - MinArrowHeadHeight);
Arrow.TopArrowHeadRadius := MinArrowHeadRadius + dRatio *
(MaxArrowHeadRadius - MinArrowHeadRadius);
Arrow.Slices := fSlices;
Arrow.Stacks := fStacks;
Arrow.Visible := true;
end;
end;
end;
// =============================================================================
end.
|
{..............................................................................}
{ Title: Special Variant BOM Reports: Agile and Engineering formats }
{ Type: Delphi Script }
{ Used On: Altium Projects (*.PrjPcb) }
{ Filename: AgileBOM.pas }
{ Author: Jeff Condit }
{ Copyright: (c) 2008 by Altium Limited }
{ Description: This script searches the project for assembly variant informa- }
{ tion and formats a report of it. When finished, the report is }
{ saved in the project directory with an *.VarRpt extension and }
{ then displayed. There are 2 passes; one to determine the neces-}
{ sary field widths, and the second to format the report. }
{ Revision: 1.0 10/03/2008 JC Initial coding }
{ 1.1 10/09/2008 JC Minor Adjustments after review: }
{ Default LibRef header changed to COHR P/N }
{ Added BOMTitle and TitleStr for substitution }
{ Auto-compile if flattened doc unavailbale }
{ Stopped long fields from misaligning comp list}
{ Default to DNI parameter if it exists }
{ Add BOMAgileSuppress for null last columns }
{ Add BOMAgileNoQuotes for fields w/o commas }
{..............................................................................}
{..............................................................................}
// GLOBAL VARIABLES SECTION
Var
CurrWorkSpace : IWorkSpace; // An Interface handle to the current workspace
CurrProject : IProject; // An Interface handle to the current Project
ProjectVariant : IProjectVariant; // An Interface handle to the current Variant
ProjectVariantCount : Integer; // Number of Variants
VarDescStr : String; // A string for the Variant Description
FlattenedDoc : IDocument; // An Interface handle to the "flattened" document
CompCount : Integer; // A count of the number of components in document
CurrComponent : IComponent; // An Interface handle to the current Component
LibRefWid : Integer; // Width of Library Reference in CompList Record
DescriptionWid : Integer; // Width of Description in CompList Record
FootprintWid : Integer; // Width of Footprint in CompList Record
PhysicalDesWid : Integer; // Width of Physical Designator in CompList Record
StuffedWid : Integer; // Width of Stuffed flag in CompList Record
LibRefStart : Integer; // Width of Library Reference in CompList Record
DescriptionStart : Integer; // Start of Description in CompList Record
FootprintStart : Integer; // Start of Footprint in CompList Record
PhysicalDesStart : Integer; // Start of Physical Designator in CompList Record
StuffedStart : Integer; // Start of Stuffed flag in CompList Record
LibRefEnd : Integer; // End of Library Reference in CompList Record
DescriptionEnd : Integer; // End of Description in CompList Record
FootprintEnd : Integer; // End of Footprint in CompList Record
PhysicalDesEnd : Integer; // End of Physical Designator in CompList Record
StuffedEnd : Integer; // End of Stuffed flag in CompList Record
StuffedPhysDesColWid : Integer; // Width of Stuffed Designator Column in Report
NoStuffPhysDesColWid : Integer; // Width of Not Stuffed Designator Column in Report
CompList : TStringList; // Component Data List
CompListCount : Integer; // A count of strings in CompList
CompanyNam : String; // A string for the Company Name
AssyNumber : String; // A string for the Assembly Number
RevNumber : String; // A string for the Revision Number
TitleStr : String; // A string for the design's Title
DateStr : TDynamicString; // A string for the date
TimeStr : TDynamicString; // A string for the time
SuppressNulLastCol : Boolean; // Flag to suppress the last column if empty
SuppressQuoteWoCommas : Boolean; // Flag to suppress quoting columns w/o commas
StuffedPhysDesList : Array[1..999] of String; // An Array of Stuffed PhysDes Lines
StuffedPhysDesString : String; // A long string of Stuffed PhysDes Lines
StuffedPhysDesCount : Integer; // The Number of lines needed for Stuffed Designators
NoStuffPhysDesList : Array[1..999] of String; // An Array of Un-Stuffed PhysDes Lines
NoStuffPhysDesString : String; // A long string of Un-Stuffed PhysDes Lines
NoStuffPhysDesCount : Integer; // The Number of lines needed for Un-Stuffed Designators
ParameterName : String; // The name of the component paramater to match teh variant by
VariantName : String; // The name of the variant to use
UseParameters : Boolean; // Use a component parameter to define the variant to use
UseVariants : Boolean; // Use variants to define the variant to use
FullyPopulated : Boolean; // Fully populate the BOM
CreateAgileBOM : Boolean; // Create a BOM in agile format
CreateEngineeringBOM : Boolean; // Create a engineering BOM
AddToProject : Boolean; // True if run from DXP>>Run Script ; False if run from OutJob
OpenOutputs : Boolean; // System parameter supplied by OutJob : open generated files
TargetFileName : String; // System parameter supplied by OutJob : desired output file name, if any
TargetFolder : String; // System parameter supplied by OutJob : desired output folder
TargetPrefix : String; // System parameter supplied by OutJob : desired output file name prefix, if any
// REPORT CONFIGURATION VARIABLES
HeaderStr1 : String; // Header line 1
HeaderStr2 : String; // Header line 2
HeaderStr3 : String; // Header line 3
HeaderStr4 : String; // Header line 4
HeaderStr5 : String; // Header line 5
HeaderStr6 : String; // Header line 6
DetailStr1 : String; // Detail First Line 1
LineFormat : String; // Format of Line
MaxCols : Integer; // Maximum Number of Columns
LastCol : Integer; // Last Column Defined
ColWidth : Array[1..99] of Integer; // Column Widths
ColStart : Array[1..99] of Integer; // Starting Column
ColEnd : Array[1..99] of Integer; // Ending Column
ColType : Array[1..99] of String; // Column Type
{...............................................................................}
{...............................................................................}
Function GetOutputFileNameWithExtension(Ext : String) : String;
Begin
If TargetFolder = '' Then
TargetFolder := CurrProject.DM_GetOutputPath;
If TargetFileName = '' Then
TargetFileName := CurrProject.DM_ProjectFileName;
Result := AddSlash(TargetFolder) + TargetPrefix + ChangeFileExt(TargetFileName, Ext);
End;
{...............................................................................}
{...............................................................................}
procedure GetState_Controls;
Begin
ParameterName := ParametersComboBox.Items[ ParametersComboBox.ItemIndex ];
VariantName := VariantsComboBox .Items[VariantsComboBox.ItemIndex];
UseParameters := UseParametersRadioButton .Checked;
UseVariants := UseVariantsRadioButton .Checked;
FullyPopulated := FullyPopulatedRadioButton .Checked;
CreateAgileBOM := CreateAgileBOMCheckBox .Checked;
CreateEngineeringBOM := CreateEngineeringBOMCheckBox.Checked;
End;
{...............................................................................}
{...............................................................................}
procedure SetState_Controls;
Begin
ParametersComboBox .ItemIndex := ParametersComboBox.Items.IndexOf(ParameterName);
VariantsComboBox .ItemIndex := VariantsComboBox .Items.IndexOf(VariantName);
UseParametersRadioButton .Checked := UseParameters;
UseVariantsRadioButton .Checked := UseVariants;
FullyPopulatedRadioButton .Checked := FullyPopulated;
CreateAgileBOMCheckBox .Checked := CreateAgileBOM;
CreateEngineeringBOMCheckBox.Checked := CreateEngineeringBOM;
End;
{...............................................................................}
{...............................................................................}
{ FUNCTION Stuffed( PhysicalDesignator : String ) determines whether the speci- }
{ fied Physical Designator represents a Stuffed part in the current Variant (or }
{ Parameter equivalent). }
{...............................................................................}
Function Stuffed(
PhysicalDesignator : String
) : Boolean;
Var
ComponentVariation : IComponentVariation; // An Interface handle to a varied component
CompCount : Integer; // The Number of Components in Flattened Document
CompIndex : Integer; // An Index for pulling out components
ParmCount : Integer; // The Number of Parameters in Component
ParmIndex : Integer; // An Index for pulling out Parameters
DNIParmName : String; // The Do Not Install Parameter Name for which we are searching
CurrParm : IParameter; // An interface handle to a Parameter
CompFound : Boolean; // Whether we are done scanning components
ParmFound : Boolean; // Whether we are done scanning components
Begin
// NOTE: Only one of the following three radio buttons will be checked:
// First, see if it is fully populated
If (FullyPopulated = True) Then Result := True;
// Second, see if we are using a component Parameter
If UseParameters Then
Begin
// Determine the Parameter Name for which we are looking
DNIParmName := ParameterName;
// Set the default answer to Not Stuffed if component cannot be found
Result := False;
// Clear the found flags
CompFound := False;
ParmFound := False;
// Determine the number of compoents in the flattened document
CompCount := FlattenedDoc.DM_ComponentCount;
// Begin walking through components to find it so we can look at it's parameter names
For CompIndex := 0 To CompCount - 1 Do
Begin
// Fetch a Component
CurrComponent := FlattenedDoc.DM_Components[ CompIndex ];
// Terminate continued searching after we find the right physical designator
If (CurrComponent.DM_PhysicalDesignator = PhysicalDesignator) Then
Begin
// The right component has been found, so cease searching more components
CompFound := True;
CompIndex := CompCount;
// Set the default answer to Stuffed if the component has been found
Result := True;
// Determine how many parameters it has
ParmCount := CurrComponent.DM_ParameterCount;
// Begin walking through parameters to find the specified one
For ParmIndex := 0 To ParmCount - 1 Do
Begin
// Fetch one of the component's Parameters
CurrParm := CurrComponent.DM_Parameters( ParmIndex );
// Terminate Continued searching after we find the right one
If (CurrParm.DM_Name = DNIParmName) Then
Begin
// The right Parameter has been found, so cease searching any more
ParmFound := True;
ParmIndex := ParmCount;
// Set the default answer to Do Not Stuffed unless certain velues exist
Result := False;
// Check for specific values which will allow this part to be stuffed
If ((CurrParm.DM_Value = '*') Or (CurrParm.DM_Value = ''))
Then Result := True;
End; // If (CurrParm.DM_Name := DNIParmName)
End; // For ParmIndex := 0 To ParmCount - 1 Do
End; // If (CurrComponent.DM_PhysicalDesignator = PhysicalDesignator) else
End; // CompIndex := 0 To CompCount - 1 Do
End; // If (UseParametersRadioButton.Checked = True) Then
// Last, see if we are using a Variant
If UseVariants Then
Begin
// If there is no Project Variant then the part is assumed stuffed
If (ProjectVariant = Nil) Then Result := True
Else
Begin
// Now that we have the valid Project Variant we must look for this component
ComponentVariation := ProjectVariant.DM_FindComponentVariationByDesignator( PhysicalDesignator );
// If no Component Variation for this designator, then component is assumed stuffed
If (ComponentVariation = Nil)
Then Result := True
// Otherwise, it is fitted unless its VariationKind is eVariation_NotFitted
Else Result := ComponentVariation.DM_VariationKind <> eVariation_NotFitted;
End; // If (ProjectVariant = Nil) Else
End; // If UseVariantsRadioButton.Checked = True)
End; // Function Stuffed( PhysicalDesignator : String ) : Boolean;
{...............................................................................}
{...............................................................................}
{ PROCEDURE FetchComponents( Dummy: Integer ) reads the Flattened schematic }
{ sheet created by compiling the project to extract a list of all components and}
{ associated information necessary for the report. This information is sorted, }
{ counted, and stored in a list. }
{...............................................................................}
procedure FetchComponents( Dummy: Integer );
Var
CompIndex : Integer; // An Index for pullin out components
PhysCompCount : Integer; // A count of the number of components in document
PhysComponent : IComponent; // An Interface handle to the current Component
PhysCompIndex : Integer; // An index for pulling out Physical Parts
CurrPart : IPart; // An Interface handle to the current Part of a Component
CurrSortStr : String; // A String to hold the sorting field
CurrPhysDesStr : String; // A String to hold the current Physical Designator
CurrFootprintStr : String; // A String to hold the current Footprint
CurrDescrStr : String; // A String to hold the current Description
CurrLibRefStr : String; // A String to hold the current Library Reference
CurrStuffedStr : String; // A String to hold the Stuffed flag for the currrent component
FormatStr : String; // A String into which one part's data can be formatted
TempStrg : String; // A temporary string for formatting
TempChar : String; // A temporary string for one Char when formatting
SortLetters : String; // A string for letters of the designator prefix
SortNumbers : String; // A string for numbers of the designator
SortRest : String; // A string for the rest of the designator
SortLetrWid : Integer; // Width of the sort letters column
SortNumbWid : Integer; // Width of the sort Numbers column
SortRestWid : Integer; // Width of the sort Rest column
SortWid : Integer; // Width of the entire sort field
SortStart : Integer; // Start of the entire sort field
SortCount : Integer; // Number of characters in the Physical Designator
SortEnd : Integer; // End of the entire sort field
LetrDone : Boolean; // Flag for processing designator prefix letters
NumbDone : Boolean; // Flag for processing designator prefix numbers
RestDone : Boolean; // Flag for processing the rest of the designator characters
SortIndex : Integer; // Temporary Index for chars in the Designator
CompCount : Integer; // The Number of Components Flattened Document
CompListIndex : Integer; // An index for strings in CompList
Begin
// Establish fields in Component List
SortLetrWid := 10;
SortNumbWid := 10;
SortRestWid := 50;
SortWid := SortLetrWid + SortNumbWid + SortRestWid;
LibRefWid := 30;
DescriptionWid := 50;
FootprintWid := 50;
PhysicalDesWid := 30;
StuffedWid := 1;
LibRefStart := 1;
SortStart := LibRefStart + LibRefWid;
DescriptionStart := SortStart + SortWid;
FootprintStart := DescriptionStart + DescriptionWid;
PhysicalDesStart := FootprintStart + FootprintWid;
StuffedStart := PhysicalDesStart + PhysicalDesWid;
LibRefEnd := SortStart - 1;
SortEnd := DescriptionStart - 1;
DescriptionEnd := FootprintStart - 1;
FootprintEnd := PhysicalDesStart - 1;
PhysicalDesEnd := StuffedStart - 1;
StuffedEnd := StuffedStart + StuffedWid - 1;
// Fetch the Flattened schematic sheet document. This is a fictitious document
// generated when the project is compiled containing all components from all
// sheets. This is much more useful for making lists of everything than rummaging
// through all the sheets one at a time. This sheet is not graphical in that
// it cannot be viewed like a schematic, but you can view what's in it by using
// the Navigator panel.
FlattenedDoc := CurrProject.DM_DocumentFlattened;
// If we couldn't get the flattened sheet, then most likely the project has
// not been compiled recently
If (FlattenedDoc = Nil) Then
Begin
// First try compiling the project
AddStringParameter( 'Action', 'Compile' );
AddStringParameter( 'ObjectKind', 'Project' );
RunProcess( 'WorkspaceManager:Compile' );
// Try Again to open the flattened document
FlattenedDoc := CurrProject.DM_DocumentFlattened;
If (FlattenedDoc = Nil) Then
Begin
ShowMessage('NOTICE: Compile the Project before Running this report.');
Close;
Exit;
End; // If (FlattenedDoc = Nil) Then
End; // If (FlattenedDoc = Nil) Then
// Now that we have the flattened document, check how many components are in it
CompCount := FlattenedDoc.DM_ComponentCount;
// Set Up Progress Bar
ProgressBar.Min := 0;
ProgressBar.Max := CompCount - 1;
ProgressBar.Step := 1;
ProgressBar.Position := 0;
ProgressBar.Visible := True;
// Walk through every component one-by-one pulling out needed information and
// writing it into the component string list
For CompIndex := 0 To CompCount - 1 Do
Begin
CurrComponent := FlattenedDoc.DM_Components[ CompIndex ];
// Update Progress Bar
ProgressBar.Position := CompIndex;
// Much information about the component can only be retrieved by examining
// one the its sub-parts (Strange, but true.)
CurrPart := CurrComponent.DM_SubParts[0];
// Create the Sort String
// Initialize the sort strings and flags
SortLetters := '';
SortNumbers := '';
SortRest := '';
LetrDone := False;
NumbDone := False;
RestDone := False;
// Fetch the physical designator string so we can parse it
TempStrg := Trim( CurrPart.DM_PhysicalDesignator );
SortCount := Length( Tempstrg );
// Now iterate through its characters
For SortIndex := 1 To SortCount Do
Begin
// Fetch the next character
TempChar := Copy( TempStrg, SortIndex, 1 );
// If processing prefix letters:
If (LetrDone = False)
Then
Begin
// See if it is a letter and will fit
If ( ( ((TempChar >= 'A') And (TempChar <= 'Z'))
Or ((TempChar >= 'a') And (TempChar <= 'z')) )
And (Length( SortLetters ) < SortLetrWid) )
Then SortLetters := SortLetters + TempChar
Else LetrDone := True;
End; // If (LetrDone = False)
// If processing the prefix numbers:
If ((LetrDone = True) And (NumbDone = False))
Then
Begin
// See if it is a number and will fit
If ( ((TempChar >= '0') And (TempChar <= '9'))
And (Length( SortNumbers ) < SortNumbWid) )
Then SortNumbers := SortNumbers + TempChar
Else NumbDone := True;
End; // If ((LetrDone = True) And (NumbDone = False))
// If processing the rest of the physical designator:
If ((LetrDone = True) And (NumbDone = True) And (RestDone = False))
Then
Begin
// See if there is room for the rest of it
If (Length( SortRest ) < SortRestWid)
Then SortRest := SortRest + TempChar
Else RestDone := True;
End; // If ((LetrDone = True) And (NumbDone = True) And (RestDone = False))
End; // For (SortIndex := 1 To SortWid Do
// Now create the sort formatted string
TempStrg :=
SortLetters
+ StringOfChar( ' ', SortLetrWid - Length( SortLetters ) )
+ StringOfChar( '0', SortNumbWid - Length( SortNumbers ) )
+ SortNumbers
+ SortRest
+ StringOfChar( ' ', SortRestWid - Length( SortRest ) );
// Exactly fill the Sorting field
If ( Length( TempStrg ) > SortWid) // If too long
Then TempStrg := Copy( TempStrg, 1, SortWid );
CurrSortStr := TempStrg + StringOfChar( ' ', SortWid - Length( TempStrg ) ); // Pad if needed
// Exactly fill the Library Reference field
TempStrg := Trim( CurrPart.DM_LibraryReference );
If ( Length( TempStrg ) > LibRefWid) // If too long
Then TempStrg := Copy( TempStrg, 1, LibRefWid );
CurrLibRefStr := TempStrg + StringOfChar( ' ', LibRefWid - Length( TempStrg ) ); // Pad if needed
// Exactly fill the Description field
TempStrg := Trim( CurrPart.DM_Description );
If ( Length( TempStrg ) > DescriptionWid) // If too long
Then TempStrg := Copy( TempStrg, 1, DescriptionWid );
CurrDescrStr := TempStrg + StringOfChar( ' ', DescriptionWid - Length( TempStrg ) ); // Pad if needed
// Exactly fill the Footprint field
TempStrg := Trim( CurrPart.DM_Footprint );
If ( Length( TempStrg ) > FootprintWid) // If too long
Then TempStrg := Copy( TempStrg, 1, FootprintWid );
CurrFootprintStr := TempStrg + StringOfChar( ' ', FootprintWid - Length( TempStrg ) ); // Pad if needed
// Exactly fill the Physical Designator field
TempStrg := Trim( CurrPart.DM_PhysicalDesignator );
If ( Length( TempStrg ) > PhysicalDesWid) // If too long
Then TempStrg := Copy( TempStrg, 1, PhysicalDesWid );
CurrPhysDesStr := TempStrg + StringOfChar( ' ', PhysicalDesWid - Length( TempStrg ) ); // Pad if needed
// Exactly fill the Stuffed flag field
If Stuffed( CurrPart.DM_PhysicalDesignator )
Then CurrStuffedStr := 'Y'
Else CurrStuffedStr := 'N';
// Format the collected data
FormatStr :=
CurrLibRefStr
+ CurrSortStr
+ CurrDescrStr
+ CurrFootprintStr
+ CurrPhysDesStr
+ CurrStuffedStr;
// Add it to the string list
CompList.Add := FormatStr;
End; // For CompIndex := 0 To CompCount - 1 Do
// Sort the string list (ASCII Ordered left to right)
CompList.Sort;
// Record how many records ar in the list for later processing control
CompListCount := CompList.Count;
// Hide Progress Bar
ProgressBar.Visible := False;
End; // procedure FetchComponents( Dummy: Integer );
{...............................................................................}
{...............................................................................}
{ PROCEDURE LoadParameterNames( Dummy: Integer ) reads the Flattened schematic }
{ sheet created by compiling the project to extract a list parameter names and }
{ adds them the the Parameter Drop-Down control for choosing by the user. }
{...............................................................................}
procedure LoadParameterNames( Dummy: Integer );
Var
CompCount : Integer; // The Number of Components in the Flattened Document
CompIndex : Integer; // An Index for pulling out components
ParmCount : Integer; // The Number of Parameters in a Component
ParmIndex : Integer; // An Index for pulling out parameters
CurrParm : IParameter; // An interface handle to the current parameter
NameCount : Integer; // The Number of parameter Names found
NameIndex : Integer; // An Index for pulling out parameter Names
DNIIndex : Integer; // The Index for the parameter named "DNI"
NameList : TStringList; // Exapndable parameter Name list
Begin
// Fetch the Flattened schematic sheet document. This is a fictitious document
// generated when the project is compiled containing all components from all
// sheets. This is much more useful for making lists of everything than rummaging
// through all the sheets one at a time. This sheet is not graphical in that
// it cannot be viewed like a schematic, but you can view what's in it by using
// the Navigator panel.
FlattenedDoc := CurrProject.DM_DocumentFlattened;
// If we couldn't get the flattened sheet, then most likely the project has
// not been compiled recently
If (FlattenedDoc = Nil) Then
Begin
// First try compiling the project
AddStringParameter( 'Action', 'Compile' );
AddStringParameter( 'ObjectKind', 'Project' );
RunProcess( 'WorkspaceManager:Compile' );
// Try Again to open the flattened document
FlattenedDoc := CurrProject.DM_DocumentFlattened;
If (FlattenedDoc = Nil) Then
Begin
ShowMessage('NOTICE: Compile the Project before Running this report.');
Close;
Exit;
End; // If (FlattenedDoc = Nil) Then
End; // If (FlattenedDoc = Nil) Then
// Create an expandable string list to hold parameter Names
NameList := TStringList.Create;
// Let the TStringList automatically sort itself and remove duplicates as it is created
NameList.Sorted := True;
NameList.Duplicates := dupIgnore;
// Now that we have the flattened document, check how many components are in it
CompCount := FlattenedDoc.DM_ComponentCount;
// Walk through every component one-by-one so we can look at it's parameter names
For CompIndex := 0 To CompCount - 1 Do
Begin
// Fetch a Component
CurrComponent := FlattenedDoc.DM_Components[ CompIndex ];
// Determine how many parameters it has
ParmCount := CurrComponent.DM_ParameterCount;
// Walk through every parameter of this component one-by-one
For ParmIndex := 0 To ParmCount - 1 Do
Begin
// Fetch one of the component's Parameters
CurrParm := CurrComponent.DM_Parameters( ParmIndex );
// Add it's name to the string list
NameList.Add := CurrParm.DM_Name;
End; // For ParmIndex := 0 To ParmCount - 1 Do
End; // CompIndex := 0 To CompCount - 1 Do
// Determine how many records are in the parameter list
NameCount := NameList.Count;
// Add all parameter names in this list to the Parameters Combo-Box
// and also default to the parameter named DNI if it exists
DNIIndex := 0;
For NameIndex := 0 To NameCount - 1 Do
Begin
If (NameList.Strings[ NameIndex ] = 'DNI') Then DNIIndex := NameIndex;
ParametersComboBox.Items.Add( NameList.Strings[ NameIndex ] );
End;
// Choose the entry to start with
ParametersComboBox.ItemIndex := DNIIndex;
// Free up the Parameter Name List as we no longer need it
NameList.Free;
End;
{...............................................................................}
{...............................................................................}
{ FUNCTION HasNoCommas( TestStrg : String ) : Boolean returns True if there are }
{ no commas in the string. }
{...............................................................................}
function HasNoCommas( TestStrg : String ) : Boolean;
Var
TempStrg : String; // A temporary string
Begin
TempStrg := StringReplace( TestStrg, ',', '', MkSet( rfReplaceAll, rfIgnoreCase ) );
If (Length( TempStrg ) <> Length( TestStrg ) )
Then Result := False
Else Result := True;
End;
{...............................................................................}
{...............................................................................}
{ PROCEDURE SetupProjectVariant( Dummy: Integer ) finds and sets-up the Project }
{ Variant with a description matching that chosen in the Variants Combo-Box. }
{...............................................................................}
procedure SetupProjectVariant( Dummy: Integer );
Var
ProjVarIndex : Integer; // Index for iterating through variants
TempVariant : IProjectVariant; // A temporary Handle for a ProjectVariant
Begin
// Determine how many ProjectVariants are defined within this focussed Project
ProjectVariantCount := CurrProject.DM_ProjectVariantCount;
ProjectVariant := Nil;
// Find the Project Variant matching the Variants Combo-Box
For ProjVarIndex := 0 To ProjectVariantCount - 1 Do
Begin
// Fetch the currently indexed project Assembly Variant
TempVariant := CurrProject.DM_ProjectVariants[ ProjVarIndex ];
// See if the Description matches that in the Variants Combo-Box
If (VariantName = TempVariant.DM_Description)
Then ProjectVariant := CurrProject.DM_ProjectVariants[ ProjVarIndex ];
End;
End;
{...............................................................................}
{...............................................................................}
{ Function PerformSubstitutions( CurrString : String ) is used to insert vari- }
{ ables such as dat and time into strings at the location of predefined markers.}
{ Markers supported so far are: <DATE>, <TIME>, <COMPANY>, <ASSY>, and <REV>. }
{ Date and time are read from the system when the OK button is clicked. Other }
{ values are determined when the report is configured, usually from project par-}
{ ameters. }
{...............................................................................}
Function PerformSubstitutions( CurrString : String ) : String;
Begin
// Search for and replace all occurrances of special strings regardless of case
CurrString := StringReplace( CurrString, '<DATE>', DateStr, MkSet( rfReplaceAll, rfIgnoreCase ) );
CurrString := StringReplace( CurrString, '<TIME>', TimeStr, MkSet( rfReplaceAll, rfIgnoreCase ) );
CurrString := StringReplace( CurrString, '<COMPANY>', CompanyNam, MkSet( rfReplaceAll, rfIgnoreCase ) );
CurrString := StringReplace( CurrString, '<TITLE>', TitleStr, MkSet( rfReplaceAll, rfIgnoreCase ) );
CurrString := StringReplace( CurrString, '<ASSY>', AssyNumber, MkSet( rfReplaceAll, rfIgnoreCase ) );
CurrString := StringReplace( CurrString, '<REV>', RevNumber, MkSet( rfReplaceAll, rfIgnoreCase ) );
// Return the modified string
Result := CurrString;
End;
{...............................................................................}
{...............................................................................}
{ PROCEDURE procedure ClearPhysDesStrings( Dummy: Integer ) clears the PhysDes }
{ Strings so there are no entries. }
{...............................................................................}
procedure ClearPhysDesStrings( Dummy: Integer );
Begin
StuffedPhysDesString := '';
NoStuffPhysDesString := '';
End; // procedure ClearPhysDesStrings( Dummy: Integer )
{...............................................................................}
{...............................................................................}
{ PROCEDURE procedure AddToStuffedPhysDesString( PhysDes: String ) adds another }
{ Designator into the StuffedPhysDesString for later reporting. }
{...............................................................................}
procedure AddToStuffedPhysDesString( PhysDes: String );
Begin
If (Length( StuffedPhysDesString ) = 0)
Then StuffedPhysDesString := PhysDes
Else StuffedPhysDesString := StuffedPhysDesString + ',' + PhysDes;
End; // procedure AddToStuffedPhysDesString( PhysDes: String );
{...............................................................................}
{...............................................................................}
{ PROCEDURE procedure AddToNoStuffPhysDesString( PhysDes: String ) adds another }
{ Designator into the NoStuffPhysDesString for later reporting. }
{...............................................................................}
procedure AddToNoStuffPhysDesString( PhysDes: String );
Begin
If (Length( NoStuffPhysDesString ) = 0)
Then NoStuffPhysDesString := 'DNI: ' + PhysDes
Else NoStuffPhysDesString := NoStuffPhysDesString + ',' + PhysDes;
End; // procedure AddToNoStuffPhysDesString( PhysDes: String );
{...............................................................................}
{...............................................................................}
{ PROCEDURE ConfigureAgileReport( Dummy: Integer ) parses all headers and con- }
{ figuration strings. From that, it configures all the variables necessary to }
{ generate the Agile report. Control is done through adding Project >> Project }
{ Options >> Parameters. The following are supported: }
{ BOMAssyNum -- Usually required to get the AssyNumber in the Header }
{ BOMAgileHeader1 -- Usually not required }
{ BOMAgileDetail1 -- Usually not required }
{ BOMAgileSuppress -- Usually not required (Suppresses last col if empty) }
{ BOMAgileNoQuotes -- Usually not required (Suppresses quoting empty columns }
{...............................................................................}
procedure ConfigureAgileReport( Dummy: Integer );
Var
ParmCount : Integer; // The number of parameters
ParmIndex : Integer; // An index for the current parameter
CurrParm : IParameter; // The current parameter
Begin
// First, setup the project assembly variant matching the Variants Combo-Box
SetupProjectVariant( 0 );
// Set up the default strings
HeaderStr1 := 'Parent,Child,Qty,Find Num,Ref Des,BoM Notes';
AssyNumber := '<1234567890ABC>';
DetailStr1 := '<ASSY>,D120031,0,0,,Lead-Free Processing Specification';
// Initialize default controls
SuppressNulLastCol := False;
SuppressQuoteWoCommas := False;
// So we can use an alternate method: Scan the project file
ParmCount := CurrProject.DM_ParameterCount;
For ParmIndex := 0 To ParmCount - 1 Do
Begin
CurrParm := CurrProject.DM_Parameters( ParmIndex );
If (CurrParm.DM_Name = 'BOMAssyNum') Then AssyNumber := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMAgileHeader1') Then HeaderStr1 := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMAgileDetail1') Then DetailStr1 := CurrParm.DM_Value;
// Use BOMAgileSuppress to suppress the last column when empty
If (CurrParm.DM_Name = 'BOMAgileSuppress')
Then If (Copy( CurrParm.DM_Value, 1, 1) <> 'N') Then SuppressNulLastCol := True;
// Use BOMAgileNoQuotes to suppress quoting fields w/o commas
If (CurrParm.DM_Name = 'BOMAgileNoQuotes')
Then If (Copy( CurrParm.DM_Value, 1, 1) <> 'N') Then SuppressQuoteWoCommas := True;
End;
// Now substitute variables into the header strings
DetailStr1 := PerformSubstitutions( DetailStr1 );
End; // procedure ConfigureAgileReport( Dummy: Integer );
{...............................................................................}
{...............................................................................}
{ PROCEDURE: CreateAgileReport( Dummy: Integer ) creates, formats, and writes an}
{ Agile formatted BOM out to a file in the project directory, adds it to the }
{ project under Generated >> Text Documents, and opens it up for display. The }
{ file is named the same as the project except with an extension of *.AgileBOM }
{...............................................................................}
procedure CreateAgileReport( Dummy: Integer );
Var
LineIndex : Integer; // An Index for pulling out components
CompListIndex : Integer; // An index for strings in CompList
AgileReport : TStringList; // Expandable String List for Report
AgileReportFileName : String; // String containing the name of the report file
ReportDocument : IServerDocument; // An Interface to the Report Document
FormattedLine : String; // A String for formatting on report line
StuffQty : Integer; // Stuffed Quantity of the current part
CurrStrg : String; // A string for the current component record
PrevStrg : String; // A string for the previous component record
TempStr2 : String; // A temporary string for column formatting
CurrPhysDes : String; // A string for the current Physical Designator
PrevPhysDes : String; // A string for the previous Physical Designator
PhysDesIndex : Integer; // An Index for wrapped PhysDes Arrays
MaxPhysDes : Integer; // The Max Count of Wrapped Designator lines
CurrLibRef : String; // A string for the current Library Reference
PrevLibRef : String; // A string for the current Library Reference
LibRefCount : Integer; // A count of the number of Library References outputted
FindNumScale : Integer; // A scaling factor for counting up
ColIndex : Integer; // An index for the current column
IsStuffed : Boolean; // A flag indicating whether or not a component is stuffed
Begin
// Configure all columns and variables from project parameters or defaults
ConfigureAgileReport( 0 );
// Create a string list into which we can write the report
AgileReport := TStringList.Create;
// Initalize the Library Reference counter for Agile Report
LibRefCount := 0; // First "Find" number
FindNumScale := 10; // Increment between "Find" numbers
// Add the already-formatted header and detail lines into the report (if any)
If (Length( Trim( HeaderStr1 ) ) > 0) Then AgileReport.Add( HeaderStr1 );
If (Length( Trim( DetailStr1 ) ) > 0) Then
Begin
AgileReport.Add( DetailStr1 );
LibRefCount := LibRefCount + 1;
End;
// Clear out the lists of Stuffed and Non-Stuffed Physical Designators
ClearPhysDesStrings( 0 );
// Set Up Progress Bar
ProgressBar.Min := 0;
ProgressBar.Max := CompListCount - 1;
ProgressBar.Step := 1;
ProgressBar.Position := 0;
ProgressBar.Visible := True;
// Format a line for each line in the component list
For CompListIndex := 0 To CompListCount - 1 Do
Begin
// Update Progress Bar
ProgressBar.Position := CompListIndex;
// Save the record, designator, and library reference from the previous pass
PrevStrg := CurrStrg;
PrevLibRef := CurrLibRef;
PrevPhysDes := CurrPhysDes;
// Get the record, designator, and library reference for the current pass
CurrStrg := CompList.Strings[ CompListIndex ];
CurrLibRef := Trim( Copy( CurrStrg, LibRefStart, LibRefWid ) );
CurrPhysDes := Trim( Copy( CurrStrg, PhysicalDesStart, PhysicalDesWid ) );
// First Pass only: Init previous variable to match current variables
If (CompListIndex = 0)
Then
Begin
PrevStrg := CurrStrg;
PrevLibRef := CurrLibRef;
PrevPhysDes := CurrPhysDes;
End; // If (CompListIndex = 0) Then
// If Library Reference is unchanged, we need to consolidate it with previous records
If (PrevLibRef = CurrLibRef)
Then
Begin
// Determine if Current component is stuffed or not
If (Copy( CurrStrg, StuffedStart, StuffedWid ) = 'Y')
Then IsStuffed := True
Else IsStuffed := False;
// If so, Increment the Stuffed Quantity
If IsStuffed Then StuffQty := StuffQty + 1;
// Consolidate Here
If IsStuffed
Then AddToStuffedPhysDesString( CurrPhysDes )
Else AddToNoStuffPhysDesString( CurrPhysDes );
End
Else // Otherwise, we are now on a new part and so need to print the previous record
Begin
// Formatted the line string to be outputSuppressQuoteWoCommas
FormattedLine := '';
// Format output of the assembly number
TempStr2 := AssyNumber;
If ((SuppressQuoteWoCommas = True) And (HasNoCommas( TempStr2 ) = True))
Then FormattedLine := FormattedLine + TempStr2
Else FormattedLine := FormattedLine + '"' + TempStr2 + '"';
// Format output of the library reference
TempStr2 := Trim( Copy( PrevStrg, LibRefStart, LibRefWid ) );
If ((SuppressQuoteWoCommas = True) And (HasNoCommas( TempStr2 ) = True))
Then FormattedLine := FormattedLine + ',' + TempStr2
Else FormattedLine := FormattedLine + ',"' + TempStr2 + '"';
// Format output of the stuffed quantity
FormattedLine := FormattedLine + ',' + IntToStr( StuffQty );
// Format output of the find number
FormattedLine := FormattedLine + ',' + IntToStr( LibRefCount * FindNumScale );
// Format output of the stuffed designators list
TempStr2 := Trim( StuffedPhysDesString );
If ((SuppressQuoteWoCommas = True) And (HasNoCommas( TempStr2 ) = True))
Then FormattedLine := FormattedLine + ',' + TempStr2
Else FormattedLine := FormattedLine + ',"' + TempStr2 + '"';
// Format output of the non-stuffed designators list
TempStr2 := Trim( NoStuffPhysDesString );
If ( (Length( TempStr2 ) > 0) Or (SuppressNulLastCol = False) ) Then
Begin
If ((SuppressQuoteWoCommas = True) And (HasNoCommas( TempStr2 ) = True))
Then FormattedLine := FormattedLine + ',' + TempStr2
Else FormattedLine := FormattedLine + ',"' + TempStr2 + '"';
End;
// Add this formatted line to the report
AgileReport.Add( FormattedLine );
LibRefCount := LibRefCount + 1;
// Clear out the wrapped lists of Stuffed and Non-Stuffed Physical Designators
ClearPhysDesStrings( 0 );
// Having printed the previous group we need to reset the stuffed quantity counter
// Determine if Current component is stuffed or not
If (Copy( CurrStrg, StuffedStart, StuffedWid ) = 'Y')
Then IsStuffed := True
Else IsStuffed := False;
If IsStuffed
Then StuffQty := 1
Else StuffQty := 0;
If IsStuffed
Then AddToStuffedPhysDesString( CurrPhysDes )
Else AddToNoStuffPhysDesString( CurrPhysDes );
End; // If (PrevLibRef = CurrLibRef) Else
End; // For CompListIndex := 0 To CompListCount - 1 Do
// Hide Progress Bar
ProgressBar.Visible := False;
// All components have been reported, so name the Agile BOM Report file
AgileReportFileName := GetOutputFileNameWithExtension('.AgileBOM');
// Save the report to the specified file name and eliminate the string list
AgileReport.SaveToFile( AgileReportFileName );
AgileReport.Free;
If AddToProject Then
// Add the report file to the current project (under Generated >> Text Documents)
CurrProject.DM_AddGeneratedDocument( AgileReportFileName );
If OpenOutputs Then
Begin
// Try to open the report document again using the OpenDocument process of the Client server
ReportDocument := Client.OpenDocument( 'Text', AgileReportFileName );
// If we get it opened up again then show it to the users
If (ReportDocument <> Nil) Then Client.ShowDocument( ReportDocument );
End;
End; // procedure CreateAgileReport( Dummy: Integer );
{...............................................................................}
{...............................................................................}
{ PROCEDURE procedure ClearPhysDesLists( Dummy: Integer ) clears the PhysDes }
{ Lists so there are no entries. }
{...............................................................................}
procedure ClearPhysDesLists( Dummy: Integer );
Begin
StuffedPhysDesCount := 1;
StuffedPhysDesList[ StuffedPhysDesCount ] := '';
NoStuffPhysDesCount := 1;
NoStuffPhysDesList[ NoStuffPhysDesCount ] := '';
End; // procedure ClearPhysDesLists( Dummy: Integer );
{...............................................................................}
{...............................................................................}
{ PROCEDURE procedure AddToStuffedPhysDesList( PhysDes: String ) adds another }
{ Designator into the StuffedPhysDesList for later reporting. }
{...............................................................................}
procedure AddToStuffedPhysDesList( PhysDes: String );
Var
TrialLen : Integer;
Begin
TrialLen :=
Length( StuffedPhysDesList[ StuffedPhysDesCount ] )
+ 1 // for preceeding comma
+ Length( PhysDes );
If (TrialLen <= StuffedPhysDesColWid)
Then // It will fit so put it in. Omit comma at beginning of field
Begin
If (Length( StuffedPhysDesList[ StuffedPhysDesCount ] ) = 0)
Then StuffedPhysDesList[ StuffedPhysDesCount ] :=
StuffedPhysDesList[ StuffedPhysDesCount ] + PhysDes
Else StuffedPhysDesList[ StuffedPhysDesCount ] :=
StuffedPhysDesList[ StuffedPhysDesCount ] + ',' + PhysDes;
End
Else // It won't fit so put it in the next record (sans comma)
Begin
StuffedPhysDesCount := StuffedPhysDesCount + 1;
StuffedPhysDesList[ StuffedPhysDesCount ] := PhysDes;
End;
End; // procedure AddToStuffedPhysDesList( PhysDes: String );
{...............................................................................}
{...............................................................................}
{ PROCEDURE procedure AddToNoStuffPhysDesList( PhysDes: String ) adds another }
{ Designator into the NoStuffPhysDesList for later reporting. }
{...............................................................................}
procedure AddToNoStuffPhysDesList( PhysDes: String );
Var
TrialLen : Integer;
Begin
TrialLen :=
Length( NoStuffPhysDesList[ NoStuffPhysDesCount ] )
+ 1 // for preceeding comma
+ Length( PhysDes );
If (TrialLen <= NoStuffPhysDesColWid)
Then // It will fit so put it in. Omit comma at beginning of field
Begin
If (Length( NoStuffPhysDesList[ NoStuffPhysDesCount ] ) = 0)
Then NoStuffPhysDesList[ NoStuffPhysDesCount ] :=
NoStuffPhysDesList[ NoStuffPhysDesCount ] + PhysDes
Else NoStuffPhysDesList[ NoStuffPhysDesCount ] :=
NoStuffPhysDesList[ NoStuffPhysDesCount ] + ',' + PhysDes;
End
Else // It won't fit so put it in the next record (sans comma)
Begin
NoStuffPhysDesCount := NoStuffPhysDesCount + 1;
NoStuffPhysDesList[ NoStuffPhysDesCount ] := PhysDes;
End;
End; // procedure AddToNoStuffPhysDesList( PhysDes: String );
{...............................................................................}
{...............................................................................}
{ PROCEDURE ConfigureEngineeringReport( Dummy: Integer ) parses all headers and }
{ configurations strings. Form that, it configures all the variables necessary }
{ to generate the engineering report. Control is done through adding Project >>}
{ Project Options >> Parameters. The following are supported: }
{ BOMCompany -- Usually required to get the company name inthe header }
{ BOMAssyNum -- Usually required to get the AssyNumber in the Header }
{ BOMRevision -- Usually required to get the Revision in the Header }
{ BOMTitle -- Usually required to get the design's Title in the Header }
{ BOMEngrgHeader1 -- Usually not required }
{ BOMEngrgHeader2 -- Usually not required }
{ BOMEngrgHeader3 -- Usually not required }
{ BOMEngrgHeader4 -- Usually not required }
{ BOMEngrgHeader5 -- Usually not required }
{ BOMEngrgHeader6 -- Usually not required }
{ BOMEngrgLineFormat -- Usually not required }
{...............................................................................}
procedure ConfigureEngineeringReport( Dummy: Integer );
Var
OptionsStorage : IOptionsStorage;
ParmCount : Integer; // The number of parameters
ParmIndex : Integer; // An index for the current parameter
CurrParm : IParameter; // The current parameter
CharCount : Integer; // The number of chars in the line format string
CharIndex : Integer; // An index for the current char
CurrChar : String; // One character from the line format string
PrevChar : String; // The previous character
ColIndex : Integer; // An index for the current column
Begin
// First, setup the project assembly variant matching the Variants Combo-Box
SetupProjectVariant( 0 );
// Set up the default header and line format strings
HeaderStr1 := '<COMPANY> ENGINEERING BOM FOR PWA: <ASSY>-<REV> TITLE: <TITLE>';
HeaderStr2 := 'PROPRIETARY AND CONFIDENTIAL, <COMPANY>';
HeaderStr3 := 'CREATED: <DATE> <TIME>';
HeaderStr4 := '';
HeaderStr5 := 'FIND COHR P/N DESCRIPTION QUAN REFERENCE DNI REFERENCE FOOTPRINT';
HeaderStr6 := '---- --------------- ---------------------- ---- ------------------- ------------------- ---------------------------------';
LineFormat := 'LLLLBBPPPPPPPPPPPPPPPPBDDDDDDDDDDDDDDDDDDDDDDDDQQQQBBSSSSSSSSSSSSSSSSSSSBBNNNNNNNNNNNNNNNNNNNBBFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
CompanyNam := 'ALTIUM, INC.';
AssyNumber := '<1234567890ABC>';
// So we use an alternate method: Scan the project file
ParmCount := CurrProject.DM_ParameterCount;
For ParmIndex := 0 To ParmCount - 1 Do
Begin
CurrParm := CurrProject.DM_Parameters( ParmIndex );
If (CurrParm.DM_Name = 'BOMCompany') Then CompanyNam := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMAssyNum') Then AssyNumber := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMRevision') Then RevNumber := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMTitle') Then TitleStr := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMEngrgHeader1') Then HeaderStr1 := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMEngrgHeader2') Then HeaderStr2 := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMEngrgHeader3') Then HeaderStr3 := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMEngrgHeader4') Then HeaderStr4 := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMEngrgHeader5') Then HeaderStr5 := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMEngrgHeader6') Then HeaderStr6 := CurrParm.DM_Value;
If (CurrParm.DM_Name = 'BOMLineFormat') Then LineFormat := CurrParm.DM_Value;
End;
// Now substitute variables into the header strings
HeaderStr1 := PerformSubstitutions( HeaderStr1 );
HeaderStr2 := PerformSubstitutions( HeaderStr2 );
HeaderStr3 := PerformSubstitutions( HeaderStr3 );
HeaderStr4 := PerformSubstitutions( HeaderStr4 );
HeaderStr5 := PerformSubstitutions( HeaderStr5 );
HeaderStr6 := PerformSubstitutions( HeaderStr6 );
// Now its time to parse the line format string
// Set up column width defaults for each field
ColIndex := 1;
MaxCols := 99;
ColWidth[ ColIndex ] := 0;
ColType[ ColIndex ] := Copy( LineFormat, 1, 1 );
CharCount := Length( LineFormat );
CurrChar := Copy( LineFormat, CharIndex, 1 );
For CharIndex := 1 To CharCount Do
Begin
PrevChar := CurrChar;
CurrChar := Copy( LineFormat, CharIndex, 1 );
If (ColIndex <= MaxCols) Then
Begin
If (CurrChar = PrevChar) Then
Begin
ColWidth[ ColIndex ] := ColWidth[ ColIndex ] + 1;
// Record the widths of the Stuffed and Non-stuffed Designator report columns
If (ColType[ ColIndex ] = 'S') Then StuffedPhysDesColWid := ColWidth[ ColIndex ];
If (ColType[ ColIndex ] = 'N') Then NoStuffPhysDesColWid := ColWidth[ ColIndex ];
End
Else
Begin
// First, record the widths of the Stuffed and Non-stuffed Designator report columns
If (ColType[ ColIndex ] = 'S') Then StuffedPhysDesColWid := ColWidth[ ColIndex ];
If (ColType[ ColIndex ] = 'N') Then NoStuffPhysDesColWid := ColWidth[ ColIndex ];
// Then switch to the next new column
ColIndex := ColIndex + 1;
ColWidth[ ColIndex ] := 1;
ColType[ ColIndex ] := Copy( LineFormat, CharIndex, 1 );
End;
End;
End;
LastCol := ColIndex;
// Calculate all start and end columns for each field
ColStart[ 1 ] := 1;
ColEnd[ 1 ] := ColStart[ 1 ] + ColWidth[ 1 ];
For ColIndex := 2 To LastCol Do
Begin
ColStart[ ColIndex ] := ColStart[ ColIndex - 1 ] + ColWidth[ ColIndex - 1 ];
ColEnd[ ColIndex ] := ColStart[ ColIndex ] + ColWidth[ ColIndex ];
End;
End; // procedure ConfigureEngineeringReport( Dummy: Integer );
{...............................................................................}
{...............................................................................}
{ PROCEDURE: CreateEngineeringReport( Dummy: Integer ) creates, formats, and }
{ writes the Engineering BOM out to a file in the project directory, adds it to }
{ the project under Generated >> Text Documents, & opens it up for display. The}
{ file is named the same as the project except with an extension of *.EngrBOM }
{...............................................................................}
procedure CreateEngineeringReport( Dummy: Integer );
Var
LineIndex : Integer; // An Index for pulling out components
CompListIndex : Integer; // An index for strings in CompList
EngineeringReport : TStringList; // Expandable String List for Report
EngrgReportFileName : String; // String containing the name of the report file
ReportDocument : IServerDocument; // An Interface to the Report Document
FormattedLine : String; // A String for formatting on report line
StuffQty : Integer; // Stuffed Quantity of the current part
CurrStrg : String; // A string for the current component record
PrevStrg : String; // A string for the previous component record
TempStr2 : String; // A temporary string for column formatting
CurrPhysDes : String; // A string for the current Physical Designator
PrevPhysDes : String; // A string for the previous Physical Designator
PhysDesIndex : Integer; // An Index for wrapped PhysDes Arrays
MaxPhysDes : Integer; // The Max Count of Wrapped Designator lines
CurrLibRef : String; // A string for the current Library Reference
PrevLibRef : String; // A string for the current Library Reference
LibRefCount : Integer; // A count of the number of Library References outputted
FindNumScale : Integer; // A scaling factor for counting up
ColIndex : Integer; // An index for the current column
IsStuffed : Boolean; // A flag indicating whether or not a component is stuffed
Begin
// Configure all columns and variables from project parameters or defaults
ConfigureEngineeringReport( 0 );
// Create a string list into which we can write the report
EngineeringReport := TStringList.Create;
// Add the already-formatted header lines into the report
EngineeringReport.Add( HeaderStr1 );
EngineeringReport.Add( HeaderStr2 );
EngineeringReport.Add( HeaderStr3 );
EngineeringReport.Add( HeaderStr4 );
// If the last header line or pair of header lines are blank, they will be omitted
If ((Length( Trim( HeaderStr6 ) ) > 0) Or (Length( Trim( HeaderStr6 ) ) > 0))
Then EngineeringReport.Add( HeaderStr5 );
If (Length( Trim( HeaderStr6 ) ) > 0)
Then EngineeringReport.Add( HeaderStr6 );
// Initalize the Library Reference counter for Engineering Report
LibRefCount := 1;
FindNumScale := 1;
// Clear out the wrapped lists of Stuffed and Non-Stuffed Physical Designators
ClearPhysDesLists( 0 );
// Set Up Progress Bar
ProgressBar.Min := 0;
ProgressBar.Max := CompListCount - 1;
ProgressBar.Step := 1;
ProgressBar.Position := 0;
ProgressBar.Visible := True;
// Format a line for each line in the component list
For CompListIndex := 0 To CompListCount - 1 Do
Begin
// Update Progress Bar
ProgressBar.Position := CompListIndex;
// Save the record, designator, and library reference from the previous pass
PrevStrg := CurrStrg;
PrevLibRef := CurrLibRef;
PrevPhysDes := CurrPhysDes;
// Get the record, designator, and library reference for the current pass
CurrStrg := CompList.Strings[ CompListIndex ];
CurrLibRef := Trim( Copy( CurrStrg, LibRefStart, LibRefWid ) );
CurrPhysDes := Trim( Copy( CurrStrg, PhysicalDesStart, PhysicalDesWid ) );
// First Pass only: Init previous variable to match current variables
If (CompListIndex = 0)
Then
Begin
PrevStrg := CurrStrg;
PrevLibRef := CurrLibRef;
PrevPhysDes := CurrPhysDes;
End; // If (CompListIndex = 0) Then
// If the library reference is the same, we need to consolidate it with
// previous records
If (PrevLibRef = CurrLibRef)
Then
Begin
// Determine if Current component is stuffed or not
If (Copy( CurrStrg, StuffedStart, StuffedWid ) = 'Y')
Then IsStuffed := True
Else IsStuffed := False;
// If so, Increment the Stuffed Quantity
If IsStuffed Then StuffQty := StuffQty + 1;
// Consolidate Here
If IsStuffed
Then AddToStuffedPhysDesList( CurrPhysDes )
Else AddToNoStuffPhysDesList( CurrPhysDes );
End
Else // Otherwise, we need to print the previous record
Begin
// Clear the current formatted line string
FormattedLine := '';
// Append each column into it per the formatting definitions
For ColIndex := 1 To LastCol Do
Begin
// Handle blank columns (B)
If ColType[ ColIndex ] = 'B' Then
Begin
TempStr2 := StringOfChar( ' ', ColWidth[ ColIndex ] );
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'B' Then
// Handle Line number columns (L)
If ColType[ ColIndex ] = 'L' Then
Begin
TempStr2 := IntToStr( LibRefCount * FindNumScale );
TempStr2 := StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) ) + TempStr2;
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'L' Then
// Handle Part number (LibraryRef) columns (P)
If ColType[ ColIndex ] = 'P' Then
Begin
If (ColWidth[ ColIndex ] < LibRefWid)
Then TempStr2 := Copy( PrevStrg, LibRefStart, ColWidth[ ColIndex ] )
Else TempStr2 := Copy( PrevStrg, LibRefStart, LibRefWid );
TempStr2 := Tempstr2 + StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) );
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'P' Then
// Handle Description columns (D)
If ColType[ ColIndex ] = 'D' Then
Begin
If (ColWidth[ ColIndex ] < DescriptionWid)
Then TempStr2 := Copy( PrevStrg, DescriptionStart, ColWidth[ ColIndex ] )
Else TempStr2 := Copy( PrevStrg, DescriptionStart, DescriptionWid );
TempStr2 := Tempstr2 + StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) );
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'D' Then
// Handle stuffed Quantity columns (Q)
If ColType[ ColIndex ] = 'Q' Then
Begin
TempStr2 := IntToStr( StuffQty );
TempStr2 := StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) ) + TempStr2;
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'Q' Then
// Handle Stuffed designator list columns (S)
If ColType[ ColIndex ] = 'S' Then
Begin
TempStr2 := StuffedPhysDesList[ 1 ];
TempStr2 := Tempstr2 + StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) );
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'S' Then
// Handle Non-stuffed designator list columns (N)
If ColType[ ColIndex ] = 'N' Then
Begin
TempStr2 := NoStuffPhysDesList[ 1 ];
TempStr2 := Tempstr2 + StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) );
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'N' Then
// Handle Footprint columns (F)
If ColType[ ColIndex ] = 'F' Then
Begin
If (ColWidth[ ColIndex ] < FootprintWid)
Then TempStr2 := Copy( PrevStrg, FootprintStart, ColWidth[ ColIndex ] )
Else TempStr2 := Copy( PrevStrg, FootprintStart, FootprintWid );
TempStr2 := Tempstr2 + StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) );
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'F' Then
End; // For ColIndex := 1 To LastCol Do
// Add this formatted line to the report
EngineeringReport.Add( FormattedLine );
LibRefCount := LibRefCount + 1;
// Output wrapped followup lines as follows:
// Determine the last designator records we need to access from the arrays
If (StuffedPhysDesCount > NoStuffPhysDesCount)
Then MaxPhysDes := StuffedPhysDesCount
Else MaxPhysDes := NoStuffPhysDesCount;
// The first rows were already used in the formatted line
// Now we output the rest of the lines with these two columns only
For PhysDesIndex := 2 To MaxPhysDes Do
Begin
// Clear the current formatted line string
FormattedLine := '';
// Append each column into it per the formatting definitions
For ColIndex := 1 To LastCol Do
Begin
// Handle Stuffed designator list columns (S)
If ColType[ ColIndex ] = 'S' Then
Begin
If (PhysDesIndex <= StuffedPhysDesCount)
Then TempStr2 := StuffedPhysDesList[ PhysDesIndex ]
Else TempStr2 := ' ';
TempStr2 := Tempstr2 + StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) );
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'S' Then
// Handle Non-stuffed designator list columns (N)
If ColType[ ColIndex ] = 'N' Then
Begin
If (PhysDesIndex <= NoStuffPhysDesCount)
Then TempStr2 := NoStuffPhysDesList[ PhysDesIndex ]
Else TempStr2 := ' ';
TempStr2 := Tempstr2 + StringOfChar( ' ', ColWidth[ ColIndex ] - Length( TempStr2 ) );
FormattedLine := FormattedLine + TempStr2;
End; // If ColType[ ColIndex ] = 'N' Then
// Handle everything else with blanks
If ((ColType[ ColIndex ] <> 'S') And (ColType[ ColIndex ] <> 'N')) Then
Begin
TempStr2 := StringOfChar( ' ', ColWidth[ ColIndex ] );
FormattedLine := FormattedLine + TempStr2;
End; // If ((ColType[ ColIndex ] <> 'S') And (ColType[ ColIndex ] <> 'N')) Then
End; // For ColIndex := 1 To LastCol Do
// Add this extra formatted line to the report
EngineeringReport.Add( FormattedLine );
End; // For ( PhysDesIndex := 2 To MaxPhysDes Do
// Clear out the wrapped lists of Stuffed and Non-Stuffed Physical Designators
ClearPhysDesLists( 0 );
// Having printed the previous group we need to reset the stuffed quantity counter
// Determine if Current component is stuffed or not
If (Copy( CurrStrg, StuffedStart, StuffedWid ) = 'Y')
Then IsStuffed := True
Else IsStuffed := False;
If IsStuffed
Then StuffQty := 1
Else StuffQty := 0;
If IsStuffed
Then AddToStuffedPhysDesList( CurrPhysDes )
Else AddToNoStuffPhysDesList( CurrPhysDes );
End; // If (PrevLibRef = CurrLibRef) Else
End; // For CompListIndex := 0 To CompListCount - 1 Do
// Hide Progress Bar
ProgressBar.Visible := False;
// All components have been reported, so name the Engineering BOM Report file
EngrgReportFileName := GetOutputFileNameWithExtension('.EngrBOM');
// Save the report to the specified file name and eliminate the string list
EngineeringReport.SaveToFile( EngrgReportFileName );
EngineeringReport.Free;
If AddToProject Then
// Add the report file to the current project (under Generated >> Text Documents)
CurrProject.DM_AddGeneratedDocument( EngrgReportFileName );
If OpenOutputs Then
Begin
// Try to open the report document again using the OpenDocument process of the Client server
ReportDocument := Client.OpenDocument( 'Text', EngrgReportFileName );
// If we get it opened up again then show it to the users
If (ReportDocument <> Nil) Then Client.ShowDocument( ReportDocument );
End;
End; // procedure CreateEngineeringReport( Dummy: Integer );
{...............................................................................}
{...............................................................................}
{ PROCEDURE: ReWriteActionLabel( Dummy: Integer ) examines the states of the }
{ various controls on the Form and from this information constructs a string }
{ describing what would be done if the OK button is clicked. This string is }
{ displayed on the Form in the Action Label just above the Cancel & OK buttons. }
{...............................................................................}
procedure ReWriteActionLabel( Dummy: Integer );
Var
// Define a set of strings for defining pieces of a sentence
StringA : String;
StringB : String;
StringC : String;
StringD : String;
StringE : String;
StringF : String;
StringG : String;
Begin
GetState_Controls;
// They are all initialized to a single space
StringA := ' ';
StringB := ' ';
StringC := ' ';
StringD := ' ';
StringE := ' ';
StringF := ' ';
StringG := ' ';
// Strings A & B say which BOM(s) will be run based on the two BOM Creation check-boxes
// If both are unchecked, no BOMs will be created
If ((CreateAgileBOM = False) And (CreateEngineeringBOM = False))
Then
Begin
// If both are unchecked, no BOMs will be created
StringA := 'No ';
StringB := 's';
End;
// If only the CreateAgileBOM check-box is checked, only the Agile BOM will be created
If ((CreateAgileBOM = True ) And (CreateEngineeringBOM = False))
Then
Begin
StringA := 'only Agile ';
StringB := '';
End;
// If only the CreateEngineeringBOM check-box is checked, only the Engineering BOM will be created
If ((CreateAgileBOM = False) And (CreateEngineeringBOM = True ))
Then
Begin
StringA := 'only Engineering ';
StringB := '';
End;
// If both are checked, both the Agile and Engineering BOMs will be created
If ((CreateAgileBOM = True ) And (CreateEngineeringBOM = True ))
Then
Begin
StringA := 'both Agile and Engineering ';
StringB := 's';
End;
// The rest of the strings say which Parameter of Variant will define the Variant reported
// If the UseParameter Radio-Button is selected the Variant reported will be
// defined by the Parameter selected in the Parameters Combo-Box
If UseParameters
Then
Begin
StringC := 'Variant';
StringD := ' using ';
StringE := ' Parameter: ';
StringF := ParameterName;
StringG := '.';
End;
// If the UseVariants Radio-Button is selected the Variant reported will be
// defined by the Variant selected in the Variants Combo-Box
If UseVariants
Then
Begin
StringC := 'Variant';
StringD := ' using';
StringE := ' Variant: ';
StringF := VariantName;
StringG := '.';
End;
// If the FullyPopulated Radio-Button is selected, no Variant will be used
// and the fully populated board will be reported
If FullyPopulated
Then
Begin
StringC := 'Fully Populated';
StringD := '.';
StringE := ' ';
StringF := ' ';
End;
// Finally, all the strings are concatenated to produce the Action Label
// displayed just above the OK and Cancel buttons
ActionLabel.Caption := 'Create ' + StringA + StringC + ' BOM' + StringB + StringD + StringE + StringF + StringG;
End;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: InitializeProject( Dummy: Integer ) several things. First, it }
{ makes sure the Workspace and Focussed Project can be opened and if not exits }
{ the script. Second, it loads the variant names for this project into the Var-}
{ iants Combo-Box and select the first one. And third, it re-writes the Action }
{ label on the Form describing what action will be done when the OK button is }
{ clicked. }
{...............................................................................}
Procedure InitializeProject( Dummy: Integer );
Var
ProjVarIndex : Integer; // Index for iterating through variants
Begin
// Make sure the current Workspace opens or else quit this script
CurrWorkSpace := GetWorkSpace;
If (CurrWorkSpace = Nil) Then Exit;
// Make sure the currently focussed Project in this Workspace opens or else
// quit this script
CurrProject := CurrWorkspace.DM_FocusedProject;
If CurrProject = Nil Then Exit;
// Determine how many Assembly Variants are defined within this focussed Project
ProjectVariantCount := CurrProject.DM_ProjectVariantCount;
// Process each Project Assembly Variant sequentially
For ProjVarIndex := 0 To ProjectVariantCount - 1 Do
Begin
// Fetch the currently indexed project Assembly Variant
ProjectVariant := CurrProject.DM_ProjectVariants[ ProjVarIndex ];
VariantsComboBox.Items.Add( ProjectVariant.DM_Description );
End;
// Choose first variant to start with
VariantsComboBox.ItemIndex := 0;
ProjectVariant := CurrProject.DM_ProjectVariants[ 0 ];
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
End;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: Initialize does things necessary for the Form to operate properly, }
{ such as making sure the Workspace and Project open, loading the Combo-Boxes }
{ with the proper choices, and initializing other settings. }
{...............................................................................}
procedure Initialize;
begin
// Open Workspace, Project, Get Variants, etc.
InitializeProject( 0 );
// Add Parameters to Parameters ComboBox
LoadParameterNames( 0 );
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
end;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: TAgileBOMForm.UseParametersRadioButtonClick(Sender: TObject) is an }
{ event handler for the UseParameters Radio-Button. When the user clicks on it }
{ this procedure is called. }
{...............................................................................}
procedure TAgileBOMForm.UseParametersRadioButtonClick(Sender: TObject);
begin
// When clicked, this radio button become checked and all the others unchecked
UseParametersRadioButton.Checked := True;
UseVariantsRadioButton.Checked := False;
FullyPopulatedRadioButton.Checked := False;
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
end;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: TAgileBOMForm.ParametersComboBoxChange(Sender: TObject) is an event}
{ handler for the Parameters Combo-Box. When the user clicks on it, this pro- }
{ cedure is called. }
{...............................................................................}
procedure TAgileBOMForm.ParametersComboBoxChange(Sender: TObject);
begin
// When clicked, the Parameters Combo-Box is automatically activated for selecting.
// However, we should also check the associated UseParameters radio button
// and uncheck all the others
UseParametersRadioButton.Checked := True;
UseVariantsRadioButton.Checked := False;
FullyPopulatedRadioButton.Checked := False;
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
end;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: TAgileBOMForm.UseVariantsRadioButtonClick(Sender: TObject) is an }
{ event handler for the UseVariants Radio-Button. When the user clicks on it }
{ this procedure is called. }
{...............................................................................}
procedure TAgileBOMForm.UseVariantsRadioButtonClick(Sender: TObject);
begin
// When clicked, this radio button become checked and all the others unchecked
UseVariantsRadioButton.Checked := True;
UseParametersRadioButton.Checked := False;
FullyPopulatedRadioButton.Checked := False;
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
end;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: TAgileBOMForm.VariantsComboBoxChange(Sender: TObject) is an event }
{ handler for the Variants Combo-Box. When the user clicks on it, this proced- }
{ ure is called. }
{...............................................................................}
procedure TAgileBOMForm.VariantsComboBoxChange(Sender: TObject);
begin
// When clicked, the Variants Combo-Box is automatically activated for selecting.
// However, we should also check the associated UseVariants radio button
// and uncheck all the others
UseVariantsRadioButton.Checked := True;
UseParametersRadioButton.Checked := False;
FullyPopulatedRadioButton.Checked := False;
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
end;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: TAgileBOMForm.FullyPopulatedRadioButtonClick(Sender: TObject) is an}
{ event handler for the FullyPopulated Radio-Button. When the user clicks on it}
{ this procedure is called. }
{...............................................................................}
procedure TAgileBOMForm.FullyPopulatedRadioButtonClick(Sender: TObject);
begin
// When clicked, this radio button become checked and all the others unchecked
FullyPopulatedRadioButton.Checked := True;
UseParametersRadioButton.Checked := False;
UseVariantsRadioButton.Checked := False;
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
end;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: TAgileBOMForm.CreateAgileBOMCheckBoxClick(Sender: TObject) is an }
{ event handler for the CreateAgileBOM Check-Box. When the user clicks on it }
{ this procedure is called. }
{...............................................................................}
procedure TAgileBOMForm.CreateAgileBOMCheckBoxClick(Sender: TObject);
begin
// This procedure toggles CreateAgileBOMCheckBox.Checked automatically
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
end;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: TAgileBOMForm.CreateEngineeringBOMCheckBoxClick(Sender: TObject) is}
{ an event handler for the CreateEngineeringBOM Check-Box. When the user clicks}
{ on it this procedure is called. }
{...............................................................................}
procedure TAgileBOMForm.CreateEngineeringBOMCheckBoxClick(Sender: TObject);
begin
// This procedure toggles CreateEngineeringBOMCheckBox.Checked automatically
// Based on current settings on the form, re-write the description of what
// action will be done when the OK button is pressed
ReWriteActionLabel( 0 );
end;
{...............................................................................}
{...............................................................................}
Procedure Generate_BOM;
Begin
// Fetch the current Date and Time for later use in the report
DateStr := GetCurrentDateString();
TimeStr := GetCurrentTimeString();
// Create a list within which components can be gathered and sorted
CompList := TStringList.Create;
// Locate components and write salient information on each into the list
FetchComponents( 0 );
// If the Engineering BOM is checked for creation, create it
If CreateEngineeringBOM
Then CreateEngineeringReport( 0 );
// If the Agile BOM is checked for creation, create it
If CreateAgileBOM
Then CreateAgileReport( 0 );
// Now that we are done writing reports, Free up the list we created earlier
CompList.Free;
End;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: SetState_FromParameters decodes a parameter string and sets all }
{ settings accordingly. }
{...............................................................................}
Procedure SetState_FromParameters(AParametersList : String);
Var
S : String;
Begin
InitializeProject( 0 );
ParameterName := '';
VariantName := '';
UseParameters := False;
UseVariants := False;
FullyPopulated := False;
CreateAgileBOM := False;
CreateEngineeringBOM := False;
OpenOutputs := True;
AddToProject := True;
TargetFolder := '';
TargetFileName := '';
TargetPrefix := '';
If GetState_Parameter(AParametersList, 'ParameterName' , S) Then ParameterName := S;
If GetState_Parameter(AParametersList, 'VariantName' , S) Then VariantName := S;
If GetState_Parameter(AParametersList, 'UseParameters' , S) Then UseParameters := StringsEqual(S, 'True');
If GetState_Parameter(AParametersList, 'UseVariants' , S) Then UseVariants := StringsEqual(S, 'True');
If GetState_Parameter(AParametersList, 'FullyPopulated' , S) Then FullyPopulated := StringsEqual(S, 'True');
If GetState_Parameter(AParametersList, 'CreateAgileBOM' , S) Then CreateAgileBOM := StringsEqual(S, 'True');
If GetState_Parameter(AParametersList, 'CreateEngineeringBOM', S) Then CreateEngineeringBOM := StringsEqual(S, 'True');
If GetState_Parameter(AParametersList, 'OpenOutputs' , S) Then OpenOutputs := StringsEqual(S, 'True');
If GetState_Parameter(AParametersList, 'AddToProject' , S) Then AddToProject := StringsEqual(S, 'True');
If GetState_Parameter(AParametersList, 'TargetFileName' , S) Then TargetFileName := S;
If GetState_Parameter(AParametersList, 'TargetFolder' , S) Then TargetFolder := S;
If GetState_Parameter(AParametersList, 'TargetPrefix' , S) Then TargetPrefix := S;
SetState_Controls;
End;
{...............................................................................}
{...............................................................................}
{ FUNCTION: GetState_FromParameters encodes all settings as a parameter string. }
{...............................................................................}
Function GetState_FromParameters : String;
Begin
GetState_Controls;
Result := '';
Result := Result + 'ParameterName=' + ParameterName;
Result := Result + '|' + 'VariantName=' + VariantName;
Result := Result + '|' + 'UseParameters=' + BoolToStr(UseParameters , True);
Result := Result + '|' + 'UseVariants=' + BoolToStr(UseVariants , True);
Result := Result + '|' + 'FullyPopulated=' + BoolToStr(FullyPopulated , True);
Result := Result + '|' + 'CreateAgileBOM=' + BoolToStr(CreateAgileBOM , True);
Result := Result + '|' + 'CreateEngineeringBOM=' + BoolToStr(CreateEngineeringBOM, True);
End;
{...............................................................................}
{...............................................................................}
{ MAIN ENTRY POINT: This procedure is the main entry point for this script. It }
{ has no parameters and hence is listed when you select a script to be run. }
{ It shows the form with default settings, and, if the user clicks OK, }
{ generates an output file with the desired settings. }
{...............................................................................}
Procedure AgileBOM;
Begin
Initialize;
OpenOutputs := True;
AddToProject := True;
If AgileBOMForm.ShowModal = mrOK Then
Begin
GetState_Controls;
Generate_BOM;
Close;
End;
End;
{...............................................................................}
{...............................................................................}
{ PROCEDURE: Generate is the entry point when running a Script Output from an }
{ OutJob document. It generates an output file without showing the form. The }
{ settings to use are supplied from OutJob as a parameter string. }
{...............................................................................}
Procedure Generate(Parameters : String);
Begin
SetState_FromParameters(Parameters);
Generate_BOM;
End;
{...............................................................................}
{...............................................................................}
{ FUNCTION: Configure is the entry point for the right-click Configure command }
{ in an OutJob document. It shows the form with the supplied settings (encoded }
{ as a parameter string), and, if the user clicks OK, it returns the new }
{ settings. These new settings will be saved by OutJob, and applied in }
{ subsequent invocations of the Generate procedure. }
{...............................................................................}
Function Configure(Parameters : String) : String;
Begin
Result := '';
Initialize;
SetState_FromParameters(Parameters);
If AgileBOMForm.ShowModal = mrOK Then
Begin
Result := GetState_FromParameters;
Close;
End;
End;
{...............................................................................}
{...............................................................................}
{ FUNCTION: PredictOutputFileNames is an entry point called from Boards view. }
{ It should returns the full path names of all files that will be generated by }
{ the Generate procedure, without actually generating them. The file names }
{ should be returned via the Result string, separated by '|' characters. }
{...............................................................................}
Function PredictOutputFileNames(Parameters : String) : String;
Var
OutputFileNames : TStringList;
Begin
SetState_FromParameters(Parameters);
OutputFileNames := TStringList.Create;
OutputFileNames.Delimiter := '|';
OutputFileNames.StrictDelimiter := True;
If CreateEngineeringBOM Then
OutputFileNames.Add(GetOutputFileNameWithExtension('.EngrBOM'));
If CreateAgileBOM Then
OutputFileNames.Add(GetOutputFileNameWithExtension('.AgileBOM'));
Result := OutputFileNames.DelimitedText;
OutputFileNames.Free;
End;
{...............................................................................}
|
unit Form_Main;
// Description: HMAC Test Vector Suite
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// This test application verifies the HMAC implementation by checking it's
// output against known test vectors stored separatly in a file
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
HashAlgUnified_U;
type
TTestDetails = record
FieldsPopulated: integer;
Hash: string;
TestCaseNo: integer;
Key: string;
KeyLength: integer;
Data: string;
DataLength: integer;
Digest: string;
end;
TfrmMain = class(TForm)
pbTestHashes: TButton;
mmoReport: TMemo;
edFilename: TEdit;
Label1: TLabel;
pbBrowse: TButton;
OpenDialog1: TOpenDialog;
pbClose: TButton;
procedure pbTestHashesClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure pbBrowseClick(Sender: TObject);
procedure FormResize(Sender: TObject);
private
HashObj: THashAlgUnified;
function ExecuteTest(Test: TTestDetails; var generatedHMAC: string; var failureReason: string): boolean;
function ConvertToBinary(var data: string): boolean;
public
function SelfTest(filename: string): boolean;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
uses
SDUGeneral,
HashValue_U,
HMAC;
const
FIELD_POPULATED_HASH = 1;
FIELD_POPULATED_TESTCASENO = 2;
FIELD_POPULATED_KEY = 4;
FIELD_POPULATED_KEYLEN = 8;
FIELD_POPULATED_DATA = 16;
FIELD_POPULATED_DATALEN = 32;
FIELD_POPULATED_DIGEST = 64;
FIELDS_POPULATED_NONE = 0;
FIELDS_POPULATED_ALL = FIELD_POPULATED_HASH +
FIELD_POPULATED_TESTCASENO +
FIELD_POPULATED_KEY +
FIELD_POPULATED_KEYLEN +
FIELD_POPULATED_DATA +
FIELD_POPULATED_DATALEN +
FIELD_POPULATED_DIGEST;
procedure TfrmMain.pbTestHashesClick(Sender: TObject);
begin
SelfTest(edFilename.text);
end;
function TfrmMain.SelfTest(filename: string): boolean;
const
DETAIL_HASH = 'hash';
DETAIL_TEST_CASE_NO = 'test_case';
DETAIL_KEY = 'key';
DETAIL_KEY_LEN = 'key_len';
DETAIL_DATA = 'data';
DETAIL_DATA_LEN = 'data_len';
DETAIL_KEY_DIGEST = 'key_digest';
DETAIL_DIGEST = 'digest';
DETAIL_DIGEST96 = 'digest-96';
var
currTest: TTestDetails;
stlTestData: TStringList;
i: integer;
cntOK: integer;
cntFailed: integer;
cntTotal: integer;
dataType: string;
UCdataType: string;
data: string;
digest: THashValue;
testResult: boolean;
failureReason: string;
generatedHMAC: string;
begin
cntOK := 0;
cntFailed := 0;
cntTotal := 0;
stlTestData:= TStringList.Create();
try
mmoReport.lines.Clear();
mmoReport.lines.add('Reading test data from file:');
mmoReport.lines.add(filename);
mmoReport.lines.add('');
stlTestData.LoadFromFile(filename);
currTest.FieldsPopulated := FIELDS_POPULATED_NONE;
digest:= THashValue.Create();
try
for i:=0 to (stlTestData.count-1) do
begin
// Disregard comment and blank lines
if (
(Trim(stlTestData[i]) = '') or
(Pos('#', Trim(stlTestData[i])) = 1)
) then
begin
continue;
end;
// File consists of blocks of test data as given in the following
// example:
//
// -- begin test block --
// hash = md5
// test_case = 1
// key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
// key_len = 16
// data = "Hi There"
// data_len = 8
// digest = 0x9294727a3638bb1c13f48ef8158bfc9d
// -- end test block --
// Split line
SDUSplitString(stlTestData[i], dataType, data, '=');
dataType := Trim(dataType);
data := Trim(data);
UCdataType := uppercase(dataType);
if (UCdataType = uppercase(DETAIL_HASH)) then
begin
currTest.Hash := data;
currTest.FieldsPopulated := currTest.FieldsPopulated + FIELD_POPULATED_HASH;
end
else if (UCdataType = uppercase(DETAIL_TEST_CASE_NO)) then
begin
currTest.TestCaseNo := strtoint(data);
currTest.FieldsPopulated := currTest.FieldsPopulated + FIELD_POPULATED_TESTCASENO;
end
else if (UCdataType = uppercase(DETAIL_KEY)) then
begin
currTest.Key := data;
currTest.FieldsPopulated := currTest.FieldsPopulated + FIELD_POPULATED_KEY;
end
else if (UCdataType = uppercase(DETAIL_KEY_LEN)) then
begin
currTest.KeyLength := strtoint(data);
currTest.FieldsPopulated := currTest.FieldsPopulated + FIELD_POPULATED_KEYLEN;
end
else if (UCdataType = uppercase(DETAIL_DATA)) then
begin
currTest.Data := data;
currTest.FieldsPopulated := currTest.FieldsPopulated + FIELD_POPULATED_DATA;
end
else if (UCdataType = uppercase(DETAIL_DATA_LEN)) then
begin
currTest.DataLength := strtoint(data);
currTest.FieldsPopulated := currTest.FieldsPopulated + FIELD_POPULATED_DATALEN;
end
else if (UCdataType = uppercase(DETAIL_DIGEST)) then
begin
currTest.Digest := data;
currTest.FieldsPopulated := currTest.FieldsPopulated + FIELD_POPULATED_DIGEST;
end
else if (
(UCdataType = uppercase(DETAIL_KEY_DIGEST)) or
(UCdataType = uppercase(DETAIL_DIGEST96))
) then
begin
// Ignored...
end
else
begin
mmoReport.lines.add('ABORTING: Unrecognised line in test file, line '+inttostr(i));
Result := FALSE;
exit;
end;
if (currTest.FieldsPopulated = FIELDS_POPULATED_ALL) then
begin
inc(cntTotal);
mmoReport.lines.add('Hash : '+currTest.Hash);
mmoReport.lines.add('TestCaseNo : '+inttostr(currTest.TestCaseNo));
mmoReport.lines.add('Key : '+currTest.Key);
mmoReport.lines.add('KeyLength : '+inttostr(currTest.KeyLength)+' bytes');
mmoReport.lines.add('Data : '+currTest.Data);
mmoReport.lines.add('DataLength : '+inttostr(currTest.DataLength)+' bytes');
mmoReport.lines.add('Expected HMAC : '+currTest.Digest);
testResult := ExecuteTest(currTest, generatedHMAC, failureReason);
mmoReport.lines.add('Generated HMAC: '+generatedHMAC);
if testResult then
begin
mmoReport.lines.add('Result : PASS');
inc(cntOK);
end
else
begin
mmoReport.lines.add('Result : FAILURE: '+failureReason);
inc(cntFailed);
end;
mmoReport.lines.add('');
currTest.FieldsPopulated := FIELDS_POPULATED_NONE;
end;
end;
finally
digest.Free();
end;
finally
stlTestData.Free();
end;
mmoReport.lines.add('');
mmoReport.lines.add('');
mmoReport.lines.add('RESULTS SUMMARY');
mmoReport.lines.add('===============');
mmoReport.lines.add('Total tests: '+inttostr(cntTotal));
mmoReport.lines.add(' Passed: '+inttostr(cntOK));
mmoReport.lines.add(' Failed: '+inttostr(cntFailed));
Result := (cntFailed = 0);
end;
// Generate HMAC, returning TRUE/FALSE if the generated HMAC matches the
// expected one.
// Either way, "generatedHMAC" will be set to the generated HMAC
// On failure, "failureReason" will be set to the reason why the HMAC failed
function TfrmMain.ExecuteTest(Test: TTestDetails; var generatedHMAC: string; var failureReason: string): boolean;
var
retVal: boolean;
MACValue: TMACValue;
hashType: fhHashType;
key: string;
data: string;
expected: string;
begin
retVal := TRUE;
failureReason := '';
generatedHMAC := '';
MACValue := TMACValue.Create();
try
key := Test.Key;
data:= Test.Data;
expected:= Test.Digest;
if not(ConvertToBinary(key)) then
begin
failureReason := 'Unable to understand key';
retVal := FALSE;
end
else if not(ConvertToBinary(data)) then
begin
failureReason := 'Unable to understand data';
retVal := FALSE;
end
else if not(ConvertToBinary(expected)) then
begin
failureReason := 'Unable to understand expected digest';
retVal := FALSE;
end;
// Handle special cases
// Sanity checks...
if (length(key) <> Test.KeyLength) then
begin
failureReason := 'Key length incorrect';
retVal := FALSE;
end
else if (length(data) <> Test.DataLength) then
begin
failureReason := 'Data length incorrect';
retVal := FALSE;
end;
if (retVal) then
begin
hashType := HashObj.GetHashTypeForTitle(Test.Hash);
HashObj.ActiveHash := hashType;
retVal := HMACString(key, data, HashObj, MACValue);
if not(retVal) then
begin
failureReason := 'Unable to generate HMAC';
end
else
begin
generatedHMAC := lowercase('0x'+MACValue.ValueAsASCIIHex);
if (MACValue.ValueAsBinary <> expected) then
begin
failureReason := 'HMAC value calculated doens''t match expected value';
retVal := FALSE;
end;
end;
end;
finally
MACValue.Free();
end;
Result := retVal;
end;
// Convert data from test file into binary string
function TfrmMain.ConvertToBinary(var data: string): boolean;
const
// This is crude, but...
SPECIAL_dd_x_50 = '0xdd repeated 50 times';
SPECIAL_cd_x_50 = '0xcd repeated 50 times';
SPECIAL_aa_x_80 = '0xaa repeated 80 times';
var
retVal: boolean;
tmpData: string;
begin
retVal := FALSE;
if (uppercase(data) = uppercase(SPECIAL_dd_x_50)) then
begin
data := StringOfChar(#$dd, 50);
retVal := TRUE;
end
else if (uppercase(data) = uppercase(SPECIAL_cd_x_50)) then
begin
data := StringOfChar(#$cd, 50);
retVal := TRUE;
end
else if (uppercase(data) = uppercase(SPECIAL_aa_x_80)) then
begin
data := StringOfChar(#$aa, 80);
retVal := TRUE;
end
else if (Pos('0x', data) = 1) then
begin
// ASCII encoded hex values...
// e.g. 0x123456...
Delete(data, 1, 2);
retVal := SDUParseASCIIToData(data, tmpData);
data := tmpData;
end
else if (Pos('"', data) = 1) then
begin
// Literal string
// e.g. "what do ya want for nothing?"
Delete(data, 1, 1);
Delete(data, Length(data), 1);
retVal := TRUE;
end;
Result := retVal;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
HashObj := THashAlgUnified.Create(nil);
self.caption := Application.Title;
edFilename.text := '..\docs\RFC2202_machine_readable_tests.txt';
mmoReport.lines.clear();
// Fixed width font
mmoReport.Font.Name := 'Courier';
end;
procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
HashObj.Free();
end;
procedure TfrmMain.pbBrowseClick(Sender: TObject);
begin
SDUOpenSaveDialogSetup(OpenDialog1, edFilename.text);
if OpenDialog1.Execute then
begin
edFilename.text := OpenDialog1.FileName;
end;
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
SDUCenterControl(pbTestHashes, ccHorizontal);
end;
END.
|
unit Demo.Miscellaneous.Customize;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_Miscellaneous_Customize = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_Miscellaneous_Customize.GenerateChart;
var
PieChart, BarChart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
// PieChart
PieChart := TcfsGChartProducer.Create;
PieChart.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART;
PieChart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Topping'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Slices')
]);
PieChart.Data.AddRow(['Mushrooms', 3]);
PieChart.Data.AddRow(['Onions', 1]);
PieChart.Data.AddRow(['Olives', 1]);
PieChart.Data.AddRow(['Zucchini', 1]);
PieChart.Data.AddRow(['Pepperoni', 2]);
PieChart.Options.Title('How Much Pizza I Ate Last Night');
PieChart.Options.TitleTextStyle(TcfsGChartOptions.TextStyleToJSObject('gray', 12, true, false));
PieChart.Options.Legend('textStyle', TcfsGChartOptions.TextStyleToJSObject('gray', 12, true, false));
PieChart.Options.PieSliceTextStyle(TcfsGChartOptions.TextStyleToJSObject('', 12, true, false));
PieChart.Options.Colors(['#e0440e', '#e6693e', '#ec8f6e', '#f3b49f', '#f6c7b6']);
PieChart.Options.Is3D(True);
// BarChart
BarChart := TcfsGChartProducer.Create;
BarChart.ClassChartType := TcfsGChartProducer.CLASS_BAR_CHART;
BarChart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Year'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Sales'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Expenses')
]);
BarChart.Data.AddRow(['2013', 1000, 400]);
BarChart.Data.AddRow(['2014', 1170, 460]);
BarChart.Data.AddRow(['2015', 660, 1120]);
BarChart.Data.AddRow(['2016', 1030, 540]);
BarChart.Options.Title('Company Performance');
BarChart.Options.TitleTextStyle(TcfsGChartOptions.TextStyleToJSObject('gray', 12, true, false));
BarChart.Options.Legend('textStyle', TcfsGChartOptions.TextStyleToJSObject('gray', 12, true, false));
BarChart.Options.ChartArea('width', '50%');
BarChart.Options.Colors(['green', 'red']);
BarChart.Options.hAxis('title', 'milions €');
BarChart.Options.hAxis('textStyle', '{bold: true, fontSize: 10, color: ''silver''}');
BarChart.Options.hAxis('titleTextStyle', '{bold: true, italic: false, fontSize: 11, color: ''silver''}');
BarChart.Options.hAxis('minValue', 0);
BarChart.Options.vAxis('title', 'Year');
BarChart.Options.vAxis('textStyle', '{bold: true, fontSize: 11, color: ''gray''}');
BarChart.Options.vAxis('titleTextStyle', '{bold: true, italic: false, fontSize: 12, color: ''gray''}');
BarChart.Options.DataOpacity(0.5);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div id="PieChart" style="width: 100%;height: 50%;"></div>'
+ '<div id="BarChart" style="width: 100%;height: 50%;"></div>'
);
GChartsFrame.DocumentGenerate('PieChart', PieChart);
GChartsFrame.DocumentGenerate('BarChart', BarChart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_Miscellaneous_Customize);
end.
|
{
******************************************************************************
IcmpPing
Implementação de Ping através de ICMP.DLL.
******************************************************************************
Criado por Cristiano Kliemann (cristianok@ieg.com.br).
Visite http://www.cristianok.hpg.com.br e veja outros exemplos, dicas e
tutoriais sobre Delphi e assuntos relacionados.
Qualquer dúvida ou sugestão, sinta-se a vontade para enviar um e-mail.
Essa unidade foi criada com o propósito de estudo e pode pode ser modificada e
usada em qualquer aplicativo, comercial ou não, desde que mantenha o minha
autoria.
******************************************************************************
}
unit IcmpPing;
interface
uses SysUtils, Windows;
type
TPing = class;
EPingException = class(Exception);
EPingAddrNotesolvedException = class(Exception);
THostResolvedEvent = procedure(Sender: TPing; AHost, AIp: string) of object;
TPing = class(TObject)
private
FHandle: THandle;
FOnHostResolved: THostResolvedEvent;
protected
procedure DoHostResolved(AHost, AIp: string); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
function Ping(AHost: string; ATimeout: Cardinal; ADataSize: Word;
var ReplyIp: string;
var ReplyDataSize: Word;
var ReplyTTL: Cardinal;
var ReplyStatus: LongWord): Integer; overload;
function Ping(AHost: string; ATimeout: Cardinal = 5000; ADataSize: Word = 32): Integer; overload;
published
property OnHostResolved: THostResolvedEvent read FOnHostResolved write FOnHostResolved;
end;
function GetIcmpReplyStatusMessage(AReplyStatus: LongWord): string;
implementation
uses WinSock;
type
TIcmpCreateFileProc = function: THandle; stdcall;
TIcmpCloseHandleProc = function(IcmpHandle: THandle): BOOL; stdcall;
TIcmpSendEchoProc = function(
IcmpHandle: THandle;
DestinationAddress: LongWord;
RequestData: Pointer;
RequestSize: Word;
RequestOptions: Pointer;
ReplyBuffer: Pointer;
ReplySize: DWORD;
Timeout: DWORD): DWORD; stdcall;
TIpOptionInformation = packed record
TTL: Byte;
TOS: Byte;
Flags: Byte;
OptionsSize: Byte;
Options: Pointer;
end;
TIcmpEchoReply = packed record
Address: LongWord;
Status: LongWord;
RoundTripTime: LongWord;
DataSize: Word;
Reserved: Word;
Data: Pointer;
Options: TIpOptionInformation;
end;
var
IcmpModule: HModule;
IcmpCreateFile: TIcmpCreateFileProc;
IcmpCloseHandle: TIcmpCloseHandleProc;
IcmpSendEcho: TIcmpSendEchoProc;
WinSockLoaded: Boolean;
function IcmpLoaded: Boolean;
begin
Result := IcmpModule <> 0;
end;
procedure IcmpUnload;
begin
if not IcmpLoaded then EXIT;
FreeLibrary(IcmpModule);
end;
procedure IcmpLoad;
begin
if IcmpLoaded then EXIT;
IcmpModule := LoadLibrary('icmp.dll');
if IcmpModule = 0 then
raise EPingException.Create('ICMP.DLL não pôde ser carregada.');
try
IcmpCreateFile := GetProcAddress(IcmpModule, 'IcmpCreateFile');
if not Assigned(IcmpCreateFile) then
raise EPingException.Create('ICMP.DLL inválida.');
IcmpCloseHandle := GetProcAddress(IcmpModule, 'IcmpCloseHandle');
if not Assigned(IcmpCloseHandle) then
raise EPingException.Create('ICMP.DLL inválida.');
IcmpSendEcho := GetProcAddress(IcmpModule, 'IcmpSendEcho');
if not Assigned(IcmpSendEcho) then
raise EPingException.Create('ICMP.DLL inválida.');
except
IcmpUnload;
raise;
end;
end;
procedure WinSockLoad;
var
D: TWSAData;
Res: Integer;
begin
if not WinSockLoaded then begin
FillChar(D, SizeOf(D), 0);
Res := WSAStartup($0101, D);
if Res <> 0 then begin
raise EPingException.CreateFmt('WinSock não pôde ser carregada. (%d)', [Res]);
end;
WinSockLoaded := True;
end;
end;
procedure WinSockUnload;
begin
if WinSockLoaded then begin
WSACleanup;
WinSockLoaded := False;
end;
end;
{ TPing }
constructor TPing.Create;
begin
WinSockLoad;
IcmpLoad;
FHandle := IcmpCreateFile;
if FHandle = INVALID_HANDLE_VALUE then
raise EPingException.Create('Não pude criar handle ICMP.');
end;
destructor TPing.Destroy;
begin
IcmpCloseHandle(FHandle);
inherited;
end;
function TPing.Ping(AHost: string; ATimeout: Cardinal; ADataSize: Word;
var ReplyIp: string;
var ReplyDataSize: Word;
var ReplyTTL: Cardinal;
var ReplyStatus: LongWord): Integer;
var
Addr: PInAddr;
Req: PChar;
Reply: ^TIcmpEchoReply;
Res: Cardinal;
HostEnt: PHostEnt;
begin
HostEnt := gethostbyname(PChar(AHost));
if HostEnt = nil then
raise EPingAddrNotesolvedException.CreateFmt('Endereço ''%s'' não resolvido', [AHost]);
Addr := PInAddr(HostEnt.h_addr^);
DoHostResolved(AHost, inet_ntoa(Addr^));
Req := AllocMem(ADataSize);
try
Reply := AllocMem(SizeOf(TIcmpEchoReply) + ADataSize);
try
Res := IcmpSendEcho(FHandle, LongWord(Addr^), @Req, ADataSize, nil, Reply,
SizeOf(TIcmpEchoReply) + ADataSize, ATimeOut);
if Res > 0 then begin
ReplyStatus := Reply.Status;
Result := Reply.RoundTripTime;
ReplyIp := inet_ntoa(TInAddr(Reply.Address));
ReplyDataSize := Reply.DataSize;
ReplyTTL := Reply.Options.TTL;
end else begin
Result := -1;
end;
finally
FreeMem(Reply);
end;
finally
FreeMem(Req);
end;
end;
//54.69.69.66
procedure TPing.DoHostResolved(AHost, AIp: string);
begin
if Assigned(FOnHostResolved) then FOnHostResolved(Self, AHost, AIp);
end;
function TPing.Ping(AHost: string; ATimeout: Cardinal = 5000;
ADataSize: Word = 32): Integer;
var
ReplyIP: string;
ReplyDataSize: Word;
ReplyStatus: LongWord;
ReplyTTL: Cardinal;
begin
Result := Ping(AHost, ADataSize, ATimeout, ReplyIP, ReplyDataSize, ReplyTTL, ReplyStatus);
if ReplyStatus <> 0 then Result := -1;
end;
{ EPingReplyException }
function GetIcmpReplyStatusMessage(AReplyStatus: LongWord): string;
begin
case AReplyStatus of
0: Result := 'Sucesso';
11001: Result := 'Buffer muito pequeno';
11003: Result := 'Host destino inalcancavel';
11004: Result := 'Protocolo destino inalcancavel';
11005: Result := 'Porta destino inalcancavel';
11006: Result := 'Sem recursos disponiveis';
11007: Result := 'Opcao incorreta';
11008: Result := 'Erro de hardware';
11009: Result := 'Pacote muito grande';
11010: Result := 'Tempo expirou';
11011: Result := 'Requisicao incorreta';
11012: Result := 'Rota incorreta';
11013: Result := 'TTL expirou em transito';
11014: Result := 'TTL Exprd Reassemb';
11015: Result := 'Problema com parametros';
11016: Result := 'Source Quench';
11017: Result := 'Opcao muito grande';
11018: Result := 'Destino incorreto';
11019: Result := 'Endereco excluido';
11020: Result := 'Spec MTU Change';
11021: Result := 'MTU Change';
11022: Result := 'Unload';
11050: Result := 'General Failure';
else
Result := Format('Status desconhecido (%d)', [AReplyStatus]);
end;
end;
initialization
{ Nada }
finalization
IcmpUnload;
WinSockUnload;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.Application;
{$I Kitto.Defines.inc}
interface
uses
Classes,
FCGIApp;
type
TKExtAppThread = class(TThread)
private
FAppTitle: string;
FTCPPort: Integer;
FSessionTimeout: Integer;
FIcon: string;
protected
procedure Execute; override;
public
destructor Destroy; override;
public
procedure Configure;
property AppTitle: string read FAppTitle;
property TCPPort: Integer read FTCPPort;
property SessionTimeout: Integer read FSessionTimeout;
property Icon: string read FIcon;
end;
implementation
uses
SysUtils,
EF.Logger, EF.Localization,
Kitto.Config,
Kitto.Ext.Session;
{ TKExtAppThread }
procedure TKExtAppThread.Configure;
var
LConfig: TKConfig;
begin
LConfig := TKConfig.Create;
try
TEFLogger.Instance.Log('Configuring thread...');
FAppTitle := LConfig.AppTitle;
FTCPPort := LConfig.Config.GetInteger('FastCGI/TCPPort', 2014);
FSessionTimeout := LConfig.Config.GetInteger('FastCGI/SessionTimeout', 30);
FIcon := LConfig.FindImageURL(LConfig.AppIcon);
TEFLogger.Instance.Log('AppName: ' + LConfig.AppName);
TEFLogger.Instance.Log('AppTitle: ' + _(FAppTitle));
TEFLogger.Instance.LogFmt('TCPPort: %d', [FTCPPort]);
TEFLogger.Instance.LogFmt('SessionTimeout: %d', [FSessionTimeout]);
TEFLogger.Instance.LogFmt('Config.SystemHomePath: %s', [LConfig.SystemHomePath]);
TEFLogger.Instance.LogFmt('Config.AppHomePath: %s', [LConfig.AppHomePath]);
finally
FreeAndNil(LConfig);
end;
end;
destructor TKExtAppThread.Destroy;
begin
//Application.TerminateAllThreads;
FreeAndNil(Application);
inherited;
end;
procedure TKExtAppThread.Execute;
begin
FreeAndNil(Application);
Application := CreateWebApplication(_(FAppTitle), TKExtSession, FTCPPort, FSessionTimeout);
Application.Icon := FIcon;
Application.Run(Self);
end;
end.
|
(*
* FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV
*
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*)
unit uListViewFPG;
interface
uses LCLIntf, LCLType, ComCtrls, Graphics, Controls, SysUtils, Classes,
ClipBrd, Forms, Dialogs,
uLanguage, uFPG, uTools, uIniFile,
uLoadImage, uColor16bits, uFrmMessageBox ,IntfGraphics;
type
TFPGListView = class( TListView)
private
{ Private declarations }
Ffpg: TFpg;
public
{ Public declarations }
procedure Load_Images( progressBar : TProgressBar);
procedure Insert_Images(lImages : TStringList; dir : string; var progressBar : TProgressBar);
procedure Insert_Imagescb( var progressBar : TProgressBar);
procedure add_items( index : Word);
procedure replace_item( index : Word);
procedure freeFPG;
published
property Fpg : TFpg read Ffpg write Ffpg ;
property Align;
property AllocBy;
property Anchors;
property AutoSort;
property AutoWidthLastColumn;
property BorderSpacing;
property BorderStyle;
property BorderWidth;
property Checkboxes;
property Color;
property Columns;
property ColumnClick;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
// property DefaultItemHeight;
// property DropTarget;
property Enabled;
// property FlatScrollBars;
property Font;
// property FullDrag;
property GridLines;
property HideSelection;
// property HotTrack;
// property HotTrackStyles;
// property HoverTime;
property IconOptions;
// property ItemIndex; shouldn't be published, see bug 16367
property Items;
property LargeImages;
property MultiSelect;
property OwnerData;
// property OwnerDraw;
property ParentColor default False;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property RowSelect;
property ScrollBars;
property ShowColumnHeaders;
property ShowHint;
// property ShowWorkAreas;
property SmallImages;
property SortColumn;
property SortDirection;
property SortType;
property StateImages;
property TabStop;
property TabOrder;
property ToolTips;
property Visible;
property ViewStyle;
property OnAdvancedCustomDraw;
property OnAdvancedCustomDrawItem;
property OnAdvancedCustomDrawSubItem;
property OnChange;
property OnClick;
property OnColumnClick;
property OnCompare;
property OnContextPopup;
property OnCreateItemClass;
property OnCustomDraw;
property OnCustomDrawItem;
property OnCustomDrawSubItem;
property OnData;
property OnDataFind;
property OnDataHint;
property OnDataStateChange;
property OnDblClick;
property OnDeletion;
property OnDragDrop;
property OnDragOver;
property OnEdited;
property OnEditing;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnItemChecked;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnSelectItem;
property OnStartDock;
property OnStartDrag;
property OnUTF8KeyPress;
end;
procedure Register;
implementation
procedure TFPGListView.Load_Images( progressBar : TProgressBar);
var
count : Integer;
begin
//Limpiamos la lista de imagenes
LargeImages.Clear;
Items.Clear;
LargeImages.Width := inifile_sizeof_icon;
LargeImages.Height := inifile_sizeof_icon;
progressBar.Position := 0;
progressBar.Show;
progressBar.Repaint;
for count:= 1 to Fpg.Count do
begin
with Fpg.images[count] do
begin
add_items(count);
if (count mod inifile_repaint_number) = 0 then
begin
progressBar.Position:= (count * 100) div Fpg.Count;
progressBar.Repaint;
end;
end;
end;
progressBar.Hide;
end;
procedure TFPGListView.Insert_Images(lImages : TStringList; dir : string;
var progressBar : TProgressBar);
var
i : Integer;
bmp_src : TBitmap;
file_source, filename : string;
index : word;
begin
// Creamos el bitmap fuente y destino
bmp_src := TBitmap.Create;
// Se inializa la barra de progresión
progressBar.Position := 0;
progressBar.Show;
progressBar.Repaint;
for i := 0 to lImages.Count - 1 do
begin
index:=Fpg.indexOfCode( Fpg.lastcode);
if index<>0 then
begin
if MessageDlg('El código: '+intToStr(Fpg.lastcode)+' ya existe. ¿Desea sobrescribirlo?',mtConfirmation,[mbYes,mbNo],0) = mrNo then
continue;
end;
filename := lImages.Strings[i];
// Se prepara la ruta del fichero
file_source := prepare_file_source(Dir, filename);
// Se carga la imagen
loadImageFile(bmp_src, file_source);
(*
// Se incrementa el código de la imagen
Fpg.last_code := Fpg.last_code + 1;
// Busca hasta que encuentre un código libre
while CodeExists(Fpg.last_code) do
Fpg.last_code := Fpg.last_code + 1;
*)
// ver como meter fpgedit2009
if index<>0 then
begin
fpg.replace_bitmap( index, ChangeFileExt(filename,''), ChangeFileExt(filename,''), bmp_src );
replace_item( index);
end else begin
Fpg.Count := Fpg.Count + 1;
fpg.add_bitmap( Fpg.Count, ChangeFileExt(filename,''), ChangeFileExt(filename,''), bmp_src );
add_items( Fpg.Count);
end;
Fpg.lastcode := Fpg.lastcode + 1;
//bmp_src.FreeImage;
progressBar.Position:= ((i+1) * 100) div lImages.Count;
progressBar.Repaint;
end;
Fpg.lastcode := Fpg.lastcode - 1;
bmp_src.Free;
Fpg.update := true;
Repaint;
progressBar.Hide;
end;
procedure TFPGListView.Insert_Imagescb( var progressBar : TProgressBar);
var
bmp_src : TBitmap;
begin
// Se inializa la barra de progresión
progressBar.Position := 50;
progressBar.Show;
progressBar.Repaint;
bmp_src := TBitmap.Create;
bmp_src.PixelFormat := pf32bit;
try
bmp_src.LoadFromClipBoardFormat( cf_BitMap);
except
bmp_src.Destroy;
progressBar.Hide;
feMessageBox(LNG_STRINGS[LNG_ERROR], LNG_STRINGS[LNG_NOT_CLIPBOARD_IMAGE], 0, 0);
Exit;
end;
LargeImages.Width := inifile_sizeof_icon;
LargeImages.Height := inifile_sizeof_icon;
// Se incrementa el código de la imagen
Fpg.lastcode := Fpg.lastcode + 1;
// Busca hasta que encuentre un código libre
while Fpg.CodeExists(Fpg.lastcode) do
Fpg.lastcode := Fpg.lastcode + 1;
// ver como meter fpgedit2009
Fpg.Count := Fpg.Count + 1;
fpg.add_bitmap( Fpg.Count, 'ClipBoard', 'ClipBoard', bmp_src );
add_items( Fpg.Count);
progressBar.Hide;
bmp_src.Destroy;
Fpg.update := true;
end;
procedure TFPGListView.add_items( index : Word);
var
list_bmp : TListItem;
bmp_dst: TBitMap;
begin
// Pintamos el icono
DrawProportional(Fpg.images[index].bmp, bmp_dst, color);
list_bmp := Items.Add;
list_bmp.ImageIndex := LargeImages.add(bmp_dst, nil);
// Se establece el código del FPG
list_bmp.Caption := NumberTo3Char( Fpg.images[index].graph_code );
// Se añaden los datos de la imagen a la lista
list_bmp.SubItems.Add(Fpg.images[index].fpname);
list_bmp.SubItems.Add(Fpg.images[index].name);
list_bmp.SubItems.Add(IntToStr(Fpg.images[index].width));
list_bmp.SubItems.Add(IntToStr(Fpg.images[index].height));
list_bmp.SubItems.Add(IntToStr(Fpg.images[index].points));
end;
procedure TFPGListView.replace_item( index : Word);
var
list_bmp : TListItem;
bmp_dst: TBitMap;
begin
// Pintamos el icono
DrawProportional(Fpg.images[index].bmp, bmp_dst, color);
list_bmp := Items.Item[index -1];
LargeImages.Replace(index-1, bmp_dst, Nil);
//list_bmp.ImageIndex :=
// Se añaden los datos de la imagen a la lista
list_bmp.SubItems.Strings[0]:=Fpg.images[index].fpname;
list_bmp.SubItems.Strings[1]:=Fpg.images[index].name;
list_bmp.SubItems.Strings[2]:=IntToStr(Fpg.images[index].width);
list_bmp.SubItems.Strings[3]:=IntToStr(Fpg.images[index].height);
// list_bmp.SubItems.Strings[4]:=IntToStr(Fpg.images[index].points);
end;
procedure TFPGListView.FreeFPG;
begin
FreeAndNil(ffpg);
end;
procedure Register;
begin
RegisterComponents('Common Controls',[TFPGListView]);
end;
end.
|
unit NSqlSys;
{$I NSql.Inc}
interface
uses
FmtBcd,
Windows;
type
IAdvDestroy = interface
['{F91FBA49-2129-44DB-ADAF-F6566A19B41B}']
procedure StartDestroy;
end;
TAdvInterfacedObject = class(TObject, IInterface, IAdvDestroy)
private
FInDestroyProcess: Boolean;
protected
FRefCount: Integer;
function QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} IID: TGUID; out Obj): HResult; stdcall;
function InternalQueryInterface(const IID: TGUID; out Obj): Boolean; virtual;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
function GetUseRefCounting: Boolean; virtual; abstract;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
property UseRefCounting: Boolean read GetUseRefCounting;
procedure StartDestroy; virtual;
property InDestroyProcess: Boolean read FInDestroyProcess;
end;
TNotThreadSafeAdvInterfacedObject = class(TObject, IInterface, IAdvDestroy)
private
FInDestroyProcess: Boolean;
protected
FRefCount: Integer;
function QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} IID: TGUID; out Obj): HResult; stdcall;
function InternalQueryInterface(const IID: TGUID; out Obj): Boolean; virtual;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
function GetUseRefCounting: Boolean; virtual; abstract;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
property UseRefCounting: Boolean read GetUseRefCounting;
procedure StartDestroy; virtual;
property InDestroyProcess: Boolean read FInDestroyProcess;
end;
TNonInterlockedInterfacedObject = class(TObject, IInterface)
private
protected
FRefCount: Integer;
function QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; virtual; stdcall;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
end;
{$TYPEINFO ON}
TAdvInterfacedObjectWTI = class(TAdvInterfacedObject)
end;
TNotThreadSafeAdvInterfacedObjectWTI = class(TNotThreadSafeAdvInterfacedObject)
end;
{$TYPEINFO OFF}
INSqlCriticalSection = interface
['{69EC46A1-CE76-4889-8750-9203E67537D9}']
procedure Enter;
procedure Leave;
end;
function NSqlCriticalSectionGuard: INSqlCriticalSection;
function NSqlStringToBcd(const S: UnicodeString): TBcd;
function NSqlBcdToString(const Bcd: TBcd): UnicodeString;
function NSqlDoubleToBcd(const D: Double): TBcd;
function NSqlBcdToDouble(const Bcd: TBcd): Double;
function NSqlFormatFloat(const Format: UnicodeString; const Value: Extended): UnicodeString;
function NSqlSameTextUnicode(const S1, S2: UnicodeString): Boolean;
function NSqlUnicodeStringToUtf8Bytes(const S: UnicodeString): AnsiString;
function NSqlConvertToUnicodeString(const S: AnsiString; FromCodePage: Word): UnicodeString; overload
function NSqlConvertToUnicodeString(Data: Pointer; Count: Integer; FromCodePage: Word): UnicodeString; overload;
function NSqlUtf8BytesToUnicodeString(const S: AnsiString): UnicodeString;
function NSqlConvertToUtf8String(Data: Pointer; Count: Integer; FromCodePage: Word): AnsiString; overload;
function NSqlConvertToUtf8String(const S: AnsiString; FromCodePage: Word): AnsiString; overload;
//function NSqlCreateUtf8String(Data: Pointer; Count: Integer): AnsiString;
function NSqlCreateByteString(Data: Pointer; Count: Integer): AnsiString;
procedure NSqlRaiseLastOSError(LastError: DWORD); overload;
procedure NSqlRaiseLastOSError; overload;
function NSqlBinToHex(const Source: AnsiString): AnsiString;
implementation
uses
SysUtils;
type
TCriticalSectionGuard = class(TInterfacedObject, INSqlCriticalSection)
private
FSection: TRTLCriticalSection;
protected
procedure Enter;
procedure Leave;
public
constructor Create;
destructor Destroy; override;
end;
var
FBcdFormatSettings: TFormatSettings;
function NSqlSameTextUnicode(const S1, S2: UnicodeString): Boolean;
const
CSTR_EQUAL = 2; { string 1 equal to string 2 }
begin
Result := Windows.CompareStringW(Windows.LOCALE_INVARIANT, Windows.NORM_IGNORECASE, PWideChar(S1),
Length(S1), PWideChar(S2), Length(S2)) = CSTR_EQUAL;
end;
function NSqlUnicodeStringToUtf8Bytes(const S: UnicodeString): AnsiString;
var
Len: Integer;
ResLen: Integer;
begin
Len := Length(S);
if Len <> 0 then
begin
ResLen := Len * 4 + 1;
SetLength(Result, ResLen); // SetLength includes space for null terminator
ResLen := Windows.WideCharToMultiByte(Windows.CP_UTF8, 0, PWideChar(S), Len, PAnsiChar(Result), ResLen, nil, nil);
SetLength(Result, ResLen);
end
else
Result := '';
end;
function NSqlConvertToUnicodeString(const S: AnsiString; FromCodePage: Word): UnicodeString; overload;
//var
// Len: Integer;
// ResLen: Integer;
begin
if S <> '' then
Result := NSqlConvertToUnicodeString(Pointer(S), Length(S), FromCodePage)
else
Result := '';
// if FromCodePage > 0 then
// begin
// Len := Length(S);
// if Len > 0 then
// begin
// ResLen := Len * 4 + 1;
// SetLength(Result, ResLen);
// ResLen := MultiByteToWideChar(FromCodePage, 0, Pointer(S), Len, PWideChar(Result), ResLen);
// SetLength(Result, ResLen);
// end
// else
// Result := '';
// end
// else
// Assert(False);
end;
function NSqlConvertToUnicodeString(Data: Pointer; Count: Integer; FromCodePage: Word): UnicodeString; overload;
var
Len: Integer;
ResLen: Integer;
begin
if FromCodePage > 0 then
begin
Len := Count;
if Len > 0 then
begin
if not Assigned(Data) then
Assert(False);
ResLen := Len * 4 + 1;
SetLength(Result, ResLen);
ResLen := MultiByteToWideChar(FromCodePage, 0, Data, Len, PWideChar(Result), ResLen);
SetLength(Result, ResLen);
end
else
Result := '';
end
else
Assert(False);
end;
function NSqlUtf8BytesToUnicodeString(const S: AnsiString): UnicodeString;
var
Len: Integer;
ResLen: Integer;
begin
Len := Length(S);
if Len <> 0 then
begin
ResLen := Len + 1;
SetLength(Result, ResLen); // SetLength includes space for null terminator
ResLen := Windows.MultiByteToWideChar(Windows.CP_UTF8, 0, PAnsiChar(S), Len, PWideChar(Result), ResLen);
SetLength(Result, ResLen);
end
else
Result := '';
end;
function NSqlConvertToUtf8String(Data: Pointer; Count: Integer; FromCodePage: Word): AnsiString; overload;
begin
Result := NSqlUnicodeStringToUtf8Bytes(NSqlConvertToUnicodeString(Data, Count, FromCodePage));
end;
function NSqlConvertToUtf8String(const S: AnsiString; FromCodePage: Word): AnsiString; overload;
begin
Result := NSqlUnicodeStringToUtf8Bytes(NSqlConvertToUnicodeString(S, FromCodePage));
end;
//function NSqlCreateUtf8String(Data: Pointer; Count: Integer): AnsiString;
//begin
// SetLength(Result, Count);
// if Count > 0 then
// Move(Data^, Pointer(Result)^, Count);
//end;
function NSqlCreateByteString(Data: Pointer; Count: Integer): AnsiString;
begin
SetLength(Result, Count);
if Count > 0 then
Move(Data^, Pointer(Result)^, Count);
end;
procedure NSqlRaiseLastOSError(LastError: DWORD); overload;
var
Error: EOSError;
begin
if LastError <> 0 then
Error := EOSError.CreateFmt('System Error (code %d):' + sLineBreak + '%s', [LastError, SysErrorMessage(LastError)])
else
Error := EOSError.Create('System Error (code 0)');
Error.ErrorCode := LastError;
raise Error;
end;
procedure NSqlRaiseLastOSError; overload;
begin
NSqlRaiseLastOSError(GetLastError);
end;
procedure BinToHexImpl(Buffer: PAnsiChar; Text: PAnsiChar; BufSize: Integer);
const
Convert: array[0..15] of AnsiChar = AnsiString('0123456789ABCDEF');
var
I: Integer;
begin
for I := 0 to BufSize - 1 do
begin
Text[0] := Convert[Byte(Buffer[I]) shr 4];
Text[1] := Convert[Byte(Buffer[I]) and $F];
Inc(Text, 2);
end;
end;
function NSqlBinToHex(const Source: AnsiString): AnsiString;
begin
SetLength(Result, Length(Source) * 2);
if Length(Source) > 0 then
BinToHexImpl(PAnsiChar(Source), PAnsiChar(Result), Length(Source));
end;
function NSqlCriticalSectionGuard: INSqlCriticalSection;
begin
Result := TCriticalSectionGuard.Create;
end;
function NSqlStringToBcd(const S: UnicodeString): TBcd;
begin
Result := StrToBcd(S{$IFDEF NSQL_XEUP}, FBcdFormatSettings{$ENDIF});
end;
function NSqlDoubleToBcd(const D: Double): TBcd;
begin
Result := NSqlStringToBcd(FloatToStr(D, FBcdFormatSettings));
end;
function NSqlBcdToDouble(const Bcd: TBcd): Double;
begin
Result := StrToFloat(NSqlBcdToString(Bcd), FBcdFormatSettings);
end;
function NSqlBcdToString(const Bcd: TBcd): UnicodeString;
begin
Result := BcdToStr(Bcd{$IFDEF NSQL_2010UP}, FBcdFormatSettings{$ENDIF});
end;
function NSqlFormatFloat(const Format: UnicodeString; const Value: Extended): UnicodeString;
begin
Result := FormatFloat(Format, Value, FBcdFormatSettings);
end;
{ TAdvInterfacedObject }
function TAdvInterfacedObject._AddRef: Integer;
begin
Result := InterlockedIncrement(FRefCount)
end;
function TAdvInterfacedObject._Release: Integer;
begin
Result := InterlockedDecrement(FRefCount);
if Result = 0 then
if UseRefCounting or InDestroyProcess then
Destroy;
end;
procedure TAdvInterfacedObject.AfterConstruction;
begin
InterlockedDecrement(FRefCount);
inherited;
end;
procedure TAdvInterfacedObject.BeforeDestruction;
var
S: UnicodeString;
begin
if RefCount <> 0 then
begin
S := IntToStr(RefCount);
Assert(RefCount = 0, ClassName + '.ReferenceCount = ' + S);
end;
inherited;
end;
class function TAdvInterfacedObject.NewInstance: TObject;
begin
Result := inherited NewInstance;
TAdvInterfacedObject(Result).FRefCount := 1;
end;
function TAdvInterfacedObject.QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID, Obj) or InternalQueryInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
procedure TAdvInterfacedObject.StartDestroy;
begin
FInDestroyProcess := True;
_AddRef;
_Release;
end;
function TAdvInterfacedObject.InternalQueryInterface(const IID: TGUID;
out Obj): Boolean;
begin
Result := False;
end;
{ TNotThreadSafeAdvInterfacedObject }
function TNotThreadSafeAdvInterfacedObject._AddRef: Integer;
begin
Inc(FRefCount);
Result := FRefCount;
end;
function TNotThreadSafeAdvInterfacedObject._Release: Integer;
begin
Dec(FRefCount);
Result := FRefCount;
if Result = 0 then
if UseRefCounting or InDestroyProcess then
Destroy;
end;
procedure TNotThreadSafeAdvInterfacedObject.AfterConstruction;
begin
Dec(FRefCount);
inherited;
end;
procedure TNotThreadSafeAdvInterfacedObject.BeforeDestruction;
var
S: UnicodeString;
begin
if RefCount <> 0 then
begin
S := IntToStr(RefCount);
Assert(RefCount = 0, ClassName + '.ReferenceCount = ' + S);
end;
inherited;
end;
class function TNotThreadSafeAdvInterfacedObject.NewInstance: TObject;
begin
Result := inherited NewInstance;
TNotThreadSafeAdvInterfacedObject(Result).FRefCount := 1;
end;
function TNotThreadSafeAdvInterfacedObject.QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID, Obj) or InternalQueryInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
procedure TNotThreadSafeAdvInterfacedObject.StartDestroy;
begin
FInDestroyProcess := True;
_AddRef;
_Release;
end;
function TNotThreadSafeAdvInterfacedObject.InternalQueryInterface(const IID: TGUID;
out Obj): Boolean;
begin
Result := False;
end;
{ TNonInterlockedInterfacedObject }
function TNonInterlockedInterfacedObject._AddRef: Integer;
begin
Inc(FRefCount);
Result := FRefCount;
end;
function TNonInterlockedInterfacedObject._Release: Integer;
begin
Dec(FRefCount);
Result := FRefCount;
if Result = 0 then
Destroy;
end;
procedure TNonInterlockedInterfacedObject.AfterConstruction;
begin
Dec(FRefCount);
inherited;
end;
procedure TNonInterlockedInterfacedObject.BeforeDestruction;
var
S: UnicodeString;
begin
if FRefCount <> 0 then
begin
S := IntToStr(FRefCount);
Assert(FRefCount = 0, ClassName + '.ReferenceCount = ' + S);
end;
inherited;
end;
class function TNonInterlockedInterfacedObject.NewInstance: TObject;
begin
Result := inherited NewInstance;
TNonInterlockedInterfacedObject(Result).FRefCount := 1;
end;
function TNonInterlockedInterfacedObject.QueryInterface({$IFDEF FPC_HAS_CONSTREF}constref{$ELSE}const{$ENDIF} IID: TGUID;
out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
{ TCriticalSectionGuard }
constructor TCriticalSectionGuard.Create;
begin
inherited;
InitializeCriticalSection(FSection);
end;
destructor TCriticalSectionGuard.Destroy;
begin
DeleteCriticalSection(FSection);
inherited;
end;
procedure TCriticalSectionGuard.Enter;
begin
EnterCriticalSection(FSection);
end;
procedure TCriticalSectionGuard.Leave;
begin
LeaveCriticalSection(FSection);
end;
initialization
FillChar(FBcdFormatSettings, SizeOf(FBcdFormatSettings), 0);
FBcdFormatSettings.DecimalSeparator := '.';
end.
|
unit UnihanReader;
{
Parses Unihan format.
Unihan is organized as a bunch of files:
Unihan_Readings.txt
Unihan_Variants.txt
...
Each associates some properties to kanji:
U+53C1 kAccountingNumeric 3
U+kanjiHex [tab] kPropertyName [tab] Value
Some properties can have multiple values for a single kanji.
Simple way to parse this is to parse every file line by line, and look for
the properties you need.
}
interface
uses SysUtils;
{ Do not pass here lines starting with this character.
Alternatively, use IsUnihanComment() }
const
UNIHAN_COMMENT: WideChar = '#';
type
EUnihanParsingException = class(Exception);
TUnihanPropertyEntry = record
char: UnicodeString; //it can be multibyte
propType: string;
value: string;
procedure Reset;
end;
PUnihanPropertyEntry = ^TUnihanPropertyEntry;
{ Returns true if the line in question is a comment line. }
function IsUnihanComment(const s: UnicodeString): boolean;
{ Parses a valid non-empty non-comment line and populates the record }
procedure ParseUnihanLine(const s: UnicodeString; ed: PUnihanPropertyEntry);
{ Parsers for some special property formats }
type
TVariantValue = record
char: UnicodeString;
sources: array of string;
end;
TVariantValues = array of TVariantValue;
procedure ParseVariantProperty(const s: UnicodeString; out variants: TVariantValues);
function RadicalOf(const radval: string): string;
function StrokeCountOf(const radval: string): string;
implementation
resourcestring
eNoCharHexCode = 'Record does not begin with U+hex code';
eInvalidCharHexCode = 'Invalid char hex code: %s';
eInvalidHexCharacter = 'Invalid hex character "%s"';
eNoPropertyName = 'Missing property name';
eNoPropertyValue = 'Missing property value';
function IsUnihanComment(const s: UnicodeString): boolean;
var pc: PWideChar;
begin
pc := PWideChar(integer(s)); //do not uniquestr on cast
if pc=nil then begin
Result := false;
exit;
end;
while pc^=' ' do Inc(pc);
Result := pc^=UNIHAN_COMMENT;
end;
procedure TUnihanPropertyEntry.Reset;
begin
char := '';
propType := '';
value := '';
end;
//Returns a value in range 0..15 for a given hex character, or throws an exception
function HexCharCode(const c:char): byte; inline;
begin
if (ord(c)>=ord('0')) and (ord(c)<=ord('9')) then
Result := ord(c)-ord('0')
else
if (ord(c)>=ord('A')) and (ord(c)<=ord('F')) then
Result := 10 + ord(c)-ord('A')
else
if (ord(c)>=ord('a')) and (ord(c)<=ord('f')) then
Result := 10 + ord(c)-ord('a')
else
raise EUnihanParsingException.CreateFmt(eInvalidHexCharacter,[c]);
end;
{ Decodes stuff like U+20B3A into a character (possibly multibyte) }
function DecodeUplusChar(const ch: UnicodeString): UnicodeString;
var uni_idx, i: integer;
begin
Result := '';
if Length(ch)<6 then
raise EUnihanParsingException.CreateFmt(eInvalidCharHexCode, [ch]);
if (ch[1]<>'U') or (ch[2]<>'+') then
raise EUnihanParsingException.CreateFmt(eInvalidCharHexCode, [ch]);
uni_idx := 0;
if (Length(ch)>8) or (Length(ch)<=2) then //need at least U+1234 four chars
raise EUnihanParsingException.CreateFmt(eInvalidCharHexCode, [ch]);
for i := 3 to Length(ch) do
uni_idx := uni_idx shl 4 + HexCharCode(ch[i]);
if uni_idx<=$FFFF then
Result := WideChar(Word(uni_idx))
else
if uni_idx>$10FFFF then
raise EUnihanParsingException.CreateFmt(eInvalidCharHexCode, [ch])
else begin
uni_idx := uni_idx - $10000; //max $FFFFF remains
Result :=
WideChar(Word($D800+(uni_idx and $FFC00) shr 10)) //base + top ten bits = lead surrogate
+ WideChar(Word($DC00+(uni_idx and $003FF))); //base + low ten bits = trail surrogate
end;
end;
{ Do not pass empty or comment lines }
procedure ParseUnihanLine(const s: UnicodeString; ed: PUnihanPropertyEntry);
var i_next: integer;
val, tmp: string;
begin
val := s;
if val[1]<>'U' then
raise EUnihanParsingException.Create(eNoCharHexCode);
ed.Reset;
i_next := pos(#09, val);
if i_next<0 then
raise EUnihanParsingException.Create(eNoPropertyName);
tmp := copy(val,1,i_next-1);
ed.char := DecodeUplusChar(tmp);
if Length(ed.char)<=0 then
raise EUnihanParsingException.CreateFmt(eInvalidCharHexCode, [tmp]);
delete(val,1,i_next);
i_next := pos(#09, val);
if i_next<0 then
raise EUnihanParsingException.Create(eNoPropertyValue);
ed.propType := copy(val, 1, i_next-1);
ed.value := copy(val, i_next+1, MaxInt);
end;
{ Used in most properties in Unihan_Variants.txt
Ex.: U+70AE<kMeyerWempe U+7832<kLau,kMatthews,kMeyerWempe U+791F<kLau,kMatthews }
procedure ParseVariantProperty(const s: UnicodeString; out variants: TVariantValues);
var tmp, part, src: UnicodeString;
i_sp: integer;
new_v: TVariantValue;
begin
SetLength(Variants,0);
tmp := s;
i_sp := pos(' ', tmp);
while (i_sp>0) or (tmp<>'') do begin
if i_sp>0 then begin
part := copy(tmp,1,i_sp-1);
delete(tmp,1,i_sp);
end else begin //last part
part := tmp;
tmp := '';
end;
i_sp := pos('<', part);
if i_sp<=0 then begin
new_v.char := DecodeUplusChar(part);
part := '';
end else begin
new_v.char := DecodeUplusChar(copy(part,1,i_sp-1));
delete(part,1,i_sp);
end;
SetLength(new_v.sources, 0);
i_sp := pos(',',part);
while (i_sp>0) or (part<>'') do begin
if i_sp>0 then begin
src := copy(part,1,i_sp-1);
delete(part,1,i_sp);
end else begin //last part
src := part;
part := '';
end;
SetLength(new_v.sources, Length(new_v.sources)+1);
new_v.sources[Length(new_v.sources)-1] := src;
i_sp := pos(',',part);
end;
SetLength(variants, Length(variants)+1);
variants[Length(variants)-1] := new_v;
variants[Length(variants)-1].sources := copy(new_v.sources);
i_sp := pos(' ', tmp);
end;
end;
{
Radicals are stored in radical['][.stroke_count]['] format, where
stroke_count is the number of strokes not counting the radical.
' is used to indicated that "the character uses a standard simplification"
}
function RadicalOf(const radval: string): string;
var i: integer;
begin
i := pos('.', radval);
if i<=0 then
Result := radval
else
Result := copy(radval,1,i-1);
if (Length(Result)>0) and (Result[Length(Result)]='''') then
SetLength(Result, Length(Result)-1);
end;
function StrokeCountOf(const radval: string): string;
var i: integer;
begin
i := pos('.', radval);
if i<=0 then
Result := ''
else
Result := copy(radval,i+1,MaxInt);
if (Length(Result)>0) and (Result[Length(Result)]='''') then
SetLength(Result, Length(Result)-1);
end;
end.
|
unit abWinsock;
interface
uses Windows, Winsock;
type
TClientSocket = class(TObject)
private
FAddress: PChar;
FData: Pointer;
FTag: Integer;
FConnected: Boolean;
protected
FSocket: TSocket;
public
property Connected: Boolean read FConnected;
property Data: Pointer read FData write FData;
property Socket: TSocket read FSocket;
property Tag: integer read FTag write FTag;
procedure Connect(Address: string; Port: Integer);
destructor Destroy; override;
procedure Disconnect();
function ReceiveBuffer(var Buffer; BufferSize: Integer): Integer;
function ReceiveLength(): Integer;
function ReceiveString(): String;
function SendBuffer(var Buffer; BufferSize: Integer): Integer;
function SendString(const Buffer: String): Integer;
end;
var
WSAData: TWSAData;
implementation
procedure TClientSocket.Connect(Address: String; Port: Integer);
var
SockAddrIn: TSockAddrIn;
HostEnt: PHostEnt;
begin
Disconnect;
FAddress := pchar(Address);
FSocket := Winsock.socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
SockAddrIn.sin_family := AF_INET;
SockAddrIn.sin_port := htons(Port);
SockAddrIn.sin_addr.s_addr := inet_addr(FAddress);
if SockAddrIn.sin_addr.s_addr = INADDR_NONE then
begin
HostEnt := gethostbyname(FAddress);
if HostEnt = nil then
begin
Exit;
end;
SockAddrIn.sin_addr.s_addr := Longint(PLongint(HostEnt^.h_addr_list^)^);
end;
Winsock.Connect(FSocket, SockAddrIn, SizeOf(SockAddrIn));
FConnected := True;
end;
procedure TClientSocket.Disconnect();
begin
closesocket(FSocket);
FConnected := False;
end;
function TClientSocket.ReceiveLength(): Integer;
begin
Result := ReceiveBuffer(Pointer(nil)^, -1);
end;
function TClientSocket.ReceiveBuffer(var Buffer; BufferSize: Integer): Integer;
begin
if BufferSize = -1 then
begin
if ioctlsocket(FSocket, FIONREAD, Longint(Result)) = SOCKET_ERROR then
begin
Result := SOCKET_ERROR;
Disconnect;
end;
end
else
begin
Result := recv(FSocket, Buffer, BufferSize, 0);
if Result = 0 then
begin
Disconnect;
end;
if Result = SOCKET_ERROR then
begin
Result := WSAGetLastError;
if Result = WSAEWOULDBLOCK then
begin
Result := 0;
end
else
begin
Disconnect;
end;
end;
end;
end;
function TClientSocket.ReceiveString(): String;
begin
SetLength(Result, ReceiveBuffer(Pointer(nil)^, -1));
SetLength(Result, ReceiveBuffer(Pointer(Result)^, Length(Result)));
end;
function TClientSocket.SendBuffer(var Buffer; BufferSize: Integer): Integer;
var
ErrorCode: Integer;
begin
Result := send(FSocket, Buffer, BufferSize, 0);
if Result = SOCKET_ERROR then
begin
ErrorCode := WSAGetLastError;
if (ErrorCode = WSAEWOULDBLOCK) then
begin
Result := -1;
end
else
begin
Disconnect;
end;
end;
end;
function TClientSocket.SendString(const Buffer: String): Integer;
begin
Result := SendBuffer(Pointer(Buffer)^, Length(Buffer));
end;
destructor TClientSocket.Destroy;
begin
inherited Destroy;
Disconnect;
end;
initialization
WSAStartUp(257, WSAData);
finalization
WSACleanup;
end.
|
unit XLSClassFactory5;
interface
uses Classes, SysUtils;
type TXLSClassFactoryType = (xcftNames,xcftNamesMember,
xcftMergedCells,xcftMergedCellsMember,
xcftHyperlinks,xcftHyperlinksMember,
xcftDataValidations,xcftDataValidationsMember,
xcftConditionalFormat,xcftConditionalFormats,
xcftAutofilter,xcftAutofilterColumn,
xcftDrawing);
type TXLSClassFactory = class(TObject)
protected
public
function CreateAClass(AClassType: TXLSClassFactoryType; AOwner: TObject = Nil): TObject; virtual; abstract;
// function GetAClass(AClassType: TXLSClassFactoryType): TObject; virtual; abstract;
end;
implementation
end.
|
unit UPicFun;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ExtDlgs, jpeg;
procedure CombinBmp(BmpFilNames: Tstrings; MType: string;
var Desbmp: Tbitmap);overload;
procedure CombinBmp(BmpFilNames: Tstrings; HNum: integer;ZNum:integer;
var Desbmp: Tbitmap);overload;
FUNCTION LoadGraphicsFile(CONST Filename: STRING): TBitmap;
procedure GetLocalPic(FileName:String;EndX,EndY:integer;StX:integer;StY:integer;var Bmp:TBitmap);
procedure Bmp2Jpg(Bmp: TBitmap; Quality: Integer;var Jpg:TJpegImage) ;
function DuFenMiao_To_Miao( aDuFenMiao:string ): double;
function Miao_To_DuFenMiao( i_Miao:double; aDu_Sp:String='-'; aFen_Sp:String='-'; aMiao_Sp:String='' ):string;
procedure bmpSaveasJpg(Tmpbmp:Tbitmap;FilePath:String);
procedure CombinPic(ZNum,HNum:integer;StJd,StWd,DeltJd,DeltWd:string;Filepath,SavePath:String;IsGoOn:Boolean=true);
implementation
uses COMMON_FUNC;
procedure CombinBmp(BmpFilNames: Tstrings; MType: string;
var Desbmp: Tbitmap);
var
i:integer;
G_Imag : TBitmap;
Mwidth,Mheight:integer;
aImgWid,aImgHei:array of integer;
begin
G_Imag:= TBitmap.Create;
Mwidth:=0;
MHeight := 0;
try
setlength(aImgWid,BmpFilNames.Count);
setlength(aImgHei,BmpFilNames.Count);
for i:=0 to BmpFilNames.Count-1 do
begin
G_Imag:=LoadGraphicsFile(BmpFilNames.Strings[i]);
aImgWid[i]:=G_Imag.width;
aImgHei[i]:=G_Imag.height;
if MType ='横排' then
begin
if G_Imag.Height>MHeight then MHeight := G_Imag.Height;
Mwidth:=G_Imag.Width+Mwidth;
end;
if MType ='竖排' then
begin
if G_Imag.Width>Mwidth then Mwidth := G_Imag.Width;
MHeight:=G_Imag.Height+MHeight;
end;
if MType ='四方' then
begin
end;
end;
Desbmp.Width := Mwidth;
Desbmp.Height:= MHeight;
for i:=0 to BmpFilNames.Count-1 do
begin
G_Imag:=LoadGraphicsFile(BmpFilNames.Strings[i]);
if MType ='横排' then
begin
if i=0 then
Desbmp.Canvas.CopyRect(
Rect(0,0,G_Imag.Width,MHeight),G_Imag.Canvas,
Rect(0,0,G_Imag.Width,G_Imag.Height))
else
Desbmp.Canvas.CopyRect(
Rect(aImgWid[i-1],0,Mwidth,MHeight),G_Imag.Canvas,
Rect(0,0,G_Imag.Width,G_Imag.Height));
end;
if MType ='竖排' then
begin
if i=0 then
Desbmp.Canvas.CopyRect(
Rect(0,0,Mwidth,G_Imag.Height),G_Imag.Canvas,
Rect(0,0,G_Imag.Width,G_Imag.Height))
else
Desbmp.Canvas.CopyRect(
Rect(0,aImgHei[i-1],Mwidth,MHeight),G_Imag.Canvas,
Rect(0,0,G_Imag.Width,G_Imag.Height));
end;
end;
finally
G_Imag.Free;
end;
end;
procedure CombinBmp(BmpFilNames: Tstrings; HNum: integer;ZNum:integer;
var Desbmp: Tbitmap);overload;
begin
end;
//------------------------------------------------------------------------------
//功能:装入图片文件
//------------------------------------------------------------------------------
FUNCTION LoadGraphicsFile(CONST Filename: STRING): TBitmap;
VAR
Extension: STRING;
{$IFDEF GIF}
GIFImage : TGIFImage;
{$ENDIF}
Icon : TIcon;
JPEGImage: TJPEGImage;
Metafile : TMetafile;
BEGIN
RESULT := NIL; // In case anything goes wrong
IF FileExists(Filename)
THEN BEGIN
// Extension := UpperCase(ExtractFileExt(Filename));
Extension := UpperCase( COPY(Filename, LENGTH(Filename)-2, 3) );
// Quick and dirty check that file type is OK
ASSERT( (Extension = 'BMP') OR
(Extension = 'EMF') OR
{$IFDEF GIF}
(Extension = 'GIF') OR
{$ENDIF}
(Extension = 'ICO') OR
(Extension = 'JPG') OR
(Extension = 'WMF') );
RESULT := TBitmap.Create;
// BMP File -- no additional work to get TBitmap
IF Extension = 'BMP'
THEN RESULT.LoadFromFile(Filename);
{$IFDEF GIF}
// GIF File
IF Extension = 'GIF'
THEN BEGIN
GIFImage := TGIFImage.Create;
TRY
GIFImage.LoadFromFile(Filename);
RESULT.Height := GIFImage.Height;
RESULT.Width := GIFImage.Width;
RESULT.PixelFormat := pf24bit;
RESULT.Canvas.Draw(0,0, GIFImage)
FINALLY
GIFImage.Free
END
END;
{$ENDIF}
// ICO File
IF Extension = 'ICO'
THEN BEGIN
Icon := TIcon.Create;
TRY
TRY
Icon.LoadFromFile(Filename);
RESULT.Height := Icon.Height;
RESULT.Width := Icon.Width;
RESULT.PixelFormat := pf24bit; // avoid palette problems
RESULT.Canvas.Draw(0,0, Icon)
EXCEPT
// Ignore problem icons, e.g., Stream read errors
END;
FINALLY
Icon.Free
END
END;
// JPG File
IF Extension = 'JPG'
THEN BEGIN
JPEGImage := TJPEGImage.Create;
TRY
JPEGImage.LoadFromFile(Filename);
RESULT.Height := JPEGImage.Height;
RESULT.Width := JPEGImage.Width;
RESULT.PixelFormat := pf24bit;
RESULT.Canvas.Draw(0,0, JPEGImage)
FINALLY
JPEGImage.Free
END
END;
// Windows Metafiles, WMF or EMF
IF (Extension = 'WMF') OR
(Extension = 'EMF')
THEN BEGIN
Metafile := TMetafile.Create;
TRY
Metafile.LoadFromFile(Filename);
RESULT.Height := Metafile.Height;
RESULT.Width := Metafile.Width;
RESULT.PixelFormat := pf24bit; // avoid palette problems
RESULT.Canvas.Draw(0,0, Metafile)
FINALLY
Metafile.Free
END
END;
END;
// If Graphic is missing or invalid, create the "Red X"
IF RESULT = NIL
THEN BEGIN
RESULT := TBitmap.Create;
RESULT.Height := 32;
RESULT.Width := 32;
RESULT.PixelFormat := pf24bit;
WITH RESULT.Canvas DO BEGIN
Pen.Color := clRed;
Pen.Width := 3;
MoveTo( 2, 2);
LineTo(29,29);
MoveTo( 2,29);
LineTo(29, 2);
END
END
END {LoadGraphicFile};
procedure GetLocalPic(FileName:String;EndX,EndY:integer;StX:integer;StY:integer;var Bmp:TBitmap);
Var
SrPic:Tbitmap;
begin
try
if FileName='' then exit;
bmp.Height :=EndY-StY;
bmp.Width :=EndX-StX;
SrPic:=Tbitmap.Create;
try
SrPic :=LoadGraphicsFile(FileName);
bmp.Canvas.CopyRect(
Rect(StX,Sty,EndX,EndY),SrPic.Canvas,
Rect(StX,Sty,EndX,EndY));
finally
SrPic.Free;
end;
//Showmessage(IntToStr(result.Width));
except
on e:Exception do raise exception.Create('GetLocalPic出错!'+e.Message);
end;
end;
procedure Bmp2Jpg(Bmp: TBitmap; Quality: Integer;var Jpg:TJpegImage) ;
begin
if Assigned(Bmp)
then begin
Jpg.Assign(Bmp); {Its all folks...}
Jpg.CompressionQuality := Quality;
Jpg.JPEGNeeded; {Key method...}
Jpg.Compress;
end;
end;
function DuFenMiao_To_Miao( aDuFenMiao:string ): double;
var
aDu : double ;
aFen : double ;
aMiao :double;
begin
//36-42-49.2
aDu := StrToFloat( NamedItem( 0, aDuFenMiao, '-' ) )*3600 ;
aFen := StrToFloat( NamedItem( 1, aDuFenMiao, '-' ) )*60;
aMiao := StrToFloat( NamedItem( 2, aDuFenMiao, '-' ) );
result:= aDu+aFen+aMiao ;
end;
function Miao_To_DuFenMiao( i_Miao:double; aDu_Sp:String='-'; aFen_Sp:String='-'; aMiao_Sp:String='' ):string;
var
aMiao_Int,aDu,aFen_Int,aMiao,aFen:integer;
aRes:double;
aMiao_Text: String;
begin
aMiao_Int := trunc(i_Miao);
aRes := i_Miao - aMiao_Int;
aDu := trunc( aMiao_Int/ 3600 );
aFen_Int := aMiao_Int mod 3600 ;
aFen := trunc( aFen_Int/60 );
aMiao := aFen_Int mod 60 ;
aMiao_Text := Format( '%4.2f',[aMiao+aRes] );
//FloatToStr(double(aMiao)+aRes)
result:= ( IntToStr(aDu)+aDu_Sp+IntToStr(aFen)+aFen_Sp+ aMiao_Text+aMiao_Sp);
//36-42-49.2
end;
procedure bmpSaveasJpg(Tmpbmp:Tbitmap;FilePath:String);
var
JPEGImage : TJPEGImage;
begin
JPEGImage := TJPEGImage.Create;
try
Bmp2Jpg(Tmpbmp,50,JPEGImage);
if not directoryexists(ExtractFileDir(filePath)) then Mkdir(ExtractFileDir(filePath));
JPEGImage.SaveToFile(FilePath);
finally
JPEGImage.Free;
end;
end;
procedure CombinPic(ZNum,HNum:integer;StJd,StWd,DeltJd,DeltWd:string;Filepath,SavePath:String;IsGoOn:Boolean=true);
var
i,j:integer;
PicFileNames:Tstrings;
FileName,WdStr,JdStr:String;
nbmp : TBitmap;
errorfile:Tstrings;
begin
PicFileNames:=Tstringlist.Create;
errorfile:=Tstringlist.Create;
nbmp:= TBitmap.Create;
try
PicFileNames.Clear;
for i:=0 to HNum-1 do
begin
for j:=0 to ZNum-1 do
begin
if not IsGoOn then exit;
application.ProcessMessages;
if DirectoryExists(Filepath) then
begin
JdStr :=Miao_To_DuFenMiao(DuFenMiao_To_Miao(StJd)+j*strtofloat(DeltJd));
WdStr :=Miao_To_DuFenMiao(DuFenMiao_To_Miao(StWd)+i*strtofloat(DeltWd));
FileName:=Filepath+'\'+WdStr+'N,'+JdStr+'W.jpg';
if fileexists(fileName) then
begin
PicFileNames.Add(FileName);
end
else
errorfile.Add(filename);
end;//if DirectoryExists
end;//for j:=0...
end;//for i:=0...
if PicFileNames.Count<=0 then
begin
showmessage('无可处理图片!');
exit;
end;
CombinBmp(PicFileNames,HNum,ZNum, nbmp);
bmpSaveasJpg(nbmp,SavePath+'\'+GetFileName_NoExt(ExtractFileName(PicFileNames.Strings[0]))+IntToStr(HNum)+'&'+IntTOStr(ZNum)+'.jpg');
if errorfile.Count>0 then
errorfile.SaveToFile(SavePath+'\'+StJd+'W'+StWd+'N'+'errorfilenames.txt');
finally
PicFileNames.Free;
errorfile.Free;
nbmp.Free;
end;
end;
end.
|
unit FMX.Barcode.DROID;
// based on Brian Long work around Activities (http://blong.com)
// will use the zxing app installed in the device to scan
// for more info see https://github.com/zxing/zxing/wiki/Scanning-Via-Intent
interface
uses
System.Classes,
System.SysUtils,
System.Messaging
{$IFDEF ANDROID}
, FMX.Helpers.Android
, Androidapi.Helpers
, Androidapi.JNIBridge
, Androidapi.JNI.JavaTypes
, Androidapi.JNI.GraphicsContentViewText
, Androidapi.JNI.App
, Androidapi.JNI.Net
, Androidapi.JNI.Toast
{$ENDIF}
;
const ScanRequestCode: Integer = 0;
{$IFDEF ANDROID}
type
TFMXBarcodeGetResult = procedure(Sender: TObject; AResult: String) of object;
TFMXBarcode = class(TComponent)
private
FOnGetResult: TFMXBarcodeGetResult;
FMessageSubscriptionID: Integer;
function LaunchActivityForResult(const Intent: JIntent;
RequestCode: Integer): Boolean;
procedure HandleActivityMessage(const Sender: TObject; const M: TMessage);
function DoActivityResult(RequestCode, ResultCode: Integer;
Data: JIntent): Boolean;
procedure InternalLaunchQRScanner(RequestCode: Integer;
bQRCode: Boolean = False);
public
procedure Show(bQRCode: Boolean = False);
property OnGetResult: TFMXBarcodeGetResult read FOnGetResult
write FOnGetResult;
end;
{$ENDIF}
implementation
{ TBarcodeDROID }
{$IFDEF ANDROID}
procedure TFMXBarcode.HandleActivityMessage(const Sender: TObject;
const M: TMessage);
begin
if M is TMessageResultNotification then
DoActivityResult(TMessageResultNotification(M).RequestCode, TMessageResultNotification(M).ResultCode,
TMessageResultNotification(M).Value);
end;
function TFMXBarcode.LaunchActivityForResult(const Intent: JIntent;
RequestCode: Integer): Boolean;
var
ResolveInfo: JResolveInfo;
begin
ResolveInfo := TAndroidHelper.Activity.getPackageManager.resolveActivity(Intent, 0);
Result := ResolveInfo <> nil;
if Result then
TAndroidHelper.Activity.startActivityForResult(Intent, RequestCode);
end;
procedure TFMXBarcode.InternalLaunchQRScanner(RequestCode: Integer;
bQRCode: Boolean = False);
var
Intent: JIntent;
begin
Intent := TJIntent.JavaClass.init
(StringToJString('com.google.zxing.client.android.SCAN'));
Intent.setPackage(StringToJString('com.google.zxing.client.android'));
if bQRCode then
Intent.putExtra(StringToJString('SCAN_MODE'),
StringToJString('QR_CODE_MODE'));
if not LaunchActivityForResult(Intent, RequestCode) then
Toast('Cannot display QR scanner', ShortToast);
end;
function TFMXBarcode.DoActivityResult(RequestCode, ResultCode: Integer;
Data: JIntent): Boolean;
var
ScanContent, ScanFormat: string;
begin
Result := False;
TMessageManager.DefaultManager.Unsubscribe(TMessageResultNotification,
FMessageSubscriptionID);
FMessageSubscriptionID := 0;
if RequestCode = ScanRequestCode then
begin
if ResultCode = TJActivity.JavaClass.RESULT_OK then
begin
if Assigned(Data) then
begin
ScanContent := JStringToString
(Data.getStringExtra(StringToJString('SCAN_RESULT')));
ScanFormat := JStringToString
(Data.getStringExtra(StringToJString('SCAN_RESULT_FORMAT')));
OnGetResult(Self, ScanContent);
end;
end
else if ResultCode = TJActivity.JavaClass.RESULT_CANCELED then
begin
Toast('You cancelled the scan', ShortToast);
OnGetResult(Self, '');
end;
Result := True;
end;
end;
procedure TFMXBarcode.Show(bQRCode: boolean);
begin
FMessageSubscriptionID := TMessageManager.DefaultManager.SubscribeToMessage
(TMessageResultNotification, HandleActivityMessage);
InternalLaunchQRScanner(ScanRequestCode, bQRCode);
end;
{$ENDIF}
end.
|
program TimerTest;
uses sgTypes, sgTimers, sgUtils;
procedure Main();
var
time1, time2 : LongWord;
tmr : Timer;
begin
WriteLn('Testing Timer...');
time1 := GetTicks();
Delay(1000);
time2 := GetTicks();
WriteLn('complete... Should have taken ~1000, took: ', time2 - time1 );
WriteLn();
WriteLn('Creating Timer...');
tmr := CreateTimer('MyTimer');
if not Assigned(tmr) then WriteLn('Timer was not assigned!');
StartTimer(tmr);
Delay(1000);
WriteLn('part way at: ', TimerTicks(tmr));
Delay(1000);
PauseTimer(tmr);
WriteLn('complete... Should have taken ~2000, took: ', TimerTicks(tmr));
Delay(1000);
WriteLn('test resume');
ResumeTimer(tmr);
Delay(1000);
PauseTimer(tmr);
WriteLn('complete... Should have taken ~3000, took: ', TimerTicks(tmr));
WriteLn('reset...');
ResetTimer(tmr);
WriteLn('time is now: ', TimerTicks('MyTimer'));
ResumeTimer(tmr);
Delay(1000);
WriteLn('part way at: ', TimerTicks('MyTimer'));
Delay(1000);
PauseTimer('MyTimer');
WriteLn('complete... Should have taken ~2000, took: ', TimerTicks(tmr));
WriteLn('restarting...');
ResetTimer('MyTimer');
WriteLn('done');
end;
begin
Main();
end. |
unit ufrmDialogTipePerusahaan;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls,
StdCtrls, uRetnoUnit, uModTipePerusahaan, ufraFooterDialog3Button,
uDMClient, uAppUtils, System.Actions, Vcl.ActnList, uInterface;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogTipePerusahaan = class(TfrmMasterDialog, ICRUDAble)
lbl1: TLabel;
edtCode: TEdit;
Lbl2: TLabel;
edtName: TEdit;
procedure actDeleteExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FIsProcessSuccessfull: boolean;
FTipePerusahaanId: Integer;
FFormMode: TFormMode;
FModTipePerusahaan: TModTipePerusahaan;
// FPerusahaan : TnewTipePerusahaan;
IDLokal : Integer;
function GetModTipePerusahaan: TModTipePerusahaan;
procedure SetFormMode(const Value: TFormMode);
procedure SetIsProcessSuccessfull(const Value: Boolean);
procedure SetTipePerusahaanId(const Value: Integer);
procedure prepareAddData;
procedure SimpanData;
property ModTipePerusahaan: TModTipePerusahaan read GetModTipePerusahaan write
FModTipePerusahaan;
public
procedure LoadData(aID: string);
{ Public declarations }
published
property FormMode: TFormMode read FFormMode write SetFormMode;
property TipePerusahaanId: Integer read FTipePerusahaanId write SetTipePerusahaanId;
property IsProcessSuccessfull: Boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull;
end;
var
frmDialogTipePerusahaan: TfrmDialogTipePerusahaan;
implementation
uses uTSCommonDlg, uConn, uDXUtils;
{$R *.dfm}
procedure TfrmDialogTipePerusahaan.actDeleteExecute(Sender: TObject);
begin
inherited;
if ModTipePerusahaan.ID = '' then exit;
if TAppUtils.Confirm('Anda Yakin Hapus Data?') = False then exit;
try
DMClient.CrudClient.DeleteFromDB(ModTipePerusahaan);
TAppUtils.Information('Data Berhasil Dihapus');
Self.ModalResult:=mrOk;
except
TAppUtils.Error('Gagal Hapus Data');
raise
end;
end;
procedure TfrmDialogTipePerusahaan.actSaveExecute(Sender: TObject);
begin
inherited;
SimpanData;
end;
procedure TfrmDialogTipePerusahaan.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogTipePerusahaan := nil;
end;
procedure TfrmDialogTipePerusahaan.SetFormMode(const Value: TFormMode);
begin
FFormMode := Value;
end;
procedure TfrmDialogTipePerusahaan.SetIsProcessSuccessfull(const Value: boolean);
begin
FIsProcessSuccessfull := Value;
end;
procedure TfrmDialogTipePerusahaan.SetTipePerusahaanId(const Value: Integer);
begin
FTipePerusahaanId := Value;
end;
procedure TfrmDialogTipePerusahaan.prepareAddData;
begin
edtCode.Clear;
edtName.Clear;
end;
procedure TfrmDialogTipePerusahaan.FormShow(Sender: TObject);
begin
inherited;
if (FFormMode = fmEdit) then
begin
{
IDLokal := StrToInt(frmTipePerusahaan.strgGrid.Cells[2,frmTipePerusahaan.strgGrid.row]);
if FPerusahaan.LoadByID(IDLokal,DialogUnit) then
begin
edtCode.Text := FPerusahaan.Kode;
edtName.Text := FPerusahaan.Nama;
end;}
// showDataEdit(TipePerusahaanId)
end else
prepareAddData();
end;
procedure TfrmDialogTipePerusahaan.FormCreate(Sender: TObject);
begin
inherited;
self.AssignKeyDownEvent;
// FPerusahaan := TnewTipePerusahaan.Create(Self);
end;
function TfrmDialogTipePerusahaan.GetModTipePerusahaan: TModTipePerusahaan;
begin
if not assigned(FModTipePerusahaan) then
FModTipePerusahaan := TModTipePerusahaan.Create;
Result := FModTipePerusahaan;
end;
procedure TfrmDialogTipePerusahaan.LoadData(aID: string);
begin
ModTipePerusahaan := DmClient.CrudClient.Retrieve(TModTipePerusahaan.ClassName, aID) as TModTipePerusahaan;
edtCode.Text := ModTipePerusahaan.TPPERSH_CODE;
edtName.Text := ModTipePerusahaan.TPPERSH_NAME;
end;
procedure TfrmDialogTipePerusahaan.SimpanData;
begin
if not ValidateEmptyCtrl then exit;
ModTipePerusahaan.TPPERSH_CODE := edtCode.Text;
ModTipePerusahaan.TPPERSH_NAME := edtName.Text;
try
DMClient.CrudClient.SaveToDB(ModTipePerusahaan);
TAppUtils.Information('Data Berhasil Disimpan');
Self.ModalResult:=mrOk;
except
TAppUtils.Error('Gagal Simpan Data');
raise
end;
end;
end.
|
unit OTFE_U;
// Description: Abstract base class for OTF Encryption systems
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
{$M+} //enable rtti
// -----------------------------------------------------------------------------
interface
// -----------------------------------------------------------------------------
uses
classes,
Windows, // Needed for UINT, ULONG
sysUtils,
//sdu
sdugeneral,
OTFEConsts_U;
// -----------------------------------------------------------------------------
const
VERSION_ID_FAILURE = $FFFFFFFF;
// -- begin Windows standard bits taken from "dbt.h", not included with Delphi --
const
DBT_DEVICEARRIVAL = $8000; // System detected a new device
DBT_DEVICEREMOVEPENDING = $8003; // About to remove, still available
DBT_DEVICEREMOVECOMPLETE = $8004; // Device has been removed
DBT_DEVNODES_CHANGED = $0007; // Some added or removed - update yourself
DBT_DEVTYP_VOLUME = $00000002; // logical volume
type
DEV_BROADCAST_HDR = packed record
dbch_size: ULONG;
dbch_devicetype: ULONG;
dbch_reserved: ULONG;
end;
PDEV_BROADCAST_HDR = ^DEV_BROADCAST_HDR;
DEV_BROADCAST_VOLUME = packed record
dbch_size: ULONG;
dbch_devicetype: ULONG;
dbch_reserved: ULONG;
dbcv_unitmask: ULONG;
dbcv_flags: WORD; // USHORT
dummy: WORD; // Padding to word boundry
end;
PDEV_BROADCAST_VOLUME = ^DEV_BROADCAST_VOLUME;
// -- end Windows standard bits taken from "dbt.h", not included with Delphi --
// -----------------------------------------------------------------------------
type
TOTFE = class(TObject)
private
{ private declarations here}
protected
FActive: boolean;
FLastErrCode: integer; // See OTFEConsts_U.pas
procedure DestroyString(var theString: string);
procedure DestroyTStringList(theTStringList: TStringList);
function SortString(theString: Ansistring): Ansistring;
// Set the component active/inactive
// Note: Must raise exception if status is set to TRUE, but the component
// cannot be set to this state
procedure SetActive(status: Boolean); virtual;
// Raises exception if the component isn't active
procedure CheckActive();
// Broadcast a message, notifying everyone that a drive has been
// added/removed
// addedNotRemoved - Set to TRUE to broadcast that the specified drive
// letter has just been added, or FALSE to broadcast it's
// removal
procedure BroadcastDriveChangeMessage(addedNotRemoved: boolean; driveLetter: char); overload;
// devChangeEvent - Set to DBT_DEVICEREMOVEPENDING/DBT_DEVICEREMOVECOMPLETE/DBT_DEVICEARRIVAL
procedure BroadcastDriveChangeMessage(devChangeEvent: cardinal; driveLetter: char); overload;
public
constructor Create; reintroduce; virtual;
destructor Destroy(); override;
// === Mounting, dismounting drives ========================================
// Prompt the user for a password (and drive letter if necessary), then
// mount the specified volume file
// Returns the drive letter of the mounted volume on success, #0 on failure
function Mount(volumeFilename: ansistring; readonly: boolean = FALSE): char; overload; virtual; abstract;
// As previous Mount, but more than one volumes is specified. Volumes are
// mounted using the same password
// Sets mountedAs to the drive letters of the mounted volumes, in order.
// Volumes that could not be mounted have #0 as their drive letter
// Returns TRUE if any of the volumes mounted correctly, otherwise FALSE
function Mount(volumeFilenames: TStringList; var mountedAs: DriveLetterString; readonly: boolean = FALSE): boolean; overload; virtual; abstract;
// Example:
// Set:
// volumeFilenames[0] = c:\test0.dat
// volumeFilenames[1] = c:\test1.dat
// volumeFilenames[2] = c:\test2.dat
// Call Mount described above in which:
// volume test0.dat was sucessfully mounted as W:
// volume test1.dat failed to mount
// volume test2.dat was sucessfully mounted as X:
// Then this function should set:
// mountedAs = 'W.X' (where '.' is #0)
// Given the "mountedAs" parameter set by the above Mount(...) function,
// this will give a count of the number of volumes mounted successfully, and failed
procedure CountMountedResults(mountedAs: DriveLetterString; out CntMountedOK: integer; out CntMountFailed: integer); virtual;
// Prompt the user for a device (if appropriate) and password (and drive
// letter if necessary), then mount the device selected
// Returns the drive letter of the mounted devices on success, #0 on failure
function MountDevices(): DriveLetterString; virtual; abstract;
// Determine if OTFE component can mount devices.
// Returns TRUE if it can, otherwise FALSE
function CanMountDevice(): boolean; virtual; abstract;
// Work out the order in which to dismount drives, taking into account
// the potential for one drive to be mounted within another
// Returns "dismountDrives" in the order in which they should be dismounted
function DismountOrder(dismountDrives: DriveLetterString): DriveLetterString;
// Dismount by volume filename
// Returns TRUE on success, otherwise FALSE
function Dismount(volumeFilename: string; emergency: boolean = FALSE): boolean; overload; virtual; abstract;
// Dismount by drive letter
// Returns TRUE on success, otherwise FALSE
function Dismount(driveLetter: DriveLetterChar; emergency: boolean = FALSE): boolean; overload; virtual; abstract;
// Dismount all mounted drives
// Returns a string containing the drive letters for all drives that could
// not be dismounted
function DismountAll(emergency: boolean = FALSE): DriveLetterString; virtual;
// === Miscellaneous =======================================================
// Returns the human readable name of the OTFE product the component
// supports (e.g. "CrossCrypt", "ScramDisk")
// Returns '' on error
function Title(): string; overload; virtual; abstract;
// Returns TRUE if the underlying driver is installed and the component can
// be used, otherwise FALSE
function IsDriverInstalled(): boolean; overload; virtual;
// Returns version ID of underlying driver (VERSION_ID_FAILURE on error)
// (Returns cardinal and not string representation in order to facilitate
// processing of the version number by the calling function)
function Version(): cardinal; virtual; abstract;
// Returns version ID of underlying driver ('' on error)
function VersionStr(): string; virtual; abstract;
// Check version is at least "minVersion"
function CheckVersionAtLeast(minVersion: cardinal): boolean; virtual;
// Returns TRUE if the file specified appears to be an encrypted volume file
function IsEncryptedVolFile(volumeFilename: string): boolean; virtual; abstract;
// Returns a string containing the drive letters (in uppercase) of all
// mounted drives (e.g. 'DGH') in alphabetical order
function DrivesMounted(): DriveLetterString; virtual; abstract;
// Returns a count of drives mounted (included for completeness)
function CountDrivesMounted(): integer; virtual;
// Returns the volume filename for a given mounted drive
// (empty string on failure)
function GetVolFileForDrive(driveLetter: DriveLetterChar): string; virtual; abstract;
// Returns the drive letter for a mounted volume file
// (#0 on failure)
function GetDriveForVolFile(volumeFilename: string): DriveLetterChar; virtual; abstract;
// Check to see if there are any volume files mounted on the given drive
// Returns the drive letters of any mounted volumes
function VolsMountedOnDrive(driveLetter: DriveLetterChar): DriveLetterString; virtual;
// Test to see if the specified drive is readonly
// Returns TRUE if the drive is readonly, otherwise FALSE
function IsDriveReadonly(driveLetter: DriveLetterChar): boolean; virtual;
// Returns a string describing the last error
function GetLastErrorMsg(): string; virtual;
// Returns a string containing the main executable to the OTF crypto system
// (the one used mounting, if there's more than one executable)
// Returns "" on error
function GetMainExe(): string; virtual; abstract;
// Returns a disk-encryption specific record containing information on the
// specified encrypted drive
//
// (Can't represent in the base class, but...)
// function GetDriveInfo(driveLetter: char): TDiskInfo; virtual; abstract;
published
property Active: boolean read FActive write SetActive;
property LastErrorCode: integer read FLastErrCode write FLastErrCode default OTFE_ERR_SUCCESS;
end;
// Helper function to take a string containing driveletters, and generates a
// prettyprinted version
// e.g. DFGI -> D:, F:, G:, I:
// Any #0 characters in the string passed in will be ignored
function prettyPrintDriveLetters(driveLetters: DriveLetterString): string;
// Returns the number of characters in "driveLetters" which aren't #0
function CountValidDrives(driveLetters: DriveLetterString): integer;
// Change CWD to anywhere other than a mounted drive
// This must be done before any dismount, in case the user changed the CWD to a
// dir stored within the drive to be dismounted (e.g. by mounting another
// volume stored within that mounted drive - the mount dialog would change the
// CWD)
procedure ChangeCWDToSafeDir();
// -----------------------------------------------------------------------------
implementation
uses
ShlObj, // Needed for SHChangeNotify(...), etc
Messages // Needed for WM_DEVICECHANGE
;
// -----------------------------------------------------------------------------
function prettyPrintDriveLetters(driveLetters: DriveLetterString): string;
var
i: integer;
validLetters: string;
begin
Result := '';
validLetters := '';
for i:=1 to length(driveLetters) do
begin
if (driveLetters[i] <> #0) then
begin
validLetters := validLetters + driveLetters[i];
end;
end;
for i:=1 to length(validLetters) do
begin
if (Result <> '') then
begin
Result := Result + ', ';
end;
Result := Result + validLetters[i] + ':';
end;
end;
// -----------------------------------------------------------------------------
function CountValidDrives(driveLetters: DriveLetterString): integer;
var
i: integer;
begin
Result := 0;
for i:=1 to length(driveLetters) do
begin
if (driveLetters[i] <> #0) then
begin
inc(Result);
end;
end;
end;
// -----------------------------------------------------------------------------
procedure ChangeCWDToSafeDir();
var
windowsDir: string;
begin
windowsDir := SDUGetSpecialFolderPath(SDU_CSIDL_WINDOWS);
SDUSetCurrentWorkingDirectory(windowsDir);
end;
// -----------------------------------------------------------------------------
constructor TOTFE.Create;
begin
inherited;
FActive := FALSE;
FLastErrCode:= OTFE_ERR_SUCCESS;
end;
// -----------------------------------------------------------------------------
destructor TOTFE.Destroy();
begin
inherited;
end;
// -----------------------------------------------------------------------------
// Destroy the contents of the supplied TStringList
procedure TOTFE.DestroyTStringList(theTStringList: TStringList);
var
i: integer;
j: integer;
begin
randomize();
for i:=0 to (theTStringList.Count-1) do
begin
for j:=0 to length(theTStringList[i]) do
begin
theTStringList[i] := format('%'+inttostr(length(theTStringList[i]))+'s', [chr(random(255))]);
end;
end;
theTStringList.Clear();
end;
// -----------------------------------------------------------------------------
// Destroy the contents of the supplied string
procedure TOTFE.DestroyString(var theString: string);
var
i: integer;
begin
randomize();
for i:=0 to length(theString) do
begin
theString := format('%'+inttostr(length(theString))+'s', [chr(random(255))]);
end;
end;
// -----------------------------------------------------------------------------
// Returns a string describing the last error
// If no error, returns an empty string
function TOTFE.GetLastErrorMsg(): string;
begin
Result := ''; // OTFE_ERR_SUCCESS
case FLastErrCode of
// See OTFEConsts_U.pas for descriptions
OTFE_ERR_NOT_ACTIVE : Result := 'Component not active';
OTFE_ERR_DRIVER_FAILURE : Result := 'Driver failure';
OTFE_ERR_USER_CANCEL : Result := 'User cancelled operation';
OTFE_ERR_WRONG_PASSWORD : Result := 'Wrong Keyphrase entered';
OTFE_ERR_VOLUME_FILE_NOT_FOUND : Result := 'Container file not found';
OTFE_ERR_INVALID_DRIVE : Result := 'Invalid drive';
OTFE_ERR_MOUNT_FAILURE : Result := 'Mount failure';
OTFE_ERR_DISMOUNT_FAILURE : Result := 'Dismount failure';
OTFE_ERR_FILES_OPEN : Result := 'Files open in container';
OTFE_ERR_STREAMING_DATA : Result := 'Can''t dismount while still streaming data, or was doing so in the last few seconds';
OTFE_ERR_FILE_NOT_ENCRYPTED_VOLUME : Result := 'File is not an encrypted container';
OTFE_ERR_UNABLE_TO_LOCATE_FILE : Result := 'Unable to locate file';
OTFE_ERR_DISMOUNT_RECURSIVE : Result := 'Dismounting recursively mounted drive';
OTFE_ERR_INSUFFICENT_RIGHTS : Result := 'Insufficient rights';
OTFE_ERR_NOT_W9X : Result := 'Operation not available under Windows 95/98/ME';
OTFE_ERR_NOT_WNT : Result := 'Operation not available under Windows NT/2000';
OTFE_ERR_NO_FREE_DRIVE_LETTERS : Result := 'There are no free drive letters';
// BestCrypt
OTFE_ERR_UNKNOWN_ALGORITHM : Result := 'Unknown algorithm';
OTFE_ERR_UNKNOWN_KEYGEN : Result := 'Unknown key generator';
// ScramDisk
OTFE_ERR_UNABLE_MOUNT_COMPRESSED : Result := 'Can''t mount compressed container';
// PANIC!
OTFE_ERR_UNKNOWN_ERROR : Result := 'Unknown error';
end;
end;
// -----------------------------------------------------------------------------
// Returns the number of drives mounted
function TOTFE.CountDrivesMounted(): integer;
begin
FLastErrCode:= OTFE_ERR_SUCCESS;
Result := length(DrivesMounted());
end;
// -----------------------------------------------------------------------------
{ Dismounts all mounted drives
result is any drives that failed to unmount
}
function TOTFE.DismountAll(emergency: boolean = FALSE): DriveLetterString;
var
drvsMounted: DriveLetterString;
i: integer;
begin
FLastErrCode:= OTFE_ERR_SUCCESS;
drvsMounted := DrivesMounted();
Result := '';
// Dismount in correct order!
drvsMounted := DismountOrder(drvsMounted);
for i:=1 to length(drvsMounted) do begin
if not(Dismount(drvsMounted[i], emergency)) then begin
FLastErrCode:= OTFE_ERR_DISMOUNT_FAILURE;
Result := Result + drvsMounted[i];
end;
end;
end;
// -----------------------------------------------------------------------------
// Returns TRUE if the underlying driver is installed and the component can
// be used, otherwise FALSE
function TOTFE.IsDriverInstalled(): boolean;
begin
Result := TRUE;
FLastErrCode:= OTFE_ERR_SUCCESS;
if not(Active) then
begin
try
Active := TRUE;
except
end;
Result := Active;
Active := FALSE;
end;
if not(Result) then
begin
FLastErrCode:= OTFE_ERR_DRIVER_FAILURE;
end;
end;
// -----------------------------------------------------------------------------
// Check version is at least "minVersion"
function TOTFE.CheckVersionAtLeast(minVersion: cardinal): boolean;
begin
Result := (
(Version() <> VERSION_ID_FAILURE) and
(Version() >= minVersion)
);
end;
// -----------------------------------------------------------------------------
// Set the component active/inactive
// [IN] status - the status of the component
procedure TOTFE.SetActive(status: Boolean);
begin
FLastErrCode:= OTFE_ERR_SUCCESS;
FActive := status;
end;
// -----------------------------------------------------------------------------
// Sort the contents of a string into alphabetical order, assuming each char
// only appears once. and is all upper case
function TOTFE.SortString(theString: Ansistring): Ansistring;
var
output: Ansistring;
i: AnsiChar;
begin
output := '';
for i:='A' to 'Z' do
begin
if pos(i, theString)>0 then
begin
output := output + i;
end;
end;
Result := output;
end;
// Raises exception if the component isn't active
procedure TOTFE.CheckActive();
begin
FLastErrCode:= OTFE_ERR_SUCCESS;
if not(FActive) then begin
FLastErrCode := OTFE_ERR_NOT_ACTIVE;
raise EOTFEException.Create(OTFE_EXCPT_NOT_ACTIVE);
end;
end;
// -----------------------------------------------------------------------------
// Check to see if there are any volume files mounted on the given drive
// Returns the drive letters of any mounted volumes
function TOTFE.VolsMountedOnDrive(driveLetter: DriveLetterChar): DriveLetterString;
var
mountedDrives: DriveLetterString;
volFilename: string;
i: integer;
begin
Result := '';
driveLetter := upcase(driveLetter);
mountedDrives := DrivesMounted();
for i:=1 to length(mountedDrives) do
begin
volFilename := GetVolFileForDrive(mountedDrives[i]);
volFilename := uppercase(volFilename);
if (length(volFilename)>=3) then begin
if (volFilename[2]=':') and
(volFilename[3]='\') or (volFilename[3]='/') then begin
if (volFilename[1]=driveLetter) then begin
Result := Result + mountedDrives[i];
end;
end;
end;
end;
end;
// -----------------------------------------------------------------------------
// Work out the order in which to dismount drives, taking into account
// the potential for one drive to be mounted within another
// Returns "dismountDrives" in the order in which they should be dismounted
function TOTFE.DismountOrder(dismountDrives: DriveLetterString): DriveLetterString;
var
unorderedDrives: String;
unorderedDrivesHosts: string;
sortedDrives: String;
sortedDrivesHosts: string;
tmpDrives: String;
tmpDrivesHosts: string;
i: integer;
volFilename: string;
hostDrive: char;
begin
unorderedDrives := dismountDrives;
// Get all host drive letters for recursivly mounted drives
unorderedDrivesHosts := '';
for i:=1 to length(dismountDrives) do
begin
volFilename := GetVolFileForDrive(dismountDrives[i]);
volFilename := uppercase(volFilename);
hostDrive := #0;
if (length(volFilename)>=3) then
begin
if (volFilename[2]=':') and
(volFilename[3]='\') or (volFilename[3]='/') then
begin
hostDrive := char(volFilename[1]);
end;
end;
unorderedDrivesHosts := unorderedDrivesHosts + hostDrive;
end;
// NOTE: AT THIS STAGE, unorderedDrives and unorderedDrivesHosts are in the
// same order; unorderedDrivesHosts[X] is the host drive for
// unorderedDrives[X], with unorderedDrivesHosts[X] set to #0 if it's
// not hosted on a mounted drive
// Finally, get the drives into the order in which they should be dismounted
// in...
sortedDrives := '';
sortedDrivesHosts:= '';
while (length(unorderedDrives)>0) do
begin
tmpDrives := '';
tmpDrivesHosts:= '';
for i:=1 to length(unorderedDrives) do
begin
if ((Pos(unorderedDrivesHosts[i], dismountDrives)=0) or
(Pos(unorderedDrivesHosts[i], sortedDrives)>0)) then
begin
sortedDrives := unorderedDrives[i] + sortedDrives;
sortedDrivesHosts := unorderedDrivesHosts[i] + sortedDrivesHosts;
end
else
begin
tmpDrives := unorderedDrives[i] + tmpDrives;
tmpDrivesHosts := unorderedDrivesHosts[i] + tmpDrivesHosts;
end;
end;
unorderedDrives := tmpDrives;
unorderedDrivesHosts := tmpDrivesHosts;
end;
Result := sortedDrives;
end;
// -----------------------------------------------------------------------------
// devChangeEvent - Set to DBT_DEVICEREMOVEPENDING/DBT_DEVICEREMOVECOMPLETE/DBT_DEVICEARRIVAL
procedure TOTFE.BroadcastDriveChangeMessage(devChangeEvent: cardinal; driveLetter: char);
var
dbv: DEV_BROADCAST_VOLUME;
unitMask: ULONG;
i: ansichar;
ptrBroadcast: PByte;
dwRecipients: DWORD;
begin
ptrBroadcast := nil;
if (devChangeEvent <> DBT_DEVNODES_CHANGED) then begin
driveLetter := upcase(driveLetter);
unitMask := 1;
{ TODO -otdk -crefactor : conversion to ansi OK? }
{ TODO -otdk -cinvestigate : why a bit mask }
for i:='B' to AnsiChar(driveLetter) do begin
unitMask := unitMask shl 1;
end;
dbv.dbch_size := sizeof(dbv);
dbv.dbch_devicetype := DBT_DEVTYP_VOLUME;
dbv.dbch_reserved := 0;
dbv.dbcv_unitmask := unitMask;
dbv.dbcv_flags := 0;
ptrBroadcast := SysGetMem(sizeof(dbv));
Move(dbv, ptrBroadcast^, sizeof(dbv));
end;
try
{
// Don't use PostMessage(...) here!
// If we use PostMessage(...) on mounting, Windows explorer will show the new
// drive... And a second later, remove it from its display!
SendMessage(
HWND_BROADCAST,
WM_DEVICECHANGE,
devChangeEvent,
lParam
);
}
dwRecipients := BSM_APPLICATIONS;
BroadcastSystemMessage(
(
BSF_IGNORECURRENTTASK or
BSF_POSTMESSAGE or
BSF_FORCEIFHUNG
{
BSF_NOHANG
BSF_NOTIMEOUTIFNOTHUNG
}
),
@dwRecipients,
//BSM_ALLCOMPONENTS
WM_DEVICECHANGE,
devChangeEvent,
integer(ptrBroadcast)
);
finally
if (ptrBroadcast <> nil) then begin
SysFreeMem(ptrBroadcast);
end;
end;
// Sleep briefly to allow things to settle down
// Not needed now that using SysGetmem(...)/SysFreemem(...) instead of
// AllocMem(...)/<nothing!>
// sleep(500);
end;
// -----------------------------------------------------------------------------
procedure TOTFE.BroadcastDriveChangeMessage(addedNotRemoved: boolean; driveLetter: char);
var
wndWParam: cardinal;
drivePath: string;
ptrDrive: Pointer;
//UNICODE TEST - ptrDrive: PWideChar;
begin
driveLetter := upcase(driveLetter);
drivePath := driveLetter + ':\'+#0;
// +1 to include terminating NULL
ptrDrive := SysGetMem((length(drivePath) + 1));
//UNICODE TEST - ptrDrive := SysGetMem(((length(drivePath) + 1)*sizeof(WCHAR)));
try
StrMove(ptrDrive, PChar(drivePath), length(drivePath));
//UNICODE TEST - // Convert to UNICODE
//UNICODE TEST - StringToWideChar(drivePath, ptrDrive, (length(drivePath)+1));
if addedNotRemoved then
begin
wndWParam := DBT_DEVICEARRIVAL;
SHChangeNotify(SHCNE_DRIVEADD, SHCNF_PATH, ptrDrive, nil);
//UNICODE TEST - SHChangeNotify(SHCNE_DRIVEADD, SHCNF_PATHW, ptrDrive, nil);
// Update dir is required in order to get Explorer's treeview to
// correctly display the newly mounted volume's label and drive letter.
// Note: atm, we're setting this to the drive which has been added,
// though it looks like Windows actually sends a NULL/empty string
// here
//
// Amusing side note to the TrueCrypt developers: You've been missing
// this since TrueCrypt v3.1, and had this fault reported in your forums
// many times by different users over the years. It might be worth your
// adding something like this into TrueCrypt to resolve the problem? ;)
SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATH, ptrDrive, nil);
//UNICODE TEST - SHChangeNotify(SHCNE_UPDATEDIR, SHCNF_PATHW, ptrDrive, nil);
end
else
begin
wndWParam := DBT_DEVICEREMOVECOMPLETE;
SHChangeNotify(SHCNE_DRIVEREMOVED, SHCNF_PATH, ptrDrive, nil);
//UNICODE TEST - SHChangeNotify(SHCNE_DRIVEREMOVED, SHCNF_PATHW, ptrDrive, nil);
end;
finally
SysFreeMem(ptrDrive);
end;
BroadcastDriveChangeMessage(DBT_DEVNODES_CHANGED, driveLetter);
BroadcastDriveChangeMessage(wndWParam, driveLetter);
if addedNotRemoved then
begin
BroadcastDriveChangeMessage(DBT_DEVNODES_CHANGED, driveLetter);
end;
end;
// -----------------------------------------------------------------------------
// Test to see if the specified drive is readonly
// Returns TRUE if the drive is readonly, otherwise FALSE
function TOTFE.IsDriveReadonly(driveLetter: DriveLetterChar): boolean;
function GenerateRandomFilename(): string;
var
outputFilename: string;
i: integer;
begin
outputFilename := '';
for i:=1 to 20 do
begin
outputFilename := outputFilename + chr(ord('A')+random(26));
end;
Result := outputFilename;
end;
var
F: TextFile;
OldMode: UINT;
I: Integer;
rndFilename: string;
begin
Result := FALSE;
// This function has been tested, and works OK if the disk is full
// This function has been tested, and works OK if the root directory is full of
// files, and no more can be added
randomize();
rndFilename := driveLetter + ':\'+ GenerateRandomFilename();
while FileExists(rndFilename) do
begin
rndFilename := driveLetter + ':\'+ GenerateRandomFilename();
end;
OldMode := SetErrorMode(SEM_FAILCRITICALERRORS);
{$I-}
AssignFile(F, rndFilename); // File you want to write to here.
Rewrite(F);
{$I+}
I := IOResult;
SetErrorMode(OldMode);
if I <> 0 then
begin
Result := ((I AND $FFFFFFFF)=ERROR_WRITE_PROTECT);
end
else
begin
CloseFile(F);
SysUtils.DeleteFile(rndFilename);
end;
end;
// -----------------------------------------------------------------------------
// Given the "mountedAs" parameter set by the above Mount(...) function,
// this will give a count of the number of volumes mounted successfully, and failed
procedure TOTFE.CountMountedResults(mountedAs: DriveLetterString; out CntMountedOK: integer; out CntMountFailed: integer);
var
i: integer;
begin
CntMountedOK := 0;
CntMountFailed := 0;
for i:=1 to length(mountedAs) do begin
if (mountedAs[i] = #0) then begin
inc(CntMountFailed);
end else begin
inc(CntMountedOK);
end;
end;
end;
// -----------------------------------------------------------------------------
END.
|
unit TpRepeater;
interface
uses
Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils,
Types,
ThTag, ThPanel,
TpControls;
type
TTpRepeater = class(TThPanel)
private
FOnGenerate: TTpEvent;
FCount: Integer;
FOnRepeat: TTpEvent;
protected
procedure SetCount(const Value: Integer);
public
procedure CellTag(inTag: TThTag); override;
published
property Count: Integer read FCount write SetCount;
property OnGenerate: TTpEvent read FOnGenerate write FOnGenerate;
property OnRepeat: TTpEvent read FOnRepeat write FOnRepeat;
end;
implementation
{ TTpRepeater }
procedure TTpRepeater.SetCount(const Value: Integer);
begin
FCount := Value;
end;
procedure TTpRepeater.CellTag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Add(tpClass, 'TTpRepeater');
Add('tpName', Name);
Add('tpCount', Count);
Add('tpOnGenerate', OnGenerate);
Add('tpOnRepeat', OnRepeat);
end;
end;
end.
|
unit DesignManager;
interface
uses
Windows, Messages, Classes, Controls, Forms,
LrObserverList;
const
LRM_PROPCHANGE = WM_USER + $01;
type
TObjectArray = array of TObject;
//
TDesignFilterEvent = procedure(inSender: TObject; inObject: TObject;
var inFilter: Boolean) of object;
TDesignGetAddClassEvent = procedure(Sender: TObject;
var ioClass: string) of object;
//
TDesignManager = class(TComponent)
private
FContainer: TComponent;
FDesignObjects: TObjectArray;
FDesignObservers: TLrObserverList;
FOnChange: TNotifyEvent;
FOnFilter: TDesignFilterEvent;
FOnGetAddClass: TDesignGetAddClassEvent;
FPropertyObservers: TLrObserverList;
FSelected: TObjectArray;
FSelectionObservers: TLrObserverList;
Handle: HWND;
protected
function GetAddClass: string;
function GetSelectedObject: TObject;
procedure Change;
procedure LrmPropChange(var inMessage: TMessage); message LRM_PROPCHANGE;
procedure SetContainer(const Value: TComponent);
procedure UpdateDesignList;
procedure WndProc(var inMsg: TMessage);
public
constructor Create(inOwner: TComponent); override;
destructor Destroy; override;
procedure DesignChange;
function Filter(inObject: TObject): Boolean;
procedure ObjectSelected(inSender, inObject: TObject);
procedure ObjectsSelected(inSender: TObject; inSelected: array of TObject);
procedure PropertyChange(inSender: TObject);
property AddClass: string read GetAddClass;
property Container: TComponent read FContainer write SetContainer;
property DesignObjects: TObjectArray read FDesignObjects;
property DesignObservers: TLrObserverList read FDesignObservers;
property OnFilter: TDesignFilterEvent read FOnFilter write FOnFilter;
property OnGetAddClass: TDesignGetAddClassEvent read FOnGetAddClass
write FOnGetAddClass;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property PropertyObservers: TLrObserverList read FPropertyObservers;
property SelectionObservers: TLrObserverList read FSelectionObservers;
property Selected: TObjectArray read FSelected;
property SelectedObject: TObject read GetSelectedObject;
end;
var
DesignMgr: TDesignManager;
implementation
{ TDesignManager }
constructor TDesignManager.Create(inOwner: TComponent);
begin
inherited;
Handle := Classes.AllocateHWnd(WndProc);
FSelectionObservers := TLrObserverList.Create;
FDesignObservers := TLrObserverList.Create;
FPropertyObservers := TLrObserverList.Create;
end;
destructor TDesignManager.Destroy;
begin
FPropertyObservers.Free;
FDesignObservers.Free;
FSelectionObservers.Free;
Classes.DeallocateHWnd(Handle);
inherited;
end;
procedure TDesignManager.Change;
begin
if Assigned(OnChange) then
OnChange(Self);
end;
procedure TDesignManager.DesignChange;
begin
UpdateDesignList;
DesignObservers.Notify(Self);
//Change;
end;
function TDesignManager.Filter(inObject: TObject): Boolean;
begin
Result := false;
if Assigned(OnFilter) then
OnFilter(Self, inObject, Result);
end;
procedure TDesignManager.UpdateDesignList;
var
c, i: Integer;
begin
if Container = nil then
FDesignObjects := nil
else begin
c := 0;
SetLength(FDesignObjects, Container.ComponentCount);
for i := 0 to Pred(Container.ComponentCount) do
if not Filter(Container.Components[i]) then
begin
FDesignObjects[c] := Container.Components[i];
Inc(c);
end;
SetLength(FDesignObjects, c);
end;
end;
procedure TDesignManager.SetContainer(const Value: TComponent);
begin
FContainer := Value;
UpdateDesignList;
DesignObservers.Notify(Self);
end;
procedure TDesignManager.ObjectSelected(inSender: TObject; inObject: TObject);
begin
ObjectsSelected(inSender, [ inObject ]);
// FSelectedObject := inObject;
// SelectionObservers.NotifyExcept(Self, inSender);
end;
procedure TDesignManager.ObjectsSelected(inSender: TObject;
inSelected: array of TObject);
var
i: Integer;
begin
SetLength(FSelected, Length(inSelected));
for i := 0 to Pred(Length(inSelected)) do
FSelected[i] := inSelected[i];
SelectionObservers.NotifyExcept(Self, inSender);
end;
function TDesignManager.GetAddClass: string;
begin
if Assigned(OnGetAddClass) then
OnGetAddClass(Self, Result)
else
Result := '';
end;
procedure TDesignManager.PropertyChange(inSender: TObject);
begin
PostMessage(Handle, LRM_PROPCHANGE, Integer(inSender), 0);
end;
procedure TDesignManager.WndProc(var inMsg: TMessage);
begin
case inMsg.Msg of
LRM_PROPCHANGE: LrmPropChange(inMsg);
else
inMsg.Result :=
DefWindowProc(Handle, inMsg.Msg, inMsg.wParam, inMsg.lParam);
end;
end;
procedure TDesignManager.LrmPropChange(var inMessage: TMessage);
begin
PropertyObservers.NotifyExcept(Self, TObject(inMessage.wParam));
end;
function TDesignManager.GetSelectedObject: TObject;
begin
if Length(Selected) > 0 then
Result := Selected[0]
else
Result := nil;
end;
end.
|
uses UConst;
function read_txt(filename: string): array of array of real;
begin
foreach var (i, line) in ReadLines(filename).Numerate(0) do
begin
SetLength(result, i + 1);
result[i] := line.ToReals
end;
end;
function mix_flows(ratio: array of real;
fractions: array of array of real): array of real;
begin
result := ArrFill(fractions.Length, 0.0);
foreach var i in fractions.Indices do
foreach var j in ratio.Indices do
result[i] += ratio[j] * fractions[i][j]
end;
function get_octane_number(c: array of real;
octane_numbers: array of real;
bi: array of real): real;
begin
result := 0.0;
foreach var i in c.Indices do
result += octane_numbers[i] * c[i];
foreach var i in c.Indices do
for var j := i + 1 to c.High do
result += bi[i] * bi[j] * c[i] * c[j]
end;
begin
var data := read_txt('data.txt');
var ratio := Arr(0.1, 0.1, 0.1, 0.1, 0.2, 0.4);
var fractions := mix_flows(ratio, data);
var ron := get_octane_number(fractions, UConst.RON, UConst.Bi);
var flow := ArrFill(fractions.Length, 0.0);
foreach var j in ratio.Indices do
begin
foreach var i in data.Indices do
flow[i] := data[i][j];
println($'Октанове число потока {j + 1} = {get_octane_number(flow, UConst.RON, UConst.Bi):f3}')
end;
println;
println($'Октановое число смеси = {ron:f3}')
end. |
{ Gasmas - simple mostly procedural 2D game-oriented routines for FreePascal }
unit Gasmas;
{$MODE OBJFPC}{$H+}
interface
uses
Classes, SysUtils;
type
TGraphicsOption = (goFullscreen, goDoublePixels, goResizeable,
goAutoFullscreen, goAutoHidePointer);
TGraphicsOptions = set of TGraphicsOption;
TSurfaceOption = (soOptimizable);
TSurfaceOptions = set of TSurfaceOption;
TBlitOption = (boBlend, boFlipHorizontal, boFlipVertical);
TBlitOptions = set of TBlitOption;
TColor = packed record
Blue, Green, Red, Alpha: Byte;
end;
TColorArray = array of TColor;
TSurface = object
private
FHandle: Pointer;
FWidth: Integer;
FHeight: Integer;
FMinX, FMinY, FMaxX, FMaxY: Integer;
FOptions: TSurfaceOptions;
procedure SetMinX(const AValue: Integer); inline;
procedure SetMinY(const AValue: Integer); inline;
procedure SetMaxX(const AValue: Integer); inline;
procedure SetMaxY(const AValue: Integer); inline;
procedure ClipChanged;
public
property MinX: Integer read FMinX write SetMinX;
property MinY: Integer read FMinY write SetMinY;
property MaxX: Integer read FMaxX write SetMaxX;
property MaxY: Integer read FMaxY write SetMaxY;
property Handle: Pointer read FHandle;
property Width: Integer read FWidth;
property Height: Integer read FHeight;
property Options: TSurfaceOptions read FOptions;
end;
TKey = (
vkNone, vkUnknown,
vkEscape, vkF1, vkF2, vkF3, vkF4, vkF5, vkF6, vkF7, vkF8, vkF9, vkF10,
vkF11, vkF12, vkScrollLock, vkPause, vkBackQuote, vk0, vk1, vk2, vk3, vk4,
vk5, vk6, vk7, vk8, vk9, vkMinus, vkEquals, vkBackspace, vkInsert,
vkHome, vkPageUp, vkPageDown, vkTab, vkA, vkB, vkC, vkD, vkE, vkF, vkG,
vkH, vkI, vkJ, vkK, vkL, vkM, vkN, vkO, vkP, vkQ, vkR, vkS, vkT, vkU,
vkV, vkW, vkX, vkY, vkZ, vkLeftBracket, vkRightBracket, vkBackSlash,
vkEnter, vkCapsLock, vkSemiColon, vkQuote, vkShift, vkComma, vkPeriod,
vkSlash, vkControl, vkAlt, vkLeftMeta, vkRightMeta, vkSpace, vkDelete,
vkEnd, vkLeft, vkRight, vkUp, vkDown, vkNumLock, vkDivide, vkMultiply,
vkSubtract, vkAdd, vkKeypad0, vkKeypad1, vkKeypad2, vkKeypad3,
vkKeypad4, vkKeypad5, vkKeypad6, vkKeypad7, vkKeypad8, vkKeypad9,
vkKeypadPoint, vkMouse, vkLeftButton, vkMiddleButton, vkRightButton,
vkWheelUp, vkWheelDown, vkEndOfKeys
);
const
DefaultHorizontalResolution = 640;
DefaultVerticalResolution = 480;
DefaultCaption = 'Gasmas Graphics';
DefaultGraphicsOptions = [goResizeable, goAutoFullscreen];
DoublePixelsGraphicsOptions = DefaultGraphicsOptions + [goDoublePixels];
FullscreenGraphicsOptions = DefaultGraphicsOptions + [goFullscreen];
DefaultSurfaceOptions = [];
DefaultBlitOptions = [];
MouseKeys = [vkMouse, vkLeftButton, vkMiddleButton, vkRightButton,
vkWheelUp, vkWheelDown];
KeyNames: array [TKey] of string = (
'none', 'unknown', 'escape', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7',
'f8', 'f9', 'f10', 'f11', 'f12', 'scroll lock', 'pause', '`', '0', '1',
'2', '3', '4', '5', '6', '7', '8', '9', '-', '=', 'backspace', 'insert',
'home', 'page up', 'page down', 'tab', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', '[', ']', '\', 'enter', 'caps lock', ';', '''',
'shift', ',', '.', '/', 'control', 'alt', 'left meta', 'right meta',
'space', 'delete', 'end', 'left', 'right', 'up', 'down', 'num lock',
'keypad divide', 'keypad multiply', 'keypad subtract', 'keypad add',
'keypad 0', 'keypad 1', 'keypad 2', 'keypad 3', 'keypad 4', 'keypad 5',
'keypad 6', 'keypad 7', 'keypad 8', 'keypad 9', 'keypad point',
'mouse motion', 'left button', 'middle button', 'right button',
'wheel up', 'wheel down', 'end of keys'
);
var
Screen: TSurface;
KeyState: array [TKey] of Boolean;
MouseX, MouseY: Integer;
FramesPerSecond: Integer;
ShowFramesPerSecond: Boolean;
IgnoreMouseKeys: Boolean;
function InitGraphics(HRes: Integer=DefaultHorizontalResolution;
VRes: Integer=DefaultVerticalResolution;
GraphicsOptions: TGraphicsOptions=DefaultGraphicsOptions;
Caption: string=DefaultCaption): Boolean;
procedure CloseGraphics;
procedure UpdateGraphics;
function GraphicsOpen: Boolean;
procedure ShowPointer(Show: Boolean);
function CreateSurface(Width, Height: Integer; out Surface: TSurface; SurfaceOptions: TSurfaceOptions=DefaultSurfaceOptions): Boolean;
procedure DestroySurface(var Surface: TSurface);
function DuplicateSurface(out Target: TSurface; const Source: TSurface; SurfaceOptions: TSurfaceOptions=DefaultSurfaceOptions): Boolean;
function SetPointerImage(const Surface: TSurface; HotX: Integer=0; HotY: Integer=0): Boolean;
procedure ClearPointerImage;
function Lock(const Surface: TSurface; out Pixels: TColorArray): Boolean;
procedure Unlock(const Surface: TSurface);
procedure Blit(const Target, Source: TSurface; X: Integer=0; Y: Integer=0; BlitOptions: TBlitOptions=DefaultBlitOptions);
procedure Plot(const Target: TSurface; X, Y: Integer; const Color: TColor);
function ColorAt(const Surface: TSurface; X, Y: Integer): TColor;
function SaveSurface(const Surface: TSurface; FileName: string): Boolean;
function DecodeSurface(var Data; out Surface: TSurface; SurfaceOptions: TSurfaceOptions=DefaultSurfaceOptions): Boolean;
function LoadSurface(FileName: string; out Surface: TSurface; SurfaceOptions: TSurfaceOptions=DefaultSurfaceOptions): Boolean;
function Color(R, G, B: Byte; A: Byte=255): TColor; inline;
function ReadKey: TKey;
function KeyPressed: Boolean;
function LastKey: TKey;
function GetTicks: Cardinal;
procedure ClearBuffer(out Buff; Size: Cardinal);
implementation
{$IFDEF WINDOWS}
{$INCLUDE gaswin32.inc}
{$ENDIF}
{$IFDEF LINUX}
{$INCLUDE gaslinux.inc}
{$ENDIF}
function SaveSurface(const Surface: TSurface; FileName: string): Boolean;
var
Pixels: TColorArray;
Stream: TFileStream = nil;
ID: packed array [1..4] of Char;
I: Integer;
begin
Result:=False;
if not Lock(Surface, Pixels) then Exit;
try
Stream:=TFileStream.Create(FileName, fmCreate);
ID[1]:='G';
ID[2]:='A';
ID[3]:='S';
ID[4]:='U';
Stream.Write(ID, 4);
Stream.WriteByte(Surface.Width and $FF);
Stream.WriteByte(Surface.Width shr 8);
Stream.WriteByte(Surface.Height and $FF);
Stream.WriteByte(Surface.Height shr 8);
for I:=0 to High(Pixels) do
with Pixels[I] do begin
Stream.WriteByte(Red);
Stream.WriteByte(Green);
Stream.WriteByte(Blue);
Stream.WriteByte(Alpha);
end;
Result:=True;
except
end;
Unlock(Surface);
FreeAndNil(Stream);
end;
function DecodeSurface(var Data; out Surface: TSurface; SurfaceOptions: TSurfaceOptions=DefaultSurfaceOptions): Boolean;
var
Bytes: PByte;
ID: array [1..4] of Char;
Width, Height: Integer;
I, Ctr: Integer;
Pixels: TColorArray;
begin
Result:=False;
Bytes:=PByte(@Data);
{$HINTS-}Move(Bytes^, ID, 4);{$HINTS+}
if (ID[1] <> 'G') or (ID[2] <> 'A') or (ID[3] <> 'S') or (ID[4] <> 'U') then Exit;
Width:=Bytes[4] or (Bytes[5] shl 8);
Height:=Bytes[6] or (Bytes[7] shl 8);
if not CreateSurface(Width, Height, Surface, SurfaceOptions) then Exit;
if not Lock(Surface, Pixels) then begin
DestroySurface(Surface);
Exit(False);
end;
Ctr:=8;
for I:=0 to High(Pixels) do
with Pixels[I] do begin
Red:=Bytes[Ctr]; Inc(Ctr);
Green:=Bytes[Ctr]; Inc(Ctr);
Blue:=Bytes[Ctr]; Inc(Ctr);
Alpha:=Bytes[Ctr]; Inc(Ctr);
end;
Unlock(Surface);
Result:=True;
end;
function LoadSurface(FileName: string; out Surface: TSurface; SurfaceOptions: TSurfaceOptions=DefaultSurfaceOptions): Boolean;
var
Stream: TFileStream = nil;
Buffer: Pointer = nil;
begin
Result:=False;
try
Stream:=TFileStream.Create(FileName, fmOpenRead);
Buffer:=GetMem(Stream.Size);
Stream.Read(Buffer^, Stream.Size);
Result:=DecodeSurface(Buffer^, Surface, SurfaceOptions);
except
end;
if Assigned(Buffer) then FreeMem(Buffer);
FreeAndNil(Stream);
end;
procedure ClearBuffer(out Buff; Size: Cardinal);
begin
{$PUSH}{$HINTS OFF}
FillChar(Buff, Size, #0);
{$POP}
end;
function Color(R, G, B, A: Byte): TColor;
begin
with Result do begin
Red:=R;
Green:=G;
Blue:=B;
Alpha:=A;
end;
end;
{ TSurface }
procedure TSurface.SetMinX(const AValue: Integer);
begin
if FMinX=AValue then Exit;
FMinX:=AValue;
if FMinX < 0 then FMinX:=0 else if FMinX > FMaxX then FMinX:=FMaxX;
ClipChanged;
end;
procedure TSurface.SetMinY(const AValue: Integer);
begin
if FMinY=AValue then Exit;
FMinY:=AValue;
if FMinY < 0 then FMinY:=0 else if FMinY > FMaxY then FMinY:=FMaxY;
ClipChanged;
end;
procedure TSurface.SetMaxX(const AValue: Integer);
begin
if FMaxX=AValue then Exit;
FMaxX:=AValue;
if FMaxX >= Width then FMaxX:=Width - 1 else if FMaxX < FMinX then FMaxX:=FMinX;
ClipChanged;
end;
procedure TSurface.SetMaxY(const AValue: Integer);
begin
if FMaxY=AValue then Exit;
FMaxY:=AValue;
if FMaxY >= Height then FMaxY:=Height - 1 else if FMaxY < FMinY then FMaxY:=FMinY;
ClipChanged;
end;
initialization
ShowFramesPerSecond:=True;
finalization
if GraphicsOpen then CloseGraphics;
end.
|
unit Unit3; { Module for support Get Battery Info by IOCTL }
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Windows;
type
{--- IOCTL common definitions ---}
DeviceInterfaceData = packed record
cbSize:Dword; // Struct. size, caller must set
classguid:TGuid; // Interface class GUID
flags:DWord; // Interface flags
rsvd:UInt64; // Reserved
end; PDevIntData = ^DeviceInterfaceData;
DeviceInfoData = packed record
cbSize:Dword; // Struct. size, caller must set
classguid:TGuid; // Interface class GUID
devinst:DWord; // Handle to device instance
rsvd:UInt64; // Reserved
end; PDevInfoData = ^DeviceInfoData;
DeviceInterfaceDetailData = packed record
cbSize:Dword; // Struct. size, caller must set
DevicePath:Array [0..1023] of Char; // Path for use file operations
end; PDevIntDetData = ^DeviceInterfaceDetailData;
{--- IOCTL definitions for batteries ---}
{--- IOCTL BATTERY INFORMATION request, output buffer formats ---}
{ required fixing, yet used constant offsets }
BATTERY_INFORMATION = packed record
Capabilities:DWord;
Technology:Byte;
Reserved:Array [0..2] of Byte;
Chemistry:Array [0..3] of Word; // UNICODE
DesignedCapacity:DWord;
FullChargedCapacity:DWord;
DefaultAlert1:DWord;
DefaultAlert2:DWord;
CriticalBias:DWord;
CycleCount:DWord
end; P_BATTERY_INFORMATION = ^BATTERY_INFORMATION;
{--- IOCTL BATTERY INFORMATION request input buffer format ---}
BATTERY_QUERY_INFORMATION = packed record
BatteryTag:DWord;
InformationLevel:DWord; // type is BATTERY_QUERY_INFORMATION_LEVEL
AtRate:DWord
end; P_BATTERY_QUERY_INFORMATION = ^BATTERY_QUERY_INFORMATION;
{--- IOCTL BATTERY STATUS request input buffer format ---}
{ input buffer for this IOCTL request }
BATTERY_WAIT_STATUS = packed record
BatteryTag:DWord; // tag for battery select
Timeout:DWord; // timeouts handling option
PowerState:DWord; // select state, for output data association
LowCapacity:DWord;
HighCapacity:DWord
end; P_BATTERY_WAIT_STATUS = ^BATTERY_WAIT_STATUS;
{--- IOCTL BATTERY STATUS request output buffer format ---}
{ output buffer for this IOCTL request }
BATTERY_STATUS = packed record
PowerState:DWord;
Capacity:DWord;
Voltage:DWord;
Rate:DWord
end; P_BATTERY_STATUS = ^BATTERY_STATUS;
{---------- OS API used library functions declarations, as constant -----------}
function SetupDiGetClassDevsA // Function name, "A"=ASCII, "W"=UNICODE
( pClassGuid: Pointer; // Pointer to device class GUID
Enumerator: PChar; // Pointer to enumerator name
hwndParent: Hwnd; // Pointer to parent window handle
flags:Dword // Control flags for return filtering
): Hwnd; // Return handle for DEVICE INFORM. SET
stdcall; external 'setupapi.dll';
function SetupDiEnumDeviceInterfaces // Function name
( hdevinfo: Hwnd; // Handle for DEVICE INFORMATION SET
devinfo: PChar; // Pointer to Dev. Info enum. control
pClassGuid: Pointer; // Pointer to device class GUID
idev: UInt32; // Member index
devint:PDevIntData // Pointer to Device Interface Data
): Boolean; // Result flag
stdcall; external 'setupapi.dll';
function SetupDiGetDeviceInterfaceDetailA // Fnc.name, "A"=ASCII, "W"=UNICODE
( hdevinfo: Hwnd; // Handle for DEVICE INFORMATION SET
devint:PDevIntData; // Pointer to Device Interface Data
devintdet:PDevIntDetData; // Pointer to Dev. Int. Detail Data
devintdetsize:DWord; // Size of Dev. Int. Detail Data
reqsize:Pointer; // Pointer to output dword: req. size
devinfo:Pointer // Pointer to output devinfo data
): Boolean; // Result flag
stdcall; external 'setupapi.dll';
{---------- Module procedures entry points ------------------------------------}
{ arrays (not scalars) because some batteries (maximum=10) supported }
function InitIoctl
( var sa1: Array of String; // Enumeration paths for combo box
var sn2: Array of DWord; // Battery tags as numbers
var sa2: Array of String; // Battery tags as strings
var sa3: Array of String; // Battery models as strings
var sa4: Array of String; // Battery manufacture name as strings
var sn5: Array of DWord; // Battery manufacture date as numbers
var sa5: Array of String; // Battery manufacture date as strings
var sa6: Array of String; // Battery serial number as strings
var sa7: Array of String; // Battery unique id as strings
var ss8: Array of String; // Battery chemistry, short string
var sl8: Array of String; // Battery chemistry, long string
{--- Additions for v0.04 ---}
var sn09: Array of Byte; // Battery rechargable flag as number
var sa09: Array of String; // ... as string
var sn10: Array of DWord; // Battery designed capacity as number
var sa10: Array of String; // ... as string
var sn11: Array of DWord; // Battery full charge capacity as number
var sa11: Array of String; // ... as string
var sn12: Array of DWord; // Battery default alert #1 cap. as num.
var sa12: Array of String; // ... as string
var sn13: Array of DWord; // Battery default alert #2 cap. as num.
var sa13: Array of String; // ... as string
var sn14: Array of DWord; // Battery critical bias capac. as num.
var sa14: Array of String; // ... as string
var sn15: Array of DWord; // Battery cycle count as number
var sa15: Array of String; // ... as string
var sn16: Array of DWord; // Battery temperature as number
var sa16: Array of String; // ... as string
var sn17: Array of DWord; // Battery power state as number
var sa17: Array of String; // ... as string
var sn18: Array of DWord; // Battery current capacity as number
var sa18: Array of String; // ... as string
var sn19: Array of DWord; // Battery current voltage as number
var sa19: Array of String; // ... as string
var sn20: Array of Integer; // Battery current rate (+/-) as number
var sa20: Array of String // ... as string
): Integer;
implementation
function InitIoctl ( var sa1:Array of String;
var sn2: Array of DWord;
var sa2: Array of String;
var sa3: Array of String;
var sa4: Array of String;
var sn5: Array of DWord;
var sa5: Array of String;
var sa6: Array of String;
var sa7: Array of String;
var ss8: Array of String;
var sl8: Array of String;
{--- Additions for v0.04 ---}
var sn09: Array of Byte;
var sa09: Array of String;
var sn10: Array of DWord;
var sa10: Array of String;
var sn11: Array of DWord;
var sa11: Array of String;
var sn12: Array of DWord;
var sa12: Array of String;
var sn13: Array of DWord;
var sa13: Array of String;
var sn14: Array of DWord;
var sa14: Array of String;
var sn15: Array of DWord;
var sa15: Array of String;
var sn16: Array of DWord;
var sa16: Array of String;
var sn17: Array of DWord;
var sa17: Array of String;
var sn18: Array of DWord;
var sa18: Array of String;
var sn19: Array of DWord;
var sa19: Array of String;
var sn20: Array of Integer;
var sa20: Array of String
): Integer;
const
{--- Months for date ---}
Months: Array [0..12] of String = ( '?',
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December' );
{--- IOCTL base constants ---}
GUID_DEVCLASS_BATTERY:TGUID = '{72631E54-78A4-11D0-BCF7-00AA00B7B32A}';
DIGCF_FLAGS:UInt32=$00000012; // PRESENT=02H, DEVICEINTERFACE=10H
BUFFER_TOO_SMALL=122; // Error code for buffer re-allocation
{--- File IO constants ---}
facc:UInt64 = GENERIC_READ OR GENERIC_WRITE;
fshr:UInt64 = FILE_SHARE_READ OR FILE_SHARE_WRITE;
fsec:UInt64 = 0;
fcdp:UInt64 = OPEN_EXISTING;
fatr:UInt64 = FILE_ATTRIBUTE_NORMAL;
ftpl:UInt64 = 0;
{--- Device IO control constants ---}
IOCTL_BATTERY_QUERY_TAG : UInt32 = $00294040;
IOCTL_BATTERY_QUERY_INFORMATION : UInt32 = $00294044;
IOCTL_BATTERY_QUERY_STATUS : UInt32 = $0029404C;
{--- Battery types decoder ---}
BatteryTypes: Array [0..15] of String = (
'N/A' , 'Data is not readable',
'PbAc' , 'Lead Acid' ,
'LION' , 'Lithium Ion' ,
'Li-I' , 'Lithium Ion' ,
'NiCd' , 'Nickel Cadmium' ,
'NiMH' , 'Nickel Metal Hydride' ,
'NiZn' , 'Nickel Zinc' ,
'RAM' , 'Rechargeable Alkaline-Manganese' );
{--- Battery technologies decoder ---}
BatteryTechnologies: Array [0..2] of String = (
'Nonrechargeable', 'Rechargeable', 'Unknown type' );
{--- Battery states decoder ---}
BatteryStates: Array [0..3] of String = (
'Online', 'Discharging', 'Charging', 'Critical' );
{--- IOCTL requests codes for battery ---}
BatteryInformation = 0;
BatteryDeviceName = 4;
BatteryManufactureName = 6;
BatteryManufactureDate = 5;
BatterySerialNumber = 8;
BatteryUniqueId = 7;
BatteryTemperature =2;
var
{--- Common variables ---}
count:Integer;
status:Boolean;
p1,p2:Pointer;
h1,h2:Hwnd;
f1:Dword;
cbRequired:UInt32;
e1:UInt64;
{--- Device interface variables ---}
intf1: DeviceInterfaceData =
( cbSize:sizeof(DeviceInterfaceData);
classguid:'{00000000-0000-0000-0000-000000000000}';
flags:0;
rsvd:0 );
p3:PDevIntData;
{--- Device info variables ---}
info1: DeviceInfoData =
( cbSize:sizeof(DeviceInfoData);
classguid:'{00000000-0000-0000-0000-000000000000}';
devinst:0;
rsvd:0 );
p4:PDevInfoData;
{--- Device interface detail data ---}
path1: DeviceInterfaceDetailData =
// ( cbSize:sizeof(DeviceInterfaceDetailData) );
( cbSize:8 ); // Size of constant part only
p5:PDevIntDetData;
p6:Pointer;
{--- File IO variables ---}
fpnt:Pointer;
hBattery:THandle;
{--- Device IO control variables ---}
InBuf:BATTERY_QUERY_INFORMATION;
OutBuf:Array [0..1023] of Char;
OutRet:UInt32;
ShortInBuf:DWord;
cbuf:Char;
pbuf:PChar;
pbufd:PDWord;
ibuf:UInt32;
ubuf:Integer;
valid:Integer;
ts:String;
fbuf:Boolean;
dbuf:double;
{--- Additions for get status request, special records used ---}
{ need optimization for use same memory and pointers for different requests }
InWaitStatus:BATTERY_WAIT_STATUS = ( BatteryTag:0; Timeout:0; PowerState:1;
LowCapacity:50; HighCapacity:100 );
OutStatus:BATTERY_STATUS = ( PowerState:0; Capacity:0;
Voltage:0; Rate:0 );
pstin:P_BATTERY_WAIT_STATUS;
pstout:P_BATTERY_STATUS;
begin
{--- Initializing output data ---}
count:=0;
{--- Get handle for access DEVICE INFORMATION SET with list of batteries ---}
p1:=@GUID_DEVCLASS_BATTERY;
UInt64(p2):=0;
UInt64(h1):=0;
UInt64(h2):=0;
f1:=DIGCF_FLAGS;
h1 := SetupDiGetClassDevsA ( p1, p2, h2, f1 ); // (1)
{--- Enumerate device interfaces ---}
if h1<>0 then
begin
p3:=@intf1;
//p4:=@info1;
p5:=@path1;
p6:=@cbRequired;
cbRequired:=path1.cbSize;
{---------- Start cycle for maximum 10 batteries ------------------------------}
repeat
{--- Get path for output string and IOCTL file I/O ---}
status := SetupDiEnumDeviceInterfaces // (2)
( h1, p2, p1, count, p3 );
if status=false then break; // break if error
status := SetupDiGetDeviceInterfaceDetailA // (3)
( h1, p3, p2, 0, p6, p2 );
if status=true then break; // break if error: no errors with size=0
e1:=GetLastError();
if (e1<>BUFFER_TOO_SMALL) then break; // break if other type of errors
if cbRequired > 1024-8 then break; // break if required size too big
status := SetupDiGetDeviceInterfaceDetailA // (4)
( h1, p3, p5, cbRequired, p2, p2 );
if status=false then break; // break if error
sa1[count]:=path1.DevicePath;
{--- Open device as file for IOCTL operations ---}
fpnt:=@path1.DevicePath;
hBattery:=0;
hBattery := CreateFile // (5)
( fpnt, facc, fshr, LPSECURITY_ATTRIBUTES(fsec), fcdp, fatr, ftpl );
if hBattery <> 0 then
begin
{--- IOCTL DeviceIoControl usage notes for Battery Info.
Parm#1 = HANDLE: device handle returned by CreateFile function
Parm#2 = REQUEST CODE: IOCTL_BATTERY_QUERY_INFORMATION
Parm#3 = POINTER: pointer to input buffer
Parm#4 = DWORD: size of input buffer
Parm#5 = POINTER: pointer to output buffer
Parm#6 = DWORD: size of output buffer
Parm#7 = POINTER: pointer to dword: variable output return size
Parm#8 = POINTER: pointer to OVERLAPPED structure for asynchronous ---}
{--- Get BATTERY TAG and store for return to caller ---}
ShortInBuf:=0;
OutRet:=0;
status := DeviceIoControl // (6)
( hBattery, IOCTL_BATTERY_QUERY_TAG,
@ShortInBuf, sizeof(ShortInBuf),
@InBuf.BatteryTag, sizeof(InBuf.BatteryTag),
@OutRet, POVERLAPPED(0) );
if ( (status=true) AND ( InBuf.BatteryTag<>0 ) ) then
{--- Begin big conditional block ---}
begin
sn2[count] := InBuf.BatteryTag;
sa2[count] := ' ' + Format( '%.8Xh',[ InBuf.BatteryTag ] );
OutRet:=0;
{--- Battery model string ---}
InBuf.InformationLevel:=BatteryDeviceName;
sa3[count]:=' n/a';
status := DeviceIoControl // (7)
( hBattery, IOCTL_BATTERY_QUERY_INFORMATION,
@InBuf, sizeof(InBuf), @OutBuf, sizeof(OutBuf),
@OutRet, POVERLAPPED(0) );
if ((status=true) AND (OutRet>0)) then
begin
pbuf:=@OutBuf;
sa3[count]:=' ';
valid:=0;
for ibuf:=1 to (OutRet DIV 2) do // DIV 2 because UNICODE
begin
cbuf:=pbuf^; // transit char is redundant, for debug
sa3[count] := sa3[count] + cbuf;
pbuf+=2; // +2 (not +1) because UNICODE
if ((Byte(cbuf)<>0) AND (Byte(cbuf)<>32)) then valid:=1;
if (Byte(cbuf)=0) then break;
end;
if (valid=0) then sa3[count]:=' n/a';
end;
{--- Battery vendor string ---}
InBuf.InformationLevel:=BatteryManufactureName;
sa4[count]:=' n/a';
status := DeviceIoControl // (8)
( hBattery, IOCTL_BATTERY_QUERY_INFORMATION,
@InBuf, sizeof(InBuf), @OutBuf, sizeof(OutBuf),
@OutRet, POVERLAPPED(0) );
if ((status=true) AND (OutRet>0) ) then
begin
pbuf:=@OutBuf;
sa4[count]:=' ';
valid:=0;
for ibuf:=1 to (OutRet DIV 2) do // DIV 2 because UNICODE
begin
cbuf:=pbuf^; // transit char is redundant, for debug
sa4[count] := sa4[count] + cbuf;
pbuf+=2; // +2 (not +1) because UNICODE
if ((Byte(cbuf)<>0) AND (Byte(cbuf)<>32)) then valid:=1;
if (Byte(cbuf)=0) then break;
end;
if (valid=0) then sa4[count]:=' n/a';
end;
{--- Battery manufacture date as number and as string ---}
InBuf.InformationLevel:=BatteryManufactureDate;
sn5[count]:=0;
sa5[count]:=' n/a';
status := DeviceIoControl // (9)
( hBattery, IOCTL_BATTERY_QUERY_INFORMATION,
@InBuf, sizeof(InBuf), @OutBuf, sizeof(OutBuf),
@OutRet, POVERLAPPED(0) );
if ((status=true) AND (OutRet>0)) then
begin
pbuf := @OutBuf;
sa5[count]:=' ';
pbufd := @OutBuf;
sn5[count] := pbufd^;
sa5[count] := ' ' + IntToStr (( pbufd^ SHR 16 ) AND $FFFF ) + ', ';
cbuf := (pbuf+1)^;
if UInt32(cbuf) > 12 then cbuf:=Char(0);
sa5[count] := sa5[count] + Months[UInt32(cbuf)] + ' ';
sa5[count] := sa5[count] + IntToStr (UInt32(pbuf^));
end else sn5[count]:=0;
{--- Battery serial number string ---}
InBuf.InformationLevel:=BatterySerialNumber;
sa6[count]:=' n/a';
status := DeviceIoControl // (10)
( hBattery, IOCTL_BATTERY_QUERY_INFORMATION,
@InBuf, sizeof(InBuf), @OutBuf, sizeof(OutBuf),
@OutRet, POVERLAPPED(0) );
if ((status=true) AND (OutRet>0)) then
begin
pbuf:=@OutBuf;
sa6[count]:=' ';
valid:=0;
for ibuf:=1 to (OutRet DIV 2) do // DIV 2 because UNICODE
begin
cbuf:=pbuf^; // transit char is redundant, for debug
sa6[count] := sa6[count] + cbuf;
pbuf+=2; // +2 (not +1) because UNICODE
if ((Byte(cbuf)<>0) AND (Byte(cbuf)<>32)) then valid:=1;
if (Byte(cbuf)=0) then break;
end;
if (valid=0) then sa6[count]:=' n/a';
end;
{--- Battery unique id string ---}
InBuf.InformationLevel:=BatterySerialNumber;
sa7[count]:=' n/a';
status := DeviceIoControl // (11)
( hBattery, IOCTL_BATTERY_QUERY_INFORMATION,
@InBuf, sizeof(InBuf), @OutBuf, sizeof(OutBuf),
@OutRet, POVERLAPPED(0) );
if ((status=true) AND (OutRet>0)) then
begin
pbuf:=@OutBuf;
sa7[count]:=' ';
valid:=0;
for ibuf:=1 to (OutRet DIV 2) do // DIV 2 because UNICODE
begin
cbuf:=pbuf^; // transit char is redundant, for debug
sa7[count] := sa7[count] + cbuf;
pbuf+=2; // +2 (not +1) because UNICODE
if ((Byte(cbuf)<>0) AND (Byte(cbuf)<>32)) then valid:=1;
if (Byte(cbuf)=0) then break;
end;
if (valid=0) then sa7[count]:=' n/a';
end;
{--- Battery chemistry, as part of battery info ---}
InBuf.InformationLevel:=BatteryInformation;
ss8[count]:=' ';
sl8[count]:=' n/a';
ts:='';
status := DeviceIoControl // (12)
( hBattery, IOCTL_BATTERY_QUERY_INFORMATION,
@InBuf, sizeof(InBuf), @OutBuf, sizeof(OutBuf),
@OutRet, POVERLAPPED(0) );
if ((status=true) AND (OutRet>0)) then
begin
pbuf:=@OutBuf;
pbuf+=8;
for ibuf:=0 to 3 do
begin
cbuf:=pbuf^;
if Byte(cbuf)=0 then break;
ss8[count]:=ss8[count]+cbuf;
ts:=ts+cbuf;
pbuf+=1;
end;
for ibuf:=0 to (length(BatteryTypes) DIV 2)-1 do
begin
if ( AnsiCompareText(ts, BatteryTypes[ibuf*2]) ) = 0 then
begin
sl8[count] := ' ' + BatteryTypes [ibuf*2+1];
end;
end;
end;
{--- Battery technology, rechargable flag, use previous read IOCTL data ---}
pbuf:=@OutBuf;
ibuf:=(PByte(pbuf+4))^;
sn09[count] := ibuf;
if (ibuf>2) then ibuf:=2;
sa09[count] := ' ' + BatteryTechnologies[ibuf];
{--- Designed capacity ---}
if ( ( ((PDWord(pbuf))^) AND $40000000 )<>0 )
then fbuf:=true else fbuf:=false;
ibuf:=(PDWord(pbuf+12))^;
sn10[count] := ibuf;
sa10[count] := ' n/a';
if (ibuf<>0) then
begin
if (fbuf=false) then sa10[count] := ' ' + IntToStr(ibuf) + ' mWh'
else sa10[count] := ' ' + IntToStr(ibuf) + ' relative ratio units';
end;
if ( (ibuf<=100) AND (ibuf<>0) ) then
sa10[count] := ' Unknown parameter encoding';
{--- Full-charged capacity ---}
ibuf:=(PDWord(pbuf+16))^;
sn11[count] := ibuf;
sa11[count] := ' n/a';
if (ibuf<>0) then
begin
if (fbuf=false) then sa11[count] := ' ' + IntToStr(ibuf) + ' mWh'
else sa11[count] := ' ' + IntToStr(ibuf) + ' relative ratio units';
end;
if ( (ibuf<=100) AND (ibuf<>0) ) then
sa11[count] := ' Unknown parameter encoding';
{--- Default alert #1 capacity ---}
ibuf:=(PDWord(pbuf+20))^;
sn12[count] := ibuf;
sa12[count] := ' n/a';
if (ibuf<>0) then
begin
if (fbuf=false) then sa12[count] := ' ' + IntToStr(ibuf) + ' mWh'
else sa12[count] := ' ' + IntToStr(ibuf) + ' relative ratio units';
end;
// if ( (ibuf<=100) AND (ibuf<>0) ) then
// sa12[count] := ' Unknown parameter encoding';
{--- Default alert #2 capacity ---}
ibuf:=(PDWord(pbuf+24))^;
sn13[count] := ibuf;
sa13[count] := ' n/a';
if (ibuf<>0) then
begin
if (fbuf=false) then sa13[count] := ' ' + IntToStr(ibuf) + ' mWh'
else sa13[count] := ' ' + IntToStr(ibuf) + ' relative ratio units';
end;
// if ( (ibuf<=100) AND (ibuf<>0) ) then
// sa13[count] := ' Unknown parameter encoding';
{--- Critical bias ---}
ibuf:=(PDWord(pbuf+28))^;
sn14[count] := ibuf;
sa14[count] := ' n/a';
if (ibuf<>0) then
begin
if (fbuf=false) then sa14[count] := ' ' + IntToStr(ibuf) + ' mWh'
else sa14[count] := ' ' + IntToStr(ibuf) + ' relative ratio units';
end;
// if ( (ibuf<=100) AND (ibuf<>0) ) then
// sa14[count] := ' Unknown parameter encoding';
{--- Cycle count ---}
ibuf:=(PDWord(pbuf+32))^;
sn15[count] := ibuf;
sa15[count] := ' n/a';
if (ibuf<>0) then sa15[count] := ' ' + IntToStr(ibuf) + ' cycles';
{--- Battery temperture string ---}
InBuf.InformationLevel:=BatteryTemperature;
sn16[count]:=0;
sa16[count]:=' n/a';
status := DeviceIoControl // (13)
( hBattery, IOCTL_BATTERY_QUERY_INFORMATION,
@InBuf, sizeof(InBuf), @OutBuf, sizeof(OutBuf),
@OutRet, POVERLAPPED(0) );
if ((status=true) AND (OutRet>0)) then
begin
pbuf := @OutBuf;
ibuf := (PDWord(pbuf))^;
dbuf := ibuf;
dbuf := dbuf*10 - 273.15;
sn16[count] := ibuf;
if (ibuf<>0) then
sa16[count] := ' ' + Format( '%.1F',[ dbuf ] ) + ' C';
if ( (dbuf<-100.0) OR (dbuf>150.0) ) then
sa16[count] := ' Unknown parameter encoding';
end;
{--- Battery status read, for next 4 parameters ---}
sn17[count]:=0; sn18[count]:=0; sn19[count]:=0; sn20[count]:=0;
ts:=' n/a';
sa17[count]:=ts; sa18[count]:=ts; sa19[count]:=ts; sa20[count]:=ts;
pstin := @InWaitStatus;
pstout := @OutStatus;
pstin^.BatteryTag := InBuf.BatteryTag;
status := DeviceIoControl // (14)
( hBattery, IOCTL_BATTERY_QUERY_STATUS,
pstin, sizeof(InWaitStatus), pstout, sizeof(OutStatus),
@OutRet, POVERLAPPED(0) );
if ((status=true) AND (OutRet>0)) then
begin
{--- Status field 1 of 4, power status ---}
ibuf := pstout^.PowerState;
sn17[count] := ibuf;
ts := ' ';
if (ibuf AND $00000001) <> 0 then
begin
ts := ts + BatteryStates[0]
end;
if (ibuf AND $00000002) <> 0 then
begin
if (length(ts)>1) then ts+=' , ';
ts := ts + BatteryStates[1]
end;
if (ibuf AND $00000004) <> 0 then
begin
if (length(ts)>1) then ts+=' , ';
ts := ts + BatteryStates[2]
end;
if (ibuf AND $00000008) <> 0 then
begin
if (length(ts)>1) then ts+=' , ';
ts := ts + BatteryStates[3]
end;
sa17[count] := ts;
{--- Status field 2 of 4, capacity ---}
ibuf := pstout^.Capacity;
sn18[count] := ibuf;
sa18[count] := ' n/a';
if (ibuf<>0) then
begin
if (fbuf=false) then sa18[count] := ' ' + IntToStr(ibuf) + ' mWh'
else sa18[count] := ' ' + IntToStr(ibuf) + ' relative ratio units';
end;
if ( (ibuf<=100) AND (ibuf<>0) ) then
sa18[count] := ' Unknown parameter encoding';
{--- Status field 3 of 4, voltage ---}
ibuf := pstout^.Voltage;
sn19[count] := ibuf;
sa19[count] := ' n/a';
dbuf := ibuf;
dbuf := dbuf/1000.0;
if (ibuf<>0) then
begin
sa19[count] := Format( ' %.3F',[ dbuf ] ) + ' volts';
if (dbuf<5.0) OR (dbuf>50.0) then
sa19[count] := ' Unknown parameter encoding';
end;
{--- Status field 4 of 4, rate ---}
ubuf := pstout^.Rate;
sn20[count] := ubuf;
sa20[count] := ' n/a';
if (ubuf<>0) then
begin
sa20[count] := ' ' + IntToStr(ubuf) + ' mW';
if ( ubuf > 1000000000 ) OR ( ubuf < -1000000000 ) then
sa20[count] := ' Unknown parameter encoding';
end;
{--- End of status request conditional section ---}
end;
{--- End of tag-conditional section ---}
end;
{--- Close current battery handle ---}
CloseHandle(hBattery);
end;
{--- Make cycle for maximum 10 batteries ---}
count+=1;
until (count>9);
{---------- End cycle for maximum 10 batteries --------------------------------}
end;
{--- Return ---}
InitIoctl:=count;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFApp;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
WinApi.Windows, System.Classes, System.UITypes,
{$ELSE}
Windows, Classes,
{$ENDIF}
uCEFTypes, uCEFInterfaces, uCEFBaseRefCounted, uCEFSchemeRegistrar, uCEFApplication;
type
TCefAppOwn = class(TCefBaseRefCountedOwn, ICefApp)
protected
procedure OnBeforeCommandLineProcessing(const processType: ustring; const commandLine: ICefCommandLine); virtual; abstract;
procedure OnRegisterCustomSchemes(const registrar: TCefSchemeRegistrarRef); virtual; abstract;
procedure GetResourceBundleHandler(var aHandler : ICefResourceBundleHandler); virtual; abstract;
procedure GetBrowserProcessHandler(var aHandler : ICefBrowserProcessHandler); virtual; abstract;
procedure GetRenderProcessHandler(var aHandler : ICefRenderProcessHandler); virtual; abstract;
public
constructor Create; virtual;
end;
TCustomCefApp = class(TCefAppOwn)
protected
FCefApp : TCefApplication;
procedure OnBeforeCommandLineProcessing(const processType: ustring; const commandLine: ICefCommandLine); override;
procedure OnRegisterCustomSchemes(const registrar: TCefSchemeRegistrarRef); override;
procedure GetResourceBundleHandler(var aHandler : ICefResourceBundleHandler); override;
procedure GetBrowserProcessHandler(var aHandler : ICefBrowserProcessHandler); override;
procedure GetRenderProcessHandler(var aHandler : ICefRenderProcessHandler); override;
public
constructor Create(const aCefApp : TCefApplication); reintroduce;
destructor Destroy; override;
end;
implementation
uses
{$IFDEF DELPHI16_UP}
System.SysUtils,
{$ELSE}
SysUtils,
{$ENDIF}
uCEFLibFunctions, uCEFMiscFunctions, uCEFCommandLine, uCEFConstants;
// TCefAppOwn
procedure cef_app_on_before_command_line_processing(self: PCefApp;
const process_type: PCefString;
command_line: PCefCommandLine); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefAppOwn) then
TCefAppOwn(TempObject).OnBeforeCommandLineProcessing(CefString(process_type), TCefCommandLineRef.UnWrap(command_line));
end;
procedure cef_app_on_register_custom_schemes(self: PCefApp; registrar: PCefSchemeRegistrar); stdcall;
var
TempWrapper : TCefSchemeRegistrarRef;
TempObject : TObject;
begin
TempWrapper := nil;
try
try
TempWrapper := TCefSchemeRegistrarRef.Create(registrar);
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefAppOwn) then
TCefAppOwn(TempObject).OnRegisterCustomSchemes(TempWrapper);
except
on e : exception do
if CustomExceptionHandler('cef_app_on_register_custom_schemes', e) then raise;
end;
finally
if (TempWrapper <> nil) then FreeAndNil(TempWrapper);
end;
end;
function cef_app_get_resource_bundle_handler(self: PCefApp): PCefResourceBundleHandler; stdcall;
var
TempObject : TObject;
TempHandler : ICefResourceBundleHandler;
begin
Result := nil;
TempHandler := nil;
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefAppOwn) then
begin
TCefAppOwn(TempObject).GetResourceBundleHandler(TempHandler);
Result := CefGetData(TempHandler);
end;
end;
function cef_app_get_browser_process_handler(self: PCefApp): PCefBrowserProcessHandler; stdcall;
var
TempObject : TObject;
TempHandler : ICefBrowserProcessHandler;
begin
Result := nil;
TempHandler := nil;
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefAppOwn) then
begin
TCefAppOwn(TempObject).GetBrowserProcessHandler(TempHandler);
Result := CefGetData(TempHandler);
end;
end;
function cef_app_get_render_process_handler(self: PCefApp): PCefRenderProcessHandler; stdcall;
var
TempObject : TObject;
TempHandler : ICefRenderProcessHandler;
begin
Result := nil;
TempHandler := nil;
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefAppOwn) then
begin
TCefAppOwn(TempObject).GetRenderProcessHandler(TempHandler);
Result := CefGetData(TempHandler);
end;
end;
constructor TCefAppOwn.Create;
begin
inherited CreateData(SizeOf(TCefApp));
with PCefApp(FData)^ do
begin
on_before_command_line_processing := cef_app_on_before_command_line_processing;
on_register_custom_schemes := cef_app_on_register_custom_schemes;
get_resource_bundle_handler := cef_app_get_resource_bundle_handler;
get_browser_process_handler := cef_app_get_browser_process_handler;
get_render_process_handler := cef_app_get_render_process_handler;
end;
end;
// TCustomCefApp
constructor TCustomCefApp.Create(const aCefApp : TCefApplication);
begin
inherited Create;
FCefApp := aCefApp;
end;
destructor TCustomCefApp.Destroy;
begin
FCefApp := nil;
inherited Destroy;
end;
procedure TCustomCefApp.OnBeforeCommandLineProcessing(const processType: ustring; const commandLine: ICefCommandLine);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnBeforeCommandLineProcessing(processType, commandLine);
end;
procedure TCustomCefApp.OnRegisterCustomSchemes(const registrar: TCefSchemeRegistrarRef);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnRegisterCustomSchemes(registrar);
end;
procedure TCustomCefApp.GetResourceBundleHandler(var aHandler : ICefResourceBundleHandler);
begin
if (FCefApp <> nil) then
FCefApp.Internal_CopyResourceBundleHandler(aHandler)
else
aHandler := nil;
end;
procedure TCustomCefApp.GetBrowserProcessHandler(var aHandler : ICefBrowserProcessHandler);
begin
if (FCefApp <> nil) then
FCefApp.Internal_CopyBrowserProcessHandler(aHandler)
else
aHandler := nil;
end;
procedure TCustomCefApp.GetRenderProcessHandler(var aHandler : ICefRenderProcessHandler);
begin
if (FCefApp <> nil) then
FCefApp.Internal_CopyRenderProcessHandler(aHandler)
else
aHandler := nil;
end;
end.
|
unit SQLiteDataSetProvider;
interface
uses
SysUtils, Classes, Provider, DB, DBClient, DSIntf, SQLite3, Contnrs, Windows;
type
TSiagriDataPacketWriter = class;
TDataSetToSQLiteBind = class;
TDataSetProviderWrap = class(Provider.TBaseProvider)
private
FDataSet: TDataSet;
FDataSetOpened: Boolean;
FDSWriter: TDataPacketWriter;
end;
TEditMask = type string;
TMyField = class(TComponent)
private
FAutoGenerateValue: TAutoRefreshFlag;
FDataSet: TDataSet;
FFieldName: string;
FFields: TFields;
FDataType: TFieldType;
FReadOnly: Boolean;
FFieldKind: TFieldKind;
FAlignment: TAlignment;
FVisible: Boolean;
FRequired: Boolean;
FValidating: Boolean;
FSize: Integer;
FOffset: Integer;
FFieldNo: Integer;
FDisplayWidth: Integer;
FDisplayLabel: string;
FEditMask: TEditMask;
FValueBuffer: Pointer;
end;
TSQLiteDataSetProvider = class(TDataSetProvider)
private
FTempDataSetName: String;
FDataPacketWriter: TSiagriDataPacketWriter;
function GetTemporaryTableNameID: String;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
end;
TSQLiteAux = class
public
class function GenerateFieldsSQL(FieldDefs: TFieldDefs): String; static; public
class procedure CheckError(Erro: Integer);
class procedure ExecuteSQL(const SQL: String);
class procedure PrepareSQL(const SQL: String; var Stmt: TSQLiteStmt);
class function GetTableName(DataSet: TDataSet): String;
class procedure SetFieldData(FInsertStmt: TSQLiteStmt; Field: TField);
end;
TSiagriDataPacketWriter = class(TDataPacketWriter)
private
FDataSetToSQLiteBind: TDataSetToSQLiteBind;
protected
procedure AddColumn(const Info: TPutFieldInfo); override;
procedure AddConstraints(DataSet: TDataSet); override;
procedure AddDataSetAttributes(DataSet: TDataSet); override;
procedure AddFieldLinks(const Info: TInfoArray); override;
procedure AddIndexDefs(DataSet: TDataSet; const Info: TInfoArray); override;
procedure WriteMetaData(DataSet: TDataSet; const Info: TInfoArray;
IsReference: Boolean = False); override;
function WriteDataSet(DataSet: TDataSet; var Info: TInfoArray;
RecsOut: Integer): Integer; override;
published
public
procedure GetDataPacket(DataSet: TDataSet; var RecsOut: Integer;
out Data: OleVariant); override;
constructor Create; override;
destructor Destroy; override;
end;
PInsertSQLiteRec = ^TInsertSQLiteRec;
TInsertSQLiteRec = record
Table: String;
DataSet: TDataSet;
InsertStmt: TSQLiteStmt;
FieldsDefs: TFieldDefs;
Params: TParams;
end;
PDataSetToSQLiteBind = ^TDataSetToSQLiteBind;
TDataSetToSQLiteBind = class
private
FBindings: TList;
procedure GenerateInsertStmt(Rec: PInsertSQLiteRec);
public
function GetBinding(DataSet: TDataSet): PInsertSQLiteRec; overload;
function GetBinding(DataSetName: String): PInsertSQLiteRec; overload;
constructor Create;
destructor Destroy; override;
end;
var
Database: TSQLiteDB;
TemporaryTableID: Int64;
FIgnore: PAnsiChar;
FieldTempBuffer: TBlobByteData;
implementation
uses Dialogs, TypInfo, Math, FmtBCD;
{ TSiagriDataSetProvider }
destructor TSQLiteDataSetProvider.Destroy;
begin
// Provider destroy FDataPacketWriter.Free;
inherited;
end;
function TSQLiteDataSetProvider.GetTemporaryTableNameID: String;
begin
Inc(TemporaryTableID);
Result := 'TMP_' + IntToHex(TemporaryTableID, 2);
end;
constructor TSQLiteDataSetProvider.Create(AOwner: TComponent);
begin
inherited;
FTempDataSetName := GetTemporaryTableNameID;
FDataPacketWriter := TSiagriDataPacketWriter.Create;
TDataSetProviderWrap(Self).FDSWriter := FDataPacketWriter;
end;
{ TSQLiteAux }
class procedure TSQLiteAux.CheckError(Erro: Integer);
var
S: PAnsiChar;
begin
if not (Erro in [SQLITE_DONE, SQLITE_OK]) then
begin
S := _SQLite3_ErrMsg(Database);
raise Exception.Create(String(UTF8String(S)));
end;
end;
class procedure TSQLiteAux.ExecuteSQL(const SQL: String);
var
SQL8: UTF8String;
begin
SQL8 := UTF8String(SQL);
CheckError(_SQLite3_Exec(Database, @SQL8[1], nil, nil, FIgnore));
end;
function GetStrDataType(DataType: TFieldType): String;
begin
case DataType of
ftString, ftWideString:
Result := 'TEXT';
ftOraBlob, ftOraClob, ftBytes, ftVarBytes, ftBlob, ftMemo, ftGraphic, ftFmtMemo:
Result := 'BLOB';
ftSmallint, ftInteger, ftWord, ftLargeint, ftBoolean,
ftTime, ftDate:
Result := 'INTEGER';
ftDateTime, ftTimeStamp,
ftFloat, ftCurrency, ftBCD:
Result := 'REAL';
else
raise Exception.Create('Field type not supported: ' + GetEnumName(TypeInfo(TFieldType), Ord(DataType)));
end;
end;
class function TSQLiteAux.GenerateFieldsSQL(FieldDefs: TFieldDefs): String;
var
I: Integer;
begin
Result := '';
for I := 0 to FieldDefs.Count - 1 do
with FieldDefs[I] do
Result := Result + Format('%s %s, ', [Name, GetStrDataType(DataType)]);
end;
class function TSQLiteAux.GetTableName(DataSet: TDataSet): String;
var
Owner: TComponent;
begin
Owner := DataSet.Owner;
Result := DataSet.Name;
while (Owner <> nil) and (Owner.Name <> '') do
begin
Result := Owner.Name + '_' + Result;
Owner := Owner.Owner;
end;
end;
class procedure TSQLiteAux.PrepareSQL(const SQL: String; var Stmt: TSQLiteStmt);
var
SQL8: UTF8String;
begin
SQL8 := UTF8String(SQL);
CheckError(_SQLite3_Prepare_v2(Database, @SQL8[1], -1, Stmt, FIgnore));
end;
class procedure TSQLiteAux.SetFieldData(FInsertStmt: TSQLiteStmt;
Field: TField);
var
pindex, BlobSize, date: Integer;
Null: Boolean;
TimeStamp: TTimeStamp;
bcd: String;
begin
inherited;
pindex := Field.FieldNo;
if Field.DataSize > Length(FieldTempBuffer) then
SetLength(FieldTempBuffer, Max(1024, Field.DataSize));
if Field.IsBlob then
begin
BlobSize := Field.DataSet.GetBlobFieldData(Field.FieldNo, FieldTempBuffer);
Null := BlobSize = 0;
end
else
Null := not Field.DataSet.GetFieldData(Field.FieldNo, @FieldTempBuffer[0]);
if Null then
TSQLiteAux.CheckError(_SQLite3_Bind_null(FInsertStmt, pindex))
else
case Field.DataType of
ftString, ftWideString:
begin
TSQLiteAux.CheckError(_SQLite3_Bind_text(FInsertStmt, pindex,
@FieldTempBuffer[0], -1, SQLITE_TRANSIENT));
end;
ftOraBlob, ftOraClob, ftBytes, ftVarBytes, ftBlob, ftMemo, ftGraphic, ftFmtMemo:
TSQLiteAux.CheckError(_SQLite3_Bind_Blob(FInsertStmt, pindex,
@FieldTempBuffer[0], BlobSize, nil));
ftSmallint, ftInteger, ftWord, ftBoolean:
TSQLiteAux.CheckError(_SQLite3_Bind_Int(FInsertStmt, pindex,
PInteger(@FieldTempBuffer[0])^));
ftLargeint:
TSQLiteAux.CheckError(_SQLite3_Bind_int64(FInsertStmt, pindex,
PInt64(@FieldTempBuffer[0])^));
ftTime:
begin
TSQLiteAux.CheckError(_SQLite3_Bind_Int(FInsertStmt, pindex,
PInteger(@FieldTempBuffer[0])^));
end;
ftDate:
begin
date := PInteger(@FieldTempBuffer[0])^;
TSQLiteAux.CheckError(_SQLite3_Bind_Int(FInsertStmt, pindex,
date));
end;
ftDateTime, ftTimeStamp,
ftFloat, ftCurrency:
TSQLiteAux.CheckError(_SQLite3_Bind_Double(FInsertStmt, pindex,
PDouble(@FieldTempBuffer[0])^));
ftBCD, ftFMTBcd:
begin
bcd := BcdToStr(PBcd(@FieldTempBuffer[0])^);
TSQLiteAux.CheckError(_SQLite3_Bind_text(FInsertStmt, pindex,
@bcd[1], -1, SQLITE_TRANSIENT));
end;
else
raise Exception.Create('Field type not supported');
end;
end;
{ TSiagriDataPacketWriter }
procedure TSiagriDataPacketWriter.AddColumn(const Info: TPutFieldInfo);
begin
ShowMessage('AddColumn');
end;
procedure TSiagriDataPacketWriter.AddConstraints(DataSet: TDataSet);
begin
ShowMessage('AddConstraints');
end;
procedure TSiagriDataPacketWriter.AddDataSetAttributes(DataSet: TDataSet);
begin
ShowMessage('AddDataSetAttributes');
end;
procedure TSiagriDataPacketWriter.AddFieldLinks(const Info: TInfoArray);
begin
ShowMessage('AddFieldLinks');
end;
procedure TSiagriDataPacketWriter.AddIndexDefs(DataSet: TDataSet; const Info: TInfoArray);
begin
ShowMessage('AddIndexDefs');
end;
constructor TSiagriDataPacketWriter.Create;
begin
inherited;
FDataSetToSQLiteBind := TDataSetToSQLiteBind.Create;
end;
destructor TSiagriDataPacketWriter.Destroy;
begin
FDataSetToSQLiteBind.Free;
inherited;
end;
procedure TSiagriDataPacketWriter.GetDataPacket(DataSet: TDataSet; var RecsOut: Integer; out Data: OleVariant);
var
FPutFieldInfo: TInfoArray;
SQL: String;
i: Integer;
begin
TSQLiteAux.ExecuteSQL('BEGIN TRANSACTION');
try
FPutFieldInfo := nil;
while FDataSetToSQLiteBind.FBindings.Count > 0 do
begin
i := FDataSetToSQLiteBind.FBindings.Count - 1;
SQL := Format('drop table %s', [PInsertSQLiteRec(FDataSetToSQLiteBind.FBindings[i]).Table]);
TSQLiteAux.ExecuteSQL(SQL);
FDataSetToSQLiteBind.FBindings.Delete(i);
end;
RecsOut := WriteDataSet(DataSet, FPutFieldInfo, RecsOut);
finally
TSQLiteAux.ExecuteSQL('COMMIT TRANSACTION');
end;
Data := Integer(@FDataSetToSQLiteBind);
end;
function TSiagriDataPacketWriter.WriteDataSet(DataSet: TDataSet; var Info: TInfoArray; RecsOut: Integer): Integer;
var
i, count: Integer;
Rec: PInsertSQLiteRec;
Details: TList;
HasDetails: Boolean;
function OpenCloseDetails(Info: TInfoArray; ActiveState: Boolean): Boolean;
var
I, RecsOut: Integer;
List: TList;
begin
Result := False;
for I := 0 to Details.Count -1 do
begin
TDataSet(Details[i]).Active := ActiveState;
if ActiveState then
begin
RecsOut := -1;
WriteDataSet(TDataSet(Details[i]), Info, RecsOut);
end;
end;
end;
begin
Result := 0;
if RecsOut = AllRecords then
RecsOut := High(Integer);
Rec := FDataSetToSQLiteBind.GetBinding(DataSet);
Details := TList.Create;
try
DataSet.GetDetailDataSets(Details);
HasDetails := Details.Count > 0;
count := DataSet.FieldCount;
while not DataSet.Eof do
begin
_SQLite3_Reset(Rec.InsertStmt);
for i := 0 to count - 1 do
begin
TSQLiteAux.SetFieldData(Rec.InsertStmt, DataSet.Fields[i]);
end;
_SQLite3_Step(Rec.InsertStmt);
Inc(Result);
if HasDetails then
OpenCloseDetails(Info, true);
if Result < RecsOut then
begin
DataSet.Next;
end;
end;
OpenCloseDetails(Info, False);
finally
Details.Free;
end;
end;
procedure TSiagriDataPacketWriter.WriteMetaData(DataSet: TDataSet; const Info: TInfoArray; IsReference: Boolean);
begin
end;
{ TDataSetToSQLiteBind }
constructor TDataSetToSQLiteBind.Create;
begin
inherited;
FBindings := TList.Create;
end;
destructor TDataSetToSQLiteBind.Destroy;
var
i: Integer;
begin
for i := 0 to FBindings.Count - 1 do
FreeMem(FBindings[i]);
FBindings.Free;
inherited;
end;
function TDataSetToSQLiteBind.GetBinding(DataSet: TDataSet): PInsertSQLiteRec;
var
i: Integer;
Rec: PInsertSQLiteRec;
FieldsSQL, CreateSQL: String;
List: TList;
Params: TParams;
begin
if DataSet.FieldDefs.Count = 0 then
raise Exception.Create('No fields in dataset.');
for i := 0 to FBindings.Count - 1 do
if (PInsertSQLiteRec(FBindings[i]).DataSet = DataSet) then
begin
Result := PInsertSQLiteRec(FBindings[i]);
Exit;
end;
Rec := AllocMem(sizeof(TInsertSQLiteRec));
Rec.Table := TSQLiteAux.GetTableName(DataSet);
Rec.DataSet := DataSet;
Rec.FieldsDefs := TFieldDefs.Create(DataSet);
Rec.FieldsDefs.Assign(DataSet.FieldDefs);
Rec.InsertStmt := nil;
FieldsSQL := TSQLiteAux.GenerateFieldsSQL(DataSet.FieldDefs);
FieldsSQL := Copy(FieldsSQL, 1, Length(FieldsSQL) - 2);
CreateSQL := Format('create table %s (%s)', [Rec.Table, FieldsSQL]);
TSQLiteAux.ExecuteSQL(CreateSQL);
Params := IProviderSupport(DataSet).PSGetParams;
Rec.Params := Params;
if Assigned(Params) and (Params.Count > 0) then
begin
CreateSQL := Format('create index idx_pars_%s on %s(', [Rec.Table, Rec.Table]);
for i := 0 to Params.Count - 1 do
CreateSQL := CreateSQL + Params[i].Name + ', ';
CreateSQL := Copy(CreateSQL, 1, Length(CreateSQL)-2) + ')';
TSQLiteAux.ExecuteSQL(CreateSQL);
end;
GenerateInsertStmt(Rec);
List := TList.Create;
try
DataSet.GetDetailDataSets(List);
for i := 0 to List.Count - 1 do
Rec.FieldsDefs.Add(DataSet.Name + TDataSet(List[i]).Name, ftDataSet);
finally
List.Free;
end;
FBindings.Add(Rec);
Result := Rec;
end;
procedure TDataSetToSQLiteBind.GenerateInsertStmt(Rec: PInsertSQLiteRec);
var
i: Integer;
Name, SQL, Fields: String;
begin
Fields := '';
for i := 0 to Rec.DataSet.FieldCount - 1 do
begin
Name := Rec.DataSet.Fields[i].FieldName;
Fields := Fields + Name + ', ';
end;
Fields := Copy(Fields, 1, Length(Fields)-2);
SQL := 'insert into ' + Rec.Table + '(' + Fields + ') values (' +
StringReplace(':' + Fields, ', ', ', :', [rfReplaceAll]) + ')';
if (Rec.InsertStmt <> nil) then
_SQLite3_Finalize(Rec.InsertStmt);
TSQLiteAux.PrepareSQL(SQL, Rec.InsertStmt);
end;
function TDataSetToSQLiteBind.GetBinding(DataSetName: String): PInsertSQLiteRec;
var
i: Integer;
begin
for i := 0 to FBindings.Count - 1 do
if (PInsertSQLiteRec(FBindings[i]).Table = DataSetName) then
begin
Result := PInsertSQLiteRec(FBindings[i]);
Exit;
end;
raise Exception.Create('Dataset not found.');
end;
initialization
TemporaryTableID := 0;
if _SQLite3_Open(':memory:', Database) <> 0 then
raise Exception.Create('Can''t open memory database.');
finalization
_SQLite3_Close(Database);
end.
|
unit Wwlocate;
{
//
// Component : TwwLocateDialog
//
// Non-indexed searching
//
// Copyright (c) 1995, 1996, 1997 by Woll2Woll Software
//
//
}
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, db, ExtCtrls,
dbtables, dbctrls, {Wwdbcomb, }wwstr;
type
TwwLocateMatchType = (mtExactMatch, mtPartialMatchStart, mtPartialMatchAny);
TwwFieldSortType = (fsSortByFieldNo, fsSortByFieldName);
TwwDefaultButtonType = (dbFindFirst, dbFindNext);
TwwFieldSelection = (fsAllFields, fsVisibleFields);
TwwLocateDlg = class;
TwwOnInitLocateDlgEvent = procedure(Dialog : TwwLocateDlg) of object;
TwwLocateDlg = class(TForm)
SearchTypeGroup: TGroupBox;
FieldsGroup: TGroupBox;
CaseSensitiveCheckBox: TCheckBox;
ExactMatchBtn: TRadioButton;
PartialMatchStartBtn: TRadioButton;
PartialMatchAnyBtn: TRadioButton;
Panel1: TPanel;
FieldValueGroup: TGroupBox;
SearchValue: TEdit;
FirstButton: TButton;
NextButton: TButton;
FieldNameComboBox: TComboBox;
procedure FindFirst(Sender: TObject);
procedure FindNextBtnClick(Sender: TObject);
procedure BitBtn1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FieldNameComboBoxChange(Sender: TObject);
procedure FieldNameComboBoxEnter(Sender: TObject);
procedure FieldNameComboBoxExit(Sender: TObject);
procedure FieldNameComboBoxKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
private
Function GetFieldNameFromTitle(fieldTitle: string): string;
procedure ApplyIntl;
public
DataSet: TDataSet;
CancelBtn: TButton;
DlgComponent: TComponent;
Function FindMatch(FromBeginning: boolean): boolean;
constructor Create(AOwner: TComponent); override;
end;
TwwLocateDialog = class(TComponent)
private
FCaption: String;
FDataField: String;
FDataLink: TDataLink;
FFieldValue: string;
FMatchType: TwwLocatematchType;
FCaseSensitive: boolean;
FSortFields: TwwFieldSortType;
FDefaultButton: TwwDefaultButtonType;
FFieldSelection: TwwFieldSelection;
FShowMessages: boolean;
FOnInitDialog: TwwOnInitLocateDlgEvent;
procedure SetDataSource(value : TDataSource);
Function GetDataSource: TDataSource;
protected
procedure DoInitDialog; virtual; { called by locate dialog form }
public
Form: TwwLocateDlg; {Used by TwwLocateDlg }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: boolean; virtual; { shows dialog }
function FindPrior: boolean;
function FindNext: boolean;
function FindFirst: boolean;
property FieldValue: string read FFieldValue write FFieldValue;
published
property Caption: string read FCaption write FCaption;
property DataSource: TDataSource read GetDataSource write SetDataSource;
property SearchField: String read FDataField write FDataField;
property MatchType: TwwLocateMatchType read FMatchType write FMatchType;
property CaseSensitive: boolean read FCaseSensitive write FCaseSensitive;
property SortFields: TwwFieldSortType read FSortFields write FSortFields;
property DefaultButton: TwwDefaultButtonType read FDefaultButton write FDefaultButton;
property FieldSelection: TwwFieldSelection read FFieldSelection write FFieldSelection;
property ShowMessages: boolean read FShowMessages write FShowMessages;
property OnInitDialog: TwwOnInitLocateDlgEvent read FOnInitDialog write FOnInitDialog;
end;
Function wwFindMatch(FromBeginning: boolean;
DataSet: TDataSet;
searchField: string;
searchValue: string;
matchType: TwwLocateMatchType;
caseSens: boolean): boolean;
var
wwLocateDlg: TwwLocateDlg;
implementation
uses wwCommon, wwSystem, wwintl, wwtable,
(*
{$ifdef DELPHI3_CS}
wwclient,
{$endif}
*)
{$ifdef win32}
bde;
{$else}
dbiprocs, dbierrs, dbitypes;
{$endif}
{$R *.DFM}
Function Match(val1: string; val2: string;
matchType: TwwLocateMatchType;
caseSens: boolean): boolean;
var matchPos: integer;
begin
if not caseSens then val1:= Uppercase(val1);
if MatchType = mtExactMatch then begin
if length(val1)<>length(val2) then result:= False
else begin
if length(val1)=0 then result:= True
else begin
matchPos:= Pos(val2, val1);
result:= (matchPos=1);
end
end
end else if matchType = mtPartialMatchStart then
begin
matchPos:= Pos(val2, val1);
result:= (matchPos=1);
end
else if MatchType = mtPartialMatchAny then
begin
matchPos:= Pos(val2, val1);
result:= (matchPos<>0);
end
else result:= False;
end;
Function MemoMatch(field : TField;
memoBuffer: PChar; val1 :Pchar;
matchType: TwwLocateMatchType;
caseSens: boolean): boolean;
var matchPtr: PChar;
numread: integer;
blobStream: TBlobStream;
begin
result:= False;
blobStream:= Nil;
try
blobStream:= TBlobStream.create(TBlobField(field), bmRead);
if blobStream=Nil then begin
MessageDlg('Fail to create blob', mtinformation, [mbok], 0);
exit;
end;
numread:= blobStream.read(memobuffer^, 32767);
memobuffer[numread]:= #0; { null-terminate }
if numread = 0 then strcopy(memobuffer, '');
if not caseSens then strUpper(memobuffer);
if MatchType = mtExactMatch then begin
if strlen(val1)<>numread then result:= False
else begin
matchPtr:= strPos(memobuffer, val1);
if matchPtr<>Nil then
result:= (matchPtr=memoBuffer);
end
end else if matchType = mtPartialMatchStart then
begin
matchPtr:= strPos(memobuffer, val1);
if matchPtr<>Nil then
result:= (matchPtr=memoBuffer);
end
else if MatchType = mtPartialMatchAny then
begin
matchPtr:= strPos(memobuffer, val1);
result:= (matchPtr<>Nil);
end
else result:= False;
finally
blobStream.free;
end;
end;
Function ValueAsString(field : TField; buffer: PChar) : string;
type
WordPtr =^Word;
IntegerPtr = ^Integer;
LongPtr =^LongInt;
FloatPtr = ^Double;
TDateTimeRec = record
case TFieldType of
ftDate: (Date: Longint);
ftTime: (Time: Longint);
ftDateTime: (DateTime: TDateTime);
end;
DateTimePtr = ^TDateTimeRec;
var
DateTimeData: TDateTimeRec;
floatValue: Double;
{$ifdef win32}
TimeStamp: TTimeStamp;
{$endif}
begin
result:= '';
case field.DataType of
ftString:
begin
if (field is TStringField) then
if TStringField(field).transliterate then
OemToAnsi(buffer, buffer);
result:= strPas(buffer);
end;
ftSmallInt, ftWord: result:= inttostr(WordPtr(buffer)^);
ftInteger: result:= inttostr(LongPtr(buffer)^);
{$ifdef win32}
ftAutoInc: result:= inttostr(LongPtr(buffer)^); { 12/2/96 - Support autoincrement field }
{$endif}
ftFloat, ftBCD, ftCurrency:
begin
floatValue:= FloatPtr(buffer)^;
result:= floattostr(floatValue);
end;
ftBoolean: begin
if buffer[0]<>char(0) then result:= 'True'
else result:= 'False';
end;
ftDateTime: begin
DateTimeData:= DateTimePtr(buffer)^;
{$ifdef win32}
result := DateToStr(TimeStampToDateTime(MSecsToTimeStamp(FloatPtr(Buffer)^))); {12/10/96 }
{$else}
result:= DateToStr(DateTimeData.DateTime/MSecsPerDay);
{$endif}
end;
ftDate : begin
DateTimeData:= DateTimePtr(buffer)^;
{$ifdef win32}
TimeStamp.Time:= 0;
TimeStamp.Date:= DateTimeData.Date;
result:= DateToStr(TimeStampToDateTime(TimeStamp));
{$else}
result:= DateToStr(DateTimeData.Date);
{$endif}
end;
ftTime : begin
DateTimeData:= DateTimePtr(buffer)^;
result:= TimeToStr(DateTimeData.Time/MSecsPerDay);
end;
else;
end
end;
Function wwFindMatch(FromBeginning: boolean;
DataSet: TDataSet;
searchField: string;
searchValue: string;
matchType: TwwLocateMatchType;
caseSens: boolean): boolean;
var FindText, TableFieldValue: string;
fieldNo: integer;
MatchFound: boolean;
cfindText, recBuffer, buffer, memobuffer: PChar;
isBlank: Bool;
Bookmark: TBookmark;
fldtype: TFieldType;
curfield: TField;
currentValue: string;
stopOnMismatch: boolean;
firstIndexField: TField;
IndexFieldCount: integer;
Function IndexCaseSensitive(Tbl: TDataSet): boolean;
var i: integer;
begin
result:= False;
if Tbl is TTable then with Tbl as TTable do begin
for i:= 0 to IndexDefs.count-1 do begin
if (Uppercase(IndexDefs.Items[i].Name)=Uppercase(IndexName)) then begin
result:= not (ixCaseInsensitive in IndexDefs.Items[i].Options);
break;
end
end
end
(*
{$ifdef DELPHI3_CS}
else with Tbl as TwwClientDataSet do begin
for i:= 0 to IndexDefs.count-1 do begin
if (Uppercase(IndexDefs.Items[i].Name)=Uppercase(IndexName)) then begin
result:= not (ixCaseInsensitive in IndexDefs.Items[i].Options);
break;
end
end
end
{$endif}
*)
end;
{ Make sure indexed field is in field map}
Function ValidIndexField: boolean;
var parts: TStrings;
i: integer;
begin
(*
{$ifdef DELPHI3_CS}
if (DataSet is TwwClientDataSet) then begin
result:= True;
exit;
end;
{$endif}
*)
result:= False;
parts:= TStringList.create;
with (DataSet as TTable) do for i:= 0 to IndexDefs.count-1 do begin
with IndexDefs do begin
if (Uppercase(IndexName)=Uppercase(Items[i].name)) then
begin
strBreakApart(Items[i].fields, ';', parts);
if parts.count<=0 then continue;
result:= FindField(parts[0])<>Nil;
break;
end
end
end;
parts.Free;
end;
procedure ApplyMatch;
begin
dataset.updatecursorpos; {4/14/97}
dataset.resync([rmExact,rmCenter]); { Always call resync }
{ dataset.resync([]); { Always call resync }
MatchFound := True;
end;
Function FloatingType(field: TField): boolean;
begin
result:= field.DataType in [ftFloat, ftBCD, ftCurrency];
end;
Function GetNextFieldValue(Forward: boolean; var FieldValue: string): boolean;
begin
FieldValue:= '';
if wwisNonBDEField(curField) then begin
Result:= not DataSet.eof;
if Result then begin
Dataset.Next;
FieldValue:= curField.asString;
end
end
else begin
result:= dbiGetNextRecord((Dataset as TDBDataSet).handle, dbiNoLock, buffer, nil)=0;
if result then begin
dbiGetField((DataSet as TDBDataSet).handle, FieldNo+1, buffer, recBuffer, isBlank);
if isBlank then FieldValue:= '' { 4/29/97 - Delphi 1 bug with null fields requires this }
else FieldValue:= ValueAsString(curField, recBuffer); {5/24/95}
end
end
end;
begin
Result:= False;
DataSet.checkBrowseMode;
curField:= DataSet.findField(searchField);
if curField=Nil then begin
MessageDlg('Field ' + searchField + ' not found.', mtWarning, [mbok], 0);
exit;
end;
FieldNo:= curField.FieldNo - 1;
if wwMemAvail(32767) then begin
MessageDlg('Out of memory', mtWarning, [mbok], 0);
exit;
end;
DataSet.updateCursorPos;
if not caseSens then FindText:= Uppercase(SearchValue)
else FindText:= SearchValue;
stopOnMismatch:= False;
(* {$ifdef Delphi3_cs}
if ((dataSet is TTable)
or (dataset is TwwClientDataSet))
{$else}
if (dataSet is TTable)
{$endif}
*)
if (dataSet is TTable)
and (curField.dataType<>ftMemo) and (not wwIsTableQuery(DataSet)) then
begin
(* {$ifdef Delphi3_cs}
if (dataSet is TTable) then begin
(dataset as TTable).IndexDefs.update;
FirstIndexField:= (dataSet as TTable).indexfields[0];
IndexFieldCount:= (dataSet as TTable).indexFieldCount;
end
else begin
(dataset as TwwClientDataSet).IndexDefs.update;
FirstIndexField:= (dataSet as TwwClientDataSet).indexfields[0];
IndexFieldCount:= (dataSet as TwwClientDataSet).indexFieldCount;
end;
{$else}
(dataset as TTable).IndexDefs.update;
FirstIndexField:= (dataSet as TTable).indexfields[0];
IndexFieldCount:= (dataSet as TTable).indexFieldCount;
{$endif}
*)
(dataset as TTable).IndexDefs.update;
IndexFieldCount:= (dataSet as TTable).indexFieldCount;
if IndexFieldCount>0 then FirstIndexField:= (dataSet as TTable).indexfields[0]
else FirstIndexField:= nil;
if not caseSens then currentValue:= Uppercase(curField.asString)
else currentValue:= curField.asString;;
if (indexFieldCount>0) and (matchType=mtExactMatch) and
validIndexField and
(Uppercase(curField.fieldName) = Uppercase(FirstIndexField.fieldName)) and
((currentValue<>FindText) or FromBeginning) and (curField.dataType<>ftBoolean) then
begin
if (curField.DataType <> ftString) or {case sensitive matches index }
(IndexCaseSensitive(dataSet) = caseSens) then
begin
if (dataSet is TTable) then
result:= (dataSet as TTable).findKey([FindText]);
(* {$ifdef Delphi3_cs}
else
result:= (dataSet as TwwClientDataSet).findKey([FindText]);
{$else}
;
{$endif}*)
exit;
end
end;
{ Partial match start using index}
if (indexFieldCount>0) and (matchType=mtPartialMatchStart) and
validIndexField and
(Uppercase(curField.fieldName) = Uppercase(FirstIndexField.fieldName)) and
(curField.dataType=ftString) then
begin
if (IndexCaseSensitive(dataSet) = caseSens) then
begin
stopOnMismatch:= True;
if ((not Match(FirstIndexField.asString, FindText, matchType, caseSens)) or
fromBeginning) then
begin
if not FromBeginning then begin
if not caseSens then begin
if (FindText<uppercase(FirstIndexField.asString)) then exit; {Not found}
end
else begin
if (FindText<FirstIndexField.asString) then exit; {Not found}
end
end;
if (dataSet is TTable) then
(dataSet as TTAble).findNearest([FindText]);
(* {$ifdef Delphi3_cs}
else
(dataSet as TwwClientDataSet).findNearest([FindText]);
{$else}
;
{$endif}*)
result:= Match(FirstIndexField.asString, FindText, matchType, caseSens);
exit;
end
end
end
end;
buffer:= Nil;
recBuffer:= Nil;
cfindText:= Nil;
memoBuffer:= Nil;
bookmark:= nil;
try
fldType:= curField.DataType;
GetMem(buffer, 32767);
GetMem(recBuffer, 256);
Bookmark:= Dataset.GetBookmark;
if FromBeginning then begin
DataSet.First; { do before allocating blob }
DataSet.updateCursorPos;
end;
if fldType = ftMemo then begin
GetMem(memoBuffer, 32767);
GetMem(cFindText, 256);
strpcopy(cfindText, FindText);
if not caseSens then strupper(CFindText);
end;
Screen.cursor:= crHourGlass;
if FromBeginning then begin
if fldType <> ftMemo then begin
if (matchType = mtExactMatch) and FloatingType(curField) and (FindText<>'') then begin
if wwStrToFloat(FindText) and (curField.asFloat=StrToFloat(FindText)) then
begin
ApplyMatch;
exit;
end
end
else if Match(curField.asString, FindText, matchType, caseSens) then
begin
ApplyMatch;
exit;
end
end
else begin
if MemoMatch(curField, memoBuffer, CFindText, matchType, caseSens) then
begin
ApplyMatch;
exit;
end
end;
DataSet.updateCursorPos;
end;
MatchFound:= False;
if fldType <> ftMemo then begin
if wwisNonBDEField(curField) then Dataset.DisableControls;
while GetNextFieldValue(True, TableFieldValue) do
begin
if (matchType = mtExactMatch) and FloatingType(curField) and (FindText<>'') then begin
if wwStrToFloat(FindText) and (StrToFloat(TableFieldValue)=StrToFloat(FindText)) then
begin
ApplyMatch;
exit;
end
end
else if Match(TableFieldValue, FindText, matchType, caseSens) then
begin
ApplyMatch;
break;
end
else if StopOnMismatch then break;
end
end
else begin
while True do
begin
if DataSet is TDBDataSet then
if dbiGetNextRecord((Dataset as TDBDataSet).handle, dbiNoLock, buffer, nil)<>0 then exit
else begin {5/12/97}
if DataSet.eof then exit;
DataSet.Next;
end;
if MemoMatch(curField, memoBuffer, CFindText, matchType, caseSens) then
begin
ApplyMatch;
break;
end
end
end;
finally
if wwisNonBDEField(curField) then Dataset.EnableControls;
FreeMem(recBuffer, 256);
FreeMem(buffer, 32767);
if curField.dataType = ftMemo then begin
FreeMem(cFindText, 256);
FreeMem(memoBuffer, 32767);
end;
Screen.cursor:= crDefault;
if (not MatchFound) then dataSet.gotoBookmark(bookmark);
dataSet.FreeBookmark(bookmark);
result:= MatchFound;
end;
end;
constructor TwwLocateDlg.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
CancelBtn:= TButton(wwCreateCommonButton(Self, bkCancel));
CancelBtn.TabOrder := 5;
CancelBtn.Width:= (screen.pixelsperinch * 72) div 96;
CancelBtn.visible:= True;
CancelBtn.Top:= NextButton.Top;
CancelBtn.Left:= FieldsGroup.Left + FieldsGroup.Width - CancelBtn.Width - 1;
CancelBtn.Height:= (screen.pixelsperinch * 27) div 96;
end;
Function TwwLocateDlg.GetFieldNameFromTitle(fieldTitle: string): string;
var i: integer;
begin
result:= '';
with DataSet do begin
{ Give priority to non-calculated fields of the same name, if they exist }
for i:= 0 to fieldCount-1 do begin
if wwisNonPhysicalField(fields[i]) then continue;
if strReplaceChar(fields[i].displayLabel,'~',' ')=strReplaceChar(fieldTitle,'~',' ') then begin
result:= fields[i].FieldName;
exit;
end
end;
for i:= 0 to fieldCount-1 do begin
if not wwisNonPhysicalField(fields[i]) then continue;
if strReplaceChar(fields[i].displayLabel,'~', ' ')=strReplaceChar(fieldTitle,'~', ' ') then begin
result:= fields[i].FieldName;
exit;
end
end
end;
end;
Function TwwLocateDlg.FindMatch(FromBeginning: boolean): boolean;
var
MatchType: TwwLocateMatchType;
curFieldName: string;
begin
result:= false;
if ExactMatchBtn.Checked then
MatchType:= mtExactmatch
else if PartialMatchStartBtn.Checked then
MatchType:= mtPartialMatchStart
else MatchType:= mtPartialMatchAny;
curFieldName:= getfieldNameFromTitle(FieldNameComboBox.text);
if curFieldName='' then exit;
result:= wwFindMatch(FromBeginning, DataSet, curFieldName,
searchValue.text, matchType, CaseSensitiveCheckbox.State<> cbUnchecked);
end;
procedure TwwLocateDlg.FindFirst(Sender: TObject);
begin
if not FindMatch(True) then begin
MessageDlg(wwInternational.UserMessages.LocateNoMatches,
mtInformation, [mbok], 0);
end
else ModalResult:= mrOK;
end;
procedure TwwLocateDlg.FindNextBtnClick(Sender: TObject);
begin
if not FindMatch(False) then begin
MessageDlg(wwInternational.UserMessages.LocateNoMoreMatches,
mtInformation, [mbok], 0);
end
else ModalResult:= mrOK;
end;
procedure TwwLocateDlg.BitBtn1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (key = VK_ESCAPE) then
ModalResult := mrCancel;
end;
function TwwLocateDialog.Execute: boolean;
var
field: TField;
i: integer;
begin
result:= True;
with TwwLocateDlg.create(Application) do
try
if (DataSource=Nil) or (DataSource.dataSet=Nil) or
(not DataSource.dataSet.active) then begin
MessageDlg('DataSource does not reference an active DataSet', mtError, [mbok], 0);
exit;
end;
DlgComponent:= Self;
field:= DataSource.DataSet.findField(SearchField);
FieldNameComboBox.items.clear;
if SortFields = fsSortByFieldNo then
FieldNameComboBox.sorted:= False;
if DefaultButton = dbFindFirst then begin
FirstButton.Default:= True;
NextButton.Default:= False;
end
else begin
FirstButton.Default:= False;
NextButton.Default:= True;
end;
with DataSource.DataSet do begin
for i:= 0 to fieldCount-1 do begin
{ if not fields[i].calculated then begin}
if (fields[i].dataType = ftBlob) or (fields[i].dataType=ftGraphic) or
(fields[i].dataType = ftVarBytes) or (fields[i].dataType=ftBytes) then
continue;
if (FFieldSelection = fsAllFields) or (fields[i].visible) then
FieldNameComboBox.items.add(strReplaceChar(fields[i].DisplayLabel, '~',' '));
{ end}
end
end;
if field<>Nil then begin
SearchValue.Text:= fieldValue;
FieldNameCombobox.itemIndex:=
FieldNameComboBox.items.indexOf(strReplaceChar(Field.displayLabel, '~',' '));
end
else SearchValue.text:= '';
DataSet:= dataSource.DataSet;
caseSensitiveCheckBox.checked:= caseSensitive;
case matchType of
mtExactMatch: ExactMatchBtn.checked:= True;
mtPartialMatchStart: PartialMatchStartBtn.checked:= True;
mtPartialMatchAny: PartialMatchAnyBtn.checked:= True;
end;
Caption:= self.Caption;
Result := ShowModal = IDOK;
{ Use user selections from dialog to update this component }
if ExactMatchBtn.Checked then
MatchType:= mtExactmatch
else if PartialMatchStartBtn.Checked then
MatchType:= mtPartialMatchStart
else MatchType:= mtPartialMatchAny;
caseSensitive:= caseSensitiveCheckBox.checked;
fieldValue:= SearchValue.Text;
SearchField:= getfieldNameFromTitle(FieldNameComboBox.text);
finally
Free;
end
end;
constructor TwwLocateDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
MatchType:= mtPartialMatchStart;
caseSensitive:= False;
SortFields:= fsSortByFieldName;
Caption:= 'Locate Field Value';
FDefaultButton:= dbFindNext;
FFieldSelection:= fsAllFields;
FDataLink:= TDataLink.create;
FShowMessages:= True;
end;
destructor TwwLocatedialog.Destroy;
begin
FDataLink.free;
inherited destroy;
end;
procedure TwwLocateDialog.SetDataSource(value : TDataSource);
begin
FDataLink.dataSource:= value;
end;
Function TwwLocateDialog.getDataSource: TDataSource;
begin
Result:= FdataLink.dataSource;
end;
function TwwLocateDialog.FindPrior: boolean;
begin
result:= False;
end;
function TwwLocateDialog.FindFirst: boolean;
begin
result:= False;
if (dataSource=Nil) or (datasource.dataset=Nil) or (not datasource.dataset.active) then
begin
MessageDlg('DataSource does not refer to an active table!', mtWarning, [mbok], 0);
exit;
end;
if FieldValue='' then begin
DefaultButton:= dbFindFirst;
result:= execute;
end
else begin
result:= wwFindMatch(True, DataSource.DataSet, SearchField, FieldValue,
matchType, caseSensitive);
if (not result) and FShowMessages then
MessageDlg(wwInternational.UserMessages.LocateNoMoreMatches,
mtInformation, [mbok], 0);
end
end;
function TwwLocateDialog.FindNext: boolean;
begin
result:= False;
if (dataSource=Nil) or (datasource.dataset=Nil) or (not datasource.dataset.active) then
begin
MessageDlg('DataSource does not refer to an active table!', mtWarning, [mbok], 0);
exit;
end;
if FieldValue='' then begin
DefaultButton:= dbFindNext;
result:= execute;
end
else begin
result:= wwFindMatch(False, DataSource.DataSet, SearchField, FieldValue,
matchType, caseSensitive);
if (not result) and FShowMessages then
MessageDlg(wwInternational.UserMessages.LocateNoMoreMatches,
mtInformation, [mbok], 0);
end
end;
procedure TwwLocateDlg.FieldNameComboBoxChange(Sender: TObject);
begin
SearchValue.Text:= '';
if not FieldNameComboBox.DroppedDown then SearchValue.setFocus;
end;
procedure TwwLocateDlg.FieldNameComboBoxEnter(Sender: TObject);
begin
NextButton.default:= False;
end;
procedure TwwLocateDlg.FieldNameComboBoxExit(Sender: TObject);
begin
NextButton.default:= True;
end;
procedure TwwLocateDlg.FieldNameComboBoxKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if (Key=VK_Return) and FieldNameComboBox.DroppedDown then
begin
FieldNameComboBox.DroppedDown := False;
SearchValue.setFocus;
end
end;
procedure TwwLocateDlg.FormShow(Sender: TObject);
var Dlg: TwwLocateDialog;
begin
ApplyIntl;
Dlg:= DlgComponent as TwwLocateDialog;
Dlg.Form:= self;
Dlg.DoInitDialog;
end;
Procedure TwwLocateDialog.DoInitDialog;
begin
if Assigned(FOnInitDialog) then OnInitDialog(Form);
end;
procedure TwwLocateDlg.ApplyIntl;
begin
Font.Style:= wwInternational.DialogFontStyle;
with wwInternational.LocateDialog do begin
FieldValueGroup.caption:= FieldValueLabel;
SearchTypeGroup.caption:= SearchTypeLabel;
CaseSensitiveCheckbox.caption:= CaseSensitiveLabel;
ExactMatchBtn.caption:= MatchExactLabel;
PartialMatchStartBtn.caption:= MatchStartLabel;
PartialMatchAnyBtn.caption:= MatchAnyLabel;
FieldsGroup.caption:= FieldsLabel;
FirstButton.caption:= BtnFirst;
NextButton.caption:= BtnNext;
CancelBtn.caption:= BtnCancel;
SearchValue.Hint:= FieldValueHint;
CaseSensitiveCheckbox.Hint:= CaseSensitiveHint;
ExactMatchBtn.Hint:= MatchExactHint;
PartialMatchStartBtn.Hint:= MatchStartHint;
PartialMatchAnyBtn.Hint:= MatchAnyHint;
FirstButton.Hint:= BtnFirstHint;
NextButton.Hint:= BtnNextHint;
FieldNameComboBox.Hint:= FieldNameHint;
end;
end;
end.
|
unit NewFrontiers.Configuration.Ini;
interface
uses NewFrontiers.Configuration, IniFiles;
type
/// <summary>
/// Gibt an, wie die INI Datei geöffnet werden soll. Bei imAlwaysOpen, wird
/// die Datei einmal geöffnet und beim Zerstören des Objekts wieder
/// geschlossen. Bei imAlwaysClosed wird die Datei nach jedem Zugriff
/// geschlossen.
/// </summary>
TIniMode = (imAlwaysOpen, imAlwaysClosed);
TConfigurationIni = class(TInterfacedObject, IConfiguration)
protected
_filename: string;
_iniFile: TIniFile;
_mode: TIniMode;
procedure loadConfiguration;
procedure closeConfiguration;
public
/// <summary>
/// Dateiname inklusive Pfad
/// </summary>
property Filename: string read _filename write _filename;
/// <summary>
/// Modus für das Verhalten der Ini-Datei. Default: imAlwaysOpen
/// </summary>
property Mode: TIniMode read _mode write _mode;
constructor Create;
destructor Destroy; override;
function getString(aName: string; aDefault: string = ''): string;
function getInteger(aName: string; aDefault: integer = 0): integer;
function getBoolean(aName: string; aDefault: boolean = false): boolean;
function getDateTime(aName: string; aDefault: TDateTime = 0): TDateTime;
function setString(aName, aValue: string): boolean;
function setInteger(aName: string; aValue: integer): boolean;
function setBoolean(aName: string; aValue: boolean): boolean;
function setDateTime(aName: string; aValue: TDateTime): boolean;
end;
implementation
uses SysUtils, NewFrontiers.Utility.StringUtil, Classes;
{ TNfsConfigurationIni }
procedure TConfigurationIni.closeConfiguration;
begin
if (_iniFile = nil) then
begin
// TODO: Datei anlegen, falls diese nicht existiert
loadConfiguration;
end;
_iniFile.Free;
_iniFile := nil;
end;
constructor TConfigurationIni.Create;
begin
_mode := imAlwaysOpen;
end;
destructor TConfigurationIni.Destroy;
begin
closeConfiguration;
inherited;
end;
function TConfigurationIni.getBoolean(aName: string;
aDefault: boolean): boolean;
var Ident, Section: string;
begin
if (_iniFile = nil) then
loadConfiguration;
TStringUtil.StringParts(aName, '.', Section, Ident);
result := _iniFile.ReadBool(Section, Ident, aDefault);
if (_mode = imAlwaysClosed) then
closeConfiguration;
end;
function TConfigurationIni.getDateTime(aName: string;
aDefault: TDateTime): TDateTime;
var Ident, Section: string;
begin
if (_iniFile = nil) then
loadConfiguration;
TStringUtil.StringParts(aName, '.', Section, Ident);
result := _iniFile.ReadDateTime(Section, Ident, aDefault);
if (_mode = imAlwaysClosed) then
closeConfiguration;
end;
function TConfigurationIni.getInteger(aName: string;
aDefault: integer): integer;
var Ident, Section: string;
begin
if (_iniFile = nil) then
loadConfiguration;
TStringUtil.StringParts(aName, '.', Section, Ident);
result := _iniFile.ReadInteger(Section, Ident, aDefault);
if (_mode = imAlwaysClosed) then
closeConfiguration;
end;
function TConfigurationIni.getString(aName, aDefault: string): string;
var Ident, Section: string;
begin
if (_iniFile = nil) then
loadConfiguration;
TStringUtil.StringParts(aName, '.', Section, Ident);
if (not _iniFile.SectionExists(Section)) then
raise Exception.Create('Section ' + Section + ' in INI-Datei ' + Filename + ' nicht gefunden');
result := _iniFile.ReadString(Section, Ident, aDefault);
if (_mode = imAlwaysClosed) then
closeConfiguration;
end;
procedure TConfigurationIni.loadConfiguration;
begin
if (not FileExists(_filename)) then
raise Exception.Create(Format('Datei %s konnte nicht gefunden werden', [_filename]));
_iniFile := TIniFile.Create(Filename);
end;
function TConfigurationIni.setBoolean(aName: string; aValue: boolean): boolean;
var Ident, Section: string;
begin
result := true;
if (_iniFile = nil) then
loadConfiguration;
TStringUtil.StringParts(aName, '.', Section, Ident);
_iniFile.WriteBool(Section, Ident, aValue);
if (_mode = imAlwaysClosed) then
closeConfiguration;
end;
function TConfigurationIni.setDateTime(aName: string;
aValue: TDateTime): boolean;
var Ident, Section: string;
begin
result := true;
if (_iniFile = nil) then
loadConfiguration;
TStringUtil.StringParts(aName, '.', Section, Ident);
_iniFile.WriteDateTime(Section, Ident, aValue);
if (_mode = imAlwaysClosed) then
closeConfiguration;
end;
function TConfigurationIni.setInteger(aName: string;
aValue: integer): boolean;
var Ident, Section: string;
begin
result := true;
if (_iniFile = nil) then
loadConfiguration;
TStringUtil.StringParts(aName, '.', Section, Ident);
_iniFile.WriteInteger(Section, Ident, aValue);
if (_mode = imAlwaysClosed) then
closeConfiguration;
end;
function TConfigurationIni.setString(aName, aValue: string): boolean;
var Ident, Section: string;
begin
result := true;
if (_iniFile = nil) then
loadConfiguration;
TStringUtil.StringParts(aName, '.', Section, Ident);
_iniFile.WriteString(Section, Ident, aValue);
if (_mode = imAlwaysClosed) then
closeConfiguration;
end;
end.
|
unit SynUniFormatConTEXT;
{$I SynUniHighlighter.inc}
interface
uses
{$IFDEF SYN_CLX}
QClasses,
QGraphics,
QSynUniFormat,
QSynUniClasses,
QSynUniRules,
QSynUniHighlighter
{$ELSE}
Classes,
Graphics,
{$IFDEF SYN_COMPILER_6_UP}
Variants,
{$ENDIF}
SynUniFormat,
SynUniFormatNativeXml,
SynUniClasses,
SynUniRules,
SynUniHighlighter,
{$IFDEF CODEFOLDING}
SynEditCodeFolding,
{$ENDIF}
{$ENDIF}
SysUtils,
{ XMLIntf; } // DW
SimpleXML,
SynUniFormatNativeXml20;
type
TSynUniConTEXTAdditionalSettings = class
private
fCommentEndString: string;
fCommentBegString: string;
fBlockIndentEndStrings: string;
fBlockIndentBegStrings: string;
fBracketHighlightEndChars: string;
fBracketHighlightBegChars: string;
public
property BracketHighlightBegChars: string read fBracketHighlightBegChars write fBracketHighlightBegChars;
property BracketHighlightEndChars: string read fBracketHighlightEndChars write fBracketHighlightEndChars;
property BlockIndentBegStrings: string read fBlockIndentBegStrings write fBlockIndentBegStrings;
property BlockIndentEndStrings: string read fBlockIndentEndStrings write fBlockIndentEndStrings;
property CommentBegString: string read fCommentBegString write fCommentBegString;
property CommentEndString: string read fCommentEndString write fCommentEndString;
end;
type
TSynUniFormatConTEXT = class(TSynUniFormatNativeXml20)
class function ImportAdditional(AdditionalSettings: TSynUniConTEXTAdditionalSettings; ANode: IXMLNode): Boolean;
class function ExportAdditional(AdditionalSettings: TSynUniConTEXTAdditionalSettings; ANode: IXMLNode): Boolean;
class function ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; override;
class function ExportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; override;
end;
implementation
//------------------------------------------------------------------------------
class function TSynUniFormatConTEXT.ImportAdditional(
AdditionalSettings: TSynUniConTEXTAdditionalSettings;
ANode: IXMLNode): Boolean;
begin
with AdditionalSettings do begin
with ANode.EnsureChild('BracketHighlight') do begin
BracketHighlightBegChars := VarToStr(GetVarAttr('BegChars', ''));
BracketHighlightEndChars := VarToStr(GetVarAttr('EndChars', ''));
end;
with ANode.EnsureChild('BlockAutoIndent') do begin
BlockIndentBegStrings := VarToStr(GetVarAttr('BegStr', ''));
BlockIndentEndStrings := VarToStr(GetVarAttr('EndStr', ''));
end;
with ANode.EnsureChild('Comments') do begin
CommentBegString := VarToStr(GetVarAttr('BegStr', ''));
CommentEndString := VarToStr(GetVarAttr('EndStr', ''));
end;
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatConTEXT.ExportAdditional(
AdditionalSettings: TSynUniConTEXTAdditionalSettings;
ANode: IXMLNode): Boolean;
begin
with AdditionalSettings do begin
with ANode.EnsureChild('BracketHighlight') do begin
if (Length(BracketHighlightBegChars) <> 0) then
SetVarAttr('BegChars', BracketHighlightBegChars);
if (Length(BracketHighlightEndChars) <> 0) then
SetVarAttr('EndChars', BracketHighlightEndChars);
end;
with ANode.EnsureChild('BlockAutoIndent') do begin
if (Length(BlockIndentBegStrings) <> 0) then
SetVarAttr('BegStr', BlockIndentBegStrings);
if (Length(BlockIndentEndStrings) <> 0) then
SetVarAttr('EndStr', BlockIndentEndStrings);
end;
with ANode.EnsureChild('Comments') do begin
if (Length(CommentBegString) <> 0) then
SetVarAttr('BegStr', CommentBegString);
if (Length(CommentEndString) <> 0) then
SetVarAttr('EndStr', CommentEndString);
end;
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatConTEXT.ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean;
begin
inherited ImportHighlighter(SynUniSyn, ANode);
{
//TODO: Insert try..except
with ANode, SynUniSyn do
begin
Clear();
with EnsureChild('SyntaxColoring') do begin
ImportInfo(Info, EnsureChild('Info'));
ImportSchemes(Schemes, EnsureChild('Schemes'));
//# если убират?эт?строку, то перестанет работать. Замени её на чт?нить правильное ;-)
SynUniSyn.ActiveScheme := Schemes.GetSchemeName('Default');
ImportEditorProperties(EditorProperties, EnsureChild('Editor'));
ImportRange(MainRules, EnsureChild('MainRules'));
end;
ImportCodeFolding(FoldRegions, EnsureChild('CodeFolding').ChildNodes); //###
FormatVersion := '2.0';
end;
Result := True;
}
end;
//------------------------------------------------------------------------------
class function TSynUniFormatConTEXT.ExportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean;
begin
{
ANode.SetVarAttr('Version', '2.0');
with SynUniSyn do
begin
with ANode.AppendElement('SyntaxColoring') do
begin
ExportInfo(Info, AppendElement('Info'));
ExportSchemes(Schemes, AppendElement('Schemes'));
ExportEditorProperties(EditorProperties, AppendElement('Editor'));
ExportRange(MainRules, AppendElement('MainRules'));
end;
ExportCodeFolding(FoldRegions, ANode.AppendElement('CodeFolding'));
end;
Result := True;
}
end;
//------------------------------------------------------------------------------
end.
|
unit UPlat;
interface
uses
w3system, UE, UGlobalsNoUserTypes;
const
CRUMBLE_DELAY = 20;
MOVE_SPEED_INC = 0.5;
MOVE_SPEED_MAX = 5;
type TPlat = class(TObject)
X, Y : float; //X and Y co-ordinates
Width, Height : float;
GravSpeed : float; //How fast the gravity is
XMove,YMove : float; //How much the platform can move in the x and y direction
XMoved,YMoved : float; //How much the platform has moved in the x and y directions
InitX,InitY : float; //The initial x and y
MovingX,MovingY : boolean; //If the platform is moving in the x or y direction
MoveSpeed : float; //How fast the platform it moving
TimeTillFall : integer; //Time left till the platfrom will fall
horizontal, jumpThrough, noFall, NoWallJump, Crumble, Crumbling, Moves : boolean; //Possible properties of the platform
turretOnLeftOrTop, turretOnRightOrBottom : boolean; //If the platfrom is on the Left/Top side or the Right/Bottom side
constructor createR(ScreenWidth, ScreenHeight, PHeight, PWidth : integer;
Door1, Door2 : UE.TE; Rand, Fix : array of TPlat; verticals, through, fall, noWallJumps,
crumbles, Movers, MoversLtoR, MaximumMove, onToporLefts, onBottomorRights : float = 0);
constructor createF(newX, newY, newWidth, newHeight : integer; ThroughorWallJump, fall, willCrumble, //Through or no Wall Jump is so that
//if its a vertical it will disable wall jumps if its
//true instead of making a new paramiter
willMove, MovesUp : boolean = false; MaxMove : integer = 0;
onTopOrLeft, onBottomOrRight : boolean = false);
procedure CrumbleUpdate();
function MoveUpdate(px, py, px2, py2 : float) : array [0..1] of float; //returns a vector to move the player x and y
function PlayerCollidesPlat(px, py, px2, py2 : float) : boolean;
function collidesWithDoor(Door : TE) : boolean;
function collidesWithPlat(Plat : TPlat) : boolean;
end;
implementation
constructor TPlat.createF(newX, newY, newWidth, newHeight : integer; ThroughorWallJump, fall, willCrumble,
willMove, MovesUp : boolean = false; MaxMove : integer = 0;
onTopOrLeft, onBottomOrRight : boolean = false);
begin
X := newX;
Y := newY;
Width := newWidth;
Height := newHeight;
jumpThrough := ThroughorWallJump;
NoWallJump := false;
noFall := fall;
Crumble := willCrumble;
if Width < Height then //if it is vertical
begin
horizontal := false;
jumpThrough := false;
NoWallJump := ThroughorWallJump; //Only verticals can be wall jump platforms
jumpThrough := false;
end
else
horizontal := true;
GravSpeed := 0;
TimeTillFall := 0;
Moves := willMove;
InitX := newX;
InitY := newY;
if Moves then
begin
if MovesUp then
begin
MovingX := false;
MovingY := true;
XMove := 0;
YMove := MaxMove;
InitY := newY + (MaxMove/2);
end
else
begin
MovingX := true;
MovingY := false;
XMove := MaxMove;
YMove := 0;
InitX := newX + (MaxMove/2);
end;
XMoved := 0;
YMoved := 0;
end;
MoveSpeed := 0;
if onTopOrLeft then
turretOnLeftOrTop := true;
if onBottomOrRight then
turretOnRightOrBottom := true;
end;
constructor TPlat.createR(ScreenWidth, ScreenHeight, PHeight, PWidth : integer;
Door1, Door2 : UE.TE; Rand, Fix : array of TPlat; verticals, through, fall, NoWallJumps,
crumbles, Movers, MoversLtoR, MaximumMove, onToporLefts, onBottomorRights : float = 0);
const
MAX_TRIES = 10; //How many times it will try to spawn
var
i : integer;
Spawned : boolean;
howMany : integer;
vertical : integer;
begin
vertical := randomint(100); //This will pick a random number
if vertical < verticals then //if it is below the verticals percentage, it is vertical
horizontal := False
else
horizontal := True;
//Runs a spawning procedure if it is a horizontal platform
if horizontal = True then
begin
while Spawned = False do //Keeps spawning till it is not overlapping anything
begin
//Spawns a platform on the screen if it is not under the max_Tries
if howMany <= MAX_TRIES then
begin
//Picks a random x position on the screen
X := randomint(ScreenWidth);
//Picks a random Y position on the screen, then adds
//75 so the player can use it
Y := randomint(ScreenHeight - 75) + 75;
//picks a width between 50 and 200
Width := randomint(150) + 50;
Height := 10;
Spawned := True;
end
//Otherwise it will try off screen too, meaning it is struggling to spawn
//so it basically skips it
else
begin
//Picks a random x position
X := randomint(ScreenWidth + 10000);
//Picks a random Y position
Y := randomint(ScreenHeight + 10000);
//Adds 75 so the player can jump on it
Y += 75;
//Picks a width between 50 and 200
Width := randomint(150) + 50;
Height := 10;
Spawned := True;
end;
if Spawned = True then
begin
if collidesWithDoor(Door1) then //Checks if it overlapped with the door
begin
Spawned := False; //If it failed it will say it failed to spawn
howMany += 1; //Adds a try so it can count how many times it has failed
end;
end;
if Spawned = True then //Only works if the previous things worked
begin
if collidesWithDoor(Door2) then //Checks if it overlapped with the door
begin
Spawned := False; //If it failed it will say it failed to spawn
howMany += 1; //Adds a try so it can count how many times it has failed
end;
end;
if Spawned = True then //Only works if the previous things worked
begin
for i := 0 to High(Fix) do //Iterates through the fixed plats
begin
if collidesWithPlat(Fix[i]) then //checks if it overlapped
begin
Spawned := False; //If it failed it will say it failed to spawn.
howMany += 1; //Adds a try so it can count how many times it has failed.
end;
end;
end;
if Spawned = True then //Only works if the previous things worked
begin
for i := 0 to High(Rand) do //iterates through the random plats
begin
//Checks if it is horizontal as it is allowed to spawn over verticals
if Rand[i].horizontal = True then
begin
if collidesWithPlat(Rand[i]) then //checks if it overlapped
begin
Spawned := False; //If it failed it will record it failed to spawn
howMany += 1; //Adds a try so it can count how many times it has failed
end;
end;
end;
end;
end;
end;
//If it was selected vertical it will run the vertical spawning code
if horizontal = False then
begin
while Spawned = False do //Keeps spawning till it is not overlapping anything
begin
//Spawns a platform on the screen if it is not under the max_Tries
if howMany <= MAX_TRIES then
begin
//Picks a random x position on the screen
X := randomint(ScreenWidth);
//Picks a random Y position on the screen, then adds
//75 so the player can use it
Y := randomint(ScreenHeight - 75) + 75;
Width := 10;
//Sets the height to something between 50 and 200
Height := randomint(150) + 50;
Spawned := True;
end
//Otherwise it will try off screen too, meaning it is stuggling to spawn
//so it basically skips it
else
begin
//Picks a random x position
X := randomint(ScreenWidth + 10000);
//Picks a random Y position
Y := randomint(ScreenHeight + 10000);
//adds 75 so the player can use it
Y += 75;
Width := 10;
//Sets the height to something between 50 and 200
Height := randomint(150) + 50;
Spawned := True;
end;
if Spawned = True then
begin
if collidesWithDoor(Door1) then //checks if it overlapped with the door
begin
Spawned := False; //If it failed it will record that it failed to spawn
howMany += 1; //Adds a try so it can count how many times it has failed
end;
end;
if Spawned = True then //Only works if the previous things worked
begin
if collidesWithDoor(Door2) then //checks if it overlapped with the door
begin
Spawned := False; //If it failed it will say it failed to spawn
howMany += 1; //Adds a try so it can count how many times it has failed
end;
end;
if Spawned = True then //Only works if the previous things worked
begin
for i := 0 to High(Fix) do //Iterates through the fixed platforms
begin
if collidesWithPlat(Fix[i]) then //checks if it overlapped
begin
Spawned := False; //If it failed it will say it failed to spawn
howMany += 1; //Adds a try so it can count how many times it has failed
end;
end;
end;
if Spawned = True then //Only works if the previous things worked
begin
for i := 0 to High(Rand)do //Iterates through the Random platforms
begin
//Checks if it is vertical as it is allowed to spawn over horizontal
if Rand[i].horizontal = False then
begin
if collidesWithPlat(Rand[i]) then //checks if it overlapped
begin
Spawned := False; //If it failed it will say it failed to spawn
howMany += 1; //Adds a try so it can count how many times it has failed
end;
end;
end;
end;
end;
end;
var canNotFall := randomint(100); //Picks a random number
if (canNotFall < fall) then //if the number is below the percentage of noFall plats turn off falling
noFall := true
else
noFall := false;
var canJumpThrough := randomint(100); //picks a random number
if (canJumpThrough < through) and (horizontal) then //if the number is below the percentage of jumpThrough plats turn on jumpThrough
//and not vertical to avoid bugs
jumpThrough := true
else
jumpThrough := false;
var canWallJump := randomint(100); //picks a random number
if (canWallJump < noWallJumps) and (horizontal = false) then //if the number is below the percentage of noWallJump plats turn off wall
//jumps and it must not be horizontal as you can always wall jump off a horizontal
NoWallJump := true
else
NoWallJump := false;
var willCrumble := randomint(100); //picks a random number
if willCrumble < crumbles then //if the number is below the percentage of crumble plats turn on crumbling
Crumble := true
else
Crumble := false;
var willMove := randomint(100); //picks a random number
if willMove < Movers then //if the number is below the percentage of moving plats it will move
Moves := true
else
Moves := false;
var MAXMOVING := randomint(Trunc(MaximumMove)); //picks a random number under the max move allowed
var willMoveonX := randomint(100); //picks a random number
if willMoveonX < MoversLtoR then //if the number is below the percentage of Xmove plats it will move on the X axis
begin
MovingX := true;
XMove := MAXMOVING;
end
else
begin
MovingY := true;
YMove := MAXMOVING;
end;
InitX := X + (XMove / 2); //sets the centre x
InitY := Y + (YMove / 2); //sets the centre y
var TurretProb := random * 100; //Picks a random number
if TurretProb < onToporLefts then //Spawn a turret on the left or top if it was under the percentage for the amount of
//turrets on the left or top sides
turretOnLeftOrTop := true;
TurretProb := random * 100; //Picks a random number again
if TurretProb < onBottomorRights then //Spawn a turret on the right or bottom if it was under the
//percentage for the amount of turrets on the right or bottom sides
turretOnRightOrBottom := true;
end;
procedure TPlat.CrumbleUpdate();
begin
if Crumbling then
begin
if TimeTillFall > CRUMBLE_DELAY then
begin
GravSpeed += 1;
Y += GravSpeed;
end;
inc(TimeTillFall);
end;
end;
function TPlat.MoveUpdate(px, py, px2, py2 : float) : array [0 .. 1] of float; //Updates moving platforms
var
Return : array [0 .. 1] of float;
begin
if (Moves) and (Crumbling = false) then //Only run if it moves and is not crumbling
begin
if MovingX then //runs code for if the plat is moving on the X axis
begin
if MoveSpeed > 0 then //If the moving speed is positive
begin
if XMoved >= XMove/2 - Width then //If the current location is over the max
MoveSpeed -= MOVE_SPEED_INC //decrease the moving speed
else
MoveSpeed += MOVE_SPEED_INC; //otherwise increase it
if MoveSpeed > MOVE_SPEED_MAX then //If the movespeed is over its max
begin
MoveSpeed := MOVE_SPEED_MAX; //make it equal to the max
end;
XMoved += MoveSpeed; //Add the movespeed to the amount of x moved
X := InitX + XMoved; //set the plat's x
if PlayerCollidesPlat(px, py, px2, py2) then //Adds the move speed and moves the player x if it is on the plat
Return[0] := MoveSpeed;
end
else //Otherwise
begin
if XMoved <= -XMove/2 then //if the amount moved is under the minimum
MoveSpeed += MOVE_SPEED_INC //make it move right
else
MoveSpeed -= MOVE_SPEED_INC; //otherwise make it speed up going left
if MoveSpeed <= -MOVE_SPEED_MAX then //if the movespeed it over its max
MoveSpeed := -MOVE_SPEED_MAX; //make it equal to the max
XMoved += MoveSpeed; //add the movespeed to the max (actually decreasing the moved amount)
X := InitX + XMoved; //set the x
if PlayerCollidesPlat(px, py, px2, py2) then //Adds the move speed and moves the player x if it is on the plat
Return[0] := MoveSpeed;
end;
end
else if MovingY then //run code if the y is moving
begin
if MoveSpeed > 0 then //If the movespeed is positive
begin
if YMoved >= YMove/2 - Height then //if the amount moved is over its max
MoveSpeed -= MOVE_SPEED_INC //decrease the movespeed
else
MoveSpeed += MOVE_SPEED_INC; //otherwise keep increasing it
if MoveSpeed > MOVE_SPEED_MAX then //if the movespeed is over its max speed
begin
MoveSpeed := MOVE_SPEED_MAX; //set the movespeed it its max
end;
YMoved += MoveSpeed; //add the movespeed to the amount moved
Y := InitY + YMoved; //set the y
if PlayerCollidesPlat(px, py, px2, py2) then //Adds the move speed and moves the player y if it is on the plat
Return[1] := MoveSpeed;
end
else //otherwise if the movespeed is negative
begin
if YMoved <= -YMove/2 then //If the amount moved is under its minimum
MoveSpeed += MOVE_SPEED_INC //increase the speed (start making it positive)
else
MoveSpeed -= MOVE_SPEED_INC; //otherwise keep decreasing it
if MoveSpeed <= -MOVE_SPEED_MAX then //if the movespeed is its max (or more)
MoveSpeed := -MOVE_SPEED_MAX; //make it equal to its max move speed
YMoved += MoveSpeed; //add the movespeed the amount moved (decreasing it)
Y := InitY + YMoved; //set the y
end;
end;
end;
Exit(Return);
end;
function TPlat.PlayerCollidesPlat(px, py, px2, py2 : float) : boolean;
begin
if (px2 > X) and (px2 < X + Width) then //Checks if the X overlap
begin
//Has some leniency on the upper bound of the collision so that it will
//definitely pick up the player so that it can stay on the platform as it moves down
if (py2 >= Y - 6) and (py < Y + Height) then //checks if the y overlap
Exit(true); //if both pass, it collides
end;
Exit(false); //otherwise it didn't
end;
function TPlat.collidesWithDoor(Door : TE) : boolean;
var
//If it picks up the x does not conflict, it will not bother with
//the y as this will be false
stillCheck : boolean;
begin
stillCheck := false;
//Testing X overlap:
//Tests if the right hand side is overlapping the door
if (X + Width <= Door.X + UE.WIDTH) and (X + Width >= Door.X) then
begin
stillCheck := true; //The X overlapped, so still need to test the y
end
//Tests if the left hand side is overlapping the door
else if (X <= Door.X + UE.WIDTH) and (X >= Door.X) then
begin
stillCheck := true; //The X overlapped, so still need to test the y
end
//Tests if it is spawning over the door
else if (X <= Door.X) and (X + Width >= Door.X + UE.WIDTH) then
begin
stillCheck := true; //The X overlapped, so still need to test the y
end;
if stillCheck then //It will only test the y is it overlapped with the x
begin
//Tests Y:
//Tests if the bottom is overlapping the door
if (Y + Height <= Door.Y + UE.HEIGHT) and (Y + Height >= Door.Y) then
begin
Exit(True); //It collided with both x and y so overlaps
end
//Tests if the top is overlapping the door
else if (Y <= Door.Y + UE.HEIGHT) and (Y >= Door.Y) then
begin
Exit(True); //It collided with both x and y so overlaps
end
//Test if it is spawning over the door
else if (Y + Height >= Door.Y) and (Y <= Door.Y) then
begin
Exit(True); //It collided with both x and y so overlaps
end
end;
Exit(False); //It didn't overlap on both, so it doesn't overlap so returns false.
end;
function TPlat.collidesWithPlat(Plat : TPlat) : boolean;
var
//If it picks up that the x doesn't conflict, it won't bother
//with the y as this will be false.
stillCheck : boolean;
begin
stillCheck := false;
//Checks the X:
//Tests if the right side spawns over the platform with
//some extra room for the player
if (X + Width <= Plat.X + Plat.Width + (2 * PLAYERHEAD)) and
(X + Width >= Plat.X - (2 * PLAYERHEAD)) then
begin
stillCheck := true; //X overlapped so need to test the Y
end
//Tests if the left side spawns over the platform with
//some extra room for the player
else if (X <= Plat.X + Plat.Width + (2 * PLAYERHEAD)) and
(X >= Plat.X - (2 * PLAYERHEAD)) then
begin
stillCheck := true; //X overlapped so need to test the Y
end
//Tests if the platform spawns over the other platform with
//some extra room for the player
else if (X + Width >= Plat.X + Plat.Width + (2 * PLAYERHEAD)) and
(X <= Plat.X - (2 * PLAYERHEAD)) then
begin
stillCheck := true; //X overlapped so need to test the Y
end;
if stillCheck then //if it overlapped x, it is only then worth testing y
begin
//Tests Y:
//Tests if the bottom spawns over the platform with some
//extra room for the player
if (Y + Height <= Plat.Y + Plat.Height + ((4 / 3) * (PLAYERHEIGHT))) and
(Y + Height >= Plat.Y - ((4 / 3) * (PLAYERHEIGHT))) then
begin
Exit(True) //It collided with both x and y so overlaps
end
//Tests if the top spawns over the platform with some
//extra room for the player
else if (Y <= Plat.Y + Plat.Height + ((4 / 3) * (PLAYERHEIGHT))) and
(Y >= Plat.Y - ((4 / 3) * (PLAYERHEIGHT))) then
begin
Exit(True) //It collided with both x and y so overlaps
end
//Tests if the platform spawns over the other platform with some
//extra room for the player
else if (Y + Height >= Plat.Y + Plat.Height + ((4 / 3) * (PLAYERHEIGHT))) and
(Y <= Plat.Y - ((4 / 3) * (PLAYERHEIGHT))) then
begin
Exit(True) //It collided with both x and y so overlaps
end;
end;
Exit(False); //It did not overlap both times, so does not overlap
end;
end. |
unit UContador;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UtelaCadastro, Vcl.StdCtrls,
Vcl.ComCtrls, Vcl.Mask, Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Generics.Collections,
UContadorVO, UContadorController, UPessoa, UPessoasVO, UPessoasController, biblioteca;
type
TFTelaCadastroContador = class(TFTelaCadastro)
GroupBox3: TGroupBox;
RadioButtonPessoa: TRadioButton;
Label6: TLabel;
LabeledEditPessoa: TEdit;
BitBtn3: TBitBtn;
LabeledEditNomePessoa: TEdit;
Label1: TLabel;
LabeledEditLogin: TEdit;
Label5: TLabel;
LabeledEditSenha: TEdit;
Label2: TLabel;
Edit1: TEdit;
MaskEditDtInicio: TMaskEdit;
Label3: TLabel;
Label4: TLabel;
Label7: TLabel;
MaskEdit1: TMaskEdit;
Label8: TLabel;
MaskEdit2: TMaskEdit;
RadioButton1: TRadioButton;
function DoSalvar: boolean; override;
function MontaFiltro: string;
procedure DoConsultar; override;
function DoExcluir: boolean; override;
procedure BitBtnNovoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BitBtn3Click(Sender: TObject);
procedure LabeledEditPessoaExit(Sender: TObject);
procedure MaskEditDtInicioExit(Sender: TObject);
procedure MaskEdit1Exit(Sender: TObject);
procedure MaskEdit2Exit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
idCondominio : Integer;
procedure GridParaEdits; override;
function EditsToObject(Contador: TContadorVO): TContadorVO;
end;
var
FTelaCadastroContador: TFTelaCadastroContador;
ControllerContador: TContadorController;
implementation
{$R *.dfm}
{ TFTelaCadastroContador }
procedure TFTelaCadastroContador.BitBtn3Click(Sender: TObject);
var
FormPessoaConsulta: TFTelaCadastroPessoa;
begin
FormPessoaConsulta := TFTelaCadastroPessoa.Create(nil);
FormPessoaConsulta.FechaForm := true;
FormPessoaConsulta.ShowModal;
if (FormPessoaConsulta.ObjetoRetornoVO <> nil) then
begin
LabeledEditPessoa.Text := IntToStr(TPessoasVO(FormPessoaConsulta.ObjetoRetornoVO).idpessoa);
LabeledEditNomePessoa.Text := TPessoasVO(FormPessoaConsulta.ObjetoRetornoVO).nome;
end;
FormPessoaConsulta.Release;
end;
procedure TFTelaCadastroContador.BitBtnNovoClick(Sender: TObject);
begin
inherited;
LabeledEditPessoa.setFocus;
end;
procedure TFTelaCadastroContador.DoConsultar;
var
listaContador: TObjectList<TContadorVO>;
filtro: string;
begin
filtro := MontaFiltro;
listaContador := ControllerContador.Consultar(filtro, 'ORDER BY DTENTRADA DESC');
PopulaGrid<TContadorVO>(listaContador);
end;
function TFTelaCadastroContador.DoExcluir: boolean;
var
Contador: TContadorVO;
begin
try
try
Contador := TContadorVO.Create;
Contador.idContador := CDSGrid.FieldByName('IDCONTADOR').AsInteger;
ControllerContador.Excluir(Contador);
except
on E: Exception do
begin
ShowMessage('Ocorreu um erro ao excluir o registro: ' + #13 + #13 +
E.Message);
Result := false;
end;
end;
finally
end;
end;
function TFTelaCadastroContador.DoSalvar: boolean;
var
Contador: TContadorVO;
begin
Contador:=EditsToObject(TContadorVO.Create);
try
try
Contador.ValidarCamposObrigatorios();
if (StatusTela = stInserindo) then
begin
Contador.idCondominio := idCondominio;
ControllerContador.Inserir(Contador);
result := true;
end
else if (StatusTela = stEditando) then
begin
Contador := ControllerContador.ConsultarPorId(CDSGrid.FieldByName('IDCONTADOR')
.AsInteger);
Contador := EditsToObject(Contador);
ControllerContador.Alterar(Contador);
Result := true;
end
except
on E: Exception do
begin
ShowMessage(E.Message);
Result := false;
end;
end;
finally
end;
end;
function TFTelaCadastroContador.EditsToObject(
Contador: TContadorVO): TContadorVO;
begin
if (LabeledEditPessoa.Text <> '') then
Contador.idPessoa := strtoint(LabeledEditPessoa.Text);
if (LabeledEditLogin.Text<> '') then
Contador.Crc := LabeledEditLogin.Text;
if (LabeledEditSenha.Text<>'') then
Contador.Ocupacao := LabeledEditSenha.Text;
if (MaskEditDtInicio.Text<>' / / ') then
Contador.dtEntrada := StrToDate(MaskEditDtInicio.Text);
if (MaskEdit1.Text <> ' / / ') then
Contador.dtSaida := StrToDate(MaskEdit1.Text);
if (Edit1.Text <> '')then
Contador.CertidaoReg := Edit1.Text;
if (MaskEdit2.Text <> ' / / ') then
Contador.dtValidade := StrToDate(MaskEdit2.Text);
Result := Contador;
end;
procedure TFTelaCadastroContador.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
FreeAndNil(ControllerContador);
end;
procedure TFTelaCadastroContador.FormCreate(Sender: TObject);
begin
ClasseObjetoGridVO := TContadorVO;
RadioButtonPessoa.Checked := true;
ControllerContador := TContadorController.Create;
inherited;
end;
procedure TFTelaCadastroContador.GridParaEdits;
var
Contador: TContadorVO;
begin
inherited;
Contador := nil;
if not CDSGrid.IsEmpty then
Contador := ControllerContador.ConsultarPorId(CDSGrid.FieldByName('IDCONTADOR')
.AsInteger);
if Contador <> nil then
begin
if Contador.PessoaVO <> nil then
begin
LabeledEditPessoa.Text := IntToStr(Contador.PessoaVO.idPessoa);
LabeledEditNomePessoa.Text := Contador.PessoaVO.nome;
end;
LabeledEditLogin.Text := Contador.Crc;
LabeledEditSenha.Text := Contador.Ocupacao;
if (Contador.dtEntrada <> 0) then
MaskEditDtInicio.Text := DateToStr(Contador.dtEntrada);
if (Contador.dtSaida <> 0 ) then
MaskEdit1.Text := DateToStr(COntador.dtSaida);
if (Contador.dtValidade <> 0) then
MaskEdit2.Text := DateToStr(Contador.dtValidade);
Edit1.Text := Contador.CertidaoReg;
end;
end;
procedure TFTelaCadastroContador.LabeledEditPessoaExit(Sender: TObject);
var
PessoaController:TPessoasController;
PessoaVO: TPessoasVO;
begin
if LabeledEditPessoa.Text <> '' then
begin
try
PessoaController := TPessoasController.Create;
PessoaVO := PessoaController.ConsultarPorId(StrToInt(LabeledEditPessoa.Text));
labeledEditNomePessoa.Text := PessoaVO.nome;
LabeledEditPessoa.Text := inttostr(PessoaVO.idPessoa);
PessoaController.Free;
except
raise Exception.Create('Código Inválido');
end;
end;
end;
procedure TFTelaCadastroContador.MaskEdit1Exit(Sender: TObject);
begin
EventoValidaData(sender);
end;
procedure TFTelaCadastroContador.MaskEdit2Exit(Sender: TObject);
begin
EventoValidaData(sender);
end;
procedure TFTelaCadastroContador.MaskEditDtInicioExit(Sender: TObject);
begin
EventoValidaData(sender);
end;
function TFTelaCadastroContador.MontaFiltro: string;
begin
Result := ' (IDCONDOMINIO = '+inttostr(IDCONDOMINIO)+')';
if (RadioButtonPessoa.Checked = true) then
begin
if (editBusca.Text <> '') then
begin
Result := Result + ' and ( UPPER(CRC) LIKE ' +
QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ') ';
end;
end;
if (RadioButton1.Checked = true) then
begin
if (editBusca.Text <> '') then
begin
Result := Result + ' and ( UPPER(NOME) LIKE ' +
QuotedStr('%' + UpperCase(editBusca.Text) + '%') + ' ) ';
end;
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082502
////////////////////////////////////////////////////////////////////////////////
unit android.provider.FontsContract_Columns;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JFontsContract_Columns = interface;
JFontsContract_ColumnsClass = interface(JObjectClass)
['{3874E60A-C440-41A2-BBB8-DA95B7532454}']
function _GetFILE_ID : JString; cdecl; // A: $19
function _GetITALIC : JString; cdecl; // A: $19
function _GetRESULT_CODE : JString; cdecl; // A: $19
function _GetRESULT_CODE_FONT_NOT_FOUND : Integer; cdecl; // A: $19
function _GetRESULT_CODE_FONT_UNAVAILABLE : Integer; cdecl; // A: $19
function _GetRESULT_CODE_MALFORMED_QUERY : Integer; cdecl; // A: $19
function _GetRESULT_CODE_OK : Integer; cdecl; // A: $19
function _GetTTC_INDEX : JString; cdecl; // A: $19
function _GetVARIATION_SETTINGS : JString; cdecl; // A: $19
function _GetWEIGHT : JString; cdecl; // A: $19
property FILE_ID : JString read _GetFILE_ID; // Ljava/lang/String; A: $19
property ITALIC : JString read _GetITALIC; // Ljava/lang/String; A: $19
property RESULT_CODE : JString read _GetRESULT_CODE; // Ljava/lang/String; A: $19
property RESULT_CODE_FONT_NOT_FOUND : Integer read _GetRESULT_CODE_FONT_NOT_FOUND;// I A: $19
property RESULT_CODE_FONT_UNAVAILABLE : Integer read _GetRESULT_CODE_FONT_UNAVAILABLE;// I A: $19
property RESULT_CODE_MALFORMED_QUERY : Integer read _GetRESULT_CODE_MALFORMED_QUERY;// I A: $19
property RESULT_CODE_OK : Integer read _GetRESULT_CODE_OK; // I A: $19
property TTC_INDEX : JString read _GetTTC_INDEX; // Ljava/lang/String; A: $19
property VARIATION_SETTINGS : JString read _GetVARIATION_SETTINGS; // Ljava/lang/String; A: $19
property WEIGHT : JString read _GetWEIGHT; // Ljava/lang/String; A: $19
end;
[JavaSignature('android/provider/FontsContract_Columns')]
JFontsContract_Columns = interface(JObject)
['{621EA4AE-FB0F-4A43-B444-871F2BDD8A71}']
end;
TJFontsContract_Columns = class(TJavaGenericImport<JFontsContract_ColumnsClass, JFontsContract_Columns>)
end;
const
TJFontsContract_ColumnsFILE_ID = 'file_id';
TJFontsContract_ColumnsITALIC = 'font_italic';
TJFontsContract_ColumnsRESULT_CODE = 'result_code';
TJFontsContract_ColumnsRESULT_CODE_FONT_NOT_FOUND = 1;
TJFontsContract_ColumnsRESULT_CODE_FONT_UNAVAILABLE = 2;
TJFontsContract_ColumnsRESULT_CODE_MALFORMED_QUERY = 3;
TJFontsContract_ColumnsRESULT_CODE_OK = 0;
TJFontsContract_ColumnsTTC_INDEX = 'font_ttc_index';
TJFontsContract_ColumnsVARIATION_SETTINGS = 'font_variation_settings';
TJFontsContract_ColumnsWEIGHT = 'font_weight';
implementation
end.
|
namespace AwaitSample;
interface
uses
System,
System.Drawing,
System.Collections,
System.Collections.Generic,
System.Windows.Forms,
System.ComponentModel,
System.IO,
System.Windows.Threading;
type
MainForm = partial class(System.Windows.Forms.Form)
private
const WAIT_MESSAGE = 'Please wait...';
var fIsRunning: Boolean;
method buttonCount_Click(sender: System.Object; e: System.EventArgs);
method buttonChoosePath_Click(sender: System.Object; e: System.EventArgs);
method CountFiles(path: String): Int32;
protected
method Dispose(disposing: Boolean); override;
public
constructor;
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
InitializeComponent();
end;
method MainForm.Dispose(disposing: Boolean);
begin
if disposing then begin
if assigned(components) then
components.Dispose();
end;
inherited Dispose(disposing);
end;
{$ENDREGION}
method MainForm.buttonChoosePath_Click(sender: System.Object; e: System.EventArgs);
begin
var lFolderBrowserDialog := new FolderBrowserDialog;
if (lFolderBrowserDialog.ShowDialog = DialogResult.OK) then
textBoxPath.Text := lFolderBrowserDialog.SelectedPath
end;
method MainForm.buttonCount_Click(sender: System.Object; e: System.EventArgs);
begin
if fIsRunning then begin
MessageBox.Show("Counting process is already running, please wait.", "Warning");
exit
end;
progressBarCounting.Style := ProgressBarStyle.Marquee;
labelFilesCount.Text := WAIT_MESSAGE;
fIsRunning := true;
try
//Asynconous call definition
var x := async CountFiles(textBoxPath.Text);
//'Await' allows to use the result of an asynchronous call to continuous operation in a synchronous way, application stays responsive
labelFilesCount.Text := Convert.ToString(await x);
except
on ex: Exception do
labelFilesCount.Text := 'Error: '+ ex.Message;
end;
//When asynchronous operation is finished, application execution continues with next statement
progressBarCounting.Style := ProgressBarStyle.Continuous;
fIsRunning := false;
end;
method MainForm.CountFiles(path: String): Int32;
begin
var lFilesCount: Int32;
try
lFilesCount := Directory.GetFiles(path).Length;
except
end;
result := lFilesCount;
var lDirectories: array of String;
try
lDirectories := Directory.GetDirectories(path);
except
end;
for each d in lDirectories do
result := result + CountFiles(d);
end;
end.
|
unit uSCMCheckSaveStorageFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uBaseEditFrm, ExtCtrls, Menus, cxLookAndFeelPainters, StdCtrls,
cxButtons, DB, DBClient, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxCalendar, cxButtonEdit, cxLabel;
type
TFrm_SCMCheckSaveStorage = class(TSTBaseEdit)
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
btOk: TcxButton;
btCancel: TcxButton;
cxButton1: TcxButton;
cdsCheckBill: TClientDataSet;
cxSaveDate: TcxDateEdit;
lbCheckDate: TLabel;
cxButton2: TcxButton;
btDelSto: TcxButton;
cxLabel1: TcxLabel;
cxbtnWarehouse: TcxButtonEdit;
procedure btOkClick(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure cxButton1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btDelStoClick(Sender: TObject);
procedure FormCanResize(Sender: TObject; var NewWidth,
NewHeight: Integer; var Resize: Boolean);
procedure cxbtnWarehousePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
{ Private declarations }
FWareHouseID : string;
public
{ Public declarations }
end;
var
Frm_SCMCheckSaveStorage: TFrm_SCMCheckSaveStorage;
procedure OpenCheckSaveStorage;
implementation
uses Pub_Fun, FrmCliDM,uFrm_CheckBillState,uMaterDataSelectHelper;
{$R *.dfm}
procedure OpenCheckSaveStorage;
begin
try
Application.CreateForm(TFrm_SCMCheckSaveStorage,Frm_SCMCheckSaveStorage);
Frm_SCMCheckSaveStorage.ShowModal;
finally
Frm_SCMCheckSaveStorage.Free;
end;
end;
procedure TFrm_SCMCheckSaveStorage.btOkClick(Sender: TObject);
var ErrMsg,SaveDate : string;
begin
if cxSaveDate.Text = '' then
begin
ShowMsg(Handle,'请选择盘点日期!',[]);
cxSaveDate.SetFocus;
Abort;
end;
if trim(cxbtnWarehouse.text)='' then
begin
ShowMsg(Handle,'请选择盘点仓库!',[]);
cxbtnWarehouse.SetFocus;
Abort;
end;
//检查单据
SaveDate := FormatDateTime('yyyy-mm-dd', cxSaveDate.Date);
if CliDM.E_CheckBillState(FWareHouseID,SaveDate,cdsCheckBill,ErrMsg) then //有未处理单据
begin
ShowCheckBillState(cdsCheckBill);
Exit;
end;
//保存库存
if not CliDM.E_CheckSaveStorage(1,UserInfo.LoginUser_FID,FWareHouseID,SaveDate,cdsCheckBill,ErrMsg) then
begin
ShowMsg(Handle, ErrMsg,[]);
Abort;
end
else
begin
ShowMsg(Handle, '保存库存成功!',[]);
btCancel.SetFocus;
end;
end;
procedure TFrm_SCMCheckSaveStorage.cxButton2Click(Sender: TObject);
var ErrMsg,SaveCheckDate : string;
begin
if cxSaveDate.Text = '' then
begin
ShowMsg(Handle,'请选择盘点日期!',[]);
cxSaveDate.SetFocus;
Abort;
end;
if trim(cxbtnWarehouse.text)='' then
begin
ShowMsg(Handle,'请选择盘点仓库!',[]);
cxbtnWarehouse.SetFocus;
Abort;
end;
SaveCheckDate := FormatDateTime('yyyy-mm-dd', cxSaveDate.Date);
//检查单据
if CliDM.E_CheckBillState(FWareHouseID,SaveCheckDate,cdsCheckBill,ErrMsg) then //有未处理单据
begin
ShowCheckBillState(cdsCheckBill);
Exit;
end
else
begin
ShowMsg(Handle,ErrMsg,[]);
btOk.SetFocus;
end;
end;
procedure TFrm_SCMCheckSaveStorage.btCancelClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TFrm_SCMCheckSaveStorage.cxButton1Click(Sender: TObject);
var ErrMsg : string;
begin
inherited;
if CliDM.Pub_POSOut(UserInfo.LoginUser_FID,UserInfo.Warehouse_FID,ErrMsg) then
ShowMsg(Handle, '计算库存成功!',[])
else
ShowMsg(Handle, ErrMsg,[]);
end;
procedure TFrm_SCMCheckSaveStorage.FormCreate(Sender: TObject);
begin
inherited;
//LoadImage(UserInfo.ExePath+'\Img\POS_Edit_Top2.jpg',Image1);
//LoadImage(UserInfo.ExePath+'\Img\POS_Edit_Top2.jpg',Image2);
end;
procedure TFrm_SCMCheckSaveStorage.btDelStoClick(Sender: TObject);
var ErrMsg,SaveCheckDate : string;
begin
if cxSaveDate.Text = '' then
begin
ShowMsg(Handle,'请选择盘点日期!',[]);
cxSaveDate.SetFocus;
Abort;
end;
if trim(cxbtnWarehouse.text)='' then
begin
ShowMsg(Handle,'请选择盘点仓库!',[]);
cxbtnWarehouse.SetFocus;
Abort;
end;
SaveCheckDate := FormatDateTime('yyyy-mm-dd', cxSaveDate.Date);
//删除保存库存
if CliDM.E_CheckSaveStorage(2,UserInfo.LoginUser_FID,FWareHouseID,SaveCheckDate,cdsCheckBill,ErrMsg) then
ShowMsg(Handle,'删除【'+SaveCheckDate+'】保存库存成功!',[])
else
begin
ShowMsg(Handle,ErrMsg,[]);
exit;
end;
end;
procedure TFrm_SCMCheckSaveStorage.FormCanResize(Sender: TObject;
var NewWidth, NewHeight: Integer; var Resize: Boolean);
begin
inherited;
Resize:=false;
end;
procedure TFrm_SCMCheckSaveStorage.cxbtnWarehousePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
inherited;
FWareHouseID := '';
with Select_Warehouse('','',1) do
begin
if not IsEmpty then
begin
FWareHouseID :=fieldbyname('FID').AsString ;
cxbtnWarehouse.Text := fieldbyname('Fname_l2').AsString;
end;
end;
end;
end.
|
unit uWinAPIRedirections;
interface
uses
WinApi.Windows,
System.SysUtils,
System.StrUtils,
uAPIHook,
uStrongCrypt,
uWinApiRuntime,
uProgramCommunication,
uTransparentEncryption,
uTransparentEncryptor;
{$WARN SYMBOL_PLATFORM OFF}
const
NTDLLFile = 'ntdll.dll';
STATUS_NO_SUCH_FILE = $C000000F;
procedure HookPEModule(Module: HModule; Recursive: Boolean = True);
function CreateFileWHookProc(lpFileName: PWideChar; dwDesiredAccess, dwShareMode: DWORD;
lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD;
hTemplateFile: THandle): THandle; stdcall;
function OpenFileAHookProc(const lpFileName: LPCSTR; var lpReOpenBuff: TOFStruct; uStyle: UINT): HFILE; stdcall;
function CreateFileAHookProc(lpFileName: PAnsiChar; dwDesiredAccess, dwShareMode: DWORD;
lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD;
hTemplateFile: THandle): THandle; stdcall;
function SetFilePointerExHookProc(hFile: THandle; liDistanceToMove: TLargeInteger;
const lpNewFilePointer: PLargeInteger; dwMoveMethod: DWORD): BOOL; stdcall;
function SetFilePointerHookProc(hFile: THandle; lDistanceToMove: Longint;
lpDistanceToMoveHigh: Pointer; dwMoveMethod: DWORD): DWORD; stdcall;
function ReadFileHookProc(hFile: THandle; var Buffer; nNumberOfBytesToRead: DWORD; lpNumberOfBytesRead: PDWORD; lpOverlapped: POverlapped): BOOL; stdcall;
function ReadFileExHookProc(hFile: THandle; lpBuffer: Pointer; nNumberOfBytesToRead: DWORD; lpOverlapped: POverlapped; lpCompletionRoutine: TPROverlappedCompletionRoutine): BOOL; stdcall;
function CloseHandleHookProc(hObject: THandle): BOOL; stdcall;
function LoadLibraryAHookProc(lpLibFileName: PAnsiChar): HMODULE; stdcall;
function LoadLibraryWHookProc(lpLibFileName: PWideChar): HMODULE; stdcall;
function GetProcAddressHookProc(hModule: HMODULE; lpProcName: LPCSTR): FARPROC; stdcall;
function GetFileSizeEx(hFile: THandle; var lpFileSize: Int64): BOOL; stdcall; external 'kernel32.dll';
function LdrLoadDll(szcwPath: PWideChar;
pdwLdrErr: PULONG;
pUniModuleName: PUnicodeString;
pResultInstance: PHandle): NTSTATUS; stdcall; external NTDLLFile;
function NtCreateFile(FileHandle: PHANDLE; DesiredAccess: ACCESS_MASK;
ObjectAttributes: POBJECT_ATTRIBUTES; IoStatusBlock: PIO_STATUS_BLOCK;
AllocationSize: PLARGE_INTEGER; FileAttributes: ULONG; ShareAccess: ULONG;
CreateDisposition: ULONG; CreateOptions: ULONG; EaBuffer: PVOID;
EaLength: ULONG): NTSTATUS; stdcall; external NTDLLFile;
function NtQueryDirectoryFile(FileHandle: HANDLE; Event: HANDLE; ApcRoutine: PIO_APC_ROUTINE; ApcContext: PVOID;
IoStatusBlock: PIO_STATUS_BLOCK; FileInformation: PVOID; FileInformationLength: ULONG;
FileInformationClass: FILE_INFORMATION_CLASS; ReturnSingleEntry: ByteBool; FileName: PUnicodeString;
RestartScan: ByteBool): NTSTATUS; stdcall; external NTDLLFile;
function NtQueryInformationFile(FileHandle: HANDLE;
IoStatusBlock: PIO_STATUS_BLOCK;
FileInformation: PVOID;
FileInformationLength: ULONG;
FileInformationClass: FILE_INFORMATION_CLASS
): NTSTATUS; stdcall; external NTDLLFile;
var
DefaultDll: string;
implementation
//hooks file opening
function CreateProcessACallbackProc(appName, cmdLine: pchar; processAttr, threadAttr: PSecurityAttributes; inheritHandles: bool; creationFlags: dword; environment: pointer; currentDir: pchar; const startupInfo: TStartupInfo; var processInfo: TProcessInformation) : bool; stdcall;
begin
Result := CreateProcessANextHook(appName, cmdLine, processAttr, threadAttr, inheritHandles, creationFlags, environment, currentDir, startupInfo, processInfo);
//If explorer opens files like regedit or netstat - we can now auto inject our DLL into them hooking their API ;)!!!!
//this will now keep injecting and recurring in every process which is ran through the created ones :)
InjectDllToTarget(DefaultDll, processInfo.dwProcessId, @InjectedProc, 1000);
end;
//hooks file opening
function CreateProcessWCallbackProc(appName, cmdLine: pwidechar; processAttr, threadAttr: PSecurityAttributes; inheritHandles: bool; creationFlags: dword; environment: pointer; currentDir: pwidechar; const startupInfo: TStartupInfo; var processInfo: TProcessInformation) : bool; stdcall;
begin
Result := CreateProcessWNextHook(appName, cmdLine, processAttr, threadAttr, inheritHandles, creationFlags, environment, currentDir, startupInfo, processInfo);
//If explorer opens files like regedit or netstat - we can now auto inject our DLL into them hooking their API ;)!!!!
//this will now keep injecting and recurring in every process which is ran through the created ones :)
InjectDllToTarget(DefaultDll, processInfo.dwProcessId, @InjectedProc, 1000);
end;
function DuplicateHandleHookProc (hSourceProcessHandle, hSourceHandle, hTargetProcessHandle: THandle;
lpTargetHandle: PHandle; dwDesiredAccess: DWORD;
bInheritHandle: BOOL; dwOptions: DWORD): BOOL; stdcall;
begin
if IsEncryptedHandle(hSourceHandle) then
NotifyEncryptionError('DuplicateHandleHookProc');
Result := DuplicateHandleNextHook(hSourceProcessHandle, hSourceHandle, hTargetProcessHandle, lpTargetHandle, dwDesiredAccess,
bInheritHandle, dwOptions);
end;
function GetFileAttributesExAHookProc(lpFileName: PAnsiChar; fInfoLevelId: TGetFileExInfoLevels; lpFileInformation: Pointer): BOOL; stdcall;
var
Attributes: ^WIN32_FILE_ATTRIBUTE_DATA;
FileSize: Int64;
LastError: DWORD;
begin
Result := GetFileAttributesExANextHook(lpFileName, fInfoLevelId, lpFileInformation);
if fInfoLevelId = GetFileExInfoStandard then
begin
LastError := GetLastError;
if ValidEnryptFileEx(string(AnsiString(lpFileName))) then
begin
Attributes := lpFileInformation;
Int64Rec(FileSize).Lo := Attributes.nFileSizeLow;
Int64Rec(FileSize).Hi := Attributes.nFileSizeHigh;
FileSize := FileSize - SizeOf(TEncryptedFileHeader) - SizeOf(TEncryptFileHeaderExV1);
Attributes.nFileSizeLow := Int64Rec(FileSize).Lo;
Attributes.nFileSizeHigh := Int64Rec(FileSize).Hi;
end;
SetLastError(LastError);
end else
NotifyEncryptionError('GetFileAttributesExA, not GetFileExInfoStandard');
end;
function GetFileAttributesExWHookProc(lpFileName: PWideChar; fInfoLevelId: TGetFileExInfoLevels; lpFileInformation: Pointer): BOOL; stdcall;
var
Attributes: ^WIN32_FILE_ATTRIBUTE_DATA;
FileSize: Int64;
LastError: DWORD;
begin
Result := GetFileAttributesExWNextHook(lpFileName, fInfoLevelId, lpFileInformation);
if fInfoLevelId = GetFileExInfoStandard then
begin
LastError := GetLastError;
if ValidEnryptFileEx(lpFileName) then
begin
Attributes := lpFileInformation;
Int64Rec(FileSize).Lo := Attributes.nFileSizeLow;
Int64Rec(FileSize).Hi := Attributes.nFileSizeHigh;
FileSize := FileSize - SizeOf(TEncryptedFileHeader) - SizeOf(TEncryptFileHeaderExV1);
Attributes.nFileSizeLow := Int64Rec(FileSize).Lo;
Attributes.nFileSizeHigh := Int64Rec(FileSize).Hi;
end;
SetLastError(LastError);
end else
NotifyEncryptionError('GetFileAttributesExW, not GetFileExInfoStandard');
end;
function FindFirstFileAHookProc(lpFileName: PAnsiChar; var lpFindFileData: TWIN32FindDataA): THandle; stdcall;
var
FileSize: Int64;
LastError: DWORD;
begin
Result := FindFirstFileANextHook(lpFileName, lpFindFileData);
LastError := GetLastError;
if ValidEnryptFileEx(string(AnsiString(lpFileName))) then
begin
Int64Rec(FileSize).Lo := lpFindFileData.nFileSizeLow;
Int64Rec(FileSize).Hi := lpFindFileData.nFileSizeHigh;
FileSize := FileSize - SizeOf(TEncryptedFileHeader) - SizeOf(TEncryptFileHeaderExV1);
lpFindFileData.nFileSizeLow := Int64Rec(FileSize).Lo;
lpFindFileData.nFileSizeHigh := Int64Rec(FileSize).Hi;
end;
SetLastError(LastError);
end;
function FindFirstFileWHookProc(lpFileName: PWideChar; var lpFindFileData: TWIN32FindDataW): THandle; stdcall;
var
FileSize: Int64;
LastError: DWORD;
begin
Result := FindFirstFileWNextHook(lpFileName, lpFindFileData);
LastError := GetLastError;
if ValidEnryptFileEx(lpFileName) then
begin
Int64Rec(FileSize).Lo := lpFindFileData.nFileSizeLow;
Int64Rec(FileSize).Hi := lpFindFileData.nFileSizeHigh;
FileSize := FileSize - SizeOf(TEncryptedFileHeader) - SizeOf(TEncryptFileHeaderExV1);
lpFindFileData.nFileSizeLow := Int64Rec(FileSize).Lo;
lpFindFileData.nFileSizeHigh := Int64Rec(FileSize).Hi;
end;
SetLastError(LastError);
end;
function GetFileSizeHookProc(hFile: THandle; lpFileSizeHigh: Pointer): DWORD; stdcall;
var
FileSize: Int64;
begin
Result := GetFileSizeNextHook(hFile, lpFileSizeHigh);
if IsEncryptedHandle(hFile) then
begin
Int64Rec(FileSize).Lo := Result;
Int64Rec(FileSize).Hi := 0;
if Assigned(lpFileSizeHigh) then
Int64Rec(FileSize).Hi := PCardinal(lpFileSizeHigh)^;
FileSize := FileSize - SizeOf(TEncryptedFileHeader) - SizeOf(TEncryptFileHeaderExV1);
Result := Int64Rec(FileSize).Lo;
if Assigned(lpFileSizeHigh) then
PCardinal(lpFileSizeHigh)^ := Int64Rec(FileSize).Hi;
end;
end;
function GetFileSizeExHookProc(hFile: THandle; var lpFileSize: Int64): BOOL; stdcall;
begin
Result := GetFileSizeExNextHook(hFile, lpFileSize);
if IsEncryptedHandle(hFile) then
lpFileSize := lpFileSize - SizeOf(TEncryptedFileHeader) - SizeOf(TEncryptFileHeaderExV1);
end;
function CreateFileMappingAHookProc(hFile: THandle; lpFileMappingAttributes: PSecurityAttributes;
flProtect, dwMaximumSizeHigh, dwMaximumSizeLow: DWORD; lpName: PAnsiChar): THandle; stdcall;
begin
Result := CreateFileMappingANextHook(hFile, lpFileMappingAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName);
if IsEncryptedHandle(hFile) then
AddFileMapping(hFile, Result);
end;
function CreateFileMappingWHookProc(hFile: THandle; lpFileMappingAttributes: PSecurityAttributes;
flProtect, dwMaximumSizeHigh, dwMaximumSizeLow: DWORD; lpName: PWideChar): THandle; stdcall;
begin
Result := CreateFileMappingWNextHook(hFile, lpFileMappingAttributes, flProtect, dwMaximumSizeHigh, dwMaximumSizeLow, lpName);
if IsEncryptedHandle(hFile) then
AddFileMapping(hFile, Result);
end;
function MapViewOfFileHookProc(hFileMappingObject: THandle; dwDesiredAccess: DWORD;
dwFileOffsetHigh, dwFileOffsetLow: DWORD; dwNumberOfBytesToMap: SIZE_T): Pointer; stdcall;
begin
if IsInternalFileMapping(hFileMappingObject) then
begin
Result := GetInternalFileMapping(hFileMappingObject, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap);
Exit;
end;
Result := MapViewOfFileNextHook(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap);
end;
function UnmapViewOfFileHookProc(lpBaseAddress: Pointer): BOOL; stdcall;
begin
//TODO: free block
Result := UnmapViewOfFileNextHook(lpBaseAddress);
end;
function MapViewOfFileExHookProc(hFileMappingObject: THandle; dwDesiredAccess: DWORD;
dwFileOffsetHigh, dwFileOffsetLow: DWORD; dwNumberOfBytesToMap: SIZE_T; lpBaseAddress: Pointer): Pointer; stdcall;
var
Data: Pointer;
begin
if lpBaseAddress = nil then
Exit(MapViewOfFileHookProc(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap));
if IsInternalFileMapping(hFileMappingObject) then
begin
Data := GetInternalFileMapping(hFileMappingObject, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap);
try
Result := lpBaseAddress;
CopyMemory(Result, Data, dwNumberOfBytesToMap);
finally
FreeMem(Data);
end;
Exit;
end;
Result := MapViewOfFileExNextHook(hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, dwFileOffsetLow, dwNumberOfBytesToMap, lpBaseAddress);
end;
function _lopenHookProc(const lpPathName: LPCSTR; iReadWrite: Integer): HFILE; stdcall;
begin
if MessageBox(0, 'Функция: _lopen', 'Позволить ?', MB_YESNO or MB_ICONQUESTION) = IDYES then
result := _lOpenNextHook( lpPathName,iReadWrite)
else
result := 0;
end;
function _lreadHookProc(hFile: HFILE; lpBuffer: Pointer; uBytes: UINT): UINT; stdcall;
var
dwCurrentFilePosition: Int64;
begin
dwCurrentFilePosition := FileSeek(hFile, Int64(0), FILE_CURRENT);
result := _lReadNextHook(hFile, lpBuffer, uBytes);
ReplaceBufferContent(hFile, lpBuffer, dwCurrentFilePosition, uBytes, Result, nil, nil);
end;
function _lcreatHookProc(const lpPathName: LPCSTR; iAttribute: Integer): HFILE; stdcall;
begin
if MessageBox(0, 'Функция: _lcreat', 'Позволить ?', MB_YESNO or MB_ICONQUESTION) = IDYES then
result := _lCreatNextHook(lpPathName, iAttribute)
else
result := 0;
end;
function GetModuleName(hModule: HMODULE): string;
var
szFileName: array[0..MAX_PATH] of Char;
ModuleFileLength: Integer;
begin
FillChar(szFileName, SizeOf(szFileName), #0);
ModuleFileLength := GetModuleFileName(hModule, szFileName, MAX_PATH);
SetString(Result, szFileName, ModuleFileLength);
end;
function IsSystemDll(dllName: string): Boolean;
begin
//disable hook by dll name, currenltly can inject to any dll
Result := False;
end;
procedure ProcessDllLoad(Module: HModule; lpLibFileName: string);
begin
if (Module > 0) and not IsSystemDll(lpLibFileName) then
HookPEModule(Module, False);
end;
function LoadLibraryExAHookProc(lpLibFileName: PAnsiChar; hFile: THandle; dwFlags: DWORD): HMODULE; stdcall;
begin
Result := LoadLibraryExANextHook(lpLibFileName, hFile, dwFlags);
end;
function LoadLibraryExWHookProc(lpLibFileName: PWideChar; hFile: THandle; dwFlags: DWORD): HMODULE; stdcall;
begin
Result := LoadLibraryExWNextHook(lpLibFileName, hFile, dwFlags);
end;
function LoadLibraryWHookProc(lpLibFileName: PWideChar): HMODULE; stdcall;
begin
Result := LoadLibraryWNextHook(lpLibFileName);
end;
function LoadLibraryAHookProc(lpLibFileName: PAnsiChar): HMODULE; stdcall;
begin
Result := LoadLibraryANextHook(lpLibFileName);
end;
{ .: NT_SUCCESS :. }
function NT_SUCCESS(const Status: NTSTATUS): Boolean;
begin
Result := (Integer(Status) >= 0);
end;
function LdrLoadDllHookProc(szcwPath: PWideChar;
pdwLdrErr: PULONG;
pUniModuleName: PUnicodeString;
pResultInstance: PHandle): NTSTATUS; stdcall;
var
LastError: DWORD;
begin
Result := LdrLoadDllNextHook(szcwPath, pdwLdrErr, pUniModuleName, pResultInstance);
if (pResultInstance <> nil) and (pResultInstance^ > 0) then
begin
LastError := GetLastError;
ProcessDllLoad(pResultInstance^, pUniModuleName.Buffer);
SetLastError(LastError);
end;
end;
function NtCreateFileHookProc(FileHandle: PHANDLE; DesiredAccess: ACCESS_MASK;
ObjectAttributes: POBJECT_ATTRIBUTES; IoStatusBlock: PIO_STATUS_BLOCK;
AllocationSize: PLARGE_INTEGER; FileAttributes: ULONG; ShareAccess: ULONG;
CreateDisposition: ULONG; CreateOptions: ULONG; EaBuffer: PVOID;
EaLength: ULONG): NTSTATUS; stdcall;
var
LastError: DWORD;
lpFileName: PWideChar;
begin
Result := NtCreateFileNextHook(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock,
AllocationSize, FileAttributes, ShareAccess, CreateDisposition,
CreateOptions, EaBuffer, EaLength);
if NT_SUCCESS(Result) then
begin
LastError := GetLastError;
lpFileName := ObjectAttributes.ObjectName.Buffer;
if IsHookStarted then
begin
if FILE_TYPE_DISK = GetFileType(Result) {not StartsStr('\\.', string(AnsiString(lpFileName))) and not IsSystemPipe(string(AnsiString(lpFileName)))} then
begin //TODO: use overlaped if use this hook
if ValidEncryptFileExHandle(FileHandle^, False) then
begin
if (DesiredAccess and GENERIC_WRITE > 0) then
begin
CloseHandle(FileHandle^);
FileHandle^ := INVALID_HANDLE_VALUE;
Result := ERROR_ACCESS_DENIED;
SetLastError(ERROR_ACCESS_DENIED);
Exit;
end; //TODO: use overlaped if use this hook
InitEncryptedFile(string(AnsiString(lpFileName)), FileHandle^, False);
end;
end;
end;
SetLastError(LastError);
end;
end;
procedure ProcessFSAttributes(FileHandle: HANDLE; FileInformation: PVOID; FileInformationLength: ULONG;
FileInformationClass: FILE_INFORMATION_CLASS; STATUS: NTSTATUS);
var
FullFileName: string;
DirectoryName: PWideChar;
Offset: ULONG;
FileDirectoryInfo: PFILE_DIRECTORY_INFORMATION;
FileFullDirectoryInfo: PFILE_FULL_DIRECTORY_INFORMATION;
FileBothDirectoryInfo: PFILE_BOTH_DIRECTORY_INFORMATION;
begin
if not (NT_SUCCESS(STATUS)) then
Exit;
if not (FileInformationClass in [FileDirectoryInformation,
FileFullDirectoryInformation,
FileBothDirectoryInformation{,
FileNamesInformation}]) or
(STATUS = STATUS_NO_SUCH_FILE) or
(FileInformationLength = 0) then Exit;
//get firectory name
GetMem(DirectoryName, 1024 + 1);
GetFinalPathNameByHandle(FileHandle, DirectoryName, 1024, VOLUME_NAME_DOS or VOLUME_NAME_NONE);
FreeMem(DirectoryName);
FileFullDirectoryInfo := nil;
Offset := 0;
case (FileInformationClass) of
FileDirectoryInformation:
begin
repeat
FileDirectoryInfo := Pointer((NativeUInt(FileInformation) + Offset));
FullFileName := string(DirectoryName) + string(FileDirectoryInfo.FileName);
if ValidEnryptFileEx(FullFileName) then
FileDirectoryInfo.EndOfFile := FileDirectoryInfo.EndOfFile - 75;
Offset := Offset + FileDirectoryInfo.NextEntryOffset;
until (FileDirectoryInfo.NextEntryOffset = 0);
end;
FileFullDirectoryInformation:
begin
repeat
FileFullDirectoryInfo := Pointer((NativeUInt(FileInformation) + Offset));
FullFileName := string(DirectoryName) + string(FileFullDirectoryInfo.FileName);
if ValidEnryptFileEx(FullFileName) then
FileFullDirectoryInfo.EndOfFile := FileFullDirectoryInfo.EndOfFile - 75;
Offset := Offset + FileFullDirectoryInfo.NextEntryOffset;
until (FileFullDirectoryInfo.NextEntryOffset = 0);
end;
FileBothDirectoryInformation:
begin
repeat
FileBothDirectoryInfo := Pointer((NativeUInt(FileInformation) + Offset));
FullFileName := string(DirectoryName) + string(FileBothDirectoryInfo.FileName);
if ValidEnryptFileEx(FullFileName) then
FileFullDirectoryInfo.EndOfFile := FileFullDirectoryInfo.EndOfFile - 75;
Offset := Offset + FileBothDirectoryInfo.NextEntryOffset;
until (FileBothDirectoryInfo.NextEntryOffset = 0);
end;
FileNamesInformation:
begin
(*FileNamesInfo = NULL;
do
{
LastFileNamesInfo = FileNamesInfo;
FileNamesInfo = (PVOID)((ULONG)FileInformation + Offset);
if (FileNamesInfo->FileName[0] == 0x5F00)
{
if (!FileNamesInfo->NextEntryOffset)
{
if(LastFileNamesInfo) LastFileNamesInfo->NextEntryOffset = 0;
else status = STATUS_NO_SUCH_FILE;
return status;
} else
if (LastFileNamesInfo) LastFileNamesInfo->NextEntryOffset += FileNamesInfo->NextEntryOffset;
}
Offset += FileNamesInfo->NextEntryOffset;
} while (FileNamesInfo->NextEntryOffset);
break; *)
end;
end;
end;
function NtQueryDirectoryFileHookProc(FileHandle: HANDLE; Event: HANDLE; ApcRoutine: PIO_APC_ROUTINE; ApcContext: PVOID;
IoStatusBlock: PIO_STATUS_BLOCK; FileInformation: PVOID; FileInformationLength: ULONG;
FileInformationClass: FILE_INFORMATION_CLASS; ReturnSingleEntry: ByteBool; FileName: PUnicodeString;
RestartScan: ByteBool): NTSTATUS; stdcall;
begin
Result := NtQueryDirectoryFileNextHook(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
FileInformation, FileInformationLength, FileInformationClass,
ReturnSingleEntry, FileName, RestartScan);
ProcessFSAttributes(FileHandle, FileInformation, FileInformationLength, FileInformationClass, Result);
end;
function NtQueryInformationFileHookProc(FileHandle: HANDLE;
IoStatusBlock: PIO_STATUS_BLOCK;
FileInformation: PVOID;
FileInformationLength: ULONG;
FileInformationClass: FILE_INFORMATION_CLASS
): NTSTATUS; stdcall;
begin
Result := NtQueryInformationFileNextHook(FileHandle, IoStatusBlock, FileInformation,
FileInformationLength, FileInformationClass);
// ProcessFSAttributes(FileHandle, FileInformation, FileInformationLength, FileInformationClass, Result);
end;
procedure HookPEModule(Module: HModule; Recursive: Boolean = True);
begin
{$IFDEF DEBUG}
HookCode(Module, Recursive, @CreateProcessA, @CreateProcessACallbackProc, @CreateProcessANextHook);
HookCode(Module, Recursive, @CreateProcessW, @CreateProcessWCallbackProc, @CreateProcessWNextHook);
{REPLACED BY LdrLoadDll}
hookCode(Module, Recursive, @LoadLibraryA, @LoadLibraryAHookProc, @LoadLibraryANextHook);
hookCode(Module, Recursive, @LoadLibraryW, @LoadLibraryWHookProc, @LoadLibraryWNextHook);
hookCode(Module, Recursive, @LoadLibraryExA, @LoadLibraryExAHookProc, @LoadLibraryExANextHook);
hookCode(Module, Recursive, @LoadLibraryExW, @LoadLibraryExWHookProc, @LoadLibraryExWNextHook);
{ANOTHER HOOKS}
hookCode(Module, Recursive, @DuplicateHandle, @DuplicateHandleHookProc, @DuplicateHandleNextHook);
{REPLACED BY NtCreateFile}
{NOT IMPLEMENTED HOOKS}
hookCode(Module, Recursive, @_lopen, @_lopenHookProc, @_lopenNextHook);
hookCode(Module, Recursive, @_lcreat, @_lcreatHookProc, @_lcreatNextHook);
{$ENDIF}
hookCode(Module, Recursive, @LdrLoadDll, @LdrLoadDllHookProc, @LdrLoadDllNextHook);
//hookCode(Module, Recursive, @NtCreateFile, @NtCreateFileHookProc, @NtCreateFileNextHook);
//hookCode(Module, Recursive, @NtQueryDirectoryFile, @NtQueryDirectoryFileHookProc, @NtQueryDirectoryFileNextHook);
//hookCode(Module, Recursive, @NtQueryInformationFile, @NtQueryInformationFileHookProc, @NtQueryInformationFileNextHook);
hookCode(Module, Recursive, @GetProcAddress, @GetProcAddressHookProc, @GetProcAddressNextHook);
hookCode(Module, Recursive, @GetFileSize, @GetFileSizeHookProc, @GetFileSizeNextHook);
hookCode(Module, Recursive, @GetFileSizeEx, @GetFileSizeExHookProc, @GetFileSizeExNextHook);
hookCode(Module, Recursive, @FindFirstFileA, @FindFirstFileAHookProc, @FindFirstFileANextHook);
hookCode(Module, Recursive, @FindFirstFileW, @FindFirstFileWHookProc, @FindFirstFileWNextHook);
hookCode(Module, Recursive, @GetFileAttributesExA, @GetFileAttributesExAHookProc, @GetFileAttributesExANextHook);
hookCode(Module, Recursive, @GetFileAttributesExW, @GetFileAttributesExWHookProc, @GetFileAttributesExWNextHook);
hookCode(Module, Recursive, @CreateFileA, @CreateFileAHookProc, @CreateFileANextHook);
hookCode(Module, Recursive, @CreateFileW, @CreateFileWHookProc, @CreateFileWNextHook);
hookCode(Module, Recursive, @OpenFile, @OpenFileAHookProc, @OpenFileNextHook);
hookCode(Module, Recursive, @SetFilePointerEx, @SetFilePointerExHookProc, @SetFilePointerExNextHook);
hookCode(Module, Recursive, @SetFilePointer, @SetFilePointerHookProc, @SetFilePointerNextHook);
hookCode(Module, Recursive, @_lread, @_lreadHookProc, @_lreadNextHook);
hookCode(Module, Recursive, @ReadFile, @ReadFileHookProc, @ReadFileNextHook);
hookCode(Module, Recursive, @ReadFileEx, @ReadFileExHookProc, @ReadFileExNextHook);
hookCode(Module, Recursive, @CloseHandle, @CloseHandleHookProc, @CloseHandleNextHook);
hookCode(Module, Recursive, @CreateFileMappingA, @CreateFileMappingAHookProc, @CreateFileMappingANextHook);
hookCode(Module, Recursive, @CreateFileMappingW, @CreateFileMappingWHookProc, @CreateFileMappingWNextHook);
hookCode(Module, Recursive, @MapViewOfFile, @MapViewOfFileHookProc, @MapViewOfFileNextHook);
hookCode(Module, Recursive, @MapViewOfFileEx, @MapViewOfFileExHookProc, @MapViewOfFileExNextHook);
hookCode(Module, Recursive, @UnmapViewOfFile, @UnmapViewOfFileHookProc, @UnmapViewOfFileNextHook);
end;
procedure FixProcAddress(hModule: HMODULE; lpProcName: LPCSTR; var proc: FARPROC);
var
Module, ProcName: string;
begin
if ULONG_PTR(lpProcName) shr 16 = 0 then
Exit;
Module := AnsiLowerCase(ExtractFileName(GetModuleName(hModule)));
ProcName := AnsiLowerCase(string(AnsiString(lpProcName)));
if (Module = 'kernel32.dll') then
begin
if ProcName = AnsiLowerCase('_lopen') then
proc := @_lopenHookProc;
if ProcName = AnsiLowerCase('_lread') then
proc := @_lreadHookProc;
if ProcName = AnsiLowerCase('_lcreat') then
proc := @_lcreatHookProc;
if ProcName = AnsiLowerCase('LoadLibraryA') then
proc := @LoadLibraryAHookProc;
if ProcName = AnsiLowerCase('LoadLibraryW') then
proc := @LoadLibraryWHookProc;
if ProcName = AnsiLowerCase('LoadLibraryExA') then
proc := @LoadLibraryExAHookProc;
if ProcName = AnsiLowerCase('LoadLibraryExW') then
proc := @LoadLibraryExWHookProc;
if ProcName = AnsiLowerCase('GetProcAddress') then
proc := @GetProcAddressHookProc;
if ProcName = AnsiLowerCase('FindFirstFileA') then
proc := @FindFirstFileAHookProc;
if ProcName = AnsiLowerCase('FindFirstFileW') then
proc := @FindFirstFileWHookProc;
if ProcName = AnsiLowerCase('GetFileAttributesExA') then
proc := @GetFileAttributesExAHookProc;
if ProcName = AnsiLowerCase('GetFileAttributesExW') then
proc := @GetFileAttributesExWHookProc;
if ProcName = AnsiLowerCase('GetFileSize') then
proc := @GetFileSizeHookProc;
if ProcName = AnsiLowerCase('GetFileSizeEx') then
proc := @GetFileSizeExHookProc;
if ProcName = AnsiLowerCase('DuplicateHandle') then
proc := @DuplicateHandleHookProc;
if ProcName = AnsiLowerCase('CreateFileMappingA') then
proc := @CreateFileMappingAHookProc;
if ProcName = AnsiLowerCase('CreateFileMappingW') then
proc := @CreateFileMappingWHookProc;
if ProcName = AnsiLowerCase('MapViewOfFile') then
proc := @MapViewOfFileHookProc;
if ProcName = AnsiLowerCase('MapViewOfFileEx') then
proc := @MapViewOfFileExHookProc;
if ProcName = AnsiLowerCase('UnmapViewOfFile') then
proc := @UnmapViewOfFileHookProc;
if ProcName = AnsiLowerCase('OpenFile') then
proc := @OpenFileAHookProc;
if ProcName = AnsiLowerCase('CreateFileA') then
proc := @CreateFileAHookProc;
if ProcName = AnsiLowerCase('CreateFileW') then
proc := @CreateFileWHookProc;
if ProcName = AnsiLowerCase('SetFilePointer') then
proc := @SetFilePointerHookProc;
if ProcName = AnsiLowerCase('SetFilePointerEx') then
proc := @SetFilePointerExHookProc;
if ProcName = AnsiLowerCase('ReadFile') then
proc := @ReadFileHookProc;
if ProcName = AnsiLowerCase('ReadFileEx') then
proc := @ReadFileExHookProc;
if ProcName = AnsiLowerCase('CloseHandle') then
proc := @CloseHandleHookProc;
end;
end;
function GetProcAddressHookProc(hModule: HMODULE; lpProcName: LPCSTR): FARPROC; stdcall;
begin
Result := GetProcAddressNextHook(hModule, lpProcName);
if IsHookStarted then
FixProcAddress(hModule, lpProcName, Result);
end;
function OpenFileAHookProc(const lpFileName: LPCSTR; var lpReOpenBuff: TOFStruct; uStyle: UINT): HFILE; stdcall;
begin
Result := OpenFileNextHook(lpFileName, lpReOpenBuff, uStyle);
if IsHookStarted then
if ValidEnryptFileEx(string(AnsiString(lpFileName))) then
InitEncryptedFile(string(AnsiString(lpFileName)), Result, False);
end;
function CreateFileAHookProc(lpFileName: PAnsiChar; dwDesiredAccess, dwShareMode: DWORD;
lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD;
hTemplateFile: THandle): THandle; stdcall;
var
LastError: DWORD;
begin
if dwFlagsAndAttributes and FILE_FLAG_NO_BUFFERING = FILE_FLAG_NO_BUFFERING then
dwFlagsAndAttributes := dwFlagsAndAttributes xor FILE_FLAG_NO_BUFFERING; //remove flag, unsupported!
Result := CreateFileANextHook(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile );
LastError := GetLastError;
if IsHookStarted then
begin
if FILE_TYPE_DISK = GetFileType(Result) then
begin
if ValidEncryptFileExHandle(Result, dwFlagsAndAttributes and FILE_FLAG_OVERLAPPED > 0) then
begin
if (dwDesiredAccess and GENERIC_WRITE > 0) then
begin
CloseHandle(Result);
Result := INVALID_HANDLE_VALUE;
SetLastError(ERROR_ACCESS_DENIED);
Exit;
end;
InitEncryptedFile(string(AnsiString(lpFileName)), Result, dwFlagsAndAttributes and FILE_FLAG_OVERLAPPED > 0);
end;
end;
end;
SetLastError(LastError);
end;
function CreateFileWHookProc(lpFileName: PWideChar; dwDesiredAccess, dwShareMode: DWORD;
lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD;
hTemplateFile: THandle): THandle; stdcall;
var
LastError: DWORD;
begin
if dwFlagsAndAttributes and FILE_FLAG_NO_BUFFERING = FILE_FLAG_NO_BUFFERING then
dwFlagsAndAttributes := dwFlagsAndAttributes xor FILE_FLAG_NO_BUFFERING; //remove flag
Result := CreateFileWNextHook( lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile );
LastError := GetLastError;
if IsHookStarted then
begin
if FILE_TYPE_DISK = GetFileType(Result) then
begin
if ValidEncryptFileExHandle(Result, dwFlagsAndAttributes and FILE_FLAG_OVERLAPPED > 0) then
begin
if (dwDesiredAccess and GENERIC_WRITE > 0) then
begin
CloseHandle(Result);
Result := INVALID_HANDLE_VALUE;
SetLastError(ERROR_ACCESS_DENIED);
Exit;
end;
InitEncryptedFile(lpFileName, Result, dwFlagsAndAttributes and FILE_FLAG_OVERLAPPED > 0);
end;
end;
end;
SetLastError(LastError);
end;
function SetFilePointerHookProc(hFile: THandle; lDistanceToMove: Longint; lpDistanceToMoveHigh: Pointer; dwMoveMethod: DWORD): DWORD; stdcall;
begin
Result := FixFileSize(hFile, lDistanceToMove, lpDistanceToMoveHigh, dwMoveMethod, SetFilePointerNextHook);
end;
function SetFilePointerExHookProc(hFile: THandle; liDistanceToMove: TLargeInteger; const lpNewFilePointer: PLargeInteger; dwMoveMethod: DWORD): BOOL; stdcall;
begin
Result := FixFileSizeEx(hFile, liDistanceToMove, lpNewFilePointer, dwMoveMethod, SetFilePointerExNextHook);
end;
function ReadFileHookProc(hFile: THandle; var Buffer; nNumberOfBytesToRead: DWORD; lpNumberOfBytesRead: PDWORD; lpOverlapped: POverlapped): BOOL; stdcall;
var
dwCurrentFilePosition: Int64;
LastError: DWORD;
lpNumberOfBytesTransferred: DWORD;
IsFileEncrypted: Boolean;
begin
LastError := GetLastError;
dwCurrentFilePosition := FileSeek(hFile, Int64(0), FILE_CURRENT);
SetLastError(LastError);
IsFileEncrypted := IsEncryptedFileHandle(hFile);
if Assigned(lpOverlapped) then
begin
Int64Rec(dwCurrentFilePosition).Lo := lpOverlapped^.Offset;
Int64Rec(dwCurrentFilePosition).Hi := lpOverlapped^.OffsetHigh;
Result := ReadFileNextHook(hFile, Buffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
LastError := GetLastError;
//TODO: MSDN: If the ReadFile function attempts to read past the end of the file, the function returns zero, and GetLastError returns ERROR_HANDLE_EOF.
if not Result and (GetLastError = ERROR_IO_PENDING) then
begin
if GetOverlappedResult(hFile, lpOverlapped^, lpNumberOfBytesTransferred, True) then
begin
ReplaceBufferContent(hFile, Buffer, dwCurrentFilePosition, lpNumberOfBytesTransferred, lpNumberOfBytesTransferred, lpOverlapped, @Result);
SetLastError(LastError);
end;
end;
end else
begin
if IsFileEncrypted then
begin
//move to header size to have correct result code from OS, should be updated to use
FileSeek(hFile, SizeOf(TEncryptedFileHeader) + SizeOf(TEncryptFileHeaderExV1), FILE_CURRENT);
end;
Result := ReadFileNextHook(hFile, Buffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped);
if (lpNumberOfBytesRead <> nil) and (lpNumberOfBytesRead^ > 0) then
begin
//move back header size
if IsFileEncrypted then
FileSeek(hFile, -(SizeOf(TEncryptedFileHeader) + SizeOf(TEncryptFileHeaderExV1)), FILE_CURRENT);
LastError := GetLastError;
ReplaceBufferContent(hFile, Buffer, dwCurrentFilePosition, nNumberOfBytesToRead, lpNumberOfBytesRead^, nil, @Result);
SetLastError(LastError);
end;
end;
end;
function ReadFileExHookProc(hFile: THandle; lpBuffer: Pointer; nNumberOfBytesToRead: DWORD; lpOverlapped: POverlapped; lpCompletionRoutine: TPROverlappedCompletionRoutine): BOOL; stdcall;
begin
//TODO: support this method
NotifyEncryptionError('ReadFileEx');
Result := ReadFileExNextHook(hFile, lpBuffer, nNumberOfBytesToRead, lpOverlapped, lpCompletionRoutine);
end;
function CloseHandleHookProc(hObject: THandle): BOOL; stdcall;
var
LastError: Cardinal;
begin
Result := CloseHandleNextHook(hObject);
LastError := GetLastError;
CloseFileHandle(hObject);
SetLastError(LastError);
end;
initialization
SetEncryptionErrorHandler(NotifyEncryptionError);
end.
|
unit uFrmPO;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, DateBox, Mask, Db, DBTables,
ADODB, SuperComboADO, siComp, siLangRT, PaiDeForms;
type
TFrmPO = class(TFrmParentForms)
Panel1: TPanel;
Panel9: TPanel;
Panel3: TPanel;
scVendor: TSuperComboADO;
OrderDate: TDateBox;
Label1: TLabel;
Label2: TLabel;
quInsertPO: TADOQuery;
Label3: TLabel;
dtEstArriv: TDateBox;
scStore: TSuperComboADO;
Label4: TLabel;
btOK: TButton;
btCancel: TButton;
Label5: TLabel;
edtPayDays: TEdit;
Label6: TLabel;
Label7: TLabel;
memOBS: TMemo;
cmdUpdatePO: TADOCommand;
procedure btOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edtPayDaysKeyPress(Sender: TObject; var Key: Char);
procedure scVendorSelectItem(Sender: TObject);
private
FPODataSet: TADOQuery;
FIsInc: Boolean;
FIsOpened: Boolean;
procedure SetCaptionForm;
procedure SetDefaulfValues;
procedure SetLockedFields;
function ValidateFields: Boolean;
procedure InsertPO;
procedure UpdatePO;
public
function Start(ADataSet: TADOQuery; AIsInc, AIsOpened: Boolean): Boolean;
end;
implementation
uses uDM, uMsgBox, uMsgConstant, uDMGlobal, uCharFunctions;
{$R *.DFM}
function TFrmPO.Start(ADataSet: TADOQuery; AIsInc, AIsOpened: Boolean): Boolean;
begin
FPODataSet := ADataSet;
FIsInc := AIsInc;
FIsOpened := AIsOpened;
SetCaptionForm;
SetDefaulfValues;
SetLockedFields;
Result := (ShowModal = mrOK);
end;
procedure TFrmPO.btOKClick(Sender: TObject);
begin
if ValidateFields then
try
if FIsInc then
InsertPO
else
UpdatePO;
except
MsgBox(MSG_CRT_ERROR_OCURRED, vbInformation + vbOKOnly);
ModalResult := mrNone;
end
else
ModalResult := mrNone;
end;
procedure TFrmPO.FormShow(Sender: TObject);
begin
inherited;
if FIsInc then
begin
scVendor.SetFocus;
OrderDate.Text := DateTimeToStr(Date());
dtEstArriv.Date := Now + 7;
scStore.LookUpValue := IntToStr(DM.fStore.ID);
end
else
edtPayDays.SetFocus;
end;
procedure TFrmPO.edtPayDaysKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
Key := ValidateQty(Key);
end;
procedure TFrmPO.InsertPO;
var
iIDPO: Integer;
begin
iIDPO := DM.GetNextID('PO.IDPO');
with quInsertPO do
begin
Parameters.ParambyName('IDPO').Value := iIDPO;
Parameters.ParambyName('IDFornecedor').Value := StrToInt(scVendor.LookUpValue);
Parameters.ParambyName('IDStore').Value := StrToIntDef(scStore.LookUpValue, DM.fStore.ID);
Parameters.ParambyName('DataPedido').Value := OrderDate.Date;
Parameters.ParambyName('EstArriv').Value := dtEstArriv.Date;
Parameters.ParambyName('Aberto').Value := True;
Parameters.ParambyName('PayDays').Value := StrToIntDef(edtPayDays.Text,0);
Parameters.ParamByName('OBS').Value := memOBS.Text;
ExecSQL;
end;
end;
procedure TFrmPO.UpdatePO;
begin
with cmdUpdatePO do
begin
Parameters.ParamByName('IDPO').Value := FPODataSet.FieldByName('IDPO').AsInteger;
Parameters.ParamByName('DataPedido').Value := OrderDate.Date;
Parameters.ParamByName('EstArrival').Value := dtEstArriv.Date;
Parameters.ParamByName('PayDays').Value := StrToIntDef(edtPayDays.Text,0);
Parameters.ParamByName('OBS').Value := memOBS.Text;
Execute;
end;
end;
function TFrmPO.ValidateFields: Boolean;
begin
Result := False;
if Trim(scStore.LookUpValue) = '' then
begin
MsgBox(MSG_CRT_NO_STORE_SELECTED, vbCritical + vbOkOnly);
Exit;
end;
if Trim(scVendor.LookUpValue) = '' then
begin
MsgBox(MSG_CRT_NO_VENDOR, vbCritical + vbOkOnly);
Exit;
end;
Result := True;
end;
procedure TFrmPO.SetCaptionForm;
begin
case DMGlobal.IDLanguage of
LANG_ENGLISH:
if FIsInc then
Self.Caption := 'New PO'
else
Self.Caption := 'Update PO';
LANG_PORTUGUESE:
if FIsInc then
Self.Caption := 'Novo Pedido de Compra'
else
Self.Caption := 'Alterar Pedido de Compra';
LANG_SPANISH:
if FIsInc then
Self.Caption := 'Nuevo Pedido Compra'
else
Self.Caption := 'Alterar Pedido Compra';
end;
end;
procedure TFrmPO.SetDefaulfValues;
begin
if FIsInc then
begin
scStore.LookUpValue := '';
scStore.ReadOnly := False;
scStore.Color := clWhite;
scVendor.LookUpValue := '';
scVendor.ReadOnly := False;
scVendor.Color := clWhite;
OrderDate.Text := '';
dtEstArriv.Text := '';
edtPayDays.Text := '';
memOBS.Text := '';
end
else
begin
scStore.LookUpValue := FPODataSet.FieldByName('IDStore').AsString;
scStore.ReadOnly := True;
scStore.ParentColor := True;
scVendor.LookUpValue := FPODataSet.FieldByName('IDFornecedor').AsString;
scVendor.ReadOnly := True;
scVendor.ParentColor := True;
OrderDate.Date := FPODataSet.FieldByName('DataPedido').AsDateTime;
dtEstArriv.Date := FPODataSet.FieldByName('EstArrival').AsDateTime;
edtPayDays.Text := FPODataSet.FieldByName('PayDays').AsString;
memOBS.Text := FPODataSet.FieldByName('OBS').AsString;
end;
end;
procedure TFrmPO.SetLockedFields;
begin
if FIsOpened then
begin
OrderDate.Enabled := True;
OrderDate.ParentColor := False;
dtEstArriv.Enabled := True;
dtEstArriv.ParentColor := False;
edtPayDays.ReadOnly := False;
edtPayDays.ParentColor := False;
memOBS.ReadOnly := False;
memOBS.ParentColor := False;
end
else
begin
OrderDate.Enabled := False;
OrderDate.ParentColor := True;
dtEstArriv.Enabled := False;
dtEstArriv.ParentColor := True;
edtPayDays.ReadOnly := True;
edtPayDays.ParentColor := True;
memOBS.ReadOnly := True;
memOBS.ParentColor := True;
end;
end;
procedure TFrmPO.scVendorSelectItem(Sender: TObject);
begin
inherited;
edtPayDays.Text := IntToStr(dm.GetDayShiftVendorTerms(scVendor.LookUpFieldValue));
end;
end.
|
unit NamedPipes;
{$mode objfpc}{$H+}
interface
uses
Windows, Classes, SysUtils;
type
TPipeDirection = (pdInOut, pdIn, pdOut);
TNamedPipeStream = class(TStream)
public const
DefaultBufferSize: Integer = 64 * 1024; // 64K
private
FPipeName: String;
FPipeHandle: THandle;
FDirection: TPipeDirection;
FBufferSize: Integer;
function GetIsOpen: Boolean;
procedure SetPipeName(const Value: String);
procedure SetDirection(const Value: TPipeDirection);
procedure SetBufferSize(const Value: Integer);
protected
procedure CheckOpen;
procedure CheckClosed;
procedure Initialize; virtual;
class function GetSystemPipePath(const APipeName: String): String;
public
constructor Create(const APipeName: String; ADirection: TPipeDirection = pdInOut);
destructor Destroy; override;
function TryOpen: Boolean;
procedure Open; virtual;
procedure Close; virtual;
procedure Flush;
function AvailableBytes: Cardinal;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
property PipeHandle: THandle read FPipeHandle;
property PipeName: String read FPipeName write SetPipeName;
property Direction: TPipeDirection read FDirection write SetDirection;
property BufferSize: Integer read FBufferSize write SetBufferSize;
property IsOpen: Boolean read GetIsOpen;
end;
TNamedPipeServerStream = class(TNamedPipeStream)
public const
DefaultMaxInstances = 1;
DefaultOverlapped = True;
private
FMaxInstances: Integer;
FOverlapped: Boolean;
procedure SetMaxInstances(Value: Integer);
function GetMaxInstancesUnlimited: Boolean;
procedure SetMaxInstancesUnlimited(Value: Boolean);
procedure SetOverlapped(Value: Boolean);
procedure InternalCreatePipe;
protected
procedure Initialize; override;
procedure CheckOverlapped;
public
procedure Open; override;
procedure WaitForConnection;
function WaitForConnection(AWaitTimeout: Integer): Boolean;
procedure Disconnect;
property MaxInstances: Integer read FMaxInstances write SetMaxInstances;
property MaxInstancesUnlimited: Boolean read GetMaxInstancesUnlimited write SetMaxInstancesUnlimited;
property Overlapped: Boolean read FOverlapped write SetOverlapped;
end;
TNamedPipeClientStream = class(TNamedPipeStream)
private
procedure InternalCreatePipe;
public
procedure Open; override;
function Open(ABusyWaitTimeout: Integer): Boolean;
function WaitForIdle(ABusyWaitTimeout: Integer): Boolean;
end;
ENamedPipeError = class(Exception);
resourcestring
SErrorPipeOpen = 'This operation is illegal when the pipe is open.';
SErrorPipeClosed = 'This operation is illegal when the pipe is closed.';
SErrorPipeOverlappedRequired = 'This operation requires a pipe with an overlapped feature enabled.';
SErrorPipeTimeoutInvalid = 'Invalid timeout value (%d).';
implementation
const
FILE_FLAG_FIRST_PIPE_INSTANCE = DWORD($00080000);
PIPE_UNLIMITED_INSTANCES = 255;
NMPWAIT_USE_DEFAULT_WAIT = DWORD($00000000);
NMPWAIT_WAIT_FOREVER = DWORD($ffffffff);
{$REGION 'TNamedPipeStream'}
class function TNamedPipeStream.GetSystemPipePath(const APipeName: String): String;
begin
Result := '\\.\pipe\' + APipeName;
end;
constructor TNamedPipeStream.Create(const APipeName: String; ADirection: TPipeDirection);
begin
FPipeName := APipeName;
FDirection := ADirection;
FPipeHandle := INVALID_HANDLE_VALUE;
FBufferSize := DefaultBufferSize;
Initialize;
end;
destructor TNamedPipeStream.Destroy;
begin
Close;
inherited Destroy;
end;
procedure TNamedPipeStream.Initialize;
begin
// Virtual method to be overridden by descendants.
end;
procedure TNamedPipeStream.Open;
begin
// Virtual method to be overridden by descendants.
end;
function TNamedPipeStream.TryOpen: Boolean;
begin
try
Open;
Result := True;
except
Result := False;
end;
end;
procedure TNamedPipeStream.Close;
begin
if FPipeHandle <> INVALID_HANDLE_VALUE then
begin
CloseHandle(FPipeHandle);
FPipeHandle := INVALID_HANDLE_VALUE;
end;
end;
procedure TNamedPipeStream.CheckOpen;
begin
if not IsOpen then
raise ENamedPipeError.Create(SErrorPipeClosed);
end;
procedure TNamedPipeStream.CheckClosed;
begin
if IsOpen then
raise ENamedPipeError.Create(SErrorPipeOpen);
end;
function TNamedPipeStream.GetIsOpen: Boolean;
begin
Result := FPipeHandle <> INVALID_HANDLE_VALUE;
end;
procedure TNamedPipeStream.SetPipeName(const Value: String);
begin
CheckClosed;
FPipeName := Value;
end;
procedure TNamedPipeStream.SetDirection(const Value: TPipeDirection);
begin
CheckClosed;
FDirection := Value;
end;
procedure TNamedPipeStream.SetBufferSize(const Value: Integer);
begin
CheckClosed;
FBufferSize := Value;
end;
// TODO: Async pipe read with a timeout, using ReadFileEx in overlapped mode.
function TNamedPipeStream.Read(var Buffer; Count: Longint): Longint;
begin
CheckOpen;
Result := FileRead(FPipeHandle, Buffer, Count);
if Result = -1 then
RaiseLastOSError;
end;
// TODO: Async pipe write with a timeout, using WriteFileEx in overlapped mode.
function TNamedPipeStream.Write(const Buffer; Count: Longint): Longint;
begin
CheckOpen;
Result := FileWrite(FPipeHandle, Buffer, Count);
if Result = -1 then
RaiseLastOSError;
end;
procedure TNamedPipeStream.Flush;
begin
CheckOpen;
FlushFileBuffers(FPipeHandle);
end;
function TNamedPipeStream.AvailableBytes: Cardinal;
var
TotalBytesAvail: DWORD;
PeekResult: WINBOOL;
begin
CheckOpen;
PeekResult := PeekNamedPipe(FPipeHandle, nil, 0, nil, @TotalBytesAvail, nil);
if LongWord(PeekResult) = 0 then
RaiseLastOSError;
Result := TotalBytesAvail;
end;
{$ENDREGION}
{$REGION 'TNamedPipeServerStream'}
function TNamedPipeServerStream.GetMaxInstancesUnlimited: Boolean;
begin
Result := FMaxInstances = PIPE_UNLIMITED_INSTANCES;
end;
procedure TNamedPipeServerStream.SetMaxInstancesUnlimited(Value: Boolean);
begin
CheckClosed;
if Value then
FMaxInstances := PIPE_UNLIMITED_INSTANCES
else
FMaxInstances := DefaultMaxInstances;
end;
procedure TNamedPipeServerStream.SetOverlapped(Value: Boolean);
begin
CheckClosed;
FOverlapped := Value;
end;
procedure TNamedPipeServerStream.SetMaxInstances(Value: Integer);
begin
CheckClosed;
// MSDN: Acceptable values are in the range 1 through PIPE_UNLIMITED_INSTANCES (255).
if (Value <= 0) or (Value >= PIPE_UNLIMITED_INSTANCES) then
Value := PIPE_UNLIMITED_INSTANCES;
FMaxInstances := Value;
end;
procedure TNamedPipeServerStream.Initialize;
begin
inherited Initialize;
FOverlapped := DefaultOverlapped;
FMaxInstances := DefaultMaxInstances;
end;
procedure TNamedPipeServerStream.CheckOverlapped;
begin
if not FOverlapped then
raise ENamedPipeError.Create(SErrorPipeOverlappedRequired);
end;
procedure TNamedPipeServerStream.InternalCreatePipe;
var
PipePath: String;
dwOpenMode, dwPipeMode, nMaxInstances: DWORD;
begin
// Pipe path
PipePath := GetSystemPipePath(FPipeName);
// Direction
case FDirection of
pdInOut:
dwOpenMode := PIPE_ACCESS_DUPLEX;
pdIn:
dwOpenMode := PIPE_ACCESS_INBOUND;
pdOut:
dwOpenMode := PIPE_ACCESS_OUTBOUND;
else
dwOpenMode := 0;
end;
// Overlapped
if FOverlapped then
dwOpenMode := dwOpenMode or FILE_FLAG_OVERLAPPED;
// Pipe mode
dwPipeMode := PIPE_TYPE_BYTE or PIPE_READMODE_BYTE or PIPE_WAIT; // blocking byte mode
// Max instances
nMaxInstances := FMaxInstances;
if FMaxInstances = 1 then
dwOpenMode := dwOpenMode or FILE_FLAG_FIRST_PIPE_INSTANCE;
// Create server pipe
FPipeHandle := CreateNamedPipe(
PChar(PipePath), dwOpenMode, dwPipeMode, nMaxInstances,
FBufferSize, FBufferSize, 0, nil);
end;
procedure TNamedPipeServerStream.Open;
begin
CheckClosed;
InternalCreatePipe;
if FPipeHandle = INVALID_HANDLE_VALUE then
RaiseLastOSError;
end;
// Disconnect a currently connect client from the pipe.
procedure TNamedPipeServerStream.Disconnect;
begin
DisconnectNamedPipe(FPipeHandle);
end;
// Wait for a client process to connect to an instance of a named pipe.
procedure TNamedPipeServerStream.WaitForConnection;
var
ConnectResult: WINBOOL;
begin
// If a client connects before the function is called, the function returns
// zero and GetLastError returns ERROR_PIPE_CONNECTED. This can happen if
// a client connects in the interval between the call to CreateNamedPipe
// and the call to ConnectNamedPipe. In this situation, there is a good
// connection between client and server, even though the function returns zero.
ConnectResult := ConnectNamedPipe(FPipeHandle, nil);
if (LongWord(ConnectResult) = 0) and (GetLastError <> ERROR_PIPE_CONNECTED) then
RaiseLastOSError;
end;
// Wait for the specified amount of time for a client process to connect
// to an instance of a named pipe. Returns TRUE if connected, or FALSE otherwise.
function TNamedPipeServerStream.WaitForConnection(AWaitTimeout: Integer): Boolean;
var
ConnectResult, OverlapResult: WINBOOL;
OverlapEvent: THandle;
OverlapStruct: Windows.OVERLAPPED;
dwDummy, dwTimeout: DWORD;
begin
Result := False;
CheckOverlapped;
// < 0 - infinite wait
// = 0 - return immediately
// > 0 - wait for N milliseconds
if AWaitTimeout < 0 then
dwTimeout := Windows.INFINITE
else
dwTimeout := AWaitTimeout;
// Create an event
OverlapEvent := CreateEvent(
nil, // default security attribute
True, // manual-reset event
False, // initial state
nil); // unnamed event object
if OverlapEvent = 0 then
RaiseLastOSError;
// Start waiting for a connection
try
OverlapStruct := Default(Windows.OVERLAPPED);
OverlapStruct.hEvent := OverlapEvent;
ConnectResult := ConnectNamedPipe(FPipeHandle, @OverlapStruct);
if LongWord(ConnectResult) = 0 then
begin
case GetLastError of
// Pipe has just connected
ERROR_PIPE_CONNECTED:
Result := True;
// Pipe is awaiting a connection
ERROR_IO_PENDING:
begin
// Wait for the signal or timeout
if WaitForSingleObject(OverlapEvent, dwTimeout) = WAIT_OBJECT_0 then
begin
// Check that IO operation has been completed
dwDummy := 0;
OverlapResult := GetOverlappedResult(FPipeHandle, OverlapStruct, dwDummy, False);
Result := LongWord(OverlapResult) <> 0;
end;
// Cancel pending IO operation if it still hasn't been completed
if not Result then
CancelIo(FPipeHandle);
end;
end;
end;
finally
CloseHandle(OverlapEvent);
end;
end;
{$ENDREGION}
{$REGION 'TNamedPipeClientStream'}
procedure TNamedPipeClientStream.InternalCreatePipe;
var
PipePath: String;
dwDesiredAccess, dwShareMode, dwCreationDisposition: DWORD;
begin
// Pipe path
PipePath := GetSystemPipePath(FPipeName);
// Desired access
case FDirection of
pdInOut:
dwDesiredAccess := GENERIC_READ or GENERIC_WRITE;
pdIn:
// Will also need FILE_WRITE_ATTRIBUTES if need to call SetNamedPipeHandleState
dwDesiredAccess := GENERIC_READ;
pdOut:
// Will also need FILE_READ_ATTRIBUTES if need to call GetNamedPipeInfo or GetNamedPipeHandleState
dwDesiredAccess := GENERIC_WRITE;
else
dwDesiredAccess := 0;
end;
// Share mode
dwShareMode := 0; // no sharing
// Creation disposition
dwCreationDisposition := OPEN_EXISTING;
// Create client pipe
FPipeHandle := CreateFile(
PChar(PipePath), dwDesiredAccess, dwShareMode,
nil, dwCreationDisposition, 0, 0);
end;
// Open the client end of the pipe. Exception is raised if not successful,
// e.g. server pipe does not exist.
procedure TNamedPipeClientStream.Open;
begin
CheckClosed;
InternalCreatePipe;
if FPipeHandle = INVALID_HANDLE_VALUE then
RaiseLastOSError;
end;
// Open the client end of the pipe and allow waiting for a specified timeout
// if the pipe is busy (occupied by a another client). This function may return
// FALSE before the timeout has expired, in case of the race condition where
// another client beats us to taking the only remaining client slot.
// Exception is raised if any problems have occurred,
// e.g. server pipe does not exist.
function TNamedPipeClientStream.Open(ABusyWaitTimeout: Integer): Boolean;
begin
CheckClosed;
// Wait for pipe client slot to become available
// < 0 - infinite wait
// = 0 - return immediately
// > 0 - wait for N milliseconds
if ABusyWaitTimeout <> 0 then
if not WaitForIdle(ABusyWaitTimeout) then
Exit(False);
// Beware that even if WaitNamedPipe tells us that the pipe is ready
// to accept a connection, another client may setup a connection
// before we get a chance to connect ourselves (a race condition).
// Attempt to create client pipe
InternalCreatePipe;
// Pipe created successfully
if FPipeHandle <> INVALID_HANDLE_VALUE then
Result := True
// Server pipe is busy
else if GetLastError = ERROR_PIPE_BUSY then
Result := False
// Some problem has occurred
else
RaiseLastOSError;
end;
// Wait for an existing server pipe to become idle, i.e. awaiting a connection
// from a client. Exception is raised if any problems have occurred,
// e.g. server pipe does not exist.
function TNamedPipeClientStream.WaitForIdle(ABusyWaitTimeout: Integer): Boolean;
var
PipePath: String;
WaitResult: WINBOOL;
dwTimeout: DWORD;
begin
// < 0 - infinite wait
// = 0 - not supported, clashes with NMPWAIT_USE_DEFAULT_WAIT=0
// > 0 - wait for N milliseconds
if ABusyWaitTimeout < 0 then
dwTimeout := NMPWAIT_WAIT_FOREVER
else if (ABusyWaitTimeout = NMPWAIT_USE_DEFAULT_WAIT) then
raise ENamedPipeError.CreateFmt(SErrorPipeTimeoutInvalid, [ABusyWaitTimeout])
else
dwTimeout := ABusyWaitTimeout;
// Pipe path
PipePath := GetSystemPipePath(FPipeName);
// Wait for pipe client slot to become available
WaitResult := WaitNamedPipe(PChar(PipePath), dwTimeout);
// Beware that even if WaitNamedPipe tells us that the pipe is ready
// to accept a connection, another client may setup a connection
// before we get a chance to connect ourselves (a race condition).
// Server is ready for a connection?
Result := LongWord(WaitResult) <> 0;
// Check for non-timeout problems
if not Result then
if GetLastError <> ERROR_SEM_TIMEOUT then
RaiseLastOSError;
end;
{$ENDREGION}
end.
|
unit UPrinter;
(*====================================================================
Implementation of printing
======================================================================*)
{$ifndef DELPHI1}
{$LONGSTRINGS ON}
{$endif}
interface
uses
SysUtils,
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Graphics, FSettings,
UTypes
{$ifndef DELPHI1}
, UFont {Windows}
{$endif}
;
type
TPrintFontStyle = (pfsNormal, pfsBold, pfsItalic);
{ define FULLCTL - if defined, the Printer object is not used at all
if not defined, the printer object is used, but between BeginDoc and
EndDoc no Printer properties or methods are used, so it cannot
influence the font
Full Control is not finished yet - does not recognize orientation
}
var
TopPrintAreaPx, BottomPrintAreaPx: Integer;
LeftPrintAreaPx, RightPrintAreaPx: Integer;
WidthPx, HeightPx: Integer;
LineHeightPx: Integer;
Widthmm, Heightmm: Integer;
XPxPer1cm, YPxPer1cm: Integer;
XPxPer1mm, YPxPer1mm: Integer;
TimePrinted: ShortString;
procedure QPrinterReset(QGlobalOptions: TGlobalOptions);
procedure QPrinterNewPage;
procedure QPrinterSaveAndSetFont(PrintFontStyle: TPrintFontStyle);
procedure QPrinterRestoreFont;
///procedure QPrinterTextRect(Rect: TRect; X, Y: Integer; const Text: string);
procedure QPrinterMoveTo(X, Y: Integer);
procedure QPrinterLineTo(X, Y: Integer);
procedure QPrinterSetLineWidth(Width: Integer);
procedure QPrinterBeginDoc(Title: string);
procedure QPrinterEndDoc;
function QPrinterGetTextWidth(const Text: String): Integer;
//-----------------------------------------------------------------------------
implementation
uses
Printers, UBaseUtils, ULang;
var
QPHandle: HDC;
{$ifdef LOGFONT}
PrintLogFont: TLogFont;
PrintLogFontSize: Integer;
{$else}
PrintFont: TFont;
{$endif}
{$ifdef FULLCTL}
Device: array[0..256] of char;
Driver: array[0..256] of char;
Port: array[0..256] of char;
DeviceMode: THandle;
{$endif}
//-----------------------------------------------------------------------------
{$ifdef FULLCTL}
function AbortProc(Prn: HDC; Error: Integer): Bool; stdcall;
begin
//Application.ProcessMessages;
Result := True;
end;
{$endif}
//-----------------------------------------------------------------------------
function QPrinterGetTextWidth(const Text: String): Integer;
var
Extent: TSize;
begin
{$ifdef LOGFONT}
if Windows.GetTextExtentPoint(QPHandle, PChar(Text), Length(Text), Extent) then
Result := Extent.cX else
Result := 0;
{$else}
Result := Printer.Canvas.TextWidth(Text);
{$endif}
end;
//-----------------------------------------------------------------------------
function QPrinterGetTextHeight(const Text: String): Integer;
var
Extent: TSize;
begin
{$ifdef LOGFONT}
if Windows.GetTextExtentPoint(QPHandle, PChar(Text), Length(Text), Extent) then
Result := Extent.cY else
Result := 0;
{$else}
Result := Printer.Canvas.TextHeight(Text);
{$endif}
end;
//-----------------------------------------------------------------------------
procedure QPrinterSetFont;
{$ifdef LOGFONT}
var
PixelsPerInch: longint;
FontHandle: HFont;
PreviousFontHandle: HFont;
begin
PrintLogFont.lfWeight := FW_NORMAL;
PrintLogFont.lfItalic := 0;
PixelsPerInch := GetDeviceCaps(QPHandle, LOGPIXELSY);
PrintLogFont.lfHeight := -MulDiv(PrintLogFontSize, PixelsPerInch, 72);
FontHandle := CreateFontIndirect(PrintLogFont);
PreviousFontHandle := SelectObject(QPHandle, FontHandle);
DeleteObject(PreviousFontHandle);
end;
{$else}
begin
Printer.Canvas.Font.Assign(PrintFont);
end;
{$endif}
//-----------------------------------------------------------------------------
procedure QPrinterSaveAndSetFont(PrintFontStyle: TPrintFontStyle);
{$ifdef LOGFONT}
var
PixelsPerInch: longint;
FontHandle: HFont;
PreviousFontHandle: HFont;
begin
if PrintFontStyle = pfsNormal then
begin
PrintLogFont.lfWeight := FW_NORMAL;
PrintLogFont.lfItalic := 0;
end;
if PrintFontStyle = pfsBold then
begin
PrintLogFont.lfWeight := FW_BOLD;
PrintLogFont.lfItalic := 0;
end;
if PrintFontStyle = pfsItalic then
begin
PrintLogFont.lfWeight := FW_NORMAL;
PrintLogFont.lfItalic := 1;
end;
PixelsPerInch := GetDeviceCaps(QPHandle, LOGPIXELSY);
PrintLogFont.lfHeight := -MulDiv(PrintLogFontSize, PixelsPerInch, 72);
FontHandle := CreateFontIndirect(PrintLogFont);
PreviousFontHandle := SelectObject(QPHandle, FontHandle);
DeleteObject(PreviousFontHandle);
end;
{$else}
begin
Printer.Canvas.Font.Style := [];
if PrintFontStyle = pfsItalic then
Printer.Canvas.Font.Style := [fsItalic];
if PrintFontStyle = pfsBold then
Printer.Canvas.Font.Style := [fsBold];
end;
{$endif}
//-----------------------------------------------------------------------------
procedure QPrinterRestoreFont;
begin
{$ifdef LOGFONT}
QPrinterSetFont;
{$else}
Printer.Canvas.Font.Style := [];
{$endif}
end;
//-----------------------------------------------------------------------------
procedure RecheckHandle;
begin
{$ifdef LOGFONT}
QPHandle := Printer.Handle;
QPrinterSetFont;
{$endif}
end;
//-----------------------------------------------------------------------------
procedure QPrinterReset(QGlobalOptions: TGlobalOptions);
begin
{$ifdef FULLCTL}
Printer.GetPrinter(Device, Driver, Port, DeviceMode);
QPHandle := Windows.CreateIC(Driver, Device, Port, @DeviceMode);
Widthmm := GetDeviceCaps(QPHandle, HORZSIZE);
Heightmm := GetDeviceCaps(QPHandle, VERTSIZE);
WidthPx := GetDeviceCaps(QPHandle, HORZRES);
HeightPx := GetDeviceCaps(QPHandle, VERTRES);
XPxPer1cm := round((WidthPx / Widthmm) * 10);
YPxPer1cm := round((HeightPx / Heightmm) * 10);
XPxPer1mm := XPxPer1cm div 10 + 1;
YPxPer1mm := YPxPer1cm div 10 + 1;
TopPrintAreaPx := (QGlobalOptions.TopMargin * YPxPer1cm) div 10;
BottomPrintAreaPx := HeightPx - (QGlobalOptions.BottomMargin * YPxPer1cm) div 10;
LeftPrintAreaPx := (QGlobalOptions.LeftMargin * XPxPer1cm) div 10;
RightPrintAreaPx := WidthPx - (QGlobalOptions.RightMargin * XPxPer1cm) div 10;
TimePrinted := lsQDir + DateTimeToStr(Now);
PrintLogFont := QGlobalOptions.PrintLogFont;
PrintLogFontSize := QGlobalOptions.PrintLogFontSize;
QPrinterSetFont;
LineHeightPx := QPrinterGetTextHeight('άΘΑ/yp') + 1;
if QPHandle <> 0 then DeleteDC(QPHandle);
QPHandle := 0;
{$else}
Widthmm := GetDeviceCaps(Printer.Handle, HORZSIZE);
Heightmm := GetDeviceCaps(Printer.Handle, VERTSIZE);
WidthPx := GetDeviceCaps(Printer.Handle, HORZRES);
HeightPx := GetDeviceCaps(Printer.Handle, VERTRES);
XPxPer1cm := round((WidthPx / Widthmm) * 10);
YPxPer1cm := round((HeightPx / Heightmm) * 10);
XPxPer1mm := XPxPer1cm div 10 + 1;
YPxPer1mm := YPxPer1cm div 10 + 1;
TopPrintAreaPx := (QGlobalOptions.TopMargin * YPxPer1cm) div 10;
BottomPrintAreaPx := HeightPx - (QGlobalOptions.BottomMargin * YPxPer1cm) div 10;
LeftPrintAreaPx := (QGlobalOptions.LeftMargin * XPxPer1cm) div 10;
RightPrintAreaPx := WidthPx - (QGlobalOptions.RightMargin * XPxPer1cm) div 10;
TimePrinted := lsQDir + DateTimeToStr(Now);
{$ifdef LOGFONT}
PrintLogFont := QGlobalOptions.PrintLogFont;
PrintLogFontSize := QGlobalOptions.PrintLogFontSize;
RecheckHandle;
{$else}
PrintFont := QGlobalOptions.PrintFont;
Printer.Canvas.Font.Assign(PrintFont);
{$endif}
LineHeightPx := QPrinterGetTextHeight('άΘΑ/yp') + 1;
{$endif}
end;
//-----------------------------------------------------------------------------
procedure QPrinterNewPage;
begin
{$ifdef FULLCTL}
EndPage(QPHandle);
StartPage(QPHandle);
{$else}
Printer.NewPage;
RecheckHandle;
{$endif}
end;
//-----------------------------------------------------------------------------
procedure QPrinterTextRect(Rect: TRect; X, Y: Integer; const Text: string);
var
Options: Integer;
begin
{$ifdef LOGFONT}
Options := ETO_CLIPPED;
Windows.ExtTextOut(QPHandle, X, Y, Options, @Rect, PChar(Text),
Length(Text), nil);
{$else}
Printer.Canvas.TextRect(Rect, X, Y, Text);
{$endif}
end;
//-----------------------------------------------------------------------------
procedure QPrinterMoveTo(X, Y: Integer);
begin
{$ifdef LOGFONT}
Windows.MoveToEx(QPHandle, X, Y, nil);
{$else}
Printer.Canvas.MoveTo(X, Y);
{$endif}
end;
//-----------------------------------------------------------------------------
procedure QPrinterLineTo(X, Y: Integer);
begin
{$ifdef LOGFONT}
Windows.LineTo(QPHandle, X, Y);
{$else}
Printer.Canvas.LineTo(X, Y);
{$endif}
end;
//-----------------------------------------------------------------------------
procedure QPrinterSetLineWidth(Width: Integer);
var
LogPen: TLogPen;
PenHandle, PreviousHandle: HPen;
begin
{$ifdef LOGFONT}
with LogPen do
begin
lopnStyle := PS_SOLID;
lopnWidth.X := Width;
lopnColor := 0;
end;
PenHandle := CreatePenIndirect(LogPen);
PreviousHandle := SelectObject(QPHandle, PenHandle);
DeleteObject(PreviousHandle);
{$else}
Printer.Canvas.Pen.Width := Width;
{$endif}
end;
//-----------------------------------------------------------------------------
procedure QPrinterBeginDoc(Title: string);
{$ifdef FULLCTL}
var
CTitle: array[0..31] of Char;
DocInfo: TDocInfo;
begin
if QPHandle = 0 then
QPHandle := Windows.CreateDC(Driver, Device, Port, @DeviceMode);
QPrinterSetFont;
StrPLCopy(CTitle, Title, SizeOf(CTitle) - 1);
FillChar(DocInfo, SizeOf(DocInfo), 0);
with DocInfo do
begin
cbSize := SizeOf(DocInfo);
lpszDocName := CTitle;
lpszOutput := nil;
end;
SetAbortProc(QPHandle, AbortProc);
StartDoc(QPHandle, DocInfo);
StartPage(QPHandle);
end;
{$else}
begin
Printer.Title := Title;
Printer.BeginDoc;
RecheckHandle;
end;
{$endif}
//-----------------------------------------------------------------------------
procedure QPrinterEndDoc;
var
PreviousPenHandle: HPen;
PreviousFontHandle: HFont;
begin
{$ifdef FULLCTL}
PreviousPenHandle := SelectObject(QPHandle, GetStockObject(BLACK_PEN));
DeleteObject(PreviousPenHandle);
PreviousFontHandle := SelectObject(QPHandle, GetStockObject(SYSTEM_FONT));
DeleteObject(PreviousFontHandle);
EndPage(QPHandle);
Windows.EndDoc(QPHandle);
if QPHandle <> 0 then DeleteDC(QPHandle);
QPHandle := 0;
{$else}
{$ifdef LOGFONT}
PreviousPenHandle := SelectObject(QPHandle, GetStockObject(BLACK_PEN));
DeleteObject(PreviousPenHandle);
PreviousFontHandle := SelectObject(QPHandle, GetStockObject(SYSTEM_FONT));
DeleteObject(PreviousFontHandle);
{$endif}
Printer.EndDoc;
{$endif}
end;
//-----------------------------------------------------------------------------
begin
QPHandle := 0;
end.
|
unit SplashUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, jpeg, ExtCtrls, StdCtrls, ShellAPI;
type
TSplashScreen = class(TForm)
Image: TImage;
MailLabel: TLabel;
Status: TLabel;
procedure FormDestroy(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure MailLabelMouseEnter(Sender: TObject);
procedure MailLabelMouseLeave(Sender: TObject);
procedure MailLabelMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ImageMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
procedure SetStatusText(const Value: String);
public
{ Public declarations }
AsInfo:Boolean;
class function DefaultStatus:String;
property StatusText:String write SetStatusText;
end;
var
SplashScreen: TSplashScreen;
SMHTName, SVersion, SEngine: String;
implementation
uses StrUtils;
{$R *.dfm}
procedure TSplashScreen.FormDestroy(Sender: TObject);
begin
if Sender=SplashScreen then SplashScreen:=nil
end;
procedure TSplashScreen.FormActivate(Sender: TObject);
begin
with Status do
begin
if AsInfo then Caption:=DefaultStatus;
Top:=Status.Top-Status.Height
end;
Update
end;
procedure TSplashScreen.MailLabelMouseEnter(Sender: TObject);
begin
MailLabel.Font.Style:=MailLabel.Font.Style+[fsUnderline];
Update
end;
procedure TSplashScreen.MailLabelMouseLeave(Sender: TObject);
begin
MailLabel.Font.Style:=MailLabel.Font.Style-[fsUnderline];
Update
end;
procedure TSplashScreen.MailLabelMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
ShellExecute(Handle,nil,PChar('mailto:'+MailLabel.Caption+'?subject=WebChecker'),nil,nil,1)
end;
procedure TSplashScreen.ImageMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if AsInfo then Close
end;
procedure TSplashScreen.SetStatusText(const Value: String);
var S:TDateTime;
begin
Status.Caption:=Value+'...';
S:=Now;
while Now-S<0.5/(24*60*60) do Update;
end;
procedure TSplashScreen.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree
end;
class function TSplashScreen.DefaultStatus: String;
begin
Result:=
IfThen(SVersion<>'', 'Версія програми: '+SVersion)+
IfThen(SEngine<>'', #13#10'Ядро браузера: '+'MSIE '+SEngine)+
IfThen(SMHTName<>'',#13#10'Web-архіватор: '+SMHTName);
end;
end.
|
unit hfsGlobal;
{$I NoRTTI.inc}
interface
uses
graphics, Types, SysUtils, srvConst;
const
{$I RnQBuiltTime.inc}
CURRENT_VFS_FORMAT :integer = 1;
CRLF = #13#10;
CRLFA = RawByteString(#13#10);
TAB = #9;
BAK_EXT = '.bak';
VFS_FILE_IDENTIFIER = 'HFS.VFS';
CFG_KEY = 'Software\rejetto\HFS';
CFG_FILE = 'hfs.ini';
TPL_FILE = 'hfs.tpl';
IPS_FILE = 'hfs.ips.txt';
VFS_TEMP_FILE = '~temp.vfs';
HFS_HTTP_AGENT = 'HFS/'+VERSION;
EVENTSCRIPTS_FILE = 'hfs.events';
MACROS_LOG_FILE = 'macros-log.html';
PREVIOUS_VERSION = 'hfs.old.exe';
PROTECTED_FILES_MASK = 'hfs.*;*.htm*;descript.ion;*.comment;*.md5;*.corrupted;*.lnk';
G_VAR_PREFIX = '#';
ETA_FRAME = 5; // time frame for ETA (in seconds)
DOWNLOAD_MIN_REFRESH_TIME :Tdatetime = 1/(5*SECONDS); // 5 Hz
BYTES_GROUPING_THRESHOLD :Tdatetime = 1/SECONDS; // group bytes in log
IPS_THRESHOLD = 50; // used to avoid an external file for few IPs (ipsEverConnected list)
STATUSBAR_REFRESH = 10; // tenth of second
MAX_RECENT_FILES = 5;
MANY_ITEMS_THRESHOLD = 1000;
COMPRESSION_THRESHOLD = 10*KILO; // if more than X bytes, VFS files are compressed
STARTING_SNDBUF = 32000;
YESNO :array [boolean] of string=('no','yes');
DEFAULT_MIME = 'application/octet-stream';
IP_SERVICES_URL = 'http://hfsservice.rejetto.com/ipservices.php';
SELF_TEST_URL = 'http://hfstest.rejetto.com/';
// LIBS_DOWNLOAD_URL = 'http://rejetto.com/hfs/';
LIBS_DOWNLOAD_URL = 'http://libs.rnq.ru/';
HFS_GUIDE_URL = 'http://www.rejetto.com/hfs/guide/';
ALWAYS_ON_WEB_SERVER = 'google.com';
ADDRESS_COLOR = clGreen;
BG_ERROR = $BBBBFF;
ENCODED_TABLE_HEADER = 'this is an encoded table'+CRLF;
TRAY_ICON_SIZE = 32;
DEFAULT_MIME_TYPES: array [0..25] of string = (
'*.htm;*.html', 'text/html',
'*.jpg;*.jpeg;*.jpe', 'image/jpeg',
'*.gif', 'image/gif',
'*.png', 'image/png',
'*.bmp', 'image/bmp',
'*.ico', 'image/x-icon',
'*.mpeg;*.mpg;*.mpe', 'video/mpeg',
'*.avi', 'video/x-msvideo',
'*.txt', 'text/plain',
'*.css', 'text/css',
'*.js', 'text/javascript',
'*.mkv', 'video/x-matroska',
'*.webp', 'image/webp'
);
// messages
resourcestring
S_PORT_LABEL = 'Port: %s';
S_PORT_ANY = 'any';
DISABLED = 'disabled';
MSG_OK = 'Ok';
// messages
MSG_MENU_VAL = ' (%s)';
MSG_DL_TIMEOUT = 'No downloads timeout';
MSG_MAX_CON = 'Max connections';
MSG_MAX_CON_SING = 'Max connections from single address';
MSG_MAX_SIM_ADDR = 'Max simultaneous addresses';
MSG_MAX_SIM_ADDR_DL = 'Max simultaneous addresses downloading';
MSG_MAX_SIM_DL_SING = 'Max simultaneous downloads from single address';
MSG_MAX_SIM_DL = 'Max simultaneous downloads';
MSG_SET_LIMIT = 'Set limit';
MSG_UNPROTECTED_LINKS = 'Links are NOT actually protected.'
+#13'The feature is there to be used with the "list protected items only..." option.'
+#13'Continue?';
MSG_SAME_NAME ='An item with the same name is already present in this folder.'
+#13'Continue?';
MSG_CONTINUE = 'Continue?';
MSG_PROCESSING = 'Processing...';
MSG_SPEED_KBS = '%.1f kB/s';
MSG_OPTIONS_SAVED = 'Options saved';
MSG_SOME_LOCKED = 'Some items were not affected because locked';
MSG_ITEM_LOCKED = 'The item is locked';
MSG_INVALID_VALUE = 'Invalid value';
MSG_EMPTY_NO_LIMIT = 'Leave blank to get no limits.';
MSG_ADDRESSES_EXCEED = 'The following addresses exceed the limit:'#13'%s';
MSG_NO_TEMP = 'Cannot save temporary file';
MSG_ERROR_REGISTRY = 'Can''t write to registry.'
+#13'You may lack necessary rights.';
MSG_MANY_ITEMS = 'You are putting many files.'
+#13'Try using real folders instead of virtual folders.'
+#13'Read documentation or ask on the forum for help.';
MSG_ADD_TO_HFS = '"Add to HFS" has been added to your Window''s Explorer right-click menu.';
MSG_SINGLE_INSTANCE = 'Sorry, this feature only works with the "Only 1 instance" option enabled.'
+#13#13'You can find this option under Menu -> Start/Exit'
+#13'(only in expert mode)';
MSG_ENABLED = 'Option enabled';
MSG_DISABLED = 'Option disabled';
MSG_COMM_ERROR = 'Network error. Request failed.';
MSG_CON_PAUSED = 'paused';
MSG_CON_SENT = '%s / %s sent';
MSG_CON_RECEIVED = '%s / %s received';
type
// Pboolean = ^boolean;
TfilterMethod = function(self:Tobject):boolean;
Thelp = ( HLP_NONE, HLP_TPL );
TpreReply = (PR_NONE, PR_BAN, PR_OVERLOAD);
TuploadResult = record
fn, reason:string;
speed:integer;
size: int64;
end;
type
TTrayShows = (TS_downloads, TS_connections, TS_uploads, TS_hits, TS_ips, TS_ips_ever, TS_none);
implementation
end.
|
unit uSiteUtils;
interface
uses
Winapi.Windows,
Winapi.ShellApi,
System.SysUtils,
Dmitry.Utils.System,
uConstants,
uTranslate,
uActivationUtils,
uUpTime;
procedure DoHelp;
procedure DoHomeContactWithAuthor;
procedure DoHomePage;
procedure DoBuyApplication;
procedure DoDonate;
function GenerateProgramSiteParameters: string;
implementation
function GenerateProgramSiteParameters: string;
begin
Result := '?v=' + ProductVersion + '&ac=' + TActivationManager.Instance.ApplicationCode + '&ut=' + IntToStr(GetCurrentUpTime);
end;
procedure DoHelp;
begin
ShellExecute(GetActiveWindow, 'open', PWideChar(ResolveLanguageString(HomePageURL) + '?mode=help'), nil, nil, SW_NORMAL);
end;
procedure DoHomePage;
begin
ShellExecute(GetActiveWindow, 'open', PWideChar(ResolveLanguageString(HomePageURL)), nil, nil, SW_NORMAL);
end;
procedure DoHomeContactWithAuthor;
begin
ShellExecute(GetActiveWindow, 'open', PWideChar('mailto:' + ProgramMail + '?subject=''''' + ProductName + ''''''), nil, nil, SW_NORMAL);
end;
procedure DoBuyApplication;
var
BuyUrl: string;
begin
BuyUrl := ResolveLanguageString(BuyPageURL) + GenerateProgramSiteParameters;
ShellExecute(GetActiveWindow, 'open', PWideChar(BuyUrl), nil, nil, SW_NORMAL);
end;
procedure DoDonate;
begin
ShellExecute(GetActiveWindow, 'open', PWideChar(ResolveLanguageString(DonateURL)), nil, nil, SW_NORMAL);
end;
end.
|
constructor TGPoint.Create(x_,y_:extended;L:TList;C:TCanvas);
begin
x:=x_;
y:=y_;
inherited Create(L,C);
Color.Color:=$00FFFFFF;
closeDist:=2;
end;
//------------------------------------------------------------------
function TGPoint.Clone:TGraphObject;
var a:TGPoint;
begin
a:=TGPoint.Create(x,y,nil,getCanvas);
a.orig_index:=getOrigIndex;
result:=a;
end;
//------------------------------------------------------------------
procedure TGPoint.draw;
begin
getcanvas.pixels[round(x),round(y)]:=color.Color;
end;
//------------------------------------------------------------------
procedure TGPoint.clear;
begin
end;
//------------------------------------------------------------------
function TGPoint.getX:extended;
begin
result:=x;
end;
//------------------------------------------------------------------
function TGPoint.getY:extended;
begin
result:=y;
end;
//------------------------------------------------------------------
function TGPoint.DistanceTo(p:TGPoint):extended;
begin
result:=sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
end;
//------------------------------------------------------------------
function TGPoint.DistanceTo(x_,y_:extended):extended;
begin
result:=sqrt((x_-x)*(x_-x)+(y_-y)*(y_-y));
end;
//------------------------------------------------------------------
procedure TGPoint.MoveTo(x_,y_:extended);
begin
x:=x_;
y:=y_;
end;
//------------------------------------------------------------------
function TGPoint.Match(p:TGPoint):boolean;
begin
result:= (DistanceTo(p) <= CloseDist);
end;
//------------------------------------------------------------------
function TGPoint.Match(x_,y_:extended):boolean;
begin
result:= (DistanceTo(x_,y_) <= CloseDist);
end;
//------------------------------------------------------------------
function TGPoint.Angle(p:TGPoint):extended; // required for building the convex hull
begin
result:=arcsin((p.x-x)/distanceto(p));
if (p.x>=x) and (p.y>=y) then
else
if (p.x>=x) and (p.y<y) then
result:=pi-result else
if (p.x<x) and (p.y>=y) then
result:=(pi+pi)+result else
if (p.x<x) and (p.y<y) then
result:=pi-result;
end;
//------------------------------------------------------------------
function TGPoint.IsRightTurn(p1,p2:TGPoint):boolean; // required for Graham scan
var a1,a2:extended;
begin
a1:=angle(p1);
a2:=angle(p2);
a1:=a1-a2;
if a1<0 then a1:=2*pi+a1;
if a1>pi then result:=true else result:=false;
end;
//------------------------------------------------------------------
function TGPoint.areCollinear(a,b:TGPoint):boolean;
begin
result:= ((b.y-a.y)*(x-a.x)-(b.x-a.x)*(y-a.y))=0;
end;
//------------------------------------------------------------------
function TGPoint.Bisector(p:TGPoint):TGLine;
var a:TGLine;
sx,sy,dx,dy:extended;
begin
sx:= (x+p.x)/2;
sy:= (y+p.y)/2;
dx:= p.x-x;
dy:= p.y-y;
a:=TGLine.Create(TGPoint.Create(sx-dy,sy+dx,nil,nil),TGPoint.Create(sx+dy,sy-dx,nil,nil),Vector,nil,getCanvas);
a.bisectorOf[1]:=getOrigIndex;
a.bisectorOf[2]:=p.getOrigIndex;
result:=a;
end;
//------------------------------------------------------------------
// Got this one from the internet
function TGPoint.CircleCenter(a,b:TGPoint):TGPoint;
var u,v,den:extended;
begin
u := ((a.x-b.x)*(a.x+b.x) + (a.y-b.y)*(a.y+b.y)) / 2.0;
v := ((b.x-x)*(b.x+x) + (b.y-y)*(b.y+y)) / 2.0;
den := (a.x-b.x)*(b.y-y) - (b.x-x)*(a.y-b.y);
result:=TGPoint.Create((u*(b.y-y) - v*(a.y-b.y)) / den,
(v*(a.x-b.x) - u*(b.x-x)) / den,nil,getcanvas);
end;
|
unit E_Options;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, ToolEdit, ExtCtrls, ComCtrls, E_Var, ChooseOrg, Buttons,
Db, DBTables, RxLookup, uCommonForm,uOilQuery,Ora, uOilStoredProc;
type
TE_OptionsForm = class(TCommonForm)
PageControl1: TPageControl;
Panel2: TPanel;
bbCancel: TBitBtn;
bbOk: TBitBtn;
TabSheet2: TTabSheet;
Panel3: TPanel;
Panel4: TPanel;
cbImpLog: TCheckBox;
edImpLogFile: TEdit;
cb_I1C_TestRecordExists: TCheckBox;
cb_I1C_WITHNDS: TCheckBox;
cb_I1C_ANALIZEORGNAME: TCheckBox;
cb_I1C_ReplaceOrgName: TCheckBox;
cb_I1C_AddFirmaAuto: TCheckBox;
cb_I1C_SearchST: TCheckBox;
cb_I1C_SearchNB: TCheckBox;
procedure bbOkClick(Sender: TObject);
procedure LoadValues;
procedure ApplyChanges;
private
public
end;
var
E_OptionsForm: TE_OptionsForm;
procedure ShowOptions(Page:integer);
implementation
{$R *.DFM}
uses UDbFunc, ListSelect, ExFunc, E_CurRate;
//==============================================================================
procedure TE_OptionsForm.LoadValues;
begin
cb_I1C_TestRecordExists.Checked := E_I1C_TESTRECORDEXISTS;
cb_I1C_WITHNDS.Checked := E_I1C_WITHNDS;
cb_I1C_AnalizeOrgName.Checked := E_I1C_ANALIZEORGNAME;
cb_I1C_ReplaceOrgName.Checked := E_I1C_REPLACEORGNAME;
cb_I1C_SearchST.Checked := E_I1C_SEARCHST;
cb_I1C_SearchNB.Checked := E_I1C_SEARCHNB;
end;
//==============================================================================
procedure ShowOptions(Page: integer);
var
F: TE_OptionsForm;
begin
Application.CreateForm(TE_OptionsForm, F);
if Page >= F.PageControl1.PageCount then Page := 0;
F.PageControl1.ActivePage := F.PageControl1.Pages[Page];
F.LoadValues;
F.ShowModal;
F.Free;
end;
//==============================================================================
procedure TE_OptionsForm.ApplyChanges;
begin
E_I1C_TESTRECORDEXISTS := cb_I1C_TestRecordExists.Checked;
E_I1C_WITHNDS := cb_I1C_WITHNDS.Checked;
E_I1C_ANALIZEORGNAME := cb_I1C_AnalizeOrgName.Checked;
E_I1C_REPLACEORGNAME := cb_I1C_ReplaceOrgName.Checked;
E_I1C_ADDFIRMAAUTO := cb_I1C_AddFirmaAuto.Checked;
E_I1C_SEARCHST := cb_I1C_SearchST.Checked;
E_I1C_SEARCHNB := cb_I1C_SearchNB.Checked;
end;
//==============================================================================
procedure TE_OptionsForm.bbOkClick(Sender: TObject);
begin
ApplyChanges;
if MessageDlg(TranslateText('Сохранить опции?'), mtConfirmation, [mbYes,mbNo], 0) = mrYes then
E_SaveVar;
ModalResult := mrOk;
end;
//==============================================================================
end.
|
unit ImageRGBData;
interface
uses Windows, Graphics, Abstract2DImageData, RGBSingleDataSet, dglOpenGL;
type
T2DImageRGBData = class (TAbstract2DImageData)
private
// Gets
function GetData(_x, _y, _c: integer):single;
// Sets
procedure SetData(_x, _y, _c: integer; _value: single);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y: integer):single; override;
function GetGreenPixelColor(_x,_y: integer):single; override;
function GetBluePixelColor(_x,_y: integer):single; override;
function GetAlphaPixelColor(_x,_y: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y: integer; _value:single); override;
public
// Gets
function GetOpenGLFormat:TGLInt; override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
// properties
property Data[_x,_y,_c:integer]:single read GetData write SetData; default;
end;
implementation
// Constructors and Destructors
procedure T2DImageRGBData.Initialize;
begin
FData := TRGBSingleDataSet.Create;
end;
// Gets
function T2DImageRGBData.GetData(_x, _y, _c: integer):single;
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: Result := (FData as TRGBSingleDataSet).Red[(_y * FXSize) + _x];
1: Result := (FData as TRGBSingleDataSet).Green[(_y * FXSize) + _x];
else
begin
Result := (FData as TRGBSingleDataSet).Blue[(_y * FXSize) + _x];
end;
end;
end
else
begin
Result := -99999;
end;
end;
function T2DImageRGBData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB(Round((FData as TRGBSingleDataSet).Blue[_Position]) and $FF,Round((FData as TRGBSingleDataSet).Green[_Position]) and $FF,Round((FData as TRGBSingleDataSet).Red[_Position]) and $FF);
end;
function T2DImageRGBData.GetRPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBSingleDataSet).Red[_Position]) and $FF;
end;
function T2DImageRGBData.GetGPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBSingleDataSet).Green[_Position]) and $FF;
end;
function T2DImageRGBData.GetBPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBSingleDataSet).Blue[_Position]) and $FF;
end;
function T2DImageRGBData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T2DImageRGBData.GetRedPixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBSingleDataSet).Red[(_y * FXSize) + _x];
end;
function T2DImageRGBData.GetGreenPixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBSingleDataSet).Green[(_y * FXSize) + _x];
end;
function T2DImageRGBData.GetBluePixelColor(_x,_y: integer):single;
begin
Result := (FData as TRGBSingleDataSet).Blue[(_y * FXSize) + _x];
end;
function T2DImageRGBData.GetAlphaPixelColor(_x,_y: integer):single;
begin
Result := 0;
end;
function T2DImageRGBData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T2DImageRGBData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TRGBSingleDataSet).Red[_Position] := GetRValue(_Color);
(FData as TRGBSingleDataSet).Green[_Position] := GetGValue(_Color);
(FData as TRGBSingleDataSet).Blue[_Position] := GetBValue(_Color);
end;
procedure T2DImageRGBData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TRGBSingleDataSet).Red[_Position] := _r;
(FData as TRGBSingleDataSet).Green[_Position] := _g;
(FData as TRGBSingleDataSet).Blue[_Position] := _b;
end;
procedure T2DImageRGBData.SetRedPixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBSingleDataSet).Red[(_y * FXSize) + _x] := _value;
end;
procedure T2DImageRGBData.SetGreenPixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBSingleDataSet).Green[(_y * FXSize) + _x] := _value;
end;
procedure T2DImageRGBData.SetBluePixelColor(_x,_y: integer; _value:single);
begin
(FData as TRGBSingleDataSet).Blue[(_y * FXSize) + _x] := _value;
end;
procedure T2DImageRGBData.SetAlphaPixelColor(_x,_y: integer; _value:single);
begin
// do nothing
end;
procedure T2DImageRGBData.SetData(_x, _y, _c: integer; _value: single);
begin
if (_x >= 0) and (_x < FXSize) and (_y >= 0) and (_y < FYSize) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: (FData as TRGBSingleDataSet).Red[(_y * FXSize) + _x] := _value;
1: (FData as TRGBSingleDataSet).Green[(_y * FXSize) + _x] := _value;
2: (FData as TRGBSingleDataSet).Blue[(_y * FXSize) + _x] := _value;
end;
end;
end;
// Misc
procedure T2DImageRGBData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBSingleDataSet).Red[x] := Round((FData as TRGBSingleDataSet).Red[x] * _Value);
(FData as TRGBSingleDataSet).Green[x] := Round((FData as TRGBSingleDataSet).Green[x] * _Value);
(FData as TRGBSingleDataSet).Blue[x] := Round((FData as TRGBSingleDataSet).Blue[x] * _Value);
end;
end;
procedure T2DImageRGBData.Invert;
var
x,maxx: integer;
begin
maxx := (FXSize * FYSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBSingleDataSet).Red[x] := 1 - (FData as TRGBSingleDataSet).Red[x];
(FData as TRGBSingleDataSet).Green[x] := 1 - (FData as TRGBSingleDataSet).Green[x];
(FData as TRGBSingleDataSet).Blue[x] := 1 - (FData as TRGBSingleDataSet).Blue[x];
end;
end;
end.
|
unit Demo.Histogram.Sample;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_Histogram_Sample = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_Histogram_Sample.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_HISTOGRAM_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Dinosaur'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Length')
]);
Chart.Data.AddRow(['Acrocanthosaurus (top-spined lizard)', 12.2]);
Chart.Data.AddRow(['Albertosaurus (Alberta lizard)', 9.1]);
Chart.Data.AddRow(['Allosaurus (other lizard)', 12.2]);
Chart.Data.AddRow(['Apatosaurus (deceptive lizard)', 22.9]);
Chart.Data.AddRow(['Archaeopteryx (ancient wing)', 0.9]);
Chart.Data.AddRow(['Argentinosaurus (Argentina lizard)', 36.6]);
Chart.Data.AddRow(['Baryonyx (heavy claws)', 9.1]);
Chart.Data.AddRow(['Brachiosaurus (arm lizard)', 30.5]);
Chart.Data.AddRow(['Ceratosaurus (horned lizard)', 6.1]);
Chart.Data.AddRow(['Coelophysis (hollow form)', 2.7]);
Chart.Data.AddRow(['Compsognathus (elegant jaw)', 0.9]);
Chart.Data.AddRow(['Deinonychus (terrible claw)', 2.7]);
Chart.Data.AddRow(['Diplodocus (double beam)', 27.1]);
Chart.Data.AddRow(['Dromicelomimus (emu mimic)', 3.4]);
Chart.Data.AddRow(['Gallimimus (fowl mimic)', 5.5]);
Chart.Data.AddRow(['Mamenchisaurus (Mamenchi lizard)', 21.0]);
Chart.Data.AddRow(['Megalosaurus (big lizard)', 7.9]);
Chart.Data.AddRow(['Microvenator (small hunter)', 1.2]);
Chart.Data.AddRow(['Ornithomimus (bird mimic)', 4.6]);
Chart.Data.AddRow(['Oviraptor (egg robber)', 1.5]);
Chart.Data.AddRow(['Plateosaurus (flat lizard)', 7.9]);
Chart.Data.AddRow(['Sauronithoides (narrow-clawed lizard)', 2.0]);
Chart.Data.AddRow(['Seismosaurus (tremor lizard)', 45.7]);
Chart.Data.AddRow(['Spinosaurus (spiny lizard)', 12.2]);
Chart.Data.AddRow(['Supersaurus (super lizard)', 30.5]);
Chart.Data.AddRow(['Tyrannosaurus (tyrant lizard)', 15.2]);
Chart.Data.AddRow(['Ultrasaurus (ultra lizard)', 30.5]);
Chart.Data.AddRow(['Velociraptor (swift robber)', 1.8]);
// Options
Chart.Options.Title('Lengths of dinosaurs, in meters');
Chart.Options.Legend('position', 'none');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_Histogram_Sample);
end.
|
unit UTimeWatcher;
interface
//------------------------------------------------------------------------------
uses
SysUtils, Windows;
procedure StartCount(
const ID: Integer
);
procedure EndAndWriteCount(
const ID: Integer
);
//------------------------------------------------------------------------------
implementation
var
GCounterPerSec: TLargeInteger;
GFile: text;
GTimeStorage: array[0..999] of TLargeInteger;
procedure StartCount(
const ID: Integer
);
begin
QueryPerformanceCounter(GTimeStorage[ID]);
end;
procedure EndAndWriteCount(
const ID: Integer
);
var
TickEnd: TLargeInteger;
ElapsedTime: Double;
begin
QueryPerformanceCounter(TickEnd);
ElapsedTime := (TickEnd - GTimeStorage[ID]) / GCounterPerSec;
if (ElapsedTime < 1) then
Writeln(GFile, ID:3, ' => ', (ElapsedTime * 1000):10:6, ' ms')
else
Writeln(GFile, ID:3, ' => ', ElapsedTime:11:6, ' m');
end;
//------------------------------------------------------------------------------
initialization
AssignFile(GFile, ExtractFileDir(ParamStr(0)) + '\TimeLog.txt');
Rewrite(GFile);
QueryPerformanceFrequency(GCounterPerSec);
//------------------------------------------------------------------------------
finalization
CloseFile(GFile);
end.
|
unit Win.WebBrowser;
interface
(*
Special thanks to David Esperalta, aka Dec @ http://www.clubdelphi.com/foros/member.php?u=4681
http://www.clubdelphi.com/foros/showthread.php?p=507565
*)
uses
System.Win.Registry;
type
{$REGION 'TInternetExplorerVersion'}
{$SCOPEDENUMS ON}
/// <summary> Version Numbers for Windows Internet Explorer </summary>
TInternetExplorerVersion = (
/// <summary> Internet Explorer 11 </summary>
IE11,
/// <summary> Internet Explorer 10 </summary>
IE10,
/// <summary> Internet Explorer 9 </summary>
IE9,
/// <summary> Internet Explorer 8 </summary>
IE8,
/// <summary> Internet Explorer 7 </summary>
IE7
);
{$SCOPEDENUMS OFF}
{$ENDREGION}
{$REGION 'TInternetExplorerVersionHelper'}
TInternetExplorerVersionHelper = record helper for TInternetExplorerVersion
public
/// <summary> Returns the Flag specified by Windows API for the given Internet Explorer Version </summary>
function Value: Integer;
end;
{$ENDREGION}
{$REGION 'TWinWebBrowserEmulation'}
/// <summary> Class that tweaks the Windows Registry to enable TWebBrowser emulation support </summary>
TWinWebBrowserEmulation = class
strict private
/// <summary> Creates and returns a TRegistry pointing to the FEATURE_BROWSER_EMULATION Key </summary>
function OpenWebBrowserEmulationRegistry(out ARegistry: TRegistry): Boolean;
strict protected
/// <summary> Returns the full Key Path to the FEATURE_BROWSER_EMULATION </summary>
function GetFeatureBrowserEmulationRegistryKey: string; virtual;
/// <summary> Returns the Name of the Application Executable </summary>
function GetExeName: string; virtual;
public
/// <summary> Tweaks the Windows Registry allowing TWebBrowser Support for the given Internet Explorer Version </summary>
procedure EnableBrowserEmulation(const Version: TInternetExplorerVersion);
/// <summary> Restores any changes done to the Windows Registry </summary>
procedure RestoreBrowserEmulation;
end;
{$ENDREGION}
implementation
uses
Winapi.Windows,
System.SysUtils;
{$REGION 'TWinWebBrowserEmulation'}
function TWinWebBrowserEmulation.GetExeName: string;
begin
Result := ExtractFileName(ParamStr(0));
end;
function TWinWebBrowserEmulation.GetFeatureBrowserEmulationRegistryKey: string;
begin
Result := 'Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION';
end;
function TWinWebBrowserEmulation.OpenWebBrowserEmulationRegistry(out ARegistry: TRegistry): Boolean;
begin
Result := False;
ARegistry := TRegistry.Create;
try
ARegistry.RootKey := HKEY_CURRENT_USER;
Result := ARegistry.OpenKey(GetFeatureBrowserEmulationRegistryKey, True);
finally
if not Result then
ARegistry.Free;
end;
end;
procedure TWinWebBrowserEmulation.RestoreBrowserEmulation;
var
Registry: TRegistry;
begin
if not OpenWebBrowserEmulationRegistry(Registry) then
Exit;
try
if Registry.ValueExists(GetExeName) then
Registry.DeleteKey(GetExeName);
Registry.CloseKey
finally
Registry.Free;
end;
end;
procedure TWinWebBrowserEmulation.EnableBrowserEmulation(const Version: TInternetExplorerVersion);
var
Registry: TRegistry;
begin
if not OpenWebBrowserEmulationRegistry(Registry) then
Exit;
try
if not Registry.ValueExists(GetExeName) then
Registry.WriteInteger(GetExeName, Version.Value);
Registry.CloseKey
finally
Registry.Free;
end;
end;
{$ENDREGION}
{$REGION 'TInternetExplorerVersionHelper'}
function TInternetExplorerVersionHelper.Value: Integer;
begin
// Values from http://msdn.microsoft.com/en-us/library/ee330730(VS.85).aspx#browser_emulation
case Self of
TInternetExplorerVersion.IE11: Result := 11000;
TInternetExplorerVersion.IE10: Result := 10000;
TInternetExplorerVersion.IE9: Result := 9000;
TInternetExplorerVersion.IE8: Result := 8000;
TInternetExplorerVersion.IE7: Result := 7000;
else
raise Exception.Create('TInternetExplorerVersionHelper.Value: Unknown value');
end;
end;
{$ENDREGION}
end. |
unit ThAnchor;
interface
uses
SysUtils, Classes, Graphics,
ThChangeNotifier, ThTag, ThAnchorStyles;
type
TThCustomAnchor = class(TThChangeNotifier)
private
FTarget: string;
FHref: string;
FStyles: TThAnchorStyles;
FName: string;
procedure SetName(const Value: string);
protected
procedure SetHref(const Value: string);
procedure SetTarget(const Value: string);
procedure SetStyles(const Value: TThAnchorStyles);
protected
procedure Tag(inTag: TThTag); virtual;
protected
property Href: string read FHref write SetHref;
property Name: string read FName write SetName;
property Target: string read FTarget write SetTarget;
property Styles: TThAnchorStyles read FStyles write SetStyles;
public
constructor Create;
destructor Destroy; override;
function Wrap(const inContent: string): string;
function Empty: Boolean;
end;
//
TThAnchor = class(TThCustomAnchor)
public
property Name;
published
property Href;
property Styles;
property Target;
end;
implementation
{ TThCustomAnchor }
constructor TThCustomAnchor.Create;
begin
FStyles := TThAnchorStyles.Create;
end;
destructor TThCustomAnchor.Destroy;
begin
FStyles.Free;
inherited;
end;
function TThCustomAnchor.Empty: Boolean;
begin
Result := (Href = '') and (FTarget = '');
end;
procedure TThCustomAnchor.Tag(inTag: TThTag);
begin
inTag.Add('href', Href);
inTag.Add('target', Target);
end;
function TThCustomAnchor.Wrap(const inContent: string): string;
begin
if Empty then
Result := inContent
else
with TThTag.Create('a') do
try
if Self.Styles.HasStyles and (Name <> '') then
Add('class', Name);
Content := inContent;
Tag(ThisTag);
Result := HTML;
finally
Free;
end;
end;
procedure TThCustomAnchor.SetHref(const Value: string);
begin
FHref := Value;
Change;
end;
procedure TThCustomAnchor.SetTarget(const Value: string);
begin
FTarget := Value;
Change;
end;
procedure TThCustomAnchor.SetStyles(const Value: TThAnchorStyles);
begin
FStyles.Assign(Value);
end;
procedure TThCustomAnchor.SetName(const Value: string);
begin
FName := Value;
end;
end.
|
(*
* DGL(The Delphi Generic Library)
*
* Copyright (c) 2004
* HouSisong@gmail.com
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*)
//------------------------------------------------------------------------------
// 具现化的TNotifyEvent类型的声明
// Create by HouSisong, 2004.11.30
//------------------------------------------------------------------------------
unit DGL_TNotifyEvent;
interface
uses
SysUtils, Classes;
{$I DGLCfg.inc_h}
const
_NULL_Value:TNotifyEvent=nil;
type
_ValueType = TNotifyEvent;
{$define _DGL_ClassFunction_Specific} //特殊处理
function _HashValue(const Key: _ValueType):Cardinal;{$ifdef _DGL_Inline} inline; {$endif}//Hash函数
{$define _DGL_Compare} //比较函数
function _IsEqual(const a,b :_ValueType):boolean; {$ifdef _DGL_Inline} inline; {$endif}//result:=(a=b);
function _IsLess(const a,b :_ValueType):boolean; {$ifdef _DGL_Inline} inline; {$endif} //result:=(a<b); 默认排序准则
{$I DGL.inc_h}
type
TEventAlgorithms = _TAlgorithms;
IEventIterator = _IIterator;
IEventContainer = _IContainer;
IEventSerialContainer = _ISerialContainer;
IEventVector = _IVector;
IEventList = _IList;
IEventDeque = _IDeque;
IEventStack = _IStack;
IEventQueue = _IQueue;
IEventPriorityQueue = _IPriorityQueue;
IEventSet = _ISet;
IEventMultiSet = _IMultiSet;
TEventVector = _TVector;
TEventDeque = _TDeque;
TEventList = _TList;
IEventVectorIterator = _IVectorIterator; //速度比_IIterator稍快一点:)
IEventDequeIterator = _IDequeIterator; //速度比_IIterator稍快一点:)
IEventListIterator = _IListIterator; //速度比_IIterator稍快一点:)
TEventStack = _TStack;
TEventQueue = _TQueue;
TEventPriorityQueue = _TPriorityQueue;
//
IEventMapIterator = _IMapIterator;
IEventMap = _IMap;
IEventMultiMap = _IMultiMap;
TEventSet = _TSet;
TEventMultiSet = _TMultiSet;
TEventMap = _TMap;
TEventMultiMap = _TMultiMap;
TEventHashSet = _THashSet;
TEventHashMultiSet = _THashMultiSet;
TEventHashMap = _THashMap;
TEventHashMultiMap = _THashMultiMap;
implementation
uses
HashFunctions;
{$I DGL.inc_pas}
function _HashValue(const Key :_ValueType):Cardinal; overload;
begin
result:=HashValue_Int64(PInt64(@@Key)^);
end;
function _IsEqual(const a,b :_ValueType):boolean; //result:=(a=b);
begin
result:=(PInt64(@@a)^)=PInt64(@@b)^;
end;
function _IsLess(const a,b :_ValueType):boolean; //result:=(a<b); 默认排序准则
begin
result:=(PInt64(@@a)^)<PInt64(@@b)^;
end;
initialization
Assert(sizeof(int64)=sizeof(_ValueType));
end.
|
(*
Category: SWAG Title: MENU MANAGEMENT ROUTINES
Original name: 0009.PAS
Description: Pickable Litebar Menu
Author: GORDY FRENCH
Date: 05-31-96 09:16
*)
{
>Here's some neat lightbars that I made. REALLY easy to use, pretty
>simple.
>Feel free to use it, like I care.. Just don't yell at me fer what it
>does. }
Program lite;
Uses crt;
Type
literec = Record {Litebar config rec}
choices: Integer;
menu: Array [1..25] Of String;
othercolor, barcolor: Integer;
End;
Function litebar (lite: literec): Integer;
(*
Procedure HideCursor; Assembler;
Asm
MOV AX, $0100 {Hides cursor}
MOV CX, $2607
Int $10
End;
Procedure ShowCursor; Assembler;
Asm
MOV AX, $0100
MOV CX, $0506 {Unhides cursor}
Int $10
End;
*)
Label ack, stop;
Var
on: Integer;
X, Y: Integer;
key: Char; {Various vars}
okey: Byte;
lastone: Integer;
litesize: Integer;
Begin
{hidecursor;}
X := WhereX; {Record starting positions}
Y := WhereY;
TextColor (lite. othercolor); {Change color}
TextBackground (0); {Change background}
litesize := 0;
For on := 1 To lite. choices Do Begin {This for loop writes the options.}
GotoXY (X, Y + on - 1);
WriteLn (lite. menu [on] );
If Length (lite. menu [on] ) > litesize Then litesize := Length
(lite. menu [on] );
End;
For on := 1 To lite. choices Do Begin {This for loop makes the >lightbar}
If Length (lite. menu [on] ) < litesize Then Begin {the same >length}
Repeat
lite. menu [on] := lite. menu [on] + ' ';
Until Length (lite. menu [on] ) >= litesize;
End;
End;
on := 1;
lastone := 999;
Repeat {Main loop}
If lastone <> 999 Then Begin {redraw last option (reset background}
GotoXY (X, Y + lastone - 1);
TextBackground (0);
WriteLn (lite. menu [lastone] );
End;
GotoXY (X, Y + on - 1); {go to option}
TextBackground (lite. barcolor); {change color}
WriteLn (lite. menu [on] ); {rewrite current option (background)}
ack: Repeat key := ReadKey Until key In [#13, #0]; {get a key}
If key = #0 Then Begin {was it extended? process it.}
okey := Ord (ReadKey);
If (okey = 72) Then Begin {up}
If on = 1 Then Begin lastone := on; on := lite. choices End
Else If on <> 1 Then Begin lastone := on; Dec (on); End;
End
Else If (okey = 80) Then Begin {down}
If on = lite. choices Then Begin lastone := on; on := 1 End
Else If (on < lite. choices) Then Begin lastone := on;
Inc (on);
End;
End Else Goto ack;
Continue;
End Else
If key = #13 Then Goto stop Else {enter}
If key = ' ' Then If on = lite. choices Then on := 1 Else If
on < lite. choices Then Dec (on) Else
Goto ack;
Until 5 < 4; {loop.}
stop: {end it}
litebar := on; {tell us what they picked}
{ShowCursor;} {turn cursor back on}
End;
Var picked: Integer;
litecfg: literec;
Begin
TextBackground (0); {Reset backround}
ClrScr;
GotoXY (4, 4); {where is menu going to be?}
litecfg. choices := 4; {set choices}
litecfg. menu [1] := 'Player Editor'; {--\ }
litecfg. menu [2] := 'Software Editor'; { |____set choices}
litecfg. menu [3] := 'CPU Editor'; { | }
litecfg. menu [4] := 'Quit'; {--/ }
litecfg. othercolor := 3; {Set foreground color}
litecfg. barcolor := 1; {Set background color}
picked := litebar (litecfg); {Run the lightbars!}
TextBackground (0); {change background back (req'd)}
ClrScr; {clear it}
WriteLn ('You picked number ', picked, ', which is ', litecfg. menu[picked], '.');
{/\ Tell them what they did /\}
End.
|
unit Magento.Entidade.Produto;
interface
uses
Magento.Interfaces, System.JSON, System.SysUtils,
System.Generics.Collections;
type
TMagentoEntidadeProduto = class (TInterfacedObject, iMagentoEntidadeProduto)
private
FJSON : TJSONObject;
FJSONProduct : TJSONObject;
FJSONArray : TJSONArray;
FSku : String;
FName : String;
FAttribute_set_id : String;
FPrice : Real;
FStatus : Integer;
FVisibility : Integer;
FType_id : TTipoProduto;
FWeight : String;
public
constructor Create;
destructor Destroy; override;
class function New : iMagentoEntidadeProduto;
function NewProduto : iMagentoEntidadeProduto;
function Sku(value : String) : iMagentoEntidadeProduto;
function Name(value : String) : iMagentoEntidadeProduto;
function Attribute_set_id(value : Integer) : iMagentoEntidadeProduto;
function Price(value : Real) : iMagentoEntidadeProduto;
function Status(value : Boolean) : iMagentoEntidadeProduto;
function Visibility(value : Boolean) : iMagentoEntidadeProduto;
function Type_id(value : TTipoProduto) : iMagentoEntidadeProduto;
function Weight(value : String) : iMagentoEntidadeProduto;
function Extension_attributes : iMagentoExtensionAttributes; overload;
function Extension_attributes(value : TJSONObject) : iMagentoEntidadeProduto; overload;
function Custom_attributes : iMagnetoCustom_attributes; overload;
function Custom_attributes(value : TJSONArray) : iMagentoEntidadeProduto; overload;
function Custom_attributes(value : TDictionary<String,String>) : iMagentoEntidadeProduto; overload;
function MediaGalleryEntries : iMagentoMediaGalleryEntries; overload;
function MediaGalleryEntries(value : TJSONArray) : iMagentoEntidadeProduto; overload;
function &End : TJSONObject;
end;
implementation
{ TMagentoEntidadeProduto }
uses Magento.Factory;
function TMagentoEntidadeProduto.Attribute_set_id(
value: Integer): iMagentoEntidadeProduto;
begin
Result := Self;
FJSON.AddPair('attribute_set_id',TJSONNumber.Create(value));
end;
function TMagentoEntidadeProduto.&End: TJSONObject;
begin
Result := TJSONObject.Create.AddPair('product', FJSON);
end;
function TMagentoEntidadeProduto.Extension_attributes(
value: TJSONObject): iMagentoEntidadeProduto;
begin
Result := Self;
FJSON.AddPair('extension_attributes', value);
end;
function TMagentoEntidadeProduto.MediaGalleryEntries(
value: TJSONArray): iMagentoEntidadeProduto;
begin
Result := Self;
FJSON.AddPair('mediaGalleryEntries', value);
end;
function TMagentoEntidadeProduto.MediaGalleryEntries: iMagentoMediaGalleryEntries;
begin
Result := TMagentoFactory.New.MediaGalleryEntries(Self);
end;
constructor TMagentoEntidadeProduto.Create;
begin
FJSON := TJSONObject.Create;
end;
function TMagentoEntidadeProduto.Custom_attributes(
value: TDictionary<String, String>): iMagentoEntidadeProduto;
var
Key : String;
lJSONArray : TJSONArray;
lJSON : TJSONObject;
begin
Result := Self;
lJSONArray := TJSONArray.Create;
for Key in Value.Keys do
begin
lJSON := TJSONObject.Create;
lJSON.AddPair('attribute_code',key);
lJSON.AddPair('value',Value.Items[key]);
lJSONArray.Add(lJSON);
end;
FJSON.AddPair('custom_attributes',lJSONArray);
end;
function TMagentoEntidadeProduto.Custom_attributes: iMagnetoCustom_attributes;
begin
Result := TMagentoFactory.New.Custom_attributes(self);
end;
function TMagentoEntidadeProduto.Custom_attributes(
value: TJSONArray): iMagentoEntidadeProduto;
begin
Result := Self;
FJSON.AddPair('custom_attributes', value);
end;
destructor TMagentoEntidadeProduto.Destroy;
begin
FJSON.DisposeOf;
inherited;
end;
function TMagentoEntidadeProduto.Extension_attributes: iMagentoExtensionAttributes;
begin
Result := TMagentoFactory.New.ExtensionAttributes(Self);
end;
function TMagentoEntidadeProduto.NewProduto: iMagentoEntidadeProduto;
begin
Result := Self;
end;
class function TMagentoEntidadeProduto.New: iMagentoEntidadeProduto;
begin
Result := self.Create;
end;
function TMagentoEntidadeProduto.Name(value: String): iMagentoEntidadeProduto;
begin
Result := Self;
FJSON.AddPair('name',value);
end;
function TMagentoEntidadeProduto.Price(value: Real): iMagentoEntidadeProduto;
begin
Result := Self;
FJSON.AddPair('price',TJSONNumber.Create(value));
end;
function TMagentoEntidadeProduto.Sku(value: String): iMagentoEntidadeProduto;
begin
Result := Self;
FJSON.AddPair('sku',value);
end;
function TMagentoEntidadeProduto.Status(value : Boolean) : iMagentoEntidadeProduto;
begin
Result := Self;
if Value then
FJSON.AddPair('status', TJSONNumber.Create(1));
end;
function TMagentoEntidadeProduto.Type_id(
value: TTipoProduto): iMagentoEntidadeProduto;
var
lTipo : String;
begin
Result := Self;
lTipo := LowerCase(TTipoProduto(value).ToString);
FJSON.AddPair('type_id',Copy(lTipo,3,Length(lTipo)));
end;
function TMagentoEntidadeProduto.Visibility(value : Boolean) : iMagentoEntidadeProduto;
begin
Result := Self;
if Value then
FJSON.AddPair('visibility', TJSONNumber.Create(4));
end;
function TMagentoEntidadeProduto.Weight(value: String): iMagentoEntidadeProduto;
begin
Result := Self;
FJSON.AddPair('weight', value);
end;
end.
|
unit ProfileManager;
interface
uses
SysUtils,
kCritSct,
StringSupport,
AdvObjects, AdvStringMatches, AdvStringObjectMatches, AdvGenerics,
FHIRResources, FHIRUtilities, FHIRConstants, FHIRTypes;
Type
TProfileManager = class (TAdvObject)
private
lock : TCriticalSection;
FProfilesById : TAdvMap<TFHIRStructureDefinition>; // all current profiles by identifier (ValueSet.identifier)
FProfilesByURL : TAdvMap<TFHIRStructureDefinition>; // all current profiles by their URL
// FExtensions : TAdvStringObjectMatch;
function GetProfileByUrl(url: String): TFHirStructureDefinition;
function GetProfileByType(aType: TFhirResourceType): TFHirStructureDefinition; // all profiles by the key they are known from (mainly to support drop)
public
constructor Create; override;
destructor Destroy; override;
function Link : TProfileManager; overload;
procedure SeeProfile(key : Integer; profile : TFHirStructureDefinition);
procedure DropProfile(aType: TFhirResourceType; id : String);
procedure loadFromFeed(feed : TFHIRBundle);
function getExtensionDefn(source : TFHirStructureDefinition; url : String; var profile : TFHirStructureDefinition; var extension : TFHirStructureDefinition) : boolean;
function getProfileStructure(source : TFHirStructureDefinition; url : String; var profile : TFHirStructureDefinition) : boolean;
function getLinks(non_resources : boolean) : TAdvStringMatch;
property ProfileByURL[url : String] : TFHirStructureDefinition read GetProfileByUrl; default;
property ProfileByType[aType : TFhirResourceType] : TFHirStructureDefinition read GetProfileByType;
end;
{
This encapsulates a reference to an element definition within a structure.
The path may be replace
}
TProfileDefinition = class (TAdvObject)
private
FProfiles : TProfileManager;
FProfile : TFHirStructureDefinition;
FElement : TFhirElementDefinition;
statedPath : String;
FType : TFhirElementDefinitionType;
function GetTypes: TFhirElementDefinitionTypeList;
function GetPath: String;
function GetName: String;
Property Types : TFhirElementDefinitionTypeList read GetTypes;
public
Constructor Create(profiles : TProfileManager; profile : TFHirStructureDefinition); overload;
Destructor Destroy; override;
procedure setType(t : TFhirElementDefinitionType);
function statedType : TFhirElementDefinitionType;
function hasTypeChoice : boolean;
Property path : String read GetPath;
Property name : String read GetName;
function getById(id : String) : TProfileDefinition;
end;
implementation
{ TProfileManager }
constructor TProfileManager.Create;
begin
inherited;
lock := TCriticalSection.Create('profiles');
FProfilesById := TAdvMap<TFhirStructureDefinition>.create;
FProfilesByURL := TAdvMap<TFhirStructureDefinition>.create;
end;
destructor TProfileManager.Destroy;
begin
FProfilesById.free;
FProfilesByURL.free;
lock.Free;
inherited;
end;
function TProfileManager.getExtensionDefn(source: TFHirStructureDefinition; url: String; var profile: TFHirStructureDefinition; var extension : TFHirStructureDefinition): boolean;
//var
// id, code : String;
// i : integer;
begin
raise Exception.Create('not done yet');
{ result := false;
if url.StartsWith('#') then
begin
profile := source;
code := url.Substring(1);
end
else
begin
StringSplit(url, '#', id, code);
lock.Lock;
try
profile := FProfilesByIdentifier.Matches[id] as TFHirStructureDefinition;
finally
lock.Unlock;
end;
end;
if (profile <> nil) then
begin
extension := nil;
for i := 0 to profile.extensionDefnList.Count - 1 do
if profile.extensionDefnList[i].code = url.Substring(1) then
extension := profile.extensionDefnList[i];
result := extension <> nil;
end;}
end;
function TProfileManager.getLinks(non_resources : boolean): TAdvStringMatch;
var
p : TFHirStructureDefinition;
url : String;
begin
lock.Lock('getLinks');
try
result := TAdvStringMatch.Create;
try
for url in FProfilesByURL.Keys do
begin
if (not url.startsWith('http:')) then
begin
p := FProfilesByURL[url];
if non_resources or StringArrayExistsSensitive(CODES_TFhirResourceType, p.snapshot.elementList[0].path) then
result.Add(url, p.name);
end;
end;
result.Link;
finally
result.Free;
end;
finally
lock.Unlock;
end;
end;
function TProfileManager.GetProfileByType(aType: TFhirResourceType): TFHirStructureDefinition;
begin
result := GetProfileByUrl('http://hl7.org/fhir/Profile/'+CODES_TFHIRResourceType[aType]);
end;
function TProfileManager.GetProfileByUrl(url: String): TFHirStructureDefinition;
begin
if FProfilesByURL.ContainsKey(url) then
result := FProfilesByURL[url].Link
else
result := nil;
end;
function TProfileManager.getProfileStructure(source: TFHirStructureDefinition; url: String; var profile: TFHirStructureDefinition): boolean;
var
id, code : String;
begin
result := false;
if url.StartsWith('#') then
begin
profile := source;
code := url.Substring(1);
end
else
begin
StringSplit(url, '#', id, code);
lock.Lock;
try
profile := FProfilesByURL[id].Link;
finally
lock.Unlock;
end;
end;
if profile = nil then
result := false
else
begin
result := true;
end;
if (code <> '') then
raise Exception.Create('Not Done Yet');
end;
function TProfileManager.Link: TProfileManager;
begin
result := TProfileManager(inherited Link);
end;
procedure TProfileManager.loadFromFeed(feed: TFHIRBundle);
var
i : integer;
begin
for i := 0 to feed.entryList.Count - 1 do
begin
if feed.entryList[i].resource is TFHirStructureDefinition then
SeeProfile(i, feed.entryList[i].resource as TFHirStructureDefinition);
end;
end;
procedure TProfileManager.SeeProfile(key: Integer; profile: TFHirStructureDefinition);
begin
lock.Lock('SeeProfile');
try
FProfilesById.AddOrSetValue(profile.id, profile.Link);
FProfilesByURL.AddOrSetValue(profile.url, profile.Link);
finally
lock.Unlock;
end;
end;
procedure TProfileManager.DropProfile(aType: TFhirResourceType; id : String);
var
p : TFHirStructureDefinition;
begin
lock.Lock('DropProfile');
try
if FProfilesById.ContainsKey(id) then
begin
p := FProfilesById[id];
FProfilesByURL.Remove(p.url);
FProfilesById.Remove(id);
end;
finally
lock.Unlock;
end;
end;
{ TProfileDefinition }
constructor TProfileDefinition.Create(profiles: TProfileManager; profile: TFHirStructureDefinition);
begin
Create;
FProfiles := profiles;
FProfile := profile;
FElement := profile.snapshot.elementList[0].link;
end;
destructor TProfileDefinition.Destroy;
begin
FType.free;
FProfiles.Free;
FProfile.Free;
FElement.Free;
inherited;
end;
function TProfileDefinition.getById(id: String): TProfileDefinition;
var
path : String;
i : integer;
profile : TFHirStructureDefinition;
elements : TFhirElementDefinitionList;
begin
// if FActualPath = '' then
// path := id
// else if not id.StartsWith(FStatedPath) then
// raise Exception.Create('Bad Path "'+id+'"')
// else
// path := FActualPath+ id.Substring(FStatedPath.Length);
if id.endsWith('/1') then
id := id.subString(0, id.length-2);
if (Types.Count = 0) or (Types[0].code = 'Resource') then
begin
path := id;
profile := FProfile;
end
else if Types.Count = 1 then
begin
profile := FProfiles['http://hl7.org/fhir/Profile/'+Types[0].code];
if (profile = nil) then
raise Exception.Create('Unable to find profile for '+Types[0].code+' @ '+id);
path := Types[0].code+id.Substring(statedPath.Length);
end
else if FType <> nil then
begin
profile := FProfiles['http://hl7.org/fhir/Profile/'+FType.code];
if (profile = nil) then
raise Exception.Create('Unable to find profile for '+FType.code+' @ '+id);
if not id.startsWith(statedPath+'._'+FType.tags['type']) then
raise Exception.Create('Internal logic error');
path := Types[0].code+id.Substring(statedPath.Length+2+FType.tags['type'].length);
end
else
raise Exception.Create('not handled - multiple types');
elements := profile.snapshot.elementList;
result := nil;
for i := 0 to elements.Count - 1 do
if elements[i].path = path then
begin
result := TProfileDefinition.Create(FProfiles.Link, profile.Link);
try
result.FElement := elements[i].Link;
result.statedPath := id;
result.link;
finally
result.free;
end;
break;
end;
if result = nil then
raise Exception.Create('Unable to resolve path "'+id+'"');
end;
function TProfileDefinition.GetName: String;
begin
result := path.substring(path.lastIndexOf('.')+1);
end;
function TProfileDefinition.GetPath: String;
begin
result := FElement.path;
end;
function TProfileDefinition.GetTypes: TFhirElementDefinitionTypeList;
begin
result := FElement.type_List;
end;
function TProfileDefinition.hasTypeChoice: boolean;
begin
result := Types.Count > 1;
end;
procedure TProfileDefinition.setType(t: TFhirElementDefinitionType);
begin
FType.Free;
FType := t;
end;
function TProfileDefinition.statedType: TFhirElementDefinitionType;
begin
if Types.Count = 0 then
result := nil
else if Types.Count = 1 then
result := Types[0]
else
raise Exception.Create('Shouldn''t get here');
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit MV.CameraLookAt;
interface
uses
MV.Utils, FMX.Types, FMX.Types3D, System.Types;
type
TCameraLookAt = class
private
FRotation:TPointf;
FDistance: Single;
FTarget: TVector3D;
FEye: TVector3D;
procedure SetRotation(const ARotation:TPointf);
procedure SetDistance(const ADistance:Single);
public
constructor Create();
function GetCameraMatrix(const AContext :TContext3D): TMatrix3D;
function GetLoacalVector(const AMove: TVector3D):TVector3D;
property Eye: TVector3D read FEye;
property Rotation: TPointf read FRotation write SetRotation;
property Distance: Single read FDistance write SetDistance;
property Target: TVector3D read FTarget write FTarget;
procedure Zoom(const ADelta: Single);
procedure Rotate(const Ax, Ay: Single);
procedure Move(const ADir: TVector3D);
end;
implementation
procedure TCameraLookAt.Rotate(const Ax, Ay: Single);
begin
Rotation := PointF( Rotation.X + Ax, Rotation.Y + Ay);
end;
procedure TCameraLookAt.Move(const ADir: TVector3D);
begin
Target := Vector3dAdd(Target, GetLoacalVector(ADir));
end;
procedure TCameraLookAt.Zoom(const ADelta: Single);
begin
Distance := Distance + ADelta;
end;
function TCameraLookAt.GetLoacalVector(const AMove: TVector3D):TVector3D;
var
LDir, LUp, LSide: TVector3D;
begin
LUp := Vector3D(0,0,1);
LDir := Vector3DNormalize(SphericalToRect(FRotation, FDistance));
LSide := Vector3DNormalize(Vector3DCrossProduct(LUp, LDir));
LUp := Vector3DCrossProduct(LDir, LSide);
result := Vector3DScale(LSide,AMove.x );
result := Vector3DAdd(result, Vector3DScale(LUp , -AMove.y ));
result := Vector3DAdd(result, Vector3DScale(LDir ,AMove.z ));
end;
procedure TCameraLookAt.SetRotation(const ARotation:TPointf);
begin
FRotation:= ARotation;
if FRotation.Y > 140 then
FRotation.Y := 140;
if FRotation.Y < 1 then
FRotation.Y := 1;
end;
procedure TCameraLookAt.SetDistance(const ADistance:Single);
begin
FDistance := ADistance;
if FDistance < 1 then
FDistance := 1
else if FDistance > 250 then
FDistance := 250;
end;
constructor TCameraLookAt.Create();
begin
FRotation.X := 45;
FRotation.Y := 70;
FDistance := 80;
FTarget := Vector3D(0, 0, 15);
end;
function TCameraLookAt.GetCameraMatrix(const AContext :TContext3D): TMatrix3D;
var
LTransform: Tmatrix3D;
m: TMatrix3D;
begin
FEye := Vector3DAdd(FTarget, SphericalToRect(FRotation, FDistance));
LTransform := MatrixLookAtRH(FEye, FTarget, Vector3D(0, 0, 1));
result := Matrix3DMultiply(LTransform, AContext.CurrentPojectionMatrix);
end;
end.
|
unit ModelUndoEngine;
interface
uses Model, BasicDataTypes, BasicFunctions;
type
TModelUndoRedo = class
private
FMaxStackSize: cardinal;
FIsStackLimited: boolean;
FModels: array of array of TModel;
FLabels: array of array of string;
FIDs: array of integer;
// Constructors and Destructors;
procedure Clear;
// Gets
function GetSize(_ModelID: integer): integer;
function GetLabel(_ModelID, _LabelID: integer): string;
function GetPosition(var _ModelID: integer): boolean;
public
// Constructors and Destructors;
constructor Create;
destructor Destroy; override;
// Add and remove
procedure Add(var _Model: TModel; const _Label: string);
procedure Remove(_ModelID: integer);
function Restore(_ModelID, _NumMoves: integer): TModel;
// Properties
property MaxStackSize: cardinal read FMaxStackSize;
property Size[_ModelID: integer]: integer read GetSize;
property Labels[_ModelID, _LabelID: integer]: string read GetLabel;
end;
implementation
// Constructors and Destructors
constructor TModelUndoRedo.Create;
begin
SetLength(FModels, 0);
SetLength(FLabels, 0);
SetLength(FIDs, 0);
FIsStackLimited := false;
FMaxStackSize := 10;
end;
destructor TModelUndoRedo.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TModelUndoRedo.Clear;
var
i,j: integer;
begin
i := 0;
while i <= High(FModels) do
begin
j := Low(FModels[i]);
while j <= High(FModels[i]) do
begin
FModels[i, j].Free;
FLabels[i, j] := '';
end;
SetLength(FModels[i], 0);
SetLength(FLabels[i], 0);
inc(i);
end;
SetLength(FModels, 0);
SetLength(FLabels, 0);
SetLength(FIDs, 0);
end;
// Add and remove.
procedure TModelUndoRedo.Add(var _Model: TModel; const _Label: string);
var
i, j: integer;
begin
// locate i first.
i := _Model.ID;
if not GetPosition(i) then
begin
SetLength(FIDs, High(FIDs) + 2);
i := High(FIDs);
FIDs[High(FIDs)] := _Model.ID;
SetLength(FModels, High(FModels) + 2);
SetLength(FLabels, High(FLabels) + 2);
SetLength(FModels[i], 0);
SetLength(FLabels[i], 0);
end;
// Now we check for potential restrictions and alocate memory for it, if needed.
if FIsStackLimited then
begin
if High(FModels[i]) >= FMaxStackSize then
begin
// remove first element.
FModels[i, 0].Free;
j := 0;
while j < High(FModels[i]) do
begin
FModels[i, j] := FModels[i, j+1];
FLabels[i, j] := CopyString(FLabels[i, j+1]);
inc(j);
end;
end
else
begin
SetLength(FModels[i], High(FModels[i])+2);
SetLength(FLabels[i], High(FModels[i])+1);
end;
end
else
begin
SetLength(FModels[i], High(FModels[i])+2);
SetLength(FLabels[i], High(FModels[i])+1);
end;
// Now we add the model.
FModels[i, High(FModels[i])] := TModel.Create(_Model);
FModels[i, High(FModels[i])].ID := _Model.ID;
FLabels[i, High(FLabels[i])] := CopyString(_Label);
end;
procedure TModelUndoRedo.Remove(_ModelID: integer);
var
j: integer;
Position: integer;
begin
Position := _ModelID;
if GetPosition(Position) then
begin
// clear memory
j := Low(FModels[Position]);
while j <= High(FModels[Position]) do
begin
FModels[Position, j].Free;
FLabels[Position, j] := '';
inc(j);
end;
SetLength(FModels[Position], 0);
SetLength(FLabels[Position], 0);
// swap the other models
j := Position;
while j < High(FModels) do
begin
FIDs[j] := FIDs[j + 1];
FModels[j] := FModels[j + 1];
FLabels[j] := FLabels[j + 1];
inc(j);
end;
// remove last element.
SetLength(FModels, High(FModels));
SetLength(FLabels, High(FLabels));
SetLength(FIDs, High(FIDs));
end;
end;
function TModelUndoRedo.Restore(_ModelID, _NumMoves: Integer): TModel;
var
i: integer;
Position: integer;
begin
Position := _ModelID;
Result := nil;
if GetPosition(Position) then
begin
if _NumMoves > (High(FModels[Position])+1) then
begin
Result := nil;
Clear;
end
else
begin
i := 0;
while i < _NumMoves do
begin
FModels[Position, High(FModels)-i].Free;
inc(i);
end;
Result := FModels[Position, High(FModels[Position])-i];
SetLength(FModels[Position], High(FModels[Position])-i);
end;
end;
end;
// Gets
function TModelUndoRedo.GetSize(_ModelID: integer): integer;
var
Position: integer;
begin
Position := _ModelID;
if GetPosition(Position) then
begin
Result := High(FModels[Position])+1;
end
else
begin
Result := 0;
end;
end;
function TModelUndoRedo.GetLabel(_ModelID, _LabelID: integer): string;
var
Position: integer;
begin
Position := _ModelID;
if GetPosition(Position) then
begin
if (_LabelID >= 0) and (_LabelID <= High(FLabels[Position])) then
begin
Result := FLabels[Position, _LabelID];
end
else
begin
Result := '';
end;
end
else
begin
Result := '';
end;
end;
function TModelUndoRedo.GetPosition(var _ModelID: integer): boolean;
var
i: integer;
begin
// locate i first.
i := 0;
Result := false;
while (i <= High(FIDs)) and (not Result) do
begin
if FIDs[i] = _ModelID then
begin
_ModelID := i;
Result := true;
end
else
begin
inc(i);
end;
end;
end;
end.
|
// RemObjects CS to Pascal 0.1
namespace UT3Bots.Communications;
interface
uses
System,
System.IO,
System.Net.Sockets,
System.Text,
System.Diagnostics;
type
UT3Connection = public class
private
var _tcpClient: TcpClient;
var _streamReader: StreamReader;
var _streamWriter: StreamWriter;
var _networkStream: NetworkStream;
var _server: String;
var _port: Integer;
assembly
method Connect(): Boolean;
private
//throw;
method Listen();
assembly
method HandleRead(ar: IAsyncResult);
method OnData(args: TcpDataEventArgs);
method OnError(args: TcpErrorEventArgs);
assembly
method Disconnect();
method ReadLine(): String;
method SendLine(Message: String);
constructor(server: String; port: Integer);
property IsConnected: Boolean read get_IsConnected;
method get_IsConnected: Boolean;
event OnDataReceived: EventHandler<TcpDataEventArgs>;
event OnErrorOccurred: EventHandler<TcpErrorEventArgs>;
end;
SocketState = class
assembly or protected
var data: array of Byte := new Byte[300];
var stream: NetworkStream;
end;
TcpDataEventArgs = public class(EventArgs)
private
var _data: array of Byte;
assembly or protected
constructor(Data: array of Byte);
property Data: array of Byte read get_Data;
method get_Data: array of Byte;
end;
TcpErrorEventArgs = public class(EventArgs)
private
var _error: Exception;
assembly or protected
constructor (Error: Exception);
property Error: Exception read get_Error;
method get_Error: Exception;
end;
implementation
method UT3Connection.Connect(): Boolean;
begin
if IsConnected then
begin
Trace.WriteLine('Already Connected - Disconnect First', &Global.TRACE_ERROR_CATEGORY);
exit false
end;
try
Self._tcpClient := new TcpClient(Self._server, Self._port);
_networkStream := Self._tcpClient.GetStream();
Self._streamReader := new StreamReader(new StreamReader(_networkStream).BaseStream, System.Text.Encoding.ASCII);
Self._streamWriter := new StreamWriter(new StreamWriter(_networkStream).BaseStream, System.Text.Encoding.ASCII);
Listen();
except
on ex: Exception do
begin
Trace.WriteLine(String.Format('The Connection Could Not Be Established: {0}.', ex.Message), &Global.TRACE_ERROR_CATEGORY);
if (Self._streamReader <> nil) then
begin
Self._streamReader.Close()
end;
if (Self._streamWriter <> nil) then
begin
Self._streamWriter.Close()
end;
end;
end;
exit ((Self._streamReader <> nil) and (Self._streamWriter <> nil));
end;
method UT3Connection.Listen();
begin
var state: SocketState := new SocketState();
state.stream := _networkStream;
var ar: IAsyncResult := _networkStream.BeginRead(state.data, 0, state.data.Length, @HandleRead, state)
end;
method UT3Connection.HandleRead(ar: IAsyncResult);
begin
var state: SocketState := SocketState(ar.AsyncState);
var stream: NetworkStream := state.stream;
var r: Integer;
if not stream.CanRead then
begin
exit
end
else
begin
end;
try
r := stream.EndRead(ar)
except
on ex: Exception do
begin
OnError(new TcpErrorEventArgs(ex));
Trace.WriteLine(String.Format('TCP Connection Error: {0}.', ex.Message), &Global.TRACE_NORMAL_CATEGORY);
Disconnect();
exit
end
end;
var rdata: array of Byte := new Byte[r];
Buffer.BlockCopy(state.data, 0, rdata, 0, r);
OnData(new TcpDataEventArgs(rdata));
try
Listen();
except
on ex: Exception do
begin
OnError(new TcpErrorEventArgs(ex))
end
end
end;
method UT3Connection.OnData(args: TcpDataEventArgs);
begin
var temp: EventHandler<TcpDataEventArgs> := OnDataReceived;
if (temp <> nil) then
begin
temp(Self, args)
end;
end;
method UT3Connection.OnError(args: TcpErrorEventArgs);
begin
var temp: EventHandler<TcpErrorEventArgs> := OnErrorOccurred;
if temp <> nil then
begin
temp(Self, args)
end;
end;
method UT3Connection.Disconnect();
begin
if Self._tcpClient.Client.Connected then
begin
Self._tcpClient.Client.Disconnect(false);
Self._tcpClient.Client.Close();
Self._tcpClient.Close()
end;
Self._streamReader.Close()
end;
method UT3Connection.ReadLine(): String;
begin
if Self._streamReader <> nil then
begin
var line: String := Self._streamReader.ReadLine();
Trace.WriteLine(String.Format('Received Server Line: {0}.', line), &Global.TRACE_NORMAL_CATEGORY);
exit line
end
else
begin
Trace.WriteLine('Error reading from connection!', &Global.TRACE_ERROR_CATEGORY);
exit ''
end
end;
method UT3Connection.SendLine(Message: String);
begin
if Self._streamWriter <> nil then
begin
Trace.WriteLine(String.Format('Sending Server Line: {0}.', Message), &Global.TRACE_NORMAL_CATEGORY);
Self._streamWriter.WriteLine(Message);
Self._streamWriter.Flush()
end
else
begin
Trace.WriteLine('Error writing to connection!', &Global.TRACE_ERROR_CATEGORY)
end;
end;
constructor UT3Connection(server: String; port: Integer);
begin
Self._server := server;
Self._port := port;
Connect();
end;
method UT3Connection.get_IsConnected: Boolean;
begin
Result := ((Self._tcpClient <> nil) and (Self._tcpClient.Connected));
end;
constructor TcpDataEventArgs(Data: array of Byte);
begin
Self._data := Data;
end;
method TcpDataEventArgs.get_Data: array of Byte;
begin
Result := Self._data;
end;
constructor TcpErrorEventArgs(Error: Exception);
begin
Self._error := Error
end;
method TcpErrorEventArgs.get_Error: Exception;
begin
Result := Self._error
end;
end.
|
unit ItemShopTableForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, StdCtrls, Menus,
CountedDynArrayString,
InflatablesList_ItemShop,
InflatablesList_Item,
InflatablesList_Manager;
const
IL_ITEMSHOPTABLE_ITEMCELL_WIDTH = 300;
IL_ITEMSHOPTABLE_ITEMCELL_HEIGHT = 35;
type
TILItemShopTableRow = record
Item: TILItem;
Shops: array of TILItemShop;
end;
TILItemShopTable = array of TILItemShopTableRow;
TfItemShopTableForm = class(TForm)
dgTable: TDrawGrid;
lblNoTable: TLabel;
cbCompactView: TCheckBox;
lblSelectedInfo: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure dgTableDblClick(Sender: TObject);
procedure dgTableSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure dgTableDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure dgTableMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure cbCompactViewClick(Sender: TObject);
private
{ Private declarations }
fDrawBuffer: TBitmap;
fILManager: TILManager;
fKnownShops: TCountedDynArrayString;
fTable: TILItemShopTable;
fTracking: Boolean;
fTrackPoint: TPoint;
protected
// table building
procedure EnumShops;
procedure BuildTable;
procedure FillTable;
procedure AdjustTable;
// other methods
procedure UpdateInfo(SelCol,SelRow: Integer);
public
{ Public declarations }
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure ShowTable;
end;
var
fItemShopTableForm: TfItemShopTableForm;
implementation
{$R *.dfm}
uses
InflatablesList_Utils,
InflatablesList_LocalStrings;
procedure TfItemShopTableForm.EnumShops;
var
i,j: Integer;
begin
// enumerate shops
CDA_Clear(fKnownShops);
For i := fILManager.ItemLowIndex to fILManager.ItemHighIndex do
If fILManager[i].DataAccessible then
For j := fILManager[i].ShopLowIndex to fILManager[i].ShopHighIndex do
If not CDA_CheckIndex(fKnownShops,CDA_IndexOf(fKnownShops,fILManager[i][j].Name)) then
CDA_Add(fKnownShops,fILManager[i][j].Name);
// sort the shop list
CDA_Sort(fKnownShops);
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.BuildTable;
var
i,j: Integer;
Index: Integer;
begin
SetLength(fTable,fILManager.ItemCount);
For i := fILManager.ItemLowIndex to fILManager.ItemHighIndex do
begin
fTable[i].Item := fILManager.Items[i];
SetLength(fTable[i].Shops,CDA_Count(fKnownShops));
// make sure the shops array contains only nil references
For j := Low(fTable[i].Shops) to High(fTable[i].Shops) do
fTable[i].Shops[j] := nil;
// fill shops by name
If fTable[i].Item.DataAccessible then
For j := fTable[i].Item.ShopLowIndex to fTable[i].Item.ShopHighIndex do
begin
Index := CDA_IndexOf(fKnownShops,fTable[i].Item[j].Name);
If CDA_CheckIndex(fKnownShops,Index) then
fTable[i].Shops[Index] := fTable[i].Item[j];
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.FillTable;
var
TableVisible: Boolean;
i: Integer;
MinHeight: Integer;
TempSize: TSize;
begin
If Length(fTable) > 0 then
TableVisible := Length(fTable[Low(fTable)].Shops) > 0
else
TableVisible := False;
If TableVisible then
begin
dgTable.RowCount := Length(fTable) + 1;
dgTable.ColCount := Length(fTable[0].Shops) + 1;
dgTable.DefaultRowHeight := IL_ITEMSHOPTABLE_ITEMCELL_HEIGHT;
// get minimal height of the first line
MinHeight := 0;
For i := CDA_Low(fKnownShops) to CDA_High(fKnownShops) do
If IL_GetRotatedTextSize(dgTable.Canvas,CDA_GetItem(fKnownShops,i),90,TempSize) then
If MinHeight < TempSize.cy + 20 then
MinHeight := TempSize.cy + 20;
If MinHeight > 50 then
dgTable.RowHeights[0] := MinHeight
else
dgTable.RowHeights[0] := 50;
end;
dgTable.Visible := TableVisible;
lblNoTable.Visible := not TableVisible;
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.AdjustTable;
begin
If cbCompactView.Checked then
dgTable.DefaultColWidth := 25
else
dgTable.DefaultColWidth := 65;
dgTable.ColWidths[0] := IL_ITEMSHOPTABLE_ITEMCELL_WIDTH;
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.UpdateInfo(SelCol,SelRow: Integer);
var
Shop: TILItemShop;
TempStr: String;
begin
If dgTable.Visible and (SelRow > 0) and (SelCol > 0) then
begin
If Assigned(fTable[Pred(SelRow)].Shops[Pred(SelCol)]) then
begin
Shop := fTable[Pred(SelRow)].Shops[Pred(SelCol)];
If Shop.Price > 0 then
begin
If Shop.Available <> 0 then
begin
If Shop.Price <= fTable[Pred(SelRow)].Item.UnitPriceLowest then
TempStr := ' (lowest price)'
else If Shop.Price >= fTable[Pred(SelRow)].Item.UnitPriceHighest then
TempStr := ' (highest price)'
else
TempStr := '';
lblSelectedInfo.Caption := IL_Format('%s %sin %s: %s%d pcs at %d %s%s%s',
[fTable[Pred(SelRow)].Item.TitleStr,IL_BoolToStr(Shop.Selected,'','selected '),
Shop.Name,IL_BoolToStr(Shop.Available < 0,'','more than '),Abs(Shop.Available),Shop.Price,
IL_CURRENCY_SYMBOL,TempStr,IL_BoolToStr(Shop.IsAvailableHere(True),', too few pieces','')]);
end
else lblSelectedInfo.Caption := IL_Format('%s %sin %s: %d %s, not available',
[fTable[Pred(SelRow)].Item.TitleStr,IL_BoolToStr(Shop.Selected,'','selected '),
Shop.Name,Shop.Price,IL_CURRENCY_SYMBOL]);
end
else lblSelectedInfo.Caption := IL_Format('%s is not available in %s',
[fTable[Pred(SelRow)].Item.TitleStr,CDA_GetItem(fKnownShops,Pred(SelCol))]);
end
else lblSelectedInfo.Caption := IL_Format('%s is not available in %s',
[fTable[Pred(SelRow)].Item.TitleStr,CDA_GetItem(fKnownShops,Pred(SelCol))]);
end
else lblSelectedInfo.Caption := '';
end;
//==============================================================================
procedure TfItemShopTableForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
CDA_Init(fKnownShops);
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.Finalize;
begin
// nothing to do here
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.ShowTable;
begin
EnumShops;
BuildTable;
FillTable;
AdjustTable;
UpdateInfo(dgTable.Col,dgTable.Row);
fTracking := False;
ShowModal;
end;
//==============================================================================
procedure TfItemShopTableForm.FormCreate(Sender: TObject);
begin
fDrawBuffer := TBitmap.Create;
fDrawBuffer.PixelFormat := pf24bit;
fDrawBuffer.Canvas.Font.Assign(dgTable.Font);
dgTable.DoubleBuffered := True;
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(fDrawBuffer);
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.dgTableDblClick(Sender: TObject);
var
MousePos: TPoint;
CellCoords: TPoint;
i,TempInt: Integer;
ItemShop: TILItemShop;
Dummy: Boolean;
begin
// get which cell was clicked
MousePos := dgTable.ScreenToClient(Mouse.CursorPos);
CellCoords.X := -1;
CellCoords.Y := -1;
// get column
TempInt := dgTable.ColWidths[0]; // fixed col
For i := dgTable.LeftCol to Pred(dgTable.ColCount) do
If (MousePos.X >= TempInt) and (MousePos.X < TempInt + dgTable.ColWidths[i]) then
begin
CellCoords.X := i;
Break{For i};
end
else Inc(TempInt,dgTable.ColWidths[i]);
// get row
TempInt := dgTable.RowHeights[0]; // fixed row
For i := dgTable.TopRow to Pred(dgTable.RowCount) do
If (MousePos.Y >= TempInt) and (MousePos.Y < TempInt + dgTable.RowHeights[i]) then
begin
CellCoords.Y := i;
Break{For i};
end
else Inc(TempInt,dgTable.RowHeights[i]);
// do the (un)selection
If (CellCoords.X >= 0) and (CellCoords.Y >= 0) then
begin
ItemShop := fTable[Pred(CellCoords.Y)].Shops[Pred(CellCoords.X)];
If Assigned(ItemShop) then
ItemShop.Selected := not ItemShop.Selected;
Dummy := True;
dgTableSelectCell(nil,CellCoords.X,CellCoords.Y,Dummy);
dgTable.Invalidate;
end
else Beep;
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.dgTableSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
UpdateInfo(ACol,ARow);
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.dgTableDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
BoundsRect: TRect;
TempStr: String;
Shop: TILItemShop;
TempSize: TSize;
procedure SetBrushColors(Brush: TBrush; TrueColor,FalseColor: TColor; Switch: Boolean);
begin
If Switch then
Brush.Color := TrueColor
else
Brush.Color := FalseColor;
end;
begin
If (Sender is TDrawGrid) and Assigned(fDrawBuffer) then
begin
// adjust draw buffer size
If fDrawBuffer.Width < (Rect.Right - Rect.Left) then
fDrawBuffer.Width := Rect.Right - Rect.Left;
If fDrawBuffer.Height < (Rect.Bottom - Rect.Top) then
fDrawBuffer.Height := Rect.Bottom - Rect.Top;
BoundsRect := Classes.Rect(0,0,Rect.Right - Rect.Left,Rect.Bottom - Rect.Top);
with fDrawBuffer.Canvas do
begin
Font.Style := [];
Pen.Style := psClear;
Brush.Style := bsSolid;
If gdFixed in State then
begin // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
If (ARow > 0) and (ACol = 0) then
begin
// items
Draw(BoundsRect.Left,BoundsRect.Top,fTable[Pred(ARow)].Item.RenderMini);
fTable[Pred(ARow)].Item.RenderMini.Dormant;
Pen.Color := clSilver; // for grid lines
end
else If (ARow = 0) and (ACol > 0) then
begin
// shops
Brush.Color := $00E4E4E4;
Rectangle(BoundsRect);
If IL_GetRotatedTextSize(fDrawBuffer.Canvas,CDA_GetItem(fKnownShops,Pred(ACol)),90,TempSize) then
IL_DrawRotatedText(fDrawBuffer.Canvas,CDA_GetItem(fKnownShops,Pred(ACol)),90,
((BoundsRect.Right - BoundsRect.Left) - TempSize.cx) div 2,
((BoundsRect.Bottom - BoundsRect.Top) - TempSize.cy) div 2 + TempSize.cy);
Pen.Color := clGray;
end
else
begin
// other fixed cells (upper left corner)
Brush.Color := $00FFE8EA; // shade of blue
Rectangle(BoundsRect);
Pen.Color := clGray;
end;
end
else // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
begin
// shop cells
Shop := fTable[Pred(ARow)].Shops[Pred(ACol)];
If Assigned(Shop) then
begin
// background
If Shop.IsAvailableHere(True) then
begin
// valid shop
If Shop.Price <= fTable[Pred(ARow)].Item.UnitPriceLowest then
SetBrushColors(Brush,$0069FF62,$00CEFFCC,gdSelected in State)
else If Shop.Price >= fTable[Pred(ARow)].Item.UnitPriceHighest then
SetBrushColors(Brush,$003CFAFF,$00C4FEFF,gdSelected in State)
else
SetBrushColors(Brush,$00E6E6E6,clWhite,gdSelected in State);
end
// invalid shop (item not available here
else SetBrushColors(Brush,$005EBAFF,$00B7E0FF,gdSelected in State);
Rectangle(BoundsRect);
// text
Brush.Style := bsClear;
If cbCompactView.Checked then
begin
// price rotated by 90deg and without currency symbol
Font.Style := font.Style + [fsBold];
If Shop.Price > 0 then
TempStr := IL_Format('%d',[Shop.Price])
else
TempStr := '-';
If IL_GetRotatedTextSize(fDrawBuffer.Canvas,TempStr,90,TempSize) then
IL_DrawRotatedText(fDrawBuffer.Canvas,TempStr,90,
BoundsRect.Right - TempSize.cx - 1,
BoundsRect.Top + TempSize.cy + 2);
end
else
begin
// price
Font.Style := Font.Style + [fsBold];
If Shop.Price > 0 then
TempStr := IL_Format('%d %s',[Shop.Price,IL_CURRENCY_SYMBOL])
else
TempStr := '-';
TextOut(BoundsRect.Right - TextWidth(TempStr) - 5,2,TempStr);
// available
Font.Style := font.Style - [fsBold];
If Shop.Available > 0 then
TempStr := IL_Format('%d pcs',[Shop.Available])
else If Shop.Available < 0 then
TempStr := IL_Format('%d+ pcs',[Abs(Shop.Available)])
else
TempStr := '';
TextOut(BoundsRect.Right - TextWidth(TempStr) - 5,18,TempStr);
end;
// selection mark
If Shop.Selected then
begin
Pen.Style := psClear;
Brush.Style := bsSolid;
Brush.Color := clBlue;
Rectangle(BoundsRect.Left,BoundsRect.Top,BoundsRect.Left + 10,BoundsRect.Bottom);
end;
end
else
begin
// shop not assigned
SetBrushColors(Brush,$00D6D6D6,$00F7F7F7,gdSelected in State);
Rectangle(BoundsRect);
end;
Pen.Color := clSilver;
end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Pen.Style := psSolid;
MoveTo(BoundsRect.Left,BoundsRect.Bottom - 1);
LineTo(BoundsRect.Right - 1,BoundsRect.Bottom - 1);
LineTo(BoundsRect.Right - 1,BoundsRect.Top - 1);
end;
// move drawbuffer to the canvas
TDrawGrid(Sender).Canvas.CopyRect(Rect,fDrawBuffer.Canvas,BoundsRect);
end;
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.dgTableMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
If ssRight in Shift then
begin
If fTracking then
begin
// horizontal movement
If Abs(fTrackPoint.X - Mouse.CursorPos.X) >= dgTable.DefaultColWidth then
begin
If (fTrackPoint.X - Mouse.CursorPos.X) > 0 then
begin
// cursor moved left
If dgTable.LeftCol < (dgTable.ColCount - ((dgTable.ClientWidth - dgTable.ColWidths[0]) div dgTable.DefaultColWidth)) then
dgTable.LeftCol := dgTable.LeftCol + 1;
fTrackPoint.X := fTrackPoint.X - dgTable.DefaultColWidth;
end
else
begin
// cursor moved right
If dgTable.LeftCol > 1 then
dgTable.LeftCol := dgTable.LeftCol - 1;
fTrackPoint.X := fTrackPoint.X + dgTable.DefaultColWidth;
end;
end;
// vertical movement
If Abs(fTrackPoint.Y - Mouse.CursorPos.Y) >= dgTable.DefaultRowHeight then
begin
If (fTrackPoint.Y - Mouse.CursorPos.Y) > 0 then
begin
// cursor moved up
If dgTable.TopRow < (dgTable.RowCount - ((dgTable.ClientHeight - dgTable.RowHeights[0]) div dgTable.DefaultRowHeight)) then
dgTable.TopRow := dgTable.TopRow + 1;
fTrackPoint.Y := fTrackPoint.Y - dgTable.DefaultRowHeight;
end
else
begin
// cursor moved down
If dgTable.TopRow > 1 then
dgTable.TopRow := dgTable.TopRow - 1;
fTrackPoint.Y := fTrackPoint.Y + dgTable.DefaultRowHeight;
end;
end;
end
else
begin
fTracking := True;
fTrackPoint := Mouse.CursorPos;
end;
end
else fTracking := False;
end;
//------------------------------------------------------------------------------
procedure TfItemShopTableForm.cbCompactViewClick(Sender: TObject);
begin
AdjustTable;
end;
end.
|
unit lotofacil_frequencia;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fgl, ZConnection, ZDataset, Dialogs, Math, db, Grids;
type
TInt_Int = specialize TFPGMap<integer, integer>;
TList_Int = specialize TFPGList<TInt_Int>;
// No banco de dados, há uma tabela de nome 'lotofacil_resultado_frequencia', que armazena
// a frequência das 25 bolas pra cada concurso.
// Então, toda vez que um concurso é inserido nas tabelas do banco de dados, uma trigger
// é responsável por realizar esta análise.
// Na análise da frequência, é considerado os seguintes parâmetros:
// Se a bola é nova no concurso atual, em relação ao anterior;
// Se a bola é repetida no concurso atual, em relação ao anterior;
// Se a bola ainda não saiu no concurso atual, nem no concurso atual;
// Se a bola deixou de sair no concurso atual, em relação ao concurso anterior;
TFreq_array_bidimensional = array of array of Integer;
TFrequencia_de_para = record
concurso: Integer;
bola_rank_de_para: array[1..25] of array[1..25] of Array[1..25] of Byte;
bola_freq_de_para: array[1..25] of array[1..25] of array[1..25] of Integer;
end;
TFrequencia_Status = record
concurso: Integer;
bola_da_coluna_atual: array[1..25] of Byte;
bola_anterior_da_coluna_atual: array[1..25] of Byte;
coluna_anterior_da_bola_atual: array[1..25] of Byte;
id_coluna_da_bola: array[1..25] of Byte;
frequencia_da_bola: array[1..25] of Integer;
frequencia_anterior_da_bola: array[1..25] of Integer;
//bola_na_posicao_do_rank: array [1..25] of Byte;
//frequencia_na_posicao_do_rank: array [1..25] of Integer;
//rank_da_bola: array[1..25] of Byte;
//bola_na_posicao_do_rank_anterior: array[1..25] of Byte;
//frequencia_da_bola: array[1..25] of Integer;
//frequencia_da_bola_rank_anterior: array[1..25] of Integer;
//frequencia_na_posicao_do_rank_anterior: array[1..25] of Integer;
//rank_anterior_da_bola: array[1..25] of Byte;
bola_se_repetindo: array[1..25] of Boolean;
frequencia_se_repetindo: array[1..25] of Boolean;
bola_qt_vz_mesma_posicao_do_rank: array [1..25] of Byte;
frequencia_qt_vz_mesma_posicao_do_rank: array [1..25] of Byte;
frequencia_status : array [1..25] of string;
end;
TFrequencia_Status_Array = array of TFrequencia_Status;
TFrequencia_comparacao_opcoes = record
concurso_inicial: Integer;
concurso_final: Integer;
sql_conexao: TZConnection;
end;
TFrequencia_opcoes = record
concurso_inicial: Integer;
concurso_final : Integer;
sql_conexao: TZConnection;
sgr_controle: TStringGrid;
end;
procedure frequencia_gerar_estatistica(sql_conexao: TZConnection);
procedure frequencia_atualizar_combinacoes_lotofacil(sql_conexao: TZConnection; concurso: integer);
procedure frequencia_gerar_comparacao(frequencia_opcoes: TFrequencia_opcoes);
function frequencia_obter_todas(frequencia_opcoes: TFrequencia_opcoes;
var frequencia_status: TFrequencia_Status_Array
): boolean;
procedure frequencia_exibir_comparacao(frequencia_opcoes: TFrequencia_opcoes;
frequencia_status: TFrequencia_Status_Array);
implementation
{
Vamos obter todos os registros da tabela 'lotofacil.lotofacil_resultado_frequencia', nesta
tabela, há os campos com o prefixo 'num_' e onde cada campo com tal prefixo, tem o sufixo
que corresponde a cada bola da lotofacil, então, num_1 e num_2, por exemplo, corresponde,
às bolas 1 e 2.
O valor de tais campo será:
Menor que -1, se a bola do concurso atual em relação ao último concurso ainda não saiu.
Igual a -1, se a bola do concurso atual em relação ao último concurso deixou de sair.
Igual a 1, se a bola do concurso atual em relação ao último concurso é nova.
Maior que 1, se a bola do concurso atual em relação ao último concurso está se repetindo.
Então, por exemplo, seja bola 1 em vários concursos, sequenciais e consecutivos:
-1,-2,-3,1,2,3,4,5,-1,-2,1,2,3,
acima, valores negativos indica que a bola não saiu e valores positivos indica que a bola
saiu, então, toda vez que houver uma transição de sair pra não-sair ou de não-sair pra sair, devemos
registrar o maior valor da transição, então, no exemplo acima:
-3 e 5, é o maior valor antes da transição, poderíamos contabilizar de outra forma, mas assim,
não conseguíriamos identificar a frequência com facilidade.
Então, na procedure abaixo, nosso objetivo é contabilizar, quantas vezes, cada valor apareceu
na transição entre sair e não-sair ou de não-sair pra sair.
}
procedure frequencia_gerar_estatistica(sql_conexao: TZConnection);
var
frequencia_lista: TList_Int;
frequencia_num_mapa: TInt_Int;
uA, uB, frequencia_atual: integer;
// Armazena todos os registros da tabela de frequência.
frequencia: array of array of integer;
// Armazena a frequência anterior, quando estivermos processando os registros.
frequencia_anterior: array[0..25] of integer;
sql_query: TZQuery;
qt_registros, valor_atual, valor_frequencia_atual, frequencia_contabilizacao, chave_atual: longint;
begin
// Vamos criar a lista e o mapa que armazena as frequências.
frequencia_lista := TList_Int.Create;
frequencia_lista.Clear;
// O índice da lista corresponde ao número da bola,
// não iremos usar o índice 0.
frequencia_lista.Add(nil);
for uA := 1 to 25 do
begin
frequencia_num_mapa := TInt_Int.Create;
frequencia_lista.Add(frequencia_num_mapa.Create);
frequencia_lista[uA].Clear;
end;
// Vamos obter todos os registros;
try
sql_query := TZQuery.Create(nil);
sql_query.Connection := sql_conexao;
sql_query.Sql.Clear;
sql_query.Sql.Add('Select * from lotofacil.lotofacil_resultado_num_frequencia');
sql_query.Sql.Add('order by concurso asc');
sql_query.Open;
sql_query.First;
sql_query.Last;
qt_registros := sql_query.RecordCount;
// Armazena em arranjo todos os registros, pra posterior análise.
// Devemos inserir 1 a mais, pois, ao criar dinamicamente, o arranjo
// será baseado em zero, iremos preferencialmente começar em 1.
// Na dimensão 1, iremos criar 26 posições de 0 a 25, pois, se
// indicássemos 25, ficaria de 0 a 24, e estaría errado.
// Iremos fazer desta forma pois, assim, conseguirmos identificar em qual coluna
// estamos.
SetLength(frequencia, qt_registros + 1, 26);
// A variável abaixo, serve pra percorrer o arranjo 'frequencia'.
// Iremos começar do índice 1.
uA := 1;
sql_query.First;
while (not sql_query.EOF) or (uA <= qt_registros) do
begin
for uB := 1 to 25 do
begin
valor_frequencia_atual := sql_query.FieldByName('num_' + IntToStr(uB)).AsInteger;
frequencia[uA, uB] := valor_frequencia_atual;
end;
sql_query.Next;
Inc(uA);
end;
sql_query.Close;
// Agora, iremos pegar a frequência do primeiro registro.
for uA := 1 to 25 do
begin
frequencia_anterior[uA] := frequencia[1, uA];
end;
// Agora, iremos comparar o sinal da frequência atual com o valor da frequência anterior.
// se, o sinal forem diferentes, quer dizer que houve transição, então, devemos, pegar
// o valor da frequência anterior e verificar se já estive este valor como chave na variável
// do tipo mapa, se sim, devemos somar mais ao valor da chave, senão, contabilizaremos como 1.
for uA := 2 to qt_registros do
begin
for uB := 1 to 25 do
begin
// Se o sinal da frequência anterior e da frequência atual são
// diferentes, quer dizer que há uma transição, que quer dizer que
// a bola do concurso anterior saiu e no concurso atual não saiu ou
// que a bola do concurso anterior ainda não havia saído e neste concurso saiu.
if Sign(frequencia_anterior[uB]) <> Sign(frequencia[uA, uB]) then
begin
// Se é a primeira vez deste valor de frequência, iremos armazenar na variável
// do tipo map com o valor 1, se não for, quer dizer, que iremos somar mais
// 1, ao valor da chave que corresponde à esta frequência.
// Obtém o mapa atual.
frequencia_num_mapa := frequencia_lista[uB];
// Valor da frequência a ser contabilizada.
frequencia_atual := frequencia_anterior[uB];
if frequencia_num_mapa.IndexOf(frequencia_atual) = -1 then
begin
frequencia_num_mapa.Add(frequencia_atual, 1);
end
else
begin
// Se chegarmos aqui, quer dizer, que a frequência já existe no
// mapa, devemos obter a contabilização atual.
frequencia_contabilizacao := frequencia_num_mapa.KeyData[frequencia_atual];
Inc(frequencia_contabilizacao);
frequencia_num_mapa.AddOrSetData(frequencia_atual, frequencia_contabilizacao);
end;
frequencia_lista[ub] := frequencia_num_mapa;
end;
frequencia_anterior[uB] := frequencia[uA, uB];
end;
end;
// Agora, contabiliza a última frequência, pois, p
for uB := 1 to 25 do
begin
// Obtém o mapa atual.
frequencia_num_mapa := frequencia_lista[uB];
// Valor da frequência a ser contabilizada.
frequencia_atual := frequencia_anterior[uB];
if frequencia_num_mapa.IndexOf(frequencia_atual) = -1 then
begin
frequencia_num_mapa.Add(frequencia_atual, 1);
end
else
begin
// Se chegarmos aqui, quer dizer, que a frequência já existe no
// mapa, devemos obter a contabilização atual.
frequencia_contabilizacao := frequencia_num_mapa.KeyData[frequencia_atual];
Inc(frequencia_contabilizacao);
frequencia_num_mapa.AddOrSetData(frequencia_atual, frequencia_contabilizacao);
end;
end;
// Agora, exibe os dados.
for uA := 1 to 25 do
begin
frequencia_num_mapa := frequencia_lista[uA];
for uB := 0 to Pred(frequencia_num_mapa.Count) do
begin
chave_atual := frequencia_num_mapa.Keys[uB];
end;
end;
FreeAndNil(sql_query);
except
On Exc: Exception do
begin
FreeAndNil(sql_query);
MessageDlg('', 'Erro, ' + Exc.Message, mtError, [mbOK], 0);
Exit;
end;
end;
end;
{
Atualiza todas as combinações da lotofacil de 15 números, com a frequência relativa
ao concurso escolhido pelo usuário.
}
procedure frequencia_atualizar_combinacoes_lotofacil(sql_conexao: TZConnection; concurso: integer);
const
// Quantidade de combinações de 15 números na lotofacil.
LTF_CMB_15_BOLAS = 3268760;
var
frequencia_num_concurso: array [0..25] of integer;
sql_query : TZQuery;
frequencia_concurso, qt_registros, zero_um: longint;
frequencia_combinacoes: array of array of integer;
uA, soma_frequencia, uB, qt_ainda_nao_saiu, qt_saiu, qt_repetindo, qt_deixou_de_sair,
qt_novo, qt_registros_lidos: integer;
sql_insert, zero_um_anterior, zero_um_atual: string;
begin
// Obtém a frequência do concurso escolhido.
try
sql_query := TZQuery.Create(nil);
sql_query.Connection := sql_conexao;
// Deleta os dados da tabela.
sql_query.Sql.Clear;
sql_query.Sql.Add('Truncate lotofacil.lotofacil_frequencia');
sql_query.ExecSql;
sql_query.Sql.Clear;
sql_query.Sql.Add('Select * from lotofacil.lotofacil_resultado_num_frequencia');
sql_query.Sql.Add('where concurso = ' + IntToStr(concurso));
sql_query.Open;
sql_query.First;
sql_query.Last;
qt_registros := sql_query.RecordCount;
if qt_registros = 0 then
begin
MessageDlg('', 'Nenhum registro localizado', mtError, [mbOK], 0);
Exit;
end;
// Copia a frequencia pra o vetor.
sql_query.First;
for uA := 1 to 25 do
begin
frequencia_concurso := sql_query.FieldByName('num_' + IntToStr(uA)).AsInteger;
frequencia_num_concurso[uA] := frequencia_concurso;
end;
// Vamos percorrer todas as combinações e comparar com a frequência do concurso.
sql_query.Sql.Clear;
sql_query.SQL.Add('Select * from lotofacil.lotofacil_num');
sql_query.Sql.Add('where ltf_qt = 15');
sql_query.Sql.Add('Order by ltf_id asc');
sql_query.Open;
sql_query.First;
sql_query.Last;
qt_registros := sql_query.RecordCount;
if qt_registros <> LTF_CMB_15_BOLAS then
begin
MessageDlg('', 'Erro, não há 3268760 registros com 15 bolas', mtError, [mbOK], 0);
Exit;
end;
// Na dimensão 2, há 8 campos:
// ltf_id,sm_df,qt_ainda_nao_saiu,qt_novo,qt_repetindo,qt_deixou_de_sair.
SetLength(frequencia_combinacoes, qt_registros + 1, 8);
zero_um_anterior := '';
sql_query.First;
for uA := 1 to qt_registros do
begin
soma_frequencia := 0;
qt_ainda_nao_saiu := 0;
qt_novo := 0;
qt_repetindo := 0;
qt_deixou_de_sair := 0;
zero_um_atual := '';
for uB := 1 to 25 do
begin
zero_um := sql_query.FieldByName('num_' + IntToStr(uB)).AsInteger;
// Vamos verificar se o registro anterior é igual ao atual.
if zero_um_atual <> '' then begin
zero_um_atual := zero_um_atual + '_';
end;
zero_um_atual := zero_um_atual + IntToStr(zero_um);
frequencia_concurso := frequencia_num_concurso[uB];
//Writeln('uB:', uB, 'zero_um:', zero_um, 'freq_conc: ', frequencia_concurso);
// Nos ifs abaixo, funciona assim, a variável 'zero_um' tem o valor
// '1' se a bola saiu naquela combinação, '0' caso contrário,
// então, iremos comparar com a frequência do concurso.
// Na frequência do concurso, temos, números positivos e negativos,
// um número positivo e maior que zero, indica se a bola é nova
// naquele concurso em relação a outro ou está se repetindo e
// se um número negativo, quer dizer, que a bola ainda não saiu ou deixou
// de sair.
if (zero_um = 1) and (sign(frequencia_concurso) = 1) then
begin
Inc(frequencia_concurso);
Inc(qt_repetindo);
end
else
if (zero_um = 1) and (sign(frequencia_concurso) = -1) then
begin
frequencia_concurso := 1;
Inc(qt_novo);
end
else if (zero_um = 0) and (sign(frequencia_concurso) = 1) then
begin
frequencia_concurso := -1;
Inc(qt_deixou_de_sair);
end
else if (zero_um = 0) and (sign(frequencia_concurso) = -1) then
begin
Inc(frequencia_concurso, -1);
Inc(qt_ainda_nao_saiu);
end else begin
//Writeln('Caiu aqui, verificar.');
end;
// Após alterar.
//Writeln('uB:', uB, 'zero_um:', zero_um, 'freq_conc: ', frequencia_concurso);
soma_frequencia := soma_frequencia + frequencia_concurso;
end;
if zero_um_anterior = zero_um_atual then begin
//Writeln('zero_um=zero_um_anterior');
end;
zero_um_anterior := zero_um_atual;
sql_query.Next;
if sql_query.EOF = true then begin
//Writeln('EOF');
END;;
frequencia_combinacoes[uA, 0] := uA;
frequencia_combinacoes[uA, 1] := concurso;
frequencia_combinacoes[uA, 2] := soma_frequencia;
frequencia_combinacoes[uA, 3] := qt_ainda_nao_saiu;
frequencia_combinacoes[uA, 4] := qt_novo;
frequencia_combinacoes[uA, 5] := qt_repetindo;
frequencia_combinacoes[uA, 6] := qt_deixou_de_sair;
end;
sql_insert := 'Insert into lotofacil.lotofacil_frequencia(' +
'ltf_id,concurso,sm_df,qt_ainda_nao_saiu,qt_novo' +
',qt_repetindo,qt_deixou_de_sair)values';
sql_query.Sql.Clear;
qt_registros_lidos := 0;
for uA := 1 to qt_registros do
begin
if qt_registros_lidos = 0 then
begin
sql_query.Sql.Clear;
sql_query.Sql.Add(sql_insert);
end;
if qt_registros_lidos > 0 then
begin
sql_query.Sql.Add(',');
end;
sql_query.Sql.Add(Format('(%d,%d,%d,%d,%d,%d,%d)',
[frequencia_combinacoes[uA, 0], frequencia_combinacoes[uA, 1],
frequencia_combinacoes[uA, 2], frequencia_combinacoes[uA, 3],
frequencia_combinacoes[uA, 4], frequencia_combinacoes[uA, 5],
frequencia_combinacoes[uA, 6]]));
Inc(qt_registros_lidos);
if qt_registros_lidos = 1000 then
begin
//Writeln(sql_query.SQL.Text);
sql_query.ExecSql;
sql_query.SQL.Clear;
qt_registros_lidos := 0;
end;
end;
// Se restou algo, iremos gravar
if qt_registros <> 0 then begin
sql_query.ExecSql;
end;
sql_query.Close;
FreeAndNil(sql_query);
except
On Exc: Exception do
begin
Exit;
end;
end;
end;
{
Gera uma estatística comparando todas as frequências.
}
procedure frequencia_gerar_comparacao(frequencia_opcoes: TFrequencia_opcoes);
var
frequencia_status: TFrequencia_Status_Array;
begin
frequencia_opcoes.sql_conexao := frequencia_opcoes.sql_conexao;
if frequencia_obter_todas(frequencia_opcoes, frequencia_status) = false then begin
Exit;
end;
// Agora, vamos exibir a estatística de frequência.
frequencia_exibir_comparacao(frequencia_opcoes, frequencia_status);
end;
{
Obtém a informação de cada frequência da tabela 'lotofacil.lotofacil_resultado_frequencia'.
}
function frequencia_obter_todas(frequencia_opcoes: TFrequencia_opcoes;
var frequencia_status: TFrequencia_Status_Array): boolean;
var
sql_query: TZQuery;
qt_registros: LongInt;
indice_registro, uA, rank_atual: Integer;
concurso_atual, bola_atual, frequencia_atual, concurso_anterior,
indice_registro_anterior, frequencia_anterior_da_bola,
frequencia_anterior_na_posicao_do_rank,
frequencia_na_posicao_do_rank_anterior, id_coluna: Integer;
bola_na_posicao_do_rank_anterior, rank_anterior_da_bola,
id_coluna_anterior_da_bola_atual, bola_anterior_da_coluna: Byte;
begin
try
sql_query := TZQuery.Create(Nil);
sql_query.Connection := frequencia_opcoes.sql_conexao;
sql_query.Sql.Clear;
sql_query.Sql.Add('Select * from lotofacil.v_lotofacil_resultado_bolas_frequencia');
sql_query.Sql.Add('order by concurso desc, frequencia desc, bola asc');
sql_query.Open;
sql_query.First;
sql_query.Last;
qt_registros := sql_query.RecordCount;
if qt_registros = 0 then begin
Exit(False);
end;
// Verifica se a quantidade de registros é múltipla de 25.
if qt_registros mod 25 <> 0 then begin
Exception.Create('Erro, a quantidade de registros retornadas, deve ser uma ' +
' quantidade múltipla de 25');
Exit(False);
end;
// Cada frequência de bola de cada combinação, é armazenada em um registro
// por isso, devemos dividir por 5, pois, ao processar no loop, em breve,
// a seguir, iremos colocar todas as bolas, dentro de um única variável
// do tipo registro.
SetLength(frequencia_status, qt_registros div 25 );
Writeln(Length(frequencia_status));
if Length(frequencia_status) <= 0 then begin
Exception.Create('Não há memória pra alocar o arranjo.');
Exit(False);
end;
// Reseta o primeiro arranjo.
FillByte(frequencia_status[0], sizeof(TFrequencia_Status), 0);
sql_query.First;
indice_registro := -1;
while (qt_registros > 0) and (sql_query.EOF = false) do begin
// No sql, iremos percorrer do menor concurso até o último concurso
// referente a frequência e de tal forma que as bolas esteja disposta
// em ordem decrescente de frequência, caso, duas bolas tenha a mesma
// frequência, então, a menor bola aparece primeiro.
// Cada concurso, gera a frequência pra cada bola, por isto, há 25 registros
// por combinação.
// No loop abaixo, iremos percorrer as 25 posições e inserir em uma
// única variável do tipo 'record', assim fica fácil manipular
// a informação.
Inc(indice_registro);
if indice_registro = 0 then begin
indice_registro_anterior := 0;
end else begin
indice_registro_anterior := indice_registro - 1;
end;
for uA := 1 to 25 do begin
id_coluna := uA;
concurso_atual := sql_query.FieldByName('concurso').AsInteger;
bola_atual := sql_query.FieldByName('bola').AsInteger;
frequencia_atual := sql_query.FieldByName('frequencia').AsInteger;
// Vamos armazenar os dados.
frequencia_status[indice_registro].concurso:= concurso_atual;
frequencia_status[indice_registro].bola_da_coluna_atual[id_coluna] := bola_atual;
frequencia_status[indice_registro].frequencia_da_bola[bola_atual] := frequencia_atual;
frequencia_status[indice_registro].id_coluna_da_bola[bola_atual] := id_coluna;
if frequencia_atual > 0 then begin
frequencia_status[indice_registro].frequencia_status[uA]:= 'REP';
end else if frequencia_atual = 1 then begin
frequencia_status[indice_registro].frequencia_status[uA]:= 'NOVO';
end else if frequencia_atual = -1 then begin
frequencia_status[indice_registro].frequencia_status[uA]:= 'DX_S';
end else begin
frequencia_status[indice_registro].frequencia_status[uA]:= 'AI_NS';
end;
// Aqui, iremos pegar a estatística da frequência anterior:
// Bola que estava na mesma posição do rank, na frequência anterior.
bola_anterior_da_coluna := frequencia_status[indice_registro_anterior].bola_anterior_da_coluna_atual[id_coluna];
id_coluna_anterior_da_bola_atual := frequencia_status[indice_registro_anterior].coluna_anterior_da_bola_atual[bola_atual];
//bola_na_posicao_do_rank_anterior := frequencia_status[indice_registro_anterior].bola_na_posicao_do_rank[rank_atual];
//rank_anterior_da_bola := frequencia_status[indice_registro_anterior].rank_anterior_da_bola[bola_atual];
// A frequência anterior da bola atual.
frequencia_anterior_da_bola := frequencia_status[indice_registro_anterior].frequencia_da_bola[bola_atual];
// A frequência na posição do rank anterior.
// frequencia_na_posicao_do_rank_anterior := frequencia_status[indice_registro_anterior].frequencia_na_posicao_do_rank[rank_atual];
// Agora, insere estas informações no registro atual.
frequencia_status[indice_registro].bola_anterior_da_coluna_atual[id_coluna] := bola_anterior_da_coluna;
frequencia_status[indice_registro].frequencia_anterior_da_bola[bola_atual] := frequencia_anterior_da_bola;
//frequencia_status[indice_registro].frequencia_na_posicao_do_rank_anterior[rank_atual] := frequencia_na_posicao_do_rank_anterior;
frequencia_status[indice_registro].coluna_anterior_da_bola_atual[bola_atual] := id_coluna_anterior_da_bola_atual;
// Cada bola é disposta de tal forma, que as bolas que mais sai estão ordenadas da
// esquerda pra direita, conforme o valor de frequência, então é possível que
// a mesma bola na mesma posição do rank se repita e também pode acontecer
// da frequência de um concurso anterior de um rank ser igual à frequência do concurso atual,
// no mesmo rank, isto ocorre se a frequência do concurso anterior, de um outro rank,
// deslocar pra um outro rank, também, descreveremos isto.
if bola_atual = bola_na_posicao_do_rank_anterior then begin
Inc(frequencia_status[indice_registro].bola_qt_vz_mesma_posicao_do_rank[rank_atual]);
end else begin
frequencia_status[indice_registro].bola_qt_vz_mesma_posicao_do_rank[rank_atual] := 0;
end;
if frequencia_anterior_na_posicao_do_rank = frequencia_atual then begin
Inc(frequencia_status[indice_registro].frequencia_qt_vz_mesma_posicao_do_rank[rank_atual]);
end else begin
frequencia_status[indice_registro].frequencia_qt_vz_mesma_posicao_do_rank[rank_atual] := 0;
end;
sql_query.Next;
Dec(qt_registros);
end;
end;
FreeAndNil(sql_query);
except
On Exc: Exception do begin
MessageDlg('', 'Erro, ' + Exc.Message, mtError, [mbok], 0);
Exit(False);
end;
end;
Exit(True);
end;
procedure frequencia_exibir_comparacao(frequencia_opcoes: TFrequencia_opcoes;
frequencia_status: TFrequencia_Status_Array);
const
sgr_controle_campos : array[0..26] of string = (
'Concurso', '#', '1', '2','3', '4','5',
'6', '7','8', '9','10',
'11', '12','13', '14','15',
'16', '17','18', '19','20',
'21', '22','23', '24','25');
var
sgr_controle: TStringGrid;
coluna_atual: TGridColumn;
uA, indice_linha_sgr_controle, indice_coluna, indice_linha,
sgr_controle_total_de_linhas, indice_freq_status, frequencia_atual: Integer;
concurso_numero: QWord;
frequencia_anterior, bola_anterior, frequencia_rank_atual,
frequencia_rank_anterior, frequencia_bola_rank_anterior,
frequencia_bola_atual, frequencia_anterior_bola_atual: Integer;
qt_vz_freq_repetindo, bola_rank_atual, bola_rank_anterior,
rank_anterior_da_bola_atual, bola_da_coluna_atual,
coluna_anterior_da_bola_atual, bola_anterior_da_coluna_atual: Byte;
frq_status: String;
bola_se_repetindo, frequencia_se_repetindo: Boolean;
begin
if Length(frequencia_status) <= 0 then begin
MessageDlg('', 'Não há nenhum registro.', mtError, [mbok], 0);
Exit;
end;
sgr_controle := frequencia_opcoes.sgr_controle;
sgr_controle.Columns.Clear;
sgr_controle.RowCount := 1;
sgr_controle.FixedRows:=1;
// No controle, haverá as colunas:
// concurso, sigla, rnk_1, até rnk_25.
// rnk, significa o rank da bola quanto mais a esquerda, mais frequente é a bola.
for uA := 0 to High(sgr_controle_campos) do begin
coluna_atual := sgr_controle.columns.Add;
coluna_atual.Alignment:= taCenter;
coluna_atual.Font.Size := 12;
coluna_atual.Font.Name := 'Consolas';
coluna_atual.Title.Alignment := taCenter;
coluna_atual.Title.Caption := sgr_controle_campos[uA];
coluna_atual.Title.Font.Name := 'Consolas';
coluna_atual.Title.Font.Size := 12;
end;
// A frequẽncia pra cada combinação, ocupará mais de uma linha,
// então, precisamos multiplicar pelo números de linhas.
// Haverá 8 linhas, por concurso.
sgr_controle_total_de_linhas := Length(frequencia_status) * 10;
// Haverá 1 linha a mais por causa do cabeçalho.
sgr_controle.RowCount := sgr_controle_total_de_linhas + 1;
// Agora, vamos gerar os dados.
indice_linha := 1;
indice_coluna := 2;
indice_freq_status := 0;
while indice_linha <= sgr_controle_total_de_linhas do begin
// Concurso.
concurso_numero := frequencia_status[indice_freq_status].concurso;
sgr_controle.Cells[0, indice_linha] := IntToStr(concurso_numero);
// Pra cada frequência, haverá 5 linhas, que representa as informações de frequência.
sgr_controle.Cells[1, indice_linha] := 'STATUS';
sgr_controle.Cells[1, indice_linha + 1] := 'BL_RNK_AT';
sgr_controle.Cells[1, indice_linha + 2] := 'BL_RNK_ANT';
sgr_controle.Cells[1, indice_linha + 3] := 'RNK_ANT_BL_AT';
sgr_controle.Cells[1, indice_linha + 4] := 'BL_RPT';
sgr_controle.Cells[1, indice_linha + 5] := 'FRQ_RNK_AT';
sgr_controle.Cells[1, indice_linha + 6] := 'FRQ_RNK_ANT';
sgr_controle.Cells[1, indice_linha + 7] := 'FRQ_BL_RNK_ANT';
//sgr_controle.Cells[1, indice_linha + 7] := 'QT_VZ_BL_RPT';
//sgr_controle.Cells[1, indice_linha + 8] := 'FRQ_RPT';
indice_coluna := 2;
for uA := 1 to 25 do begin
bola_da_coluna_atual := frequencia_status[indice_freq_status].bola_da_coluna_atual[uA];
bola_anterior_da_coluna_atual := frequencia_status[indice_freq_status].bola_anterior_da_coluna_atual[uA];
coluna_anterior_da_bola_atual := frequencia_status[indice_freq_status].coluna_anterior_da_bola_atual[bola_rank_atuaL];
frequencia_bola_atual := frequencia_status[indice_freq_status].frequencia_da_bola[uA];
frequencia_anterior_bola_atual := frequencia_status[indice_freq_status].frequencia_anterior_da_bola[uA];
//frequencia_bola_rank_anterior := frequencia_status[indice_freq_status].frequencia_da_bola_rank_anterior[bola_rank_atual];
bola_se_repetindo := frequencia_status[indice_freq_status].bola_se_repetindo[uA];
frequencia_se_repetindo := frequencia_status[indice_freq_status].frequencia_se_repetindo[uA];
qt_vz_freq_repetindo := frequencia_status[indice_freq_status].frequencia_qt_vz_mesma_posicao_do_rank[uA];
frq_status := frequencia_status[indice_freq_status].frequencia_status[uA];
sgr_controle.Cells[indice_coluna, indice_linha] := frq_status;
sgr_controle.Cells[indice_coluna, indice_linha + 1] := IntToStr(bola_da_coluna_atual);
sgr_controle.Cells[indice_coluna, indice_linha + 2] := IntToStr(bola_anterior_da_coluna_atual);
sgr_controle.Cells[indice_coluna, indice_linha + 3] := IntToStr(rank_anterior_da_bola_atual);
if bola_se_repetindo then begin
sgr_controle.Cells[indice_coluna, indice_linha + 4] := 'BL_S';
end else begin
sgr_controle.Cells[indice_coluna, indice_linha + 4] := 'BL_N';
end;
sgr_controle.Cells[indice_coluna, indice_linha + 5] := IntToStr(frequencia_rank_atual);
sgr_controle.Cells[indice_coluna, indice_linha + 6] := IntToStr(frequencia_rank_anterior);
if frequencia_se_repetindo then begin
sgr_controle.Cells[indice_coluna, indice_linha + 7] := 'FQ_S';
end else begin
sgr_controle.Cells[indice_coluna, indice_linha + 7] := 'FQ_N';
end;
sgr_controle.Cells[indice_coluna, indice_linha + 7] := IntToStr(frequencia_bola_rank_anterior);
Inc(indice_coluna);
end;
Inc(indice_linha, 10);
Inc(indice_freq_status);
end;
sgr_controle.AutoSizeColumns;
end;
end.
|
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0082.PAS
Description: Spell a Number
Author: MIKE COPELAND
Date: 01-27-94 17:36
*)
{
From: MIKE COPELAND
Subj: Spell a Number
---------------------------------------------------------------------------
>> I'm in the process of writing a Checkbook program for my Job
>> and I was wondering if anyone out there has a routine to
>> convert a check amount written in numerical to text. Here's an
>> example of what I need. Input Variable : 142.50
>> Needed Output : One Hundred Forty Two 50/100--------------------
What you're looking for is "spell-a-number", and here's a program
which does it. Note that this one operates only on integer-type data,
and you'll have to modify it for the decimal part - but that's the
easiest task... If you have questions, just post them here.
}
program Spell_A_Number; { MRCopeland 901105 }
USES CRT;
const C_ONES : array[1..9] of string[6] = ('one ','two ','three ','four ',
'five ','six ','seven ','eight ','nine ');
C_TEEN : array[0..9] of string[10] = ('ten ','eleven ','twelve ',
'thirteen ','fourteen ','fifteen ',
'sixteen ','seventeen ','eighteen',
'nineteen');
C_TENS : array[2..9] of string[8] = ('twenty ','thirty ','forty ',
'fifty ','sixty ','seventy ','eighty ',
'ninety ');
var I,J : LongInt; { global data }
procedure HUNS (N : LongInt); { process a 0-999 value }
var P : integer; { local work variable }
begin
P := N div 100; N := N mod 100; { any 100-900? }
if P > 0 then
write (C_ONES[P],'hundred ');
P := N div 10; N := N mod 10; { 10-90 }
if P > 1 then { 20-90 }
write (C_TENS[P])
else
if P = 1 then { 10-19 }
write (C_TEEN[N]);
if (P <> 1) and (N > 0) then { remainder of 1-9, 20-99 }
write (C_ONES[N]);
end; { HUNS }
begin { MAIN LINE }
ClrScr;
write ('Enter a value> '); readln (I);
if I > 0 then
begin
J := I div 1000000; I := I mod 1000000;
if J > 0 then { process millions }
begin
HUNS (J); write ('million ')
end;
J := I div 1000; I := I mod 1000;
if J > 0 then { process thousands }
begin
HUNS (J); write ('thousand ')
end;
HUNS (I) { process 0-999 remainder }
end { if }
end.
|
unit uECFList;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit,
DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, dxBar, uECFFch,
DBClient, Provider, ADODB;
type
TECFList = class(TForm)
grdECF: TcxGrid;
grdECFTableView: TcxGridDBTableView;
grdECFLevel: TcxGridLevel;
dsECF: TDataSource;
pnlBottom: TPanel;
btnClose: TcxButton;
grdECFTableViewIDECF: TcxGridDBColumn;
grdECFTableViewNumeroECF: TcxGridDBColumn;
grdECFTableViewNumeroSerie: TcxGridDBColumn;
grdECFTableViewCashRegister: TcxGridDBColumn;
grdECFTableViewStore: TcxGridDBColumn;
bmList: TdxBarManager;
bbNew: TdxBarButton;
bbEdit: TdxBarButton;
bbDelete: TdxBarButton;
quECF: TADOQuery;
quECFIDECF: TIntegerField;
quECFIDStore: TIntegerField;
quECFIDCashRegister: TIntegerField;
quECFNumeroECF: TIntegerField;
quECFNumeroSerie: TStringField;
quECFCashRegister: TStringField;
quECFStore: TStringField;
dspECF: TDataSetProvider;
cdsECF: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure bbNewClick(Sender: TObject);
procedure bbEditClick(Sender: TObject);
procedure bbDeleteClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure dsECFDataChange(Sender: TObject; Field: TField);
private
FFch: TECFFch;
public
function Start: boolean;
end;
implementation
uses uDMSintegra;
{$R *.dfm}
procedure TECFList.bbNewClick(Sender: TObject);
begin
with FFch do
try
if not Assigned(FFch) then
FFch := TECFFch.Create(Self);
FFch.Start(cdsECF);
FFch.NewRecord;
except
on E: Exception do
ShowMessage('Erro ao criar novo ECF. Erro: ' + E.Message);
end;
cdsECF.Refresh;
end;
procedure TECFList.bbEditClick(Sender: TObject);
begin
with FFch do
try
if not Assigned(FFch) then
FFch := TECFFch.Create(Self);
FFch.Start(cdsECF);
FFch.EditRecord;
cdsECF.ApplyUpdates(-1);
except
on E: Exception do
ShowMessage('Erro ao editar ECF. Erro: ' + E.Message);
end;
cdsECF.Refresh;
end;
procedure TECFList.FormDestroy(Sender: TObject);
begin
with DMSintegra do
begin
quStore.Close;
quCashRegister.Close;
end;
FreeAndNil(FFch);
end;
procedure TECFList.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TECFList.bbDeleteClick(Sender: TObject);
begin
if MessageDlg('Deseja realmente excluir?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
cdsECF.Delete;
cdsECF.ApplyUpdates(-1);
cdsECF.Refresh;
end;
end;
procedure TECFList.dsECFDataChange(Sender: TObject; Field: TField);
begin
bbEdit.Enabled := cdsECF.RecordCount > 0;
bbDelete.Enabled := bbEdit.Enabled;
end;
function TECFList.Start: boolean;
begin
ShowModal;
Result := True;
end;
procedure TECFList.FormCreate(Sender: TObject);
begin
cdsECF.Open;
end;
end.
|
{$A+,B-,D+,E-,F+,G+,I+,L+,N+,O-,P-,Q-,R-,S+,T-,V-,X+,Y+}
{-[■]------------------------------------------------------------------------
F-Code and Asm source preprocessor
Version 1.0
Copyright (c) 1997 by Alexander Demin
----------------------------------------------------------------------------
}
Uses Stacks;
Const
{ Conditions table size }
N = 9;
{ Conditions tables }
{ Warning: Short words in Conds table must follow after longer ones }
Conds : array [ 1..N ] of string[4]
= ( 'LOOP', '<>0', '<=', '>=', '<>', '=0', '<', '>', '=' );
Repls : array [ 1..N ] of string[4]
= ( 'LOOP', 'NE', 'LE', 'GE', 'NE', 'EQ', 'LT', 'GT', 'EQ' );
var
IfStack : TIntStack;
DoStack : TIntStack;
ForStack : TIntStack;
StyStack : TStrStack;
S : string;
c, R : string;
i, j, Y : word;
function UpStr( S : string ) : string;
var
i : word;
begin
for i:=1 to length( S ) do S[i]:=UpCase(S[i]);
UpStr:=S;
end;
function IntToStr( N : word ) : string;
var
T : string;
begin
Str( N:5, T );
IntToStr:=T;
end;
{ --------------------------------------------------------------------------
Replace words in the C in accordance with Conds/Repls tables.
If replacement has been done, function returns the index of the next
position in the C after this replacement and the value of Index
doesn't matter.
Otherwise function inserts ' @' ( unconditional jump sign )
into the Index-prosition and returns the the index of then position
after inserted ' @' ( value of Index+2 ).
}
function ReplaceConds( var C, S : string; Index : integer ) : integer;
var
i, j : integer;
Res : integer;
begin
Res:=0;
for j:=1 to N do begin
i:=Pos( Conds[j], C ); { Search current Condition }
if i<>0 then begin { Found ? }
delete( S, i, Length(Conds[j]) ); { Delete condition }
insert( Repls[j], S, i ); { Insert replacement }
Res:=i+Length(Repls[j]); { Calculate the index after }
break; { The replacement and break loop }
end; { Ignore the value of Index }
end;
if Res=0 then begin { Are there no replacements ? }
Insert( ' @', S, Index ); { Yeeh... Insert the unconditional }
Res:=Index+2; { jump sign }
end; { and return the value of Index+2 }
ReplaceConds:=Res;
end;
{ ------------------------------------------------------------------------- }
begin
IfStack.Init; { 15th bit of the IF-stack means:
0 - there is no Else-way
1 - there is Else-way
}
DoStack.Init;
ForStack.Init;
StyStack.Init;
{ Main processing loop }
while not eof do begin
readln( S );
C:=UpStr( S );
{ Replace $If-condition.
Warning: Condition must be present
}
if Pos( '$IF', C )<>0 then begin
i:=ReplaceConds( C, S, 0);
{ Clear the 15th bit -> there is no Else-way }
insert( ', '+IntToStr( IfStack.Push ), S, i );
end
{ Process $Else-way
}
else if Pos( '$ELSE', C )<>0 then begin
i:=Pos( '$ELSE', C );
insert( ' '+IntToStr( IfStack.Top ), S, i+5 );
{ Set up the 15th bit -> there is Else-way }
IfStack.Data[ IfStack.Ptr ]:=IfStack.Data[ IfStack.Ptr ] or $8000;
end
{ Process $EndIf word
}
else if Pos( '$ENDIF', C )<>0 then begin
i:=Pos( '$ENDIF', C );
insert( ' '+
{ Mask the 15th bit - it isn't the part of the number }
IntToStr( IfStack.Pop and $7FFF )+', '+
{ Set this number in accordance with the 15th bit }
IntToStr( (IfStack.Data[ IfStack.Ptr+1 ] and $8000) shr 15),
S, i+6 );
end
{ Process $Do word
}
else if Pos( '$DO', C )<>0 then begin
i:=Pos( '$DO', C );
insert( ' '+IntToStr( DoStack.Push), S, i+3 );
end
{ Replace $ExitDo condition
Warning: Condition can be absent.
if there is no condition, insert '@'- unconditional jump sign
otherwise replace the condition in accordance with
Conds/Repls tables.
}
else if Pos( '$EXITDO', C )<>0 then begin
i:=Pos( '$EXITDO', C )+7;
j:=ReplaceConds( C, S, i);
insert( ', '+IntToStr( DoStack.Top), S, j );
end
{ Replace $ContDo condition
Warning: Condition can be absent.
if there is no condition, insert '@'- unconditional jump sign
otherwise replace the condition in accordance with
Conds/Repls tables.
}
else if Pos( '$CONTDO', C )<>0 then begin
i:=Pos( '$CONTDO', C )+7;
j:=ReplaceConds( C, S, i);
insert( ', '+IntToStr( DoStack.Top), S, j );
end
{ Replace $EndDo-condition.
Warning: Condition must be present
}
else if Pos( '$ENDDO', C )<>0 then begin
i:=ReplaceConds( C, S, 0)+6;
insert( ', '+IntToStr( DoStack.Pop ), S, i );
end
{ Process $For word
}
else if Pos( '$FOR', C )<>0 then begin
i:=Pos( '$FOR', C );
insert( ' '+IntToStr( ForStack.Push), S, i+4 );
end
{ Replace $ExitFor condition
Warning: Condition can be absent.
if there is no condition, insert '@'- unconditional jump sign
otherwise replace the condition in accordance with
Conds/Repls tables.
}
else if Pos( '$EXITFOR', C )<>0 then begin
i:=Pos( '$EXITFOR', C )+8;
j:=ReplaceConds( C, S, i);
insert( ', '+IntToStr( ForStack.Top), S, j );
end
{ Replace $ContFor condition
Warning: Condition can be absent.
if there is no condition, insert '@'- unconditional jump sign
otherwise replace the condition in accordance with
Conds/Repls tables.
}
else if Pos( '$CONTFOR', C )<>0 then begin
i:=Pos( '$CONTFOR', C )+8;
j:=ReplaceConds( C, S, i);
insert( ', '+IntToStr( ForStack.Top), S, j );
end
{ Process $Step word
}
else if Pos( '$STEP', C )<>0 then begin
i:=Pos( '$STEP', C );
insert( ' '+IntToStr( ForStack.Pop), S, i+5 );
end
{ Process $Loop word
}
else if Pos( '$LOOP', C )<>0 then begin
i:=Pos( '$LOOP', C );
insert( ' '+IntToStr( ForStack.Pop), S, i+5 );
end
{ Restore registers
}
else if Pos( 'RESTORE', C )<>0 then begin
i:=Pos( 'RESTORE', C );
delete( S, i, 7 );
insert( 'Pop', S, i );
Insert( StyStack.Pop, S, i+3 );
end
{ Push registers and save reversed order of them
}
else if Pos( 'STORE', C )<>0 then begin
i:=Pos( 'STORE', C );
delete( S, i, 5 );
insert( 'Push', S, i );
C:=''; { Reversed order string }
i:=i+4;
j:=i; { Start index }
while j<=Length(S) do begin { Replace all comma to blank }
if S[j]=',' then S[j]:=' ';
inc(j);
end;
{ Take the each word and insert it at the begining of C }
while i<=Length(S) do begin
{ Pass through all blanks and tabs }
while (i<=Length(S)) and (S[i]<=' ') do Inc( i );
{ Get current word }
R:='';
while (i<=Length(S)) and (S[i]>' ') do begin
R:=R+S[i];
Inc( i );
end;
{ Insert the word at the begining of the register's string }
Insert( ' '+R+' ', C, 1 );
inc(i);
end;
StyStack.Push(C); { Put the registers string into the stack }
end;
writeln( S );
end;
end.
|
unit Wwstr;
{
//
// Commonly used string manipulation functions
//
// Copyright (c) 1995 by Woll2Woll Software
//
}
interface
uses classes, dialogs, wwtypes;
type
strCharSet = Set of char;
procedure strBreakApart(s: string; delimeter: string; parts: TStrings);
Function strGetToken(s: string; delimeter: string; var APos: integer): string;
Procedure strStripPreceding(var s: string; delimeter: strCharSet);
Procedure strStripTrailing(var s: string; delimeter: strCharSet);
Procedure strStripWhiteSpace(var s: string);
Function strRemoveChar(str: string; removeChar: char): string;
Function strReplaceChar(field1Name: string; removeChar, replaceChar: char): string;
Function strReplaceCharWithStr(str: string; removeChar: char;replaceStr: string): string;
Function wwEqualStr(s1, s2: string): boolean;
Function strCount(s: string; delimeter: char): integer;
Function strWhiteSpace : strCharSet;
Function wwGetWord(s: string; var APos: integer; Options: TwwGetWordOptions;
DelimSet: strCharSet): string;
Function strTrailing(s: string; delimeter: char): string;
implementation
uses sysutils;
Function strWhiteSpace : strCharSet;
begin
Result := [' ',#9];
end;
Function strGetToken(s: string; delimeter: string; var APos: integer): string;
var tempStr: string;
endStringPos: integer;
begin
result:= '';
if APos<=0 then exit;
if APos>length(s) then exit;
tempStr:= copy(s, APos, length(s)+1-APos);
{Converts to Uppercase for check if delimeter more than one character}
if (length(delimeter)=1) then
{$IFNDEF VER100}
endStringPos:= pos(delimeter, tempStr)
{$ELSE}
endStringPos:= AnsiPos(delimeter, tempStr)
{$ENDIF}
else begin
delimeter := ' ' + delimeter + ' ';
{$IFNDEF VER100}
endStringPos:= pos(UpperCase(delimeter),UpperCase(tempStr));
{$ELSE}
endStringPos:= AnsiPos(UpperCase(delimeter),UpperCase(tempStr));
{$ENDIF}
end;
if endStringPos<=0 then begin
result:= tempStr;
APos:= -1;
end
else begin
result:= copy(tempStr, 1, endStringPos-1);
APos:= APos + endStringPos + length(delimeter) - 1;
end
end;
procedure strBreakApart(s: string; delimeter : string; parts : TStrings);
var curpos: integer;
curStr: string;
begin
parts.clear;
curStr:= s;
repeat
{$IFNDEF VER100}
curPos:= pos(delimeter, curStr);
{$ELSE}
curPos:= AnsiPos(delimeter, curStr);
{$ENDIF}
if (curPos>0) then begin
parts.add(copy(curStr, 1, curPos-1));
curStr:= copy(curStr, curPos+1, length(curStr)-(curPos));
end
else parts.add(curStr);
until curPos=0;
end;
Procedure strStripWhiteSpace(var s: string);
var tempstr: string;
begin
tempstr := s;
strStripPreceding(tempstr,strWhiteSpace);
strStripTrailing(tempstr,strWhiteSpace);
s := tempstr;
end;
Procedure strStripPreceding(var s: string; delimeter: strCharSet);
var i,len: integer;
begin
i:= 1;
len:= length(s);
while (i<=length(s)) and (s[i] in delimeter) do i:= i+1;
if ((len<>0) and (i<=len)) then
s:= copy(s,i,len-i+1)
else if (len<>0) then s:='';
end;
Procedure strStripTrailing(var s: string; delimeter: strCharSet);
var len: integer;
begin
len:= length(s);
while (len>0) and (s[len] in delimeter) do len:= len-1;
{$IFDEF WIN32}
setLength(s, len);
{$ELSE}
s[0]:= char(len);
{$ENDIF}
end;
Function strRemoveChar(str: string; removeChar: char): string;
var i,j: integer;
s: string;
begin
j:= 0;
{$IFDEF WIN32}
setLength(s, length(str));
{$ENDIF}
for i:= 1 to length(str) do begin
if (str[i] <> removeChar) then
begin
j:= j + 1;
s[j]:= str[i]
end
end;
{$IFDEF WIN32}
setLength(s, j);
{$ELSE}
s[0]:= char(j);
{$ENDIF}
result:= s;
end;
Function strReplaceChar(field1Name: string; removeChar, replaceChar: char): string;
var i,j: integer;
s: string;
begin
j:= 0;
{$IFDEF WIN32}
setLength(s, length(field1name));
{$ENDIF}
for i:= 1 to length(field1Name) do begin
j:= j + 1;
if (field1Name[i] <> removeChar) then
s[j]:= field1Name[i]
else s[j]:= replaceChar;
end;
{$IFDEF WIN32}
setLength(s, j);
{$ELSE}
s[0]:= char(j);
{$ENDIF}
result:= s;
end;
Function strReplaceCharWithStr(str: string; removeChar: char;replaceStr: string): string;
var i: integer;
begin
Result := '';
for i:= 1 to length(str) do begin
if (str[i] <> removeChar) then
Result := Result + str[i]
else Result:= Result + replaceStr;
end;
end;
Function strAddDoublequote(str: string):string;
var i,j: integer;
s: string;
begin
j:= 0;
{ s:='';}
for i:= 1 to length(str) do begin
end;
{$IFDEF WIN32}
setLength(s, length(str));
{$ENDIF}
for i:= 1 to length(str) do begin
j:= j + 1;
if (str[i] <> '''') then
s[j]:= str[i]
else begin
s[j]:= str[i];
s[j+1]:=str[i];
j:= j+1;
end;
end;
{$IFDEF WIN32}
setLength(s, j);
{$ELSE}
s[0]:= char(j);
{$ENDIF}
result:= s;
end;
Function wwEqualStr(s1, s2: string): boolean;
begin
result:= uppercase(s1)=uppercase(s2);
end;
Function strCount(s: string; delimeter: char): integer;
var i, count: integer;
begin
count:= 0;
for i:= 1 to length(s) do
if s[i]=delimeter then inc(count);
result:= count;
end;
Function wwGetWord(s: string; var APos: integer;
Options: TwwGetWordOptions; DelimSet: strCharSet): string;
var i: integer;
Function max(x,y: integer): integer;
begin
if x>y then result:= x
else result:= y;
end;
Procedure StripQuotes;
begin
if not (wwgwStripQuotes in Options) then exit;
if (Result[1]='"') or (Result[1]='''') then
if (Result[length(Result)] = '"') or
(Result[length(Result)] = '''') then
Result:= copy(Result, 2, length(Result)-2)
else
Result:= copy(Result, 2, length(Result)-1);
end;
begin
result:= '';
if APos<=0 then exit;
if APos>length(s) then exit;
i:= APos;
if (wwgwSkipLeadingBlanks in Options) then
begin
while (i<=length(s)) and ((s[i]=' ') or (s[i]=#9)) do inc(i);
APos:= i;
end;
if (wwgwQuotesAsWords in Options) then
begin
if s[i]='"' then begin
inc(i);
while (i<=length(s)) and (s[i]<>'"') do inc(i);
if s[i]='"' then begin
result:= copy(s, APos, i+1-APos);
APos:= i+1;
end
else if (i>length(s)) then begin
result:= copy(s, APos, length(s));
APos:= length(s)+1;
end;
StripQuotes;
exit;
end
end;
while (i<=length(s)) and (s[i] in [#33..#255]) do begin
if (s[i] in DelimSet) then break
else inc(i);
end;
result:= copy(s, APos, max(i-APos, 1));
if length(result)>1 then APos:= i
else APos:= i+1;
end;
Function strTrailing(s: string; delimeter: char): string;
var apos: integer;
begin
apos:= pos(s, delimeter);
if apos>=1 then
result:= copy(s, apos+1, length(s)-apos)
else result:= '';
end;
end.
|
namespace Events;
interface
uses
System.Windows.Forms,
System.Drawing,
Events.EventClasses;
type
{ MainForm }
MainForm = class(System.Windows.Forms.Form)
{$REGION Windows Form Designer generated fields}
private
button1: System.Windows.Forms.Button;
components: System.ComponentModel.Container := nil;
method button1_Click(sender: System.Object; e: System.EventArgs);
method InitializeComponent;
{$ENDREGION}
protected
method Dispose(aDisposing: Boolean); override;
public
constructor;
class method Main;
{ The following method will be assigned to an instance of
SimpleClassWithEvents and will provide an implementation for
the delegate OnSetName }
method MyCustomSetName(Sender: SimpleClassWithEvents; var aNewName: String);
end;
implementation
{$REGION Construction and Disposition}
constructor MainForm;
begin
InitializeComponent();
end;
method MainForm.Dispose(aDisposing: boolean);
begin
if aDisposing then begin
if assigned(components) then
components.Dispose();
end;
inherited Dispose(aDisposing);
end;
{$ENDREGION}
{$REGION Windows Form Designer generated code}
method MainForm.InitializeComponent;
begin
var resources: System.ComponentModel.ComponentResourceManager := new System.ComponentModel.ComponentResourceManager(typeOf(MainForm));
self.button1 := new System.Windows.Forms.Button();
self.SuspendLayout();
//
// button1
//
self.button1.Location := new System.Drawing.Point(47, 50);
self.button1.Name := 'button1';
self.button1.Size := new System.Drawing.Size(150, 23);
self.button1.TabIndex := 0;
self.button1.Text := 'Test Events';
self.button1.Click += new System.EventHandler(@self.button1_Click);
//
// MainForm
//
self.AutoScaleBaseSize := new System.Drawing.Size(5, 13);
self.ClientSize := new System.Drawing.Size(244, 122);
self.Controls.Add(self.button1);
self.FormBorderStyle := System.Windows.Forms.FormBorderStyle.FixedDialog;
self.Icon := (resources.GetObject('$this.Icon') as System.Drawing.Icon);
self.MaximizeBox := false;
self.Name := 'MainForm';
self.Text := 'Events Sample';
self.ResumeLayout(false);
end;
{$ENDREGION}
{$REGION Application Entry Point}
[STAThread]
class method MainForm.Main;
begin
Application.EnableVisualStyles();
try
with lForm := new MainForm() do
Application.Run(lForm);
except
on E: Exception do begin
MessageBox.Show(E.Message);
end;
end;
end;
{$ENDREGION}
method MainForm.button1_Click(sender: System.Object; e: System.EventArgs);
var dummy : SimpleClassWithEvents;
begin
dummy := new SimpleClassWithEvents;
{ Notice the += operator used to assign delegates. Each event can
have multiple handler hooked up to it, and += is used to add one event
to the list. Conversely, -= could be used to remove a particular
handler. }
dummy.OnSetName += MyCustomSetName;
{ If you un-comment this line, MyCustomSetName will be called twice when
we set a value to dummy.Name. }
//dummy.OnSetName += MyCustomSetName;
dummy.Name := 'Jack London';
end;
method MainForm.MyCustomSetName(Sender: SimpleClassWithEvents; var aNewName: string);
begin
MessageBox.Show('Setting Name from '+Sender.Name+' to '+aNewName);
end;
end. |
unit uValidSenha;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, DB, DBTables, SysUtils, Dialogs, ExtCtrls, Mask, ADODB, siComp,
siLangRT, PaiDeForms;
type
TValidSenha = class(TFrmParentForms)
Label1: TLabel;
EditPassword: TEdit;
Panel1: TPanel;
Panel9: TPanel;
Panel3: TPanel;
quSaveSenha: TADOQuery;
Label2: TLabel;
btOK: TButton;
btCancel: TButton;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btOKClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
MyExpDate : TDateTime;
function ValidateSenha(ExpDate : TDateTime; Password : String) : Boolean;
public
{ Public declarations }
IsSave : Boolean;
function Start(ExpDate : TDateTime) : boolean;
end;
implementation
uses uDM, uMsgBox, Math, uMsgConstant, uDMGlobal;
{$R *.DFM}
function TValidSenha.ValidateSenha(ExpDate : TDateTime; Password : String) : Boolean;
var
Day, Month, Year : Word;
AuxValue : Double;
begin
DecodeDate(ExpDate, Year, Month, Day);
AuxValue := Ln(Year) + Power(LnXP1(Month), Ln(Day));
Result := (Trim(Password) = FloatToStr(AuxValue));
end;
function TValidSenha.Start(ExpDate : TDateTime) : boolean;
begin
MyExpDate := ExpDate;
Result := (ShowModal = mrOk);
end;
procedure TValidSenha.FormShow(Sender: TObject);
begin
EditPassword.SetFocus;
end;
procedure TValidSenha.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TValidSenha.btOKClick(Sender: TObject);
begin
if not ValidateSenha(MyExpDate, EditPassword.Text) then
begin
MsgBox(MSG_CRT_ERROR_STACK_SIZE, vbOkOnly + vbInformation);
Exit;
end;
// Grava a Senha
if IsSave then
begin
with quSaveSenha do
begin
Parameters.ParamByName('DataExp').Value := MyExpDate;
Parameters.ParamByName('Password').Value := Trim(EditPassword.Text);
ExecSQL;
end;
end;
ModalResult := mrOK;
end;
procedure TValidSenha.btCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TValidSenha.FormCreate(Sender: TObject);
begin
inherited;
IsSave := False;
end;
end.
|
unit DSA.Sorts.InsertionSort;
interface
uses
System.SysUtils,
DSA.Interfaces.Comparer,
DSA.Utils;
type
TInsertionSort<T> = class
private type
TArr_T = TArray<T>;
ICmp_T = IComparer<T>;
var
class procedure __swap(var a, b: T);
public
/// <summary> 对arr数组进行插入排序 </summary>
class procedure Sort(var arr: TArr_T; cmp: ICmp_T); overload;
/// <summary> 对arr[l...r]范围的数组进行插入排序 </summary>
class procedure Sort(var arr: TArr_T; l, r: integer; cmp: ICmp_T); overload;
/// <summary> 优化插入排序 </summary>
class procedure Sort_Adv(var arr: TArr_T; cmp: ICmp_T);
end;
procedure Main;
implementation
uses
DSA.Sorts.SelectionSort;
type
TSelectionSort_int = TSelectionSort<integer>;
TInsertionSort_int = TInsertionSort<integer>;
procedure Main;
var
arr1, arr2, arr3: TArray_int;
n: integer;
SortTestHelper: TSortTestHelper_int;
ts1: TSelectionSort_int;
ts2: TInsertionSort_int;
begin
n := 20000;
SortTestHelper := TSortTestHelper_int.Create;
arr1 := SortTestHelper.GenerateNearlyOrderedArray(n, 1000);
arr2 := SortTestHelper.CopyArray(arr1);
arr3 := SortTestHelper.CopyArray(arr1);
ts1 := TSelectionSort_int.Create;
SortTestHelper.TestSort('SelectionSort'#9#9, arr1, ts1.Sort);
ts1.Free;
ts2 := TInsertionSort_int.Create;
SortTestHelper.TestSort('InsertionSort'#9#9, arr2, ts2.Sort);
SortTestHelper.TestSort('InsertionSort_Adv'#9, arr3, ts2.Sort_Adv);
ts2.Free;
end;
{ TInsertionSort<T> }
class procedure TInsertionSort<T>.Sort(var arr: TArr_T; cmp: ICmp_T);
var
i, j: integer;
begin
for i := 1 to Length(arr) - 1 do
begin
// 寻找元素arr[i]合适的插入位置
for j := i downto 1 do
begin
if cmp.Compare(arr[j], arr[j - 1]) < 0 then
__swap(arr[j], arr[j - 1])
else
Break;
end;
end;
end;
class procedure TInsertionSort<T>.Sort(var arr: TArr_T; l, r: integer;
cmp: ICmp_T);
var
i, j: integer;
e: T;
begin
for i := l + 1 to r do
begin
e := arr[i];
j := i;
while (j > l) and (cmp.Compare(arr[j - 1], e) > 0) do
begin
arr[j] := arr[j - 1];
Dec(j);
end;
arr[j] := e;
end;
end;
class procedure TInsertionSort<T>.Sort_Adv(var arr: TArr_T; cmp: ICmp_T);
var
i, j: integer;
e: T;
begin
for i := 1 to Length(arr) - 1 do
begin
e := arr[i];
j := i;
while (j > 0) and (cmp.Compare(e, arr[j - 1]) < 0) do
begin
arr[j] := arr[j - 1];
Dec(j);
end;
arr[j] := e;
end;
end;
class procedure TInsertionSort<T>.__swap(var a, b: T);
var
tmp: T;
begin
tmp := a;
a := b;
b := tmp;
end;
end.
|
unit RestServerMethodsUnit;
interface
uses
// RTL
System.SysUtils,
System.Classes,
System.StrUtils,
Vcl.Forms,
Vcl.Dialogs,
Vcl.Controls,
Vcl.StdCtrls,
Vcl.ExtCtrls,
// mORMot
mORMot,
mORMotHttpServer,
SynCommons,
// Custom
RestMethodsInterfaceUnit;
type
TCustomRecord = record helper for rCustomRecord
procedure FillResultFromServer();
end;
TRestMethods = class(TInjectableObjectRest, IRestMethods)
public
function HelloWorld(): string;
function Sum(val1, val2: Double): Double;
function GetCustomRecord(): rCustomRecord;
function SendCustomRecord(const CustomResult: rCustomRecord): Boolean;
function SendMultipleCustomRecords(const CustomResult: rCustomRecord; const CustomComplicatedRecord: rCustomComplicatedRecord): Boolean;
end;
implementation
{ TCustomResultSrv }
procedure TCustomRecord.FillResultFromServer();
var
i: Integer;
begin
ResultCode := 200;
ResultStr := 'Awesome';
ResultTimeStamp := Now();
SetLength(ResultArray, 3);
for i := 0 to 2 do
ResultArray[i] := 'str_' + i.ToString();
end;
{ TServiceServer }
// [!] ServiceContext can be used from any method to access low level request data
// Test 2
function TRestMethods.HelloWorld(): string;
begin
Result := 'Hello world';
end;
// Test 2.1
function TRestMethods.Sum(val1, val2: Double): Double;
begin
Result := val1 + val2;
end;
// Test 2.2
function TRestMethods.GetCustomRecord(): rCustomRecord;
begin
Result.FillResultFromServer();
end;
// Test 2.3
function TRestMethods.SendCustomRecord(const CustomResult: rCustomRecord): Boolean;
begin
Result := True;
end;
// Test 2.4
function TRestMethods.SendMultipleCustomRecords(const CustomResult: rCustomRecord; const CustomComplicatedRecord: rCustomComplicatedRecord): Boolean;
begin
Result := True;
end;
end.
|
(* WordCounter: HDO, 2003-02-28 *)
(* ----------- *)
(* Template for programs that count words in text files. *)
(*===============================================================*)
PROGRAM WordCounter;
USES
WinCrt, Timer, WordReader;
VAR
w: Word;
n: LONGINT;
BEGIN (*WordCounter*)
WriteLn('WordCounter:');
OpenFile('Kafka.txt', toLower);
StartTimer;
n := 0;
ReadWord(w);
WHILE w <> '' DO BEGIN
n := n + 1;
(*insert word in data structure and count its occurence*)
ReadWord(w);
END; (*WHILE*)
StopTimer;
CloseFile;
WriteLn('number of words: ', n);
WriteLn('elapsed time: ', ElapsedTime);
(*search in data structure for word with max. occurrence*)
END. (*WordCounter*) |
{*
* Outliner Lighto
* Copyright (C) 2011 Kostas Michalopoulos
*
* 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.
*
* Kostas Michalopoulos <badsector@runtimelegend.com>
*}
unit UI;
interface
{$MODE OBJFPC}{$H+}
uses Video;
var
FColor, BColor, CAttr: Integer;
CurX, CurY: Integer;
DoWrites: Boolean;
procedure GotoXY(X, Y: Integer);
procedure InvertCharAt(X, Y: Integer);
procedure Color(F, B: Integer);
procedure WriteChar(Ch: Char);
procedure WriteStr(Str: string);
procedure Top(s: string);
procedure Status(s: string);
procedure ClearEOL;
procedure ClrTo(x1, x2, y: Integer);
procedure ClearBackScreen;
implementation
procedure GotoXY(X, Y: Integer);
begin
if X < 0 then X:=0 else if X > ScreenWidth - 1 then X:=ScreenWidth - 1;
if Y < 0 then Y:=0 else if Y > ScreenHeight - 1 then Y:=ScreenHeight - 1;
CurX:=X;
CurY:=Y;
end;
procedure InvertCharAt(X, Y: Integer);
var
A: Integer;
begin
if (X < 0) or (Y < 0) or (X >= ScreenWidth) or (Y >= ScreenHeight) then Exit;
A:=Y*ScreenWidth + X;
if DoWrites then begin
VideoBuf^[A]:=(VideoBuf^[A] and $FF) or ((not (VideoBuf^[A] shr 8)) shl 8);
UpdateScreen(False);
end;
end;
procedure Color(F, B: Integer);
begin
FColor:=F;
BColor:=B;
CAttr:=F + (B shl 4);
end;
procedure WriteChar(Ch: Char);
var
A: Integer;
begin
A:=CurY*ScreenWidth + CurX;
if DoWrites then
VideoBuf^[A]:=Byte(Ch) or (CAttr shl 8);
if CurX < ScreenWidth - 1 then Inc(CurX);
end;
procedure WriteStr(Str: string);
var
i: Integer;
begin
for i:=1 to Length(Str) do WriteChar(Str[i]);
end;
procedure Top(s: string);
begin
Color(0, 7);
GotoXY(0, 0);
WriteStr(s);
ClearEOL;
end;
procedure Status(s: string);
var
i: Integer;
Hi: Boolean;
begin
Hi:=False;
Color(0, 7);
GotoXY(0, ScreenHeight - 1);
for i:=1 to Length(s) do begin
if s[i]='~' then begin
Hi:=not Hi;
if Hi then Color(4, 7) else Color(0, 7);
end else WriteChar(s[i]);
end;
Color(0, 7);
ClearEOL;
end;
procedure ClearEOL;
var
x: Integer;
begin
if CurX=ScreenWidth - 1 then Exit;
for x:=CurX to ScreenWidth - 1 do WriteChar(' ');
end;
procedure ClrTo(x1, x2, y: Integer);
var
x: Integer;
begin
GotoXY(x1, y);
for x:=x1 to x2 do WriteChar(' ');
end;
procedure ClearBackScreen;
var
i: Integer;
begin
for i:=0 to ScreenWidth*ScreenHeight - 1 do VideoBuf^[i]:=32 or (7 shl 8);
GotoXY(0, 0);
end;
initialization
DoWrites:=True;
end.
|
unit Entities;
interface
uses
Aurelius.Mapping.Attributes;
type
[Entity]
[Automapping]
TPerson = class
private
FId: integer;
FLastName: string;
FFirstName: string;
FEmail: string;
public
property Id: integer read FId;
property LastName: string read FLastName write FLastName;
property FirstName: string read FFirstName write FFirstName;
property Email: string read FEmail write FEmail;
end;
implementation
end.
|
unit SDUMRUList;
interface
uses
Classes,
IniFiles,
Menus,
SDURegistry;
type
{$TYPEINFO ON}// Needed to allow "published"
// Forward declaration
TSDUMRUList = class ;
TSDUMRUItemClickEvent = procedure(mruList: TSDUMRUList; idx: Integer) of object;
TSDUMRUList = class
PROTECTED
FMaxItems: Cardinal;
FItems: TStringList;
FOnClick: TSDUMRUItemClickEvent;
procedure SetMaxItems(cnt: Cardinal);
procedure ClearItemsBeyondMax();
procedure MRUItemClick(Sender: TObject);
PUBLIC
constructor Create();
destructor Destroy(); OVERRIDE;
procedure InsertAfter(mnuItem: TMenuItem);
procedure InsertUnder(mnuItem: TMenuItem);
procedure RemoveMenuItems(mnu: TMenu); OVERLOAD;
procedure RemoveMenuItems(mnu: TMenuItem); OVERLOAD;
procedure Add(item: String); OVERLOAD;
procedure Add(items: TStringList); OVERLOAD;
function Load(iniFile: TCustomIniFile; MRUSection: String = 'MRU'): Boolean; OVERLOAD;
function Load(reg: TSDURegistry; MRUSubKey: String = 'MRU'): Boolean; OVERLOAD;
// Warning: The SaveMRU(...) functions will *delete* the section/subkey
// specified, and recreate it.
function Save(iniFile: TCustomIniFile; MRUSection: String = 'MRU'): Boolean; OVERLOAD;
function Save(reg: TSDURegistry; MRUSubKey: String = 'MRU'): Boolean; OVERLOAD;
PUBLISHED
property MaxItems: Cardinal Read FMaxItems Write SetMaxItems;
property Items: TStringList Read FItems Write FItems;
property OnClick: TSDUMRUItemClickEvent Read FOnClick Write FOnClick;
end;
implementation
uses
SysUtils;
const
// Tag to identify MRU menuitems.
// Low WORD is holds index into "Items"
MRUL_TAG = $12340000;
DEFAULT_MRU_LENGTH = 5;
constructor TSDUMRUList.Create();
begin
FItems := TStringList.Create();
FMaxItems := DEFAULT_MRU_LENGTH;
end;
destructor TSDUMRUList.Destroy();
begin
FItems.Free();
end;
procedure TSDUMRUList.InsertAfter(mnuItem: TMenuItem);
var
i: Integer;
tmpItem: TMenuItem;
parentMenuItem: TMenuItem;
mnuIdx: Integer;
begin
if (items.Count > 0) then begin
parentMenuItem := mnuItem.Parent;
mnuIdx := mnuItem.MenuIndex;
tmpItem := TMenuItem.Create(nil);
tmpItem.Caption := '-';
tmpItem.Tag := MRUL_TAG;
Inc(mnuIdx);
parentMenuItem.Insert(mnuIdx, tmpItem);
for i := 0 to (items.Count - 1) do begin
tmpItem := TMenuItem.Create(nil);
tmpItem.Caption := '&' + IntToStr(i + 1) + ' ' + Items[i];
tmpItem.Tag := MRUL_TAG + i;
tmpItem.OnClick := MRUItemClick;
Inc(mnuIdx);
parentMenuItem.Insert(mnuIdx, tmpItem);
end;
end;
end;
procedure TSDUMRUList.InsertUnder(mnuItem: TMenuItem);
var
i: Integer;
tmpItem: TMenuItem;
begin
for i := 0 to (items.Count - 1) do begin
tmpItem := TMenuItem.Create(mnuItem);
tmpItem.Caption := '&' + IntToStr(i + 1) + ' ' + Items[i];
tmpItem.Tag := MRUL_TAG + i;
tmpItem.OnClick := MRUItemClick;
mnuItem.Add(tmpItem);
end;
end;
procedure TSDUMRUList.RemoveMenuItems(mnu: TMenu);
var
i: Integer;
begin
for i := (mnu.Items.Count - 1) downto 0 do begin
RemoveMenuItems(mnu.Items[i]);
end;
end;
// Remove any subitems beneath this menuitem
procedure TSDUMRUList.RemoveMenuItems(mnu: TMenuItem);
var
i: Integer;
begin
for i := (mnu.Count - 1) downto 0 do begin
RemoveMenuItems(mnu.Items[i]);
if ((mnu.Items[i].tag and MRUL_TAG) = MRUL_TAG) then begin
mnu.Delete(i);
end;
end;
end;
procedure TSDUMRUList.SetMaxItems(cnt: Cardinal);
begin
FMaxItems := cnt;
ClearItemsBeyondMax();
end;
procedure TSDUMRUList.Add(items: TStringList);
var
i: Integer;
begin
for i := 0 to (items.Count - 1) do begin
Add(items[i]);
end;
end;
procedure TSDUMRUList.Add(item: String);
var
idx: Integer;
begin
// Delete any existing instance of the item
idx := Items.IndexOf(item);
if (idx >= 0) then begin
Items.Delete(idx);
end;
// Add the item to the head of the list
Items.Insert(0, item);
ClearItemsBeyondMax();
end;
// If there are more items that the max allowed, delete the oldest
procedure TSDUMRUList.ClearItemsBeyondMax();
var
i: Integer;
begin
for i := (Items.Count - 1) downto MaxItems do begin
Items.Delete(i);
end;
end;
procedure TSDUMRUList.MRUItemClick(Sender: TObject);
var
idx: Integer;
begin
if (Sender is TMenuItem) then begin
idx := TMenuItem(Sender).Tag and $FFFF;
if Assigned(FOnClick) then begin
FOnClick(self, idx);
end;
end;
end;
function TSDUMRUList.Load(iniFile: TCustomIniFile; MRUSection: String = 'MRU'): Boolean;
var
i: Integer;
cnt: Integer;
readItem: String;
begin
Result := False;
try
MaxItems := iniFile.ReadInteger(MRUSection, 'MaxItems', MaxItems);
cnt := iniFile.ReadInteger(MRUSection, 'Items', 0);
FItems.Clear();
for i := 0 to (cnt - 1) do begin
readItem := iniFile.ReadString(MRUSection, IntToStr(i), '');
FItems.Add(readItem);
end;
Result := True;
except
on E: Exception do begin
// Do nothing; just swallow the error - Result already set to FALSE
end;
end;
end;
function TSDUMRUList.Load(reg: TSDURegistry; MRUSubKey: String = 'MRU'): Boolean;
var
i: Integer;
cnt: Integer;
readItem: String;
begin
Result := False;
try
if reg.OpenKey(MRUSubKey, False) then begin
MaxItems := reg.ReadInteger('MaxItems', MaxItems);
cnt := reg.ReadInteger('Items', 0);
FItems.Clear();
for i := 0 to (cnt - 1) do begin
readItem := reg.ReadString(IntToStr(i), '');
FItems.Add(readItem);
end;
Result := True;
end;
except
on E: Exception do begin
// Do nothing; just swallow the error - Result already set to FALSE
end;
end;
end;
function TSDUMRUList.Save(iniFile: TCustomIniFile; MRUSection: String = 'MRU'): Boolean;
var
i: Integer;
begin
Result := False;
try
try
iniFile.EraseSection(MRUSection);
except
on E: Exception do begin
// Do nothing; section may not have existed
end;
end;
iniFile.WriteInteger(MRUSection, 'MaxItems', MaxItems);
iniFile.WriteInteger(MRUSection, 'Items', Items.Count);
for i := 0 to (FItems.Count - 1) do begin
iniFile.WriteString(MRUSection, IntToStr(i), Items[i]);
end;
Result := True;
except
on E: Exception do begin
// Do nothing; just swallow the error - Result already set to FALSE
end;
end;
end;
function TSDUMRUList.Save(reg: TSDURegistry; MRUSubKey: String = 'MRU'): Boolean;
var
i: Integer;
begin
Result := False;
try
reg.DeleteKey(MRUSubKey);
if reg.OpenKey(MRUSubKey, True) then begin
reg.WriteInteger('MaxItems', MaxItems);
reg.WriteInteger('Items', Items.Count);
for i := 0 to (FItems.Count - 1) do begin
reg.WriteString(IntToStr(i), Items[i]);
end;
Result := True;
end;
except
on E: Exception do begin
// Do nothing; just swallow the error - Result already set to FALSE
end;
end;
end;
end.
|
{
Update Constraint File script Version 1.0
In brief, you have the ability to change the swap group Ids for the pins of a
FPGA component on the PCB document without invoking the FPGA Pin Swap Manager.
These swap group ids are stored as records in the constraint file
part of a configuration in the FPGA project.
The sequence is as follows;
1) select pads
2) run script (which i would hook to a shortcut key)
3) pops a dialog where you type in a swap group number
4) updates/inserts SWAPID type records in this specified constraint file
if there are multiple configurations for this project...
you have the ability to choose which constraint file that targets the FPGA device.
Major limitation at the moment - for multiple records with same TargetIDs
the first SWAPIDs found for same TargetIDs are replaced only.
A warning dialog is invoked and scirpt is closed if the following conditions are met:
No PCB document
No selected pads on the pcb
No configurations
No Constraint files
Copyright Altium Ltd (c) 2005.
}
{..............................................................................}
{..............................................................................}
Var
SwapIDValue : String;
SL : TStringList;
{..............................................................................}
{..............................................................................}
Procedure UpdateConstraintFilesWithNewGroupSwapIDs;
Var
ConstraintFileCount : Integer;
Workspace : IWorkspace;
ConfigCount : Integer;
Config : IConfiguration;
FirstTargetDeviceName : String;
First : Boolean;
Board : IPCB_Board;
Pad : IPCB_Pad;
Iterator : IPCB_BoardIterator;
I,J : Integer;
Begin
// Retrieve the current board
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then
Begin
Showmessage('This is not a PCB document!');
Exit;
End;
// Retrieve the configurations and their constraint files.
Workspace := GetWorkSpace;
If Workspace = Nil Then Exit;
Workspace.DM_FocusedProject.DM_Compile;
ConfigCount := Workspace.DM_FocusedProject.DM_ConfigurationCount;
If ConfigCount = 0 Then
Begin
ShowMessage('No configuration file found!');
Exit;
End;
For I := 0 to ConfigCount - 1 Do
Begin
Config := Workspace.DM_FocusedProject.DM_Configurations(I);
ConstraintFileCount := Config.DM_ConstraintsFileCount;
If ConstraintFileCount = 0 Then
Begin
ShowMessage('No constraint files found!');
Exit;
End;
First := True;
For J := 0 to ConstraintFileCount - 1 Do
Begin
If First Then
Begin
First := False;
FirstTargetDeviceName := Config.DM_GetTargetDeviceName;
End;
fUpdate.cbConstraintFiles.items.add(ExtractFileName(Config.DM_ConstraintsFilePath(j)));
End;
End;
fUpdate.cbConstraintFiles.itemindex := 0;
fUpdate.labelTargetDeviceName.Caption := 'Target Device Name: ' + FirstTargetDeviceName;
// Retrieve the board iterator
Iterator := Board.BoardIterator_Create;
Iterator.AddFilter_ObjectSet(MkSet(ePadObject));
Iterator.AddFilter_LayerSet(AllLayers);
Iterator.AddFilter_Method(eProcessAll);
// Look for selected pads and update the List box
I := 0;
Pad := Iterator.FirstPCBObject;
While (Pad <> Nil) Do
Begin
If Pad.Selected then
Begin
fUpdate.clbPads.Items.Add[Pad.Name];
fUpdate.clbPads.Checked[i] := True;
Inc(I);
End;
Pad := Iterator.NextPCBObject;
End;
Board.BoardIterator_Destroy(Iterator);
// if pad count zero then exit. whats the point!
If fUpdate.clbPads.items.count > 0 Then
Begin
SwapIDValue := IntToStr(fUpdate.editSwapID.Text);
fUpdate.ShowModal;
End
Else
Showmessage('No pads were selected!');
End;
{..............................................................................}
{..............................................................................}
procedure TfUpdate.cbConstraintFilesClick(Sender: TObject);
Var
Workspace : IWorkspace;
I,J : Integer;
ConstraintFileCount : Integer;
ConfigCount : Integer;
Config : IConfiguration;
ConstraintFileName : String;
Begin
ConstraintFilename := cbConstraintFiles.Items[cbConstraintFiles.ItemIndex];
Workspace := GetWorkSpace;
ConfigCount := Workspace.DM_FocusedProject.DM_ConfigurationCount;
For I := 0 to ConfigCount - 1 Do
Begin
Config := Workspace.DM_FocusedProject.DM_Configurations(I);
ConstraintFileCount := Config.DM_ConstraintsFileCount;
For J := 0 to ConstraintFileCount - 1 Do
Begin
If ConstraintFileName = ExtractFileName(Config.DM_ConstraintsFilePath(j)) Then
Begin
fUpdate.labelTargetDeviceName.Caption := 'Target Device Name: ' + Config.DM_GetTargetDeviceName;
Break;
End;
End;
End;
End;
{..............................................................................}
{..............................................................................}
Function UpdateConstraintRecords(AList: TCheckListBox, AFileName : String) : TStringList;
Var
I,J : Integer;
ARecord : String;
PinID : String;
ANewRecord : String;
TempList : TStringlist;
Begin
// populate temporary list with checked entries only.
TempList := TStringList.Create;
For j := 0 To aList.Count - 1 Do
If alist.Checked[j] Then
TempList.Add(AList.Items[j]);
SwapIDValue := fUpdate.EditSwapID.Text;
Try
SL := TStringList.Create;
SL.LoadFromFile(AFileName);
SL.SaveToFile(AFileName + 'BackUp'); // back up the original file!
// update existing TargetKind=Pin records
For I := 0 to SL.Count - 1 Do
Begin
ARecord := UpperCase(SL.Strings[i]);
If CheckNameAndValue(Trim(ARecord), 'RECORD','CONSTRAINT') Then
Begin
If CheckNameAndValue(Trim(ARecord), 'TARGETKIND','PIN') Then
Begin
//go thru the entries of the ListBoxPads.Items
J := 0;
While J < TempList.Count Do
Begin
PinId := TempList.Strings[j];
If CheckNameAndValue(Trim(ARecord),'TARGETID',PinID) Then
Begin
ANewRecord := UpdateOrInsertNameValue(Trim(ARecord),'SWAPID',SwapIDValue);
SL.Delete(I);
SL.Insert(I,ANewRecord);
// since the SwapID record has been updated,
// remove the pad item from the list.
TempList.Delete(J);
Break;
End
Else
Inc(J);
End;
End;
End;
End;
// insert new TargetKind=Pin records
// based on the pad entries in TempPadList
For j := 0 To TempList.Count - 1 Do
Begin
PinId := TempList.Strings[j];
ANewRecord := 'Record=Constraint | TargetKind=Pin | TargetId=' + PinID + ' | SWAPID=' + SwapIDValue;
SL.Add(ANewRecord);
End;
// display the new contents in the memo
fPreviewer.MemoConstraintFile.Text := SL.Text;
fPreviewer.ShowModal;
If fPreviewer.ModalResult = mrOk Then
SL.SaveToFile(AFileName);
Finally
TempList.Free;
SL.Free;
End;
End;
{..............................................................................}
{..............................................................................}
procedure TfUpdate.bOKClick(Sender: TObject);
Var
Workspace : IWorkspace;
ConstraintFileName : String;
ConfigCount : Integer;
Config : IConfiguration;
ConstraintFileCount : Integer;
I,J : Integer;
Begin
Workspace := GetWorkSpace;
ConfigCount := Workspace.DM_FocusedProject.DM_ConfigurationCount;
For I := 0 to ConfigCount - 1 Do
Begin
Config := Workspace.DM_FocusedProject.DM_Configurations(I);
ConstraintFileCount := Config.DM_ConstraintsFileCount;
//check if combolist item same as the constraint filename.
For J := 0 to ConstraintFileCount - 1 Do
If ExtractFileName(Config.DM_ConstraintsFilePath(j)) =
cbConstraintFiles.items(cbConstraintFiles.itemindex) Then
ConstraintFilename := Config.DM_ConstraintsFilePath(j);
End;
UpdateConstraintRecords(clbPads,ConstraintFileName);
Close;
End;
{..............................................................................}
{..............................................................................}
Procedure TfUpdate.Button2Click(Sender: TObject);
Begin
Close;
End;
{..............................................................................}
{..............................................................................}
procedure TfUpdate.bEnableAllClick(Sender: TObject);
var
I : Integer;
begin
For I := 0 to clbPads.Items.Count - 1 Do
clbPads.Checked[i] := True;
end;
{..............................................................................}
{..............................................................................}
procedure TfUpdate.bDisableAllClick(Sender: TObject);
var
I : Integer;
begin
For I := 0 to clbPads.Items.Count - 1 Do
clbPads.Checked[i] := False;
end;
{..............................................................................}
{..............................................................................}
procedure TfUpdate.UpDown1Changing(Sender: TObject; var AllowChange: Boolean);
begin
SwapIDValue := IntToStr(fUpdate.editSwapID.Text);
end;
{..............................................................................}
{..............................................................................}
{ Typical Constraint file with SWAPIDs
Record=Constraint | TargetKind=Pin | TargetId=10
Record=Constraint | TargetKind=Pin | TargetId=11
Record=Constraint | TargetKind=Pin | TargetId=15 | SWAPID=1
Record=Constraint | TargetKind=Pin | TargetId=16 | SWAPID=1
Record=Constraint | TargetKind=Pin | TargetId=17 | SWAPID=1
Record=Constraint | TargetKind=Pin | TargetId=18 | SWAPID=1
}
|
unit GorGraph;
interface
type
PBImage=^TBImage;
TImage=record {obrazek pomoci spojoveho seznamu,}
imgBegin,imgEnd:PBImage; {odpada omezeni 64kB}
dx,dy:integer; {dx,dy=velikosti obrazku}
end;
PFrame=^TFrame;
TAnim=record {animace pomoci spojoveho seznamu,}
imgBegin,imgEnd:PFrame; {jeden snimek <64kB}
Pos:PFrame; {Pos=ukazatel na pozici akt. snimku}
dx,dy:integer; {dx,dy=velikosti snimku}
end;
TFrame=record {snimek animace}
Image:pointer; {ukazatel na obrazek kompatibilni s PutImage}
IsNext:boolean; {je dalsi, pro cteni ze souboru}
Next:PFrame; {ukazatel na dalsi snimek}
end;
TBImage=record {blok(cast) obrazku TImage}
y1,y2:integer; {rozsah bloku}
size:word; {velikost obrazku}
Image:pointer; {ukazatel na obrazek kompatibilni s PutImage}
IsNext:boolean; {je dalsi, pro cteni ze souboru}
Next:PBImage;
end;
{Prevod integeru na string}
function SStr(i:longint):string;
{Zobrazeni obrazku PCX na pozici x1,y1. Do dx,dy se ulozi rozmery.
setpal povoluje nastaveni palety}
function DrawPCX (x1,y1:integer;filename:string;var dx,dy:integer;setpal:boolean):boolean;
{Okamzite zobrazeni blokoveho obrazku typu TImage pomoci nacteni ze souboru.
Do dx,dy se ulozi rozmery. BitBlt je zpusob vykresleni.}
function DrawGIM (x1,y1:integer;filename:string;var dx,dy:integer;BitBlt:word):boolean;
{Inicializace blokoveho obrazku typu TImage}
procedure NewBImage (var Image:TImage);
{Uvolneni blokoveho obrazku typu TImage}
procedure DisposeBImage (var Image:TImage);
{Sejmuti blokoveho obrazku typu TImage z obrazovky z obdelnika o
souradnicich x1,y1,x2,y2}
procedure GetBImage (x1,y1,x2,y2:integer;var Image:TImage);
{Zobrazeni blokoveho obrazku typu TImage ulozeneho v pameti v
promenne predane pomoci Image. BitBlt je zpusob vykresleni.}
procedure DrawBImage (x1,y1:integer;var Image:TImage;BitBlt:word);
{Inicializace animace s rozmery dx,dy}
procedure NewAnim (dx,dy:integer;var Anim:TAnim);
{Uvolneni animace}
procedure DisposeAnim (var Anim:TAnim);
{Pridani snimku do animace, sejmuteho z obrazovky z obdelnika o
souradnicich x,y,Anim.dx,Anim,dy}
procedure AddFrame (x,y:integer;var Anim:TAnim);
{Vykresleni snimku animace na pozici x,y. Je-li jump true, skoci na dalsi snimek}
procedure DrawFrame (x,y:integer;var Anim:TAnim;BitBlt:word;jump:boolean);
{Konverze PCX souboru na animaci}
procedure ConvertToAnim (filemask,filename:string);
{Nahrani animace ze souboru do Anim}
procedure LoadAnim (filename:string;var Anim:TAnim);
{Konverze PCX na blokovy obrazek}
procedure ConvertToBImage (filemask:string;filename:string);
{Nahrani blokoveho obrazku do Image}
procedure LoadBImage (filename:string;var Image:TImage);
{Zjisteni hodnoty pixelu z blokoveho obrazku ulozeneho v Image}
function GetBImPixel (x,y:integer;var Image:TImage):word;
{Zjisteni hodnoty pixelu obrazku kompatibilniho z PutImage ulozeneho v Image}
function GetImagePixel (x,y:integer;Image:pointer):word;
implementation
uses dos,graph,crt;
{$I SVGAUTIL.INC}
function SStr(i:longint):string;
var s:string;
begin
Str(i,s);
SStr:=s;
end;
{Nastaveni palety}
procedure SetDACPalette(NumOfColors:Word;var RGBBuf);
var Regs:Registers;
begin
with Regs do begin
AH:=$10;
AL:=$12;
ES:=Seg(RGBBuf);
DX:=Ofs(RGBBuf);
BX:=$00;
CX:=NumOfColors;
end;
Intr($10,Regs);
end;
procedure NewAnim (dx,dy:integer;var Anim:TAnim);
begin
Anim.imgBegin:=nil;
Anim.imgEnd:=nil;
Anim.Pos:=nil;
Anim.dx:=dx;
Anim.dy:=dy;
end;
procedure DisposeAnim (var Anim:TAnim);
var tmpFrame:PFrame;
begin
if Anim.imgBegin=nil then exit; {nic tam neni}
repeat
tmpFrame:=Anim.imgBegin;
Anim.imgBegin:=Anim.imgBegin^.Next;
FreeMem (tmpFrame^.Image,word(Anim.dx+1)*word(Anim.dy+1)+4);
Dispose (tmpFrame);
tmpFrame:=nil;
until Anim.imgBegin=nil;
end;
procedure AddFrame (x,y:integer;var Anim:TAnim);
var img:pointer;
size:longint;
tmpFrame:PFrame;
begin
New (tmpFrame);
size:=word(Anim.dx+1)*word(Anim.dy+1)+4; {velikost snimku}
if (size>MaxAvail) or (size>65500) then exit; {je dost pameti?}
GetMem(img,size); {alokace}
GetImage(x,y,x+Anim.dx,y+Anim.dy,img^); {sejmuti}
tmpFrame^.Image:=img;
tmpFrame^.IsNext:=false;
tmpFrame^.Next:=nil;
if Anim.imgBegin=nil then begin {pridani}
Anim.imgBegin:=tmpFrame;
Anim.Pos:=Anim.imgBegin;
Anim.imgEnd:=tmpFrame;
end else begin
Anim.imgEnd^.Next:=tmpFrame;
Anim.imgEnd^.IsNext:=true;
Anim.imgEnd:=tmpFrame;
end;
end;
procedure DrawFrame (x,y:integer;var Anim:TAnim;BitBlt:word;jump:boolean);
begin
if Anim.Pos<>nil then begin
PutImage (x,y,Anim.Pos^.Image^,BitBlt);
if jump then Anim.Pos:=Anim.Pos^.Next;
end else begin
PutImage (x,y,Anim.imgBegin^.Image^,BitBlt);
if jump then Anim.Pos:=Anim.imgBegin^.Next;
end;
end;
{Pridani lomitka na konec cesty}
function AddPSlash (path:string):string;
begin
if path[length(path)]<>'\' then AddPSlash:=path+'\' else AddPSlash:=path;
if path='' then AddPSlash:='';
end;
procedure ConvertToAnim (filemask,filename:string);
var srec:SearchRec;
tmpFrame:PFrame;
path:DirStr;
name:NameStr;
ext:ExtStr;
NumWrite:word;
Anim:TAnim;
dx,dy:integer;
f:file;
begin
FindFirst(filemask,AnyFile,srec); {nalezeni prvniho souboru}
FSplit(filemask,path,name,ext); {rozporcovani cesty}
ClearDevice; {smazani obrazovky}
DrawPCX(0,0,AddPSlash(path)+srec.Name,dx,dy,false); {vykresleni PCX souboru}
NewAnim (dx,dy,Anim); {inicializace animace}
while DosError = 0 do
begin
AddFrame (0,0,Anim); {pridani snimku}
FindNext(srec); {dalsi soubor}
if DosError=0 then DrawPCX(0,0,AddPSlash(path)+srec.Name,dx,dy,false);
end;
Assign (f,filename); {otevreni vysledneho souboru}
Rewrite (f,1); {pro prepis}
BlockWrite (f,Anim,SizeOf(Anim),NumWrite);
repeat {ukladani a uvolnovani pameti}
tmpFrame:=Anim.imgBegin;
BlockWrite (f,tmpFrame^,SizeOf(TFrame),NumWrite);
BlockWrite (f,tmpFrame^.Image^,word(Anim.dx+1)*word(Anim.dy+1)+4,NumWrite);
Anim.imgBegin:=Anim.imgBegin^.Next;
FreeMem (tmpFrame^.Image,word(Anim.dx+1)*word(Anim.dy+1)+4);
Dispose (tmpFrame);
tmpFrame:=nil;
until Anim.imgBegin=nil;
Close(f); {uzavreni souboru}
end;
procedure ConvertToBImage (filemask:string;filename:string);
var srec:SearchRec;
tmpBImage:PBImage;
path,path2:DirStr;
name:NameStr;
ext:ExtStr;
NumWrite:word;
Image:TImage;
dx,dy:integer;
f:file;
begin
FindFirst(filemask,AnyFile,srec);
FSplit(filemask,path,name,ext);
ClearDevice;
DrawPCX(0,0,AddPSlash(path)+srec.Name,dx,dy,true);
NewBImage (Image);
while DosError = 0 do
begin
Assign (f,filename);
Rewrite (f,1);
BlockWrite (f,dx,SizeOf(dx),NumWrite);
BlockWrite (f,dy,SizeOf(dy),NumWrite);
GetBImage(0,0,dx,dy,Image);
repeat
tmpBImage:=Image.imgBegin;
if tmpBImage=nil then break;
with tmpBImage^ do begin
BlockWrite (f,y1,SizeOf(y1),NumWrite);
BlockWrite (f,y2,SizeOf(y2),NumWrite);
BlockWrite (f,size,SizeOf(size),NumWrite);
BlockWrite (f,Image^,size,NumWrite);
BlockWrite (f,IsNext,SizeOf(IsNext),NumWrite);
end;
Image.imgBegin:=Image.imgBegin^.Next;
FreeMem (tmpBImage^.Image,tmpBImage^.size);
Dispose (tmpBImage);
tmpBImage:=nil;
until Image.imgBegin=nil;
Close(f);
FindNext(srec);
if DosError=0 then begin
DrawPCX(0,0,AddPSlash(path)+srec.Name,dx,dy,false);
ClearDevice;
end;
end;
end;
procedure LoadAnim (filename:string;var Anim:TAnim);
var f:file;
tmpFrame:PFrame;
img:pointer;
size:longint;
NumRead:word;
begin
Assign (f,filename);
Reset (f,1);
BlockRead (f,Anim,SizeOf(Anim),NumRead);
with Anim do begin
imgBegin:=nil;
imgEnd:=nil;
Pos:=nil;
end;
repeat
New (tmpFrame);
BlockRead (f,tmpFrame^,SizeOf(TFrame),NumRead);
if SizeOf(TFrame)<>NumRead then begin
Dispose (tmpFrame);
break;
end;
size:=word(Anim.dx+1)*word(Anim.dy+1)+4;
if (size>MaxAvail) or (size>65500) then exit;
GetMem(img,size);
BlockRead (f,img^,size,NumRead);
tmpFrame^.Image:=img;
tmpFrame^.Next:=nil;
if Anim.imgBegin=nil then begin
Anim.imgBegin:=tmpFrame;
Anim.Pos:=Anim.imgBegin;
Anim.imgEnd:=tmpFrame;
end else begin
Anim.imgEnd^.Next:=tmpFrame;
Anim.imgEnd:=tmpFrame;
end;
until (NumRead = 0);
close (f);
end;
procedure NewBImage(var Image:TImage);
begin
Image.imgBegin:=nil;
Image.imgEnd:=nil;
end;
procedure DisposeBImage (var Image:TImage);
var tmpBImage:PBImage;
begin
if Image.imgBegin=nil then exit;
repeat
tmpBImage:=Image.imgBegin;
Image.imgBegin:=Image.imgBegin^.Next;
FreeMem (tmpBImage^.Image,tmpBImage^.size);
Dispose (tmpBImage);
until Image.imgBegin=nil;
end;
procedure GetBImage (x1,y1,x2,y2:integer;var Image:TImage);
var tmpBImage:PBImage;
img:pointer;
procedure AddNewBlock (x1,y1,x2,y2:integer); {adds part of image (size<64kB)}
var size:longint;
begin
size:=word(abs(x1-x2)+1)*word(abs(y1-y2)+1)+4;
if size>MaxAvail then exit;
new (tmpBImage);
tmpBImage^.size:=size;
GetMem (img,size);
GetImage (x1,y1,x2,y2,img^);
tmpBImage^.IsNext:=false;
tmpBImage^.Next:=nil;
tmpBImage^.Image:=img;
tmpBImage^.y1:=y1;
tmpBImage^.y2:=y2;
if Image.imgBegin=nil then begin
Image.imgBegin:=tmpBImage;
Image.imgEnd:=tmpBImage;
end else begin
Image.imgEnd^.Next:=tmpBImage;
Image.imgEnd^.IsNext:=true;
Image.imgEnd:=tmpBImage;
end;
end;
var usize:longint;
lsize:integer; {size of a line}
bsize:word;
dy1,dy2:integer;
const safesize=65000; {bezpecna velikost}
begin
usize:=(longint(abs(x2-x1)+1)*longint(abs(y2-y1)+1))+4; {celova velikost obrazku (muze byt >64kB)}
if usize>MaxAvail then exit;
lsize:=abs(x1-x2); {velikost radku}
if lsize=0 then exit;
bsize:=(safesize div lsize)*lsize; {velikost bloku}
dy1:=y1; {blok od radku dy1}
dy2:=y1+(bsize div lsize); { do radku dy2}
if dy2>y2 then dy2:=y2;
Image.dx:=abs(x1-x2);
Image.dy:=abs(y1-y2);
while usize>=0 do begin
AddNewBlock (x1,dy1,x2,dy2); {pridani bloku}
usize:=usize-bsize; {zmensuje velikost s pridavanim bloku}
dy1:=dy2; {blok od-do}
dy2:=dy2+(bsize div lsize);
if dy2>y2 then dy2:=y2; {posledni blok je zbytek}
end;
end;
procedure LoadBImage (filename:string;var Image:TImage);
var f:file;
tmpBImage:PBImage;
img:pointer;
size:longint;
NumRead:word;
begin
Assign (f,filename);
Reset (f,1);
with Image do begin
imgBegin:=nil;
imgEnd:=nil;
end;
BlockRead (f,Image.dx,SizeOf(Image.dx),NumRead);
BlockRead (f,Image.dy,SizeOf(Image.dy),NumRead);
repeat
New (tmpBImage);
tmpBImage^.Next:=nil;
with tmpBImage^ do begin
BlockRead (f,y1,SizeOf(y1),NumRead);
BlockRead (f,y2,SizeOf(y2),NumRead);
BlockRead (f,size,SizeOf(size),NumRead);
if size>MaxAvail then begin {neni-li dost pameti, tak konec}
Dispose(tmpBImage);
exit
end else GetMem (Image,size);
BlockRead (f,Image^,size,NumRead);
BlockRead (f,IsNext,SizeOf(IsNext),NumRead);
if SizeOf(IsNext)<>NumRead then begin {to uz je konec}
FreeMem (Image,size);
Dispose (tmpBImage);
break;
end;
end;
if Image.imgBegin=nil then begin
Image.imgBegin:=tmpBImage;
Image.imgEnd:=tmpBImage;
end else begin
Image.imgEnd^.Next:=tmpBImage;
Image.imgEnd^.IsNext:=true;
Image.imgEnd:=tmpBImage;
end;
until (not tmpBImage^.IsNext);
close (f);
end;
function GetBImPixel (x,y:integer;var Image:TImage):word;
var tmpBImage,tmp2BImage:PBImage;
pc:^word;
begin
GetBImPixel:=0;
if Image.imgBegin=nil then exit;
tmpBImage:=Image.imgBegin;
while (tmpBImage<>nil) and not ((tmpBImage^.y1<=y) and (tmpBImage^.y2>=y)) do begin
tmpBImage:=tmpBImage^.Next;
end;
{Zjisteni pixelu pomoci pointeru na word}
{Zacina se na segmentu a offsetu tmpBImage^.Image^}
{prida se potrebny posun v pameti 1pixel=1byte ve 256-barevnem rezimu}
{prvni 4 bajty jsou pro rozmery obrazku}
if (tmpBImage=nil) or ((longint(y-tmpBImage^.y1)*longint(Image.dx+1)+x+4)<0) then exit;
pc:=Ptr(Seg(tmpBImage^.Image^),Ofs(tmpBImage^.Image^)+(word(y-tmpBImage^.y1)*word(Image.dx+1))+x+4);
GetBImPixel:=pc^;
end;
function GetImagePixel (x,y:integer;Image:pointer):word;
var pc:^word;
dx,dy:^word;
begin
GetImagePixel:=0;
dx:=Ptr(Seg(Image^),Ofs(Image^)); {zjisteni rozmeru - prvni 4 bajty}
dy:=Ptr(Seg(Image^),Ofs(Image^)+2);
{podobne jako v GetBImPixel}
if (y*(dx^+1)+x+4)<0 then exit;
pc:=Ptr(Seg(Image^),Ofs(Image^)+(y*(dx^+1))+x+4);
GetImagePixel:=pc^;
end;
function DrawGIM (x1,y1:integer;filename:string;var dx,dy:integer;BitBlt:word):boolean;
var dy1,dy2:integer;
size:word;
Image:pointer;
IsNext:boolean;
NumRead:word;
f:file;
begin
Assign (f,filename);
Reset (f,1);
BlockRead (f,dx,SizeOf(dx),NumRead);
BlockRead (f,dy,SizeOf(dy),NumRead);
repeat
BlockRead (f,dy1,SizeOf(dy1),NumRead);
BlockRead (f,dy2,SizeOf(dy2),NumRead);
BlockRead (f,size,SizeOf(size),NumRead);
if size>MaxAvail then begin {pokud neni pamet tak se procedura ukonci}
DrawGIM:=false;
exit;
end else GetMem (Image,size);
BlockRead (f,Image^,size,NumRead);
BlockRead (f,IsNext,SizeOf(IsNext),NumRead);
PutImage(x1,y1+dy1,Image^,BitBlt);
FreeMem (Image,size); {pamet se hned uvolni}
until (not IsNext);
close (f);
end;
procedure DrawBImage (x1,y1:integer;var Image:TImage;BitBlt:word);
var tmpBImage:PBImage;
ry:integer;
begin
tmpBImage:=Image.imgBegin;
ry:=0;
while tmpBImage<>nil do begin
PutImage (x1,y1+ry,tmpBImage^.Image^,BitBlt);
ry:=ry+tmpBImage^.y2-tmpBImage^.y1;
tmpBImage:=tmpBImage^.Next;
end;
end;
function DrawPCX (x1,y1:integer;filename:string;var dx,dy:integer;setpal:boolean):boolean;
Const
BufferSize = 4096;
type
TPCXHeader = record
Ident, {PCX identifikace=$0a}
Ver, {PCX verze}
Code, {PCX komprese $01-RLE}
BPP : Byte; {bitu na pixel}
X1, Y1, X2, Y2, {rozmery}
Xr, Yr : Word; {dpi rozliseni}
Pall : array[1..48] of Byte; {16-barevna paleta}
R, {rezervovano=0}
colplane : Byte; {?}
BPL, {bajtu na radku}
PalTyp : Word; {typ palety}
other : array[1..58] of Byte; {zbytek rezervovan}
end;
Var f : file;
NumRead, Counter: Word;
Header: TPCXHeader;
XEnd2: Word;
L1, i, X, Y: Word;
Buffer: ARRAY[1..BufferSize] OF Byte;
Color, rep: Byte;
RGBPal: ARRAY[0..255] of Record R,G,B: Byte end;
begin
DrawPCX:=false;
Assign(f, filename);
{$I-} Reset(f, 1); {$I+}
if ioresult<>0 then exit;
BlockRead(f, Header, SizeOf(Header), NumRead);
If NumRead <> SizeOf(Header) then exit;
If (Header.Ident <> 10) or (Header.Ver <> 5) or (Header.Code<>1) then exit;
if setpal then begin
Seek(f, FileSize(f)-768); {skoci pred paletu}
BlockRead(f, RGBPal, Sizeof(RGBPal)); {precte paletu}
FOR i:=0 TO 255 DO {nastavi paletu}
with RGBPal[i] do
begin
R:=R shr 2;
G:=G shr 2;
B:=B shr 2;
end;
SetDACPalette(256,RGBPal);
end;
Seek(f, 128); {skoci pred zacatek dat obrazku}
Y:= 0;
X:= 0;
Counter:= 4096; {pozice v bufferu}
While (Y < Header.Y2+1) do begin
Inc(Counter);
If Counter>BufferSize then {nacteni bufferu}
begin
BlockRead(f, Buffer, BufferSize, NumRead);
Counter:=1;
end;
If Buffer[Counter]>=192 then begin
rep:=Buffer[Counter]-192; {kolikrat se pixel opakuje}
Inc(Counter); {dalsi pixel}
If Counter > BufferSize then begin
BlockRead(f, Buffer, BufferSize, NumRead);
Counter:=1;
end;
Color:= Buffer[Counter];
end else begin
rep:=1;
Color:=Buffer[Counter];
end;
for L1:= 1 to rep do
begin
If X = Header.BPL then {test konce radku}
begin
Inc(Y);
X:= 0;
end;
PutPixel(X+x1, Y+y1, Color); {vykresleni pixelu}
Inc(X)
end;
end;
dx:=Header.X2-Header.X1; {nastaveni velikosti}
dy:=Header.Y2-Header.Y1;
Close(f);
end;
begin
end. |
unit EditWarehouseFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, DBClient, StdCtrls, DBCtrls, Mask, RzEdit, RzDBEdit,
RzButton, RzLabel, ExtCtrls, RzPanel,CommonLIB;
type
TfrmEditWarehouse = class(TForm)
RzPanel1: TRzPanel;
RzLabel1: TRzLabel;
RzLabel3: TRzLabel;
btnSave: TRzBitBtn;
btnCancel: TRzBitBtn;
RzDBEdit17: TRzDBEdit;
RzDBEdit1: TRzDBEdit;
DBCheckBox1: TDBCheckBox;
cdsWarehouse: TClientDataSet;
dsWarehouse: TDataSource;
RzLabel2: TRzLabel;
RzDBEdit2: TRzDBEdit;
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnSaveClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
FWarehouseCode: integer;
FAppParameter: TDLLParameter;
procedure SetWarehouseCode(const Value: integer);
procedure SetAppParameter(const Value: TDLLParameter);
{ Private declarations }
public
{ Public declarations }
property WarehouseCode : integer read FWarehouseCode write SetWarehouseCode;
property AppParameter : TDLLParameter read FAppParameter write SetAppParameter;
end;
var
frmEditWarehouse: TfrmEditWarehouse;
implementation
uses CdeLIB, STDLIB;
{$R *.dfm}
{ TfrmEditWarehouse }
procedure TfrmEditWarehouse.SetWarehouseCode(const Value: integer);
begin
FWarehouseCode := Value;
cdsWarehouse.Data :=GetDataSet('select * from ICMTTWH0 where WH0COD='+IntToStr(WarehouseCode));
end;
procedure TfrmEditWarehouse.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_ESCAPE then btnCancelClick(nil);
if Key=VK_F11 then btnSaveClick(nil);
end;
procedure TfrmEditWarehouse.btnSaveClick(Sender: TObject);
var IsNew : boolean;
begin
if cdsWarehouse.State in [dsinsert] then
begin
IsNew := true;
cdsWarehouse.FieldByName('WH0COD').AsInteger :=getCdeRun('SETTING','RUNNING','WH0COD','CDENM1');
if cdsWarehouse.FieldByName('WH0ACT').IsNull then
cdsWarehouse.FieldByName('WH0ACT').AsString:='A';
setEntryUSRDT(cdsWarehouse,FAppParameter.UserID);
setSystemCMP(cdsWarehouse,FAppParameter.Company,FAppParameter.Branch,FAppParameter.Department,FAppParameter.Section);
end;
if cdsWarehouse.State in [dsinsert,dsedit] then
setModifyUSRDT(cdsWarehouse,FAppParameter.UserID);
if cdsWarehouse.State in [dsedit,dsinsert] then cdsWarehouse.Post;
if cdsWarehouse.ChangeCount>0 then
begin
UpdateDataset(cdsWarehouse,'select * from ICMTTWH0 where WH0COD='+IntToStr(FWarehouseCode)) ;
if IsNew then
setCdeRun('SETTING','RUNNING','WH0COD','CDENM1');
end;
FWarehouseCode:= cdsWarehouse.FieldByName('WH0COD').AsInteger;
Close;
end;
procedure TfrmEditWarehouse.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmEditWarehouse.SetAppParameter(const Value: TDLLParameter);
begin
FAppParameter := Value;
end;
end.
|
unit ideSHEnvironmentConfiguratorFrm;
interface
{$I .inc}
uses
SHDesignIntf, ideSHObject,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ideSHBaseDialogFrm, AppEvnts, StdCtrls, ExtCtrls, ComCtrls,
VirtualTrees, ImgList;
type
TPageType = (ptPackage, ptLibrary, ptModule);
TEnvironmentConfiguratorForm = class(TBaseDialogForm)
Panel1: TPanel;
Panel2: TPanel;
btnAdd: TButton;
btnRemove: TButton;
Panel3: TPanel;
Bevel4: TBevel;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
TabSheet3: TTabSheet;
OpenDialog1: TOpenDialog;
Bevel5: TBevel;
Bevel6: TBevel;
Bevel7: TBevel;
Panel7: TPanel;
PackageTree: TVirtualStringTree;
Panel8: TPanel;
LibraryTree: TVirtualStringTree;
Panel9: TPanel;
ModuleTree: TVirtualStringTree;
ImageList1: TImageList;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure PageControl1Change(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FConfigurator: TideBTObject;
{ Tree }
procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure TreePaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType);
procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
function GetPageType: TPageType;
procedure RecreateTree(APageType: TPageType);
protected
procedure DoOnIdle; override;
public
{ Public declarations }
procedure Add;
procedure Remove;
property PageType: TPageType read GetPageType;
end;
var
EnvironmentConfiguratorForm: TEnvironmentConfiguratorForm;
implementation
uses
ideSHConsts, ideSHMessages, ideSHSysUtils, ideSHSystem, ideSHMainFrm
, sysSHVersionInfo;
{$R *.dfm}
type
PTreeRec = ^TTreeRec;
TTreeRec = record
NormalText: string;
StaticText: string;
ImageIndex: Integer;
FileName: string;
FileVersion:string;
end;
var
// ContainsNode,
RequiresNode, TimeNode: PVirtualNode;
FileName: string;
procedure Info_PackageInfoProc(const Name: string; NameType: TNameType; Flags: Byte; Param: Pointer);
var
NodeData: PTreeRec;
UnitNode: PVirtualNode;
S, UnitName: string;
begin
S := EmptyStr;
UnitName := Name;
if (Flags and ufMainUnit) <> 0 then
begin
if Length(S) > 0 then S := Format('%s, ', [S]);
S := S + 'Main';
end;
if (Flags and ufPackageUnit) <> 0 then
begin
if Length(S) > 0 then S := Format('%s, ', [S]);
S := S + 'Package';
end;
if (Flags and ufWeakUnit) <> 0 then
begin
if Length(S) > 0 then S := Format('%s, ', [S]);
S := S + 'Weak';
end;
if (Flags and ufOrgWeakUnit) <> 0 then
begin
if Length(S) > 0 then S := Format('%s, ', [S]);
S := S + 'OrgWeak';
end;
if (Flags and ufImplicitUnit) <> 0 then
begin
if Length(S) > 0 then S := Format('%s, ', [S]);
S := S + 'Implicit';
end;
if (Flags and ufWeakPackageUnit) <> 0 then
begin
if Length(S) > 0 then S := Format('%s, ', [S]);
S := S + 'WeakPackage';
end;
if Length(S) > 0 then S := Format('%s %s', [S, 'Unit']);
case NameType of
ntContainsUnit:
begin
{ UnitNode := EnvironmentConfiguratorForm.ModuleTree.AddChild(ContainsNode);
NodeData := EnvironmentConfiguratorForm.ModuleTree.GetNodeData(UnitNode);
NodeData.NormalText := UnitName;
NodeData.StaticText := S;
NodeData.ImageIndex := 3;
NodeData.FileName := FileName;}
end;
ntRequiresPackage:
begin
UnitNode := EnvironmentConfiguratorForm.ModuleTree.AddChild(RequiresNode);
NodeData := EnvironmentConfiguratorForm.ModuleTree.GetNodeData(UnitNode);
NodeData.NormalText := UnitName;
NodeData.StaticText := S;
NodeData.ImageIndex := 0;
NodeData.FileName := FileName;
end;
ntDcpBpiName: ;
end;
end;
function Info_EnumModuleProc(HInstance: Longint; Data: Pointer): Boolean;
type
TPackageLoad = procedure;
var
NodeData: PTreeRec;
MainNode: PVirtualNode;
ModuleName, ModuleDescr, PathName: string;
Flags: Integer;
PackageLoad: TPackageLoad;
I: Integer;
begin
@PackageLoad := GetProcAddress(HInstance, 'Initialize'); //Do not localize
SetLength(ModuleName, 255);
GetModuleFileName(HInstance, PChar(ModuleName), Length(ModuleName));
ModuleName := PChar(ModuleName);
FileName := ModuleName;
ModuleDescr := GetPackageDescription(PChar(ModuleName));
if Length(ModuleDescr) = 0 then ModuleDescr := '< None >';
PathName := ExtractFilePath(ModuleName);
ModuleName := ExtractFileName(ModuleName);
if not Assigned(PackageLoad) then
begin
if Assigned(RegistryIntf) then
for I := 0 to Pred(RegistryIntf.GetRegLibraryCount) do
if AnsiSameText(RegistryIntf.GetRegLibraryName(I), ModuleName) then
ModuleDescr := RegistryIntf.GetRegLibraryDescription(I);
{ if ModuleName = 'BlazeTop32.exe' then
begin
ModuleDescr := 'BlazeTop IDE'
end}
end;
with EnvironmentConfiguratorForm.ModuleTree do
begin
BeginUpdate;
try
MainNode := AddChild(nil);
if ModuleName = 'BlazeTop32.exe' then
MoveTo(MainNode,EnvironmentConfiguratorForm.ModuleTree,amAddChildFirst,False);
NodeData := GetNodeData(MainNode);
NodeData.NormalText := ModuleDescr;
NodeData.StaticText := ModuleName;
NodeData.FileVersion:= VersionString(FileName);
if Pos('BlazeTop', NodeData.NormalText) = 1 then
NodeData.ImageIndex := 1
else
NodeData.ImageIndex := 0;
NodeData.FileName := FileName;
{ ContainsNode := AddChild(MainNode);
NodeData := GetNodeData(ContainsNode);
NodeData.NormalText := 'Contains';
NodeData.StaticText := EmptyStr;
NodeData.ImageIndex := 2;
NodeData.FileName := FileName;}
RequiresNode := AddChild(MainNode);
NodeData := GetNodeData(RequiresNode);
NodeData.NormalText := 'Requires';
NodeData.StaticText := EmptyStr;
NodeData.ImageIndex := 2;
NodeData.FileName := FileName;
GetPackageInfo(HInstance, nil, Flags, Info_PackageInfoProc);
TimeNode := InsertNode(MainNode, amAddChildFirst);
NodeData := GetNodeData(TimeNode);
NodeData.StaticText := PathName;
NodeData.ImageIndex := 4;
NodeData.FileName := FileName;
if (Flags and pfDesignOnly) = pfDesignOnly then
NodeData.NormalText := 'Design-time package'
else
if (Flags and pfRunOnly) = pfRunOnly then
NodeData.NormalText := 'Run-time package'
else
if (Flags and pfExeModule) = pfExeModule then
begin
if not Assigned(PackageLoad) then
begin
if Pos('.exe', ModuleName) > 0 then
NodeData.NormalText := 'Executable file'
//if (Flags and pfLibraryModule) = pfLibraryModule then
else
NodeData.NormalText := 'Dynamic-link library';
end else
NodeData.NormalText := 'Design-time and Run-time package';
end;
finally
EndUpdate;
end;
FocusedNode := GetFirst;
Selected[FocusedNode] := True;
end;
Result := True;
end;
{ EnvironmentConfiguratorForm }
function TEnvironmentConfiguratorForm.GetPageType: TPageType;
begin
Result := ptPackage;
if Assigned(FConfigurator) and Assigned(FConfigurator.PageCtrl) then
Result := TPageType(FConfigurator.PageCtrl.ActivePageIndex);
end;
procedure TEnvironmentConfiguratorForm.FormCreate(Sender: TObject);
begin
PageControl1.ActivePageIndex := 0;
FConfigurator := TideBTObject.Create(Self);
FConfigurator.PageCtrl := PageControl1;
FConfigurator.Flat := True;
SetFormSize(540, 640);
Position := poScreenCenter;
inherited;
Caption := Format('%s', [SCaptionDialogConfigurator]);
ButtonsMode := bmOK;
CaptionOK := Format('%s', [SCaptionButtonClose]);
btnRemove.Enabled := False;
Memo1.Lines.Text := EmptyStr;
PackageTree.OnGetNodeDataSize := TreeGetNodeDataSize;
PackageTree.OnFreeNode := TreeFreeNode;
PackageTree.OnPaintText := TreePaintText;
PackageTree.OnGetText := TreeGetText;
PackageTree.OnGetImageIndex := TreeGetImageIndex;
PackageTree.OnFocusChanged := TreeFocusChanged;
LibraryTree.OnGetNodeDataSize := TreeGetNodeDataSize;
LibraryTree.OnFreeNode := TreeFreeNode;
LibraryTree.OnPaintText := TreePaintText;
LibraryTree.OnGetText := TreeGetText;
LibraryTree.OnGetImageIndex := TreeGetImageIndex;
LibraryTree.OnFocusChanged := TreeFocusChanged;
ModuleTree.OnGetNodeDataSize := TreeGetNodeDataSize;
ModuleTree.OnFreeNode := TreeFreeNode;
ModuleTree.OnPaintText := TreePaintText;
ModuleTree.OnGetText := TreeGetText;
ModuleTree.OnGetImageIndex := TreeGetImageIndex;
ModuleTree.OnFocusChanged := TreeFocusChanged;
end;
procedure TEnvironmentConfiguratorForm.FormShow(Sender: TObject);
begin
inherited;
RecreateTree(ptPackage);
PackageTree.FocusedNode := PackageTree.GetFirst;
if Assigned(PackageTree.FocusedNode) then
PackageTree.Selected[PackageTree.FocusedNode] := True;
end;
procedure TEnvironmentConfiguratorForm.RecreateTree(APageType: TPageType);
var
I, Count, ImageIndex: Integer;
MainNode: PVirtualNode;
NodeData: PTreeRec;
begin
try
Screen.Cursor := crHourGlass;
case APageType of
ptPackage:
begin
Count := RegistryIntf.RegPackageCount;
ImageIndex := 1;
PackageTree.Clear;
for I := 0 to Pred(Count) do
begin
PackageTree.BeginUpdate;
try
MainNode := PackageTree.AddChild(nil);
NodeData := PackageTree.GetNodeData(MainNode);
NodeData.NormalText := RegistryIntf.GetRegPackageDescription(I);
NodeData.StaticText := ExtractFileName(RegistryIntf.GetRegPackageFileName(I));
NodeData.FileName := RegistryIntf.GetRegPackageFileName(I);
NodeData.FileVersion:= VersionString(NodeData.FileName);
NodeData.ImageIndex := ImageIndex;
finally
PackageTree.EndUpdate;
end;
end;
end;
ptLibrary:
begin
Count := RegistryIntf.RegLibraryCount;
ImageIndex := 1;
LibraryTree.Clear;
for I := 0 to Pred(Count) do
begin
LibraryTree.BeginUpdate;
try
MainNode := LibraryTree.AddChild(nil);
NodeData := LibraryTree.GetNodeData(MainNode);
NodeData.NormalText := RegistryIntf.GetRegLibraryDescription(I);
NodeData.StaticText := ExtractFileName(RegistryIntf.GetRegLibraryFileName(I));
NodeData.FileName := RegistryIntf.GetRegLibraryFileName(I);
NodeData.FileVersion:= VersionString(NodeData.FileName);
NodeData.ImageIndex := ImageIndex;
finally
LibraryTree.EndUpdate;
end;
end;
end;
ptModule:
begin
if ModuleTree.RootNodeCount = 0 then
begin
ModuleTree.Clear;
EnumModules(Info_EnumModuleProc, nil);
end;
end;
end;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TEnvironmentConfiguratorForm.DoOnIdle;
begin
case PageType of
ptPackage:
begin
OpenDialog1.Filter := 'Package (*.bpl)|*.bpl'; {do not localize}
btnAdd.Enabled := True;
btnRemove.Enabled := Assigned(RegistryIntf) and (RegistryIntf.RegPackageCount > 0);
end;
ptLibrary:
begin
OpenDialog1.Filter := 'Library (*.dll)|*.dll'; {do not localize}
btnAdd.Enabled := True;
btnRemove.Enabled := Assigned(RegistryIntf) and (RegistryIntf.RegLibraryCount > 0);
end;
ptModule:
begin
btnAdd.Enabled := False;
btnRemove.Enabled := False;
end;
end;
{$IFNDEF ENTERPRISE_EDITION}
btnAdd.Enabled := False;
btnRemove.Enabled := False;
{$ENDIF}
end;
procedure TEnvironmentConfiguratorForm.Add;
var
I: Integer;
begin
with OpenDialog1 do
begin
case PageType of
ptPackage:
begin
InitialDir := GetDirPath(SDirBin);
if Execute then
begin
ModuleTree.Clear;
for I := Pred(Files.Count) downto 0 do
if not RegistryIntf.ExistsPackage(Files[I]) then
begin
RegistryIntf.RegisterPackage(Files[I]);
RegistryIntf.SavePackagesToFile;
RecreateTree(ptPackage);
PackageTree.FocusedNode := PackageTree.GetLast;
if Assigned(PackageTree.FocusedNode) then
PackageTree.Selected[PackageTree.FocusedNode] := True;
if Assigned(NavigatorIntf) then NavigatorIntf.RecreatePalette;
end else
ShowMsg(Format(SPackageExists, [ExtractFileName(Files[I])]), mtWarning);
end;
end;
ptLibrary:
begin
InitialDir := GetDirPath(SDirBin);
if Execute then
begin
ModuleTree.Clear;
for I := Pred(Files.Count) downto 0 do
if not RegistryIntf.ExistsLibrary(Files[I]) then
begin
RegistryIntf.RegisterLibrary(Files[I]);
RegistryIntf.SaveLibrariesToFile;
RecreateTree(ptLibrary);
LibraryTree.FocusedNode := LibraryTree.GetLast;
if Assigned(LibraryTree.FocusedNode) then
LibraryTree.Selected[LibraryTree.FocusedNode] := True;
end else
ShowMsg(Format(SLibraryExists, [ExtractFileName(Files[I])]), mtWarning);
end;
end;
end;
end;
end;
procedure TEnvironmentConfiguratorForm.Remove;
var
Data: PTreeRec;
NextNode: PVirtualNode;
begin
case PageType of
ptPackage:
begin
if Assigned(PackageTree.FocusedNode) then
begin
Data := PackageTree.GetNodeData(PackageTree.FocusedNode);
if ShowMsg(Format(SPackageRemoveQuestion + sLineBreak + SPackageRemoveWarning, [Data.FileName]), mtConfirmation) then
begin
RegistryIntf.UnRegisterPackage(Data.FileName);
RegistryIntf.SavePackagesToFile;
NextNode := PackageTree.FocusedNode.NextSibling;
if not Assigned(NextNode) then NextNode := PackageTree.FocusedNode.PrevSibling;
PackageTree.DeleteNode(PackageTree.FocusedNode);
if Assigned(NextNode) then
begin
PackageTree.FocusedNode := PackageTree.GetLast;
PackageTree.Selected[PackageTree.FocusedNode] := True;
end;
end;
end;
end;
ptLibrary:
begin
if Assigned(LibraryTree.FocusedNode) then
begin
Data := LibraryTree.GetNodeData(LibraryTree.FocusedNode);
if ShowMsg(Format(SLibraryRemoveQuestion + sLineBreak + SLibraryRemoveWarning, [Data.FileName]), mtConfirmation) then
begin
RegistryIntf.UnRegisterLibrary(Data.FileName);
RegistryIntf.SaveLibrariesToFile;
NextNode := LibraryTree.FocusedNode.NextSibling;
if not Assigned(NextNode) then NextNode := LibraryTree.FocusedNode.PrevSibling;
LibraryTree.DeleteNode(LibraryTree.FocusedNode);
if Assigned(NextNode) then
begin
LibraryTree.FocusedNode := LibraryTree.GetLast;
LibraryTree.Selected[LibraryTree.FocusedNode] := True;
end;
end;
end;
end;
end;
end;
{ PageControl }
procedure TEnvironmentConfiguratorForm.PageControl1Change(Sender: TObject);
begin
case PageControl1.ActivePageIndex of
0: TreeFocusChanged(PackageTree, PackageTree.FocusedNode, 0);
1: if LibraryTree.RootNodeCount = 0 then
begin
RecreateTree(ptLibrary);
LibraryTree.FocusedNode := LibraryTree.GetFirst;
if Assigned(LibraryTree.FocusedNode) then
LibraryTree.Selected[LibraryTree.FocusedNode] := True;
TreeFocusChanged(LibraryTree, LibraryTree.FocusedNode, 0);
end;
2: if ModuleTree.RootNodeCount = 0 then
begin
RecreateTree(ptModule);
TreeFocusChanged(ModuleTree, ModuleTree.FocusedNode, 0);
end;
end;
end;
{ Buttons }
procedure TEnvironmentConfiguratorForm.btnAddClick(Sender: TObject);
begin
Add;
end;
procedure TEnvironmentConfiguratorForm.btnRemoveClick(Sender: TObject);
begin
Remove;
end;
{ Tree }
procedure TEnvironmentConfiguratorForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TTreeRec);
end;
procedure TEnvironmentConfiguratorForm.TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if Assigned(Data) then Finalize(Data^);
end;
procedure TEnvironmentConfiguratorForm.TreePaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
begin
if Sender.Tag = 2 then
case Column of
0: case TextType of
ttNormal: {if Pos('BlazeTop', Data.NormalText) = 1 then
TargetCanvas.Font.Style := Canvas.Font.Style + [fsBold]};
ttStatic: TargetCanvas.Font.Color := clGray;
end;
1: case TextType of
ttNormal: ;
ttStatic: ;
end;
2: case TextType of
ttNormal: ;
ttStatic: ;
end;
end;
end;
procedure TEnvironmentConfiguratorForm.TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
Data: PTreeRec;
NodeLevel: Integer;
begin
Data := Sender.GetNodeData(Node);
NodeLevel := Sender.GetNodeLevel(Node);
if Sender.Tag = 2 then
begin
case Column of
0: case TextType of
ttNormal: CellText := Data.NormalText;
ttStatic: if NodeLevel > 0 then
CellText := Data.StaticText;
end;
1: case TextType of
ttNormal: if NodeLevel = 0 then
CellText := Data.StaticText
else
CellText := EmptyStr;
ttStatic: CellText := EmptyStr;
end;
2: case TextType of
ttNormal: if NodeLevel = 0 then
CellText := Data.FileVersion
else
CellText := EmptyStr;
ttStatic: CellText := EmptyStr;
end;
end;
end else
begin
case Column of
0: case TextType of
ttNormal: CellText := Data.NormalText;
ttStatic: ;
end;
1: case TextType of
ttNormal: CellText := Data.StaticText;
ttStatic: ;
end;
2: case TextType of
ttNormal: CellText := Data.FileVersion;
ttStatic: ;
end;
end;
end;
end;
procedure TEnvironmentConfiguratorForm.TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if (Kind = ikNormal) or (Kind = ikSelected) then
case Column of
0: ImageIndex := Data.ImageIndex;
1: ImageIndex := -1;
2: ImageIndex := -1;
end;
end;
procedure TEnvironmentConfiguratorForm.TreeFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
var
Data: PTreeRec;
begin
if Assigned(Sender.FocusedNode) then
begin
Data := Sender.GetNodeData(Node);
Memo1.Lines.Text := Data.FileName;
end else
Memo1.Lines.Text := EmptyStr;
end;
end.
|
//*****************************************************************//
// //
// Sorting Algorithms in Delphi //
// Copyrightę BrandsPatch LLC //
// http://www.explainth.at //
// //
// All Rights Reserved //
// //
// Permission is granted to use, modify and redistribute //
// the code in this Delphi unit on the condition that this //
// notice is retained unchanged. //
// //
// BrandsPatch declines all responsibility for any losses, //
// direct or indirect, that may arise as a result of using //
// this code. //
// //
//*****************************************************************//
unit Sorts;
interface
uses Windows,SysUtils;
type TSortArray = array[0..8191] of Double;
type TSortProc = procedure(var Vals:TSortArray;ACount:Integer);
procedure BubbleSort(var Vals:TSortArray;ACount:Integer);
procedure SelSort(var Vals:TSortArray;ACount:Integer);
procedure InsertSort(var Vals:TSortArray;ACount:Integer);
procedure HeapSort(var Vals:TSortArray;ACount:Integer);
procedure MergeSort(var Vals:TSortArray;ACount:Integer);
procedure QuickSort(var Vals:TSortArray;ACount:Integer);
procedure ShellSort(var Vals:TSortArray;ACount:Integer);
implementation
//******************************
//
// O(n^2) Sorts - time required roughly propotional to n^2
// where n is the number of items to be sorted
//
//******************************
procedure BubbleSort(var Vals:TSortArray;ACount:Integer);
var i,j,k:Integer;
Hold:Double;
begin
for i:=ACount - 1 downto 0 do
begin
for j:=1 to i do
begin
k:=j - 1;
if (Vals[k] <= Vals[j]) then Continue;
Hold:=Vals[k];
Vals[k]:=Vals[j];
Vals[j]:=Hold;
{Starting from the bottom of the array each time we
find a smaller value lower down the array we cause
it to "bubble-up". Conversely bigger values "sink".
The problem is that both sinking nor bubbling
occur in steps of one index shift so the process
is slow with multiple value exchanges at each step}
end;
end;
end;
procedure SelSort(var Vals:TSortArray;ACount:Integer);
var i,j,AMin:Integer;
Hold:Double;
begin
for i:=0 to ACount - 2 do
begin
AMin:=i;
for j:=i + 1 to ACount - 1 do
if (Vals[j] < Vals[AMin]) then AMin:=j;
//find smallest Vals in subsequent members of the array
Hold:=Vals[i];
Vals[i]:=Vals[AMin];
Vals[AMin]:=i;
//move the smallest value to its rightful position
{If AMin has not changed, still = i, we end up doing a pointless
swap. However, it turns out more economical than running an if
test and issuing a Continue
As a general rule there is no good reason for using this sort.
Consider the Inertion sort instead}
end;
end;
procedure InsertSort(var Vals:TSortArray;ACount:Integer);
var i,j,k:Integer;
Hold:Double;
begin
for i:=1 to ACount - 1 do
begin
Hold:=Vals[i];
j:=i;k:=j - 1;
while ((j > 0) and (Vals[k] > Hold)) do
begin
Vals[j]:=Vals[k];
dec(j);
dec(k);
end;
Vals[j]:=Hold;
end;
{Better than the bubble sort because we move one
value at a time to its correct position in the array.
There are no value exchanges and only one value
assignment per iteratin of the inner loop
As a general rule the best of the O(n^2) sorts}
end;
//***********************************************************
//
// O(nlog2n) sorts - time required roughly proportional to
// n*log2n where n is the number of items to be sorted
//
//***********************************************************
procedure HeapSort(var Vals:TSortArray;ACount:Integer);
var i,ACountM,HalfCount,L:Integer;
Hold,M:Double;
procedure BuildHeap(p:Integer);
begin
M:=Vals[p];
//the value in the (P)arent node
while (p <= HalfCount) do
{the lower half of the array represents the bottom of the heap
which will get ordered anyway}
begin
L:=p shl 1 + 1;
//for a 0 based array the children are at 2p + 1 and 2p + 2
inc(L,ord((L < ACountM) and (Vals[L + 1] > Vals[L])));
//L is the (L)eft child. L + 1, if it exists, is the right child
if ((M >= Vals[L]) or (L >= ACount)) then break;
//parent bigger than both children so subtree is in order
Vals[p]:=Vals[L];
Vals[L]:=M;
//swap parent with bigger child, L or L + 1
p:=L;
{now examine the subtree for that child, if it exists
Note that we do need to update M - the original parent
moved down the heap and became a child and we are now
testing ITS children}
end;
end;
procedure RestoreHeap(p,n:Integer);
begin
M:=Vals[p];
{As before, p = Parent, L = Left Child & M = parent value
However, we need to leave out array elements from Vals[n+1]
onwards since they are already ordered and should not go
back onto the heap.}
while (p <= n shr 1) do
begin
L:=p shl 1 + 1;
inc(L,ord((L < n) and (Vals[L + 1] > Vals[L])));
//if the right child exists & is the bigger of the two
//arithmetic on L is faster than doing an if test here
if ((M >= Vals[L]) or (L > n)) then break;
{here we risk finding a "child" that actually belongs to
already ordered portion of the array. To avoid this we
check L > n}
Vals[p]:=Vals[L];
Vals[L]:=M;
p:=L;
end;
end;
begin
HalfCount:=ACount shr 1;
ACountM:=ACount - 1;
for i:=HalfCount downto 0 do BuildHeap(i);
{at this point we have a heap. The heap is in an array
which itself is unordered}
for i:=ACountM downto 1 do
begin
Hold:=Vals[i];
Vals[i]:=Vals[0];
Vals[0]:=Hold;
{at each iteration Vals[0] contains the top of the heap. We move
it to the end of the heap - for starters, the end of the array
and subsequently one position up at each iteration
With this done what is left of the array is no longer a valid
heap - we just orphaned the child nodes at Vals[2] and Vals[3]
by taking away their parrent - so we rebuild the heap. However,
we should not do this for a heap with just one element or else
we would disorder the already ordered array.
This sort does not use recursion - the other O(nlog2n) sorts,
except the Shell sort, do. This can be a consideration with
large datasets since recursion places a considerable performance
overhead}
if (i > 1) then RestoreHeap(0,i-1);
end;
end;
procedure MergeSort(var Vals:TSortArray;ACount:Integer);
var AVals:TSortArray;
procedure Merge(ALo,AMid,AHi:Integer);
var i,j,k,m:Integer;
begin
i:=0;
for j:=ALo to AMid do
begin
AVals[i]:=Vals[j];
inc(i);
//copy lower half or Vals into temporary array AVals
end;
i:=0;j:=AMid + 1;k:=ALo;//j could be undefined after the for loop!
while ((k < j) and (j <= AHi)) do
if (AVals[i] <= Vals[j]) then
begin
Vals[k]:=AVals[i];
inc(i);inc(k);
end else
begin
Vals[k]:=Vals[j];
inc(k);inc(j);
end;
{locate next greatest value in Vals or AVals and copy it to the
right position.}
for m:=k to j - 1 do
begin
Vals[m]:=AVals[i];
inc(i);
end;
//copy back any remaining, unsorted, elements
end;
procedure PerformMergeSort(ALo,AHi:Integer);
var AMid:Integer;
begin
if (ALo < AHi) then
begin
AMid:=(ALo + AHi) shr 1;
PerformMergeSort(ALo,AMid);
PerformMergeSort(AMid + 1,AHi);
Merge(ALo,AMid,AHi);
end;
end;
begin
PerformMergeSort(0,ACount - 1);
end;
procedure QuickSort(var Vals:TSortArray;ACount:Integer);
procedure PerformQuickSort(ALo,AHi:Integer);
var i,j,k,m:Integer;
Hold:Double;
begin
i:=ALo;j:=AHi;
Hold:=Vals[(ALo + AHi) shr 1];
//for starters take the midpoint value as the comparison value CV
repeat
repeat
m:=ord(Vals[i] < Hold) or (ord(Vals[j] > Hold) shl 1);
inc(i,ord(m and 1 > 0));
dec(j,ord(m and 2 > 0));
{Most implementations use two while loops. For moderately
large values of ACount there is a significant benefit in
using a single repeat loop and some math as we have done
here.}
until (m = 0);
{We do the following
a. Increase i until Vals[i] >= CV
b. Decrease j until Vals[j] <= CV
}
if (i <= j) then
begin
Hold:=Vals[i];
Vals[i]:=Vals[j];
Vals[j]:=Hold;
inc(i);dec(j);
{If i is to the left of, or same as, j then we swap Vals
at i & j. Incidentally this gives us a new CV}
end;
until (i > j);
//keep repeating until i > j
if (ALo < j) then PerformQuickSort(ALo,j);
if (i < AHi) then PerformQuickSort(i,AHi);
end;
begin
PerformQuickSort(0,ACount - 1);
end;
type TShellCols = array[0..15] of Integer;
procedure ShellSort(var Vals:TSortArray;ACount:Integer);
var i,j,k,h,v:Integer;
Hold:Double;
const ShellCols:TShellCols = (1391376,463792,198768,86961,
33936,13776,4592,1968,861,336,
112,48,21,7,3,1);
//predefine the column sequence to be used
begin
for k:=0 to 15 do
begin
h:=ShellCols[k];
{the inner loop will not execute if the number of columns is
greater than ACount.}
for i:=h to ACount - 1 do
begin
Hold:=Vals[i];
j:=i;
while ((j >= h) and (Vals[j-h] > HOld)) do
begin
Vals[j]:=Vals[j-h];
dec(j,h);
end;
{In the inner loop we do a simplified insertion sort}
Vals[j]:=Hold;
end;
end;
end;
end.
|
unit ThAlertAnimation;
interface
uses
System.Classes, System.Types,
FMX.Types, FMX.Controls, FMX.Ani, FMX.Objects;
type
TAlertAnimation = class(TControl)
private
FText: TText;
FMessagePanel: TRoundRect;
FAnimation: TFloatAnimation;
procedure Finished(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Message(msg: string);
end;
implementation
uses
FMX.Graphics;
{ TAlertAnimation }
constructor TAlertAnimation.Create(AOwner: TComponent);
begin
inherited;
Visible := False;
HitTest := False;
Height := 80;
FMessagePanel := TRoundRect.Create(Self);
FMessagePanel.Parent := Self;
FMessagePanel.Align := TAlignLayout.Client;
FMessagePanel.Fill.Color := $00FF333333;
FMessagePanel.HitTest := False;
FText := TText.Create(Self);
FText.Parent := FMessagePanel;
FText.Align := TAlignLayout.Client;
FText.Font.Size := 35;
FText.Color := $FFFFFFFF;
FText.HitTest := False;
FAnimation := TFloatAnimation.Create(Self);
FAnimation.Parent := Self;
FAnimation.PropertyName := 'Opacity';
FAnimation.OnFinish := Finished;
FAnimation.StartValue := 0.8;
FAnimation.StopValue := 0;
FAnimation.Delay := 1;
FAnimation.Duration := 0.4;
end;
destructor TAlertAnimation.Destroy;
begin
inherited;
end;
procedure TAlertAnimation.Finished(Sender: TObject);
begin
Visible := False;
end;
procedure TAlertAnimation.Message(msg: string);
begin
FText.Text := msg;
FText.Canvas.Font.Size := FText.Font.Size;
Width := FText.Canvas.TextWidth(msg) * 1.1;
if not Assigned(FParent) then
Exit;
Position.X := (TControl(Parent).Width - Width) / 2;
Position.Y := (TControl(Parent).Height - Height) / 2;
if FAnimation.Running then
FAnimation.Stop;
Visible := True;
FAnimation.Start;
end;
end.
|
unit mckMenuEditor;
interface
{$I KOLDEF.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, StdCtrls, ComCtrls,
//*///////////////////////////////////////
{$IFDEF _D6orHigher} //
DesignIntf, DesignEditors, //
{$ELSE} //
//////////////////////////////////////////
DsgnIntf,
//*///////////////////////////////////////
{$ENDIF} //
//*///////////////////////////////////////
ToolIntf, EditIntf, ExptIntf;
type
TKOLMenuDesign = class(TForm)
public
tvMenu: TTreeView;
btAdd: TButton;
btDelete: TButton;
btSubmenu: TButton;
btUp: TBitBtn;
btDown: TBitBtn;
btOK: TButton;
btInsert: TButton;
chbStayOnTop: TCheckBox;
procedure btInsertClick(Sender: TObject);
procedure tvMenuChange(Sender: TObject; Node: TTreeNode);
procedure btAddClick(Sender: TObject);
procedure btSubmenuClick(Sender: TObject);
procedure btDeleteClick(Sender: TObject);
procedure btOKClick(Sender: TObject);
procedure chbStayOnTopClick(Sender: TObject);
procedure btUpClick(Sender: TObject);
procedure btDownClick(Sender: TObject);
private
FMenuComponent: TComponent;
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure Set_Menu(const Value: TComponent);
{ Private declarations }
procedure NewItem( Insert, SubItem: Boolean );
procedure CheckButtons;
function MenuItemTitle( MI: TComponent ): String;
public
{ Public declarations }
Constructor Create( AOwner: TComponent ); override;
property MenuComponent: TComponent read FMenuComponent write Set_Menu;
procedure MakeActive;
procedure RefreshItems;
end;
var
KOLMenuDesign: TKOLMenuDesign;
implementation
uses
mckObjs, mirror;
//{$R *.DFM}
{$R MckMenuEdArrows.res}
{ TMenuDesign }
procedure TKOLMenuDesign.MakeActive;
var MI: TKOLMenuItem;
F: TForm;
D: IDesigner;
FD: IFormDesigner;
begin
if tvMenu.Items.Count > 0 then
if tvMenu.Selected = nil then
tvMenu.Selected := tvMenu.Items[ 0 ];
if tvMenu.Selected <> nil then
begin
MI := tvMenu.Selected.Data;
if MI = nil then Exit;
// set here MI as a current component in Object Inspector
F := (MenuComponent as TKOLMenu).ParentForm;
if F <> nil then
begin
//*///////////////////////////////////////////////////////
{$IFDEF _D6orHigher} //
F.Designer.QueryInterface(IFormDesigner,D); //
{$ELSE} //
//*///////////////////////////////////////////////////////
D := F.Designer;
//*///////////////////////////////////////////////////////
{$ENDIF} //
//*///////////////////////////////////////////////////////
if D <> nil then
if QueryFormDesigner( D, FD ) then
begin
RemoveSelection( FD );
FD.SelectComponent( MI );
end;
end;
end;
CheckButtons;
end;
procedure TKOLMenuDesign.Set_Menu(const Value: TComponent);
var M: TKOLMenu;
I: Integer;
MI: TKOLMenuItem;
procedure AddItem( Node: TTreeNode; MI: TKOLMenuItem );
var NewNode: TTreeNode;
I: Integer;
begin
NewNode := tvMenu.Items.AddChild( Node, MenuItemTitle( MI ) );
NewNode.Data := MI;
for I := 0 to MI.Count - 1 do
AddItem( NewNode, MI.SubItems[ I ] );
end;
begin
FMenuComponent := Value;
M := Value as TKOLMenu;
tvMenu.HandleNeeded;
tvMenu.Items.BeginUpdate;
try
tvMenu.Items.Clear;
for I := 0 to M.Count - 1 do
begin
MI := M.Items[ I ];
AddItem( nil, MI );
end;
if tvMenu.Items.Count > 0 then
tvMenu.FullExpand;
finally
tvMenu.Items.EndUpdate;
end;
{$IFNDEF _D5orD6} // Bug in earlier Delphi2..Delphi4
tvMenu.Items.EndUpdate;
{$ENDIF}
CheckButtons;
MakeActive;
end;
procedure TKOLMenuDesign.btInsertClick(Sender: TObject);
begin
NewItem( True, False );
end;
procedure TKOLMenuDesign.FormDestroy(Sender: TObject);
var M: TKOLMenu;
begin
if MenuComponent <> nil then
try
M := MenuComponent as TKOLMenu;
M.ActiveDesign := nil;
except
end;
end;
procedure TKOLMenuDesign.tvMenuChange(Sender: TObject; Node: TTreeNode);
begin
MakeActive;
CheckButtons;
end;
procedure TKOLMenuDesign.CheckButtons;
begin
btDelete.Enabled := (tvMenu.Selected <> nil) and (tvMenu.Selected.Count = 0);
btSubmenu.Enabled := (tvMenu.Selected <> nil) and (tvMenu.Selected.Count = 0);
btUp.Enabled := (tvMenu.Selected <> nil) and (tvMenu.Selected.GetPrevSibling <> nil);
btDown.Enabled := (tvMenu.Selected <> nil) and (tvMenu.Selected.GetNextSibling <> nil);
end;
procedure TKOLMenuDesign.NewItem(Insert, Subitem: Boolean);
var N, NN: TTreeNode;
MI: TKOLMenuItem;
C: TComponent;
I: Integer;
AParent: TKOLMenuItem;
begin
N := tvMenu.Selected;
if (N = nil) and (tvMenu.Items.Count > 0) then Exit;
if (N = nil) or (N.Parent = nil) and not SubItem then
C := MenuComponent
else
if (N <> nil) and SubItem then
C := N.Data
else
C := N.Parent.Data;
if (N <> nil) and not Subitem and not Insert then
if N.GetNextSibling <> nil then
begin
Insert := True;
N := N.GetNextSibling;
end;
AParent := nil;
if C is TKOLMenuItem then
AParent := C as TKOLMenuItem;
if Subitem or (N = nil) then
MI := TKOLMenuItem.Create( MenuComponent, AParent, nil )
else
if not Insert and (N.GetNextSibling = nil) then
MI := TKOLMenuItem.Create( MenuComponent, AParent, nil )
else
MI := TKOLMenuItem.Create( MenuComponent, AParent, N.Data );
for I := 1 to MaxInt do
begin
if MenuComponent <> nil then
if (MenuComponent as TKOLMenu).NameAlreadyUsed( 'N' + IntToStr( I ) ) then
continue;
MI.Name := 'N' + IntToStr( I );
break;
end;
if (N = nil) or (not Insert and not SubItem) then
NN := tvMenu.Items.Add( N, '[ ' + MI.Name + ' ]' )
else
if not Subitem then
NN := tvMenu.Items.Insert( N, '[ ' + MI.Name + ' ]' )
else
begin
NN := tvMenu.Items.AddChild( N, '[ ' + MI.Name + ' ]' );
end;
NN.Data := MI;
NN.MakeVisible;
tvMenu.Selected := NN;
CheckButtons;
MakeActive;
end;
procedure TKOLMenuDesign.RefreshItems;
var I: Integer;
N: TTreeNode;
MI: TKOLMenuItem;
begin
for I := 0 to tvMenu.Items.Count - 1 do
begin
N := tvMenu.Items[ I ];
MI := N.Data;
if MI <> nil then
N.Text := MenuItemTitle( MI );
end;
end;
procedure TKOLMenuDesign.btAddClick(Sender: TObject);
begin
NewItem( False, False );
end;
procedure TKOLMenuDesign.btSubmenuClick(Sender: TObject);
begin
NewItem( False, True );
end;
procedure TKOLMenuDesign.btDeleteClick(Sender: TObject);
var N, NN: TTreeNode;
MI: TKOLMenuItem;
S: String;
F: TForm;
D: IDesigner;
FD: IFormDesigner;
begin
N := tvMenu.Selected;
if N = nil then Exit;
S := N.Text;
Rpt( 'Deleting: ' + S, WHITE );
MI := N.Data;
if MI = nil then Exit;
NN := N.GetNextSibling;
if NN = nil then
NN := N.GetPrevSibling;
if NN = nil then
NN := N.Parent;
if NN = nil then
begin
if MenuComponent <> nil then
begin
F := (MenuComponent as TKOLMenu).ParentForm;
if F <> nil then
begin
//*///////////////////////////////////////////////////////
{$IFDEF _D6orHigher} //
F.Designer.QueryInterface(IFormDesigner,D); //
{$ELSE} //
//*///////////////////////////////////////////////////////
D := F.Designer;
//*///////////////////////////////////////////////////////
{$ENDIF} //
//*///////////////////////////////////////////////////////
if D <> nil then
if QueryFormDesigner( D, FD ) then
begin
RemoveSelection( FD );
FD.SelectComponent( MenuComponent );
end;
end;
end;
end;
N.Free;
Rpt( 'Deleted: ' + S, WHITE );
S := MI.Name;
MI.Free;
Rpt( 'ITEM Destroyed: ' + S, WHITE );
if NN <> nil then
begin
tvMenu.Selected := NN;
Rpt( 'Selected: ' + IntToStr( Integer( NN ) ), WHITE );
end;
if MenuComponent <> nil then
begin
(MenuComponent as TKOLMenu).Change;
Rpt( 'Changed: ' + MenuComponent.Name, WHITE );
end;
CheckButtons;
Rpt( 'Buttons checked. Deleting of ' + S + ' finished.', WHITE );
end;
procedure TKOLMenuDesign.btOKClick(Sender: TObject);
begin
Close;
end;
function TKOLMenuDesign.MenuItemTitle(MI: TComponent): String;
begin
Result := (MI as TKOLMenuITem).Caption;
if Result = '' then
Result := '[ ' + MI.Name + ' ]';
end;
procedure TKOLMenuDesign.FormClose(Sender: TObject;
var Action: TCloseAction);
var F: TForm;
D: IDesigner;
FD: IFormDesigner;
begin
if MenuComponent <> nil then
begin
Rpt( 'Closing KOLMenuEditor form', WHITE );
F := (MenuComponent as TKOLMenu).ParentForm;
if F <> nil then
begin
Rpt( 'Form found: ' + F.Name, WHITE );
//*///////////////////////////////////////////////////////
{$IFDEF _D6orHigher} //
F.Designer.QueryInterface(IFormDesigner,D); //
{$ELSE} //
//*///////////////////////////////////////////////////////
D := F.Designer;
//*///////////////////////////////////////////////////////
{$ENDIF} //
//*///////////////////////////////////////////////////////
if D <> nil then
begin
Rpt( 'IDesigner interface returned', WHITE );
if QueryFormDesigner( D, FD ) then
begin
Rpt( 'IFormDesigner interface quered', WHITE );
try
RemoveSelection( FD );
FD.SelectComponent( MenuComponent );
except
Rpt( 'EXCEPTION *** Could not clear selection!', WHITE )
end;
end;
end;
end;
end;
end;
procedure TKOLMenuDesign.chbStayOnTopClick(Sender: TObject);
begin
if chbStayOnTop.Checked then
FormStyle := fsStayOnTop
else
FormStyle := fsNormal;
end;
procedure TKOLMenuDesign.btUpClick(Sender: TObject);
var CurNode: TTreeNode;
CurMI: TKOLMenuItem;
AC: TControl;
begin
CurNode := tvMenu.Selected;
if CurNode = nil then Exit;
if CurNode.GetPrevSibling = nil then Exit;
CurMI := CurNode.Data;
if CurMI = nil then Exit;
if MenuComponent = nil then Exit;
if not(MenuComponent is TKOLMenu) then Exit;
CurMI.MoveUp;
CurNode.MoveTo( CurNode.GetPrevSibling, naInsert );
AC := ActiveControl;
CheckButtons;
if AC = btUp then
if not btUp.Enabled then
PostMessage( Handle, WM_NEXTDLGCTL, 0, 0 );
end;
procedure TKOLMenuDesign.btDownClick(Sender: TObject);
var CurNode: TTreeNode;
CurMI: TKOLMenuItem;
AC: TControl;
begin
CurNode := tvMenu.Selected;
if CurNode = nil then Exit;
if CurNode.GetNextSibling = nil then Exit;
CurMI := CurNode.Data;
if CurMI = nil then Exit;
if MenuComponent = nil then Exit;
if not(MenuComponent is TKOLMenu) then Exit;
CurMI.MoveDown;
if CurNode.GetNextSibling.GetNextSibling = nil then
CurNode.MoveTo( CurNode.GetNExtSibling, naAdd )
else
CurNode.MoveTo( CurNode.GetNextSibling.GetNextSibling, naInsert );
AC := ActiveControl;
CheckButtons;
if AC = btDown then
if not btDown.Enabled then
PostMessage( Handle, WM_NEXTDLGCTL, 0, 0 );
end;
procedure TKOLMenuDesign.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_DELETE:
if btDelete.Enabled then
btDelete.Click;
VK_INSERT:
if btInsert.Enabled then
btInsert.Click;
VK_UP:
if GetKeyState( VK_CONTROL ) < 0 then
if btUp.Enabled then
btUp.Click;
VK_DOWN:
if GetKeyState( VK_CONTROL ) < 0 then
if btDown.Enabled then
btDown.Click;
VK_RIGHT:
begin
if (tvMenu.Selected <> nil) and (tvMenu.Selected.Count = 0) then
begin
if btSubmenu.Enabled then
btSubmenu.Click;
Key := 0;
end
{else
if ActiveControl <> tvMenu then
Key := 0};
end;
VK_LEFT:
begin
{if ActiveControl <> tvMenu then
Key := 0};
end;
end;
end;
constructor TKOLMenuDesign.Create(AOwner: TComponent);
begin
CreateNew(AOwner);
Left := 299;
Top := 81;
BorderIcons := [biSystemMenu, biMinimize];
BorderStyle := bsToolWindow ;
ClientHeight := 299 ;
ClientWidth := 343 ;
//Color := clBtnFace ;
//Font.Charset := DEFAULT_CHARSET ;
//Font.Color := clWindowText ;
//Font.Height := -11 ;
//Font.Name := 'MS Sans Serif' ;
//Font.Style := [] ;
KeyPreview := True ;
//OldCreateOrder := False ;
{$IFDEF _D4orD5}
Position := poDesktopCenter ;
{$ENDIF}
{$IFDEF _D2orD3}
Position := poScreenCenter ;
{$ENDIF}
Scaled := False ;
Visible := True ;
OnClose := FormClose ;
OnDestroy := FormDestroy ;
OnKeyDown := FormKeyDown ;
//PixelsPerInch := 96 ;
//TextHeight := 13 ;
tvMenu := TTreeView.Create( Self ) ;
tvMenu.Parent := Self ;
tvMenu.Left := 6 ;
tvMenu.Top := 6 ;
tvMenu.Width := 227 ;
tvMenu.Height := 285 ;
tvMenu.HideSelection := False ;
//tvMenu.Indent := 19 ;
tvMenu.ReadOnly := True ;
//tvMenu.TabOrder := 0 ;
tvMenu.OnChange := tvMenuChange ;
btOK := TButton.Create( Self ) ;
btOK.Parent := Self;
btOK.Left := 244 ;
btOK.Top := 6 ;
btOK.Width := 91 ;
btOK.Height := 25 ;
btOK.Caption := 'Close' ;
//btOK.TabOrder := 1 ;
btOK.OnClick := btOKClick ;
btUp := TBitBtn.Create( Self ) ;
btUp.Parent := Self;
btUp.Left := 244 ;
btUp.Top := 90 ;
btUp.Width := 40 ;
btUp.Height := 27 ;
btUp.Enabled := False ;
//btUp.TabOrder := 2 ;
btUp.OnClick := btUpClick ;
btUp.Glyph.Handle := LoadBitmap( hInstance, 'MCKARROWUP' );
btDown := TBitBtn.Create( Self ) ;
btDown.Parent := Self;
btDown.Left := 295 ;
btDown.Top := 90 ;
btDown.Width := 40 ;
btDown.Height := 27 ;
btDown.Enabled := False ;
//btDown.TabOrder := 3 ;
btDown.OnClick := btDownClick ;
btDown.Glyph.Handle := LoadBitmap( hInstance, 'MCKARROWDN' );
btInsert := TButton.Create( Self ) ;
btInsert.Parent := Self;
btInsert.Left := 244 ;
btInsert.Top := 170 ;
btInsert.Width := 91 ;
btInsert.Height := 25 ;
btInsert.Caption := 'Insert' ;
//btInsert.TabOrder := 4 ;
btInsert.OnClick := btInsertClick ;
btAdd := TButton.Create( Self ) ;
btAdd.Parent := Self;
btAdd.Left := 244 ;
btAdd.Top := 202 ;
btAdd.Width := 91 ;
btAdd.Height := 25 ;
btAdd.Caption := 'Add' ;
//btAdd.TabOrder := 5 ;
btAdd.OnClick := btAddClick ;
btDelete := TButton.Create( Self ) ;
btDelete.Parent := Self;
btDelete.Left := 244 ;
btDelete.Top := 234 ;
btDelete.Width := 91 ;
btDelete.Height := 25 ;
btDelete.Caption := 'Delete' ;
btDelete.Enabled := False ;
//btDelete.TabOrder := 6 ;
btDelete.OnClick := btDeleteClick ;
btSubmenu := TButton.Create( Self ) ;
btSubMenu.Parent := Self;
btSubmenu.Left := 244 ;
btSubmenu.Top := 266 ;
btSubmenu.Width := 91 ;
btSubmenu.Height := 25 ;
btSubmenu.Caption := 'New submenu' ;
btSubmenu.Enabled := False ;
//btSubmenu.TabOrder := 7 ;
btSubmenu.OnClick := btSubmenuClick ;
chbStayOnTop := TCheckBox.Create( Self ) ;
chbStayOnTop.Parent := Self;
chbStayOnTop.Left := 244 ;
chbStayOnTop.Top := 40 ;
chbStayOnTop.Width := 91 ;
chbStayOnTop.Height := 17 ;
chbStayOnTop.Caption := 'Stay On Top' ;
//chbStayOnTop.TabOrder := 8 ;
chbStayOnTop.OnClick := chbStayOnTopClick;
end;
end. |
unit Demo.ColumnChart.Trendlines;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_ColumnChart_Trendlines = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
uses
System.SysUtils, System.DateUtils;
procedure TDemo_ColumnChart_Trendlines.GenerateChart;
var
Chart: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_COLUMN_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtTimeOfDay, 'Time of Day'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Motivation Level'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Energy Level')
]);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(8, 0, 0, 0), '8 am');
Chart.Data.SetValue(1, 1);
Chart.Data.SetValue(2, 0.25);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(9, 0, 0, 0), '9 am');
Chart.Data.SetValue(1, 2);
Chart.Data.SetValue(2, 0.5);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(10, 0, 0, 0), '10 am');
Chart.Data.SetValue(1, 3);
Chart.Data.SetValue(2, 1);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(11, 0, 0, 0), '11 am');
Chart.Data.SetValue(1, 4);
Chart.Data.SetValue(2, 2.25);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(12, 0, 0, 0), '12 pm');
Chart.Data.SetValue(1, 5);
Chart.Data.SetValue(2, 2.25);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(13, 0, 0, 0), '1 pm');
Chart.Data.SetValue(1, 6);
Chart.Data.SetValue(2, 3);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(14, 0, 0, 0), '2 pm');
Chart.Data.SetValue(1, 7);
Chart.Data.SetValue(2, 4);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(15, 0, 0, 0), '3 pm');
Chart.Data.SetValue(1, 8);
Chart.Data.SetValue(2, 5.25);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(16, 0, 0, 0), '4 pm');
Chart.Data.SetValue(1, 9);
Chart.Data.SetValue(2, 7.5);
Chart.Data.AddRow;
Chart.Data.SetValue(0, EncodeTime(17, 0, 0, 0), '5 pm');
Chart.Data.SetValue(1, 10);
Chart.Data.SetValue(2, 10);
// Options
Chart.Options.Title('Motivation and Energy Level Throughout the Day');
Chart.Options.Colors(['#9575cd', '#33ac71']);
Chart.Options.hAxis('title', 'Time of Day');
Chart.Options.hAxis('format', 'h:mm a');
Chart.Options.hAxis('viewWindow', '{ min: [7, 30, 0], max: [17, 30, 0]}');
Chart.Options.vAxis('title', 'Rating (scale of 1-10)');
Chart.Options.Trendlines([ '0: {type: ''linear'', lineWidth: 5, opacity: .3}', '1: {type: ''exponential'', lineWidth: 10, opacity: .3}']);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_ColumnChart_Trendlines);
end.
|
unit dialogsx;
{$mode Delphi} //{$mode objfpc}
{$Include isgui.inc}
{$H+}
interface
uses
SysUtils,IniFiles;
{$IFNDEF GUI}
type
TMsgDlgBtn = (mbYes, mbNo, mbOK, mbCancel, mbAbort, mbRetry, mbIgnore, mbAll, mbNoToAll, mbYesToAll, mbHelp);
TMsgDlgButtons = set of TMsgDlgBtn;
TMsgDlgType = (mtWarning, mtError, mtInformation, mtConfirmation, mtCustom);
{$ENDIF}
procedure Msg (lStr: string);
procedure ShowMsg (lStr: string);
procedure msgfx (a,b,c,d: double); overload; //fx used to help debugging - reports number values
//function MsgDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint): Word;
function GetInt(lStr: string; lMin,lDefault,lMax: integer): integer;
function GetFloat(lStr: string; lMin,lDefault,lMax: single): single;
procedure MyReadLn;//no GUI: waits for user
function GetStr(lPrompt: string): string;
//procedure vx (a,b,c,d: double);
const
mrCancel = 2;
mrAbort = 1;// idAbort
mrNo = 0;
implementation
{$IFDEF GUI}uses
dialogs; {$ENDIF}
procedure vx (a,b,c,d: double); //vx used to help debugging - reports number values
begin
msg(floattostr(a)+':'+floattostr(b)+':'+floattostr(c)+':'+floattostr(d));
end;
procedure MyReadLn;
{$IFDEF GUI}
begin
//do nothing
end;
{$ELSE}
begin
{$IFNDEF UNIX}
if IsConsole then
ReadLn;
{$ENDIF}
end;
{$ENDIF}
function MsgDlg(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; HelpCtx: Longint): Word;
{$IFDEF GUI}
begin
result := 0;
ShowMsg('WARNING: MsgDlg not coded. Unabled to process this '+Msg);
{$ELSE}
begin
result := 0;
writeln('WARNING: dialogs not being used. Unabled to process this '+Msg);
{$ENDIF}
end;
procedure ShowMsg (lStr: string);
begin
{$IFDEF GUI}
ShowMessage(lStr); //if you get an error here - adjust isgui.inc
{$ELSE}
writeln(lStr)
{$ENDIF}
end;
procedure msgfx (a,b,c,d: double); overload; //fx used to help debugging - reports number values
begin
{$IFDEF GUI}
msg(floattostr(a)+'x'+floattostr(b)+'x'+floattostr(c)+'x'+floattostr(d));
{$ELSE}
msg(floattostr(a)+'x'+floattostr(b)+'x'+floattostr(c)+'x'+floattostr(d));
{$ENDIF}
end;
procedure Msg (lStr: string);
begin
{$IFDEF GUI}
Showmessage(lStr);
{$ELSE}
writeln(lStr)
{$ENDIF}
end;
function GetStr(lPrompt: string): string;
{$IFDEF GUI}
var
lOK: boolean;
begin
lOK := InputQuery(lPrompt, lPrompt, result);
if not lOK then
result := '';
end;
{$ELSE}
var
lS: string;
begin
writeln ( lPrompt);
readln(lS);
result := lS;
end;
{$ENDIF}
function GetFloat(lStr: string; lMin,lDefault,lMax: single): single;
{$IFDEF GUI}
var
s: string;
begin
s := floattostr(ldefault);
InputQuery('Integer required',lStr,s);
try
result := StrToFloat(S);
except
on Exception : EConvertError do
result := ldefault;
end;
if result < lmin then
result := lmin;
if result > lmax then
result := lmax;
end;
{$ELSE}
var
lS: string;
lError,lI: integer;
begin
writeln ( lStr+' ['+floattostr(lMin)+'..'+floattostr(lMax)+'], default '+floattostr(lDefault));
readln(lS);
Val(lS,lI,lError);
if lError = 0 then
result := (lI)
else begin
writeln(floattostr(lDefault));
result := lDefault;
end;
if result < lMin then
result := lMin;
if result > lMax then
result := lMax;
end;
{$ENDIF}
function GetInt(lStr: string; lMin,lDefault,lMax: integer): integer;
{$IFDEF GUI}
var
s: string;
begin
s := inttostr(ldefault);
InputQuery('Integer required',lStr,s);
try
result := StrToInt(S);
except
on Exception : EConvertError do
result := ldefault;
end;
if result < lmin then
result := lmin;
if result > lmax then
result := lmax;
end;
{$ELSE}
var
lS: string;
lError,lI: integer;
begin
writeln ( lStr+' ['+inttostr(lMin)+'..'+inttostr(lMax)+'], default '+inttostr(lDefault));
readln(lS);
Val(lS,lI,lError);
if lError = 0 then
result := round(lI)
else begin
writeln(inttostr(lDefault));
result := lDefault;
end;
if result < lMin then
result := lMin;
if result > lMax then
result := lMax;
end;
{$ENDIF}
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [AGENCIA_BANCO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit AgenciaBancoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
BancoVO;
type
TAgenciaBancoVO = class(TVO)
private
FID: Integer;
FID_BANCO: Integer;
FCODIGO: String;
FDIGITO: String;
FNOME: String;
FLOGRADOURO: String;
FNUMERO: String;
FCEP: String;
FBAIRRO: String;
FMUNICIPIO: String;
FUF: String;
FTELEFONE: String;
FGERENTE: String;
FCONTATO: String;
FOBSERVACAO: String;
//Transientes
FBancoNome: String;
FBancoVO: TBancoVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdBanco: Integer read FID_BANCO write FID_BANCO;
property BancoNome: String read FBancoNome write FBancoNome;
property Codigo: String read FCODIGO write FCODIGO;
property Digito: String read FDIGITO write FDIGITO;
property Nome: String read FNOME write FNOME;
property Logradouro: String read FLOGRADOURO write FLOGRADOURO;
property Numero: String read FNUMERO write FNUMERO;
property Cep: String read FCEP write FCEP;
property Bairro: String read FBAIRRO write FBAIRRO;
property Municipio: String read FMUNICIPIO write FMUNICIPIO;
property Uf: String read FUF write FUF;
property Telefone: String read FTELEFONE write FTELEFONE;
property Gerente: String read FGERENTE write FGERENTE;
property Contato: String read FCONTATO write FCONTATO;
property Observacao: String read FOBSERVACAO write FOBSERVACAO;
//Transientes
property BancoVO: TBancoVO read FBancoVO write FBancoVO;
end;
TListaAgenciaBancoVO = specialize TFPGObjectList<TAgenciaBancoVO>;
implementation
constructor TAgenciaBancoVO.Create;
begin
inherited;
FBancoVO := TBancoVO.Create;
end;
destructor TAgenciaBancoVO.Destroy;
begin
FreeAndNil(FBancoVO);
inherited;
end;
initialization
Classes.RegisterClass(TAgenciaBancoVO);
finalization
Classes.UnRegisterClass(TAgenciaBancoVO);
end.
|
unit uResources;
interface
uses
Winapi.Windows,
Generics.Collections,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Imaging.JPEG,
Vcl.Imaging.pngImage,
Dmitry.Imaging.JngImage,
uMemory;
type
TResourceUtils = class
class function LoadGraphicFromRES<T: TGraphic, constructor>(ResName: string): T;
end;
function GetFolderPicture: TPNGImage;
function GetLogoPicture: TJngImage;
function GetExplorerBackground: TPNGImage;
function GetLoadingImage: TJngImage;
function GetActivationImage: TPNGImage;
function GetPrinterPatternImage: TJpegImage;
function GetBigPatternImage: TJpegImage;
function GetFilmStripImage: TPNGImage;
function GetPathSeparatorImage: TBitmap;
function GetNoHistogramImage: TPNGImage;
function GetCollectionSyncImage: TPngImage;
function GetNavigateDownImage: TPngImage;
function GetFaceMaskImage: TPngImage;
{$R MAIN.res}
{$R Logo.res}
{$R Directory_Large.res}
{$R ExplorerBackground.res}
{$R Manifest.res}
{$R Loading.res}
{$R Activation.res}
{$R PrinterPattern.res}
{$R BigPattern.res}
{$R Film_Strip.res}
{$R PathSeparator.res}
{$R NoHistogram.res}
{$R SampleDB.res}
{$R Import.res}
{$R CollectionSync.res}
{$R ExplorerItems.res}
{$R FaceMask.res}
//Icons
{$R db_icons.res}
{$R ZoomRc.res}
{$R editor.res}
{$R explorer.res}
{$R cmd_icons.res}
//for mobile test
{$IFDEF MOBILE_TEST}
{$R MOBILE_FS.res}
{$ENDIF}
{$R explorer_search.res}
function GetRCDATAResourceStream(ResName: string): TMemoryStream;
implementation
function GetRCDATAResourceStream(ResName: string): TMemoryStream;
var
MyRes: Integer;
MyResP: Pointer;
MyResS: Integer;
begin
Result := nil;
MyRes := FindResource(HInstance, PWideChar(ResName), RT_RCDATA);
if MyRes <> 0 then begin
MyResS := SizeOfResource(HInstance,MyRes);
MyRes := LoadResource(HInstance,MyRes);
if MyRes <> 0 then begin
MyResP := LockResource(MyRes);
if MyResP <> nil then begin
Result := TMemoryStream.Create;
with Result do begin
Write(MyResP^, MyResS);
Seek(0, soFromBeginning);
end;
UnLockResource(MyRes);
end;
FreeResource(MyRes);
end
end;
end;
{ TResourceUtils }
class function TResourceUtils.LoadGraphicFromRES<T>(ResName: string): T;
var
RCDataStream: TMemoryStream;
begin
Result := nil;
RCDataStream := GetRCDATAResourceStream(ResName);
if RCDataStream <> nil then
begin
Result := T.Create;
Result.LoadFromStream(RCDataStream);
F(RCDataStream);
end;
end;
function GetFolderPicture: TPNGImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TPngImage>('DIRECTORY_LARGE');
end;
function GetExplorerBackground: TPNGImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TPngImage>('EXPLORERBACKGROUND');
end;
function GetLoadingImage: TJngImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TJngImage>('LOADING');
end;
function GetLogoPicture: TJngImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TJngImage>('LOGO');
end;
function GetActivationImage: TPNGImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TPngImage>('ACTIVATION');
end;
function GetPrinterPatternImage: TJpegImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TJpegImage>('PRINTERPATTERN');
end;
function GetBigPatternImage: TJpegImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TJpegImage>('BIGPATTERN');
end;
function GetFilmStripImage: TPNGImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TPngImage>('FILM_STRIP');
end;
function GetPathSeparatorImage: TBitmap;
begin
Result := TResourceUtils.LoadGraphicFromRES<TBitmap>('PATH_SEPARATOR');
end;
function GetNoHistogramImage: TPNGImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TPngImage>('NO_HISTOGRAM');
end;
function GetCollectionSyncImage: TPngImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TPngImage>('COLLECTION_SYNC');
end;
function GetNavigateDownImage: TPngImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TPngImage>('NAVIGATEDOWN');
end;
function GetFaceMaskImage: TPngImage;
begin
Result := TResourceUtils.LoadGraphicFromRES<TPngImage>('FACEMASK');
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fMacroSelect;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Menus, ExtCtrls, uMacros, uMultiLanguage,
MainInstance, uCommon;
type
TfmMacroSelect = class(TForm)
lvMacros: TListView;
btnCancel: TButton;
labMessage: TLabel;
btnPlay: TButton;
procedure FormShow(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnSelectAllClick(Sender: TObject);
procedure btnPlayClick(Sender: TObject);
procedure lvMacrosDblClick(Sender: TObject);
private
procedure InstanceFileOpenNotify(var Msg: tMessage); message wmMainInstanceOpenFile;
public
SelectedMacro :pTMacro;
end;
implementation
uses
fMain;
{$R *.DFM}
////////////////////////////////////////////////////////////////////////////////////////////
// Messages
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmMacroSelect.InstanceFileOpenNotify(var Msg: tMessage);
begin
fmMain.InstanceFileOpenNotify(Msg);
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmMacroSelect.btnSelectAllClick(Sender: TObject);
var
i :integer;
begin
for i:=0 to lvMacros.Items.Count-1 do
lvMacros.Items[i].Checked:=TRUE;
end;
//------------------------------------------------------------------------------------------
procedure TfmMacroSelect.btnPlayClick(Sender: TObject);
begin
if Assigned(lvMacros.Selected) then
SelectedMacro:=pTMacro(lvMacros.Selected.Data);
Close;
end;
//------------------------------------------------------------------------------------------
procedure TfmMacroSelect.lvMacrosDblClick(Sender: TObject);
begin
if Assigned(lvMacros.Selected) then
btnPlayClick(SELF);
end;
//------------------------------------------------------------------------------------------
procedure TfmMacroSelect.btnCancelClick(Sender: TObject);
begin
SelectedMacro:=nil;
Close;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmMacroSelect.FormShow(Sender: TObject);
var
i :integer;
mac :pTMacro;
begin
mlApplyLanguageToForm(SELF, Name);
lvMacros.Columns[0].Caption:=mlStr(ML_MACRO_MANAGE_LV_CAPT_NAME,'Name');
lvMacros.Columns[1].Caption:=mlStr(ML_MACRO_MANAGE_LV_CAPT_SHORTCUT,'Shortcut');
lvMacros.Items.BeginUpdate;
try
lvMacros.Items.Clear;
for i:=0 to fmMain.Macros.Count-1 do begin
mac:=pTMacro(fmMain.Macros.strMacros.Objects[i]);
if Assigned(mac) then begin
with lvMacros.Items.Add do begin
Caption:=fmMain.Macros.strMacros[i];
SubItems.Add(ShortcutToText(Shortcut(mac^.Key,mac^.Shift)));
Data:=mac;
end;
end;
end;
finally
lvMacros.Items.EndUpdate;
end;
if (lvMacros.Items.Count>0) then
lvMacros.Selected:=lvMacros.Items[0];
lvMacros.SetFocus;
end;
//------------------------------------------------------------------------------------------
end.
|
unit uDemoViewTipo3;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ScrollBox,
FMX.Memo, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts,
uInterfaces,
uAtributos,
uDemoInterfaces,
uDemoViewModels,
uTypes,
uView,
uDemoViewFrameTipo1,
uDemoViewFrameTipo2;
type
[ViewForVM(IMyViewModel3, TMyViewModel3)]
TfrmMultiVista = class(TFormView<IMyViewModel3, TMyViewModel3>)
Layout1: TLayout;
Layout2: TLayout;
Layout3: TLayout;
Button1: TButton;
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FFrame1: TFrame1;
FFrame2: TFrame2;
public
{ Public declarations }
function GetVM_AsInterface: IMyViewModel3; override;
function GetVM_AsObject: TMyViewModel3; override;
end;
var
frmMultiVista: TfrmMultiVista;
implementation
{$R *.fmx}
{ TfrmMultiVista }
procedure TfrmMultiVista.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(GetVM_AsInterface.Hello);
end;
procedure TfrmMultiVista.FormCreate(Sender: TObject);
begin
inherited;
FFrame1 := TFrame1.Create(Self);
Layout1.AddObject(FFrame1);
FFrame1.Align := TAlignLayout.Client;
FFrame2 := TFrame2.Create(Self);
Layout2.AddObject(FFrame2);
FFrame2.Align := TAlignLayout.Client;
GetVM_AsInterface.VM_Tipo1 := FFrame1.GetVM_AsInterface;
GetVM_AsInterface.VM_Tipo2 := FFrame2.GetVM_AsInterface;
end;
function TfrmMultiVista.GetVM_AsInterface: IMyViewModel3;
begin
Result := FViewModel as IMyViewModel3
end;
function TfrmMultiVista.GetVM_AsObject: TMyViewModel3;
begin
Result := FViewModel as TMyViewModel3;
end;
end.
|
(*
Category: SWAG Title: FILE HANDLING ROUTINES
Original name: 0047.PAS
Description: Filedate and Time
Author: GREG ESTABROOKS
Date: 02-03-94 10:57
*)
{
ET>How can I change the file's date and time without opening that file??
ET>I appreciate (some) example source code, so I can look how it is done.
ET>Thanks.
In order to change a files date/timestamp you'll have open the file
whether you use the TP SetFTime routine or use Int 21h Function 5701
BUT by Opening it for reading you can change it to whatever you want.
If you open it for writing then the TimeStamp will automatically be
changed to whatever the time was when you closed it.
Here's a little demo that changes the files timestamp to whatever the
current time is:
(NOTE this does not test for existance of the file before settingthe time.)}
{*******************************************************************}
PROGRAM SetFileDateAndTimeDemo; { Jan 8/93, Greg Estabrooks. }
USES CRT, { IMPORT Clrscr,Writeln. }
DOS; { IMPORT SetFTime,PackTime,DateTime,}
{ GetTime,GetDate. }
VAR
Hour,Min,Sec,Sec100 :WORD; { Variables to hold current time. }
Year,Mon,Day,DayoW :WORD; { Variables to hold current date. }
F2Change :FILE; { Handle for file to change. }
NewTime :LONGINT; { Longint Holding new Date/Time. }
FTime :DateTime; { For use with packtime. }
BEGIN
Clrscr; { Clear the screen. }
GetTime(Hour,Min,Sec,Sec100); { Get Current System Time. }
GetDate(Year,Mon,Day,DayoW); { Get Current System Date. }
FTime.Year := Year; { Assign new year. }
FTime.Month:= Mon; { Assign new month. }
FTime.Day := Day; { Assign New Day. }
FTime.Hour:= Hour; { Assign New hour. }
FTime.Min := Min; { Assign New Minute. }
FTime.Sec := Sec; { Assign New Seconds. }
PackTime(FTime,NewTime); { Now covert Time/Date to a longint.}
Assign(F2Change,ParamStr(1)); { Assign file handle to file to change.}
Reset(F2Change); { Open file for reading. }
SetFTime(F2Change,NewTime); { Now change to our time. }
Close(F2Change); { Close File. }
END.{SetFileDateAndTimeDemo}
{*******************************************************************}
|
unit SpFoto_ImgSize;
interface
uses Classes,JPEG;
procedure GetJPGSize(const sFile: string; var wWidth, wHeight: word);
procedure GetPNGSize(const sFile: string; var wWidth, wHeight: word);
procedure GetGIFSize(const sGIFFile: string; var wWidth, wHeight: word);
procedure GetJpegPPI(const AFileName:String; var AResolutionUnit,AXPP,AYPP:Word);
implementation
uses SysUtils{, Dialogs};
function ReadMWord(f: TFileStream): word;
type
TMotorolaWord = record
case byte of
0: (Value: word);
1: (Byte1, Byte2: byte);
end;
var
MW: TMotorolaWord;
begin
{ It would probably be better to just read these two bytes in normally }
{ and then do a small ASM routine to swap them. But we aren't talking }
{ about reading entire files, so I doubt the performance gain would be }
{ worth the trouble. }
f.Read(MW.Byte2, SizeOf(Byte));
f.Read(MW.Byte1, SizeOf(Byte));
Result := MW.Value;
end;
procedure GetJPGSize(const sFile: string; var wWidth, wHeight: word);
var
jpg: TJpegImage;
begin
jpg := TJpegImage.Create;
try
jpg.Loadfromfile( sFile );
wWidth := jpg.Width;
wHeight := jpg.Height;
finally
jpg.free;
end;
end;
procedure GetPNGSize(const sFile: string; var wWidth, wHeight: word);
type
TPNGSig = array[0..7] of byte;
const
ValidSig: TPNGSig = (137,80,78,71,13,10,26,10);
var
Sig: TPNGSig;
f: tFileStream;
x: integer;
begin
FillChar(Sig, SizeOf(Sig), #0);
f := TFileStream.Create(sFile, fmOpenRead);
try
f.Read(Sig[0], SizeOf(Sig));
for x := Low(Sig) to High(Sig) do
if Sig[x] <> ValidSig[x] then exit;
f.Seek(18, 0);
wWidth := ReadMWord(f);
f.Seek(22, 0);
wHeight := ReadMWord(f);
finally
f.Free;
end;
end;
procedure GetGIFSize(const sGIFFile: string; var wWidth, wHeight: word);
type
TGIFHeader = record
Sig: array[0..5] of char;
ScreenWidth, ScreenHeight: word;
Flags, Background, Aspect: byte;
end;
TGIFImageBlock = record
Left, Top, Width, Height: word;
Flags: byte;
end;
var
f: file;
Header: TGifHeader;
ImageBlock: TGifImageBlock;
nResult: integer;
x: integer;
c: char;
DimensionsFound: boolean;
begin
wWidth := 0;
wHeight := 0;
if sGifFile = '' then
exit;
{$I-}
FileMode := 0; { read-only }
AssignFile(f, sGifFile);
reset(f, 1);
if IOResult <> 0 then
{ Could not open file }
exit;
{ Read header and ensure valid file. }
BlockRead(f, Header, SizeOf(TGifHeader), nResult);
if (nResult <> SizeOf(TGifHeader)) or (IOResult <> 0) or
(StrLComp('GIF', Header.Sig, 3) <> 0) then
begin
{ Image file invalid }
close(f);
exit;
end;
{ Skip color map, if there is one }
if (Header.Flags and $80) > 0 then
begin
x := 3 * (1 SHL ((Header.Flags and 7) + 1));
Seek(f, x);
if IOResult <> 0 then
begin
{ Color map thrashed }
close(f);
exit;
end;
end;
DimensionsFound := False;
FillChar(ImageBlock, SizeOf(TGIFImageBlock), #0);
{ Step through blocks. }
BlockRead(f, c, 1, nResult);
while (not EOF(f)) and (not DimensionsFound) do
begin
case c of
',': { Found image }
begin
BlockRead(f, ImageBlock, SizeOf(TGIFImageBlock), nResult);
if nResult <> SizeOf(TGIFImageBlock) then begin
{ Invalid image block encountered }
close(f);
exit;
end;
wWidth := ImageBlock.Width;
wHeight := ImageBlock.Height;
DimensionsFound := True;
end;
'y' : { Skip }
begin
{ NOP }
end;
{ nothing else. just ignore }
end;
BlockRead(f, c, 1, nResult);
end;
close(f);
{$I+}
end;
procedure GetJpegPPI(const AFileName:String;var AResolutionUnit,AXPP,AYPP:Word);
{Byte 13 gives the dimensions in which the pixel density is given later
in the header, 0 = pixels, 1 = DPI, 2 = dots per centimeter.
Bytes 14/15 give X density.
Bytes 16/17 give Y density.}
{Exif
48 00 00 00 01 00 00 00 48 00 00 00 01
72x72 PPI}
const
BufferSize = 50;
var
Buffer : String;
index : Integer;
FileStream : TFileStream;
xResolution: Word;
yResolution: Word;
ResolutionUnit:Word;
begin
FileStream := TFileStream.Create(AFileName,
fmOpenRead or fmShareDenyNone);
try
SetLength(Buffer, BufferSize);
FileStream.Read(buffer[1], BufferSize);
index := Pos('JFIF'+#$00, buffer);
if index > 0 then
begin
FileStream.Seek(index+6, soFromBeginning);
{ FileStream.Read(ResolutionUnit,1);
FileStream.Read(xResolution, 2);
FileStream.Read(yResolution, 2);
xResolution := Swap(xResolution);
yResolution := Swap(yResolution);
}
FileStream.Read(ResolutionUnit,1);
xResolution := ReadMWord(FileStream);
yResolution := ReadMWord(FileStream);
AXPP:=xResolution;
AYPP:=yResolution;
end
else //Exif or JFXX
Exit;
finally
FileStream.Free
end;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.TemplateDataPanel;
{$I Kitto.Defines.inc}
interface
uses
Ext, ExtChart, ExtData, ExtPascal, ExtPascalUtils,
EF.Tree,
Kitto.Metadata.DataView, Kitto.Ext.Base, Kitto.Ext.DataPanelLeaf;
type
TKExtTemplateDataPanel = class(TKExtDataPanelLeafController)
strict private
FDataView: TExtDataView;
procedure CreateTemplateView;
function ProcessTemplate(const ATemplate: string): string;
strict protected
procedure InitDefaults; override;
procedure SetViewTable(const AValue: TKViewTable); override;
procedure AddTopToolbarToolViewButtons; override;
function IsActionSupported(const AActionName: string): Boolean; override;
function GetSelectCall(const AMethod: TExtProcedure): TExtFunction; override;
function GetSelectConfirmCall(const AMessage: string; const AMethod: TExtProcedure): string; override;
published
end;
implementation
uses
Classes,
SysUtils, StrUtils,
EF.Localization, EF.Macros, EF.StrUtils,
Kitto.Types, Kitto.Ext.Utils, Kitto.Metadata.Models, Kitto.Metadata.Views,
Kitto.Ext.Session, Kitto.Ext.Controller, Kitto.Ext.XSLTools;
{ TKExtTemplateDataPanel }
procedure TKExtTemplateDataPanel.AddTopToolbarToolViewButtons;
begin
inherited AddToolViewButtons(ViewTable.FindNode('Controller/ToolViews'), TopToolbar);
end;
procedure TKExtTemplateDataPanel.CreateTemplateView;
var
LFileName: string;
LTemplate: string;
begin
LFileName := Session.Config.FindResourcePathName(Config.GetExpandedString('TemplateFileName'));
if LFileName <> '' then
LTemplate := TextFileToString(LFileName, TEncoding.UTF8)
else
LTemplate := Config.GetString('Template');
if LTemplate = '' then
FDataView.Tpl := 'TemplateFileName or Template parameters not specified.'
else
begin
TEFMacroExpansionEngine.Instance.Expand(LTemplate);
FDataView.Tpl := ProcessTemplate(LTemplate);
end;
FDataView.Store := ClientStore;
end;
function TKExtTemplateDataPanel.GetSelectCall(const AMethod: TExtProcedure): TExtFunction;
begin
Result := JSFunction(Format('ajaxDataViewSelection("yes", "", {params: {methodURL: "%s", dataView: %s, fieldNames: "%s"}});',
[MethodURI(AMethod), FDataView.JSName, Join(ViewTable.GetKeyFieldAliasedNames, ',')]));
end;
function TKExtTemplateDataPanel.GetSelectConfirmCall(const AMessage: string; const AMethod: TExtProcedure): string;
begin
Result := Format('selectDataViewConfirmCall("%s", "%s", %s, "%s", {methodURL: "%s", dataView: %s, fieldNames: "%s"});',
[_('Confirm operation'), AMessage, FDataView.JSName, ViewTable.Model.CaptionField.FieldName, MethodURI(AMethod),
FDataView.JSName, Join(ViewTable.GetKeyFieldAliasedNames, ',')]);
end;
function TKExtTemplateDataPanel.ProcessTemplate(const ATemplate: string): string;
var
I: Integer;
begin
Assert(Assigned(ViewTable));
Result := ATemplate;
for I := 0 to ViewTable.FieldCount - 1 do
begin
if ViewTable.Fields[I].IsPicture then
Result := ReplaceText(Result, '{' + ViewTable.Fields[I].AliasedName + '}',
'{' + ViewTable.Fields[I].GetURLFieldName + '}');
end;
end;
procedure TKExtTemplateDataPanel.InitDefaults;
begin
inherited;
FDataView := TExtDataView.CreateAndAddTo(Items);
FDataView.EmptyText := _('No data to display.');
FDataView.Region := rgCenter;
FDataView.AutoScroll := True;
end;
function TKExtTemplateDataPanel.IsActionSupported(const AActionName: string): Boolean;
begin
Result := True;
end;
procedure TKExtTemplateDataPanel.SetViewTable(const AValue: TKViewTable);
begin
Assert(Assigned(AValue));
inherited;
FDataView.Id := Config.GetString('TemplateView/Id');
FDataView.ItemSelector := Config.GetString('TemplateView/SelectorClass');
FDataView.OverClass := Config.GetString('TemplateView/OverClass');
if ViewTable.GetBoolean('Controller/IsMultiSelect', False) then
FDataView.MultiSelect := True
else
FDataView.SingleSelect := True;
// FDataView.On('dblclick', JSFunction('this, idx, node, e', GetAjaxCode(
// DefaultAction, )
CreateTemplateView;
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('TemplateDataPanel', TKExtTemplateDataPanel);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('TemplateDataPanel');
end.
|
unit cyhtAnalysisForm;
interface
uses
Forms, BaseForm, Classes, Controls, SysUtils, StdCtrls,
QuickSortList, QuickList_double, StockDayDataAccess,
define_price, define_dealitem,
Rule_CYHT;
type
TfrmCyhtAnalysisData = record
Rule_Cyht_Price: TRule_Cyht_Price;
StockDayDataAccess: TStockDayDataAccess;
end;
TfrmCyhtAnalysis = class(TfrmBase)
btncomputecyht: TButton;
edtstock: TEdit;
edtdatasrc: TComboBox;
lbl1: TLabel;
lbl2: TLabel;
procedure btncomputecyhtClick(Sender: TObject);
protected
fCyhtAnalysisData: TfrmCyhtAnalysisData;
function getDataSrcCode: integer;
function getDataSrcWeightMode: TWeightMode;
function getStockCode: integer;
procedure ComputeCYHT(ADataSrcCode: integer; AWeightMode: TWeightMode; AStockPackCode: integer); overload;
procedure ComputeCYHT(ADataSrcCode: integer; ADealItem: PRT_DealItem; AWeightMode: TWeightMode; AOutput: TALDoubleList); overload;
public
constructor Create(AOwner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
define_datasrc,
StockDayData_Load,
BaseStockApp;
constructor TfrmCyhtAnalysis.Create(AOwner: TComponent);
begin
inherited;
FillChar(fCyhtAnalysisData, SizeOf(fCyhtAnalysisData), 0);
end;
function TfrmCyhtAnalysis.getDataSrcCode: integer;
begin
Result := DataSrc_163;
end;
function TfrmCyhtAnalysis.getDataSrcWeightMode: TWeightMode;
begin
Result := weightNone;
end;
function TfrmCyhtAnalysis.getStockCode: integer;
begin
Result := getStockCodePack(edtstock.Text);
end;
procedure TfrmCyhtAnalysis.btncomputecyhtClick(Sender: TObject);
begin
ComputeCYHT(getDataSrcCode, getDataSrcWeightMode, getStockCode);
end;
procedure TfrmCyhtAnalysis.ComputeCYHT(ADataSrcCode: integer; ADealItem: PRT_DealItem; AWeightMode: TWeightMode; AOutput: TALDoubleList);
var
tmpSK: double;
begin
if nil = ADealItem then
exit;
if 0 = ADealItem.EndDealDate then
begin
if nil <> fCyhtAnalysisData.StockDayDataAccess then
begin
fCyhtAnalysisData.StockDayDataAccess.Free;
end;
fCyhtAnalysisData.StockDayDataAccess := TStockDayDataAccess.Create(ADealItem, ADataSrcCode, AWeightMode);
try
StockDayData_Load.LoadStockDayData(App, fCyhtAnalysisData.StockDayDataAccess);
if (0 < fCyhtAnalysisData.StockDayDataAccess.RecordCount) then
begin
if nil <> fCyhtAnalysisData.Rule_Cyht_Price then
begin
FreeAndNil(fCyhtAnalysisData.Rule_Cyht_Price);
end;
fCyhtAnalysisData.Rule_Cyht_Price := TRule_Cyht_Price.Create();
try
fCyhtAnalysisData.Rule_Cyht_Price.OnGetDataLength := fCyhtAnalysisData.StockDayDataAccess.DoGetRecords;
fCyhtAnalysisData.Rule_Cyht_Price.OnGetPriceOpen := fCyhtAnalysisData.StockDayDataAccess.DoGetStockOpenPrice;
fCyhtAnalysisData.Rule_Cyht_Price.OnGetPriceClose := fCyhtAnalysisData.StockDayDataAccess.DoGetStockClosePrice;
fCyhtAnalysisData.Rule_Cyht_Price.OnGetPriceHigh := fCyhtAnalysisData.StockDayDataAccess.DoGetStockHighPrice;
fCyhtAnalysisData.Rule_Cyht_Price.OnGetPriceLow := fCyhtAnalysisData.StockDayDataAccess.DoGetStockLowPrice;
fCyhtAnalysisData.Rule_Cyht_Price.Execute;
tmpSK := fCyhtAnalysisData.Rule_Cyht_Price.SK[fCyhtAnalysisData.StockDayDataAccess.RecordCount - 1];
AOutput.AddObject(tmpSK, TObject(ADealItem));
finally
FreeAndNil(fCyhtAnalysisData.Rule_Cyht_Price);
end;
end;
finally
FreeAndNil(fCyhtAnalysisData.StockDayDataAccess);
end;
end;
end;
procedure TfrmCyhtAnalysis.ComputeCYHT(ADataSrcCode: integer; AWeightMode: TWeightMode; AStockPackCode: integer);
var
i: integer;
tmpStockItem: PRT_DealItem;
tmpCyht: TALDoubleList;
tmpResultOutput: TStringList;
begin
tmpCyht := TALDoubleList.Create;
try
tmpCyht.Duplicates := lstDupAccept;
if 0 <> ADataSrcCode then
begin
tmpStockItem := TBaseStockApp(App).StockItemDB.FindItem(IntToStr(AStockPackCode));
ComputeCYHT(ADataSrcCode, tmpStockItem, AWeightMode, tmpCyht);
end else
begin
for i := 0 to TBaseStockApp(App).StockItemDB.RecordCount - 1 do
begin
tmpStockItem := TBaseStockApp(App).StockItemDB.RecordItem[i];
ComputeCYHT(ADataSrcCode, tmpStockItem, AWeightMode, tmpCyht);
end;
end;
tmpCyht.Sort;
tmpResultOutput := TStringList.Create;
try
for i := 0 to tmpCyht.Count - 1 do
begin
tmpStockItem := PRT_DealItem(tmpCyht.Objects[i]);
tmpResultOutput.Add(FloatToStr(tmpCyht[i]) + ' -- ' + tmpStockItem.sCode);
end;
tmpResultOutput.SaveToFile('Cyht' + FormatDateTime('yyyymmdd_hhnnss', now) + '.txt');
finally
tmpResultOutput.Free;
end;
finally
tmpCyht.Free;
end;
end;
end.
|
unit uAutorController;
interface
uses SysUtils, uAutorModel, uPadraoController, Dialogs, StrUtils;
type
TAutorController = class(TPadraoController)
public
function GravarRegistro(AAutorModel: TAutorModel): Boolean;
function ExcluirRegistro(ACodigo: Integer): Boolean;
end;
implementation
{ TAutorController }
function TAutorController.ExcluirRegistro(ACodigo: Integer): Boolean;
begin
Result := True;
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Text :=
'DELETE FROM AUTOR WHERE CODIGO = :codigo';
FQuery.ParamByName('codigo').AsInteger := ACodigo;
try
FQuery.ExecSQL();
frMain.FLogController.GravaLog('Excluiu Autor '+ ACodigo.ToString);
except
on E: Exception do
begin
Result := False;
frMain.FLogController.GravaLog('Erro ao excluir Autor '+ ACodigo.ToString);
ShowMessage('Ocorreu um erro ao excluir o registro');
end;
end;
end;
function TAutorController.GravarRegistro(AAutorModel: TAutorModel): Boolean;
var LSQL: String;
LCodigo: Integer;
LInsert: Boolean;
begin
Result := True;
LInsert := AAutorModel.Codigo = 0;
if LInsert then
begin
LCodigo := RetornaPrimaryKey('CODIGO', 'AUTOR');
LSQL :=
'INSERT INTO AUTOR VALUES (:codigo, :nome)';
end
else
begin
LCodigo := AAutorModel.Codigo;
LSQL :=
'UPDATE AUTOR SET NOME = :nome WHERE CODIGO = :codigo';
end;
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Text := LSQL;
FQuery.ParamByName('codigo').AsInteger := LCodigo;
FQuery.ParamByName('nome').AsString := AAutorModel.Nome;
try
FQuery.ExecSQL();
frMain.FLogController.GravaLog(
IfThen(LInsert, 'Inseriu ', 'Editou ') +
'Autor: código: ' + LCodigo.ToString +
' nome: ' + AAutorModel.Nome);
except
on E: Exception do
begin
Result := False;
frMain.FLogController.GravaLog(
'Erro ao '+
IfThen(LInsert, 'Inserir ', 'Editar ') +
'Autor: código: ' + LCodigo.ToString +
' nome: ' + AAutorModel.Nome);
ShowMessage('Ocorreu um erro na inclusão do autor.');
end;
end;
end;
end.
|
unit frmExamples;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
ExtCtrls,
StdCtrls,
ComCtrls, Vcl.Imaging.pngimage;
type
TfrmUsageExamples = class(TForm)
scrlbx1: TScrollBox;
mmo1: TMemo;
img1: TImage;
pgc1: TPageControl;
ts1: TTabSheet;
mmo2: TMemo;
img2: TImage;
mmo3: TMemo;
img3: TImage;
mmo4: TMemo;
img4: TImage;
procedure btnExtractRunAsLouClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmUsageExamples : TfrmUsageExamples;
implementation
{$R *.dfm}
procedure TfrmUsageExamples.btnExtractRunAsLouClick(Sender: TObject);
var
sPath : string;
begin
if
(MessageDlg('Are you sure you want to extract RunAsLOU.exe to the program''s current directory?',
mtConfirmation, [mbYes, mbNo], 0) <> mrYes) then
begin
Exit;
end;
//
sPath := ExcludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
// if main.Form1.ExtractRunAsLou then
// begin
// MessageBox(0, PChar('RunAsLOU.exe succesfully extracted to: ' + #13#10
// + '<' + sPath + '\>'), '', MB_ICONINFORMATION or MB_OK);
// end
// else
// begin
// MessageBox(0, PChar('RunAsLOU.exe succesfully extracted to: ' + #13#10
// + '<' + sPath + '\>'), '', MB_ICONERROR or MB_OK);
// end;
end;
end.
|
unit E_VersionsInfo;
interface
type
TVersionType = (vtApplication, vtDatabase, vtMap);
TVersions = array[TVersionType] of string;
const
CVersionTypeNames: TVersions =
(
'Версия программы: ',
'Версия базы данных: ',
'Версия карты: '
);
var
GVersionsInfo: TVersions =
(
'нет данных',
'нет данных',
'нет данных'
);
implementation
end.
|
unit uDMValidateInventoryTextFile;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDMValidateTextFile, DB, ADODB;
type
TDMValidateInventoryTextFile = class(TDMValidateTextFile)
private
function ValidateIsEmpty(Field, Erro: String): Boolean;
function ValidateQty: Boolean;
{ Private declarations }
public
function Validate: Boolean; override;
end;
var
DMValidateInventoryTextFile: TDMValidateInventoryTextFile;
implementation
{$R *.dfm}
{ TDMValidateInventoryTextFile }
function TDMValidateInventoryTextFile.Validate: Boolean;
begin
TextFile.First;
while not TextFile.Eof do
begin
if ValidateIsEmpty('Model','Empty Model') then
if ValidateIsEmpty('Category','Empty Category') and (ImpExpConfig.Values['UseQty'] = 'Y') then
ValidateQty;
TextFile.Next;
end;
Result := True;
end;
function TDMValidateInventoryTextFile.ValidateIsEmpty(Field,
Erro: String): Boolean;
begin
Result := (LinkedColumns.Values[Field] <> '');
if Result then
Result := TextFile.FieldByName(LinkedColumns.Values[Field]).AsString <> '';
TextFile.Edit;
TextFile.FieldByName('Warning').AsString := '';
TextFile.FieldByName('Validation').AsBoolean := Result;
if not Result then
TextFile.FieldByName('Warning').AsString := Erro;
TextFile.Post;
end;
function TDMValidateInventoryTextFile.ValidateQty: Boolean;
begin
try
Result := ValidateIsEmpty('Qty','Empty Qty');
if Result then
StrtoFloat(TextFile.FieldByName(LinkedColumns.Values['Qty']).AsString);
except
Result := False;
TextFile.Edit;
TextFile.FieldByName('Validation').AsBoolean := Result;
TextFile.FieldByName('Warning').AsString := 'Qty Invalid';
end;
end;
end.
|
unit curv;
interface
uses define_types, matmath, sysutils, Dialogs;
procedure GenerateCurv(fnm: string; var faces: TFaces; vertices: TVertices; isSmooth: boolean);
procedure GenerateCurvRGB(fnm: string; vertexRGBA : TVertexRGBA; num_f: integer);
implementation
function curvK(v0, v1, n0, n1: TPoint3f): single;
//http://computergraphics.stackexchange.com/questions/1718/what-is-the-simplest-way-to-compute-principal-curvature-for-a-mesh-triangle
//local curvature for an edge
// k = ((n1-n0)⋅(n1-p0))/len(p1,p0)
var
len: single;
begin
result := 0;
len := vectorLength(v0,v1);
if len <= 0 then exit; //avoid div/0
result := vectorDot(vectorSubtractF(n1,n0), vectorSubtractF(v1,v0));
result := result / len;
end;
procedure SaveCurv(fnm: string; k: TFloats; num_f: integer);
//simple format used by Freesurfer BIG-ENDIAN
// https://github.com/bonilhamusclab/MRIcroS/blob/master/%2BfileUtils/%2Bpial/readPial.m
// http://www.grahamwideman.com/gw/brain/fs/surfacefileformats.htm
var
f: File;
i: integer;
num_vS, num_v, num_fS, ValsPerVertex : LongWord;
b : byte = 255;
kS: TFloats;
begin
num_v := length(k);
if (num_v < 3) or (num_f < 1) then exit;
num_vS := num_v;
num_fS := num_f;
ValsPerVertex := 1;
AssignFile(f, fnm);
FileMode := fmOpenWrite;
try
Rewrite(f,1);
blockwrite(f, b, 1 ); //since these files do not have a file extension, check first 3 bytes "0xFFFFFF"
blockwrite(f, b, 1 ); //since these files do not have a file extension, check first 3 bytes "0xFFFFFF"
blockwrite(f, b, 1 ); //since these files do not have a file extension, check first 3 bytes "0xFFFFFF"
{$IFDEF ENDIAN_LITTLE}
SwapLongWord(num_vS);
SwapLongWord(num_fS);
SwapLongWord(ValsPerVertex);
{$ENDIF}
blockwrite(f, num_vS, 4 ); //uint32
blockwrite(f, num_fS, 4 ); //uint32
blockwrite(f, ValsPerVertex, 4 ); //uint32
{$IFDEF ENDIAN_LITTLE}
setlength(kS, num_v);
for i := 0 to (num_v-1) do begin
kS[i] := k[i];
SwapSingle(kS[i]);
end;
blockwrite(f,kS[0], 4 * num_v);
setlength(kS, 0);
{$ELSE}
blockwrite(f,k[0], 4 * num_v);
{$ENDIF}
CloseFile(f);
except
// If there was an error the reason can be found here
on E: EInOutError do begin
{$IFDEF UNIX} writeln('Unable to create '+fnm+' Details: '+ E.ClassName+ '/'+ E.Message);{$ENDIF}
Showmessage('Unable to create '+fnm+' Details: '+ E.ClassName+ '/'+ E.Message);
end;
end;
end;
procedure GenerateCurvRGB(fnm: string; vertexRGBA : TVertexRGBA; num_f: integer);
var
i: integer;
k: TFloats;
begin
//vertexRGBA : array of TRGBA;
if length(vertexRGBA) < 3 then exit;
setlength(k, length(vertexRGBA));
for i := 0 to (length(vertexRGBA)-1) do
k[i] := 0.5 * (1 - ((vertexRGBA[i].r+vertexRGBA[i].g+vertexRGBA[i].b) * (1/765)));
SaveCurv(fnm, k, num_f);
k := nil;
end;
procedure SmoothK (var vK : TFloats; var faces: TFaces);
//smooth curvature across neighbors
//vK : one curvature value k for each vertex, faces: triangle face indices
var
inK: TFloats;
nK : array of integer;
i, num_v, x, y, z: integer;
begin
num_v := length(vK);
setlength(inK, num_v);
setlength(nK, num_v);
//tK := Copy(vK, Low(vK), num_v);
for i := 0 to (num_v-1) do begin
inK[i] := vK[i];
vK[i] := 0;
nK[i] := 0;
end;
for i := 0 to (length(faces)-1) do begin //compute the normal for each face
X := faces[i].X;
Y := faces[i].Y;
Z := faces[i].Z;
nK[X] := nK[X] + 1;
nK[Y] := nK[Y] + 1;
nK[Z] := nK[Z] + 1;
vK[X] := vK[X] + inK[X];
vK[Y] := vK[Y] + inK[Y];
vK[Z] := vK[Z] + inK[Z];
end;
setlength(inK, 0);
for i := 0 to (num_v-1) do
if nK[i] > 1 then
vK[i] := vK[i] / nK[i];
setlength(nK, 0);
end;
procedure GenerateCurv(fnm: string; var faces: TFaces; vertices: TVertices; isSmooth: boolean);
var
vNorm : array of TPoint3f;
vK : TFloats;
vnK : array of integer;
fNorm: TPoint3f;
k, mx, scale: single;
i, X, Y, Z: integer;
begin
if (length(vertices) < 3) or (length(faces) < 1) then exit;
//compute surface normals...
setlength(vNorm, length(vertices));
fNorm := ptf(0,0,0);
for i := 0 to (length(vertices)-1) do
vNorm[i] := fNorm;
for i := 0 to (length(faces)-1) do begin //compute the normal for each face
fNorm := getSurfaceNormal(vertices[faces[i].X], vertices[faces[i].Y], vertices[faces[i].Z]);
vectorAdd(vNorm[faces[i].X] , fNorm);
vectorAdd(vNorm[faces[i].Y] , fNorm);
vectorAdd(vNorm[faces[i].Z] , fNorm);
end;
for i := 0 to (length(vertices)-1) do
vectorNormalize(vNorm[i]);
//compute curv
setlength(vK, length(vertices));
setlength(vnK, length(vertices));
for i := 0 to (length(vertices)-1) do begin
vK[i] := 0.0;
vnK[i] := 0;
end;
for i := 0 to (length(faces)-1) do begin //compute the curvature for each edge
X := faces[i].X;
Y := faces[i].Y;
Z := faces[i].Z;
//we will add curvature of two edges to each vertex of triangle
inc(vnK[X],2);
inc(vnK[Y],2);
inc(vnK[Z],2);
//compute edge X-Y
k := curvK(vertices[X], vertices[Y], vNorm[X], vNorm[Y]);
vK[X] := vK[X]+ k;
vK[Y] := vK[Y]+ k;
//compute edge Y-Z
k := curvK(vertices[Y], vertices[Z], vNorm[Y], vNorm[Z]);
vK[Y] := vK[Y]+ k;
vK[Z] := vK[Z]+ k;
//compute edge Z-X
k := curvK(vertices[Z], vertices[X], vNorm[Z], vNorm[X]);
vK[Z] := vK[Z]+ k;
vK[X] := vK[X]+ k;
end;
//compute mean curvature for each vertex
for i := 0 to (length(vertices)-1) do begin
if vnK[i] > 0 then
vK[i] := vK[i]/vnK[i];
end;
//optional: smooth curves
if (isSmooth) then
SmoothK (vK, faces);
//normalize curvature from
mx := vK[0];
for i := 0 to (length(vertices)-1) do
if abs(vK[i]) > mx then
mx := abs(vK[i]);
if mx = 0.0 then exit; //no variability: a flat plane?
scale := 1/mx; //-1..1
for i := 0 to (length(vertices)-1) do
vK[i] := (vK[i] * scale) * -1; //-1 to match freesurfer
SaveCurv(fnm, vK, length(faces));
end;
end.
|
{******************************************************************************}
{ }
{ Delphi cross platform socket library }
{ }
{ Copyright (c) 2017 WiNDDRiVER(soulawing@gmail.com) }
{ }
{ Homepage: https://github.com/winddriver/Delphi-Cross-Socket }
{ }
{******************************************************************************}
unit MyCat.Util.Logger;
interface
uses
System.Classes, System.SysUtils, System.IOUtils, System.Diagnostics,
System.Generics.Collections, Utils.Utils, Utils.DateTime;
type
TLogType = (ltNormal, ltWarning, ltError, ltException);
TLogTypeSets = set of TLogType;
const
LogTypeStr: array [TLogType] of string = ('', 'WAR', 'ERR', 'EXP');
type
ILogger = interface
['{D9AE7F7B-95DE-4840-98FA-A49A4368D658}']
function GetFilters: TLogTypeSets;
procedure SetFilters(const Value: TLogTypeSets);
function GetLogDir: string;
function GetLogFileName(ALogType: TLogType; ADate: TDateTime): string;
procedure AppendLog(const ALog: string; const ATimeFormat: string; ALogType: TLogType = ltNormal; const CRLF: string = ''); overload;
procedure AppendLog(const ALog: string; ALogType: TLogType = ltNormal; const CRLF: string = ''); overload;
procedure AppendLog(const Fmt: string; const Args: array of const; const ATimeFormat: string; ALogType: TLogType = ltNormal; const CRLF: string = ''); overload;
procedure AppendLog(const Fmt: string; const Args: array of const; ALogType: TLogType = ltNormal; const CRLF: string = ''); overload;
procedure Flush;
property Filters: TLogTypeSets read GetFilters write SetFilters;
end;
TLogItem = record
Time: TDateTime;
Text: string;
end;
TLogBuffer = TList<TLogItem>;
TLogger = class(TInterfacedObject, ILogger)
private const
FLUSH_INTERVAL = 200;
private
FFilters: TLogTypeSets;
class var FLogger: ILogger;
class constructor Create;
class destructor Destroy;
function GetFilters: TLogTypeSets;
procedure SetFilters(const Value: TLogTypeSets);
private
FBuffer: array [TLogType] of TLogBuffer;
FBufferLock: array [TLogType] of TObject;
FShutdown, FQuit: Boolean;
procedure _Lock(const ALogType: TLogType); inline;
procedure _Unlock(const ALogType: TLogType); inline;
procedure _WriteLogFile(const ALogType: TLogType);
procedure _WriteAllLogFiles; inline;
procedure _CreateWriteThread;
procedure _Shutdown; inline;
protected
procedure _AppendLogToBuffer(const S: string; ALogType: TLogType);
public
constructor Create; virtual;
destructor Destroy; override;
function GetLogDir: string;
function GetLogFileName(ALogType: TLogType; ADate: TDateTime): string;
procedure AppendLog(const ALog: string; const ATimeFormat: string; ALogType: TLogType = ltNormal; const CRLF: string = ''); overload;
procedure AppendLog(const ALog: string; ALogType: TLogType = ltNormal; const CRLF: string = ''); overload;
procedure AppendLog(const Fmt: string; const Args: array of const; const ATimeFormat: string; ALogType: TLogType = ltNormal; const CRLF: string = ''); overload;
procedure AppendLog(const Fmt: string; const Args: array of const; ALogType: TLogType = ltNormal; const CRLF: string = ''); overload;
procedure Flush;
property Filters: TLogTypeSets read GetFilters write SetFilters;
class property Logger: ILogger read FLogger;
end;
procedure AppendLog(const ALog: string; const ATimeFormat: string; ALogType: TLogType = ltNormal; const CRLF: string = ';'); overload;
procedure AppendLog(const ALog: string; ALogType: TLogType = ltNormal; const CRLF: string = ';'); overload;
procedure AppendLog(const Fmt: string; const Args: array of const; const ATimeFormat: string; ALogType: TLogType = ltNormal; const CRLF: string = ';'); overload;
procedure AppendLog(const Fmt: string; const Args: array of const; ALogType: TLogType = ltNormal; const CRLF: string = ';'); overload;
function Logger: ILogger;
var
// 默认日志目录
// 留空由程序自动设定
DefaultLogDir: string = '';
implementation
class constructor TLogger.Create;
begin
FLogger := TLogger.Create;
end;
class destructor TLogger.Destroy;
begin
end;
constructor TLogger.Create;
var
I: TLogType;
begin
FFilters := [ltNormal, ltWarning, ltError, ltException];
for I := Low(TLogType) to High(TLogType) do
begin
FBuffer[I] := TLogBuffer.Create;
FBufferLock[I] := TObject.Create;
end;
_CreateWriteThread;
end;
destructor TLogger.Destroy;
var
I: TLogType;
begin
Flush;
_Shutdown;
for I := Low(TLogType) to High(TLogType) do
begin
FreeAndNil(FBuffer[I]);
FreeAndNil(FBufferLock[I]);
end;
inherited Destroy;
end;
procedure TLogger.Flush;
begin
_WriteAllLogFiles;
end;
function TLogger.GetFilters: TLogTypeSets;
begin
Result := FFilters;
end;
function TLogger.GetLogDir: string;
begin
if (DefaultLogDir <> '') then
Result := DefaultLogDir
else
Result :=
{$IFDEF MSWINDOWS}
TUtils.AppPath +
{$ELSE}
TUtils.AppDocuments +
{$ENDIF}
TUtils.AppName + '.log' + PathDelim;
end;
function TLogger.GetLogFileName(ALogType: TLogType; ADate: TDateTime): string;
begin
Result := LogTypeStr[ALogType];
if (Result <> '') then
Result := Result + '-';
Result := Result + TUtils.DateTimeToStr(ADate, 'YYYY-MM-DD') + '.log';
end;
procedure TLogger.SetFilters(const Value: TLogTypeSets);
begin
FFilters := Value;
end;
procedure TLogger._CreateWriteThread;
begin
TThread.CreateAnonymousThread(
procedure
var
LWatch: TStopwatch;
begin
LWatch := TStopwatch.StartNew;
while not FShutdown do
begin
if (LWatch.ElapsedTicks > FLUSH_INTERVAL) then
begin
Flush;
LWatch.Reset;
LWatch.Start;
end;
Sleep(10);
end;
Flush;
FQuit := True;
end).Start;
end;
procedure TLogger._Lock(const ALogType: TLogType);
begin
System.TMonitor.Enter(FBufferLock[ALogType]);
end;
procedure TLogger._Shutdown;
begin
FShutdown := True;
while not FQuit do
Sleep(1);
end;
procedure TLogger._Unlock(const ALogType: TLogType);
begin
System.TMonitor.Exit(FBufferLock[ALogType]);
end;
procedure TLogger._WriteLogFile(const ALogType: TLogType);
var
LLogDir, LLogFile: string;
LLastTime: TDateTime;
I: Integer;
LLogItem: TLogItem;
LBuffer: TBytesStream;
procedure _WriteLogToBuffer(const ALogItem: TLogItem);
var
LBytes: TBytes;
begin
LBytes := TEncoding.UTF8.GetBytes(ALogItem.Text);
LBuffer.Seek(0, TSeekOrigin.soEnd);
LBuffer.Write(LBytes, Length(LBytes));
end;
procedure _WriteBufferToFile(const ALogFile: string);
var
LStream: TFileStream;
LBytes: TBytes;
begin
try
LStream := TFile.Open(ALogFile, TFileMode.fmOpenOrCreate, TFileAccess.faReadWrite, TFileShare.fsRead);
try
LStream.Seek(0, TSeekOrigin.soEnd);
LBytes := LBuffer.Bytes;
SetLength(LBytes, LBuffer.Size);
LStream.Write(LBytes, Length(LBytes));
finally
FreeAndNil(LStream);
end;
except
end;
end;
begin
_Lock(ALogType);
try
if (FBuffer[ALogType].Count <= 0) then Exit;
LLastTime := 0;
LLogDir := GetLogDir;
ForceDirectories(LLogDir);
LBuffer := TBytesStream.Create(nil);
try
for I := 0 to FBuffer[ALogType].Count - 1 do
begin
LLogItem := FBuffer[ALogType].Items[I];
_WriteLogToBuffer(LLogItem);
if not LLogItem.Time.IsSameDay(LLastTime)
or (I >= FBuffer[ALogType].Count - 1) then
begin
LLastTime := LLogItem.Time;
LLogFile := LLogDir + GetLogFileName(ALogType, LLogItem.Time);
_WriteBufferToFile(LLogFile);
LBuffer.Clear;
end;
end;
FBuffer[ALogType].Clear;
finally
FreeAndNil(LBuffer);
end;
finally
_Unlock(ALogType);
end;
end;
procedure TLogger._WriteAllLogFiles;
var
I: TLogType;
begin
for I := Low(TLogType) to High(TLogType) do
_WriteLogFile(I);
end;
procedure TLogger.AppendLog(const ALog: string; const ATimeFormat: string; ALogType: TLogType; const CRLF: string);
var
LText: string;
begin
if not (ALogType in FFilters) then Exit;
if (CRLF <> '') then
LText := StringReplace(ALog, sLineBreak, CRLF, [rfReplaceAll])
else
LText := ALog;
LText := TUtils.DateTimeToStr(Now, ATimeFormat) + ' ' + LText + sLineBreak;
_AppendLogToBuffer(LText, ALogType);
end;
procedure TLogger.AppendLog(const ALog: string; ALogType: TLogType; const CRLF: string);
begin
AppendLog(ALog, 'HH:NN:SS:ZZZ', ALogType, CRLF);
end;
procedure TLogger.AppendLog(const Fmt: string; const Args: array of const; const ATimeFormat: string; ALogType: TLogType; const CRLF: string);
begin
AppendLog(TUtils.ThreadFormat(Fmt, Args), ATimeFormat, ALogType, CRLF);
end;
procedure TLogger.AppendLog(const Fmt: string; const Args: array of const; ALogType: TLogType; const CRLF: string);
begin
AppendLog(TUtils.ThreadFormat(Fmt, Args), ALogType, CRLF);
end;
procedure TLogger._AppendLogToBuffer(const S: string; ALogType: TLogType);
var
LLogItem: TLogItem;
begin
_Lock(ALogType);
try
LLogItem.Time := Now;
LLogItem.Text := S;
FBuffer[ALogType].Add(LLogItem);
finally
_Unlock(ALogType);
end;
end;
procedure AppendLog(const ALog: string; const ATimeFormat: string; ALogType: TLogType = ltNormal; const CRLF: string = ';');
begin
Logger.AppendLog(ALog, ATimeFormat, ALogType, CRLF);
end;
procedure AppendLog(const ALog: string; ALogType: TLogType = ltNormal; const CRLF: string = ';');
begin
Logger.AppendLog(ALog, ALogType, CRLF);
end;
procedure AppendLog(const Fmt: string; const Args: array of const; const ATimeFormat: string; ALogType: TLogType = ltNormal; const CRLF: string = ';');
begin
Logger.AppendLog(Fmt, Args, ATimeFormat, ALogType, CRLF);
end;
procedure AppendLog(const Fmt: string; const Args: array of const; ALogType: TLogType = ltNormal; const CRLF: string = ';');
begin
Logger.AppendLog(Fmt, Args, ALogType, CRLF);
end;
function Logger: ILogger;
begin
Result := TLogger.FLogger;
end;
end.
|
unit frm_Upgrade;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.Grids, Vcl.Menus;
type
TfrmUpgrade = class(TForm)
pnl2: TPanel;
lbl1: TLabel;
lblVersion: TLabel;
btnOK: TButton;
edtVersion: TEdit;
mmo: TMemo;
sgdFiles: TStringGrid;
pmFile: TPopupMenu;
mniAdd: TMenuItem;
mniDelete: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure mniAddClick(Sender: TObject);
procedure mniDeleteClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
UpgradePath: string;
implementation
uses
frm_DM, UPCommon, UPMsgPack, Xml.XMLDoc, Xml.XMLIntf;
// 获取版本号
function GetFileVersionStr(const AFileName: string): string;
var
FileName: string;
InfoSize, Wnd: DWORD;
VerBuf: Pointer;
FI: PVSFixedFileInfo;
VerSize: DWORD;
begin
Result := '-1';
// GetFileVersionInfo modifies the filename parameter data while parsing.
// Copy the string const into a local variable to create a writeable copy.
FileName := AFileName;
UniqueString(FileName);
InfoSize := GetFileVersionInfoSize(PChar(FileName), Wnd);
if InfoSize <> 0 then
begin
GetMem(VerBuf, InfoSize);
try
if GetFileVersionInfo(PChar(FileName), Wnd, InfoSize, VerBuf) then
begin
if VerQueryValue(VerBuf, '\', Pointer(FI), VerSize) then
begin
Result := IntToStr(HIWORD(FI.dwFileVersionMS)) + '.' +
IntToStr(LOWORD(FI.dwFileVersionMS)) + '.' +
IntToStr(HIWORD(FI.dwFileVersionLS)) + '.' +
IntToStr(LOWORD(FI.dwFileVersionLS));
end;
end;
finally
FreeMem(VerBuf);
end;
end;
end;
{$R *.dfm}
procedure TfrmUpgrade.btnOKClick(Sender: TObject);
var
vXmlDoc: IXMLDocument;
vFileNode: IXMLNode;
vR: Integer;
begin
if sgdFiles.RowCount <= 1 then Exit;
vXmlDoc := TXMLDocument.Create(nil);
vXmlDoc.Active := True;
vXmlDoc.Version := '1.0';
vXmlDoc.DocumentElement := vXmlDoc.CreateNode('HCUpdateFile');
vXmlDoc.DocumentElement.Attributes['upfver'] := '1';
for vR := 1 to sgdFiles.RowCount - 1 do
begin
vFileNode := vXmlDoc.DocumentElement.AddChild('file' + vR.ToString);
vFileNode.Text := sgdFiles.Cells[1, vR]; // name
vFileNode.Attributes['version'] := sgdFiles.Cells[0, vR];
vFileNode.Attributes['path'] := sgdFiles.Cells[2, vR];
vFileNode.Attributes['size'] := sgdFiles.Cells[4, vR];
end;
if dm.ExecSql(Format('INSERT INTO UpdateInfo (version, memo, files) VALUES (''%s'', ''%s'', ''%s'')',
[edtVersion.Text, mmo.Text, vXmlDoc.XML.Text]))
then
begin
ShowMessage('提交成功!');
btnOK.Enabled := False;
end;
end;
procedure TfrmUpgrade.FormCreate(Sender: TObject);
begin
sgdFiles.ColCount := 5;
sgdFiles.ColWidths[0] := 80;
sgdFiles.ColWidths[1] := 100;
sgdFiles.ColWidths[2] := 100;
sgdFiles.ColWidths[3] := 100;
sgdFiles.ColWidths[4] := 0;
//
sgdFiles.Cells[0, 0] := '版本';
sgdFiles.Cells[1, 0] := '文件名';
sgdFiles.Cells[2, 0] := '客户端路径';
sgdFiles.Cells[3, 0] := '大小';
end;
procedure TfrmUpgrade.mniAddClick(Sender: TObject);
var
vDlg: TOpenDialog;
vFileName, vPath: string;
vFileHandle: THandle;
vFileSize: Cardinal;
i: Integer;
begin
vDlg := TOpenDialog.Create(Self);
try
vDlg.InitialDir := UpgradePath;
if vDlg.Execute then
begin
if vDlg.FileName <> '' then
begin
vFileHandle := FileOpen(vDlg.FileName, 0);
try
vFileSize := GetFileSize(vFileHandle, nil);
finally
FileClose(vFileHandle);
end;
if vFileSize > MAX_OBJECT_SIZE then
begin
ShowMessage(Format('文件体积超过允许的最大值 %s!', [BytesToStr(MAX_OBJECT_SIZE)]));
Exit;
end;
vFileName := ExtractFileName(vDlg.FileName);
vPath := StringReplace(ExtractFilePath(vDlg.FileName), UpgradePath, '', [rfReplaceAll, rfIgnoreCase]);
for i := 1 to sgdFiles.RowCount - 1 do
begin
if (sgdFiles.Cells[1, i] = vFileName) and (sgdFiles.Cells[2, i] = vPath) then
begin
ShowMessage('已经存在此文件!');
Exit;
end;
end;
sgdFiles.RowCount := sgdFiles.RowCount + 1;
if sgdFiles.RowCount > 1 then
sgdFiles.FixedRows := 1;
sgdFiles.Cells[0, sgdFiles.RowCount - 1] := GetFileVersionStr(vDlg.FileName);
sgdFiles.Cells[1, sgdFiles.RowCount - 1] := vFileName;
sgdFiles.Cells[2, sgdFiles.RowCount - 1] := vPath;
sgdFiles.Cells[3, sgdFiles.RowCount - 1] := BytesToStr(vFileSize);
sgdFiles.Cells[4, sgdFiles.RowCount - 1] := vFileSize.ToString;
end;
end;
finally
FreeAndNil(vDlg);
end;
end;
procedure TfrmUpgrade.mniDeleteClick(Sender: TObject);
var
vR, vC: Integer;
begin
if sgdFiles.Row < 1 then Exit;
for vR := sgdFiles.Row to sgdFiles.RowCount - 2 do
begin
for vC := 0 to 3 do
sgdFiles.Cells[vC, vR] := sgdFiles.Cells[vC, vR + 1];
end;
sgdFiles.RowCount := sgdFiles.RowCount - 1;
if sgdFiles.RowCount <= 1 then
sgdFiles.FixedRows := 0;
end;
end.
|
(*
NUME AUTOR: Mitrea Cristina
SUBIECT: Teoria grafelor
TEMA NR.: 2
PROBLEMA:
Se da un graf G=(X,U) si doua varfuri p,q ale acestui graf. Sa se conceapa
un algorim care determina un drum de valoare minima de la varful p la varful
q folosind si algoritmul lui Moore-Dijkstra var. 1.
Se considera ca G=(X,U) (X={1,2,3,...,n}) unde G este un graf cu valori
pozitive ale arcelor
NOTATII:
INFINIT-valoarea drumului de la vf. i la vf. j, pntru care nu exista drum
de la i la j
l(i,j)=l(u) : valoarea arcului (i,j)
| INFINIT daca i=j |
v(i,j)=| l(i,j) daca (i,j) apartine lui U | : matricea valorilor arcelor
| INFINIT daca (i,j) nu apartine lui U |
H(j)=| 0, daca j=p | : valoarea minima
| min(H(i)+v(i,j), i=1,n) daca j<>p | a drumurilor de la p la j
: daca nu exista drum,
val min=INFINIT
S(i)=|0, daca pentru vf. i s-a det. val. min a drumului de la p la i|
|i, altfel |
S-multimea vf. pt care s-a det. val. min a drumului de la p la i
d(i)= al i-lea varf dintr-un drum de valoare minima de la p la q
PROIECTARE:
Algoritmul lui Moore-Dijkstra care determina valorile minime drumurilor
de la varful 1 la vf. i, unde i apartine multimii {1,...,n}-{p}:
(a)initialzari
H(1):=0;
H(i):=|l(p,i), i succesor al lui 1|
|INFINIT,altfel |
s:={2,3,..,n}
(b)testul de stop
| * fie j din S a.i. H(j)=min{H(i)/i din S}
s:=S-{j}
daca S={} atunci stop
sfdaca
(c)iteratia de baza
pentru | * i din intersectie de Succesori(j) si S executa
H(i):=min{H(I),H(j)+v(j,i)
sfpentru
goto (b)
Algoritmul lui Moore-Dijkstra adaptat pentru determinarea minimului
lungimilor drumurilor de la p la i unde i apartine multimii {1,...,n}-{p}:
in algoritmul anterior se inlocuieste vf. 1 cu vf. p(se poneste de la p) si
se calculeaza valorile minime ale drumurilor de la vf p la toate varfurile
grafului.
H(p):=0;
H(i):=|l(p,i), i succesor al lui p|
|INFINIT,altfel |
s:={2,3,..,n}
repeta
| * fie j din S a.i. H(j)=min{H(i)/i din S}
s:=S-{j}
pentru | * i din intersectie de Succesori(j) si S executa
H(i):=min{H(I),H(j)+v(j,i)
sfpentru
pana cand S={}
Algoritm pentru det. unui drum de lungime minima de la varful 1 la varful i:
(a)initializari
citeste i
j:=i
k:=1,
d(k):=j
(b)iteratia de baza
Cat timp d(k)<>j executa
| * Fie z un predecesor al lui j pentru care H(z)+v(z,j)=H(j))
j:=z
k:=k+1
d(k):=j
SfCat
Algoritm adaptat pentru det. unui drum de lungime minima de la vf. p la
vf. q:
in algoritmul anterior se inlocuieste vf. 1 cu vf. q si se det. drumul de
lungime minima de la vf. q la vf. i=p
j:=q
k:=1, d(k):=j
Cat timp d(k)<>p executa
| * Fie i un predecesor al lui j pentru care H(i)+v(i,j)=H(j))
j:=i
k:=k+1
d(k):=j
SfCat
Determinand valorile minime ale drumurilor de la vf. p la toate vf. grafului
cu algoritmul lui Moore-Dijkstra adptat vom determina cu ultimul algoritm
desris un drum de valoare minima de la vf. p la vf. q.
EXEMPLU:
Date
7
3 5
1 2 7
2 4 4
4 7 4
1 3 1
3 6 7
6 5 3
5 7 10
3 2 5
3 5 2
2 5 2
2 6 3
6 4 6
0 0 0
Rezultate
valoarea maxima a lungimilor drumurilor de la 3 la 5 este 11
drumul este: 3-2-6-5
*)
const MAX=10;
INFINIT=10000;
type tab=array[1..MAX] of integer;
mat=array[1..MAX] of tab;
function arc(i,j:integer; v:mat):boolean;
begin
arc:= (v[i,j]<>INFINIT)
end;
procedure InitCit(w:string;
var n:integer; var v:mat;
var H,S:tab; var p,q:integer);
var i,j,k:integer;
f:text;
begin
assign(f,w);
reset(f);
for i:=1 to MAX do
for j:=1 to MAX do v[i,j]:=INFINIT;
readln(f,n);
readln(f,p,q);
readln(f,i,j,k);
while i<>0 do begin
v[i,j]:=k;
readln(f,i,j,k)
end;
H[p]:=0;
S[p]:=0;
for i:=1 to n do
if i<>p then
begin
H[i]:=v[p,i];
S[i]:=i;
end;
close(f)
end;
function evida(n:integer; S:tab):boolean;
var vb:boolean;
i:integer;
begin
vb:=true;
for i:=1 to n do
if (S[i]<>0) then vb:=false;
evida:=vb;
end;
procedure Dijkstra(n,p:integer; v:mat; var H,S:tab);
var i,j,min:integer;
begin
repeat
min:=INFINIT;
j:=0;
for i:=1 to n do
if ((S[i]<>0)and(H[S[i]]<=min)) then
begin
min:=H[S[i]];
j:=S[i];
end;
S[j]:=0;
for i:=1 to n do
if (arc(j,i,v)and(S[i]=i))
then if (H[j]+v[j,i] < H[i])
then H[i]:=H[j]+v[j,i];
until evida(n,S)
end;
procedure Tip(n:integer; v:mat; H:tab; p,q:integer);
var i,j,k:integer;
gata:boolean;
d:tab;
begin
if H[q]=INFINIT then begin
writeln('nu exista drum de la ',p,' la ',q);
halt
end;
write('valoarea minima a lungimilor drumurilor ');
writeln('de la ',p,' la ',q,' este ',H[q]);
j:=q;
k:=1;
d[k]:=j;
while (d[k]<>p) do begin
gata:=FALSE; i:=1;
while (not gata) and (i<=n) do
if (arc(i,j,v) and (H[i]+v[i,j]=H[j]))
then gata:=TRUE
else inc(i);
j:=i;
inc(k); d[k]:=j
end;
write('drumul este: '); write(d[k]);
for i:=k-1 downto 1 do write('-',d[i]);
writeln
end;
var n,p,q:integer;
v:mat;
H,S:tab;
begin
InitCit('tema2.dat',n,v,H,S,p,q);
Dijkstra(n,p,v,H,S);
Tip(n,v,H,p,q);
readln;
end.
|
unit ZPeoplePrivCtrl_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel,
cxControls, cxGroupBox, StdCtrls, cxButtons,
PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase,
ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr,
cxSpinEdit, FIBQuery, pFIBQuery, pFIBStoredProc, Unit_ZGlobal_Consts,
ActnList, zProc, zMessages, zPeoplePrivCtrl_DM;
type
TFZPeoplePrivControl = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
BoxOptions: TcxGroupBox;
EditDateEnd: TcxDateEdit;
EditDateBeg: TcxDateEdit;
DateBegLabel: TcxLabel;
DateEndLabel: TcxLabel;
LabelAmountPriv: TcxLabel;
BoxMan: TcxGroupBox;
EditMan: TcxButtonEdit;
LabelMan: TcxLabel;
BoxPriv: TcxGroupBox;
LabelPrivilege: TcxLabel;
EditPrivilege: TcxButtonEdit;
SpinEditPrivAmount: TcxSpinEdit;
Actions: TActionList;
Action1: TAction;
procedure CancelBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure EditManPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure EditPrivilegePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormCreate(Sender: TObject);
procedure Action1Execute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
PId_man:LongWord;
PId_Priv:Integer;
PParameter:TZPeoplePrivParameters;
PResault:Variant;
PLanguageIndex:Byte;
DM:TDM_Ctrl;
public
constructor Create(AOwner:TComponent;ComeDB:TISC_DB_HANDLE;AParameter:TZPeoplePrivParameters);reintroduce;
property Resault:Variant read PResault;
end;
implementation
uses VarConv;
{$R *.dfm}
constructor TFZPeoplePrivControl.Create(AOwner: TComponent;ComeDB:TISC_DB_HANDLE;AParameter:TZPeoplePrivParameters);
begin
inherited Create(AOwner);
PParameter:=AParameter;
PLanguageIndex:=LanguageIndex;
//******************************************************************************
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
LabelMan.Caption := LabelMan_Caption[PLanguageIndex];
LabelPrivilege.Caption := LabelPrivilege_Caption[PLanguageIndex];
LabelAmountPriv.Caption := LabelExpense_Caption[PLanguageIndex];
DateBegLabel.Caption := LabelDateBeg_Caption[PLanguageIndex]+' - ';
DateEndLabel.Caption := ' - '+AnsiLowerCase(LabelDateEnd_Caption[PLanguageIndex]);
//******************************************************************************
self.EditDateEnd.Date := date;
self.EditDateBeg.Date := date;
//******************************************************************************
DM:=TDM_Ctrl.Create(self);
//******************************************************************************
case AParameter.TypeId of
zppctIdPeoplePriv: DM.DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_PEOPLE_PRIV_SELECTONE('+IntToStr(AParameter.ID)+',2)';
zppctIdPeople: DM.DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_PEOPLE_PRIV_SELECTONE('+IntToStr(AParameter.ID)+',1)';
end;
IF AParameter.TypeId<>zppctNULL then
begin
DM.DataBase.Handle:=ComeDB;
DM.DSet.Open;
if not VarIsNULL(DM.DSet['FIO']) then
begin
PId_man := DM.DSet['ID_MAN'];
EditMan.Text := VarToStr(DM.DSet['TN'])+' - '+VarTostr(DM.DSet['FIO']);
end;
if not VarIsNull(DM.DSet['NAME_PRIV']) then
begin
PId_Priv := DM.DSet['ID_PRIV'];
EditPrivilege.Text := VarToStr(DM.DSet['KOD_PRIV'])+' - '+VarToStr(DM.DSet['NAME_PRIV']);
end;
if not VarIsNull(DM.DSet['EXPENSE']) then SpinEditPrivAmount.Value := DM.DSet['EXPENSE'];
if not VarIsNull(DM.DSet['MIN_AMOUNT_PRIV']) then
SpinEditPrivAmount.Properties.MinValue := DM.DSet['MIN_AMOUNT_PRIV'];
if not VarIsNull(DM.DSet['MAX_AMOUNT_PRIV']) then
SpinEditPrivAmount.Properties.MaxValue := DM.DSet['MAX_AMOUNT_PRIV'];
if not VarIsNull(DM.DSet['PRIV_DBEG']) then
begin
EditDateBeg.Properties.MinDate := VarToDateTime(DM.DSet['PRIV_DBEG']);
EditDateEnd.Properties.MinDate := VarToDateTime(DM.DSet['PRIV_DBEG']);
EditDateBeg.Date := VarToDateTime(DM.DSet['PRIV_DBEG']);
end;
if not VarIsNull(DM.DSet['PRIV_DEND']) then
begin
EditDateBeg.Properties.MaxDate := VarToDateTime(DM.DSet.FieldValues['PRIV_DEND']);
//EditDateEnd.Properties.MaxDate := VarToDateTime(DM.DSet.FieldValues['PRIV_DEND']);
EditDateEnd.Date := VarToDateTime(DM.DSet['PRIV_DEND']);
end;
if (not VarIsNull(DM.DSet['MIN_AMOUNT_PRIV'])) and
(DM.DSet['MAX_AMOUNT_PRIV']=DM.DSet['MIN_AMOUNT_PRIV']) then begin
SpinEditPrivAmount.Value := DM.DSet['MIN_AMOUNT_PRIV'];
SpinEditPrivAmount.Properties.ReadOnly := True;
end;
if (not VarIsNull(DM.DSet['PRIV_DBEG'])) and
(DM.DSet['PRIV_DEND']=DM.DSet['PRIV_DBEG']) then
begin
EditDateEnd.Date := VarToDateTime(DM.DSet['PRIV_DEND']);
EditDateEnd.Properties.ReadOnly := True;
EditDateBeg.Date := VarToDateTime(DM.DSet['PRIV_DBEG']);
EditDateBeg.Properties.ReadOnly := True;
end;
case AParameter.ControlFormStyle of
zcfsInsert:
begin
BoxMan.Enabled := False;
Caption := ZPeoplePrivCtrl_Caption_Insert[PLanguageIndex];
end;
zcfsUpdate:
begin
BoxMan.Enabled := False;
BoxOptions.Enabled := True;
Caption := ZPeoplePrivCtrl_Caption_Update[PLanguageIndex];
if not VarIsNull(DM.DSet['DATE_BEG']) then
EditDateBeg.Date := VarToDateTime(DM.DSet['DATE_BEG']);
if not VarIsNull(DM.DSet['DATE_END']) then
EditDateEnd.Date := VarToDateTime(DM.DSet['DATE_END']);
end;
zcfsShowDetails:
begin
BoxOptions.Enabled := False;
BoxMan.Enabled := False;
BoxPriv.Enabled := False;
YesBtn.Visible := False;
CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex];
Caption := ZPeoplePrivCtrl_Caption_Detail[PLanguageIndex];
end;
end;
end;
end;
procedure TFZPeoplePrivControl.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFZPeoplePrivControl.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if DM.DefaultTransaction.Active then DM.DefaultTransaction.Commit;
end;
procedure TFZPeoplePrivControl.EditManPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Man:Variant;
begin
Man:=LoadPeopleModal(self,DM.DataBase.Handle);
if VarArrayDimCount(Man)> 0 then
if Man[0]<>NULL then
begin
EditMan.Text := Man[1]+' '+Man[2]+' '+Man[3];
PId_Man := Man[0];
end;
end;
procedure TFZPeoplePrivControl.EditPrivilegePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var Privilege:Variant;
begin
Privilege:=LoadPrivileges(self,DM.DataBase.Handle,zfsModal);
if VarArrayDimCount(Privilege)> 0 then
if Privilege[0]<>NULL then
begin
EditPrivilege.Text := Privilege[1];
PId_Priv := Privilege[0];
if Privilege[2]=Privilege[3] then
begin
SpinEditPrivAmount.Value := Privilege[2];
SpinEditPrivAmount.Properties.ReadOnly := True;
end
else
begin
SpinEditPrivAmount.Properties.MaxValue := Privilege[3];
SpinEditPrivAmount.Value := Privilege[2];
SpinEditPrivAmount.Properties.MinValue := Privilege[2];
SpinEditPrivAmount.Properties.ReadOnly := False;
end;
if Privilege[4]=Privilege[5] then
begin
EditDateEnd.Date := VarToDateTime(Privilege[4]);
EditDateBeg.Date := VarToDateTime(Privilege[4]);
EditDateEnd.Properties.ReadOnly := True;
EditDateBeg.Properties.ReadOnly := True;
end
else
begin
EditDateEnd.Properties.MaxDate := VarToDateTime(Privilege[5]);
EditDateEnd.Properties.MinDate := VarToDateTime(Privilege[4]);
EditDateBeg.Properties.MaxDate := VarToDateTime(Privilege[5]);
EditDateBeg.Properties.MinDate := VarToDateTime(Privilege[4]);
EditDateEnd.Properties.ReadOnly := False;
EditDateBeg.Properties.ReadOnly := False;
end;
BoxOptions.Enabled := True;
end;
end;
procedure TFZPeoplePrivControl.FormCreate(Sender: TObject);
begin
if PParameter.ControlFormStyle=zcfsDelete then
begin
if ZShowMessage(ZPeoplePrivCtrl_Caption_Delete[PLanguageIndex],DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then
with DM do
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_PEOPLE_PRIV_D';
StoredProc.Prepare;
StoredProc.ParamByName('ID_PEOPLE_PRIV').AsInteger := PParameter.ID;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end
else
ModalResult:=mrCancel;
Exit;
end;
end;
procedure TFZPeoplePrivControl.Action1Execute(Sender: TObject);
begin
If EditMan.Text = '' then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ManInput_ErrorText[PLanguageIndex],mtWarning,[mbOK]);
if BoxMan.Enabled then EditMan.SetFocus;
Exit;
end;
If EditPrivilege.Text = '' then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputPrivilege_Error_Text[PLanguageIndex],mtWarning,[mbOK]);
if BoxPriv.Enabled then EditPrivilege.SetFocus;
Exit;
end;
If (SpinEditPrivAmount.Text = '') or (SpinEditPrivAmount.Value=0) then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputExpense_Error_Text[PLanguageIndex],mtWarning,[mbOK]);
if BoxOptions.Enabled then SpinEditPrivAmount.SetFocus;
Exit;
end;
if EditDateEnd.Date < EditDateBeg.Date then
begin
ZShowMessage(Error_Caption[PLanguageIndex],ZeInputTerms_ErrorText[PLanguageIndex],mtWarning,[mbOK]);
if BoxPriv.Enabled then EditDateBeg.SetFocus;
Exit;
end;
case PParameter.ControlFormStyle of
zcfsInsert:
with DM do
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_PEOPLE_PRIV_I';
StoredProc.Prepare;
StoredProc.ParamByName('ID_PEOPLE').AsInteger := PId_man;
StoredProc.ParamByName('ID_PRIV').AsInteger := PId_Priv;
StoredProc.ParamByName('DATE_BEG').AsDate := StrToDate(EditDateBeg.Text);
StoredProc.ParamByName('DATE_END').AsDate := StrToDate(EditDateEnd.Text);
StoredProc.ParamByName('EXPENSE').AsInteger := SpinEditPrivAmount.Value;
StoredProc.ExecProc;
PResault := StoredProc.ParamByName('ID_PEOPLE_PRIV').AsInteger;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end;
zcfsUpdate:
with DM do
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_PEOPLE_PRIV_U';
StoredProc.Prepare;
StoredProc.ParamByName('ID_PEOPLE_PRIV').AsInteger := PParameter.ID;
StoredProc.ParamByName('ID_PEOPLE').AsInteger := PId_man;
StoredProc.ParamByName('ID_PRIV').AsInteger := PId_Priv;
StoredProc.ParamByName('DATE_BEG').AsDate := StrToDate(EditDateBeg.Text);
StoredProc.ParamByName('DATE_END').AsDate := StrToDate(EditDateEnd.Text);
StoredProc.ParamByName('EXPENSE').AsInteger := SpinEditPrivAmount.Value;
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
ModalResult:=mrYes;
except
on e:exception do
begin
ZShowMessage(Error_Caption[PLanguageIndex],e.Message,mtError,[mbOK]);
StoredProc.Transaction.Rollback;
end;
end;
end;
end;
procedure TFZPeoplePrivControl.FormDestroy(Sender: TObject);
begin
if DM<>nil then DM.Destroy;
end;
end.
|
unit UConverteInvertido;
interface
uses UConverteTexto,System.StrUtils;
type
TConverteInvertido = class(TConverteTexto)
public
procedure Converter(vTexto : String); Override;
end;
implementation
procedure TConverteInvertido.Converter(vTexto : String);
begin
if vTexto <> '' then
Resultado := ReverseString(vTexto);
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.CalendarPanel;
{$I Kitto.Defines.inc}
interface
uses
Ext, ExtPascal, ExtPascalUtils, ExtensibleCalendar, ExtData,
EF.Tree,
Kitto.Metadata.DataView, Kitto.Ext.Base, Kitto.Ext.DataPanelLeaf;
type
TKExtCalendarPanel = class(TKExtDataPanelLeafController)
strict private
FCalendarPanel: TExtensibleCalendarPanel;
FCalendarStore: TExtDataStore;
FCalendarReader: TExtDataJsonReader;
procedure CreateAndInitCalendar;
function GetStartDateDBName: string;
function GetEndDateDBName: string;
function GetDateFieldNameForNewRecords: string;
function CreateCalendarReader: TExtDataJsonReader;
function CreateCalendarStore: TExtDataStore;
strict protected
function GetSelectCall(const AMethod: TExtProcedure): TExtFunction; override;
function GetSelectConfirmCall(const AMessage: string; const AMethod: TExtProcedure): string; override;
property CalendarStore: TExtDataStore read FCalendarStore;
procedure SetViewTable(const AValue: TKViewTable); override;
function IsClientStoreAutoLoadEnabled: Boolean; override;
function GetRecordPageFilter: string; override;
function IsActionSupported(const AActionName: string): Boolean; override;
procedure SetNewRecordDefaultValues(const ANode: TEFNode); override;
published
procedure GetCalendarRecords;
procedure LoadData; override;
procedure CalendarDayClick(This : TExtensibleCalendarPanel; Dt : TDateTime; Allday : Boolean; El : TExtElement);
end;
implementation
uses
SysUtils, StrUtils, Types,
{$IFDEF D21+}JSON, {$ELSE}DBXJSON,{$ENDIF}
EF.Localization, EF.Macros, EF.StrUtils, EF.SQL,
Kitto.Types, Kitto.Ext.Utils, Kitto.Metadata.Models, Kitto.Ext.Session,
Kitto.Ext.Controller;
{ TKExtCalendarPanel }
procedure TKExtCalendarPanel.CalendarDayClick(This : TExtensibleCalendarPanel; Dt : TDateTime; Allday : Boolean; El : TExtElement);
begin
NewRecord;
end;
procedure TKExtCalendarPanel.CreateAndInitCalendar;
begin
Assert(ClientStore <> nil);
FCalendarPanel := TExtensibleCalendarPanel.CreateAndAddTo(Items);
FCalendarPanel.Region := rgCenter;
FCalendarPanel.Border := False;
FCalendarPanel.DayText := _('Day');
FCalendarPanel.MonthText := _('Month');
FCalendarPanel.GoText := _('Go');
FCalendarPanel.JumpToText := _('Jump to:');
// Disables the built-in editors.
//FCalendarPanel.ReadOnly := True;
FCalendarPanel.ShowDayView := True;
FCalendarPanel.ShowMultiDayView := True; // 3 days
FCalendarPanel.ShowWeekView := True;
FCalendarPanel.ShowMultiWeekView := True; // 2 weeks
FCalendarPanel.ShowMonthView := True;
FCalendarPanel.ActiveItem := 4; // month view
FCalendarPanel.ShowNavBar := True;
FCalendarPanel.ShowTodayText := True;
FCalendarPanel.ShowTime := True;
FCalendarPanel.On('dayclick', JSFunction('cal, dt, allday, el',
GetAjaxCode(NewRecord, '', ['m', '%dt.getMonth() + 1', 'y', '%dt.getFullYear()', 'd', '%dt.getDate()', 'allday', '%allday']) + 'return false;'));
FCalendarPanel.EventStore := ClientStore;
FCalendarPanel.CalendarStore := CalendarStore;
end;
function TKExtCalendarPanel.GetRecordPageFilter: string;
var
LStartDateStr: string;
LEndDateStr: string;
LFilter: string;
function ParseJSDate(const ADateYMD: string): TDateTime;
var
LParts: TStringDynArray;
begin
LParts := EF.StrUtils.Split(ADateYMD, '-');
if Length(LParts) = 3 then
Result := EncodeDate(StrToInt(LParts[0]), StrToInt(LParts[1]), StrToInt(LParts[2]))
else
Result := 0;
end;
begin
Result := inherited GetRecordPageFilter;
LStartDateStr := Session.Query['start'];
LEndDateStr := Session.Query['end'];
if (LStartDateStr <> '') and (LEndDateStr <> '') then
begin
LStartDateStr := Session.Config.DBConnections[ViewTable.DatabaseName].DBEngineType.FormatDateTime(ParseJSDate(LStartDateStr));
LEndDateStr := Session.Config.DBConnections[ViewTable.DatabaseName].DBEngineType.FormatDateTime(ParseJSDate(LEndDateStr));
LFilter := GetStartDateDBName + ' between ' + SQLQuotedStr(LStartDateStr) + ' and ' + SQLQuotedStr(LEndDateStr) +
' or ' + SQLQuotedStr(LStartDateStr) + ' between ' + GetStartDateDBName + ' and ' + GetEndDateDBName;
if Result = '' then
Result := LFilter
else
Result := Result + ' and (' + LFilter + ')';
end;
end;
function TKExtCalendarPanel.GetSelectCall(const AMethod: TExtProcedure): TExtFunction;
begin
Result := JSFunction(Format('ajaxCalendarSelection("yes", "", {params: {methodURL: "%s", calendarPanel: %s, fieldNames: "%s"}});',
[MethodURI(AMethod), FCalendarPanel.JSName, Join(ViewTable.GetKeyFieldAliasedNames, ',')]));
end;
function TKExtCalendarPanel.GetSelectConfirmCall(const AMessage: string;
const AMethod: TExtProcedure): string;
begin
Result := Format('selectCalendarConfirmCall("%s", "%s", %s, "%s", {methodURL: "%s", calendarPanel: %s, fieldNames: "%s"});',
[_('Confirm operation'), AMessage, FCalendarPanel.JSName, ViewTable.Model.CaptionField.FieldName, MethodURI(AMethod),
FCalendarPanel.JSName, Join(ViewTable.GetKeyFieldAliasedNames, ',')]);
end;
function TKExtCalendarPanel.GetStartDateDBName: string;
begin
Result := ViewTable.FieldByAliasedName('StartDate').DBNameOrExpression;
end;
function TKExtCalendarPanel.GetEndDateDBName: string;
begin
Result := ViewTable.FieldByAliasedName('EndDate').DBNameOrExpression;
end;
procedure TKExtCalendarPanel.SetNewRecordDefaultValues(const ANode: TEFNode);
var
LDay: Integer;
LMonth: Integer;
LYear: Integer;
begin
LDay := Session.QueryAsInteger['d'];
LMonth := Session.QueryAsInteger['m'];
LYear := Session.QueryAsInteger['y'];
ANode.GetNode('Sys/DefaultValues/' + GetDateFieldNameForNewRecords, True).AsDateTime := EncodeDate(LYear, LMonth, LDay);
end;
procedure TKExtCalendarPanel.GetCalendarRecords;
var
LJSONArray: TJSONArray;
procedure AddItem(const AId: Integer; const ATitle, ADescription: string;
const AColorId: Integer; AIsHidden: Boolean);
var
LObject: TJSONObject;
begin
LObject := TJSONObject.Create;
LObject.AddPair('CalendarId', TJSONNumber.Create(AId));
LObject.AddPair('Title', ATitle);
LObject.AddPair('Description', ADescription);
LObject.AddPair('ColorId', TJSONNumber.Create(AColorId));
{$IFDEF D22+}
LObject.AddPair('IsHidden', TJSONBool.Create(AIsHidden));
{$ELSE}
if AIsHidden then
LObject.AddPair('IsHidden', TJSONTrue.Create)
else
LObject.AddPair('IsHidden', TJSONFalse.Create);
{$ENDIF}
if AIsHidden then
LJSONArray.AddElement(LObject);
end;
begin
LJSONArray := TJSONArray.Create;
try
AddItem(1, 'First', 'First Calendar', 16711680, False);
AddItem(2, 'Second', 'Second Calendar', 65280, False);
AddItem(3, 'Third', 'Third Calendar', 255, False);
AddItem(4, 'Fourth', 'Fourth Calendar', 16711680, False);
AddItem(5, 'Fifth', 'Fifth Calendar', 65280, False);
AddItem(6, 'Sixth', 'Sixth Calendar', 255, False);
AddItem(7, 'Seventh', 'Seventh Calendar', 16711680, False);
AddItem(8, 'Eighth', 'Eighth Calendar', 65280, False);
AddItem(9, 'Ninth', 'Ninth Calendar', 255, False);
AddItem(10, 'Tenth', 'Tenth Calendar', 65280, False);
Session.ResponseItems.AddJSON(Format('{Success: true, Total: %d, Root: %s}',
[3, {$IFDEF D21+}LJSONArray.ToJSON{$ELSE}LJSONArray.ToString{$ENDIF}]));
finally
FreeAndNil(LJSONArray);
end;
end;
function TKExtCalendarPanel.GetDateFieldNameForNewRecords: string;
begin
Result := ViewTable.GetString('Controller/DateFieldName', 'StartDate');
end;
function TKExtCalendarPanel.IsActionSupported(const AActionName: string): Boolean;
begin
Result := True;
end;
function TKExtCalendarPanel.IsClientStoreAutoLoadEnabled: Boolean;
begin
// We don't need to call the store's load method, as the calendar
// panel does that automatically.
Result := False;
end;
procedure TKExtCalendarPanel.LoadData;
begin
inherited;
if Assigned(CalendarStore) then
CalendarStore.Load(JSObject(''));
end;
procedure TKExtCalendarPanel.SetViewTable(const AValue: TKViewTable);
begin
inherited;
Assert(Assigned(AValue));
FCalendarStore := CreateCalendarStore;
FCalendarReader := CreateCalendarReader;
FCalendarStore.Reader := FCalendarReader;
CreateAndInitCalendar;
end;
function TKExtCalendarPanel.CreateCalendarReader: TExtDataJsonReader;
procedure AddReaderField(const AReader: TExtDataJsonReader; const AName, AType: string; const AUseNull: Boolean);
var
LField: TExtDataField;
begin
LField := TExtDataField.CreateAndAddTo(AReader.Fields);
LField.Name := AName;
LField.&Type := AType;
LField.UseNull := AUseNull;
end;
begin
Assert(Assigned(ViewTable));
Result := TExtDataJsonReader.Create(Self, JSObject('')); // Must pass '' otherwise invalid code is generated.
Result.Root := 'Root';
Result.TotalProperty := 'Total';
Result.MessageProperty := 'Msg';
Result.SuccessProperty := 'Success';
AddReaderField(Result, 'CalendarId', 'int', False);
AddReaderField(Result, 'Title', 'string', False);
AddReaderField(Result, 'Description', 'string', False);
AddReaderField(Result, 'ColorId', 'string', False);
AddReaderField(Result, 'Hidden', 'boolean', False);
end;
function TKExtCalendarPanel.CreateCalendarStore: TExtDataStore;
begin
Result := TExtDataStore.Create(Self);
Result.RemoteSort := False;
Result.Url := MethodURI(GetCalendarRecords);
Result.On('exception', JSFunction('proxy, type, action, options, response, arg', 'loadError(type, action, response);'));
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('CalendarPanel', TKExtCalendarPanel);
TKExtSession.AddAdditionalRef('/extensible-1.0.2/resources/css/extensible-all', True);
TKExtSession.AddAdditionalRef('/extensible-1.0.2/lib/extensible-all' + {$IFDEF DebugExtJS}'-debug'{$ELSE}''{$ENDIF});
// TKExtSession.AddAdditionalRef('{ext}/examples/calendar/resources/css/calendar', True);
// TKExtSession.AddAdditionalRef('{ext}/examples/calendar/calendar-all' + {$IFDEF DebugExtJS}'-debug'{$ELSE}''{$ENDIF});
(*
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/Ext.calendar');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/templates/DayHeaderTemplate');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/templates/DayBodyTemplate');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/templates/DayViewTemplate');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/templates/BoxLayoutTemplate');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/templates/MonthViewTemplate');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/dd/CalendarScrollManager');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/dd/StatusProxy');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/dd/CalendarDD');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/dd/DayViewDD');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/EventRecord');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/widgets/CalendarPicker');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/WeekEventRenderer');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/views/CalendarView');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/views/DayHeaderView');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/views/DayBodyView');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/views/DayView');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/views/MonthDayDetailView');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/views/MonthView');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/views/WeekView');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/widgets/DateRangeField');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/widgets/ReminderField');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/EventEditForm');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/EventEditWindow');
TKExtSession.AddAdditionalRef('{ext}/examples/calendar/src/CalendarPanel');
*)
finalization
TKExtControllerRegistry.Instance.UnregisterClass('CalendarPanel');
end.
|
//------------------------------------------------------------------------------
//Commands UNIT
//------------------------------------------------------------------------------
// What it does-
// This Unit was built to house the routines dealing with processing
// console commands.
//
// Notes -
// RaX-The EXIT command simply sets Run FALSE in the parser. Look for it in
// Parse()
//
// Changes -
// September 20th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
unit Commands;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Classes;
type
//------------------------------------------------------------------------------
//TCommands CLASS
//------------------------------------------------------------------------------
TCommands = class
public
Procedure Parse(InputText : String);
private
function Credits : String;
function Help : String;
//function Reload() : String;
function Restart() : String;
function Start(Values : TStringList) : String;
function Stop(Values : TStringList) : String;
end;{TCommands}
//------------------------------------------------------------------------------
implementation
uses
SysUtils,
Main,
LoginServer,
CharacterServer,
InterServer,
ZoneServer,
Globals;
//------------------------------------------------------------------------------
//Parse() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Parses InputText for commands. Sets MainProc.Run which determines
// whether or not the entire program should continue to run.
// (See Exit Command)
//
// Changes -
// September 20th, 2006 - RaX - Added Trim function before using InputText to
// force commands even when whitespace is present
// before it.
// September 20th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Procedure TCommands.Parse(InputText : String);
var
StringIn : TStringList;
Index : Integer;
Command : String;
Values : TStringList;
Error : String;
begin
if InputText > '' then begin
StringIn := TStringList.Create;
try
StringIn.DelimitedText := Trim(InputText);
if StringIn.DelimitedText[1] = '/' then begin
Command := LowerCase(StringIn.Strings[0]); //Gets the command text
Values := TStringList.Create;
try
for Index := 1 to StringIn.Count-1 do begin //retrieves values after the command
Values.Add(StringIn.Strings[Index]);
end;
{Start Command Parser}
if Command = '/exit' then
begin
MainProc.Run := FALSE;
Error := '';
end else
if Command = '/reload' then
begin
Error := 'Reload not setup till all DB is done';//ADataBase.Reload;
end else
if Command = '/credits' then
begin
Error := Credits;
end else
if Command = '/help' then
begin
Error := Help;
end else
if Command = '/restart' then
begin
Error := Restart;
end else
if Command = '/start' then
begin
Error := Start(Values);
end else
if Command = '/stop' then
begin
Error := Stop(Values);
end else
begin
Error := Command + ' does not exist!';
end;
{End Command Parser}
finally //Begin Cleanup
Values.Free;
end;
if Error <> '' then begin //Display Errors
Console.Message('Command ' + Command + ' failed - ' + Error, 'Command Parser', MS_ALERT)
end else begin
Console.Message('Command ' + Command + ' success!', 'Command Parser', MS_ALERT);
end;
end;
finally
StringIn.Free;
end;
end;
end;{TCommands.Parse}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Credits() FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Displays third party credits for Helios.
//
// Changes -
// February 25th, 2007 - RaX - Created Header.
//
//------------------------------------------------------------------------------
Function TCommands.Credits;
var
ThirdParty : TStringList;
LineIndex : Integer;
begin
Result := '';
if FileExists(AppPath + '3rdParty.txt') then
begin
ThirdParty := TStringList.Create;
ThirdParty.LoadFromFile(AppPath + '3rdParty.txt');
for LineIndex := 0 to ThirdParty.Count - 1 do
begin
Console.WriteLn(' '+ThirdParty.Strings[LineIndex]);
end;
ThirdParty.Free;
end;
end;//Credits
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Help() FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Writes a list of commands to the console.
//
// Changes -
// September 20th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
function TCommands.Help : String;
begin
Console.WriteLn('The available console commands are as follows...');
Console.WriteLn('--------------------------------------');
Console.WriteLn('/start - starts a server');
Console.WriteLn('/stop - stops a server');
Console.WriteLn('/restart - restarts all enabled servers');
Console.WriteLn('/exit - exits the program');
Console.WriteLn('/credits - displays our credits.');
Console.WriteLn('/help - lists all console commands');
Console.WriteLn('--------------------------------------');
Result := '';
end;{Help}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Reload() FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Will(in the future) free up and reload the Databases.
//
// Changes -
// September 20th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
{function TCommands.Reload() : String;
begin
//To be done when all DB is done. One swoop kill
end;{Reload}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Restart() FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Restarts all enabled servers.
//
// Changes -
// September 20th, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
function TCommands.Restart() : String;
begin
MainProc.Shutdown;
MainProc.Startup;
Result := '';
end;{Restart}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Start() FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Starts a server.
//
// Changes -
// September 20th, 2006 - RaX - Created Header.
// [2007/06/21] Tsusai - Creates the servers now.
//
//------------------------------------------------------------------------------
function TCommands.Start(Values : TStringList) : String;
begin
if Values.Count > 0 then
begin
Values[0] := LowerCase(Values[0]);
if Values[0] = 'login' then
begin
if not Assigned(MainProc.LoginServer) then
begin
MainProc.LoginServer := TLoginServer.Create;
MainProc.LoginServer.Start;
end;
end else
if Values[0] = 'character' then
begin
if not Assigned(MainProc.CharacterServer) then
begin
MainProc.CharacterServer := TCharacterServer.Create;
MainProc.CharacterServer.Start;
MainProc.CharacterServer.ConnectToLogin;
end;
end else
if Values[0] = 'inter' then
begin
if not Assigned(MainProc.InterServer) then
begin
MainProc.InterServer := TInterServer.Create;
MainProc.InterServer.Start;
end;
end else
if Values[0] = 'zone' then
begin
if not Assigned(MainProc.ZoneServer) then
begin
MainProc.ZoneServer := TZoneServer.Create;
MainProc.ZoneServer.Start;
MainProc.ZoneServer.ConnectToCharacter;
MainProc.ZoneServer.ConnectToInter;
end;
end else
begin
Result := Values[0] + ' is not a valid server';
end;
end else
begin
//display help for Start()
Console.WriteLn('Using /Start...');
Console.WriteLn('"/Start <ServerName>" - starts <ServerName>');
Console.WriteLn('ServerName can be "Login", "Character", "Zone", or "Inter"');
end;
end;{Start}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Stop() FUNCTION
//------------------------------------------------------------------------------
// What it does-
// Stops a server.
//
// Changes -
// September 20th, 2006 - RaX - Created Header.
// [2007/06/21] Tsusai - Frees the servers now.
//
//------------------------------------------------------------------------------
function TCommands.Stop(Values : TStringList) : String;
begin
if Values.Count > 0 then
begin
Values[0] := LowerCase(Values[0]);
if Values[0] = 'login' then
begin
if Assigned(MainProc.LoginServer) then
begin
MainProc.LoginServer.Stop;
FreeAndNil(MainProc.LoginServer);
end;
end else
if Values[0] = 'character' then
begin
if Assigned(MainProc.CharacterServer) then
begin
MainProc.CharacterServer.Stop;
FreeAndNil(MainProc.CharacterServer);
end;
end else
if Values[0] = 'inter' then
begin
if Assigned(MainProc.InterServer) then
begin
MainProc.InterServer.Stop;
FreeAndNil(MainProc.InterServer);
end;
end else
if Values[0] = 'zone' then
begin
if Assigned(MainProc.ZoneServer) then
begin
MainProc.ZoneServer.Stop;
FreeAndNil(MainProc.ZoneServer);
end;
end else
begin
Result := Values[0] + ' is not a valid server';
end;
end else
begin
//display help for Stop()
Console.WriteLn('Using /Stop...');
Console.WriteLn('"/Stop <ServerName>" - stops <ServerName>');
Console.WriteLn('ServerName can be "Login", "Character", "Zone", or "Inter"');
end;
end;{Stop}
//------------------------------------------------------------------------------
end{Commands}.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.