text stringlengths 14 6.51M |
|---|
unit POOCalculadora.Model.Classs.helpers;
interface
uses
Vcl.Controls, System.SysUtils;
type
TCaptionHelper = record helper for TCaption
function ToCurrency : Currency;
end;
TStringHelper = record helper for String
function ToCurrency : Currency;
end;
implementation
{ TCaptionHelper }
function TCaptionHelper.ToCurrency: Currency;
begin
Result := StrToCurr(Self);
end;
{ TStringHelper }
function TStringHelper.ToCurrency: Currency;
begin
Result := StrToCurr(Self);
end;
end.
|
unit Views.Mensagem;
interface
uses
Views.Interfaces.Mensagem,
Services.ComplexTypes,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.Objects, FMX.Controls.Presentation,
FMX.StdCtrls, FMX.Ani;
type
TViewMensagem = class(TForm, IViewMensagem)
RectangleBodyView: TRectangle;
Layout: TLayout;
RectangleBodyMessage: TRectangle;
AnimationShowView: TFloatAnimation;
AnimationShowMessage: TFloatAnimation;
LabelTitulo: TLabel;
LayoutBotoes: TLayout;
ImageMessage: TImage;
LabelMessage: TLabel;
LayoutBtnConfirmar: TLayout;
LabelConfirmar: TLabel;
LayoutBtnCancelar: TLayout;
LabelCancelar: TLabel;
RectangleConfirmar: TRectangle;
RectangleCancelar: TRectangle;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure AnimationShowViewFinish(Sender: TObject);
procedure LabelCancelarClick(Sender: TObject);
procedure LabelConfirmarClick(Sender: TObject);
strict private
class var _mensagem : TViewMensagem;
private
{ Private declarations }
FTipo : TTipoMensagem;
FCallbackProcedureObject : TCallbackProcedureObject;
public
{ Public declarations }
class function GetInstance() : IViewMensagem;
function Tipo(Value : TTipoMensagem) : IViewMensagem;
function Titulo(Value : String) : IViewMensagem;
function Mensagem(Value : String) : IViewMensagem;
function CallbackProcedure(Value : TCallbackProcedureObject) : IViewMensagem;
procedure &End;
end;
implementation
uses
Services.Utils;
{$R *.fmx}
{ TViewMensagem }
function TViewMensagem.CallbackProcedure(Value: TCallbackProcedureObject): IViewMensagem;
begin
Result := Self;
FCallbackProcedureObject := Value;
end;
procedure TViewMensagem.&End;
begin
//Self.Show;
Self.ShowModal(procedure (ModalResult : TModalResult)
begin
;
end);
end;
procedure TViewMensagem.AnimationShowViewFinish(Sender: TObject);
begin
AnimationShowMessage.Start;
end;
procedure TViewMensagem.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := TCloseAction.caFree;
_mensagem := nil;
end;
procedure TViewMensagem.FormCreate(Sender: TObject);
begin
Layout.Opacity := 0;
FCallbackProcedureObject := nil;
end;
procedure TViewMensagem.FormShow(Sender: TObject);
begin
AnimationShowView.Start;
end;
class function TViewMensagem.GetInstance: IViewMensagem;
begin
if not Assigned(_mensagem) then
Application.CreateForm(TViewMensagem, _mensagem);
Result := _mensagem;
end;
procedure TViewMensagem.LabelCancelarClick(Sender: TObject);
begin
Self.Close;
end;
procedure TViewMensagem.LabelConfirmarClick(Sender: TObject);
begin
if Assigned(FCallbackProcedureObject) then
FCallbackProcedureObject(Sender);
Self.Close;
end;
function TViewMensagem.Mensagem(Value: String): IViewMensagem;
begin
Result := Self;
LabelMessage.Text := Value.Trim;
end;
function TViewMensagem.Tipo(Value: TTipoMensagem): IViewMensagem;
begin
Result := Self;
FTipo := Value;
LayoutBtnConfirmar.Visible := False;
LayoutBtnCancelar.Visible := True;
LayoutBtnConfirmar.Margins.Right := 0;
LayoutBtnCancelar.Margins.Left := 0;
LabelConfirmar.Text := 'OK';
LabelCancelar.Text := 'FECHAR';
case FTipo of
TTipoMensagem.tipoMensagemInformacao:
begin
LayoutBtnCancelar.Margins.Left := 0;
TServicesUtils.ResourceImage('icon_message_informe', ImageMessage);
end;
TTipoMensagem.tipoMensagemAlerta:
begin
TServicesUtils.ResourceImage('icon_message_alert', ImageMessage);
end;
TTipoMensagem.tipoMensagemErro:
begin
TServicesUtils.ResourceImage('icon_message_error', ImageMessage);
end;
TTipoMensagem.tipoMensagemSucesso:
begin
TServicesUtils.ResourceImage('icon_message_sucess', ImageMessage);
end;
TTipoMensagem.tipoMensagemPergunta:
begin
TServicesUtils.ResourceImage('icon_message_question', ImageMessage);
LayoutBtnConfirmar.Visible := True;
LayoutBtnCancelar.Visible := True;
LayoutBtnConfirmar.Margins.Right := 140;
LayoutBtnCancelar.Margins.Left := 140;
LabelConfirmar.Text := 'SIM';
LabelCancelar.Text := 'NÃO';
end;
end;
end;
function TViewMensagem.Titulo(Value: String): IViewMensagem;
begin
Result := Self;
LabelTitulo.Text := Value.Trim.ToUpper;
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2008-8-20
描述: 管理权限项
*******************************************************************************}
unit UFormPopitem;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, ExtCtrls, ImgList, Menus;
type
TfFormPopItem = class(TForm)
Lv1: TListView;
GroupBox1: TGroupBox;
BtnExit: TButton;
Label1: TLabel;
EditID: TComboBox;
EditName: TLabeledEdit;
ImageList1: TImageList;
BtnSave: TButton;
PMenu1: TPopupMenu;
mDelete: TMenuItem;
mRefresh: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BtnSaveClick(Sender: TObject);
procedure Lv1Click(Sender: TObject);
procedure mRefreshClick(Sender: TObject);
procedure mDeleteClick(Sender: TObject);
procedure EditIDKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
procedure LoadPopItems;
procedure InitFormData;
{*初始化数据*}
function BuildValidSQL: string;
{*构建语句*}
public
{ Public declarations }
end;
procedure ShowPopItemSetupForm;
//入口函数
implementation
{$R *.dfm}
uses
IniFiles, UDataModule, ULibFun, USysFun, USysConst, USysPopedom;
//------------------------------------------------------------------------------
procedure ShowPopItemSetupForm;
begin
with TfFormPopItem.Create(Application) do
begin
Caption := '权限项';
InitFormData;
ShowModal;
Free;
end;
end;
procedure TfFormPopItem.FormCreate(Sender: TObject);
var nStr: string;
nIni: TIniFile;
begin
nIni := TIniFile.Create(gPath + sFormConfig);
try
LoadFormConfig(Self, nIni);
nStr := nIni.ReadString(Name, 'LvWidth', '');
LoadListViewColumn(nStr, Lv1);
finally
nIni.Free;
end;
end;
procedure TfFormPopItem.FormClose(Sender: TObject;
var Action: TCloseAction);
var nIni: TIniFile;
begin
nIni := TIniFile.Create(gPath + sFormConfig);
try
SaveFormConfig(Self, nIni);
nIni.WriteString(Name, 'LvWidth', MakeListViewColumnInfo(Lv1));
finally
nIni.Free;
end;
end;
//------------------------------------------------------------------------------
//Desc: 载入权限项
procedure TfFormPopItem.LoadPopItems;
var nStr,nID: string;
nList: TStrings;
i,nCount,nPos: integer;
begin
nList := TStringList.Create;
try
if Assigned(Lv1.Selected) then
nID := Lv1.Selected.Caption
else nID := '';
Lv1.Clear;
gPopedomManager.LoadPopItemList(nList, gSysParam.FProgID);
nCount := nList.Count - 1;
for i:=0 to nCount do
with Lv1.Items.Add do
begin
nStr := nList[i];
nPos := Pos(';', nList[i]);
//ID;Name
Caption := Copy(nStr, 1, nPos - 1);
System.Delete(nStr, 1, nPos);
SubItems.Add(nStr);
ImageIndex := 0;
if Caption = nID then
begin
Selected := True;
MakeVisible(True);
end;
end;
finally
nList.Free;
end;
end;
//Desc: 初始化界面
procedure TfFormPopItem.InitFormData;
var i,nCount: integer;
begin
EditID.Items.Clear;
nCount := Ord('9');
for i:=Ord('0') to nCount do
EditID.Items.Add(Char(i));
//number
nCount := Ord('Z');
for i:=Ord('A') to nCount do
EditID.Items.Add(Char(i));
//charactor
LoadPopItems;
//popedom items
end;
//Desc: 构建语句
function TfFormPopItem.BuildValidSQL: string;
var nStr: string;
begin
nStr := 'Select Count(*) From $Table Where P_ID=''$ID'' and P_ProgID=''$PID''';
nStr := MacroValue(nStr, [MI('$Table', gSysParam.FTablePopItem),
MI('$ID', EditID.Text), MI('$PID', gSysParam.FProgID)]);
FDM.SQLQuery.Close;
FDM.SQLQuery.SQL.Text := nStr;
FDM.SQLQuery.Open;
if FDM.SQLQuery.Fields[0].AsInteger > 0 then
Result := 'Update $Table Set P_Name=''$Name'' Where P_ID=''$ID'''
else Result := 'Insert into $Table(P_ID, P_ProgID, P_Name) Values(''$ID'', ''$PID'',''$Name'')';
Result := MacroValue(Result, [MI('$Table', gSysParam.FTablePopItem),
MI('$Name', EditName.Text), MI('$ID', EditID.Text),
MI('$PID', gSysParam.FProgID)]);
//adjust macro
end;
//Desc: 保存
procedure TfFormPopItem.BtnSaveClick(Sender: TObject);
begin
if EditID.ItemIndex < 0 then
begin
EditID.SetFocus;
ShowMsg('请选择有效的权限标记', sHint); Exit;
end;
BtnSave.Enabled := False;
try
FDM.Command.Close;
FDM.Command.SQL.Text := BuildValidSQL;
if FDM.Command.ExecSQL > -1 then
begin
ShowMsg('保存成功', sHint);
LoadPopItems;
end;
finally
BtnSave.Enabled := True;
end;
end;
//------------------------------------------------------------------------------
//Desc: 同步界面
procedure TfFormPopItem.Lv1Click(Sender: TObject);
begin
if Assigned(Lv1.Selected) then
begin
EditID.ItemIndex := EditID.Items.IndexOf(Lv1.Selected.Caption);
EditName.Text := Lv1.Selected.SubItems[0];
end;
end;
//Desc: 刷新
procedure TfFormPopItem.mRefreshClick(Sender: TObject);
begin
LoadPopItems;
end;
//Desc: 删除
procedure TfFormPopItem.mDeleteClick(Sender: TObject);
var nStr: string;
begin
if Assigned(Lv1.Selected) then
begin
nStr := 'Delete From %s Where P_ID=''%s''';
nStr := Format(nStr, [gSysParam.FTablePopItem, Lv1.Selected.Caption]);
FDM.Command.Close;
FDM.Command.SQL.Text := nStr;
if FDM.Command.ExecSQL > 0 then
begin
LoadPopItems;
ShowMsg('删除成功', sHint);
end;
end;
end;
//Desc: 切换焦点
procedure TfFormPopItem.EditIDKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_Return: BtnSave.Click;
VK_Left: SwitchFocusCtrl(Self, False);
VK_Right: SwitchFocusCtrl(Self, True);
end;
end;
end.
|
(******************************************************************************
* *
* Usermanager *
* NTUser -- Core unit *
* *
* Copyright (c) 2006 Michael Puff http://www.michael-puff.de *
* *
* Many thanks to motzi for his work on this unit. *
* *
******************************************************************************)
unit NTUser;
{$I ..\..\CompilerSwitches.inc}
interface
uses
Windows,
NetAPI,
lsaapi,
List,
Exceptions,
ActiveX;
type
TGroup = class;
TGroupCollection = class;
//------------------------------------------------------------------------------
// Basisklasse für Treeview-Items (User / Group)
//------------------------------------------------------------------------------
TTVEntry = class
protected
FServer: WideString;
public
function GetCaption: WideString; virtual; abstract;
function GetImageIndex: Integer; virtual; abstract;
function GetChildList: TList; virtual; abstract;
property Server: WideString read FServer;
end;
//------------------------------------------------------------------------------
// Kapselt alle Infos für einen Account
//------------------------------------------------------------------------------
TUser = class(TTVEntry)
private
FModified: Boolean;
FEditable: Boolean;
FInitialized: Boolean;
Fui3: TUserInfo3;
FGroups: TGroupCollection;
FAutoLoginPW: WideString;
procedure Initialize();
procedure SetStrings(ui3: PUserInfo3);
function GetGroups: TGroupCollection;
function GetName: WideString;
function GetFullName: WideString;
procedure SetFullName(const Value: WideString);
function GetInternetDomainTrustAccount: Boolean;
function GetNormalAccount: Boolean;
function GetTempDublicateAccount: Boolean;
function GetWorkstationTrustAccount: Boolean;
function GetServerTrustAccount: Boolean;
function GetAccountExpires: Cardinal;
function GetAutoLogin: Boolean;
function GetCantChangePW: Boolean;
function GetCountLogons: Cardinal;
function GetDeactivated: Boolean;
function GetDescription: WideString;
function GetDontExpire: Boolean;
function GetErroneousLogons: Cardinal;
function GetHideAccount: Boolean;
function GetHomeDir: WideString;
function GetLastLogon: Cardinal;
function GetMustChangePW: Boolean;
function GetPWAge: Cardinal;
function GetQuota: Cardinal;
function GetScriptPath: WideString;
function GetUserID: Cardinal;
procedure SetName(const Value: WideString);
procedure SetAccountExpires(const Value: DWORD);
procedure SetAutoLogin(const Value: Boolean);
procedure SetAutoLoginPW(const Value: WideString);
procedure SetCantChangePW(const Value: Boolean);
procedure SetInternetDomainTrustAccount(const Value: Boolean);
procedure SetNormalAccount(const Value: Boolean);
procedure SetTempDublicateAccount(const Value: Boolean);
procedure SetWorkstationTrustAccount(const Value: Boolean);
procedure SetServerTrustAccount(const Value: Boolean);
procedure SetDeactivated(const Value: Boolean);
procedure SetDescription(const Value: WideString);
procedure SetDontExpire(const Value: Boolean);
procedure SetHideAccount(const Value: Boolean);
procedure SetHomeDir(const Value: WideString);
procedure SetMustChangePW(const Value: Boolean);
procedure SetPassword(const Value: WideString);
procedure SetScriptPath(const Value: WideString);
procedure AddToGroup(const Value: WideString);
procedure RemoveFromGroup(const Value: WideString);
function GetEditable: Boolean;
public
constructor Create(const server: WideString; ui3: PUserInfo3); overload;
constructor Create(const server: WideString; lgmi: PLocalGroupMembersInfo3); overload;
destructor Destroy; override;
procedure Add;
procedure Save;
procedure Del;
function GetCaption: WideString; override;
function GetImageIndex: Integer; override;
function GetChildList: TList; override;
property Groups: TGroupCollection read GetGroups;
property Modified: Boolean read FModified write FModified;
property Editable: Boolean read GetEditable;
property Name: WideString read GetName write SetName;
property FullName: WideString read GetFullName write SetFullName;
property Description: WideString read GetDescription write SetDescription;
property InternetDomainTrustAccount: Boolean read GetInternetDomainTrustAccount write
SetInternetDomainTrustAccount;
property NormalAccount: Boolean read GetNormalAccount write SetNormalAccount;
property TempDublicateAccount: Boolean read GetTempDublicateAccount write SetTempDublicateAccount;
property WorkStationTrustAccount: Boolean read GetWorkstationTrustAccount write SetWorkstationTrustAccount;
property ServerTrustAccount: Boolean read GetServerTrustAccount write SetServerTrustAccount;
property HomeDir: WideString read GetHomeDir write SetHomeDir;
property ScriptPath: WideString read GetScriptPath write SetScriptPath;
property Password: WideString write SetPassword;
property CantChangePW: Boolean read GetCantChangePW write SetCantChangePW;
property DontExpire: Boolean read GetDontExpire write SetDontExpire;
property MustChangePW: Boolean read GetMustChangePW write SetMustChangePW;
property Deactivated: Boolean read GetDeactivated write SetDeactivated;
property AutoLogin: Boolean read GetAutoLogin write SetAutoLogin;
property AutoLoginPW: WideString write SetAutoLoginPW;
property HideAccount: Boolean read GetHideAccount write SetHideAccount;
property AddGroup: WideString write AddToGroup;
property RemoveGroup: WideString write RemoveFromGroup;
property PWAge: Cardinal read GetPWAge;
property LastLogon: Cardinal read GetLastLogon;
property CountLogons: Cardinal read GetCountLogons;
property ErroneousLogons: Cardinal read GetErroneousLogons;
property AccountExpires: Cardinal read GetAccountExpires;
property Quota: Cardinal read GetQuota;
property UserID: Cardinal read GetUserID;
end;
//------------------------------------------------------------------------------
// Typisierte TList - Verwaltet eine Liste von TUser-Objekten
//------------------------------------------------------------------------------
TUserCollection = class(TList)
private
function Get(Index: Integer): TUser;
procedure Put(Index: Integer; const Value: TUser);
public
class function GetAll(const Server: WideString; filter: DWord = FILTER_NORMAL_ACCOUNT): TUserCollection;
class function GetGroupMembers(Group: TGroup): TUserCollection;
function Add(Item: TUser): Integer;
function First: TUser;
function IndexOf(Item: TUser): Integer;
property Items[Index: Integer]: TUser read Get write Put; default;
end;
//------------------------------------------------------------------------------
// Kapselt alle Infos für eine Gruppe
//------------------------------------------------------------------------------
TGroup = class(TTVEntry)
private
Flgi0: TLocalGroupInfo0;
Flgi1: TLocalGroupInfo1;
FMembers: TUserCollection;
function GetName: WideString;
function GetUsers: TUserCollection;
public
constructor Create(const Server: WideString; lgi0: PLocalGroupInfo0); overload;
constructor Create(const Server: WideString; lgi1: TLocalGroupInfo1); overload;
destructor Destroy; override;
function GetCaption: WideString; override;
function GetImageIndex: Integer; override;
function GetChildList: TList; override;
property Members: TUserCollection read GetUsers;
property Name: WideString read GetName;
function GetComment: WideString;
procedure Add;
procedure Del;
end;
//------------------------------------------------------------------------------
// Typisierte TList - Verwaltet eine Liste von TGroup-Objekten
//------------------------------------------------------------------------------
TGroupCollection = class(TList)
private
function Get(Index: Integer): TGroup;
procedure Put(Index: Integer; const Value: TGroup);
public
class function GetAll(const Server: WideString): TGroupCollection;
class function GetUserGroups(User: TUser): TGroupCollection;
function Add(Item: TGroup): Integer;
procedure Delete(const Group: WideString);
function First: TGroup;
function IndexOf(Item: TGroup): Integer;
property Items[Index: Integer]: TGroup read Get write Put; default;
end;
//------------------------------------------------------------------------------
// Kapselt alle Infos für ein Privileg
//------------------------------------------------------------------------------
TPrivilege = class(TObject)
private
FServer: string;
FRightConstant: string;
FRightDescription: string;
function GetRightConstant: string;
function GetDescription: string;
procedure SetDescription(const RightConstant: string);
public
constructor Create(const Server, RightConstant: string);
property Constant: string read GetRightConstant;
property Description: string read GetDescription;
end;
//------------------------------------------------------------------------------
// Typisierte TList - Verwaltet eine Liste von TPrivilege-Objekten
//------------------------------------------------------------------------------
TPrivilegeCollection = class(TList)
private
function Get(Index: Integer): TPrivilege;
procedure Put(Index: Integer; const Value: TPrivilege);
public
class function GetAll(const Server: WideString): TPrivilegeCollection;
class function GetUserPrivileges(const Server, User: WideString): TPrivilegeCollection;
function Add(Item: TPrivilege): Integer;
function IndexOf(Item: TPrivilege): Integer;
property Items[Index: Integer]: TPrivilege read Get write Put; default;
end;
procedure GrantPrivilege(const Server, Group, Privilege: string; Grant: Boolean);
const
PrivArray : array[0..27] of string = ('SeInteractiveLogonRight', 'SeNetworkLogonRight', 'SeBatchLogonRight',
'SeServiceLogonRight', 'SeCreateTokenPrivilege', 'SeAssignPrimaryTokenPrivilege', 'SeLockMemoryPrivilege',
'SeIncreaseQuotaPrivilege', 'SeUnsolicitedInputPrivilege', 'SeMachineAccountPrivilege', 'SeTcbPrivilege',
'SeSecurityPrivilege', 'SeTakeOwnershipPrivilege', 'SeLoadDriverPrivilege', 'SeSystemProfilePrivilege',
'SeSystemtimePrivilege', 'SeProfileSingleProcessPrivilege', 'SeIncreaseBasePriorityPrivilege',
'SeCreatePagefilePrivilege', 'SeCreatePermanentPrivilege', 'SeBackupPrivilege', 'SeRestorePrivilege',
'SeShutdownPrivilege', 'SeDebugPrivilege', 'SeAuditPrivilege', 'SeSystemEnvironmentPrivilege',
'SeChangeNotifyPrivilege', 'SeRemoteShutdownPrivilege');
implementation
uses
MpuTools,
MpuRegistry;
procedure FillPWideCharFromString(var pwc: PWideChar; str: string);
var
cchLen : DWORD;
begin
pwc := nil;
if (Length(str) > 0) then
begin
cchLen := Length(str) + 1;
pwc := PWideChar(GlobalAlloc(GPTR, cchLen * sizeof(WideChar)));
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, @str[1], Length(str), pwc, cchLen);
end;
end;
////////////////////////////////////////////////////////////////////////////////
function IsInGroup(const Value: WideString; Groups: TGroupCollection): Boolean;
var
i : Integer;
s : WideString;
begin
result := false;
for i := 0 to Groups.Count - 1 do
begin
s := Groups.Items[i].GetName;
if (s = Value) then
begin
result := True;
exit;
end;
end;
end;
{$HINTS OFF}
procedure GrantPrivilege(const Server, Group, Privilege: string; Grant: Boolean);
var
sid : PSID;
sidSize, sidNameUse: DWORD;
domainNameSize : DWORD;
domainName : array[0..DNLEN] of Char;
attributes : TLsaObjectAttributes;
policyHandle : LSA_HANDLE;
lsaComputerName, rightsLsaUnicodeString: TLSAUnicodeStr;
status : NTStatus;
begin
status := STATUS_SUCCESS;
sidSize := 65536;
GetMem(sid, sidSize);
domainNameSize := DNLEN + 1;
try
if LookupAccountName(PChar(Server), PChar(Group), sid, sidSize, domainName, domainNameSize, sidNameUse) then
begin
lsaComputerName := TLsaUnicodeStr.CreateFromStrW(Server);
try
FillChar(attributes, SizeOf(attributes), 0);
status := LsaOpenPolicy(lsaComputerName.value, attributes, POLICY_CREATE_ACCOUNT or POLICY_LOOKUP_NAMES,
policyHandle);
if status = STATUS_SUCCESS then
try
rightsLsaUnicodeString := TLsaUnicodeStr.CreateFromStrW(privilege);
try
if Grant then
status := LsaAddAccountRights(PolicyHandle, sid, @rightsLsaUnicodeString.value, 1)
else
status := LsaRemoveAccountRights(PolicyHandle, sid, False, @rightsLsaUnicodeString.value, 1);
finally
rightsLsaUnicodeString.Free
end
finally
LsaClose(PolicyHandle)
end
finally
lsaComputerName.Free
end
end
finally
FreeMem(sid)
end;
//if status <> STATUS_SUCCESS then
//raise ENetAPIError.Create(LsaNtStatusToWinError(status));
end;
{$HINTS ON}
////////////////////////////////////////////////////////////////////////////////
function GetAccountSid(const Server, User: WideString; var Sid: PSID): DWORD;
var
dwDomainSize, dwSidSize: DWord;
R : LongBool;
wDomain : WideString;
Use : DWord;
begin
Result := 0;
SetLastError(0);
dwSidSize := 0;
dwDomainSize := 0;
R := LookupAccountNameW(PWideChar(Server), PWideChar(User), nil, dwSidSize,
nil, dwDomainSize, Use);
if (not R) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) then
begin
SetLength(wDomain, dwDomainSize);
Sid := GetMemory(dwSidSize);
R := LookupAccountNameW(PWideChar(Server), PWideChar(User), Sid,
dwSidSize, PWideChar(wDomain), dwDomainSize, Use);
if not R then
begin
FreeMemory(Sid);
Sid := nil;
end;
end
else
Result := GetLastError;
end;
////////////////////////////////////////////////////////////////////////////////
function AutoLogIn(Computer, User: string): Boolean;
var
MyReg : TMpuRegistry;
AutoLogon : WideString;
DefaultUsername : WideString;
begin
MyReg := TMpuRegistry.CreateW(Computer, HKEY_LOCAL_MACHINE);
try
with MyReg do
begin
if Connect = 0 then
begin
if OpenKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon', KEY_READ) = 0 then
begin
ReadStringW('AutoAdminLogon', AutoLogon);
ReadStringW('DefaultUsername', DefaultUsername);
end;
end;
end;
finally
MyReg.Free;
end;
result := (AutoLogon = '1') and (DefaultUsername = User);
end;
////////////////////////////////////////////////////////////////////////////////
function SetWinlogonPassword(const Server, Password: WideString): Boolean;
var
oa : TLSAObjectAttributes;
hPolicy : LSA_HANDLE;
usServer : TLSAUnicodeString;
usKeyName : TLSAUnicodeString;
usPassWord : TLSAUnicodeString;
Status : NTSTATUS;
begin
ZeroMemory(@oa, sizeof(oa));
oa.Length := sizeof(oa);
try
RtlInitUnicodeString(@usServer, PWideChar(Server));
Status := LsaOpenPolicy(usServer, oa, POLICY_CREATE_SECRET, hPolicy);
if (NT_SUCCESS(Status)) then
begin
RtlInitUnicodeString(@usKeyName, 'DefaultPassword');
RtlInitUnicodeString(@usPassWord, PWideChar(Password));
Status := LsaStorePrivateData(hPolicy, usKeyName, usPassword);
end;
finally
LsaClose(hPolicy);
end;
Result := NT_SUCCESS(Status);
end;
////////////////////////////////////////////////////////////////////////////////
function SetAutoWinlogon(Server: WideString; Activate: Boolean; Username, Password: WideString): Boolean;
var
usPassword : TLSAUnicodeString;
usServer : TLSAUnicodeString;
reg : TMpuRegistry;
begin
Result := False;
reg := TMpuRegistry.CreateW(Server, HKEY_LOCAL_MACHINE);
if (Assigned(reg)) then
try
reg.Connect;
if reg.OpenKeyW('Software\Microsoft\Windows NT\CurrentVersion\Winlogon', KEY_WRITE) = 0 then
begin
// Username
if Username <> '' then
reg.WriteStringW('DefaultUserName', Username)
else
reg.DeleteValueName('DefaultUserName');
// Domain
if Server <> '' then
reg.WriteStringW('DefaultDomainName', Server)
else
reg.DeleteValueName('DefaultDomainName');
// Init unicode string
RtlInitUnicodeString(@usPassword, PWideChar(Password));
RtlInitUnicodeString(@usServer, PWideChar(Server));
// Set the password in secret stash
if SetWinlogonPassword(usServer.Buffer, usPassword.Buffer) then
begin
Result := True;
end;
reg.DeleteValueName('DefaultPassword');
// Activate autologon
reg.WriteString('AutoAdminLogon', IntToStr(ord(Activate)));
end;
finally
reg.Free;
end;
end;
////////////////////////////////////////////////////////////////////////////////
function RemoveAutoLogin(const Machine: string): LongInt;
var
MyReg : TMpuRegistry;
ret : LongInt;
begin
MyReg := TMpuRegistry.CreateW(Machine, HKEY_LOCAL_MACHINE);
try
with MyReg do
begin
ret := Connect;
if ret = 0 then
begin
ret :=
OpenKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon',
KEY_WRITE);
if ret = 0 then
begin
DeleteValueName('DefaultPassword');
ret := WriteString('AutoAdminLogon', '0');
end;
end;
end;
finally
MyReg.Free;
end;
result := ret;
end;
////////////////////////////////////////////////////////////////////////////////
function IsAccountHidden(const Machine, User: string): Boolean;
var
MyReg : TMpuRegistry;
ret : Integer;
Hidden : LongInt;
begin
Hidden := 0;
result := False;
MyReg := TMpuRegistry.CreateW(Machine, HKEY_LOCAL_MACHINE);
try
with MyReg do
begin
ret := Connect;
if ret = 0 then
begin
ret := OpenKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList', KEY_READ);
if ret = 0 then
begin
ReadInt(User, Hidden);
result := Hidden = 0;
end
else
result := False;
end;
end;
finally
MyReg.Free;
end;
end;
////////////////////////////////////////////////////////////////////////////////
function HideAccountFnc(const Computer, User: string; Hide: Boolean): LongInt;
var
MyReg : TMpuRegistry;
ret : LongInt;
begin
MyReg := TMpuRegistry.CreateW(Computer, HKEY_LOCAL_MACHINE);
try
with MyReg do
begin
ret := Connect;
if ret = 0 then
begin
ret := CreateKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList');
if ret = 0 then
begin
if Hide then
ret := WriteInt(User, 0)
else
ret := WriteInt(User, 1);
end;
end;
end;
finally
MyReg.Free;
end;
result := ret;
end;
////////////////////////////////////////////////////////////////////////////////
{ TUser }
constructor TUser.Create(const server: WideString; ui3: PUserInfo3);
begin
FEditable := True;
FInitialized := True;
FServer := server;
Fui3 := ui3^; // DWords kopieren
// LPWSTRs müssen extra kopiert werden
SetStrings(ui3);
end;
////////////////////////////////////////////////////////////////////////////////
constructor TUser.Create(const server: WideString; lgmi: PLocalGroupMembersInfo3);
begin
FEditable := False;
FInitialized := False;
FServer := server;
Fui3.usri3_name := SysAllocString(PWideChar(ExtractFilenameW(lgmi.lgrmi3_domainandname)));
end;
////////////////////////////////////////////////////////////////////////////////
destructor TUser.Destroy;
begin
FGroups.Free;
SysFreeString(Fui3.usri3_name);
SysFreeString(Fui3.usri3_home_dir);
SysFreeString(Fui3.usri3_comment);
SysFreeString(Fui3.usri3_script_path);
SysFreeString(Fui3.usri3_full_name);
SysFreeString(Fui3.usri3_usr_comment);
SysFreeString(Fui3.usri3_parms);
SysFreeString(Fui3.usri3_workstations);
SysFreeString(Fui3.usri3_logon_server);
SysFreeString(Fui3.usri3_profile);
SysFreeString(Fui3.usri3_home_dir_drive);
inherited;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetAutoLogin: Boolean;
var
AutoLogon : WideString;
DefaultUsername : WideString;
begin
with TMpuRegistry.CreateW(FServer, HKEY_LOCAL_MACHINE) do
try
Connect;
if OpenKeyW('SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon', KEY_READ) = 0 then
begin
ReadStringW('AutoAdminLogon', AutoLogon);
ReadStringW('DefaultUsername', DefaultUsername);
end;
finally
Free;
end;
result := (AutoLogon = '1') and (DefaultUsername = Name);
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetAccountExpires: Cardinal;
begin
Initialize();
Result := Fui3.usri3_acct_expires;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetCantChangePW: Boolean;
begin
Initialize();
Result := (Fui3.usri3_flags and UF_PASSWD_CANT_CHANGE) = UF_PASSWD_CANT_CHANGE;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetCaption: WideString;
begin
Result := Name;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetChildList: TList;
begin
Result := Groups;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetDeactivated: Boolean;
begin
Initialize();
Result := (Fui3.usri3_flags and UF_ACCOUNTDISABLE) = UF_ACCOUNTDISABLE;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetInternetDomainTrustAccount: Boolean;
begin
Initialize();
Result := (Fui3.usri3_flags and UF_INTERDOMAIN_TRUST_ACCOUNT) = UF_INTERDOMAIN_TRUST_ACCOUNT;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetNormalAccount: Boolean;
begin
Initialize();
Result := (Fui3.usri3_flags and UF_NORMAL_ACCOUNT) = UF_NORMAL_ACCOUNT;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetTempDublicateAccount: Boolean;
begin
Initialize();
Result := (Fui3.usri3_flags and UF_TEMP_DUPLICATE_ACCOUNT) = UF_TEMP_DUPLICATE_ACCOUNT;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetWorkstationTrustAccount: Boolean;
begin
Initialize();
Result := (Fui3.usri3_flags and UF_WORKSTATION_TRUST_ACCOUNT) = UF_WORKSTATION_TRUST_ACCOUNT;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetServerTrustAccount: Boolean;
begin
Initialize();
Result := (Fui3.usri3_flags and UF_SERVER_TRUST_ACCOUNT) = UF_SERVER_TRUST_ACCOUNT;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetDontExpire: Boolean;
begin
Initialize();
Result := (Fui3.usri3_flags and UF_DONT_EXPIRE_PASSWD) = UF_DONT_EXPIRE_PASSWD;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetDescription: WideString;
begin
Initialize();
Result := Fui3.usri3_comment;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetCountLogons: Cardinal;
begin
Initialize();
Result := Fui3.usri3_num_logons;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetEditable: Boolean;
begin
if not FInitialized then
Initialize();
Result := FEditable;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetErroneousLogons: Cardinal;
begin
Initialize();
Result := Fui3.usri3_bad_pw_count;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetFullName: WideString;
begin
Initialize;
Result := Fui3.usri3_full_name;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetGroups: TGroupCollection;
begin
if FGroups = nil then
FGroups := TGroupCollection.GetUserGroups(Self);
Result := FGroups;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetHideAccount: Boolean;
begin
Initialize();
result := IsAccountHidden(self.Server, Self.GetName);
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetHomeDir: WideString;
begin
Initialize();
Result := Fui3.usri3_home_dir;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetImageIndex: Integer;
const
imageIndex : array[Boolean] of Integer = (1, 4);
begin
Result := imageIndex[Deactivated or not Editable];
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetLastLogon: Cardinal;
begin
Initialize();
Result := Fui3.usri3_last_logon;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetMustChangePW: Boolean;
begin
Initialize();
Result := Fui3.usri3_password_expired <> 0;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetName: WideString;
begin
// kein Initialize() -> Name ist immer gesetzt!
Result := Fui3.usri3_name;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetQuota: Cardinal;
begin
Initialize();
Result := Fui3.usri3_max_storage;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetUserID: Cardinal;
begin
Initialize();
Result := Fui3.usri3_user_id;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetScriptPath: WideString;
begin
Initialize();
Result := Fui3.usri3_script_path;
end;
////////////////////////////////////////////////////////////////////////////////
function TUser.GetPWAge: Cardinal;
begin
Initialize();
Result := Fui3.usri3_password_age;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.Initialize();
var
ui3 : PUserInfo3;
error : DWORD;
begin
if FInitialized then
Exit;
FInitialized := True;
ui3 := nil;
try
error := NetUserGetInfo(PWideChar(Server), Fui3.usri3_name, 3, Pointer(ui3));
if error = NERR_UserNotFound then
Exit
else if (error <> NERR_SUCCESS) then
raise ENetAPIError.Create(error);
FEditable := True;
SysFreeString(Fui3.usri3_name);
Fui3 := ui3^;
SetStrings(ui3);
finally
NetApiBufferFree(ui3);
end;
end;
procedure TUser.SetAccountExpires(const Value: DWORD);
begin
Fui3.usri3_acct_expires := TIMEQ_FOREVER;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetAutoLogin(const Value: Boolean);
var
lpwcsPassword,
lpwcsServer,
lpwcsUsername : PWideChar;
begin
FillPWideCharFromString(lpwcsUsername, string(self.Name));
FillPWideCharFromString(lpwcsServer, string(FServer));
FillPWideCharFromString(lpwcsPassword, string(FAutoLoginPW));
if Value then
SetAutoWinlogon(lpwcsServer, Value, lpwcsUsername, lpwcsPassword)
else
RemoveAutoLogin(FServer);
if (Assigned(lpwcsUsername)) then
GlobalFree(HGLOBAL(lpwcsUsername));
if (Assigned(lpwcsServer)) then
GlobalFree(HGLOBAL(lpwcsServer));
if (Assigned(lpwcsPassword)) then
GlobalFree(HGLOBAL(lpwcsPassword));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetInternetDomainTrustAccount(const Value: Boolean);
begin
if Value then
Fui3.usri3_flags := Fui3.usri3_flags or UF_INTERDOMAIN_TRUST_ACCOUNT
else
Fui3.usri3_flags := Fui3.usri3_flags and not UF_INTERDOMAIN_TRUST_ACCOUNT
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetNormalAccount(const Value: Boolean);
begin
if Value then
Fui3.usri3_flags := Fui3.usri3_flags or UF_NORMAL_ACCOUNT
else
Fui3.usri3_flags := Fui3.usri3_flags and not UF_NORMAL_ACCOUNT
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetTempDublicateAccount(const Value: Boolean);
begin
if Value then
Fui3.usri3_flags := Fui3.usri3_flags or UF_TEMP_DUPLICATE_ACCOUNT
else
Fui3.usri3_flags := Fui3.usri3_flags and not UF_TEMP_DUPLICATE_ACCOUNT
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetWorkstationTrustAccount(const Value: Boolean);
begin
if Value then
Fui3.usri3_flags := Fui3.usri3_flags or UF_WORKSTATION_TRUST_ACCOUNT
else
Fui3.usri3_flags := Fui3.usri3_flags and not UF_WORKSTATION_TRUST_ACCOUNT
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetServerTrustAccount(const Value: Boolean);
begin
if Value then
Fui3.usri3_flags := Fui3.usri3_flags or UF_SERVER_TRUST_ACCOUNT
else
Fui3.usri3_flags := Fui3.usri3_flags and not UF_SERVER_TRUST_ACCOUNT
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetDeactivated(const Value: Boolean);
begin
if Value then
Fui3.usri3_flags := Fui3.usri3_flags or UF_ACCOUNTDISABLE
else
Fui3.usri3_flags := Fui3.usri3_flags and not UF_ACCOUNTDISABLE
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetDontExpire(const Value: Boolean);
begin
if Value then
Fui3.usri3_flags := Fui3.usri3_flags or UF_DONT_EXPIRE_PASSWD
else
Fui3.usri3_flags := Fui3.usri3_flags and not UF_DONT_EXPIRE_PASSWD;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetDescription(const Value: WideString);
begin
SysFreeString(Fui3.usri3_comment);
Fui3.usri3_comment := SysAllocString(PWideChar(Value));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetCantChangePW(const Value: Boolean);
begin
if Value then
Fui3.usri3_flags := Fui3.usri3_flags or UF_PASSWD_CANT_CHANGE
else
Fui3.usri3_flags := Fui3.usri3_flags and not UF_PASSWD_CANT_CHANGE;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetAutoLoginPW(const Value: WideString);
begin
FAutoLoginPW := Value;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetName(const Value: WideString);
begin
Initialize;
SysFreeString(Fui3.usri3_name);
Fui3.usri3_name := SysAllocString(PWideChar(Value));
end;
procedure TUser.SetFullName(const Value: WideString);
begin
SysFreeString(Fui3.usri3_full_name);
Fui3.usri3_full_name := SysAllocString(PWideChar(Value));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetScriptPath(const Value: WideString);
begin
SysFreeString(Fui3.usri3_script_path);
Fui3.usri3_script_path := SysAllocString(PWideChar(Value));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetPassword(const Value: WideString);
begin
SysFreeString(Fui3.usri3_password);
Fui3.usri3_password := SysAllocString(PWideChar(Value));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetHideAccount(const Value: Boolean);
begin
HideAccountFnc(FServer, self.GetName, Value);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetMustChangePW(const Value: Boolean);
begin
Fui3.usri3_password_expired := Ord(Value);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetHomeDir(const Value: WideString);
begin
SysFreeString(Fui3.usri3_home_dir);
Fui3.usri3_home_dir := SysAllocString(PWideChar(Value));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.AddToGroup(const Value: WideString);
var
pSID : Pointer;
error : Integer;
begin
error := 0;
FGroups := TGroupCollection.Create;
try
FGroups.GetUserGroups(self);
// check whether user is in group
// if not, add to group
if not IsInGroup(Value, self.GetGroups) then
begin
if (GetAccountSid(FServer, self.GetName, pSID) = 0) and Assigned(pSID) then
begin
error := NetLocalGroupAddMembers(PWideChar(Server), PWideChar(Value), 0, @pSID, 1);
FreeMemory(pSID);
if (error <> NERR_SUCCESS) and (error <> 1378) then
raise ENetAPIError.Create(error);
end
else
raise ENetAPIError.Create(error);
end;
finally
Fgroups.Free;
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.RemoveFromGroup(const Value: WideString);
var
error : Integer;
Member : PLocalGroupMembersInfo3;
begin
error := 0;
FGroups := TGroupCollection.Create;
try
FGroups.GetUserGroups(self);
// remover group from group list
Self.FGroups.Delete(Value);
// check whether user is in group
// if user is not in group, remove from group
if not IsInGroup(Value, self.GetGroups) then
begin
GetMem(Member, sizeof(TLocalGroupMembersInfo3));
try
//Self.FGroups.Delete(Value); // 2006-12-08
Member.lgrmi3_domainandname := PWideChar(copy(FServer, 3, length(FServer)) + '\' + self.GetName);
error := NetLocalGroupDelMembers(PWideChar(FServer), PWideChar(Value), 3, Member, 1);
finally
FreeMem(Member, sizeof(TLocalGroupMembersInfo3));
// ignore error if user is not in group
// because we are iterating through all avaiable groups
if (error <> NERR_Success) and (error <> ERROR_MEMBER_NOT_IN_ALIAS) then
raise ENetAPIError.Create(error);
end;
end;
finally
Self.FGroups.Free;
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.SetStrings(ui3: PUserInfo3);
begin
with ui3^ do
begin
Fui3.usri3_name := SysAllocString(usri3_name);
Fui3.usri3_home_dir := SysAllocString(usri3_home_dir);
Fui3.usri3_comment := SysAllocString(usri3_comment);
Fui3.usri3_script_path := SysAllocString(usri3_script_path);
Fui3.usri3_full_name := SysAllocString(usri3_full_name);
Fui3.usri3_usr_comment := SysAllocString(usri3_usr_comment);
Fui3.usri3_parms := SysAllocString(usri3_parms);
Fui3.usri3_workstations := SysAllocString(usri3_workstations);
Fui3.usri3_logon_server := SysAllocString(usri3_logon_server);
Fui3.usri3_profile := SysAllocString(usri3_profile);
Fui3.usri3_home_dir_drive := SysAllocString(usri3_home_dir_drive);
//Fui3.usri3_password := SysAllocString(usri3_password);
end;
end;
////////////////////////////////////////////////////////////////////////////////
{ TUserCollection }
function TUserCollection.Add(Item: TUser): Integer;
begin
Result := inherited Add(Item);
end;
////////////////////////////////////////////////////////////////////////////////
function TUserCollection.First: TUser;
begin
Result := inherited First();
end;
////////////////////////////////////////////////////////////////////////////////
function TUserCollection.Get(Index: Integer): TUser;
begin
Result := inherited Get(Index);
end;
////////////////////////////////////////////////////////////////////////////////
class function TUserCollection.GetAll(const Server: WideString;
filter: DWord = FILTER_NORMAL_ACCOUNT): TUserCollection;
var
bufPtr : Pointer;
pCurrent : PUserInfo3;
readCount, totalCount: DWord;
error : DWord;
i : Integer;
begin
Result := nil;
if Server = '' then
raise EArgumentNull.Create('Server');
bufPtr := nil;
try
error := NetUserEnum(PWideChar(Server), 3, filter, bufPtr,
MAX_PREFERRED_LENGTH, readCount, totalCount, nil);
if (error <> NERR_SUCCESS) then
raise ENetAPIError.Create(error);
Result := TUserCollection.Create();
pCurrent := bufPtr;
Result.SetCapacity(readCount);
for i := 0 to readCount - 1 do
begin
Result.Add(TUser.Create(Server, pCurrent));
Inc(pCurrent);
end;
finally
NetApiBufferFree(bufPtr);
end;
end;
////////////////////////////////////////////////////////////////////////////////
class function TUserCollection.GetGroupMembers(Group: TGroup): TUserCollection;
var
bufPtr : Pointer;
pCurrent : PLocalGroupMembersInfo3;
readCount, totalCount: DWord;
error : DWord;
i : Integer;
begin
Result := nil;
if Group = nil then
raise EArgumentNull.Create('Group');
bufPtr := nil;
try
error := NetLocalGroupGetMembers(PWideChar(Group.Server), PWideChar(Group.Name),
3, bufPtr, MAX_PREFERRED_LENGTH, readCount, totalCount, nil);
if (error <> NERR_SUCCESS) then
raise ENetAPIError.Create(error);
Result := TUserCollection.Create();
pCurrent := bufPtr;
Result.SetCapacity(readCount);
for i := 0 to readCount - 1 do
begin
Result.Add(TUser.Create(Group.Server, pCurrent));
Inc(pCurrent);
end;
finally
NetApiBufferFree(bufPtr);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.Add;
const
DOMAIN_GROUP_RID_USERS = $00000201;
var
error : DWORD;
begin
Fui3.usri3_primary_group_id := DOMAIN_GROUP_RID_USERS;
error := NetUserAdd(PWideChar(FServer), 3, @Fui3, nil);
if error <> 0 then
raise ENetAPIError.Create(error);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.Save;
var
error : DWORD;
begin
Fui3.usri3_logon_hours := nil;
Fui3.usri3_acct_expires := TIMEQ_FOREVER;
error := NetUserSetInfo(PWideChar(FServer), PWideChar(GetCaption), 3, @Fui3, nil);
if error <> 0 then
raise ENetAPIError.Create(error);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUser.Del;
var
error : DWORD;
begin
error := NetUserDel(PWideChar(FServer), PWideChar(self.GetCaption));
if error <> 0 then
raise ENetAPIError.Create(error);
end;
////////////////////////////////////////////////////////////////////////////////
function TUserCollection.IndexOf(Item: TUser): Integer;
begin
Result := inherited IndexOf(Item);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TUserCollection.Put(Index: Integer; const Value: TUser);
begin
inherited Put(Index, Value);
end;
////////////////////////////////////////////////////////////////////////////////
{ TGroup }
constructor TGroup.Create(const Server: WideString; lgi0: PLocalGroupInfo0);
begin
FServer := Server;
Flgi0.lgrpi0_name := SysAllocString(lgi0^.lgrpi0_name);
end;
////////////////////////////////////////////////////////////////////////////////
constructor TGroup.Create(const Server: WideString; lgi1: TLocalGroupInfo1);
begin
FServer := Server;
Flgi1 := lgi1;
end;
////////////////////////////////////////////////////////////////////////////////
destructor TGroup.Destroy;
begin
FMembers.Free;
SysFreeString(Flgi0.lgrpi0_name);
inherited;
end;
////////////////////////////////////////////////////////////////////////////////
function TGroup.GetCaption: WideString;
begin
Result := Name;
end;
////////////////////////////////////////////////////////////////////////////////
function TGroup.GetChildList: TList;
begin
Result := Members;
end;
////////////////////////////////////////////////////////////////////////////////
function TGroup.GetImageIndex: Integer;
begin
Result := 2;
end;
////////////////////////////////////////////////////////////////////////////////
function TGroup.GetName: WideString;
begin
Result := Flgi0.lgrpi0_name;
end;
////////////////////////////////////////////////////////////////////////////////
function TGroup.GetComment: WideString;
var
bufPtr : Pointer;
error : DWORD;
begin
error := NetLocalGroupGetInfo(PWideChar(FServer), PWideChar(self.Name), 1, bufPtr);
if (error <> NERR_SUCCESS) then
raise ENetAPIError.Create(error);
Result := PLocalGroupInfo1(bufPtr)^.lgrpi1_comment;
NetApiBufferFree(bufPtr)
end;
////////////////////////////////////////////////////////////////////////////////
function TGroup.GetUsers: TUserCollection;
begin
if FMembers = nil then
FMembers := TUserCollection.GetGroupMembers(Self);
Result := FMembers;
end;
///////////////////////////////////////////////////////////////////////////////
procedure TGroup.Add;
var
error : DWORD;
begin
error := NetLocalGroupAdd(PWideChar(FServer), 1, @Flgi1, nil);
if error <> NERR_SUCCESS then
raise ENetAPIError.Create(error);
end;
///////////////////////////////////////////////////////////////////////////////
procedure TGroup.Del;
var
error : DWORD;
Group : WideString;
begin
Group := Flgi1.lgrpi1_name;
error := NetLocalGroupDel(PWideChar(FServer), PWideChar(Group));
if error <> NERR_SUCCESS then
raise ENetAPIError.Create(error);
end;
///////////////////////////////////////////////////////////////////////////////
{ TGroupCollection }
function TGroupCollection.Get(Index: Integer): TGroup;
begin
Result := inherited Get(Index);
end;
////////////////////////////////////////////////////////////////////////////////
function TGroupCollection.Add(Item: TGroup): Integer;
begin
Result := inherited Add(Item);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TGroupCollection.Delete(const Group: WideString);
var
i : Integer;
s : WideString;
begin
for i := self.Count - 1 downto 0 do
begin
s := self.Items[i].GetName;
if Group = s then
begin
inherited Delete(i);
exit;
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TGroupCollection.First: TGroup;
begin
Result := inherited First();
end;
////////////////////////////////////////////////////////////////////////////////
class function TGroupCollection.GetAll(const Server: WideString): TGroupCollection;
var
bufPtr : Pointer;
pCurrent : PLocalGroupInfo0;
readCount, totalCount: DWord;
error : DWord;
i : Integer;
begin
Result := nil;
if Server = '' then
raise EArgumentNull.Create('Server');
bufPtr := nil;
try
error := NetLocalGroupEnum(PWideChar(Server), 0, bufPtr, MAX_PREFERRED_LENGTH, readCount, totalCount, nil);
if (error <> NERR_SUCCESS) then
raise ENetAPIError(error);
Result := TGroupCollection.Create();
pCurrent := bufPtr;
Result.SetCapacity(readCount);
for i := 0 to readCount - 1 do
begin
Result.Add(TGroup.Create(Server, pCurrent));
Inc(pCurrent);
end;
finally
NetApiBufferFree(bufPtr)
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TGroupCollection.Put(Index: Integer; const Value: TGroup);
begin
inherited Put(Index, Value);
end;
////////////////////////////////////////////////////////////////////////////////
function TGroupCollection.IndexOf(Item: TGroup): Integer;
begin
Result := inherited IndexOf(Item);
end;
////////////////////////////////////////////////////////////////////////////////
class function TGroupCollection.GetUserGroups(User: TUser): TGroupCollection;
var
bufPtr : Pointer;
pCurrent : PLocalGroupInfo0;
readCount, totalCount: DWord;
error : DWord;
i : Integer;
begin
Result := nil;
if User = nil then
raise EArgumentNull.Create('User');
bufPtr := nil;
try
error := NetUserGetLocalGroups(PWideChar(User.Server), PWideChar(User.Name), 0, 0, bufPtr, MAX_PREFERRED_LENGTH,
readCount, totalCount);
if (error <> NERR_SUCCESS) then
raise ENetAPIError.Create(error);
Result := TGroupCollection.Create();
pCurrent := bufPtr;
Result.SetCapacity(readCount);
for i := 0 to readCount - 1 do
begin
Result.Add(TGroup.Create(User.Server, pCurrent));
Inc(pCurrent);
end;
finally
NetApiBufferFree(bufPtr)
end;
end;
{ TPrivilege }
constructor TPrivilege.Create(const Server, RightConstant: string);
begin
FServer := Server;
FRightConstant := RightConstant;
self.SetDescription(RightConstant);
end;
function TPrivilege.GetDescription: string;
begin
Result := self.FRightDescription;
end;
function TPrivilege.GetRightConstant: string;
begin
result := self.FRightConstant;
end;
procedure TPrivilege.SetDescription(const RightConstant: string);
var
languageID : Cardinal;
buffer : array[0..256] of Char;
bufSize : Cardinal;
begin
bufSize := sizeof(buffer);
if LookupPrivilegeDisplayName(PChar(FServer), PChar(self.Constant), buffer, bufSize, languageID) then
FRightDescription := string(buffer)
else
FRightDescription := self.Constant;
end;
{ TPrivilegeCollection }
function TPrivilegeCollection.Add(Item: TPrivilege): Integer;
begin
Result := inherited Add(Item);
end;
function TPrivilegeCollection.Get(Index: Integer): TPrivilege;
begin
Result := inherited Get(Index);
end;
class function TPrivilegeCollection.GetAll(const Server: WideString): TPrivilegeCollection;
var
i : Integer;
begin
Result := TPrivilegeCollection.Create;
for i := 0 to length(PrivArray) - 1 do
begin
Result.Add(TPrivilege.Create(Server, PrivArray[i]));
end;
end;
class function TPrivilegeCollection.GetUserPrivileges(const Server, User: WideString): TPrivilegeCollection;
var
sid : PSID;
sidSize : DWORD;
sidNameUse : SID_NAME_USE;
domainName : array[0..DNLEN + 1] of Char;
domainNameSize : DWORD;
lsaComputerName : TLsaUnicodeStr;
lsaRights, p : PLsaUnicodeString;
objectAttributes : TLsaObjectAttributes;
policyHandle : LSA_HANDLE;
status : NTSTATUS;
rightsCount, i, err: Integer;
begin
status := 0;
Result := TPrivilegeCollection.Create;
rightsCount := 0;
sidSize := 65536;
GetMem(sid, sidSize);
try
domainNameSize := DNLEN + 1;
if LookupAccountName(PChar(string(Server)), PChar(string(User)), sid, sidSize, domainName, domainNameSize,
sidNameUse) then
begin
ReallocMem(sid, sidSize);
lsaComputerName := TLsaUnicodeStr.CreateFromStrW(Server);
try
FillChar(objectAttributes, sizeof(objectAttributes), 0);
status := lsaapi.LsaOpenPolicy(lsaComputername.Value, ObjectAttributes, POLICY_LOOKUP_NAMES, PolicyHandle);
if status = STATUS_SUCCESS then
try
status := LsaEnumerateAccountRights(PolicyHandle, sid, lsaRights, rightsCount);
if status = STATUS_SUCCESS then
try
p := lsaRights;
for i := 0 to rightsCount - 1 do
begin
Result.Add(TPrivilege.Create(Server, LsaUnicodeStringToStr(p^)));
Inc(p)
end;
finally
LsaFreeMemory(lsaRights)
end
else
begin
err := LsaNTStatusToWinError(status);
if (err <> 2) and (err <> 5) then
raise ENetAPIError.Create(err);
end
finally
LsaClose(PolicyHandle)
end
else
begin
err := LsaNTStatusToWinError(status);
raise ENetAPIError.Create(err);
end;
finally
lsaComputerName.Free
end
end
else
begin
err := LsaNTStatusToWinError(status);
raise ENetAPIError.Create(err);
end;
finally
FreeMem(sid)
end;
end;
function TPrivilegeCollection.IndexOf(Item: TPrivilege): Integer;
begin
Result := inherited IndexOf(Item);
end;
procedure TPrivilegeCollection.Put(Index: Integer; const Value: TPrivilege);
begin
end;
end.
|
{ Subroutine STRING_PARITY_OFF (S)
*
* Turn the parity bit off for each byte in the string.
}
module string_parity_off;
define string_parity_off;
%include 'string2.ins.pas';
procedure string_parity_off ( {turn parity bits off for all chars in string}
in out s: univ string_var_arg_t); {string}
var
i: sys_int_machine_t; {loop counter}
begin
for i := 1 to s.len do begin {once for each character in string}
s.str[i] := chr(ord(s.str[i]) & 8#177); {mask off high bit of byte}
end; {back for next character}
end;
|
unit aOPCCollection;
interface
uses
Classes, SysUtils,
uDCObjects,
aOPCClass, aCustomOPCSource;
type
TTagCollection = class;
{ TTagCollectionItem }
TTagCollectionItem = class(TCollectionItem)
private
FDataLink: TaOPCDataLink;
FOnChange: TNotifyEvent;
FName: string;
procedure SetDataLink(Value: TaOPCDataLink);
function GetPhysID: TPhysID;
function GetValue: string;
procedure SetPhysID(const Value: TPhysID);
procedure SetValue(const Value: string);
function GetOPCSource: TaCustomOPCSource;
function GetStairsOptions: TDCStairsOptionsSet;
procedure SetOPCSource(const Value: TaCustomOPCSource);
procedure SetStairsOptions(const Value: TDCStairsOptionsSet);
procedure SetName(const Value: string);
protected
procedure ChangeData(Sender:TObject);virtual;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property DataLink: TaOPCDataLink read FDataLink write SetDataLink;
published
property Name: string read FName write SetName;
property OPCSource : TaCustomOPCSource
read GetOPCSource write SetOPCSource;
property PhysID:TPhysID read GetPhysID write SetPhysID;
property StairsOptions : TDCStairsOptionsSet
read GetStairsOptions write SetStairsOptions default [];
property Value:string read GetValue write SetValue;
property OnChange:TNotifyEvent read FOnChange write FOnChange;
end;
TTagCollectionItemClass = class of TCollectionItem;
{ TTagCollection }
TTagCollection = class(TCollection)
private
FOnChanged: TNotifyEvent;
function GetTagItem(Index: Integer): TTagCollectionItem;
procedure SetTagItem(Index: Integer; const Value: TTagCollectionItem);
protected
FOwner: TPersistent;
//function GetOwner: TPersistent; override;
procedure Update(Item: TCollectionItem); override;
public
//constructor Create(Owner: TPersistent);
property Items[Index: Integer]: TTagCollectionItem
read GetTagItem write SetTagItem; default;
published
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
end;
implementation
{ TTagCollectionItem }
procedure TTagCollectionItem.Assign(Source: TPersistent);
var
aSourceItem: TTagCollectionItem;
begin
if Source is TTagCollectionItem then
begin
aSourceItem := TTagCollectionItem(Source);
FDataLink.PhysID := aSourceItem.FDataLink.PhysID;
FDataLink.StairsOptions := aSourceItem.FDataLink.StairsOptions;
end
else
inherited Assign(Source);
end;
procedure TTagCollectionItem.ChangeData(Sender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
constructor TTagCollectionItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FDataLink := TaOPCDataLink.Create(Self);
FDataLink.OnChangeData := ChangeData;
FDataLink.StairsOptions := [];
end;
destructor TTagCollectionItem.Destroy;
begin
FOnChange := nil;
OPCSource := nil;
FDataLink.Free;
inherited Destroy;
end;
function TTagCollectionItem.GetOPCSource: TaCustomOPCSource;
begin
Result := FDataLink.OPCSource;
end;
function TTagCollectionItem.GetPhysID: TPhysID;
begin
Result := FDataLink.PhysID;
end;
function TTagCollectionItem.GetStairsOptions: TDCStairsOptionsSet;
begin
Result := FDataLink.StairsOptions;
end;
function TTagCollectionItem.GetValue: string;
begin
Result := FDataLink.Value;
end;
procedure TTagCollectionItem.SetDataLink(Value: TaOPCDataLink);
begin
FDataLink.PhysID := Value.PhysID;
end;
procedure TTagCollectionItem.SetName(const Value: string);
begin
FName := Value;
end;
procedure TTagCollectionItem.SetOPCSource(const Value: TaCustomOPCSource);
begin
FDataLink.OPCSource := Value;
end;
procedure TTagCollectionItem.SetPhysID(const Value: TPhysID);
begin
FDataLink.PhysID := Value;
end;
procedure TTagCollectionItem.SetStairsOptions(
const Value: TDCStairsOptionsSet);
begin
FDataLink.StairsOptions := Value;
end;
procedure TTagCollectionItem.SetValue(const Value: string);
begin
if DataLink.Value<>Value then
DataLink.Value := Value;
end;
{ TTagCollection }
//constructor TTagCollection.Create(Owner: TPersistent);
//begin
// inherited Create(TTagCollectionItem);
// FOwner := Owner;
//end;
function TTagCollection.GetTagItem(Index: Integer): TTagCollectionItem;
begin
Result := TTagCollectionItem(inherited Items[Index]);
end;
procedure TTagCollection.SetTagItem(Index: Integer;
const Value: TTagCollectionItem);
begin
inherited Items[Index] := Value;
end;
//function TTagCollection.GetOwner: TPersistent;
//begin
// Result := FOwner;
//end;
procedure TTagCollection.Update(Item: TCollectionItem);
begin
inherited Update(Item);
if Assigned(FOnChanged) then FOnChanged(Item);
end;
end.
|
unit uForms;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,Lst_CadastroERP, MinhasClasses,uCad_CadastroPaiERP,uListagemPadraoERP,
Generics.Collections,cxPC,TypInfo;
type
TClasseCadastroSimples = class of TfrmLstCadastroSimplesERP;
TClasseCadastroPai = class of TfrmCad_CadastroPaiERP;
CampoChave = Variant;
TrotinasForms = class
class Procedure AbreFormCadastroPai<MyForm: TfrmCad_CadastroPaiERP >(TipoOperacaoForm: TTipoOperacaoForm);
class Procedure AbreFormListagemPadrao<MyForm: TfrmListagemPadraoERP >;
class procedure AbreFormSimples(aForm: TfrmLstCadastroSimplesERP; aClasse: TClasseCadastroSimples;TipoOperacao: TTipoOperacaoForm = toNada);
class procedure AbreFormSimplesPeloTipoPesquisa(aTipoPesquisa: TTipoPesquisa;TipoOperacaoForm: TTipoOperacaoForm = toNada);
class Function AbreCadastroNCM(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class Function AbreCadastroEmpresa(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class Function AbreCadastroCliente(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class Function AbreCadastroGrupoCliente(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class Function AbreCadastroCargos(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class Function AbreCadastroUsuario(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroDepartamento(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroFuncionarios(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroFornecedor(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroLinha(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroGrupo(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroLocalizacao(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroProduto(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroFabricante(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroUnidade(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroCodigoMunicipalServico(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroProcessoServico(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroPeridicidade(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroBanco(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroContaBancaria(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroCondicaoPagamento(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreProposta(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroTipoContrato(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreContratos(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreManutencaoEquipamentoCliente(pIdCliente: Integer;TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroTipoOS(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroStatusOS(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreInclusaoOS(pIdProposta: Integer = -1): CampoChave;
class function AbreCentralOS: CampoChave;
class procedure AbreEntradaProduto;
class procedure AbreAgenda(IdAgenda: Integer = -1);
class function AbreCadastroOperacaoEstoque(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class Procedure AbreListageEntrada;
CLASS procedure AbreVenda(IdVenda: Integer = - 1);
class function AbreCadastroTransportadora(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
class function AbreCadastroAlmoxarifado(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
private
end;
implementation
uses uCadNCM, Lst_Empresa, Cad_Cliente, Cad_usuario, uCad_Funcionario,
uCad_Fornecedor, uCad_Produto, uLst_Periodicidade, uLst_ContaBancaria,
uLst_CondicaoPagamento, uLst_Proposta, uLst_TipoContrato, uLst_Contratos,
uDlg_EquipamentoCliente, uLst_TipoOS, uLst_StatusOS, uLst_OS, uCad_OS,
uAgenda, uPrincipal, uEntrada, Lst_OperacaoEstoque, uLst_Entrada, uSaida,
uCad_Transportadora;
class procedure TrotinasForms.AbreAgenda(IdAgenda: Integer = -1);
begin
Try
frmAgenda := TfrmAgenda.Create(nil);
frmAgenda.IdAgenda := IdAgenda;
frmAgenda.ShowModal;
Finally
FreeAndNil(frmAgenda);
End;
end;
class function TrotinasForms.AbreCadastroAlmoxarifado(
TipoOperacao: TTipoOperacaoForm): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPAlmoxarifado,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroBanco(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPBanco,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroCargos(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPCargo,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroCliente(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormCadastroPai<TfrmCad_Cliente>(TipoOperacao);
end;
class function TrotinasForms.AbreCadastroCodigoMunicipalServico(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPCodigoMunicipalServico,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroCondicaoPagamento(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimples(frmLst_CondicaoPagamento, TfrmLst_CondicaoPagamento,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroContaBancaria(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimples(frmLst_ContaBancaria, TfrmLst_ContaBancaria,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroDepartamento(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPDepartamento,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroEmpresa(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimples(frmLst_Empresa, TfrmLst_Empresa,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroFabricante(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPFabricante,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroFornecedor(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormCadastroPai<TfrmCad_Fornecedor>(TipoOperacao);
end;
class function TrotinasForms.AbreCadastroFuncionarios(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormCadastroPai<TfrmCadFuncionario>(TipoOperacao);
end;
class function TrotinasForms.AbreCadastroGrupo(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPGrupo,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroGrupoCliente(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPGrupoCliente,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroLinha(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPLinha,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroLocalizacao(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPLocalizacao,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroNCM(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormCadastroPai<TfrmCad_NCM>(TipoOperacao);
end;
class function TrotinasForms.AbreCadastroOperacaoEstoque(
TipoOperacao: TTipoOperacaoForm): CampoChave;
begin
AbreFormSimples(frmLst_OperacaoEstoque,TfrmLst_OperacaoEstoque,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroPeridicidade(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimples(frmLst_Periodicidade,TfrmLst_Periodicidade,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroProcessoServico(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPProcessosservico,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroProduto(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormCadastroPai<TfrmCad_Produto>(TipoOperacao);
end;
class function TrotinasForms.AbreCadastroStatusOS(
TipoOperacao: TTipoOperacaoForm): CampoChave;
begin
AbreFormSimples(frmLst_StatusOS,TfrmLst_StatusOS,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroTipoContrato(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimples(frmLst_TipoContrato, TfrmLst_TipoContrato,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroTipoOS(
TipoOperacao: TTipoOperacaoForm): CampoChave;
begin
AbreFormSimples(frmLst_TipoOS,TfrmLst_TipoOS,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroTransportadora(
TipoOperacao: TTipoOperacaoForm): CampoChave;
begin
AbreFormCadastroPai<TfrmCad_Transportadora>(TipoOperacao);
end;
class function TrotinasForms.AbreCadastroUnidade(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormSimplesPeloTipoPesquisa(tpERPUnidade,TipoOperacao);
end;
class function TrotinasForms.AbreCadastroUsuario(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormCadastroPai<TfrmCad_usuario>(TipoOperacao);
end;
class function TrotinasForms.AbreCentralOS: CampoChave;
begin
AbreFormListagemPadrao<TfrmLst_OS>
end;
class function TrotinasForms.AbreContratos(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormListagemPadrao<TfrmLst_Contratos>
end;
class procedure TrotinasForms.AbreEntradaProduto;
begin
if not Assigned(frmEntradaEstoque) then
frmEntradaEstoque := TfrmEntradaEstoque.Create(nil);
if frmEntradaEstoque.Showing then
frmEntradaEstoque.BringToFront
else
frmEntradaEstoque.Show;
end;
class procedure TrotinasForms. AbreFormSimples(aForm: TfrmLstCadastroSimplesERP; aClasse: TClasseCadastroSimples;TipoOperacao: TTipoOperacaoForm = toNada);
begin
Try
Application.CreateForm(aClasse, aform);
case TipoOperacao of
toNada: ;
toEditar:
aForm.EditReg := True;
toIncluir:
aForm.NovoReg := True ;
end;
aForm.ShowModal;
Finally
FreeAndNil(aForm);
End;
end;
class procedure TrotinasForms.AbreFormSimplesPeloTipoPesquisa(aTipoPesquisa: TTipoPesquisa;TipoOperacaoForm: TTipoOperacaoForm);
var
aForm : TfrmLstCadastroSimplesERP;
begin
Try
Application.CreateForm(TfrmLstCadastroSimplesERP, aform);
aForm.TipoPesquisa := aTipoPesquisa;
case TipoOperacaoForm of
toNada: ;
toEditar:
aForm.EditReg := True;
toIncluir:
aForm.NovoReg := True ;
end;
aForm.ShowModal;
Finally
FreeAndNil(aForm);
End;
end;
class function TrotinasForms.AbreInclusaoOS(pIdProposta: Integer = -1): CampoChave;
begin
frmCad_OS := TfrmCad_OS.Create(nil);
Try
frmCad_OS.NovoReg := True;
frmCad_OS.IdProposta := pIdProposta;
frmCad_OS.ShowModal;
Finally
FreeAndNil(frmCad_OS);
End;
end;
class procedure TrotinasForms.AbreListageEntrada;
begin
AbreFormListagemPadrao<TfrmLst_Entrada>;
end;
class function TrotinasForms.AbreManutencaoEquipamentoCliente(pIdCliente: Integer;TipoOperacao: TTipoOperacaoForm): CampoChave;
begin
Try
frmDlg_EquipamentoCliente := TfrmDlg_EquipamentoCliente.Create(nil);
frmDlg_EquipamentoCliente.IdCliente := IntToSTr(pIdCliente);
case TipoOperacao of
toNada: ;
toEditar:
frmDlg_EquipamentoCliente.EditReg := True;
toIncluir:
frmDlg_EquipamentoCliente.NovoReg := True;
end;
if frmDlg_EquipamentoCliente.ShowModal= mrOk Then
Result := frmDlg_EquipamentoCliente.pDataSet.FieldByName('IDCLIENTEEQUIPAMENTOS').Value;
Finally
FreeAndNil(frmDlg_EquipamentoCliente);
End;
end;
class function TrotinasForms.AbreProposta(TipoOperacao: TTipoOperacaoForm = toNada): CampoChave;
begin
AbreFormListagemPadrao<TfrmLst_Proposta>;
end;
class procedure TrotinasForms.AbreVenda(IdVenda: Integer);
begin
if not Assigned(frmSaida) Then
frmSaida := TfrmSaida.Create(nil);
if frmSaida.Showing Then
frmSaida.BringToFront
else
frmSaida.Show;
end;
{ TTelas }
class procedure TrotinasForms.AbreFormCadastroPai<MyForm>(TipoOperacaoForm: TTipoOperacaoForm);
var
aForm: MyForm;
begin
Try
Application.CreateForm(MyForm, aform);
case TipoOperacaoForm of
toNada:;
toEditar:
aForm.EditReg := True;
toIncluir:
aForm.NovoReg := True;
end;
aForm.ShowModal;
Finally
FreeAndNil(aForm);
End;
end;
class procedure TrotinasForms.AbreFormListagemPadrao<MyForm>;
var
aForm: MyForm;
begin
Try
Application.CreateForm(MyForm, aform);
aForm.ShowModal;
Finally
FreeAndNil(aForm);
End;
end;
end.
|
unit frmFlowReader;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, StdCtrls, ExtCtrls, ComCtrls, Grids, TeeProcs,
TeEngine, Chart, CheckLst, Spin, contnrs, Series, TeeEdit,
Menus, MyFormUnit, RbwDataGrid4;
type
TfrmCellFlows = class(TMyForm)
Panel1: TPanel;
btnSelectFile: TButton;
OpenDialog1: TOpenDialog;
BitBtn1: TBitBtn;
btnUpdatePlot: TButton;
chartFlow: TChart;
seCells: TSpinEdit;
Panel2: TPanel;
clbDataSets: TCheckListBox;
dgCells: TRbwDataGrid4;
Splitter1: TSplitter;
Splitter2: TSplitter;
ChartEditor1: TChartEditor;
MainMenu1: TMainMenu;
File1: TMenuItem;
SelectBudgetFile1: TMenuItem;
UpdatePlot1: TMenuItem;
Exit1: TMenuItem;
FormatChart1: TMenuItem;
lblCounts: TLabel;
Label1: TLabel;
comboModelChoice: TComboBox;
sbFormat: TSpeedButton;
BitBtn2: TBitBtn;
Help1: TMenuItem;
Help2: TMenuItem;
About1: TMenuItem;
ExportData1: TMenuItem;
sdExportData: TSaveDialog;
btnPlotAll: TButton;
btnPlotNone: TButton;
procedure btnSelectFileClick(Sender: TObject);
procedure btnUpdatePlotClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure seCellsChange(Sender: TObject);
procedure FormatChart1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure clbDataSetsClickCheck(Sender: TObject);
procedure Help2Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure ExportData1Click(Sender: TObject);
procedure dgCellsStateChange(Sender: TObject; ACol, ARow: Integer;
const Value: TCheckBoxState);
procedure dgCellsEndUpdate(Sender: TObject);
procedure btnPlotAllClick(Sender: TObject);
procedure btnPlotNoneClick(Sender: TObject);
private
SeriesList: TObjectList;
procedure ClearList;
function ReadDataSetNames(FileName: string; const Names: TStrings;
out NCOL, NROW, NLAY: Integer): boolean;
function RowCellText(const ARow: integer): string;
procedure ActivateSeries;
procedure AdjustColRowLayer(const DataTypeIndex: integer; var Col, Row,
Layer: integer);
function OppositeFace(const Name: string): string;
procedure ChangePlots(Value: Boolean);
{ Private declarations }
public
{ Public declarations }
end;
var
frmCellFlows: TfrmCellFlows;
implementation
uses IntListUnit, frmModChartUnit, frmAboutUnit, ReadModflowArrayUnit,
frmBudgetPrecisionQueryUnit;
{$R *.DFM}
const
FlowRightFace = 'Flow Right Face';
FlowLeftFace = 'Flow Left Face';
FlowFrontFace = 'Flow Front Face';
FlowBackFace = 'Flow Back Face';
FlowLowerFace = 'Flow Lower Face';
FlowUpperFace = 'Flow Upper Face';
//type
// TText = array[0..15] of Char;
//procedure ReadArray(var TOTIM: single; var KSTP, KPER, IRESULT: longint;
// var TEXT: TModflowDesc; TextLength: LongInt)
// stdcall; external 'ReadFlow.dll';
//
//procedure OpenBudgetFile(var IRESULT, NC, NR, NL: longint; NAME: string;
// NameLength: longint);
// stdcall; external 'ReadFlow.dll';
//
//procedure CloseBudgetFile;
// stdcall; external 'ReadFlow.dll';
//
//procedure GetValue(var Layer, Row, Column: longint; var Value: single);
// stdcall; external 'ReadFlow.dll';
procedure ReadArray96(var TOTIM: single; var KSTP, KPER, IRESULT: longint;
var TEXT: TModflowDesc; TextLength: LongInt)
stdcall; external 'ReadFlow96.dll';
procedure OpenBudgetFile96(var IRESULT, NC, NR, NL: longint; NAME: string;
NameLength: longint);
stdcall; external 'ReadFlow96.dll';
procedure CloseBudgetFile96;
stdcall; external 'ReadFlow96.dll';
procedure GetValue96(var Layer, Row, Column: longint; var Value: single);
stdcall; external 'ReadFlow96.dll';
Function TfrmCellFlows.OppositeFace(const Name: string): string;
begin
result := '';
if Name = FlowRightFace then
begin
result := FlowLeftFace;
end
else if Name = FlowFrontFace then
begin
result := FlowBackFace;
end
else if Name = FlowLowerFace then
begin
result := FlowUpperFace
end;
end;
function TfrmCellFlows.ReadDataSetNames(FileName: string;
const Names: TStrings; out NCOL, NROW, NLAY: longint): boolean;
var
Dir: string;
IRESULT: longint;
AName: string;
TEXT: TModflowDesc;
KSTP, KPER: longint;
CharIndex: integer;
DataIndicies: TIntegerList;
NamePosition: integer;
DataIndex: integer;
TOTIM: single;
PERTIM, TOTIMD: TModflowDouble;
OppositeDataSetName: string;
FileStream : TFileStream;
Precision: TModflowPrecision;
DESC: TModflowDesc;
A3DArray: T3DTModflowArray;
begin
result := False;
Dir := GetCurrentDir;
try
SetCurrentDir(ExtractFileDir(FileName));
FileStream := nil;
FileName := ExtractFileName(FileName);
try
Precision := mpSingle;
if comboModelChoice.ItemIndex = 1 then
begin
FileStream := TFileStream.Create(FileName,
fmOpenRead or fmShareDenyWrite);
Precision := QueryBudgetPrecision(FileStream);
IRESULT := 0;
// OpenBudgetFile(IRESULT, NCOL, NROW, NLAY, FileName,
// Length(FileName));
end
else
begin
OpenBudgetFile96(IRESULT, NCOL, NROW, NLAY, FileName,
Length(FileName));
end;
if IRESULT = 2 then
begin
Beep;
ShowMessage('Error: Empty budget file');
Exit;
end
else if IRESULT <> 0 then
begin
Beep;
ShowMessage('Unknown Error');
Exit;
end;
DataIndex := -1;
while IResult = 0 do
begin
result := True;
TEXT := ' ';
if comboModelChoice.ItemIndex = 1 then
begin
case Precision of
mpSingle:
ReadModflowSinglePrecFluxArray(FileStream, KSTP, KPER,
PERTIM, TOTIMD, DESC, NCOL, NROW, NLAY, A3DArray, IRESULT);
mpDouble:
ReadModflowDoublePrecFluxArray(FileStream, KSTP, KPER,
PERTIM, TOTIMD, DESC, NCOL, NROW, NLAY, A3DArray, IRESULT);
else Assert(False);
end;
TEXT := DESC;
TOTIM := TOTIMD;
// ReadArray(TOTIM, KSTP, KPER, IRESULT, TEXT, Length(Text));
end
else
begin
ReadArray96(TOTIM, KSTP, KPER, IRESULT, TEXT, Length(Text));
end;
if IRESULT = 1 then
begin
Exit;
end
else if IRESULT = 2 then
begin
ShowMessage('Error, Empty budget file');
result := False;
Exit;
end
else if IRESULT <> 0 then
begin
ShowMessage('Unknown Error');
result := False;
Exit;
end
else
begin
Inc(DataIndex);
for CharIndex := 1 to 15 do
begin
if Text[CharIndex - 1] <> ' ' then
begin
Text[CharIndex] := LowerCase(Text[CharIndex])[1];
end;
end;
AName := Trim(TEXT);
NamePosition := Names.IndexOf(AName);
if NamePosition < 0 then
begin
DataIndicies := TIntegerList.Create;
Names.AddObject(AName, DataIndicies);
end
else
begin
DataIndicies := Names.Objects[NamePosition] as TIntegerList;
end;
DataIndicies.Add(DataIndex);
OppositeDataSetName := OppositeFace(AName);
if OppositeDataSetName <> '' then
begin
NamePosition := Names.IndexOf(OppositeDataSetName);
if NamePosition < 0 then
begin
DataIndicies := TIntegerList.Create;
Names.AddObject(OppositeDataSetName, DataIndicies);
end
else
begin
DataIndicies := Names.Objects[NamePosition] as TIntegerList;
end;
DataIndicies.Add(-DataIndex-1);
end;
end;
end;
finally
if comboModelChoice.ItemIndex = 1 then
begin
FileStream.Free;
// CloseBudgetFile;
end
else
begin
CloseBudgetFile96;
end;
end;
finally
SetCurrentDir(Dir);
end;
end;
procedure TfrmCellFlows.btnSelectFileClick(Sender: TObject);
var
NCOL, NROW, NLAY: longint;
begin
if OpenDialog1.Execute then
begin
lblCounts.Caption := 'Columns: 0, Rows: 0, Layers: 0';
chartFlow.Title.Text.Clear;
chartFlow.Title.Text.Add('Flow Rates: '
+ ExtractFileName(OpenDialog1.FileName));
ClearList;
dgCells.Enabled := ReadDataSetNames(OpenDialog1.FileName,
clbDataSets.Items, NCOL, NROW, NLAY);
if dgCells.Enabled then
begin
lblCounts.Caption := Format('Columns: %d, Rows: %d, Layers: %d',
[NCOL, NROW, Abs(NLAY)]);
dgCells.Columns[0].Max := NCOL;
dgCells.Columns[1].Max := NROW;
dgCells.Columns[2].Max := Abs(NLAY);
end;
seCells.Enabled := dgCells.Enabled;
btnUpdatePlot.Enabled := dgCells.Enabled;
sbFormat.Enabled := dgCells.Enabled;
btnUpdatePlotClick(nil);
end;
end;
function TfrmCellFlows.RowCellText(Const ARow: integer): string;
begin
result := ' ('
+ dgCells.Cells[0, ARow] + ','
+ dgCells.Cells[1, ARow] + ','
+ dgCells.Cells[2, ARow] + ')';
end;
procedure TfrmCellFlows.ActivateSeries;
var
DataTypeIndex, CellIndex: integer;
SList: TObjectList;
Series: TLineSeries;
begin
if (SeriesList = nil) or (SeriesList.Count <> clbDataSets.Items.Count) then
begin
Exit;
end;
for DataTypeIndex := 0 to SeriesList.Count - 1 do
begin
SList := SeriesList[DataTypeIndex] as TObjectList;
if SList.Count <> dgCells.RowCount - 1 then
begin
Exit;
end;
for CellIndex := 0 to SList.Count - 1 do
begin
Series := SList[CellIndex] as TLineSeries;
if Series.Title = clbDataSets.Items[DataTypeIndex] + RowCellText(CellIndex+1) then
begin
Series.Active := clbDataSets.Checked[DataTypeIndex] and
dgCells.Checked[3,CellIndex+1];
end;
end;
end;
end;
procedure TfrmCellFlows.AdjustColRowLayer(const DataTypeIndex: integer;
var Col, Row, Layer: integer);
var
DataSetName: string;
begin
DataSetName := clbDataSets.Items[DataTypeIndex];
if DataSetName = FlowLeftFace then
begin
Dec(Col);
end
else if DataSetName = FlowBackFace then
begin
Dec(Row);
end
else if DataSetName = FlowUpperFace then
begin
Dec(Layer);
end;
end;
procedure TfrmCellFlows.btnUpdatePlotClick(Sender: TObject);
var
IRESULT: longint;
KSTP, KPER: longint;
TEXT: TModflowDesc;
Value: single;
Layer, Row, Column: longint;
Series: TLineSeries;
FileName: string;
DataTypeIndex, CellIndex: integer;
SList: TObjectList;
IntList: TIntegerList;
Cells: array of array of integer;
NCOL, NROW, NLAY: longint;
DataSetIndex: integer;
TOTIM: single;
ColorIndex: integer;
AStyle: TSeriesPointerStyle;
FileStream : TFileStream;
Precision: TModflowPrecision;
PERTIM, TOTIMD: TModflowDouble;
A3DArray: T3DTModflowArray;
DESC: TModflowDesc;
PriorTotTime: double;
begin
SetLength(Cells, 3, dgCells.RowCount - 1);
for CellIndex := 1 to dgCells.RowCount - 1 do
begin
Cells[0, CellIndex - 1] := StrToInt(dgCells.Cells[0, CellIndex]);
Cells[1, CellIndex - 1] := StrToInt(dgCells.Cells[1, CellIndex]);
Cells[2, CellIndex - 1] := StrToInt(dgCells.Cells[2, CellIndex]);
end;
SeriesList.Clear;
ColorIndex := -1;
AStyle := High(TSeriesPointerStyle);
for DataTypeIndex := 0 to clbDataSets.Items.Count - 1 do
begin
SList := TObjectList.Create;
SeriesList.Add(SList);
for CellIndex := 1 to dgCells.RowCount - 1 do
begin
Series := TLineSeries.Create(self);
Series.XValues.Order := loNone;
SList.Add(Series);
Series.ParentChart := chartFlow;
Series.Pointer.HorizSize := 4;
Series.Pointer.VertSize := 4;
Series.Pointer.Visible := True;
Series.Title := clbDataSets.Items[DataTypeIndex] + RowCellText(CellIndex);
Series.Active := clbDataSets.Checked[DataTypeIndex] and
dgCells.Checked[3, CellIndex];
Inc(ColorIndex);
if ColorIndex >= Length(ColorPalette) then
begin
ColorIndex := 0;
end;
Series.SeriesColor := ColorPalette[ColorIndex];
if AStyle = High(TSeriesPointerStyle) then
begin
AStyle := Low(TSeriesPointerStyle)
end
else
begin
Inc(AStyle);
end;
while AStyle in [psSmallDot, psNothing] do
begin
Inc(AStyle);
end;
Series.Pointer.Style := AStyle;
end;
end;
FileStream := nil;
FileName := ExtractFileName(OpenDialog1.FileName);
try
Precision := mpSingle;
if comboModelChoice.ItemIndex = 1 then
begin
FileStream := TFileStream.Create(FileName,
fmOpenRead or fmShareDenyWrite);
Precision := QueryBudgetPrecision(FileStream);
IRESULT := 0;
// OpenBudgetFile(IRESULT, NCOL, NROW, NLAY, FileName,
// Length(FileName));
end
else
begin
OpenBudgetFile96(IRESULT, NCOL, NROW, NLAY, FileName,
Length(FileName));
end;
if IResult <> 0 then
Exit;
PriorTotTime := -1;
DataSetIndex := -1;
while IResult = 0 do
begin
TEXT := ' ';
if comboModelChoice.ItemIndex = 1 then
begin
case Precision of
mpSingle:
ReadModflowSinglePrecFluxArray(FileStream, KSTP, KPER,
PERTIM, TOTIMD, DESC, NCOL, NROW, NLAY, A3DArray, IRESULT);
mpDouble:
ReadModflowDoublePrecFluxArray(FileStream, KSTP, KPER,
PERTIM, TOTIMD, DESC, NCOL, NROW, NLAY, A3DArray, IRESULT);
else Assert(False);
end;
TEXT := DESC;
TOTIM := TOTIMD;
NLAY := Abs(NLAY);
// ReadArray(TOTIM, KSTP, KPER, IRESULT, TEXT, Length(Text));
end
else
begin
ReadArray96(TOTIM, KSTP, KPER, IRESULT, TEXT, Length(Text));
end;
if TOTIM < 0 then
begin
TOTIM := PriorTotTime;
end
else
begin
PriorTotTime := TOTIM;
end;
if IRESULT = 1 then
begin
Exit;
end
else if IRESULT = 2 then
begin
ShowMessage('Error, Empty budget file');
Exit;
end
else if IRESULT <> 0 then
begin
ShowMessage('Unknown Error');
Exit;
end
else
begin
Inc(DataSetIndex);
for DataTypeIndex := 0 to clbDataSets.Items.Count - 1 do
begin
IntList := clbDataSets.Items.Objects[DataTypeIndex] as TIntegerList;
if IntList.IndexOf(DataSetIndex) >= 0 then
begin
SList := SeriesList[DataTypeIndex] as TObjectList;
for CellIndex := 1 to dgCells.RowCount - 1 do
begin
Series := SList[CellIndex - 1] as TLineSeries;
Column := Cells[0, CellIndex - 1];
Row := Cells[1, CellIndex - 1];
Layer := Cells[2, CellIndex - 1];
if comboModelChoice.ItemIndex = 1 then
begin
Value := A3DArray[Abs(Layer)-1,Row-1,Column-1];
// GetValue(Layer, Row, Column, Value);
end
else
begin
GetValue96(Layer, Row, Column, Value);
end;
if TOTIM >= 0 then
begin
Series.AddXY(TOTIM, Value);
chartFlow.BottomAxis.Title.Caption := 'Time';
end
else
begin
Series.AddXY(Series.Count + 1, Value);
chartFlow.BottomAxis.Title.Caption := 'Stored Time Step';
end
end;
end;
if IntList.IndexOf(-DataSetIndex-1) >= 0 then
begin
SList := SeriesList[DataTypeIndex] as TObjectList;
for CellIndex := 1 to dgCells.RowCount - 1 do
begin
Series := SList[CellIndex - 1] as TLineSeries;
Column := Cells[0, CellIndex - 1];
Row := Cells[1, CellIndex - 1];
Layer := Cells[2, CellIndex - 1];
AdjustColRowLayer(DataTypeIndex, Column, Row, Layer);
if (Column >= 1) and (Row >= 1) and (Layer >= 1) then
begin
if comboModelChoice.ItemIndex = 1 then
begin
Value := A3DArray[Layer-1,Row-1,Column-1];
// GetValue(Layer, Row, Column, Value);
end
else
begin
GetValue96(Layer, Row, Column, Value);
end;
// Reverse sign of Value because flow is in opposite direction.
Value := -Value;
end
else
begin
Value := 0;
end;
if TOTIM >= 0 then
begin
Series.AddXY(TOTIM, Value);
chartFlow.BottomAxis.Title.Caption := 'Time';
end
else
begin
Series.AddXY(Series.Count + 1, Value);
chartFlow.BottomAxis.Title.Caption := 'Stored Time Step';
end
end;
end;
end;
end;
end;
finally
if comboModelChoice.ItemIndex = 1 then
begin
FileStream.Free;
// CloseBudgetFile;
end
else
begin
CloseBudgetFile96;
end;
end;
end;
procedure TfrmCellFlows.ClearList;
var
NameIndex: integer;
begin
for NameIndex := 0 to clbDataSets.Items.Count - 1 do
begin
clbDataSets.Items.Objects[NameIndex].Free;
end;
clbDataSets.Items.Clear;
SeriesList.Clear;
end;
procedure TfrmCellFlows.FormDestroy(Sender: TObject);
begin
ClearList;
SeriesList.Free;
end;
procedure TfrmCellFlows.FormCreate(Sender: TObject);
begin
dgCells.Cells[0, 0] := 'Col';
dgCells.Cells[1, 0] := 'Row';
dgCells.Cells[2, 0] := 'Lay';
dgCells.Cells[3, 0] := 'Plot';
dgCells.Cells[0, 1] := '1';
dgCells.Cells[1, 1] := '1';
dgCells.Cells[2, 1] := '1';
dgCells.Checked[3, 1] := True;
SeriesList := TObjectList.Create;
comboModelChoice.ItemIndex := 1;
Constraints.MinWidth := Width;
end;
procedure TfrmCellFlows.seCellsChange(Sender: TObject);
var
FirstRow: integer;
RowIndex: integer;
begin
FirstRow := dgCells.RowCount;
dgCells.RowCount := seCells.Value + 1;
for RowIndex := FirstRow to dgCells.RowCount - 1 do
begin
dgCells.Cells[0, RowIndex] := dgCells.Cells[0, RowIndex - 1];
dgCells.Cells[1, RowIndex] := dgCells.Cells[1, RowIndex - 1];
dgCells.Cells[2, RowIndex] := dgCells.Cells[2, RowIndex - 1];
dgCells.Checked[3, RowIndex] := dgCells.Checked[3, RowIndex - 1];
end;
end;
procedure TfrmCellFlows.FormatChart1Click(Sender: TObject);
begin
mHHelp.ChmFile := ChartHelpFileName;
try
ChartEditor1.Execute;
finally
mHHelp.ChmFile := HelpFileName;
end;
end;
procedure TfrmCellFlows.Exit1Click(Sender: TObject);
begin
inherited
Close;
end;
procedure TfrmCellFlows.FormShow(Sender: TObject);
begin
MainMenu1.Merge(frmModChart.mainMenuFormChoice);
end;
procedure TfrmCellFlows.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
if Visible then
begin
frmModChart.Close
end;
end;
procedure TfrmCellFlows.clbDataSetsClickCheck(Sender: TObject);
begin
inherited;
ActivateSeries;
end;
procedure TfrmCellFlows.Help2Click(Sender: TObject);
begin
inherited;
Application.HelpContext(HelpContext);
end;
procedure TfrmCellFlows.About1Click(Sender: TObject);
begin
inherited;
// show the "About" form
frmAbout.ShowModal;
end;
procedure TfrmCellFlows.ExportData1Click(Sender: TObject);
var
GroupIndex: integer;
Group: TList;
SeriesIndex: integer;
Series : TLineSeries;
ExportFile: TStringList;
TimeIndex: integer;
begin
inherited;
if sdExportData.Execute then
begin
ExportFile := TStringList.Create;
try
for GroupIndex := 0 to SeriesList.Count-1 do
begin
Group := SeriesList[GroupIndex] as TList;
for SeriesIndex := 0 to Group.Count -1 do
begin
Series := Group[SeriesIndex];
if Series.Visible then
begin
ExportFile.Add(chartFlow.BottomAxis.Title.Caption + #9
+ Series.Title + ' (Col, Row, Lay)');
for TimeIndex := 0 to Series.XValues.Count -1 do
begin
ExportFile.Add(FloatToStr(Series.XValues[TimeIndex]) + #9
+ FloatToStr(Series.YValues[TimeIndex]));
end;
ExportFile.Add('');
end;
end;
end;
ExportFile.SaveToFile(sdExportData.FileName);
finally
ExportFile.Free;
end;
end;
end;
procedure TfrmCellFlows.dgCellsStateChange(Sender: TObject; ACol,
ARow: Integer; const Value: TCheckBoxState);
begin
inherited;
ActivateSeries;
end;
procedure TfrmCellFlows.dgCellsEndUpdate(Sender: TObject);
begin
inherited;
seCells.Value := dgCells.RowCount -1;
end;
procedure TfrmCellFlows.ChangePlots(Value: Boolean);
var
RowIndex: integer;
begin
for RowIndex := 0 to dgCells.RowCount -1 do
begin
dgCells.Checked[3,RowIndex] := Value;
end;
end;
procedure TfrmCellFlows.btnPlotAllClick(Sender: TObject);
begin
inherited;
ChangePlots(True);
ActivateSeries;
end;
procedure TfrmCellFlows.btnPlotNoneClick(Sender: TObject);
begin
inherited;
ChangePlots(False);
end;
end.
|
program testarray19(output);
{array as byval parameter to procedure}
type myarr = array [1..5] of integer;
var a: myarr; i:integer;
procedure initarr(var z:myarr);
var i:integer;
begin
i := 1;
while i <= 5 do begin
z[i] := i * i;
i := i + 1;
end;
end;
procedure printarray(q:myarr);
var i:integer;
begin
i := 1;
while i <= 5 do begin
writeln(q[i]);
i := i + 1;
end;
end;
begin
initarr(a);
printarray(a);
end.
|
unit TextStream;
interface
Uses
Classes,
SysUtils;
Type
TVector = Record X, Y , Z : Single; end;
TRGB = Record R, G, B : Byte; end;
TRGBA = Record R, G , B , A : Byte; end;
TColor = Record R, G , B , A : Single; end;
TCoord = Record U , V : Single; End;
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{---- TTextStream -------------------------------------------------------------}
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
TSetOfChar = set of Char;
TTextStream = class(TStringList)
private
fSeparators: TSetOfChar;
fOpenBracket: String;
fCloseBracket: String;
fText: String;
fPosition: Integer;
fBrackets: Integer;
fLevel: integer;
fSpace : String;
public
Constructor Create;
Procedure LoadFromFile(Const FileName : String);Override;
function GetNextToken: String;
Function ExtractFromQuote: String;
Procedure AddString(AMessage: String; AString: String);
Procedure AddInteger(AMessage: String; AInteger: Integer);
Procedure AddSingle(AMessage: String; ASingle: Single);
Procedure AddBoolean(AMessage: String; ABoolean: Boolean);
Procedure AddVector(AMessage: String; AVector: TVector);
Procedure AddRGB(AMessage: String; ARGB: TRGB);
Procedure AddRGBA(AMessage: String; ARGBA: TRGBA);
Procedure AddColor(AMessage: String; AColor: TColor);
Procedure AddCoord(AMessage: String; ACoord: TCoord);
Function GetString(AMessage: String) : String;
Function GetInteger(AMessage: String) : Integer;
Function GetSingle(AMessage: String) : Single;
Function GetBoolean(AMessage: String) : Boolean;
Function GetVector(AMessage: String) : TVector;
Function GetCoord(AMessage: String) : TCoord;
Function GetColor(AMessage: String) : TColor;
Function GetRGB(AMessage: String): TRGB;
Function GetRGBA(AMessage: String): TRGBA;
Procedure LevelUp;
Procedure LevelDown;
property BracketLevel: Integer read FBrackets;
property Separators: TSetOfChar read FSeparators write FSeparators;
property OpenBracket: String read FOpenBracket write FOpenBracket;
property CloseBracket: String read FCloseBracket write FCloseBracket;
Property Position : Integer Read fPosition;
end;
function StripQuotes(const s: String): String;
implementation
function StripQuotes(const s: String): String;
begin
Result := s;
if (Result[1] = '''') or (Result[1] = '"') then
Delete(Result, 1, 1);
if (Result[Length(Result)] = '''') or (Result[Length(Result)] = '"') then
Delete(Result, Length(Result), 1);
end;
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
{---- TTextStream ------------------------------------------------------------}
{++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}
constructor TTextStream.Create;
var
sl: TStringList;
begin
inherited Create;
FSeparators := [
#0, // Null character (is this ever used in Pascal strings?)
#9, // Tab
#10, // LF
#13, // CR
' ' // Space
];
FOpenBracket := '{';
FCloseBracket := '}';
fLevel := 0;
end;
Procedure TTextStream.LoadFromFile(Const FileName : String);
Begin
inherited LoadFromFile(FileName);
FText := Text;
FPosition := 1;
FBrackets := 0;
End;
function TTextStream.GetNextToken: String;
var
res: String;
n: Integer;
begin
n := Length(FText);
while (FPosition <= n) and (FText[FPosition] in FSeparators) do INC(FPosition);
res := '';
while (FPosition <= n) and (not (FText[FPosition] in FSeparators)) do
begin
res := res + FText[FPosition];
INC(FPosition);
end;
if res = FOpenBracket then INC(FBrackets)
else if res = FCloseBracket then DEC(FBrackets);
if FBrackets < 0 then raise Exception.Create('Brackets do not match!');
Result := res;
end;
Function TTextStream.ExtractFromQuote : String;
Var
Tok : String;
Begin
tok := GetNextToken;
Result := tok;
while tok[Length(tok)] <> '"' do
begin
tok := GetNextToken;
Result := Result + ' ' + tok;
end;
Result := StripQuotes(Result);
end;
Procedure TTextStream.AddString(AMessage: String; AString: String);
Begin
Add(fSpace + AMessage + ' "' + AString + '"');
end;
Procedure TTextStream.AddInteger(AMessage: String; AInteger: Integer);
Var
Tmp: String;
begin
Tmp :=AMessage + ' ' + IntToStr(AInteger);
Add(fSpace + Tmp);
end;
Procedure TTextStream.AddSingle(AMessage: String; ASingle: Single);
Var
Tmp: String;
begin
Tmp :=AMessage + ' ' + FloatToStr(ASingle);
Add(fSpace + Tmp);
end;
Procedure TTextStream.AddBoolean(AMessage: String; ABoolean: Boolean);
Var
Tmp: String;
begin
if ABoolean then Tmp := AMessage + ' TRUE' else Tmp := AMessage + ' FALSE';
Add(fSpace + Tmp);
end;
Procedure TTextStream.AddVector(AMessage: String; AVector: TVector);
Var
Tmp: String;
begin
Tmp :=AMessage + ' ' + FloatToStr(AVector.x)+ ' ' + FloatToStr(AVector.Y)+ ' ' + FloatToStr(AVector.Z);
Add(fSpace + Tmp);
end;
Procedure TTextStream.AddCoord(AMessage: String; ACoord: TCoord);
Var
Tmp: String;
begin
Tmp :=AMessage + ' ' + FloatToStr(ACoord.U)+ ' ' + FloatToStr(ACoord.V);
Add(fSpace + Tmp);
end;
Procedure TTextStream.AddRGB(AMessage: String; ARGB: TRGB);
Var
Tmp: String;
begin
Tmp :=AMessage + ' ' + IntToStr(ARGB.R)+ ' ' + IntToStr(ARGB.G)+ ' ' + IntToStr(ARGB.B) ;
Add(fSpace + Tmp);
end;
Procedure TTextStream.AddRGBA(AMessage: String; ARGBA: TRGBA);
Var
Tmp: String;
begin
Tmp :=AMessage + ' ' + IntToStr(ARGBA.R)+ ' ' + IntToStr(ARGBA.G)+ ' ' + IntToStr(ARGBA.B) + ' ' + IntToStr(ARGBA.A);
Add(fSpace + Tmp);
end;
Procedure TTextStream.AddColor(AMessage: String; AColor: TColor);
Var
Tmp: String;
begin
Tmp :=AMessage + ' ' + FloatToStr(AColor.R)+ ' ' + FloatToStr(AColor.G)+ ' ' + FloatToStr(AColor.B) + ' ' + FloatToStr(AColor.A);
Add(fSpace + Tmp);
end;
{------------------------------------------------------------------------------}
Function TTextStream.GetString(AMessage: String) : String;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then Result := ExtractFromQuote;
end;
Function TTextStream.GetInteger(AMessage: String) : Integer;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then Result := StrToInt(GetNextToken)
else raise Exception.Create(AMEssage + ' Not Found !');
end;
Function TTextStream.GetSingle(AMessage: String) : Single;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then Result := StrToFloat(GetNextToken)
else raise Exception.Create(AMEssage + ' Not Found !');
end;
Function TTextStream.GetBoolean(AMessage: String) : Boolean;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then
begin
Tok := GetNextToken;
if SameText(Tok, 'TRUE') then REsult := True Else Result := False;
end else raise Exception.Create(AMEssage + ' Not Found !');
end;
Function TTextStream.GetVector(AMessage: String) : TVector;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then
begin
REsult.X := StrToFloat(GetNextToken);
REsult.Y := StrToFloat(GetNextToken);
REsult.Z := StrToFloat(GetNextToken);
end else raise Exception.Create(AMEssage + ' Not Found !');
end;
Function TTextStream.GetRGB(AMessage: String): TRGB;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then
begin
Result.R := StrToInt(GetNextToken);
Result.G := StrToInt(GetNextToken);
Result.B := StrToInt(GetNextToken);
end else raise Exception.Create(AMEssage + ' Not Found !');
end;
Function TTextStream.GetRGBA(AMessage: String): TRGBA;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then
begin
Result.R := StrToInt(GetNextToken);
Result.G := StrToInt(GetNextToken);
Result.B := StrToInt(GetNextToken);
Result.A := StrToInt(GetNextToken);
end else raise Exception.Create(AMEssage + ' Not Found !');
end;
Function TTextStream.GetColor(AMessage: String) : TColor;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then
begin
Result.R := StrToFloat(GetNextToken);
Result.G := StrToFloat(GetNextToken);
Result.B := StrToFloat(GetNextToken);
Result.A := StrToFloat(GetNextToken);
end else raise Exception.Create(AMEssage + ' Not Found !');
end;
Function TTextStream.GetCoord(AMessage: String) : TCoord;
Var
Tok : String;
Begin
Tok := GetNextToken;
if SameText(Tok, AMessage) then
begin
Result.U := StrToFloat(GetNextToken);
Result.V := StrToFloat(GetNextToken);
end else raise Exception.Create(AMEssage + ' Not Found !');
end;
Procedure TTextStream.LevelUp;
Var
I:integer;
begin
inc(flevel);
fSpace := '';
For I := 1 to fLevel do fSpace := fSpace + ' ';
end;
Procedure TTextStream.LevelDown;
Var
I: integer;
begin
Dec(fLevel);
if fLevel<0 then Exception.Create('Level Too Low');
fSpace := '';
For I := 1 to fLevel do fSpace := fSpace + ' ';
end;
end.
|
(*
@abstract(Contient les classes pour l'application de filtres de déformations )
-------------------------------------------------------------------------------------------------------------
@created(2017-08-22)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(22/08/2017 : Creation)
@item(18/06/2019 : Mise à jour)
)
-------------------------------------------------------------------------------------------------------------
@bold(Notes :)@br
-------------------------------------------------------------------------------------------------------------
@bold(Dépendances) : BZClasses, BZMath, BZVectorMath, BZVectorMathEx, BZColors, BZGraphic, BZBitmapFilterClasses
-------------------------------------------------------------------------------------------------------------
@bold(Credits :)
@unorderedList(
@item(FPC/Lazarus)
)
-------------------------------------------------------------------------------------------------------------
@bold(Licence) : MPL / LGPL
------------------------------------------------------------------------------------------------------------- *)
unit BZBitmapDeformationFilters;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Math,
BZClasses, BZMath, BZVectorMath, BZVectorMathEx, BZColors, BZGraphic, BZBitmapFilterClasses;
type
{ TBZBitmapTwirlFilter }
TBZBitmapTwirlFilter = Class(TBZCustomBitmapFilterTransformation)
protected
FCenterX : Integer;
FCenterY : Integer;
FRadius : Integer;
FRadSqr : Integer;
FAngle : Integer;
procedure PrepareTransformation; override;
function ComputeTransformation(x,y : Integer) : TBZFloatPoint; override;
public
Constructor Create(Const AOwner: TBZBaseBitmap; Const DirectWrite :Boolean = False); override;
property CenterX : Integer read FCenterX write FCenterX;
property CenterY : Integer read FCenterY write FCenterY;
property Radius : Integer read FRadius write FRadius;
property Angle : Integer read FAngle write FAngle;
end;
{ TBZBitmapPinchFilter }
TBZBitmapPinchFilter = Class(TBZCustomBitmapFilterTransformation)
protected
FCenterX : Integer;
FCenterY : Integer;
FRadius : Integer;
FRadSqr : Integer;
FAngle : Integer;
FAmount : Single;
procedure PrepareTransformation; override;
function ComputeTransformation(x,y : Integer) : TBZFloatPoint; override;
public
Constructor Create(Const AOwner: TBZBaseBitmap; Const DirectWrite :Boolean = False); override;
property CenterX : Integer read FCenterX write FCenterX;
property CenterY : Integer read FCenterY write FCenterY;
property Radius : Integer read FRadius write FRadius;
property Angle : Integer read FAngle write FAngle;
property Amount : Single read FAmount write FAmount;
end;
{ TBZBitmapFishEyeFilter }
TBZBitmapFishEyeFilter = Class(TBZCustomBitmapFilterTransformation)
protected
FAmount : Single;
FRadiusMax : Single;
FCenterX : Integer;
FCenterY : Integer;
FRadius : Integer;
procedure PrepareTransformation; override;
function ComputeTransformation(x,y : Integer) : TBZFloatPoint; override;
public
Constructor Create(Const AOwner: TBZBaseBitmap; Const DirectWrite :Boolean = False); override;
property CenterX : Integer read FCenterX write FCenterX;
property CenterY : Integer read FCenterY write FCenterY;
property Radius : Integer read FRadius write FRadius;
property Amount : Single read FAmount write FAmount;
end;
{ TBZBitmapWaveFilter }
TBZWaveDistorsionMode = (wdmSine, wdmSquare, wdmSawTooth, wdmTriangle, wdmRandom);
TBZBitmapWaveDistorsionFilter = Class(TBZCustomBitmapFilterTransformation)
private
protected
FAmplitudeX : Single;
FAmplitudeY : Single;
FWaveLengthX : Single;
FWaveLengthY : Single;
FMode : TBZWaveDistorsionMode;
procedure PrepareTransformation; override;
function ComputeTransformation(x,y : Integer) : TBZFloatPoint; override;
public
Constructor Create(Const AOwner: TBZBaseBitmap; Const DirectWrite :Boolean = False); override;
property Mode : TBZWaveDistorsionMode read FMode write FMode;
property AmplitudeX : Single read FAmplitudeX write FAmplitudeX;
property AmplitudeY : Single read FAmplitudeY write FAmplitudeY;
property WaveLengthX : Single read FWaveLengthX write FWaveLengthX;
property WaveLengthY : Single read FWaveLengthY write FWaveLengthY;
end;
{ TBZBitmapWaveRippleFilter }
TBZBitmapWaterRippleFilter = Class(TBZCustomBitmapFilterTransformation)
private
protected
FCenterX : Integer;
FCenterY : Integer;
FRadius : Integer;
FAmplitude : Single;
FWaveLength : Single;
FPhase : Single;
FRadSqr : Single;
procedure PrepareTransformation; override;
function ComputeTransformation(x,y : Integer) : TBZFloatPoint; override;
public
Constructor Create(Const AOwner: TBZBaseBitmap; Const DirectWrite :Boolean = False); override;
property CenterX : Integer read FCenterX write FCenterX;
property CenterY : Integer read FCenterY write FCenterY;
property Radius : Integer read FRadius write FRadius;
property Amplitude : Single read FAmplitude write FAmplitude;
property WaveLength : Single read FWaveLength write FWaveLength;
property Phase : Single read FPhase write FPhase;
end;
TBZBitmapDiffusionFilter = Class(TBZCustomBitmapFilterTransformation)
protected
FCosLUT, FSinLUT : Array[0..255] of Single;
FForceHorizontal : Single;
FForceVertical : Single;
FMinDistance : Single;
FMaxDistance : Single;
procedure PrepareTransformation; override;
function ComputeTransformation(x,y : Integer) : TBZFloatPoint; override;
public
Constructor Create(Const AOwner: TBZBaseBitmap; Const DirectWrite :Boolean = False); override;
property Horizontal : Single read FForceHorizontal write FForceHorizontal;
property Vertical : Single read FForceVertical write FForceVertical;
property MinDistance : Single read FMinDistance write FMinDistance;
property MaxDistance : Single read FMaxDistance write FMaxDistance;
end;
TBZBitmapAffineTransformationFilter = Class(TBZCustomBitmapFilterTransformation)
protected
FMatrix : TBZAffineMatrix;
procedure PrepareTransformation; override;
function ComputeTransformation(x,y : Integer) : TBZFloatPoint; override;
public
Constructor Create(Const AOwner: TBZBaseBitmap; Const DirectWrite :Boolean = False); override;
property Matrix : TBZAffineMatrix read FMatrix write FMatrix;
end;
{ TBZBitmapPolarTransformationFilter }
TBZPolarTransformationMode = (ptmToPolar, ptmToCartesian);
TBZBitmapPolarTransformationFilter = Class(TBZCustomBitmapFilterTransformation)
private
protected
FMode : TBZPolarTransformationMode;
FCenterX : Integer;
FCenterY : Integer;
//FRadius : Integer;
FMin, FMax : Integer;
FX, FY,
FSqrY,
FAngleFactor,
FCurrentRadius : Single;
FCenterMin : Single;
procedure PrepareTransformation; override;
procedure DoOnNextLine; override;
function ComputeTransformation(x,y : Integer) : TBZFloatPoint; override;
public
Constructor Create(Const AOwner: TBZBaseBitmap; Const DirectWrite :Boolean = False); override;
property CenterX : Integer read FCenterX write FCenterX;
property CenterY : Integer read FCenterY write FCenterY;
property Mode : TBZPolarTransformationMode read FMode write FMode;
//property Radius : Integer read FRadius write FRadius;
end;
implementation
uses BZUtils;
{ TBZBitmapPolarTransformationFilter }
Constructor TBZBitmapPolarTransformationFilter.Create(Const AOwner : TBZBaseBitmap; Const DirectWrite : Boolean);
begin
inherited Create(AOwner, False);
//FRadius := 100;
FCenterX := OwnerBitmap.CenterX;
FCenterY := OwnerBitmap.CenterY;
FMode := ptmToPolar;
FEdgeAction := peaClamp;
FScannerDescription := 'Transformation polaire';
end;
procedure TBZBitmapPolarTransformationFilter.PrepareTransformation;
begin
inherited PrepareTransformation;
if OwnerBitmap.Width >= OwnerBitmap.Height then
begin
FMin := OwnerBitmap.Height;
FMax := OwnerBitmap.Width;
end
else
begin
FMin := OwnerBitmap.Width;
FMax := OwnerBitmap.MaxHeight;
end;
if FMode = ptmToCartesian then
begin
FAngleFactor := 360 / FMax;
FCurrentRadius := 0;
end
else
begin
FCurrentRadius := 0;
FAngleFactor := FMax / 360;
end;
FCenterMin := Min(FCenterX, FCenterY); // * 0.5;
end;
procedure TBZBitmapPolarTransformationFilter.DoOnNextLine;
begin
if FMode = ptmToPolar then
begin
FY := FCenterY - FCurrentY;
FSqrY := FY * FY;
end
else
begin
FCurrentRadius := FCenterMin * (FCurrentY / FMin);
end;
end;
function TBZBitmapPolarTransformationFilter.ComputeTransformation(x, y : Integer) : TBZFloatPoint;
Var
CosAngle, SinAngle, Theta, r, a, Angle : Single;
cx : Single;
begin
if FMode = ptmToCartesian then
begin
FX := X - FCenterX ;
Theta := DegToRadian(FX * FAngleFactor);
CosAngle := System.Cos(Theta);
SinAngle := System.Sin(Theta);
Result.X := FCenterX + (-FCurrentRadius * SinAngle);
Result.Y := FCenterY + (FCurrentRadius * CosAngle);
end
else
begin
cx := FCenterX - x;
r := System.Sqrt(cx*cx + FSqrY);
a := Math.ArcTan2(cx, -FY) - cPI;
// On ajuste pour que l'angle soit dans l'interval [0,360] et non pas dans l'interval [-180,180]
if a < 0 then a := a + c2PI;
Angle := RadianToDeg(a);
//if Angle<0 then Angle := Angle + 360;
Result.X := (Angle * FAngleFactor);
Result.Y := OwnerBitmap.Height * (r / FCenterMin);
end;
end;
{%region=====[ TBZBitmapTwirlFilter ]============================================}
Constructor TBZBitmapTwirlFilter.Create(Const AOwner : TBZBaseBitmap; Const DirectWrite : Boolean);
begin
inherited Create(AOwner, DirectWrite);
FRadius := 100;
FCenterX := OwnerBitmap.CenterX;
FCenterY := OwnerBitmap.CenterY;
FAngle := 0;
FEdgeAction := peaClamp;
FScannerDescription := 'Tournoyer';
end;
procedure TBZBitmapTwirlFilter.PrepareTransformation;
begin
inherited PrepareTransformation;
FRadSqr := FRadius * FRadius;
end;
function TBZBitmapTwirlFilter.ComputeTransformation(x, y : Integer) : TBZFloatPoint;
Var
a, Dist : Single;
{$CODEALIGN VARMIN=16}
p1, p2 : TBZFloatPoint;
{$CODEALIGN VARMIN=4}
begin
p1.Create(x,y);
p2.Create(FCenterX, FCenterY);
p1 := p1 - p2;
//p2 := p1;
Dist := p1.LengthSquare;
if (Dist > FRadSqr) then
begin
Result.X := x;
Result.Y := y;
end
else
begin
Dist := Sqrt(Dist);
a := ArcTan2(p1.Y, p1.x) + DegToRadian(FAngle) * (FRadius - Dist) / FRadius;
Result.X := FCenterX + Dist * Cos(a);
Result.Y := FCenterY + Dist * Sin(a);
end;
end;
{%endregion%}
{%region=====[ TBZBitmapPinchFilter ]============================================}
Constructor TBZBitmapPinchFilter.Create(Const AOwner : TBZBaseBitmap; Const DirectWrite : Boolean);
begin
inherited Create(AOwner, DirectWrite);
FRadius := 100;
FCenterX := OwnerBitmap.CenterX;
FCenterY := OwnerBitmap.CenterY;
FAngle := 0;
FAmount := 0.8;
FEdgeAction := peaClamp;
FFilterGetPixel := psmMean; //psmBicubic; // psmBilinear;
FScannerDescription := 'Pincer et tournoyer';
end;
procedure TBZBitmapPinchFilter.PrepareTransformation;
begin
inherited PrepareTransformation;
FRadSqr := FRadius * FRadius;
end;
function TBZBitmapPinchFilter.ComputeTransformation(x, y : Integer) : TBZFloatPoint;
Var
t, r , a, s, c, Dist : Single;
{$CODEALIGN VARMIN=16}
p1, p2 : TBZFloatPoint;
{$CODEALIGN VARMIN=4}
begin
p1.Create(x,y);
p2.Create(FCenterX, FCenterY);
p1 := p1 - p2;
//p2 := p1;
Dist := p1.LengthSquare;
if (Dist > FRadSqr) then // or (Dist = 0) then
begin
Result.X := x;
Result.Y := y;
end
else
begin
Dist := System.Sqrt(Dist / FRadSqr);
t := Math.power( System.sin( cPiDiv2 * dist ), -amount);
p2.Create(t,t);
p1 := p1 * p2;
r := 1.0 - dist;
a := DegToRadian(FAngle) * r * r;
s := System.sin(a);
c := System.cos(a);
Result.X := FCenterX + c * p1.x - s * p1.y;
Result.Y := FCenterY + s * p1.x + c * p1.y;
end;
end;
{%endregion%}
{%region=====[ TBZBitmapFishEyeFilter ]==========================================}
Constructor TBZBitmapFishEyeFilter.Create(Const AOwner : TBZBaseBitmap; Const DirectWrite : Boolean);
begin
inherited Create(AOwner, DirectWrite);
FRadius:= 0;
FAmount := 1;
FEdgeAction := peaClamp;
FScannerDescription := 'Distortion de lentille';
end;
procedure TBZBitmapFishEyeFilter.PrepareTransformation;
begin
inherited PrepareTransformation;
FRadiusMax := FRadius * FAmount; //OwnerBitmap.Width * FAmount;
end;
function TBZBitmapFishEyeFilter.ComputeTransformation(x, y : Integer) : TBZFloatPoint;
Var
Dist, Dist2 : Single;
{$CODEALIGN VARMIN=16}
p1, p2, pDist1, pDist2 : TBZFloatPoint;
{$CODEALIGN VARMIN=4}
begin
p1.Create(x,y);
p2.Create(FCenterX, FCenterY);
p1 := p1 - p2;
//p2 := p1;
Dist := p1.Length;
if (Dist = 0) then
begin
Result.X := FCenterX;
Result.Y := FCenterY; //OwnerBitmap.CenterY;
end
else
begin
//= 1.0 + ((0.5 - dist) / 0.5) * scale
Dist2 := FRadiusMax / 2 * (1 / (1 - Dist / FRadiusMax) - 1);
//r' = r + (1 - sqrt(1 -r^2)) / 2
pDist2.Create(Dist2, Dist2);
pDist1.Create(Dist, Dist);
Result := (((p1 * pDist2) / pDist1) + p2);
//Result.X := p1.x * Dist2 / Dist + xmid;
//Result.Y := p1.y * Dist2 / Dist + ymid;
end;
end;
{%endregion%}
{%region=====[ TBZBitmapWaveFilter ]=============================================}
Constructor TBZBitmapWaveDistorsionFilter.Create(Const AOwner : TBZBaseBitmap; Const DirectWrite : Boolean);
begin
inherited Create(AOwner, DirectWrite);
FEdgeAction := peaClamp;
FAmplitudeX := 5.0;
FWaveLengthX := 16;
FAmplitudeY := 0.0;
FWaveLengthY := 16;
FMode := wdmSine; //wdmRandom; //wdmSquare; //wdmTriangle; //wdmSawTooth;
FScannerDescription := 'Ondulation';
end;
procedure TBZBitmapWaveDistorsionFilter.PrepareTransformation;
begin
inherited PrepareTransformation;
Randomize;
end;
function TBZBitmapWaveDistorsionFilter.ComputeTransformation(x, y : Integer) : TBZFloatPoint;
var
nx, ny, fx, fy, rx, ry : Single;
begin
nx := y / FWaveLengthX;
ny := x / FWaveLengthY;
Case FMode of
wdmSine :
begin
fx := Sin(nx);
fy := Sin(ny);
end;
wdmSquare :
begin
fx := Sign(Sin(nx));
fy := Sign(Sin(ny));
end;
wdmSawTooth :
begin
fx := modulus(nx,1.0);
fy := modulus(ny,1.0);
end;
wdmTriangle :
begin
rx := modulus(nx,1.0);
ry := modulus(ny,1.0);
if rx >= 0.5 then rx := 1.0 - rx;
if ry >= 0.5 then ry := 1.0 - ry;
fx := rx + rx;
fy := ry + ry;
end;
wdmRandom :
begin
fx := (Random * (nx + nx)) - nx; //fx.RandomRange(-1.0, 1.0);
fy := (Random * (ny + ny)) - ny;
end;
//wdmNoise:
//begin
// fx := NoiseGenerator.Noise1D(fx);
// fy := NoiseGenerator.Noise1D(fy);
//end;
end;
Result.x := x + FAmplitudeX * fx;
Result.y := y + FAmplitudeY * fy;
end;
{%endregion%}
{%region=====[ TBZBitmapWaveRippleFilter ]=======================================}
Constructor TBZBitmapWaterRippleFilter.Create(Const AOwner : TBZBaseBitmap; Const DirectWrite : Boolean);
begin
inherited Create(AOwner, DirectWrite);
FRadius := 100;
FCenterX := OwnerBitmap.CenterX;
FCenterY := OwnerBitmap.CenterY;
FAmplitude := 5.0;
FWaveLength := 16;
FPhase := 1.0;
FScannerDescription := 'Ondulation d''eau';
end;
procedure TBZBitmapWaterRippleFilter.PrepareTransformation;
begin
inherited PrepareTransformation;
FRadSqr := FRadius * FRadius;
end;
function TBZBitmapWaterRippleFilter.ComputeTransformation(x, y : Integer) : TBZFloatPoint;
Var
a, Dist : Single;
{$CODEALIGN VARMIN=16}
p1, p2 : TBZFloatPoint;
{$CODEALIGN VARMIN=4}
begin
p1.Create(x,y);
p2.Create(FCenterX, FCenterY);
p2 := p1 - p2;
//p2 := p1;
Dist := p2.LengthSquare;
if (Dist > FRadSqr) then
begin
Result.X := x;
Result.Y := y;
end
else
begin
Dist := Sqrt(Dist);
a := FAmplitude * Sin(Dist / FWaveLength * c2Pi - FPhase);
a := a * (FRadius - Dist) / FRadius;
if ( Dist <> 0 ) then a := a * FWavelength / Dist;
Result := p1 + (p2 * a);
end;
end;
{%endregion%}
{%region=====[ TBZBitmapDiffusionFilter ]========================================}
Constructor TBZBitmapDiffusionFilter.Create(Const AOwner : TBZBaseBitmap; Const DirectWrite : Boolean);
begin
inherited Create(AOwner, DirectWrite);
FForceVertical := 1.0;
FForceHorizontal := 1.0;
FScannerDescription := 'Eparpiller';
end;
procedure TBZBitmapDiffusionFilter.PrepareTransformation;
Var
i : byte;
a : Single;
begin
inherited PrepareTransformation;
For i:=0 to 255 do
begin
a := c2Pi * i / 256;
FCosLUT[i] := FForceVertical * Cos(a);
FSinLUT[i] := FForceHorizontal * Sin(a);
end;
Randomize;
end;
function TBZBitmapDiffusionFilter.ComputeTransformation(x, y : Integer) : TBZFloatPoint;
Var
d, dx, dy : Single;
i : Byte;
begin
i := Random(255);
d := Random;
dx := max(FMinDistance, min(FMaxDistance, d * FSinLUT[i]));
dy := max(FMinDistance, min(FMaxDistance, d * FCosLUT[i]));
Result.x := x + dx;
Result.y := y + dy;
end;
{%endregion%}
{%region=====[ TBZBitmapAffineTransformationFilter ]=============================}
Constructor TBZBitmapAffineTransformationFilter.Create(Const AOwner : TBZBaseBitmap; Const DirectWrite : Boolean);
begin
inherited Create(AOwner, DirectWrite);
FEdgeAction := peaZero;
FMatrix.CreateIdentityMatrix;
end;
procedure TBZBitmapAffineTransformationFilter.PrepareTransformation;
begin
inherited PrepareTransformation;
FMatrix := FMatrix.Invert;
end;
function TBZBitmapAffineTransformationFilter.ComputeTransformation(x, y : Integer) : TBZFloatPoint;
Var
{$CODEALIGN VARMIN=16}
pt : TBZFloatPoint;
{$CODEALIGN VARMIN=4}
begin
pt.Create(x,y);
//Result := FMatrix.TransformPoint(pt);
Result := pt * FMatrix;
end;
{%endregion%}
end.
|
unit frmStructuresNewStructureUnit;
{$mode delphi}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Registry, LCLType, ExtCtrls, betterControls;
type
{ TfrmStructuresNewStructure }
TfrmStructuresNewStructure = class(TForm)
btnCancel: TButton;
btnOk: TButton;
cbUseAutoTypes: TCheckBox;
cbGuessFieldTypes: TCheckBox;
edtGuessSize: TEdit;
edtStructName: TEdit;
labelStructureSize: TLabel;
labelStructureName: TLabel;
Panel1: TPanel;
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
function getStructName: string;
procedure setStructName(v: string);
function getUseAutoTypes: boolean;
function getGuessFieldTypes: boolean;
function getGuessSize: integer;
procedure setGuessSize(v: integer);
private
{ private declarations }
public
{ public declarations }
property structName: string read getStructName write setStructName;
property useAutoTypes: boolean read getUseAutoTypes;
property guessFieldTypes: boolean read getGuessFieldTypes;
property guessSize: integer read getGuessSize write setGuessSize;
end;
implementation
uses mainunit2;
resourcestring
rsWindowTitle = 'New Structure';
rsUseAutoTypesIfAvailable = 'Use Auto Types If Available';
rsGuessFieldTypes = 'Guess Field Types';
rsStructureName = 'Structure Name:';
rsSize = 'Size:';
{$R *.lfm}
{ TfrmStructuresNewStructure }
procedure TfrmStructuresNewStructure.setStructName(v: string);
begin
self.edtStructName.Text := v;
end;
function TfrmStructuresNewStructure.getStructName: String;
begin
result := self.edtStructName.Text;
end;
function TfrmStructuresNewStructure.getUseAutoTypes: Boolean;
begin
result := self.cbUseAutoTypes.Checked;
end;
function TfrmStructuresNewStructure.getGuessFieldTypes: Boolean;
begin
result := self.cbGuessFieldTypes.Checked;
end;
function TfrmStructuresNewStructure.getGuessSize : Integer;
begin
try
result := StrToInt(self.edtGuessSize.Text);
except
On E : EConvertError do
result := -1;
end;
end;
procedure TfrmStructuresNewStructure.setGuessSize(v : Integer);
begin
self.edtGuessSize.Text := Format('%d', [v]);
end;
procedure TfrmStructuresNewStructure.btnOkClick(Sender: TObject);
var
reg: TRegistry;
begin
reg := tregistry.create;
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey('\Software\'+strCheatEngine+'\DissectData',true) then
begin
reg.WriteBool('Use Auto Types', useAutoTypes);
reg.WriteBool('Guess Field Types', guessFieldTypes);
reg.WriteInteger('Guess Size', guessSize);
end;
finally
reg.free;
end;
modalresult := mrok;
end;
procedure TfrmStructuresNewStructure.FormCreate(Sender: TObject);
var
reg: TRegistry;
begin
reg := TRegistry.create;
try
self.Caption := rsWindowTitle;
self.labelStructureName.Caption := rsStructureName;
self.labelStructureSize.Caption := rsSize;
self.cbUseAutoTypes.Caption := rsUseAutoTypesIfAvailable;
self.cbGuessFieldTypes.Caption := rsGuessFieldTypes;
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey('\Software\'+strCheatEngine+'\DissectData',false) then
begin
if reg.ValueExists('Use Auto Types') then self.cbUseAutoTypes.Checked := reg.ReadBool('Use Auto Types') else self.cbUseAutoTypes.Checked := true;
if reg.ValueExists('Guess Field Types') then self.cbGuessFieldTypes.Checked := reg.ReadBool('Guess Field Types') else self.cbGuessFieldTypes.Checked := true;
if reg.ValueExists('Guess Size') then self.edtGuessSize.Text := Format('%d', [reg.ReadInteger('Guess Size')]) else guessSize := 4096;
if (guessSize <= 0) then guessSize := 4096;
end;
finally
reg.free;
end;
end;
procedure TfrmStructuresNewStructure.FormShow(Sender: TObject);
begin
self.edtStructName.SelectAll;
self.ActiveControl := self.edtStructName;
end;
end.
|
{------------------------------------
功能说明:实现ISplashForm接口(闪屏窗体接口)
创建日期:2008.12.07
作者:WZW
版权:WZW
-------------------------------------}
unit SplashFormObj;
interface
uses SysUtils, Messages, SplashFormIntf, SplashForm;
type
TSplashFormObj = class(TInterfacedObject, ISplashForm)
private
FSplashForm: Tfrm_Splash;
protected
{ISplashForm}
procedure Show;
procedure loading(const msg: String);
function GetWaitTime: Cardinal;
procedure Hide;
public
constructor Create;
destructor Destroy; override;
end;
implementation
uses SysFactory;
{ TSplashFormObj }
constructor TSplashFormObj.Create;
begin
FSplashForm := Tfrm_Splash.Create(nil);
end;
destructor TSplashFormObj.Destroy;
begin
FSplashForm.Free;
inherited;
end;
function TSplashFormObj.GetWaitTime: Cardinal;
begin
Result := 0;
end;
procedure TSplashFormObj.Hide;
begin
FSplashForm.Hide;
end;
procedure TSplashFormObj.Show;
begin
FSplashForm.Show;
end;
procedure TSplashFormObj.loading(const msg: String);
begin
FSplashForm.mm_Loading.Lines.Add(' ' + msg);
FSplashForm.Refresh;
end;
function Create_SplashFormObj(Param: Integer): TObject;
begin
Result := TSplashFormObj.Create;
end;
initialization
TIntfFactory.Create(ISplashForm, @Create_SplashFormObj);
finalization
end.
|
unit AZCUserPasswordDialogs;
{$mode objfpc}{$H+}
{$modeswitch unicodestrings}
{$namespace zeljus.com.userpassworddialog}
interface
uses androidr15;
type
{ AZCUserPasswordDialog }
AZCUserPasswordDialog = class(AAAlertDialog)
procedure onClick(para1: ACDialogInterface; para2: jint); overload;
private
FUserNameEdit: AWEditText;
FPasswordEdit: AWEditText;
function GetPassword: JLString;
function GetUserName: JLString;
procedure SetPassword(Value: JLString);
procedure SetUserName(Value: JLString);
public
constructor create(para1: ACContext); overload;
public
property UserName: JLString read GetUserName write SetUserName;
property Password: JLString read GetPassword write SetPassword;
end;
implementation
{ AZCUserPasswordDialog }
function AZCUserPasswordDialog.GetUserName: JLString;
begin
Result := FUserNameEdit.getText.toString;
end;
procedure AZCUserPasswordDialog.onClick(para1: ACDialogInterface; para2: jint);
begin
end;
function AZCUserPasswordDialog.GetPassword: JLString;
begin
Result := FPasswordEdit.getText.toString;
end;
procedure AZCUserPasswordDialog.SetPassword(Value: JLString);
begin
FPasswordEdit.setText(Value);
FPasswordEdit.selectAll();
end;
procedure AZCUserPasswordDialog.SetUserName(Value: JLString);
begin
FUserNameEdit.setText(Value);
end;
constructor AZCUserPasswordDialog.create(para1: ACContext);
var
UserNameCaption : AWTextView;
PasswordCaption : AWTextView;
layout : AWLinearLayout;
begin
inherited Create(para1);
setTitle(AAActivity(para1).getTitle.toString);
setIcon(AAActivity(para1).getPackageManager.getApplicationIcon(AAActivity(para1).getApplicationInfo));
layout:= AWLinearLayout.Create(Self.getContext);
layout.setOrientation(AWLinearLayout.VERTICAL);
UserNameCaption:= AWTextView.create(self.getContext);
UserNameCaption.setText(JLString('User name: '));
layout.addView(UserNameCaption);
FUserNameEdit:= AWEditText.create(Self.getContext);
layout.addView(FUserNameEdit);
PasswordCaption:= AWTextView.create(self.getContext);
PasswordCaption.setText(JLString('Password: '));
layout.addView(PasswordCaption);
FPasswordEdit:= AWEditText.create(Self.getContext);
FPasswordEdit.requestFocus;
FPasswordEdit.setInputType(ATInputType.TYPE_TEXT_VARIATION_PASSWORD);
FPasswordEdit.setTransformationMethod(ATMPasswordTransformationMethod.create);
layout.addView(FPasswordEdit);
setView(layout);
setButton(JLString('Ok'), ACDialogInterface.InnerOnClickListener(para1)); //-1
setButton2(JLString('Cancel'), ACDialogInterface.InnerOnClickListener(para1)); //-2
getWindow.setSoftInputMode(AVWindowManager.InnerLayoutParams.SOFT_INPUT_STATE_VISIBLE);
end;
end.
|
(*
Copyright 2016 Michael Justin
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 SimpleLogger;
interface
uses
djLogAPI, Classes, SysUtils;
type
TSimpleLogLevel = (Trace, Debug, Info, Warn, Error);
{ TSimpleLogger }
TSimpleLogger = class(TInterfacedObject, ILogger)
private
FDateTimeFormat: string;
FLevel: TSimpleLogLevel;
FName: string;
FShowDateTime: Boolean;
function GetElapsedTime: LongInt;
function DateTimeStr: string;
function LevelAsString(const ALogLevel: TSimpleLogLevel): string;
function IsEnabledFor(ALogLevel: TSimpleLogLevel): Boolean;
procedure WriteMsg(const ALogLevel: TSimpleLogLevel; const AMsg: string);
overload;
procedure WriteMsg(const ALogLevel: TSimpleLogLevel; const AMsg: string;
const AException: Exception); overload;
procedure SetLevel(AValue: TSimpleLogLevel);
public
constructor Create(const AName: string);
procedure Debug(const AMsg: string); overload;
procedure Debug(const AFormat: string; const AArgs: array of const); overload;
procedure Debug(const AMsg: string; const AException: Exception); overload;
procedure Error(const AMsg: string); overload;
procedure Error(const AFormat: string; const AArgs: array of const); overload;
procedure Error(const AMsg: string; const AException: Exception); overload;
procedure Info(const AMsg: string); overload;
procedure Info(const AFormat: string; const AArgs: array of const); overload;
procedure Info(const AMsg: string; const AException: Exception); overload;
procedure Warn(const AMsg: string); overload;
procedure Warn(const AFormat: string; const AArgs: array of const); overload;
procedure Warn(const AMsg: string; const AException: Exception); overload;
procedure Trace(const AMsg: string); overload;
procedure Trace(const AFormat: string; const AArgs: array of const); overload;
procedure Trace(const AMsg: string; const AException: Exception); overload;
function Name: string;
function IsDebugEnabled: Boolean;
function IsErrorEnabled: Boolean;
function IsInfoEnabled: Boolean;
function IsWarnEnabled: Boolean;
function IsTraceEnabled: Boolean;
property DateTimeFormat: string read FDateTimeFormat write FDateTimeFormat;
property Level: TSimpleLogLevel read FLevel write SetLevel;
property ShowDateTime: Boolean read FShowDateTime write FShowDateTime;
end;
{ TSimpleLoggerFactory }
TSimpleLoggerFactory = class(TInterfacedObject, ILoggerFactory)
public
constructor Create;
destructor Destroy; override;
function GetLogger(const AName: string): ILogger;
end;
procedure Configure(const AStrings: TStrings); overload;
procedure Configure(const AKey, AValue: string); overload;
implementation
type
{ TSimpleLoggerConfiguration }
TSimpleLoggerConfiguration = class(TObject)
private
FDateTimeFormat: string;
FLevel: TSimpleLogLevel;
FShowDateTime: Boolean;
public
constructor Create;
procedure Configure(const AStrings: TStrings); overload;
procedure Configure(const AKey, AValue: string); overload;
property DateTimeFormat: string read FDateTimeFormat;
property Level: TSimpleLogLevel read FLevel;
property ShowDateTime: Boolean read FShowDateTime;
end;
resourcestring
SNoFactory = 'A logger factory must be created before calling Configure';
const
MilliSecsPerDay = 24 * 60 * 60 * 1000;
SBlanks = ' ';
var
{ Contains logger configuration }
Config: TSimpleLoggerConfiguration;
{ Start time for the logging process - to compute elapsed time. }
StartTime: TDateTime;
procedure Configure(const AStrings: TStrings);
begin
Assert(Assigned(Config), SNoFactory);
Config.Configure(AStrings);
end;
procedure Configure(const AKey, AValue: string);
begin
Assert(Assigned(Config), SNoFactory);
Config.Configure(AKey, AValue);
end;
{ TSimpleLoggerConfiguration }
constructor TSimpleLoggerConfiguration.Create;
begin
FLevel := Info;
end;
procedure TSimpleLoggerConfiguration.Configure(const AStrings: TStrings);
var
Line: string;
begin
Line := LowerCase(AStrings.Values['defaultLogLevel']);
if Line <> '' then
begin
if Line = 'trace' then FLevel := Trace
else if Line = 'debug' then FLevel := Debug
else if Line = 'info' then FLevel := Info
else if Line = 'warn' then FLevel := Warn
else if Line = 'error' then FLevel := Error;
end;
Line := LowerCase(AStrings.Values['showDateTime']);
if Line <> '' then
begin
FShowDateTime := (Line = 'true');
FDateTimeFormat := 'hh:nn:ss.zzz';
end;
Line := LowerCase(AStrings.Values['dateTimeFormat']);
if Line <> '' then
begin
try
FormatDateTime(Line, Now);
FDateTimeFormat := Line;
except
on E: Exception do
begin
FDateTimeFormat := '';
end;
end;
end;
end;
procedure TSimpleLoggerConfiguration.Configure(const AKey, AValue: string);
var
SL: TStrings;
begin
SL := TStringList.Create;
try
SL.Values[AKey] := AValue;
Configure(SL);
finally
SL.Free;
end;
end;
{ TSimpleLogger }
constructor TSimpleLogger.Create(const AName: string);
begin
FName := AName;
end;
function TSimpleLogger.LevelAsString(const ALogLevel: TSimpleLogLevel): string;
begin
case ALogLevel of
SimpleLogger.Trace: Result := 'TRACE';
SimpleLogger.Debug: Result := 'DEBUG';
SimpleLogger.Info: Result := 'INFO';
SimpleLogger.Warn: Result := 'WARN';
SimpleLogger.Error: Result := 'ERROR';
end;
end;
function TSimpleLogger.IsEnabledFor(ALogLevel: TSimpleLogLevel): Boolean;
begin
Result := Ord(FLevel) <= Ord(ALogLevel);
end;
procedure TSimpleLogger.WriteMsg(const ALogLevel: TSimpleLogLevel; const AMsg: string);
begin
WriteLn(DateTimeStr + ' '
+ LevelAsString(ALogLevel) + ' '
+ Name + ' - '
+ AMsg);
end;
function TSimpleLogger.DateTimeStr: string;
begin
if ShowDateTime and (DateTimeFormat <> '') then
Result := FormatDateTime(DateTimeFormat, Now)
else
Result := IntToStr(GetElapsedTime);
end;
{ The elapsed time since package start up (in milliseconds). }
function TSimpleLogger.GetElapsedTime: LongInt;
begin
Result := Round((Now - StartTime) * MilliSecsPerDay);
end;
procedure TSimpleLogger.WriteMsg(const ALogLevel: TSimpleLogLevel; const AMsg: string;
const AException: Exception);
begin
WriteMsg(ALogLevel,
AMsg + SLineBreak
+ SBlanks + AException.ClassName + SLineBreak
+ SBlanks + AException.Message);
end;
procedure TSimpleLogger.SetLevel(AValue: TSimpleLogLevel);
begin
if FLevel = AValue then Exit;
FLevel := AValue;
end;
procedure TSimpleLogger.Debug(const AMsg: string);
begin
if IsDebugEnabled then
WriteMsg(SimpleLogger.Debug, AMsg);
end;
procedure TSimpleLogger.Debug(const AFormat: string; const AArgs: array of const);
begin
if IsDebugEnabled then
WriteMsg(SimpleLogger.Debug, Format(AFormat, AArgs));
end;
procedure TSimpleLogger.Debug(const AMsg: string; const AException: Exception);
begin
if IsDebugEnabled then
WriteMsg(SimpleLogger.Debug, AMsg, AException);
end;
procedure TSimpleLogger.Error(const AMsg: string; const AException: Exception);
begin
if IsErrorEnabled then
WriteMsg(SimpleLogger.Error, AMsg, AException);
end;
function TSimpleLogger.Name: string;
begin
Result := FName;
end;
procedure TSimpleLogger.Error(const AFormat: string;
const AArgs: array of const);
begin
if IsErrorEnabled then
WriteMsg(SimpleLogger.Error, Format(AFormat, AArgs));
end;
procedure TSimpleLogger.Error(const AMsg: string);
begin
if IsErrorEnabled then
WriteMsg(SimpleLogger.Error, AMsg);
end;
function TSimpleLogger.IsDebugEnabled: Boolean;
begin
Result := IsEnabledFor(SimpleLogger.Debug);
end;
function TSimpleLogger.IsErrorEnabled: Boolean;
begin
Result := IsEnabledFor(SimpleLogger.Error);
end;
function TSimpleLogger.IsInfoEnabled: Boolean;
begin
Result := IsEnabledFor(SimpleLogger.Info);
end;
function TSimpleLogger.IsTraceEnabled: Boolean;
begin
Result := IsEnabledFor(SimpleLogger.Trace);
end;
function TSimpleLogger.IsWarnEnabled: Boolean;
begin
Result := IsEnabledFor(SimpleLogger.Warn);
end;
procedure TSimpleLogger.Info(const AFormat: string;
const AArgs: array of const);
begin
if IsInfoEnabled then
WriteMsg(SimpleLogger.Info, Format(AFormat, AArgs));
end;
procedure TSimpleLogger.Info(const AMsg: string);
begin
if IsInfoEnabled then
WriteMsg(SimpleLogger.Info, AMsg);
end;
procedure TSimpleLogger.Info(const AMsg: string; const AException: Exception);
begin
if IsInfoEnabled then
WriteMsg(SimpleLogger.Info, AMsg, AException);
end;
procedure TSimpleLogger.Trace(const AMsg: string; const AException: Exception);
begin
if IsTraceEnabled then
WriteMsg(SimpleLogger.Trace, AMsg, AException);
end;
procedure TSimpleLogger.Trace(const AFormat: string;
const AArgs: array of const);
begin
if IsTraceEnabled then
WriteMsg(SimpleLogger.Trace, Format(AFormat, AArgs));
end;
procedure TSimpleLogger.Trace(const AMsg: string);
begin
if IsTraceEnabled then
WriteMsg(SimpleLogger.Trace, AMsg);
end;
procedure TSimpleLogger.Warn(const AMsg: string; const AException: Exception);
begin
if IsWarnEnabled then
WriteMsg(SimpleLogger.Warn, AMsg, AException);
end;
procedure TSimpleLogger.Warn(const AFormat: string;
const AArgs: array of const);
begin
if IsWarnEnabled then
WriteMsg(SimpleLogger.Warn, Format(AFormat, AArgs));
end;
procedure TSimpleLogger.Warn(const AMsg: string);
begin
if IsWarnEnabled then
WriteMsg(SimpleLogger.Warn, AMsg);
end;
{ TSimpleLoggerFactory }
constructor TSimpleLoggerFactory.Create;
begin
inherited Create;
end;
destructor TSimpleLoggerFactory.Destroy;
begin
inherited;
end;
function TSimpleLoggerFactory.GetLogger(const AName: string): ILogger;
var
Logger: TSimpleLogger;
begin
Logger := TSimpleLogger.Create(AName);
Logger.DateTimeFormat := Config.DateTimeFormat;
Logger.Level := Config.Level;
Logger.ShowDateTime := Config.ShowDateTime;
Result := Logger;
end;
initialization
StartTime := Now;
Config := TSimpleLoggerConfiguration.Create;
finalization
Config.Free;
end.
|
unit UBus;
interface
uses
Threading, SyncObjs, generics.collections, // RTL
LoggerPro, LoggerPro.FileAppender, // Logger
UEvent, UChannel; // Business
type
IReceiver = interface
['{0BBA7853-1FB2-45E9-92AE-BE38091FE8EF}']
procedure ReceiveMsg(AMsg: IEventMsg);
end;
TEventBus = class
strict private
FMailBoxCriticalSec: TCriticalSection;
FMailBox: TQueue<IEventMsg>;
// Get all receiver ordered by channel
FReceivers: TDictionary<TChannel, TList<IReceiver>>;
FChannels: TDictionary<string, TChannel>;
FBroadcastChannel: TChannelBroadCast;
FTerminated: Boolean;
FFlagIncomingMessage: TEvent;
FDispatchTask: ITask;
procedure DispatchEvent;
public
constructor Create;
destructor Destroy; override;
procedure ConnectTo(const AMsgReceiver: IReceiver; AChannelsToSubscribe: TArray<TChannel>);
function CreateNewChannel(const AName: string): TChannel;
function GetChannelByName(const AName: string): TChannel;
procedure SendMessage(AMsg: IEventMsg);
procedure StartBus;
procedure StopBus;
property BroadcastChannel: TChannelBroadCast read FBroadcastChannel write FBroadcastChannel;
end;
var
Log: ILogWriter;
implementation
uses
Classes, Sysutils;
procedure TEventBus.ConnectTo(const AMsgReceiver: IReceiver; AChannelsToSubscribe: TArray<TChannel>);
var
LChannel: TChannel;
LReceiverLst: TList<IReceiver>;
I: Integer;
begin
FReceivers.TryGetValue(FBroadcastChannel, LReceiverLst);
LReceiverLst.Add(AMsgReceiver);
if Assigned(AChannelsToSubscribe) then
begin
for LChannel in AChannelsToSubscribe do
begin
if FReceivers.TryGetValue(LChannel, LReceiverLst) then
LReceiverLst.Add(AMsgReceiver)
else
begin
LReceiverLst := TList<IReceiver>.Create;
LReceiverLst.Add(AMsgReceiver);
FReceivers.Add(LChannel, LReceiverLst);
end;
end;
end;
end;
constructor TEventBus.Create;
begin
FMailBoxCriticalSec := TCriticalSection.Create;
FMailBox := TQueue<IEventMsg>.Create;
FFlagIncomingMessage := TEvent.Create(nil, False, False, 'Incomming Msg');
FReceivers := TDictionary<TChannel, TList<IReceiver>>.Create;
FChannels := TDictionary<string, TChannel>.Create;
FBroadcastChannel := TChannelBroadCast.Create(TChannelBroadCast.BROADCAST_NAME);
FBroadcastChannel.Description := 'WARNING SPECIAL BROADCAST CHANNEL';
FReceivers.Add(FBroadcastChannel, TList<IReceiver>.Create);
Log := BuildLogWriter([TLoggerProFileAppender.Create]);
end;
function TEventBus.CreateNewChannel(const AName: string): TChannel;
var
LCreatedChannel: UChannel.TChannel;
begin
LCreatedChannel := TChannel.Create(AName);
FChannels.Add(AName, LCreatedChannel);
Result := LCreatedChannel;
end;
destructor TEventBus.Destroy;
var
LReciverList: TList<IReceiver>;
LChannel: TChannel;
begin
StopBus;
if Assigned(FDispatchTask) then
TTask.WaitForAll([FDispatchTask]);
FBroadcastChannel.Free;
for LChannel in FChannels.Values do
begin
LChannel.Free
end;
FChannels.Free;
for LReciverList in FReceivers.Values do
begin
LReciverList.Free;
end;
FReceivers.Free;
FFlagIncomingMessage.Free;
FMailBox.Free;
FMailBoxCriticalSec.Free;
inherited;
end;
procedure TEventBus.DispatchEvent;
var
LChannel: UChannel.TChannel;
LMsg: IEventMsg;
I: Integer;
LReceiverLst: TList<IReceiver>;
LReceiverPair: TPair<TChannel, TList<IReceiver>>;
procedure SendMsg;
var
LReceiver: IReceiver;
begin
for LReceiver in LReceiverLst do
begin
LReceiver.ReceiveMsg(LMsg);
end;
end;
begin
while not FTerminated do
begin
FFlagIncomingMessage.WaitFor;
Log.Debug('Unlock Event', 'Dispatch');
while true do
begin
FMailBoxCriticalSec.Enter;
try
// Sleep(1000); //Test Slow BUS
if (FMailBox.Count = 0) then
begin
Break;
end;
Log.Debug('Enter critical section', 'Dispatch');
LMsg := FMailBox.Dequeue;
Log.DebugFmt('Message dequeue : %s', [LMsg.GetDescription], 'Dispatch');
finally
Log.Debug('leave critical section', 'Dispatch');
FMailBoxCriticalSec.Leave;
end;
for I := 0 to LMsg.GetChannelCount - 1 do
begin
LChannel := LMsg.GetChannelByIndex(I);
Log.DebugFmt('Message %s on channel %s',
[LMsg.GetDescription, LChannel.Name], 'Dispatch');
if FReceivers.TryGetValue(LChannel, LReceiverLst) then
begin
Log.DebugFmt('%d receiver on msg %s',
[LReceiverLst.Count, LMsg.GetDescription], 'Dispatch');
SendMsg;
end;
end;
end;
end;
end;
function TEventBus.GetChannelByName(const AName: string): TChannel;
begin
FChannels.TryGetValue(AName, Result);
end;
procedure TEventBus.SendMessage(AMsg: IEventMsg);
begin
FMailBoxCriticalSec.Enter;
try
Log.Debug('Enter critical section', 'SendMsg');
FMailBox.Enqueue(AMsg);
Log.DebugFmt('Message send : %s', [AMsg.GetDescription], 'SendMsg');
FFlagIncomingMessage.SetEvent;
finally
Log.Debug('Leave critical section', 'SendMsg');
FMailBoxCriticalSec.Leave;
end;
end;
procedure TEventBus.StartBus;
begin
FDispatchTask := TTask.Create(DispatchEvent).Start;
end;
procedure TEventBus.StopBus;
begin
FTerminated := True;
FFlagIncomingMessage.SetEvent; // unlock the event to close the threaded dispatcher func
end;
end.
|
namespace SQLDeployment.Core;
uses
Dapper,
System.Data.SqlClient,
SQLDeployment.Core.Models,
System.Text.RegularExpressions,
System.Threading.Tasks;
type
DeploymentExtensions = public extension class(Deployment)
private
///
/// With this text
/// "There is already an object named 'get_sailed_for_boat' in the database";
/// Will extract get_sailed_for_boat
///
method ExistingStoredProcedure(message:String): tuple of (Boolean,String);
begin
var pattern := "(?:There is already an object named ')(.*)(?:' in the database)";
var reg := new Regex(pattern);
var someMatch := reg.Match(message);
if((someMatch.Success) and (someMatch.Groups.Count=2))then
begin
exit (true,someMatch.Groups[1].Value);
end;
exit (false,nil);
end;
protected
method Execute(connection:SqlConnection; filename:String):Task;
begin
Console.WriteLine($'Running {filename}');
var sql := System.IO.File.ReadAllText(filename);
var repeatWithDrop := false;
var storedProcedure := '';
try
await connection.ExecuteAsync(sql);
except
on S:SqlException do
begin
var storedProcedureInfo := ExistingStoredProcedure(S.Message);
if not storedProcedureInfo.Item1 then
begin
raise;
end;
storedProcedure := storedProcedureInfo.Item2;
repeatWithDrop := true;
end;
end;
if(repeatWithDrop)then
begin
Console.WriteLine($'Dropping stored procedure {storedProcedure} before running');
await connection.ExecuteAsync($'drop procedure {storedProcedure}');
await connection.ExecuteAsync(sql);
end;
end;
public
method Deploy:Task;
begin
using connection := new SqlConnection(self.Connection) do
begin
for each folder in self.Folders do
begin
var name := folder.Name;
if(folder.Name.StartsWith('~'))then
begin
name := folder.Name.Replace('~',System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
end;
for each file in folder.Files do
begin
var filename := $'{name}/{file.Name}';
if System.IO.File.Exists(filename) then
begin
await Execute(connection, filename);
end
else
begin
Console.WriteLine($'{filename} does not exist');
end;
end;
end;
end;
end;
end;
end. |
{******************************************************************************}
{Create By: David }
{******************************************************************************}
{ 调试单元 }
unit uDebug;
interface
uses
SysUtils, Windows, IdContext, IdSync, IdSchedulerOfThread;
procedure DebugLog(Msg: WideString; filename: string); overload;
procedure DebugLog(Msg: WideString); overload;
procedure DebugLog(Msg: WideString; const Args: array of const); overload;
procedure Logger(AContext: TIdContext; s: string); overload;
procedure Logger(s: string); overload;
procedure DebugMemo(Msg: string);
implementation
//uses
// fMain;
var
FLogLock: TRTLCriticalSection;
FMemoLock: TRTLCriticalSection;
procedure DebugLog(Msg: WideString; filename: string);
var
F: TextFile;
begin
EnterCriticalSection(FLogLock);
try
try
AssignFile(F, filename);
if FileExists(FileName) then
Append(F)
else
Rewrite(F);
Writeln( F, DateTimeToStr(Now) + ' ' + Msg ); { Read first line of file }
Writeln( F, '' );
CloseFile(F);
except
end;
finally
LeaveCriticalSection(FLogLock);
end;
end;
procedure DebugLog(Msg: WideString);
begin
DebugLog(Msg, ExtractFilePath(Paramstr(0)) + 'Log\Log.' + FormatDateTime('yyyymmdd', Date) + '.txt');
end;
procedure DebugLog(Msg: WideString; const Args: array of const);
begin
DebugLog(Format(Msg, Args));
end;
procedure DebugLogx(s: string);
begin
//frmMain.mmoLog.Lines.Add(datetimetostr(now)+' '+s);
end;
procedure Logger(AContext: TIdContext; s: string);
begin
// if not frmMain.chkDebug.Checked then
// Exit;
// frmmain.LogStr_Lock;
try
// frmMain.LogStr_Write(s);
// TIdSync.SynchronizeMethod(frmMain.LogStr_Update); //Indy10同步
// TIdYarnOfThread(AContext.Yarn).Thread.Synchronize(frmMain.LogStr_Update);
finally
// frmmain.LogStr_Release;
end;
end;
procedure Logger(s: string);
begin
// if not frmMain.chkDebug.Checked then
// Exit;
// frmMain.mmoDebug.Lines.Add(s);
Exit;
// frmmain.LogStr_Lock;
try
// frmMain.LogStr_Write(s);
// frmMain.LogStr_Update;
finally
// frmmain.LogStr_Release;
end;
end;
procedure DebugMemo(Msg: string);
begin
EnterCriticalSection(FMemoLock);
try
// frmMain.mmoDebug.Lines.Add(Msg);
finally
LeaveCriticalSection(FMemoLock);
end;
end;
initialization
InitializeCriticalSection(FLogLock);
InitializeCriticalSection(FMemoLock);
finalization
DeleteCriticalSection(FLogLock);
DeleteCriticalSection(FMemoLock);
end.
|
unit NovusPlugin;
interface
Uses Windows, SysUtils, Classes ;
const
func_GetPluginObject = 'GetPluginObject';
type
INovusPlugin = interface
['{7AAD37E6-7B50-4266-8268-E8955FC6209E}']
function GetPluginName: string; safecall;
procedure Initialize; safecall;
procedure Finalize; safecall;
property PluginName: string read GetPluginName;
end;
TGetPluginObject = function: INovusPlugin; stdcall;
PPluginInfo = ^TPluginInfo;
TPluginInfo = record
FileName: string;
Handle: Thandle;
Plugin: INovusPlugin;
GetPluginObjectFunc: TGetPluginObject;
end;
TNovusPlugins = class(Tobject)
private
protected
fPlugins: TList;
function GetPlugins(Index: integer): INovusPlugin;
function GetPluginCount: Integer;
public
constructor Create;
destructor Destroy; override;
function FindPlugin(const aPluginName: string; out aPlugin: INovusPlugin): boolean;
function LoadPlugin(const aFilename: String): Boolean;
procedure UnloadPlugin(aIndex: integer);
procedure UnloadAllPlugins;
property Plugins[Index: integer]: INovusPlugin read GetPlugins; default;
property PluginCount: integer read GetPluginCount;
end;
implementation
uses System.Generics.Defaults;
constructor TNovusPlugins.Create;
begin
fPlugins := TList.Create;
end;
destructor TNovusPlugins.Destroy;
begin
if (fPlugins <> nil) then
begin
UnloadAllPlugins;
fplugins.Free;
end;
end;
procedure TNovusPlugins.UnloadAllPlugins;
var
I: integer;
begin
for i := PluginCount - 1 downto 0 do
UnloadPlugin(I);
end;
procedure TNovusPlugins.UnloadPlugin(aIndex: integer);
var
FPluginInfo: PPluginInfo;
lHandle: Thandle;
begin
if PluginCount = 0 then Exit;
FPluginInfo := fPlugins[aIndex];
if (FPluginInfo^.Handle = 0) then Exit;
try
FPluginInfo^.Plugin.Finalize;
lHandle := FPluginInfo^.Handle;
FPluginInfo^.Plugin := nil;
if (lHandle <> 0) then FreeLibrary(lHandle);
finally
Dispose(FPluginInfo);
fPlugins.Delete(aIndex);
end;
end;
function TNovusPlugins.LoadPlugin(const aFilename: String): Boolean;
var
lHandle: THandle;
FPluginInfo: PPluginInfo;
ptr: pointer;
FPlugin: INovusPlugin;
begin
Result := False;
if not FileExists(aFileName) then Exit;
Try
New(FPluginInfo);
FPluginInfo^.FileName := aFileName;
FPluginInfo^.Handle := 0;
FPluginInfo^.Handle := LoadLibrary(Pchar(aFileName));
ptr := GetProcAddress(FPluginInfo^.Handle, func_GetPluginObject);
@FPluginInfo^.GetPluginObjectFunc := ptr;
FPlugin := FPluginInfo.GetPluginObjectFunc();
FPluginInfo^.Plugin := FPlugin;
FPlugin := nil;
if FindPlugin(FPluginInfo^.Plugin.PluginName, FPlugin) then
raise Exception.Create('Plugin Loaded already');
FPlugin := nil;
FPluginInfo^.Plugin.Initialize;
fPlugins.Add(FPluginInfo);
Result := True;
Except
lHandle := FPluginInfo^.Handle;
FPluginInfo^.Plugin := nil;
Dispose(FPluginInfo);
if (lHandle <> 0) then FreeLibrary(lHandle);
raise;
End;
end;
function TNovusPlugins.FindPlugin(const aPluginName: string; out aPlugin: INovusPlugin): boolean;
var
i: integer;
begin
Result := false;
aPlugin := nil;
for i := 0 to (PluginCount - 1) do
if SameText(Plugins[i].PluginName, aPluginName) then
begin
aPlugin := Plugins[i];
result := true;
Exit;
end;
end;
function TNovusPlugins.GetPlugins(Index: integer): INovusPlugin;
begin
result := PPluginInfo(fPlugins[Index])^.Plugin;
end;
function TNovusPlugins.GetPluginCount: integer;
begin
result := fPlugins.Count;
end;
end.
|
unit acNoteBook;
{.$DEFINE LOGGED}
interface
uses Messages, Windows, SysUtils, Classes, Controls, Forms, Menus, Graphics,
StdCtrls, sCommonData, ExtCtrls, acSBUtils{$IFDEF LOGGED}, sDebugMsgs{$ENDIF};
type
{$IFNDEF NOTFORHELP}
TacWndArray = array of TacMainWnd;
TsPage = class(TPage); // For compatibility with old version
{$ENDIF}
TsNotebook = class(TNoteBook)
{$IFNDEF NOTFORHELP}
private
FCommonData: TsCommonData;
wa : TacWndArray;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AfterConstruction; override;
procedure Loaded; override;
procedure WndProc(var Message: TMessage); override;
published
property Align;
property Anchors;
property Color;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Font;
property Enabled;
property Constraints;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
{$ENDIF}
property SkinData : TsCommonData read FCommonData write FCommonData;
end;
implementation
uses Consts, sConst, sMessages, sVclUtils, sGraphUtils, sAlphaGraph, sStyleSimply, acntUtils;
{ TsNotebook }
constructor TsNotebook.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCommonData := TsCommonData.Create(Self, True);
FCommonData.COC := COC_TsCheckBox;
end;
destructor TsNotebook.Destroy;
var
i : integer;
begin
if Assigned(FCommonData) then FreeAndNil(FCommonData);
for i := 0 to Length(wa) - 1 do if (wa[i] <> nil) and wa[i].Destroyed then FreeAndNil(wa[i]);
inherited Destroy;
end;
procedure TsNotebook.AfterConstruction;
begin
inherited;
FCommonData.Loaded;
end;
procedure TsNotebook.Loaded;
begin
inherited;
FCommonData.Loaded;
end;
type
TacPageWnd = class(TacMainWnd)
protected
Notebook : TsNotebook;
Page : TPage;
public
procedure PrepareCache;
procedure AC_WMPaint(Message : TWMPaint);
procedure acWndProc(var Message: TMessage); override;
end;
procedure TsNotebook.WndProc(var Message: TMessage);
var
i : integer;
Page : TPage;
begin
{$IFDEF LOGGED}
AddToLog(Message);
{$ENDIF}
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_CTRLHANDLED : begin Message.Result := 1; Exit end;
AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end;
AC_REMOVESKIN : begin
for i := 0 to ControlCount - 1 do if Controls[i] is TPage then SendMessage(TPage(Controls[i]).Handle, Message.Msg, Message.WParam, Message.LParam);
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_UPDATENOW or RDW_NOERASE or RDW_ALLCHILDREN);
end;
exit
end;
AC_SETNEWSKIN : begin
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then CommonWndProc(Message, FCommonData);
for i := 0 to ControlCount - 1 do if Controls[i] is TPage then SendMessage(TPage(Controls[i]).Handle, Message.Msg, Message.WParam, Message.LParam);
Exit
end;
AC_REFRESH : begin
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_ERASE or RDW_ALLCHILDREN);
end;
for i := 0 to ControlCount - 1 do if Controls[i] is TPage then SendMessage(TPage(Controls[i]).Handle, Message.Msg, Message.WParam, Message.LParam);
Exit
end;
AC_GETBG : begin
GetBGInfo(PacBGInfo(Message.LParam), Parent);
inc(PacBGInfo(Message.LParam)^.Offset.X, Left);
inc(PacBGInfo(Message.LParam)^.Offset.Y, Top);
Exit;
end;
AC_GETCONTROLCOLOR : if SkinData.FOwnerControl <> nil then begin
CommonMessage(Message, SkinData);
Exit;
end;
end;
case Message.Msg of
WM_PARENTNOTIFY : begin
case Message.WParamLo of
WM_CREATE : for i := 0 to ControlCount - 1 do if (Self.Controls[i] is TPage) and (TPage(Controls[i]).Handle = THandle(Message.LParam)) then begin
Page := TPage(Controls[i]);
SetLength(wa, Length(wa) + 1);
wa[Length(wa) - 1] := TacPageWnd.Create(Page.Handle, nil, SkinData.SkinManager, SkinData.SkinSection);
wa[Length(wa) - 1].SkinData.FOwnerControl := Page;
TacPageWnd(wa[Length(wa) - 1]).Notebook := Self;
TacPageWnd(wa[Length(wa) - 1]).Page := Page;
AddToAdapter(Self);
Break;
end;
end;
end;
end;
if not ControlIsReady(Self) or (FCommonData = nil) or not FCommonData.Skinned then inherited else begin
if Message.Msg = SM_ALPHACMD then begin
case Message.WParamHi of
AC_ENDPARENTUPDATE : if FCommonData.Updating then begin
FCommonData.Updating := False;
for i := 0 to ControlCount - 1 do if Controls[i] is TPage then SendMessage(TPage(Controls[i]).Handle, Message.Msg, Message.WParam, Message.LParam);
end;
AC_PREPARING : begin
Message.Result := integer(FCommonData.FUpdating);
Exit;
end;
AC_URGENTPAINT : begin
CommonWndProc(Message, FCommonData);
if FCommonData.UrgentPainting then begin
InitCacheBmp(FCommonData);
FCommonData.BGChanged := False;
end;
end
else CommonMessage(Message, FCommonData);
end;
end
else begin
case Message.Msg of
WM_ERASEBKGND : begin
if PageIndex < Length(wa) then begin
Message.Result := SendMessage(wa[PageIndex].CtrlHandle, Message.Msg, Message.WParam, 1);
Exit;
// GetBGInfo(@BgInfo, wa[PageIndex].CtrlHandle);
end;
end;
end;
CommonWndProc(Message, FCommonData);
inherited;
end;
end;
end;
{ TacPageWnd }
procedure TacPageWnd.AC_WMPaint(Message: TWMPaint);
var
PS : TPaintStruct;
DC : hdc;
cRect : TRect;
i : integer;
begin
InitCtrlData(CtrlHandle, ParentWnd, WndRect, ParentRect, WndSize, WndPos, Caption);
if (csPaintCopy in Page.ControlState) and (Message.Msg = WM_ERASEBKGND) then begin
if not SkinData.Updating then begin
PrepareCache;
BitBlt(Message.DC, 0, 0, WndSize.cx, WndSize.cy, SkinData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
end
else begin
if not InAnimationProcess and (Message.Msg <> WM_ERASEBKGND) then BeginPaint(CtrlHandle, ps);
SkinData.FUpdating := SkinData.Updating;
if not SkinData.FUpdating then begin
if (Message.DC = 0) or (Message.Unused <> 1)
then DC := GetWindowDC(CtrlHandle)
else DC := Message.DC;
PrepareCache;
if DlgMode then begin
cRect.Top := SkinData.SkinManager.MaskWidthTop(SkinData.BorderIndex);
cRect.Left := SkinData.SkinManager.MaskWidthLeft(SkinData.BorderIndex);
cRect.Right := WndSize.cx - SkinData.SkinManager.MaskWidthRight(SkinData.BorderIndex);
cRect.Bottom := WndSize.cy - SkinData.SkinManager.MaskWidthBottom(SkinData.BorderIndex);
ExcludeClipRect(DC, cRect.Left, cRect.Top, cRect.Right, cRect.Bottom);
end;
if (Page = nil) then CopyHwndCache(CtrlHandle, SkinData, Rect(0, 0, 0, 0), Rect(0, 0, WndSize.cx, WndSize.cy), DC, False) else begin
for i := 0 to Page.ControlCount - 1 do if Page.Controls[i] is TWinControl then Page.Controls[i].ControlStyle := Page.Controls[i].ControlStyle + [csOpaque];
CopyWinControlCache(Page, SkinData, Rect(0, 0, 0, 0), Rect(0, 0, WndSize.cx, WndSize.cy), DC, False);
end;
PaintControls(DC, Page, False, Point(0, 0));
if (Message.DC = 0) or (Message.Unused <> 1) then ReleaseDC(CtrlHandle, DC);
SetParentUpdated(CtrlHandle);
end;
if not InAnimationProcess and (Message.Msg <> WM_ERASEBKGND) then EndPaint(CtrlHandle, ps);
end;
end;
procedure TacPageWnd.acWndProc(var Message: TMessage);
var
i : integer;
begin
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_CTRLHANDLED : begin Message.Result := 1; Exit end;
AC_SETNEWSKIN : begin
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then CommonWndProc(Message, SkinData);
AlphaBroadCastCheck(Skindata.FOwnerControl, CtrlHandle, Message);
Exit;
end;
end;
if SkinData.Skinned then begin
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_REMOVESKIN : begin
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, SkinData);
RedrawWindow(Page.Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_UPDATENOW or RDW_NOERASE or RDW_ALLCHILDREN);
end;
AlphaBroadCastCheck(Skindata.FOwnerControl, CtrlHandle, Message);
Exit;
end;
AC_REFRESH : begin
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, SkinData);
end;
AlphaBroadCastCheck(Skindata.FOwnerControl, CtrlHandle, Message);
end;
AC_CHILDCHANGED : begin
CommonMessage(Message, SkinData);
Exit;
end;
AC_GETBG : begin
InitBGInfo(SkinData, PacBGInfo(Message.LParam), 0, CtrlHandle);
Exit;
end;
AC_ENDPARENTUPDATE : if SkinData.Updating then begin
SkinData.Updating := False;
SendMessage(CtrlHandle, WM_PAINT, 0, 0);
SendMessage(CtrlHandle, WM_NCPAINT, 0, 0);
for i := 0 to TWincontrol(Skindata.FOwnerControl).ControlCount - 1 do if TWincontrol(Skindata.FOwnerControl).Controls[i] is TWinControl then SendMessage(TWinControl(TWincontrol(Skindata.FOwnerControl).Controls[i]).Handle, Message.Msg, Message.WParam, Message.LParam);
end;
AC_PREPARING : begin
Message.Result := integer(Notebook.SkinData.FUpdating);
Exit;
end;
AC_GETCONTROLCOLOR : begin
CommonMessage(Message, SkinData);
Exit;
end
else if CommonMessage(Message, SkinData) then Exit;
end;
case Message.Msg of
WM_ERASEBKGND : if not DlgMode then begin
AC_WMPaint(TWMPaint(Message));
Message.Result := 1;
Exit;
end;
WM_NCPAINT : if DlgMode then begin
AC_WMPaint(TWMPaint(MakeMessage(WM_NCPAINT, 0, 0, 0)));
Exit;
end;
WM_PRINT : if not DlgMode then begin
SkinData.BGChanged := True;
Message.LParam := 1;
AC_WMPaint(TWMPaint(Message));
end;
WM_PAINT : if not DlgMode then begin
AC_WMPaint(TWMPaint(Message));
Exit;
end;
WM_SIZE, WM_MOVE : SkinData.BGChanged := True;
WM_PARENTNOTIFY : if (Message.WParam and $FFFF = WM_CREATE) or (Message.WParam and $FFFF = WM_DESTROY) then begin
inherited;
if (Message.WParamLo = WM_CREATE) and Assigned(Notebook) then AddToAdapter(Notebook);
exit;
end;
end;
end;
inherited;
end;
procedure TacPageWnd.PrepareCache;
var
ParentBG : TacBGInfo;
CI : TCacheInfo;
begin
InitCacheBmp(SkinData);
SkinData.FCacheBmp.Width := WndSize.cx;
SkinData.FCacheBmp.Height := WndSize.cy;
ParentBG.BgType := btUnknown;
ParentBG.PleaseDraw := False;
GetBGInfo(@ParentBG, NoteBook.Parent);
CI := BGInfoToCI(@ParentBG);
PaintItem(SkinData, CI, False, 0, Rect(0, 0, WndSize.cx, WndSize.cy), Point(Notebook.Left, Notebook.Top), SkinData.FCacheBMP, True);
SkinData.BGChanged := False;
end;
initialization
Classes.RegisterClasses([TsPage]); // For compatibility with old version
finalization
end.
|
unit dmoUserMaintU;
interface
uses
System.SysUtils, System.Classes, Data.DB, Data.Win.ADODB;
type
TdmoUserMaint = class(TDataModule)
qryUser: TADOQuery;
qryUserRole: TADOQuery;
qryProgName: TADOQuery;
ADOQuery1: TADOQuery;
qryMenuItems: TADOQuery;
ADOCommand1: TADOCommand;
qryUserLog: TADOQuery;
qryAccessLevel: TADOQuery;
Function OpenQueryPrograme:Integer;
Function OpenQueryUser: Integer;
Function GetUserRoleID(TheUserID : Integer): Integer;
Procedure OpenQueryUserRole;
Procedure OpenQueryMenuItems;
Function AddNewProg(TheName : String) : Integer;
Procedure DeleteProg;
Procedure AddUser(sUserName, sUserFullName, sUserPassword, sUserEmail: String; theRoleID: Integer);
Procedure DeleteUser;
procedure qryMenuItemsBeforePost(DataSet: TDataSet);
private
{ Private declarations }
Procedure GetCurrentUserRoleDetail(TheRoleID : Integer);
Function ExistsProgName(TheName: String):Boolean;
Function GetID(tbIDname, tbName : String): Integer;
public
{ Public declarations }
End;
var
dmoUserMaint: TdmoUserMaint;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses DmoConnectionUserU, globals;
{$R *.dfm}
{ TdmoUserMaint }
Function TdmoUserMaint.AddNewProg(TheName: String): Integer;
Var
itbID : Integer;
Begin
Thename := ReplaceCharinStr(TheName, ' ', '');
If ExistsProgName(TheName) Then
Begin
Result := -1;
Error('Programme name already exists');
End
Else
Begin
qryProgName.Active := False;
qryProgName.SQL.Clear;
qryProgName.SQL.Add('Insert Into ProgName (ProgNameID, Description) Values ( :p1, :p2)');
result := 0;
itbID := GetID('ProgNameID', 'ProgName');
If itbID > -1 Then
Begin
itbID := itbID + 1;
qryProgName.Parameters.ParamByName('p1').Value := itbID;
qryProgName.Parameters.ParamByName('p2').Value := Thename;
End;
Try
qryProgName.ExecSQL;
result := itbID;
Except
On E: Exception Do
Begin
Error('Error raised writing programme name to database');
Error('Exception class name = '+E.ClassName);
Error('Exception message = '+E.Message);
End;
End;
End;
End;
Procedure TdmoUserMaint.AddUser(sUserName, sUserFullName, sUserPassword, sUserEmail: String; theRoleID: Integer);
Var
s1 : String;
Begin
LogInUserID := GetID('UserID', 'tbUser') + 1;
s1 := 'INSERT INTO tbUser (UserID, UserLoginName, UserPassword, '
+ 'UserCurrent, UserDisplayName, UserEmailAddress) '
+ 'VALUES (' + IntToStr(LogInUserID)+', ' + quotedStr(sUserName) + ', ' + QuotedStr(sUserPassword) + ', '
+ '1, ' + QuotedStr(sUserFullName) + ', ' + quotedStr(sUserEmail) + ')';
ADOCommand1.CommandText := s1;
ADOCommand1.Execute;
UserLogID := GetID('UserLogID', 'UserLog') + 1;
s1 := 'INSERT INTO UserLog (UserLogID, UserRoleID, ProgNameID, UserID) '
+ 'VALUES (' + IntToStr(UserLogID)+', ' + IntToStr(theRoleID) + ', '
+ IntToStr(iProgNameID) + ', ' + IntToStr(LogInUserID) + ')';
ADOCommand1.CommandText := s1;
ADOCommand1.Execute;
End;
Procedure TdmoUserMaint.DeleteProg;
Var
TheID : Integer;
Begin
TheID := qryProgName.FieldByName('ProgNameID').AsInteger;
ADOCommand1.CommandText := 'Delete From MenuItem Where ProgNameID = ' + IntToStr(TheID);
ADOCommand1.Execute;
ADOCommand1.CommandText := 'Delete From UserLog Where ProgNameID = ' + IntToStr(TheID);
ADOCommand1.Execute;
ADOCommand1.CommandText := 'Delete From ProgName Where ProgNameID = ' + IntToStr(TheID);
ADOCommand1.Execute;
end;
Procedure TdmoUserMaint.DeleteUser;
Var
TheID : Integer;
Begin
TheID := qryUser.FieldByName('UserID').AsInteger;
ADOCommand1.CommandText := 'Delete From UserLog Where UserID = ' + IntToStr(TheID);
ADOCommand1.Execute;
ADOCommand1.CommandText := 'Delete From tbUser Where UserID = ' + IntToStr(TheID);
ADOCommand1.Execute;
LogInUserID := OpenQueryUser;
OpenQueryUserRole;
End;
Function TdmoUserMaint.ExistsProgName(TheName: String): Boolean;
Begin
Result := False;
ADOQuery1.Active := False;
ADOQuery1.SQL.Clear;
ADOQuery1.SQL.Add('Select * from Progname Where Description = ' + quotedStr(TheName));
Try
ADOQuery1.Active := True;
If ADOQuery1.RecordCount = 1 Then
Result := True;
Finally
ADOQuery1.Active := False;
End;
End;
Function TdmoUserMaint.GetID(tbIDname, tbName: String): Integer;
Var
ii : Integer;
s1 : String;
Begin
adoQuery1.Active := False;
adoQuery1.SQL.Clear;
s1 := 'Select TOP 1 ' + tbIDname + ' from ' + tbName + ' Order By ' + tbIDname;
adoQuery1.SQL.Add('Select TOP 1 ' + tbIDname + ' from ' + tbName + ' Order By ' + tbIDname + ' DESC');
Try
adoQuery1.Active := True;
ii := ADOQuery1.RecordCount;
s1 := QuotedStr(tbIDname);
Result := ADOQuery1.FieldByName(tbIDname).AsInteger;
Except
On E: Exception Do
Begin
Result := -1;
Error('Exception class name = '+E.ClassName);
Error('Exception message = '+E.Message);
End;
End;
End;
Function TdmoUserMaint.OpenQueryPrograme:Integer;
Begin
qryProgName.Active := False;
qryProgName.SQL.Clear;
qryProgName.SQL.Add('Select * From ProgName');
Result := 0;
Try
qryProgName.Active := True;
If qryProgName.RecordCount > 0 Then
Result := qryProgName.FieldByName('ProgNameID').AsInteger;
Except
On E: Exception Do
Begin
Error('Error opening ProgName table');
Error('Exception class name = '+E.ClassName);
Error('Exception message = '+E.Message);
End;
End;
End;
Procedure TdmoUserMaint.GetCurrentUserRoleDetail(TheRoleID : Integer);
Var
s1 : String;
Begin
qryAccessLevel.Active := False;
qryAccessLevel.SQL.Clear;
s1 := 'Select UserRoleID, Description, AccessLevel From UserRole '
+ ' Where UserRoleID = ' + IntToStr(TheRoleID);
qryAccessLevel.SQL.Add(s1);
Try
qryAccessLevel.Active := True;
UserAccessLevel := qryAccessLevel.FieldByName('AccessLevel').AsInteger;
UserAccessName := qryAccessLevel.FieldByName('Description').AsString;
Except
On E: Exception Do
Begin
s1 := 'Error opening UserRole table'
+ CRLF
+ 'Exception class name = '+E.ClassName
+ CRLF
+ 'Exception message = '+E.Message;
Error(s1);
End;
End;
End;
Function TdmoUserMaint.GetUserRoleID(TheUserID : Integer): Integer;
Var
s1 : String;
Begin
qryUserLog.Active := False;
qryUserLog.SQL.Clear;
s1 := 'Select UserLogID, UserRoleID, ProgNameID, UserID From UserLog '
+ ' Where UserID = ' + IntToStr(LogInUserID);
qryUserLog.SQL.Add(s1);
Result := 0;
Try
qryUserLog.Active := True;
Result := qryUserLog.FieldByName('UserRoleID').AsInteger;
GetCurrentUserRoleDetail(Result);
Except
On E: Exception Do
Begin
s1 := 'Error opening UserLog table'
+ CRLF
+ 'Exception class name = '+E.ClassName
+ CRLF
+ 'Exception message = '+E.Message;
Error(s1);
End;
End;
End;
Function TdmoUserMaint.OpenQueryUser: Integer;
Begin
qryUser.Active := False;
qryUser.SQL.Clear;
qryUser.SQL.Add('Select * From tbUser');
Result := 0;
Try
qryUser.Active := True;
Result := qryUser.FieldByName('UserID').AsInteger;
Except
On E: Exception Do
Begin
Error('Error opening User table');
Error('Exception class name = '+E.ClassName);
Error('Exception message = '+E.Message);
End;
End;
End;
Procedure TdmoUserMaint.OpenQueryUserRole;
Var
s1 : String;
Begin
qryUserRole.Active := False;
qryUserRole.SQL.Clear;
qryUserRole.SQL.Add('Select * From UserRole');
Try
qryUserRole.Active := True;
Except
On E: Exception Do
Begin
s1 := 'Error opening UserRole table'
+ CRLF
+ 'Exception class name = '+E.ClassName
+ CRLF
+ 'Exception message = '+E.Message;
Error(s1);
End;
End;
End;
Procedure TdmoUserMaint.OpenQueryMenuItems;
Var
s1 : String;
Begin
qryMenuItems.Active := False;
qryMenuItems.SQL.Clear;
s1 := 'SELECT * FROM MenuItem Where ProgNameID = '
+ IntToStr(iProgNameID)
+ 'Order by Description';
qryMenuItems.SQL.Add(s1);
Try
qryMenuItems.Active := True;
Except
On E: Exception Do
Begin
Error('Error opening Menu Items');
Error('Exception class name = '+E.ClassName);
Error('Exception message = '+E.Message);
End;
End;
End;
Procedure TdmoUserMaint.qryMenuItemsBeforePost(DataSet: TDataSet);
Var
FtheID : Integer;
Begin
If qryMenuItems.State in [dsInsert] Then
Begin
FtheID := GetID('MenuItemID', 'MenuItem') + 1;
qryMenuItems.FieldByName('MenuItemID').AsInteger := FtheID;
qryMenuItems.FieldByName('ProgNameID').AsInteger := iProgNameID;
End;
End;
End.
|
unit Lbledit;
interface
Uses SysUtils,StdCtrls,Classes,Buttons,Controls,ExtCtrls,Menus,
Messages,SQLCtrls,DBTables,WinTypes,TSQLCls;
Type TLabelEdit=class(TSQLControl)
protected
FOnKeyUp:TKeyEvent;
procedure WriteCaption(s:string);
Function ReadCaption:String;
procedure WriteText(s:string);
Function ReadText:String;
procedure WriteOnChange(s:TNotifyEvent);
Function ReadOnChange:TNotifyEvent;
procedure WritePC(s:boolean);
Function ReadPC:boolean;
procedure WriteRO(s:boolean);
Function ReadRO:boolean;
procedure WriteML(s:integer);
Function ReadML:integer;
procedure LEOnEnter(Sender:TObject);
public
BackUp:String;
Data:longint;
Lbl:TLabel;
Edit:TEdit;
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure WMSize(var Msg:TMessage); message WM_SIZE;
function GetHeight:integer;
procedure Value(sl:TStringList); override;
procedure SetValue(var q:TQuery); override;
procedure LEOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure LEOnExit(Sender:TObject);
published
property Caption:String read ReadCaption write WriteCaption;
property Text:String read ReadText write WriteText;
property ParentColor:boolean read ReadPC write WritePC;
property ReadOnly:boolean read ReadRO write WriteRO;
property OnChange:TNotifyEvent read ReadOnChange write WriteOnChange;
property OnKeyUp:TKeyEvent read FOnKeyUp write FOnKeyUp;
property MaxLength:integer read ReadML write WriteML;
property Align;
property DragCursor;
property DragMode;
property Enabled;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
end;
procedure Register;
implementation
function TLabelEdit.GetHeight:integer;
begin
GetHeight:=-Edit.Font.Height+13-Lbl.Font.Height
end;
destructor TLabelEdit.Destroy;
begin
Lbl.Free;
Edit.Free;
inherited Destroy
end;
constructor TLabelEdit.Create(AOwner:TComponent);
begin
FOnKeyUp:=NIL;
inherited create(AOwner);
Lbl:=TLabel.Create(self);
Edit:=TEdit.Create(self);
Lbl.Parent:=self;
Edit.Parent:=self;
Lbl.Left:=0;
Lbl.Top:=0;
Edit.Left:=0;
OnEnter:=LEOnEnter;
OnExit:=LEOnExit;
Edit.OnKeyUp:=LEOnKeyUp
end;
procedure TLabelEdit.Value(sl:TStringList);
begin
if Assigned(fValueEvent) then fValueEvent(self,sl)
else
if Visible then sl.Add(sql.MakeStr(Text))
else sl.Add('NULL')
end;
procedure TLabelEdit.SetValue(var q:TQuery);
begin
if Assigned(fSetValueEvent) then fSetValueEvent(self,q)
else
try
Text:=q.FieldByName(fFieldName).AsString;
except
end;
end;
procedure TLabelEdit.WMSize(var Msg:TMessage);
begin
Lbl.Height:=-Lbl.Font.Height+3;
Lbl.Width:=Msg.LParamLo;
Edit.Top:=Lbl.Height;
Edit.Height:=-Edit.Font.Height+10;
Edit.Width:=Msg.LParamLo;
Height:=Edit.Height+Lbl.Height;
Width:=Msg.LParamLo;
end;
procedure TLabelEdit.WriteCaption(s:String);
begin
Lbl.Caption:=s
end;
function TLabelEdit.ReadCaption:String;
begin
ReadCaption:=Lbl.Caption
end;
procedure TLabelEdit.WritePC(s:boolean);
begin
Edit.ParentColor:=s
end;
function TLabelEdit.ReadPC:boolean;
begin
ReadPC:=Edit.ParentColor
end;
procedure TLabelEdit.WriteRO(s:boolean);
begin
Edit.ReadOnly:=s
end;
function TLabelEdit.ReadRO:boolean;
begin
ReadRO:=Edit.ReadOnly
end;
procedure TLabelEdit.WriteML(s:integer);
begin
Edit.MaxLength:=s
end;
function TLabelEdit.ReadML:integer;
begin
ReadML:=Edit.MaxLength
end;
procedure TLabelEdit.WriteText(s:String);
begin
Edit.Text:=TrimRight(s)
end;
function TLabelEdit.ReadText:String;
begin
ReadText:=Edit.Text
end;
procedure TLabelEdit.WriteOnChange(s:TNotifyEvent);
begin
Edit.OnChange:=s
end;
function TLabelEdit.ReadOnChange:TNotifyEvent;
begin
ReadOnChange:=Edit.OnChange
end;
procedure Register;
begin
RegisterComponents('MyOwn',[TLabelEdit])
end;
procedure TLabelEdit.LEOnEnter(Sender:TObject);
begin
Edit.SetFocus;
BackUp:=Edit.Text
end;
procedure TLabelEdit.LEOnExit(Sender:TObject);
begin
BackUp:=Edit.Text
end;
procedure TLabelEdit.LEOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=VK_ESCAPE then
Edit.Text:=BackUp;
if Assigned(fOnKeyUp) then
fOnKeyUp(Sender, Key, Shift);
end;
end.
|
unit Constantes;
interface
Const
OPE_ESCAPE = 0 ;
OPE_INCLUSAO = 1 ;
OPE_ALTERACAO = 2 ;
OPE_EXCLUSAO = 3 ;
TAG_FIELD = -1 ;
TAG_KEY = -2 ;
// Sql
ERRO_KEYVIOLATION = 1 ;
PAGREC_STATUS_ABERTO = 'A' ;
PAGREC_STATUS_CANCELADO = 'C' ;
PAGREC_STATUS_RECEBIDO = 'R' ;
PAGREC_STATUS_PAGO = 'P' ;
// Movimentacao bancaria
MV_TIPO_CREDITO = 'C' ;
MV_TIPO_DEBITO = 'D' ;
MV_TIPO_CANCELADO = 'X' ;
// Status dos lancamentos contabeis
LC_STATUS_ABERTO = 'A' ;
LC_STATUS_ENCERRADO = 'E' ;
// Tipo de contas para fechamento
FECHA_BANCO = 'B' ;
FECHA_CONTAB = 'C' ;
// Tipos de movimentos de clientes
MOVCLI_COMPRA = 'C' ;
MOVCLI_VENDA = 'V' ;
MOVCLI_TRANSF = 'T' ;
MOVCLI_DELCOM = 'c' ;
MOVCLI_DELVEN = 'v' ;
MOVCLI_ALTCOM = 'O' ;
MOVCLI_ALTVEN = 'E' ;
// Tipos de Operacoes (OpeID )
OPEID_TRANSF = -1 ;
OPEID_PENDBR = -2 ;
implementation
end.
|
unit StateGameEnd;
interface
uses
Windows, Messages, AvL, avlUtils, OpenGL, oglExtensions, VSEOpenGLExt, VSECore;
const
SIDGameEnd = 'GameEnd';
SScores = 'Scores';
ScoresCount = 5;
type
TStateGameEnd = class(TGameState)
private
FFont, FLargeFont: Cardinal;
FHighScore: Integer;
FScores: array[0..ScoresCount - 1] of Integer;
procedure DrawLine(Font, Y: Integer; const Line: string);
protected
function GetName: string; override;
public
constructor Create;
procedure Draw; override;
function Activate: Cardinal; override;
procedure Deactivate; override;
procedure OnEvent(var Event: TCoreEvent); override;
end;
implementation
uses
VSERender2D, VSEGUI, StateMenu, StateGame
{$IFDEF VSE_CONSOLE}, VSEConsole{$ENDIF}{$IFDEF VSE_LOG}, VSELog{$ENDIF};
{TStateGameEnd}
constructor TStateGameEnd.Create;
begin
inherited Create;
FFont:=Render2D.CreateFont(UIFont, 20, false);
FLargeFont:=Render2D.CreateFont(UIFont, 40, false);
end;
procedure TStateGameEnd.Draw;
var
i: Integer;
begin
Core.GetState(Core.FindState(SIDGame)).Draw;
Render2D.Enter;
gleColor(clRed);
DrawLine(FLargeFont, 150, 'Game Over');
if FHighScore >= 0 then
DrawLine(FFont, 250, 'You have got high score!');
gleColor($80000000);
Render2D.DrawRect(310, 300, 180, 210);
gleColor(clText);
DrawLine(FFont, 300, 'Scores:');
for i := 0 to High(FScores) do
begin
if i = FHighScore then
gleColor(clRed)
else
gleColor(clText);
DrawLine(FFont, 350 + 30 * i, IntToStr(FScores[i]));
end;
Render2D.Leave;
end;
function TStateGameEnd.Activate: Cardinal;
var
Score, i, j: Integer;
begin
Result := inherited Activate;
FHighScore := -1;
Score := TStateGame(Core.GetState(Core.FindState(SIDGame))).Score;
for i := 0 to High(FScores) do
FScores[i] := Settings.Int[SScores, IntToStr(i)];
for i := 0 to High(FScores) do
if Score > FScores[i] then
begin
FHighScore := i;
for j := High(FScores) downto i + 1 do
FScores[j] := FScores[j - 1];
FScores[i] := Score;
Break;
end;
if FHighScore >= 0 then
for i := 0 to High(FScores) do
Settings.Int[SScores, IntToStr(i)] := FScores[i];
end;
procedure TStateGameEnd.Deactivate;
begin
TStateGame(Core.GetState(Core.FindState(SIDGame))).ClearBricks;
end;
procedure TStateGameEnd.OnEvent(var Event: TCoreEvent);
begin
if ((Event is TMouseEvent) and ((Event as TMouseEvent).EvType in [meDown, meUp])) or (Event is TKeyEvent) or
((Event is TSysNotify) and ((Event as TSysNotify).Notify = snMinimized)) then
Core.SwitchState(SIDMenu);
inherited;
end;
function TStateGameEnd.GetName: string;
begin
Result:=SIDGameEnd;
end;
procedure TStateGameEnd.DrawLine(Font, Y: Integer; const Line: string);
begin
Render2D.TextOut(Font, 400 - Render2D.TextWidth(Font, Line) / 2, Y, Line);
end;
end.
|
{
Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit DataGrabber.ConnectionView;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls,
Vcl.ActnList, Vcl.ExtCtrls,
Spring.Collections,
VirtualTrees,
OMultiPanel,
DataGrabber.Interfaces, DataGrabber.ConnectionProfiles;
{$REGION 'documentation'}
{
A IConnectionView instance consists of
- one editorview (IEditorView)
- one or more dataviews corresponding to the user input in the editor as
multiple datasets can be returned as a result of one statement
(IDataView).
- a list of connectionprofiles (those defined in the settings)
- an active connection profile (of the available profiles in
FSettings.ConnectionProfiles)
}
{$ENDREGION}
type
TfrmConnectionView = class(TForm, IConnectionView)
pnlMain : TOMultiPanel;
pnlTop : TPanel;
pnlVST : TPanel;
splVertical : TSplitter;
pnlTopRight : TPanel;
pnlBottom : TPanel;
procedure FVSTProfilesBeforeCellPaint(
Sender : TBaseVirtualTree;
TargetCanvas : TCanvas;
Node : PVirtualNode;
Column : TColumnIndex;
CellPaintMode : TVTCellPaintMode;
CellRect : TRect;
var ContentRect : TRect
);
procedure FVSTProfilesGetText(
Sender : TBaseVirtualTree;
Node : PVirtualNode;
Column : TColumnIndex;
TextType : TVSTTextType;
var CellText : string
);
procedure FVSTProfilesFocusChanged(
Sender : TBaseVirtualTree;
Node : PVirtualNode;
Column : TColumnIndex
);
procedure FVSTProfilesPaintText(
Sender : TBaseVirtualTree;
const TargetCanvas : TCanvas;
Node : PVirtualNode;
Column : TColumnIndex;
TextType : TVSTTextType
);
procedure FormShortCut(var Msg: TWMKey; var Handled: Boolean);
procedure FormShow(Sender: TObject);
procedure splVerticalMoved(Sender: TObject);
private
FEditorView : IEditorView;
FActiveDataView : IDataView;
FData : IData;
FVSTProfiles : TVirtualStringTree;
FDefaultNode : PVirtualNode;
FDataViewList : IList<IDataView>;
FPageControl : TPageControl;
FMultiPanel : TOMultiPanel;
FManager : IConnectionViewManager;
{$REGION 'property access methods'}
function GetManager: IConnectionViewManager;
function GetForm: TForm;
function GetData: IData;
function GetActiveDataView: IDataView;
function GetEditorView: IEditorView;
function GetActiveConnectionProfile: TConnectionProfile;
{$ENDREGION}
procedure DataAfterExecute(Sender: TObject);
procedure DataBeforeExecute(Sender: TObject);
function GetDataView(AIndex: Integer): IDataView;
protected
procedure InitializeConnectionProfilesView;
procedure Copy;
procedure UpdateActions; override;
procedure ApplySettings;
procedure UpdateActiveDataView;
function ExportAsWiki: string;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
constructor Create(
AOwner : TComponent;
AManager : IConnectionViewManager;
AData : IData
); reintroduce; virtual;
property Form: TForm
read GetForm;
property Data: IData
read GetData;
property ActiveConnectionProfile: TConnectionProfile
read GetActiveConnectionProfile;
property EditorView: IEditorView
read GetEditorView;
property ActiveDataView: IDataView
read GetActiveDataView;
property DataViews[AIndex: Integer]: IDataView
read GetDataView;
property Manager: IConnectionViewManager
read GetManager;
end;
implementation
uses
System.UITypes,
Vcl.GraphUtil,
Data.DB,
Spring, Spring.Container,
DDuce.ObjectInspector.zObjectInspector,
DDuce.Logger, DDuce.Factories.VirtualTrees,
DataGrabber.Utils, DataGrabber.Factories;
{$R *.dfm}
{$REGION 'construction and destruction'}
constructor TfrmConnectionView.Create(AOwner: TComponent;
AManager: IConnectionViewManager; AData: IData);
begin
inherited Create(AOwner);
Guard.CheckNotNull(AManager, 'AManager');
Guard.CheckNotNull(AData, 'AData');
FManager := AManager;
FData := AData;
end;
procedure TfrmConnectionView.AfterConstruction;
begin
inherited AfterConstruction;
Data.OnBeforeExecute.Add(DataBeforeExecute);
Data.OnAfterExecute.Add(DataAfterExecute);
FDataViewList := TCollections.CreateInterfaceList<IDataView>;
InitializeConnectionProfilesView;
FEditorView := TDataGrabberFactories.CreateEditorView(Self, Manager);
FEditorView.AssignParent(pnlTopRight);
ApplySettings;
pnlMain.MinPosition := 0;
pnlMain.PanelCollection[0].Position := 1;
pnlMain.SplitterSize := 0;
end;
procedure TfrmConnectionView.BeforeDestruction;
begin
if Assigned(Data) then
begin
Data.OnAfterExecute.Remove(DataAfterExecute);
Data.OnBeforeExecute.Remove(DataBeforeExecute);
end;
FEditorView := nil;
FActiveDataView := nil;
FData := nil;
FDataViewList := nil;
inherited BeforeDestruction;
end;
{$ENDREGION}
{$REGION 'event handlers'}
{$REGION 'Data'}
procedure TfrmConnectionView.DataAfterExecute(Sender: TObject);
var
I : Integer;
TS : TTabSheet;
DV : IDataView;
B : Boolean;
begin
if Assigned(FMultiPanel) then
begin
FMultiPanel.PanelCollection.Clear;
FreeAndNil(FMultiPanel);
end;
FActiveDataView := nil;
FDataViewList.Clear;
if Assigned(FPageControl) then
begin
FreeAndNil(FPageControl);
end;
B := (Manager.Settings.ResultDisplayLayout = TResultDisplayLayout.Tabbed)
and (not Data.DataEditMode);
if B then
begin
FPageControl := TPageControl.Create(Self);
FPageControl.Parent := pnlBottom;
FPageControl.Align := alClient;
FPageControl.TabPosition := tpBottom;
end
else
begin
FMultiPanel := TOMultiPanel.Create(Self);
FMultiPanel.SplitterSize := 8;
FMultiPanel.Parent := pnlBottom;
FMultiPanel.Align := alClient;
if Manager.Settings.ResultDisplayLayout = TResultDisplayLayout.Vertical then
begin
FMultiPanel.PanelType := ptHorizontal;
end
else
begin
FMultiPanel.PanelType := ptVertical;
end;
end;
if Data.MultipleResultSets and (Data.DataSetCount > 1) then
begin
for I := 0 to Data.DataSetCount - 1 do
begin
DV := TDataGrabberFactories.CreateDataView(
Self,
Manager,
Data.Items[I]
);
DV.PopupMenu := Manager.ConnectionViewPopupMenu;
FActiveDataView := DV;
if B then
begin
TS := TTabSheet.Create(FPageControl);
TS.Caption := Format('[%d]', [I]);
TS.PageControl := FPageControl;
DV.AssignParent(TS);
end
else
begin
DV.AssignParent(FMultiPanel);
end;
FDataViewList.Add(DV);
end;
end
else
begin
DV := TDataGrabberFactories.CreateDataView(
Self,
Manager,
Data.ResultSet
);
DV.PopupMenu := Manager.ConnectionViewPopupMenu;
DV.AssignParent(pnlBottom);
FActiveDataView := DV;
end;
pnlMain.SplitterSize := 8;
pnlMain.PanelCollection[0].Position := 0.2;
end;
procedure TfrmConnectionView.DataBeforeExecute(Sender: TObject);
begin
FActiveDataView := nil;
end;
{$ENDREGION}
{$REGION 'FVSTProfiles'}
procedure TfrmConnectionView.FVSTProfilesBeforeCellPaint(
Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode;
Column: TColumnIndex; CellPaintMode: TVTCellPaintMode; CellRect: TRect;
var ContentRect: TRect);
var
VST : TVirtualStringTree absolute Sender;
begin
TargetCanvas.Brush.Color :=
Manager.Settings.ConnectionProfiles[Node.Index].ProfileColor;
TargetCanvas.FillRect(CellRect);
if Sender.FocusedNode = Node then
begin
TargetCanvas.Pen.Width := 1;
TargetCanvas.Pen.Color := clBlue;
TargetCanvas.Rectangle(CellRect);
end;
end;
procedure TfrmConnectionView.FVSTProfilesFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
begin
if ContainsFocus(Self) then
ApplySettings;
end;
procedure TfrmConnectionView.FVSTProfilesGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
begin
CellText := Manager.Settings.ConnectionProfiles[Node.Index].DisplayName;
if Manager.Settings.ConnectionProfiles[Node.Index] =
(Owner as IConnectionViewManager).DefaultConnectionProfile
then
FDefaultNode := Node;
end;
procedure TfrmConnectionView.FVSTProfilesPaintText(Sender: TBaseVirtualTree;
const TargetCanvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType);
begin
if Sender.FocusedNode = Node then
begin
TargetCanvas.Font.Style := TargetCanvas.Font.Style + [fsBold];
end;
end;
{$ENDREGION}
{ Needed to allow the shortcuts of the manager's actions to be executed. }
procedure TfrmConnectionView.FormShortCut(var Msg: TWMKey;
var Handled: Boolean);
begin
Handled := True;
end;
procedure TfrmConnectionView.FormShow(Sender: TObject);
begin
FVSTProfiles.SetFocus;
if Assigned(FDefaultNode) then
begin
FVSTProfiles.FocusedNode := FDefaultNode
end
else
begin
FVSTProfiles.FocusedNode := FVSTProfiles.GetFirstVisible;
end;
EditorView.SetFocus;
end;
procedure TfrmConnectionView.splVerticalMoved(Sender: TObject);
begin
FVSTProfiles.Invalidate;
end;
{$ENDREGION}
{$REGION 'property access methods'}
function TfrmConnectionView.GetActiveConnectionProfile: TConnectionProfile;
begin
if Assigned(FVSTProfiles.FocusedNode) then
Exit(Manager.Settings.ConnectionProfiles.Items[FVSTProfiles.FocusedNode.Index])
else
Exit(nil);
end;
function TfrmConnectionView.GetData: IData;
begin
Result := FData;
end;
function TfrmConnectionView.GetDataView(AIndex: Integer): IDataView;
begin
Guard.CheckIndex(FDataViewList.Count, AIndex);
Result := FDataViewList[AIndex];
end;
function TfrmConnectionView.GetActiveDataView: IDataView;
begin
Result := FActiveDataView;
end;
function TfrmConnectionView.GetManager: IConnectionViewManager;
begin
Result := FManager;
end;
function TfrmConnectionView.GetEditorView: IEditorView;
begin
Result := FEditorView;
end;
function TfrmConnectionView.GetForm: TForm;
begin
Result := Self;
end;
{$ENDREGION}
{$REGION 'protected methods'}
function TfrmConnectionView.ExportAsWiki: string;
var
DV : IDataView;
S : string;
begin
if not FDataViewList.IsEmpty then
begin
for DV in FDataViewList do
begin
S := S + DV.ResultsToWikiTable(True);
S := S + #13#10;
end;
end;
Result := S;
end;
procedure TfrmConnectionView.InitializeConnectionProfilesView;
begin
FVSTProfiles := TVirtualStringTreeFactory.CreateGrid(Self, pnlVST);
FVSTProfiles.AlignWithMargins := False;
FVSTProfiles.RootNodeCount := Manager.Settings.ConnectionProfiles.Count;
FVSTProfiles.OnBeforeCellPaint := FVSTProfilesBeforeCellPaint;
FVSTProfiles.OnGetText := FVSTProfilesGetText;
FVSTProfiles.OnFocusChanged := FVSTProfilesFocusChanged;
FVSTProfiles.OnPaintText := FVSTProfilesPaintText;
FVSTProfiles.Header.Options := FVSTProfiles.Header.Options - [hoVisible];
FVSTProfiles.TreeOptions.PaintOptions := FVSTProfiles.TreeOptions.PaintOptions
- [toHideSelection, toUseExplorerTheme, toHotTrack];
FVSTProfiles.Colors.FocusedSelectionColor := clBtnHighlight;
FVSTProfiles.Margins.Right := 0;
FVSTProfiles.Indent := 0;
FVSTProfiles.Alignment := taCenter;
FVSTProfiles.Constraints.MinWidth := 150;
FVSTProfiles.Constraints.MinHeight := 100;
FVSTProfiles.Constraints.MaxWidth := 300;
end;
procedure TfrmConnectionView.ApplySettings;
var
CP: TConnectionProfile;
begin
FVSTProfiles.RootNodeCount := Manager.Settings.ConnectionProfiles.Count;
FVSTProfiles.Refresh;
if FVSTProfiles.RootNodeCount > 0 then
begin
if not Assigned(FVSTProfiles.FocusedNode) then
begin
FVSTProfiles.FocusedNode := FVSTProfiles.GetFirst;
end;
CP := Manager.Settings.ConnectionProfiles.Items[
FVSTProfiles.FocusedNode.Index
];
Application.Title := CP.Name;
Caption := CP.Name;
FEditorView.Color := ColorAdjustLuma(CP.ProfileColor, 25, True);
Data.ConnectionSettings.Assign(CP.ConnectionSettings);
end;
end;
procedure TfrmConnectionView.Copy;
begin
if EditorView.EditorFocused then
EditorView.CopyToClipboard
else
ActiveDataView.Copy;
end;
procedure TfrmConnectionView.UpdateActions;
begin
inherited UpdateActions;
if ContainsFocus(Self) then
begin
if Manager.ActiveConnectionView <> (Self as IConnectionView) then
begin
Manager.ActiveConnectionView := Self;
EditorView.SetFocus;
end;
Manager.UpdateActions;
if Assigned(FActiveDataView) and not FActiveDataView.IsActiveDataView then
UpdateActiveDataView;
end;
end;
procedure TfrmConnectionView.UpdateActiveDataView;
var
DV : IDataView;
begin
for DV in FDataViewList do
begin
if DV.IsActiveDataView then
FActiveDataView := DV;
end;
end;
{$ENDREGION}
end.
|
unit untInifilehelper;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IniFiles, Dialogs;
type
{ IniFileHelper }
TIniFileHelper = class
private
iniFile: TIniFile;
strLocalDatabasePath: string;
nFingerReadInterval: integer;
strRemoteDatabaseIp: string;
nRemoteDatabasePort: word;
strSoundsPath:string;
public
constructor IniFileHelper;
destructor Destroy;
function GetValue(Key: string): string;
function SetValue(key: string; Value: string): boolean;
procedure SaveSettings;
end;
implementation
{ IniFileHelper }
destructor TIniFileHelper.Destroy;
begin
iniFile.Free;
end;
constructor TIniFileHelper.IniFileHelper;
begin
iniFile := TIniFile.Create('system.ini');
strLocalDatabasePath := iniFile.ReadString('LocalDatabase', 'Path', 'panel.db');
nFingerReadInterval := iniFile.ReadInteger('DatabaseProcess',
'FingerPrintReadInterval', 2000);
strRemoteDatabaseIP := iniFile.ReadString('DatabaseProcess',
'RemoteDatabaseIp', '127.0.0.1');
nRemoteDatabasePort := iniFile.ReadInteger('DatabaseProcess',
'RemoteDatabasePort', 2000);
strSoundsPath := iniFile.ReadString('Others',
'SoundsPath', '\NANDFlash\Destap\Sounds');
end;
function TIniFileHelper.GetValue(Key: string): string;
begin
if (Key = 'LocalDatabasePath') then
begin
Result := strLocalDatabasePath;
end
else if Key = 'FingerPrintReadInterval' then
begin
Result := IntToStr(nFingerReadInterval);
end
else if Key = 'RemoteDatabaseIp' then
begin
Result := strRemoteDatabaseIp;
end
else if Key = 'RemoteDatabasePort' then
begin
Result := IntToStr(nRemoteDatabasePort);
end
else if Key= 'SoundsPath' then
begin
Result:=strSoundsPath;
end
else
Result := '';
end;
function TIniFileHelper.SetValue(key: string; Value: string): boolean;
begin
if (Key = 'LocalDatabasePath') then
begin
strLocalDatabasePath := Value;
end
else if Key = 'FingerPrintReadInterval' then
begin
nFingerReadInterval := StrToInt(Value);
end
else if Key = 'RemoteDatabaseIp' then
begin
strRemoteDatabaseIp := Value;
end
else if Key = 'RemoteDatabasePort' then
begin
nRemoteDatabasePort := StrToInt(Value);
end
else if Key= 'SoundsPath' then
begin
strSoundsPath:=Value;
end;
end;
procedure TIniFileHelper.SaveSettings;
begin
iniFile.WriteString('LocalDatabase', 'Path', strLocalDatabasePath);
iniFile.WriteInteger('DatabaseProcess', 'FingerPrintReadInterval',
nFingerReadInterval);
iniFile.WriteString('DatabaseProcess', 'RemoteDatabaseIp', strRemoteDatabaseIp);
iniFile.WriteInteger('DatabaseProcess', 'RemoteDatabasePort', nRemoteDatabasePort);
iniFile.WriteString('Others','SoundsPath', strSoundsPath );
end;
end.
|
unit PictureSampleMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
XLSReadWriteII, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
btnWrite: TButton;
XLS: TXLSReadWriteII;
procedure Button1Click(Sender: TObject);
procedure btnWriteClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.btnWriteClick(Sender: TObject);
begin
XLS.Clear;
// Add a sheet. There are two sheets now.
XLS.Sheets.Add;
XLS.Sheets[0].Name := 'Sheet1';
XLS.Sheets[1].Name := 'Sheet2';
XLS.Filename := 'PictureSample.xls';
// Add two pictures.
with XLS.Pictures.Add do begin
Filename := 'pig.jpg';
Width := 250;
Height := 167;
end;
with XLS.Pictures.Add do begin
Filename := 'snow.jpg';
Width := 300;
Height := 200;
end;
// Insert a pig on the first sheet.
with XLS.Sheets[0].SheetPictures.Add do begin
Col := 2;
Row := 1;
PictureName := 'pig.jpg';
end;
// Insert a smaller pig...
with XLS.Sheets[0].SheetPictures.Add do begin
Col := 2;
Row := 14;
Zoom := 50;
PictureName := 'pig.jpg';
end;
// Insert another picture on the second sheet.
with XLS.Sheets[1].SheetPictures.Add do begin
Col := 2;
Row := 5;
PictureName := 'snow.jpg';
end;
XLS.Write;
end;
end.
|
unit ExceptionHandle;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, ExtCtrls, ComCtrls, StdCtrls, Buttons;
type
Tfrm_Exception = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
edt_Exceptionclass: TEdit;
edt_SourceClass: TEdit;
mm_ExceptionMsg: TMemo;
btn_OK: TBitBtn;
Image1: TImage;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
function GetExceptionClass: String;
procedure SetExceptionClass(const Value: String);
procedure SetExceptionMsg(const Value: String);
procedure SetSourceClass(const Value: string);
function GetSourceClass: string;
function GetExceptionMsg: String;
{ Private declarations }
public
property ExceptionClass: String read GetExceptionClass write SetExceptionClass;
property SourceClass: string read GetSourceClass write SetSourceClass;
property ExceptionMsg: String read GetExceptionMsg write SetExceptionMsg;
end;
var
frm_Exception: Tfrm_Exception;
implementation
{$R *.dfm}
procedure Tfrm_Exception.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure Tfrm_Exception.FormShow(Sender: TObject);
begin
MessageBeep(16);
end;
function Tfrm_Exception.GetExceptionClass: String;
begin
Result := self.edt_Exceptionclass.Text;
end;
function Tfrm_Exception.GetExceptionMsg: String;
begin
Result := mm_ExceptionMsg.Text;
end;
function Tfrm_Exception.GetSourceClass: string;
begin
Result := edt_Sourceclass.Text;
end;
procedure Tfrm_Exception.SetExceptionClass(const Value: String);
begin
edt_ExceptionClass.Text := Value;
end;
procedure Tfrm_Exception.SetExceptionMsg(const Value: String);
begin
mm_ExceptionMsg.text := Value;
end;
procedure Tfrm_Exception.SetSourceClass(const Value: string);
begin
edt_SourceClass.text := Value;
end;
end.
|
unit Relation;
interface
uses
Classes, Types, OpElement, WriterIntf;
type
TRelation = class(TOpElement)
private
FInverse: Boolean;
FDereference: Boolean;
public
procedure GetDCPUSource(AWriter: IWriter); override;
property Inverse: Boolean read FInverse write FInverse;
property Dereference: Boolean read FDereference write FDereference;
end;
implementation
uses
CodeElement, StrUtils;
{ TRelation }
procedure TRelation.GetDCPUSOurce;
var
i: Integer;
LTrue, LFalse: string;
begin
for i := 0 to SubElements.Count - 1 do
begin
SubElements.Items[i].GetDCPUSource(AWriter);
if i > 0 then
begin
LTrue := '0xffff';
LFalse := '0';
if (i = SubElements.Count - 1) and Inverse then
begin
LTrue := '0';
LFalse := '0xffff';
end;
AWriter.Write('set z, pop');
AWriter.Write('set y, pop');
AWriter.Write('set x, ' + LFalse);
AWriter.Write(Operations.Items[i-1].GetAssembly(['y', 'z', 'x', LTrue, LFalse]));
AWriter.Write('set x, ' + LTrue);
AWriter.Write('set push, x');
end;
end;
if Dereference then
begin
AWriter.Write('set x, pop');
AWriter.Write('set x, [x]');
AWriter.Write('set push, x');
end;
if (SubElements.Count = 1) and Inverse then
begin
AWriter.Write('set x, pop');
AWriter.Write('xor x, 0xffff');
AWriter.Write('set push, x');
end;
end;
end.
|
unit PWEditInfoWellBinding;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DialogForm, ImgList, ActnList, FramesWizard, ComCtrls, ToolWin;
type
TfrmEditInfoWellBinding = class(TCommonDialogForm)
private
protected
function GetEditingObjectName: string; override;
procedure NextFrame(Sender: TObject); override;
procedure FinishClick(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
frmEditInfoWellBinding: TfrmEditInfoWellBinding;
implementation
{$R *.dfm}
uses PWInfoWellBindingFrame, Well, ReasonChange, Facade;
{ TCommonDialogForm1 }
constructor TfrmEditInfoWellBinding.Create(AOwner: TComponent);
begin
inherited;
dlg.AddFrame(TfrmWellBinding);
dlg.ActiveFrameIndex := 0;
dlg.FinishEnableIndex := 0;
Caption := 'Редактор привязочной информации по скважине';
dlg.OnFinishClick := FinishClick;
Height := 580;
Width := 710;
end;
destructor TfrmEditInfoWellBinding.Destroy;
begin
inherited;
end;
procedure TfrmEditInfoWellBinding.FinishClick(Sender: TObject);
var w: TWell;
begin
try
w := EditingObject as TWell;
Save;
w.LastModifyDate := Date;
w.Update;
w.WellPosition.Update;
w.WellOrgStatuses.Update(w.WellOrgStatuses);
ShowMessage('Изменения успешно сохранены.');
except
end;
end;
function TfrmEditInfoWellBinding.GetEditingObjectName: string;
begin
Result := 'Скважина';
end;
procedure TfrmEditInfoWellBinding.NextFrame(Sender: TObject);
begin
inherited;
end;
end.
|
{ p_40_2 - полицейская база данных с применением массива }
program p_40_2;
const cNumbers = 1000; { размер массива с номерами автомобилей }
type tNumbers = array[1..cNumbers] of integer;
var numbers: tNumbers; { массив номеров }
fact: integer; { фактическое количество номеров в файле }
f: text; { файл с номерами }
num: integer; { номер проверяемого автомобиля }
{ Процедура ввода номеров из файла }
procedure ReadFromFile(var aFile: text);
var i: integer;
begin
fact := 0;
for i:=1 to cNumbers do begin
while Eoln(aFile) do
if Eof(aFile) then Break
else Readln(aFile);
if Eof(aFile) then Break;
Read(aFile, numbers[i]);
fact := fact + 1;
end;
end;
{ Функция поиска в массиве номеров автомобилей }
function FindNumber(aNum: integer): boolean;
var i: integer; { текущий номер в БД }
begin
FindNumber := false; { на случай, если файл пуст }
{ читаем номера из файла, пока НЕ конец файла И номер НЕ найден }
for i:=1 to fact do
if aNum=numbers[i] then begin
FindNumber := true;
Break;
end;
end;
{----- главная программа -----}
begin
Assign(f, 'p_38_2_in.txt');
Reset(f);
{ ввод номеров из файла }
ReadFromFile(f);
Close(f);
{главный цикл}
repeat
Write('Укажите номер автомобиля: ');
Readln(num);
if FindNumber(num)
then Writeln('Эта машина в розыске, хватайте его!')
else Writeln('Пропустите его');
until num=0; { 0 - признак завершения программы }
end.
|
unit IncludeHandler;
interface
uses
System.Classes,
System.SysUtils,
System.IOUtils,
SimpleParser.Lexer.Types;
type
TIncludeHandler = class(TInterfacedObject, IIncludeHandler)
private
FPath: string;
public
constructor Create(const Path: string);
function GetIncludeFileContent(const ParentFileName, IncludeName: string;
out Content: string; out FileName: string): Boolean;
end;
implementation
constructor TIncludeHandler.Create(const Path: string);
begin
inherited Create;
FPath := Path;
end;
function TIncludeHandler.GetIncludeFileContent(const ParentFileName, IncludeName: string;
out Content: string; out FileName: string): Boolean;
var
FileContent: TStringList;
begin
FileContent := TStringList.Create;
try
if not FileExists(TPath.Combine(FPath, IncludeName)) then
begin
Result := False;
Exit;
end;
FileContent.LoadFromFile(TPath.Combine(FPath, IncludeName));
Content := FileContent.Text;
FileName := TPath.Combine(FPath, IncludeName);
Result := True;
finally
FileContent.Free;
end;
end;
end.
|
unit Metrics.ClassM;
interface
uses
System.SysUtils,
System.Generics.Collections,
System.Generics.Defaults,
{--}
Metrics.ClassMethod;
type
TClassMetrics = class
private
fUnitFullPath: string;
fNameOfClass: string;
fNameOfUnit: string;
fClassMethods: TObjectList<TClassMethodMetrics>;
public
constructor Create(const aUnitFullPath: string; const aNameOfClass: string);
destructor Destroy; override;
{ }
procedure AddClassMethod(aVisibility: TVisibility; const aName: string);
function MethodCount: Integer;
function GetMethod(const aIdx: Integer): TClassMethodMetrics;
function GetMethods(): TArray<TClassMethodMetrics>;
function GetMethodsSorted: TArray<TClassMethodMetrics>;
{ }
property UnitFullPath: string read fUnitFullPath;
property NameOfClass: string read fNameOfClass;
property NameOfUnit: string read fNameOfUnit;
end;
implementation
constructor TClassMetrics.Create(const aUnitFullPath, aNameOfClass: string);
begin
fUnitFullPath := aUnitFullPath;
fNameOfClass := aNameOfClass;
fNameOfUnit := ExtractFileName(fUnitFullPath);
fClassMethods := TObjectList<TClassMethodMetrics>.Create;
end;
destructor TClassMetrics.Destroy;
begin
fClassMethods.Free;
inherited;
end;
procedure TClassMetrics.AddClassMethod(aVisibility: TVisibility;
const aName: string);
begin
fClassMethods.Add(TClassMethodMetrics.Create(aVisibility, aName));
end;
function TClassMetrics.GetMethod(const aIdx: Integer): TClassMethodMetrics;
begin
Result := fClassMethods[aIdx];
end;
function TClassMetrics.GetMethods: TArray<TClassMethodMetrics>;
begin
Result := fClassMethods.ToArray;
end;
function TClassMetrics.GetMethodsSorted: TArray<TClassMethodMetrics>;
var
classMethodMetricsList: TList<TClassMethodMetrics>;
begin
classMethodMetricsList := TList<TClassMethodMetrics>.Create();
try
classMethodMetricsList.AddRange(fClassMethods);
classMethodMetricsList.Sort(TComparer<TClassMethodMetrics>.Construct(
function(const Left, Right: TClassMethodMetrics): Integer
begin
Result := TComparer<string>.Default.Compare(Left.Name.ToUpper,
Right.Name.ToUpper)
end));
Result := classMethodMetricsList.ToArray;
finally
classMethodMetricsList.Free;
end;
end;
function TClassMetrics.MethodCount: Integer;
begin
Result := fClassMethods.Count;
end;
end.
|
(*
@abstract( Similaire TBZCustomBitmapScanner, mais spécialisé dans le rendu
de "Shader" alla GLSL mais en software via TBZBitmap.)
--------------------------------------------------------------------------------
@created(2018-07-11)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(09/02/2018 : Creation)
)
--------------------------------------------------------------------------------
@bold(Notes) :
--------------------------------------------------------------------------------
@bold(Dependances) : BZClasses, BZVectorMath, BZColors, BZGraphic, BZBitmap, BZCustomShader, BZParallelThread
--------------------------------------------------------------------------------
@bold(Credits :)
@unorderedList(
@item (basé sur GLScene http://www.sourceforge.net/glscene))
@item(J.Delauney (BeanzMaster))
)
--------------------------------------------------------------------------------
@bold(LICENCE) : MPL / GPL
-------------------------------------------------------------------------------- *)
unit BZBitmapRasterizer; //BZBitmapShaderRasterizer
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\bzscene_options.inc}
//------------------------
{$ALIGN 16}
{$CODEALIGN CONSTMIN=16}
{$CODEALIGN LOCALMIN=16}
{$CODEALIGN VARMIN=16}
//------------------------
//==============================================================================
interface
uses
Classes, SysUtils, dialogs, syncobjs,
BZClasses, BZVectorMath, BZColors, BZGraphic, BZBitmap, BZCustomShader,
BZParallelThread;
Type
{ Paramètres du SHader sofware }
TBZRasterizerParameters = packed record
StartX, EndX : LongWord;
DeltaProgress : Single;
Surface : TBZBitmap;
// Shader : TBZShader;
// Area : TBZRect;
end;
{ Pointeur vers un TBZRasterizerParameters}
PBZRasterizerParameters = ^TBZRasterizerParameters;
{ Classe de base à hériter pour le rendu de shader en software dans un TBZBitmap }
TBZCustomBitmapRasterizer = class(TBZProgressAbleObject)
private
{$CODEALIGN RECORDMIN=16}
FShader : TBZCustomSoftwareShader;
{$CODEALIGN RECORDMIN=4}
procedure SetShader(AValue: TBZCustomSoftwareShader);
protected
procedure DoRasterize(Dst: TBZBitmap; DstRect: TBZRect); virtual; abstract;
procedure InternalRasterize(Dst: TBZBitmap); overload;
procedure InternalRasterize(Dst: TBZBitmap; const DstRect: TBZRect); overload;
public
constructor Create; override;
procedure Assign(Source: TPersistent); override;
procedure Rasterize;virtual;abstract;
published
property Shader : TBZCustomSoftwareShader read FShader Write SetShader;
end;
{Classe spécialisée dans le rendu de shader en software }
TBZBitmapShaderRasterizer = Class(TBZCustomBitmapRasterizer)
private
FUpdateRowCount: Integer;
//FTextureSamples : Array of TBZBitmap
//FTextureCount : Integer;
FBuffer: TBZBitmap;
//CS : TCriticalSection;
procedure SetBuffer(Const AValue: TBZBitmap);
protected
FInternalRCI : PBZRenderingContextInfos;
procedure DoRasterizeLineProc(Sender: TObject; Index: Integer ; Data : Pointer);
procedure DoRasterize(Dst: TBZBitmap; DstRect: TBZRect); override;
public
constructor Create; override;
Destructor Destroy; override;
procedure Rasterize;override;
property UpdateRowCount: Integer read FUpdateRowCount write FUpdateRowCount;
published
property Shader;
property Buffer:TBZBitmap read FBuffer Write SetBuffer;
end;
{ Paramètres pour le rendu dans les threads }
TBZThreadShaderSettings = packed record
Shader : TBZCustomSoftwareShader;
Area : TBZRect;
Buffer : TBZBitmap;
end;
{ Liste de paramètres pour les threads (Max 4)}
TBZRasterShaderRenders = array[0..3] of TBZThreadShaderSettings;
{Classe spécialisée dans le rendu de shader en software. @br
@bold(Note) : Afin d'optimiser la vitesse du rendu, celui s'effectue dans des threads}
TBZBitmapShaderThreadRasterizer = class(TBZBitmapShaderRasterizer)
private
FRenderThreads : Array [0..3] of TBZThreadShaderSettings;
protected
procedure DoRasterizeProc(Sender: TObject; Index: Integer ; Data : Pointer);
procedure MergeBitmapToBuffer(aBmp :TBZBitmap; aRect : TBZRect);
public
constructor Create(aBuffer : TBZBitmap; aShader:TBZCustomSoftwareShader);reintroduce;
Destructor Destroy;Override;
procedure Rasterize;override;
published
property Shader;
property Buffer;
end;
implementation
uses BZLogger;
{%region%=====[ TBZBitmapShaderThreadRasterizer ]==============================}
constructor TBZBitmapShaderThreadRasterizer.Create(aBuffer : TBZBitmap; aShader : TBZCustomSoftwareShader);
Var
i : Byte;
w,h : Integer;
begin
inherited Create;
Buffer := aBuffer;
Shader := aShader;
w := Buffer.Width div 2;
h := Buffer.Height div 2;
FInternalRCI^.ViewPortSize.Create(Buffer.Width, Buffer.Height);
For i := 0 to 3 do
begin
FRenderThreads[i].Shader := aShader.Clone;
FRenderThreads[i].Buffer := TBZBitmap.Create(w,h);
Case i of
0 : FRenderThreads[0].Area.Create(0, 0, w-1, h-1);
1 : FRenderThreads[1].Area.Create(w, 0, Buffer.MaxWidth, h-1);
2 : FRenderThreads[2].Area.Create(0, h, w-1, Buffer.MaxHeight);
3 : FRenderThreads[3].Area.Create(w, h, Buffer.MaxWidth, Buffer.MaxHeight);
end;
end;
end;
Destructor TBZBitmapShaderThreadRasterizer.Destroy;
var
i : byte;
begin
For i := 3 downto 0 do
begin
FreeAndNil(FRenderThreads[i].Buffer);
FreeAndNil(FRenderThreads[i].Shader);
end;
inherited Destroy;
end;
procedure TBZBitmapShaderThreadRasterizer.DoRasterizeProc(Sender : TObject; Index : Integer; Data : Pointer);
var
MaxS, LineWidth, i,xx,yy,
mw,mh,hh,th :Longword;
C : TBZColor;
DstPix : PBZColor;
OutColor : TBZColor;
//{$CODEALIGN VARMIN=16}
//cv : TBZColorVector;
//{$CODEALIGN VARMIN=4}
begin
// GlobalLogger.LogStatus('TBZBitmapShaderThreadRasterizer.DoRasterizeProc : ' + Index.ToString);
// GlobalLogger.LogStatus('Area = ' + TBZRasterShaderRenders(Data^)[Index].Area.ToString);
xx := TBZRasterShaderRenders(Data^)[Index].Area.Left;
yy := TBZRasterShaderRenders(Data^)[Index].Area.Bottom;
// TODO : A placer dans vars globales
mh := TBZRasterShaderRenders(Data^)[Index].Area.Height;
th := mh-1;
mw := TBZRasterShaderRenders(Data^)[Index].Area.Width;
Maxs := mw*mh-1;
hh := FInternalRCI^.ViewPortSize.Height - 1;
i := 0;
TBZRasterShaderRenders(Data^)[Index].Shader.Apply(FInternalRCI,nil);
DstPix := TBZRasterShaderRenders(Data^)[Index].Buffer.GetScanLine(th);
While (i<=MaxS) do
begin
TBZRasterShaderRenders(Data^)[Index].Shader.FragCoords.Create(xx,hh-yy);
OutColor := TBZRasterShaderRenders(Data^)[Index].Shader.ShadePixel;
DstPix^:= OutColor;
inc(xx);
if (xx<=TBZRasterShaderRenders(Data^)[Index].Area.Right) then
begin
inc(DstPix);
end
else
begin
dec(yy);
xx:=TBZRasterShaderRenders(Data^)[Index].Area.Left;
Dec(th);
DstPix := TBZRasterShaderRenders(Data^)[Index].Buffer.GetScanLine(th);
end;
inc(i);
end;
TBZRasterShaderRenders(Data^)[Index].Shader.UnApply(FInternalRCI);
end;
procedure TBZBitmapShaderThreadRasterizer.MergeBitmapToBuffer(aBmp : TBZBitmap; aRect : TBZRect);
begin
Buffer.CopyBlock(aBmp, 0,0, aRect.Width, aRect.Height, aRect.Left, aRect.Top);
end;
procedure TBZBitmapShaderThreadRasterizer.Rasterize;
Var
i : Byte;
begin
ParallelFor(0,3,@DoRasterizeProc, @FRenderThreads);
For i := 0 to 3 do
begin
MergeBitmapToBuffer(FRenderThreads[i].Buffer, FRenderThreads[i].Area);
end;
end;
{%endregion%}
{%region%=====[ TBZCustomBitmapRasterizer ]====================================}
constructor TBZCustomBitmapRasterizer.Create;
begin
inherited Create;
FShader := nil;
end;
procedure TBZCustomBitmapRasterizer.SetShader(AValue: TBZCustomSoftwareShader);
begin
if FShader=AValue then Exit;
FShader:=AValue;
end;
procedure TBZCustomBitmapRasterizer.Assign(Source: TPersistent);
begin
if (Source is TBZCustomBitmapRasterizer) then
begin
inherited Assign(Source);
FShader := TBZCustomBitmapRasterizer(Source).Shader;
end
else inherited Assign(Source);
end;
procedure TBZCustomBitmapRasterizer.InternalRasterize(Dst: TBZBitmap);
begin
// GLobalLogger.LogNotice('TBZCustomBitmapRasterizer.InternalRasterize');
InternalRasterize(Dst,Dst.ClipRect);
end;
procedure TBZCustomBitmapRasterizer.InternalRasterize(Dst: TBZBitmap;const DstRect: TBZRect);
begin
DoRasterize(Dst,DstRect);
end;
{%endregion%}
{%region%=====[ TBZBitmapShaderRasterizer ]====================================}
constructor TBZBitmapShaderRasterizer.Create;
begin
inherited Create;
GetMem(FInternalRCI, Sizeof(TBZRenderingContextInfos));
FInternalRCI^.ViewPortSize.Create(0,0);
FInternalRCI^.Scene := nil;
FInternalRCI^.Engine := nil;
//FBuffer:=TBZBitmap.Create;
end;
destructor TBZBitmapShaderRasterizer.Destroy;
begin
//FreeAndNil(FBuffer);
FreeMem(FInternalRCI);
//FInternalRCI := nil;
Inherited Destroy;
end;
procedure TBZBitmapShaderRasterizer.Rasterize;
begin
//InternalRasterize(FBuffer, FBuffer.ClipRect);
DoRasterize(FBuffer, FBuffer.ClipRect);
end;
procedure TBZBitmapShaderRasterizer.SetBuffer(const AValue : TBZBitmap);
begin
if FBuffer=AValue then Exit;
//FBuffer.Assign(AValue);
FBuffer := AValue;
//ShowMessage('FBuffer : '+inttostr(FBuffer.Width)+', '+inttostr(FBuffer.Height));
//PBZRenderingContextInfos(@FInternalRCI)^.ViewPortSize.Create(FBuffer.Width,FBuffer.Height);
PBZRenderingContextInfos(@FInternalRCI)^.ViewPortSize.X:=FBuffer.Width;
PBZRenderingContextInfos(@FInternalRCI)^.ViewPortSize.Y:=FBuffer.Height;
end;
procedure TBZBitmapShaderRasterizer.DoRasterizeLineProc(Sender : TObject; Index : Integer; Data : Pointer);
Var
DstPix : PBZColor;
i, x, xx : LongWord;
{$CODEALIGN VARMIN=16}
cv : TBZColorVector;
{$CODEALIGN VARMIN=4}
OutColor : TBZColor;
begin
X := PBZRasterizerParameters(Data)^.StartX;
XX := PBZRasterizerParameters(Data)^.EndX;
DstPix := PBZRasterizerParameters(Data)^.Surface.GetPixelPtr(X ,PBZRasterizerParameters(Data)^.Surface.MaxHeight - Index);
//While (X <= XX) do
//cs.Acquire;
for i:= x to xx do
begin
FShader.FragCoords.Create(i,Index);
//cv := FShader.ShadePixel;
OutColor:= FShader.ShadePixel;
// need Renormalize RED to 0..1. RED is on X axis (coords go from -1.0 to 1.0). Not need for y
//if cv.Red <0 then cv.Red := -cv.Red; // div -1.0;
//OutColor.Create(cv);
//if OutColor.Alpha > 0 then
DstPix^:= OutColor; //FShader.ShadePixel; //
//Inc(X);
Inc(DstPix);
end;
//cs.Release;
//AdvanceProgress(PBZRasterizerParameters(Data)^.DeltaProgress,0,1,False);
end;
procedure TBZBitmapShaderRasterizer.DoRasterize(Dst: TBZBitmap;DstRect: TBZRect);
var
MaxS, LineWidth, i,xx,yy,
mw,mh :Longword;
C : TBZColor;
MultiPass : Boolean;
DstPix : PBZColor;
Delta : Single;
{$CODEALIGN VARMIN=16}
cv : TBZColorVector;
{$CODEALIGN VARMIN=4}
RasterizerParams : PBZRasterizerParameters;
begin
//GLobalLogger.LogNotice('TBZCustomBitmapRasterizer.Rasterize');
//GlobalLogger.Log('Raster Dest Rect : '+inttostr(DstRect.Left)+', '+inttostr(DstRect.Top)+', '+inttostr(DstRect.Right)+', '+inttostr(DstRect.Bottom));
if not(FShader.Enabled) then exit;
Multipass := False;
//xx := DstRect.Left;
//yy := DstRect.Bottom;
//mh := DstRect.Height;
//mw := (DstRect.Width);
//LineWidth := (DstRect.Right+1) - mw;
RasterizerParams := nil;
GetMem(RasterizerParams, Sizeof(TBZRasterizerParameters));
RasterizerParams^.StartX := DstRect.Left;
RasterizerParams^.EndX := DstRect.Right;
//RasterizerParams^.DeltaProgress := 100 / mh;
RasterizerParams^.Surface := Dst;
//InitProgress(mw,mh);
//StartProgressSection(0, 'Calcul de l''image : '); // On debute une nouvelle section globale
//Delta := 100 / mh;
//StartProgressSection(100 ,'Calcul de l''image : ');
i := 0;
DstPix := Dst.GetPixelPtr(DstRect.Left,DstRect.Top);
//PBZRenderingContextInfos(@FInternalRCI)^.ViewPortSize.X:=Dst.Width;
//PBZRenderingContextInfos(@FInternalRCI)^.ViewPortSize.Y:=Dst.Height;
FShader.Apply(FInternalRCI,nil);
// MaxS := (PBZRenderingContextInfos(@FInternalRCI)^.ViewPortSize.Width
// * PBZRenderingContextInfos(@FInternalRCI)^.ViewPortSize.Height)-1;
// globallogger.LogNotice('DstRect = ' + DstRect.ToString);
ParallelFor(DstRect.Top,DstRect.Bottom,@DoRasterizeLineProc, Pointer(RasterizerParams));
// Maxs := mw*mh-1;
// While (MultiPass=true) do
// begin
//While i<=MaxS do
//begin
// //FShader.FragCoords.Create(xx,dstRect.Height-yy);
// FShader.FragCoords.Create(xx,yy);
//
// // cv := FShader.ShadePixelFloat;
//
// // need Renormalize RED to 0..1. RED is on X axis (coords go from -1.0 to 1.0)
// // not need for y
// //if cv.Red <0 then cv.Red := -cv.Red; // div -1.0;
// //if cv.Green <0 then cv.Green := cv.Green / -1.0;
// //if cv.Blue <0 then cv.Blue := cv.Blue / -1.0;
// //if cv.Alpha <0 then cv.Alpha := cv.Alpha / -1.0;
//
// //C.Create(cv);
// //if c<>clrTransparent then
// DstPix^:= FShader.ShadePixel; // C;
// inc(xx);
// if xx<=DstRect.Right then inc(DstPix)
// else
// begin
// dec(yy);
// xx:=DstRect.Left;
// //if LineWidth>0 then
// //begin
// // Inc(DstPix, LineWidth);
// //End
// //else
// inc(DstPix) ;
// //AdvanceProgress(Delta,0,1,False);
// end;
// inc(i);
//end;
//MultiPass := FShader.UnApply(FInternalRCI);
//end;
FreeMem(RasterizerParams);
//RasterizerParams := nil;
//FinishProgressSection(False);
//FinishProgressSection(True);
end;
{%endregion%}
end.
|
{
This file is part of the FastPlaz package.
(c) Luri Darmawan <luri@fastplaz.com>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
}
unit string_helpers;
{$mode objfpc}{$H+}
{$modeswitch typehelpers}
interface
uses
common, RegExpr,
Classes, SysUtils;
type
{ TStringSmartHelper }
TStringSmartHelper = type helper(TStringHelper) for AnsiString
public
function AsDateTime: TDateTime; overload; inline;
function AsInteger: Integer; overload; inline;
function UrlEncode: AnsiString; overload; inline;
function UrlDecode: AnsiString; overload; inline;
function EscapeString: AnsiString; overload; inline;
function Explode( ADelimiter:string = ','): TStrings; overload; inline;
function IsEmpty: boolean; overload; inline;
function IsNotEmpty: boolean; overload; inline;
function IsEqualTo( AString: string): boolean; overload; inline;
function IsExists( AString: string): boolean; overload; inline;
function IsJson: boolean; overload; inline;
function IsNumeric: boolean; overload; inline;
function IsEmail: boolean; overload; inline;
function IsURL: boolean; overload; inline;
function IsDomain: boolean; overload; inline;
function Encode64: AnsiString; overload; inline;
function Decode64: AnsiString; overload; inline;
function Cut( AStartText, AStopText: string):AnsiString; overload; inline;
function SaveToFile( AFileName: string): boolean; overload; inline;
function Has( AText: string): boolean; overload; inline;
function UcWords: AnsiString; overload; inline;
function IsPregMatch( ARegex: string): boolean; overload; inline;
function Split( ADelimiter:string = ','): TStrings; overload; inline;
function StrPos( AText: string): integer; overload; inline;
end;
implementation
function TStringSmartHelper.AsDateTime: TDateTime;
var
tmpFormatSettings: TFormatSettings;
begin
tmpFormatSettings := FormatSettings;
tmpFormatSettings.DateSeparator := '-';
tmpFormatSettings.ShortDateFormat := 'yyyy-MM-dd hh:nn:ss';
Result := StrToDateTime( Self, tmpFormatSettings);
end;
function TStringSmartHelper.AsInteger: Integer;
begin
Result := s2i(Self);
end;
function TStringSmartHelper.UrlEncode: AnsiString;
begin
Result := common.UrlEncode(Self);
end;
function TStringSmartHelper.UrlDecode: AnsiString;
begin
Result := common.UrlDecode(Self);
end;
function TStringSmartHelper.EscapeString: AnsiString;
begin
Result := mysql_real_escape_string(Self);
end;
function TStringSmartHelper.Explode(ADelimiter: string): TStrings;
begin
Result := common.Explode(Self, ADelimiter);
end;
function TStringSmartHelper.IsEmpty: boolean;
begin
Result := IsNullOrEmpty( Self);
end;
function TStringSmartHelper.IsNotEmpty: boolean;
begin
Result := not IsNullOrEmpty( Self);
end;
function TStringSmartHelper.IsEqualTo(AString: string): boolean;
begin
Result := Self.Equals( AString);
end;
function TStringSmartHelper.IsExists(AString: string): boolean;
begin
Result := False;
if IsEmpty then
Exit;
if Pos( AString, Self) > 0 then
Result := True;
end;
function TStringSmartHelper.IsJson: boolean;
begin
Result := IsJsonValid(Self);
end;
function TStringSmartHelper.IsNumeric: boolean;
begin
Result := False;
try
StrToFloat( Self);
Result := True;
except
end;
end;
function TStringSmartHelper.IsEmail: boolean;
begin
Result := execregexpr('(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)', Self);
end;
function TStringSmartHelper.IsURL: boolean;
const
_REGEX_ISURL = '(http|https|ftp):\/\/([a-zA-Z0-9-]+)?(\/)?(.*)?$';
begin
Result := preg_match(_REGEX_ISURL, Self);
end;
function TStringSmartHelper.IsDomain: boolean;
begin
Result := execregexpr('^((\w+)\.)?(([\w-]+)?)(\.[\w-]+){1,2}$', Self);
end;
function TStringSmartHelper.Encode64: AnsiString;
begin
Result := base64_encode(Self);
end;
function TStringSmartHelper.Decode64: AnsiString;
begin
Result := base64_decode(Self);
end;
function TStringSmartHelper.Cut(AStartText, AStopText: string): AnsiString;
begin
Result := StringCut(AStartText, AStopText, Self);
end;
function TStringSmartHelper.SaveToFile(AFileName: string): boolean;
var
sText: TStringList;
begin
Result := False;
sText := TStringList.Create;
sText.Text := Self;
try
sText.SaveToFile(AFileName);
Result := True;
except
end;
sText.Free;
end;
function TStringSmartHelper.Has(AText: string): boolean;
begin
Result := False;
if pos( AText, Self) > 0 then
Result := True;
end;
function TStringSmartHelper.UcWords: AnsiString;
begin
Result := common.ucwords(Self);
end;
function TStringSmartHelper.IsPregMatch(ARegex: string): boolean;
begin
Result := common.preg_match(ARegex, Self);
end;
function TStringSmartHelper.Split(ADelimiter: string): TStrings;
begin
Result := Self.Explode(ADelimiter);
end;
function TStringSmartHelper.StrPos(AText: string): integer;
begin
Result := Pos( AText, Self);
end;
end.
|
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types,
FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.Layouts,
FMX.Edit;
type
TMainForm = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Button1: TButton;
Memo3: TMemo;
MaterialOxfordBlueSB: TStyleBook;
Layout1: TLayout;
Button2: TButton;
Layout2: TLayout;
Button3: TButton;
Edit1: TEdit;
IterationEdit: TEdit;
Label1: TLabel;
Label2: TLabel;
ProjectsEdit: TEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
uses
System.IOUtils;
procedure TMainForm.Button1Click(Sender: TObject);
var
LSList: TStringList;
begin
LSList := TStringList.Create;
try
LSList.Append(Memo1.Lines.Text.Replace('[[iteration]]','1'));
for var I := 0 to IterationEdit.Text.ToInteger do
LSList.Append(Memo2.Lines.Text.Replace('[[number]]',I.ToString));
LSList.Append(Memo3.Lines.Text);
LSList.SaveToFile(TPath.Combine(Edit1.Text,'LU.pas'));
finally
LSList.Free;
end;
end;
procedure TMainForm.Button2Click(Sender: TObject);
var
LDirectory: String;
LNewDirectory: String;
LIndex: Integer;
begin
LDirectory := Edit1.Text;
for LIndex := 2 to ProjectsEdit.Text.ToInteger do
begin
LNewDirectory := LDirectory.Replace('Project1','Project'+LIndex.ToString);
if TDirectory.Exists(LNewDirectory) then
TDirectory.Delete(LNewDirectory,True);
TDirectory.Copy(LDirectory,LNewDirectory);
end;
end;
procedure TMainForm.Button3Click(Sender: TObject);
var
LDirectory: String;
begin
SelectDirectory('Locate','c:\D\One-Billion-Lines-Of-Object-Pascal-Code-1msci\Project1',LDirectory);
Edit1.Text := LDirectory;
end;
end.
|
{
Copyright 2019 Ideas Awakened Inc.
Part of the "iaLib" shared code library for Delphi
For more detail, see: https://github.com/ideasawakened/iaLib
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 iaRTL.ScreenCursorStack;
{$include iaCrossFramework.inc}
interface
uses
System.UITypes;
type
TiaScreenCursorStack = class
public
class procedure PushCursor(const aNewCursor:TCursor);
class procedure PopCursor;
end;
implementation
{$IFDEF VCL}
uses
iaVCL.ScreenCursorStack;
{$IFEND}
//Expected compilation error due to two 'Uses' clause if both VCL and FMX are defined in one app
{$IFDEF FMX}
uses
iaFMX.ScreenCursorStack;
{$IFEND}
{$IFDEF VCL}
class procedure TiaScreenCursorStack.PushCursor(const aNewCursor:TCursor);
begin
TiaVCLScreenCursorStack.PushCursor(aNewCursor);
end;
class procedure TiaScreenCursorStack.PopCursor;
begin
TiaVCLScreenCursorStack.PopCursor();
end;
{$IFEND}
{$IFDEF FMX}
class procedure TiaScreenCursorStack.PushCursor(const aNewCursor:TCursor);
begin
TiaFMXScreenCursorStack.PushCursor(aNewCursor);
end;
class procedure TiaScreenCursorStack.PopCursor;
begin
TiaFMXScreenCursorStack.PopCursor();
end;
{$IFEND}
end.
|
unit LUX.GPU.OpenGL.Camera;
interface //#################################################################### ■
uses Winapi.OpenGL, Winapi.OpenGLext,
LUX, LUX.M4, LUX.Tree,
LUX.GPU.OpenGL,
LUX.GPU.OpenGL.Buffer.Unifor,
LUX.GPU.OpenGL.Scener;
type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLCamera
TGLCamera = class( TGLNode, IGLCamera )
private
const _N :Single = 0.1;
const _F :Single = 1000;
protected
_Proj :TGLUnifor<TSingleM4>;
///// アクセス
function GetProj :TSingleM4; virtual;
procedure SetProj( const Proj_:TSingleM4 ); virtual;
public
constructor Create( const Paren_:ITreeNode ); override;
destructor Destroy; override;
///// プロパティ
property Proj :TSingleM4 read GetProj write SetProj;
///// メソッド
procedure Render;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLCameraOrth
TGLCameraOrth = class( TGLCamera )
private
protected
_Size :Single;
///// アクセス
function GetSize :Single; virtual;
procedure SetSize( const Size_:Single ); virtual;
public
constructor Create( const Paren_:ITreeNode ); override;
destructor Destroy; override;
///// プロパティ
property Size :Single read GetSize write SetSize;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLCameraPers
TGLCameraPers = class( TGLCamera )
private
protected
_Angl :Single;
///// アクセス
function GetAngl :Single; virtual;
procedure SetAngl( const Angl_:Single ); virtual;
public
constructor Create( const Paren_:ITreeNode ); override;
destructor Destroy; override;
///// プロパティ
property Angl :Single read GetAngl write SetAngl;
end;
//const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】
//var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
implementation //############################################################### ■
uses System.SysUtils, System.Classes, System.Math;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLCamera
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TGLCamera.GetProj :TSingleM4;
begin
Result := _Proj[ 0 ];
end;
procedure TGLCamera.SetProj( const Proj_:TSingleM4 );
begin
_Proj[ 0 ] := Proj_;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TGLCamera.Create( const Paren_:ITreeNode );
begin
inherited;
_Proj := TGLUnifor<TSingleM4>.Create( GL_STATIC_DRAW );
_Proj.Count := 1;
end;
destructor TGLCamera.Destroy;
begin
_Proj.DisposeOf;
inherited;
end;
/////////////////////////////////////////////////////////////////////// メソッド
procedure TGLCamera.Render;
begin
_Proj.Use( 1{BinP} );
_Pose.Use( 2{BinP} );
Scener.Draw;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLCameraOrth
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TGLCameraOrth.GetSize :Single;
begin
Result := _Size;
end;
procedure TGLCameraOrth.SetSize( const Size_:Single );
var
S :Single;
begin
_Size := Size_;
S := _Size / 2;
Proj := TSingleM4.ProjOrth( -S, +S, -S, +S, _N, _F );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TGLCameraOrth.Create( const Paren_:ITreeNode );
begin
inherited;
Size := 10;
end;
destructor TGLCameraOrth.Destroy;
begin
inherited;
end;
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLCameraPers
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected
/////////////////////////////////////////////////////////////////////// アクセス
function TGLCameraPers.GetAngl :Single;
begin
Result := _Angl;
end;
procedure TGLCameraPers.SetAngl( const Angl_:Single );
var
S :Single;
begin
_Angl := Angl_;
S := _N * Tan( _Angl / 2 );
Proj := TSingleM4.ProjPers( -S, +S, -S, +S, _N, _F );
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
constructor TGLCameraPers.Create( const Paren_:ITreeNode );
begin
inherited;
Angl := 90{°};
end;
destructor TGLCameraPers.Destroy;
begin
inherited;
end;
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】
//############################################################################## □
initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化
finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化
end. //######################################################################### ■
|
unit DialogAddFundFRMUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, JvLookOut, ExtCtrls,
ImgList, Davidutilsunit, JvEdit, JvExStdCtrls, JvExControls, cxControls,
cxContainer, cxEdit, cxTextEdit, cxCurrencyEdit, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters;
type
TAddFundForm = class(TForm)
Label1: TLabel;
ButtonAdd: TButton;
Panel1: TPanel;
JvExpressButton12: TJvExpressButton;
ImageListSmallImages: TImageList;
ButtonCancel: TButton;
Label2: TLabel;
Edit1: TJvEdit;
FnpAmount: TcxCurrencyEdit;
Label3: TLabel;
cxCurrencyEditOldAmount: TcxCurrencyEdit;
procedure JvExpressButton12Click(Sender: TObject);
procedure ButtonAddClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
AddFundForm: TAddFundForm;
implementation
{$R *.dfm}
uses clientDMUnit, MainFRMUnit, GlobalsUnit;
procedure TAddFundForm.JvExpressButton12Click(Sender: TObject);
begin
FnpAmount.Value := 0;
Edit1.Text;
end;
procedure TAddFundForm.ButtonAddClick(Sender: TObject);
var
TicketToPrint: TTicketJob;
Data: WideString;
Num, LineSpacing, i: integer;
begin
if Length(Edit1.Text) < 8 then
begin
Messagedlg('Veuillez complèter la raison', mtwarning, [mbok], 0);
Exit;
end;
try
RemoteDB.Customers.DisableControls;
RemoteDB.netshop_refunds.DisableControls;
///
/// Ticket
///
if not(Mainform.Parameter['PrintersTicketEnabled'] = 'TRUE') then
if Messagedlg
('Imprimante à tickets non activée ! Voulez-vous continuer ?',
mtwarning, [mbyes, mbno], 0) = mrNo then
Exit;
if (Mainform.Parameter['PrintersTicketEnabled'] = 'TRUE') then
begin
TicketToPrint := TTicketJob.Create(self);
try
TicketToPrint.Printer := (Mainform.Parameter['PrintersTicketPrinter']);
TicketToPrint.Logo := PrintLogo;
TicketToPrint.Url := WEBURL;
TicketToPrint.ShopData := ShopDataList;
if (Mainform.Parameter['PrintersTicketContinuous'] = 'TRUE') then
TicketToPrint.Model := TmContinuous;
TicketToPrint.AddFinancialLine('Ajout :', FnpAmount.Value);
TicketToPrint.AddCustomerLine('Client # :',
RemoteDB.CustomersCustomers_nbr.Text);
TicketToPrint.AddCustomerLine('Nom :',
RemoteDB.CustomersCustomers_firstname.Text);
TicketToPrint.AddCustomerLine('Ancien bon :',
RemoteDB.CustomersCustomers_credit.Text);
TicketToPrint.AddCustomerLine('Nouveau bon :',
floattostrf((FnpAmount.Value), fffixed, 7, 2));
if Mainform.Parameter['PrintersTicketOpos'] = 'TRUE' then
TicketToPrint.PrintOpos
else
TicketToPrint.Print;
finally
TicketToPrint.Free;
end;
end; // Fin Ticket
///
/// Modification de la DB
///
RemoteDB.Customers.Edit;
RemoteDB.CustomersCustomers_credit.AsFloat := FnpAmount.Value;
RemoteDB.Customers.Post;
RemoteDB.netshop_refunds.Append;
RemoteDB.CDSActions.Append;
RemoteDB.CDSActions.FieldByName('action').AsString := 'Bon ' +
RemoteDB.CustomersCustomers_nbr.Text + ' de ' +
cxCurrencyEditOldAmount.Text + ' à ' + FnpAmount.Text;
RemoteDB.CDSActions.Post;
// RemoteDB.netshop_refunds.FieldByName('refunds_amount').Value:=FnpAmount.Value;
// RemoteDB.netshop_refunds.FieldByName('refunds_nature').AsString:='Ajout : '+Edit1.Text;
// RemoteDB.netshop_refunds.FieldByName('refunds_customer_nbr').Value:=RemoteDB.CustomersCustomers_nbr.Value;
// RemoteDB.netshop_refunds.Post;
finally
RemoteDB.Customers.EnableControls;
RemoteDB.netshop_refunds.EnableControls;
end;
self.ModalResult := MrOk;
end;
end.
|
{
Save the source of script into Data\Scripts\*.txt file
For Oblivion, Fallout 3 and New Vegas
Hotkey: Ctrl+Q
Mode: Silent
}
unit SaveScriptSource;
function Process(e: IInterface): integer;
var
s: string;
sl: TStringList;
begin
if Signature(e) <> 'SCPT' then
Exit;
s := DataPath + 'Scripts\';
if not DirectoryExists(s) then
if not ForceDirectories(s) then begin
AddMessage('Can not create output folder ' + s);
Result := 1;
Exit;
end;
s := s + EditorID(e) + '.txt';
AddMessage('Saving ' + Name(e) + ' script to ' + s);
sl := TStringList.Create;
sl.Text := GetElementEditValues(e, 'SCTX');
sl.SaveToFile(s);
sl.Free;
end;
end.
|
unit UFrmMemoEdit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmModal, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxControls,
cxContainer, cxEdit, ActnList, cxCheckBox, StdCtrls, cxButtons, ExtCtrls, cxTextEdit, cxMemo;
type
TFrmMemoEdit = class(TFrmModal)
cxmMemo: TcxMemo;
procedure btnOkClick(Sender: TObject);
private
public
class function ShowMemoEdit(ACaption: string; var AValue: string): Boolean;
end;
var
FrmMemoEdit: TFrmMemoEdit;
implementation
{$R *.dfm}
{ TFrmMemoEdit }
procedure TFrmMemoEdit.btnOkClick(Sender: TObject);
begin
inherited;
ModalResult := mrOk;
end;
class function TFrmMemoEdit.ShowMemoEdit(ACaption: string; var AValue: string): Boolean;
begin
Result := False;
FrmMemoEdit := TFrmMemoEdit.Create(nil);
try
FrmMemoEdit.Caption := ACaption;
FrmMemoEdit.cxmMemo.Text := AValue;
if FrmMemoEdit.ShowModal = mrOk then
begin
AValue := Trim(FrmMemoEdit.cxmMemo.Text);
Result := True;
end;
finally
FreeAndNil(FrmMemoEdit);
end;
end;
end.
|
unit UGitHub;
interface
procedure CheckGitHubUpdate(const Repository, CurrentVersion: string);
implementation
uses System.Classes, System.SysUtils, Vcl.Graphics,
Vcl.Dialogs, System.UITypes, System.IOUtils,
System.Net.HttpClient, System.JSON, Vcl.ExtActns, System.Zip,
UFrm, UCommon;
const URL_GITHUB = 'https://api.github.com/repos/%s/releases/latest';
type
TThCheck = class(TThread)
protected
procedure Execute; override;
private
Repository: string;
CurrentVersion: string;
procedure Check;
procedure Download(const URL: string);
procedure Log(const A: string; bBold: Boolean = True; Color: TColor = clBlack);
end;
procedure TThCheck.Execute;
begin
FreeOnTerminate := True;
try
Check;
except
on E: Exception do
Log('ERROR: '+E.Message, True, clRed);
end;
Synchronize(
procedure
begin
Frm.SetButtons(True);
end);
end;
procedure TThCheck.Log(const A: string; bBold: Boolean = True; Color: TColor = clBlack);
begin
Synchronize(
procedure
begin
Frm.Log(A, bBold, Color);
end);
end;
procedure TThCheck.Check;
var
H: THTTPClient;
Res, tag_url, tag_version, tag_zip: string;
data: TJSONObject;
Confirm: Boolean;
begin
Log('Checking for component update...');
H := THTTPClient.Create;
try
Res := H.Get(Format(URL_GITHUB, [Repository])).ContentAsString;
finally
H.Free;
end;
data := TJSONObject.ParseJSONValue(Res) as TJSONObject;
try
if data.GetValue('id')=nil then
raise Exception.Create('No releases found on GitHub');
tag_version := data.GetValue('tag_name').Value;
tag_url := data.GetValue('html_url').Value;
tag_zip := data.GetValue('zipball_url').Value;
finally
data.Free;
end;
if tag_version.StartsWith('v', True) then Delete(tag_version, 1, 1);
if CurrentVersion<>tag_version then
begin
Log(Format('New version "%s" available.', [tag_version]), True, clPurple);
Synchronize(
procedure
begin
Confirm := MessageDlg(Format(
'There is a new version "%s" of the component available at GitHub.'+
' Do you want to update it automatically?', [tag_version]),
mtInformation, mbYesNo, 0) = mrYes;
end);
if Confirm then
Download(tag_zip);
end else
Log('Your version is already updated.', True, clGreen);
end;
procedure TThCheck.Download(const URL: string);
var
Dw: TDownLoadURL;
TmpFile: string;
Z: TZipFile;
ZPath, ZFile, ZFileNormalized: string;
begin
Log('Downloading new version...');
TmpFile := TPath.GetTempFileName;
Dw := TDownLoadURL.Create(nil);
try
Dw.URL := URL;
Dw.Filename := TmpFile;
Dw.ExecuteTarget(nil);
finally
Dw.Free;
end;
Log('Extracting component updates...');
Z := TZipFile.Create;
try
Z.Open(TmpFile, zmRead);
for ZFile in Z.FileNames do
begin
try
ZFileNormalized := NormalizeAndRemoveFirstDir(ZFile);
ZPath := TPath.Combine(AppDir, ExtractFilePath(ZFileNormalized));
if not DirectoryExists(ZPath) then ForceDirectories(ZPath);
Z.Extract(ZFile, ZPath, False);
except
on E: Exception do
raise Exception.CreateFmt('Error extracting "%s": %s', [ZFile, E.Message]);
end;
end;
finally
Z.Free;
end;
Log('Reloading component info...');
Synchronize(Frm.LoadDefinitions); //reaload definitions
Log('Update complete!', True, clGreen);
end;
procedure CheckGitHubUpdate(const Repository, CurrentVersion: string);
var
C: TThCheck;
begin
if Repository.IsEmpty then Exit;
Frm.SetButtons(False);
C := TThCheck.Create(True);
C.Repository := Repository;
C.CurrentVersion := CurrentVersion;
C.Start;
end;
end.
|
(*
@abstract(Contient une classe pour le rendu de police de caractères bitmap)
--------------------------------------------------------------------------------
@created(2018-07-11)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(10/07/2018 : Creation)
)
--------------------------------------------------------------------------------
@bold(Notes) :
--------------------------------------------------------------------------------
@bold(Dependances) : BZClasses, BZGraphic, BZBitmap, BZBitmapIO;
--------------------------------------------------------------------------------
@bold(Credits :)
@unorderedList(
@item ()
@item(J.Delauney (BeanzMaster))
)
--------------------------------------------------------------------------------
@bold(LICENCE) : MPL / GPL
-------------------------------------------------------------------------------- *)
Unit BZBitmapFont;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\bzscene_options.inc}
//==============================================================================
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Spin,
BZClasses, BZGraphic, BZBitmap, BZBitmapIO;
type
{ Alignement vertical }
TBZBitmapFontVerticalAlign = ( vaTop, vaCenter, vaBottom);
{ Alignement horizontal }
TBZBitmapFontHorizontalAlign = ( haLeft, haCenter, haRight);
{ Gestion d'une police de caractères bitmap }
TBZBitmapFont = Class(TBZUpdateAbleObject)
private
FBitmap : TBZBitmap;
FAlphabet : String;
FSpaceOffset : Integer;
FNbLetterByLine : Integer;
FNbLine : Integer;
FCarWidth : Byte;
FCarHeight : Byte;
FHorizontalLowerCaseGapSize, FVerticalLowerCaseGapSize : Integer;
FHorizontalGapSize, FVerticalGapSize : Integer;
FVerticalAlign : TBZBitmapFontVerticalAlign;
FHorizontalAlign : TBZBitmapFontHorizontalAlign;
FDrawMode : TBZBitmapDrawMode;
FAlphaMode : TBZBitmapAlphaMode;
FMasterAlpha : Byte;
function GetBitmap : TBZBitmap;
procedure SetBitmap(const AValue : TBZBitmap);
procedure SetCarWidth(const AValue : Byte);
procedure SetCarHeight(const AValue : Byte);
procedure SetAlphabet(const AValue : String);
//FImageList : TBZImageList;
//FFontIndex : Integer;
protected
public
Constructor Create; override;
Constructor Create(Const BitmapFont : TBZBitmap; const aCarWidth, aCarHeight : Byte); overload;
Constructor Create(Const FileFontName : String; const aCarWidth, aCarHeight : Byte); overload;
Destructor Destroy; override;
procedure LoadFromFile(Const FileFontName : String; const aCarWidth, aCarHeight : Byte);
procedure TextOut(Bmp : TBZBitmap; px, py : Integer; Const Text : String);
procedure TextOutRect(Bmp : TBZBitmap; aRect : TBZRect ; Const Text : String; Const HorizontalAlign : TBZBitmapFontHorizontalAlign = haLeft; Const VerticalAlign : TBZBitmapFontVerticalAlign = vaTop);
//property ImageList : TBZImageList read FImageList write SetImageList;
//property FontIndex : Integer read SetIndex write SetIndex;
property Alphabet : String read FAlphabet write SetAlphabet;
property SpaceOffset : Integer read FSpaceOffset write FSpaceOffset;
property CarWidth : Byte read FCarWidth write SetCarWidth;
property CarHeight : Byte read FCarHeight write SetCarHeight;
property Bitmap : TBZBitmap read GetBitmap write SetBitmap;
property DrawMode : TBZBitmapDrawMode read FDrawMode write FDrawMode;
property AlphaMode : TBZBitmapAlphaMode read FAlphaMode write FAlphaMode;
property MasterAlpha : Byte read FMasterAlpha write FMasterAlpha;
property HorizontalLowerCaseGapSize: Integer read FHorizontalLowerCaseGapSize write FHorizontalLowerCaseGapSize;
property VerticalLowerCaseGapSize : Integer read FVerticalLowerCaseGapSize write FVerticalLowerCaseGapSize;
property HorizontalGapSize : Integer read FHorizontalGapSize write FHorizontalGapSize;
property VerticalGapSize : Integer read FVerticalGapSize write FVerticalGapSize;
end;
implementation
Uses
BZLogger, BZMath;
{%region====[ TBZBitmapFont ]=======================================================}
constructor TBZBitmapFont.Create;
begin
inherited Create;
FBitmap := TBZBitmap.Create;
FAlphabet := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>=()-''!_+\/{}^&%.=$#?*';
FDrawMode := dmSet;
FAlphaMode := amAlphaBlend;
FMasterAlpha := 255;
end;
constructor TBZBitmapFont.Create(const BitmapFont : TBZBitmap; const aCarWidth, aCarHeight : Byte);
begin
Create;
FBitmap.Assign(BitmapFont);
FCarWidth := aCarWidth;
FCarHeight := aCarHeight;
FNbLetterByLine := (FBitmap.Width div FCarWidth);
FNBLine := Round((Length(FAlphabet) / FNbLetterByLine) + 0.5);
end;
constructor TBZBitmapFont.Create(const FileFontName : String; const aCarWidth, aCarHeight : Byte);
begin
Create;
FBitmap.LoadFromFile(FileFontName);
FCarWidth := aCarWidth;
FCarHeight := aCarHeight;
FNbLetterByLine := (FBitmap.Width div FCarWidth);
FNBLine := Round((Length(FAlphabet) / FNbLetterByLine) + 0.5);
end;
destructor TBZBitmapFont.Destroy;
begin
FreeAndNil(FBitmap);
inherited Destroy;
end;
procedure TBZBitmapFont.LoadFromFile(const FileFontName : String; const aCarWidth, aCarHeight : Byte);
begin
FBitmap.LoadFromFile(FileFontName);
FCarWidth := aCarWidth;
FCarHeight := aCarHeight;
FNbLetterByLine := (FBitmap.Width div FCarWidth);
FNBLine := Round((Length(FAlphabet) / FNbLetterByLine) + 0.5);
end;
function TBZBitmapFont.GetBitmap : TBZBitmap;
begin
Result := FBitmap;
end;
procedure TBZBitmapFont.SetBitmap(const AValue : TBZBitmap);
begin
FBitmap := aValue;
FNbLetterByLine := FBitmap.Width div (FCarWidth+1);
FNBLine := FBitmap.Height div (FCarHeight+1);
end;
procedure TBZBitmapFont.SetCarHeight(const AValue : Byte);
begin
if FCarHeight = AValue then Exit;
FCarHeight := AValue;
FNBLine := Round((Length(FAlphabet) / FNbLetterByLine) + 0.5);
end;
procedure TBZBitmapFont.SetAlphabet(const AValue : String);
begin
if FAlphabet = AValue then Exit;
FAlphabet := AValue;
FNBLine := Round((Length(FAlphabet) / FNbLetterByLine) + 0.5);
end;
procedure TBZBitmapFont.SetCarWidth(const AValue : Byte);
begin
if FCarWidth = AValue then Exit;
FCarWidth := AValue;
FNbLetterByLine := (FBitmap.Width div FCarWidth);
FNBLine := Round((Length(FAlphabet) / FNbLetterByLine) + 0.5);
end;
procedure TBZBitmapFont.TextOut(Bmp : TBZBitmap; px, py : Integer; const Text : String);
Var
sx, sy, dx, dy, i, Letter, lp : Integer;
c : char;
begin
//GlobalLogger.LogNotice('Bitmap Font TextOut');
//GlobalLogger.LogNotice('Length = '+length(Text).ToString);
//GlobalLogger.LogNotice('Alphabet = '+length(FAlphabet).ToString);
//GlobalLogger.LogNotice('Lines = '+FNBLine.ToString);
//GlobalLogger.LogNotice('Char by Line = '+FNBLetterByLine.ToString);
dx := px;
for i := 1 to length(Text) do
begin
dy := py;
//GlobalLogger.LogNotice('---------------------------------------------------------------');
//GlobalLogger.LogNotice('Current Char ['+i.ToString+ '] = '+Text[i]);
c := Text[i];
if (c <> ' ') then
begin
Letter := AnsiPos(c, FAlphabet) ;
lp := ((Letter-1) div (FNBLetterByLine));
sy := FCarHeight * lp;
if ((Letter-1) > FNBLetterByLine) then
sx := (((Letter-1) mod FNBLetterByLine) * FCarWidth) // - ((lp * FNBLetterByLine)+1))
else
sx := ((Letter-1) * FCarWidth);
//GlobalLogger.LogNotice('Alphabet CharPos = '+Letter.ToString);
//GlobalLogger.LogNotice('Alphabet LinePos = '+lp.ToString);
//GlobalLogger.LogNotice('Font CharPos Y = '+sy.ToString);
//GlobalLogger.LogNotice('Font CharPos X = '+sx.ToString);
if (c in ['a'..'z']) then
begin
if (i>1) then
begin
dx := dx + (FCarWidth + FSpaceOffset) + FHorizontalLowerCaseGapSize;
dy := dy + FVerticalLowerCaseGapSize;
end;
end
else
begin
if (i>1) then
begin
dx := dx + (FCarWidth + FSpaceOffset) + FHorizontalGapSize;
dy := dy + FVerticalGapSize;
end;
end;
//GlobalLogger.LogNotice('Draw CharPos Y = '+dy.ToString);
//GlobalLogger.LogNotice('Draw CharPos X = '+dx.ToString);
bmp.PutImage(FBitmap,sx,sy,FCarWidth, FCarHeight,dx,dy, FDrawMode, FAlphaMode, FMasterAlpha);
end
else dx := dx + (FCarWidth + FSpaceOffset);
end;
end;
procedure TBZBitmapFont.TextOutRect(Bmp : TBZBitmap; aRect : TBZRect; const Text : String; const HorizontalAlign : TBZBitmapFontHorizontalAlign; const VerticalAlign : TBZBitmapFontVerticalAlign);
begin
end;
{%endregion%}
end.
|
///Проверяет, является ли год високосным
function IsLeapYear(year: integer): boolean;
begin
Assert(year > 0);
if (year mod 4 = 0) and (year mod 100 != 0) or (year mod 400 == 0):
result := true;
else:
result := false;
end;
///Получает два дня, проверяет, какой из них ближе к Новому году
///(Возвращает 1, если первый, и 2, если второй
function LaterInYear(firstDay, firstMonth, secondDay, secondMonth: integer): integer;
begin
if firstMonth > secondMonth then
result := 1
else if firstMonth < secondMonth then
result := 2
else if firstDay > secondDay then
result := 1
else
result := 2;
end;
///Определяет количество дней в заданном году
function DaysInYear(year: integer): integer;
begin
Assert(year > 0);
result := IsLeapYear(year) ? 366 : 365;
end;
///Определяет количество дней между двумя годами включительно
function DaysInYearRange(firstYear, secondYear: integer): integer;
begin
Assert(firstYear > 0);
Assert(secondYear > 0);
result := 0;
for var i := firstYear to secondYear do
begin
result += DaysInYear(i);
end;
end;
///Возвращает число секунд в данном количестве часов
function SecondsInHours(h: integer): integer := h * 3600;
begin
end. |
unit vpstring;
interface
{$H-} // Short string functions
{&Delphi+}
// ExtractFirst extracts the first substring up to, but not including
// the first occurrence of _Sep. The _S parameter is modified to
// have this part of the string removed and _First contains the substring.
// The function returns False if _S is empty.
function ExtractFirst(var _S: ShortString; var _First: ShortString; _Delimiter: Char): Boolean;
// LeftStr is short for "Copy( _s, 1, _Len )"
function LeftStr( const _S: String; _Len: Integer ): String;
// RightStr is short for "Copy( _s, 1, Pos(_Separator, _s)-1)"
function RightStr( const _s: string; _Len: integer ): string;
// TailStr is short for "Copy( _s, _Start, Length( _s ) - _Start +1 )"
function TailStr( const _S: String; _Start: Integer ): String;
// Ensure path has trailing slash (unless blank)
function EnsureSlash( const _Path: String ): String;
implementation
uses
VpSysLow;
function ExtractFirst(var _S: ShortString; var _First: ShortString; _Delimiter: Char): Boolean;
var
p: integer;
begin
Result := _S <> '';
if Result then
begin
p := Pos(_Delimiter, _S);
if p <> 0 then
begin
_First := LeftStr(_S, p-1);
_S := TailStr(_S, p+1);
end
else
begin
_First := _S;
_S := '';
end;
end;
end;
function RightStr( const _s: string; _Len: integer ): String;
begin
Result := Copy( _s, Length( _s )- _Len + 1, _Len );
end;
function LeftStr( const _s: String; _Len: Integer): String;
begin
Result := Copy( _s, 1, _Len );
end;
function TailStr( const _s: string; _Start: integer ): string;
begin
Result := Copy( _s, _Start, Length( _s ) - _Start +1 );
end;
function EnsureSlash( const _Path: String ): String;
begin
if (_Path <> '') and (_Path[Length(_Path)] <> SysPathSep) then
Result := _Path + SysPathSep
else
Result := _Path;
end;
end.
|
unit DelphiAST;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
interface
uses
SysUtils, Classes, Generics.Collections, SimpleParser, SimpleParser.Lexer,
SimpleParser.Lexer.Types, DelphiAST.Classes, DelphiAST.Consts, DelphiAST.SimpleParserEx;
type
ESyntaxTreeException = class(EParserException)
strict private
FSyntaxTree: TSyntaxNode;
public
constructor Create(Line, Col: Integer; const FileName, Msg: string; SyntaxTree: TSyntaxNode); reintroduce;
destructor Destroy; override;
property SyntaxTree: TSyntaxNode read FSyntaxTree write FSyntaxTree;
end;
TNodeStack = class
strict private
FLexer: TPasLexer;
FStack: TStack<TSyntaxNode>;
function GetCount: Integer;
public
constructor Create(Lexer: TPasLexer);
destructor Destroy; override;
function AddChild(Typ: TSyntaxNodeType): TSyntaxNode; overload;
function AddChild(Node: TSyntaxNode): TSyntaxNode; overload;
function AddValuedChild(Typ: TSyntaxNodeType; const Value: string): TSyntaxNode;
procedure Clear;
function Peek: TSyntaxNode;
function Pop: TSyntaxNode;
function Push(Typ: TSyntaxNodeType): TSyntaxNode; overload;
function Push(Node: TSyntaxNode): TSyntaxNode; overload;
function PushCompoundSyntaxNode(Typ: TSyntaxNodeType): TSyntaxNode;
function PushValuedNode(Typ: TSyntaxNodeType; const Value: string): TSyntaxNode;
property Count: Integer read GetCount;
end;
TPasSyntaxTreeBuilder = class(TmwSimplePasParEx)
private type
TTreeBuilderMethod = procedure of object;
private
procedure BuildExpressionTree(ExpressionMethod: TTreeBuilderMethod);
procedure BuildParametersList(ParametersListMethod: TTreeBuilderMethod);
procedure RearrangeVarSection(const VarSect: TSyntaxNode);
procedure ParserMessage(Sender: TObject; const Typ: TMessageEventType; const Msg: string; X, Y: Integer);
function NodeListToString(NamesNode: TSyntaxNode): string;
procedure MoveMembersToVisibilityNodes(TypeNode: TSyntaxNode);
procedure CallInheritedConstantExpression;
procedure CallInheritedExpression;
procedure CallInheritedFormalParameterList;
procedure CallInheritedPropertyParameterList;
procedure SetCurrentCompoundNodesEndPosition;
procedure DoOnComment(Sender: TObject; const Text: string);
protected
FStack: TNodeStack;
FComments: TObjectList<TCommentNode>;
procedure AccessSpecifier; override;
procedure AdditiveOperator; override;
procedure AddressOp; override;
procedure AlignmentParameter; override;
procedure AnonymousMethod; override;
procedure ArrayBounds; override;
procedure ArrayConstant; override;
procedure ArrayDimension; override;
procedure AsmStatement; override;
procedure AsOp; override;
procedure AssignOp; override;
procedure AtExpression; override;
procedure CaseElseStatement; override;
procedure CaseLabel; override;
procedure CaseLabelList; override;
procedure CaseSelector; override;
procedure CaseStatement; override;
procedure ClassClass; override;
procedure ClassConstraint; override;
procedure ClassField; override;
procedure ClassForward; override;
procedure ClassFunctionHeading; override;
procedure ClassHelper; override;
procedure ClassMethod; override;
procedure ClassMethodResolution; override;
procedure ClassMethodHeading; override;
procedure ClassProcedureHeading; override;
procedure ClassProperty; override;
procedure ClassReferenceType; override;
procedure ClassType; override;
procedure CompoundStatement; override;
procedure ConstParameter; override;
procedure ConstantDeclaration; override;
procedure ConstantExpression; override;
procedure ConstantName; override;
procedure ConstraintList; override;
procedure ConstSection; override;
procedure ConstantValue; override;
procedure ConstantValueTyped; override;
procedure ConstructorConstraint; override;
procedure ConstructorName; override;
procedure ContainsClause; override;
procedure DestructorName; override;
procedure DirectiveBinding; override;
procedure DirectiveBindingMessage; override;
procedure DirectiveCalling; override;
procedure DirectiveInline; override;
procedure DispInterfaceForward; override;
procedure DotOp; override;
procedure ElseStatement; override;
procedure EmptyStatement; override;
procedure EnumeratedType; override;
procedure ExceptBlock; override;
procedure ExceptionBlockElseBranch; override;
procedure ExceptionHandler; override;
procedure ExceptionVariable; override;
procedure ExportedHeading; override;
procedure ExportsClause; override;
procedure ExportsElement; override;
procedure ExportsName; override;
procedure ExportsNameId; override;
procedure Expression; override;
procedure ExpressionList; override;
procedure ExternalDirective; override;
procedure FieldName; override;
procedure FinalizationSection; override;
procedure FinallyBlock; override;
procedure FormalParameterList; override;
procedure ForStatement; override;
procedure ForStatementDownTo; override;
procedure ForStatementFrom; override;
procedure ForStatementIn; override;
procedure ForStatementTo; override;
procedure FunctionHeading; override;
procedure FunctionMethodName; override;
procedure FunctionProcedureName; override;
procedure GotoStatement; override;
procedure IfStatement; override;
procedure Identifier; override;
procedure ImplementationSection; override;
procedure ImplementsSpecifier; override;
procedure IndexSpecifier; override;
procedure IndexOp; override;
procedure InheritedStatement; override;
procedure InheritedVariableReference; override;
procedure InitializationSection; override;
procedure InlineVarDeclaration; override;
procedure InlineVarSection; override;
procedure InterfaceForward; override;
procedure InterfaceGUID; override;
procedure InterfaceSection; override;
procedure InterfaceType; override;
procedure LabelId; override;
procedure MainUsesClause; override;
procedure MainUsedUnitStatement; override;
procedure MethodKind; override;
procedure MultiplicativeOperator; override;
procedure NotOp; override;
procedure NilToken; override;
procedure Number; override;
procedure ObjectNameOfMethod; override;
procedure OutParameter; override;
procedure ParameterFormal; override;
procedure ParameterName; override;
procedure PointerSymbol; override;
procedure PointerType; override;
procedure ProceduralType; override;
procedure ProcedureHeading; override;
procedure ProcedureDeclarationSection; override;
procedure ProcedureProcedureName; override;
procedure PropertyName; override;
procedure PropertyParameterList; override;
procedure RaiseStatement; override;
procedure RecordConstraint; override;
procedure RecordFieldConstant; override;
procedure RecordType; override;
procedure RelativeOperator; override;
procedure RepeatStatement; override;
procedure ResourceDeclaration; override;
procedure ResourceValue; override;
procedure RequiresClause; override;
procedure RequiresIdentifier; override;
procedure RequiresIdentifierId; override;
procedure ReturnType; override;
procedure RoundClose; override;
procedure RoundOpen; override;
procedure SetConstructor; override;
procedure SetElement; override;
procedure SimpleStatement; override;
procedure SimpleType; override;
procedure StatementList; override;
procedure StorageDefault; override;
procedure StringConst; override;
procedure StringConstSimple; override;
procedure StringStatement; override;
procedure StructuredType; override;
procedure SubrangeType; override;
procedure ThenStatement; override;
procedure TryStatement; override;
procedure TypeArgs; override;
procedure TypeDeclaration; override;
procedure TypeId; override;
procedure TypeParamDecl; override;
procedure TypeParams; override;
procedure TypeSection; override;
procedure TypeSimple; override;
procedure UnaryMinus; override;
procedure UnitFile; override;
procedure UnitName; override;
procedure UnitId; override;
procedure UsesClause; override;
procedure UsedUnitName; override;
procedure VarAbsolute; override;
procedure VarDeclaration; override;
procedure VarName; override;
procedure VarParameter; override;
procedure VarSection; override;
procedure VisibilityPrivate; override;
procedure VisibilityProtected; override;
procedure VisibilityPublic; override;
procedure VisibilityPublished; override;
procedure VisibilityStrictPrivate; override;
procedure VisibilityStrictProtected; override;
procedure WhileStatement; override;
procedure WithExpressionList; override;
procedure WithStatement; override;
procedure AttributeSections; override;
procedure Attribute; override;
procedure AttributeName; override;
procedure AttributeArguments; override;
procedure PositionalArgument; override;
procedure NamedArgument; override;
procedure AttributeArgumentName; override;
procedure AttributeArgumentExpression; override;
public
constructor Create; override;
destructor Destroy; override;
function Run(SourceStream: TStream): TSyntaxNode; reintroduce; overload; virtual;
class function Run(const FileName: string; InterfaceOnly: Boolean = False;
IncludeHandler: IIncludeHandler = nil;
OnHandleString: TStringEvent = nil): TSyntaxNode; reintroduce; overload; static;
property Comments: TObjectList<TCommentNode> read FComments;
end;
implementation
uses
TypInfo;
{$IFDEF FPC}
type
TStringStreamHelper = class helper for TStringStream
class function Create: TStringStream; overload;
procedure LoadFromFile(const FileName: string);
end;
{ TStringStreamHelper }
class function TStringStreamHelper.Create: TStringStream;
begin
Result := TStringStream.Create('');
end;
procedure TStringStreamHelper.LoadFromFile(const FileName: string);
var
Strings: TStringList;
begin
Strings := TStringList.Create;
try
Strings.LoadFromFile(FileName);
Strings.SaveToStream(Self);
finally
FreeAndNil(Strings);
end;
end;
{$ENDIF}
// do not use const strings here to prevent allocating new strings every time
type
TAttributeValue = (atAsm, atTrue, atFunction, atProcedure, atClassOf, atClass,
atConst, atConstructor, atDestructor, atEnum, atInterface, atNil, atNumeric,
atOut, atPointer, atName, atString, atSubRange, atVar, atDispInterface);
var
AttributeValues: array[TAttributeValue] of string;
procedure InitAttributeValues;
var
value: TAttributeValue;
begin
for value := Low(TAttributeValue) to High(TAttributeValue) do
AttributeValues[value] := Copy(LowerCase(GetEnumName(TypeInfo(TAttributeValue), Ord(value))), 3);
end;
procedure AssignLexerPositionToNode(const Lexer: TPasLexer; const Node: TSyntaxNode);
begin
Node.Col := Lexer.PosXY.X;
Node.Line := Lexer.PosXY.Y;
Node.FileName := Lexer.FileName;
end;
{ TNodeStack }
function TNodeStack.AddChild(Typ: TSyntaxNodeType): TSyntaxNode;
begin
Result := FStack.Peek.AddChild(TSyntaxNode.Create(Typ));
AssignLexerPositionToNode(FLexer, Result);
end;
function TNodeStack.AddChild(Node: TSyntaxNode): TSyntaxNode;
begin
Result := FStack.Peek.AddChild(Node);
end;
function TNodeStack.AddValuedChild(Typ: TSyntaxNodeType;
const Value: string): TSyntaxNode;
begin
Result := FStack.Peek.AddChild(TValuedSyntaxNode.Create(Typ));
AssignLexerPositionToNode(FLexer, Result);
TValuedSyntaxNode(Result).Value := Value;
end;
procedure TNodeStack.Clear;
begin
FStack.Clear;
end;
constructor TNodeStack.Create(Lexer: TPasLexer);
begin
FLexer := Lexer;
FStack := TStack<TSyntaxNode>.Create;
end;
destructor TNodeStack.Destroy;
begin
FStack.Free;
inherited;
end;
function TNodeStack.GetCount: Integer;
begin
Result := FStack.Count;
end;
function TNodeStack.Peek: TSyntaxNode;
begin
Result := FStack.Peek;
end;
function TNodeStack.Pop: TSyntaxNode;
begin
Result := FStack.Pop;
end;
function TNodeStack.Push(Node: TSyntaxNode): TSyntaxNode;
begin
FStack.Push(Node);
Result := Node;
AssignLexerPositionToNode(FLexer, Result);
end;
function TNodeStack.PushCompoundSyntaxNode(Typ: TSyntaxNodeType): TSyntaxNode;
begin
Result := Push(Peek.AddChild(TCompoundSyntaxNode.Create(Typ)));
end;
function TNodeStack.PushValuedNode(Typ: TSyntaxNodeType;
const Value: string): TSyntaxNode;
begin
Result := Push(Peek.AddChild(TValuedSyntaxNode.Create(Typ)));
TValuedSyntaxNode(Result).Value := Value;
end;
function TNodeStack.Push(Typ: TSyntaxNodeType): TSyntaxNode;
begin
Result := FStack.Peek.AddChild(TSyntaxNode.Create(Typ));
Push(Result);
end;
{ TPasSyntaxTreeBuilder }
procedure TPasSyntaxTreeBuilder.AccessSpecifier;
begin
case ExID of
ptRead:
FStack.Push(ntRead);
ptWrite:
FStack.Push(ntWrite);
else
FStack.Push(ntUnknown);
end;
try
inherited AccessSpecifier;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.AdditiveOperator;
begin
case TokenID of
ptMinus: FStack.AddChild(ntSub);
ptOr: FStack.AddChild(ntOr);
ptPlus: FStack.AddChild(ntAdd);
ptXor: FStack.AddChild(ntXor);
end;
inherited;
end;
procedure TPasSyntaxTreeBuilder.AddressOp;
begin
FStack.Push(ntAddr);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.AlignmentParameter;
begin
FStack.Push(ntAlignmentParam);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.AnonymousMethod;
begin
FStack.Push(ntAnonymousMethod);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ArrayBounds;
begin
FStack.Push(ntBounds);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ArrayConstant;
begin
FStack.Push(ntExpressions);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ArrayDimension;
begin
FStack.Push(ntDimension);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.AsmStatement;
begin
FStack.PushCompoundSyntaxNode(ntStatements).SetAttribute(anType, AttributeValues[atAsm]);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.AsOp;
begin
FStack.AddChild(ntAs);
inherited;
end;
procedure TPasSyntaxTreeBuilder.AssignOp;
begin
FStack.AddChild(ntAssign);
inherited;
end;
procedure TPasSyntaxTreeBuilder.AtExpression;
begin
FStack.Push(ntAt);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.Attribute;
begin
FStack.Push(ntAttribute);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.AttributeArgumentExpression;
begin
FStack.Push(ntValue);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.AttributeArgumentName;
begin
FStack.AddValuedChild(ntName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.AttributeArguments;
begin
FStack.Push(ntArguments);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.AttributeName;
begin
FStack.AddValuedChild(ntName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.AttributeSections;
begin
FStack.Push(ntAttributes);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.BuildExpressionTree(
ExpressionMethod: TTreeBuilderMethod);
var
RawExprNode: TSyntaxNode;
ExprNode: TSyntaxNode;
NodeList: TList<TSyntaxNode>;
Node: TSyntaxNode;
Col, Line: Integer;
FileName: string;
begin
Line := Lexer.PosXY.Y;
Col := Lexer.PosXY.X;
FileName := Lexer.FileName;
RawExprNode := TSyntaxNode.Create(ntExpression);
try
FStack.Push(RawExprNode);
try
ExpressionMethod;
finally
FStack.Pop;
end;
if RawExprNode.HasChildren then
begin
ExprNode := FStack.Push(ntExpression);
try
ExprNode.Line := Line;
ExprNode.Col := Col;
ExprNode.FileName := FileName;
NodeList := TList<TSyntaxNode>.Create;
try
for Node in RawExprNode.ChildNodes do
NodeList.Add(Node);
TExpressionTools.RawNodeListToTree(RawExprNode, NodeList, ExprNode);
finally
NodeList.Free;
end;
finally
FStack.Pop;
end;
end;
finally
RawExprNode.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.BuildParametersList(
ParametersListMethod: TTreeBuilderMethod);
var
Params, Temp: TSyntaxNode;
ParamList, Param, TypeInfo, ParamExpr: TSyntaxNode;
ParamKind: string;
begin
Params := TSyntaxNode.Create(ntUnknown);
try
FStack.Push(ntParameters);
FStack.Push(Params);
try
ParametersListMethod;
finally
FStack.Pop;
end;
for ParamList in Params.ChildNodes do
begin
TypeInfo := ParamList.FindNode(ntType);
ParamKind := ParamList.GetAttribute(anKind);
ParamExpr := ParamList.FindNode(ntExpression);
for Param in ParamList.ChildNodes do
begin
if Param.Typ <> ntName then
Continue;
Temp := FStack.Push(ntParameter);
if ParamKind <> '' then
Temp.SetAttribute(anKind, ParamKind);
Temp.Col := Param.Col;
Temp.Line := Param.Line;
FStack.AddChild(Param.Clone);
if Assigned(TypeInfo) then
FStack.AddChild(TypeInfo.Clone);
if Assigned(ParamExpr) then
FStack.AddChild(ParamExpr.Clone);
FStack.Pop;
end;
end;
FStack.Pop;
finally
Params.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.CaseElseStatement;
begin
FStack.Push(ntCaseElse);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.CaseLabel;
begin
FStack.Push(ntCaseLabel);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.CaseLabelList;
begin
FStack.Push(ntCaseLabels);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.CaseSelector;
begin
FStack.Push(ntCaseSelector);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.CaseStatement;
begin
FStack.Push(ntCase);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ClassClass;
begin
FStack.Peek.SetAttribute(anClass, AttributeValues[atTrue]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ClassField;
var
Fields, Temp: TSyntaxNode;
Field, TypeInfo, TypeArgs: TSyntaxNode;
begin
Fields := TSyntaxNode.Create(ntFields);
try
FStack.Push(Fields);
try
inherited;
finally
FStack.Pop;
end;
TypeInfo := Fields.FindNode(ntType);
TypeArgs := Fields.FindNode(ntTypeArgs);
for Field in Fields.ChildNodes do
begin
if Field.Typ <> ntName then
Continue;
Temp := FStack.Push(ntField);
try
Temp.AssignPositionFrom(Field);
FStack.AddChild(Field.Clone);
TypeInfo := TypeInfo.Clone;
if Assigned(TypeArgs) then
TypeInfo.AddChild(TypeArgs.Clone);
FStack.AddChild(TypeInfo);
finally
FStack.Pop;
end;
end;
finally
Fields.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.ClassForward;
begin
FStack.Peek.SetAttribute(anForwarded, AttributeValues[atTrue]);
inherited ClassForward;
end;
procedure TPasSyntaxTreeBuilder.ClassFunctionHeading;
begin
FStack.Peek.SetAttribute(anKind, AttributeValues[atFunction]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ClassHelper;
begin
FStack.Push(ntHelper);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ClassMethod;
begin
FStack.Peek.SetAttribute(anClass, AttributeValues[atTrue]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ClassMethodResolution;
begin
FStack.Push(ntResolutionClause);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ClassMethodHeading;
begin
FStack.PushCompoundSyntaxNode(ntMethod);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ClassProcedureHeading;
begin
FStack.Peek.SetAttribute(anKind, AttributeValues[atProcedure]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ClassProperty;
begin
FStack.Push(ntProperty);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ClassReferenceType;
begin
FStack.Push(ntType).SetAttribute(anType, AttributeValues[atClassof]);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ClassType;
begin
FStack.Push(ntType).SetAttribute(anType, AttributeValues[atClass]);
try
inherited;
finally
MoveMembersToVisibilityNodes(FStack.Pop);
end;
end;
procedure TPasSyntaxTreeBuilder.MoveMembersToVisibilityNodes(TypeNode: TSyntaxNode);
var
child, vis: TSyntaxNode;
i: Integer;
extracted: Boolean;
begin
vis := nil;
i := 0;
while i < Length(TypeNode.ChildNodes) do
begin
child := TypeNode.ChildNodes[i];
extracted := false;
if child.HasAttribute(anVisibility) then
vis := child
else if Assigned(vis) then
begin
TypeNode.ExtractChild(child);
vis.AddChild(child);
extracted := true;
end;
if not extracted then
inc(i);
end;
end;
procedure TPasSyntaxTreeBuilder.ConstParameter;
begin
FStack.Push(ntParameters).SetAttribute(anKind, AttributeValues[atConst]);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ConstructorName;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Peek;
Temp.SetAttribute(anKind, AttributeValues[atConstructor]);
Temp.SetAttribute(anName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.CompoundStatement;
begin
FStack.PushCompoundSyntaxNode(ntStatements);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ConstantDeclaration;
begin
FStack.Push(ntConstant);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ConstantExpression;
var
ExpressionMethod: TTreeBuilderMethod;
begin
ExpressionMethod := CallInheritedConstantExpression;
BuildExpressionTree(ExpressionMethod);
end;
procedure TPasSyntaxTreeBuilder.CallInheritedFormalParameterList;
begin
inherited FormalParameterList;
end;
procedure TPasSyntaxTreeBuilder.CallInheritedConstantExpression;
begin
inherited ConstantExpression;
end;
procedure TPasSyntaxTreeBuilder.ConstantName;
begin
FStack.AddValuedChild(ntName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ConstantValue;
begin
FStack.Push(ntValue);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ConstantValueTyped;
begin
FStack.Push(ntValue);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ConstraintList;
begin
FStack.Push(ntConstraints);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ClassConstraint;
begin
FStack.Push(ntClassConstraint);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ConstructorConstraint;
begin
FStack.Push(ntConstructorConstraint);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.RecordConstraint;
begin
FStack.Push(ntRecordConstraint);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ConstSection;
var
ConstSect, Temp: TSyntaxNode;
ConstList, Constant, TypeInfo, Value: TSyntaxNode;
begin
ConstSect := TSyntaxNode.Create(ntConstants);
try
FStack.Push(ntConstants);
FStack.Push(ConstSect);
try
inherited ConstSection;
finally
FStack.Pop;
end;
for ConstList in ConstSect.ChildNodes do
begin
TypeInfo := ConstList.FindNode(ntType);
Value := ConstList.FindNode(ntValue);
for Constant in ConstList.ChildNodes do
begin
if Constant.Typ <> ntName then
Continue;
Temp := FStack.Push(ConstList.Typ);
try
Temp.AssignPositionFrom(Constant);
FStack.AddChild(Constant.Clone);
if Assigned(TypeInfo) then
FStack.AddChild(TypeInfo.Clone);
FStack.AddChild(Value.Clone);
finally
FStack.Pop;
end;
end;
end;
FStack.Pop;
finally
ConstSect.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.ContainsClause;
begin
FStack.Push(ntContains);
try
inherited;
finally
FStack.Pop;
end;
end;
constructor TPasSyntaxTreeBuilder.Create;
begin
inherited;
FStack := TNodeStack.Create(Lexer);
FComments := TObjectList<TCommentNode>.Create(True);
OnComment := DoOnComment;
end;
destructor TPasSyntaxTreeBuilder.Destroy;
begin
FStack.Free;
FComments.Free;
inherited;
end;
procedure TPasSyntaxTreeBuilder.DestructorName;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Peek;
Temp.SetAttribute(anKind, AttributeValues[atDestructor]);
Temp.SetAttribute(anName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.DirectiveBinding;
var
token: string;
begin
token := Lexer.Token;
// Method bindings:
if SameText(token, 'override') or SameText(token, 'virtual')
or SameText(token, 'dynamic')
then
FStack.Peek.SetAttribute(anMethodBinding, token)
// Other directives
else if SameText(token, 'reintroduce') then
FStack.Peek.SetAttribute(anReintroduce, AttributeValues[atTrue])
else if SameText(token, 'overload') then
FStack.Peek.SetAttribute(anOverload, AttributeValues[atTrue])
else if SameText(token, 'abstract') then
FStack.Peek.SetAttribute(anAbstract, AttributeValues[atTrue]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.DirectiveBindingMessage;
begin
FStack.Push(ntMessage);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.DirectiveCalling;
begin
FStack.Peek.SetAttribute(anCallingConvention, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.DirectiveInline;
begin
FStack.Peek.SetAttribute(anInline, AttributeValues[atTrue]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.DispInterfaceForward;
begin
FStack.Peek.SetAttribute(anForwarded, AttributeValues[atTrue]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.DotOp;
begin
FStack.AddChild(ntDot);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ElseStatement;
begin
FStack.Push(ntElse);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.EmptyStatement;
begin
FStack.Push(ntEmptyStatement);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.EnumeratedType;
var
TypeNode: TSyntaxNode;
begin
TypeNode := FStack.Push(ntType);
try
TypeNode.SetAttribute(anName, AttributeValues[atEnum]);
if ScopedEnums then
TypeNode.SetAttribute(anVisibility, 'scoped');
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExceptBlock;
begin
FStack.Push(ntExcept);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExceptionBlockElseBranch;
begin
FStack.Push(ntElse);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExceptionHandler;
begin
FStack.Push(ntExceptionHandler);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExceptionVariable;
begin
FStack.Push(ntVariable);
FStack.AddValuedChild(ntName, Lexer.Token);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExportedHeading;
begin
FStack.PushCompoundSyntaxNode(ntMethod);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExportsClause;
begin
FStack.Push(ntExports);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExportsElement;
begin
FStack.Push(ntElement);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExportsName;
var
NamesNode: TSyntaxNode;
begin
NamesNode := TSyntaxNode.Create(ntUnknown);
try
FStack.Push(NamesNode);
try
inherited;
finally
FStack.Pop;
end;
FStack.Peek.SetAttribute(anName, NodeListToString(NamesNode));
finally
NamesNode.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.ExportsNameId;
begin
FStack.AddChild(ntUnknown).SetAttribute(anName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.Expression;
var
ExpressionMethod: TTreeBuilderMethod;
begin
ExpressionMethod := CallInheritedExpression;
BuildExpressionTree(ExpressionMethod);
end;
procedure TPasSyntaxTreeBuilder.SetCurrentCompoundNodesEndPosition;
var
Temp: TCompoundSyntaxNode;
begin
Temp := TCompoundSyntaxNode(FStack.Peek);
Temp.EndCol := Lexer.PosXY.X;
Temp.EndLine := Lexer.PosXY.Y;
Temp.FileName := Lexer.FileName;
end;
procedure TPasSyntaxTreeBuilder.CallInheritedExpression;
begin
inherited Expression;
end;
procedure TPasSyntaxTreeBuilder.CallInheritedPropertyParameterList;
begin
inherited PropertyParameterList;
end;
procedure TPasSyntaxTreeBuilder.ExpressionList;
begin
FStack.Push(ntExpressions);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ExternalDirective;
begin
FStack.Push(ntExternal);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.FieldName;
begin
FStack.AddValuedChild(ntName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.FinalizationSection;
begin
FStack.PushCompoundSyntaxNode(ntFinalization);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.FinallyBlock;
begin
FStack.Push(ntFinally);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.FormalParameterList;
var
TreeBuilderMethod: TTreeBuilderMethod;
begin
TreeBuilderMethod := CallInheritedFormalParameterList;
BuildParametersList(TreeBuilderMethod);
end;
procedure TPasSyntaxTreeBuilder.ForStatement;
begin
FStack.Push(ntFor);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ForStatementDownTo;
begin
FStack.Push(ntDownTo);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ForStatementFrom;
begin
FStack.Push(ntFrom);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ForStatementIn;
begin
FStack.Push(ntIn);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ForStatementTo;
begin
FStack.Push(ntTo);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.FunctionHeading;
begin
FStack.Peek.SetAttribute(anKind, AttributeValues[atFunction]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.FunctionMethodName;
begin
FStack.AddValuedChild(ntName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.FunctionProcedureName;
var
ChildNode, NameNode, TypeParam, TypeNode, Temp: TSyntaxNode;
FullName, TypeParams: string;
begin
FStack.Push(ntName);
NameNode := FStack.Peek;
try
inherited;
for ChildNode in NameNode.ChildNodes do
begin
if ChildNode.Typ = ntTypeParams then
begin
TypeParams := '';
for TypeParam in ChildNode.ChildNodes do
begin
TypeNode := TypeParam.FindNode(ntType);
if Assigned(TypeNode) then
begin
if TypeParams <> '' then
TypeParams := TypeParams + ',';
TypeParams := TypeParams + TypeNode.GetAttribute(anName);
end;
end;
FullName := FullName + '<' + TypeParams + '>';
Continue;
end;
if FullName <> '' then
FullName := FullName + '.';
FullName := FullName + TValuedSyntaxNode(ChildNode).Value;
end;
finally
FStack.Pop;
Temp := FStack.Peek;
DoHandleString(FullName);
Temp.SetAttribute(anName, FullName);
Temp.DeleteChild(NameNode);
end;
end;
procedure TPasSyntaxTreeBuilder.GotoStatement;
begin
FStack.Push(ntGoto);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.Identifier;
begin
FStack.AddChild(ntIdentifier).SetAttribute(anName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.IfStatement;
begin
FStack.Push(ntIf);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ImplementationSection;
begin
FStack.PushCompoundSyntaxNode(ntImplementation);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ImplementsSpecifier;
begin
FStack.Push(ntImplements);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.IndexOp;
begin
FStack.Push(ntIndexed);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.IndexSpecifier;
begin
FStack.Push(ntIndex);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.InheritedStatement;
begin
FStack.Push(ntInherited);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.InheritedVariableReference;
begin
FStack.Push(ntInherited);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.InitializationSection;
begin
FStack.PushCompoundSyntaxNode(ntInitialization);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.InlineVarDeclaration;
begin
FStack.Push(ntVariables);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.InlineVarSection;
var
VarSect, Variables, Expression: TSyntaxNode;
begin
VarSect := TSyntaxNode.Create(ntUnknown);
try
Variables := FStack.Push(ntVariables);
FStack.Push(VarSect);
try
inherited InlineVarSection;
finally
FStack.Pop;
end;
RearrangeVarSection(VarSect);
Expression := VarSect.FindNode(ntExpression);
if Assigned(Expression) then
Variables.AddChild(ntAssign).AddChild(Expression.Clone);
FStack.Pop;
finally
VarSect.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.InterfaceForward;
begin
FStack.Peek.SetAttribute(anForwarded, AttributeValues[atTrue]);
inherited InterfaceForward;
end;
procedure TPasSyntaxTreeBuilder.InterfaceGUID;
begin
FStack.Push(ntGuid);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.InterfaceSection;
begin
FStack.PushCompoundSyntaxNode(ntInterface);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.InterfaceType;
begin
case TokenID of
ptInterface:
FStack.Push(ntType).SetAttribute(anType, AttributeValues[atInterface]);
ptDispInterface:
FStack.Push(ntType).SetAttribute(anType, AttributeValues[atDispInterface]);
end;
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.LabelId;
begin
FStack.AddValuedChild(ntLabel, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.MainUsedUnitStatement;
var
NameNode, PathNode, PathLiteralNode, Temp: TSyntaxNode;
begin
FStack.Push(ntUnit);
try
inherited;
NameNode := FStack.Peek.FindNode(ntUnit);
if Assigned(NameNode) then
begin
Temp := FStack.Peek;
Temp.SetAttribute(anName, NameNode.GetAttribute(anName));
Temp.DeleteChild(NameNode);
end;
PathNode := FStack.Peek.FindNode(ntExpression);
if Assigned(PathNode) then
begin
FStack.Peek.ExtractChild(PathNode);
try
PathLiteralNode := PathNode.FindNode(ntLiteral);
if PathLiteralNode is TValuedSyntaxNode then
FStack.Peek.SetAttribute(anPath, TValuedSyntaxNode(PathLiteralNode).Value);
finally
PathNode.Free;
end;
end;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.MainUsesClause;
begin
FStack.PushCompoundSyntaxNode(ntUses);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.MethodKind;
var
value: string;
begin
value := LowerCase(Lexer.Token);
DoHandleString(value);
FStack.Peek.SetAttribute(anKind, value);
inherited;
end;
procedure TPasSyntaxTreeBuilder.MultiplicativeOperator;
begin
case TokenID of
ptAnd:
FStack.AddChild(ntAnd);
ptDiv:
FStack.AddChild(ntDiv);
ptMod:
FStack.AddChild(ntMod);
ptShl:
FStack.AddChild(ntShl);
ptShr:
FStack.AddChild(ntShr);
ptSlash:
FStack.AddChild(ntFDiv);
ptStar:
FStack.AddChild(ntMul);
else
FStack.AddChild(ntUnknown);
end;
inherited;
end;
procedure TPasSyntaxTreeBuilder.NamedArgument;
begin
FStack.Push(ntNamedArgument);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.NilToken;
begin
FStack.AddChild(ntLiteral).SetAttribute(anType, AttributeValues[atNil]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.NotOp;
begin
FStack.AddChild(ntNot);
inherited;
end;
procedure TPasSyntaxTreeBuilder.Number;
var
Node: TSyntaxNode;
begin
Node := FStack.AddValuedChild(ntLiteral, Lexer.Token);
Node.SetAttribute(anType, AttributeValues[atNumeric]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ObjectNameOfMethod;
begin
FStack.AddValuedChild(ntName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.DoOnComment(Sender: TObject; const Text: string);
var
Node: TCommentNode;
begin
case TokenID of
ptAnsiComment: Node := TCommentNode.Create(ntAnsiComment);
ptBorComment: Node := TCommentNode.Create(ntAnsiComment);
ptSlashesComment: Node := TCommentNode.Create(ntSlashesComment);
else
raise EParserException.Create(Lexer.PosXY.Y, Lexer.PosXY.X, Lexer.FileName, 'Invalid comment type');
end;
AssignLexerPositionToNode(Lexer, Node);
Node.Text := Text;
FComments.Add(Node);
end;
procedure TPasSyntaxTreeBuilder.ParserMessage(Sender: TObject;
const Typ: TMessageEventType; const Msg: string; X, Y: Integer);
begin
if Typ = TMessageEventType.meError then
raise EParserException.Create(Y, X, Lexer.FileName, Msg);
end;
procedure TPasSyntaxTreeBuilder.OutParameter;
begin
FStack.Push(ntParameters).SetAttribute(anKind, AttributeValues[atOut]);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ParameterFormal;
begin
FStack.Push(ntParameters);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ParameterName;
begin
FStack.AddValuedChild(ntName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.PointerSymbol;
begin
FStack.AddChild(ntDeref);
inherited;
end;
procedure TPasSyntaxTreeBuilder.PointerType;
begin
FStack.Push(ntType).SetAttribute(anType, AttributeValues[atPointer]);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.PositionalArgument;
begin
FStack.Push(ntPositionalArgument);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ProceduralType;
begin
FStack.Push(ntType).SetAttribute(anName, Lexer.Token);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ProcedureDeclarationSection;
begin
FStack.PushCompoundSyntaxNode(ntMethod);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ProcedureHeading;
begin
FStack.Peek.SetAttribute(anKind, AttributeValues[atProcedure]);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ProcedureProcedureName;
begin
FStack.Peek.SetAttribute(anName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.PropertyName;
begin
FStack.Peek.SetAttribute(anName, Lexer.Token);
inherited PropertyName;
end;
procedure TPasSyntaxTreeBuilder.PropertyParameterList;
var
TreeBuilderMethod: TTreeBuilderMethod;
begin
TreeBuilderMethod := CallInheritedPropertyParameterList;
BuildParametersList(TreeBuilderMethod);
end;
procedure TPasSyntaxTreeBuilder.RaiseStatement;
begin
FStack.Push(ntRaise);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.RecordFieldConstant;
var
Node: TSyntaxNode;
begin
Node := FStack.PushValuedNode(ntField, Lexer.Token);
try
Node.SetAttribute(anType, AttributeValues[atName]);
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.RecordType;
begin
inherited RecordType;
MoveMembersToVisibilityNodes(FStack.Peek);
end;
procedure TPasSyntaxTreeBuilder.RelativeOperator;
begin
case TokenID of
ptAs:
FStack.AddChild(ntAs);
ptEqual:
FStack.AddChild(ntEqual);
ptGreater:
FStack.AddChild(ntGreater);
ptGreaterEqual:
FStack.AddChild(ntGreaterEqual);
ptIn:
FStack.AddChild(ntIn);
ptIs:
FStack.AddChild(ntIs);
ptLower:
FStack.AddChild(ntLower);
ptLowerEqual:
FStack.AddChild(ntLowerEqual);
ptNotEqual:
FStack.AddChild(ntNotEqual);
else
FStack.AddChild(ntUnknown);
end;
inherited;
end;
procedure TPasSyntaxTreeBuilder.RepeatStatement;
begin
FStack.Push(ntRepeat);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.RequiresClause;
begin
FStack.Push(ntRequires);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.RequiresIdentifier;
var
NamesNode: TSyntaxNode;
begin
NamesNode := TSyntaxNode.Create(ntUnknown);
try
FStack.Push(NamesNode);
try
inherited;
finally
FStack.Pop;
end;
FStack.AddChild(ntPackage).SetAttribute(anName, NodeListToString(NamesNode));
finally
NamesNode.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.RequiresIdentifierId;
begin
FStack.AddChild(ntUnknown).SetAttribute(anName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.ResourceDeclaration;
begin
FStack.Push(ntResourceString);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ResourceValue;
begin
FStack.Push(ntValue);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ReturnType;
begin
FStack.Push(ntReturnType);
try
inherited;
finally
FStack.Pop
end;
end;
procedure TPasSyntaxTreeBuilder.RoundClose;
begin
FStack.AddChild(ntRoundClose);
inherited;
end;
procedure TPasSyntaxTreeBuilder.RoundOpen;
begin
FStack.AddChild(ntRoundOpen);
inherited;
end;
class function TPasSyntaxTreeBuilder.Run(const FileName: string;
InterfaceOnly: Boolean; IncludeHandler: IIncludeHandler;
OnHandleString: TStringEvent): TSyntaxNode;
var
Stream: TStringStream;
Builder: TPasSyntaxTreeBuilder;
begin
Stream := TStringStream.Create;
try
Stream.LoadFromFile(FileName);
Builder := TPasSyntaxTreeBuilder.Create;
Builder.InterfaceOnly := InterfaceOnly;
Builder.OnHandleString := OnHandleString;
try
Builder.InitDefinesDefinedByCompiler;
Builder.IncludeHandler := IncludeHandler;
Result := Builder.Run(Stream);
finally
Builder.Free;
end;
finally
Stream.Free;
end;
end;
function TPasSyntaxTreeBuilder.Run(SourceStream: TStream): TSyntaxNode;
begin
Result := TSyntaxNode.Create(ntUnit);
try
FStack.Clear;
FStack.Push(Result);
try
self.OnMessage := ParserMessage;
inherited Run('', SourceStream);
finally
FStack.Pop;
end;
except
on E: EParserException do
raise ESyntaxTreeException.Create(E.Line, E.Col, Lexer.FileName, E.Message, Result);
on E: ESyntaxError do
raise ESyntaxTreeException.Create(E.PosXY.X, E.PosXY.Y, Lexer.FileName, E.Message, Result);
else
FreeAndNil(Result);
raise;
end;
Assert(FStack.Count = 0);
end;
function TPasSyntaxTreeBuilder.NodeListToString(NamesNode: TSyntaxNode): string;
var
NamePartNode: TSyntaxNode;
begin
Result := '';
for NamePartNode in NamesNode.ChildNodes do
begin
if Result <> '' then
Result := Result + '.';
Result := Result + NamePartNode.GetAttribute(anName);
end;
DoHandleString(Result);
end;
procedure TPasSyntaxTreeBuilder.SetConstructor;
begin
FStack.Push(ntSet);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.SetElement;
begin
FStack.Push(ntElement);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.SimpleStatement;
var
RawStatement, Temp: TSyntaxNode;
Node, LHS, RHS: TSyntaxNode;
NodeList: TList<TSyntaxNode>;
I, AssignIdx: Integer;
Position: TTokenPoint;
FileName: string;
begin
Position := Lexer.PosXY;
FileName := Lexer.FileName;
RawStatement := TSyntaxNode.Create(ntStatement);
try
FStack.Push(RawStatement);
try
inherited;
finally
FStack.Pop;
end;
if not RawStatement.HasChildren then
Exit;
if RawStatement.FindNode(ntAssign) <> nil then
begin
Temp := FStack.Push(ntAssign);
try
Temp.Col := Position.X;
Temp.Line := Position.Y;
Temp.FileName := FileName;
NodeList := TList<TSyntaxNode>.Create;
try
AssignIdx := -1;
for I := 0 to Length(RawStatement.ChildNodes) - 1 do
begin
if RawStatement.ChildNodes[I].Typ = ntAssign then
begin
AssignIdx := I;
Break;
end;
NodeList.Add(RawStatement.ChildNodes[I]);
end;
if NodeList.Count = 0 then
raise EParserException.Create(Position.Y, Position.X, Lexer.FileName, 'Illegal expression');
LHS := FStack.AddChild(ntLHS);
LHS.AssignPositionFrom(NodeList[0]);
TExpressionTools.RawNodeListToTree(RawStatement, NodeList, LHS);
NodeList.Clear;
for I := AssignIdx + 1 to Length(RawStatement.ChildNodes) - 1 do
NodeList.Add(RawStatement.ChildNodes[I]);
if NodeList.Count = 0 then
raise EParserException.Create(Position.Y, Position.X, Lexer.FileName, 'Illegal expression');
RHS := FStack.AddChild(ntRHS);
RHS.AssignPositionFrom(NodeList[0]);
TExpressionTools.RawNodeListToTree(RawStatement, NodeList, RHS);
finally
NodeList.Free;
end;
finally
FStack.Pop;
end;
end else
begin
Temp := FStack.Push(ntCall);
try
Temp.Col := Position.X;
Temp.Line := Position.Y;
NodeList := TList<TSyntaxNode>.Create;
try
for Node in RawStatement.ChildNodes do
NodeList.Add(Node);
TExpressionTools.RawNodeListToTree(RawStatement, NodeList, FStack.Peek);
finally
NodeList.Free;
end;
finally
FStack.Pop;
end;
end;
finally
RawStatement.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.SimpleType;
begin
FStack.Push(ntType).SetAttribute(anName, Lexer.Token);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.StatementList;
begin
FStack.PushCompoundSyntaxNode(ntStatements);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.StorageDefault;
begin
FStack.Push(ntDefault);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.StringConst;
var
StrConst: TSyntaxNode;
Literal, Node: TSyntaxNode;
Str: string;
begin
StrConst := TSyntaxNode.Create(ntUnknown);
try
FStack.Push(StrConst);
try
inherited;
finally
FStack.Pop;
end;
Str := '';
for Literal in StrConst.ChildNodes do
Str := Str + TValuedSyntaxNode(Literal).Value;
finally
StrConst.Free;
end;
DoHandleString(Str);
Node := FStack.AddValuedChild(ntLiteral, Str);
Node.SetAttribute(anType, AttributeValues[atString]);
end;
procedure TPasSyntaxTreeBuilder.StringConstSimple;
begin
//TODO support ptAsciiChar
FStack.AddValuedChild(ntLiteral, AnsiDequotedStr(Lexer.Token, ''''));
inherited;
end;
procedure TPasSyntaxTreeBuilder.StringStatement;
begin
FStack.AddChild(ntType).SetAttribute(anName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.StructuredType;
begin
FStack.Push(ntType).SetAttribute(anType, Lexer.Token);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.SubrangeType;
begin
FStack.Push(ntType).SetAttribute(anName, AttributeValues[atSubRange]);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.ThenStatement;
begin
FStack.Push(ntThen);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.TryStatement;
begin
FStack.Push(ntTry);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.TypeArgs;
begin
FStack.Push(ntTypeArgs);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.TypeDeclaration;
begin
FStack.PushCompoundSyntaxNode(ntTypeDecl).SetAttribute(anName, Lexer.Token);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.TypeId;
var
TypeNode, InnerTypeNode, SubNode: TSyntaxNode;
TypeName, InnerTypeName: string;
i: integer;
begin
TypeNode := FStack.Push(ntType);
try
inherited;
InnerTypeName := '';
InnerTypeNode := TypeNode.FindNode(ntType);
if Assigned(InnerTypeNode) then
begin
InnerTypeName := InnerTypeNode.GetAttribute(anName);
for SubNode in InnerTypeNode.ChildNodes do
TypeNode.AddChild(SubNode.Clone);
TypeNode.DeleteChild(InnerTypeNode);
end;
TypeName := '';
for i := Length(TypeNode.ChildNodes) - 1 downto 0 do
begin
SubNode := TypeNode.ChildNodes[i];
if SubNode.Typ = ntType then
begin
if TypeName <> '' then
TypeName := '.' + TypeName;
TypeName := SubNode.GetAttribute(anName) + TypeName;
TypeNode.DeleteChild(SubNode);
end;
end;
if TypeName <> '' then
TypeName := '.' + TypeName;
TypeName := InnerTypeName + TypeName;
DoHandleString(TypeName);
TypeNode.SetAttribute(anName, TypeName);
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.TypeParamDecl;
var
OriginTypeParamNode, NewTypeParamNode, Constraints, TypeNode: TSyntaxNode;
TypeNodeCount: integer;
TypeNodesToDelete: TList<TSyntaxNode>;
begin
OriginTypeParamNode := FStack.Push(ntTypeParam);
try
inherited;
finally
FStack.Pop;
end;
Constraints := OriginTypeParamNode.FindNode(ntConstraints);
TypeNodeCount := 0;
TypeNodesToDelete := TList<TSyntaxNode>.Create;
try
for TypeNode in OriginTypeParamNode.ChildNodes do
begin
if TypeNode.Typ = ntType then
begin
inc(TypeNodeCount);
if TypeNodeCount > 1 then
begin
NewTypeParamNode := FStack.Push(ntTypeParam);
try
NewTypeParamNode.AddChild(TypeNode.Clone);
if Assigned(Constraints) then
NewTypeParamNode.AddChild(Constraints.Clone);
TypeNodesToDelete.Add(TypeNode);
finally
FStack.Pop;
end;
end;
end;
end;
for TypeNode in TypeNodesToDelete do
OriginTypeParamNode.DeleteChild(TypeNode);
finally
TypeNodesToDelete.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.TypeParams;
begin
FStack.Push(ntTypeParams);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.TypeSection;
begin
FStack.Push(ntTypeSection);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.TypeSimple;
begin
FStack.Push(ntType).SetAttribute(anName, Lexer.Token);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.UnaryMinus;
begin
FStack.AddChild(ntUnaryMinus);
inherited;
end;
procedure TPasSyntaxTreeBuilder.UnitFile;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Peek;
AssignLexerPositionToNode(Lexer, Temp);
inherited;
end;
procedure TPasSyntaxTreeBuilder.UnitId;
begin
FStack.AddChild(ntUnknown).SetAttribute(anName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.UnitName;
var
NamesNode: TSyntaxNode;
begin
NamesNode := TSyntaxNode.Create(ntUnknown);
try
FStack.Push(NamesNode);
try
inherited;
finally
FStack.Pop;
end;
FStack.Peek.SetAttribute(anName, NodeListToString(NamesNode));
finally
NamesNode.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.UsedUnitName;
var
NamesNode, UnitNode: TSyntaxNode;
Position: TTokenPoint;
FileName: string;
begin
Position := Lexer.PosXY;
FileName := Lexer.FileName;
NamesNode := TSyntaxNode.Create(ntUnit);
try
FStack.Push(NamesNode);
try
inherited;
finally
FStack.Pop;
end;
UnitNode := FStack.AddChild(ntUnit);
UnitNode.SetAttribute(anName, NodeListToString(NamesNode));
UnitNode.Col := Position.X;
UnitNode.Line := Position.Y;
UnitNode.FileName := FileName;
finally
NamesNode.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.UsesClause;
begin
FStack.PushCompoundSyntaxNode(ntUses);
try
inherited;
SetCurrentCompoundNodesEndPosition;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VarAbsolute;
begin
FStack.Push(ntAbsolute);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VarDeclaration;
begin
FStack.Push(ntVariables);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VarName;
begin
FStack.AddValuedChild(ntName, Lexer.Token);
inherited;
end;
procedure TPasSyntaxTreeBuilder.VarParameter;
begin
FStack.Push(ntParameters).SetAttribute(anKind, AttributeValues[atVar]);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VarSection;
var
VarSect: TSyntaxNode;
begin
VarSect := TSyntaxNode.Create(ntUnknown);
try
FStack.Push(ntVariables);
FStack.Push(VarSect);
try
inherited VarSection;
finally
FStack.Pop;
end;
RearrangeVarSection(VarSect);
FStack.Pop;
finally
VarSect.Free;
end;
end;
procedure TPasSyntaxTreeBuilder.RearrangeVarSection(const VarSect: TSyntaxNode);
var
Temp: TSyntaxNode;
VarList, Variable, TypeInfo, ValueInfo: TSyntaxNode;
begin
for VarList in VarSect.ChildNodes do
begin
TypeInfo := VarList.FindNode(ntType);
ValueInfo := VarList.FindNode(ntValue);
for Variable in VarList.ChildNodes do
begin
if Variable.Typ <> ntName then
Continue;
Temp := FStack.Push(ntVariable);
try
Temp.AssignPositionFrom(Variable);
FStack.AddChild(Variable.Clone);
if Assigned(TypeInfo) then
FStack.AddChild(TypeInfo.Clone);
if Assigned(ValueInfo) then
FStack.AddChild(ValueInfo.Clone)
else
begin
Temp := VarList.FindNode([ntAbsolute, ntValue, ntExpression, ntIdentifier]);
if Assigned(Temp) then
FStack.AddChild(ntAbsolute).AddChild(Temp.Clone);
end;
finally
FStack.Pop;
end;
end;
end;
end;
procedure TPasSyntaxTreeBuilder.VisibilityStrictPrivate;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Push(ntStrictPrivate);
try
Temp.SetAttribute(anVisibility, AttributeValues[atTrue]);
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VisibilityPrivate;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Push(ntPrivate);
try
Temp.SetAttribute(anVisibility, AttributeValues[atTrue]);
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VisibilityStrictProtected;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Push(ntStrictProtected);
try
Temp.SetAttribute(anVisibility, AttributeValues[atTrue]);
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VisibilityProtected;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Push(ntProtected);
try
Temp.SetAttribute(anVisibility, AttributeValues[atTrue]);
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VisibilityPublic;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Push(ntPublic);
try
Temp.SetAttribute(anVisibility, AttributeValues[atTrue]);
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.VisibilityPublished;
var
Temp: TSyntaxNode;
begin
Temp := FStack.Push(ntPublished);
try
Temp.SetAttribute(anVisibility, AttributeValues[atTrue]);
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.WhileStatement;
begin
FStack.Push(ntWhile);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.WithExpressionList;
begin
FStack.Push(ntExpressions);
try
inherited;
finally
FStack.Pop;
end;
end;
procedure TPasSyntaxTreeBuilder.WithStatement;
begin
FStack.Push(ntWith);
try
inherited;
finally
FStack.Pop;
end;
end;
{ ESyntaxTreeException }
constructor ESyntaxTreeException.Create(Line, Col: Integer; const FileName, Msg: string;
SyntaxTree: TSyntaxNode);
begin
inherited Create(Line, Col, FileName, Msg);
FSyntaxTree := SyntaxTree;
end;
destructor ESyntaxTreeException.Destroy;
begin
FSyntaxTree.Free;
inherited;
end;
initialization
InitAttributeValues;
end. |
unit uJxdAudioFilter;
interface
uses
Windows, SysUtils, BaseClass, MMSystem, DirectShow9, ActiveX;
type
TAudioChannelStyle = (asAll, asLeft, asRight);
TxdAudioChannelFilter = class(TBCTransInPlaceFilter)
public
AudioChannelStyle: TAudioChannelStyle;
constructor Create;
destructor Destroy; override;
function CheckInputType(mtIn: PAMMediaType): HRESULT; override;
function Transform(Sample: IMediaSample): HRESULT; override;
private
procedure PCMWaveData(Buf: PByte; Length: Integer; P: PWaveFormatEx);
end;
implementation
const
CtAudioChannelFilterName = 'Audio Filter';
CtAudioChannelGUID : TGUID = '{3F06D3B4-F953-463B-BF42-FE835BEE9AB2}';
function TxdAudioChannelFilter.CheckInputType(mtIn: PAMMediaType): HRESULT;
const
WAVE_FORMAT_IEEE_FLOAT = $0003;
WAVE_FORMAT_DOLBY_AC3_SPDIF = $0092;
var
P: PWaveFormatEx;
begin
Result := VFW_E_TYPE_NOT_ACCEPTED;
if not IsEqualGUID(mtIn^.formattype, FORMAT_WaveFormatEx) then
Exit;
P := PWaveFormatEx(mtIn^.pbFormat);
if (P^.nChannels > 2) and (P^.wFormatTag <> WAVE_FORMAT_EXTENSIBLE) then
begin
Result := VFW_E_INVALIDMEDIATYPE;
Exit;
end;
if IsEqualGUID(mtIn^.majortype, MEDIATYPE_Audio) and (P^.wBitsPerSample in [8, 16, 24, 32]) and
((P^.wFormatTag = WAVE_FORMAT_PCM) or (P^.wFormatTag = WAVE_FORMAT_IEEE_FLOAT) or
(P^.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF) or (P^.wFormatTag = WAVE_FORMAT_EXTENSIBLE)) then
Result := S_OK;
end;
constructor TxdAudioChannelFilter.Create;
var
hr: HRESULT;
begin
inherited Create(CtAudioChannelFilterName, nil, CtAudioChannelGUID, hr);
AudioChannelStyle := asAll;
end;
destructor TxdAudioChannelFilter.destroy;
begin
inherited;
end;
procedure TxdAudioChannelFilter.PCMWaveData(Buf: PByte; Length: Integer; P: PWaveFormatEx);
var
I, J, K, B: Word;
begin
if (AudioChannelStyle = asAll) or (P.nChannels = 1) or (not P.wBitsPerSample in [8, 16, 24, 32]) then Exit;
try
B := P.wBitsPerSample shr 2;
K := B shr 2;
for I := 0 to Length - 1 do
begin
if I mod B = 0 then
begin
for J := 0 to B shr 1 - 1 do
if AudioChannelStyle = asLeft then
PByte(Integer(Buf) + I + J + K + 1)^ := PByte(Integer(Buf) + I + J)^
else
PByte(Integer(Buf) + I + J)^ := PByte(Integer(Buf) + I + J + K + 1)^;
end;
end;
except
end;
end;
function TxdAudioChannelFilter.Transform(Sample: IMediaSample): HRESULT;
var
Buf: PByte;
begin
Result := S_OK;
try
Sample.GetPointer(Buf);
PCMWaveData(Buf, Sample.GetActualDataLength, FInput.CurrentMediaType.MediaType.pbFormat);
except
Result := S_FALSE;
end;
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Janela de Pagamento das Parcelas
The MIT License
Copyright: Copyright (C) 2016 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</p>
@author Albert Eije
@version 2.0
******************************************************************************* }
unit UFinParcelaPagamento;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Atributos,
Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids,
DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, ViewFinLancamentoPagarVO,
ViewFinLancamentoPagarController, Tipos, Constantes, LabeledCtrls,
ActnList, RibbonSilverStyleActnCtrls, ActnMan, Mask, JvExMask, JvToolEdit,
JvExStdCtrls, JvEdit, JvValidateEdit, ToolWin, ActnCtrls, JvBaseEdits,
Generics.Collections, Biblioteca, RTTI, FinChequeEmitidoVO, AdmParametroVO,
System.Actions, Controller;
type
[TFormDescription(TConstantes.MODULO_CONTAS_PAGAR, 'Pagamento')]
TFFinParcelaPagamento = class(TFTelaCadastro)
BevelEdits: TBevel;
PanelEditsInterno: TPanel;
EditDataPagamento: TLabeledDateEdit;
EditTaxaJuro: TLabeledCalcEdit;
EditValorJuro: TLabeledCalcEdit;
EditValorMulta: TLabeledCalcEdit;
EditValorDesconto: TLabeledCalcEdit;
EditTaxaDesconto: TLabeledCalcEdit;
EditTaxaMulta: TLabeledCalcEdit;
MemoHistorico: TLabeledMemo;
ActionManager: TActionManager;
ActionBaixarParcela: TAction;
DSParcelaPagamento: TDataSource;
CDSParcelaPagamento: TClientDataSet;
CDSParcelaPagamentoID: TIntegerField;
CDSParcelaPagamentoID_FIN_PARCELA_PAGAR: TIntegerField;
CDSParcelaPagamentoID_FIN_CHEQUE_EMITIDO: TIntegerField;
CDSParcelaPagamentoID_FIN_TIPO_PAGAMENTO: TIntegerField;
CDSParcelaPagamentoID_CONTA_CAIXA: TIntegerField;
CDSParcelaPagamentoDATA_PAGAMENTO: TDateField;
CDSParcelaPagamentoTAXA_JURO: TFMTBCDField;
CDSParcelaPagamentoTAXA_MULTA: TFMTBCDField;
CDSParcelaPagamentoTAXA_DESCONTO: TFMTBCDField;
CDSParcelaPagamentoVALOR_JURO: TFMTBCDField;
CDSParcelaPagamentoVALOR_MULTA: TFMTBCDField;
CDSParcelaPagamentoVALOR_DESCONTO: TFMTBCDField;
CDSParcelaPagamentoVALOR_PAGO: TFMTBCDField;
CDSParcelaPagamentoCONTA_CAIXANOME: TStringField;
CDSParcelaPagamentoTIPO_PAGAMENTODESCRICAO: TStringField;
CDSParcelaPagamentoCHEQUENUMERO: TIntegerField;
EditIdTipoPagamento: TLabeledCalcEdit;
EditCodigoTipoPagamento: TLabeledEdit;
EditTipoPagamento: TLabeledEdit;
EditIdContaCaixa: TLabeledCalcEdit;
EditContaCaixa: TLabeledEdit;
EditValorPago: TLabeledCalcEdit;
EditValorAPagar: TLabeledCalcEdit;
EditDataVencimento: TLabeledDateEdit;
CDSParcelaPagamentoHISTORICO: TStringField;
GroupBox1: TGroupBox;
Label1: TLabel;
EditDataInicio: TLabeledDateEdit;
EditDataFim: TLabeledDateEdit;
PanelParcelaPaga: TPanel;
GridPagamentos: TJvDBUltimGrid;
ActionToolBar1: TActionToolBar;
ComboBoxTipoBaixa: TLabeledComboBox;
PanelTotaisPagos: TPanel;
ActionExcluirParcela: TAction;
procedure FormCreate(Sender: TObject);
procedure ActionBaixarParcelaExecute(Sender: TObject);
procedure CalcularTotalPago(Sender: TObject);
procedure BotaoConsultarClick(Sender: TObject);
procedure BotaoSalvarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BaixarParcela;
procedure BaixarParcelaCheque;
procedure CalcularTotais;
procedure GridCellClick(Column: TColumn);
procedure GridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
function VerificarPacotePagamentoCheque: Boolean;
procedure EditIdTipoPagamentoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditIdContaCaixaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ActionExcluirParcelaExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure GridParaEdits; override;
procedure ControlaBotoes; override;
procedure ControlaPopupMenu; override;
procedure LimparCampos; override;
function MontaFiltro: string; override;
// Controles CRUD
function DoEditar: Boolean; override;
end;
var
FFinParcelaPagamento: TFFinParcelaPagamento;
ChequeEmitido: TFinChequeEmitidoVO;
SomaCheque: Extended;
AdmParametroVO: TAdmParametroVO;
implementation
uses
FinParcelaPagamentoVO, FinParcelaPagamentoController, FinParcelaPagarVO,
FinParcelaPagarController, FinTipoPagamentoVO, FinTipoPagamentoController,
ContaCaixaVO, ContaCaixaController, UTela, USelecionaCheque, UDataModule,
AdmParametroController;
{$R *.dfm}
{$REGION 'Infra'}
procedure TFFinParcelaPagamento.FormCreate(Sender: TObject);
var
Filtro: String;
begin
ClasseObjetoGridVO := TViewFinLancamentoPagarVO;
ObjetoController := TViewFinLancamentoPagarController.Create;
inherited;
Filtro := 'ID_EMPRESA = ' + IntToStr(Sessao.Empresa.Id);
AdmParametroVO := TAdmParametroVO(TController.BuscarObjeto('AdmParametroController.TAdmParametroController', 'ConsultaObjeto', [Filtro], 'GET'));
end;
procedure TFFinParcelaPagamento.FormShow(Sender: TObject);
begin
inherited;
EditDataInicio.Date := Now;
EditDataFim.Date := Now;
end;
procedure TFFinParcelaPagamento.ControlaBotoes;
begin
inherited;
BotaoInserir.Visible := False;
BotaoExcluir.Visible := False;
BotaoCancelar.Visible := False;
BotaoAlterar.Caption := 'Confirmar [F3]';
BotaoSalvar.Caption := 'Retornar [F12]';
end;
procedure TFFinParcelaPagamento.ControlaPopupMenu;
begin
inherited;
MenuInserir.Visible := False;
MenuExcluir.Visible := False;
MenuCancelar.Visible := False;
MenuAlterar.Caption := 'Confirmar [F3]';
menuSalvar.Caption := 'Retornar [F12]';
end;
procedure TFFinParcelaPagamento.LimparCampos;
var
DataInicioInformada, DataFimInformada: TDateTime;
begin
DataInicioInformada := EditDataInicio.Date;
DataFimInformada := EditDataFim.Date;
inherited;
CDSParcelaPagamento.EmptyDataSet;
EditDataInicio.Date := DataInicioInformada;
EditDataFim.Date := DataFimInformada;
end;
{$ENDREGION}
{$REGION 'Controles CRUD'}
function TFFinParcelaPagamento.DoEditar: Boolean;
begin
if not CDSGrid.IsEmpty then
begin
if CDSGrid.FieldByName('SITUACAO_PARCELA').AsString = '02' then
begin
Application.MessageBox('Procedimento não permitido. Parcela já quitada.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
Exit;
end;
if CDSGrid.FieldByName('FORNECEDOR_SOFRE_RETENCAO').AsString = 'S' then
begin
Application.MessageBox('Procedimento não permitido. Fornecedor com retenção.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
Exit;
end;
if VerificarPacotePagamentoCheque then
begin
ChequeEmitido := TFinChequeEmitidoVO.Create;
Application.CreateForm(TFSelecionaCheque, FSelecionaCheque);
FSelecionaCheque.EditValorCheque.Value := SomaCheque;
FSelecionaCheque.ShowModal;
if FSelecionaCheque.Confirmou then
begin
ChequeEmitido.IdCheque := FSelecionaCheque.CDSChequesEmSerID_CHEQUE.AsInteger;
ChequeEmitido.DataEmissao := now;
ChequeEmitido.Valor := FSelecionaCheque.EditValorCheque.Value;
ChequeEmitido.NominalA := FSelecionaCheque.EditNominalA.Text;
ChequeEmitido.BomPara := FSelecionaCheque.EditBomPara.Date;
BaixarParcelaCheque;
FreeAndNil(FSelecionaCheque);
end;
end
else
begin
Result := inherited DoEditar;
if Result then
begin
ComboBoxTipoBaixa.SetFocus;
end;
end;
end;
end;
function TFFinParcelaPagamento.VerificarPacotePagamentoCheque: Boolean;
var
LinhaAtual: TBookMark;
ParcelasVencidas: Boolean;
begin
Result := False;
ParcelasVencidas := False;
LinhaAtual := CDSGrid.GetBookmark;
SomaCheque := 0;
CDSGrid.DisableControls;
CDSGrid.First;
while not CDSGrid.Eof do
begin
if CDSGrid.FieldByName('EmitirCheque').AsString = 'S' then
SomaCheque := SomaCheque + CDSGrid.FieldByName('VALOR_PARCELA').AsFloat;
ParcelasVencidas := CDSGrid.FieldByName('DATA_VENCIMENTO').AsDateTime < Date;
CDSGrid.Next;
end;
if CDSGrid.BookmarkValid(LinhaAtual) then
begin
CDSGrid.GotoBookmark(LinhaAtual);
CDSGrid.FreeBookmark(LinhaAtual);
end;
CDSGrid.EnableControls;
if SomaCheque = 0 then
Exit;
if ParcelasVencidas then
begin
Application.MessageBox('Procedimento não permitido. Parcela sem valores ou vencidas.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
CDSGrid.EnableControls;
Exit;
end;
Result := True;
end;
{$ENDREGION}
{$REGION 'Campos Transientes'}
procedure TFFinParcelaPagamento.EditIdTipoPagamentoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Filtro: String;
begin
if Key = VK_F1 then
begin
if EditIdTipoPagamento.Value <> 0 then
Filtro := 'ID = ' + EditIdTipoPagamento.Text
else
Filtro := 'ID=0';
try
EditIdTipoPagamento.Clear;
EditCodigoTipoPagamento.Clear;
EditTipoPagamento.Clear;
if not PopulaCamposTransientes(Filtro, TFinTipoPagamentoVO, TFinTipoPagamentoController) then
PopulaCamposTransientesLookup(TFinTipoPagamentoVO, TFinTipoPagamentoController);
if CDSTransiente.RecordCount > 0 then
begin
EditIdTipoPagamento.Text := CDSTransiente.FieldByName('ID').AsString;
EditCodigoTipoPagamento.Text := CDSTransiente.FieldByName('TIPO').AsString;
EditTipoPagamento.Text := CDSTransiente.FieldByName('DESCRICAO').AsString;
end
else
begin
Exit;
EditIdContaCaixa.SetFocus;
end;
finally
CDSTransiente.Close;
end;
end;
end;
procedure TFFinParcelaPagamento.EditIdContaCaixaKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Filtro: String;
begin
if Key = VK_F1 then
begin
if EditIdContaCaixa.Value <> 0 then
Filtro := 'ID = ' + EditIdContaCaixa.Text
else
Filtro := 'ID=0';
try
EditIdContaCaixa.Clear;
EditContaCaixa.Clear;
if not PopulaCamposTransientes(Filtro, TContaCaixaVO, TContaCaixaController) then
PopulaCamposTransientesLookup(TContaCaixaVO, TContaCaixaController);
if CDSTransiente.RecordCount > 0 then
begin
EditIdContaCaixa.Text := CDSTransiente.FieldByName('ID').AsString;
EditContaCaixa.Text := CDSTransiente.FieldByName('NOME').AsString;
end
else
begin
Exit;
EditDataVencimento.SetFocus;
end;
finally
CDSTransiente.Close;
end;
end;
end;
{$ENDREGION}
{$REGION 'Controle de Grid'}
procedure TFFinParcelaPagamento.GridCellClick(Column: TColumn);
begin
if Column.Index = 0 then
begin
if CDSGrid.FieldByName('SITUACAO_PARCELA').AsString = '02' then
begin
Application.MessageBox('Procedimento não permitido. Parcela já quitada.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
Exit;
end;
if CDSGrid.FieldByName('FORNECEDOR_SOFRE_RETENCAO').AsString = 'S' then
begin
Application.MessageBox('Procedimento não permitido. Fornecedor com retenção.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
Exit;
end;
CDSGrid.Edit;
if CDSGrid.FieldByName('EmitirCheque').AsString = '' then
CDSGrid.FieldByName('EmitirCheque').AsString := 'S'
else
CDSGrid.FieldByName('EmitirCheque').AsString := '';
CDSGrid.Post;
end;
end;
procedure TFFinParcelaPagamento.GridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
lIcone : TBitmap;
lRect: TRect;
begin
lRect := Rect;
lIcone := TBitmap.Create;
if Column.Index = 0 then
begin
if Grid.Columns[0].Width <> 32 then
Grid.Columns[0].Width := 32;
try
if Grid.Columns[1].Field.Value = '' then
begin
FDataModule.ImagensCheck.GetBitmap(0, lIcone);
Grid.Canvas.Draw(Rect.Left+8 ,Rect.Top+1, lIcone);
end
else if Grid.Columns[1].Field.Value = 'S' then
begin
FDataModule.ImagensCheck.GetBitmap(1, lIcone);
Grid.Canvas.Draw(Rect.Left+8,Rect.Top+1, lIcone);
end
finally
lIcone.Free;
end;
end;
end;
procedure TFFinParcelaPagamento.GridParaEdits;
var
Filtro: String;
begin
inherited;
if not CDSGrid.IsEmpty then
begin
ObjetoVO := TViewFinLancamentoPagarVO(TController.BuscarObjeto('ViewFinLancamentoPagarController.TViewFinLancamentoPagarController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET'));
end;
if Assigned(ObjetoVO) then
begin
EditIdContaCaixa.AsInteger := TViewFinLancamentoPagarVO(ObjetoVO).IdContaCaixa;
EditContaCaixa.Text := TViewFinLancamentoPagarVO(ObjetoVO).NomeContaCaixa;
EditDataVencimento.Date := TViewFinLancamentoPagarVO(ObjetoVO).DataVencimento;
EditValorAPagar.Value := TViewFinLancamentoPagarVO(ObjetoVO).ValorParcela;
EditTaxaJuro.Value := TViewFinLancamentoPagarVO(ObjetoVO).TaxaJuro;
EditValorJuro.Value := TViewFinLancamentoPagarVO(ObjetoVO).ValorJuro;
EditTaxaMulta.Value := TViewFinLancamentoPagarVO(ObjetoVO).TaxaMulta;
EditValorMulta.Value := TViewFinLancamentoPagarVO(ObjetoVO).ValorMulta;
EditTaxaDesconto.Value := TViewFinLancamentoPagarVO(ObjetoVO).TaxaDesconto;
EditValorDesconto.Value := TViewFinLancamentoPagarVO(ObjetoVO).ValorDesconto;
CalcularTotalPago(nil);
TFinParcelaPagamentoController.SetDataSet(CDSParcelaPagamento);
Filtro := 'ID_FIN_PARCELA_PAGAR=' + QuotedStr(IntToStr(CDSGrid.FieldByName('ID_PARCELA_PAGAR').AsInteger));
TController.ExecutarMetodo('FinParcelaPagamentoController.TFinParcelaPagamentoController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista');
CalcularTotais;
end;
end;
{$ENDREGION}
{$REGION 'Actions'}
procedure TFFinParcelaPagamento.ActionBaixarParcelaExecute(Sender: TObject);
begin
if EditIdTipoPagamento.AsInteger <= 0 then
begin
Application.MessageBox('É necessário informar o tipo de pagamento.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
EditIdTipoPagamento.SetFocus;
Exit;
end;
if EditIdContaCaixa.AsInteger <= 0 then
begin
Application.MessageBox('É necessário informar a conta caixa.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION);
EditIdContaCaixa.SetFocus;
Exit;
end;
ChequeEmitido := TFinChequeEmitidoVO.Create;
if EditCodigoTipoPagamento.Text = '02' then
begin
Application.CreateForm(TFSelecionaCheque, FSelecionaCheque);
FSelecionaCheque.EditBomPara.Date := EditDataPagamento.Date;
FSelecionaCheque.EditValorCheque.Value := EditValorPago.Value;
FSelecionaCheque.MemoHistorico.Text := MemoHistorico.Text;
FSelecionaCheque.ShowModal;
if FSelecionaCheque.Confirmou then
begin
ChequeEmitido.IdCheque := FSelecionaCheque.CDSChequesEmSerID_CHEQUE.AsInteger;
ChequeEmitido.DataEmissao := now;
ChequeEmitido.Valor := FSelecionaCheque.EditValorCheque.Value;
ChequeEmitido.NominalA := FSelecionaCheque.EditNominalA.Text;
ChequeEmitido.BomPara := FSelecionaCheque.EditBomPara.Date;
BaixarParcela;
FreeAndNil(FSelecionaCheque);
end;
end
else
BaixarParcela;
end;
procedure TFFinParcelaPagamento.ActionExcluirParcelaExecute(Sender: TObject);
var
ParcelaPagar: TFinParcelaPagarVO;
begin
/// EXERCICIO: VERIFIQUE SE A IMPLEMENTAÇÃO ESTÁ CORRETA. CORRIJA O QUE FOR NECESSÁRIO.
if CDSParcelaPagamentoID.AsInteger > 0 then
TFinParcelaPagamentoController.Exclui(CDSParcelaPagamentoID.AsInteger);
CDSParcelaPagamento.Delete;
if CDSParcelaPagamento.IsEmpty then
begin
ParcelaPagar := TFinParcelaPagarVO(TController.BuscarObjeto('FinParcelaPagarController.TFinParcelaPagarController', 'ConsultaObjeto', ['ID=' + CDSGrid.FieldByName('ID_PARCELA_PAGAR').AsString], 'GET'));
ParcelaPagar.IdFinStatusParcela := AdmParametroVO.FinParcelaAberto;
TController.ExecutarMetodo('FinParcelaPagarController.TFinParcelaPagarController', 'Altera', [ParcelaPagar], 'POST', 'Boolean');
end;
CalcularTotais;
end;
procedure TFFinParcelaPagamento.BaixarParcela;
var
ParcelaPagar: TFinParcelaPagarVO;
begin
ParcelaPagar := TFinParcelaPagarVO(TController.BuscarObjeto('FinParcelaPagarController.TFinParcelaPagarController', 'ConsultaObjeto', ['ID=' + CDSGrid.FieldByName('ID_PARCELA_PAGAR').AsString], 'GET'));
if ComboBoxTipoBaixa.ItemIndex = 0 then
ParcelaPagar.IdFinStatusParcela := AdmParametroVO.FinParcelaQuitado
else if ComboBoxTipoBaixa.ItemIndex = 1 then
ParcelaPagar.IdFinStatusParcela := AdmParametroVO.FinParcelaQuitadoParcial;
ParcelaPagar.FinParcelaPagamentoVO := TFinParcelaPagamentoVO.Create;
ParcelaPagar.FinParcelaPagamentoVO.IdFinTipoPagamento := EditIdTipoPagamento.AsInteger;
ParcelaPagar.FinParcelaPagamentoVO.IdFinParcelaPagar := ParcelaPagar.Id;
ParcelaPagar.FinParcelaPagamentoVO.IdContaCaixa := EditIdContaCaixa.AsInteger;
ParcelaPagar.FinParcelaPagamentoVO.DataPagamento := EditDataPagamento.Date;
ParcelaPagar.FinParcelaPagamentoVO.TaxaJuro := EditTaxaJuro.Value;
ParcelaPagar.FinParcelaPagamentoVO.ValorJuro := EditValorJuro.Value;
ParcelaPagar.FinParcelaPagamentoVO.TaxaMulta := EditTaxaMulta.Value;
ParcelaPagar.FinParcelaPagamentoVO.ValorMulta := EditValorMulta.Value;
ParcelaPagar.FinParcelaPagamentoVO.TaxaDesconto := EditTaxaDesconto.Value;
ParcelaPagar.FinParcelaPagamentoVO.ValorDesconto := EditValorDesconto.Value;
ParcelaPagar.FinParcelaPagamentoVO.Historico := Trim(MemoHistorico.Text);
ParcelaPagar.FinParcelaPagamentoVO.ValorPago := EditValorPago.Value;
ParcelaPagar.FinChequeEmitidoVO := ChequeEmitido;
TController.ExecutarMetodo('FinParcelaPagarController.TFinParcelaPagarController', 'Altera', [ParcelaPagar], 'POST', 'Boolean');
TFinParcelaPagamentoController.SetDataSet(CDSParcelaPagamento);
Filtro := 'ID_FIN_PARCELA_PAGAR=' + QuotedStr(IntToStr(CDSGrid.FieldByName('ID_PARCELA_PAGAR').AsInteger));
TController.ExecutarMetodo('FinParcelaPagamentoController.TFinParcelaPagamentoController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista');
CalcularTotais;
end;
procedure TFFinParcelaPagamento.BaixarParcelaCheque;
var
ParcelaPagar, ObjetoPersistencia: TFinParcelaPagarVO;
ParcelaPagamento: TFinParcelaPagamentoVO;
ListaParcelaPagar: TObjectList<TFinParcelaPagarVO>;
ListaParcelaPagamento: TObjectList<TFinParcelaPagamentoVO>;
begin
try
ListaParcelaPagar := TObjectList<TFinParcelaPagarVO>.Create;
ListaParcelaPagamento := TObjectList<TFinParcelaPagamentoVO>.Create;
CDSGrid.DisableControls;
CDSGrid.First;
while not CDSGrid.Eof do
begin
if CDSGrid.FieldByName('EmitirCheque').AsString = 'S' then
begin
ParcelaPagar := TFinParcelaPagarVO(TController.BuscarObjeto('FinParcelaPagarController.TFinParcelaPagarController', 'ConsultaObjeto', ['ID=' + CDSGrid.FieldByName('ID_PARCELA_PAGAR').AsString], 'GET'));
ParcelaPagar.IdFinStatusParcela := AdmParametroVO.FinParcelaQuitado;
ParcelaPagamento := TFinParcelaPagamentoVO.Create;
ParcelaPagamento.IdFinTipoPagamento := 2;
ParcelaPagamento.IdFinParcelaPagar := ParcelaPagar.Id;
ParcelaPagamento.IdContaCaixa := FSelecionaCheque.CDSChequesEmSerID_CONTA_CAIXA.AsInteger;
ParcelaPagamento.DataPagamento := FSelecionaCheque.EditBomPara.Date;
ParcelaPagamento.Historico := FSelecionaCheque.MemoHistorico.Text;
ParcelaPagamento.ValorPago := ParcelaPagar.Valor;
ListaParcelaPagar.Add(ParcelaPagar);
ListaParcelaPagamento.Add(ParcelaPagamento);
end;
CDSGrid.Next;
end;
CDSGrid.First;
CDSGrid.EnableControls;
ObjetoPersistencia := TFinParcelaPagarVO.Create;
ObjetoPersistencia.ListaParcelaPagarVO := ListaParcelaPagar;
ObjetoPersistencia.ListaParcelaPagamentoVO := ListaParcelaPagamento;
ObjetoPersistencia.FinChequeEmitidoVO := ChequeEmitido;
TController.ExecutarMetodo('FinParcelaPagarController.TFinParcelaPagarController', 'BaixarParcelaCheque', [ObjetoPersistencia], 'POST', 'Boolean');
BotaoConsultar.Click;
finally
end;
end;
procedure TFFinParcelaPagamento.BotaoConsultarClick(Sender: TObject);
var
Contexto: TRttiContext;
Tipo: TRttiType;
NomeClasseController: String;
begin
Filtro := MontaFiltro;
if Filtro <> 'ERRO' then
begin
Pagina := 0;
Contexto := TRttiContext.Create;
try
Tipo := Contexto.GetType(ObjetoController.ClassType);
ObjetoController.SetDataSet(CDSGrid);
NomeClasseController := ObjetoController.UnitName + '.' + ObjetoController.ClassName;
TController.ExecutarMetodo(NomeClasseController, 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista');
ControlaBotoesNavegacaoPagina;
finally
Contexto.Free;
end;
if not CDSGrid.IsEmpty then
Grid.SetFocus;
end
else
EditCriterioRapido.SetFocus;
end;
procedure TFFinParcelaPagamento.BotaoSalvarClick(Sender: TObject);
begin
inherited;
BotaoConsultar.Click;
end;
/// EXERCICIO: LEVE EM CONSIDERACAO O STATUS DA PARCELA
function TFFinParcelaPagamento.MontaFiltro: string;
var
Item: TItemComboBox;
Idx: Integer;
DataSetField: TField;
DataSet: TClientDataSet;
begin
DataSet := CDSGrid;
if ComboBoxCampos.ItemIndex <> -1 then
begin
if Trim(EditCriterioRapido.Text) = '' then
EditCriterioRapido.Text := '*';
Idx := ComboBoxCampos.ItemIndex;
Item := TItemComboBox(ComboBoxCampos.Items.Objects[Idx]);
DataSetField := DataSet.FindField(Item.Campo);
if DataSetField.DataType = ftDateTime then
begin
try
Result := '[' + Item.Campo + '] IN ' + '(' + QuotedStr(FormatDateTime('yyyy-mm-dd', StrToDate(EditCriterioRapido.Text))) + ')';
except
Application.MessageBox('Data informada inválida.', 'Erro', MB_OK + MB_ICONERROR);
Result := 'ERRO';
end;
end
else
Result := '([DATA_VENCIMENTO] between ' + QuotedStr(DataParaTexto(EditDataInicio.Date)) + ' and ' + QuotedStr(DataParaTexto(EditDataFim.Date)) + ') and [' + Item.Campo + '] LIKE ' + QuotedStr('%' + EditCriterioRapido.Text + '%');
end
else
begin
Result := ' 1=1 ';
end;
end;
procedure TFFinParcelaPagamento.CalcularTotalPago(Sender: TObject);
begin
EditValorJuro.Value := (EditValorAPagar.Value * (EditTaxaJuro.Value / 30) / 100) * (Now - EditDataVencimento.Date);
EditValorMulta.Value := EditValorAPagar.Value * (EditTaxaMulta.Value / 100);
EditValorDesconto.Value := EditValorAPagar.Value * (EditTaxaDesconto.Value / 100);
EditValorPago.Value := EditValorAPagar.Value + EditValorJuro.Value + EditValorMulta.Value - EditValorDesconto.Value;
end;
procedure TFFinParcelaPagamento.CalcularTotais;
var
Juro, Multa, Desconto, Total, Saldo: Extended;
begin
Juro := 0;
Multa := 0;
Desconto := 0;
Total := 0;
Saldo := 0;
//
CDSParcelaPagamento.DisableControls;
CDSParcelaPagamento.First;
while not CDSParcelaPagamento.Eof do
begin
Juro := Juro + CDSParcelaPagamento.FieldByName('VALOR_JURO').AsExtended;
Multa := Multa + CDSParcelaPagamento.FieldByName('VALOR_MULTA').AsExtended;
Desconto := Desconto + CDSParcelaPagamento.FieldByName('VALOR_DESCONTO').AsExtended;
Total := Total + CDSParcelaPagamento.FieldByName('VALOR_PAGO').AsExtended;
CDSParcelaPagamento.Next;
end;
CDSParcelaPagamento.First;
CDSParcelaPagamento.EnableControls;
//
PanelTotaisPagos.Caption := '| Juros: ' + FloatToStrF(Juro, ffCurrency, 15, 2) +
' | Multa: ' + FloatToStrF(Multa, ffCurrency, 15, 2) +
' | Desconto: ' + FloatToStrF(Desconto, ffCurrency, 15, 2) +
' | Total Pago: ' + FloatToStrF(Total, ffCurrency, 15, 2) +
' | Saldo: ' + FloatToStrF(Total - EditValorAPagar.Value, ffCurrency, 15, 2) + ' |';
end;
{$ENDREGION}
end.
|
unit Entidades.Comercial;
interface
{$SCOPEDENUMS ON}
uses
Generics.Collections,
Aurelius.Mapping.Attributes,
Aurelius.Types.Nullable,
Aurelius.Types.Proxy,
Entidades.Cadastro,
Entities.Scheduling;
type
TVenda = class;
TRegisterShiftItem = class;
[Entity]
[AutoMapping]
TItemVenda = class
private
FId: integer;
[Association([TAssociationProp.Required], CascadeTypeAllButRemove)]
FProduto: TProduto;
FQtde: integer;
FValorUnitario: Currency;
FValorFinal: Currency;
FAnimal: TAnimal;
[Association([], CascadeTypeAllButRemove)]
[JoinColumn('ITENS_VENDA_ID')]
FSale: TVenda;
FAppointment: TAppointment;
function GetDesconto: Currency;
public
property Desconto: Currency read GetDesconto;
public
property Id: integer read FId;
property Produto: TProduto read FProduto write FProduto;
property Qtde: integer read FQtde write FQtde;
property ValorUnitario: Currency read FValorUnitario write FValorUnitario;
property ValorFinal: Currency read FValorFinal write FValorFinal;
property Animal: TAnimal read FAnimal write FAnimal;
property Sale: TVenda read FSale write FSale;
property Appointment: TAppointment read FAppointment write FAppointment;
end;
[Enumeration(TEnumMappingType.emString, 'Cash,Card,Check,Later')]
TPaymentMode = (Cash, Card, Check, PayLater);
[Entity, Automapping]
TPaymentType = class
private
FId: integer;
[Column('NAME', [TColumnProp.Required], 50)]
FName: string;
FMode: TPaymentMode;
FDaysToReceive: integer;
public
property Id: integer read FId write FId;
property Name: string read FName write FName;
property Mode: TPaymentMode read FMode write FMode;
property DaysToReceive: integer read FDaysToReceive write FDaysToReceive;
end;
[Entity, Automapping]
TReceivable = class
private
FId: integer;
FDueDate: TDateTime;
FReceiveDate: Nullable<TDateTime>;
FAmount: Currency;
FReceived: boolean;
// FSale: TVenda;
FRegisterItem: TRegisterShiftItem;
public
property Id: integer read FId write FId;
property DueDate: TDateTime read FDueDate write FDueDate;
property ReceiveDate: Nullable<TDateTime> read FReceiveDate write FReceiveDate;
property Amount: Currency read FAmount write FAmount;
property Received: boolean read FReceived write FReceived;
property RegisterItem: TRegisterShiftItem read FRegisterItem write FRegisterItem;
end;
// [Entity, Automapping]
// TPayable = class
// end;
[Entity]
[Automapping]
TVenda = class
private
FId: integer;
[Association([], CascadeTypeAllButRemove)]
FPessoa: TPessoa;
FData: TDateTime;
[ManyValuedAssociation([TAssociationProp.Lazy], CascadeTypeAllRemoveOrphan, 'FSale')]
FItens: Proxy<TList<TItemVenda>>;
FPaymentType: TPaymentType;
function GetItens: TList<TItemVenda>;
function GetItemsTotal: Currency;
public
constructor Create;
destructor Destroy; override;
function HasAppointment(Appointment: TAppointment): boolean;
property ItemsTotal: Currency read GetItemsTotal;
property Id: integer read FId;
property Data: TDateTime read FData write FData;
property Pessoa: TPessoa read FPessoa write FPessoa;
property Itens: TList<TItemVenda> read GetItens;
property PaymentType: TPaymentType read FPaymentType write FPaymentType;
end;
// [Entity, Automapping]
// TSpendingCategory = class
// strict private
// FId: integer;
// FName: string;
// public
// property Id: integer read FId write FId;
// property Name: string read FName write FName;
// end;
[Entity, Automapping]
TRegisterShift = class
private
FId: integer;
FOpeningDate: TDateTime;
FClosingDate: Nullable<TDateTime>;
[ManyValuedAssociation([TAssociationProp.Lazy], CascadeTypeAllRemoveOrphan, 'FShift')]
FItems: Proxy<TList<TRegisterShiftItem>>;
function GetItems: TList<TRegisterShiftItem>;
function GetClosed: boolean;
public
constructor Create;
destructor Destroy; override;
property Id: integer read FId write FId;
property OpeningDate: TDateTime read FOpeningDate write FOpeningDate;
property ClosingDate: Nullable<TDateTime> read FClosingDate write FClosingDate;
property Items: TList<TRegisterShiftItem> read GetItems;
property Closed: boolean read GetClosed;
end;
[Enumeration(TEnumMappingType.emString, 'Open,Close,Sale,Payment')]
TRegisterShiftItemType = (Open, Close, Sale, Payment);
[Entity, Automapping]
TRegisterShiftItem = class
private
FId: integer;
[Column('ITEM_DATE', [TColumnProp.Required])]
FDate: TDateTime;
FAmount: Currency;
FItemType: TRegisterShiftItemType;
[Association([TAssociationProp.Required], CascadeTypeAllButRemove)]
FShift: TRegisterShift;
FPaymentType: TPaymentType;
FSale: TVenda;
public
property Id: integer read FId write FId;
property Date: TDateTime read FDate write FDate;
property ItemType: TRegisterShiftItemType read FItemType write FItemType;
property Amount: Currency read FAmount write FAmount;
property Shift: TRegisterShift read FShift write FShift;
property PaymentType: TPaymentType read FPaymentType write FPaymentType;
property Sale: TVenda read FSale write FSale;
end;
[Enumeration(TEnumMappingType.emChar, 'C,B')]
TAccountType = (Cash, Bank);
[Entity, Automapping]
TAccount = class
private
FId: integer;
[Column('NAME', [TColumnProp.Required], 100)]
FName: string;
FAccountType: TAccountType;
public
property Id: integer read FId write FId;
property Name: string read FName write FName;
property AccountType: TAccountType read FAccountType write FAccountType;
end;
[Entity, Automapping]
TAccountEntry = class
private
FId: integer;
[Association([TAssociationProp.Required], CascadeTypeAllButRemove)]
FAccount: TAccount;
[Column('ENTRY_DATE', [TColumnProp.Required])]
FDate: TDateTime;
FAmount: Currency;
[Column('Notes', [], 255)]
FNotes: Nullable<string>;
// FCategory: TSpendingCategory;
public
property Id: integer read FId write FId;
property Account: TAccount read FAccount write FAccount;
property Date: TDateTime read FDate write FDate;
property Amount: Currency read FAmount write FAmount;
property Notes: Nullable<string> read FNotes write FNotes;
// property Category: TSpendingCategory read FCategory write FCategory;
end;
implementation
{ TItemVenda }
function TItemVenda.GetDesconto: Currency;
begin
result := ValorFinal - ValorUnitario * Abs(Qtde);
end;
{ TVenda }
constructor TVenda.Create;
begin
FItens.SetInitialValue(TList<TItemVenda>.Create);
end;
destructor TVenda.Destroy;
begin
FItens.DestroyValue;
inherited;
end;
function TVenda.GetItens: TList<TItemVenda>;
begin
Result := FItens.Value;
end;
function TVenda.HasAppointment(Appointment: TAppointment): boolean;
var
Item: TItemVenda;
begin
for Item in Itens do
if (Item.Appointment <> nil) and (Item.Appointment.Id = Appointment.Id) then
Exit(true);
Result := false;
end;
function TVenda.GetItemsTotal: Currency;
var
item: TItemVenda;
begin
Result := 0;
for item in Itens do
Result := Result + item.ValorFinal;
end;
{ TRegisterShift }
constructor TRegisterShift.Create;
begin
FItems.SetInitialValue(TList<TRegisterShiftItem>.Create);
end;
destructor TRegisterShift.Destroy;
begin
FItems.DestroyValue;
inherited;
end;
function TRegisterShift.GetClosed: boolean;
begin
Result := not ClosingDate.IsNull;
end;
function TRegisterShift.GetItems: TList<TRegisterShiftItem>;
begin
Result := FItems.Value;
end;
end.
|
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä
Msg : 294 of 310
From : Norbert Igl 2:2402/300.3 16 Apr 93 23:19
To : Max Maischein 2:249/6.17
Subj : International characters
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
> Note that your uppercase characters do not include the german Umlauts
> and overlap sometimes with other foreign characters. There is a DOS
> function call to convert a string to all upcercase letters. Norbert
> Igl and I wrote a ASM implementation, maybe he could repost his all-
> Pascal version that conforms to the DOS country information.
> -max
no problem....
-------------------------8<---------------------------------}
Unit Upper;
{ Country-independent upcase-procedures (c) 1992 N.Igl
Uses the COUNRY=??? from your CONFIG.SYS to get the correct uppercase.
SpeedUp with a table-driven version to avoid multiple DOS-Calls.
Released to the public domain ( FIDO: PASCAL int'l ) in 12/92 }
Interface
function UpCase (ch:char) : Char;
function UpCaseStr( S:String): String;
Implementation uses Dos;
Const isTableOk : Boolean = FALSE;
Var theTable : Array[0..255] of Char;
Procedure SetUpTable; { called only at Unit-init }
var Regs: Registers;
x : byte;
begin
FillChar( theTable, Sizeof( theTable ), #0 );{ Fill with NULL }
For x := 1 to 255 do theTable[x] := CHAR(x); { predefined values }
if Lo(DosVersion) < 4 then { n/a in this DOS... }
begin { use Turbo's Upcase }
for x := 1 to 255 do
theTable[x] := System.Upcase(CHAR(x));
exit;
end;
Regs.AX := $6521; { "Capitalize String" }
Regs.CX := 255; { "string"-length }
Regs.DS := Seg(theTable); { DS:DX... }
Regs.DX := Ofs(theTable[1]); { ...points to the "string"}
Intr($21,Regs); { let DOS do it ! }
isTableOK := ( Regs.Flags and FCarry = 0 ); { OK ? }
end;
function UpCase( ch:char ):char;
begin
UpCase := theTable[BYTE(ch)]
end;
function UpCaseStr(S:String):String;
var x: Byte;
begin
for x := 1 to length(S) do
S[x]:= theTable[BYTE(S[x])];
UpCaseStr := S
end;
begin SetUpTable end. |
unit ImportTableData;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, ActnList, Vcl.StdCtrls,
Vcl.Mask, JvExMask, JvSpin, Ora, BCControls.Edit, BCControls.ComboBox, BCControls.SpinEdit, Vcl.Buttons, Vcl.ExtCtrls,
BCDialogs.Dlg, System.Actions, JvExControls, JvSpeedButton, BCControls.CheckBox, JvExStdCtrls, JvCheckBox;
type
TImportTableDataDialog = class(TDialog)
ActionList: TActionList;
CancelButton: TButton;
ClipboardRadioButton: TRadioButton;
ComminIntervalLabel: TLabel;
CommitIntervalSpinEdit: TBCSpinEdit;
DelimiterComboBox: TBCComboBox;
DelimiterLabel: TLabel;
FilenameLabel: TLabel;
FileRadioButton: TRadioButton;
ImportAction: TAction;
ImportButton: TButton;
Label1: TLabel;
LaunchAfterCreationCheckBox: TBCCheckBox;
LoadInEditorRadioButton: TRadioButton;
OpenFileButtonAction: TAction;
OpenFilenameEdit: TBCEdit;
OptionsGroupBox: TGroupBox;
OutputGroupBox: TGroupBox;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
SaveFileButtonAction: TAction;
SaveFilenameEdit: TBCEdit;
SchemaEdit: TBCEdit;
SchemaLabel: TLabel;
Separator1Panel: TPanel;
TableEdit: TBCEdit;
TableLabel: TLabel;
JvSpeedButton1: TJvSpeedButton;
JvSpeedButton2: TJvSpeedButton;
procedure FormDestroy(Sender: TObject);
procedure ImportActionExecute(Sender: TObject);
procedure OpenFileButtonActionExecute(Sender: TObject);
procedure SaveFileButtonActionExecute(Sender: TObject);
private
{ Private declarations }
FSession: TOraSession;
function CheckFields: Boolean;
function GetColumns(Header: string): TStrings;
function GetDelimiter: Char;
function ImportData: Boolean;
function InsertStatementOutput(ColumnTypeQuery: TOraQuery; Columns: TStrings; Line: string): string;
procedure ReadIniFile;
procedure WriteIniFile;
public
{ Public declarations }
function Open(Session: TOraSession): Boolean;
end;
function ImportTableDataDialog: TImportTableDataDialog;
implementation
{$R *.dfm}
uses
BCCommon.OptionsContainer, BigIni, ShellApi, Progress, SynEdit, Main, DB, BCCommon.StyleUtils, BCCommon.Dialogs,
BCCommon.LanguageStrings, BCCommon.FileUtils, BCCommon.Messages, BCCommon.Lib;
var
FImportTableDataDialog: TImportTableDataDialog;
function ImportTableDataDialog: TImportTableDataDialog;
begin
if not Assigned(FImportTableDataDialog) then
Application.CreateForm(TImportTableDataDialog, FImportTableDataDialog);
Result := FImportTableDataDialog;
SetStyledFormSize(Result);
end;
procedure TImportTableDataDialog.FormDestroy(Sender: TObject);
begin
FImportTableDataDialog := nil;
end;
procedure TImportTableDataDialog.ImportActionExecute(Sender: TObject);
begin
WriteIniFile;
if ImportData then
ModalResult := mrOk;
end;
function TImportTableDataDialog.Open(Session: TOraSession): Boolean;
var
Rslt: Integer;
begin
FSession := Session;
SchemaEdit.Text := Session.Schema;
ReadIniFile;
Rslt := ShowModal;
Result := Rslt = mrOk;
end;
procedure TImportTableDataDialog.OpenFileButtonActionExecute(Sender: TObject);
begin
if BCCommon.Dialogs.OpenFile(Handle, OpenFilenameEdit.Text, Format('%s'#0'*.*'#0#0, [LanguageDataModule.GetConstant('AllFiles')]),
LanguageDataModule.GetConstant('SelectFile')) then
begin
Application.ProcessMessages; { style fix }
OpenFilenameEdit.Text := BCCommon.Dialogs.Files[0];
end;
end;
procedure TImportTableDataDialog.WriteIniFile;
begin
with TBigIniFile.Create(GetINIFilename) do
try
WriteInteger('ImportSettings', 'CommitInterval', StrToInt(CommitIntervalSpinEdit.Text));
WriteBool('ImportSettings', 'LaunchAfterCreation', LaunchAfterCreationCheckBox.Checked);
WriteString('ImportSettings', 'OpenFilename', OpenFilenameEdit.Text);
WriteString('ImportSettings', 'SaveFilename', SaveFilenameEdit.Text);
WriteBool('ImportSettings', 'FileOutput', FileRadioButton.Checked);
WriteBool('ImportSettings', 'ClipboardOutput', ClipboardRadioButton.Checked);
WriteBool('ImportSettings', 'LoadInEditorOutput', LoadInEditorRadioButton.Checked);
finally
Free;
end;
end;
procedure TImportTableDataDialog.ReadIniFile;
begin
with TBigIniFile.Create(GetINIFilename) do
try
FileRadioButton.Checked := ReadBool('ImportSettings', 'FileOutput', True);
ClipboardRadioButton.Checked := ReadBool('ImportSettings', 'ClipboardOutput', False);
LoadInEditorRadioButton.Checked := ReadBool('ImportSettings', 'LoadInEditorOutput', True);
CommitIntervalSpinEdit.Value := ReadInteger('ImportSettings', 'CommitInterval', 0);
LaunchAfterCreationCheckBox.Checked := ReadBool('ImportSettings', 'LaunchAfterCreation', False);
OpenFilenameEdit.Text := ReadString('ImportSettings', 'OpenFilename', '');
SaveFilenameEdit.Text := ReadString('ImportSettings', 'SaveFilename', '');
finally
Free;
end;
end;
procedure TImportTableDataDialog.SaveFileButtonActionExecute(Sender: TObject);
var
FilterIndex: Cardinal;
begin
if BCCommon.Dialogs.SaveFile(Handle, '', Format('%s'#0'*.*'#0#0, [LanguageDataModule.GetConstant('AllFiles')]),
LanguageDataModule.GetConstant('SaveAs'), FilterIndex) then
begin
Application.ProcessMessages; { style fix }
SaveFilenameEdit.Text := BCCommon.Dialogs.Files[0];
end;
end;
function TImportTableDataDialog.CheckFields: Boolean;
begin
Result := False;
if not FileExists(OpenFilenameEdit.Text) then
begin
ShowErrorMessage(Format('File %s does not exist.', [OpenFilenameEdit.Text]));
OpenFilenameEdit.SetFocus;
Exit;
end;
if Trim(OpenFilenameEdit.Text) = '' then
begin
ShowErrorMessage('Enter Filename.');
OpenFilenameEdit.SetFocus;
Exit;
end;
if Trim(SchemaEdit.Text) = '' then
begin
ShowErrorMessage('Enter Schema.');
SchemaEdit.SetFocus;
Exit;
end;
if Trim(TableEdit.Text) = '' then
begin
ShowErrorMessage('Enter Table.');
TableEdit.SetFocus;
Exit;
end;
if FileRadioButton.Checked and (Trim(SaveFilenameEdit.Text) = '') then
begin
ShowErrorMessage('Enter Filename.');
SaveFilenameEdit.SetFocus;
Exit;
end;
Result := True;
end;
function TImportTableDataDialog.GetDelimiter: Char;
begin
case DelimiterComboBox.ItemIndex of
0: Result := ',';
1: Result := '|';
2: Result := ';';
3: Result := Chr(9);
else
Result := ' ';
end;
end;
function TImportTableDataDialog.GetColumns(Header: string): TStrings;
var
s, ColumnName: string;
Delimiter: Char;
OraQuery: TOraQuery;
begin
{ check field exists in table }
Delimiter := GetDelimiter;
Result := TStringList.Create;
OraQuery := TOraQuery.Create(nil);
with OraQuery do
try
Session := FSession;
SQL.Add('SELECT * FROM ' + TableEdit.Text);
Open;
s := Header;
while Pos(Delimiter, s) <> 0 do
begin
ColumnName := Trim(Copy(s, 0, Pos(Delimiter, s) - 1));
if OraQuery.FieldList.IndexOf(ColumnName) = -1 then
begin
ShowErrorMessage(Format('Header row in the file must have correct field names. Can''t find: %s', [ColumnName]));
Result.Clear;
Exit;
end
else
Result.Add(ColumnName);
s := Trim(Copy(s, Pos(Delimiter, s) + 1, Length(s)));
// add delimiter at the end if it doesn't exist xxx;yyy
if (Length(s) <> 0) and (Pos(Delimiter, s) = 0) then
s := s + Delimiter;
end;
finally
Close;
Free;
end;
end;
function TImportTableDataDialog.ImportData: Boolean;
var
i, j{, Row}: Integer;
Columns: TStrings;
OpenSynEdit, SaveSynEdit: TSynEdit;
Interval: Boolean;
ColumnTypeQuery: TOraQuery;
begin
Result := False;
if not CheckFields then
Exit;
ColumnTypeQuery := TOraQuery.Create(nil);
with ColumnTypeQuery do
try
Session := FSession;
SQL.Add('SELECT * FROM ' + TableEdit.Text);
Open;
except
on E: Exception do
begin
ShowErrorMessage(E.Message);
Close;
Free;
Exit;
end;
end;
OpenSynEdit := TSynEdit.Create(nil);
OpenSynEdit.Visible := False;
OpenSynEdit.Parent := Self;
OpenSynEdit.Lines.LoadFromFile(OpenFilenameEdit.Text);
SaveSynEdit := TSynEdit.Create(nil);
SaveSynEdit.Visible := False;
SaveSynEdit.Parent := Self;
Columns := nil;
try
j := OpenSynEdit.Lines.Count - 1;
ProgressDialog(Self).Open(0, j, True);
{ read header - columns }
Columns := GetColumns(OpenSynEdit.Lines.Strings[0]);
if Columns.Count > 0 then
begin
for i := 1 to j - 1 do
begin
ProgressDialog(Self).ProgressPosition := i;
ProgressDialog(Self).InformationText := Format('Importing (Row %d/%d)...', [i+1, j]);
if not ProgressDialog(Self).OnProgress then
Exit;
SaveSynEdit.Text := SaveSynEdit.Text + InsertStatementOutput(ColumnTypeQuery, Columns, OpenSynEdit.Lines.Strings[i]);
if StrToInt(CommitIntervalSpinEdit.Text) <> 0 then { Add COMMIT; }
begin
Interval := ((i + 1) mod StrToInt(CommitIntervalSpinEdit.Text)) = 0;
if Interval or (not Interval and (i = (j - 1))) then
SaveSynEdit.Text := SaveSynEdit.Text + 'COMMIT;' + CHR_ENTER;
end;
end;
if FileRadioButton.Checked then
begin
SaveSynEdit.Lines.SaveToFile(SaveFilenameEdit.Text);
if LaunchAfterCreationCheckBox.Checked then
ShellExecute(Handle, 'open', PWideChar(SaveFilenameEdit.Text), nil, nil, SW_SHOWNORMAL) ;
end;
if ClipboardRadioButton.Checked then
SaveSynEdit.CopyToClipboard;
if LoadInEditorRadioButton.Checked then
MainForm.LoadSQLIntoEditor(Format('%s@%s', [FSession.Schema, FSession.Server]), SaveSynEdit.Text);
end;
finally
if Assigned(Columns) then
Columns.Free;
OpenSynEdit.Free;
SaveSynEdit.Free;
ProgressDialog(Self).Free;
ColumnTypeQuery.Close;
ColumnTypeQuery.Free;
end;
ShowMessage('Export Done.');
Result := True;
end;
function TImportTableDataDialog.InsertStatementOutput(ColumnTypeQuery: TOraQuery; Columns: TStrings; Line: string): string;
var
i: Integer;
s, FieldValue: string;
RightMargin: Integer;
begin
RightMargin := OptionsContainer.MarginRightMargin;
Result := 'INSERT INTO ' + LowerCase(SchemaEdit.Text) + '.' + LowerCase(TableEdit.Text) + CHR_ENTER;
s := ' (';
i := 0;
while i < Columns.Count do
begin
s := s + LowerCase(Trim(Columns.Strings[i]));
Inc(i);
if i < Columns.Count then
begin
s := s + ', ';
if Length(s) + Length(Trim(Columns.Strings[i])) > RightMargin then
begin
Result := Result + s + CHR_ENTER;
s := ' ';
end;
end;
end;
if s <> '' then
Result := Result + s;
Result := Result + ')' + CHR_ENTER;
s := ' VALUES (';
i := 0;
while i < Columns.Count do
begin
if Pos(GetDelimiter, Line) > 0 then
begin
FieldValue := Copy(Line, 1, Pos(GetDelimiter, Line) - 1);
Line := Copy(Line, Pos(GetDelimiter, Line) + 1, Length(Line));
end
else
FieldValue := Line; // last, if not delimiter
if ColumnTypeQuery.FieldByName(Columns.Strings[i]).DataType = ftWideString then
begin
FieldValue := AnsiDequotedStr(FieldValue, ''''); // single
FieldValue := AnsiDequotedStr(FieldValue, '"'); // double
FieldValue := AnsiQuotedStr(FieldValue, '''');
end;
if FieldValue = '' then
begin
if ColumnTypeQuery.FieldByName(Columns.Strings[i]).DataType <> ftWideString then
FieldValue := 'NULL';
end;
if ColumnTypeQuery.FieldByName(Columns.Strings[i]).DataType = ftFloat then
FieldValue := StringReplace(FieldValue, ',', '.', []);
if (FieldValue <> 'NULL') and (ColumnTypeQuery.FieldByName(Columns.Strings[i]).DataType = ftDateTime) then
FieldValue := 'TO_DATE(' + QuotedStr({FormatDateTime(OptionsContainer.DateFormat + ' hh:nn:ss',} FieldValue){)} +
', ' + QuotedStr(OptionsContainer.DateFormat + ' ' + OptionsContainer.TimeFormat) + ')';
s := s + FieldValue;
Inc(i);
if i < Columns.Count then
begin
s := s + ', ';
if Length(s) + Length(FieldValue) > RightMargin then
begin
Result := Result + s + CHR_ENTER;
s := ' ';
end;
end;
end;
if s <> '' then
Result := Result + s;
Result := Result + ');' + CHR_ENTER;
end;
end.
|
unit TBGConnection.Model.DataSet.Factory;
interface
uses
TBGConnection.Model.DataSet.Interfaces, TBGConnection.Model.DataSet.Proxy,
TBGConnection.Model.Interfaces;
Type
TConnectionModelDataSetFactory = class(TInterfacedObject, iDataSetFactory)
private
FDriver : iDriver;
public
constructor Create(Driver : iDriver);
destructor Destroy; override;
class function New(Driver : iDriver) : iDataSetFactory;
function DataSet(Observer : ICacheDataSetSubject): iDataSet;
end;
implementation
//uses
//TBGConnection.Model.DataSet;
{ TConnectionModelDataSetFactory }
constructor TConnectionModelDataSetFactory.Create(Driver : iDriver);
begin
FDriver := Driver;
end;
function TConnectionModelDataSetFactory.DataSet(Observer : ICacheDataSetSubject): iDataSet;
begin
//Result := FDriver.
// TConnectionModelDataSet.New(Observer);
//FDataSetProxy.AddCacheDataSet(Result.GUUID, Result);
end;
destructor TConnectionModelDataSetFactory.Destroy;
begin
inherited;
end;
class function TConnectionModelDataSetFactory.New(Driver : iDriver) : iDataSetFactory;
begin
Result := Self.Create(Driver);
end;
end.
|
unit BINOperation;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TDivisionResult = record
DivPart: String;
ModPart: String;
end;
TBINOperation = class(TComponent)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
function Add(Bin1, Bin2: String): String;
function Divide(Bin1, Bin2: String): TDivisionResult;
function Multiply(Bin1, Bin2: String): String;
function Subtract(Bin1, Bin2: String): String;
published
{ Published declarations }
end;
procedure Register;
implementation
const
NUMBERS = '0123456789';
procedure Register;
begin
RegisterComponents('DSO', [TBINOperation]);
end;
function Convert(NFrom, NTo: Byte; Value: String): String;
var
v: String;
p, num: Integer;
res, npos: Int64;
begin
npos:=1;
res:=0;
p:=Length(value);
while p>0 do begin
num:=Pos(UpCase(value[p]),NUMBERS)-1;
Inc(res,num*npos);
npos:=npos*NFrom;
Dec(p);
end;
npos:=1;
res:=Abs(res);
while (res div (npos*NTo))>0 do npos:=npos*NTo;
v:='';
while npos>0 do begin
v:=v+NUMBERS[(res div npos)+1];
res:=res mod npos;
npos:=npos div NTo;
end;
Result:=v;
end;
{ TBINOperation }
function TBINOperation.Add(Bin1, Bin2: String): String;
var
n1, n2: Extended;
begin
n1:=StrToFloat(Convert(2,10,Bin1));
n2:=StrToFloat(Convert(2,10,Bin2));
Result:=Convert(10,2,FloatToStr(n1+n2));
end;
function TBINOperation.Divide(Bin1, Bin2: String): TDivisionResult;
var
n1, n2: Extended;
d,m: Extended;
begin
n1:=StrToFloat(Convert(2,10,Bin1));
n2:=StrToFloat(Convert(2,10,Bin2));
d:=Round(n1) div Round(n2);
m:=Round(n1) mod Round(n2);
Result.DivPart:=Convert(10,2,FloatToStr(d));
Result.ModPart:=Convert(10,2,FloatToStr(m));
end;
function TBINOperation.Multiply(Bin1, Bin2: String): String;
var
n1, n2: Extended;
begin
n1:=StrToFloat(Convert(2,10,Bin1));
n2:=StrToFloat(Convert(2,10,Bin2));
Result:=Convert(10,2,FloatToStr(n1*n2));
end;
function TBINOperation.Subtract(Bin1, Bin2: String): String;
var
n1, n2: Extended;
begin
n1:=StrToFloat(Convert(2,10,Bin1));
n2:=StrToFloat(Convert(2,10,Bin2));
Result:=Convert(10,2,FloatToStr(n1-n2));
end;
end.
|
{
Copyright (c) 1998-2001,2014 Karoly Balogh <charlie@amigaspirit.hu>
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
}
{ * Most simple moduleplayer possible with ISS. * }
Program ISSPlay;
Uses Crt,
ISS_Play,ISS_Sys,ISS_Load,ISS_Var
{$IFDEF OS2}
,DOSCalls
{$ENDIF}
;
Var Music : ISS_PModule;
FileName : String;
Begin
If ParamCount=0 Then Begin
WriteLn('PLY_FAIL: No filename specified!');
WriteLn;
Exit;
End;
WriteLn;
FileName:=ParamStr(1);
{ * Initializes the device drivers and the loaders. This procedure was * }
{ * done by the units' startup code, in version 0.1.6 and below, but * }
{ * beginning with 0.1.7 this should be called by the user program. * }
{ * This allows more flexible integration of the soundsystem into custom * }
{ * environments. * }
{ * IMPORTANT: This _MUST_ be the first function called, and _MUST NOT_ * }
{ * be called twice or more! * }
ISS_InitSystem;
{ * Selects the best device automatically, and sets up the soundsystem * }
If Not ISS_AutoSetup Then Begin
WriteLn('PLY_FAIL: No devices available for playback!');
Halt(1);
End;
{ * Inits the selected device and the user level system structures. * }
If Not ISS_Init Then Begin
WriteLn('PLY_FAIL: Could not initialize selected device!');
Halt(1);
End;
WriteLn;
WriteLn('PLY_LOAD: Loading module...');
If Not ISS_LoadModule(FileName,Music) Then Begin
WriteLn('PLY_FAIL: Failed to load module!');
ISS_Done;
Halt(1);
End;
ISS_InitModulePlay(Music);
WriteLn('PLY_PLAY: Starting playback...');
ISS_StartModulePlay; { * Starts the player... * }
WriteLn('PLY_PLAY: Playing... (Press any key to exit)');
Repeat
{$IFDEF OS2}
DosSleep(32); { * Moolteetaskeen' roolz 8) * }
{$ENDIF}
Until Keypressed; { * Waiting for the user * }
WriteLn('PLY_PLAY: Stopping playback.');
ISS_StopModulePlay; { * Stops the player * }
WriteLn('PLY_DONE: Shutting down module player.');
ISS_DoneModulePlay;
WriteLn('PLY_DONE: Freeing up module.');
ISS_FreeModule(Music); { * Frees up memory allocated for the module * }
{ * Shuts down selected device and deinitalizes the system. * }
{ * After this, you can call ISS_Init again, if you need. You _MUST NOT_ * }
{ * call ISS_InitSystem again! * }
ISS_Done;
While Keypressed Do Readkey;
End.
|
unit DbfIdx; { Fast word searching using hash indexing for DBF files }
{*******************************************************-
New features to add --
fix GetIndex and MakeIndex to be repeatable
UpdateIndex (re-make index if FileModified)
-*******************************************************}
interface
uses Objects, Dbf, Str;
const
IdxVers: word = $0100;
QkListMax = 256;
Copyright: string = 'DbfIdx unit Copyright (C) 8-13-04 James M. Clark';
type
PIndexList = ^TIndexList;
TIndexList = record
case word of
0: (Str: string[MaxWords]);
1: (Lst: array[0..MaxWords] of byte);
end;
PWordArray = ^TWordArray;
TWordArray = array[0..$3fff] of word;
TListRec = record
Data, Next: word;
end;
PRecList = ^TRecList;
TRecList = array[1..$2ff0] of TListRec;
TQkList = array[1..QkListMax] of word; { make variable size ? }
PDbfIdxFile = ^TDbfIdxFile;
TDbfIdxFile = object(TDbfFile)
IndexList: PIndexList; {positions of fields to index}
HashListSz: word;
HashList: PWordArray; {converts hash values to RecList indexes}
RecListLen: word;
RecListSz: word;
RecList: PRecList; {lists records for each hash hit}
WordListLen: integer;
WordList: TWordList; {list words for current search}
QkListLen: word;
QkList: TQkList; {lists records for current search}
QkLimC: word; {recommended word-match limit for search}
FileModified: boolean;
destructor Done; virtual;
{ Read memory lists from index file: }
{ (IndexList, HashList, and RecList) }
function GetIndex: boolean; virtual;
{ Make (or re-make) index file, including memory lists }
{ IndexList, HashList, and RecList: }
procedure MakeIndex(AIndexList: TIndexList;
HashSz, RecSz: word); virtual;
{ Make WordList and QkList from words in S: }
{ TryFor argument is implicitly = 8. }
procedure MakeQuickList(S: string);
{ Make WordList and QkList from words in S: }
{ Try to get at least TryFor items in the list, }
{ settling for less matches if necessary. }
procedure MakeQuickList2(S: string;
TryFor: integer); virtual;
{ Read and compare quick-list record QL with WordList: }
{ Return true if MM or more matching words. }
function Compare(QL, MM: word): boolean; virtual;
{ true if S is one char or is found in ShortList: }
function ShortWord(S: string): boolean; virtual;
{also sets FileModified:}
function WriteRec: boolean; virtual; {return success}
end;
{*******************************************************}
implementation
const
ShortListLen = 35;
WrdsPerRec = SizeOf(TListRec) div SizeOf(word);
type
TShortList = array[1..ShortListLen] of string[3];
const
Separator = ' ,.:-;:''#"!&()/?0123456789';
ShortList: TShortList = (
'AN', 'AND', 'ANY', 'ARE', 'BE', 'BUT', 'BY', 'CAN',
'FOR', 'GO', 'HE', 'HIS', 'HOW', 'II', 'III', 'IN',
'IS', 'IV', 'MY', 'NOT', 'NOW', 'OF', 'ON', 'OR',
'OUR', 'OUT', 'RE', 'THE', 'TO', 'TWO', 'UP', 'WE',
'WHO', 'WHY', 'YOU'
);
{*******************************************************}
destructor TDbfIdxFile.Done;
var
I: word;
begin
if RecList <> nil
then FreeMem(RecList, RecListSz*SizeOf(TListRec));
if HashList <> nil
then FreeMem(HashList, HashListSz*SizeOf(word));
if IndexList <> nil then begin
I:= (IndexList^.Lst[0]+2) div 2;
FreeMem(IndexList, I*SizeOf(word));
end;
inherited Done;
end; {TDbfIdxFile.Done}
{*******************************************************}
{ Read memory lists from index file: }
{ (IndexList, HashList, and RecList) }
function TDbfIdxFile.GetIndex: boolean;
var
H, I: integer;
S: string;
IndexFile: file;
xRevYr, xRevMo, xRevDa: word;
begin
GetIndex:= false;
S:= FileName;
Delete(S, Length(FileName)-2, 3);
{$I-}
Assign(IndexFile, S+'hsh');
Reset(IndexFile, SizeOf(word));
{$I+}
if IoResult <> 0 then
exit;
{ read file header: }
BlockRead(IndexFile, H, 1, I);
if H >= $0100 then begin
IdxVers:= H;
BlockRead(IndexFile, xRevYr, 1, I);
BlockRead(IndexFile, xRevMo, 1, I);
BlockRead(IndexFile, xRevDa, 1, I);
if (xRevDa <> RevDa) or
(xRevMo <> RevMo) or
(xRevYr <> RevYr)
then begin
Close(IndexFile);
exit;
end;
BlockRead(IndexFile, H, 1, I);
end;
{ read index list: }
if IndexList <> nil then begin
I:= (IndexList^.Lst[0]+2) div 2;
FreeMem(IndexList, I*SizeOf(word));
end;
GetMem(IndexList, H*SizeOf(word));
BlockRead(IndexFile, IndexList^, H, I);
if I <> H then begin
Close(IndexFile);
exit;
end;
{ read hash list: }
if HashList <> nil
then FreeMem(HashList, HashListSz*SizeOf(word));
BlockRead(IndexFile, HashListSz, 1, I);
GetMem(HashList, HashListSz*SizeOf(word));
BlockRead(IndexFile, HashList^, HashListSz, I);
if I <> HashListSz then begin
Close(IndexFile);
exit;
end;
{ read record list: }
if RecList <> nil
then FreeMem(RecList, RecListSz*SizeOf(TListRec));
BlockRead(IndexFile, RecListLen, 1, I);
RecListSz:= RecListLen;
GetMem(RecList, RecListSz*SizeOf(TListRec));
BlockRead(IndexFile, RecList^, WrdsPerRec*RecListLen, I);
if I <> WrdsPerRec*RecListLen then begin
Close(IndexFile);
exit;
end;
Close(IndexFile);
GetIndex:= true;
end; {TDbfIdxFile.GetIndex}
{*******************************************************}
{ Make (or re-make) index file, including memory lists }
{ IndexList, HashList, and RecList: }
procedure TDbfIdxFile.MakeIndex(AIndexList: TIndexList;
HashSz, RecSz: word);
var
H, I: word;
R: longint;
S: string;
IndexFile: file;
begin
{ (re)allocate and copy IndexList: }
if IndexList <> nil then begin
I:= (IndexList^.Lst[0]+2) div 2;
FreeMem(IndexList, I*SizeOf(word));
end;
H:= (AIndexList.Lst[0]+2) div 2;
GetMem(IndexList, H*SizeOf(word));
IndexList^.Str:= AIndexList.Str;
{IndexList:= PIndexList(NewStr(AIndexList.Str));}
{ (re)allocate and clear HashList: }
if HashListSz > 0 then begin
FreeMem(HashList, HashListSz*SizeOf(word));
end;
HashListSz:= 1;
repeat HashListSz:= HashListSz shl 1
until HashListSz >= HashSz;
GetMem(HashList, HashListSz*SizeOf(word));
FillChar(HashList^, HashListSz*SizeOf(word), 0);
{ (re)allocate and clear RecList: }
if RecListSz > 0 then begin
FreeMem(RecList, RecListSz*SizeOf(TListRec));
end;
RecListLen:= 0;
RecListSz:= RecSz;
GetMem(RecList, RecListSz*SizeOf(TListRec));
FillChar(RecList^, RecListSz*SizeOf(TListRec), 0);
for R:= LastRec downto 1 do begin
if RecListLen >= RecListSz-16 then {+}
break;
SeekRec(R); {opens file if needed}
ReadRec;
if not Deleted then begin
S:= '';
for I:= 1 to IndexList^.Lst[0] do begin
S:= S + GetFieldStr(IndexList^.Lst[I]) + ' ';
end;
UpCaseStr(S);
ParseStr(S, Separator, WordList, WordListLen);
for I:= 1 to WordListLen do begin
if RecListLen >= RecListSz-16 then {+}
break;
if not ShortWord(WordList[I]) then begin
H:= HashStr(WordList[I]) and (HashListSz-1);
inc(RecListLen);
RecList^[RecListLen].Data:= R;
RecList^[RecListLen].Next:= HashList^[H];
HashList^[H]:= RecListLen;
end;
end;
end;
end;
S:= FileName;
Delete(S, Length(FileName)-2, 3);
Assign(IndexFile, S+'hsh');
Rewrite(IndexFile, SizeOf(word));
BlockWrite(IndexFile, IdxVers, 1, I);
BlockWrite(IndexFile, RevYr, 1, I);
BlockWrite(IndexFile, RevMo, 1, I);
BlockWrite(IndexFile, RevDa, 1, I);
H:= (IndexList^.Lst[0]+2) div 2; {2 bytes = 1 word}
BlockWrite(IndexFile, H, 1, I);
BlockWrite(IndexFile, IndexList^, H, I);
BlockWrite(IndexFile, HashListSz, 1, I); {++ check errors ++}
BlockWrite(IndexFile, HashList^, HashListSz, I);
BlockWrite(IndexFile, RecListLen, 1, I);
BlockWrite(IndexFile, RecList^, WrdsPerRec*RecListLen, I);
Close(IndexFile);
end; {TDbfIdxFile.MakeIndex}
{*******************************************************}
{ Make WordList and QkList from words in S: }
procedure TDbfIdxFile.MakeQuickList(S: string);
begin
TDbfIdxFile.MakeQuickList2(S, 9);
end; {TDbfIdxFile.MakeQuickList}
{*******************************************************}
{ Make WordList and QkList from words in S: }
{ Try to get at least TryFor items in the list, }
{ settling for less matches if necessary. }
procedure TDbfIdxFile.MakeQuickList2(S: string; TryFor: integer);
var
H, WL, QL, RL, R: word;
Dup: boolean;
QkLCnt: TQkList; {counts word-matches for each record}
QkMaxC: word; {maximum word-match count}
QkHist: TQkList; {histogram of QkLCnt}
begin
if HashList = nil then
exit;
UpCaseStr(S);
ParseStr(S, Separator, WordList, WordListLen);
QkLimC:= 0;
QL:= WordListLen;
for WL:= 1 to QL do begin
if not ShortWord(WordList[WL]) then begin
ExpandWord(WordList[WL], WordList, WordListLen);
inc(QkLimC);
end;
end;
QkListLen:= 0;
QkMaxC:= 1;
for WL:= 1 to WordListLen do begin
if not ShortWord(WordList[WL]) then begin
H:= HashStr(WordList[WL]) and (HashListSz-1);
RL:= HashList^[H];
while RL > 0 do begin
R:= RecList^[RL].Data;
{ change to insertion sort ? }
QL:= 1;
Dup:= false;
while (QL <= QkListLen) and not Dup do begin
if QkList[QL] = R then begin
Dup:= true;
inc(QkLCnt[QL]);
if QkMaxC < QkLCnt[QL]
then QkMaxC:= QkLCnt[QL];
end;
inc(QL);
end;
if not Dup and (QkListLen < QkListMax) then begin
inc(QkListLen);
QkList[QkListLen]:= R;
QkLCnt[QkListLen]:= 1;
end;
RL:= RecList^[RL].Next;
end;
end;
end;
if QkListLen > 0 then begin
for QL:= 1 to QkMaxC do begin
QkHist[QL]:= 0;
end;
for QL:= 1 to QkListLen do begin
inc(QkHist[ QkLCnt[QL] ]);
end;
WL:= 0;
if QkMaxC < QkLimC then QkLimC:= QkMaxC;
for QL:= QkMaxC downto 1 do begin
inc(WL, QkHist[QL]);
if WL >= TryFor then exit;
if QL < QkLimC then QkLimC:= QL;
end;
end;
end; {TDbfIdxFile.MakeQuickList2}
{*******************************************************}
{ Read and compare quick-list record QL with WordList: }
{ Return true if MM or more matching words. }
function TDbfIdxFile.Compare(QL, MM: word): boolean;
var
Matches, IL, WL: word;
S: string;
begin
SeekRec(QkList[QL]);
ReadRec;
Matches:= 0;
Compare:= true;
{ for each search word.. }
for WL:= 1 to WordListLen do begin
if not ShortWord(WordList[WL]) then begin
{ for each index field.. }
for IL:= 1 to IndexList^.Lst[0] do begin
S:= GetFieldStr(IndexList^.Lst[IL]);
UpCaseStr(S);
if Pos(WordList[WL], S) > 0 then
break;
end;
if Pos(WordList[WL], S) > 0 then begin
inc(Matches);
if Matches >= MM then
exit;
end;
end;
end;
Compare:= false;
end; {TDbfIdxFile.Compare}
{*******************************************************}
{ true if S is one char or is found in ShortList: }
function TDbfIdxFile.ShortWord(S: string): boolean;
var
I: integer;
begin
if Length(S) = 1 then begin
ShortWord:= true;
exit;
end;
if Length(S) > 3 then begin
ShortWord:= false;
exit;
end;
for I:= 1 to ShortListLen do begin
if S = ShortList[I] then begin
ShortWord:= true;
exit;
end;
end;
ShortWord:= false;
end; {TDbfIdxFile.ShortWord}
{*******************************************************}
function TDbfIdxFile.WriteRec: boolean;
begin
WriteRec:= inherited WriteRec;
FileModified:= true;
end; {TDbfIdxFile.WriteRec}
{*******************************************************}
end.
|
unit ClientesORM;
interface
uses
SysUtils, Variants, Classes, DB, SqlExpr, ConexaoDB, ORMUtils;
type
TCliente = class
private
FClienteID: Integer;
FTipoPessoa: string;
FCpfCnpj: string;
FNome: string;
FCep: string;
FLogradouro: string;
FNumero: string;
FComplemento: string;
FReferencia: string;
FBairro: string;
FCidade: string;
FUf: string;
FCodigoIbge: string;
FOldTipoPessoa: string;
FOldCpfCnpj: string;
FOldNome: string;
FOldCep: string;
FOldLogradouro: string;
FOldNumero: string;
FOldComplemento: string;
FOldReferencia: string;
FOldBairro: string;
FOldCidade: string;
FOldUf: string;
FOldCodigoIbge: string;
FAcao: TAcao;
public
constructor Create; overload;
constructor Create(clienteID: Integer; acao: TAcao); overload;
constructor Create(clienteID: Integer); overload;
procedure Buscar(clienteID: Integer);
function Salvar: Integer;
function Excluir: Boolean;
published
property ClienteID: Integer read FClienteID;
property TipoPessoa: string read FTipoPessoa write FTipoPessoa;
property CpfCnpj: string read FCpfCnpj write FCpfCnpj;
property Nome: string read FNome write FNome;
property Cep: string read FCep write FCep;
property Logradouro: string read FLogradouro write FLogradouro;
property Numero: string read FNumero write FNumero;
property Complemento: string read FComplemento write FComplemento;
property Referencia: string read FReferencia write FReferencia;
property Bairro: string read FBairro write FBairro;
property Cidade: string read FCidade write FCidade;
property Uf: string read FUf write FUf;
property CodigoIbge: string read FCodigoIbge write FCodigoIbge;
property Acao: TAcao read FAcao write FAcao;
end;
implementation
{ TCliente }
procedure TCliente.Buscar(clienteID: Integer);
procedure SetOlds;
begin
FOldTipoPessoa := FTipoPessoa;
FOldCpfCnpj := FCpfCnpj;
FOldNome := FNome;
FOldCep := FCep;
FOldLogradouro := FLogradouro;
FOldNumero := FNumero;
FOldComplemento := FComplemento;
FOldReferencia := FReferencia;
FOldBairro := FBairro;
FOldCidade := FCidade;
FOldUf := FUf;
FOldCodigoIbge := FCodigoIbge;
end;
var queryClientes: TSQLQuery;
begin
queryClientes := TSQLQuery.Create(nil);
try
queryClientes.SQLConnection := SimpleCrudSQLConnection;
queryClientes.SQL.Clear;
queryClientes.SQL.Add('SELECT CLIENTES.CLIENTE_ID, ');
queryClientes.SQL.Add(' CLIENTES.TIPO_PESSOA, ');
queryClientes.SQL.Add(' CLIENTES.CPF_CNPJ, ');
queryClientes.SQL.Add(' CLIENTES.NOME, ');
queryClientes.SQL.Add(' CLIENTES.CEP, ');
queryClientes.SQL.Add(' CLIENTES.LOGRADOURO, ');
queryClientes.SQL.Add(' CLIENTES.NUMERO, ');
queryClientes.SQL.Add(' CLIENTES.COMPLEMENTO, ');
queryClientes.SQL.Add(' CLIENTES.REFERENCIA, ');
queryClientes.SQL.Add(' CLIENTES.BAIRRO, ');
queryClientes.SQL.Add(' CLIENTES.CIDADE, ');
queryClientes.SQL.Add(' CLIENTES.UF, ');
queryClientes.SQL.Add(' CLIENTES.CODIGO_IBGE ');
queryClientes.SQL.Add('FROM CLIENTES');
queryClientes.SQL.Add('WHERE CLIENTES.CLIENTE_ID = :CLIENTE_ID');
queryClientes.ParamByName('CLIENTE_ID').AsInteger := clienteID;
queryClientes.Open;
queryClientes.First;
if (queryClientes.Eof) then
begin
FClienteID := 0;
if FAcao <> paVisualizacao then
FAcao := paInclusao;
end
else
begin
FAcao := paEdicao;
FClienteID := queryClientes.FieldByName('CLIENTE_ID').AsInteger;
FTipoPessoa := queryClientes.FieldByName('TIPO_PESSOA').AsString;
FCpfCnpj := queryClientes.FieldByName('CPF_CNPJ').AsString;
FNome := queryClientes.FieldByName('NOME').AsString;
FCep := queryClientes.FieldByName('CEP').AsString;
FLogradouro := queryClientes.FieldByName('LOGRADOURO').AsString;
FNumero := queryClientes.FieldByName('NUMERO').AsString;
FComplemento := queryClientes.FieldByName('COMPLEMENTO').AsString;
FReferencia := queryClientes.FieldByName('REFERENCIA').AsString;
FBairro := queryClientes.FieldByName('BAIRRO').AsString;
FCidade := queryClientes.FieldByName('CIDADE').AsString;
FUf := queryClientes.FieldByName('UF').AsString;
FCodigoIbge := queryClientes.FieldByName('CODIGO_IBGE').AsString;
SetOlds;
end;
finally
queryClientes.Close;
FreeAndNil(queryClientes);
end;
end;
constructor TCliente.Create;
begin
FClienteID := 0;
FTipoPessoa := '';
FCpfCnpj := '';
FNome := '';
FCep := '';
FLogradouro := '';
FNumero := '';
FComplemento := '';
FReferencia := '';
FBairro := '';
FCidade := '';
FUf := '';
FCodigoIbge := '';
FAcao := paSemAcao;
end;
constructor TCliente.Create(clienteID: Integer);
begin
FClienteID := clienteID;
FTipoPessoa := '';
FCpfCnpj := '';
FNome := '';
FCep := '';
FLogradouro := '';
FNumero := '';
FComplemento := '';
FReferencia := '';
FBairro := '';
FCidade := '';
FUf := '';
FCodigoIbge := '';
Buscar(FClienteID);
end;
constructor TCliente.Create(clienteID: Integer; acao: TAcao);
begin
FAcao := acao;
Create(clienteID);
end;
function TCliente.Excluir: Boolean;
var queryClientes: TSQLQuery;
begin
Result := False;
queryClientes := TSQLQuery.Create(nil);
try
queryClientes.SQLConnection := SimpleCrudSQLConnection;
// Montando Scrip de Update
queryClientes.SQL.Clear;
queryClientes.SQL.Add('DELETE FROM CLIENTES');
queryClientes.SQL.Add('WHERE (CLIENTE_ID = :CLIENTE_ID)');
// Executando update
queryClientes.ParamByName('CLIENTE_ID').AsInteger := FClienteID;
queryClientes.ExecSQL;
finally
Result := True;
FreeAndNil(queryClientes);
end;
end;
function TCliente.Salvar: Integer;
function VerificaSeExiteRegistroRepetido(var msgExcept: string): Boolean;
var queryValidade: TSQLQuery;
begin
Result := False;
queryValidade := TSQLQuery.Create(nil);
try
queryValidade.SQLConnection := SimpleCrudSQLConnection;
queryValidade.SQL.Clear;
queryValidade.SQL.Add('SELECT COUNT(1) QTDE FROM CLIENTES');
queryValidade.SQL.Add('WHERE CLIENTES.CLIENTE_ID <> :CLIENTE_ID');
queryValidade.SQL.Add(' AND CLIENTES.CPF_CNPJ = :CPF_CNPJ');
queryValidade.ParamByName('CLIENTE_ID').AsInteger := FClienteID;
queryValidade.ParamByName('CPF_CNPJ').AsString := FCpfCnpj;
queryValidade.Open;
queryValidade.First;
if not queryValidade.eof then
begin
if queryValidade.FieldByName('QTDE').AsInteger > 0 then
begin
Result := True;
msgExcept := Format('Já exite um Cliente cadastrado com este CPF/CNPJ: %s.',
[QuotedStr(FCpfCnpj)])
end;
end;
finally
queryValidade.Close;
FreeAndNil(queryValidade);
end;
end;
function InsereCliente: Integer;
var queryClientes: TSQLQuery;
begin
queryClientes := TSQLQuery.Create(nil);
try
queryClientes.SQLConnection := SimpleCrudSQLConnection;
queryClientes.SQL.Clear;
// Construindo Sql
queryClientes.SQL.Add('INSERT INTO CLIENTES (');
queryClientes.SQL.Add(' TIPO_PESSOA, ');
queryClientes.SQL.Add(' CPF_CNPJ, ');
queryClientes.SQL.Add(' NOME, ');
queryClientes.SQL.Add(' CEP, ');
queryClientes.SQL.Add(' LOGRADOURO, ');
queryClientes.SQL.Add(' NUMERO, ');
queryClientes.SQL.Add(' COMPLEMENTO, ');
queryClientes.SQL.Add(' REFERENCIA, ');
queryClientes.SQL.Add(' BAIRRO, ');
queryClientes.SQL.Add(' CIDADE, ');
queryClientes.SQL.Add(' UF, ');
queryClientes.SQL.Add(' CODIGO_IBGE) ');
queryClientes.SQL.Add('VALUES (');
queryClientes.SQL.Add(' :TIPO_PESSOA, ');
queryClientes.SQL.Add(' :CPF_CNPJ, ');
queryClientes.SQL.Add(' :NOME, ');
queryClientes.SQL.Add(' :CEP, ');
queryClientes.SQL.Add(' :LOGRADOURO, ');
queryClientes.SQL.Add(' :NUMERO, ');
queryClientes.SQL.Add(' :COMPLEMENTO, ');
queryClientes.SQL.Add(' :REFERENCIA, ');
queryClientes.SQL.Add(' :BAIRRO, ');
queryClientes.SQL.Add(' :CIDADE, ');
queryClientes.SQL.Add(' :UF, ');
queryClientes.SQL.Add(' :CODIGO_IBGE) ');
queryClientes.SQL.Add('RETURNING CLIENTE_ID');
// Setando Parametro
queryClientes.ParamByName('TIPO_PESSOA').AsString := FTipoPessoa;
queryClientes.ParamByName('CPF_CNPJ').AsString := FCpfCnpj;
queryClientes.ParamByName('NOME').AsString := FNome;
queryClientes.ParamByName('CEP').AsString := FCep;
queryClientes.ParamByName('LOGRADOURO').AsString := FLogradouro;
queryClientes.ParamByName('NUMERO').AsString := FNumero;
queryClientes.ParamByName('COMPLEMENTO').AsString := FComplemento;
queryClientes.ParamByName('REFERENCIA').AsString := FReferencia;
queryClientes.ParamByName('BAIRRO').AsString := FBairro;
queryClientes.ParamByName('CIDADE').AsString := FCidade;
queryClientes.ParamByName('UF').AsString := FUf;
queryClientes.ParamByName('CODIGO_IBGE').AsString := FCodigoIbge;
// Executando update
queryClientes.Open;
// Retornando ClienteID
FClienteID := queryClientes.Fields[0].AsInteger;
FAcao := paEdicao;
finally
queryClientes.Close;
FreeAndNil(queryClientes);
end;
end;
function AlteraCliente: Integer;
var queryClientes: TSQLQuery;
separator: string;
begin
Result := 0;
separator := '';
queryClientes := TSQLQuery.Create(nil);
try
queryClientes.SQLConnection := SimpleCrudSQLConnection;
// Montando Scrip de Update
queryClientes.SQL.Clear;
queryClientes.SQL.Add('UPDATE CLIENTES SET ');
if (FTipoPessoa <> FOldTipoPessoa) then
begin
queryClientes.Sql.Add(Format('%sTIPO_PESSOA = %s', [separator, QuotedStr(FTipoPessoa)]));
FOldTipoPessoa := FTipoPessoa;
separator := ',';
end;
if (FCpfCnpj <> FOldCpfCnpj) then
begin
queryClientes.Sql.Add(Format('%sCPF_CNPJ = %s', [separator, QuotedStr(FCpfCnpj)]));
FOldCpfCnpj := FCpfCnpj;
separator := ',';
end;
if (FNome <> FOldNome) then
begin
queryClientes.Sql.Add(Format('%sNOME = %s', [separator, QuotedStr(FNome)]));
FOldNome := FNome;
separator := ',';
end;
if (FCep <> FOldCep) then
begin
queryClientes.Sql.Add(Format('%sCEP = %s', [separator, QuotedStr(FCep)]));
FOldCep := FCep;
separator := ',';
end;
if (FLogradouro <> FOldLogradouro) then
begin
queryClientes.Sql.Add(Format('%sLOGRADOURO = %s', [separator, QuotedStr(FLogradouro)]));
FOldLogradouro := FLogradouro;
separator := ',';
end;
if (FNumero <> FOldNumero) then
begin
queryClientes.Sql.Add(Format('%sNUMERO = %s', [separator, QuotedStr(FNumero)]));
FOldNumero := FNumero;
separator := ',';
end;
if (FComplemento <> FOldComplemento) then
begin
queryClientes.Sql.Add(Format('%sCOMPLEMENTO = %s', [separator, QuotedStr(FComplemento)]));
FOldComplemento := FComplemento;
separator := ',';
end;
if (FReferencia <> FOldReferencia) then
begin
queryClientes.Sql.Add(Format('%sREFERENCIA = %s', [separator, QuotedStr(FReferencia)]));
FOldReferencia := FReferencia;
separator := ',';
end;
if (FBairro <> FOldBairro) then
begin
queryClientes.Sql.Add(Format('%sBAIRRO = %s', [separator, QuotedStr(FBairro)]));
FOldBairro := FBairro;
separator := ',';
end;
if (FCidade <> FOldCidade) then
begin
queryClientes.Sql.Add(Format('%sCIDADE = %s', [separator, QuotedStr(FCidade)]));
FOldCidade := FCidade;
separator := ',';
end;
if (FUf <> FOldUf) then
begin
queryClientes.Sql.Add(Format('%sUF = %s', [separator, QuotedStr(FUf)]));
FOldUf := FUf;
separator := ',';
end;
if (FCodigoIbge <> FOldCodigoIbge) then
begin
queryClientes.Sql.Add(Format('%sCODIGO_IBGE = %s', [separator, QuotedStr(FCodigoIbge)]));
FOldCodigoIbge := FCodigoIbge;
separator := ',';
end;
queryClientes.SQL.Add('WHERE (CLIENTE_ID = :CLIENTE_ID)');
// Retorna se nao tiver alteracao
if separator = '' then
Exit;
// Executando update
queryClientes.ParamByName('CLIENTE_ID').AsInteger := FClienteID;
queryClientes.ExecSQL;
finally
Result := FClienteID;
FreeAndNil(queryClientes);
end;
end;
var msgExcepty: String;
begin
Result := 0;
if VerificaSeExiteRegistroRepetido(msgExcepty) then
raise exception.Create(msgExcepty);
case FAcao of
paInclusao: Result := InsereCliente;
paEdicao: Result := AlteraCliente;
paVisualizacao: raise exception.Create('Não é possivel alterar um registro no modo de visualização');
end;
end;
end.
|
unit fRelatorioPatrimonio;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, fRelatorioBasico, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit,
dxSkinsCore, dxSkinBlack, Data.DB, System.Actions, Vcl.ActnList, cxCheckBox,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
cxDBLookupComboBox, Vcl.StdCtrls, Vcl.ExtCtrls, cxGroupBox, cxRadioGroup,
dmuRelatorio, ppParameter, ppDesignLayer, ppModule, raCodMod, ppBands,
ppCtrls, ppClass, ppVar, ppPrnabl, ppCache, ppProd, ppReport, ppComm,
ppRelatv, ppDB, ppDBPipe, uClientDataSet, uTypes, System.TypInfo,
uControleAcesso;
type
TfrmRelatorioPatrimonio = class(TfrmRelatorioBasico)
rgStatus: TcxRadioGroup;
DBPipePatrimonio: TppDBPipeline;
dsPatrimonio: TDataSource;
ppPatrimonio: TppReport;
ppHeaderBand1: TppHeaderBand;
ppLabel1: TppLabel;
ppDBImage1: TppDBImage;
ppSystemVariable1: TppSystemVariable;
ppSystemVariable2: TppSystemVariable;
ppDetailBand1: TppDetailBand;
ppDBText2: TppDBText;
ppDBText4: TppDBText;
ppFooterBand1: TppFooterBand;
ppLabel2: TppLabel;
ppDBText6: TppDBText;
ppDBText7: TppDBText;
ppSystemVariable3: TppSystemVariable;
raCodeModule3: TraCodeModule;
ppDesignLayers1: TppDesignLayers;
ppDesignLayer1: TppDesignLayer;
ppParameterList1: TppParameterList;
ppDBText5: TppDBText;
ppDBText1: TppDBText;
ppDBText3: TppDBText;
ppGroup1: TppGroup;
ppGroupHeaderBand1: TppGroupHeaderBand;
ppGroupFooterBand1: TppGroupFooterBand;
ppLabel4: TppLabel;
ppLabel3: TppLabel;
ppLabel5: TppLabel;
ppLabel6: TppLabel;
ppLabel7: TppLabel;
ppLabel8: TppLabel;
ppDBText8: TppDBText;
ppShape2: TppShape;
DBPipeOrganizacao: TppDBPipeline;
DBPipeOrganizacaoppField1: TppField;
DBPipeOrganizacaoppField2: TppField;
DBPipeOrganizacaoppField3: TppField;
DBPipeOrganizacaoppField4: TppField;
procedure Ac_GerarRelatorioExecute(Sender: TObject);
private
{ Private declarations }
protected
function fprGetPermissao: String; override;
{ Public declarations }
end;
var
frmRelatorioPatrimonio: TfrmRelatorioPatrimonio;
implementation
{$R *.dfm}
procedure TfrmRelatorioPatrimonio.Ac_GerarRelatorioExecute(Sender: TObject);
begin
inherited;
dmRelatorio.cdsPatrimonio.ppuDataRequest([TParametros.coStatus], [rgStatus.ItemIndex], TOperadores.coAnd, true);
ppPatrimonio.PrintReport;
end;
function TfrmRelatorioPatrimonio.fprGetPermissao: String;
begin
Result := GetEnumName(TypeInfo(TPermissaoRelatorio), ord(relPatrimonio));
end;
end.
|
{ MIT License
Copyright (c) 2020 Viacheslav Komenda
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. }
unit event;
interface
const
key_ctrl = 1;
key_shift = 2;
key_alt = 4;
type
EventType = (NONE,
KEYBOARD,
MOUSE_MOVE,
MOUSE_PRESS_B1, MOUSE_PRESS_B2,
MOUSE_RELEASE_B1, MOUSE_RELEASE_B2
);
PEvent = ^TEvent;
TEvent = record
etype : EventType;
scancode : byte;
ascii : char;
ctrl_keys : word;
mouse_left : boolean;
mouse_right : boolean;
mouse_x : integer;
mouse_y : integer;
end;
procedure wait_event(var e : TEvent);
function has_event : boolean;
function ctrl_key_word(is_ctrl, is_shift, is_alt : boolean) : word;
implementation
uses kminput;
function has_event:boolean;
begin
has_event := kbd_haskey;
end;
procedure wait_event(var e : TEvent);
var state : byte;
newstate : byte;
mx, my : integer;
flags : byte;
key : word;
begin
fillchar(e, sizeof(TEvent), #0);
e.etype := NONE;
if mouse_avail then begin
state := mouse_buttons;
e.mouse_x := mouse_getx;
mx := mouse_getx;
my := mouse_gety;
e.mouse_y := mouse_gety;
end else begin
e.mouse_x := 0;
e.mouse_y := 0;
e.mouse_left := false;
e.mouse_right := false;
end;
while e.etype = NONE do begin
if kbd_haskey then begin
key := kbd_getkey;
e.etype := KEYBOARD;
e.scancode := hi(key);
e.ascii := chr(lo(key));
end else if mouse_avail then begin
newstate := mouse_buttons;
e.mouse_x := mouse_getx;
e.mouse_y := mouse_gety;
e.mouse_left := (newstate and MOUSE_B1) <> 0;
e.mouse_right := (newstate and MOUSE_B2) <> 0;
if state <> newstate then begin
if (newstate and MOUSE_B1) <> (state and MOUSE_B1) then begin
if (newstate and MOUSE_B1) <> 0 then
e.etype := MOUSE_PRESS_B1
else e.etype := MOUSE_RELEASE_B1;
end else if (newstate and MOUSE_B2) <> (state and MOUSE_B2) then begin
if (newstate and MOUSE_B2) <> 0 then
e.etype := MOUSE_PRESS_B2
else e.etype := MOUSE_RELEASE_B2;
end;
end else if (e.mouse_x <> mx) or (e.mouse_y <> my) then begin
e.etype := MOUSE_MOVE;
end;
end;
if e.etype = NONE then begin
asm
mov ax,$8600
xor cx, cx
mov dx, 250
int $15
end;
end;
end;
if e.etype <> MOUSE_MOVE then begin
flags := kbd_getflags;
e.ctrl_keys := ctrl_key_word(is_ctrl(flags), is_shift(flags), is_alt(flags));
end;
end;
function ctrl_key_word(is_ctrl, is_shift, is_alt : boolean) : word;
var r : word;
begin
r := 0;
if is_ctrl then r := r or key_ctrl;
if is_shift then r := r or key_shift;
if is_alt then r := r or key_alt;
ctrl_key_word := r;
end;
end.
|
unit model_lib;
{$mode objfpc}{$H+}
interface
uses
Dialogs, Controls, LazarusPackageIntf, ProjectIntf, NewItemIntf, IDEMsgIntf,
Classes, SysUtils;
resourcestring
rs_Model_Name = 'Model Generator';
rs_Model_Description = 'create unit for model database';
type
{ TFileDescModel }
TFileDescModel = class(TFileDescPascalUnit)
private
public
constructor Create; override;
function GetInterfaceUsesSection: string; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function GetUnitDirectives: string; virtual;
function GetInterfaceSource(
const Filename, SourceName, ResourceName: string): string;
override;
function GetImplementationSource(
const Filename, SourceName, ResourceName: string): string; override;
function GetResourceSource(const ResourceName: string): string; override;
function CreateSource(const Filename, SourceName, ResourceName: string): string;
override;
procedure UpdateDefaultPascalFileExtension(const DefPasExt: string); override;
end;
implementation
uses fastplaz_tools_register, model_wzd;
{ TFileDescModel }
constructor TFileDescModel.Create;
begin
inherited Create;
//DefaultSourceName:= 'modelname_model';
DefaultFileExt := '.pas';
VisibleInNewDialog := True;
IsPascalUnit := True;
end;
function TFileDescModel.GetInterfaceUsesSection: string;
begin
Result := inherited GetInterfaceUsesSection;
Result := Result + ', database_lib';
end;
function TFileDescModel.GetLocalizedName: string;
begin
Result := inherited GetLocalizedName;
Result := rs_Model_Name;
end;
function TFileDescModel.GetLocalizedDescription: string;
begin
Result := inherited GetLocalizedDescription;
Result := rs_Model_Description;
end;
function TFileDescModel.GetUnitDirectives: string;
begin
Result:='{$mode objfpc}{$H+}';
if Owner is TLazProject then
Result:=CompilerOptionsToUnitDirectives(TLazProject(Owner).LazCompilerOptions);
end;
function TFileDescModel.GetInterfaceSource(
const Filename, SourceName, ResourceName: string): string;
var
str: TStringList;
begin
//Result:=inherited GetInterfaceSource(Filename, SourceName, ResourceName);
str := TStringList.Create;
with str do
begin
Add('type');
Add(' ' + ModelName + ' = class(TSimpleModel)');
Add(' private');
Add(' public');
Add(' constructor Create(const DefaultTableName: string = '''');');
Add(' end;');
Add('');
end;
Result := str.Text;
FreeAndNil(str);
end;
function TFileDescModel.GetImplementationSource(
const Filename, SourceName, ResourceName: string): string;
var
str: TStringList;
begin
Result := inherited GetImplementationSource(Filename, SourceName, ResourceName);
str := TStringList.Create;
with str do
begin
Add('constructor ' + ModelName + '.Create(const DefaultTableName: string = '''');');
Add('Begin');
Add(' inherited Create( DefaultTableName); // table name = ' +
LowerCase(TableName) + 's') ;
Add(' //inherited Create(''yourtablename''); // if use custom tablename');
Add('End;');
Add('');
end;
Result := Result + str.Text;
FreeAndNil(str);
end;
function TFileDescModel.GetResourceSource(const ResourceName: string): string;
begin
Result := inherited GetResourceSource(ResourceName);
end;
function TFileDescModel.CreateSource(
const Filename, SourceName, ResourceName: string): string;
begin
if not bExpert then
begin;
ModelName := 'Sample';
with TfModelWizard.Create(nil) do
begin
if ShowModal = mrOk then
begin
if edt_ModelName.Text <> '' then
ModelName := edt_ModelName.Text;
end;
Free;
end;
end;
DefaultFilename := LowerCase(ModelName) + '_model.pas';
DefaultFileExt := '.pas';
DefaultSourceName := LowerCase(ModelName) + '_model';
TableName := StringReplace(LowerCase(ModelName), ' ', '_', [rfReplaceAll]);
ModelName := 'T' + StringReplace(UcWords(ModelName), ' ', '', [rfReplaceAll]) + 'Model';
Result := inherited CreateSource(LowerCase(ModelName) + '_model.pas',
SourceName, ModelName);
log('model "' + ModelName + '" created');
end;
procedure TFileDescModel.UpdateDefaultPascalFileExtension(const DefPasExt: string);
begin
inherited UpdateDefaultPascalFileExtension(DefPasExt);
end;
end.
|
unit NovusSQLDirUtils;
interface
Uses SDEngine, SysUtils, SDConsts, Activex, NovusUtilities,
Classes;
type
TNovusSQLDirUtils = class(tNovusUtilities)
public
class function GetServerTypeAsString(ServerType: TSDServerType): String;
class function GetServerTypeAsInteger(ServerType: String): Integer;
class procedure SetupSDDatabase(Const ADatabase: tsddatabase;
AServerName: String;
ARemoteDatabase: String;
AAliasName: String;
AServerType: TSDServerType;
AUserName,
APassword: string;
AParams: tStringList;
ASQLLibrary: string;
ALoginPrompt: Boolean = False;
APort: Integer = 0);
end;
implementation
class procedure TNovusSQLDirUtils.SetupSDDatabase;
begin
ADatabase.Connected := False;
ADatabase.LoginPrompt := False;
ADatabase.KeepConnection := True;
If ADatabase.DatabaseName <> AAliasName then
ADatabase.DatabaseName := AAliasName;
ADatabase.ServerType := TSDServerType(AServerType);
ADatabase.Params.Clear;
if TSDServerType(AServerType) <> stOLEDB then
begin
ADatabase.Params.Values[szUSERNAME] := AUserName;
ADatabase.Params.Values[szPASSWORD] := APassword;
end;
// Provider=SQLOLEDB.11;Persist Security Info=False;User ID=sa;Initial Catalog=tourworkpad;Data Source=127.0.0.1;
if TSDServerType(AServerType) = stOLEDB then
begin
ADatabase.Params.Add('INIT COM=FALSE');
if ASQLLibrary <> '' then
ADatabase.Remotedatabase := 'Provider=' + aSQLLibrary + ';' +
'User ID=' + aUsername + ';' +
'Password=' + aPassword + ';' +
'Initial Catalog=' + ARemoteDatabase +';' +
'Data Source=' + aServerName + ';'
else
ADatabase.Remotedatabase := 'User ID=' + aUsername + ';' +
'Password=' + aPassword + ';' +
'Initial Catalog=' + ARemoteDatabase +';' +
'Data Source=' + aServerName + ';'
end
else
If TSDServerType(AServerType) = stSQLServer then
begin
ADatabase.Params.Add('USE OLEDB=TRUE');
ADatabase.Params.Add('INIT COM=FALSE');
ADatabase.Remotedatabase := AServerName + ':' + ARemoteDatabase;
end
else
If (TSDServerType(AServerType) = stFirebird) or
(TSDServerType(AServerType) = stInterbase) then
begin
ADatabase.Params.Add('SQL Dialect=3');
If Trim(AServername) = '' then
ADatabase.Remotedatabase := ARemoteDatabase
else
If Uppercase(Trim(AServername)) = 'LOCALHOST' then
ADatabase.Remotedatabase := ARemoteDatabase
else
ADatabase.Remotedatabase := AServerName + ':' + ARemoteDatabase;
If ASQLLibrary <> '' then
ADatabase.Params.Add('Firebird API Library=' + ASQLLibrary);
end
else
begin
ADatabase.Remotedatabase := AServerName + ':' + ARemoteDatabase;
end;
if Assigned(AParams) then
ADatabase.Params.Add(AParams.Text);
(*
ADatabase.Connected := False;
ADatabase.LoginPrompt := ALoginPrompt;
ADatabase.KeepConnection := True;
ADatabase.DatabaseName := AAliasName;
ADatabase.Params.Clear;
ADatabase.ServerType := TSDServerType(AServerType);
if TSDServerType(AServerType) = stOLEDB then
begin
ADatabase.Params.Add('INIT COM=FALSE');
if ASQLClientLib <> '' then
ADatabase.Remotedatabase := 'Provider=' + ASQLClientLib + ';' +
'User ID=' + aUsername + ';' +
'Password=' + aPassword + ';' +
'Initial Catalog=' + ARemoteDatabase +';' +
'Data Source=' + aServerName + ';'
else
ADatabase.Remotedatabase := 'User ID=' + aUsername + ';' +
'Password=' + aPassword + ';' +
'Initial Catalog=' + ARemoteDatabase +';' +
'Data Source=' + aServerName + ';'
end
else
If AServerType = stSQLServer then
begin
ADatabase.ServerType := AServerType;
ADatabase.Params.Add('USE OLEDB=TRUE');
ADatabase.Params.Add('INIT COM=FALSE');
ADatabase.Params.Add('User name=' + AUserName);
ADatabase.Params.Add('Password=' + APassword);
ADatabase.Remotedatabase := AServerName + ':' + ARemoteDatabase;
end
else
If AServerType = stFirebird then
begin
ADatabase.ServerType := TSDServerType(AServerType);
ADatabase.Params.Add('User name=' + AUserName);
ADatabase.Params.Add('Password=' + APassword);
ADatabase.Params.Add('SQL Dialect=3');
If Uppercase(AServername) = 'LOCALHOST' then
ADatabase.Remotedatabase := ARemoteDatabase
else
ADatabase.Remotedatabase := AServerName + ':' + ARemoteDatabase;
end
else
If AServerType = stMySQL then
begin
ADatabase.ServerType :=TSDServerType(AServerType);
end;
if Assigned(AParams) then
ADatabase.Params.Add(AParams.Text);
If (ASQLClientLib <> '') and (TSDServerType(AServerType) <> stOLEDB) then
ADatabase.Params.Add(TNovusSQLDirUtils.GetServerTypeAsString(AServerType) + ' API Library=' + ASQLClientLib);
*)
end;
class function TNovusSQLDirUtils.GetServerTypeAsString(ServerType:
TSDServerType): String;
begin
case ServerType of
stSQLBase: Result := 'SQLBase';
stOracle: Result := 'Oracle';
stSQLServer: Result := 'SQLServer';
stSybase: Result := 'Sybase';
stDB2: Result := 'DB2';
stInformix: Result := 'Informix';
stODBC: Result := 'ODBC';
stInterbase: result := 'Interbase';
stFirebird: result := 'Firebird';
stMySQL: result := 'MySQL';
stPostgreSQL: result := 'PostgreSQL';
stOLEDB: result := 'OLEDB';
else
Result := '';
end;
end;
class function TNovusSQLDirUtils.GetServerTypeAsInteger(ServerType: String):
Integer;
begin
Result := -1;
ServerType := uppercase(serverType);
if ServerType ='SQLBASE' then
Result := integer(stSQLBase)
else
if Servertype = 'ORACLE' then
Result := integer(stOracle)
else
if ServerType = 'SQLSERVER' then
Result := integer(stSQLServer)
else
If Servertype = 'SYBASE' then
Result := integer(stSybase)
else
if Servertype = 'DB2' then
result := integer(stDB2)
else
if Servertype = 'INFORMIX' then
result := integer(stInformix)
else
if Servertype = 'ODBC' then
result := integer(stODBC)
else
if Servertype = ' INTERBASE' then
result := integer(stInterbase)
else
if Servertype = 'FIREBIRD' then
result := integer(stFirebird)
else
if Servertype = 'MYSQL' then
result := integer(stMySQL)
else
if Servertype = 'POSTGRESQL' then
result := integer(stPostgreSQL)
else
if Servertype = 'OLEDB' then
result := integer(stOLEDB);
end;
end.
|
unit CoupleStack;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, PartnerStack;
type
CoupleNode = ^TCoupleNode;
Couple = ^TCouple;
TCouple = record
Bride: TPartner;
Groom: TPartner;
end;
TCoupleNode = record
Data: TCouple;
Next: CoupleNode;
end;
{ CoupleStack }
function NewCouple(const Bride: TPartner; const Groom: TPartner): TCouple;
function Pop(var Top: CoupleNode): TCouple;
procedure Push(var Top: CoupleNode; const C: TCouple);
procedure Free(var Top: CoupleNode);
implementation
{ Создание новой пары }
function NewCouple(const Bride: TPartner; const Groom: TPartner): TCouple;
var
C: TCouple;
begin
C.Bride := Bride;
C.Groom := Groom;
Result := C;
end;
{ Процедура удаления верхнего элемента стэка }
function Pop(var Top: CoupleNode): TCouple;
var
TempNode: CoupleNode = nil;
begin
Result := Top^.Data;
TempNode := Top;
Top := Top^.Next;
Dispose(TempNode);
end;
{ Процедура добавления элемента на верх стэка }
procedure Push(var Top: CoupleNode; const C: TCouple);
var
TempNode: CoupleNode = nil;
begin
New(TempNode);
TempNode^.Data := C;
TempNode^.Next := Top;
Top := TempNode;
end;
{ Процедура освобождения памяти занятой стэком }
procedure Free(var Top: CoupleNode);
begin
while Top <> nil do
Pop(Top);
end;
end.
|
unit VkApi.Utils;
interface
uses
System.SysUtils, System.StrUtils, System.Types, VkApi.Types, System.Variants;
function UserIdToOwnerId(const UserId: Cardinal): Integer;
function GroupIdToOwnerId(const GroupId: Cardinal): Integer;
function OwnerIdToUserId(const OwnerId: Integer): Cardinal;
function OwnerIdToGroupId(const OwnerId: Integer): Cardinal;
function VkDisplayTypeToString(const ADisplayType: TVkDisplayType): string;
function VkApiVersionToString(const AApiVersion: TVkApiVersion): string;
function VkPermissionsToStr(const AVkPermissions: TVkPermissions): string;
function VkPermissionsToInt(const AVkPermissions: TVkPermissions): Integer;
function StrToVkPermissions(const AStr: string): TVkPermissions;
function IntToVkPermissions(const AInt: Integer): TVkPermissions;
function VarIsOk(const V: Variant): Boolean;
function VarValue(const V: Variant; const DefaultValue: Variant):
Variant; overload;
function VarValue(const V: Variant): Variant; overload;
implementation
function UserIdToOwnerId(const UserId: Cardinal): Integer;
begin
Result := Abs(UserId);
end;
function GroupIdToOwnerId(const GroupId: Cardinal): Integer;
begin
Result := -Abs(GroupId);
end;
function OwnerIdToUserId(const OwnerId: Integer): Cardinal;
begin
Result := Abs(OwnerId);
end;
function OwnerIdToGroupId(const OwnerId: Integer): Cardinal;
begin
Result := -Abs(OwnerId);
end;
{ functions }
function VkDisplayTypeToString(const ADisplayType: TVkDisplayType): string;
begin
case ADisplayType of
dtPage:
Result := 'page'; // do not localize
dtPopup:
Result := 'popup'; // do not localize
dtMobile:
Result := 'mobile'; // do not localize
else
Result := ''; // do not localize
end;
end;
function VkApiVersionToString(const AApiVersion: TVkApiVersion): string;
begin
case AApiVersion of
av4_0: Result := '4.0';
av4_1: Result := '4.1';
av4_2: Result := '4.2';
av4_3: Result := '4.3';
av4_4: Result := '4.4';
av4_5: Result := '4.5';
av4_6: Result := '4.6';
av4_7: Result := '4.7';
av4_8: Result := '4.8';
av4_9: Result := '4.9';
av4_91: Result := '4.91';
av4_92: Result := '4.92';
av4_93: Result := '4.93';
av4_94: Result := '4.94';
av4_95: Result := '4.95';
av4_96: Result := '4.96';
av4_97: Result := '4.97';
av4_98: Result := '4.98';
av4_99: Result := '4.99';
av4_100: Result := '4.100';
av4_101: Result := '4.101';
av4_102: Result := '4.102';
av4_103: Result := '4.103';
av4_104: Result := '4.104';
av5_0: Result := '5.0';
av5_1: Result := '5.1';
av5_2: Result := '5.2';
av5_3: Result := '5.3';
av5_4: Result := '5.4';
av5_5: Result := '5.5';
av5_6: Result := '5.6';
av5_7: Result := '5.7';
av5_8: Result := '5.8';
av5_9: Result := '5.9';
av5_10: Result := '5.10';
av5_11: Result := '5.11';
av5_12: Result := '5.12';
av5_13: Result := '5.13';
av5_14: Result := '5.14';
av5_15: Result := '5.15';
av5_16: Result := '5.16';
av5_17: Result := '5.17';
av5_18: Result := '5.18';
av5_19: Result := '5.19';
av5_20: Result := '5.20';
av5_21: Result := '5.21';
av5_22: Result := '5.22';
av5_23: Result := '5.23';
av5_24: Result := '5.24';
av5_25: Result := '5.25';
av5_26: Result := '5.26';
av5_27: Result := '5.27';
else
Result := '';
end;
end;
function VkPermissionsToStr(const AVkPermissions: TVkPermissions): string;
begin
Result := '';
if vkpNotify in AVkPermissions then
Result := Result + 'notify,';
if vkpFriends in AVkPermissions then
Result := Result + 'friends,';
if vkpPhotos in AVkPermissions then
Result := Result + 'photos,';
if vkpAudio in AVkPermissions then
Result := Result + 'audio,';
if vkpVideo in AVkPermissions then
Result := Result + 'video,';
if vkpOffers in AVkPermissions then
Result := Result + 'offers,';
if vkpQuestions in AVkPermissions then
Result := Result + 'questions,';
if vkpPages in AVkPermissions then
Result := Result + 'pages,';
if vkpLeftMenuLink in AVkPermissions then
begin
// no string for this
end;
if vkpStatus in AVkPermissions then
Result := Result + 'status,';
if vkpNotes in AVkPermissions then
Result := Result + 'notes,';
if vkpMessages in AVkPermissions then
Result := Result + 'messages,';
if vkpWall in AVkPermissions then
Result := Result + 'wall,';
if vkpAds in AVkPermissions then
Result := Result + 'ads,';
if vkpOffline in AVkPermissions then
Result := Result + 'offline,';
if vkpDocs in AVkPermissions then
Result := Result + 'docs,';
if vkpGroups in AVkPermissions then
Result := Result + 'groups,';
if vkpNotifications in AVkPermissions then
Result := Result + 'notifications,';
if vkpStats in AVkPermissions then
Result := Result + 'stats,';
if vkpEmail in AVkPermissions then
Result := Result + 'email,';
if vkpNoHttps in AVkPermissions then
Result := Result + 'nohttps';
// remove first and last commas
Result := Result.Trim([',']);
end;
function VkPermissionsToInt(const AVkPermissions: TVkPermissions): Integer;
begin
Result := 0;
if vkpNotify in AVkPermissions then
Result := Result or VKAPI_PERMISSION_NOTIFY;
if vkpFriends in AVkPermissions then
Result := Result or VKAPI_PERMISSION_FRIENDS;
if vkpPhotos in AVkPermissions then
Result := Result or VKAPI_PERMISSION_PHOTOS;
if vkpAudio in AVkPermissions then
Result := Result or VKAPI_PERMISSION_AUDIO;
if vkpVideo in AVkPermissions then
Result := Result or VKAPI_PERMISSION_VIDEO;
if vkpOffers in AVkPermissions then
Result := Result or VKAPI_PERMISSION_OFFERS;
if vkpQuestions in AVkPermissions then
Result := Result or VKAPI_PERMISSION_QUESTIONS;
if vkpPages in AVkPermissions then
Result := Result or VKAPI_PERMISSION_PAGES;
if vkpLeftMenuLink in AVkPermissions then
Result := Result or VKAPI_PERMISSION_LEFTMENULINK;
if vkpStatus in AVkPermissions then
Result := Result or VKAPI_PERMISSION_STATUS;
if vkpNotes in AVkPermissions then
Result := Result or VKAPI_PERMISSION_NOTES;
if vkpMessages in AVkPermissions then
Result := Result or VKAPI_PERMISSION_MESSAGES;
if vkpWall in AVkPermissions then
Result := Result or VKAPI_PERMISSION_WALL;
if vkpAds in AVkPermissions then
Result := Result or VKAPI_PERMISSION_ADS;
if vkpOffline in AVkPermissions then
Result := Result or VKAPI_PERMISSION_OFFLINE;
if vkpDocs in AVkPermissions then
Result := Result or VKAPI_PERMISSION_DOCS;
if vkpGroups in AVkPermissions then
Result := Result or VKAPI_PERMISSION_GROUPS;
if vkpNotifications in AVkPermissions then
Result := Result or VKAPI_PERMISSION_NOTIFICATIONS;
if vkpStats in AVkPermissions then
Result := Result or VKAPI_PERMISSION_STATS;
if vkpEmail in AVkPermissions then
Result := Result or VKAPI_PERMISSION_EMAIL;
if vkpNoHttps in AVkPermissions then
begin
// value not defined
// Result := Result or VKAPI_PERMISSION_NOHTTPS;
end;
end;
function StrToVkPermissions(const AStr: string): TVkPermissions;
var
sda: System.Types.TStringDynArray;
i: Integer;
begin
Result := [];
sda := SplitString(AStr, ',');
for i := Low(sda) to High(sda) do
begin
if SameText(sda[i], 'NOTIFY') then
Include(Result, vkpNotify);
if SameText(sda[i], 'FRIENDS') then
Include(Result, vkpFriends);
if SameText(sda[i], 'PHOTOS') then
Include(Result, vkpPhotos);
if SameText(sda[i], 'AUDIO') then
Include(Result, vkpAudio);
if SameText(sda[i], 'VIDEO') then
Include(Result, vkpVideo);
if SameText(sda[i], 'OFFERS') then
Include(Result, vkpOffers);
if SameText(sda[i], 'QUESTIONS') then
Include(Result, vkpQuestions);
if SameText(sda[i], 'PAGES') then
Include(Result, vkpPages);
if SameText(sda[i], 'LEFTMENULINK') then
Include(Result, vkpLeftMenuLink);
if SameText(sda[i], 'STATUS') then
Include(Result, vkpStatus);
if SameText(sda[i], 'NOTES') then
Include(Result, vkpNotes);
if SameText(sda[i], 'MESSAGES') then
Include(Result, vkpMessages);
if SameText(sda[i], 'WALL') then
Include(Result, vkpWall);
if SameText(sda[i], 'ADS') then
Include(Result, vkpAds);
if SameText(sda[i], 'OFFLINE') then
Include(Result, vkpOffline);
if SameText(sda[i], 'DOCS') then
Include(Result, vkpDocs);
if SameText(sda[i], 'GROUPS') then
Include(Result, vkpGroups);
if SameText(sda[i], 'NOTIFICATIONS') then
Include(Result, vkpNotifications);
if SameText(sda[i], 'STATS') then
Include(Result, vkpStats);
if SameText(sda[i], 'EMAIL') then
Include(Result, vkpEmail);
if SameText(sda[i], 'NOHTTPS') then
Include(Result, vkpNoHttps);
end;
end;
function IntToVkPermissions(const AInt: Integer): TVkPermissions;
begin
Result := [];
if (AInt and VKAPI_PERMISSION_NOTIFY) <> 0 then
Include(Result, vkpNotify);
if (AInt and VKAPI_PERMISSION_FRIENDS) <> 0 then
Include(Result, vkpFriends);
if (AInt and VKAPI_PERMISSION_PHOTOS) <> 0 then
Include(Result, vkpPhotos);
if (AInt and VKAPI_PERMISSION_AUDIO) <> 0 then
Include(Result, vkpAudio);
if (AInt and VKAPI_PERMISSION_VIDEO) <> 0 then
Include(Result, vkpVideo);
if (AInt and VKAPI_PERMISSION_OFFERS) <> 0 then
Include(Result, vkpOffers);
if (AInt and VKAPI_PERMISSION_QUESTIONS) <> 0 then
Include(Result, vkpQuestions);
if (AInt and VKAPI_PERMISSION_PAGES) <> 0 then
Include(Result, vkpPages);
if (AInt and VKAPI_PERMISSION_LEFTMENULINK) <> 0 then
Include(Result, vkpLeftMenuLink);
if (AInt and VKAPI_PERMISSION_STATUS) <> 0 then
Include(Result, vkpStatus);
if (AInt and VKAPI_PERMISSION_NOTES) <> 0 then
Include(Result, vkpNotes);
if (AInt and VKAPI_PERMISSION_MESSAGES) <> 0 then
Include(Result, vkpMessages);
if (AInt and VKAPI_PERMISSION_WALL) <> 0 then
Include(Result, vkpWall);
if (AInt and VKAPI_PERMISSION_ADS) <> 0 then
Include(Result, vkpAds);
if (AInt and VKAPI_PERMISSION_OFFLINE) <> 0 then
Include(Result, vkpOffline);
if (AInt and VKAPI_PERMISSION_DOCS) <> 0 then
Include(Result, vkpDocs);
if (AInt and VKAPI_PERMISSION_GROUPS) <> 0 then
Include(Result, vkpGroups);
if (AInt and VKAPI_PERMISSION_NOTIFICATIONS) <> 0 then
Include(Result, vkpNotifications);
if (AInt and VKAPI_PERMISSION_STATS) <> 0 then
Include(Result, vkpStats);
if (AInt and VKAPI_PERMISSION_EMAIL) <> 0 then
Include(Result, vkpEmail);
// nohttps value is not defined
// if (AInt and VKAPI_PERMISSION_NOHTTPS) <> 0 then
// Include(Result, vkpNoHttps);
end;
// variant helper
function VarIsOk(const V: Variant): Boolean;
begin
Result := not (VarIsNull(V) or VarIsEmpty(V) or VarIsError(V) or (VarToStr(V) =
EmptyStr) or VarIsClear(V));
end;
function VarValue(const V: Variant; const DefaultValue: Variant):
Variant;
begin
if VarIsOk(V) then
Result := V
else
Result := DefaultValue;
end;
function VarValue(const V: Variant): Variant; overload;
var
DefaultValue: Variant;
begin
case VarType(Result) of
varSmallInt,
varInteger,
varShortInt,
varByte,
varWord,
varLongWord,
varInt64: DefaultValue := 0;
varSingle,
varDouble: DefaultValue := 0.0;
varCurrency: DefaultValue := 0;
varDate: DefaultValue := 0;
varOleStr,
varStrArg,
varString: DefaultValue := EmptyStr;
varBoolean: DefaultValue := False;
end;
Result := VarValue(V, DefaultValue);
end;
end.
|
{8. Dado un arreglo V de N elementos ordenados en forma ascendente con componentes
repetidas, generar W con la frecuencia de los elementos de V.
Ejemplo: N=10; V=(2,2,3,3,3,3,7,9,9,9) W=(2,4,1,3) }
program Ej8;
const
todos = 9;
type
TV = array[1..todos] of byte;
Procedure startVec(var v, w: TV); // inicializa el vector
var
i: byte;
begin
for i:= 1 to todos do
begin
v[i]:= 0;
w[i]:= 0;
end;
end;
Procedure leeArchivo(var v: TV); //lee en el vector los numeros del archivo
var
arch: text;
i: byte;
begin
assign(arch, 'datos.txt'); reset(arch);
for i:= 1 to todos do
read(arch, v[i]);
close(arch);
end;
Procedure show(v: TV); // lo muestra
var
i: byte;
begin
leeArchivo(v);
for i:= 1 to todos do
write(v[i],' ');
writeln();
end;
Procedure frecW(v: TV; var w: TV);
var
i, k, cont: byte;
begin
startVec(v, w);
leeArchivo(v);
k:= 1; // if ((a mod 2 = 0) or (a mod 7 = 0)) and ((a mod 2 = 0) and (a mod 7 = 0)) then
cont:= 1; // esto es para el ejercicio 15 e de discreta
for i:= 1 to todos do
begin
if v[i] = v[i + 1] then
cont:= cont + 1
else
begin
w[cont]:= cont;
write(w[cont] : 2);
cont:= 1;
//k:= k + 1;
end;
end;
//for i:= 1 to k do
// write(w[k]:2);
end;
var
v, w: TV;
begin
startVec(v, w);
leeArchivo(v);
show(v);
frecW(v, w);
readln();
end.
|
function isPower(n:integer):boolean;
begin
if n=1 then exit(true);
if n mod 2 <> 0 then exit(false);
exit(isPower(n div 2));
end; |
unit BasisFunction;
interface
uses
Windows, SysUtils, Classes, Types, ShlObj, ActiveX, Graphics, Math, Messages;
type
TMD5Ctx = record
State: array[0..3] of Integer;
Count: array[0..1] of Integer;
case Integer of
0: (BufChar: array[0..63] of Byte);
1: (BufLong: array[0..15] of Integer);
end;
TDlgTemplateEx = packed record
dlgTemplate: DLGITEMTEMPLATE;
ClassName: string;
Caption: string;
end;
TSelectDirectoryProc = function(const Directory: string): Boolean;
TFindFileProc = procedure(const FileName: string; Info: TSearchRec);
const
SInformation = 'Info';
SError = 'Error';
SErrDataType = 'Data type mismatch';
{ 分隔字符串,ch为分隔符,Source需要分隔的字符串 }
function SplitString(const source, ch: string): TStringDynArray; overload; stdcall;
{ 分隔字符串,ch为分隔符,Source需要分隔的字符串 }
procedure SplitString(const source, ch: string; Results: TStrings); overload; stdcall;
{ 检查一个字符串是否是空的字符串,空串是指首字符和末字符中不包含非空白字符的字符串! }
function IsEmptyStr(const Str: string): Boolean; stdcall;
{ 返回当前应用程序路径 }
function AppPath: string; stdcall;
{ 返回执行模块文件名 }
function AppFile: string; stdcall;
{ 释放并置空一个对象指针 }
procedure FreeAndNilEx(var Obj); stdcall;
{ 把二进制数据十六进制化 }
function DataToHex(Data: PChar; Len: integer): string; stdcall;
{ 比较两个字符串的MD5结果是否一致 }
function MD5Match(const S, MD5Value: string): Boolean; stdcall;
{ 返回指定字符串的MD5散列值 }
function MD5String(const Value: string): string; stdcall;
procedure MD5Init(var MD5Context: TMD5Ctx);
procedure MD5Update(var MD5Context: TMD5Ctx; const Data: PChar; Len: integer);
function MD5Final(var MD5Context: TMD5Ctx): string;
function MD5Print(D: string): string;
{ 对文件求MD5散列值 }
function MD5File(FileName: string): string; stdcall;
{ 复制文件,利用Shell函数来做的 }
function CopyFiles(const Dest: string; const Files: TStrings; const UI: Boolean = False): Boolean; stdcall;
{ 复制目录,利用Shell函数来做的 }
function CopyDirectory(const Source, Dest: string; const UI: Boolean = False): boolean; stdcall;
{ 移动文件,Shell方式 }
function MoveFiles(DestDir: string; const Files: TStrings; const UI: Boolean = False): Boolean; stdcall;
{ 重命名目录,Shell方式 }
function RenameDirectory(const OldName, NewName: string): boolean; stdcall;
{ 删除目录,Shell方式 }
function DeleteDirectory(const DirName: string; const UI: Boolean = False): Boolean; stdcall;
{ 清除目录,Shell方式 }
function ClearDirectory(const DirName: string; const IncludeSub, ToRecyle: Boolean): Boolean; stdcall;
{ 删除文件,Shell方式 }
function DeleteFiles(const Files: TStrings; const ToRecyle: Boolean = True): Boolean; stdcall;
{ 返回指定文件的大小,支持超大文件 }
function FileSizeEx(const FileName: string): Int64; stdcall;
{ 返回文件大小显示 }
function GetFileSizeDisplay(const AFileSize: Int64): string;
{ 返回发送速度显示 }
function GetSpeedDisplay(const ASpeed: Double): string;
{ 动态生成一个GUID }
function GetGUID: TGUID; stdcall;
{ 返回一个动态生成的GUID的字符串 }
function GetGUIDString: string; stdcall;
{ 判断一个字符串是否是一个合法的GUID }
function IsGUID(const S: string): Boolean; stdcall;
{ 返回最近一次API调用的错误信息字符串 }
function GetLastErrorString: string; stdcall;
{ 格式化Value为指定宽度Width的字符串 }
function FixFormat(const Width: integer; const Value: Double): string; overload; stdcall;
{ 格式化Value为指定宽度Width的字符串 }
function FixFormat(const Width: integer; const Value: integer): string; overload; stdcall;
{ 保留指定位数小数个数 }
function FixDouble(const ACount: Integer; const AValue: Double): string; stdcall;
{ 修正Delphi四舍五入的BUG的Round函数 }
function RoundEx(Value: Extended): Int64; stdcall;
{ 向上四舍五入取整 }
function RoundUp(Value: Extended): Int64; stdcall;
{ 向下四舍五入取整 }
function RoundDown(Value: Extended): Int64; stdcall;
{ 修正Delphi四舍五入函数Round正方向四舍五入的BUG }
function ClassicRoundUp(const Value: Extended): Int64; stdcall;
{ 修正Delphi四舍五入函数Round负方向四舍五入的BUG }
function ClassicRoundDown(const Value: Extended): Int64; stdcall;
{ 修正Delphi四舍五入函数RoundTo的BUG }
function ClassicRoundTo(const AValue: Extended; const APrecision: TRoundToRange = 0): Extended; stdcall;
{ 交换高低字节 }
function xhl(const b: Byte): Byte; overload; stdcall;
{ 交换高低字节 }
function xhl(const W: Word): Word; overload; stdcall;
{ 交换高低字节 }
function xhl(const DW: DWord): Dword; overload; stdcall;
{ 显示一个输入文本对话框 }
function InputBoxEx(const ACaption, AHint, ADefault: string; out Text: string): Boolean; stdcall;
{ 返回指定窗口的类名 }
function GetWindowClassName(hWnd: HWND): string; stdcall;
{ 返回窗口的标题 }
function GetWindowCaption(hWnd: HWND): string; stdcall;
{ 默认对话框处理程序 }
function DefDialogProc(Wnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): Integer; stdcall;
{ 显示一个自定义对话框 }
function DialogBoxEx(const Controls: array of TDlgTemplateEx; const DlgProc: Pointer = nil): Integer;
{ 根据字体名,创建字体 }
function MakeFont(FontName: string; Size, Bold: integer; StrikeOut, Underline, Italy: Boolean): Integer; stdcall;
{ 设置指定控件的字体 }
procedure SetFont(hWnd: HWND; Font: HFONT); stdcall;
{ 显示一个信息框 }
procedure DlgInfo(const Msg, Title: string); stdcall;
{ 显示一个错误对话框 }
procedure DlgError(const Msg: string); stdcall;
{ 封装的MessageBox }
function MsgBox(const Msg: string; const Title: string = 'Info'; dType: Integer = MB_OK + MB_ICONINFORMATION): Integer; stdcall;
{ 选择目录对话框,很好用的哦 }
function SelectDirectoryEx(var Path: string; const Caption, Root: string; BIFs: DWORD = $59;
Callback: TSelectDirectoryProc = nil; const FileName: string = ''): Boolean; stdcall;
{ 在硬盘上面创建文件 }
procedure CreateFileOnDisk(FileName: string); stdcall;
{ 判断文件是否正在使用 }
function IsFileInUse(const FileName: string): Boolean; stdcall;
{ 根据扩展名返回一个临时文件名 }
function GetTmpFile(const AExt: string): string; stdcall;
function GetTmpFileEx(const APath, APre, AExt: string): string; stdcall;
{ 返回系统临时文件目录 }
function TempPath: string; stdcall;
{ 返回一个指定目录下指定文件的文件名集合 }
procedure GetFileList(Files: TStrings; Folder, FileSpec: string; SubDir: Boolean = True; CallBack: TFindFileProc = nil); stdcall;
{ 返回一个指定目录下指定文件的文件名集合,不包括子文件夹下的文件 }
procedure GetFileListName(Files: TStrings; const Folder, FileSpec: string); stdcall;
{ 返回一个指定目录下子目录的集合 }
procedure GetDirectoryList(Directorys: TStrings; const Folder: string); stdcall;
{ 返回一个指定目录下子目录名的集合 }
procedure GetDirectoryListName(Directorys: TStrings; const Folder: string); stdcall;
{ 判断Ch是否是空白字符 }
function IsSpace(const Ch: Char): Boolean; stdcall;
{ 判断Ch是否是十六进制数字字符 }
function IsXDigit(const Ch: Char): Boolean; stdcall;
{ 判断一个字符串是否是整数 }
function IsInteger(const S: string): Boolean; stdcall;
function IsInt64(const S: string): Boolean; stdcall;
{ 判断字符串是否是浮点数 }
function IsFloat(const S: string): Boolean; stdcall;
{ 返回字符串中Seperator左边的字符串,例如LeftPart('ab|cd','|')='ab' }
function LeftPart(Source, Seperator: string): string; stdcall;
{ 返回字符串中Seperator右边的字符串,例如RightPart('ab|cd','|')='cd' }
function RightPart(Source, Seperator: string): string; stdcall;
{ 返回字符串中Seperator最右边的字符串,例如LastRightPart('ab|cd|ef','|')='ef' }
function LastRightPart(Source, Seperator: string): string; stdcall;
{ 返回当前系统的GMT/UTC时间 }
function GMTNow: TDateTime; stdcall;
{ 转换本地时间为UTC时间 }
function LocaleToGMT(const Value: TDateTime): TDateTime; stdcall;
{ 转换UTC时间为本地时间 }
function GMTToLocale(const Value: TDateTime): TDateTime; stdcall;
const
CSHKeyNames: array[HKEY_CLASSES_ROOT..HKEY_DYN_DATA] of string = (
'HKEY_CLASSES_ROOT', 'HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE', 'HKEY_USERS',
'HKEY_PERFORMANCE_DATA', 'HKEY_CURRENT_CONFIG', 'HKEY_DYN_DATA');
{ 转换HKEY为字符串 }
function HKEYToStr(const Key: HKEY): string; stdcall;
{ 转换字符串为HKEY }
function StrToHKEY(const KEY: string): HKEY; stdcall;
{ 从完整注册表路径中提取HKEY }
function RegExtractHKEY(const Reg: string): HKEY; stdcall;
{ 从完整字符串中提取注册表SubKey }
function RegExtractSubKey(const Reg: string): string; stdcall;
{ 导出注册表 }
function RegExportToFile(const RootKey: HKEY; const SubKey, FileName: string): Boolean; stdcall;
{ 导入注册表 }
function RegImportFromFile(const RootKey: HKEY; const SubKey, FileName: string): Boolean; stdcall;
{ 读取注册表中指定的字符串 }
function RegReadString(const RootKey: HKEY; const SubKey, ValueName: string): string; stdcall;
{ 写入字符串到注册表中 }
function RegWriteString(const RootKey: HKEY; const SubKey, ValueName, Value: string): Boolean; stdcall;
{ 读取注册表中指定的字符串 }
function RegReadMultiString(const RootKey: HKEY; const SubKey, ValueName: string): string; stdcall;
{ 写入字符串到注册表中 }
function RegWriteMultiString(const RootKey: HKEY; const SubKey, ValueName, Value: string): Boolean; stdcall;
{ 注册表读取整数 }
function RegReadInteger(const RootKey: HKEY; const SubKey, ValueName: string): integer; stdcall;
{ 注册表写入整数 }
function RegWriteInteger(const RootKey: HKEY; const SubKey, ValueName: string; const Value: integer): Boolean; stdcall;
{ 注册表读取二进制数据 }
function RegReadBinary(const RootKey: HKEY; const SubKey, ValueName: string; Data: PChar; out Len: integer): Boolean; stdcall;
{ 注册表写入二进制 }
function RegWriteBinary(const RootKey: HKEY; const SubKey, ValueName: string; Data: PChar; Len: integer): Boolean; stdcall;
{ 判断注册表是否存在指定值 }
function RegValueExists(const RootKey: HKEY; const SubKey, ValueName: string): Boolean; stdcall;
{ 注册表主键是否存在 }
function RegKeyExists(const RootKey: HKEY; const SubKey: string): Boolean; stdcall;
{ 删除注册表主键 }
function RegKeyDelete(const RootKey: HKEY; const SubKey: string): Boolean; stdcall;
{ 删除注册表值 }
function RegValueDelete(const RootKey: HKEY; const SubKey, ValueName: string): Boolean; stdcall;
{ 获取注册表指定主键下所有的键值名列表 }
function RegGetValueNames(const RootKey: HKEY; const SubKey: string; Names: TStrings): Boolean; stdcall;
{ 获取注册表中指定主键下所有子主键名列表 }
function RegGetKeyNames(const RootKey: HKEY; const SubKey: string; Names: TStrings): Boolean; stdcall;
{ 为当前进程打开/禁止某个指定的系统特权 }
function EnablePrivilege(PrivName: string; bEnable: Boolean): Boolean; stdcall;
implementation
uses
ShellAPI;
var
ShareData: string; /// 用于临时存储数据的共享变量,主要用于回调函数中!
function SplitString(const source, ch: string): TStringDynArray;
{
分隔字符串,ch为分隔符,Source需要分隔的字符串
}
var
temp: PChar;
i: integer;
begin
Result := nil;
if Source = '' then exit;
temp := PChar(source);
i := AnsiPos(ch, temp);
while i <> 0 do
begin
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := copy(temp, 1, i - 1);
inc(temp, Length(Ch) + i - 1);
i := AnsiPos(ch, temp);
end;
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := Temp;
end;
procedure SplitString(const source, ch: string; Results: TStrings);
{
分隔字符串,ch为分隔符,Source需要分隔的字符串
}
begin
Results.CommaText := '"' + StringReplace(source, ch, '","', [rfReplaceAll]) + '"';
end;
function IsEmptyStr(const Str: string): Boolean;
begin
Result := Trim(Str) = '';
end;
function AppPath: string;
{
返回本应用程序的路径
}
begin
Result := IncludeTrailingPathDelimiter(ExtractFilePath(AppFile));
end;
function AppFile: string;
{
返回可执行模块的文件名,支持DLL!
}
var
Buff: array[0..MAX_PATH] of char;
begin
GetModuleFileName(HInstance, Buff, SizeOf(Buff));
Result := StrPas(Buff);
end;
procedure FreeAndNilEx(var Obj);
begin
if Assigned(Pointer(Obj)) then FreeAndNil(Obj);
end;
function DataToHex(Data: PChar; Len: Integer): string;
{
把指定的二进制数据转换成十六进制表示的字符串
}
begin
SetLength(Result, Len shl 1);
BinToHex(Data, PChar(Result), Len);
end;
procedure MD5Init(var MD5Context: TMD5Ctx);
begin
FillChar(MD5Context, SizeOf(TMD5Ctx), #0);
with MD5Context do
begin
State[0] := Integer($67452301);
State[1] := Integer($EFCDAB89);
State[2] := Integer($98BADCFE);
State[3] := Integer($10325476);
end;
end;
procedure MD5Transform(var Buf: array of LongInt; const Data: array of LongInt);
var
A, B, C, D: LongInt;
procedure Round1(var W: LongInt; X, Y, Z, Data: LongInt; S: Byte);
begin
Inc(W, (Z xor (X and (Y xor Z))) + Data);
W := (W shl S) or (W shr (32 - S));
Inc(W, X);
end;
procedure Round2(var W: LongInt; X, Y, Z, Data: LongInt; S: Byte);
begin
Inc(W, (Y xor (Z and (X xor Y))) + Data);
W := (W shl S) or (W shr (32 - S));
Inc(W, X);
end;
procedure Round3(var W: LongInt; X, Y, Z, Data: LongInt; S: Byte);
begin
Inc(W, (X xor Y xor Z) + Data);
W := (W shl S) or (W shr (32 - S));
Inc(W, X);
end;
procedure Round4(var W: LongInt; X, Y, Z, Data: LongInt; S: Byte);
begin
Inc(W, (Y xor (X or not Z)) + Data);
W := (W shl S) or (W shr (32 - S));
Inc(W, X);
end;
begin
A := Buf[0];
B := Buf[1];
C := Buf[2];
D := Buf[3];
Round1(A, B, C, D, Data[0] + Longint($D76AA478), 7);
Round1(D, A, B, C, Data[1] + Longint($E8C7B756), 12);
Round1(C, D, A, B, Data[2] + Longint($242070DB), 17);
Round1(B, C, D, A, Data[3] + Longint($C1BDCEEE), 22);
Round1(A, B, C, D, Data[4] + Longint($F57C0FAF), 7);
Round1(D, A, B, C, Data[5] + Longint($4787C62A), 12);
Round1(C, D, A, B, Data[6] + Longint($A8304613), 17);
Round1(B, C, D, A, Data[7] + Longint($FD469501), 22);
Round1(A, B, C, D, Data[8] + Longint($698098D8), 7);
Round1(D, A, B, C, Data[9] + Longint($8B44F7AF), 12);
Round1(C, D, A, B, Data[10] + Longint($FFFF5BB1), 17);
Round1(B, C, D, A, Data[11] + Longint($895CD7BE), 22);
Round1(A, B, C, D, Data[12] + Longint($6B901122), 7);
Round1(D, A, B, C, Data[13] + Longint($FD987193), 12);
Round1(C, D, A, B, Data[14] + Longint($A679438E), 17);
Round1(B, C, D, A, Data[15] + Longint($49B40821), 22);
Round2(A, B, C, D, Data[1] + Longint($F61E2562), 5);
Round2(D, A, B, C, Data[6] + Longint($C040B340), 9);
Round2(C, D, A, B, Data[11] + Longint($265E5A51), 14);
Round2(B, C, D, A, Data[0] + Longint($E9B6C7AA), 20);
Round2(A, B, C, D, Data[5] + Longint($D62F105D), 5);
Round2(D, A, B, C, Data[10] + Longint($02441453), 9);
Round2(C, D, A, B, Data[15] + Longint($D8A1E681), 14);
Round2(B, C, D, A, Data[4] + Longint($E7D3FBC8), 20);
Round2(A, B, C, D, Data[9] + Longint($21E1CDE6), 5);
Round2(D, A, B, C, Data[14] + Longint($C33707D6), 9);
Round2(C, D, A, B, Data[3] + Longint($F4D50D87), 14);
Round2(B, C, D, A, Data[8] + Longint($455A14ED), 20);
Round2(A, B, C, D, Data[13] + Longint($A9E3E905), 5);
Round2(D, A, B, C, Data[2] + Longint($FCEFA3F8), 9);
Round2(C, D, A, B, Data[7] + Longint($676F02D9), 14);
Round2(B, C, D, A, Data[12] + Longint($8D2A4C8A), 20);
Round3(A, B, C, D, Data[5] + Longint($FFFA3942), 4);
Round3(D, A, B, C, Data[8] + Longint($8771F681), 11);
Round3(C, D, A, B, Data[11] + Longint($6D9D6122), 16);
Round3(B, C, D, A, Data[14] + Longint($FDE5380C), 23);
Round3(A, B, C, D, Data[1] + Longint($A4BEEA44), 4);
Round3(D, A, B, C, Data[4] + Longint($4BDECFA9), 11);
Round3(C, D, A, B, Data[7] + Longint($F6BB4B60), 16);
Round3(B, C, D, A, Data[10] + Longint($BEBFBC70), 23);
Round3(A, B, C, D, Data[13] + Longint($289B7EC6), 4);
Round3(D, A, B, C, Data[0] + Longint($EAA127FA), 11);
Round3(C, D, A, B, Data[3] + Longint($D4EF3085), 16);
Round3(B, C, D, A, Data[6] + Longint($04881D05), 23);
Round3(A, B, C, D, Data[9] + Longint($D9D4D039), 4);
Round3(D, A, B, C, Data[12] + Longint($E6DB99E5), 11);
Round3(C, D, A, B, Data[15] + Longint($1FA27CF8), 16);
Round3(B, C, D, A, Data[2] + Longint($C4AC5665), 23);
Round4(A, B, C, D, Data[0] + Longint($F4292244), 6);
Round4(D, A, B, C, Data[7] + Longint($432AFF97), 10);
Round4(C, D, A, B, Data[14] + Longint($AB9423A7), 15);
Round4(B, C, D, A, Data[5] + Longint($FC93A039), 21);
Round4(A, B, C, D, Data[12] + Longint($655B59C3), 6);
Round4(D, A, B, C, Data[3] + Longint($8F0CCC92), 10);
Round4(C, D, A, B, Data[10] + Longint($FFEFF47D), 15);
Round4(B, C, D, A, Data[1] + Longint($85845DD1), 21);
Round4(A, B, C, D, Data[8] + Longint($6FA87E4F), 6);
Round4(D, A, B, C, Data[15] + Longint($FE2CE6E0), 10);
Round4(C, D, A, B, Data[6] + Longint($A3014314), 15);
Round4(B, C, D, A, Data[13] + Longint($4E0811A1), 21);
Round4(A, B, C, D, Data[4] + Longint($F7537E82), 6);
Round4(D, A, B, C, Data[11] + Longint($BD3AF235), 10);
Round4(C, D, A, B, Data[2] + Longint($2AD7D2BB), 15);
Round4(B, C, D, A, Data[9] + Longint($EB86D391), 21);
Inc(Buf[0], A);
Inc(Buf[1], B);
Inc(Buf[2], C);
Inc(Buf[3], D);
end;
procedure MD5Update(var MD5Context: TMD5Ctx; const Data: PChar; Len: integer);
var
Index, t: Integer;
begin
//Len := Length(Data);
with MD5Context do
begin
T := Count[0];
Inc(Count[0], Len shl 3);
if Count[0] < T then
Inc(Count[1]);
Inc(Count[1], Len shr 29);
T := (T shr 3) and $3F;
Index := 0;
if T <> 0 then
begin
Index := T;
T := 64 - T;
if Len < T then
begin
Move(Data, Bufchar[Index], Len);
Exit;
end;
Move(Data, Bufchar[Index], T);
MD5Transform(State, Buflong);
Dec(Len, T);
Index := T;
end;
while Len > 64 do
begin
Move(Data[Index], Bufchar, 64);
MD5Transform(State, Buflong);
Inc(Index, 64);
Dec(Len, 64);
end;
Move(Data[Index], Bufchar, Len);
end
end;
function MD5Final(var MD5Context: TMD5Ctx): string;
var
Cnt: Word;
P: Byte;
D: array[0..15] of Char;
i: Integer;
begin
for I := 0 to 15 do
Byte(D[I]) := I + 1;
with MD5Context do
begin
Cnt := (Count[0] shr 3) and $3F;
P := Cnt;
BufChar[P] := $80;
Inc(P);
Cnt := 64 - 1 - Cnt;
if Cnt > 0 then
if Cnt < 8 then
begin
FillChar(BufChar[P], Cnt, #0);
MD5Transform(State, BufLong);
FillChar(BufChar, 56, #0);
end
else
FillChar(BufChar[P], Cnt - 8, #0);
BufLong[14] := Count[0];
BufLong[15] := Count[1];
MD5Transform(State, BufLong);
Move(State, D, 16);
Result := '';
for i := 0 to 15 do
Result := Result + Char(D[i]);
end;
FillChar(MD5Context, SizeOf(TMD5Ctx), #0)
end;
function MD5Print(D: string): string;
var
I: byte;
const
Digits: array[0..15] of char =
('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
begin
Result := '';
for I := 0 to 15 do
Result := Result + Digits[(Ord(D[I + 1]) shr 4) and $0F] + Digits[Ord(D[I + 1]) and $0F];
end;
function MD5Match(const S, MD5Value: string): Boolean;
begin
Result := SameText(MD5String(S), MD5Value);
end;
function MD5String(const Value: string): string;
{
把Value进行计算MD5散列值
}
var
MD5Context: TMD5Ctx;
begin
MD5Init(MD5Context);
MD5Update(MD5Context, PChar(Value), Length(Value));
Result := MD5Print(MD5Final(MD5Context));
end;
function MD5File(FileName: string): string;
{
求文件的MD5散列值
}
var
FileHandle: THandle;
MapHandle: THandle;
ViewPointer: pointer;
Context: TMD5Ctx;
begin
MD5Init(Context);
FileHandle := CreateFile(pChar(FileName), GENERIC_READ, FILE_SHARE_READ or FILE_SHARE_WRITE,
nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0);
if FileHandle <> INVALID_HANDLE_VALUE then
try
MapHandle := CreateFileMapping(FileHandle, nil, PAGE_READONLY, 0, 0, nil);
if MapHandle <> 0 then
try
ViewPointer := MapViewOfFile(MapHandle, FILE_MAP_READ, 0, 0, 0);
if ViewPointer <> nil then
try
MD5Update(Context, ViewPointer, GetFileSize(FileHandle, nil));
finally
UnmapViewOfFile(ViewPointer);
end;
finally
CloseHandle(MapHandle);
end;
finally
CloseHandle(FileHandle);
end;
Result := MD5Print(MD5Final(Context));
end;
function CopyFiles(const Dest: string; const Files: TStrings; const UI: Boolean = False): Boolean;
{
复制文件对话框
}
var
fo: TSHFILEOPSTRUCT;
i: integer;
FFiles: string;
begin
for i := 0 to Files.Count - 1 do
FFiles := FFiles + Files[i] + #0;
FillChar(fo, SizeOf(fo), 0);
with fo do
begin
Wnd := GetActiveWindow;
wFunc := FO_COPY;
pFrom := PChar(FFiles + #0);
pTo := pchar(Dest + #0);
if UI then
fFlags := FOF_ALLOWUNDO
else
fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_ALLOWUNDO;
end;
Result := (SHFileOperation(fo) = 0);
end;
function CopyDirectory(const Source, Dest: string; const UI: Boolean = False): boolean;
{
复制目录对话框
}
var
fo: TSHFILEOPSTRUCT;
begin
FillChar(fo, SizeOf(fo), 0);
with fo do
begin
Wnd := GetActiveWindow;
wFunc := FO_COPY;
pFrom := PChar(source + #0);
pTo := PChar(Dest + #0);
if UI then
fFlags := FOF_ALLOWUNDO
else
fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR;
end;
Result := (SHFileOperation(fo) = 0);
end;
function MoveFiles(DestDir: string; const Files: TStrings; const UI: Boolean = False): Boolean;
{
移动文件对话框
}
var
fo: TSHFILEOPSTRUCT;
i: integer;
FFiles: string;
begin
for i := 0 to Files.Count - 1 do
FFiles := FFiles + Files[i] + #0;
FillChar(fo, SizeOf(fo), 0);
with fo do
begin
Wnd := GetActiveWindow;
wFunc := FO_MOVE;
pFrom := PChar(FFiles + #0);
pTo := pchar(DestDir + #0);
if UI then
fFlags := FOF_ALLOWUNDO
else
fFlags := FOF_NOCONFIRMATION or FOF_NOCONFIRMMKDIR or FOF_ALLOWUNDO;
end;
Result := (SHFileOperation(fo) = 0);
end;
function RenameDirectory(const OldName, NewName: string): boolean;
{
重名名目录
}
var
fo: TSHFILEOPSTRUCT;
begin
FillChar(fo, SizeOf(fo), 0);
with fo do
begin
Wnd := GetActiveWindow;
wFunc := FO_RENAME;
pFrom := PChar(OldName + #0);
pTo := pchar(NewName + #0);
fFlags := FOF_NOCONFIRMATION + FOF_SILENT + FOF_ALLOWUNDO;
end;
Result := (SHFileOperation(fo) = 0);
end;
function DeleteDirectory(const DirName: string; const UI: Boolean = False): Boolean;
{
删除目录
}
var
fo: TSHFILEOPSTRUCT;
begin
FillChar(fo, SizeOf(fo), 0);
with fo do
begin
Wnd := GetActiveWindow;
wFunc := FO_DELETE;
pFrom := PChar(DirName + #0);
pTo := #0#0;
fFlags := FOF_NOCONFIRMATION + FOF_SILENT;
end;
Result := (SHFileOperation(fo) = 0);
end;
function ClearDirectory(const DirName: string; const IncludeSub, ToRecyle: Boolean): Boolean;
{
清除目录
}
var
fo: TSHFILEOPSTRUCT;
begin
FillChar(fo, SizeOf(fo), 0);
with fo do
begin
Wnd := GetActiveWindow;
wFunc := FO_DELETE;
pFrom := PChar(DirName + '\*.*' + #0);
pTo := #0#0;
fFlags := FOF_SILENT or FOF_NOCONFIRMATION or FOF_NOERRORUI
or (Ord(not IncludeSub) * FOF_FILESONLY)
or (ORd(ToRecyle) or FOF_ALLOWUNDO);
end;
Result := (SHFileOperation(fo) = 0);
end;
function DeleteFiles(const Files: TStrings; const ToRecyle: Boolean = True): Boolean;
{
删除文件,可以删除到回收站中
}
var
fo: TSHFILEOPSTRUCT;
i: integer;
FFiles: string;
begin
for i := 0 to Files.Count - 1 do
FFiles := FFiles + Files[i] + #0;
FillChar(fo, SizeOf(fo), 0);
with fo do
begin
Wnd := GetActiveWindow;
wFunc := FO_DELETE;
pFrom := PChar(FFiles + #0);
pTo := nil;
if ToRecyle then
fFlags := FOF_ALLOWUNDO or FOF_NOCONFIRMATION
else
fFlags := FOF_NOCONFIRMATION;
end;
Result := (SHFileOperation(fo) = 0);
end;
function FileSizeEx(const FileName: string): Int64;
{
返回文件FileName的大小,支持超大文件
}
var
Info: TWin32FindData;
Hnd: THandle;
begin
Result := -1;
Hnd := FindFirstFile(PChar(FileName), Info);
if (Hnd <> INVALID_HANDLE_VALUE) then
begin
Windows.FindClose(Hnd);
Int64Rec(Result).Lo := Info.nFileSizeLow;
Int64Rec(Result).Hi := Info.nFileSizeHigh;
end;
end;
function GetFileSizeDisplay(const AFileSize: Int64): string;
{
返回文件大小显示
}
begin
if AFileSize >= 1024 * 1024 * 1024 then //超过G
Result := Format('%0.1f', [AFileSize / (1024 * 1024 * 1024)]) + ' GB'
else if AFileSize >= 1024 * 1024 then //超过M
Result := Format('%0.1f', [AFileSize / (1024 * 1024)]) + ' MB'
else if AFileSize >= 1024 then //超过K
Result := Format('%0.1f', [AFileSize / 1024]) + ' KB'
else
Result := IntToStr(AFileSize) + ' B';
end;
function GetSpeedDisplay(const ASpeed: Double): string;
{
返回发送速度显示
}
begin
if ASpeed >= 1024 * 1024 * 1024 then //超过G
Result := Format('%0.1f', [ASpeed / (1024 * 1024 * 1024)]) + ' GB/S'
else if ASpeed >= 1024 * 1024 then //超过M
Result := Format('%0.1f', [ASpeed / (1024 * 1024)]) + ' MB/S'
else if ASpeed >= 1024 then //超过K
Result := Format('%0.1f', [ASpeed / 1024]) + ' KB/S'
else
Result := Format('%0.1f',[ASpeed]) + ' B/S';
end;
function GetGUID: TGUID;
{
动态返回一个GUID
}
begin
CoCreateGuid(Result);
end;
function GetGUIDString: string;
{
动态返回一个GUID字符串
}
begin
Result := GUIDToString(GetGUID);
end;
function IsGUID(const S: string): Boolean;
{
判断一个字符串是否是合法的GUID
}
begin
try
StringToGUID(S);
Result := True;
except
Result := False;
end;
end;
function GetLastErrorString: string;
{
获取最后一次API操作的错误信息
}
begin
Result := SysErrorMessage(GetLastError);
end;
function FixFormat(const Width: integer; const Value: Double): string; overload;
{
格式化Value为指定宽度Width的字符串
}
var
Len: integer;
begin
Len := Length(IntToStr(Trunc(Value)));
Result := Format('%*.*f', [Width, Width - Len, Value]);
end;
function FixFormat(const Width: integer; const Value: integer): string; overload;
{
格式化Value为指定宽度的字符串,不足的位数,自动补0
}
begin
Result := Format('%.*d', [Width, Value]);
end;
function FixDouble(const ACount: Integer; const AValue: Double): string;
{
保留指定位数小数个数,后面不会出现0
}
var
dValue: Double;
begin
dValue := ClassicRoundTo(AValue, ACount);
Result := FloatToStr(dValue);
end;
function RoundEx(Value: Extended): Int64;
{
修正Delphi四舍五入的BUG的Round函数
}
procedure Set8087CW(NewCW: Word);
asm
MOV Default8087CW,AX
FNCLEX
FLDCW Default8087CW
end;
const
RoundUpCW = $1B32;
var
OldCW: Word;
begin
OldCW := Default8087CW;
try
Set8087CW(RoundUpCW);
Result := Round(Value);
finally
Set8087CW(OldCW);
end;
end;
function RoundUp(Value: Extended): Int64;
{
向上四舍五入取整
}
var
OldCW: TFPURoundingMode;
begin
OldCW := GetRoundMode;
try
SetRoundMode(rmUp);
Result := Round(Value);
finally
SetRoundMode(OldCW);
end;
end;
function RoundDown(Value: Extended): Int64;
{
向下四舍五入取整
}
var
OldCW: TFPURoundingMode;
begin
OldCW := GetRoundMode;
try
SetRoundMode(rmDown);
Result := Round(Value);
finally
SetRoundMode(OldCW);
end;
end;
function RoundToEx(const AValue: Extended; const APrecision: TRoundToRange = 0): Extended;
{
修正Delphi四舍五入函数RoundTo的BUG
}
var
ATrunc: Int64;
APower: Extended;
APre: TRoundToRange;
begin
APre := Min(Max(APrecision, Low(TRoundToRange)), High(TRoundToRange));
APower := Power(10, APre);
ATrunc := Trunc(Int(AValue*APower));
if AValue < 0 then ATrunc := ATrunc - 1;
Result := AValue*APower;
if Result >= ATrunc + 0.5 then
Result := (ATrunc + 1) / APower
else
Result := ATrunc / APower;
end;
function ClassicRoundUp(const Value: Extended): Int64;
{
修正Delphi四舍五入函数Round的BUG,
完全按照数学上定义的四舍五入方式四舍五入,
四舍五入的方向一致为正方向
}
begin
Result := Floor(Value + 0.5);
end;
function ClassicRoundDown(const Value: Extended): Int64;
{
修正Delphi四舍五入函数Round的BUG,
四舍五入的方向一致为负方向
}
begin
Result := Ceil(Value - 0.5);
end;
function ClassicRoundTo(const AValue: Extended; const APrecision: TRoundToRange): Extended;
{
修正Delphi四舍五入函数RoundTo的BUG,完全按照数学上定义的四舍五入方式四舍五入
}
var
ATrunc: Int64;
APower: Extended;
APre: TRoundToRange;
begin
APre := Min(Max(APrecision, Low(TRoundToRange)), High(TRoundToRange));
APower := Power(10, APre);
ATrunc := ClassicRoundUp(AValue*APower);
Result := AValue*APower;
if (Result > ATrunc + 0.5) or SameValue(Result, ATrunc + 0.5) then
Result := (ATrunc + 1) / APower
else
Result := ATrunc / APower;
end;
function xhl(const B: Byte): Byte; overload;
{
交换高低字节
}
asm
rol al, 4 /// 循环左移4位即可
end;
function xhl(const W: word): word; overload;
{
交换高低字节
}
asm
// xchg ah,al
rol ax, 8 /// 循环左移8位即可
end;
function xhl(const DW: DWord): Dword; overload;
{
交换高低字节
}
asm
rol eax, 16 /// 循环左移16位即可
end;
function InputBoxEx(const ACaption, AHint, ADefault: string; out Text: string): Boolean;
{
输入对话框,纯API编程
}
function DialogProc(Wnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): integer; stdcall;
begin
Result := 0;
case Msg of
WM_COMMAND:
begin
case LOWORD(wParam) of
ID_OK:
begin
ShareData := GetWindowCaption(GetDlgItem(Wnd, 101));
end;
end;
end;
end;
if Result = 0 then /// 处理所有其他未处理消息
Result := CallWindowProc(@DefDialogProc, Wnd, Msg, wParam, lParam);
end;
var
Controls: array of TDlgTemplateEx;
begin
SetLength(Controls, 5);
with Controls[0], dlgTemplate do /// 定义对话框外观
begin
style := DS_CENTER or DS_CONTEXTHELP
or WS_SYSMENU or WS_DLGFRAME or WS_CAPTION or WS_VISIBLE;
x := 0;
y := 0;
cx := 200;
cy := 75;
Caption := ACaption;
end;
with Controls[1], dlgTemplate do /// Hint label
begin
ClassName := 'EDIT';
Caption := AHint + #13#10'Press Ctrl + Enter to enter a new line';
style := ES_MULTILINE or ES_LEFT or WS_VISIBLE or ES_READONLY;
dwExtendedStyle := 0;
x := 10;
y := 5;
cx := 180;
cy := 15;
id := 100;
end;
with Controls[2], dlgTemplate do /// Edit Box
begin
ClassName := 'EDIT';
Caption := ADefault;
style := ES_MULTILINE or ES_AUTOVSCROLL
or WS_VISIBLE or WS_BORDER or WS_TABSTOP or WS_VSCROLL;
dwExtendedStyle := 0;
x := 10;
y := 25;
cx := 180;
cy := 30;
id := 101;
end;
with Controls[3], dlgTemplate do /// OK Button
begin
ClassName := 'BUTTON';
Caption := '&OK';
style := WS_VISIBLE or WS_TABSTOP or BS_DEFPUSHBUTTON;
dwExtendedStyle := 0;
x := 125;
y := 60;
cx := 30;
cy := 12;
id := ID_OK;
end;
with Controls[4], dlgTemplate do /// OK Button
begin
ClassName := 'BUTTON';
Caption := '&Cancel';
style := WS_VISIBLE or WS_TABSTOP;
dwExtendedStyle := 0;
x := 160;
y := 60;
cx := 30;
cy := 12;
id := ID_CANCEL;
end;
Result := DialogBoxEx(Controls, @DialogProc) = ID_OK;
if Result then Text := ShareData;
end;
function GetWindowClassName(hWnd: HWND): string;
{
返回指定窗口的类名
}
begin
SetLength(Result, 255);
GetClassName(hWnd, PChar(Result), Length(Result));
end;
function GetWindowCaption(hWnd: HWND): string;
{
返回指定窗口的窗口标题文字
}
begin
SetLength(Result, GetWindowTextLength(hWnd) + 1);
GetWindowText(hWnd, PChar(Result), Length(Result));
Result := PChar(Result);
end;
function DefDialogProc(Wnd: HWND; Msg: UINT; wParam: WPARAM; lParam: LPARAM): Integer; stdcall;
{
}
var
Icon: HICON;
i: integer;
C: array of TDlgTemplateEx;
Font: HFONT;
begin
Result := 0;
C := nil;
Font := 0;
Icon := 0;
case Msg of
WM_INITDIALOG:
begin
C := Pointer(lParam);
Font := MakeFont('宋体', 12, 0, False, False, False);
for i := Succ(Low(C)) to High(C) do
begin
SetWindowText(GetDlgItem(Wnd, C[i].dlgTemplate.id), PChar(C[i].Caption));
SetFont(GetDlgItem(Wnd, C[i].dlgTemplate.id), Font);
end;
Icon := LoadIcon(HInstance, 'mainicon');
SendMessage(Wnd, WM_SETICON, ICON_BIG, IfThen(Icon <> 0, Icon, LoadIcon(0, IDI_WARNING)));
Result := 1;
end;
WM_NOTIFY:
{case LOWORD(wParam) of
end };
WM_COMMAND:
case LOWORD(wParam) of
IDOK, IDCANCEL:
begin
DeleteObject(Font);
DestroyIcon(Icon);
EndDialog(Wnd, wParam);
end;
else
Result := LoWord(wParam);
end;
WM_CLOSE:
begin
DeleteObject(Font);
DestroyIcon(Icon);
EndDialog(Wnd, wParam);
end;
WM_HELP:
begin
DlgInfo('Copyright(C) , 2004, Dialog powered by DialogBoxEx.', SInformation);
end;
end;
end;
function DialogBoxEx(const Controls: array of TDlgTemplateEx; const DlgProc: Pointer = nil): Integer;
{
使用内存模版数据显示一个对话框,Controls定义对话框外观和对话框项目数据,
如何使用本函数,请参考DlgInputText函数,其为完整演示。
函数返回Controls中选择的对应项的ID,例如点击OK,则返回OK按钮的ID
}
function lpwAlign(lpIn: DWORD): DWORD;
begin
Result := lpIn + 3;
Result := Result shr 2;
Result := Result shl 2;
end;
var
hgbl: HGLOBAL; /// 用于DiaologBoxInDirect的内存数据块
lpdt: PDLGTEMPLATE; /// 对话框模版数据结构
lpwd: ^TWordArray;
lpwsz: LPWSTR;
lpdit: PDLGITEMTEMPLATE; /// 对话框条目模版数据
nchar: BYTE;
i: Integer;
begin
Result := 0;
if Length(Controls) = 0 then Exit;
hgbl := GlobalAlloc(GMEM_ZEROINIT, 4096);
if hgbl = 0 then Exit;
/// define dialog
lpdt := GlobalLock(hgbl);
lpdt.style := Controls[0].dlgTemplate.style and (not DS_SETFONT);
lpdt.dwExtendedStyle := Controls[0].dlgTemplate.dwExtendedStyle;
lpdt.cdit := Length(Controls) - 1;
lpdt.x := Controls[0].dlgTemplate.x;
lpdt.y := Controls[0].dlgTemplate.y;
lpdt.cx := Controls[0].dlgTemplate.cx;
lpdt.cy := Controls[0].dlgTemplate.cy;
lpwd := Pointer(DWORD(lpdt) + SizeOf(TDlgTemplate));
lpwd[0] := 0;
lpwd[1] := 0;
lpwsz := Pointer(DWORD(lpwd) + 4);
nchar := MultiByteToWideChar(CP_ACP, 0, PChar(Controls[0].Caption), Length(Controls[0].Caption), lpwsz, 50) + 1;
lpwd := Pointer(DWORD(lpwsz) + nchar * 2);
lpwd := Pointer(lpwAlign(DWORD(lpwd))); // align DLGITEMTEMPLATE on DWORD boundary
for i := Succ(Low(Controls)) to High(Controls) do
begin /// Define Controls
lpdit := Pointer(lpwd);
lpdit.x := Controls[i].dlgTemplate.x;
lpdit.y := Controls[i].dlgTemplate.y;
lpdit.cx := Controls[i].dlgTemplate.cx;
lpdit.cy := Controls[i].dlgTemplate.cy;
lpdit.style := Controls[i].dlgTemplate.style;
lpdit.id := Controls[i].dlgTemplate.id;
lpwd := Pointer(DWORD(lpdit) + SizeOf(TDlgItemTemplate));
lpwsz := Pointer(DWORD(lpwd));
nchar := MultiByteToWideChar(CP_ACP, 0, PChar(Controls[i].ClassName), Length(Controls[i].ClassName), lpwsz, 50) + 1;
lpwd := Pointer(DWORD(lpwsz) + nchar * 2);
lpwd[0] := 0;
lpwd := Pointer(lpwAlign(DWORD(lpwd) + 2)); // align DLGITEMTEMPLATE on DWORD boundary
end;
GlobalUnlock(hgbl);
if DlgProc = nil then
Result := DialogBoxIndirectParam(hInstance, PDlgTemplate(hgbl)^, GetActiveWindow, @DefDialogProc, Integer(@Controls))
else
Result := DialogBoxIndirectParam(hInstance, PDlgTemplate(hgbl)^, GetActiveWindow, DlgProc, Integer(@Controls));
GlobalFree(hgbl);
end;
function MakeFont(FontName: string; Size, Bold: integer; StrikeOut, Underline, Italy: Boolean): Integer;
{
创建指定的字体
}
begin
Result := CreateFont(Size, 0, 0, 0, Bold,
Ord(Italy), Ord(UnderLine), Ord(StrikeOut),
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH or FF_DONTCARE, PChar(FontName));
end;
procedure SetFont(hWnd: HWND; Font: HFONT);
{
设置控件的字体为指定的字体
}
begin
SendMessage(hWnd, WM_SETFONT, Font, 0);
end;
procedure DlgInfo(const Msg, Title: string);
{
简单的显示信息对话框
}
begin
MsgBox(Msg, Title);
end;
procedure DlgError(const Msg: string);
{
显示错误信息对话框
}
begin
MsgBox(Msg, PChar(SError), MB_ICONERROR + MB_OK);
end;
function MsgBox(const Msg: string; const Title: string = 'Info'; dType: integer = MB_OK + MB_ICONINFORMATION): integer;
{
显示一个信息对话框
}
begin
Result := MessageBox(GetActiveWindow, PChar(Msg), PChar(Title), dType);
end;
function SelectDirectoryEx(var Path: string; const Caption, Root: string; BIFs: DWORD = $59;
Callback: TSelectDirectoryProc = nil; const FileName: string = ''): Boolean;
{
调用标准的Windows浏览目录对话框并返回用户选择的目录路径,并且可以强制用户选择
的目录中必须包含某个文件
参数:
Path:输入、输出,输入作为初始化选择的目录,输出为用户选择的目录路径
Caption:给用户的提示信息
Root:作为根目录的目录,如果为空,则可以选择任意目录,不为空则用户只能选择
Root目录或者其子目录,不能选择其它的目录
BIF:控制用户能够选择目录的类型,例如是选择计算机还是打印机还是文件还是任意的
ShellObject以及对话框的外观,例如是不是有新建文件夹按钮等
FileName:如果为空,那么用户可以选择任意目录,否则的话,用户选择的目录必须包含
文件FileName
返回值:用户点击了Ok返回True,否则返回False
}
const
BIF_NEWDIALOGSTYLE = $0040;
type
TMyData = packed record
IniPath: PChar;
FileName: PChar;
Proc: TSelectDirectoryProc;
Flag: DWORD;
end;
PMyData = ^TMyData;
function BrowseCallbackProc(hwnd: HWND; uMsg: UINT; lParam: Cardinal; lpData: Cardinal): integer; stdcall;
var
PathName: array[0..MAX_PATH] of char;
begin
case uMsg of
BFFM_INITIALIZED:
SendMessage(Hwnd, BFFM_SETSELECTION, Ord(True), integer(PMyData(lpData).IniPath));
BFFM_SELCHANGED:
begin
SHGetPathFromIDList(PItemIDList(lParam), @PathName);
SendMessage(hwnd, BFFM_SETSTATUSTEXT, 0, LongInt(PChar(@PathName)));
if Assigned(PMyData(lpData).Proc) then
SendMessage(hWnd, BFFM_ENABLEOK, 0, Ord(PMyData(lpData).Proc(PathName)))
else if PMyData(lpData).FileName <> nil then
SendMessage(hWnd, BFFM_ENABLEOK, 0,
Ord(FileExists(IncludeTrailingPathDelimiter(PathName) + PMyData(lpData).FileName)))
else if (BIF_VALIDATE and PMyData(lpData).Flag) = BIF_VALIDATE then
SendMessage(hWnd, BFFM_ENABLEOK, 0, Ord(DirectoryExists(PathName)));
end;
end;
Result := 0;
end;
var
BrowseInfo: TBrowseInfo;
Buffer: PChar;
RootItemIDList, ItemIDList: PItemIDList;
ShellMalloc: IMalloc;
IDesktopFolder: IShellFolder;
Dummy: LongWord;
Data: TMyData;
begin
Result := False;
FillChar(BrowseInfo, SizeOf(BrowseInfo), 0);
if (ShGetMalloc(ShellMalloc) = S_OK) and (ShellMalloc <> nil) then
begin
Buffer := ShellMalloc.Alloc(MAX_PATH);
try
RootItemIDList := nil;
if Root <> '' then
begin
SHGetDesktopFolder(IDesktopFolder);
IDesktopFolder.ParseDisplayName(GetActiveWindow, nil, POleStr(WideString(Root)), Dummy, RootItemIDList, Dummy);
end;
with BrowseInfo do
begin
hwndOwner := GetActiveWindow;
pidlRoot := RootItemIDList;
pszDisplayName := Buffer;
lpszTitle := PChar(Caption);
ulFlags := BIFs;
lpfn := @BrowseCallbackProc;
Data.IniPath := PChar(Path);
Data.Flag := BIFs;
if FileName <> '' then
Data.FileName := PChar(FileName)
else
Data.FileName := nil;
Data.Proc := Callback;
lParam := Integer(@Data);
end;
ItemIDList := ShBrowseForFolder(BrowseInfo);
Result := ItemIDList <> nil;
if Result then
begin
ShGetPathFromIDList(ItemIDList, Buffer);
ShellMalloc.Free(ItemIDList);
Path := IncludeTrailingPathDelimiter(StrPas(Buffer));
end;
finally
ShellMalloc.Free(Buffer);
end;
end;
end;
procedure CreateFileOnDisk(FileName: string);
{
在磁盘上面创建指定的文件
}
begin
if not FileExists(FileName) then FileClose(FileCreate(FileName));
end;
function IsFileInUse(const FileName: string): boolean;
{
判断文件FileName是否正在被打开/使用
}
var
HFileRes: HFILE;
begin
if not FileExists(FileName) then
begin
Result := False;
Exit;
end;
try
HFileRes := CreateFile(pchar(FileName), GENERIC_READ,
0 {this is the trick!}, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
Result := (HFileRes = INVALID_HANDLE_VALUE);
if not Result then
CloseHandle(HFileRes);
except
Result := true;
end;
end;
function GetTmpFile(const AExt: string): string;
{
根据扩展名返回一个临时文件名
}
var
sPath: string;
begin
sPath := TempPath;
repeat
Result := sPath + '~' + IntToStr(GetTickCount) + AExt;
Sleep(1);
until not FileExists(Result);
end;
function GetTmpFileEx(const APath, APre, AExt: string): string;
{
根据扩展名返回一个临时文件名
}
begin
repeat
Result := APath + APre + IntToStr(GetTickCount) + AExt;
Sleep(1);
until not FileExists(Result);
end;
function TempPath: string;
{
返回临时文件夹目录路径
}
begin
SetLength(Result, GetTempPath(0, PChar(Result)));
ZeroMemory(PChar(Result), Length(Result));
GetTempPath(Length(Result), PChar(Result));
Result := PChar(Result);
end;
procedure GetFileList(Files: TStrings; Folder, FileSpec: string; SubDir: Boolean = True; CallBack: TFindFileProc = nil);
{
获取文件名列表
Files:用来保存返回的文件名列表
Folder:需要扫描的文件夹
FileSpec:文件名,支持通配符*和?
SubDir:是否包含子目录下的文件
}
var
SRec: TSearchRec; //Required for Find* functions.
FFolder: string;
begin
FFolder := IncludeTrailingPathDelimiter(Folder);
if FindFirst(FFolder + FileSpec, faAnyFile, SRec) = 0 then
begin
repeat
if Assigned(CallBack) then CallBack(FFolder + SRec.Name, SRec);
if ((SRec.Attr and faDirectory) <> faDirectory) and (SRec.Name[1] <> '.') then
Files.Add(FFolder + SRec.Name);
until FindNext(SRec) <> 0;
FindClose(SRec);
end;
if SubDir then
if FindFirst(FFolder + '*', faDirectory, SRec) = 0 then
begin
repeat
if ((SRec.Attr and faDirectory) = faDirectory) and (SRec.Name[1] <> '.') then
GetFileList(Files, FFolder + SRec.Name, FileSpec, SubDir, CallBack);
until FindNext(SRec) <> 0;
FindClose(SRec);
end;
end;
procedure GetFileListName(Files: TStrings; const Folder, FileSpec: string);
{
返回一个指定目录下指定文件的文件名集合,不包括子文件夹下的文件
Files:用来保存返回的文件名列表
Folder:需要扫描的文件夹
FileSpec:文件名,支持通配符*和?
}
var
SRec: TSearchRec; //Required for Find* functions.
FFolder: string;
begin
FFolder := IncludeTrailingPathDelimiter(Folder);
if FindFirst(FFolder + FileSpec, faAnyFile, SRec) = 0 then
begin
repeat
if ((SRec.Attr and faDirectory) <> faDirectory) and (SRec.Name[1] <> '.') then
Files.Add(SRec.Name);
until FindNext(SRec) <> 0;
FindClose(SRec);
end;
end;
procedure GetDirectoryList(Directorys: TStrings; const Folder: string);
{
获取文件名列表
Directorys:用来保存返回的目录列表
}
var
SRec: TSearchRec; //Required for Find* functions.
FFolder: string;
begin
FFolder := IncludeTrailingPathDelimiter(Folder);
if FindFirst(FFolder + '*.*', faAnyFile, SRec) = 0 then
begin
repeat
if ((SRec.Attr and faDirectory) = faDirectory) and (SRec.Name[1] <> '.') then
Directorys.Add(FFolder + SRec.Name);
until FindNext(SRec) <> 0;
FindClose(SRec);
end;
end;
procedure GetDirectoryListName(Directorys: TStrings; const Folder: string);
{
获取目录列表
Directorys:用来保存返回的目录名列表
}
var
SRec: TSearchRec; //Required for Find* functions.
FFolder: string;
begin
FFolder := IncludeTrailingPathDelimiter(Folder);
if FindFirst(FFolder + '*.*', faAnyFile, SRec) = 0 then
begin
repeat
if ((SRec.Attr and faDirectory) = faDirectory) and (SRec.Name[1] <> '.') then
Directorys.Add(SRec.Name);
until FindNext(SRec) <> 0;
FindClose(SRec);
end;
end;
function IsSpace(const Ch: Char): Boolean;
{
判断Ch是否是空白字符
}
begin
Result := Ch in [#32, #8, #13, #10];
end;
function IsXDigit(const Ch: Char): Boolean;
{
判断Ch是否是十六进制数字字符
}
begin
Result := ch in ['0'..'9', 'a'..'f', 'A'..'F'];
end;
function IsInteger(const S: string): Boolean;
{
判断字符串S是否是一个合法的整数,是,返回True,否则返回False
}
var
iValue: Integer;
begin
Result := TryStrToInt(S, iValue);
end;
function IsInt64(const S: string): Boolean;
var
iValue: Int64;
begin
Result := TryStrToInt64(S, iValue);
end;
function IsFloat(const S: string): Boolean;
{
判断字符串S是否是一个合法的浮点数,是,返回True,否则返回False
}
var
dValue: Double;
begin
Result := TryStrToFloat(S, dValue);
end;
function LeftPart(Source, Seperator: string): string;
{
返回字符串中Seperator左边的字符串,例如LeftPart('ab|cd','|')='ab'
只返回第一个Seperator的左右字符串,若找不到Seperator,则返回整个字符串
}
var
iPos: integer;
begin
iPos := Pos(Seperator, Source);
if iPos > 0 then
Result := Copy(Source, 1, iPos - 1)
else
Result := Source;
end;
function RightPart(Source, Seperator: string): string;
{
返回字符串中Seperator右边边的字符串,例如RightPart('ab|cd','|')='ab'
只返回第一个Seperator的右边字符串,若找不到Seperator,则返回整个字符串
}
var
iPos: integer;
begin
iPos := Pos(Seperator, Source);
if iPos > 0 then
Result := Copy(Source, iPos + Length(Seperator), Length(Source) - iPos)
else
Result := Source;
end;
function LastRightPart(Source, Seperator: string): string;
{
返回字符串中Seperator最右边的字符串,例如LastRightPart('ab|cd|ef','|')='ef'
}
var
i, iPos, iLen, iSepLen: Integer;
sPart: string;
begin
iPos := 1;
iLen := Length(Source);
iSepLen := Length(Seperator);
for i := iLen-iSepLen+1 downto 1 do
begin
sPart := Copy(Source, i, iSepLen);
if sPart = Seperator then
begin
iPos := i+1;
Break;
end;
end;
Result := Copy(Source, iPos, MAXWORD);
end;
function GMTNow: TDateTime;
{
返回当前的系统的GMT/UTC时间
}
var
TimeRec: TSystemTime;
begin
GetSystemTime(TimeRec);
Result := SystemTimeToDateTime(TimeRec);
end;
const
MinsPerDay = 24 * 60;
function GetGMTBias: Integer;
var
info: TTimeZoneInformation;
Mode: DWord;
begin
Mode := GetTimeZoneInformation(info);
Result := info.Bias;
case Mode of
TIME_ZONE_ID_INVALID: RaiseLastOSError;
TIME_ZONE_ID_STANDARD: Result := Result + info.StandardBias;
TIME_ZONE_ID_DAYLIGHT: Result := Result + info.DaylightBias;
end;
end;
function LocaleToGMT(const Value: TDateTime): TDateTime;
{
把本地时间Value转换成GMT/UTC时间
}
begin
Result := Value + (GetGMTBias / MinsPerDay);
end;
function GMTToLocale(const Value: TDateTime): TDateTime;
{
把GMT/UTC时间Value转换成本地时间
}
begin
Result := Value - (GetGMTBias / MinsPerDay);
end;
function HKEYToStr(const Key: HKEY): string;
begin
if (Key < HKEY_CLASSES_ROOT) or (Key > HKEY_DYN_DATA) then
Result := ''
else
Result := CSHKeyNames[HKEY_CLASSES_ROOT];
end;
function StrToHKEY(const KEY: string): HKEY;
begin
for Result := Low(CSHKeyNames) to High(CSHKeyNames) do
if SameText(CSHKeyNames[Result], KEY) then
Exit;
Result := $FFFFFFFF;
end;
function RegExtractHKEY(const Reg: string): HKEY;
{
从完整注册表路径中提取HKEY
}
begin
Result := StrToHKEY(LeftPart(Reg, '\'));
end;
function RegExtractSubKey(const Reg: string): string;
{
从完整字符串中提取注册表SubKey
}
begin
Result := RightPart(Reg, '\');
end;
function RegExportToFile(const RootKey: HKEY; const SubKey, FileName: string): Boolean;
{
导出注册表到文件
}
var
Key: HKEY;
begin
Result := False;
EnablePrivilege('SeBackupPrivilege', True);
if ERROR_SUCCESS = RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_ALL_ACCESS, Key) then
begin
Result := RegSaveKey(Key, PChar(FileName), nil) = ERROR_SUCCESS;
RegCloseKey(Key);
end;
end;
function RegImportFromFile(const RootKey: HKEY; const SubKey, FileName: string): Boolean;
{
导入注册表
}
begin
EnablePrivilege('SeBackupPrivilege', True);
Result := RegLoadKey(RootKey, PChar(SubKey), PChar(FileName)) = ERROR_SUCCESS;
end;
function RegReadString(const RootKey: HKEY; const SubKey, ValueName: string): string;
var
Key: HKEY;
T: DWORD;
L: DWORD;
begin
if ERROR_SUCCESS = RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_ALL_ACCESS, Key) then
begin
if ERROR_SUCCESS = RegQueryValueEx(Key, PChar(ValueName), nil, @T, nil, @L) then
begin
if T <> REG_SZ then raise Exception.Create(SErrDataType);
SetLength(Result, L);
RegQueryValueEx(Key, PChar(ValueName), nil, @T, PByte(PChar(Result)), @L);
end;
SetString(Result, PChar(Result), L - 1);
RegCloseKey(Key);
end;
end;
function RegReadInteger(const RootKey: HKEY; const SubKey, ValueName: string): integer;
var
Key: HKEY;
T: DWORD;
L: DWORD;
begin
if ERROR_SUCCESS = RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_ALL_ACCESS, Key) then
begin
if ERROR_SUCCESS = RegQueryValueEx(Key, PChar(ValueName), nil, @T, nil, @L) then
begin
if T <> REG_DWORD then raise Exception.Create(SErrDataType);
RegQueryValueEx(Key, PChar(ValueName), nil, @T, @Result, @L);
end;
RegCloseKey(Key);
end;
end;
function RegReadBinary(const RootKey: HKEY; const SubKey, ValueName: string; Data: PChar; out Len: integer): Boolean;
{
从注册表中读取二进制数据
RootKey:指定主分支
SubKey:子键的名字
ValueName:键名,可以为空,为空即表示默认值
Data:保存读取到的数据
Len:读取到的数据的长度
}
var
Key: HKEY;
T: DWORD;
begin
Result := False;
if ERROR_SUCCESS = RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_ALL_ACCESS, Key) then
begin
if ERROR_SUCCESS = RegQueryValueEx(Key, PChar(ValueName), nil, @T, nil, @Len) then
begin
ReallocMem(Data, Len);
Result := ERROR_SUCCESS = RegQueryValueEx(Key, PChar(ValueName), nil, @T, PByte(Data), @Len);
end;
RegCloseKey(Key);
end;
end;
function RegWriteString(const RootKey: HKEY; const SubKey, ValueName, Value: string): Boolean;
{
写入一个字符串到注册表中
RootKey:指定主分支
SubKey:子键的名字
ValueName:键名,可以为空,为空即表示写入默认值
Value:数据
}
var
Key: HKEY;
R: DWORD;
begin
Result := (ERROR_SUCCESS = RegCreateKeyEx(RootKey, PChar(SubKey), 0, 'Data',
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nil, Key, @R)) and
(ERROR_SUCCESS = RegSetValueEx(Key, PChar(ValueName), 0, REG_SZ, PChar(Value), Length(Value)));
RegCloseKey(Key);
end;
function RegReadMultiString(const RootKey: HKEY; const SubKey, ValueName: string): string;
{
读取注册表中指定的多字符串
}
var
Key: HKEY;
T: DWORD;
L: DWORD;
begin
if ERROR_SUCCESS = RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_ALL_ACCESS, Key) then
begin
if ERROR_SUCCESS = RegQueryValueEx(Key, PChar(ValueName), nil, @T, nil, @L) then
begin
if T <> REG_MULTI_SZ then raise Exception.Create(SErrDataType);
SetLength(Result, L);
RegQueryValueEx(Key, PChar(ValueName), nil, @T, PByte(PChar(Result)), @L);
end;
SetString(Result, PChar(Result), L);
RegCloseKey(Key);
end;
end;
function RegWriteMultiString(const RootKey: HKEY; const SubKey, ValueName, Value: string): Boolean;
{
写入字符串到注册表中
Value为#0分隔的多行字符串,最后以双#0#0结尾
}
var
Key: HKEY;
R: DWORD;
begin
Result := (ERROR_SUCCESS = RegCreateKeyEx(RootKey, PChar(SubKey), 0, 'Data',
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nil, Key, @R)) and
(ERROR_SUCCESS = RegSetValueEx(Key, PChar(ValueName), 0, REG_MULTI_SZ, PChar(Value), Length(Value)));
RegCloseKey(Key);
end;
function RegWriteInteger(const RootKey: HKEY; const SubKey, ValueName: string; const Value: integer): Boolean;
{
写入一个整数到注册表中
RootKey:指定主分支
SubKey:子键的名字
ValueName:键名,可以为空,为空即表示写入默认值
Value:数据
}
var
Key: HKEY;
R: DWORD;
begin
Result := (ERROR_SUCCESS = RegCreateKeyEx(RootKey, PChar(SubKey), 0, 'Data',
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nil, Key, @R)) and
(ERROR_SUCCESS = RegSetValueEx(Key, PChar(ValueName), 0, REG_DWORD, @Value, SizeOf(Value)));
RegCloseKey(Key);
end;
function RegWriteBinary(const RootKey: HKEY; const SubKey, ValueName: string; Data: PChar; Len: integer): Boolean;
{
从注册表中读取二进制数据
}
var
Key: HKEY;
R: DWORD;
begin
Result := (ERROR_SUCCESS = RegCreateKeyEx(RootKey, PChar(SubKey), 0, 'Data',
REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nil, Key, @R)) and
(ERROR_SUCCESS = RegSetValueEx(Key, PChar(ValueName), 0, REG_BINARY, Data, Len));
RegCloseKey(Key);
end;
function RegValueExists(const RootKey: HKEY; const SubKey, ValueName: string): Boolean;
{
判断注册表中是否存在指定的键名
}
var
Key: HKEY;
Dummy: DWORD;
begin
Result := False;
if ERROR_SUCCESS = RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_READ, Key) then
begin
Result := ERROR_SUCCESS = RegQueryValueEx(Key, PChar(ValueName), nil, @Dummy, nil, @Dummy);
RegCloseKey(Key);
end;
end;
function RegKeyExists(const RootKey: HKEY; const SubKey: string): Boolean;
{
判断注册表中是否存在指定的键
}
var
Key: HKEY;
begin
Result := RegOpenKey(RootKey, PChar(SubKey), Key) = ERROR_SUCCESS;
if Result then RegCloseKey(Key);
end;
function RegKeyDelete(const RootKey: HKEY; const SubKey: string): Boolean;
{
删除注册表中指定的主键
}
begin
Result := RegDeleteKey(RootKey, PChar(SubKey)) = ERROR_SUCCESS;
end;
function RegValueDelete(const RootKey: HKEY; const SubKey, ValueName: string): Boolean;
{
删除注册表中指定的键值
}
var
RegKey: HKEY;
begin
Result := False;
if RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_SET_VALUE, RegKey) = ERROR_SUCCESS then
begin
Result := RegDeleteValue(RegKey, PChar(ValueName)) = ERROR_SUCCESS;
RegCloseKey(RegKey);
end
end;
function RegGetValueNames(const RootKey: HKEY; const SubKey: string; Names: TStrings): Boolean;
{
返回注册表中指定主键下的所有的键名列表
}
var
RegKey: HKEY;
I: DWORD;
Size: DWORD;
NumSubKeys: DWORD;
NumSubValues: DWORD;
MaxSubValueLen: DWORD;
ValueName: string;
begin
Result := False;
if RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
if RegQueryInfoKey(RegKey, nil, nil, nil, @NumSubKeys, nil, nil, @NumSubValues,
@MaxSubValueLen, nil, nil, nil) = ERROR_SUCCESS then
begin
SetLength(ValueName, MaxSubValueLen + 1);
if NumSubValues <> 0 then
for I := 0 to NumSubValues - 1 do
begin
Size := MaxSubValueLen + 1;
RegEnumValue(RegKey, I, PChar(ValueName), Size, nil, nil, nil, nil);
Names.Add(PChar(ValueName));
end;
Result := True;
end;
RegCloseKey(RegKey);
end;
end;
function RegGetKeyNames(const RootKey: HKEY; const SubKey: string; Names: TStrings): Boolean;
{
返回注册表中指定主键下的所有子键的名称列表
}
var
RegKey: HKEY;
I: DWORD;
Size: DWORD;
NumSubKeys: DWORD;
MaxSubKeyLen: DWORD;
KeyName: string;
begin
Result := False;
if RegOpenKeyEx(RootKey, PChar(SubKey), 0, KEY_READ, RegKey) = ERROR_SUCCESS then
begin
if RegQueryInfoKey(RegKey, nil, nil, nil, @NumSubKeys, @MaxSubKeyLen, nil, nil, nil, nil, nil, nil) = ERROR_SUCCESS then
begin
SetLength(KeyName, MaxSubKeyLen + 1);
if NumSubKeys <> 0 then
for I := 0 to NumSubKeys - 1 do
begin
Size := MaxSubKeyLen + 1;
RegEnumKeyEx(RegKey, I, PChar(KeyName), Size, nil, nil, nil, nil);
Names.Add(PChar(KeyName));
end;
Result := True;
end;
RegCloseKey(RegKey);
end
end;
function EnablePrivilege(PrivName: string; bEnable: Boolean): Boolean;
{
允许/禁止指定的系统特权,PrivName:需要设置的特权名称
返回值:成功设置返回True,否则False
}
var
hToken: Cardinal;
TP: TOKEN_PRIVILEGES;
Dummy: Cardinal;
begin
OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken);
TP.PrivilegeCount := 1;
LookupPrivilegeValue(nil, pchar(PrivName), TP.Privileges[0].Luid);
if bEnable then
TP.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED
else
TP.Privileges[0].Attributes := 0;
AdjustTokenPrivileges(hToken, False, TP, SizeOf(TP), nil, Dummy);
Result := GetLastError = ERROR_SUCCESS;
CloseHandle(hToken);
end;
end.
|
unit TestRSSParser;
interface
uses
TestFramework, RSSParser, XmlDocRssParser;
type
TRSSParserTest = class(TTestCase)
private
FParser: TXmlDocParser;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure ParsesRSSDate;
procedure ParsesRSSFeed;
procedure RaisesAnExceptionWhenDateCantBeParsed;
procedure RaisesAnExceptionIfRSSIsInvalid;
procedure RaisesAnExceptionIfRSSIsEmpty;
end;
implementation
uses
System.SysUtils, System.IOUtils, System.StrUtils, RSSModel;
{ TRSSParserTest }
procedure TRSSParserTest.ParsesRSSDate;
var
d: TDateTime;
begin
d := FParser.ParseRSSDate('Mon, 06 Sep 2009 16:45:00 +0000');
CheckEquals('2009-09-06 16:45:00', FormatDateTime('yyyy-mm-dd hh:nn:ss', d));
end;
procedure TRSSParserTest.ParsesRSSFeed;
var
feedContent: string;
rssFeed: TRSSFeed;
rssItem: TRSSItem;
testFileName: string;
begin
feedContent := EmptyStr;
testFileName := ExtractFilePath(ParamStr(0)) + 'feed.xml';
feedContent := TFile.ReadAllText(testFileName, TEncoding.UTF8);
rssFeed := FParser.ParseRSSFeed(feedContent);
CheckEquals('rss.rbc.ru', rssFeed.Description);
CheckEquals('https://www.rbc.ru/', rssFeed.Link);
CheckEquals('РБК - Все материалы', rssFeed.Title);
rssItem := rssFeed.Items[0];
CheckTrue(ContainsText(rssItem.Description, 'власти затребовали средства'));
CheckEquals('https://www.rbc.ru/finances/22/07/2019/5d35b51f9a7947961e118b41', rssItem.Link);
CheckEquals('Минфин поручил вернуть деньги на ликвидацию паводка в Иркутской области', rssItem.Title);
end;
procedure TRSSParserTest.RaisesAnExceptionIfRSSIsEmpty;
begin
ExpectedException := ERSSParserException;
FParser.ParseRSSFeed('');
end;
procedure TRSSParserTest.RaisesAnExceptionIfRSSIsInvalid;
begin
ExpectedException := ERSSParserException;
FParser.ParseRSSFeed('MALFORMED XML');
end;
procedure TRSSParserTest.RaisesAnExceptionWhenDateCantBeParsed;
begin
ExpectedException := ERSSParserException;
FParser.ParseRSSDate('2011-01-02 12:34:45');
end;
procedure TRSSParserTest.SetUp;
begin
inherited;
FParser := TXmlDocParser.Create;
end;
procedure TRSSParserTest.TearDown;
begin
inherited;
FParser.Free;
end;
initialization
RegisterTest(TRSSParserTest.Suite);
end.
|
unit Steal;
(*****************************************************************************
Prozessprogrammierung SS08
Aufgabe: Muehle
Diese Unit beinhaltet die Klautask, die fuer das Klauen eines Spielsteines
des aktuellen Spielers notwendig ist.
Autor: Alexander Bertram (B_TInf 2616)
*****************************************************************************)
interface
procedure StealTask;
implementation
uses
RTKernel,
Semas, PTypes, LeadMB, Leader;
{$F+}
procedure StealTask;
(*****************************************************************************
Beschreibung:
Klautask.
In:
-
Out:
-
*****************************************************************************)
var
LeaderMessage: TLeaderMessage;
begin
{ Nachrichtart als Klaunachricht markieren }
LeaderMessage.Kind := lemkStealToken;
while true do
begin
{ An der Printscrensemaphore (ISP) warten }
Wait(PrintScreenSemaphore);
{ Spielleiter benachrichtigen }
LeadMB.PutFront(Leader.Mailbox, LeaderMessage);
end;
end;
end. |
{
Find duplicate dialogue responses and create shared INFOs for them.
Quest and Topic to collect created shared INFOs can be selected from existing shared Topics, or a new Topic can be created.
Apply to a whole plugin or selected topics.
Use Del key to remove lines you don't want to be shared in the list.
Supported games: Skyrim
}
unit CreateSharedInfos;
var
slINFOs: TStringList;
Plugin: IInterface;
frm: TForm;
lbl: TLabel;
cmbQuest, cmbTopic: TComboBox;
lvLines: TListView;
btnOk, btnCancel: TButton;
//===========================================================================
procedure DoCreateSharedInfos(quest, dial: IInterface);
var
i, j: integer;
list: TList;
sharedinfo, info: IInterface;
begin
if slINFOs.Count = 0 then
Exit;
AddMessage('Creating shared responses, please wait...');
// create new shared topic DIAL if not provided
if not Assigned(dial) then begin
dial := Add(GroupBySignature(Plugin, 'DIAL'), 'DIAL', True);
SetElementEditValues(dial, 'EDID', 'SharedInfosTopic');
SetElementEditValues(dial, 'QNAM', Name(quest));
SetElementEditValues(dial, 'PNAM', '50');
SetElementEditValues(dial, 'SNAM', 'IDAT');
Add(dial, 'DATA', True);
SetElementEditValues(dial, 'DATA\Category', 'Miscellaneous');
SetElementEditValues(dial, 'DATA\Subtype', 'SharedInfo');
end;
// process duplicate responses
for i := 0 to Pred(slINFOs.Count) do begin
list := TList(slINFOs.Objects[i]);
sharedinfo := nil;
for j := 0 to Pred(list.Count) do begin
info := ObjectToElement(list[j]);
// create shared INFO
if not Assigned(sharedinfo) then begin
sharedinfo := Add(dial, 'INFO', True);
Add(sharedinfo, 'ENAM', True);
Add(sharedinfo, 'CNAM', True);
Add(sharedinfo, 'Responses', True);
ElementAssign(ElementByPath(sharedinfo, 'Responses'), LowInteger, ElementByPath(info, 'Responses'), False);
end;
// link response INFO to the shared one
SetElementEditValues(info, 'DNAM', Name(sharedinfo));
end;
end;
// update the count of INFOs in DIAL
SetElementNativeValues(dial, 'TIFC', ElementCount(ChildGroup(dial)));
end;
//===========================================================================
procedure lvLinesData(Sender: TObject; Item: TListItem);
begin
Item.Caption := slINFOs[Item.Index];
Item.SubItems.Add(IntToStr(TList(slINFOs.Objects[Item.Index]).Count));
end;
//===========================================================================
procedure lvLinesKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
i: integer;
begin
if Key = VK_DELETE then begin
if not Assigned(lvLines.Selected) then
Exit;
i := lvLines.Selected.Index;
TList(slINFOs.Objects[i]).Free;
slINFOs.Delete(i);
lvLines.Items.Count := slINFOs.Count;
lvLines.Refresh;
end;
end;
//===========================================================================
procedure cmbQuestOnChange(Sender: TObject);
var
quest, dial: IInterface;
i: integer;
begin
cmbTopic.Items.Clear;
cmbTopic.Items.Add('<Create new topic>');
quest := ObjectToElement(cmbQuest.Items.Objects[cmbQuest.ItemIndex]);
for i := 0 to Pred(ReferencedByCount(quest)) do begin
dial := ReferencedByIndex(quest, i);
if Signature(dial) <> 'DIAL' then
Continue;
if GetElementEditValues(dial, 'DATA\Subtype') = 'SharedInfo' then
cmbTopic.Items.AddObject(Name(dial), dial);
end;
cmbTopic.ItemIndex := 0;
end;
//===========================================================================
procedure CreateSharedForm;
var
quests, quest: IInterface;
i: integer;
sl: TStringList;
begin
frm := TForm.Create(nil);
try
frm.Caption := 'Shared Infos';
frm.Width := 900;
frm.Height := 550;
frm.Position := poScreenCenter;
lbl := TLabel.Create(frm); lbl.Parent := frm;
lbl.Top := 12;
lbl.Left := 8;
lbl.Caption := 'Create shared infos in Quest';
cmbQuest := TComboBox.Create(frm);
cmbQuest.Parent := frm;
cmbQuest.Left := lbl.Left + lbl.Width + 10;
cmbQuest.Top := 8;
cmbQuest.Width := 250;
cmbQuest.Style := csDropDownList;
cmbQuest.DropDownCount := 20;
cmbQuest.OnChange := cmbQuestOnChange;
quests := GroupBySignature(Plugin, 'QUST');
sl := TStringList.Create;
for i := 0 to Pred(ElementCount(quests)) do begin
quest := ElementByIndex(quests, i);
sl.AddObject(EditorID(quest), quest);
end;
sl.Sort;
cmbQuest.Items.Assign(sl);
sl.Free;
cmbQuest.ItemIndex := 0;
lbl := TLabel.Create(frm); lbl.Parent := frm;
lbl.Top := 12;
lbl.Left := cmbQuest.Left + cmbQuest.Width + 10;
lbl.Caption := 'under Shared Topic';
cmbTopic := TComboBox.Create(frm);
cmbTopic.Parent := frm;
cmbTopic.Left := lbl.Left + lbl.Width + 10;
cmbTopic.Top := 8;
cmbTopic.Width := 350;
cmbTopic.Anchors := [akLeft, akTop, akRight];
cmbTopic.Style := csDropDownList;
cmbTopic.DropDownCount := 20;
cmbQuestOnChange(nil);
lvLines := TListView.Create(frm);
lvLines.Parent := frm;
lvLines.Left := 8;
lvLines.Top := 36;
lvLines.Width := frm.Width - 40;
lvLines.Height := frm.Height - 120;
lvLines.TabOrder := 0;
lvLines.Anchors := [akLeft, akTop, akRight, akBottom];
lvLines.ReadOnly := True;
lvLines.ViewStyle := vsReport;
lvLines.DoubleBuffered := True;
lvLines.RowSelect := True;
lvLines.Columns.Add.Caption := 'Responses';
lvLines.Columns[0].Width := lvLines.Width - 110;
lvLines.Columns.Add.Caption := 'Duplicates';
lvLines.Columns[1].Width := 80;
lvLines.OwnerData := True;
lvLines.OnData := lvLinesData;
lvLines.OnKeyDown := lvLinesKeyDown;
lvLines.Items.Count := slINFOs.Count;
btnOk := TButton.Create(frm); btnOk.Parent := frm;
btnOk.Caption := 'Create';
btnOk.ModalResult := mrOk;
btnOk.Left := frm.Width - 190;
btnOk.Top := frm.Height - 72;
btnOk.Anchors := [akBottom, akRight];
btnCancel := TButton.Create(frm); btnCancel.Parent := frm;
btnCancel.Caption := 'Cancel';
btnCancel.ModalResult := mrCancel;
btnCancel.Left := btnOk.Left + btnOk.Width + 8;
btnCancel.Top := btnOk.Top;
btnCancel.Anchors := [akBottom, akRight];
if frm.ShowModal = mrOk then
DoCreateSharedInfos(
ObjectToElement(cmbQuest.Items.Objects[cmbQuest.ItemIndex]),
ObjectToElement(cmbTopic.Items.Objects[cmbTopic.ItemIndex])
)
finally
frm.Free;
end;
end;
//===========================================================================
function Initialize: Integer;
begin
if wbGameMode <> gmTES5 then begin
MessageDlg('Supported games: Skyrim', mtInformation, [mbOk], 0);
Result := 1;
Exit;
end;
slINFOs := TStringList.Create;
end;
//===========================================================================
function Process(e: IInterface): Integer;
var
responses, response: IInterface;
i: integer;
line: string;
list: TList;
begin
// process only INFO records
if Signature(e) <> 'INFO' then
Exit;
// skip overrides
if not IsMaster(e) then
Exit;
// skip INFOs that already use shared info
if ElementExists(e, 'DNAM') then
Exit;
// skip INFOs which are shared INFOs themselves
if GetElementEditValues(LinksTo(ElementByName(e, 'Topic')), 'DATA\Subtype') = 'SharedInfo' then
Exit;
responses := ElementByName(e, 'Responses');
if not Assigned(responses) then
Exit;
// iterate over responses
for i := 0 to Pred(ElementCount(responses)) do begin
response := ElementByIndex(responses, i);
// create a line with emotion value and response text
line := ' [' + GetElementEditValues(response, 'TRDT\Emotion Type') + '] ' + GetElementEditValues(response, 'NAM1');
end;
// collect list of all responses
i := slINFOs.IndexOf(line);
// if duplicate, then add under existing entry
if i <> - 1 then
TList(slINFOs.Objects[i]).Add(e)
// if new, then add to the list
else begin
list := TList.Create;
list.Add(e);
slINFOs.AddObject(line, list);
end;
Plugin := GetFile(e);
end;
//===========================================================================
function Finalize: Integer;
var
i: integer;
list: TList;
begin
// remove single responses
for i := Pred(slINFOs.Count) downto 0 do begin
list := TList(slINFOs.Objects[i]);
if list.Count < 2 then begin
list.Free;
slINFOs.Delete(i);
end;
end;
if slINFOs.Count > 0 then
CreateSharedForm
else
MessageDlg('No duplicate responses found.', mtInformation, [mbOk], 0);
for i := 0 to Pred(slINFOs.Count) do
TList(slINFOs.Objects[i]).Free;
slINFOs.Free;
end;
end. |
unit VSEConsoleInterface;
{$IFNDEF VSE_CONSOLE}{$ERROR Please don't include VSEConsoleInterface unit without VSE_CONSOLE defined}{$ENDIF}
interface
uses
Windows, AvL, avlMath, avlUtils, OpenGL, VSEOpenGLExt, VSECore, VSEConsole;
type
TConsoleColors = (clBackground, clNormalLine, clWarningLine, clErrorLine,
clBorderLine, clCmdLineBorder, clBgLines, clScroll, clFPS);
TConsoleColorSet = array[TConsoleColors] of TColor;
TConsoleInterface = class(TModule)
private
FActive, FBlocking, FFontBold: Boolean;
FScreenHeight: Single;
FLogCache, FCmdHistory: TStringList;
FFont, FCachedLines, FLogPosition, FCursor, FCmdHistoryIndex, FLineLength: Integer;
FColors: TConsoleColorSet;
FCommandLine, FFontName: string;
procedure SetActive(Value: Boolean);
procedure AddToCache(const Line: string);
function LogEndPosition: Integer;
procedure UpdateFont(ScreenHeight: Single; Force: Boolean = false);
function ConColorHandler(Sender: TObject; Args: array of const): Boolean;
function ConFontHandler(Sender: TObject; Args: array of const): Boolean;
function HelpHandler(Sender: TObject; Args: array of const): Boolean;
public
constructor Create; override;
destructor Destroy; override;
class function Name: string; override;
procedure Draw; override;
procedure Update; override;
procedure OnEvent(var Event: TCoreEvent); override;
procedure SetColors(const Colors: TConsoleColorSet);
procedure SetFont(const Name: string; Bold: Boolean = true);
property Active: Boolean read FActive write SetActive; //Console interface is opened
property Blocking: Boolean read FBlocking write FBlocking; //Block state updates & events when active
end;
var
ConsoleInterface: TConsoleInterface; //ConsoleInterface interface
implementation
uses
VSERender2D;
const
DefFont = 'Courier New';
DefColors: TConsoleColorSet = (
$CC4D4D4D, $FF00FF00, $FF00FFFF, $FF0066FF,
$FF00FF00, $CC80CC80, $80333333, $80808080, $FFFFFF00);
ColorNames: array[TConsoleColors] of string = (
'bg', 'nln', 'wln', 'eln', 'bd', 'clbd', 'bgln', 'scrl', 'fps');
DisplayLines = 19;
VK_TILDE = 192;
function ConColors: string;
var
i: TConsoleColors;
begin;
Result := ColorNames[Low(TConsoleColors)];
for i := Succ(Low(TConsoleColors)) to High(TConsoleColors) do
Result := Result + ':' + ColorNames[i];
end;
function LastChar(const S: string): Char;
begin
Result := #0;
if S <> '' then Result := S[Length(S)];
end;
{ TConsoleInterface }
constructor TConsoleInterface.Create;
begin
inherited;
FBlocking := true;
FLogCache := TStringList.Create;
FCmdHistory := TStringList.Create;
SetColors(DefColors);
SetFont(DefFont, true);
Console['help'] := HelpHandler;
Console['confont name=s ?weight=en:b'] := ConFontHandler;
Console['concolor ?name=e' + ConColors + ' ?clr=i'] := ConColorHandler;
ConsoleInterface := Self;
end;
destructor TConsoleInterface.Destroy;
begin
ConsoleInterface := nil;
FAN(FCmdHistory);
FAN(FLogCache);
inherited;
end;
class function TConsoleInterface.Name: string;
begin
Result:='ConsoleInterface';
end;
procedure TConsoleInterface.Draw;
function RemovePostfix(const S: string): string;
begin
if LastChar(S) in [PostfixWarning, PostfixError]
then Result := Copy(S, 1, Length(S) - 1)
else Result := S;
end;
var
i, CommandLineStart: Integer;
ScreenWidth, ScreenHeight, CharWidth, CaretPos, CaretHeight, Temp: Single;
Line: string;
begin
if not FActive then Exit;
Render2D.Enter;
with Render2D.VSBounds do
begin
ScreenWidth := Right - Left;
ScreenHeight := Bottom - Top;
glPushMatrix;
glTranslate(Left, Top, 0);
end;
UpdateFont(ScreenHeight);
CharWidth := Render2D.CharWidth(FFont, '_');
if FLineLength <> Floor(ScreenWidth / CharWidth) then
begin
FLineLength := Floor(ScreenWidth / CharWidth);
FLogCache.Clear;
FCachedLines := 0;
for i := 0 to Console.Log.Count - 1 do
AddToCache(Console.Log[i]);
FLogPosition := LogEndPosition;
end;
glLineWidth(ScreenHeight / 600);
Temp := 0.503 * ScreenHeight;
gleColor(FColors[clBackground]);
Render2D.DrawRect(0, 0, ScreenWidth, Temp);
gleColor(FColors[clBorderLine]);
Render2D.DrawLine(0, Temp, ScreenWidth, Temp);
gleColor(FColors[clBgLines]);
Temp := 0.005 * ScreenHeight;
for i := 0 to 100 do
Render2D.DrawLine(0, i * Temp, ScreenWidth, i * Temp);
gleColor(FColors[clCmdLineBorder]);
Temp := 0.475 * ScreenHeight;
Render2D.DrawLine(0, Temp, ScreenWidth, Temp);
gleColor(FColors[clScroll]);
CaretHeight := Max(Temp * DisplayLines / FLogCache.Count, 0.01 * ScreenHeight);
CaretPos := Min(Temp * FLogPosition / FLogCache.Count, Temp - CaretHeight);
Temp := ScreenWidth - 0.025 * ScreenHeight;
Render2D.DrawLine(Temp, 0, Temp, 0.475 * ScreenHeight);
Render2D.DrawRect(Temp, CaretPos, 0.025 * ScreenHeight, CaretHeight);
Temp := 0.025 * ScreenHeight;
for i := 0 to Min(DisplayLines - 1, FLogCache.Count - FLogPosition - 1) do
begin
if LastChar(FLogCache[FLogPosition + i]) = PostfixError then
gleColor(FColors[clErrorLine])
else if LastChar(FLogCache[FLogPosition + i]) = PostfixWarning then
gleColor(FColors[clWarningLine])
else
gleColor(FColors[clNormalLine]);
Render2D.TextOut(FFont, 0, Temp * i, RemovePostfix(FLogCache[FLogPosition + i]));
end;
gleColor(FColors[clNormalLine]);
Temp := 0.475 * ScreenHeight;
CommandLineStart := Max(FCursor - FLineLength + 1, 0);
Line := '>' + Copy(FCommandLine, CommandLineStart + 1, FLineLength - 1);
Render2D.TextOut(FFont, 0, Temp, Line);
if (Core.Time div 500) mod 2 = 0 then
Render2D.TextOut(FFont, Render2D.TextWidth(FFont, Copy(Line, 1, FCursor - CommandLineStart)), Temp, '_');
gleColor(FColors[clBackground]);
Temp := ScreenWidth - 0.025 * ScreenHeight - 8 * CharWidth;
Render2D.DrawRect(Temp, 0, 8 * CharWidth - 1, 0.025 * ScreenHeight);
gleColor(FColors[clFPS]);
Render2D.TextOut(FFont, Temp, 0, 'FPS: ' + IntToStr(Core.FPS));
glPopMatrix;
Render2D.Leave;
end;
procedure TConsoleInterface.Update;
var
AtEnd: Boolean;
begin
AtEnd := FLogPosition = LogEndPosition;
while (FLineLength > 0) and (Console.Log.Count > FCachedLines) do
AddToCache(Console.Log[FCachedLines]);
if AtEnd then
FLogPosition := LogEndPosition;
if FActive and FBlocking then
Core.InhibitUpdate := true;
end;
procedure TConsoleInterface.OnEvent(var Event: TCoreEvent);
var
List: TStringList;
i: Integer;
S: string;
procedure SetCommandLine(const Cmd: string);
begin
FCommandLine := Cmd;
FCursor := Length(Cmd) + 1;
end;
begin
if FActive and (Event is TMouseEvent) and FBlocking then
FreeAndNil(Event)
else if FActive and (Event is TCharEvent) then
begin
with Event as TCharEvent do
if Chr in [#31..#95, #97..#126, #128..#255] then
begin
Insert(Chr, FCommandLine, FCursor);
Inc(FCursor);
end;
FreeAndNil(Event);
end
else if Event is TKeyEvent then
with Event as TKeyEvent do
begin
if not FActive then
begin
if (EvType = keUp) and (Key = VK_TILDE) then Active := true;
end
else if (EvType = keDown) then
begin
case Key of
VK_PRIOR: FLogPosition := Max(FLogPosition - DisplayLines + 1, 0);
VK_NEXT: FLogPosition := Min(FLogPosition + DisplayLines - 1, LogEndPosition);
VK_LEFT: FCursor := Max(FCursor - 1, 1);
VK_RIGHT: FCursor := Min(FCursor + 1, Length(FCommandLine) + 1);
VK_UP: if Core.KeyPressed[VK_CONTROL]
then FLogPosition := Max(FLogPosition - 1, 0)
else begin
FCmdHistoryIndex := Max(FCmdHistoryIndex - 1, 0);
SetCommandLine(FCmdHistory[FCmdHistoryIndex]);
end;
VK_DOWN: if Core.KeyPressed[VK_CONTROL]
then FLogPosition := Min(FLogPosition + 1, LogEndPosition)
else begin
FCmdHistoryIndex := Min(FCmdHistoryIndex + 1, FCmdHistory.Count - 1);
SetCommandLine(FCmdHistory[FCmdHistoryIndex]);
end;
VK_DELETE: Delete(FCommandLine, FCursor, 1);
VK_BACK: if FCursor > 1 then
begin
Delete(FCommandLine, FCursor - 1, 1);
FCursor := Max(FCursor - 1, 1);
end;
end;
end
else begin
case Key of
VK_TAB: if FCommandLine <> '' then
begin
List := Console.GetCommands(Trim(FCommandLine));
try
if List.Count = 1
then SetCommandLine(List[0] + ' ')
else if List.Count > 1 then
for i := 0 to List.Count - 1 do
Console.WriteLn(' ' + List[i]);
finally
FAN(List);
end;
end;
VK_HOME: if Core.KeyPressed[VK_CONTROL]
then FLogPosition := 0
else FCursor := 1;
VK_END: if Core.KeyPressed[VK_CONTROL]
then FLogPosition := LogEndPosition
else FCursor := Length(FCommandLine) + 1;
VK_INSERT:
begin
S := GetClipboardText;
Insert(S, FCommandLine, FCursor);
Inc(FCursor, Length(S));
end;
VK_ESCAPE: if FLogPosition <> LogEndPosition
then FLogPosition := LogEndPosition
else SetCommandLine('');
VK_RETURN:
begin
Console.WriteLn('>' + FCommandLine);
if FCommandLine <> '' then
begin
FCmdHistory.Add(FCommandLine);
if FCmdHistory.Count > 32 then FCmdHistory.Delete(0);
FCmdHistoryIndex := FCmdHistory.Count;
Console.Execute(FCommandLine);
SetCommandLine('');
end;
end;
VK_TILDE: if not Core.KeyPressed[VK_SHIFT] then Active := false;
end;
end;
if FActive then
FreeAndNil(Event);
end
else inherited;
end;
procedure TConsoleInterface.SetActive(Value: Boolean);
begin
FActive := Value;
if FActive then
begin
if FCursor = 0 then
begin
UpdateFont(Render2D.VSBounds.Bottom - Render2D.VSBounds.Top);
Console.WriteLn('Print "help" for help' + PostfixWarning);
end;
FLogPosition := LogEndPosition;
FCommandLine:='';
FCursor:=1;
FCmdHistoryIndex := FCmdHistory.Count;
end;
end;
procedure TConsoleInterface.SetColors(const Colors: TConsoleColorSet);
var
i: TConsoleColors;
begin
for i := Low(TConsoleColors) to High(TConsoleColors) do
FColors[i] := DefColors[i];
end;
procedure TConsoleInterface.SetFont(const Name: string; Bold: Boolean);
begin
FFontName := Name;
FFontBold := Bold;
UpdateFont(FScreenHeight, true);
end;
procedure TConsoleInterface.AddToCache(const Line: string);
var
Pos: Integer;
Postfix: Char;
function AddPostfix(const S: string): string;
begin
if (Postfix = ' ') or (LastChar(S) = Postfix)
then Result := S
else Result := S + Postfix;
end;
begin
if FLineLength = 0 then Exit;
if Line <> '' then
begin
Pos := 1;
Postfix := LastChar(Line);
if not (Postfix in [PostfixWarning, PostfixError]) then Postfix := ' ';
while Pos <= Length(Line) do
begin
FLogCache.Add(AddPostfix(Copy(Line, Pos, FLineLength)));
Inc(Pos, FLineLength);
end;
end
else FLogCache.Add('');
Inc(FCachedLines);
end;
function TConsoleInterface.LogEndPosition: Integer;
begin
Result := Max(FLogCache.Count - DisplayLines, 0);
end;
procedure TConsoleInterface.UpdateFont(ScreenHeight: Single; Force: Boolean);
begin
if (ScreenHeight > 0) and (Force or (FScreenHeight <> ScreenHeight)) then
begin
FFont := Render2D.CreateFont(FFontName, Round(10 * ScreenHeight / 600), FFontBold);
FScreenHeight := ScreenHeight;
end;
end;
function TConsoleInterface.ConColorHandler(Sender: TObject; Args: array of const): Boolean;
begin
Result := true;
if Length(Args) = 1 then
Console.WriteLn('Colors: ' + ConColors)
else if Length(Args) = 2 then
Console.WriteLn('$' + IntToHex(FColors[TConsoleColors(Args[1].VInteger)], 8))
else
FColors[TConsoleColors(Args[1].VInteger)] := Args[2].VInteger;
end;
function TConsoleInterface.ConFontHandler(Sender: TObject; Args: array of const): Boolean;
begin
Result := true;
FFontName := string(Args[1].VAnsiString);
if Length(Args) = 3 then
FFontBold := Boolean(Args[2].VInteger);
UpdateFont(FScreenHeight, true);
end;
function TConsoleInterface.HelpHandler(Sender: TObject; Args: array of const): Boolean;
begin
with Console do
begin
WriteLn;
WriteLn('Use command "cmdlist [prefix]" to get commands list');
WriteLn('Use PageUp, PageDown, Ctrl+Up, Ctrl+Down, Ctrl+Home, Ctrl+End, Escape to navigate console log');
WriteLn('Use Up/Down to navigate commands history');
WriteLn('Press Tab to autocomplete command');
WriteLn('Press Insert to paste from clipboard');
WriteLn('Press Escape to clear command line');
end;
Result := true;
end;
initialization
RegisterModule(TConsoleInterface);
end. |
unit ULocalBackupAutoSync;
interface
uses classes, SysUtils, DateUtils;
type
// 等待线程
TLocalAutoSyncThread = class( TThread )
public
constructor Create;
destructor Destroy; override;
protected
procedure Execute; override;
private
procedure CheckAutoSync;
end;
// 本地备份 自动同步器
TMyLocalAutoSyncHandler = class
public
LocalAutoSyncThread : TLocalAutoSyncThread;
public
constructor Create;
procedure StopThread;
end;
var
MyLocalAutoSyncHandler : TMyLocalAutoSyncHandler;
implementation
uses ULocalBackupInfo, ULocalBackupControl;
{ TLocalAutoSyncThread }
constructor TLocalAutoSyncThread.Create;
begin
inherited Create( True );
end;
destructor TLocalAutoSyncThread.Destroy;
begin
Terminate;
Resume;
WaitFor;
inherited;
end;
procedure TLocalAutoSyncThread.Execute;
var
StartTime : TDateTime;
begin
while not Terminated do
begin
StartTime := Now;
while not Terminated and ( MinutesBetween( Now, StartTime ) < 1 ) do
Sleep(100);
if Terminated then
Break;
CheckAutoSync;
end;
inherited;
end;
procedure TLocalAutoSyncThread.CheckAutoSync;
var
SyncPathList : TStringList;
i : Integer;
LocalBackupSourceRefreshNextSyncTimeHandle : TLocalBackupSourceRefreshNextSyncTimeHandle;
begin
// 同步自动同步的文件
SyncPathList := MyLocalBackupSourceReadUtil.getAutoSyncPathList;
for i := 0 to SyncPathList.Count - 1 do
MyLocalBackupSourceControl.SyncTimeBackup( SyncPathList[i] );
SyncPathList.Free;
// 刷新下一次同步时间
LocalBackupSourceRefreshNextSyncTimeHandle := TLocalBackupSourceRefreshNextSyncTimeHandle.Create;
LocalBackupSourceRefreshNextSyncTimeHandle.Update;
LocalBackupSourceRefreshNextSyncTimeHandle.Free
end;
{ TMyLocalAutoSyncHandler }
constructor TMyLocalAutoSyncHandler.Create;
begin
LocalAutoSyncThread := TLocalAutoSyncThread.Create;
LocalAutoSyncThread.Resume;
end;
procedure TMyLocalAutoSyncHandler.StopThread;
begin
LocalAutoSyncThread.Free;
end;
end.
|
unit TestuOrderValidator;
interface
uses
TestFramework,
uOrderInterfaces;
type
TestTOrderValidator = class(TTestCase)
public
procedure SetUp; override;
published
procedure TestOrderValidatorIsMock_ServiceLocator_TOrderValidatorMockServiceName();
procedure TestOrderValidatorIsRegular_ServiceLocator();
procedure TestValidateOrder;
end;
implementation
uses
uOrder,
Spring.Services,
Spring.Container,
uSpringTestCaseHelper,
uOrderValidatorMock,
uRegisterMocks;
const
SOrderValidator = 'OrderValidator';
procedure TestTOrderValidator.SetUp;
begin
GlobalContainer.Build();
end;
procedure TestTOrderValidator.TestOrderValidatorIsMock_ServiceLocator_TOrderValidatorMockServiceName();
var
OrderValidator: IOrderValidator;
begin
// Retrieving the instances with the unique service names gives back the Mock classes:
OrderValidator := ServiceLocator.GetService<IOrderValidator>(RegisterMocks.TOrderValidatorMockServiceName);
TestInterfaceImplementedByClass(OrderValidator, TOrderValidatorMock, SOrderValidator);
end;
procedure TestTOrderValidator.TestOrderValidatorIsRegular_ServiceLocator();
var
OrderValidator: IOrderValidator;
begin
// Note that going through the ServiceLocator without the names will give you the regular implementations,
// which you want for the normal business code still to work:
OrderValidator := ServiceLocator.GetService<IOrderValidator>();
TestInterfaceNotImplementedByClass(OrderValidator, TOrderValidatorMock, SOrderValidator);
end;
procedure TestTOrderValidator.TestValidateOrder;
var
Order: TOrder;
OrderValidator: IOrderValidator;
ReturnValue: Boolean;
begin
Order := TOrder.Create();
try
OrderValidator := ServiceLocator.GetService<IOrderValidator>();
ReturnValue := OrderValidator.ValidateOrder(Order);
Check(ReturnValue);
finally
Order.Free;
end;
end;
initialization
RegisterTest(TestTOrderValidator.Suite);
end.
|
unit uFormRenderFMX;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.StdCtrls;
type
TFormRenderFMX = class(TForm)
btnRender: TButton;
LabelTime: TLabel;
ToolBar1: TToolBar;
Image1: TImage;
TrackBarAntiAliasingLevel: TTrackBar;
LabelAntiAliasing: TLabel;
procedure btnRenderClick(Sender: TObject);
procedure TrackBarAntiAliasingLevelChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormRenderFMX: TFormRenderFMX;
implementation
uses
uRendererFMX, System.Diagnostics;
{$R *.fmx}
procedure TFormRenderFMX.btnRenderClick(Sender: TObject);
var sw: TStopwatch; r: TRendererFMX; bmp: TBitmap;
begin
LabelTime.Text := 'Rendering... Please wait.';
self.Invalidate;
Application.ProcessMessages;
sw := TStopwatch.StartNew;
r := TRendererFMX.Create(round(Image1.Width), round(Image1.Height), round(TrackBarAntiAliasingLevel.Value));
bmp := r.DoRender;
Image1.Bitmap.Assign(bmp);
sw.Stop;
LabelTime.Text := IntToStr(sw.ElapsedMilliseconds) + ' msec ('
+ IntToStr(sw.ElapsedTicks) + ' ticks)';
end;
procedure TFormRenderFMX.FormCreate(Sender: TObject);
begin
TrackBarAntiAliasingLevelChange(self);
end;
procedure TFormRenderFMX.TrackBarAntiAliasingLevelChange(Sender: TObject);
begin
LabelAntiAliasing.Text := 'Anti-Aliasing Level: ' + TrackBarAntiAliasingLevel.Value.ToString;
end;
end.
|
(*
* Copyright (c) 2009-2010, Ciobanu Alexandru
* 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 the <organization> 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 AUTHOR ''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 AUTHOR 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.
*)
{$I ../DeHL.Defines.inc}
unit DeHL.Collections.Heap;
interface
uses SysUtils,
DeHL.Base,
DeHL.Types,
DeHL.Exceptions,
DeHL.Arrays,
DeHL.Collections.Base;
type
/// <summary>The generic <c>heap</c> collection.</summary>
/// <remarks>This type is used to store its values in non-indexed fashion.</remarks>
THeap<T> = class(TEnexCollection<T>, IDynamic)
private type
{$REGION 'Internal Types'}
{ Internal type to store heap entries }
TEntry = record
FNext: NativeInt;
FValue: T;
end;
{ Array of internal entries }
TEntryArray = TArray<TEntry>;
{ Heap Enumerator }
TEnumerator = class(TEnumerator<T>)
private
FVer: NativeUInt;
FHeap: THeap<T>;
FCurrentIndex: NativeUInt;
FCurrent: T;
public
{ Constructor }
constructor Create(const AHeap: THeap<T>);
{ Destructor }
destructor Destroy(); override;
function GetCurrent(): T; override;
function MoveNext(): Boolean; override;
end;
{$ENDREGION}
private var
FArray: TEntryArray;
FFirstFree: NativeInt;
FCount: NativeUInt;
FVer: NativeUInt;
{ Setters and getters }
function GetItem(const AId: NativeUInt): T;
procedure SetItem(const AId: NativeUInt; const Value: T);
protected
/// <summary>Returns the number of elements in the heap.</summary>
/// <returns>A positive value specifying the number of elements in the heap.</returns>
function GetCount(): NativeUInt; override;
/// <summary>Returns the current capacity.</summary>
/// <returns>A positive number that specifies the number of elements that the heap can hold before it
/// needs to grow again.</returns>
/// <remarks>The value of this method is greater or equal to the amount of elements in the heap. If this value
/// is greater then the number of elements, it means that the heap has some extra capacity to operate upon.</remarks>
function GetCapacity(): NativeUInt;
public
/// <summary>Creates a new instance of this class.</summary>
/// <remarks>The default type object is requested.</remarks>
constructor Create(); overload;
/// <summary>Creates a new instance of this class.</summary>
/// <param name="AInitialCapacity">The heap's initial capacity.</param>
/// <remarks>The default type object is requested.</remarks>
constructor Create(const AInitialCapacity: NativeUInt); overload;
/// <summary>Creates a new instance of this class.</summary>
/// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception>
constructor Create(const AType: IType<T>); overload;
/// <summary>Creates a new instance of this class.</summary>
/// <param name="AInitialCapacity">The heap's initial capacity.</param>
/// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception>
constructor Create(const AType: IType<T>; const AInitialCapacity: NativeUInt); overload;
/// <summary>Destroys this instance.</summary>
/// <remarks>Do not call this method directly, call <c>Free</c> instead.</remarks>
destructor Destroy(); override;
/// <summary>Clears the contents of the heap.</summary>
/// <remarks>This method clears the heap and invokes type object's cleaning routines for each element.</remarks>
procedure Clear();
/// <summary>Adds an element to the heap.</summary>
/// <param name="AValue">The value to add.</param>
/// <returns>A number that uniquely identifies the element in the heap. This number should not be considered an index.</returns>
function Add(const AValue: T): NativeUInt;
/// <summary>Removes the item from the heap.</summary>
/// <param name="AId">The ID of item.</param>
/// <returns>The value identified by the ID.</returns>
/// <exception cref="DeHL.Exceptions|EKeyNotFoundException"><paramref name="AId"/> is not a valid id for this heap.</exception>
function Extract(const AId: NativeUInt): T;
/// <summary>Removes the item from the heap.</summary>
/// <param name="AId">The ID of item.</param>
/// <exception cref="DeHL.Exceptions|EKeyNotFoundException"><paramref name="AId"/> is not a valid id for this heap.</exception>
/// <remarks>This method invokes type object's cleaning routines for the removed value.</remarks>
procedure Remove(const AId: NativeUInt);
/// <summary>Checks whether the heap contains a given ID.</summary>
/// <param name="AId">The ID to check.</param>
/// <returns><c>True</c> if the ID was issues by this heap and is valid; <c>False</c> otherwise.</returns>
function Contains(const AId: NativeUInt): Boolean;
/// <summary>Tries to obtain the value associated with a given ID.</summary>
/// <param name="AId">The ID for which to try to retreive the value.</param>
/// <param name="AFoundValue">The found value (if the result is <c>True</c>).</param>
/// <returns><c>True</c> if the heap contains a value for the given ID; <c>False</c> otherwise.</returns>
function TryGetValue(const AId: NativeUInt; out AFoundValue: T): Boolean;
/// <summary>Specifies the number of elements in the heap.</summary>
/// <returns>A positive value specifying the number of elements in the heap.</returns>
property Count: NativeUInt read FCount;
/// <summary>Specifies the current capacity.</summary>
/// <returns>A positive number that specifies the number of elements that the heap can hold before it
/// needs to grow again.</returns>
/// <remarks>The value of this property is greater or equal to the amount of elements in the heap. If this value
/// if greater then the number of elements, it means that the heap has some extra capacity to operate upon.</remarks>
property Capacity: NativeUInt read GetCapacity;
/// <summary>Returns the item from associated with a given ID.</summary>
/// <param name="AId">The ID of the value.</param>
/// <returns>The element associated with the specified ID.</returns>
/// <exception cref="DeHL.Exceptions|EKeyNotFoundException"><paramref name="AId"/> is not a valid ID for this heap.</exception>
property Items[const AId: NativeUInt]: T read GetItem write SetItem; default;
/// <summary>Removes the excess capacity from the heap.</summary>
/// <remarks>This method can be called manually to force the heap to drop the extra capacity it might hold. For example,
/// after performing some massive operations of a big heap, call this method to ensure that all extra memory held by the
/// heap is released.</remarks>
procedure Shrink();
/// <summary>Forces the heap to increase its capacity.</summary>
/// <remarks>Call this method to force the heap to increase its capacity ahead of time. Manually adjusting the capacity
/// can be useful in certain situations.</remarks>
procedure Grow();
/// <summary>Returns a new enumerator object used to enumerate this heap.</summary>
/// <remarks>This method is usually called by compiler generated code. Its purpose is to create an enumerator
/// object that is used to actually traverse the heap.</remarks>
/// <returns>An enumerator object.</returns>
function GetEnumerator(): IEnumerator<T>; override;
/// <summary>Copies the values stored in the heap to a given array.</summary>
/// <param name="AArray">An array where to copy the contents of the heap.</param>
/// <param name="AStartIndex">The index into the array at which the copying begins.</param>
/// <remarks>This method assumes that <paramref name="AArray"/> has enough space to hold the contents of the heap.</remarks>
/// <exception cref="DeHL.Exceptions|EArgumentOutOfRangeException"><paramref name="AStartIndex"/> is out of bounds.</exception>
/// <exception cref="DeHL.Exceptions|EArgumentOutOfSpaceException">There array is not long enough.</exception>
procedure CopyTo(var AArray: array of T; const AStartIndex: NativeUInt); overload; override;
/// <summary>Checks whether the heap is empty.</summary>
/// <returns><c>True</c> if the heap is empty; <c>False</c> otherwise.</returns>
/// <remarks>This method is the recommended way of detecting if the heap is empty.</remarks>
function Empty(): Boolean; override;
end;
/// <summary>The generic <c>heap</c> collection designed to store objects..</summary>
/// <remarks>This type is used to store its objects in non-indexed fashion.</remarks>
TObjectHeap<T: class> = class(THeap<T>)
private
FWrapperType: TObjectWrapperType<T>;
{ Getters/Setters for OwnsObjects }
function GetOwnsObjects: Boolean;
procedure SetOwnsObjects(const Value: Boolean);
protected
/// <summary>Installs the type object.</summary>
/// <param name="AType">The type object to install.</param>
/// <remarks>This method installs a custom wrapper designed to suppress the cleanup of objects on request.
/// Make sure to call this method in descendant classes.</remarks>
/// <exception cref="DeHL.Exceptions|ENilArgumentException"><paramref name="AType"/> is <c>nil</c>.</exception>
procedure InstallType(const AType: IType<T>); override;
public
/// <summary>Specifies whether this heap owns the objects stored in it.</summary>
/// <returns><c>True</c> if the heap owns its objects; <c>False</c> otherwise.</returns>
/// <remarks>This property controls the way the heap controls the life-time of the stored objects.</remarks>
property OwnsObjects: Boolean read GetOwnsObjects write SetOwnsObjects;
end;
implementation
const
DefaultArrayLength = 32;
{ THeap<T> }
function THeap<T>.Add(const AValue: T): NativeUInt;
begin
{ Grow if required }
if FCount = NativeUInt(Length(FArray)) then
Grow();
{ Adjust the free list }
Result := FFirstFree;
FFirstFree := FArray[FFirstFree].FNext;
{ Actually store the value }
FArray[Result].FNext := -1;
FArray[Result].FValue := AValue;
Inc(FVer);
Inc(FCount);
end;
procedure THeap<T>.Clear;
var
CV: Boolean;
I: NativeInt;
begin
CV := (ElementType <> nil) and (ElementType.Management = tmManual);
for I := 0 to Length(FArray) - 1 do
begin
if CV and (FArray[I].FNext = -1) then
ElementType.Cleanup(FArray[I].FValue);
{ Adjust the next free list indices }
FArray[I].FNext := I + 1;
end;
{ The first free one starts at zero }
FFirstFree := 0;
Inc(FVer);
FCount := 0;
end;
function THeap<T>.Contains(const AId: NativeUInt): Boolean;
begin
{ Check the ID }
Result := (AId < NativeUInt(Length(FArray))) and (FArray[AId].FNext = -1);
end;
procedure THeap<T>.CopyTo(var AArray: array of T; const AStartIndex: NativeUInt);
var
I, X: NativeUInt;
begin
{ Check for indexes }
if AStartIndex >= NativeUInt(Length(AArray)) then
ExceptionHelper.Throw_ArgumentOutOfRangeError('AStartIndex');
if (NativeUInt(Length(AArray)) - AStartIndex) < FCount then
ExceptionHelper.Throw_ArgumentOutOfSpaceError('AArray');
{ Copy all good values to the array }
X := AStartIndex;
{ Iterate over the internal array and add what is good }
for I := 0 to Length(FArray) - 1 do
if FArray[I].FNext = -1 then
begin
AArray[X] := FArray[I].FValue;
Inc(X);
end;
end;
constructor THeap<T>.Create;
begin
Create(TType<T>.Default, DefaultArrayLength);
end;
constructor THeap<T>.Create(const AInitialCapacity: NativeUInt);
begin
Create(TType<T>.Default, AInitialCapacity);
end;
constructor THeap<T>.Create(const AType: IType<T>);
begin
Create(AType, DefaultArrayLength);
end;
constructor THeap<T>.Create(const AType: IType<T>; const AInitialCapacity: NativeUInt);
var
I: NativeUInt;
begin
{ Initialize instance }
if (AType = nil) then
ExceptionHelper.Throw_ArgumentNilError('AType');
InstallType(AType);
FCount := 0;
FVer := 0;
SetLength(FArray, AInitialCapacity);
{ Add all new entries to the free list }
for I := 0 to AInitialCapacity - 1 do
FArray[I].FNext := I + 1;
FFirstFree := 0;
end;
destructor THeap<T>.Destroy;
begin
{ First, clear myself }
Clear();
inherited;
end;
function THeap<T>.Empty: Boolean;
begin
{ Ha! }
Result := (FCount = 0);
end;
function THeap<T>.Extract(const AId: NativeUInt): T;
begin
{ Check the ID }
if (AId >= NativeUInt(Length(FArray))) or (FArray[AId].FNext <> -1) then
ExceptionHelper.Throw_KeyNotFoundError('AId');
{ Extract the result }
Result := FArray[AId].FValue;
{ Free this spot for other to use }
FArray[AId].FNext := FFirstFree;
FArray[AId].FValue := default(T);
FFirstFree := AId;
Inc(FVer);
Dec(FCount);
end;
function THeap<T>.GetCapacity: NativeUInt;
begin
Result := Length(FArray);
end;
function THeap<T>.GetCount: NativeUInt;
begin
Result := FCount;
end;
function THeap<T>.GetEnumerator: IEnumerator<T>;
begin
Result := TEnumerator.Create(Self);
end;
function THeap<T>.GetItem(const AId: NativeUInt): T;
begin
{ Check the ID }
if (AId >= NativeUInt(Length(FArray))) or (FArray[AId].FNext <> -1) then
ExceptionHelper.Throw_KeyNotFoundError('AId');
{ Extract the result }
Result := FArray[AId].FValue;
end;
procedure THeap<T>.Grow;
var
LNewLength, LOldLength: NativeUInt;
I: NativeInt;
begin
LOldLength := Capacity;
{ Calculate the new size }
if LOldLength < DefaultArrayLength then
LNewLength := DefaultArrayLength
else
LNewLength := LOldLength * 2;
{ Set the new size }
SetLength(FArray, LNewLength);
{ Add all new entries to the free list }
for I := LOldLength to LNewLength - 2 do
FArray[I].FNext := I + 1;
{ Connect the old free list with the newly added one }
FArray[LNewLength - 1].FNext := FFirstFree;
FFirstFree := LOldLength;
end;
procedure THeap<T>.Remove(const AId: NativeUInt);
var
LValue: T;
begin
{ Obtain the value at position }
LValue := Extract(AId);
{ Cleanup the value if necessary }
if ElementType.Management = tmManual then
ElementType.Cleanup(LValue);
end;
procedure THeap<T>.SetItem(const AId: NativeUInt; const Value: T);
begin
{ Check the ID }
if (AId >= NativeUInt(Length(FArray))) or (FArray[AId].FNext <> -1) then
ExceptionHelper.Throw_KeyNotFoundError('AId');
{ Cleanup the old inhabitant }
if ElementType.Management = tmManual then
ElementType.Cleanup(FArray[AId].FValue);
{ And set the new one }
FArray[AId].FValue := Value;
end;
procedure THeap<T>.Shrink;
var
LLen: NativeInt;
begin
{ Find the last occupied spot }
LLen := Length(FArray);
while (LLen > 0) and (FArray[LLen - 1].FNext <> -1) do Dec(LLen);
{ Readjust the array length }
SetLength(FArray, LLen);
end;
function THeap<T>.TryGetValue(const AId: NativeUInt; out AFoundValue: T): Boolean;
begin
{ Check the ID }
if (AId >= NativeUInt(Length(FArray))) or (FArray[AId].FNext <> -1) then
Exit(false);
{ Extract the result }
AFoundValue := FArray[AId].FValue;
Result := true;
end;
{ THeap<T>.TEnumerator }
constructor THeap<T>.TEnumerator.Create(const AHeap: THeap<T>);
begin
FHeap := AHeap;
FVer := AHeap.FVer;
FCurrent := default(T);
FCurrentIndex := 0;
KeepObjectAlive(FHeap);
end;
destructor THeap<T>.TEnumerator.Destroy;
begin
ReleaseObject(FHeap);
inherited;
end;
function THeap<T>.TEnumerator.GetCurrent: T;
begin
Result := FCurrent;
end;
function THeap<T>.TEnumerator.MoveNext: Boolean;
begin
if FVer <> FHeap.FVer then
ExceptionHelper.Throw_CollectionChangedError();
{ Go over all array and gather what we need }
while FCurrentIndex < NativeUInt(Length(FHeap.FArray)) do
begin
{ If the spot is occupied, take the value and stop }
if FHeap.FArray[FCurrentIndex].FNext = -1 then
begin
FCurrent := FHeap.FArray[FCurrentIndex].FValue;
Inc(FCurrentIndex);
Exit(true);
end else
Inc(FCurrentIndex);
end;
{ All array was walked, nothing found, too bad }
Result := false;
end;
{ TObjectHeap<T> }
function TObjectHeap<T>.GetOwnsObjects: Boolean;
begin
Result := FWrapperType.AllowCleanup;
end;
procedure TObjectHeap<T>.InstallType(const AType: IType<T>);
begin
{ Create a wrapper over the real type class and switch it }
FWrapperType := TObjectWrapperType<T>.Create(AType);
{ Install overridden type }
inherited InstallType(FWrapperType);
end;
procedure TObjectHeap<T>.SetOwnsObjects(const Value: Boolean);
begin
FWrapperType.AllowCleanup := Value;
end;
end.
|
unit CreateUser;
interface
uses
System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CreateObjectDialog, Grids,
JvExGrids, JvStringGrid, BCControls.StringGrid, Vcl.StdCtrls, BCControls.Edit, Vcl.ImgList, SynEditHighlighter,
SynHighlighterSQL, ActnList, ComCtrls, ToolWin, JvExComCtrls, SynEdit, Vcl.ExtCtrls, JvComCtrls,
BCControls.PageControl, DB, MemDS, DBAccess, Ora, BCControls.ToolBar, BCDialogs.Dlg, System.Actions,
BCControls.ImageList, BCControls.CheckBox, JvExStdCtrls, JvCheckBox;
type
TCreateUserDialog = class(TCreateObjectBaseDialog)
PasswordEdit: TBCEdit;
PasswordExpiredCheckBox: TBCCheckBox;
PasswordLabel: TLabel;
RolesPanel: TPanel;
RolesQuery: TOraQuery;
RolesStringGrid: TBCStringGrid;
RolesTabSheet: TTabSheet;
UsernameEdit: TBCEdit;
UsernameLabel: TLabel;
procedure FormDestroy(Sender: TObject);
protected
function CheckFields: Boolean; override;
procedure CreateSQL; override;
procedure Initialize; override;
end;
function CreateUserDialog: TCreateUserDialog;
implementation
{$R *.dfm}
uses
System.Math, BCCommon.StyleUtils, BCCommon.Messages, BCCommon.Lib;
const
CELL_PADDING = 4;
var
FCreateUserDialog: TCreateUserDialog;
function CreateUserDialog: TCreateUserDialog;
begin
if not Assigned(FCreateUserDialog) then
Application.CreateForm(TCreateUserDialog, FCreateUserDialog);
Result := FCreateUserDialog;
SetStyledFormSize(TDialog(Result));
end;
procedure TCreateUserDialog.FormDestroy(Sender: TObject);
begin
inherited;
FCreateUserDialog := nil;
end;
function TCreateUserDialog.CheckFields: Boolean;
begin
Result := False;
if Trim(UsernameEdit.Text) = '' then
begin
ShowErrorMessage('Enter user name.');
Exit;
end;
if Trim(PasswordEdit.Text) = '' then
begin
ShowErrorMessage('Enter password.');
Exit;
end;
Result := True;
end;
procedure TCreateUserDialog.Initialize;
var
i: Integer;
begin
inherited;
UsernameEdit.Text := '';
PasswordEdit.Text := '';
PasswordExpiredCheckBox.Checked := False;
RolesStringGrid.Cells[0, 0] := 'Role';
RolesStringGrid.Cells[1, 0] := 'Granted';
RolesStringGrid.Cells[2, 0] := 'Admin';
with RolesQuery do
begin
//ParamByName('P_OBJECT_NAME').AsString := SchemaParam;
Open;
i := 1; // header & first row
RolesStringGrid.RowCount := RecordCount + 1;
while not Eof do
begin
RolesStringGrid.Cells[0, i] := FieldByName('GRANTED_ROLE').AsString;
RolesStringGrid.Cells[1, i] := 'False';
RolesStringGrid.Cells[2, i] := 'False';
Inc(i);
Next;
end;
Close;
end;
end;
procedure TCreateUserDialog.CreateSQL;
var
i: Integer;
AdminOption, PasswordExpire: string;
begin
try
Screen.Cursor := crHourglass;
SourceSynEdit.Clear;
SourceSynEdit.Lines.BeginUpdate;
PasswordExpire := '';
if PasswordExpiredCheckBox.Checked then
PasswordExpire := ' PASSWORD EXPIRE';
SourceSynEdit.Lines.Text := 'CREATE USER ' + UsernameEdit.Text + ' IDENTIFIED BY "' + PasswordEdit.Text + '"' + PasswordExpire + ';' + CHR_ENTER + CHR_ENTER;
for i := 0 to RolesStringGrid.RowCount - 1 do
begin
if RolesStringGrid.Cells[1, i] = 'True' then
begin
AdminOption := '';
if RolesStringGrid.Cells[2, i] = 'True' then
AdminOption := ' WITH ADMIN OPTION';
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + 'GRANT ' + RolesStringGrid.Cells[0, i] + ' TO ' + UsernameEdit.Text + AdminOption + ';' + CHR_ENTER;
end;
end;
SourceSynEdit.Lines.Text := SourceSynEdit.Lines.Text + 'ALTER USER ' + UsernameEdit.Text + ' DEFAULT ROLE ALL;';
SourceSynEdit.Lines.EndUpdate;
finally
Screen.Cursor := crDefault;
end;
end;
end.
|
unit SheetData;
{
********************************************************************************
******* XLSReadWriteII V1.14 *******
******* *******
******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-} // Boolean short-circuit evaluation off
{$Q-} // Overflow checks off
{$R-} // Range checks off
interface
uses SysUtils, Classes, Windows, Dialogs, BIFFRecsII, XLSUtils, XLSStream,
Cell, EncodeFormulaII, ExcelMaskII, Note, Picture, CellStorage, Graphics,
CellFormats, XLSChart, SST, Validate, Math, XLSRWIIResourceStrings,
RecordStorage, XLSFonts;
type TPaneType = (ptNone,ptFrozen,ptSplit);
type TPrintSetupOption = (psoLeftToRight,psoPortrait,psoNoColor,psoDraftQuality,psoNotes,psoRowColHeading,psoGridlines,psoHorizCenter,psoVertCenter);
type TPrintSetupOptions = set of TPrintSetupOption;
type TPaperSize = (
psNone,
psLetter, { Letter 8 12 x 11 in }
psLetterSmall, { Letter Small 8 12 x 11 in }
psTabloid, { Tabloid 11 x 17 in }
psLedger, { Ledger 17 x 11 in }
psLegal, { Legal 8 12 x 14 in }
psStatement, { Statement 5 12 x 8 12 in }
psExecutive, { Executive 7 14 x 10 12 in }
psA3, { A3 297 x 420 mm }
psA4, { A4 210 x 297 mm }
psA4Small, { A4 Small 210 x 297 mm }
psA5, { A5 148 x 210 mm }
psB4, { B4 (JIS) 250 x 354 }
psB5, { B5 (JIS) 182 x 257 mm }
psFolio, { Folio 8 12 x 13 in }
psQuarto, { Quarto 215 x 275 mm }
ps10X14, { 10x14 in }
ps11X17, { 11x17 in }
psNote, { Note 8 12 x 11 in }
psEnv9, { Envelope #9 3 78 x 8 78 }
psEnv10, { Envelope #10 4 18 x 9 12 }
psEnv11, { Envelope #11 4 12 x 10 38 }
psEnv12, { Envelope #12 4 \276 x 11 }
psEnv14, { Envelope #14 5 x 11 12 }
psCSheet, { C size sheet }
psDSheet, { D size sheet }
psESheet, { E size sheet }
psEnvDL, { Envelope DL 110 x 220mm }
psEnvC5, { Envelope C5 162 x 229 mm }
psEnvC3, { Envelope C3 324 x 458 mm }
psEnvC4, { Envelope C4 229 x 324 mm }
psEnvC6, { Envelope C6 114 x 162 mm }
psEnvC65, { Envelope C65 114 x 229 mm }
psEnvB4, { Envelope B4 250 x 353 mm }
psEnvB5, { Envelope B5 176 x 250 mm }
psEnvB6, { Envelope B6 176 x 125 mm }
psEnvItaly, { Envelope 110 x 230 mm }
psEnvMonarch, { Envelope Monarch 3.875 x 7.5 in }
psEnvPersonal, { 6 34 Envelope 3 58 x 6 12 in }
psFanfoldUS, { US Std Fanfold 14 78 x 11 in }
psFanfoldStdGerman, { German Std Fanfold 8 12 x 12 in }
psFanfoldLglGerman, { German Legal Fanfold 8 12 x 13 in }
psISO_B4, { B4 (ISO) 250 x 353 mm }
psJapanesePostcard, { Japanese Postcard 100 x 148 mm }
ps9X11, { 9 x 11 in }
ps10X11, { 10 x 11 in }
ps15X11, { 15 x 11 in }
psEnvInvite, { Envelope Invite 220 x 220 mm }
psReserved48, { RESERVED--DO NOT USE }
psReserved49, { RESERVED--DO NOT USE }
psLetterExtra, { Letter Extra 9 \275 x 12 in }
psLegalExtra, { Legal Extra 9 \275 x 15 in }
psTabloidExtra, { Tabloid Extra 11.69 x 18 in }
psA4Extra, { A4 Extra 9.27 x 12.69 in }
psLetterTransverse, { Letter Transverse 8 \275 x 11 in }
psA4Transverse, { A4 Transverse 210 x 297 mm }
psLetterExtraTransverse, { Letter Extra Transverse 9\275 x 12 in }
psAPlus, { SuperASuperAA4 227 x 356 mm }
psBPlus, { SuperBSuperBA3 305 x 487 mm }
psLetterPlus, { Letter Plus 8.5 x 12.69 in }
psA4Plus, { A4 Plus 210 x 330 mm }
psA5Transverse, { A5 Transverse 148 x 210 mm }
psB5transverse, { B5 (JIS) Transverse 182 x 257 mm }
psA3Extra, { A3 Extra 322 x 445 mm }
psA5Extra, { A5 Extra 174 x 235 mm }
psB5Extra, { B5 (ISO) Extra 201 x 276 mm }
psA2, { A2 420 x 594 mm }
psA3Transverse, { A3 Transverse 297 x 420 mm }
psA3ExtraTransverse { A3 Extra Transverse 322 x 445 mm }
);
type TSheet = class;
PRowData = ^TRowData;
TRowData = record
Row: word;
Col1,Col2: word;
Height: word;
Options: word;
FormatIndex: word;
end;
THorizPagebreak = class(TCollectionItem)
private
FRow: integer;
FCol1,FCol2: integer;
public
constructor Create(Collection: TCollection); override;
published
property Row: integer read FRow write FRow;
property Col1: integer read FCol1 write FCol1;
property Col2: integer read FCol2 write FCol2;
end;
THorizPagebreaks = class(TCollection)
private
FOwner: TPersistent;
function GetItem(Index: integer): THorizPagebreak;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent);
function Add: THorizPagebreak;
property Items[Index: integer]: THorizPagebreak read GetItem; default;
end;
TVertPagebreak = class(TCollectionItem)
private
FCol: integer;
FRow1,FRow2: integer;
public
constructor Create(Collection: TCollection); override;
published
property Col: integer read FCol write FCol;
property Row1: integer read FRow1 write FRow1;
property Row2: integer read FRow2 write FRow2;
end;
TVertPagebreaks = class(TCollection)
private
FOwner: TPersistent;
function GetItem(Index: integer): TVertPagebreak;
protected
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent);
function Add: TVertPagebreak;
property Items[Index: integer]: TVertPagebreak read GetItem; default;
end;
TPrintSettings = class(TPersistent)
private
FParent: TSheet;
FScalingFactor: word;
FStartingPage: word;
FOptions: TPrintSetupOptions;
FHeaderMargin: double;
FFooterMargin: double;
FCopies: word;
FMarginLeft,FMarginRight,FMarginTop,FMarginBottom: double;
FHeader,FFooter: string;
FRow1OnEachPage: integer;
FRow2OnEachPage: integer;
FCol1OnEachPage: integer;
FCol2OnEachPage: integer;
FHorizPagebreaks: THorizPagebreaks;
FVertPagebreaks: TVertPagebreaks;
FPaperSize: TPaperSize;
FResolution: integer;
procedure SetHeader(Value: string);
procedure SetFooter(Value: string);
procedure SetRowsOnEachPage(const Value: string);
procedure SetColsOnEachPage(const Value: string);
function StrToRange(S: string; var Value1,Value2: integer): boolean;
function GetColsOnEachPage: string;
function GetRowsOnEachPage: string;
protected
function GetOwner: TPersistent; override;
public
constructor Create(Parent: TSheet);
destructor Destroy; override;
procedure Clear;
published
property Copies: word read FCopies write FCopies;
property Footer: string read FFooter write SetFooter;
property FooterMargin: double read FFooterMargin write FFooterMargin;
property Header: string read FHeader write SetHeader;
property HeaderMargin: double read FHeaderMargin write FHeaderMargin;
property MarginBottom: double read FMarginBottom write FMarginBottom;
property MarginLeft: double read FMarginLeft write FMarginLeft;
property MarginRight: double read FMarginRight write FMarginRight;
property MarginTop: double read FMarginTop write FMarginTop;
property Options: TPrintSetupOptions read FOptions write FOptions;
property PaperSize: TPaperSize read FPaperSize write FPaperSize;
property ScalingFactor: word read FScalingFactor write FScalingFactor;
property StartingPage: word read FStartingPage write FStartingPage;
property RowsOnEachPage: string read GetRowsOnEachPage write SetRowsOnEachPage;
property ColsOnEachPage: string read GetColsOnEachPage write SetColsOnEachPage;
property HorizPagebreaks: THorizPagebreaks read FHorizPagebreaks write FHorizPagebreaks;
property VertPagebreaks: TVertPagebreaks read FVertPagebreaks write FVertPagebreaks;
property Resolution: integer read FResolution write FResolution;
end;
TPane = class(TPersistent)
private
FPaneType: TPaneType;
FSplitColX: integer;
FSplitRowY: integer;
FLeftCol: integer;
FTopRow: integer;
FActivePane: byte;
public
procedure Clear;
property ActivePane: byte read FActivePane write FActivePane;
published
property PaneType: TPaneType read FPaneType write FPaneType;
property SplitColX: integer read FSplitColX write FSplitColX;
property SplitRowY: integer read FSplitRowY write FSplitRowY;
property LeftCol: integer read FLeftCol write FLeftCol;
property TopRow: integer read FTopRow write FTopRow;
end;
TMergedCell = class(TCollectionItem)
private
FCol1,FRow1,FCol2,FRow2: integer;
protected
function GetDisplayName: string; override;
function GetValid: boolean;
public
function AsRect: TRect;
procedure Assign(Source: TPersistent); override;
published
property Col1: integer read FCol1 write FCol1;
property Row1: integer read FRow1 write FRow1;
property Col2: integer read FCol2 write FCol2;
property Row2: integer read FRow2 write FRow2;
property Valid: boolean read GetValid;
end;
TMergedCells = class(TCollection)
private
function GetItem(Index: integer): TMergedCell;
protected
FOwner: TPersistent;
function GetOwner: TPersistent; override;
public
constructor Create(AOwner: TPersistent);
function Add: TMergedCell;
function IsInMerged(Col,Row: integer): integer;
property Items[Index: integer]: TMergedCell read GetItem; default;
end;
TCellData = packed record
Row: word;
Col: byte;
FormatIndex: word;
case CellType: TCellType of
ctBoolean: (vBoolean : boolean);
ctError: (vError : TCellError);
ctString: (vStrIndex : integer);
end;
TCellDataNum = packed record
Row: word;
Col: byte;
FormatIndex: word;
Value: double;
end;
TCellDataFormula = packed record
Row: word;
Col: byte;
FormatIndex: word;
Formula: Pointer;
FormulaSize: word;
case CellType: TCellType of
ctFloat: (vNumber : double);
ctBoolean: (vBoolean : boolean);
ctError: (vError : integer);
ctString: (vString : PChar);
end;
TCellDataArray = array[0..(MAXINT div SizeOf(TCellData) - 1)] of TCellData;
PCellDataArray = ^TCellDataArray;
TCellDataNumArray = array[0..(MAXINT div SizeOf(TCellDataNum) - 1)] of TCellDataNum;
PCellDataNumArray = ^TCellDataNumArray;
TCellDataFormulaArray = array[0..(MAXINT div SizeOf(TCellDataFormula) - 1)] of TCellDataFormula;
PCellDataFormulaArray = ^TCellDataFormulaArray;
TSheetOption = (soGridlines,soRowColHeadings,soProtected,soR1C1Mode,soIteration,soShowFormulas,soFrozenPanes,soShowZeros);
TSheetOptions = set of TSheetOption;
TWorkspaceOption = (woShowAutoBreaks,woApplyStyles,woRowSumsBelow,woColSumsRight,woFitToPage,woOutlineSymbols);
TWorkspaceOptions = set of TWorkspaceOption;
TSheets = class;
TSheet = class(TCollectionItem)
private
FName: string;
FCells: TCellStorage;
FPrintSettings: TPrintSettings;
FDefaultColWidth: word;
FDefaultRowHeight: word;
FMergedCells: TMergedCells;
FOptions: TSheetOptions;
FWorkspaceOptions: TWorkspaceOptions;
FCalcCount: word;
FRecalcFormulas: boolean;
FDelta: double;
FZoom: word;
FZoomPreview: word;
FFirstCol: word;
FLastCol: word;
FFirstRow: word;
FLastRow: word;
FBOUNDSHEETFilePos: integer;
FHyperlinks: TStringList;
FSheetPictures: TSheetPictures;
FNotes: TNotes;
FColumnFormats: TColumnFormats;
FCharts: TXLSCharts;
FFileCharts: TXLSInFileCharts;
FFixedRows: word;
FFixedCols: byte;
FValidations: TDataValidations;
FRows: TList;
FPane: TPane;
// Less used data.
FGridset: integer;
FRowGutter: integer;
FColGutter: integer;
FRowOutlineGutter: integer;
FColOutlineGutter: integer;
function GetAsBoolFormulaValue(Col, Row: integer): boolean;
function GetAsNumFormulaValue(Col, Row: integer): double;
function GetAsStrFormulaValue(Col, Row: integer): string;
procedure SetAsBoolFormulaValue(Col, Row: integer; const Value: boolean);
procedure SetAsNumFormulaValue(Col, Row: integer; const Value: double);
procedure SetAsStrFormulaValue(Col, Row: integer; const Value: string);
function GetHyperlink(Col, Row: integer): string;
function GetRowHeight(Index: integer): integer;
procedure SetRowHeight(Index,Value: integer);
function GetAsHTML(Col, Row: integer): string;
function GetWideName: WideString;
procedure SetWideName(const Value: WideString);
protected
procedure SetName(Value: string);
function GetName: string;
function GetDisplayName: string; override;
procedure WriteBuf(Stream: TXLSStream; RecId,Size: word; P: Pointer);
procedure CheckFirstLast(ACol,ARow: integer);
function GetDefaultWriteFormat(Version: TExcelVersion; FormatIndex: integer): word;
function GetCell(Col, Row: integer): TCell;
function GetAsBlank(Col, Row: integer): boolean;
procedure SetAsBlank(Col, Row: integer; const Value: boolean);
function GetAsInteger(Col, Row: integer): integer;
procedure SetAsInteger(Col, Row: integer; const Value: integer);
function GetAsBoolean(Col, Row: integer): boolean;
function GetAsError(Col, Row: integer): TCellError;
procedure SetAsError(Col, Row: integer; Value: TCellError);
function GetAsFloat(Col, Row: integer): double;
function GetAsFormula(Col, Row: integer): string;
function GetAsString(Col, Row: integer): string;
function GetAsWideString(Col, Row: integer): WideString;
function GetFmtAsString(Col, Row: integer): string;
procedure SetAsBoolean(Col, Row: integer; const Value: boolean);
procedure SetAsFloat(Col, Row: integer; const Value: double);
procedure SetAsFormula(Col, Row: integer; const Value: string);
procedure SetAsString(Col, Row: integer; const Value: string);
procedure SetAsWideString(Col, Row: integer; const Value: WideString);
function GetCellType(Col, Row: integer): TCellType;
function EncodeFormula(F: string; CellType: TCellType; RC,FI: integer): TFormulaCell;
function MakeFormulaCell(CellType: TCellType; Data: PByteArray; Size,RC,FI: integer): TFormulaCell;
function GetCellAlignment(Cell: TCell; Format: TCellFormat): TCellHorizAlignment;
function GetDefaultFormat(Col,Row: integer): integer;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure ClearData;
procedure NameWideString(S: WideString);
procedure WriteBlank (Col,Row,FormatIndex: integer);
procedure WriteBoolean (Col,Row,FormatIndex: integer; Value: boolean);
procedure WriteError (Col,Row,FormatIndex: integer; Value: TCellError);
procedure WriteNumber (Col,Row,FormatIndex: integer; Value: double);
procedure WriteNumFormula (Col,Row,FormatIndex: integer; Formula: string; Value: double);
procedure WriteStrFormula (Col,Row,FormatIndex: integer; Formula: string; Value: string);
procedure WriteBoolFormula (Col,Row,FormatIndex: integer; Formula: string; Value: boolean);
procedure WriteErrorFormula (Col,Row,FormatIndex: integer; Formula: string; Value: TCellError);
procedure WriteString (Col,Row,FormatIndex: integer; Value: string);
procedure WriteWideString (Col,Row,FormatIndex: integer; Value: string);
procedure WriteHyperlink (Col,Row,FormatIndex: integer; Text,Link: string);
procedure WriteStringArray (Col,Row,FormatIndex: integer; Vertical: boolean; Value: array of string);
procedure WriteWideStringArray(Col,Row,FormatIndex: integer; Vertical: boolean; Value: array of string);
// **********************************************
// *********** For internal use only. ***********
// **********************************************
procedure WriteSSTString (Col,Row,FormatIndex: integer; Value: string);
procedure WriteSSTWideString (Col,Row,FormatIndex: integer; Value: WideString);
procedure WriteSSTStringIndex (Col,Row,FormatIndex: integer; Value: integer);
procedure WriteRawNumFormula (Col,Row,FormatIndex: integer; Data: PByteArray; Len: integer; Value: double);
procedure WriteRawStrFormula (Col,Row,FormatIndex: integer; Data: PByteArray; Len: integer; Value: string);
procedure WriteRawBoolFormula (Col,Row,FormatIndex: integer; Data: PByteArray; Len: integer; Value: boolean);
procedure WriteRawErrFormula (Col,Row,FormatIndex: integer; Data: PByteArray; Len: integer; Value: byte);
procedure WriteRawArrayFormula (Col,Row,FormatIndex: integer; Data: PByteArray; Len: integer; Value: double; Arr: PByteArray; ArrLen: integer);
procedure StreamWriteCells (Version: TExcelVersion; Stream: TXLSStream);
procedure StreamWriteHyperlinks (Version: TExcelVersion; Stream: TXLSStream);
procedure StreamWriteMergedCells(Version: TExcelVersion; Stream: TXLSStream);
function RawHyperlink (Col,Row: integer): string;
procedure ClearCells;
property Hyperlinks: TStringList read FHyperlinks;
property BOUNDSHEETFilePos: integer read FBOUNDSHEETFilePos write FBOUNDSHEETFilePos;
property Cells: TCellStorage read FCells;
property RawName: string read FName;
function AddROW(Row,Col1,Col2,Height,Options,FormatIndex: word): integer;
procedure CopyRows(Sheet: TSheet);
procedure GetROW(Index: integer; ARow: PRecROW);
function ROWCount: integer;
// **********************************************
// *********** End internal use only. ***********
// **********************************************
// procedure AddCell(Cell: TCell);
function AutoWidthCol(Col: longword): integer;
procedure AutoWidthCols(Col1,Col2: longword);
procedure CalcDimensions;
procedure CalcDimensionsEx;
function Calculate(Col, Row: integer): Variant;
procedure DeleteCell(Col, Row: integer);
procedure DeleteCells(Col1, Row1, Col2, Row2: integer);
procedure PaintCell(Canvas: TCanvas; ARect: TRect; ACol,ARow: integer);
function IsEmpty: boolean;
procedure GroupRows(Row1,Row2: integer);
// Less used data
property Gridset: integer read FGridset write FGridset;
property RowGutter: integer read FRowGutter write FRowGutter;
property ColGutter: integer read FColGutter write FColGutter;
property RowOutlineGutter: integer read FRowOutlineGutter write FRowOutlineGutter;
property ColOutlineGutter: integer read FColOutlineGutter write FColOutlineGutter;
property FirstCol: word read FFirstCol write FFirstCol;
property LastCol: word read FLastCol write FLastCol;
property FirstRow: word read FFirstRow write FFirstRow;
property LastRow: word read FLastRow write FLastRow;
property AsBlank[Col,Row: integer]: boolean read GetAsBlank write SetAsBlank;
property AsInteger[Col,Row: integer]: integer read GetAsInteger write SetAsInteger;
property AsFloat[Col,Row: integer]: double read GetAsFloat write SetAsFloat;
property AsString[Col,Row: integer]: string read GetAsString write SetAsString;
property AsWideString[Col,Row: integer]: WideString read GetAsWideString write SetAsWideString;
property AsFmtString[Col,Row: integer]: string read GetFmtAsString;
property AsHTML[Col,Row: integer]: string read GetAsHTML;
property AsBoolean[Col,Row: integer]: boolean read GetAsBoolean write SetAsBoolean;
property AsError[Col,Row: integer]: TCellError read GetAsError write SetAsError;
property AsFormula[Col,Row: integer]: string read GetAsFormula write SetAsFormula;
property AsNumFormulaValue[Col,Row: integer]: double read GetAsNumFormulaValue write SetAsNumFormulaValue;
property AsStrFormulaValue[Col,Row: integer]: string read GetAsStrFormulaValue write SetAsStrFormulaValue;
property AsBoolFormulaValue[Col,Row: integer]: boolean read GetAsBoolFormulaValue write SetAsBoolFormulaValue;
property Cell[Col,Row: integer]: TCell read GetCell;
property CellType[Col,Row: integer]: TCellType read GetCellType;
property Hyperlink[Col,Row: integer]: string read GetHyperlink;
property FileCharts: TXLSInFileCharts read FFileCharts write FFileCharts;
property RowHeights[Index: integer]: integer read GetRowHeight write SetRowHeight;
property WideName: WideString read GetWideName write SetWideName;
// property Count: integer read FCellCount;
published
property Name: string read GetName write SetName;
property DefaultColWidth: word read FDefaultColWidth write FDefaultColWidth;
property DefaultRowHeight: word read FDefaultRowHeight write FDefaultRowHeight;
property PrintSettings: TPrintSettings read FPrintSettings write FPrintSettings;
property MergedCells: TMergedCells read FMergedCells write FMergedCells;
property Options: TSheetOptions read FOptions write FOptions;
property WorkspaceOptions: TWorkspaceOptions read FWorkspaceOptions write FWorkspaceOptions;
property CalcCount: word read FCalcCount write FCalcCount;
property Delta: double read FDelta write FDelta;
property Zoom: word read FZoom write FZoom;
property ZoomPreview: word read FZoomPreview write FZoomPreview;
property RecalcFormulas: boolean read FRecalcFormulas write FRecalcFormulas;
property Notes: TNotes read FNotes write FNotes;
property SheetPictures: TSheetPictures read FSheetPictures write FSheetPictures;
property ColumnFormats: TColumnFormats read FColumnFormats write FColumnFormats;
property Charts: TXLSCharts read FCharts write FCharts;
property FixedRows: word read FFixedRows write FFixedRows;
property FixedCols: byte read FFixedCols write FFixedCols;
property Validations: TDataValidations read FValidations write FValidations;
property Pane: TPane read FPane;
end;
TSheets = class(TCollection)
private
FSST: TSST2;
FXLSMask: TExcelMask;
function GetSheet(Index: integer): TSheet;
protected
FOwner: TPersistent;
function GetOwner: TPersistent; override;
function _GetOwner: TPersistent;
procedure SetBufSize(Value: integer);
function GetBufSize: integer;
public
constructor Create(AOwner: TPersistent);
destructor Destroy; override;
procedure Delete(Index: integer);
procedure Clear;
function Add: TSheet;
function SheetByName(Name: string): TSheet;
// **********************************************
// *********** For internal use only. ***********
// **********************************************
procedure WriteSST(Stream: TXLSStream);
procedure ReadSST(Stream: TXLSStream);
function AddSSTString(S: string): integer;
property MaxBufSize: integer read GetBufSize write SetBufSize;
property SST: TSST2 read FSST;
// **********************************************
// *********** End internal use only. ***********
// **********************************************
property Items[Index: integer]: TSheet read GetSheet; default;
property Owner: TPersistent read _GetOwner;
end;
implementation
uses XLSReadWriteII, DecodeFormula, CalculateFormula;
type TByte8Array = array[0..7] of byte;
{ TPrintSettings }
constructor TPrintSettings.Create(Parent: TSheet);
begin
FParent := Parent;
StartingPage := 1;
Options := [psoPortrait];
HeaderMargin := 0;
FooterMargin := 0;
MarginLeft := -1;
MarginRight := -1;
MarginTop := -1;
MarginBottom := -1;
FCopies := 1;
FPaperSize := psA4;
FScalingFactor := 100;
FRow1OnEachPage := -1;
FRow2OnEachPage := -1;
FCol1OnEachPage := -1;
FCol2OnEachPage := -1;
FHorizPagebreaks := THorizPagebreaks.Create(Self);
FVertPagebreaks := TVertPagebreaks.Create(Self);
FResolution := 600;
end;
procedure TPrintSettings.Clear;
begin
StartingPage := 1;
Options := [psoPortrait];
HeaderMargin := 0;
FooterMargin := 0;
MarginLeft := -1;
MarginRight := -1;
MarginTop := -1;
MarginBottom := -1;
FCopies := 1;
FScalingFactor := 100;
FHorizPagebreaks.Clear;
FVertPagebreaks.Clear;
end;
procedure TPrintSettings.SetHeader(Value: string);
begin
if Length(Value) > 255 then
raise Exception.Create('Header is limited to max 255 characthers')
else
FHeader := Value;
end;
procedure TPrintSettings.SetFooter(Value: string);
begin
if Length(Value) > 255 then
raise Exception.Create('Footer is limited to max 255 characthers')
else
FFooter := Value;
end;
function TPrintSettings.StrToRange(S: string; var Value1,Value2: integer): boolean;
var
p: integer;
V1, V2: integer;
begin
Result := False;
p := CPos(':',S);
if p < 1 then
Exit;
V1 := StrToIntDef(Copy(S,1,p - 1),-2);
if V1 < -1 then
Exit;
V2 := StrToIntDef(Copy(S,p + 1,MAXINT),-2);
if V2 < -1 then
Exit;
if V2 < V1 then
Exit;
if (V1 < 0) or (V2 < 0) then begin
V1 := -1;
V2 := -1;
end;
Value1 := V1;
Value2 := V2;
Result := True;
end;
procedure TPrintSettings.SetRowsOnEachPage(const Value: string);
begin
if not StrToRange(Value,FRow1OnEachPage,FRow2OnEachPage)then
raise Exception.Create(ersInvalidValue);
with TXLSReadWriteII(TSheets(FParent.Collection).Owner) do
NameDefs.AddNAME_PrintColsRows(FParent.Index,FCol1OnEachPage,FCol2OnEachPage,FRow1OnEachPage,FRow2OnEachPage);
end;
procedure TPrintSettings.SetColsOnEachPage(const Value: string);
begin
if not StrToRange(Value,FCol1OnEachPage,FCol2OnEachPage) then
raise Exception.Create(ersInvalidValue);
with TXLSReadWriteII(TSheets(FParent.Collection).Owner) do
NameDefs.AddNAME_PrintColsRows(FParent.Index,FCol1OnEachPage,FCol2OnEachPage,FRow1OnEachPage,FRow2OnEachPage);
end;
function TPrintSettings.GetColsOnEachPage: string;
begin
Result := Format('%d:%d',[FCol1OnEachPage,FCol2OnEachPage]);
end;
function TPrintSettings.GetRowsOnEachPage: string;
begin
Result := Format('%d:%d',[FRow1OnEachPage,FRow2OnEachPage]);
end;
destructor TPrintSettings.Destroy;
begin
FHorizPagebreaks.Free;
FVertPagebreaks.Free;
inherited;
end;
function TPrintSettings.GetOwner: TPersistent;
begin
Result := FParent;
end;
{ TMergedCell }
function TMergedCell.GetDisplayName: string;
begin
inherited GetDisplayName;
Result := 'MergedCell ' + IntToStr(ID);
end;
function TMergedCell.GetValid: boolean;
var
i: integer;
begin
Result := False;
if (FCol1 > FCol2) or (FRow1 > FRow2) then
Exit;
for i := 0 to Collection.Count - 1 do begin
if PtInRect(TMergedCells(Collection)[i].AsRect,Point(FCol1,FRow1)) or PtInRect(TMergedCells(Collection)[i].AsRect,Point(FCol2 - 1,FRow2 - 1)) then
Exit;
end;
Result := True;
end;
function TMergedCell.AsRect: TRect;
begin
Result := Rect(Col1,Row1,Col2,Row2);
end;
procedure TMergedCell.Assign(Source: TPersistent);
begin
if not (Source is TMergedCell) then
raise Exception.Create('Can only assign TMergedCell');
FCol1 := TMergedCell(Source).FCol1;
FRow1 := TMergedCell(Source).FRow1;
FCol2 := TMergedCell(Source).FCol2;
FRow2 := TMergedCell(Source).FRow2;
end;
constructor TMergedCells.Create(AOwner: TPersistent);
begin
inherited Create(TMergedCell);
FOwner := AOwner;
end;
function TMergedCells.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TMergedCells.GetItem(Index: integer): TMergedCell;
begin
Result := TMergedCell(inherited Items[Index]);
end;
function TMergedCells.Add: TMergedCell;
begin
Result := TMergedCell(inherited Add);
end;
function TMergedCells.IsInMerged(Col,Row: integer): integer;
begin
for Result := 0 to Count - 1 do begin
if PtInRect(Items[Result].AsRect,Point(Col,Row)) then
Exit;
end;
Result := -1;
end;
constructor TSheets.Create(AOwner: TPersistent);
begin
inherited Create(TSheet);
FOwner := AOwner;
FSST := TSST2.Create;
FXLSMask := TExcelMask.Create;
end;
destructor TSheets.Destroy;
begin
FSST.Free;
FXLSMask.Free;
inherited;
end;
procedure TSheets.Delete(Index: integer);
begin
{$ifndef ver120}
inherited Delete(Index);
{$endif}
if Count < 1 then
Add;
end;
function TSheets.Add: TSheet;
begin
Result := TSheet(inherited Add);
end;
procedure TSheets.Clear;
var
i: integer;
begin
FSST.Clear;
for i := 0 to Count - 1 do
Items[i].ClearData;
inherited Clear;
Add;
end;
function TSheets.GetSheet(Index: integer): TSheet;
begin
Result := TSheet(inherited Items[Index]);
end;
procedure TSheets.SetBufSize(Value: integer);
begin
FSST.MaxBufSize := Value;
end;
function TSheets.GetBufSize: integer;
begin
Result := FSST.MaxBufSize;
end;
function TSheets.GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TSheets.AddSSTString(S: string): integer;
begin
Result := FSST.AddString(S);
end;
procedure TSheets.WriteSST(Stream: TXLSStream);
begin
FSST.Write(Stream);
end;
procedure TSheets.ReadSST(Stream: TXLSStream);
begin
FSST.Read(Stream);
end;
constructor TSheet.Create(Collection: TCollection);
begin
inherited Create(Collection);
FCells := TCellStorage.Create;
FColumnFormats := TColumnFormats.Create(Self);
FDelta := 0.001;
FOptions := [soGridlines,soRowColHeadings,soShowZeros];
FWorkspaceOptions := [woShowAutoBreaks,woRowSumsBelow,woColSumsRight,woOutlineSymbols];
FCalcCount := 100;
FRecalcFormulas := True;
FDefaultColWidth := 8;
FDefaultRowHeight := 0;
FGridset := 1;
FZoom := 100;
FZoomPreview := 100;
FMergedCells := TMergedCells.Create(Self);
FPrintSettings := TPrintSettings.Create(Self);
FHyperlinks := TStringList.Create;
FNotes := TNotes.Create(Self);
FSheetPictures := TSheetPictures.Create(Self,TXLSReadWriteII(TSheets(Collection).Owner).Pictures);
FCharts := TXLSCharts.Create(Self,TXLSReadWriteII(TSheets(Collection).Owner).FormulaEncoder,TXLSReadWriteII(TSheets(Collection).Owner).GetName);
FFileCharts := TXLSInFileCharts.Create;
FValidations := TDataValidations.Create(Self,TXLSREadWriteII(TSheets(Collection).Owner).GetName);
FRows := TList.Create;
FPane := TPane.Create;
SetName('Sheet ' + IntToStr(ID + 1));
end;
destructor TSheet.Destroy;
begin
FCells.Free;
FRows.Free;
FValidations.Free;
FFileCharts.Free;
FCharts.Free;
FColumnFormats.Free;
FMergedCells.Free;
FPrintSettings.Free;
FSheetPictures.Free;
FNotes.Free;
FHyperlinks.Free;
FPane.Free;
inherited Destroy;
end;
procedure TSheet.ClearData;
var
i: integer;
begin
FFirstCol := $FFFF;
FLastCol := 0;
FFirstRow := $FFFF;
FLastRow := 0;
FValidations.Clear;
FHyperlinks.Clear;
FMergedCells.Clear;
FPrintSettings.Clear;
FSheetPictures.Clear;
FNotes.Clear;
FColumnFormats.Clear;
FCharts.Clear;
FFileCharts.Clear;
for i := 0 to FRows.Count - 1 do
FreeMem(Frows[i]);
FRows.Clear;
FPane.Clear;
ClearCells;
end;
procedure TSheet.CheckFirstLast(ACol,ARow: integer);
begin
if ACol < FFirstCol then FFirstCol := ACol;
if ACol > FLastCol then FLastCol := ACol;
if ARow < FFirstRow then FFirstRow := ARow;
if ARow > FLastRow then FLastRow := ARow;
end;
procedure TSheet.SetName(Value: string);
var
i: integer;
S: string;
begin
S := AnsiUppercase(Value);
if (Length(Value) > 0) and not (Value[1] in [#0,#1]) then
Value := #0 + Value;
for i := 0 to Collection.Count - 1 do begin
if AnsiUppercase(TSheets(Collection).Items[i].Name) = S then begin
raise Exception.Create('Sheet name "' + S + '" allready exists');
Exit;
end;
end;
FName := Value;
end;
procedure TSheet.NameWideString(S: WideString);
var
i: integer;
P: PByteArray;
S2: string;
begin
P := @S[1];
SetLength(S2,Length(S) * 2);
for i := 1 to Length(S2) do
S2[i] := Char(P[i - 1]);
SetName(#1 + S2);
end;
function TSheet.GetName: string;
begin
Result := Copy(FName,2,Length(FName));
end;
function TSheet.GetWideName: WideString;
var
S: string;
begin
if (FName <> '') and (FName[1] = #1) then begin
S := Copy(FName,2,MAXINT);
SetLength(Result,Length(S) div 2);
Move(Pointer(S)^,Pointer(Result)^,Length(S));
end
else begin
S := Copy(FName,2,MAXINT);
Result := S;
end;
end;
procedure TSheet.SetWideName(const Value: WideString);
var
S: string;
begin
SetLength(S,Length(Value) * 2);
Move(Pointer(Value)^,Pointer(S)^,Length(S));
SetName(#1 + S);
end;
function TSheet.GetDisplayName: string;
begin
inherited GetDisplayName;
Result := GetName;
end;
procedure TSheet.WriteBlank(Col,Row, FormatIndex: integer);
begin
FCells[ColRowToRC(Col,Row)] := TBlankCell.Create(ColRowToRC(Col,Row),FormatIndex);
end;
procedure TSheet.WriteBoolean(Col,Row, FormatIndex: integer; Value: boolean);
begin
FCells[ColRowToRC(Col,Row)] := TBooleanCell.Create(ColRowToRC(Col,Row),FormatIndex,Value);
end;
procedure TSheet.WriteError(Col,Row, FormatIndex: integer; Value: TCellError);
begin
FCells[ColRowToRC(Col,Row)] := TErrorCell.Create(ColRowToRC(Col,Row),FormatIndex,Value);
end;
procedure TSheet.WriteNumFormula(Col,Row,FormatIndex: integer; Formula: string; Value: double);
var
Cell: TNumberFormulaCell;
begin
Cell := TNumberFormulaCell(EncodeFormula(Formula,ctNumberFormula,ColRowToRC(Col,Row),FormatIndex));
Cell.NumberValue := Value;
FCells[ColRowToRC(Col,Row)] := Cell;
end;
procedure TSheet.WriteStrFormula(Col,Row,FormatIndex: integer; Formula: string; Value: string);
var
Cell: TStringFormulaCell;
begin
Cell := TStringFormulaCell(EncodeFormula(Formula,ctStringFormula,ColRowToRC(Col,Row),FormatIndex));
Cell.StringValue := Value;
FCells[ColRowToRC(Col,Row)] := Cell;
end;
procedure TSheet.WriteBoolFormula(Col,Row,FormatIndex: integer; Formula: string; Value: boolean);
var
Cell: TBooleanFormulaCell;
begin
Cell := TBooleanFormulaCell(EncodeFormula(Formula,ctBooleanFormula,ColRowToRC(Col,Row),FormatIndex));
Cell.BooleanValue := Value;
FCells[ColRowToRC(Col,Row)] := Cell;
end;
procedure TSheet.WriteErrorFormula(Col,Row,FormatIndex: integer; Formula: string; Value: TCellError);
var
Cell: TErrorFormulaCell;
begin
Cell := TErrorFormulaCell(EncodeFormula(Formula,ctErrorFormula,ColRowToRC(Col,Row),FormatIndex));
Cell.ErrorValue := Value;
FCells[ColRowToRC(Col,Row)] := Cell;
end;
procedure TSheet.WriteNumber(Col,Row, FormatIndex: integer; Value: double);
begin
FCells[ColRowToRC(Col,Row)] := TFloatCell.Create(ColRowToRC(Col,Row),FormatIndex,Value);
end;
procedure TSheet.WriteString(Col,Row, FormatIndex: integer; Value: string);
begin
FCells[ColRowToRC(Col,Row)] := TStringCell.Create(ColRowToRC(Col,Row),FormatIndex,TSheets(Collection).FSST.AddString(Value));
end;
procedure TSheet.WriteWideString(Col,Row, FormatIndex: integer; Value: string);
begin
FCells[ColRowToRC(Col,Row)] := TStringCell.Create(ColRowToRC(Col,Row),FormatIndex,TSheets(Collection).FSST.AddWideString(Value));
end;
procedure TSheet.WriteStringArray(Col, Row, FormatIndex: integer; Vertical: boolean; Value: array of string);
var
i: integer;
begin
for i := Low(Value) to High(Value) do begin
WriteString(Col,Row,FormatIndex,Value[i]);
if Vertical then
Inc(Row)
else
Inc(Col);
end;
end;
procedure TSheet.WriteWideStringArray(Col, Row, FormatIndex: integer; Vertical: boolean; Value: array of string);
var
i: integer;
begin
for i := Low(Value) to High(Value) do begin
WriteWideString(Col,Row,FormatIndex,Value[i]);
if Vertical then
Inc(Row)
else
Inc(Col);
end;
end;
procedure TSheet.WriteSSTString(Col,Row,FormatIndex: integer; Value: string);
begin
FCells[ColRowToRC(Col,Row)] := TStringCell.Create(ColRowToRC(Col,Row),FormatIndex,TSheets(Collection).SST.AddString(Value));
end;
procedure TSheet.WriteSSTWideString(Col,Row,FormatIndex: integer; Value: WideString);
begin
FCells[ColRowToRC(Col,Row)] := TStringCell.Create(ColRowToRC(Col,Row),FormatIndex,TSheets(Collection).SST.AddWideString(Value));
end;
procedure TSheet.WriteSSTStringIndex(Col,Row,FormatIndex: integer; Value: integer);
begin
FCells[ColRowToRC(Col,Row)] := TStringCell.Create(ColRowToRC(Col,Row),FormatIndex,Value);
TSheets(Collection).SST.IncRefCount(Value);
end;
procedure TSheet.WriteHyperlink(Col,Row,FormatIndex: integer; Text,Link: string);
begin
WriteString(Col,Row,FormatIndex,Text);
FHyperlinks.AddObject(Text + #9 + Link,TObject(ColRowToRC(Col,Row)));
end;
function TSheet.RawHyperlink(Col,Row: integer): string;
var
i: integer;
begin
i := FHyperlinks.IndexOfObject(TObject(ColRowToRC(Col,Row)));
if i >= 0 then
Result := FHyperlinks[i]
else
Result := '';
end;
function TSheet.GetHyperlink(Col, Row: integer): string;
var
i: integer;
begin
i := FHyperlinks.IndexOfObject(TObject(ColRowToRC(Col,Row)));
if i >= 0 then begin
Result := FHyperlinks[i];
i := CPos(#9,Result);
if i > 0 then
Result := Copy(Result,i + 1,MAXINT);
end
else
Result := '';
end;
procedure TSheet.StreamWriteHyperlinks(Version: TExcelVersion; Stream: TXLSStream);
const
Data1: array[0..23] of byte = ($D0,$C9,$EA,$79,$F9,$BA,$CE,$11,$8C,$82,$00,$AA,$00,$4B,$A9,$0B,$02,$00,$00,$00,$17,$00,$00,$00);
Data2: array[0..17] of byte = ($00,$00,$E0,$C9,$EA,$79,$F9,$BA,$CE,$11,$8C,$82,$00,$AA,$00,$4B,$A9,$0B);
var
i,p: integer;
Col,Row,L,Z: word;
Text,Link: string;
WC: PWideChar;
begin
if Version < xvExcel97 then
Exit;
Z := 0;
for i := 0 to FHyperlinks.Count - 1 do begin
Row := Integer(FHyperlinks.Objects[i]) shr 8;
Col := Integer(FHyperlinks.Objects[i]) and $000000FF;
p := CPos(#9,FHyperlinks[i]);
if p > 0 then begin
Text := Copy(FHyperlinks[i],1,p - 1);
Link := Copy(FHyperlinks[i],p + 1,MAXINT);
Stream.WriteHeader(BIFFRECID_HLINK,8 + Length(Data1) + (Length(Text) * 2 + 4) + Length(Data2) + (Length(Link) * 2 + 4) + 2);
Stream.Write(Row,2);
Stream.Write(Row,2);
Stream.Write(Col,2);
Stream.Write(Col,2);
Stream.Write(Data1,Length(Data1));
L := Length(Text);
GetMem(WC,L * 2 + 1);
try
StringToWideChar(Text,WC,L * 2);
Inc(L);
Stream.Write(L,2);
Dec(L);
Stream.Write(Z,2);
Stream.Write(WC^,L * 2);
finally
FreeMem(WC);
end;
Stream.Write(Data2,Length(Data2));
L := Length(Link) * 2;
GetMem(WC,L + 1);
try
StringToWideChar(Link,WC,L);
Inc(L,2);
Stream.Write(L,2);
Dec(L,2);
Stream.Write(Z,2);
Stream.Write(WC^,L);
finally
FreeMem(WC);
end;
Stream.Write(Z,2);
end;
end;
end;
procedure TSheet.StreamWriteMergedCells(Version: TExcelVersion; Stream: TXLSStream);
var
i,j,MaxCount: integer;
Buf: PByteArray;
begin
if Version < xvExcel97 then
Exit;
GetMem(Buf,TSheets(Collection).MaxBufSize);
try
if FMergedCells.Count > 0 then begin
MaxCount := (TSheets(Collection).MaxBufSize - 2) div 8;
if FMergedCells.Count < MaxCount then
MaxCount := FMergedCells.Count;
j := 0;
for i := 0 to FMergedCells.Count - 1 do begin
PRecMERGEDCELLS(Buf).Cells[j].Row1 := FMergedCells[i].Row1;
PRecMERGEDCELLS(Buf).Cells[j].Row2 := FMergedCells[i].Row2;
PRecMERGEDCELLS(Buf).Cells[j].Col1 := FMergedCells[i].Col1;
PRecMERGEDCELLS(Buf).Cells[j].Col2 := FMergedCells[i].Col2;
Inc(j);
if j >= MaxCount then begin
PRecMERGEDCELLS(Buf).Count := j;
Stream.WriteHeader(BIFFRECID_MERGEDCELLS,2 + j * 8);
Stream.Write(Buf^,2 + j * 8);
j := 0;
end;
end;
if j > 0 then begin
PRecMERGEDCELLS(Buf).Count := j;
Stream.WriteHeader(BIFFRECID_MERGEDCELLS,2 + j * 8);
Stream.Write(Buf^,2 + j * 8);
end;
end;
finally
FreeMem(Buf);
end;
end;
procedure TSheet.WriteBuf(Stream: TXLSStream; RecId,Size: word; P: Pointer);
begin
Stream.WriteHeader(RecID,Size);
if Size > 0 then
Stream.Write(P^,Size);
end;
function TSheet.GetDefaultWriteFormat(Version: TExcelVersion; FormatIndex: integer): word;
begin
if FormatIndex < 0 then
Result := DEFAULT_FORMAT
else if TXLSReadWriteII(TSheets(Collection).Owner).WriteDefaultData then begin
if Version < xvExcel50 then
Result := FormatIndex + DEFAULT_FORMAT40 + 1
else if Version < xvExcel97 then
Result := FormatIndex + DEFAULT_FORMATS_COUNT_50
else
Result := FormatIndex + DEFAULT_FORMATS_COUNT_97;
end
else
Result := FormatIndex ;
end;
procedure TSheet.StreamWriteCells(Version: TExcelVersion; Stream: TXLSStream);
type TMulRk = packed record
XF: word;
RK: longword;
end;
var
L: word;
S: string;
V: double;
Row,CurrRow: integer;
RK: longword;
Cell: TCell;
RecBlank: TRecBLANK;
RecNum: TRecNUMBER;
RecRK: TRecRK;
RecBool: TRecBOOLERR;
RecLabel: TRecLABEL;
RecLabelSST: TRecLABELSST;
RecFormula: TRecFORMULA_;
Buf: PByteArray;
RKCache: array[0..255] of TMulRK;
RKCachePtr: integer;
RKFirstCol,RKLastCol: integer;
function EncodeRK(const Value: double; var RK: longword): boolean;
var
D: double;
pL1, pL2: ^longword;
Mask: longword;
i: integer;
begin
Result := True;
for i:=0 to 1 do begin
D := Value * (1 + 99 * i);
pL1 := @d;
pL2 := pL1;
Inc(pL2);
if (pL1^ = 0) and ((pL2^ and 3) = 0) then begin
RK := pL2^ + i;
Exit;
end;
Mask := $1FFFFFFF;
if (Int(D) = D) and (D <= Mask) and (D >= -Mask - 1) then begin
RK := Round(D) shl 2 + i + 2;
Exit;
end;
end;
Result := False;
end;
procedure FlushRkCache;
begin
if RKCachePtr > 0 then begin
if RKCachePtr = 1 then begin
RecRK.Row := CurrRow;
RecRK.Col := RKFirstCol;
RecRK.FormatIndex := RKCache[0].XF;
RecRK.Value := RKCache[0].RK;
WriteBuf(Stream,BIFFRECID_RK7,SizeOf(TRecRK),@RecRK);
end
else begin
Stream.WriteHeader(BIFFRECID_MULRK,RKCachePtr * SizeOf(TMulRk) + 6);
Stream.WWord(CurrRow);
Stream.WWord(RKFirstCol);
Stream.Write(RKCache[0],RKCachePtr * SizeOf(TMulRk));
Stream.WWord(RKLastCol);
end;
RKCachePtr := 0;
RKFirstCol := -1;
RKLastCol := -1;
end;
end;
function AddRk(RK,XF,Col: integer): boolean;
begin
if RKCachePtr > High(RKCache) then
raise Exception.Create('RK Cache overflow');
if RKFirstCol < 0 then
RKFirstCol := Col;
if (RKLastCol >= 0) and (Col <> (RKLastCol + 1)) then
Result := False
else begin
RKLastCol := Col;
RKCache[RKCachePtr].XF := XF;
RKCache[RKCachePtr].RK := RK;
Inc(RKCachePtr);
Result := True;
end;
end;
begin
RKCachePtr := 0;
RKFirstCol := -1;
RKLastCol := -1;
GetMem(Buf,TSheets(Collection).MaxBufSize);
try
FCells.BeginIterate;
Cell := FCells.GetNext;
while Cell <> Nil do begin
Row := Cell.RowCol shr 8;
if Row <> CurrRow then
FlushRkCache;
CurrRow := Row;
if not (Cell.CellType in [ctFloat,ctInteger]) then
FlushRkCache;
case Cell.CellType of
ctBlank: begin
RecBlank.Row := Cell.RowCol shr 8;
RecBlank.Col := Cell.RowCol and $000000FF;
RecBlank.FormatIndex := GetDefaultWriteFormat(Version,Cell.FormatIndex);
// RecBlank.FormatIndex := 20;
WriteBuf(Stream,BIFFRECID_BLANK,SizeOf(TRecBLANK),@RecBlank);
end;
ctBoolean: begin
RecBool.Row := Cell.RowCol shr 8;
RecBool.Col := Cell.RowCol and $000000FF;
RecBool.FormatIndex := GetDefaultWriteFormat(Version,Cell.FormatIndex);
RecBool.BoolErr := Byte(TBooleanCell(Cell).Value);
RecBool.Error := 0;
WriteBuf(Stream,BIFFRECID_BOOLERR,SizeOf(TRecBOOLERR),@RecBool);
end;
ctError: begin
RecBool.Row := Cell.RowCol shr 8;
RecBool.Col := Cell.RowCol and $000000FF;
RecBool.FormatIndex := GetDefaultWriteFormat(Version,Cell.FormatIndex);
case TErrorCell(Cell).Value of
ErrError: raise Exception.CreateFmt(ersInvalidErrorValueInCell,[RecBool.Row,RecBool.Col]);
errNull: RecBool.BoolErr := $00;
errDiv0: RecBool.BoolErr := $07;
errValue: RecBool.BoolErr := $0F;
errRef: RecBool.BoolErr := $17;
errName: RecBool.BoolErr := $1D;
errNum: RecBool.BoolErr := $24;
errNA: RecBool.BoolErr := $2A;
end;
RecBool.Error := 1;
WriteBuf(Stream,BIFFRECID_BOOLERR,SizeOf(TRecBOOLERR),@RecBool);
end;
ctFloat,ctInteger: begin
if Cell.CellType = ctFloat then
V := TFloatCell(Cell).Value
else
V := TIntegerCell(Cell).Value;
if not (EncodeRK(V,RK) and AddRK(RK,GetDefaultWriteFormat(Version,Cell.FormatIndex),Cell.RowCol and $000000FF)) then begin
FlushRkCache;
RecNum.Row := Cell.RowCol shr 8;
RecNum.Col := Cell.RowCol and $000000FF;
RecNum.FormatIndex := GetDefaultWriteFormat(Version,Cell.FormatIndex);
RecNum.Value := V;
WriteBuf(Stream,BIFFRECID_NUMBER,SizeOf(TRecNUMBER),@RecNum);
end;
end;
ctString: begin
if Version >= xvExcel97 then begin
RecLabelSST.Row := Cell.RowCol shr 8;
RecLabelSST.Col := Cell.RowCol and $000000FF;
RecLabelSST.FormatIndex := GetDefaultWriteFormat(Version,Cell.FormatIndex);
RecLabelSST.SSTIndex := TStringCell(Cell).Value;
WriteBuf(Stream,BIFFRECID_LABELSST,SizeOf(TRecLABELSST),@RecLabelSST);
end
else begin
RecLabel.Row := Cell.RowCol shr 8;
RecLabel.Col := Cell.RowCol and $000000FF;
RecLabel.FormatIndex := GetDefaultWriteFormat(Version,Cell.FormatIndex);
S := TSheets(Collection).FSST[TStringCell(Cell).Value];
RecLabel.Len := Length(S);
Move(Pointer(S)^,RecLabel.Data,Length(S));
RecLabel.Data[Length(S)] := 0;
WriteBuf(Stream,BIFFRECID_LABEL,8 + RecLabel.Len,@RecLabel);
end;
end;
ctNumberFormula,ctStringFormula,ctBooleanFormula,ctErrorFormula,ctArrayFormula: begin
RecFORMULA.Row := Cell.RowCol shr 8;
RecFORMULA.Col := Cell.RowCol and $000000FF;
RecFORMULA.FormatIndex := GetDefaultWriteFormat(Version,Cell.FormatIndex);
if FRecalcFormulas then
RecFORMULA.Options := $02
else
RecFORMULA.Options := $00;
RecFORMULA.ParseLen := TFormulaCell(Cell).Size;
case Cell.CellType of
ctNumberFormula,ctArrayFormula: begin
RecFORMULA.Value := TNumberFormulaCell(Cell).NumberValue;
end;
ctBooleanFormula: begin
TByte8Array(RecFORMULA.Value)[0] := 1;
TByte8Array(RecFORMULA.Value)[1] := 0;
TByte8Array(RecFORMULA.Value)[2] := Byte(TBooleanFormulaCell(Cell).BooleanValue);
TByte8Array(RecFORMULA.Value)[3] := 0;
TByte8Array(RecFORMULA.Value)[4] := 0;
TByte8Array(RecFORMULA.Value)[5] := 0;
TByte8Array(RecFORMULA.Value)[6] := $FF;
TByte8Array(RecFORMULA.Value)[7] := $FF;
end;
ctErrorFormula: begin
TByte8Array(RecFORMULA.Value)[0] := 1;
TByte8Array(RecFORMULA.Value)[1] := 0;
TByte8Array(RecFORMULA.Value)[2] := CellErrorErrorCodeTo(TErrorFormulaCell(Cell).ErrorValue);
TByte8Array(RecFORMULA.Value)[3] := 0;
TByte8Array(RecFORMULA.Value)[4] := 0;
TByte8Array(RecFORMULA.Value)[5] := 0;
TByte8Array(RecFORMULA.Value)[6] := $FF;
TByte8Array(RecFORMULA.Value)[7] := $FF;
end;
ctStringFormula: begin
TByte8Array(RecFORMULA.Value)[0] := 0;
TByte8Array(RecFORMULA.Value)[1] := 0;
TByte8Array(RecFORMULA.Value)[2] := 0;
TByte8Array(RecFORMULA.Value)[3] := 0;
TByte8Array(RecFORMULA.Value)[4] := 0;
TByte8Array(RecFORMULA.Value)[5] := 0;
TByte8Array(RecFORMULA.Value)[6] := $FF;
TByte8Array(RecFORMULA.Value)[7] := $FF;
end;
end;
Stream.WriteHeader(BIFFRECID_FORMULA,SizeOf(TRecFORMULA_) + RecFORMULA.ParseLen);
Stream.Write(RecFORMULA,SizeOf(TRecFORMULA_));
Move(TFormulaCell(Cell).PTGS^,Buf^,TFormulaCell(Cell).Size);
Stream.Write(Buf^,RecFORMULA.ParseLen);
if Cell.CellType = ctStringFormula then begin
// Write STRING record.
S := TStringFormulaCell(Cell).StringValue;
L := Length(S);
if Version >= xvExcel97 then begin
if S <> '' then
S := ToMultibyte1bHeader(S);
Stream.WriteHeader(BIFFRECID_STRING,Length(S) + 2);
Stream.Write(L,2);
if L > 0 then
Stream.Write(Pointer(S)^,Length(S));
end
else begin
Stream.WriteHeader(BIFFRECID_STRING,L - 1 + 2);
Stream.Write(L,2);
if L > 0 then
Stream.Write(Pointer(S)^,L);
end;
end
else if Cell.CellType = ctArrayFormula then begin
Stream.WriteHeader(BIFFRECID_ARRAY,TArrayFormulaCell(Cell).ArraySize);
Stream.Write(TArrayFormulaCell(Cell).ArrayData^,TArrayFormulaCell(Cell).ArraySize);
end;
end;
end;
Cell := FCells.GetNext;
end;
FlushRkCache;
finally
FreeMem(Buf);
end;
end;
procedure TSheet.ClearCells;
begin
FCells.Clear;
end;
procedure TSheet.DeleteCell(Col, Row: integer);
var
i: integer;
begin
FCells.Delete(ColRowToRC(Col,Row));
i := FHyperlinks.IndexOfObject(TObject(ColRowToRC(Col,Row)));
if i >= 0 then
FHyperlinks.Delete(i);
end;
procedure TSheet.DeleteCells(Col1, Row1, Col2, Row2: integer);
var
Col,Row: integer;
begin
for Col := Col1 to Col2 do begin
for Row := Row1 to Row2 do
DeleteCell(Col,Row);
end;
end;
function TSheet.GetCell(Col, Row: integer): TCell;
begin
Result := FCells[ColRowToRC(Col,Row)];
end;
function TSheet.GetCellType(Col, Row: integer): TCellType;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if Cell <> Nil then
Result := Cell.CellType
else
Result := ctNone;
end;
function TSheet.GetAsBlank(Col, Row: integer): boolean;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) then
Result := True
else
Result := False;
end;
procedure TSheet.SetAsBlank(Col, Row: integer; const Value: boolean);
begin
FCells.CellsDefFormat[ColRowToRC(Col,Row)] := TBlankCell.Create(ColRowToRC(Col,Row),GetDefaultFormat(Col,Row));
end;
function TSheet.GetAsInteger(Col, Row: integer): integer;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) then begin
if Cell is TFloatCell then
Result := Round(TFloatCell(Cell).Value)
else if Cell is TIntegerCell then
Result := TIntegerCell(Cell).Value
else
raise Exception.Create(ersCellIsMissingOrIsOfWrongType);
end
else
raise Exception.Create(ersCellIsMissingOrIsOfWrongType);
end;
procedure TSheet.SetAsInteger(Col, Row: integer; const Value: integer);
begin
FCells.CellsDefFormat[ColRowToRC(Col,Row)] := TIntegerCell.Create(ColRowToRC(Col,Row),GetDefaultFormat(Col,Row),Value);
end;
function TSheet.GetAsBoolean(Col, Row: integer): boolean;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) and (Cell is TBooleanCell) then
Result := TBooleanCell(Cell).Value
else
raise Exception.Create(ersCellIsMissingOrIsOfWrongType);
end;
procedure TSheet.SetAsBoolean(Col, Row: integer; const Value: boolean);
begin
FCells.CellsDefFormat[ColRowToRC(Col,Row)] := TBooleanCell.Create(ColRowToRC(Col,Row),GetDefaultFormat(Col,Row),Value);
end;
function TSheet.GetAsError(Col, Row: integer): TCellError;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) and (Cell is TErrorCell) then
Result := TErrorCell(Cell).Value
else
raise Exception.Create(ersCellIsMissingOrIsOfWrongType);
end;
procedure TSheet.SetAsError(Col, Row: integer; Value: TCellError);
begin
FCells.CellsDefFormat[ColRowToRC(Col,Row)] := TErrorCell.Create(ColRowToRC(Col,Row),GetDefaultFormat(Col,Row),Value);
end;
function TSheet.GetAsFloat(Col, Row: integer): double;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) then begin
if Cell is TFloatCell then
Result := TFloatCell(Cell).Value
else if Cell is TIntegerCell then
Result := TIntegerCell(Cell).Value
else if Cell is TNumberFormulaCell then
Result := TNumberFormulaCell(Cell).NumberValue
else
Result := 0;
end
else
Result := 0;
end;
procedure TSheet.SetAsFloat(Col, Row: integer; const Value: double);
begin
FCells.CellsDefFormat[ColRowToRC(Col,Row)] := TFloatCell.Create(ColRowToRC(Col,Row),GetDefaultFormat(Col,Row),Value);
end;
function TSheet.GetAsString(Col, Row: integer): string;
var
Cell: TCell;
XLS: TXLSReadWriteII;
begin
XLS := TXLSReadWriteII(TSheets(Collection).Owner);
Cell := FCells[ColRowToRC(Col,Row)];
if Cell <> Nil then begin
case Cell.CellType of
ctNone,
ctBlank: Result := '';
ctInteger: Result := IntToStr(TIntegerCell(Cell).Value);
ctFloat: Result := FloatToStr(TFloatCell(Cell).Value);
ctString: Result := TSheets(Collection).FSST[TStringCell(Cell).Value];
ctBoolean: if TBooleanCell(Cell).Value then Result := XLS.StrTRUE else Result := XLS.StrFALSE;
ctError: Result := CellErrorNames[Integer(TErrorCell(Cell).Value)];
ctNumberFormula: if XLS.ShowFormulas then
Result := DecodeFmla(XLS.Version,TNumberFormulaCell(Cell).PTGS,TNumberFormulaCell(Cell).Size,Col,Row,XLS.GetName)
else
Result := FloatToStr(TNumberFormulaCell(Cell).NumberValue);
ctStringFormula: if XLS.ShowFormulas then
Result := DecodeFmla(XLS.Version,TStringFormulaCell(Cell).PTGS,TStringFormulaCell(Cell).Size,Col,Row,XLS.GetName)
else
Result := TStringFormulaCell(Cell).StringValue;
ctBooleanFormula: if XLS.ShowFormulas then
Result := DecodeFmla(XLS.Version,TBooleanFormulaCell(Cell).PTGS,TBooleanFormulaCell(Cell).Size,Col,Row,XLS.GetName)
else
if TBooleanFormulaCell(Cell).BooleanValue then Result := XLS.StrTRUE else Result := XLS.StrFALSE;
ctErrorFormula: if XLS.ShowFormulas then
Result := DecodeFmla(XLS.Version,TErrorFormulaCell(Cell).PTGS,TErrorFormulaCell(Cell).Size,Col,Row,XLS.GetName)
else
Result := CellErrorNames[Byte(TErrorFormulaCell(Cell).ErrorValue)];
end;
end
else
Result := '';
end;
procedure TSheet.SetAsString(Col, Row: integer; const Value: string);
begin
FCells.CellsDefFormat[ColRowToRC(Col,Row)] := TStringCell.Create(ColRowToRC(Col,Row),GetDefaultFormat(Col,Row),TSheets(Collection).FSST.AddString(Value));
end;
function TSheet.GetFmtAsString(Col, Row: integer): string;
var
Cell: TCell;
XLS: TXLSReadWriteII;
function FormatNumber(V: double; FormatIndex: integer): string;
function DoUserFormat: string;
var
S: string;
begin
S := XLS.Formats[FormatIndex].NumberFormat;
if S <> '' then begin
TSheets(Collection).FXLSMask.Mask := S;
Result := TSheets(Collection).FXLSMask.FormatNumber(V);
end
else
Result := FloatToStr(V);
end;
function FloatToFracStr(Value: double; MaxDenom: integer): string;
var
an,ad: integer;
bn,bd: integer;
n,d: integer;
sp,delta: double;
sPrefix: string;
begin
if Frac(Value) = 0 then begin
Result := FloatToStr(Value);
Exit;
end;
sPrefix := '';
if Int(Value) > 0 then begin
sPrefix := FloatToStr(Int(Value)) + ' ';
Value := Frac(Value);
end;
an := 0;
ad := 1;
bn := 1;
bd := 1;
d := ad + bd;
while (d <= MaxDenom) do begin
sp := 1e-5 * d;
n := an + bn;
delta := Value * d - n;
if delta > sp then begin
an := n;
ad := d;
end
else if delta < -sp then begin
bn := n;
bd := d;
end
else begin
Result := sPrefix + Format('%d/%d',[n,d]);
Exit;
end;
d := ad + bd;
end;
if (bd > MaxDenom) or (Abs(Value * ad - an) < Abs(Value * bd - bn)) then
Result := sPrefix + Format('%d/%d',[an,ad])
else
Result := sPrefix + Format('%d/%d',[bn,bd]);
end;
begin
if (FormatIndex >= 0) then begin
case XLS.Formats[FormatIndex].NumberFormatIndex of
$0B: Result := FloatToStrF(V,ffExponent,3,2);
$0C: Result := FloatToFracStr(V,9);
$0D: Result := FloatToFracStr(V,99);
$0E: Result := DateToStr(V);
$14: Result := FormatDateTime('t',V);
else
Result := DoUserFormat;
end;
end
else
Result := FloatToStr(V);
end;
begin
XLS := TXLSReadWriteII(TSheets(Collection).Owner);
Cell := FCells[ColRowToRC(Col,Row)];
if Cell <> Nil then begin
case Cell.CellType of
ctNone: ;
ctBlank: Result := '';
ctInteger: ;
ctFloat: Result := FormatNumber(TFloatCell(Cell).Value,Cell.FormatIndex);
ctString: Result := TSheets(Collection).FSST[TStringCell(Cell).Value];
ctBoolean: if TBooleanCell(Cell).Value then Result := XLS.StrTRUE else Result := XLS.StrFALSE;
ctError: Result := CellErrorNames[Integer(TErrorCell(Cell).Value)];
ctNumberFormula: if XLS.ShowFormulas then
Result := DecodeFmla(XLS.Version,TNumberFormulaCell(Cell).PTGS,TNumberFormulaCell(Cell).Size,Col,Row,XLS.GetName)
else
Result := FormatNumber(TNumberFormulaCell(Cell).NumberValue,Cell.FormatIndex);
ctStringFormula: if XLS.ShowFormulas then
Result := DecodeFmla(XLS.Version,TStringFormulaCell(Cell).PTGS,TStringFormulaCell(Cell).Size,Col,Row,XLS.GetName)
else
Result := TStringFormulaCell(Cell).StringValue;
ctBooleanFormula: if XLS.ShowFormulas then
Result := DecodeFmla(XLS.Version,TBooleanFormulaCell(Cell).PTGS,TBooleanFormulaCell(Cell).Size,Col,Row,XLS.GetName)
else
if TBooleanFormulaCell(Cell).BooleanValue then Result := XLS.StrTRUE else Result := XLS.StrFALSE;
ctErrorFormula: if XLS.ShowFormulas then
Result := DecodeFmla(XLS.Version,TErrorFormulaCell(Cell).PTGS,TErrorFormulaCell(Cell).Size,Col,Row,XLS.GetName)
else
Result := CellErrorNames[Byte(TErrorFormulaCell(Cell).ErrorValue)];
ctArrayFormula: if XLS.ShowFormulas then
Result := '{ARRAY FORMULA}'
else
Result := FormatNumber(TArrayFormulaCell(Cell).NumberValue,Cell.FormatIndex);
end;
end
else
Result := '';
end;
function TSheet.GetAsHTML(Col, Row: integer): string;
var
i,p,si,fi: integer;
S,S2: string;
Cell: TCell;
XLS: TXLSReadWriteII;
function GetFontIndex(FormatIndex: integer): integer;
begin
if FormatIndex >= 0 then
Result := XLS.Formats[FormatIndex].FontIndex
else
Result := 0;
end;
function PtToHTMLSize(Pt: integer): integer;
begin
case Pt of
0..8:
Result := 1;
9..10:
Result := 2;
11..12:
Result := 3;
13..15:
Result := 4;
16..20:
Result := 5;
21..24:
Result := 6;
else
Result := 7;
end;
end;
function ReplaceSpaces(S: string): string;
var
i,j: integer;
begin
i := 1;
j := 0;
while (i <= Length(S)) and (S[i] = ' ') do begin
Inc(j);
Inc(i);
end;
S := Copy(S,j + 1,MAXINT);
while j > 0 do begin
S := ' ' + S;
Dec(j);
end;
i := Length(S);
j := 0;
while (i >= 1) and (S[i] = ' ') do begin
Inc(j);
Dec(i);
end;
S := Copy(S,1,Length(S) - j);
while j > 0 do begin
S := S + ' ';
Dec(j);
end;
Result := S;
end;
function FontAsHTML(FontIndex: integer; S: string): string;
var
F: TFont;
begin
if S = '' then begin
Result := '';
Exit;
end;
F := TFont.Create;
try
XLS.Fonts[FontIndex].CopyToTFont(F);
finally
S := ReplaceSpaces(S);
S := FastReplace(S,'<','<',True);
S := FastReplace(S,'>','>',True);
if fsBold in F.Style then
S := '<b>' + S + '</b>';
if fsItalic in F.Style then
S := '<i>' + S + '</i>';
if fsUnderline in F.Style then
S := '<u>' + S + '</u>';
if F.Color = 0 then // this is the default font color, don't write it out...
Result := Format('<font face=%s size=%d>%s</font>',[F.Name,PtToHTMLSize(F.Size),S])
else
Result := Format('<font face="%s" color="#%.2X%.2X%.2X" size="%d">%s</font>',[F.Name,F.Color and $0000FF,(F.Color and $00FF00) shr 8,(F.Color and $FF0000) shr 16,PtToHTMLSize(F.Size),S]);
F.Free;
end;
end;
begin
Result := '';
XLS := TXLSReadWriteII(TSheets(Collection).Owner);
Cell := FCells[ColRowToRC(Col,Row)];
if Cell <> Nil then begin
if Cell.CellType = ctString then begin
si := TStringCell(Cell).Value;
if TSheets(Collection).SST.IsFormatted[si] then begin
fi := GetFontIndex(Cell.FormatIndex);
p := 1;
S := TSheets(Collection).SST[si];
for i := 0 to TSheets(Collection).SST.FormatCount[si] - 1 do begin
S2 := Copy(S,p,TSheets(Collection).SST.Format[si,i].Index - p + 1);
if S2 <> '' then
Result := Result + FontAsHTML(fi,S2);
p := TSheets(Collection).SST.Format[si,i].Index + 1;
fi := TSheets(Collection).SST.Format[si,i].FontIndex;
end;
S2 := Copy(S,p,MAXINT);
if S2 <> '' then
Result := Result + FontAsHTML(fi,S2);
end
else
Result := FontAsHTML(GetFontIndex(Cell.FormatIndex),GetFmtAsString(Col,Row));
end
else
Result := FontAsHTML(GetFontIndex(Cell.FormatIndex),GetFmtAsString(Col,Row));
end;
end;
function TSheet.GetAsFormula(Col, Row: integer): string;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) and (Cell is TFormulaCell) then
Result := DecodeFmla(TXLSReadWriteII(TSheets(Collection).Owner).Version,TFormulaCell(Cell).PTGS,TFormulaCell(Cell).Size,Col,Row,TXLSReadWriteII(TSheets(Collection).Owner).GetName)
else
raise Exception.Create(ersCellIsMissingOrIsOfWrongType);
end;
function TSheet.MakeFormulaCell(CellType: TCellType; Data: PByteArray; Size,RC,FI: integer): TFormulaCell;
begin
case CellType of
ctNumberFormula: Result := TNumberFormulaCell.Create(RC,FI,Data,Size);
ctStringFormula: Result := TStringFormulaCell.Create(RC,FI,Data,Size);
ctBooleanFormula: Result := TBooleanFormulaCell.Create(RC,FI,Data,Size);
ctErrorFormula: Result := TErrorFormulaCell.Create(RC,FI,Data,Size);
else
raise Exception.Create(ersInvalidFormulaCellType);
end
end;
procedure TSheet.WriteRawErrFormula(Col, Row, FormatIndex: integer; Data: PByteArray; Len: integer; Value: byte);
var
RC: integer;
Cell: TFormulaCell;
begin
RC := ColRowToRC(Col,Row);
Cell := MakeFormulaCell(ctErrorFormula,Data,Len,RC,FormatIndex);
TErrorFormulaCell(Cell).ErrorValue := ErrorCodeToCellError(Value);
FCells[RC] := Cell;
end;
procedure TSheet.WriteRawBoolFormula(Col, Row, FormatIndex: integer; Data: PByteArray; Len: integer; Value: boolean);
var
RC: integer;
Cell: TFormulaCell;
begin
RC := ColRowToRC(Col,Row);
Cell := MakeFormulaCell(ctBooleanFormula,Data,Len,RC,FormatIndex);
TBooleanFormulaCell(Cell).BooleanValue := Value;
FCells[RC] := Cell;
end;
procedure TSheet.WriteRawNumFormula(Col, Row, FormatIndex: integer; Data: PByteArray; Len: integer; Value: double);
var
RC: integer;
Cell: TFormulaCell;
begin
RC := ColRowToRC(Col,Row);
Cell := MakeFormulaCell(ctNumberFormula,Data,Len,RC,FormatIndex);
TNumberFormulaCell(Cell).NumberValue := Value;
FCells[RC] := Cell;
end;
procedure TSheet.WriteRawStrFormula(Col, Row, FormatIndex: integer; Data: PByteArray; Len: integer; Value: string);
var
RC: integer;
Cell: TFormulaCell;
begin
RC := ColRowToRC(Col,Row);
Cell := MakeFormulaCell(ctStringFormula,Data,Len,RC,FormatIndex);
TStringFormulaCell(Cell).StringValue := Value;
FCells[RC] := Cell;
end;
procedure TSheet.WriteRawArrayFormula(Col, Row, FormatIndex: integer; Data: PByteArray; Len: integer; Value: double; Arr: PByteArray; ArrLen: integer);
var
RC: integer;
Cell: TArrayFormulaCell;
begin
RC := ColRowToRC(Col,Row);
Cell := TArrayFormulaCell.Create(RC,FormatIndex,Data,Len,Arr,ArrLen);
Cell.NumberValue := Value;
FCells[RC] := Cell;
end;
function TSheet.EncodeFormula(F: string; CellType: TCellType; RC,FI: integer): TFormulaCell;
var
Buf: PByteArray;
Size: integer;
begin
if Copy(F,1,1) = '=' then
raise Exception.Create('A formula can not start with "="');
Result := Nil;
GetMem(Buf,TXLSReadWriteII(TSheets(Collection).Owner).MaxBuffSize);
try
Size := TXLSReadWriteII(TSheets(Collection).Owner).FormulaEncoder.Encode(F,Buf,TXLSReadWriteII(TSheets(Collection).Owner).MaxBuffSize);
case CellType of
ctNumberFormula: Result := TNumberFormulaCell.Create(RC,FI,Buf,Size);
ctStringFormula: Result := TStringFormulaCell.Create(RC,FI,Buf,Size);
ctBooleanFormula: Result := TBooleanFormulaCell.Create(RC,FI,Buf,Size);
else
raise Exception.Create(ersInvalidFormulaCellType);
end
finally
FreeMem(Buf);
end;
end;
procedure TSheet.SetAsFormula(Col, Row: integer; const Value: string);
begin
FCells.CellsDefFormat[ColRowToRC(Col,Row)] := EncodeFormula(Value,ctNumberFormula,ColRowToRC(Col,Row),GetDefaultFormat(Col,Row));
end;
function TSheet.GetAsBoolFormulaValue(Col, Row: integer): boolean;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) and (Cell is TBooleanFormulaCell) then
Result := TBooleanFormulaCell(Cell).BooleanValue
else
raise Exception.Create(ersCellIsMissingOrIsOfWrongType);
end;
function TSheet.GetAsNumFormulaValue(Col, Row: integer): double;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) and (Cell is TNumberFormulaCell) then
Result := TNumberFormulaCell(Cell).NumberValue
else
raise Exception.Create(ersCellIsMissingOrIsOfWrongType);
end;
function TSheet.GetAsStrFormulaValue(Col, Row: integer): string;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) and (Cell is TStringFormulaCell) then
Result := TStringFormulaCell(Cell).StringValue
else
raise Exception.Create(ersCellIsMissingOrIsOfWrongType);
end;
procedure TSheet.SetAsBoolFormulaValue(Col, Row: integer; const Value: boolean);
var
RC: integer;
Cell: TCell;
begin
RC := ColRowToRC(Col,Row);
Cell := FCells[RC];
if Cell = Nil then
raise Exception.Create(ersFormulaCellIsMissing)
else begin
if Cell is TBooleanFormulaCell then
TBooleanFormulaCell(Cell).BooleanValue := Value
else
raise Exception.Create(ersFormulaCellIsNotBoolean)
end;
end;
procedure TSheet.SetAsNumFormulaValue(Col, Row: integer; const Value: double);
var
RC: integer;
Cell: TCell;
begin
RC := ColRowToRC(Col,Row);
Cell := FCells[RC];
if Cell = Nil then
raise Exception.Create(ersFormulaCellIsMissing)
else begin
if Cell is TNumberFormulaCell then
TNumberFormulaCell(Cell).NumberValue := Value
else
raise Exception.Create(ersFormulaCellIsNotNumeric)
end;
end;
procedure TSheet.SetAsStrFormulaValue(Col, Row: integer; const Value: string);
var
RC: integer;
Cell: TCell;
begin
RC := ColRowToRC(Col,Row);
Cell := FCells[RC];
if Cell = Nil then
raise Exception.Create(ersFormulaCellIsMissing)
else begin
if Cell is TStringFormulaCell then
TStringFormulaCell(Cell).StringValue := Value
else
raise Exception.Create(ersFormulaCellIsNotString)
end;
end;
function TSheet.GetCellAlignment(Cell: TCell; Format: TCellFormat): TCellHorizAlignment;
begin
Result := chaLeft;
if (Cell.FormatIndex <= 0) or (Format.HorizAlignment = chaGeneral) then begin
case Cell.CellType of
ctInteger: Result := chaRight;
ctFloat: Result := chaRight;
ctString: Result := chaLeft;
ctBoolean: Result := chaCenter;
ctError: Result := chaCenter;
ctNumberFormula: Result := chaRight;
ctStringFormula: Result := chaLeft;
ctBooleanFormula:Result := chaLeft;
ctErrorFormula: Result := chaCenter;
ctArrayFormula: Result := chaRight;
end;
end
else
Result := Format.HorizAlignment;
end;
procedure TSheet.PaintCell(Canvas: TCanvas; ARect: TRect; ACol, ARow: integer);
const
HMARG = 1;
var
XLS: TXLSReadWriteII;
Cell: TCell;
Format: TCellFormat;
S: string;
R: TRect;
TW: integer;
NoteMark: array[0..2] of TPoint;
procedure PaintEmpty;
begin
Canvas.Pen.Style := psClear;
Canvas.Brush.Color := clWhite;
Canvas.Rectangle(R.Left + 1,R.Top + 1,R.Right,R.Bottom);
Canvas.Pen.Style := psSolid;
end;
procedure SetFont;
begin
if Cell.FormatIndex > 0 then
XLS.Fonts[Format.FontIndex].CopyToTFont(Canvas.Font)
else
XLS.Fonts[0].CopyToTFont(Canvas.Font);
end;
procedure PaintBorder(BStyle: TCellBorderStyle; BColor: TExcelColor; X1,Y1,X2,Y2: integer);
begin
if (BStyle <> cbsNone) and (BColor = xcAutomatic) then
BColor := xcBlack;
case BStyle of
cbsNone:
Exit;
cbsThin: begin
Canvas.Pen.Width := 1;
Canvas.Pen.Style := psSolid;
end;
cbsMedium: begin
Canvas.Pen.Width := 2;
Canvas.Pen.Style := psSolid;
end;
cbsDashed: begin
Canvas.Pen.Width := 1;
Canvas.Pen.Style := psDash;
end;
cbsDotted: begin
Canvas.Pen.Width := 1;
Canvas.Pen.Style := psDot;
end;
cbsThick: begin
Canvas.Pen.Width := 3;
Canvas.Pen.Style := psSolid;
end;
cbsDouble: begin
Canvas.Pen.Width := 1;
Canvas.Pen.Style := psSolid;
end;
cbsHair: begin
Canvas.Pen.Width := 1;
Canvas.Pen.Style := psSolid;
end;
cbsMediumDashed: begin
Canvas.Pen.Width := 2;
Canvas.Pen.Style := psDash;
end;
cbsDashDot: begin
Canvas.Pen.Width := 1;
Canvas.Pen.Style := psDashDot;
end;
cbsMediumDashDot: begin
Canvas.Pen.Width := 2;
Canvas.Pen.Style := psDashDot;
end;
cbsDashDotDot: begin
Canvas.Pen.Width := 1;
Canvas.Pen.Style := psDashDotDot;
end;
cbsMediumDashDotDot: begin
Canvas.Pen.Width := 2;
Canvas.Pen.Style := psDashDotDot;
end;
cbsSlantedDashDot: begin
Canvas.Pen.Width := 1;
Canvas.Pen.Style := psDashDot;
end;
end;
Canvas.Pen.Color := TExcelColorPalette[Integer(BColor)];
Canvas.MoveTo(X1,Y1);
Canvas.LineTo(X2,Y2);
end;
procedure PaintBorders;
begin
if Cell.FormatIndex <= 0 then begin
Canvas.Brush.Color := clSilver;
Canvas.FrameRect(R);
end
else begin
PaintBorder(Format.BorderTopStyle,Format.BorderTopColor,R.Left,R.Top,R.Right,R.Top);
PaintBorder(Format.BorderBottomStyle,Format.BorderBottomColor,R.Left,R.Bottom - 1,R.Right,R.Bottom - 1);
PaintBorder(Format.BorderLeftStyle,Format.BorderLeftColor,R.Left,R.Top,R.Left,R.Bottom);
PaintBorder(Format.BorderRightStyle,Format.BorderRightColor,R.Right - 1,R.Top,R.Right - 1,R.Bottom);
end;
end;
begin
XLS := TXLSReadWriteII(TSheets(Collection).Owner);
R := Rect(ARect.Left - 1,ARect.Top - 1,ARect.Right + 1,ARect.Bottom + 1);
Cell := GetCell(ACol,ARow);
if Cell = Nil then begin
PaintEmpty;
Exit;
end;
if Cell.FormatIndex < 0 then
Format := XLS.Formats[0]
else
Format := XLS.Formats[Cell.FormatIndex];
Canvas.Brush.Color := TExcelColorPalette[Integer(Format.FillPatternForeColor)];;
if Cell.CellType <> ctBlank then begin
SetFont;
S := GetFmtAsString(ACol,ARow);
TW := Canvas.TextWidth(S);
// Canvas.Pen
// Canvas.Pen.Color := clBlue;
// Canvas.Rectangle(R);
// Inc(ARect.Top);
if Format.FillPatternPattern <> 0 then begin
Inc(ARect.Right);
Inc(ARect.Bottom);
end;
if (Cell.CellType in TNumCellType) and (TW > (ARect.Right - ARect.Left - HMARG * 2)) then
Canvas.TextRect(ARect,ARect.Left + HMARG,ARect.Top,S)
else begin
case GetCellAlignment(Cell,Format) of
chaLeft: Canvas.TextRect(ARect,ARect.Left + HMARG,ARect.Top - 1,S);
chaCenter: Canvas.TextRect(ARect,ARect.Left + (ARect.Right - ARect.Left) div 2 - TW div 2,ARect.Top,S);
chaRight: Canvas.TextRect(ARect,ARect.Right - HMARG - Canvas.TextWidth(S),ARect.Top,S);
chaFill: ;
chaJustify: ;
chaCenterAcross: ;
end;
end;
end
else begin
Canvas.FillRect(R);
end;
if Notes.FindByRowCol(ColRowToRC(ACol,ARow)) >= 0 then begin
Canvas.Pen.Color := clRed;
Canvas.Brush.Color := clRed;
NoteMark[0].X := R.Right - 6;
NoteMark[0].Y := R.Top;
NoteMark[1].X := R.Right - 1;
NoteMark[1].Y := R.Top;
NoteMark[2].X := R.Right - 1;
NoteMark[2].Y := R.Top + 5;
Canvas.Polygon(NoteMark);
end;
PaintBorders;
Canvas.Pen.Width := 1;
end;
{
procedure TSheet.PaintCell(Canvas: TCanvas; Rect: TRect; Col, Row: integer);
var
Cell: TCell;
S: string;
AlignRight: boolean;
Format: TCellFormat;
procedure SizeRect(var R: TRect; By : integer);
begin
Inc(R.Left,By);
Inc(R.Top,By);
Dec(R.Right,By);
Dec(R.Bottom,By);
end;
procedure PaintCellBorder(FI: integer);
begin
if Format.BorderLeftStyle <> cbsNone then begin
Canvas.Pen.Color := XColorToTColor(Format.BorderLeftColor);
Canvas.MoveTo(Rect.Left,Rect.Top);
Canvas.LineTo(Rect.Left,Rect.Bottom);
end;
if Format.BorderTopStyle <> cbsNone then begin
Canvas.Pen.Color := XColorToTColor(Format.BorderTopColor);
Canvas.MoveTo(Rect.Left,Rect.Top);
Canvas.LineTo(Rect.Right,Rect.Top);
end;
if Format.BorderRightStyle <> cbsNone then begin
Canvas.Pen.Color := XColorToTColor(Format.BorderRightColor);
Canvas.MoveTo(Rect.Right,Rect.Top);
Canvas.LineTo(Rect.Right,Rect.Bottom + 1);
end;
if Format.BorderBottomStyle <> cbsNone then begin
Canvas.Pen.Color := XColorToTColor(Format.BorderBottomColor);
Canvas.MoveTo(Rect.Left,Rect.Bottom);
Canvas.LineTo(Rect.Right + 1,Rect.Bottom);
end;
end;
begin
SizeRect(Rect,-1);
Cell := GetCell(Col,Row);
Canvas.Pen.Color := clSilver;
Canvas.Brush.Color := clWhite;
Canvas.Rectangle(Rect);
S := GetFmtAsString(Col,Row);
AlignRight := False;
if Cell <> Nil then begin
if Cell.FormatIndex >= 0 then begin
Format := TXLSReadWriteII(TSheets(Collection).Owner).Formats[Cell.FormatIndex];
if Format.HorizAlignment <> chaGeneral then
AlignRight := Format.HorizAlignment = chaRight
else
AlignRight := Cell.CellType in [ctRK,ctInteger,ctFloat,ctNumberFormula];
Canvas.Brush.Color := TExcelColorPalette[Integer(Format.FillPatternForeColor)];
Dec(Rect.Right,1);
Dec(Rect.Bottom,1);
PaintCellBorder(Cell.FormatIndex);
end
else if Cell.CellType in [ctRK,ctInteger,ctFloat,ctNumberFormula] then
AlignRight := True;
end;
SizeRect(Rect,1);
if AlignRight then begin
SetTextAlign(Canvas.Handle,TA_RIGHT);
Canvas.TextRect(Rect,Rect.Right - 2,Rect.Top + 2,S);
SetTextAlign(Canvas.Handle,TA_LEFT);
end
else
Canvas.TextRect(Rect,Rect.Left + 2,Rect.Top + 2,S);
end;
}
function TSheet.AutoWidthCol(Col: longword): integer;
var
W,Def,Index: integer;
CurrFi: integer;
XLS: TXLSReadWriteII;
Canvas: TCanvas;
C: TCell;
CF: TColumnFormat;
begin
Canvas := TCanvas.Create;
try
CurrFi := 0;
Canvas.Handle := GetDC(GetDesktopWindow());
XLS := TXLSReadWriteII(TSheets(Collection).Owner);
XLS.Font.CopyToTFont(Canvas.Font);
Result := FDefaultColWidth * Canvas.TextWidth('8');
Def := Result;
FCells.BeginIterate;
repeat
C := FCells.GetNext;
if (C <> Nil) and ((C.RowCol and $000000FF) = Col) then begin
if C.FormatIndex >= 0 then
Index := C.FormatIndex
else
Index := 0;
if XLS.Formats[Index].FontIndex <> CurrFi then begin
CurrFi := XLS.Formats[Index].FontIndex;
XLS.Fonts[CurrFI].CopyToTFont(Canvas.Font);
end;
W := Canvas.TextWidth(GetFmtAsString(Col,C.RowCol shr 8));
if GetCellAlignment(C,XLS.Formats[Index]) = chaRight then
Inc(W,(Canvas.TextWidth(' ') * 110) div 100);
if W > Result then
Result := W;
end;
until (C = Nil);
if Result <> Def then begin
XLS.Font.CopyToTFont(Canvas.Font);
CF := FColumnFormats.ByColumn(Col);
if CF = Nil then
CF := FColumnFormats.Add;
CF.Col1 := Col;
CF.Col2 := Col;
CF.Width := Round(((Result + 4) / Canvas.TextWidth('8')) * 256);
if Assigned(XLS.OnColWidth) then
XLS.OnColWidth(Self,Col,-1,Result + 4);
end;
finally
ReleaseDC(GetDesktopWindow(),Canvas.Handle);
Canvas.Free;
end;
end;
procedure TSheet.AutoWidthCols(Col1,Col2: longword);
var
i: integer;
begin
for i := Col1 to Col2 do
AutoWidthCol(i);
end;
function TSheet.Calculate(Col, Row: integer): Variant;
var
Cell: TCell;
begin
Cell := GetCell(Col,Row);
if (Cell <> Nil) and (Cell is TFormulaCell) then
Result := CalculateFmla(TXLSReadWriteII(TSheets(Collection).Owner),TFormulaCell(Cell).PTGS,TFormulaCell(Cell).Size,Col,Row,Index)
else
Result := '';
end;
procedure TSheet.CalcDimensions;
begin
FCells.CalcDimensions;
FFirstCol := FCells.FirstCol;
FLastCol := FCells.LastCol;
FFirstRow := FCells.FirstRow;
FLastRow := FCells.LastRow;
end;
procedure TSheet.CalcDimensionsEx;
begin
FCells.CalcDimensionsEx;
FFirstCol := FCells.FirstCol;
FLastCol := FCells.LastCol;
FFirstRow := FCells.FirstRow;
FLastRow := FCells.LastRow;
end;
{ THorizPagebreaks }
function THorizPagebreaks.Add: THorizPagebreak;
begin
Result := THorizPagebreak(inherited Add);
end;
constructor THorizPagebreaks.Create(AOwner: TPersistent);
begin
inherited Create(THorizPagebreak);
FOwner := AOwner;
end;
function THorizPagebreaks.GetItem(Index: integer): THorizPagebreak;
begin
Result := THorizPagebreak(inherited Items[Index]);
end;
function THorizPagebreaks.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{ TVertPagebreaks }
function TVertPagebreaks.Add: TVertPagebreak;
begin
Result := TVertPagebreak(inherited Add);
end;
constructor TVertPagebreaks.Create(AOwner: TPersistent);
begin
inherited Create(TVertPagebreak);
FOwner := AOwner;
end;
function TVertPagebreaks.GetItem(Index: integer): TVertPagebreak;
begin
Result := TVertPagebreak(inherited Items[Index]);
end;
function TVertPagebreaks.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{ THorizPagebreak }
constructor THorizPagebreak.Create(Collection: TCollection);
begin
inherited Create(Collection);
FCol2 := 255;
end;
{ TVertPagebreak }
constructor TVertPagebreak.Create(Collection: TCollection);
begin
inherited Create(Collection);
FRow2 := 65535;
end;
function TSheets._GetOwner: TPersistent;
begin
Result := FOwner;
end;
function TSheet.AddROW(Row, Col1, Col2, Height, Options, FormatIndex: word): integer;
var
RD: PRowData;
begin
New(RD);
RD.Row := Row;
RD.Col1 := Col1;
RD.Col2 := Col2;
RD.Height := Height;
RD.Options := Options;
RD.FormatIndex := FormatIndex;
Result := FRows.Add(RD);
end;
procedure TSheet.CopyRows(Sheet: TSheet);
var
i: integer;
var
RD,RDSrc: PRowData;
begin
for i := 0 to FRows.Count - 1 do
FreeMem(Frows[i]);
FRows.Clear;
for i := 0 to Sheet.ROWCount - 1 do begin
New(RD);
RDSrc := PRowData(Sheet.FRows[i]);
Move(RDSrc^,RD^,SizeOf(TRowData));
FRows.Add(RD);
end;
end;
procedure TSheet.GetROW(Index: integer; ARow: PRecROW);
begin
ARow.Row := PRowData(FRows[Index]).Row;
ARow.Col1 := PRowData(FRows[Index]).Col1;
ARow.Col2 := PRowData(FRows[Index]).Col2;
ARow.Height := PRowData(FRows[Index]).Height;
ARow.Options := PRowData(FRows[Index]).Options;
ARow.FormatIndex := PRowData(FRows[Index]).FormatIndex;
ARow.Reserved1 := 0;
ARow.Reserved2 := 0;
end;
function TSheet.ROWCount: integer;
begin
Result := FRows.Count;
end;
function TSheet.GetRowHeight(Index: integer): integer;
var
i: integer;
begin
for i := 0 to FRows.Count - 1 do begin
if PRowData(FRows[i]).Row = Index then begin
Result := PRowData(FRows[i]).Height;
Exit;
end;
end;
Result := 255;
end;
{
Offset Bits Mask Name Contents
0 2-0 07h iOutLevel Outline level of the row
3 08h (Reserved)
4 10h fCollapsed = 1 if the row is collapsed in outlining
5 20h fDyZero = 1 if the row height is set to 0 (zero)
0 6 40h fUnsynced = 1 if the font height and row height are not compatible
7 80h fGhostDirty = 1 if the row has been formatted, even if it contains all blank cells
1 7-0 FFh (Reserved)
}
procedure TSheet.SetRowHeight(Index, Value: integer);
var
i: integer;
begin
for i := 0 to FRows.Count - 1 do begin
if PRowData(FRows[i]).Row = Index then begin
PRowData(FRows[i]).Height := Value;
PRowData(FRows[i]).Options := $0040;
PRowData(FRows[i]).FormatIndex := 15;
Exit;
end;
end;
AddROW(Index,255,255,Value,$0040,15);
end;
procedure TSheet.GroupRows(Row1, Row2: integer);
var
i,Row,Level: integer;
function FindRow(R: integer): integer;
begin
for Result := 0 to FRows.Count - 1 do begin
if PRowData(FRows[Result]).Row = R then
Exit;
end;
Result := -1;
end;
begin
for i := Row1 to Row2 do begin
Row := FindRow(i);
if Row >= 0 then
Level := PRowData(FRows[Row]).Options and $0007
else begin
Row := AddROW(i,1,1,255,$0100,15);
Level := 0;
end;
Inc(Level);
if Level > 7 then
raise Exception.Create('Row grouping level more than 7.');
PRowData(FRows[Row]).Options := PRowData(FRows[Row]).Options + Level;
if (Level + 1) > FRowOutlineGutter then begin
FRowOutlineGutter := Level + 1;
FRowGutter := Level * 29;
end;
end;
end;
function TSheet.GetAsWideString(Col, Row: integer): WideString;
var
Cell: TCell;
begin
Cell := FCells[ColRowToRC(Col,Row)];
if (Cell <> Nil) and (Cell.CellType = ctString) then
Result := TSheets(Collection).FSST.ItemsWide[TStringCell(Cell).Value]
else
Result := GetAsString(Col,Row);
end;
procedure TSheet.SetAsWideString(Col, Row: integer; const Value: WideString);
begin
FCells.CellsDefFormat[ColRowToRC(Col,Row)] := TStringCell.Create(ColRowToRC(Col,Row),GetDefaultFormat(Col,Row),TSheets(Collection).FSST.AddWideString(Value));
end;
{ TPane }
procedure TPane.Clear;
begin
FPaneType := ptNone;
FSplitColX := 0;
FSplitRowY := 0;
FLeftCol := 0;
FTopRow := 0;
end;
function TSheet.IsEmpty: boolean;
begin
FCells.BeginIterate;
Result := FCells.GetNext = Nil;
end;
function TSheets.SheetByName(Name: string): TSheet;
var
i: integer;
begin
for i := 0 to Count - 1 do begin
if AnsiLowercase(Items[i].Name) = Lowercase(Name) then begin
Result := Items[i];
Exit;
end;
end;
Result := Nil;
end;
function TSheet.GetDefaultFormat(Col, Row: integer): integer;
var
i: integer;
begin
for i := 0 to FRows.Count - 1 do begin
if PRowData(FRows[i]).Row = Row then begin
if PRowData(FRows[i]).Col1 > Col then
PRowData(FRows[i]).Col1 := Col;
if PRowData(FRows[i]).Col2 < Col then
PRowData(FRows[i]).Col2 := Col;
Result := PRowData(FRows[i]).FormatIndex;
if Result = DEFAULT_FORMAT then
Break
else
Exit;
end;
end;
for i := 0 to FColumnFormats.Count - 1 do begin
if (Col >= FColumnFormats[i].Col1) and (Col <= FColumnFormats[i].Col2) then begin
Result := FColumnFormats[i].FormatIndex;
Exit;
end;
end;
Result := -1;
end;
end.
|
unit HJYMessages;
interface
ResourceString
Err_ObjNotImpIntf = '对象%s未实现%s接口!';
Err_DontUseTInterfacedObject = '不要用TObjFactory注册TInterfacedObject及其子类实现的接口!';
Err_IntfExists = '接口%s已存在,不能重复注册!';
Err_IntfNotSupport = '对象不支持%s接口!';
Err_IIDsParamIsEmpty = 'TObjFactoryEx注册参数IIDs不能为空!';
Err_IntfNotFound = '未找到%s接口!';
Err_ModuleNotify = '处理Notify方法出错:%s';
Err_InitModule = '处理模块Init方法出错(%s),错误:%s';
Err_ModuleNotExists = '找不到包[%s],无法加载!';
Err_LoadModule = '加载模块[%s]错误:%s';
Err_finalModule = '模块[%s]final错误:%s';
Msg_InitingModule = '正在初始化包[%s]';
Msg_WaitingLogin = '正准备进入系统,请稍等...';
Msg_LoadingModule = '正在加载包[%s]...';
implementation
end.
|
unit LevelSelect;
//tutorial step1: player and target
//the player has an ammo capacity of 5 bullets, and the target heals itself each time the player reloads
//the task: destroy the target. (e.g add more bullets, make the bullets do more damage, change to code to instant kill, jump to the success code, ...)
{$mode objfpc}{$H+}
interface
uses
windows, Classes, SysUtils, gamepanel, guitextobject, staticguiobject, gamebase, player,
target, bullet,Dialogs, Graphics;
type
TLevelSelect=class(TGameBase)
private
fpanel: Tgamepanel;
player: TPlayer;
target1: Ttarget;
target2: Ttarget;
target3: Ttarget;
bullets: array[0..4] of Tbullet; //max 5 bullets on the screen at once
lastshot: qword;
rotatedirection: single;
info: TGUITextObject;
infobutton: TStaticGUIObject;
l1text, l2text, l3text: TGUITextObject;
function infoPopup(sender: tobject): boolean;
function HideInfo(sender: tobject): boolean;
public
level: integer;
procedure gametick(currentTime: qword; diff: integer); override;
procedure render; override;
function KeyHandler(TGamePanel: TObject; keventtype: integer; Key: Word; Shift: TShiftState):boolean; override;
constructor create(p: TGamePanel);
destructor destroy; override;
end;
implementation
uses registry;
function TLevelSelect.KeyHandler(TGamePanel: TObject; keventtype: integer; Key: Word; Shift: TShiftState):boolean;
var
x: boolean;
i: integer;
ct: qword;
begin
if iskeydown(VK_W) and iskeydown(VK_I) and iskeydown(VK_N) then
begin
showMessage('You lose instead!');
ExitProcess(0);
end;
if keventtype=0 then
begin
ct:=GetTickCount64;
if key=vk_space then
begin
if ct<lastshot+100 then exit; //rate limit the amount of bullets
x:=false;
for i:=0 to 4 do
if bullets[i]=nil then
begin
//create a bullet
bullets[i]:=tbullet.create(player);
bullets[i].x:=player.x;
bullets[i].y:=player.y;
bullets[i].rotation:=player.rotation;
x:=true;
lastshot:=ct;
break;
end;
end
else
begin
case key of
VK_LEFT,VK_A: if RotateDirection>=0 then rotatedirection:=-0.1;
VK_RIGHT,VK_D: if RotateDirection<=0 then rotatedirection:=+0.1;
end;
end;
end
else
begin
case key of
VK_LEFT,VK_A: if RotateDirection<0 then rotatedirection:=0;
VK_RIGHT,VK_D: if RotateDirection>0 then rotatedirection:=0;
end;
end;
result:=false;
end;
procedure TLevelSelect.render;
var i: integer;
begin
player.render;
if target1<>nil then target1.render;
if target2<>nil then target2.render;
if target3<>nil then target3.render;
for i:=0 to 4 do
if bullets[i]<>nil then
bullets[i].render;
if info<>nil then
info.render
else
begin
if infobutton<>nil then
infobutton.render;
end;
if l1text<>nil then l1text.render;
if l2text<>nil then l2text.render;
if l3text<>nil then l3text.render;
end;
procedure TLevelSelect.gametick(currentTime: qword; diff: integer);
var
i,j: integer;
begin
if ticking=false then exit;
if player<>nil then
player.rotation:=player.rotation+rotatedirection*diff;
for i:=0 to 4 do
if bullets[i]<>nil then
begin
bullets[i].travel(diff);
if (target1<>nil) and (target1.isdead=false) and bullets[i].checkCollision(target1) then //perhaps use a vector based on old x,y and new x,y
begin
target1.health:=target1.health-24;
if target1.health<=0 then
target1.explode;
freeandnil(bullets[i]);
continue;
end;
if (target2<>nil) and (target2.isdead=false) and bullets[i].checkCollision(target2) then //perhaps use a vector based on old x,y and new x,y
begin
target2.health:=target2.health-24;
if target2.health<=0 then
target2.explode;
freeandnil(bullets[i]);
continue;
end;
if (target3<>nil) and (target3.isdead=false) and bullets[i].checkCollision(target3) then //perhaps use a vector based on old x,y and new x,y
begin
target3.health:=target3.health-24;
if target3.health<=0 then
target3.explode;
freeandnil(bullets[i]);
continue;
end;
if (bullets[i]<>nil) and ((bullets[i].x>1) or (bullets[i].y>1) or (bullets[i].x<-1) or (bullets[i].y<-1)) then
begin
freeandnil(bullets[i]);
//exit;
end;
end;
if (target1<>nil) and target1.isdead and (target1.blownup) then
begin
freeandnil(target1);
level:=1;
ticking:=false;
gamewon();
exit;
end;
if (target2<>nil) and target2.isdead and (target2.blownup) then
begin
freeandnil(target2);
level:=2;
ticking:=false;
gamewon();
exit;
end;
if (target3<>nil) and target3.isdead and (target3.blownup) then
begin
freeandnil(target3);
level:=3;
ticking:=false;
gamewon();
exit;
end;
end;
function TLevelSelect.infoPopup(sender: tobject): boolean;
begin
if info<>nil then exit(false);
info:=TGUITextObject.create(fpanel);
info.firstTextBecomesMinWidth:=true;
info.width:=0.8;
info.height:=0.8;
info.x:=0;
info.y:=0;
info.rotationpoint.x:=0;
info.rotationpoint.y:=0;
info.color:=clBlack;
info.bcolor:=clWhite;
info.backgroundAlpha:=190;
info.font.Size:=9;
info.text:='Level Select:'#13#10'Destroy the target for the specific level.'#13#10' '#13#10'(Click to hide)';
info.OnClick:=@HideInfo;
result:=true;
end;
function TLevelSelect.HideInfo(sender: tobject): boolean;
begin
freeandnil(info);
result:=true;
end;
destructor TLevelSelect.destroy;
begin
if player<>nil then
freeandnil(player);
if target1<>nil then
freeandnil(target1);
if target2<>nil then
freeandnil(target2);
if target3<>nil then
freeandnil(target3);
if infobutton<>nil then
freeandnil(infobutton);
if info<>nil then
freeandnil(info);
if l1text<>nil then
l1text.destroy;
if l2text<>nil then
l2text.destroy;
if l3text<>nil then
l3text.destroy;
inherited destroy;
end;
constructor TLevelSelect.create(p: TGamePanel);
var reg: tregistry;
begin
fpanel:=p;
player:=tplayer.create;
player.x:=0;
player.y:=0.8;
target1:=TTarget.create;
target1.x:=-0.4;
target1.y:=-0.8;
target1.health:=100;
l1text:=TGUITextObject.create(p);
l1text.firstTextBecomesMinWidth:=true;
l1text.textalignment:=taCenter;
l1text.width:=target1.width;
l1text.height:=0.1;
l1text.x:=target1.x;
l1text.y:=target1.y+target1.height;
l1text.rotationpoint.x:=0;
l1text.rotationpoint.y:=1;
l1text.color:=clRed;
l1text.bcolor:=clBlack;
l1text.backgroundAlpha:=190;
l1text.font.Size:=9;
l1text.text:='Level 1';
reg:=tregistry.create;
if reg.OpenKey('\Software\Cheat Engine\GTutorial', false) then
begin
if reg.ValueExists('This does not count as a solution for tutorial 1') then
begin
target2:=TTarget.create;
target2.x:=0;
target2.y:=-0.8;
target2.health:=100;
l2text:=TGUITextObject.create(p);
l2text.firstTextBecomesMinWidth:=true;
l2text.textalignment:=taCenter;
l2text.width:=target2.width;
l2text.height:=0.1;
l2text.x:=target2.x;
l2text.y:=target2.y+target2.height;
l2text.rotationpoint.x:=0;
l2text.rotationpoint.y:=1;
l2text.color:=clRed;
l2text.bcolor:=clBlack;
l2text.backgroundAlpha:=190;
l2text.font.Size:=9;
l2text.text:='Level 2';
end;
end;
reg:=tregistry.create;
if reg.OpenKey('\Software\Cheat Engine\GTutorial', false) then
begin
if reg.ValueExists('This does not count as a solution for tutorial 2') then
begin
target3:=TTarget.create;
target3.x:=0.4;
target3.y:=-0.8;
target3.health:=100;
l3text:=TGUITextObject.create(p);
l3text.firstTextBecomesMinWidth:=true;
l3text.textalignment:=taCenter;
l3text.width:=target1.width;
l3text.height:=0.1;
l3text.x:=target3.x;
l3text.y:=target3.y+target3.height;
l3text.rotationpoint.x:=0;
l3text.rotationpoint.y:=1;
l3text.color:=clRed;
l3text.bcolor:=clBlack;
l3text.backgroundAlpha:=190;
l3text.font.Size:=9;
l3text.text:='Level 3';
end;
end;
infobutton:=TStaticGUIObject.create(p,'infobutton.png',0.1,0.1);
infobutton.rotationpoint.y:=1; //so the bottom will be the y pos
infobutton.x:=-1;
infobutton.y:=1;
infobutton.OnClick:=@infopopup;
infopopup(infobutton);
ticking:=true; //start
level:=1;
end;
end.
|
{
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Livebindings)
@created(29 Nov 2020)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Telegram : @IsaquePinheiro)
}
unit ormbr.vcl.controls;
interface
uses
System.Generics.Collections,
System.Rtti,
System.Classes,
System.SysUtils,
System.Bindings.Expression,
System.Bindings.Helper,
//
Vcl.Controls,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.Mask,
Vcl.ExtCtrls,
//
Winapi.Windows,
//
ormbr.controls.helpers;
type
/// <summary>
/// Interposer Classes TEdit
/// </summary>
TEdit = class(Vcl.StdCtrls.TEdit)
protected
procedure Change; override;
procedure SetName(const NewName: TComponentName); override;
end;
/// <summary>
/// Interposer Classes TMaskEdit
/// </summary>
TMaskEdit = class(Vcl.Mask.TMaskEdit)
protected
procedure Change; override;
procedure SetName(const NewName: TComponentName); override;
end;
/// <summary>
/// Interposer Classes TLabel
/// </summary>
TLabel = class(Vcl.StdCtrls.TLabel)
protected
procedure SetName(const NewName: TComponentName); override;
end;
/// <summary>
/// Interposer Classes TComboBox
/// </summary>
TComboBox = class(Vcl.StdCtrls.TComboBox)
protected
procedure Change; override;
procedure SetName(const NewName: TComponentName); override;
end;
/// <summary>
/// Interposer Classes TMemo
/// </summary>
TMemo = class(Vcl.StdCtrls.TMemo)
protected
procedure Change; override;
procedure SetName(const NewName: TComponentName); override;
end;
/// <summary>
/// Interposer Classes TProgressBar
/// </summary>
TProgressBar = class(Vcl.ComCtrls.TProgressBar)
protected
procedure SetName(const NewName: TComponentName); override;
end;
/// <summary>
/// Interposer Classes TButtonedEdit
/// </summary>
TButtonedEdit = class(Vcl.ExtCtrls.TButtonedEdit)
protected
procedure Change; override;
procedure SetName(const NewName: TComponentName); override;
end;
implementation
{ TEdit }
procedure TEdit.Change;
begin
inherited Change;
if TListControls.ListFieldNames.ContainsKey(Self.Name) then
TBindings.Notify(Self, TListControls.ListFieldNames.Items[Self.Name]);
end;
procedure TEdit.SetName(const NewName: TComponentName);
begin
inherited SetName(NewName);
TListControls.ListComponents.AddOrSetValue(NewName, Self);
end;
{ TLabel }
procedure TLabel.SetName(const NewName: TComponentName);
begin
inherited SetName(NewName);
TListControls.ListComponents.AddOrSetValue(NewName, Self);
end;
{ TMaskEdit }
procedure TMaskEdit.Change;
begin
inherited Change;
if TListControls.ListFieldNames.ContainsKey(Self.Name) then
TBindings.Notify(Self, TListControls.ListFieldNames.Items[Self.Name]);
end;
procedure TMaskEdit.SetName(const NewName: TComponentName);
begin
inherited SetName(NewName);
TListControls.ListComponents.AddOrSetValue(NewName, Self);
end;
{ TComboBox }
procedure TComboBox.Change;
begin
inherited Change;
if TListControls.ListFieldNames.ContainsKey(Self.Name) then
TBindings.Notify(Self, TListControls.ListFieldNames.Items[Self.Name]);
end;
procedure TComboBox.SetName(const NewName: TComponentName);
begin
inherited SetName(NewName);
TListControls.ListComponents.AddOrSetValue(NewName, Self);
end;
{ TProgressBar }
procedure TProgressBar.SetName(const NewName: TComponentName);
begin
inherited SetName(NewName);
TListControls.ListComponents.AddOrSetValue(NewName, Self);
end;
{ TMemo }
procedure TMemo.Change;
begin
inherited Change;
if TListControls.ListFieldNames.ContainsKey(Self.Name) then
TBindings.Notify(Self, TListControls.ListFieldNames.Items[Self.Name]);
end;
procedure TMemo.SetName(const NewName: TComponentName);
begin
inherited SetName(NewName);
TListControls.ListComponents.AddOrSetValue(NewName, Self);
end;
{ TButtonedEdit }
procedure TButtonedEdit.Change;
begin
inherited Change;
if TListControls.ListFieldNames.ContainsKey(Self.Name) then
TBindings.Notify(Self, TListControls.ListFieldNames.Items[Self.Name]);
end;
procedure TButtonedEdit.SetName(const NewName: TComponentName);
begin
inherited SetName(NewName);
TListControls.ListComponents.AddOrSetValue(NewName, Self);
end;
end.
|
unit ManSoy.IniFiles;
interface
uses Winapi.Windows, System.IniFiles, System.RTLConsts;
type
TMSIniFile= class(TIniFile)
public
procedure WriteStruct(const Section, Ident: string; Value: Pointer; Size: Cardinal);
procedure ReadStruct(const Section, Ident: string; Value: Pointer; Size: Cardinal);
end;
implementation
{ TMSIniFile }
procedure TMSIniFile.ReadStruct(const Section, Ident: string; Value: Pointer; Size: Cardinal);
begin
GetPrivateProfileStruct(PChar(Section), PChar(Ident), Value, Size, PChar(FileName))
end;
procedure TMSIniFile.WriteStruct(const Section, Ident: string; Value: Pointer; Size: Cardinal);
begin
if not WritePrivateProfileStruct(PChar(Section), PChar(Ident),
Value, Size, PChar(FileName)) then
raise EIniFileException.CreateResFmt(@SIniFileWriteError, [FileName]);
end;
end.
|
unit UTDMSChannel;
interface
uses
System.SysUtils,System.Classes,System.Generics.Collections,UProperty,UROWDataInfo
;
type
TChannel = class
private
objPath:AnsiString;
rawDataIndex:Integer;
lrawDataInfo:RawDataInfo;
propertyMap :TDictionary<string,TDMSropertys>;
dataList:TList<Variant>;
public
constructor Create();
function getObjPath() :string;
procedure addObj(o:Variant);
function isFull():Boolean;
procedure TypeInfo();
function getRawDataInfo:RawDataInfo;
procedure read(buffer:TFileStream);
end;
implementation
{ Channel }
uses
UTDMSSegment;
constructor TChannel.Create();
begin
inherited create;
dataList:=TList<Variant>.Create;
end;
procedure TChannel.addObj(o:Variant);
begin
dataList.add(o);
end;
function TChannel.getObjPath: string;
begin
Result:= objPath;
end;
function TChannel.getRawDataInfo: RawDataInfo;
begin
result := lrawDataInfo;
end;
function TChannel.isFull: Boolean;
begin
result := (datalist.count = lrawDataInfo.getNumOfValue);
end;
procedure TChannel.read(buffer: TFileStream;adder:TDMSSegment);
var
length:Integer;
nProperty:Integer;
i: Integer;
proper:TDMSropertys ;
bytes:array [0..4] of Byte;
Chars:array of AnsiChar;
begin
buffer.Read(bytes,4);
length := Pinteger(@bytes)^;
SetLength(Chars,length);
buffer.Read(Chars[0],length);
setlength(objpath,length);
Move(Chars[0], objpath[1], length);
Writeln('channel string name is '+objpath);
buffer.Read(bytes,4);
rawDataIndex := Pinteger(@bytes)^;
if rawDataIndex =-1 then //$FFFFFFFF
begin
Writeln('0xFFFFFFFF');
end
else if rawDataIndex = $00000000 then
begin
Writeln('0x00000000');
//lrawDataInfo :=
end
else if (rawDataIndex = $69130000) or (rawDataIndex = $69120000) then
begin
Writeln('(DAMQ ,this format is not supported!');
end
else begin
Writeln('rawDataIndex = ' + inttostr(rawDataIndex));
lrawDataInfo := RawDataInfo.Create();
lrawDataInfo.read(buffer);
end;
//get property
buffer.read(bytes,4);
nProperty:=Pinteger(@bytes)^;
propertyMap := TDictionary<string,TDMSropertys>.create;
for i := 0 to nProperty-1 do
begin
proper := TDMSropertys.create();
proper.read(buffer);
propertyMap.add( proper.getName,proper);
end;
end;
procedure TChannel.TypeInfo;
begin
end;
end.
|
unit UFileBaseInfo;
interface
uses SysUtils, Generics.Collections, UModelUtil, Classes;
type
// 文件 的 基本信息
TFileBaseInfo = class
public
FileName : string;
FileSize : Int64;
LastWriteTime : TDateTime;
public
constructor Create;
procedure SetFileName( _FileName : string );
procedure SetFileInfo( _FileSize : Int64; _LastWriteTime : TDateTime );
procedure SetFileBaseInfo( FileBaseInfo : TFileBaseInfo );
end;
{$Region ' 文件基本信息 ' }
// 临时 文件 信息
TTempFileInfo = class( TFileBaseInfo )
end;
TTempFilePart = TPair< string, TTempFileInfo >;
TTempFileHash = class( TStringDictionary< TTempFileInfo > )end;
TTempFolderHash = class;
// 临时 文件夹 信息
TTempFolderInfo = class( TFileBaseInfo )
public
TempFileHash : TTempFileHash;
TempFolderHash : TTempFolderHash;
public
constructor Create;
destructor Destroy; override;
end;
TTempFolderPart = TPair< string, TTempFolderInfo >;
TTempFolderHash = class( TStringDictionary< TTempFolderInfo > )end;
// 临时 文件副本 信息
TTempCopyInfo = class
public
CopyOwner : string; // 副本的拥有者
Status : string; // 副本的状态
public
constructor Create( _CopyOwner, _Status : string );
end;
TTempCopyPair = TPair< string , TTempCopyInfo >;
TTempCopyHash = class(TStringDictionary< TTempCopyInfo >);
{$EndRegion}
{$Region ' 备份文件信息 ' }
// 临时 备份文件 信息
TTempBackupFileInfo = class( TFileBaseInfo )
public
TempCopyHash : TTempCopyHash;
public
constructor Create;
destructor Destroy; override;
end;
TTempBackupFilePair = TPair< string , TTempBackupFileInfo >;
TTempBackupFileHash = class(TStringDictionary< TTempBackupFileInfo >);
TTempBackupFolderHash = class;
// 临时 备份目录 信息
TTempBackupFolderInfo = class( TFileBaseInfo )
public
TempBackupFileHash : TTempBackupFileHash;
TempBackupFolderHash : TTempBackupFolderHash;
public
constructor Create;
destructor Destroy; override;
end;
TTempBackupFolderPair = TPair< string, TTempBackupFolderInfo >;
TTempBackupFolderHash = class(TStringDictionary< TTempBackupFolderInfo >);
{$EndRegion}
// 过滤信息
TFileFilterInfo = class
public
FilterType : string;
FilterStr : string;
public
constructor Create( _FilterType, _FilterStr : string );
end;
TFileFilterList = class( TObjectList<TFileFilterInfo> )end;
// 备份配置
TBackupConfigInfo = class
public
CopyCount : Integer;
IsBackupupNow, IsDisable : Boolean;
public
IsAuctoSync : Boolean;
SyncTimeType, SyncTimeValue : Integer;
public
IsEncrypt : Boolean;
Password, PasswordHint : string;
public
IsKeepDeleted : Boolean;
KeepEditionCount : Integer;
public
IncludeFilterList : TFileFilterList;
ExcludeFilterList : TFileFilterList;
public
procedure SetCopyCount( _CopyCount : Integer );
procedure SetSyncInfo( _IsAutoSync : Boolean; _SyncTimeType, _SyncTimeValue : Integer );
procedure SetBackupInfo( _IsBackupNow, _IsDisable : Boolean );
procedure SetEncryptInfo( _IsEncrypt : Boolean; _Password, _PasswordHint : string );
procedure SetDeleteInfo( _IsKeepDeleted : Boolean; _KeepEditionCount : Integer );
procedure SetIncludeFilterList( _IncludeFilterList : TFileFilterList );
procedure SetExcludeFilterList( _ExcludeFilterList : TFileFilterList );
destructor Destroy; override;
end;
// 本地备份配置
TLocalBackupConfigInfo = class
public
IsBackupupNow, IsDisable : Boolean;
public
IsAuctoSync : Boolean;
SyncTimeType, SyncTimeValue : Integer;
public
IsKeepDeleted : Boolean;
KeepEditionCount : Integer;
public
IncludeFilterList : TFileFilterList;
ExcludeFilterList : TFileFilterList;
public
DesPathList : TStringList;
public
procedure SetBackupInfo( _IsBackupNow, _IsDisable : Boolean );
procedure SetSyncInfo( _IsAutoSync : Boolean; _SyncTimeType, _SyncTimeValue : Integer );
procedure SetDeleteInfo( _IsKeepDeleted : Boolean; _KeepEditionCount : Integer );
procedure SetIncludeFilterList( _IncludeFilterList : TFileFilterList );
procedure SetExcludeFilterList( _ExcludeFilterList : TFileFilterList );
procedure SetDesPathList( _DesPathList : TStringList );
destructor Destroy; override;
end;
FileFilterUtil = class
public
class function IsFileInclude( FilePath : string; sch : TSearchRec; FilterList : TFileFilterList ): Boolean;
class function IsFileExclude( FilePath : string; sch : TSearchRec; FilterList : TFileFilterList ): Boolean;
public
class function IsFolderInclude( FolderPath : string; FilterList : TFileFilterList ): Boolean;
class function IsFolderExclude( FolderPath : string; FilterList : TFileFilterList ): Boolean;
end;
const
FilterType_SmallThan = 'Smallthan';
FilterType_LargerThan = 'LargerThan';
FilterType_SystemFile = 'SystemFile';
FilterType_HiddenFile = 'HiddenFile';
FilterType_Mask = 'Mask';
FilterType_Path = 'Path';
const
FilterBoolean_Yes = 0;
FilterBoolean_No = 1;
implementation
uses UMyUtil;
{ TFileBaseInfo }
constructor TFileBaseInfo.Create;
begin
FileSize := 0;
LastWriteTime := Now;
end;
procedure TFileBaseInfo.SetFileBaseInfo(FileBaseInfo: TFileBaseInfo);
begin
FileName := FileBaseInfo.FileName;
FileSize := FileBaseInfo.FileSize;
LastWriteTime := FileBaseInfo.LastWriteTime;
end;
procedure TFileBaseInfo.SetFileInfo(_FileSize: Int64;
_LastWriteTime: TDateTime);
begin
FileSize := _FileSize;
LastWriteTime := _LastWriteTime;
end;
procedure TFileBaseInfo.SetFileName(_FileName: string);
begin
FileName := _FileName;
end;
{ TFolderInfo }
constructor TTempFolderInfo.Create;
begin
inherited;
TempFileHash := TTempFileHash.Create;
TempFolderHash := TTempFolderHash.Create;
end;
destructor TTempFolderInfo.Destroy;
begin
TempFolderHash.Free;
TempFileHash.Free;
inherited;
end;
{ TCheckCopyInfo }
constructor TTempCopyInfo.Create(_CopyOwner, _Status: string);
begin
CopyOwner := _CopyOwner;
Status := _Status;
end;
{ TCheckFileInfo }
constructor TTempBackupFileInfo.Create;
begin
inherited Create;
TempCopyHash := TTempCopyHash.Create;
end;
destructor TTempBackupFileInfo.Destroy;
begin
TempCopyHash.Free;
inherited;
end;
{ TCheckFolderInfo }
constructor TTempBackupFolderInfo.Create;
begin
inherited;
TempBackupFileHash := TTempBackupFileHash.Create;
TempBackupFolderHash := TTempBackupFolderHash.Create;
end;
destructor TTempBackupFolderInfo.Destroy;
begin
TempBackupFileHash.Free;
TempBackupFolderHash.Free;
inherited;
end;
{ TFilterInfo }
constructor TFileFilterInfo.Create(_FilterType, _FilterStr: string);
begin
FilterType := _FilterType;
FilterStr := _FilterStr;
end;
{ TBackupConfigInfo }
procedure TBackupConfigInfo.SetCopyCount(_CopyCount: Integer);
begin
CopyCount := _CopyCount;
end;
procedure TBackupConfigInfo.SetDeleteInfo(_IsKeepDeleted: Boolean;
_KeepEditionCount: Integer);
begin
IsKeepDeleted := _IsKeepDeleted;
KeepEditionCount := _KeepEditionCount;
end;
procedure TBackupConfigInfo.SetEncryptInfo(_IsEncrypt: Boolean; _Password,
_PasswordHint: string);
begin
IsEncrypt := _IsEncrypt;
Password := _Password;
PasswordHint := _PasswordHint;
end;
procedure TBackupConfigInfo.SetExcludeFilterList(
_ExcludeFilterList: TFileFilterList);
begin
ExcludeFilterList := _ExcludeFilterList;
end;
procedure TBackupConfigInfo.SetIncludeFilterList(
_IncludeFilterList: TFileFilterList);
begin
IncludeFilterList := _IncludeFilterList;
end;
destructor TBackupConfigInfo.Destroy;
begin
IncludeFilterList.Free;
ExcludeFilterList.Free;
inherited;
end;
procedure TBackupConfigInfo.SetBackupInfo(_IsBackupNow, _IsDisable: Boolean);
begin
IsBackupupNow := _IsBackupNow;
IsDisable := _IsDisable;
end;
procedure TBackupConfigInfo.SetSyncInfo(_IsAutoSync : Boolean;
_SyncTimeType, _SyncTimeValue: Integer);
begin
IsAuctoSync := _IsAutoSync;
SyncTimeType := _SyncTimeType;
SyncTimeValue := _SyncTimeValue;
end;
{ FileFilterUtil }
class function FileFilterUtil.IsFileExclude(FilePath: string; sch: TSearchRec;
FilterList: TFileFilterList): Boolean;
var
i : Integer;
FilterType, FilterStr : string;
FilterInt64 : Int64;
begin
Result := False;
for i := 0 to FilterList.Count - 1 do
begin
FilterType := FilterList[i].FilterType;
FilterStr := FilterList[i].FilterStr;
if FilterType = FilterType_SmallThan then //小于
begin
FilterInt64 := StrToInt64Def( FilterStr, 0 );
if sch.Size < FilterInt64 then // 没有通过空间限制
Result := True;
end
else
if FilterType = FilterType_LargerThan then // 大于
begin
FilterInt64 := StrToInt64Def( FilterStr, 0 );
if sch.Size > FilterInt64 then // 没有通过空间限制
Result := True;
end
else
if FilterType = FilterType_SystemFile then // 系统文件
Result := ( sch.Attr and faSysFile ) = faSysFile
else
if FilterType = FilterType_HiddenFile then // 隐藏文件
Result := ( sch.Attr and faHidden ) = faHidden
else
if FilterType = FilterType_Mask then // Mask
begin
if MyMatchMask.Check( sch.Name, FilterStr ) then
Result := True;
end
else
if FilterType = FilterType_Path then // Select Path
begin
if MyMatchMask.CheckEqualsOrChild( FilePath, FilterStr ) then
Result := True;
end;
// 已经被过滤
if Result then
Exit;
end;
end;
class function FileFilterUtil.IsFileInclude(FilePath : string; sch: TSearchRec;
FilterList: TFileFilterList): Boolean;
var
i : Integer;
FilterType, FilterStr : string;
FilterInt64 : Int64;
HasMask, MaskIn : Boolean;
HasMaskPath, MastInPath : Boolean;
begin
Result := True;
HasMask := False;
MaskIn := False;
HasMaskPath := False;
MastInPath := False;
for i := 0 to FilterList.Count - 1 do
begin
FilterType := FilterList[i].FilterType;
FilterStr := FilterList[i].FilterStr;
if FilterType = FilterType_SmallThan then //小于
begin
FilterInt64 := StrToInt64Def( FilterStr, 0 );
if sch.Size > FilterInt64 then // 没有通过空间限制
Result := False;
end
else
if FilterType = FilterType_LargerThan then // 大于
begin
FilterInt64 := StrToInt64Def( FilterStr, 0 );
if sch.Size < FilterInt64 then // 没有通过空间限制
Result := False;
end
else
if FilterType = FilterType_Mask then // Mask
begin
HasMask := True;
MaskIn := MaskIn or MyMatchMask.Check( sch.Name, FilterStr );
end
else
if FilterType = FilterType_Path then // Select Path
begin
HasMaskPath := True;
MastInPath := MastInPath or MyMatchMask.CheckEqualsOrChild( FilePath, FilterStr );
end;
// 已经被过滤
if not Result then
Exit;
end;
// 没有通过 Mask
if HasMask and not MaskIn then
Result := False;
// 没有通过 MaskPath
if HasMaskPath and not MastInPath then
Result := False;;
end;
class function FileFilterUtil.IsFolderExclude(FolderPath: string;
FilterList: TFileFilterList): Boolean;
var
i : Integer;
FilterType, FilterStr : string;
begin
Result := False;
for i := 0 to FilterList.Count - 1 do
begin
FilterType := FilterList[i].FilterType;
FilterStr := FilterList[i].FilterStr;
if FilterType = FilterType_Path then
begin
if MyMatchMask.CheckEqualsOrChild( FolderPath, FilterStr ) then
Result := True;
end;
if Result then
Break;
end;
end;
class function FileFilterUtil.IsFolderInclude(FolderPath: string;
FilterList: TFileFilterList): Boolean;
var
i : Integer;
FilterType, FilterStr : string;
HasMaskPath, MastInPath : Boolean;
begin
Result := True;
HasMaskPath := False;
MastInPath := False;
for i := 0 to FilterList.Count - 1 do
begin
FilterType := FilterList[i].FilterType;
FilterStr := FilterList[i].FilterStr;
if FilterType = FilterType_Path then
begin
HasMaskPath := True;
MastInPath := MastInPath or MyMatchMask.CheckEqualsOrChild( FolderPath, FilterStr );
end;
end;
// 没有通过 MaskPath
if HasMaskPath and not MastInPath then
Result := False;
end;
{ TLocalBackupConfigInfo }
destructor TLocalBackupConfigInfo.Destroy;
begin
DesPathList.Free;
IncludeFilterList.Free;
ExcludeFilterList.Free;
inherited;
end;
procedure TLocalBackupConfigInfo.SetBackupInfo(_IsBackupNow,
_IsDisable: Boolean);
begin
IsBackupupNow := _IsBackupNow;
IsDisable := _IsDisable;
end;
procedure TLocalBackupConfigInfo.SetDeleteInfo(_IsKeepDeleted: Boolean;
_KeepEditionCount: Integer);
begin
IsKeepDeleted := _IsKeepDeleted;
KeepEditionCount := _KeepEditionCount;
end;
procedure TLocalBackupConfigInfo.SetDesPathList(_DesPathList: TStringList);
begin
DesPathList := _DesPathList;
end;
procedure TLocalBackupConfigInfo.SetExcludeFilterList(
_ExcludeFilterList: TFileFilterList);
begin
ExcludeFilterList := _ExcludeFilterList;
end;
procedure TLocalBackupConfigInfo.SetIncludeFilterList(
_IncludeFilterList: TFileFilterList);
begin
IncludeFilterList := _IncludeFilterList;
end;
procedure TLocalBackupConfigInfo.SetSyncInfo(_IsAutoSync: Boolean;
_SyncTimeType, _SyncTimeValue: Integer);
begin
IsAuctoSync := _IsAutoSync;
SyncTimeType := _SyncTimeType;
SyncTimeValue := _SyncTimeValue;
end;
end.
|
unit Core.ScoreFrame;
interface
uses
System.SysUtils
, System.Classes
, System.Rtti
{Spring}
, Spring
, Spring.DesignPatterns
, Spring.Collections
, Generics.Collections
{BowlingGame}
, Core.BaseInterfaces
, Core.Interfaces
, Core.Observable
, Core.Link
;
type
TScoreFrame = Class;
TScoreFrameFactory = Class(TInterfacedObject, IScoreFrameFactory)
public
function CreateFrame(const AFrameNo: Integer; APrevFrame: IScoreFrame): IScoreFrame;
end;
TScoreFrame = Class(TGameObservable, IScoreFrame)
strict private
FFrameInfo: TFrameInfo;
FGameConfig: IGameConfig;
FPrevFrame: IScoreFrame;
procedure ScoreFrameChanged;
procedure Validate( const ARollInfo: TRollInfo );
strict protected
function GetFrameNo: Integer; virtual;
function GetStatus: TFrameStatus; virtual;
function GetFrameTotal: Integer; virtual;
function GetRolls: IList<TRollInfo>; virtual;
function GetFrameInfo: TFrameInfo; virtual;
function GetPrevFrameInfo: TFrameInfo;
function GetRollTotal: Integer;
public
constructor Create(const AFrameNo: Integer); overload;
constructor Create(const AFrameNo: Integer; APrevFrame: IScoreFrame); overload;
destructor Destroy; override;
procedure AddRollInfo(const ARollInfo: TRollInfo); virtual;
procedure UpdateFrameTotal(const ATotal: Integer); virtual;
procedure AddToFrameTotal(const APins: Integer); virtual;
property FrameNo: Integer read GetFrameNo;
property FrameTotal: Integer read GetFrameTotal;
property RollTotal: Integer read GetRollTotal;
property Rolls: IList<TRollInfo> read GetRolls;
property Status: TFrameStatus read GetStatus;
property FrameInfo: TFrameInfo read GetFrameInfo;
end;
implementation
uses
Spring.Services
, Core.ResourceStrings
;
{ TScoreFrameFactory }
function TScoreFrameFactory.CreateFrame(const AFrameNo: Integer;
APrevFrame: IScoreFrame): IScoreFrame;
begin
Result := TScoreFrame.Create( AFrameNo, APrevFrame );
end;
{ TScoreFrame }
constructor TScoreFrame.Create( const AFrameNo: Integer );
begin
Create( AFrameNo, nil );
end;
constructor TScoreFrame.Create( const AFrameNo: Integer;
APrevFrame: IScoreFrame );
begin
inherited Create;
FPrevFrame := APrevFrame;
FFrameInfo.FrameNo := AFrameNo;
FFrameInfo.FrameTotal := 0;
FFrameInfo.Status := fsNormal;
FFrameInfo.ExtraPinTotal := 0;
FFrameInfo.Rolls := TCollections.CreateList<TRollInfo>;
FGameConfig := ServiceLocator.GetService< IGameConfig >;
end;
destructor TScoreFrame.Destroy;
begin
inherited;
end;
function TScoreFrame.GetPrevFrameInfo: TFrameInfo;
begin
Result := TFrameInfo.Create( 0, 0, fsNormal);
if Assigned( FPrevFrame ) then
Result := FPrevFrame.FrameInfo;
end;
function TScoreFrame.GetFrameInfo: TFrameInfo;
begin
Result := FFrameInfo;
end;
function TScoreFrame.GetFrameNo: Integer;
begin
Result := FFrameInfo.FrameNo;
end;
function TScoreFrame.GetFrameTotal: Integer;
begin
Result := FFrameInfo.FrameTotal;
end;
function TScoreFrame.GetRollTotal: Integer;
begin
Result := FFrameInfo.RollTotal;
end;
function TScoreFrame.GetStatus: TFrameStatus;
begin
Result := FFrameInfo.Status;
end;
function TScoreFrame.GetRolls: IList<TRollInfo>;
begin
Result := FFrameInfo.Rolls;
end;
procedure TScoreFrame.ScoreFrameChanged;
begin
UpdateView( TValue.From( FFrameInfo) );
end;
procedure TScoreFrame.Validate( const ARollInfo: TRollInfo );
var
total: Integer;
begin
total := ( RollTotal + ARollInfo.Pins );
//only 10 pins permitted per roll
if ( ARollInfo.Pins > FGameConfig.MaxPinCountPerRoll ) then
raise EGameInvalidValueException.CreateResFmt(@SInvalidPins, [FGameConfig.MaxPinCountPerRoll]);
//non-last frame
if ( FrameNo < FGameConfig.MaxFrameCount )
and ( total > FGameConfig.MaxPinCountPerRoll ) then
raise EGameInvalidValueException.CreateResFmt(@SInvalidPins, [FGameConfig.MaxPinCountPerRoll]);
//last frame
if ( FrameNo = FGameConfig.MaxFrameCount ) then
begin
//normal status case - two rolls total should be less than 10 if one is less than 10
case Status of
fsNormal:
begin
if ( ( Rolls.Count = 1 ) and ( total > FGameConfig.MaxPinCountPerRoll ) ) then
raise EGameInvalidValueException.CreateResFmt(@SInvalidPins, [FGameConfig.MaxPinCountPerRoll]);
end;
fsSpare:
begin
if ( ( Rolls.Count > 1 ) and ( total > ( 2 * FGameConfig.MaxPinCountPerRoll ) ) ) then
raise EGameInvalidValueException.CreateResFmt(@SInvalidPins, [FGameConfig.MaxPinCountPerRoll]);
end;
fsStrike:
begin
if ( ( Rolls.Count >= 1 ) and ( total > ( 3 * FGameConfig.MaxPinCountPerRoll ) ) ) then
raise EGameInvalidValueException.CreateResFmt(@SInvalidPins, [FGameConfig.MaxPinCountPerRoll]);
end;
end;
end;
end;
procedure TScoreFrame.AddRollInfo( const ARollInfo: TRollInfo );
var
total: Integer;
begin
Validate( ARollInfo );
FFrameInfo.Rolls.Add( ARollInfo );
Inc( FFrameInfo.RollTotal, ARollInfo.Pins );
total := FFrameInfo.RollTotal;
if Assigned( FPrevFrame ) then
total := FPrevFrame.FrameTotal + FFrameInfo.RollTotal;
UpdateFrameTotal( total );
//check for total is spare or strike
if FFrameInfo.RollTotal = FGameConfig.MaxPinCountPerRoll then
begin
//spare
FFrameInfo.Status := fsSpare;
//strike - current roll.pins hit max pin per roll
if ( ARollInfo.Pins = FGameConfig.MaxPinCountPerRoll ) then
FFrameInfo.Status := fsStrike;
end;
ScoreFrameChanged;
end;
procedure TScoreFrame.AddToFrameTotal(const APins: Integer);
begin
Inc( FFrameInfo.ExtraPinTotal, APins );
UpdateFrameTotal( GetPrevFrameInfo.FrameTotal + RollTotal + FFrameInfo.ExtraPinTotal );
end;
procedure TScoreFrame.UpdateFrameTotal( const ATotal: Integer );
begin
FFrameInfo.FrameTotal := ATotal;
ScoreFrameChanged;
end;
end.
|
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Win.ScktComp,
Vcl.ComCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls, System.JSON;
type
TForm2 = class(TForm)
Panel1: TPanel;
Image1: TImage;
Label1: TLabel;
Label2: TLabel;
connecting_status: TLabel;
nickname: TLabel;
Panel2: TPanel;
RichEdit1: TRichEdit;
Panel3: TPanel;
Edit1: TEdit;
Button1: TButton;
ClientSocket1: TClientSocket;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ClientSocket1Connect(Sender: TObject; Socket: TCustomWinSocket);
procedure ClientSocket1Connecting(Sender: TObject;
Socket: TCustomWinSocket);
procedure ClientSocket1Disconnect(Sender: TObject;
Socket: TCustomWinSocket);
procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
procedure Button1Click(Sender: TObject);
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
ClientUserName: RawByteString;
end;
var
Form2: TForm2;
Connected: Boolean = False;
MessageField: TRichEdit;
MessageWriteField: TEdit;
Connecting_Status: TLabel;
Client: TClientSocket;
implementation
{$R *.dfm}
procedure ScrollToEnd(ARichEdit: TRichEdit);
var
isSelectionHidden: Boolean;
begin
with ARichEdit do
begin
SelStart := Perform( EM_LINEINDEX, Lines.Count, 0);//Set caret at end
isSelectionHidden := HideSelection;
try
HideSelection := False;
Perform( EM_SCROLLCARET, 0, 0); // Scroll to caret
finally
HideSelection := isSelectionHidden;
end;
end;
end;
procedure addMessage(Who: String; Text: AnsiString);
var
Title: string;
CurrentTime: string;
begin
Title := Who + ' (' + DateToStr(Date()) + ' ' + TimeToStr(Now()) + '):';
MessageField.SelAttributes.Style := [fsBold];
MessageField.Lines.Add(Title);
MessageField.Lines.Add(Text);
MessageField.Lines.Add('');
ScrollToEnd(MessageField);
MessageWriteField.Clear;
end;
function prepareRequest(UserName: string; Msg: AnsiString = ''): TJSONObject;
var
JSONData: TJSONObject;
begin
JSONData := TJSONObject.Create;
JSONData.AddPair('username', UserName );
JSONData.AddPair('message', Msg);
prepareRequest := JSONData;
end;
procedure sendRequest(Data: TJSONObject);
begin
Client.Socket.SendText(Data.ToString)
end;
procedure TForm2.Button1Click(Sender: TObject);
var
PreparedData: TJSONObject;
begin
if (Connected = False ) OR (Text = '') then Exit;
PreparedData := prepareRequest(ClientUserName, Edit1.Text);
sendRequest(PreparedData);
addMessage('Вы', Edit1.Text);
end;
procedure TForm2.ClientSocket1Connect(Sender: TObject;
Socket: TCustomWinSocket);
var
PreparedData: TJSONObject;
begin
connecting_status.Caption := '';
PreparedData := prepareRequest(ClientUserName);
sendRequest(PreparedData);
Connected := True;
end;
procedure TForm2.ClientSocket1Connecting(Sender: TObject;
Socket: TCustomWinSocket);
begin
connecting_status.Caption := 'Идёт подключение';
end;
procedure TForm2.ClientSocket1Disconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
connecting_status.Caption := 'Disconnected';
Connected := False;
end;
procedure TForm2.ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
connecting_status.Caption := 'Какая-то странная ошибка. Лучше позови Нурхата';
Connected := False;
end;
procedure TForm2.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
var
StringMessage: string;
Action: string;
UserName: string;
MessageFrom: string;
JSONMessage: TJSONObject;
begin
JSONMessage := TJSONObject.Create;
StringMessage := Socket.ReceiveText;
try
JSONMessage.Parse(TEncoding.UTF8.GetBytes(StringMessage), 0);
Action := JSONMessage.GetValue('action').Value;
UserName := JSONMessage.GetValue('username').Value;
MessageFrom := JSONMessage.GetValue('message').Value;
finally
JSONMessage.Free;
end;
addMessage(UserName, MessageFrom);
end;
procedure TForm2.Edit1KeyPress(Sender: TObject; var Key: Char);
var
PreparedData: TJSONObject;
begin
if Ord(Key) = VK_RETURN then
begin
Button1.Click;
end;
end;
procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Client.Socket.Close;
Application.Terminate;
end;
procedure TForm2.FormShow(Sender: TObject);
begin
Connecting_Status := connecting_status;
MessageField := RichEdit1;
MessageWriteField := Edit1;
Client := ClientSocket1;
nickname.Caption := ClientUserName;
Client.Host := '207.180.208.165';
Client.Port := 4141;
Client.Active := True;
end;
end.
|
unit TShapes;
{ Author: Ann Lynnworth, 21 January 1996.
This was written to demonstrate some of the ideas of TComponentExtensions,
a component originally published as part of TPack, by Michael Ax.
To quickly get the idea: add this unit to your Delphi library, go to the
Samples palette and then place a TFramedRedCircle on a form...
Please see _Delphi In-Depth_, edited by Cary Jensen, for a complete
description of this code.
This unit is distributed free of charge.
}
interface
uses
SysUtils
{$IFDEF WIN32}
, Windows
{$ELSE}
, WinTypes
{$ENDIF}
, Messages, Classes, Graphics, Controls, ExtCtrls
, Xtension {from TPack; needed for TComponentExtensions}
;
const
perfectFrameWidth=3; {used by TFrame}
{We are only customizing TFrame so that we can make it 'clear' and have
a perfect width... }
type
TFrame = class(TShape)
public
{ Public declarations }
Constructor Create(aOwner:TComponent); Override;
end;
{ TFramedRedCircle is the "real example." }
type
TFramedRedCircle = class(TShape)
{Add a variable, cx, to "graft on" the functionality. See
xtension.pas for source to TComponentExtensions. }
cx: TComponentExtensions;
private
{ Private declarations }
fFrame:TFrame;
public
{ Public declarations }
Constructor Create(aOwner:TComponent); Override;
Destructor Destroy; Override;
procedure Notification(AComponent: TComponent; Operation: TOperation); Override;
procedure Loaded; Override;
procedure Paint; Override;
published
{ Published declarations }
{ here is the pointer to the other-object that we'll create
automatically. }
property Frame:TFrame read fFrame write fFrame;
end;
procedure Register;
{------------------------------------------------------------------------------}
implementation
Constructor TFrame.Create(aOwner:TComponent);
begin
inherited Create(aOwner);
Brush.Style:=bsClear; {it wouldn't be a frame if you couldn't see through}
Pen.Width:=perfectFrameWidth; {anything > 1 is noticable}
end;
{------------------------------------------------------------------------------}
Constructor TFramedRedCircle.Create(aOwner:TComponent);
begin
inherited Create(aOwner);
cx:= TComponentExtensions.Create(Self);
{We want to do some fancy tricks if and only if we are in the
designer.}
{Here's some code that does NOT work because Delphi hasn't set this yet:
if csDesigning in ComponentState }
{Here's an alternative that DOES work. The tForm Name property is
only set while you're in the designer to aviod duplicate names with
multiple instances of the form. This lets us 'sneak in' some
design-time only code into a component's constructor *before*
Delphi gets around to setting the 'ComponentState' property.}
if aOwner.Name<>'' then begin {aOwner is the Form}
Shape:=stCircle;
Brush.Color:=clRed;
cx.SetIfFoundExactly(fFrame,TFrame);
cx.MakeIfNil(fFrame,TFrame); {create TFrame if none found on form}
{ It is NOT POSSIBLE to set the location of fFrame here because
in this moment, our circle is sitting at 0,0 and has not yet
been moved to its real location, as determined by your click.
Paint is used to accomplish this instead.}
end;
end;
procedure TFramedRedCircle.Paint;
var
goHereLeft, goHereTop:integer;
thisDiameter:integer;
offset:integer;
begin
inherited Paint;
if fFrame<>nil then begin
{offset=how much displacement between frame and circle}
offset:=FFrame.pen.width+1;
goHereLeft:=Left-offset;
goHereTop :=Top-offset;
{base the frame size on circle width}
thisDiameter:=width+(offset*2);
with fFrame do begin
left:=goHereLeft;
top :=goHereTop;
height:=thisDiameter;
width :=thisDiameter;
end;
end;
end;
Destructor TFramedRedCircle.Destroy;
begin
cx.free; {what we create, we must destroy}
inherited Destroy;
end;
procedure TFramedRedCircle.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then begin
cx.NilIfSet(fFrame,AComponent); {disconnect if fFrame is being removed}
end;
end;
procedure TFramedRedCircle.Loaded;
begin
inherited Loaded;
{this is sort of cool; if you run the form, the frame moves into place.}
{i.e. this works even if you get rid of the Paint method. with paint
overridden, there is no need for this piece.}
{if fFrame<>nil then
with fFrame do begin
left:=self.Left-(pen.width+1);
top :=self.Top -(pen.width+1);
end;}
end;
{------------------------------------------------------------------------------}
procedure Register;
begin
RegisterComponents('Samples', [TFramedRedCircle, TFrame]);
end;
end.
{ </PRE> }
|
unit uDM;
interface
uses
System.SysUtils, System.Classes, acPathDialog, sDialogs, Vcl.Dialogs,
System.Actions, Vcl.ActnList, Vcl.XPStyleActnCtrls, Vcl.ActnMan, Vcl.ImgList,
Vcl.Controls, acAlphaImageList, sPageControl, sStatusBar, Vcl.ComCtrls,
uSharedGlobals, uGroup, uProject, uProjectFile, VirtualTrees,
uVisualMASMOptions, BCEditor.Editor, BCCommon.Dialog.Popup.Highlighter.Color,
BCCommon.FileUtils, UITypes, BCEditor.Highlighter;
type
Tdm = class(TDataModule)
iml32x32Icons: TsAlphaImageList;
iml64x64Icons: TsAlphaImageList;
sAlphaImageList1: TsAlphaImageList;
ActionManager1: TActionManager;
actOptions: TAction;
actFileNew32BitWindowsExeAppAddToGroup: TAction;
actAbout: TAction;
actNew32BitWindowsDllApp: TAction;
actNew64BitWindowsExeApp: TAction;
actNew64BitWindowsDllApp: TAction;
actNew16BitDOSComApp: TAction;
actSearchFind: TAction;
actFindInFiles: TAction;
actSearchReplace: TAction;
actSearchAgain: TAction;
actSearchPrevious: TAction;
actGoToLineNumber: TAction;
actWelcomePage: TAction;
actHelpInstallingVisualMASM: TAction;
actGettingStarted: TAction;
actHelloWorldMSDOS: TAction;
actHelloWorldWindows: TAction;
actAskQuestionsProvideFeedback: TAction;
actNew16BitDOSExeApp: TAction;
actNew16BitWindowsExeApp: TAction;
actNew16BitWindowsDllApp: TAction;
actResources: TAction;
actClosePage: TAction;
actAddNewAssemblyFile: TAction;
actViewProjectManager: TAction;
actViewOutput: TAction;
actViewCommandLine: TAction;
actProperties: TAction;
actNewOther: TAction;
actAddNewTextFile: TAction;
actAddToProject: TAction;
actAddNewBatchFile: TAction;
actNewProjectGroup: TAction;
actOpenProject: TAction;
actShowInExplorer: TAction;
actDOSPromnptHere: TAction;
actRemoveFromProject: TAction;
actDeleteFile: TAction;
actSave: TAction;
actAddNewProject: TAction;
actAddExistingProject: TAction;
actNew16BitDOSComAppAddToGroup: TAction;
actEditUndo: TAction;
actEditRedo: TAction;
actEditCut: TAction;
actEditCopy: TAction;
actEditPaste: TAction;
actCopyPath: TAction;
actReopenFile: TAction;
actAssembleFile: TAction;
actProjectBuild: TAction;
actProjectOptions: TAction;
actFileRename: TAction;
actProjectRename: TAction;
actGroupRename: TAction;
actProjectAssemble: TAction;
actProjectSave: TAction;
actProjectSaveAs: TAction;
actGroupSaveAs: TAction;
actFileSaveAs: TAction;
actGroupRemoveProject: TAction;
actGroupSave: TAction;
actProjectRun: TAction;
actFileSaveAll: TAction;
actEditDelete: TAction;
actEditCommentLine: TAction;
actEditSelectAll: TAction;
actFileOpen: TAction;
actProjectMakeActiveProject: TAction;
actFileClose: TAction;
actFileCloseAll: TAction;
actGroupAssembleAllProjects: TAction;
actGroupBuildAllProjects: TAction;
ImageList1: TImageList;
dlgSave: TsSaveDialog;
dlgOpen: TsOpenDialog;
dlgPath: TsPathDialog;
actGroupNewGroup: TAction;
procedure actAddNewAssemblyFileExecute(Sender: TObject);
procedure actGroupNewGroupExecute(Sender: TObject);
procedure actAddNewProjectExecute(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
procedure actAboutExecute(Sender: TObject);
private
FGroup: TGroup;
FVisualMASMOptions: TVisualMASMOptions;
FPopupHighlighterColorDialog: TPopupHighlighterColorDialog;
FHighlighterColorStrings: TStringList;
FHighlighterStrings: TStringList;
FMASMHighlighter: TBCEditorHighlighter;
public
procedure CreateEditor(projectFile: TProjectFile);
procedure Initialize;
procedure SynchronizeProjectManagerWithGroup;
property Group: TGroup read FGroup;
property VisualMASMOptions: TVisualMASMOptions read FVisualMASMOptions;
procedure SaveGroup;
end;
var
dm: Tdm;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
uses
uFrmMain, uFrmNewItems, uFrmAbout;
procedure Tdm.Initialize;
begin
FVisualMASMOptions := TVisualMASMOptions.Create;
FVisualMASMOptions.LoadFile;
FGroup := TGroup.Create(DEFAULT_PROJECTGROUP_NAME);
FHighlighterStrings := GetHighlighters;
FHighlighterColorStrings := GetHighlighterColors;
// FMASMHighlighter := TBCEditorHighlighter.Create(frmMain);
// FMASMHighlighter.LoadFromFile(HIGHLIGHTER_FILENAME);
// FMASMHighlighter.Colors.LoadFromFile(EDITOR_COLORS_FILENAME);
end;
procedure Tdm.SynchronizeProjectManagerWithGroup;
var
project: TProject;
projectFile: TProjectFile;
rootNode: PVirtualNode;
projectNode: PVirtualNode;
fileNode: PVirtualNode;
data: PProjectData;
promptResult: integer;
begin
if FGroup=nil then exit;
if FGroup.Modified then
begin
promptResult := MessageDlg('Save changes?',mtCustom,[mbYes,mbNo,mbCancel], 0);
if promptResult = mrYes then
begin
SaveGroup;
end else if promptResult = mrCancel then
begin
exit;
end;
end;
frmMain.vstProject.BeginUpdate;
frmMain.vstProject.Clear;
// Add the root node
rootNode := frmMain.vstProject.AddChild(nil);
frmMain.vstProject.Expanded[rootNode] := true;
data := frmMain.vstProject.GetNodeData(rootNode);
data^.ProjectId := '';
data^.Name := FGroup.Name;
data^.Level := 0;
data^.FileId := '';
data^.FileSize := 0;
for project in FGroup.Projects.Values do
begin
// Project node
projectNode := frmMain.vstProject.AddChild(rootNode);
frmMain.vstProject.Expanded[projectNode] := true;
data := frmMain.vstProject.GetNodeData(projectNode);
data^.ProjectId := project.Id;
data^.Name := project.Name;
data^.Level := 1;
data^.FileId := '';
data^.FileSize := 0;
data^.ProjectIntId := project.IntId;
// Project Files
for projectFile in project.ProjectFiles.Values do
begin
fileNode := frmMain.vstProject.AddChild(projectNode);
data := frmMain.vstProject.GetNodeData(fileNode);
data^.ProjectId := project.Id;
data^.ProjectIntId := project.IntId;
data^.Name := projectFile.Name;
data^.Level := 2;
data^.FileId := projectFile.Id;
data^.FileSize := projectFile.SizeInBytes;
data^.FileIntId := projectFile.IntId;
end;
end;
frmMain.vstProject.Refresh;
frmMain.vstProject.FullExpand;
frmMain.vstProject.EndUpdate;
if (FGroup <> nil) and (FGroup.ActiveProject <> nil) then
begin
frmMain.tabProject.Caption := FGroup.ActiveProject.Name;
if FGroup.ActiveProject.Modified or ((FGroup.ActiveProject<> nil) and (FGroup.ActiveProject.Modified)) then
frmMain.tabProject.Caption := MODIFIED_CHAR+frmMain.tabProject.Caption;
end;
end;
procedure Tdm.SaveGroup;
begin
//
end;
procedure Tdm.actAboutExecute(Sender: TObject);
begin
frmAbout.ShowModal;
end;
procedure Tdm.actAddNewAssemblyFileExecute(Sender: TObject);
var
projectFile: TProjectFile;
begin
projectFile := TProjectFile.Create(DEFAULT_FILE_NAME);
CreateEditor(projectFile);
end;
procedure Tdm.actAddNewProjectExecute(Sender: TObject);
begin
frmNewItems.AddNewProject(true);
frmNewItems.ShowModal;
end;
procedure Tdm.actGroupNewGroupExecute(Sender: TObject);
begin
// Create the new group
FGroup := TGroup.Create(DEFAULT_PROJECTGROUP_NAME);
SynchronizeProjectManagerWithGroup;
end;
procedure Tdm.CreateEditor(projectFile: TProjectFile);
var
memo: TBCEditor;
tabSheet: TsTabSheet;
statusBar: TsStatusBar;
statusPanel: TStatusPanel;
begin
tabSheet := TsTabSheet.Create(frmMain.sPageControl1);
tabSheet.Caption := projectFile.Name;
if projectFile.Modified then
tabSheet.Caption := MODIFIED_CHAR+tabSheet.Caption;
tabSheet.Tag := projectFile.IntId;
tabSheet.PageControl := frmMain.sPageControl1;
tabSheet.TabMenu := frmMain.popTabs;
projectFile.IsOpen := true;
tabSheet.Hint := projectFile.Path;
tabSheet.ShowHint := true;
// statusBar := TsStatusBar.Create(tabSheet);
// statusBar.Parent := tabSheet;
// statusBar.Align := alBottom;
// statusBar.SizeGrip := false;
// statusBar.Height := 19;
// statusBar.AutoHint := true; // Show hint from menus like the short-cuts
//// statusBar.OnHint := StatusBarHintHandler;
// // Cursor position
// statusPanel := statusBar.Panels.Add;
// statusPanel.Width := 70;
// statusPanel.Alignment := taCenter;
// // MODIFIED status
// statusPanel := statusBar.Panels.Add;
// statusPanel.Width := 70;
// statusPanel.Alignment := taCenter;
// // INSERT status
// statusPanel := statusBar.Panels.Add;
// statusPanel.Width := 70;
// statusPanel.Alignment := taCenter;
// statusPanel.Text := 'Insert';
// // Line count
// statusPanel := statusBar.Panels.Add;
// statusPanel.Width := 130;
// statusPanel.Alignment := taLeftJustify;
// // Regular text
// statusPanel := statusBar.Panels.Add;
// statusPanel.Width := 70;
// statusPanel.Alignment := taLeftJustify;
//memo := TSynMemo.Create(tabSheet);
memo := TBCEditor.Create(tabSheet);
memo.Parent := tabSheet;
memo.Align := alClient;
// case projectFile.ProjectFileType of
// pftASM: memo.Highlighter := synASMMASM;
// pftRC: memo.Highlighter := synRC;
// pftTXT: ;
// pftDLG: ;
// pftBAT: memo.Highlighter := synBat;
// pftINI: memo.Highlighter := synINI;
// pftCPP: memo.Highlighter := synCPP;
// end;
//memo.ActiveLineColor := $002C2923;
// memo.ActiveLineColor := BrightenColor(frmMain.sSkinManager1.GetGlobalColor);
//memo.ActiveLineColor := frmMain.sSkinManager1.GetGlobalColor;
//memo.ActiveLineColor := BrightenColor(frmMain.sSkinManager1.GetHighLightColor(false));
//memo.ActiveLineColor := DarkenColor(frmMain.sSkinManager1.GetHighLightColor(false));
memo.PopupMenu := frmMain.popMemo;
// memo.TabWidth := 4;
//// memo.OnChange := DoOnChangeSynMemo;
memo.Encoding := TEncoding.ANSI;
memo.HelpType := htKeyword;
memo.Highlighter.LoadFromFile(HIGHLIGHTER_FILENAME);
memo.Highlighter.Colors.LoadFromFile(EDITOR_COLORS_FILENAME);
// memo.Highlighter := FMASMHighlighter;
//memo.LoadFromFile(GetHighlighterFileName('JSON.json'));
memo.Lines.Text := memo.Highlighter.Info.General.Sample;
// memo.Scroll.Bars := TScrollStyle.ssBoth;
memo.Minimap.Visible := true;
memo.ShowHint := true;
memo.CodeFolding.Visible := memo.Highlighter.CodeFoldingRangeCount > 0;
// TitleBar.Items[TITLE_BAR_HIGHLIGHTER].Caption := Editor.Highlighter.Name;
memo.MoveCaretToBOF;
// memo.OnStatusChange := SynEditorStatusChange;
// memo.OnSpecialLineColors := SynEditorSpecialLineColors;
// memo.OnKeyDown := SynMemoKeyDown;
// memo.OnMouseCursor := SynMemoMouseCursor;
// memo.OnEnter := SynMemoOnEnter;
// memo.SelectedColor.Background := frmMain.sSkinManager1.GetHighLightColor(true);
// memo.SelectedColor.Foreground := frmMain.sSkinManager1.GetHighLightFontColor(true);
// memo.BookMarkOptions.BookmarkImages := ImageList1;
// memo.Gutter.ShowLineNumbers := true;
// memo.Gutter.DigitCount := 5;
// memo.Gutter.Color := frmMain.sSkinManager1.GetGlobalColor;
// memo.Gutter.Font.Color := frmMain.sSkinManager1.GetGlobalFontColor;
// memo.Gutter.BorderColor := frmMain.sSkinManager1.GetGlobalFontColor;
// memo.Gutter.Gradient := false;
//// memo.Gutter.GradientStartColor := frmMain.sSkinManager1.GetGlobalColor;
//// memo.Gutter.GradientEndColor := clBlack;
// //memo.Gutter.GradientSteps := 200; // 48 = default
// memo.RightEdgeColor := clNone;
// memo.WantTabs := true;
// memo.Options := [eoAutoIndent, eoDragDropEditing, eoEnhanceEndKey,
// eoScrollPastEol, eoShowScrollHint,
// //eoSmartTabs, // eoTabsToSpaces,
// eoSmartTabDelete, eoGroupUndo, eoTabIndent];
// scpDOSCOM.Editor := memo;
// SynCompletionProposal1.Editor := memo;
// SynAutoComplete1.Editor := memo;
// memo.Text := projectFile.Content;
//// memo.Font.Name := 'Tiny';
//// memo.Font.Size := 1;
// FDebugSupportPlugins.AddObject('',TDebugSupportPlugin.Create(memo, projectFile));
frmMain.sPageControl1.ActivePage := tabSheet;
memo.SetFocus;
// UpdateStatusBarForMemo(memo);
end;
procedure Tdm.DataModuleCreate(Sender: TObject);
begin
Initialize;
end;
end.
|
(**
* $Id: dco.framework.Handler.pas 794 2014-04-28 16:00:24Z QXu $
*
* 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 dco.framework.Handler;
interface
uses
superobject { An universal object serialization framework with Json support },
dco.framework.Command;
type
THandleNotificationMethod = procedure(const Params: ISuperObject) of object;
THandleRequestMethod = procedure(const Params: ISuperObject; out Result: ISuperObject) of object;
type
/// <summary>This interface defines a RPC handler.</summary>
IHandler = interface
/// <summary>Returns the identifier of the object.</summary>
function GetId: string;
/// <summary>Pushs a protocol specific message to handling queue.</summary>
procedure Write(const Message_: string);
/// <summary>Registers a notification handler.</summary>
procedure AddNotificationHandler(Command: TCommand.TClassReference; Method: THandleNotificationMethod);
/// <summary>Registers a request handler.</summary>
procedure AddRequestHandler(Command: TCommand.TClassReference; Method: THandleRequestMethod);
end;
implementation
end.
|
unit uGnLinkedList;
interface
uses
SysUtils, uGnEnumerator, uGnStructures;
const
cPageNodeCount = 16;
type
TGnNodeManager = class
strict private
FNodeSize: NativeUInt;
FPageSize: NativeUint;
FPageList: array of Pointer;
FPageListCount: NativeUint;
FFreeNodeHeader: Pointer;
procedure AllocPage;
public
constructor Create(const ANodeCount: NativeUInt);
destructor Destroy; override;
function AllocNode: Pointer;
procedure FreeNode(const ANode: Pointer);
procedure FreeAll;
end;
IGnLinkedList<_T> = interface(IGnList<_T>)
procedure Append(const AData: _T); overload;
procedure Append(const AItemList: array of _T); overload;
procedure Delete;
end;
TGnLinkedList<_T> = class(TInterfacedObject, IGnLinkedList<_T>)
public
type
PLinkedListItem = ^TLinkedListItem;
TLinkedListItem = record
Data: _T;
Next: PLinkedListItem;
Prev: PLinkedListItem;
end;
TEnumeratorSpec = TGnEnumerator<_T, PLinkedListItem>;
IGnLinkedListSpec = IGnLinkedList<_T>;
strict private
FFakeFirst, FFakeLast, FCursor: PLinkedListItem;
FCount: NativeUint;
FNodeManager: TGnNodeManager;
function EnumGetCurrent(const AItem: PLinkedListItem): _T;
function EnumMoveNext(var AItem: PLinkedListItem): Boolean;
function GetCurrent: _T; inline;
function GetCount: NativeUint;
public
constructor Create;
destructor Destroy; override;
function GetEnumerator: TEnumeratorSpec;
procedure Clear;
procedure Append(const AData: _T); overload;
procedure Append(const AItemList: array of _T); overload;
procedure Delete;
function Prev: Boolean;
function Next: Boolean;
function First: Boolean;
function Last: Boolean;
function IsLast: Boolean;
function IsFirst: Boolean;
function IsEmpty: Boolean;
property Current: _T read GetCurrent;
property Count: NativeUint read GetCount;
end;
TGnLinkedList_ShortInt = TGnLinkedList<ShortInt>;
TGnLinkedList_SmallInt = TGnLinkedList<SmallInt>;
TGnLinkedList_Integer = TGnLinkedList<Integer>;
TGnLinkedList_Byte = TGnLinkedList<Byte>;
TGnLinkedList_Word = TGnLinkedList<Word>;
TGnLinkedList_Cardinal = TGnLinkedList<Cardinal>;
implementation
{ TGnNodeManager }
procedure TGnNodeManager.AllocPage;
var
NewPage: Pointer;
i: NativeUint;
begin
Getmem(NewPage, FPageSize);
Inc(FPageListCount);
SetLength(FPageList, FPageListCount);
FPageList[FPageListCount - 1] := NewPage;
FFreeNodeHeader := NewPage;
for i := 0 to cPageNodeCount - 2 do
begin
NativeUInt(NewPage^) := NativeUInt(NewPage) + FNodeSize;
NativeUInt(NewPage) := NativeUInt(NewPage) + FNodeSize;
end;
Pointer(NewPage^) := nil;
end;
function TGnNodeManager.AllocNode: Pointer;
begin
if not Assigned(FFreeNodeHeader) then
AllocPage;
Result := FFreeNodeHeader;
FFreeNodeHeader := Pointer(FFreeNodeHeader^);
end;
procedure TGnNodeManager.FreeNode(const ANode: Pointer);
begin
Pointer(ANode^) := FFreeNodeHeader;
FFreeNodeHeader := ANode;
end;
procedure TGnNodeManager.FreeAll;
var
i: NativeUint;
begin
for i := 0 to FPageListCount - 1 do
Freemem(FPageList[i], FPageSize);
FFreeNodeHeader := nil;
FPageListCount := 0;
end;
constructor TGnNodeManager.Create(const ANodeCount: NativeUInt);
begin
FNodeSize := ANodeCount;
FPageSize := FNodeSize * cPageNodeCount;
end;
destructor TGnNodeManager.Destroy;
var
i: NativeUint;
begin
if FPageListCount > 0 then
for i := 0 to FPageListCount - 1 do
Freemem(FPageList[i], FPageSize);
inherited Destroy;
end;
{ TGnLinkedList<_T> }
function TGnLinkedList<_T>.EnumGetCurrent(const AItem: PLinkedListItem): _T;
begin
Result := AItem^.Data;
end;
function TGnLinkedList<_T>.EnumMoveNext(var AItem: PLinkedListItem): Boolean;
begin
AItem := AItem^.Next;
Result := (AItem <> nil);
end;
function TGnLinkedList<_T>.GetCurrent: _T;
begin
Result := FCursor^.Data;
end;
constructor TGnLinkedList<_T>.Create;
begin
inherited Create;
New(FFakeFirst);
New(FFakeLast);
FFakeFirst^.Next := FFakeLast;
FFakeFirst^.Prev := nil;
FFakeLast^.Prev := FFakeFirst;
FFakeLast^.Next := nil;
FCursor := FFakeFirst;
FNodeManager := TGnNodeManager.Create(SizeOf(TLinkedListItem));
end;
destructor TGnLinkedList<_T>.Destroy;
begin
Clear;
Dispose(FFakeFirst);
Dispose(FFakeLast);
FNodeManager.Destroy;
inherited Destroy;
end;
function TGnLinkedList<_T>.GetEnumerator: TEnumeratorSpec;
begin
Result := TEnumeratorSpec.Create(FFakeFirst, EnumGetCurrent, EnumMoveNext);
end;
function TGnLinkedList<_T>.GetCount: NativeUint;
begin
Result := FCount;
end;
procedure TGnLinkedList<_T>.Clear;
var
Item, TempItem: PLinkedListItem;
begin
Item := FFakeFirst^.Next;
while Item <> FFakeLast do
begin
TempItem := Item;
Item := Item^.Next;
FNodeManager.FreeNode(TempItem);
end;
FFakeFirst^.Next := FFakeLast;
FFakeLast^.Prev := FFakeFirst;
FCursor := nil;
FCount := 0;
end;
procedure TGnLinkedList<_T>.Append(const AData: _T);
var
NewItem: PLinkedListItem;
begin
NewItem := PLinkedListItem(FNodeManager.AllocNode);
NewItem^.Data := AData;
NewItem^.Prev := FFakeLast^.Prev;
FFakeLast^.Prev^.Next := NewItem;
NewItem^.Next := FFakeLast;
FFakeLast^.Prev := NewItem;
Inc(FCount);
end;
procedure TGnLinkedList<_T>.Append(const AItemList: array of _T);
var
NewItem: PLinkedListItem;
NewData: _T;
begin
for NewData in AItemList do
begin
NewItem := PLinkedListItem(FNodeManager.AllocNode);
NewItem^.Data := NewData;
NewItem^.Prev := FFakeLast^.Prev;
FFakeLast^.Prev^.Next := NewItem;
NewItem^.Next := FFakeLast;
FFakeLast^.Prev := NewItem;
Inc(FCount);
end;
end;
procedure TGnLinkedList<_T>.Delete;
var
TempItem: PLinkedListItem;
begin
if Assigned(FCursor) then
begin
FCursor^.Prev^.Next := FCursor^.Next;
FCursor^.Next^.Prev := FCursor^.Prev;
TempItem := FCursor;
FCursor := FCursor^.Next;
FNodeManager.FreeNode(TempItem);
end;
Dec(FCount);
end;
function TGnLinkedList<_T>.Next: Boolean;
begin
if FCursor^.Next <> FFakeLast then
FCursor := FCursor^.Next;
end;
function TGnLinkedList<_T>.Prev: Boolean;
begin
if FCursor^.Prev <> FFakeFirst then
FCursor := FCursor^.Prev;
end;
function TGnLinkedList<_T>.First: Boolean;
begin
FCursor := FFakeFirst^.Next;
end;
function TGnLinkedList<_T>.IsLast: Boolean;
begin
Result := (FCursor = nil) or (FCursor = FFakeLast) or (FCursor^.Next = FFakeLast);
end;
function TGnLinkedList<_T>.IsEmpty: Boolean;
begin
Result := FCount = 0;
end;
function TGnLinkedList<_T>.IsFirst: Boolean;
begin
end;
function TGnLinkedList<_T>.Last: Boolean;
begin
FCursor := FFakeLast^.Prev;
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit dbcbr.metadata.oracle;
interface
uses
SysUtils,
StrUtils,
Variants,
DB,
Generics.Collections,
dbebr.factory.interfaces,
dbcbr.metadata.register,
dbcbr.metadata.extract,
dbcbr.database.mapping,
dbcbr.types.mapping;
type
TCatalogMetadataOracle = class(TCatalogMetadataAbstract)
protected
procedure SetFieldType(var AColumnMIK: TColumnMIK); virtual;
function GetSelectTables: string; override;
function GetSelectTableColumns(ATableName: string): string; override;
function GetSelectPrimaryKey(ATableName: string): string; override;
function GetSelectPrimaryKeyColumns(APrimaryKeyName: string): string; override;
function GetSelectForeignKey(ATableName: string): string; override;
function GetSelectForeignKeyColumns(AForeignKeyName: string): string; overload;
function GetSelectIndexe(ATableName: string): string; override;
function GetSelectIndexeColumns(AIndexeName: string): string; override;
function GetSelectTriggers(ATableName: string): string; override;
function GetSelectChecks(ATableName: string): string; override;
function GetSelectViews: string; override;
function GetSelectSequences: string; override;
function Execute: IDBResultSet;
public
procedure CreateFieldTypeList; override;
procedure GetCatalogs; override;
procedure GetSchemas; override;
procedure GetTables; override;
procedure GetColumns(ATable: TTableMIK); override;
procedure GetPrimaryKey(ATable: TTableMIK); override;
procedure GetIndexeKeys(ATable: TTableMIK); override;
procedure GetForeignKeys(ATable: TTableMIK); override;
procedure GetTriggers(ATable: TTableMIK); override;
procedure GetChecks(ATable: TTableMIK); override;
procedure GetSequences; override;
procedure GetProcedures; override;
procedure GetFunctions; override;
procedure GetViews; override;
procedure GetDatabaseMetadata; override;
end;
implementation
{ TSchemaExtractSQLite }
procedure TCatalogMetadataOracle.CreateFieldTypeList;
begin
if Assigned(FFieldType) then
begin
FFieldType.Clear;
FFieldType.Add('CHAR', ftFixedChar);
FFieldType.Add('BINARY_FLOAT', ftFloat);
FFieldType.Add('BINARY_DOUBLE', ftBCD);
FFieldType.Add('BOOLEAN', ftBoolean);
FFieldType.Add('VARCHAR2', ftString);
FFieldType.Add('NCHAR', ftFixedWideChar);
FFieldType.Add('NVARCHAR', ftWideString);
FFieldType.Add('NVARCHAR2', ftWideString);
FFieldType.Add('NUMBER', ftCurrency);
FFieldType.Add('DATE', ftDateTime);
FFieldType.Add('CLOB', ftMemo);
FFieldType.Add('NCLOB', ftWideMemo);
FFieldType.Add('BLOB', ftOraBlob);
FFieldType.Add('TIMESTAMP', ftTimeStamp);
FFieldType.Add('TIMESTAMP(6)', ftTimeStamp);
FFieldType.Add('FLOAT', ftFloat);
FFieldType.Add('BFILE', ftWideString);
FFieldType.Add('LONG', ftMemo);
FFieldType.Add('UROWID', ftWideString);
FFieldType.Add('ROWID', ftWideString);
{
FFieldType.Add('RAW', ftGuid);
FFieldType.Add('LONG RAW', ftGuid);
}
end;
end;
function TCatalogMetadataOracle.Execute: IDBResultSet;
var
oSQLQuery: IDBQuery;
begin
inherited;
oSQLQuery := FConnection.CreateQuery;
try
oSQLQuery.CommandText := FSQLText;
Exit(oSQLQuery.ExecuteQuery);
except
raise
end;
end;
procedure TCatalogMetadataOracle.GetDatabaseMetadata;
begin
inherited;
GetCatalogs;
end;
procedure TCatalogMetadataOracle.GetCatalogs;
begin
inherited;
FCatalogMetadata.Name := '';
GetSchemas;
end;
procedure TCatalogMetadataOracle.GetChecks(ATable: TTableMIK);
var
oDBResultSet: IDBResultSet;
oCheck: TCheckMIK;
begin
inherited;
FSQLText := GetSelectChecks(ATable.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oCheck := TCheckMIK.Create(ATable);
oCheck.Name := VarToStr(oDBResultSet.GetFieldValue('check_name'));
oCheck.Description := '';
oCheck.Condition := VarToStr(oDBResultSet.GetFieldValue('check_condition'));
ATable.Checks.Add(UpperCase(oCheck.Name), oCheck);
end;
end;
procedure TCatalogMetadataOracle.GetSchemas;
begin
inherited;
FCatalogMetadata.Schema := '';
GetSequences;
GetTables;
end;
procedure TCatalogMetadataOracle.GetTables;
var
oDBResultSet: IDBResultSet;
oTable: TTableMIK;
begin
inherited;
FSQLText := GetSelectTables;
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oTable := TTableMIK.Create(FCatalogMetadata);
oTable.Name := VarToStr(oDBResultSet.GetFieldValue('table_name'));
oTable.Description := VarToStr(oDBResultSet.GetFieldValue('table_description'));
/// <summary>
/// Extrair colunas da tabela
/// </summary>
GetColumns(oTable);
/// <summary>
/// Extrair Primary Key da tabela
/// </summary>
GetPrimaryKey(oTable);
/// <summary>
/// Extrair Foreign Keys da tabela
/// </summary>
GetForeignKeys(oTable);
/// <summary>
/// Extrair Indexes da tabela
/// </summary>
GetIndexeKeys(oTable);
/// <summary>
/// Extrair Checks da tabela
/// </summary>
GetChecks(oTable);
/// <summary>
/// Adiciona na lista de tabelas extraidas
/// </summary>
FCatalogMetadata.Tables.Add(UpperCase(oTable.Name), oTable);
end;
end;
procedure TCatalogMetadataOracle.GetColumns(ATable: TTableMIK);
function ExtractDefaultValue(ADefaultValue: Variant): string;
begin
Result := '';
if ADefaultValue <> Null then
Result := Trim(ADefaultValue);
if Result = '0.000' then
Result := '0';
end;
function ResolveIntegerNullValue(AValue: Variant): Integer;
begin
Result := 0;
if AValue <> Null then
Result := VarAsType(AValue, varInteger);
end;
var
oDBResultSet: IDBResultSet;
oColumn: TColumnMIK;
begin
inherited;
FSQLText := GetSelectTableColumns(ATable.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oColumn := TColumnMIK.Create(ATable);
oColumn.Name := VarToStr(oDBResultSet.GetFieldValue('column_name'));
oColumn.Position := VarAsType(oDBResultSet.GetFieldValue('column_position'), varInteger) -1;
oColumn.Size := ResolveIntegerNullValue(oDBResultSet.GetFieldValue('column_size'));
oColumn.Precision := ResolveIntegerNullValue(oDBResultSet.GetFieldValue('column_precision'));
oColumn.Scale := ResolveIntegerNullValue(oDBResultSet.GetFieldValue('column_scale'));
oColumn.NotNull := VarToStr(oDBResultSet.GetFieldValue('column_nullable')) = 'N';
oColumn.DefaultValue := ExtractDefaultValue(VarToStr(oDBResultSet.GetFieldValue('column_defaultvalue')));
oColumn.Description := VarToStr(oDBResultSet.GetFieldValue('column_description'));
oColumn.TypeName := VarToStr(oDBResultSet.GetFieldValue('column_typename'));
/// <summary>
/// Seta o tipo do campo
/// </summary>
SetFieldType(oColumn);
/// <summary>
/// Resolve Field Type
/// </summary>
GetFieldTypeDefinition(oColumn);
ATable.Fields.Add(FormatFloat('000000', oColumn.Position), oColumn);
end;
end;
procedure TCatalogMetadataOracle.GetPrimaryKey(ATable: TTableMIK);
procedure GetPrimaryKeyColumns(APrimaryKey: TPrimaryKeyMIK);
var
oDBResultSet: IDBResultSet;
oColumn: TColumnMIK;
begin
FSQLText := GetSelectPrimaryKeyColumns(APrimaryKey.Table.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oColumn := TColumnMIK.Create(ATable);
oColumn.Name := VarToStr(oDBResultSet.GetFieldValue('column_name'));
oColumn.Position := VarAsType(oDBResultSet.GetFieldValue('column_position'), varInteger) -1;
oColumn.NotNull := True;
APrimaryKey.Fields.Add(FormatFloat('000000', oColumn.Position), oColumn);
end;
end;
var
oDBResultSet: IDBResultSet;
begin
inherited;
FSQLText := GetSelectPrimaryKey(ATable.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
ATable.PrimaryKey.Name := VarToStr(oDBResultSet.GetFieldValue('pk_name'));
ATable.PrimaryKey.Description := VarToStr(oDBResultSet.GetFieldValue('pk_description'));
/// <summary>
/// Extrai as columnas da primary key
/// </summary>
GetPrimaryKeyColumns(ATable.PrimaryKey);
end;
end;
procedure TCatalogMetadataOracle.SetFieldType(var AColumnMIK: TColumnMIK);
begin
if AColumnMIK.TypeName = 'NUMBER' then
begin
if AColumnMIK.Precision = 0 then
begin
/// (ftSmallint, ftInteger, ftWord, ftLargeint, ftAutoInc, ftLongWord, ftShortint, ftByte);
AColumnMIK.FieldType := ftInteger;
AColumnMIK.Size := 0;
end
else if AColumnMIK.Precision > 0 then
begin
/// (ftFloat, ftCurrency, ftBCD, ftExtended, ftSingle, ftFMTBcd);
AColumnMIK.FieldType := ftCurrency;
end;
Exit
end
else
if MatchText(AColumnMIK.TypeName, ['BLOB','CLOB','NCLOB']) then
AColumnMIK.Size := 0;
inherited SetFieldType(AColumnMIK);
end;
procedure TCatalogMetadataOracle.GetForeignKeys(ATable: TTableMIK);
procedure GetForeignKeyColumns(AForeignKey: TForeignKeyMIK);
var
oDBResultSet: IDBResultSet;
oFromField: TColumnMIK;
oToField: TColumnMIK;
begin
FSQLText := GetSelectForeignKeyColumns(AForeignKey.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
/// <summary>
/// Coluna tabela source
/// </summary>
oFromField := TColumnMIK.Create(ATable);
oFromField.Name := VarToStr(oDBResultSet.GetFieldValue('column_name'));
oFromField.Position := VarAsType(oDBResultSet.GetFieldValue('column_position'), varInteger) -1;
AForeignKey.FromFields.Add(FormatFloat('000000', oFromField.Position), oFromField);
/// <summary>
/// Coluna tabela referencia
/// </summary>
oToField := TColumnMIK.Create(ATable);
oToField.Name := VarToStr(oDBResultSet.GetFieldValue('column_reference'));
oToField.Position := VarAsType(oDBResultSet.GetFieldValue('column_referenceposition'), varInteger) -1;
AForeignKey.ToFields.Add(FormatFloat('000000', oToField.Position), oToField);
end;
end;
var
oDBResultSet: IDBResultSet;
oForeignKey: TForeignKeyMIK;
begin
inherited;
FSQLText := GetSelectForeignKey(ATable.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oForeignKey := TForeignKeyMIK.Create(ATable);
oForeignKey.Name := VarToStr(oDBResultSet.GetFieldValue('fk_name'));
oForeignKey.FromTable := VarToStr(oDBResultSet.GetFieldValue('table_reference'));
oForeignKey.OnUpdate := None;
oForeignKey.OnDelete := GetRuleAction(VarToStr(oDBResultSet.GetFieldValue('fk_deleteaction')));
oForeignKey.Description := VarToStr(oDBResultSet.GetFieldValue('fk_description'));
ATable.ForeignKeys.Add(oForeignKey.Name, oForeignKey);
/// <summary>
/// Gera a lista de campos do foreignkey
/// </summary>
GetForeignKeyColumns(oForeignKey);
end;
end;
procedure TCatalogMetadataOracle.GetFunctions;
begin
inherited;
end;
procedure TCatalogMetadataOracle.GetProcedures;
begin
inherited;
end;
procedure TCatalogMetadataOracle.GetSequences;
var
oDBResultSet: IDBResultSet;
oSequence: TSequenceMIK;
begin
inherited;
FSQLText := GetSelectSequences;
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oSequence := TSequenceMIK.Create(FCatalogMetadata);
oSequence.TableName := VarToStr(oDBResultSet.GetFieldValue('name'));
oSequence.Name := VarToStr(oDBResultSet.GetFieldValue('name'));
oSequence.Description := VarToStr(oDBResultSet.GetFieldValue('description'));
FCatalogMetadata.Sequences.Add(UpperCase(oSequence.Name), oSequence);
end;
end;
procedure TCatalogMetadataOracle.GetTriggers(ATable: TTableMIK);
var
oDBResultSet: IDBResultSet;
oTrigger: TTriggerMIK;
begin
inherited;
FSQLText := GetSelectTriggers(ATable.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oTrigger := TTriggerMIK.Create(ATable);
oTrigger.Name := VarToStr(oDBResultSet.GetFieldValue('name'));
oTrigger.Description := '';
oTrigger.Script := VarToStr(oDBResultSet.GetFieldValue('sql'));
ATable.Triggers.Add(UpperCase(oTrigger.Name), oTrigger);
end;
end;
procedure TCatalogMetadataOracle.GetIndexeKeys(ATable: TTableMIK);
procedure GetIndexeKeyColumns(AIndexeKey: TIndexeKeyMIK);
var
oDBResultSet: IDBResultSet;
oColumn: TColumnMIK;
begin
FSQLText := GetSelectIndexeColumns(AIndexeKey.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oColumn := TColumnMIK.Create(ATable);
oColumn.Name := VarToStr(oDBResultSet.GetFieldValue('column_name'));
oColumn.Position := VarAsType(oDBResultSet.GetFieldValue('column_position'), varInteger) -1;
AIndexeKey.Fields.Add(FormatFloat('000000', oColumn.Position), oColumn);
end;
end;
var
oDBResultSet: IDBResultSet;
oIndexeKey: TIndexeKeyMIK;
begin
inherited;
FSQLText := GetSelectIndexe(ATable.Name);
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oIndexeKey := TIndexeKeyMIK.Create(ATable);
oIndexeKey.Name := VarToStr(oDBResultSet.GetFieldValue('indexe_name'));
oIndexeKey.Unique := VarToStr(oDBResultSet.GetFieldValue('indexe_unique')) = 'UNIQUE';
ATable.IndexeKeys.Add(UpperCase(oIndexeKey.Name), oIndexeKey);
/// <summary>
/// Gera a lista de campos do indexe
/// </summary>
GetIndexeKeyColumns(oIndexeKey);
end;
end;
procedure TCatalogMetadataOracle.GetViews;
var
oDBResultSet: IDBResultSet;
oView: TViewMIK;
begin
inherited;
FSQLText := GetSelectViews;
oDBResultSet := Execute;
while oDBResultSet.NotEof do
begin
oView := TViewMIK.Create(FCatalogMetadata);
oView.Name := VarToStr(oDBResultSet.GetFieldValue('view_name'));
oView.Script := VarToStr(oDBResultSet.GetFieldValue('view_script'));
oView.Description := VarToStr(oDBResultSet.GetFieldValue('view_description'));
FCatalogMetadata.Views.Add(UpperCase(oView.Name), oView);
end;
end;
function TCatalogMetadataOracle.GetSelectPrimaryKey(ATableName: string): string;
begin
Result := ' select rc.constraint_name as pk_name, ' +
' '''' as pk_description ' +
' from user_constraints rc ' +
' where (rc.constraint_type = ''P'') ' +
' and (rc.table_name = ' + QuotedStr(ATableName) + ')' +
' order by rc.constraint_name ';
end;
function TCatalogMetadataOracle.GetSelectPrimaryKeyColumns(APrimaryKeyName: string): string;
begin
Result := ' select c.column_name as column_name, ' +
' c.position as column_position ' +
' from user_constraints t ' +
' inner join user_cons_columns c on c.constraint_name = t.constraint_name ' +
' where (t.constraint_type = ''P'') ' +
' and t.table_name = ' + QuotedStr(APrimaryKeyName) +
' order by t.table_name, ' +
' t.constraint_name, ' +
' c.position ';
end;
function TCatalogMetadataOracle.GetSelectSequences: string;
begin
Result := ' select sequence_name as name, ' +
' '''' as description ' +
' from user_sequences ';
end;
function TCatalogMetadataOracle.GetSelectTableColumns(ATableName: string): string;
begin
Result := ' select c.column_name as column_name, ' +
' c.column_id as column_position, ' +
' c.data_length as column_size, ' +
' c.data_precision as column_precision, ' +
' c.data_scale as column_scale, ' +
' '''' as column_collation, ' +
' c.nullable as column_nullable, ' +
' c.data_default as column_defaultvalue, ' +
' a.comments as column_description, ' +
' c.data_type as column_typename, ' +
' c.character_set_name as column_charset ' +
' from user_tab_cols c' +
' inner join user_col_comments a on a.table_name = c.table_name ' +
' and a.column_name = c.column_name ' +
' where c.table_name in (' + QuotedStr(ATableName) + ') ' +
' order by c.column_id';
end;
function TCatalogMetadataOracle.GetSelectTables: string;
begin
Result := ' select tab.table_name as table_name, ' +
' com.comments as table_description ' +
' from user_tables tab ' +
' inner join user_tab_comments com on com.table_name = tab.table_name ' +
' where tab.table_name not like ''%$%'' ' +
' order by tab.table_name ';
end;
function TCatalogMetadataOracle.GetSelectTriggers(ATableName: string): string;
begin
{ TODO -oISAQUE : Falta checar campos para preencher a classe }
Result := ' select tg.trigger_name, ' +
' tg.table_name, ' +
' tg.trigger_type, ' +
' tg.triggering_event, ' +
' tg.base_object_type, ' +
' tg.column_name, ' +
' tg.referencing_names, ' +
' tg.when_clause, ' +
' tg.status, ' +
' tg.description, tg.trigger_body, ' +
' dbms_metadata.get_ddl(''TRIGGER'', tg.trigger_name) as ddl ' +
' from sys.user_triggers t ' +
' where tg.constraint_name not like ''%$%'' ' +
' and tg.constraint_name not like ''SYS_%'' ' +
' where tg.table_name = ' + QuotedStr(ATableName) +
' order by tg.trigger_name ';
end;
function TCatalogMetadataOracle.GetSelectChecks(ATableName: string): string;
begin
Result := ' select ck.constraint_name as check_name, ' +
' ck.search_condition as check_condition ' +
' from user_constraints ck ' +
' where ck.constraint_type = ''C'' ' +
' and ck.constraint_name not like ''%$%'' ' +
' and ck.constraint_name not like ''SYS_%'' ' +
' and ck.table_name = ' + QuotedStr(ATableName) +
' order by ck.constraint_name ';
end;
function TCatalogMetadataOracle.GetSelectForeignKey(ATableName: string): string;
begin
Result := ' select cons.constraint_name as fk_name, ' +
' '''' as fk_updateaction, ' +
' cons.delete_rule as fk_deleteaction, ' +
' conr.table_name as table_reference, ' +
' cons.r_constraint_name as fk_referencename, ' +
' '''' as fk_description ' +
' from user_constraints cons ' +
' left join user_constraints conr on conr.constraint_name = cons.r_constraint_name ' +
' where cons.table_name in(' + QuotedStr(ATableName) + ') ' +
' and cons.constraint_type in(''U'',''R'') ' +
' order by cons.constraint_name ';
end;
function TCatalogMetadataOracle.GetSelectForeignKeyColumns(AForeignKeyName: string): string;
begin
Result := ' select cols.column_name as column_name, ' +
' cols.position as column_position, ' +
' colr.column_name as column_reference, ' +
' colr.position as column_referenceposition ' +
' from user_constraints cons ' +
' left join user_cons_columns cols on cols.constraint_name = cons.constraint_name ' +
' left join user_cons_columns colr on colr.constraint_name = cons.r_constraint_name ' +
' where cons.constraint_type = ''R'' and cols.position = colr.position ' +
' and cons.constraint_name in(' + QuotedStr(AForeignKeyName) +') ' +
' order by cols.position';
end;
function TCatalogMetadataOracle.GetSelectViews: string;
begin
Result := ' select vw.view_name as view_name, ' +
' dbms_metadata.get_ddl(''VIEW'', vw.view_name) as view_script, ' +
' '''' as view_description, ' +
' from user_views vw';
end;
function TCatalogMetadataOracle.GetSelectIndexe(ATableName: string): string;
begin
Result := ' select idx.index_name as indexe_name, ' +
' idx.uniqueness as indexe_unique, ' +
' '''' as indexe_description ' +
' from user_indexes idx ' +
' inner join user_constraints usc on idx.table_owner = usc.owner(+) ' +
' and idx.index_name = usc.index_name(+) ' +
' and idx.table_name = usc.table_name(+) ' +
' where (usc.constraint_type not in(''P'') or usc.constraint_type is null) ' +
' and idx.index_type not in(''LOB'') ' +
' and idx.table_name in(' + QuotedStr(ATableName) + ') ' +
' order by idx.table_name, idx.index_name';
end;
function TCatalogMetadataOracle.GetSelectIndexeColumns(AIndexeName: string): string;
begin
Result := ' select c.column_name, ' +
' c.column_position, ' +
' case when c.descend = ''DESC'' ' +
' then ''D'' ' +
' else ''A'' ' +
' end as sort_order, ' +
' e.column_expression, ' +
' case when e.column_expression is null ' +
' then 1 ' +
' else 0 ' +
' end as isnull_expression ' +
' from user_ind_columns c, user_ind_expressions e ' +
// ' where c.index_owner = e.index_owner(+) ' +
' where c.index_name = e.index_name(+) ' +
' and c.column_position = e.column_position(+) ' +
' and c.index_name in(' + QuotedStr(AIndexeName) + ') ' +
' order by c.column_position';
end;
initialization
TMetadataRegister.GetInstance.RegisterMetadata(dnOracle, TCatalogMetadataOracle.Create);
end.
|
unit trolimunkalap;
{$mode objfpc}
interface
uses
Classes, SysUtils, FileUtil, IpHtml, LResources, Forms, Controls, Graphics,
Dialogs, ExtCtrls, StdCtrls, ComCtrls, global, database, sqlite3ds, dateutils;
type
{ TfrmTroliMunkalap }
TfrmTroliMunkalap = class(TForm)
btnAlkatreszFelvetel : TButton;
btnAlkatreszTorlesAListabol : TButton;
btnKilepLezarasNelkul : TButton;
btnMunkalapLezarasa : TButton;
btnWorksFelvetel : TButton;
btnWorksTorlesAListabol : TButton;
chkTroliPreventiv : TCheckBox;
cmbAlkatreszek : TComboBox;
cmbWorks : TComboBox;
edtDS7i : TEdit;
edtTroliTipus : TEdit;
edtKarbantarto : TEdit;
GroupBox1 : TGroupBox;
IpHtmlPanel1 : TIpHtmlPanel;
Label1 : TLabel;
Label2 : TLabel;
Label3 : TLabel;
lstFelvettAlkatreszek : TListBox;
lstWorks : TListBox;
memMegjegyzesek : TMemo;
Shape1 : TShape;
Shape2 : TShape;
Shape3 : TShape;
Shape4 : TShape;
tabComment : TTabSheet;
tabMainSheet : TPageControl;
tabUsedParts : TTabSheet;
tabWorks : TTabSheet;
procedure btnAlkatreszFelvetelClick(Sender : TObject);
procedure btnAlkatreszTorlesAListabolClick(Sender : TObject);
procedure btnKilepLezarasNelkulClick(Sender : TObject);
procedure btnMunkalapLezarasaClick(Sender : TObject);
procedure btnWorksFelvetelClick(Sender : TObject);
procedure btnWorksTorlesAListabolClick(Sender : TObject);
procedure FormCloseQuery(Sender : TObject; var CanClose : boolean);
procedure FormShow(Sender : TObject);
private
{ private declarations }
troliJavitasokDataset,troliAlkatreszekDataset,myDataset: TSqlite3Dataset;
bTroliPreventive: boolean; //ha az adott heten kell prevozni a trolit akkor = 1
wWeekNum :word;
public
{ public declarations }
end;
var
frmTroliMunkalap : TfrmTroliMunkalap;
implementation
uses trolijavitas,fomenu;
{ TfrmTroliMunkalap }
procedure TfrmTroliMunkalap.FormCloseQuery(Sender : TObject; var CanClose : boolean);
var
iRet: integer;
sInfo: string;
begin
writeLogMessage('Troli munkalap - kilépés mentés nélkül start : '+userName);
sInfo := 'Figyelem !' + chr(13) + chr(13) +
'Ha most kilép, a munkalap törlésre kerül !' + chr(13) +
'Biztos hogy ki akar lépni ?';
iRet := MessageDlg('Kilépés lezárás nélkül...',sInfo,mtWarning,mbYesNo,0);
if (iRet <> mrYes) then
begin
CanClose := false;
exit;
end ;
CanClose := true;
//writeLogMessage('Trolimunkalap bezárás mentés nélkül - Adatbázisok bezárása START, felhasználó : ' + userName);
//dbClose(troliAlkatreszekDataset);
//dbClose(troliJavitasokDataset);
//writeLogMessage('Trolimunkalap bezárás mentés nélkül - Adatbázisok bezárása OK, felhasználó : ' + userName);
frmTroliMunkalap.Hide;
frmMainMenu.Show;
end;
procedure TfrmTroliMunkalap.btnWorksFelvetelClick(Sender : TObject);
var
iWorkID,i,iTempID: integer;
begin
//Elvégzett munka felvétele a listába (lstWorks)
//Az elvégzett munkából csak egyet szabad felvinni !
iWorkID:=integer(cmbWorks.Items.Objects[cmbWorks.ItemIndex]);
for i := 0 to lstWorks.Items.Count -1 do
begin
iTempID := integer(lstWorks.Items.Objects[i]);
if (iWorkID = iTempID) then
begin
ShowMessage('A következő javítás már szerepel a listában :' + #10 + #10 +
cmbWorks.Text);
exit;
end;
end;
writeLogMessage('Troli munka hozzáadása : ' + cmbWorks.Text + ' ...Felhasználó : '+userName);
lstWorks.Items.AddObject(cmbWorks.Text,TObject(iWorkID));
lstWorks.Refresh;
end;
procedure TfrmTroliMunkalap.btnWorksTorlesAListabolClick(Sender : TObject);
begin
//Kiválasztott munka törlése a listából :
if (lstWorks.ItemIndex < 0) then exit;
lstWorks.Items.Delete(lstWorks.ItemIndex);
lstWorks.Refresh;
end;
procedure TfrmTroliMunkalap.btnAlkatreszFelvetelClick(Sender : TObject);
var
iPartID: integer;
begin
//Alkatrész felvétele a listába (lstFelvettAlkatreszek)
//Ha egy alk.-ből többet is felhasznált,akkor azt többször kell felvinni a listába !
iPartID:=integer(cmbAlkatreszek.Items.Objects[cmbAlkatreszek.ItemIndex]);
lstFelvettAlkatreszek.Items.AddObject(cmbAlkatreszek.Text,TObject(iPartID));
lstFelvettAlkatreszek.Refresh;
writeLogMessage('Troli alkatrész hozzáadása : ' + cmbAlkatreszek.Text + ' ...Felhasználó : '+userName);
//ShowMessage(inttostr(iPartID));
end;
procedure TfrmTroliMunkalap.btnAlkatreszTorlesAListabolClick(Sender : TObject);
begin
//Kiválasztott alkatrész törlése a listából :
if (lstFelvettAlkatreszek.ItemIndex < 0) then exit;
lstFelvettAlkatreszek.Items.Delete(lstFelvettAlkatreszek.ItemIndex);
lstFelvettAlkatreszek.Refresh;
end;
procedure TfrmTroliMunkalap.btnKilepLezarasNelkulClick(Sender : TObject);
begin
frmTroliMunkalap.Close;
end;
procedure TfrmTroliMunkalap.btnMunkalapLezarasaClick(Sender : TObject);
var
sDate: string;
sInfo: AnsiString;
iRepairID: Integer; //munkalap adatbázis ID!
i: Integer; //ciklusokhoz
iTempID,iRet: Integer;
begin
//Lett felvíve munka?
if (lstWorks.Count = 0) then
begin
ShowMessage('Az elvégzett munkák közül legalább egyet fel kell venni a listába !');
cmbWorks.SetFocus;
exit;
end;
//Ha az adott troli ki van irva a hetre prevora es nem lett bepipalva akkor feldobjuk a lehetoseget:
if (bTroliPreventive = true and chkTroliPreventiv.Checked = false) then
begin
sInfo := 'Figyelem !' + chr(13) + chr(13) +
'A troli (sorszám: ' + IntToStr(iTroliNumber) + ') erre a hétre ki van írva preventív karbantartásra!' + chr(13) +
'Megtörtént a preventív?';
iRet := MessageDlg('Troli preventív megerősítés...',sInfo,mtInformation,mbYesNo,0);
if (iRet = mrYes) then chkTroliPreventiv.Checked := true;
end;
//Biztos hogy az adatok rendben vannak?
sInfo := 'Figyelem !' + chr(13) + chr(13) +
'A munkalap lezárása után már nincs lehetőség a munkalap adatainak módosítására !' + chr(13) +
'Biztos hogy lezárja a munkalapot ?';
iRet := MessageDlg('Munkalap lezárás megerősítés...',sInfo,mtInformation,mbYesNo,0);
if (iRet <> mrYes) then exit;
try
try
//writeLogMessage('Troli munkalap hozzáadása...');
sDate := FormatDateTime('YYYY-MM-DD',Now); //'2010-04-25';
myDataset := dbConnect('trolley_repair','SELECT * FROM trolley_repair ORDER BY id;','id');
with myDataset do
begin
Insert;
FieldByName('u_id').AsInteger := userDB_ID;
FieldByName('tr_date').AsString := sDate;
FieldByName('tr_comment').AsString := memMegjegyzesek.Text;
FieldByName('tr_end').AsInteger := 1;
FieldByName('tr_del').AsInteger := 0;
FieldByName('tr_type').AsInteger := iTroliTipus;
FieldByName('tr_ds7i').AsString := DS7i;
FieldByName('tr_lineid').AsInteger := iLineID;
FieldByName('tr_machine').AsInteger := iMachineID;
FieldByName('tr_wd_num').AsString := sOperatorWDNum;
FieldByName('tr_op_name').AsString := sOperatorName;
FieldByName('tr_position').AsInteger := iTroliPosition;
FieldByName('tr_number').AsInteger := iTroliNumber;
FieldByName('tr_e_date').AsString := sKirakasDatuma;
if (chkTroliPreventiv.Checked) then
FieldByName('tr_preventiv').AsInteger := 1
else
FieldByName('tr_preventiv').AsInteger := 0;
Post;
ApplyUpdates;
end;
except
on E: Exception do
begin
sInfo := 'TfrmTroliMunkalap.btnMunkalapLezarasaClick - '+e.Message + chr(13) +
'userDB_ID : ' + IntToStr(userDB_ID) + chr(13) +
'sDate : ' + sDate + chr(13) +
'memMegjegyzesek : ' + memMegjegyzesek.Text + chr(13) +
'iTroliTipus : ' + IntToStr(iTroliTipus) + chr(13) +
'DS7i : ' + DS7i + chr(13) +
'iLineID : ' + IntToStr(iLineID) + chr(13) +
'iMachineID : ' + inttostr(iMachineID) + chr(13) +
'sOperatorWDNum : ' + sOperatorWDNum + chr(13) +
'sOperatorName : ' + sOperatorName + chr(13) +
'iTroliPosition : ' + IntToStr(iTroliPosition);
//writeLogMessage(sInfo);
end;
end;
finally
dbClose(myDataset)
end;
Sleep(500);
//Kell az új munkalap azonosítója :
try
try
writeLogMessage('Troli munkalap azonosító lekérdezése...');
myDataset := dbConnect('trolley_repair','SELECT * FROM trolley_repair WHERE tr_ds7i = "' + DS7i + '" AND u_id = '
+ IntToStr(userDB_ID) + ' ORDER BY id;','id');
myDataset.Last;
iRepairID := myDataset.FieldByName('id').AsInteger;
except
on E: Exception do
begin
sInfo := 'Kell az új munkalap azonosítója :' + chr(13) +
'TfrmTroliMunkalap.btnMunkalapLezarasaClick - '+e.Message + chr(13) +
'userDB_ID : ' + IntToStr(userDB_ID) + chr(13) +
'SQL : ' + 'SELECT * FROM trolley_repair WHERE tr_ds7i = "' + DS7i +
'" AND u_id = ' + IntToStr(userDB_ID) + ' ORDER BY id;';
writeLogMessage(sInfo);
end;
end;
finally
dbClose(myDataset)
end;
//Felhasznált alkatrészek bejegyzése :
try
try
writeLogMessage('Troli felhasznált alkatrészek bejegyzése...');
myDataset := dbConnect('used_trolley_parts','SELECT * FROM used_trolley_parts ORDER BY id;','id');
for i := 0 to lstFelvettAlkatreszek.Items.Count - 1 do
begin
iTempID := Integer(lstFelvettAlkatreszek.Items.Objects[i]);
with myDataset do
begin
Insert;
FieldByName('t_p_id').AsInteger := iTempID;
FieldByName('t_r_id').AsInteger := iRepairID;
Post;
ApplyUpdates;
end;
end;
except
on E: Exception do
begin
sInfo := 'Felhasznált alkatrészek bejegyzése :' + chr(13) +
'TfrmTroliMunkalap.btnMunkalapLezarasaClick - '+e.Message + chr(13) +
't_p_id : ' + IntToStr(iTempID) + chr(13) +
't_r_id : ' + IntToStr(iRepairID) + chr(13) +
'lstFelvettAlkatreszek.Items.Count : ' + IntToStr(lstFelvettAlkatreszek.Items.Count) + chr(13) +
'SQL : ' + 'SELECT * FROM used_trolley_parts ORDER BY id;';
writeLogMessage(sInfo);
end;
end;
finally
dbClose(myDataset)
end;
Sleep(500);
//Elvégzett javítások bejegyzése :
try
try
writeLogMessage('Troli elvégzett javítások hozzáadása...');
myDataset := dbConnect('trolley_works','SELECT * FROM trolley_works ORDER BY id;','id');
for i := 0 to lstWorks.Items.Count - 1 do
begin
iTempID := Integer(lstWorks.Items.Objects[i]);
with myDataset do
begin
Insert;
FieldByName('t_r_code_id').AsInteger := iTempID;
FieldByName('r_id').AsInteger := iRepairID;
Post;
ApplyUpdates;
end;
end;
except
on E: Exception do
begin
sInfo := 'Elvégzett javítások bejegyzése :' + chr(13) +
'TfrmTroliMunkalap.btnMunkalapLezarasaClick - '+e.Message + chr(13) +
't_r_code_id : ' + IntToStr(iTempID) + chr(13) +
'r_id : ' + IntToStr(iRepairID) + chr(13) +
'lstWorks.Items.Count : ' + IntToStr(lstWorks.Items.Count) + chr(13) +
'SQL : ' + 'SELECT * FROM trolley_works ORDER BY id;';
writeLogMessage(sInfo);
end;
end;
finally
dbClose(myDataset)
end;
Sleep(500);
//Ha preventiv volt a trolin akkor frissiteni kell a trolley_preventive -tablat is az aktualis heten!!
try
//writeLogMessage('Troli preventív bejegyzése...');
if (chkTroliPreventiv.Checked) then
begin
myDataset := dbConnect('trolley_preventive','update trolley_preventive set tr_p_ok = 1 ' +
'where tr_p_ds7i = "' + IntToStr(iTroliNumber) + '" and tr_p_week = ' + IntToStr(wWeekNum) + ';','id');
dbClose(myDataset);
end;
except
on e: Exception do
begin
dbClose(myDataset);
sInfo := 'Troli preventív bejegyzése :' + chr(13) +
'TfrmTroliMunkalap.btnMunkalapLezarasaClick - '+e.Message + chr(13) +
'chkTroliPreventiv.Checked : ';
if (chkTroliPreventiv.Checked) then
sInfo:=sInfo+'true'
else
sInfo:=sInfo+'false';
//writeLogMessage(sInfo);
end;
end;
//Az újonan nyitott munkalap lezárva :
writeLogMessage('Troli munkalap lezárásra került....Felhasználó : ' + userName);
ShowMessage('A munkalap sikeresen lezárásra került !');
frmTroliMunkalap.Hide;
frmMainMenu.Show;
end;
procedure TfrmTroliMunkalap.FormShow(Sender : TObject);
type
rFAdatok = record
sDS7i :string;
sUname :string;
sWorks :array of string;
sParts :array of string;
sCost :string;
sComment :string;
sDate :string; //Javítás dátuma
bPreventiv :Boolean; //Ha preventí volt akkor = true
end ;
var
i,j,it,iRows,iActualRow :integer;
sData,sSQL,sMelok,sTroliPreventiv :String;
aTroliAdatok :array of rFAdatok;
iTad,iPartsNum,iWorksNum,iTworkID :integer;
worksDataset,partsDataset,preventiveDataset :TSqlite3Dataset;
rPartsCost,rtCost :double;
sTroliInfos :AnsiString;
begin
writeLogMessage('Troli munkalap megjelenítése....Felhasználó : ' + userName);
//Mezők beállítása:
edtKarbantarto.Text := userName;
edtDS7i.Text := IntToStr(iTroliNumber); //DS7i;
edtTroliTipus.Text := sTroliTipus;
cmbWorks.Clear;
lstWorks.Clear;
lstWorks.Sorted := false;
cmbAlkatreszek.Clear;
lstFelvettAlkatreszek.Clear;
lstFelvettAlkatreszek.Sorted := false;
memMegjegyzesek.Text := '';
chkTroliPreventiv.Checked := false;
chkTroliPreventiv.Enabled := false;
tabWorks.Show;
wWeekNum:=WeekOfTheYear(Now); //aktualis het...
troliJavitasokDataset := dbConnect('trolley_r_c','SELECT * FROM trolley_r_c;','id');
sSQL := 'select * from parts where p_type = ' + IntToStr(iTroliTipus + 5) + ' and p_del = 0;';
troliAlkatreszekDataset := dbConnect('parts',sSQL,'id');
myDataset := dbConnect('trolley_repair','SELECT * FROM trolley_repair WHERE tr_del=0;','id');
worksDataset := dbConnect('trolley_works','select * from trolley_works','id');
partsDataset := dbConnect('used_trolley_parts','select * from used_trolley_parts','id');
//Ha van az adott hetre preventive ehez a trolihoz akkor mehet a pipa...
bTroliPreventive := false;
preventiveDataset := dbConnect('trolley_preventive','select * from trolley_preventive where tr_p_week = ' +
IntToStr(wWeekNum) + ' and tr_p_ds7i = "' + IntToStr(iTroliNumber) + '" and tr_p_ok = 0;','id');
if (preventiveDataset.RecordCount > 0) then
begin
chkTroliPreventiv.Checked := true;
chkTroliPreventiv.Enabled := true;
bTroliPreventive := true;
end;
//Elvégzendő javítások feltöltése :
Repeat
sData := troliJavitasokDataset.FieldByName('tr_r_desc').AsString;
it := troliJavitasokDataset.FieldByName('id').AsInteger;
cmbWorks.Items.AddObject(sData,TObject(it));
troliJavitasokDataset.Next;
Until troliJavitasokDataset.Eof;
cmbWorks.ItemIndex := 0;
dbClose(troliJavitasokDataset);
//Feederalkatrészek feltöltése a feeder típusától függően :
if (troliAlkatreszekDataset.RecordCount > 0) then
begin
Repeat
sData := troliAlkatreszekDataset.FieldByName('p_ordernum').AsString + ' - '
+ troliAlkatreszekDataset.FieldByName('p_name').AsString;
cmbAlkatreszek.Items.AddObject(sData,TObject(troliAlkatreszekDataset.FieldByName('id').AsInteger));
troliAlkatreszekDataset.Next;
Until troliAlkatreszekDataset.Eof;
troliAlkatreszekDataset.First;
cmbAlkatreszek.ItemIndex := 0;
end;
dbClose(troliAlkatreszekDataset);
//A trolihoz tartozó adatok összegyüjtése :
//DS7i-hez tartozó lezárt munkalapok :
dbUpdate(myDataset,'select trolley_repair.id as rep_id,trolley_repair.tr_ds7i,trolley_repair.tr_date,' +
'trolley_repair.tr_comment,trolley_repair.tr_preventiv,users.id,users.u_name from trolley_repair,users where tr_ds7i="' +
DS7i + '" and tr_end = 1 and users.id = trolley_repair.u_id order by trolley_repair.id;');
myDataset.First;
iRows := myDataset.RecordCount;
//végig kell menni a trolihoz tartozó munkalapokon:
if (iRows > 0) then
begin
iActualRow := 1;
SetLength(aTroliAdatok,iRows+1);
Repeat
//Aktuális munkalap db-id -je :
iTworkID := myDataset.FieldByName('rep_id').AsInteger;
//DS7i,javító,dátum,megjegyzés kitöltése :
aTroliAdatok[iActualRow].sDS7i := DS7i;
aTroliAdatok[iActualRow].sUname := myDataset.FieldByName('u_name').AsString;
aTroliAdatok[iActualRow].sComment := myDataset.FieldByName('tr_comment').AsString;
aTroliAdatok[iActualRow].sDate:= myDataset.FieldByName('tr_date').AsString;
if (myDataset.FieldByName('tr_preventiv').AsInteger = 0) then
aTroliAdatok[iActualRow].bPreventiv := false
else
aTroliAdatok[iActualRow].bPreventiv := true;
//trolihoz tartozó elvégzett munkák :
dbUpdate(worksDataset,'select trolley_r_c.tr_r_desc from trolley_r_c,trolley_works where trolley_works.r_id = '
+ IntToStr(iTworkID) + ' and trolley_works.t_r_code_id = trolley_r_c.id');
sData := '';
iWorksNum := worksDataset.RecordCount;
SetLength(aTroliAdatok[iActualRow].sWorks,iWorksNum+1);
//ShowMessage('iWorksNum : '+inttostr(iWorksNum));
for i := 1 to iWorksNum do
begin
aTroliAdatok[iActualRow].sWorks[i] := worksDataset.FieldByName('tr_r_desc').AsString;
worksDataset.Next;
//ShowMessage('Munka : '+aTroliAdatok[iActualRow].sWorks[i]);
end;
//troliba épített alkatrészek :
rPartsCost := 0;
dbUpdate(partsDataset,'select parts.p_name,parts.p_cost from used_trolley_parts,parts where ' +
'used_trolley_parts.t_r_id = ' + IntToStr(iTworkID) + ' and used_trolley_parts.t_p_id = parts.id;');
sData := '';
rPartsCost := 0;
iPartsNum := partsDataset.RecordCount;
SetLength(aTroliAdatok[iActualRow].sParts,iPartsNum+1);
//ShowMessage('iPartsNum : '+inttostr(iPartsNum));
for i := 1 to iPartsNum do
begin
aTroliAdatok[iActualRow].sParts[i] := partsDataset.FieldByName('p_name').AsString;
try
rtCost := partsDataset.FieldByName('p_cost').AsFloat;
except
rtCost := 0;
end;
rPartsCost := rPartsCost + rtCost;
partsDataset.Next;
//ShowMessage('Alkatrész : '+aTroliAdatok[iActualRow].sParts[i]);
end;
if (rPartsCost <= 0) then aTroliAdatok[iActualRow].sCost := '0.0';
if (rPartsCost > 0) then aTroliAdatok[iActualRow].sCost := FloatToStr(rPartsCost);
iActualRow := iActualRow + 1;
myDataset.Next;
Until myDataset.Eof;
end ;
dbClose(partsDataset);
dbClose(worksDataset);
//Adatok megjelenítése HTML táblázatban :
iTad := Length(aTroliAdatok);
//ShowMessage('Troli adatok száma : '+IntToStr(iTad));
if (iTad > 0) then
begin
//van már ehez a trolihoz adat felvíve...
sTroliInfos := '';
sTroliInfos := '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>';
sTroliInfos := sTroliInfos +
'<table align="center" width="98%" border="1" CELLPADDING=4 CELLSPACING=0 >' +
'<tr align="center" height="40px"><td><b>Azonosító</b></td><td><b>Jav. dátum</b></td><td><b>Karbantartó</b></td>' +
'<td><b>Elvégzett munkák</b></td><td><b>Felhasznált alkatrészek</b></td>' +
'<td><b>Költség (EUR)</b></td><td><b>Megjegyzések...</b></td><td><b>Preventív</b></td></tr>';
for i := 1 to iTad-1 do
begin
iPartsNum := Length(aTroliAdatok[i].sParts);
iWorksNum := Length(aTroliAdatok[i].sWorks);
sTroliInfos := sTroliInfos + '<tr>' +
'<td><font size="1">' + aTroliAdatok[i].sDS7i + '</font></td>' +
'<td><font size="1">' + aTroliAdatok[i].sDate + '</font></td>' +
'<td><font size="1">' + aTroliAdatok[i].sUname + '</font></td>' +
'<td align="left"><font size="1">';
if (iWorksNum >= 1) then
for j := 1 to iWorksNum-1 do
begin
sTroliInfos := sTroliInfos + aTroliAdatok[i].sWorks[j];
if (iWorksNum > j) then sTroliInfos := sTroliInfos + '<br>';
end
else
sTroliInfos := sTroliInfos + '<br>';
sTroliInfos := sTroliInfos + '</font></td><td align="left"><font size="1">';
if (iPartsNum >= 1) then
for j := 1 to iPartsNum-1 do
begin
sTroliInfos := sTroliInfos + aTroliAdatok[i].sParts[j];
if (iPartsNum > j) then sTroliInfos := sTroliInfos + '<br>';
end
else
sTroliInfos := sTroliInfos + '<br>';
if (aTroliAdatok[i].bPreventiv) then
sTroliPreventiv := 'IGEN'
else
sTroliPreventiv := 'NEM';
sTroliInfos := sTroliInfos + '</font></td><td><font size="1">' + aTroliAdatok[i].sCost +
'</font></td><td align="left"><font size="1">' + aTroliAdatok[i].sComment + '</font></td>' +
'<td><font size="1">' + sTroliPreventiv + '</font></td>';
sTroliInfos := sTroliInfos + '</tr>';
end;
sTroliInfos := sTroliInfos + '</table></body></html>';
IpHtmlPanel1.SetHtmlFromStr(sTroliInfos);
end;
//ShowMessage(sTroliInfos);
IpHtmlPanel1.Refresh;
dbClose(myDataset);
end;
initialization
{$I trolimunkalap.lrs}
end.
|
unit URepositorioAgendamento;
interface
uses
URepositorioDB
, UAgendamento
, SqlExpr
;
type
TRepositorioAgendamento = class(TRepositorioDB<TAGENDAMENTO>)
protected
//Atribui os dados do banco no objeto
procedure AtribuiDBParaEntidade(const coAGENDAMENTO: TAGENDAMENTO); override;
//Atribui os dados do objeto no banco
procedure AtribuiEntidadeParaDB(const coAGENDAMENTO: TAGENDAMENTO;
const coSQLQuery: TSQLQuery); override;
public
constructor Create;
end;
implementation
{ TRepositorioUsuario }
uses
UEntidade
, UMensagens
;
{ TRepositorioAgendamento }
procedure TRepositorioAgendamento.AtribuiDBParaEntidade(
const coAGENDAMENTO: TAGENDAMENTO);
begin
inherited;
//Consultor:
coAGENDAMENTO.ID_CONSULTOR := FSQLSelect.FieldByName(FLD_AGENDAMENTO_ID_CONSULTOR).AsInteger;
coAGENDAMENTO.NOME_CONSULTOR := FSQLSelect.FieldByName(FLD_AGENDAMENTO_NOME_CONSULTOR).AsString;
//Cliente:
coAGENDAMENTO.ID_CLIENTE := FSQLSelect.FieldByName(FLD_AGENDAMENTO_ID_CLIENTE).AsInteger;
coAGENDAMENTO.NOME_CLIENTE := FSQLSelect.FieldByName(FLD_AGENDAMENTO_NOME_CLIENTE).AsString;
//Agendamento:
coAGENDAMENTO.DATA_INICIO := FSQLSelect.FieldByName(FLD_AGENDAMENTO_DATA_INICIO).AsDateTime;
coAGENDAMENTO.DATA_TERMINO := FSQLSelect.FieldByName(FLD_AGENDAMENTO_DATA_TERMINO).AsDateTime;
coAGENDAMENTO.HORARIO_INICIO := FSQLSelect.FieldByName(FLD_AGENDAMENTO_HORARIO_INICIO).AsDateTime;
coAGENDAMENTO.HORARIO_TERMINO := FSQLSelect.FieldByName(FLD_AGENDAMENTO_HORARIO_TERMINO).AsDateTime;
coAGENDAMENTO.DURACAO := FSQLSelect.FieldByName(FLD_AGENDAMENTO_DURACAO).AsDateTime;
coAGENDAMENTO.OBSERVACAO := FSQLSelect.FieldByName(FLD_AGENDAMENTO_OBSERVACAO).AsString;
end;
procedure TRepositorioAgendamento.AtribuiEntidadeParaDB(
const coAGENDAMENTO: TAGENDAMENTO; const coSQLQuery: TSQLQuery);
begin
inherited;
//Consultor:
coSQLQuery.ParamByName(FLD_AGENDAMENTO_ID_CONSULTOR).AsInteger := coAGENDAMENTO.ID_CONSULTOR;
coSQLQuery.ParamByName(FLD_AGENDAMENTO_NOME_CONSULTOR).AsString := coAGENDAMENTO.NOME_CONSULTOR;
//Cliente:
coSQLQuery.ParamByName(FLD_AGENDAMENTO_ID_CLIENTE).AsInteger := coAGENDAMENTO.ID_CLIENTE;
coSQLQuery.ParamByName(FLD_AGENDAMENTO_NOME_CLIENTE).AsString := coAGENDAMENTO.NOME_CLIENTE;
//Agendamento:
coSQLQuery.ParamByName(FLD_AGENDAMENTO_DATA_INICIO).AsDate := coAGENDAMENTO.DATA_INICIO;
coSQLQuery.ParamByName(FLD_AGENDAMENTO_DATA_TERMINO).AsDate := coAGENDAMENTO.DATA_TERMINO;
coSQLQuery.ParamByName(FLD_AGENDAMENTO_HORARIO_INICIO).AsTime := coAGENDAMENTO.HORARIO_INICIO;
coSQLQuery.ParamByName(FLD_AGENDAMENTO_HORARIO_TERMINO).AsTime := coAGENDAMENTO.HORARIO_TERMINO;
coSQLQuery.ParamByName(FLD_AGENDAMENTO_DURACAO).AsTime := coAGENDAMENTO.DURACAO;
coSQLQuery.ParamByName(FLD_AGENDAMENTO_OBSERVACAO).AsString := coAGENDAMENTO.OBSERVACAO;
end;
constructor TRepositorioAgendamento.Create;
begin
Inherited Create(TAGENDAMENTO, TBL_AGENDAMENTO, FLD_ENTIDADE_ID, STR_AGENDAMENTO);
end;
end.
|
unit Server.Models.Cadastros.Midias;
interface
uses
System.Classes,
DB,
System.SysUtils,
Generics.Collections,
/// orm
dbcbr.mapping.attributes,
dbcbr.types.mapping,
ormbr.types.lazy,
ormbr.types.nullable,
dbcbr.mapping.register, Server.Models.Base.TabelaBase;
type
[Entity]
[Table('MIDIAS','')]
[PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')]
TMidias = class(TTabelaBase)
private
fNOME: String;
function Getid: Integer;
procedure Setid(const Value: Integer);
procedure GetNOME(const Value: String);
public
constructor create;
destructor destroy; override;
{ Public declarations }
[Restrictions([NotNull, Unique])]
[Column('CODIGO', ftInteger)]
[Dictionary('CODIGO','','','','',taCenter)]
property id: Integer read Getid write Setid;
[Column('NOME', ftString, 35)]
[Dictionary('NOME','Mensagem de validação','','','',taLeftJustify)]
property NOME: String read fNOME write GetNOME;
end;
implementation
{ TMidias }
uses Infotec.Utils;
constructor TMidias.create;
begin
end;
destructor TMidias.destroy;
begin
inherited;
end;
function TMidias.Getid: Integer;
begin
Result := fid;
end;
procedure TMidias.GetNOME(const Value: String);
begin
fNOME := TInfotecUtils.RemoverEspasDuplas(Value);
end;
procedure TMidias.Setid(const Value: Integer);
begin
fid := Value;
end;
initialization
TRegisterClass.RegisterEntity(TMidias);
end.
|
(******************************************************************************
* PasVulkan *
******************************************************************************
* Version see PasVulkan.Framework.pas *
******************************************************************************
* zlib license *
*============================================================================*
* *
* Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) *
* *
* 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 acknowledgement 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. *
* *
******************************************************************************
* General guidelines for code contributors *
*============================================================================*
* *
* 1. Make sure you are legally allowed to make a contribution under the zlib *
* license. *
* 2. The zlib license header goes at the top of each source file, with *
* appropriate copyright notice. *
* 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan *
* Pascal header. *
* 4. After a pull request, check the status of your pull request on *
http://github.com/BeRo1985/pasvulkan *
* 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= *
* 3.1.1 *
* 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, *
* but if needed, make it out-ifdef-able. *
* 7. No use of third-party libraries/units as possible, but if needed, make *
* it out-ifdef-able. *
* 8. Try to use const when possible. *
* 9. Make sure to comment out writeln, used while debugging. *
* 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, *
* x86-64, ARM, ARM64, etc.). *
* 11. Make sure the code runs on all platforms with Vulkan support *
* *
******************************************************************************)
unit PasVulkan.Sprites;
{$i PasVulkan.inc}
{$ifndef fpc}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=24.0}
{$legacyifend on}
{$ifend}
{$endif}
{$endif}
interface
uses SysUtils,
Classes,
Math,
PUCU,
Vulkan,
PasVulkan.Types,
PasVulkan.Math,
PasVulkan.Collections,
PasVulkan.Framework,
PasVulkan.XML,
PasVulkan.VectorPath,
PasVulkan.Streams,
PasVulkan.SignedDistanceField2D,
PasVulkan.Image.BMP,
PasVulkan.Image.JPEG,
PasVulkan.Image.PNG,
PasVulkan.Image.QOI,
PasVulkan.Image.TGA;
type EpvSpriteAtlas=class(Exception);
TpvSpriteTexture=class
private
fTexture:TpvVulkanTexture;
fWidth:TpvInt32;
fHeight:TpvInt32;
fUploaded:boolean;
fDirty:boolean;
fSRGB:boolean;
fDepth16Bit:boolean;
fPixels:TpvPointer;
public
constructor Create(const aPixels:TpvPointer;const aWidth,aHeight:TpvInt32;const aSRGB:boolean=false;const aDepth16Bit:boolean=false); reintroduce;
destructor Destroy; override;
procedure Upload(const aDevice:TpvVulkanDevice;
const aGraphicsQueue:TpvVulkanQueue;
const aGraphicsCommandBuffer:TpvVulkanCommandBuffer;
const aGraphicsFence:TpvVulkanFence;
const aTransferQueue:TpvVulkanQueue;
const aTransferCommandBuffer:TpvVulkanCommandBuffer;
const aTransferFence:TpvVulkanFence;
const aMipMaps:boolean);
procedure Unload;
published
property Texture:TpvVulkanTexture read fTexture;
property Width:TpvInt32 read fWidth;
property Height:TpvInt32 read fHeight;
property Uploaded:boolean read fUploaded;
property Dirty:boolean read fDirty write fDirty;
property Depth16Bit:boolean read fDepth16Bit;
end;
TpvSpriteAtlasArrayTextureTexels=array of byte;
TpvSpriteAtlasArrayTexture=class;
PpvSpriteAtlasArrayTextureLayerRectNode=^TpvSpriteAtlasArrayTextureLayerRectNode;
TpvSpriteAtlasArrayTextureLayerRectNode=record
Left:PpvSpriteAtlasArrayTextureLayerRectNode;
Right:PpvSpriteAtlasArrayTextureLayerRectNode;
x:TpvInt32;
y:TpvInt32;
Width:TpvInt32;
Height:TpvInt32;
FreeArea:TpvInt32;
ContentWidth:TpvInt32;
ContentHeight:TpvInt32;
end;
TPVulkanSpriteAtlasArrayTextureLayerRectNodes=array of PpvSpriteAtlasArrayTextureLayerRectNode;
PpvSpriteAtlasArrayTextureLayer=^TpvSpriteAtlasArrayTextureLayer;
TpvSpriteAtlasArrayTextureLayer=record
Next:PpvSpriteAtlasArrayTextureLayer;
ArrayTexture:TpvSpriteAtlasArrayTexture;
RootNode:PpvSpriteAtlasArrayTextureLayerRectNode;
end;
TpvSpriteAtlasArrayTexture=class
private
fTexels:TpvSpriteAtlasArrayTextureTexels;
fTexture:TpvVulkanTexture;
fWidth:TpvInt32;
fHeight:TpvInt32;
fLayers:TpvInt32;
fCountTexels:TpvInt64;
fDepth16Bit:boolean;
fSRGB:boolean;
fUploaded:boolean;
fDirty:boolean;
fSpecialSizedArrayTexture:boolean;
fBytesPerPixel:TpvInt32;
fLayerRootNodes:TPVulkanSpriteAtlasArrayTextureLayerRectNodes;
fInverseSize:TpvVector2;
public
constructor Create(const aSRGB,aDepth16Bit:boolean); reintroduce;
destructor Destroy; override;
procedure Resize(const aWidth,aHeight,aLayers:TpvInt32);
procedure CopyIn(const aData;const aSrcWidth,aSrcHeight,aDestX,aDestY,aDestLayer:TpvInt32);
function GetTexelPointer(const aX,aY,aLayer:TpvInt32):TpvPointer;
procedure Upload(const aDevice:TpvVulkanDevice;
const aGraphicsQueue:TpvVulkanQueue;
const aGraphicsCommandBuffer:TpvVulkanCommandBuffer;
const aGraphicsFence:TpvVulkanFence;
const aTransferQueue:TpvVulkanQueue;
const aTransferCommandBuffer:TpvVulkanCommandBuffer;
const aTransferFence:TpvVulkanFence;
const aMipMaps:boolean);
procedure Unload;
property InverseSize:TpvVector2 read fInverseSize;
published
property Texture:TpvVulkanTexture read fTexture;
property Width:TpvInt32 read fWidth;
property Height:TpvInt32 read fHeight;
property Layers:TpvInt32 read fLayers;
property CountTexels:TpvInt64 read fCountTexels;
property Uploaded:boolean read fUploaded;
property Dirty:boolean read fDirty write fDirty;
end;
TpvSpriteAtlasArrayTextures=array of TpvSpriteAtlasArrayTexture;
PpvSpriteFlag=^TpvSpriteFlag;
TpvSpriteFlag=
(
SignedDistanceField,
Rotated
);
PpvSpriteFlags=^TpvSpriteFlags;
TpvSpriteFlags=set of TpvSpriteFlag;
PpvSpriteTrimmedHullVectors=^TpvSpriteTrimmedHullVectors;
TpvSpriteTrimmedHullVectors=TpvVector2Array;
TpvSpriteTrimmedHullVectorsArray=array of TpvSpriteTrimmedHullVectors;
TpvSprite=class
private
fName:TpvRawByteString;
fFlags:TpvSpriteFlags;
fArrayTexture:TpvSpriteAtlasArrayTexture;
fX:TpvInt32;
fY:TpvInt32;
fLayer:TpvInt32;
fWidth:TpvInt32;
fHeight:TpvInt32;
fTrimmedX:TpvInt32;
fTrimmedY:TpvInt32;
fTrimmedWidth:TpvInt32;
fTrimmedHeight:TpvInt32;
fOffsetX:TpvFloat;
fOffsetY:TpvFloat;
fScaleX:TpvFloat;
fScaleY:TpvFloat;
fTrimmedHullVectors:TpvSpriteTrimmedHullVectors;
fTrimmedOffset:TpvVector2;
fTrimmedSize:TpvVector2;
fTrimmedRect:TpvRect;
fOffset:TpvVector2;
fSize:TpvVector2;
fSignedDistanceFieldVariant:TpvSignedDistanceField2DVariant;
function GetSignedDistanceField:boolean; inline;
procedure SetSignedDistanceField(const aSignedDistanceField:boolean); inline;
function GetRotated:boolean; inline;
procedure SetRotated(const aRotated:boolean); inline;
public
constructor Create; reintroduce;
destructor Destroy; override;
procedure Update;
property TrimmedHullVectors:TpvSpriteTrimmedHullVectors read fTrimmedHullVectors write fTrimmedHullVectors;
property TrimmedOffset:TpvVector2 read fTrimmedOffset;
property TrimmedSize:TpvVector2 read fTrimmedSize;
property TrimmedRect:TpvRect read fTrimmedRect;
property Offset:TpvVector2 read fOffset;
property Size:TpvVector2 read fSize;
published
property Name:TpvRawByteString read fName write fName;
property ArrayTexture:TpvSpriteAtlasArrayTexture read fArrayTexture write fArrayTexture;
property x:TpvInt32 read fX write fX;
property y:TpvInt32 read fY write fY;
property Layer:TpvInt32 read fLayer write fLayer;
property Width:TpvInt32 read fWidth write fWidth;
property Height:TpvInt32 read fHeight write fHeight;
property TrimmedX:TpvInt32 read fTrimmedX write fTrimmedX;
property TrimmedY:TpvInt32 read fTrimmedY write fTrimmedY;
property TrimmedWidth:TpvInt32 read fTrimmedWidth write fTrimmedWidth;
property TrimmedHeight:TpvInt32 read fTrimmedHeight write fTrimmedHeight;
property OffsetX:TpvFloat read fOffsetX write fOffsetX;
property OffsetY:TpvFloat read fOffsetY write fOffsetY;
property ScaleX:TpvFloat read fScaleX write fScaleX;
property ScaleY:TpvFloat read fScaleY write fScaleY;
property SignedDistanceField:boolean read GetSignedDistanceField write SetSignedDistanceField;
property SignedDistanceFieldVariant:TpvSignedDistanceField2DVariant read fSignedDistanceFieldVariant write fSignedDistanceFieldVariant;
property Rotated:boolean read GetRotated write SetRotated;
end;
TpvSprites=array of TpvSprite;
TpvSpriteAtlasSpriteStringHashMap=class(TpvStringHashMap<TpvSprite>);
PpvSpriteNinePatchRegionMode=^TpvSpriteNinePatchRegionMode;
TpvSpriteNinePatchRegionMode=
(
Stretch,
Tile,
StretchXTileY,
TileXStretchY
);
PpvSpriteNinePatchRegion=^TpvSpriteNinePatchRegion;
TpvSpriteNinePatchRegion=record
public
Mode:TpvSpriteNinePatchRegionMode;
Left:TpvInt32;
Top:TpvInt32;
Width:TpvInt32;
Height:TpvInt32;
constructor Create(const aMode:TpvSpriteNinePatchRegionMode;const aLeft,aTop,aWidth,aHeight:TpvInt32);
end;
PpvSpriteNinePatchRegions=^TpvSpriteNinePatchRegions;
TpvSpriteNinePatchRegions=array[0..2,0..2] of TpvSpriteNinePatchRegion;
PpvSpriteNinePatch=^TpvSpriteNinePatch;
TpvSpriteNinePatch=record
Regions:TpvSpriteNinePatchRegions;
end;
TpvSpriteAtlas=class
private
const FileFormatGUID:TGUID='{DBF9E645-5C92-451B-94F7-134C891D484F}';
private
fDevice:TpvVulkanDevice;
fArrayTextures:TpvSpriteAtlasArrayTextures;
fCountArrayTextures:TpvInt32;
fList:TList;
fHashMap:TpvSpriteAtlasSpriteStringHashMap;
fDepth16Bit:boolean;
fSRGB:boolean;
fIsUploaded:boolean;
fMipMaps:boolean;
fUseConvexHullTrimming:boolean;
fWidth:TpvInt32;
fHeight:TpvInt32;
fMaximumCountArrayLayers:TpvInt32;
function GetCount:TpvInt32;
function GetItem(Index:TpvInt32):TpvSprite;
procedure SetItem(Index:TpvInt32;Item:TpvSprite);
function GetSprite(const aName:TpvRawByteString):TpvSprite;
procedure AddSprite(const aSprite:TpvSprite);
function LoadImage(const aDataPointer:TpvPointer;
const aDataSize:TVkSizeInt;
var aImageData:TpvPointer;
var aImageWidth,aImageHeight:TpvInt32):boolean;
public
constructor Create(const aDevice:TpvVulkanDevice;const aSRGB:boolean=false;const aDepth16Bit:boolean=false); reintroduce;
destructor Destroy; override;
procedure Upload(const aGraphicsQueue:TpvVulkanQueue;
const aGraphicsCommandBuffer:TpvVulkanCommandBuffer;
const aGraphicsFence:TpvVulkanFence;
const aTransferQueue:TpvVulkanQueue;
const aTransferCommandBuffer:TpvVulkanCommandBuffer;
const aTransferFence:TpvVulkanFence); virtual;
procedure Unload; virtual;
function Uploaded:boolean; virtual;
procedure ClearAll; virtual;
function LoadXML(const aTextureStream:TStream;const aStream:TStream):boolean;
function LoadRawSprite(const aName:TpvRawByteString;aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvInt32;const aAutomaticTrim:boolean=true;const aPadding:TpvInt32=2;const aTrimPadding:TpvInt32=1;const aDepth16Bit:boolean=false;const aTrimmedHullVectors:PpvSpriteTrimmedHullVectors=nil):TpvSprite;
function LoadSignedDistanceFieldSprite(const aName:TpvRawByteString;const aVectorPath:TpvVectorPath;const aImageWidth,aImageHeight:TpvInt32;const aScale:TpvDouble=1.0;const aOffsetX:TpvDouble=0.0;const aOffsetY:TpvDouble=0.0;const aAutomaticTrim:boolean=true;const aPadding:TpvInt32=2;const aTrimPadding:TpvInt32=1;const aSDFVariant:TpvSignedDistanceField2DVariant=TpvSignedDistanceField2DVariant.Default;const aProtectBorder:boolean=false):TpvSprite; overload;
function LoadSignedDistanceFieldSprite(const aName,aSVGPath:TpvRawByteString;const aImageWidth,aImageHeight:TpvInt32;const aScale:TpvDouble=1.0;const aOffsetX:TpvDouble=0.0;const aOffsetY:TpvDouble=0.0;const aVectorPathFillRule:TpvVectorPathFillRule=TpvVectorPathFillRule.NonZero;const aAutomaticTrim:boolean=true;const aPadding:TpvInt32=2;const aTrimPadding:TpvInt32=1;const aSDFVariant:TpvSignedDistanceField2DVariant=TpvSignedDistanceField2DVariant.Default;const aProtectBorder:boolean=false):TpvSprite; overload;
function LoadSprite(const aName:TpvRawByteString;aStream:TStream;const aAutomaticTrim:boolean=true;const aPadding:TpvInt32=2;const aTrimPadding:TpvInt32=1):TpvSprite;
function LoadSprites(const aName:TpvRawByteString;aStream:TStream;aSpriteWidth:TpvInt32=64;aSpriteHeight:TpvInt32=64;const aAutomaticTrim:boolean=true;const aPadding:TpvInt32=2;const aTrimPadding:TpvInt32=1):TpvSprites;
procedure LoadFromStream(const aStream:TStream);
procedure LoadFromFile(const aFileName:string);
procedure SaveToStream(const aStream:TStream;const aFast:boolean=false);
procedure SaveToFile(const aFileName:string;const aFast:boolean=false);
property Device:TpvVulkanDevice read fDevice;
property Count:TpvInt32 read GetCount;
property Items[Index:TpvInt32]:TpvSprite read GetItem write SetItem;
property Sprites[const Name:TpvRawByteString]:TpvSprite read GetSprite; default;
published
property MipMaps:boolean read fMipMaps write fMipMaps;
property UseConvexHullTrimming:boolean read fUseConvexHullTrimming write fUseConvexHullTrimming;
property Width:TpvInt32 read fWidth write fWidth;
property Height:TpvInt32 read fHeight write fHeight;
property MaximumCountArrayLayers:TpvInt32 read fMaximumCountArrayLayers write fMaximumCountArrayLayers;
end;
implementation
uses PasDblStrUtils,
PasVulkan.Archive.ZIP,
PasVulkan.ConvexHullGenerator2D;
const MipMapLevels:array[boolean] of TpvInt32=(1,-1);
function NewTextureRectNode:PpvSpriteAtlasArrayTextureLayerRectNode;
begin
GetMem(result,SizeOf(TpvSpriteAtlasArrayTextureLayerRectNode));
FillChar(result^,SizeOf(TpvSpriteAtlasArrayTextureLayerRectNode),AnsiChar(#0));
end;
procedure FreeTextureRectNode(const Node:PpvSpriteAtlasArrayTextureLayerRectNode);
begin
if assigned(Node) then begin
FreeTextureRectNode(Node^.Left);
FreeTextureRectNode(Node^.Right);
Node^.Left:=nil;
Node^.Right:=nil;
FreeMem(Node);
end;
end;
function InsertTextureRectNode(const Node:PpvSpriteAtlasArrayTextureLayerRectNode;const Width,Height,Area:TpvInt32):PpvSpriteAtlasArrayTextureLayerRectNode;
var RemainWidth,RemainHeight:TpvInt32;
begin
result:=nil;
if (Width<=Node^.Width) and (Height<=Node^.Height) and (Area<=Node^.FreeArea) then begin
if assigned(Node^.Left) or assigned(Node^.Right) then begin
// This node has children nodes, so this node has content already, so the subnodes will be processing
if assigned(Node^.Left) then begin
result:=InsertTextureRectNode(Node^.Left,Width,Height,Area);
if assigned(result) then begin
dec(Node^.FreeArea,Area);
exit;
end;
end;
if assigned(Node^.Right) then begin
result:=InsertTextureRectNode(Node^.Right,Width,Height,Area);
if assigned(result) then begin
dec(Node^.FreeArea,Area);
exit;
end;
end;
end else begin
// No children nodes, so allocate a rect here and subdivide the remained space into two subnodes
RemainWidth:=Node^.Width-Width;
RemainHeight:=Node^.Height-Height;
Node^.Left:=NewTextureRectNode;
Node^.Right:=NewTextureRectNode;
if RemainWidth<=RemainHeight then begin
Node^.Left^.x:=Node^.x+Width;
Node^.Left^.y:=Node^.y;
Node^.Left^.Width:=RemainWidth;
Node^.Left^.Height:=Height;
Node^.Left^.FreeArea:=Node^.Left^.Width*Node^.Left^.Height;
Node^.Right^.x:=Node^.x;
Node^.Right^.y:=Node^.y+Height;
Node^.Right^.Width:=Node^.Width;
Node^.Right^.Height:=RemainHeight;
Node^.Right^.FreeArea:=Node^.Right^.Width*Node^.Right^.Height;
end else begin
Node^.Left^.x:=Node^.x;
Node^.Left^.y:=Node^.y+Height;
Node^.Left^.Width:=Width;
Node^.Left^.Height:=RemainHeight;
Node^.Left^.FreeArea:=Node^.Left^.Width*Node^.Left^.Height;
Node^.Right^.x:=Node^.x+Width;
Node^.Right^.y:=Node^.y;
Node^.Right^.Width:=RemainWidth;
Node^.Right^.Height:=Node^.Height;
Node^.Right^.FreeArea:=Node^.Right^.Width*Node^.Right^.Height;
end;
Node^.Left^.ContentWidth:=0;
Node^.Left^.ContentHeight:=0;
Node^.Right^.ContentWidth:=0;
Node^.Right^.ContentHeight:=0;
Node^.ContentWidth:=Width;
Node^.ContentHeight:=Height;
dec(Node^.FreeArea,Area);
result:=Node;
end;
end;
end;
constructor TpvSpriteTexture.Create(const aPixels:pointer;const aWidth,aHeight:TpvInt32;const aSRGB:boolean=false;const aDepth16Bit:boolean=false);
begin
inherited Create;
fTexture:=nil;
fPixels:=aPixels;
fWidth:=aWidth;
fHeight:=aHeight;
fSRGB:=aSRGB;
fDepth16Bit:=aDepth16Bit;
fUploaded:=false;
fDirty:=true;
end;
destructor TpvSpriteTexture.Destroy;
begin
Unload;
FreeAndNil(fTexture);
fPixels:=nil;
inherited Destroy;
end;
procedure TpvSpriteTexture.Upload(const aDevice:TpvVulkanDevice;
const aGraphicsQueue:TpvVulkanQueue;
const aGraphicsCommandBuffer:TpvVulkanCommandBuffer;
const aGraphicsFence:TpvVulkanFence;
const aTransferQueue:TpvVulkanQueue;
const aTransferCommandBuffer:TpvVulkanCommandBuffer;
const aTransferFence:TpvVulkanFence;
const aMipMaps:boolean);
type PPixel16Bit=^TPixel16Bit;
TPixel16Bit=packed record
r,g,b,a:TpvUInt16;
end;
const Div16Bit=1.0/65536.0;
var BytesPerPixel,Index:TpvInt32;
Format:TVkFormat;
UploadPixels:pointer;
s16,d16:PPixel16Bit;
c:TpvVector4;
begin
if not fUploaded then begin
FreeAndNil(fTexture);
UploadPixels:=fPixels;
try
if fDepth16Bit then begin
BytesPerPixel:=16;
if fSRGB then begin
Format:=VK_FORMAT_R16G16B16A16_UNORM;
GetMem(UploadPixels,fWidth*fHeight*BytesPerPixel);
s16:=fPixels;
d16:=UploadPixels;
for Index:=1 to fWidth*fHeight do begin
c:=ConvertSRGBToLinear(TpvVector4.InlineableCreate(s16^.r,s16^.g,s16^.g,s16^.b)*Div16Bit);
d16^.r:=Min(Max(round(Clamp(c.r,0.0,1.0)*65536.0),0),65535);
d16^.g:=Min(Max(round(Clamp(c.g,0.0,1.0)*65536.0),0),65535);
d16^.b:=Min(Max(round(Clamp(c.b,0.0,1.0)*65536.0),0),65535);
d16^.a:=Min(Max(round(Clamp(c.a,0.0,1.0)*65536.0),0),65535);
inc(s16);
inc(d16);
end;
end else begin
Format:=VK_FORMAT_R16G16B16A16_UNORM;
end;
end else begin
BytesPerPixel:=8;
if fSRGB then begin
Format:=VK_FORMAT_R8G8B8A8_SRGB;
end else begin
Format:=VK_FORMAT_R8G8B8A8_UNORM;
end;
end;
fTexture:=TpvVulkanTexture.CreateFromMemory(aDevice,
aGraphicsQueue,
aGraphicsCommandBuffer,
aGraphicsFence,
aTransferQueue,
aTransferCommandBuffer,
aTransferFence,
Format,
VK_SAMPLE_COUNT_1_BIT,
Max(1,fWidth),
Max(1,fHeight),
0,
0,
1,
MipMapLevels[aMipMaps],
[TpvVulkanTextureUsageFlag.TransferDst,TpvVulkanTextureUsageFlag.Sampled],
UploadPixels,
fWidth*fHeight*BytesPerPixel,
false,
false,
1,
true);
fTexture.WrapModeU:=TpvVulkanTextureWrapMode.ClampToBorder;
fTexture.WrapModeV:=TpvVulkanTextureWrapMode.ClampToBorder;
fTexture.WrapModeW:=TpvVulkanTextureWrapMode.ClampToBorder;
fTexture.BorderColor:=VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
fTexture.UpdateSampler;
finally
if UploadPixels<>fPixels then begin
FreeMem(UploadPixels);
end;
end;
fUploaded:=true;
end;
end;
procedure TpvSpriteTexture.Unload;
begin
if fUploaded then begin
FreeAndNil(fTexture);
fUploaded:=false;
end;
end;
constructor TpvSpriteAtlasArrayTexture.Create(const aSRGB,aDepth16Bit:boolean);
begin
inherited Create;
fTexels:=nil;
fTexture:=nil;
fLayerRootNodes:=nil;
fWidth:=0;
fHeight:=0;
fLayers:=0;
fCountTexels:=0;
fDepth16Bit:=aDepth16Bit;
fSRGB:=aSRGB;
fUploaded:=false;
fDirty:=true;
fSpecialSizedArrayTexture:=false;
if fDepth16Bit then begin
fBytesPerPixel:=8;
end else begin
fBytesPerPixel:=4;
end;
end;
destructor TpvSpriteAtlasArrayTexture.Destroy;
var LayerIndex:TpvInt32;
begin
Unload;
FreeAndNil(fTexture);
for LayerIndex:=0 to fLayers-1 do begin
if assigned(fLayerRootNodes[LayerIndex]) then begin
FreeTextureRectNode(fLayerRootNodes[LayerIndex]);
fLayerRootNodes[LayerIndex]:=nil;
end;
end;
fLayerRootNodes:=nil;
fTexels:=nil;
inherited Destroy;
end;
procedure TpvSpriteAtlasArrayTexture.Resize(const aWidth,aHeight,aLayers:TpvInt32);
var y,LayerIndex,OldWidth,OldHeight,OldLayers:TpvInt32;
OldTexels:TpvSpriteAtlasArrayTextureTexels;
begin
if (fWidth<>aWidth) or
(fHeight<>aHeight) or
(fLayers<>aLayers) then begin
OldWidth:=fWidth;
OldHeight:=fHeight;
OldLayers:=fLayers;
OldTexels:=fTexels;
try
fTexels:=nil;
fWidth:=aWidth;
fHeight:=aHeight;
fLayers:=aLayers;
fCountTexels:=TpvInt64(fWidth)*TpvInt64(fHeight)*TpvInt64(fLayers);
if fCountTexels>0 then begin
SetLength(fTexels,fCountTexels*fBytesPerPixel);
FillChar(fTexels[0],fCountTexels*fBytesPerPixel,#0);
for LayerIndex:=0 to Min(fLayers,OldLayers)-1 do begin
for y:=0 to Min(fHeight,OldHeight)-1 do begin
Move(OldTexels[(((TpvInt64(LayerIndex)*OldHeight)+y)*OldWidth)*fBytesPerPixel],
fTexels[(((TpvInt64(LayerIndex)*fHeight)+y)*fWidth)*fBytesPerPixel],
Min(fWidth,OldWidth)*fBytesPerPixel);
end;
end;
end;
for LayerIndex:=fLayers to Min(OldLayers,length(fLayerRootNodes))-1 do begin
if assigned(fLayerRootNodes[LayerIndex]) then begin
FreeTextureRectNode(fLayerRootNodes[LayerIndex]);
fLayerRootNodes[LayerIndex]:=nil;
end;
end;
SetLength(fLayerRootNodes,fLayers);
for LayerIndex:=OldLayers to fLayers-1 do begin
fLayerRootNodes[LayerIndex]:=NewTextureRectNode;
fLayerRootNodes[LayerIndex]^.x:=0;
fLayerRootNodes[LayerIndex]^.y:=0;
fLayerRootNodes[LayerIndex]^.Width:=fWidth;
fLayerRootNodes[LayerIndex]^.Height:=fHeight;
fLayerRootNodes[LayerIndex]^.FreeArea:=fWidth*fHeight;
end;
fInverseSize:=TpvVector2.InlineableCreate(1.0/fWidth,1.0/fHeight);
finally
OldTexels:=nil;
end;
end;
end;
procedure TpvSpriteAtlasArrayTexture.CopyIn(const aData;const aSrcWidth,aSrcHeight,aDestX,aDestY,aDestLayer:TpvInt32);
var dy,sx,dw:TpvInt32;
begin
sx:=Min(0,-aDestX);
dw:=Min(Max(aSrcWidth-sx,0),fWidth-aDestX);
if dw>0 then begin
for dy:=Min(Max(aDestY,0),fHeight-1) to Min(Max(aDestY+(aSrcHeight-1),0),fHeight-1) do begin
Move(PpvUInt8Array(TpvPointer(@aData))^[(((dy-aDestY)*aSrcWidth)+sx)*fBytesPerPixel],
fTexels[((((TpvInt64(aDestLayer)*fHeight)+dy)*fWidth)+aDestX)*fBytesPerPixel],
dw*fBytesPerPixel);
end;
end;
end;
function TpvSpriteAtlasArrayTexture.GetTexelPointer(const aX,aY,aLayer:TpvInt32):TpvPointer;
begin
result:=@fTexels[((((TpvInt64(aLayer)*fHeight)+aY)*fWidth)+aX)*fBytesPerPixel];
end;
procedure TpvSpriteAtlasArrayTexture.Upload(const aDevice:TpvVulkanDevice;
const aGraphicsQueue:TpvVulkanQueue;
const aGraphicsCommandBuffer:TpvVulkanCommandBuffer;
const aGraphicsFence:TpvVulkanFence;
const aTransferQueue:TpvVulkanQueue;
const aTransferCommandBuffer:TpvVulkanCommandBuffer;
const aTransferFence:TpvVulkanFence;
const aMipMaps:boolean);
type PPixel16Bit=^TPixel16Bit;
TPixel16Bit=packed record
r,g,b,a:TpvUInt16;
end;
const Div16Bit=1.0/65536.0;
var BytesPerPixel,Index:TpvInt32;
Format:TVkFormat;
UploadPixels:pointer;
s16,d16:PPixel16Bit;
c:TpvVector4;
begin
if not fUploaded then begin
FreeAndNil(fTexture);
UploadPixels:=@fTexels[0];
try
if fDepth16Bit then begin
if fSRGB then begin
Format:=VK_FORMAT_R16G16B16A16_UNORM;
GetMem(UploadPixels,fCountTexels*fBytesPerPixel);
s16:=@fTexels[0];
d16:=UploadPixels;
for Index:=1 to fCountTexels do begin
c:=ConvertSRGBToLinear(TpvVector4.InlineableCreate(s16^.r,s16^.g,s16^.g,s16^.b)*Div16Bit);
d16^.r:=Min(Max(round(Clamp(c.r,0.0,1.0)*65536.0),0),65535);
d16^.g:=Min(Max(round(Clamp(c.g,0.0,1.0)*65536.0),0),65535);
d16^.b:=Min(Max(round(Clamp(c.b,0.0,1.0)*65536.0),0),65535);
d16^.a:=Min(Max(round(Clamp(c.a,0.0,1.0)*65536.0),0),65535);
inc(s16);
inc(d16);
end;
end else begin
Format:=VK_FORMAT_R16G16B16A16_UNORM;
end;
BytesPerPixel:=16;
end else begin
if fSRGB then begin
Format:=VK_FORMAT_R8G8B8A8_SRGB;
end else begin
Format:=VK_FORMAT_R8G8B8A8_UNORM;
end;
BytesPerPixel:=8;
end;
fTexture:=TpvVulkanTexture.CreateFromMemory(aDevice,
aGraphicsQueue,
aGraphicsCommandBuffer,
aGraphicsFence,
aTransferQueue,
aTransferCommandBuffer,
aTransferFence,
Format,
VK_SAMPLE_COUNT_1_BIT,
Max(1,fWidth),
Max(1,fHeight),
0,
Max(1,fLayers),
1,
MipMapLevels[aMipMaps],
[TpvVulkanTextureUsageFlag.TransferDst,TpvVulkanTextureUsageFlag.Sampled],
UploadPixels,
fCountTexels*fBytesPerPixel,
false,
false,
1,
true);
fTexture.WrapModeU:=TpvVulkanTextureWrapMode.ClampToBorder;
fTexture.WrapModeV:=TpvVulkanTextureWrapMode.ClampToBorder;
fTexture.WrapModeW:=TpvVulkanTextureWrapMode.ClampToBorder;
fTexture.BorderColor:=VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
fTexture.UpdateSampler;
finally
if UploadPixels<>@fTexels[0] then begin
FreeMem(UploadPixels);
end;
end;
fUploaded:=true;
end;
end;
procedure TpvSpriteAtlasArrayTexture.Unload;
begin
if fUploaded then begin
FreeAndNil(fTexture);
fUploaded:=false;
end;
end;
constructor TpvSprite.Create;
begin
inherited Create;
Name:='';
OffsetX:=0.0;
OffsetY:=0.0;
ScaleX:=1.0;
ScaleY:=1.0;
fTrimmedHullVectors:=nil;
end;
destructor TpvSprite.Destroy;
begin
fTrimmedHullVectors:=nil;
Name:='';
inherited Destroy;
end;
procedure TpvSprite.Update;
begin
fTrimmedOffset:=TpvVector2.InlineableCreate(fTrimmedX,fTrimmedY);
if Rotated then begin
fTrimmedSize:=TpvVector2.InlineableCreate(fTrimmedHeight,fTrimmedWidth);
end else begin
fTrimmedSize:=TpvVector2.InlineableCreate(fTrimmedWidth,fTrimmedHeight);
end;
fTrimmedRect:=TpvRect.CreateRelative(fTrimmedOffset,fTrimmedSize);
fOffset:=TpvVector2.InlineableCreate(x,y);
fSize:=TpvVector2.InlineableCreate(fWidth,fHeight);
end;
function TpvSprite.GetSignedDistanceField:boolean;
begin
result:=TpvSpriteFlag.SignedDistanceField in fFlags;
end;
procedure TpvSprite.SetSignedDistanceField(const aSignedDistanceField:boolean);
begin
if aSignedDistanceField then begin
Include(fFlags,TpvSpriteFlag.SignedDistanceField);
end else begin
Exclude(fFlags,TpvSpriteFlag.SignedDistanceField);
end;
end;
function TpvSprite.GetRotated:boolean;
begin
result:=TpvSpriteFlag.Rotated in fFlags;
end;
procedure TpvSprite.SetRotated(const aRotated:boolean);
begin
if aRotated then begin
Include(fFlags,TpvSpriteFlag.Rotated);
end else begin
Exclude(fFlags,TpvSpriteFlag.Rotated);
end;
end;
constructor TpvSpriteNinePatchRegion.Create(const aMode:TpvSpriteNinePatchRegionMode;const aLeft,aTop,aWidth,aHeight:TpvInt32);
begin
Mode:=aMode;
Left:=aLeft;
Top:=aTop;
Width:=aWidth;
Height:=aHeight;
end;
constructor TpvSpriteAtlas.Create(const aDevice:TpvVulkanDevice;const aSRGB:boolean=false;const aDepth16Bit:boolean=false);
begin
fDevice:=aDevice;
fArrayTextures:=nil;
fCountArrayTextures:=0;
fList:=TList.Create;
fHashMap:=TpvSpriteAtlasSpriteStringHashMap.Create(nil);
fDepth16Bit:=aDepth16Bit;
fSRGB:=aSRGB;
fIsUploaded:=false;
fMipMaps:=true;
fUseConvexHullTrimming:=false;
fWidth:=Min(VULKAN_SPRITEATLASTEXTURE_WIDTH,fDevice.PhysicalDevice.Properties.limits.maxImageDimension2D);
fHeight:=Min(VULKAN_SPRITEATLASTEXTURE_HEIGHT,fDevice.PhysicalDevice.Properties.limits.maxImageDimension2D);
fMaximumCountArrayLayers:=fDevice.PhysicalDevice.Properties.limits.maxImageArrayLayers;
inherited Create;
end;
destructor TpvSpriteAtlas.Destroy;
var Index:TpvInt32;
begin
Unload;
for Index:=0 to fCountArrayTextures-1 do begin
FreeAndNil(fArrayTextures[Index]);
end;
fArrayTextures:=nil;
ClearAll;
fHashMap.Free;
fList.Free;
inherited Destroy;
end;
procedure TpvSpriteAtlas.ClearAll;
var Index:TpvInt32;
begin
for Index:=0 to fList.Count-1 do begin
TpvSprite(Items[Index]).Free;
Items[Index]:=nil;
end;
fList.Clear;
fHashMap.Clear;
end;
procedure TpvSpriteAtlas.Upload(const aGraphicsQueue:TpvVulkanQueue;
const aGraphicsCommandBuffer:TpvVulkanCommandBuffer;
const aGraphicsFence:TpvVulkanFence;
const aTransferQueue:TpvVulkanQueue;
const aTransferCommandBuffer:TpvVulkanCommandBuffer;
const aTransferFence:TpvVulkanFence);
var Index:TpvInt32;
ArrayTexture:TpvSpriteAtlasArrayTexture;
begin
if not fIsUploaded then begin
for Index:=0 to fCountArrayTextures-1 do begin
ArrayTexture:=fArrayTextures[Index];
if not ArrayTexture.Uploaded then begin
ArrayTexture.Upload(fDevice,
aGraphicsQueue,
aGraphicsCommandBuffer,
aGraphicsFence,
aTransferQueue,
aTransferCommandBuffer,
aTransferFence,
fMipMaps);
ArrayTexture.Dirty:=false;
end;
end;
fIsUploaded:=true;
end;
end;
procedure TpvSpriteAtlas.Unload;
var Index:TpvInt32;
ArrayTexture:TpvSpriteAtlasArrayTexture;
begin
if fIsUploaded then begin
for Index:=0 to fCountArrayTextures-1 do begin
ArrayTexture:=fArrayTextures[Index];
if ArrayTexture.Uploaded then begin
ArrayTexture.Unload;
end;
end;
fIsUploaded:=false;
end;
end;
function TpvSpriteAtlas.Uploaded:boolean;
begin
result:=fIsUploaded;
end;
function TpvSpriteAtlas.GetCount:TpvInt32;
begin
result:=fList.Count;
end;
function TpvSpriteAtlas.GetItem(Index:TpvInt32):TpvSprite;
begin
result:=TpvSprite(fList.Items[Index]);
end;
procedure TpvSpriteAtlas.SetItem(Index:TpvInt32;Item:TpvSprite);
begin
fList.Items[Index]:=TpvPointer(Item);
end;
function TpvSpriteAtlas.GetSprite(const aName:TpvRawByteString):TpvSprite;
begin
result:=fHashMap[aName];
end;
procedure TpvSpriteAtlas.AddSprite(const aSprite:TpvSprite);
begin
fHashMap.Add(aSprite.Name,aSprite);
fList.Add(aSprite);
end;
function TpvSpriteAtlas.LoadImage(const aDataPointer:TpvPointer;
const aDataSize:TVkSizeInt;
var aImageData:TpvPointer;
var aImageWidth,aImageHeight:TpvInt32):boolean;
type PFirstBytes=^TFirstBytes;
TFirstBytes=array[0..63] of TpvUInt8;
PDDSHeader=^TDDSHeader;
TDDSHeader=packed record
dwMagic:TpvUInt32;
dwSize:TpvUInt32;
dwFlags:TpvUInt32;
dwHeight:TpvUInt32;
dwWidth:TpvUInt32;
dwPitchOrLinearSize:TpvUInt32;
dwDepth:TpvUInt32;
dwMipMapCount:TpvUInt32;
end;
var Index,x,y:TpvInt32;
p8:PpvUInt8;
p16:PpvUInt16;
PNGPixelFormat:TpvPNGPixelFormat;
NewImageData:TpvPointer;
SRGB:boolean;
v:TpvFloat;
begin
result:=false;
if (aDataSize>7) and (PFirstBytes(aDataPointer)^[0]=$89) and (PFirstBytes(aDataPointer)^[1]=$50) and (PFirstBytes(aDataPointer)^[2]=$4e) and (PFirstBytes(aDataPointer)^[3]=$47) and (PFirstBytes(aDataPointer)^[4]=$0d) and (PFirstBytes(aDataPointer)^[5]=$0a) and (PFirstBytes(aDataPointer)^[6]=$1a) and (PFirstBytes(aDataPointer)^[7]=$0a) then begin
PNGPixelFormat:=TpvPNGPixelFormat.Unknown;
if LoadPNGImage(aDataPointer,aDataSize,aImageData,aImageWidth,aImageHeight,false,PNGPixelFormat) then begin
result:=true;
if fDepth16Bit then begin
if PNGPixelFormat=TpvPNGPixelFormat.R8G8B8A8 then begin
// Convert to R16G1B16A16
GetMem(NewImageData,aImageWidth*aImageHeight*8);
try
p8:=aImageData;
p16:=NewImageData;
for Index:=1 to aImageWidth*aImageHeight*4 do begin
p16^:=p8^ or (TpvUInt16(p8^) shl 8);
inc(p8);
inc(p16);
end;
finally
FreeMem(aImageData);
aImageData:=NewImageData;
end;
end;
end else begin
if PNGPixelFormat=TpvPNGPixelFormat.R16G16B16A16 then begin
// Convert to R8G8B8A8 in-place
p8:=aImageData;
p16:=aImageData;
for Index:=1 to aImageWidth*aImageHeight*4 do begin
p8^:=p16^ shr 8;
inc(p8);
inc(p16);
end;
end;
end;
end;
end else begin
if (aDataSize>4) and (PFirstBytes(aDataPointer)^[0]=TpvUInt8(AnsiChar('q'))) and (PFirstBytes(aDataPointer)^[1]=TpvUInt8(AnsiChar('o'))) and (PFirstBytes(aDataPointer)^[2]=TpvUInt8(AnsiChar('i'))) and (PFirstBytes(aDataPointer)^[3]=TpvUInt8(AnsiChar('f'))) then begin
result:=LoadQOIImage(aDataPointer,aDataSize,aImageData,aImageWidth,aImageHeight,false,SRGB);
if result and not SRGB then begin
if fDepth16Bit then begin
GetMem(NewImageData,aImageWidth*aImageHeight*8);
try
p8:=aImageData;
p16:=NewImageData;
Index:=0;
for y:=1 to aImageHeight do begin
for x:=1 to aImageWidth do begin
if (Index and 3)<>3 then begin
// Only convert the RGB color channels, but not the alpha channel
v:=p8^/255.0;
if v<0.0031308 then begin
v:=v*12.92;
end else begin
v:=(Power(v,1.0/2.4)*1.055)-0.055;
end;
p16^:=Min(Max(Round(v*65535.0),0),65535);
end;
inc(p8);
inc(p16);
inc(Index);
end;
end;
finally
FreeMem(aImageData);
aImageData:=NewImageData;
end;
exit;
end else begin
p8:=aImageData;
Index:=0;
for y:=1 to aImageHeight do begin
for x:=1 to aImageWidth do begin
if (Index and 3)<>3 then begin
// Only convert the RGB color channels, but not the alpha channel
v:=p8^/255.0;
if v<0.0031308 then begin
v:=v*12.92;
end else begin
v:=(Power(v,1.0/2.4)*1.055)-0.055;
end;
p8^:=Min(Max(Round(v*255.0),0),255);
end;
inc(p8);
inc(Index);
end;
end;
end;
end;
end else if (aDataSize>2) and (PFirstBytes(aDataPointer)^[0]=TpvUInt8(AnsiChar('B'))) and (PFirstBytes(aDataPointer)^[1]=TpvUInt8(AnsiChar('M'))) then begin
result:=LoadBMPImage(aDataPointer,aDataSize,aImageData,aImageWidth,aImageHeight,false);
end else if (aDataSize>2) and (((PFirstBytes(aDataPointer)^[0] xor $ff) or (PFirstBytes(aDataPointer)^[1] xor $d8))=0) then begin
result:=LoadJPEGImage(aDataPointer,aDataSize,aImageData,aImageWidth,aImageHeight,false);
end else begin
result:=LoadTGAImage(aDataPointer,aDataSize,aImageData,aImageWidth,aImageHeight,false);
end;
if result and fDepth16Bit then begin
// Convert to R16G1B16A16
GetMem(NewImageData,aImageWidth*aImageHeight*8);
try
p8:=aImageData;
p16:=NewImageData;
for Index:=1 to aImageWidth*aImageHeight*4 do begin
p16^:=p8^ or (TpvUInt16(p8^) shl 8);
inc(p8);
inc(p16);
end;
finally
FreeMem(aImageData);
aImageData:=NewImageData;
end;
end;
end;
end;
function TpvSpriteAtlas.LoadXML(const aTextureStream:TStream;const aStream:TStream):boolean;
var XML:TpvXML;
MemoryStream:TMemoryStream;
i,j:TpvInt32;
XMLItem,XMLChildrenItem:TpvXMLItem;
XMLTag,XMLChildrenTag:TpvXMLTag;
SpriteName:TpvRawByteString;
Sprite:TpvSprite;
SpriteAtlasArrayTexture:TpvSpriteAtlasArrayTexture;
ImageData:TpvPointer;
ImageWidth,ImageHeight:TpvInt32;
begin
result:=false;
if assigned(aTextureStream) and assigned(aStream) then begin
SpriteAtlasArrayTexture:=nil;
MemoryStream:=TMemoryStream.Create;
try
aStream.Seek(0,soBeginning);
MemoryStream.CopyFrom(aTextureStream,aTextureStream.Size);
MemoryStream.Seek(0,soBeginning);
ImageData:=nil;
try
if LoadImage(MemoryStream.Memory,MemoryStream.Size,ImageData,ImageWidth,ImageHeight) then begin
SpriteAtlasArrayTexture:=TpvSpriteAtlasArrayTexture.Create(fSRGB,fDepth16Bit);
SpriteAtlasArrayTexture.Resize(ImageWidth,ImageHeight,1);
if length(fArrayTextures)<(fCountArrayTextures+1) then begin
SetLength(fArrayTextures,(fCountArrayTextures+1)*2);
end;
fArrayTextures[fCountArrayTextures]:=SpriteAtlasArrayTexture;
inc(fCountArrayTextures);
SpriteAtlasArrayTexture.fSpecialSizedArrayTexture:=true;
SpriteAtlasArrayTexture.Dirty:=true;
SpriteAtlasArrayTexture.fLayerRootNodes[0].FreeArea:=0;
SpriteAtlasArrayTexture.fLayerRootNodes[0].ContentWidth:=ImageWidth;
SpriteAtlasArrayTexture.fLayerRootNodes[0].ContentHeight:=ImageHeight;
SpriteAtlasArrayTexture.CopyIn(ImageData^,ImageWidth,ImageHeight,0,0,0);
end;
finally
if assigned(ImageData) then begin
FreeMem(ImageData);
end;
end;
finally
MemoryStream.Free;
end;
if assigned(SpriteAtlasArrayTexture) then begin
MemoryStream:=TMemoryStream.Create;
try
aStream.Seek(0,soBeginning);
MemoryStream.CopyFrom(aStream,aStream.Size);
MemoryStream.Seek(0,soBeginning);
XML:=TpvXML.Create;
try
if XML.Parse(MemoryStream) then begin
for i:=0 to XML.Root.Items.Count-1 do begin
XMLItem:=XML.Root.Items[i];
if assigned(XMLItem) and (XMLItem is TpvXMLTag) then begin
XMLTag:=TpvXMLTag(XMLItem);
if XMLTag.Name='TextureAtlas' then begin
for j:=0 to XMLTag.Items.Count-1 do begin
XMLChildrenItem:=XMLTag.Items[j];
if assigned(XMLChildrenItem) and (XMLChildrenItem is TpvXMLTag) then begin
XMLChildrenTag:=TpvXMLTag(XMLChildrenItem);
if XMLChildrenTag.Name='sprite' then begin
SpriteName:=XMLChildrenTag.GetParameter('n','');
if length(SpriteName)>0 then begin
Sprite:=TpvSprite.Create;
Sprite.ArrayTexture:=SpriteAtlasArrayTexture;
Sprite.Name:=SpriteName;
Sprite.x:=StrToIntDef(String(XMLChildrenTag.GetParameter('x','0')),0);
Sprite.y:=StrToIntDef(String(XMLChildrenTag.GetParameter('y','0')),0);
Sprite.Layer:=0;
Sprite.Width:=StrToIntDef(String(XMLChildrenTag.GetParameter('oW',XMLChildrenTag.GetParameter('w','0'))),0);
Sprite.Height:=StrToIntDef(String(XMLChildrenTag.GetParameter('oH',XMLChildrenTag.GetParameter('h','0'))),0);
Sprite.TrimmedX:=StrToIntDef(String(XMLChildrenTag.GetParameter('oX','0')),0);
Sprite.TrimmedY:=StrToIntDef(String(XMLChildrenTag.GetParameter('oY','0')),0);
Sprite.TrimmedWidth:=StrToIntDef(String(XMLChildrenTag.GetParameter('w','0')),0);
Sprite.TrimmedHeight:=StrToIntDef(String(XMLChildrenTag.GetParameter('h','0')),0);
Sprite.Rotated:=XMLChildrenTag.GetParameter('r','n')='y';
Sprite.Update;
AddSprite(Sprite);
end;
end;
end;
end;
end;
end;
end;
end;
finally
XML.Free;
end;
finally
MemoryStream.Free;
end;
result:=true;
end;
end;
end;
function TpvSpriteAtlas.LoadRawSprite(const aName:TpvRawByteString;aImageData:TpvPointer;const aImageWidth,aImageHeight:TpvInt32;const aAutomaticTrim:boolean=true;const aPadding:TpvInt32=2;const aTrimPadding:TpvInt32=1;const aDepth16Bit:boolean=false;const aTrimmedHullVectors:PpvSpriteTrimmedHullVectors=nil):TpvSprite;
var x,y,x0,y0,x1,y1,TextureIndex,LayerIndex,Layer,TotalPadding,PaddingIndex,Index:TpvInt32;
ArrayTexture,TemporaryArrayTexture:TpvSpriteAtlasArrayTexture;
Node:PpvSpriteAtlasArrayTextureLayerRectNode;
Sprite:TpvSprite;
sp,dp:PpvUInt32;
sp16,dp16:PpvUInt64;
p8:PpvUInt8;
p16:PpvUInt16;
OK,SpecialSizedArrayTexture:boolean;
WorkImageData,TrimmedImageData:TpvPointer;
TrimmedImageWidth:TpvInt32;
TrimmedImageHeight:TpvInt32;
ConvexHull2DPixels:TpvConvexHull2DPixels;
TrimmedHullVectors:TpvSpriteTrimmedHullVectors;
CenterX,CenterY,CenterRadius:TpvFloat;
begin
result:=nil;
TrimmedHullVectors:=nil;
TrimmedImageData:=nil;
try
TotalPadding:=aPadding shl 1;
ArrayTexture:=nil;
Node:=nil;
Layer:=-1;
if assigned(aImageData) and (aImageWidth>0) and (aImageHeight>0) then begin
WorkImageData:=aImageData;
try
if aDepth16Bit and not fDepth16Bit then begin
// Convert to R8G8B8A8
GetMem(WorkImageData,aImageWidth*aImageHeight*4);
p8:=WorkImageData;
p16:=aImageData;
for Index:=1 to aImageWidth*aImageHeight*4 do begin
p8^:=p16^ shr 8;
inc(p8);
inc(p16);
end;
end else if fDepth16Bit and not aDepth16Bit then begin
// Convert to R16G1B16A16
GetMem(WorkImageData,aImageWidth*aImageHeight*8);
p8:=aImageData;
p16:=WorkImageData;
for Index:=1 to aImageWidth*aImageHeight*4 do begin
p16^:=p8^ or (TpvUInt16(p8^) shl 8);
inc(p8);
inc(p16);
end;
end;
x0:=0;
y0:=0;
x1:=aImageWidth;
y1:=aImageHeight;
if aAutomaticTrim then begin
// Trim input
if fDepth16Bit then begin
for x:=0 to aImageWidth-1 do begin
OK:=true;
for y:=0 to aImageHeight-1 do begin
sp16:=WorkImageData;
inc(sp16,(y*aImageWidth)+x);
if ((sp16^ shr 56) and $ff)<>0 then begin
OK:=false;
break;
end;
end;
if OK then begin
x0:=x;
end else begin
break;
end;
end;
sp16:=WorkImageData;
for y:=0 to aImageHeight-1 do begin
OK:=true;
for x:=0 to aImageWidth-1 do begin
if ((sp16^ shr 56) and $ff)<>0 then begin
OK:=false;
break;
end;
inc(sp16);
end;
if OK then begin
y0:=y;
end else begin
break;
end;
end;
for x:=aImageWidth-1 downto 0 do begin
OK:=true;
for y:=0 to aImageHeight-1 do begin
sp16:=WorkImageData;
inc(sp16,(y*aImageWidth)+x);
if ((sp16^ shr 56) and $ff)<>0 then begin
OK:=false;
break;
end;
end;
if OK then begin
x1:=x+1;
end else begin
break;
end;
end;
for y:=aImageHeight-1 downto 0 do begin
OK:=true;
sp16:=WorkImageData;
inc(sp16,y*aImageWidth);
for x:=0 to aImageWidth-1 do begin
if ((sp16^ shr 56) and $ff)<>0 then begin
OK:=false;
break;
end;
inc(sp16);
end;
if OK then begin
y1:=y+1;
end else begin
break;
end;
end;
end else begin
for x:=0 to aImageWidth-1 do begin
OK:=true;
for y:=0 to aImageHeight-1 do begin
sp:=WorkImageData;
inc(sp,(y*aImageWidth)+x);
if (sp^ and $ff000000)<>0 then begin
OK:=false;
break;
end;
end;
if OK then begin
x0:=x;
end else begin
break;
end;
end;
sp:=WorkImageData;
for y:=0 to aImageHeight-1 do begin
OK:=true;
for x:=0 to aImageWidth-1 do begin
if (sp^ and $ff000000)<>0 then begin
OK:=false;
break;
end;
inc(sp);
end;
if OK then begin
y0:=y;
end else begin
break;
end;
end;
for x:=aImageWidth-1 downto 0 do begin
OK:=true;
for y:=0 to aImageHeight-1 do begin
sp:=WorkImageData;
inc(sp,(y*aImageWidth)+x);
if (sp^ and $ff000000)<>0 then begin
OK:=false;
break;
end;
end;
if OK then begin
x1:=x+1;
end else begin
break;
end;
end;
for y:=aImageHeight-1 downto 0 do begin
OK:=true;
sp:=WorkImageData;
inc(sp,y*aImageWidth);
for x:=0 to aImageWidth-1 do begin
if (sp^ and $ff000000)<>0 then begin
OK:=false;
break;
end;
inc(sp);
end;
if OK then begin
y1:=y+1;
end else begin
break;
end;
end;
end;
end;
TrimmedImageData:=nil;
try
if (x0<x1) and (y0<y1) and not ((x0=0) and (y0=0) and (x1=aImageWidth) and (y1=aImageHeight)) then begin
if aTrimPadding>0 then begin
x0:=Max(0,x0-aTrimPadding);
y0:=Max(0,y0-aTrimPadding);
x1:=Min(aImageWidth,x1+aTrimPadding);
y1:=Min(aImageHeight,y1+aTrimPadding);
end;
TrimmedImageWidth:=x1-x0;
TrimmedImageHeight:=y1-y0;
if fDepth16Bit then begin
GetMem(TrimmedImageData,TrimmedImageWidth*TrimmedImageHeight*SizeOf(TpvUInt64));
dp16:=TrimmedImageData;
for y:=y0 to y1-1 do begin
sp16:=WorkImageData;
inc(sp16,(y*aImageWidth)+x0);
for x:=x0 to x1-1 do begin
dp16^:=sp16^;
inc(sp16);
inc(dp16);
end;
end;
end else begin
GetMem(TrimmedImageData,TrimmedImageWidth*TrimmedImageHeight*SizeOf(TpvUInt32));
dp:=TrimmedImageData;
for y:=y0 to y1-1 do begin
sp:=WorkImageData;
inc(sp,(y*aImageWidth)+x0);
for x:=x0 to x1-1 do begin
dp^:=sp^;
inc(sp);
inc(dp);
end;
end;
end;
end else begin
TrimmedImageWidth:=aImageWidth;
TrimmedImageHeight:=aImageHeight;
if fDepth16Bit then begin
GetMem(TrimmedImageData,TrimmedImageWidth*TrimmedImageHeight*SizeOf(TpvUInt64));
Move(WorkImageData^,TrimmedImageData^,TrimmedImageWidth*TrimmedImageHeight*SizeOf(TpvUInt64));
end else begin
GetMem(TrimmedImageData,TrimmedImageWidth*TrimmedImageHeight*SizeOf(TpvUInt32));
Move(WorkImageData^,TrimmedImageData^,TrimmedImageWidth*TrimmedImageHeight*SizeOf(TpvUInt32));
end;
x0:=0;
y0:=0;
end;
finally
if WorkImageData<>aImageData then begin
FreeMem(WorkImageData);
end;
end;
if fUseConvexHullTrimming and ((TrimmedImageWidth*TrimmedImageHeight)>0) then begin
if assigned(aTrimmedHullVectors) then begin
TrimmedHullVectors:=copy(aTrimmedHullVectors^);
for x:=0 to length(TrimmedHullVectors)-1 do begin
TrimmedHullVectors[x].xy:=TrimmedHullVectors[x].xy-TpvVector2.InlineableCreate(x0,y0);
end;
end else if aAutomaticTrim then begin
ConvexHull2DPixels:=nil;
try
SetLength(ConvexHull2DPixels,TrimmedImageWidth*TrimmedImageHeight);
if fDepth16Bit then begin
for y:=0 to TrimmedImageHeight-1 do begin
for x:=0 to TrimmedImageWidth-1 do begin
sp16:=TrimmedImageData;
inc(sp16,(y*TrimmedImageWidth)+x);
ConvexHull2DPixels[(y*TrimmedImageWidth)+x]:=((sp16^ shr 56) and $ff)<>0;
end;
end;
end else begin
for y:=0 to TrimmedImageHeight-1 do begin
for x:=0 to TrimmedImageWidth-1 do begin
sp:=TrimmedImageData;
inc(sp,(y*TrimmedImageWidth)+x);
ConvexHull2DPixels[(y*TrimmedImageWidth)+x]:=(sp^ and $ff000000)<>0;
end;
end;
end;
GetConvexHull2D(ConvexHull2DPixels,
TrimmedImageWidth,
TrimmedImageHeight,
TrimmedHullVectors,
8,
CenterX,
CenterY,
CenterRadius,
1.0,//Max(1.0,aPadding*0.5),
1.0,//Max(1.0,aPadding*0.5),
2);
finally
ConvexHull2DPixels:=nil;
end;
end;
end;
ArrayTexture:=nil;
// Get free texture area
for TextureIndex:=0 to fCountArrayTextures-1 do begin
TemporaryArrayTexture:=fArrayTextures[TextureIndex];
if not TemporaryArrayTexture.fSpecialSizedArrayTexture then begin
for LayerIndex:=0 to TemporaryArrayTexture.fLayers-1 do begin
if assigned(TemporaryArrayTexture.fLayerRootNodes[LayerIndex]) then begin
// Including 2px texel bilinear interpolation protection border pixels
Node:=InsertTextureRectNode(TemporaryArrayTexture.fLayerRootNodes[LayerIndex],
TrimmedImageWidth+TotalPadding,
TrimmedImageHeight+TotalPadding,
(TrimmedImageWidth+TotalPadding)*(TrimmedImageHeight+TotalPadding));
if assigned(TemporaryArrayTexture) and assigned(Node) then begin
ArrayTexture:=TemporaryArrayTexture;
Layer:=LayerIndex;
break;
end;
end;
if (Layer>=0) and (assigned(ArrayTexture) and assigned(Node)) then begin
break;
end;
end;
end;
end;
SpecialSizedArrayTexture:=false;
// First try to resize a already existent atlas array texture by an one new layer, but not on
// special sized atlas array textures for big sprites, which are larger than a normal atlas
// array texture in width and height, or for external imported sprite atlases
if (Layer<0) or not (assigned(ArrayTexture) and assigned(Node)) then begin
for TextureIndex:=0 to fCountArrayTextures-1 do begin
TemporaryArrayTexture:=fArrayTextures[TextureIndex];
if ((TrimmedImageWidth+TotalPadding)<=TemporaryArrayTexture.fWidth) and
((TrimmedImageHeight+TotalPadding)<=TemporaryArrayTexture.fHeight) and
(TemporaryArrayTexture.fLayers<fMaximumCountArrayLayers) and
not TemporaryArrayTexture.fSpecialSizedArrayTexture then begin
LayerIndex:=TemporaryArrayTexture.fLayers;
TemporaryArrayTexture.Resize(TemporaryArrayTexture.fWidth,TemporaryArrayTexture.fHeight,LayerIndex+1);
Node:=InsertTextureRectNode(TemporaryArrayTexture.fLayerRootNodes[LayerIndex],
TrimmedImageWidth+TotalPadding,
TrimmedImageHeight+TotalPadding,
(TrimmedImageWidth+TotalPadding)*(TrimmedImageHeight+TotalPadding));
if assigned(Node) then begin
ArrayTexture:=TemporaryArrayTexture;
Layer:=LayerIndex;
break;
end else begin
// Undo for saving vRAM space
TemporaryArrayTexture.Resize(TemporaryArrayTexture.fWidth,TemporaryArrayTexture.fHeight,TemporaryArrayTexture.fLayers-1);
end;
end;
end;
end;
// Otherwise allocate a fresh new atlas array texture
if (Layer<0) or not (assigned(ArrayTexture) and assigned(Node)) then begin
Layer:=0;
SpecialSizedArrayTexture:=(fWidth<=TrimmedImageWidth) or (fHeight<=TrimmedImageHeight);
ArrayTexture:=TpvSpriteAtlasArrayTexture.Create(fSRGB,fDepth16Bit);
ArrayTexture.fSpecialSizedArrayTexture:=SpecialSizedArrayTexture;
ArrayTexture.Resize(Max(fWidth,TrimmedImageWidth),Max(fHeight,TrimmedImageHeight),1);
if length(fArrayTextures)<(fCountArrayTextures+1) then begin
SetLength(fArrayTextures,(fCountArrayTextures+1)*2);
end;
fArrayTextures[fCountArrayTextures]:=ArrayTexture;
inc(fCountArrayTextures);
ArrayTexture.Dirty:=true;
if SpecialSizedArrayTexture then begin
Node:=InsertTextureRectNode(ArrayTexture.fLayerRootNodes[Layer],
TrimmedImageWidth,
TrimmedImageHeight,
TrimmedImageWidth*TrimmedImageHeight);
end else begin
Node:=InsertTextureRectNode(ArrayTexture.fLayerRootNodes[Layer],
TrimmedImageWidth+TotalPadding,
TrimmedImageHeight+TotalPadding,
(TrimmedImageWidth+TotalPadding)*(TrimmedImageHeight+TotalPadding));
end;
end;
Assert((Layer>=0) and (assigned(ArrayTexture) and (Layer<ArrayTexture.fLayers) and assigned(Node)));
if not ((Layer>=0) and (assigned(ArrayTexture) and (Layer<ArrayTexture.fLayers) and assigned(Node))) then begin
raise EpvSpriteAtlas.Create('Can''t load raw sprite');
end;
begin
Sprite:=TpvSprite.Create;
Sprite.ArrayTexture:=ArrayTexture;
Sprite.Layer:=Layer;
Sprite.Name:=aName;
if SpecialSizedArrayTexture then begin
Sprite.fX:=Node^.x;
Sprite.fY:=Node^.y;
Sprite.fWidth:=aImageWidth;
Sprite.fHeight:=aImageHeight;
Sprite.fTrimmedX:=x0;
Sprite.fTrimmedY:=y0;
Sprite.fTrimmedWidth:=TrimmedImageWidth;
Sprite.fTrimmedHeight:=TrimmedImageHeight;
Sprite.fTrimmedHullVectors:=TrimmedHullVectors;
Sprite.Rotated:=false;
AddSprite(Sprite);
if fDepth16Bit then begin
for y:=0 to TrimmedImageHeight-1 do begin
sp16:=TrimmedImageData;
inc(sp16,y*TrimmedImageWidth);
dp16:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+y,Layer));
Move(sp16^,dp16^,TrimmedImageWidth*SizeOf(TpvUInt64));
end;
end else begin
for y:=0 to TrimmedImageHeight-1 do begin
sp:=TrimmedImageData;
inc(sp,y*TrimmedImageWidth);
dp:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+y,Layer));
Move(sp^,dp^,TrimmedImageWidth*SizeOf(TpvUInt32));
end;
end;
end else begin
Sprite.fX:=Node^.x+aPadding;
Sprite.fY:=Node^.y+aPadding;
Sprite.fWidth:=aImageWidth;
Sprite.fHeight:=aImageHeight;
Sprite.fTrimmedX:=x0;
Sprite.fTrimmedY:=y0;
Sprite.fTrimmedWidth:=TrimmedImageWidth;
Sprite.fTrimmedHeight:=TrimmedImageHeight;
Sprite.fTrimmedHullVectors:=TrimmedHullVectors;
Sprite.Rotated:=false;
AddSprite(Sprite);
if fDepth16Bit then begin
for y:=0 to TrimmedImageHeight-1 do begin
sp16:=TrimmedImageData;
inc(sp16,y*TrimmedImageWidth);
dp16:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+y,Layer));
Move(sp16^,dp16^,TrimmedImageWidth*SizeOf(TpvUInt64));
end;
begin
sp16:=TrimmedImageData;
for PaddingIndex:=-1 downto -aPadding do begin
dp16:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+PaddingIndex,Layer));
Move(sp16^,dp16^,TrimmedImageWidth*SizeOf(TpvUInt64));
end;
sp16:=TrimmedImageData;
inc(sp16,(TrimmedImageHeight-1)*TrimmedImageWidth);
for PaddingIndex:=0 to aPadding-1 do begin
dp16:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+TrimmedImageHeight+PaddingIndex,Layer));
Move(sp16^,dp16^,TrimmedImageWidth*SizeOf(TpvUInt64));
end;
end;
for y:=-1 to TrimmedImageHeight do begin
sp16:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+y,Layer));
for PaddingIndex:=-1 downto -aPadding do begin
dp16:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x+PaddingIndex,Sprite.y+y,Layer));
dp16^:=sp16^;
end;
sp16:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x+(TrimmedImageWidth-1),Sprite.y+y,Layer));
for PaddingIndex:=0 to aPadding-1 do begin
dp16:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x+TrimmedImageWidth+PaddingIndex,Sprite.y+y,Layer));
dp16^:=sp16^;
end;
end;
end else begin
for y:=0 to TrimmedImageHeight-1 do begin
sp:=TrimmedImageData;
inc(sp,y*TrimmedImageWidth);
dp:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+y,Layer));
Move(sp^,dp^,TrimmedImageWidth*SizeOf(TpvUInt32));
end;
begin
sp:=TrimmedImageData;
for PaddingIndex:=-1 downto -aPadding do begin
dp:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+PaddingIndex,Layer));
Move(sp^,dp^,TrimmedImageWidth*SizeOf(TpvUInt32));
end;
sp:=TrimmedImageData;
inc(sp,(TrimmedImageHeight-1)*TrimmedImageWidth);
for PaddingIndex:=0 to aPadding-1 do begin
dp:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+TrimmedImageHeight+PaddingIndex,Layer));
Move(sp^,dp^,TrimmedImageWidth*SizeOf(TpvUInt32));
end;
end;
for y:=-1 to TrimmedImageHeight do begin
sp:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x,Sprite.y+y,Layer));
for PaddingIndex:=-1 downto -aPadding do begin
dp:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x+PaddingIndex,Sprite.y+y,Layer));
dp^:=sp^;
end;
sp:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x+(TrimmedImageWidth-1),Sprite.y+y,Layer));
for PaddingIndex:=0 to aPadding-1 do begin
dp:=TpvPointer(ArrayTexture.GetTexelPointer(Sprite.x+TrimmedImageWidth+PaddingIndex,Sprite.y+y,Layer));
dp^:=sp^;
end;
end;
end;
end;
ArrayTexture.Dirty:=true;
end;
finally
if assigned(TrimmedImageData) then begin
FreeMem(TrimmedImageData);
end;
end;
Sprite.Update;
result:=Sprite;
end else begin
raise EpvSpriteAtlas.Create('Can''t load sprite');
end;
finally
TrimmedHullVectors:=nil;
end;
end;
function TpvSpriteAtlas.LoadSignedDistanceFieldSprite(const aName:TpvRawByteString;const aVectorPath:TpvVectorPath;const aImageWidth,aImageHeight:TpvInt32;const aScale:TpvDouble;const aOffsetX:TpvDouble;const aOffsetY:TpvDouble;const aAutomaticTrim:boolean;const aPadding:TpvInt32;const aTrimPadding:TpvInt32;const aSDFVariant:TpvSignedDistanceField2DVariant;const aProtectBorder:boolean):TpvSprite;
var SignedDistanceField:TpvSignedDistanceField2D;
VectorPathShape:TpvVectorPathShape;
begin
SignedDistanceField.Pixels:=nil;
try
SignedDistanceField.Width:=aImageWidth;
SignedDistanceField.Height:=aImageHeight;
SetLength(SignedDistanceField.Pixels,aImageWidth*aImageHeight);
VectorPathShape:=TpvVectorPathShape.Create(aVectorPath);
try
TpvSignedDistanceField2DGenerator.Generate(SignedDistanceField,VectorPathShape,aScale,aOffsetX,aOffsetY,aSDFVariant,aProtectBorder);
finally
FreeAndNil(VectorPathShape);
end;
result:=LoadRawSprite(aName,@SignedDistanceField.Pixels[0],aImageWidth,aImageHeight,aAutomaticTrim,aPadding,aTrimPadding);
result.SignedDistanceField:=true;
result.SignedDistanceFieldVariant:=aSDFVariant;
finally
SignedDistanceField.Pixels:=nil;
end;
end;
function TpvSpriteAtlas.LoadSignedDistanceFieldSprite(const aName,aSVGPath:TpvRawByteString;const aImageWidth,aImageHeight:TpvInt32;const aScale:TpvDouble;const aOffsetX:TpvDouble;const aOffsetY:TpvDouble;const aVectorPathFillRule:TpvVectorPathFillRule;const aAutomaticTrim:boolean;const aPadding:TpvInt32;const aTrimPadding:TpvInt32;const aSDFVariant:TpvSignedDistanceField2DVariant;const aProtectBorder:boolean):TpvSprite;
var VectorPath:TpvVectorPath;
begin
VectorPath:=TpvVectorPath.CreateFromSVGPath(aSVGPath);
try
VectorPath.FillRule:=aVectorPathFillRule;
result:=LoadSignedDistanceFieldSprite(aName,VectorPath,aImageWidth,aImageHeight,aScale,aOffsetX,aOffsetY,aAutomaticTrim,aPadding,aTrimPadding,aSDFVariant,aProtectBorder);
finally
VectorPath.Free;
end;
end;
function TpvSpriteAtlas.LoadSprite(const aName:TpvRawByteString;aStream:TStream;const aAutomaticTrim:boolean=true;const aPadding:TpvInt32=2;const aTrimPadding:TpvInt32=1):TpvSprite;
var InputImageData,ImageData:TpvPointer;
InputImageDataSize,ImageWidth,ImageHeight:TpvInt32;
begin
result:=nil;
if assigned(aStream) then begin
try
InputImageDataSize:=aStream.Size;
GetMem(InputImageData,InputImageDataSize);
try
aStream.Seek(0,soBeginning);
aStream.Read(InputImageData^,InputImageDataSize);
ImageData:=nil;
try
if LoadImage(InputImageData,InputImageDataSize,ImageData,ImageWidth,ImageHeight) then begin
result:=LoadRawSprite(aName,ImageData,ImageWidth,ImageHeight,aAutomaticTrim,aPadding,aTrimPadding);
end else begin
raise EpvSpriteAtlas.Create('Can''t load image');
end;
finally
if assigned(ImageData) then begin
FreeMem(ImageData);
end;
end;
finally
if assigned(InputImageData) then begin
FreeMem(InputImageData);
end;
end;
finally
end;
end else begin
raise EpvSpriteAtlas.Create('Can''t load sprite');
end;
end;
function TpvSpriteAtlas.LoadSprites(const aName:TpvRawByteString;aStream:TStream;aSpriteWidth:TpvInt32=64;aSpriteHeight:TpvInt32=64;const aAutomaticTrim:boolean=true;const aPadding:TpvInt32=2;const aTrimPadding:TpvInt32=1):TpvSprites;
var InputImageData,ImageData,SpriteData:TpvPointer;
InputImageDataSize,ImageWidth,ImageHeight,Count,x,y,sy,sw,sh:TpvInt32;
sp,dp:PpvUInt32;
begin
result:=nil;
if assigned(aStream) and (aSpriteWidth>0) and (aSpriteHeight>0) then begin
try
InputImageDataSize:=aStream.Size;
GetMem(InputImageData,InputImageDataSize);
try
aStream.Seek(0,soBeginning);
aStream.Read(InputImageData^,InputImageDataSize);
ImageData:=nil;
try
if LoadImage(InputImageData,InputImageDataSize,ImageData,ImageWidth,ImageHeight) then begin
GetMem(SpriteData,(aSpriteWidth*aSpriteHeight)*SizeOf(TpvUInt32));
try
Count:=((ImageWidth+(aSpriteWidth-1)) div aSpriteWidth)*((ImageHeight+(aSpriteHeight-1)) div aSpriteHeight);
SetLength(result,Count);
Count:=0;
y:=0;
while y<ImageHeight do begin
sh:=ImageHeight-y;
if sh<0 then begin
sh:=0;
end else if sh>aSpriteHeight then begin
sh:=aSpriteHeight;
end;
if sh>0 then begin
x:=0;
while x<ImageWidth do begin
FillChar(SpriteData^,(aSpriteWidth*aSpriteHeight)*SizeOf(TpvUInt32),AnsiChar(#0));
sw:=ImageWidth-x;
if sw<0 then begin
sw:=0;
end else if sw>aSpriteWidth then begin
sw:=aSpriteWidth;
end;
if sw>0 then begin
sp:=ImageData;
inc(sp,(ImageWidth*y)+x);
dp:=SpriteData;
for sy:=0 to sh-1 do begin
Move(sp^,dp^,sw*SizeOf(TpvUInt32));
inc(sp,ImageWidth);
inc(dp,aSpriteWidth);
end;
result[Count]:=LoadRawSprite(aName+TpvRawByteString(IntToStr(Count)),SpriteData,aSpriteWidth,aSpriteHeight,aAutomaticTrim,aPadding,aTrimPadding);
inc(Count);
end else begin
break;
end;
inc(x,aSpriteWidth);
end;
end else begin
break;
end;
inc(y,aSpriteHeight);
end;
SetLength(result,Count);
finally
FreeMem(SpriteData);
end;
end else begin
raise EpvSpriteAtlas.Create('Can''t load image');
end;
finally
if assigned(ImageData) then begin
FreeMem(ImageData);
end;
end;
finally
if assigned(InputImageData) then begin
FreeMem(InputImageData);
end;
end;
finally
end;
end else begin
raise EpvSpriteAtlas.Create('Can''t load sprites');
end;
end;
procedure TpvSpriteAtlas.LoadFromStream(const aStream:TStream);
var Archive:TpvArchiveZIP;
Stream:TMemoryStream;
Entry:TpvArchiveZIPEntry;
Index,SubIndex,SubSubIndex:TpvSizeInt;
ArrayTexture:TpvSpriteAtlasArrayTexture;
Sprite:TpvSprite;
ImageData:TpvPointer;
ImageWidth,ImageHeight:TpvInt32;
PNGPixelFormat:TpvPNGPixelFormat;
p8:PpvUInt8;
p16:PpvUInt16;
BufferedStream:TpvSimpleBufferedStream;
function ReadUInt8:TpvUInt8;
begin
BufferedStream.ReadBuffer(result,SizeOf(TpvUInt8));
end;
function ReadUInt16:TpvUInt16;
begin
result:=ReadUInt8;
result:=result or (TpvUInt16(ReadUInt8) shl 8);
end;
function ReadUInt32:TpvUInt32;
begin
result:=ReadUInt8;
result:=result or (TpvUInt32(ReadUInt8) shl 8);
result:=result or (TpvUInt32(ReadUInt8) shl 16);
result:=result or (TpvUInt32(ReadUInt8) shl 24);
end;
function ReadInt32:TpvInt32;
begin
result:=ReadUInt32;
end;
function ReadUInt64:TpvUInt64;
begin
result:=ReadUInt8;
result:=result or (TpvUInt64(ReadUInt8) shl 8);
result:=result or (TpvUInt64(ReadUInt8) shl 16);
result:=result or (TpvUInt64(ReadUInt8) shl 24);
result:=result or (TpvUInt64(ReadUInt8) shl 32);
result:=result or (TpvUInt64(ReadUInt8) shl 40);
result:=result or (TpvUInt64(ReadUInt8) shl 48);
result:=result or (TpvUInt64(ReadUInt8) shl 56);
end;
function ReadInt64:TpvInt64;
begin
result:=ReadUInt64;
end;
function ReadFloat:TpvFloat;
begin
PpvUInt32(TpvPointer(@result))^:=ReadUInt32;
end;
function ReadDouble:TpvDouble;
begin
PpvUInt64(TpvPointer(@result))^:=ReadUInt64;
end;
function ReadString:TpvRawByteString;
begin
result:='';
SetLength(result,ReadInt32);
if length(result)>0 then begin
BufferedStream.ReadBuffer(result[1],length(result));
end;
end;
var FileGUID:TGUID;
ui8:TpvUInt8;
NewImageData:TpvPointer;
WidthValue,HeightValue,LayersValue,CountSprites,CountTrimmedHullVectors:TpvInt32;
IsQOI,SRGBQOI,OK:Boolean;
begin
Unload;
for Index:=0 to fCountArrayTextures-1 do begin
FreeAndNil(fArrayTextures[Index]);
end;
fArrayTextures:=nil;
ClearAll;
Archive:=TpvArchiveZIP.Create;
try
Archive.LoadFromStream(aStream);
Entry:=Archive.Entries.Find('sprites.dat');
if not assigned(Entry) then begin
raise EpvSpriteAtlas.Create('Missing sprites.dat');
end;
Stream:=TMemoryStream.Create;
try
Entry.SaveToStream(Stream);
BufferedStream:=TpvSimpleBufferedStream.Create(Stream,false,4096);
try
FileGUID.D1:=ReadUInt32;
FileGUID.D2:=ReadUInt16;
FileGUID.D3:=ReadUInt16;
FileGUID.D4[0]:=ReadUInt8;
FileGUID.D4[1]:=ReadUInt8;
FileGUID.D4[2]:=ReadUInt8;
FileGUID.D4[3]:=ReadUInt8;
FileGUID.D4[4]:=ReadUInt8;
FileGUID.D4[5]:=ReadUInt8;
FileGUID.D4[6]:=ReadUInt8;
FileGUID.D4[7]:=ReadUInt8;
if not CompareMem(@TpvSpriteAtlas.FileFormatGUID,@FileGUID,SizeOf(TGUID)) then begin
raise EpvSpriteAtlas.Create('Mismatch file format GUID');
end;
fWidth:=ReadInt32;
fHeight:=ReadInt32;
fMaximumCountArrayLayers:=ReadInt32;
ui8:=ReadUInt8;
fMipMaps:=(ui8 and 1)<>0;
fSRGB:=(ui8 and 2)<>0;
fUseConvexHullTrimming:=(ui8 and 4)<>0;
fDepth16Bit:=(ui8 and 8)<>0;
fCountArrayTextures:=ReadInt32;
CountSprites:=ReadInt32;
SetLength(fArrayTextures,fCountArrayTextures);
for Index:=0 to fCountArrayTextures-1 do begin
fArrayTextures[Index]:=TpvSpriteAtlasArrayTexture.Create(fSRGB,fDepth16Bit);
end;
for Index:=0 to fCountArrayTextures-1 do begin
ArrayTexture:=fArrayTextures[Index];
WidthValue:=ReadInt32;
HeightValue:=ReadInt32;
LayersValue:=ReadInt32;
ArrayTexture.Resize(WidthValue,HeightValue,LayersValue);
ui8:=ReadUInt8;
ArrayTexture.fSpecialSizedArrayTexture:=true;
ArrayTexture.fDirty:=true;
end;
for Index:=0 to CountSprites-1 do begin
Sprite:=TpvSprite.Create;
try
Sprite.fName:=ReadString;
SubIndex:=ReadInt32;
if (SubIndex<0) or (SubIndex>=fCountArrayTextures) then begin
raise EpvSpriteAtlas.Create('Sprite array texture index out of range');
end;
Sprite.fArrayTexture:=fArrayTextures[SubIndex];
ui8:=ReadUInt8;
Sprite.fFlags:=[];
if (ui8 and 1)<>0 then begin
Include(Sprite.fFlags,TpvSpriteFlag.SignedDistanceField);
end;
if (ui8 and 2)<>0 then begin
Include(Sprite.fFlags,TpvSpriteFlag.Rotated);
end;
Sprite.fX:=ReadInt32;
Sprite.fY:=ReadInt32;
Sprite.fLayer:=ReadInt32;
Sprite.fWidth:=ReadInt32;
Sprite.fHeight:=ReadInt32;
Sprite.fTrimmedX:=ReadInt32;
Sprite.fTrimmedY:=ReadInt32;
Sprite.fTrimmedWidth:=ReadInt32;
Sprite.fTrimmedHeight:=ReadInt32;
Sprite.fOffsetX:=ReadFloat;
Sprite.fOffsetY:=ReadFloat;
Sprite.fScaleX:=ReadFloat;
Sprite.fScaleY:=ReadFloat;
if TpvSpriteFlag.SignedDistanceField in Sprite.fFlags then begin
Sprite.fSignedDistanceFieldVariant:=TpvSignedDistanceField2DVariant(TpvUInt8(ReadUInt8));
end;
Sprite.fTrimmedHullVectors:=nil;
if (ui8 and 4)<>0 then begin
CountTrimmedHullVectors:=ReadInt32;
if CountTrimmedHullVectors>0 then begin
SetLength(Sprite.fTrimmedHullVectors,CountTrimmedHullVectors);
for SubIndex:=0 to CountTrimmedHullVectors-1 do begin
Sprite.fTrimmedHullVectors[SubIndex].x:=ReadFloat;
Sprite.fTrimmedHullVectors[SubIndex].y:=ReadFloat;
end;
end;
end;
Sprite.Update;
finally
AddSprite(Sprite);
end;
end;
finally
BufferedStream.Free;
end;
finally
Stream.Free;
end;
for Index:=0 to fCountArrayTextures-1 do begin
ArrayTexture:=fArrayTextures[Index];
if assigned(ArrayTexture) then begin
for SubIndex:=0 to ArrayTexture.fLayers-1 do begin
IsQOI:=false;
Entry:=Archive.Entries.Find(TpvRawByteString(IntToStr(Index)+'_'+IntToStr(SubIndex)+'.png'));
if not assigned(Entry) then begin
Entry:=Archive.Entries.Find(TpvRawByteString(IntToStr(Index)+'_'+IntToStr(SubIndex)+'.qoi'));
if assigned(Entry) then begin
IsQOI:=true;
end else begin
raise EpvSpriteAtlas.Create('Missing '+IntToStr(Index)+'_'+IntToStr(SubIndex)+'.[png|qoi]');
end;
end;
Stream:=TMemoryStream.Create;
try
Entry.SaveToStream(Stream);
ImageData:=nil;
try
OK:=false;
if IsQOI then begin
if LoadQOIImage(TMemoryStream(Stream).Memory,
TMemoryStream(Stream).Size,
ImageData,
ImageWidth,
ImageHeight,
false,
SRGBQOI) then begin
OK:=true;
PNGPixelFormat:=TpvPNGPixelFormat.R8G8B8A8;
end;
end else begin
if LoadPNGImage(TMemoryStream(Stream).Memory,
TMemoryStream(Stream).Size,
ImageData,
ImageWidth,
ImageHeight,
false,
PNGPixelFormat) then begin
OK:=true;
end;
end;
if OK then begin
if (ImageWidth=ArrayTexture.fWidth) and
(ImageHeight=ArrayTexture.fHeight) then begin
if fDepth16Bit then begin
if PNGPixelFormat=TpvPNGPixelFormat.R8G8B8A8 then begin
// Convert to R16G1B16A16
GetMem(NewImageData,ImageWidth*ImageHeight*8);
try
p8:=ImageData;
p16:=NewImageData;
for SubSubIndex:=1 to ImageWidth*ImageHeight*4 do begin
p16^:=p8^ or (TpvUInt16(p8^) shl 8);
inc(p8);
inc(p16);
end;
finally
FreeMem(ImageData);
ImageData:=NewImageData;
end;
end;
end else begin
if PNGPixelFormat=TpvPNGPixelFormat.R16G16B16A16 then begin
// Convert to R8G8B8A8 in-place
p8:=ImageData;
p16:=ImageData;
for SubSubIndex:=1 to ImageWidth*ImageHeight*4 do begin
p8^:=p16^ shr 8;
inc(p8);
inc(p16);
end;
end;
end;
ArrayTexture.fLayerRootNodes[SubIndex].FreeArea:=0;
ArrayTexture.fLayerRootNodes[SubIndex].ContentWidth:=ImageWidth;
ArrayTexture.fLayerRootNodes[SubIndex].ContentHeight:=ImageHeight;
ArrayTexture.CopyIn(ImageData^,ImageWidth,ImageHeight,0,0,SubIndex);
end else begin
if IsQOI then begin
raise EpvSpriteAtlas.Create(IntToStr(Index)+'_'+IntToStr(SubIndex)+'.qoi has wrong size');
end else begin
raise EpvSpriteAtlas.Create(IntToStr(Index)+'_'+IntToStr(SubIndex)+'.png has wrong size');
end;
end;
end else begin
if IsQOI then begin
raise EpvSpriteAtlas.Create('Corrupt '+IntToStr(Index)+'_'+IntToStr(SubIndex)+'.qoi');
end else begin
raise EpvSpriteAtlas.Create('Corrupt '+IntToStr(Index)+'_'+IntToStr(SubIndex)+'.png');
end;
end;
finally
if assigned(ImageData) then begin
FreeMem(ImageData);
end;
end;
finally
Stream.Free;
end;
end;
end;
end;
finally
Archive.Free;
end;
end;
procedure TpvSpriteAtlas.LoadFromFile(const aFileName:string);
var Stream:TStream;
begin
Stream:=TFileStream.Create(aFileName,fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
procedure TpvSpriteAtlas.SaveToStream(const aStream:TStream;const aFast:boolean=false);
var Archive:TpvArchiveZIP;
Entry:TpvArchiveZIPEntry;
Index,SubIndex,SubSubIndex:TpvSizeInt;
ArrayTexture:TpvSpriteAtlasArrayTexture;
Sprite:TpvSprite;
BufferedStream:TpvSimpleBufferedStream;
procedure WriteUInt8(const aValue:TpvUInt8);
begin
BufferedStream.WriteBuffer(aValue,SizeOf(TpvUInt8));
end;
procedure WriteUInt16(const aValue:TpvUInt16);
begin
WriteUInt8(TpVUInt8(aValue shr 0));
WriteUInt8(TpVUInt8(aValue shr 8));
end;
procedure WriteUInt32(const aValue:TpvUInt32);
begin
WriteUInt8(TpVUInt8(aValue shr 0));
WriteUInt8(TpVUInt8(aValue shr 8));
WriteUInt8(TpVUInt8(aValue shr 16));
WriteUInt8(TpVUInt8(aValue shr 24));
end;
procedure WriteInt32(const aValue:TpvInt32);
begin
WriteUInt32(aValue);
end;
procedure WriteUInt64(const aValue:TpvUInt64);
begin
WriteUInt8(TpVUInt8(aValue shr 0));
WriteUInt8(TpVUInt8(aValue shr 8));
WriteUInt8(TpVUInt8(aValue shr 16));
WriteUInt8(TpVUInt8(aValue shr 24));
WriteUInt8(TpVUInt8(aValue shr 32));
WriteUInt8(TpVUInt8(aValue shr 40));
WriteUInt8(TpVUInt8(aValue shr 48));
WriteUInt8(TpVUInt8(aValue shr 56));
end;
procedure WriteInt64(const aValue:TpvInt64);
begin
WriteUInt64(aValue);
end;
procedure WriteFloat(const aValue:TpvFloat);
begin
WriteUInt32(PpvUInt32(TpvPointer(@aValue))^);
end;
procedure WriteDouble(const aValue:TpvDouble);
begin
WriteUInt64(PpvUInt64(TpvPointer(@aValue))^);
end;
procedure WriteString(const aValue:TpvRawByteString);
begin
WriteInt32(length(aValue));
if length(aValue)>0 then begin
BufferedStream.WriteBuffer(aValue[1],length(aValue));
end;
end;
begin
Archive:=TpvArchiveZIP.Create;
try
Entry:=Archive.Entries.Add('sprites.dat');
try
Entry.Stream:=TMemoryStream.Create;
try
BufferedStream:=TpvSimpleBufferedStream.Create(Entry.Stream,false,4096);
try
WriteUInt32(TpvSpriteAtlas.FileFormatGUID.D1);
WriteUInt16(TpvSpriteAtlas.FileFormatGUID.D2);
WriteUInt16(TpvSpriteAtlas.FileFormatGUID.D3);
WriteUInt8(TpvSpriteAtlas.FileFormatGUID.D4[0]);
WriteUInt8(TpvSpriteAtlas.FileFormatGUID.D4[1]);
WriteUInt8(TpvSpriteAtlas.FileFormatGUID.D4[2]);
WriteUInt8(TpvSpriteAtlas.FileFormatGUID.D4[3]);
WriteUInt8(TpvSpriteAtlas.FileFormatGUID.D4[4]);
WriteUInt8(TpvSpriteAtlas.FileFormatGUID.D4[5]);
WriteUInt8(TpvSpriteAtlas.FileFormatGUID.D4[6]);
WriteUInt8(TpvSpriteAtlas.FileFormatGUID.D4[7]);
WriteInt32(fWidth);
WriteInt32(fHeight);
WriteInt32(fMaximumCountArrayLayers);
WriteUInt8((TpvUInt8(ord(fMipMaps) and 1) shl 0) or
(TpvUInt8(ord(fsRGB) and 1) shl 1) or
(TpvUInt8(ord(fUseConvexHullTrimming) and 1) shl 2) or
(TpvUInt8(ord(fDepth16Bit) and 1) shl 3));
WriteInt32(fCountArrayTextures);
WriteInt32(fList.Count);
for Index:=0 to fCountArrayTextures-1 do begin
ArrayTexture:=fArrayTextures[Index];
WriteInt32(ArrayTexture.fWidth);
WriteInt32(ArrayTexture.fHeight);
WriteInt32(ArrayTexture.fLayers);
WriteUInt8(0);
end;
for Index:=0 to fList.Count-1 do begin
Sprite:=fList[Index];
if assigned(Sprite) then begin
WriteString(Sprite.fName);
SubSubIndex:=0;
for SubIndex:=0 to fCountArrayTextures-1 do begin
if Sprite.fArrayTexture=fArrayTextures[SubIndex] then begin
SubSubIndex:=SubIndex;
break;
end;
end;
WriteInt32(SubSubIndex);
WriteUInt8((TpvUInt8(ord(TpvSpriteFlag.SignedDistanceField in Sprite.fFlags) and 1) shl 0) or
(TpvUInt8(ord(TpvSpriteFlag.Rotated in Sprite.fFlags) and 1) shl 1) or
(TpvUInt8(ord(length(Sprite.fTrimmedHullVectors)>0) and 1) shl 2));
WriteInt32(Sprite.fX);
WriteInt32(Sprite.fY);
WriteInt32(Sprite.fLayer);
WriteInt32(Sprite.fWidth);
WriteInt32(Sprite.fHeight);
WriteInt32(Sprite.fTrimmedX);
WriteInt32(Sprite.fTrimmedY);
WriteInt32(Sprite.fTrimmedWidth);
WriteInt32(Sprite.fTrimmedHeight);
WriteFloat(Sprite.fOffsetX);
WriteFloat(Sprite.fOffsetY);
WriteFloat(Sprite.fScaleX);
WriteFloat(Sprite.fScaleY);
if TpvSpriteFlag.SignedDistanceField in Sprite.fFlags then begin
WriteUInt8(TpvUInt8(Sprite.fSignedDistanceFieldVariant));
end;
if length(Sprite.fTrimmedHullVectors)>0 then begin
WriteInt32(length(Sprite.fTrimmedHullVectors));
for SubIndex:=0 to length(Sprite.fTrimmedHullVectors)-1 do begin
WriteFloat(Sprite.fTrimmedHullVectors[SubIndex].x);
WriteFloat(Sprite.fTrimmedHullVectors[SubIndex].y);
end;
end;
end;
end;
finally
BufferedStream.Free;
end;
finally
if aFast then begin
Entry.CompressionLevel:=2;
end else begin
Entry.CompressionLevel:=4;
end;
end;
finally
end;
for Index:=0 to fCountArrayTextures-1 do begin
ArrayTexture:=fArrayTextures[Index];
if assigned(ArrayTexture) then begin
for SubIndex:=0 to ArrayTexture.fLayers-1 do begin
if fDepth16Bit then begin
Entry:=Archive.Entries.Add(TpvRawByteString(IntToStr(Index)+'_'+IntToStr(SubIndex)+'.png'));
end else begin
Entry:=Archive.Entries.Add(TpvRawByteString(IntToStr(Index)+'_'+IntToStr(SubIndex)+'.png'));
end;
try
Entry.Stream:=TMemoryStream.Create;
if fDepth16Bit then begin
SavePNGImageAsStream(ArrayTexture.GetTexelPointer(0,0,SubIndex),
ArrayTexture.fWidth,
ArrayTexture.fHeight,
Entry.Stream,
TpvPNGPixelFormat.R16G16B16A16,
aFast);
end else begin
SavePNGImageAsStream(ArrayTexture.GetTexelPointer(0,0,SubIndex),
ArrayTexture.fWidth,
ArrayTexture.fHeight,
Entry.Stream,
TpvPNGPixelFormat.R8G8B8A8,
aFast);
{ SaveQOIImageAsStream(ArrayTexture.GetTexelPointer(0,0,SubIndex),
ArrayTexture.fWidth,
ArrayTexture.fHeight,
Entry.Stream,
true);}
end;
finally
Entry.CompressionLevel:=0;
end;
end;
end;
end;
Archive.SaveToStream(aStream);
finally
Archive.Free;
end;
end;
procedure TpvSpriteAtlas.SaveToFile(const aFileName:string;const aFast:boolean=false);
var Stream:TStream;
begin
Stream:=TFileStream.Create(aFileName,fmCreate);
try
SaveToStream(Stream,aFast);
finally
Stream.Free;
end;
end;
end.
|
unit uCefScriptClickElement;
interface
uses
//
//
uCefScriptBase, uCefScriptNavBase, uCefWebAction, uCefUtilType;
type
TScriptClickElement = class(TCefScriptNavBase)
private
FSpeed: Integer;
FTag: string;
FId: string;
FName: string;
FClass: string;
FAttrName: string;
FValueRegExpr: string;
FTextRegExpr: string;
protected
function DoNavEvent(const AWebAction: TCefWebAction): Boolean; override;
public
constructor Create(const ASpeed: TCefUISpeed; const ATag, AId, AName,
AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string;
const ASetAsNav: Boolean;
const AParent: TCefScriptBase); overload;
constructor Create(const ASpeed: TCefUISpeed; const AId: string;
const ASetAsNav: Boolean;
const AParent: TCefScriptBase); overload;
constructor Create(const AId: string; const ASetAsNav: Boolean;
const AParent: TCefScriptBase); overload;
class function GetScriptName: string; override;
end;
implementation
uses
//
uCefUIFunc, uCefUtilConst;
{ TScriptClickElement }
constructor TScriptClickElement.Create(const ASpeed: TCefUISpeed; const ATag, AId, AName,
AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string; const ASetAsNav: Boolean;
const AParent: TCefScriptBase);
begin
inherited Create('', ASetAsNav, AParent);
FSpeed := ASpeed;
FTag := ATag;
FId := AId;
FName := AName;
FClass := AClass;
FAttrName := AAttrName;
FValueRegExpr := AAttrValueRegExpr;
FTextRegExpr := ATextRegExpr;
//
if FSpeed = 0 then
FSpeed := SPEED_DEF
end;
constructor TScriptClickElement.Create(const ASpeed: TCefUISpeed; const AId: string;
const ASetAsNav: Boolean; const AParent: TCefScriptBase);
begin
Create(ASpeed, '', AId, '', '', '', '', '', ASetAsNav, AParent)
end;
constructor TScriptClickElement.Create(const AId: string;
const ASetAsNav: Boolean; const AParent: TCefScriptBase);
begin
Create(AParent.Controller.Speed, AId, ASetAsNav, AParent)
end;
function TScriptClickElement.DoNavEvent(const AWebAction: TCefWebAction): Boolean;
var bol: Boolean;
begin
bol := CefUIScrollToElement(Chromium.Browser, FAbortEvent, FSpeed, FTag, FId, FName, FClass, FAttrName, FValueRegExpr, FTextRegExpr);
if not bol then
begin
FailMsg2('fail scroll to element');
Exit(False);
end;
bol := CefUIMouseMoveToElement(Chromium.Browser, FAbortEvent, FController.Cursor, FSpeed, False, FTag, FId, FName, FClass, FAttrName, FValueRegExpr, FTextRegExpr);
if not bol then
begin
FailMsg2('fail mouse move to element');
Exit(False);
end;
CefUIMouseClick(Self);// Chromium.Browser, FController.Cursor);
Exit(True);
end;
class function TScriptClickElement.GetScriptName: string;
begin
Result := 'click';
end;
end.
|
unit frmMainUnit;
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,
RbwDataGrid4, System.Generics.Collections, Vcl.ComCtrls, Vcl.Mask, JvExMask,
JvToolEdit;
type
TScoringMatrix = array of array of integer;
TfrmMain = class(TForm)
pnl1: TPanel;
btn1: TButton;
ed1: TLabeledEdit;
pc1: TPageControl;
tabScoring_Matrix: TTabSheet;
tabPriorities: TTabSheet;
rdgPriorities: TRbwDataGrid4;
rdgScoringMatrix: TRbwDataGrid4;
btnAnalyze: TButton;
fedExcel: TJvFilenameEdit;
lbl1: TLabel;
fedCSV: TJvFilenameEdit;
lbl2: TLabel;
procedure btn1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure rdgPrioritiesBeforeDrawCell(Sender: TObject; ACol, ARow: Integer);
procedure btnAnalyzeClick(Sender: TObject);
private
procedure CalculateData(AXLSFile: string);
procedure InitializeScoringMatrix(var ScoringMatrix: TScoringMatrix);
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
const
TruePriorities: array[0..9] of Integer = (1,1,2,2,2,2,3,3,3,3);
xlWorkbookDefault = 51;
implementation
uses
Vcl.OleAuto;
{$R *.dfm}
procedure TfrmMain.btn1Click(Sender: TObject);
var
AnInt: Integer;
RowIndex: Integer;
Tier: Integer;
Value: Integer;
Score: Integer;
IntList: TList<Integer>;
ScoringMatrix: TScoringMatrix;
begin
Score := 0;
InitializeScoringMatrix(ScoringMatrix);
IntList := TList<Integer>.Create;
try
for RowIndex := 1 to rdgPriorities.RowCount - 1 do
begin
AnInt := StrToIntDef(rdgPriorities.Cells[1,RowIndex], 11);
if AnInt = 0 then
begin
AnInt := 11;
end;
if AnInt <> 11 then
begin
Assert(IntList.IndexOf(AnInt) < 0, 'No two items should receive the same rank.');
IntList.Add(AnInt);
end;
case RowIndex of
1..2: Tier := 1;
3..6: Tier := 2;
7..10: Tier := 3;
else Assert(False);
end;
Value := ScoringMatrix[AnInt-1, Tier-1];
Score := Score+ Value;
end;
finally
IntList.Free;
end;
ed1.Text := IntToStr(Score);
end;
procedure TfrmMain.btnAnalyzeClick(Sender: TObject);
begin
if FileExists(fedExcel.FileName) and (fedCSV.FileName <> '') then
begin
CalculateData(fedExcel.FileName);
ShowMessage('Done');
end
else
begin
Beep;
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
var
index: Integer;
begin
pc1.ActivePageIndex := 0;
rdgScoringMatrix.BeginUpdate;
try
for index := 1 to 10 do
begin
rdgScoringMatrix.Cells[index,0] := IntToStr(index);
end;
rdgScoringMatrix.Cells[11,0] := 'Missing or Wrong';
rdgScoringMatrix.Cells[0,1] := 'Tier 1';
rdgScoringMatrix.Cells[1,1] := '10';
rdgScoringMatrix.Cells[2,1] := '10';
rdgScoringMatrix.Cells[3,1] := '9';
rdgScoringMatrix.Cells[4,1] := '8';
rdgScoringMatrix.Cells[5,1] := '7';
rdgScoringMatrix.Cells[6,1] := '6';
rdgScoringMatrix.Cells[7,1] := '5';
rdgScoringMatrix.Cells[8,1] := '4';
rdgScoringMatrix.Cells[9,1] := '3';
rdgScoringMatrix.Cells[10,1] := '2';
rdgScoringMatrix.Cells[11,1] := '-5';
rdgScoringMatrix.Cells[0,2] := 'Tier 2';
rdgScoringMatrix.Cells[1,2] := '3';
rdgScoringMatrix.Cells[2,2] := '4';
rdgScoringMatrix.Cells[3,2] := '5';
rdgScoringMatrix.Cells[4,2] := '5';
rdgScoringMatrix.Cells[5,2] := '5';
rdgScoringMatrix.Cells[6,2] := '5';
rdgScoringMatrix.Cells[7,2] := '4';
rdgScoringMatrix.Cells[8,2] := '3';
rdgScoringMatrix.Cells[9,2] := '2';
rdgScoringMatrix.Cells[10,2] := '1';
rdgScoringMatrix.Cells[11,2] := '-3';
rdgScoringMatrix.Cells[0,3] := 'Tier 3';
rdgScoringMatrix.Cells[1,3] := '-3';
rdgScoringMatrix.Cells[2,3] := '-2';
rdgScoringMatrix.Cells[3,3] := '-1';
rdgScoringMatrix.Cells[4,3] := '0';
rdgScoringMatrix.Cells[5,3] := '1';
rdgScoringMatrix.Cells[6,3] := '2';
rdgScoringMatrix.Cells[7,3] := '3';
rdgScoringMatrix.Cells[8,3] := '3';
rdgScoringMatrix.Cells[9,3] := '3';
rdgScoringMatrix.Cells[10,3] := '3';
rdgScoringMatrix.Cells[11,3] := '-1';
finally
rdgScoringMatrix.EndUpdate;
end;
rdgPriorities.BeginUpdate;
try
rdgPriorities.Cells[0,1] := 'Fetal Distress';
rdgPriorities.Cells[0,2] := 'Seizure/ PreE';
rdgPriorities.Cells[0,3] := 'Breech';
rdgPriorities.Cells[0,4] := 'Cesarean';
rdgPriorities.Cells[0,5] := 'Pain';
rdgPriorities.Cells[0,6] := 'Preterm/ GA';
rdgPriorities.Cells[0,7] := 'PCN/ Risk';
rdgPriorities.Cells[0,8] := 'Labor Status';
rdgPriorities.Cells[0,9] := 'Teen Support System Single';
rdgPriorities.Cells[0,10] := 'Primip Knowl Deficit';
rdgPriorities.Cells[1,0] := 'Assigned Priority';
finally
rdgPriorities.EndUpdate;
end;
end;
procedure TfrmMain.rdgPrioritiesBeforeDrawCell(Sender: TObject; ACol,
ARow: Integer);
begin
if (ACol = 1) and (ARow >= 1) and (rdgPriorities.Cells[ACol,ARow] <> '')
and (rdgPriorities.Cells[ACol,ARow] <> '0')
and (rdgPriorities.Cols[1].IndexOf(rdgPriorities.Cells[ACol,ARow]) < ARow) then
begin
rdgPriorities.Canvas.Brush.Color := clRed;
end;
end;
procedure TfrmMain.CalculateData(AXLSFile: string);
const
xlCellTypeLastCell = $0000000B;
ProblemLabelCol = 1;
ProblemPresentCol = 2;
ProblemRepeatedCol = 3;
WrongProblemCol = 4;
AssignedPriorityCol = 6;
PriorityScoreCol = 7;
EvidenceKeyCol = 8;
EvidenceCol = 9;
InterventionsKeyCol = 10;
InterventionsCol = 11;
OutcomesKeyCol = 12;
OutcomesCol = 13;
FirstDataRowPartA = 5;
LastDataRowPartA = 14;
TotalsPartARow = 15;
PercentPartARow = 16;
FirstDataRowPartB = 19;
LastDataRowPartB = 21;
TotalsPartBRow = 22;
IDRow = 1;
IDCol = 14;
RaterIDCol = 9;
PartBValueColKey = 2;
PartBValueCol = 3;
PartBValuePercentCol = 4;
TotalRow = 22;
TotalCol = 17;
MinimumPriorityScore = -5*2 + -3*4 -1*2 -3 -2 -1*8;
MaximumPriorityScore = 10*2 + 5*4 + 3*4;
PriorityScoreRange = MaximumPriorityScore-MinimumPriorityScore;
ColumnLabels: array[0..9] of string = ('Fetal_Distress', 'PreE',
'Breech', 'Cesarean', 'Pain', 'Preterm/GA', 'PNC/ Risk', 'Labor_Status',
'Teen_Support_System_Single', 'Primip_Knowl_Deficit');
var
XLApp, Sheet: OLEVariant;
RangeMatrix: Variant;
x, y: Integer;
RowIndex: Integer;
ColIndex: Integer;
ParticipantID: string;
SheetCount: Integer;
SheetIndex: integer;
LineBuilder: TStringBuilder;
OutputFile: TStringList;
AString: string;
TotalProblems: Integer;
TotalRepeated: Integer;
Present: Integer;
PercentProblems: double;
PercentWrongProbs: double;
WrongProbs: Integer;
Priority: Integer;
Tier: Integer;
ScoringMatrix: TScoringMatrix;
PriorityScore: integer;
PriorityScoreTotal: Integer;
RaterID: string;
Repeated: Integer;
PriorityScorePercent: double;
Evidence: Integer;
TotalEvidence: Integer;
TotalEvidenceKey: Integer;
TotalEvidencePercent: double;
TotalInterventionsKey: Integer;
Interventions: Integer;
TotalOutcomesKey: Integer;
Outcomes: Integer;
TotalInterventions: Integer;
Intervetions: Integer;
TotalInterventionsPercent: double;
TotalOutcomes: Integer;
TotalOutcomesPercent: double;
PartBKey: array of integer;
PartBValues: array of integer;
PartBKeyValue: Integer;
PartBKeyTotal: Integer;
AValue: Integer;
APercent: double;
Total: Double;
TitleLine: string;
begin
SetLength(PartBKey, LastDataRowPartB-FirstDataRowPartB+1);
SetLength(PartBValues, LastDataRowPartB-FirstDataRowPartB+1);
InitializeScoringMatrix(ScoringMatrix);
XLApp := CreateOleObject('Excel.Application');
LineBuilder := TStringBuilder.Create;
OutputFile := TStringList.Create;
try
XLApp.Visible := False;
XLApp.Workbooks.Open(AXLSFile);
Sheet := XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[1];
Sheet.Select;
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
x := XLApp.ActiveCell.Row;
y := XLApp.ActiveCell.Column;
RangeMatrix := XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;
TotalEvidenceKey := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := RangeMatrix[RowIndex,EvidenceKeyCol];
if AString = '' then
begin
AString := '0';
end;
Evidence := StrToInt(AString);
TotalEvidenceKey := TotalEvidenceKey + Evidence;
end;
TotalInterventionsKey := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := RangeMatrix[RowIndex,InterventionsKeyCol];
if AString = '' then
begin
AString := '0';
end;
Interventions := StrToInt(AString);
TotalInterventionsKey := TotalInterventionsKey + Interventions;
end;
TotalOutcomesKey := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := RangeMatrix[RowIndex,OutcomesKeyCol];
if AString = '' then
begin
AString := '0';
end;
Outcomes := StrToInt(AString);
TotalOutcomesKey := TotalOutcomesKey + Outcomes;
end;
PartBKeyTotal := 0;
for RowIndex := FirstDataRowPartB to LastDataRowPartB do
begin
AString := RangeMatrix[RowIndex,PartBValueColKey];
PartBKeyValue := StrToInt(AString);
PartBKey[RowIndex-FirstDataRowPartB] := PartBKeyValue;
PartBKeyTotal := PartBKeyTotal + PartBKeyValue;
end;
LineBuilder.Append('StudyID, ');
LineBuilder.Append('Rater, ');
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := ColumnLabels[RowIndex-FirstDataRowPartA];
LineBuilder.Append(AString);
LineBuilder.Append('_Present, ');
end;
LineBuilder.Append('Total_Problems_Identified, ');
LineBuilder.Append('Problems_Identified%, ');
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := ColumnLabels[RowIndex-FirstDataRowPartA];
// AString := RangeMatrix[RowIndex,ProblemLabelCol];
LineBuilder.Append(AString);
LineBuilder.Append('_Repeated, ');
end;
LineBuilder.Append('Total_Problems_Repeated, ');
LineBuilder.Append('NumWrong, ');
LineBuilder.Append('NumWrong%, ');
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := ColumnLabels[RowIndex-FirstDataRowPartA];
LineBuilder.Append(AString);
LineBuilder.Append('_Priority_Assigned, ');
end;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := ColumnLabels[RowIndex-FirstDataRowPartA];
LineBuilder.Append(AString);
LineBuilder.Append('_Priority_Score, ');
end;
LineBuilder.Append('Total_Priority_Score, ');
LineBuilder.Append('Total_Priority_Score_%, ');
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := ColumnLabels[RowIndex-FirstDataRowPartA];
LineBuilder.Append(AString);
LineBuilder.Append('_Evidence, ');
end;
LineBuilder.Append('"Total_Evidence", ');
LineBuilder.Append('"Evidence%", ');
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := ColumnLabels[RowIndex-FirstDataRowPartA];
LineBuilder.Append(AString);
LineBuilder.Append('_Interventions, ');
end;
LineBuilder.Append('Interventions_Total, ');
LineBuilder.Append('Interventions%, ');
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := ColumnLabels[RowIndex-FirstDataRowPartA];
LineBuilder.Append(AString);
LineBuilder.Append('_Outcomes_ID''d, ');
end;
LineBuilder.Append('Outcomes_Total, ');
LineBuilder.Append('Outcomes%, ');
for RowIndex := FirstDataRowPartB to LastDataRowPartB do
begin
AString := RangeMatrix[RowIndex,ProblemLabelCol];
AString := StringReplace(AString, ' ', '_', [rfReplaceAll, rfIgnoreCase]);
LineBuilder.Append(AString);
LineBuilder.Append('_ID''d, ');
end;
for RowIndex := FirstDataRowPartB to LastDataRowPartB do
begin
AString := RangeMatrix[RowIndex,ProblemLabelCol];
AString := StringReplace(AString, ' ', '_', [rfReplaceAll, rfIgnoreCase]);
LineBuilder.Append(AString);
LineBuilder.Append('_ID''d%, ');
end;
LineBuilder.Append('Total');
TitleLine := LineBuilder.ToString;
// OutputFile.Add();
LineBuilder.Clear;
SheetCount := XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets.Count;
for SheetIndex := 1 to SheetCount do
begin
Sheet := XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[SheetIndex];
Sheet.Select;
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
RangeMatrix := XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;
ParticipantID := RangeMatrix[IDRow,IDCol];
LineBuilder.Append(ParticipantID);
LineBuilder.Append(', ');
RaterID := RangeMatrix[IDRow,RaterIDCol];
LineBuilder.Append(RaterID);
LineBuilder.Append(', ');
TotalProblems := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := RangeMatrix[RowIndex,ProblemPresentCol];
if AString = '' then
begin
AString := '0';
end;
LineBuilder.Append(AString);
LineBuilder.Append(', ');
Present := StrToInt(AString);
if not (Present in [0,1]) then
begin
Beep;
MessageDlg(Format(
'Incorrect coding for "problem present" for %s', [ParticipantID]),
mtError, [mbOK], 0);
Exit;
end;
TotalProblems := TotalProblems + Present;
end;
// Total Problems Identified
LineBuilder.Append(TotalProblems);
LineBuilder.Append(', ');
Sheet.Cells[TotalsPartARow, ProblemPresentCol].Value := TotalProblems;
// Percent Problems Identified);
PercentProblems := TotalProblems/10;
LineBuilder.Append(PercentProblems);
LineBuilder.Append(', ');
Sheet.Cells[PercentPartARow, ProblemPresentCol].NumberFormat := '0%';
Sheet.Cells[PercentPartARow, ProblemPresentCol].Value := PercentProblems;
TotalRepeated := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := RangeMatrix[RowIndex,ProblemRepeatedCol];
if AString = '' then
begin
AString := '0';
end;
LineBuilder.Append(AString);
LineBuilder.Append(', ');
Repeated := StrToInt(AString);
TotalRepeated := TotalRepeated + Repeated;
end;
// Total Problems Repeated
LineBuilder.Append(TotalRepeated);
LineBuilder.Append(', ');
Sheet.Cells[TotalsPartARow, ProblemRepeatedCol].Value := TotalRepeated;
// Unkeyed Score
AString := UpperCase(RangeMatrix[TotalsPartARow,WrongProblemCol]);
if AString = '' then
begin
AString := '0';
end;
WrongProbs := StrToInt(AString);
LineBuilder.Append(WrongProbs);
LineBuilder.Append(', ');
Sheet.Cells[TotalsPartARow, WrongProblemCol].Value := WrongProbs;
// Unkeyed Score Percent
PercentWrongProbs := (10-WrongProbs)/10;
LineBuilder.Append(PercentWrongProbs);
LineBuilder.Append(', ');
Sheet.Cells[PercentPartARow, WrongProblemCol].NumberFormat := '0%';
Sheet.Cells[PercentPartARow, WrongProblemCol].Value := PercentWrongProbs;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := RangeMatrix[RowIndex,AssignedPriorityCol];
if AString = '' then
begin
Priority := 0;
end
else
begin
Priority := StrToInt(AString);
end;
LineBuilder.Append(Priority);
LineBuilder.Append(', ');
end;
PriorityScoreTotal := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
AString := RangeMatrix[RowIndex,AssignedPriorityCol];
if AString = '' then
begin
Priority := 11;
end
else
begin
Priority := StrToInt(AString);
if Priority = 0 then
begin
Priority := 11;
end;
end;
case RowIndex - FirstDataRowPartA + 1 of
1..2:
begin
Tier := 1;
end;
3..6:
begin
Tier := 2;
end;
7..10:
begin
Tier := 3;
end;
else Assert(False);
end;
PriorityScore := ScoringMatrix[Priority-1, Tier-1];
LineBuilder.Append(PriorityScore);
LineBuilder.Append(', ');
PriorityScoreTotal := PriorityScoreTotal + PriorityScore;
Sheet.Cells[RowIndex, PriorityScoreCol].Value := PriorityScore;
end;
PriorityScoreTotal := PriorityScoreTotal - WrongProbs;
LineBuilder.Append(PriorityScoreTotal);
LineBuilder.Append(', ');
Sheet.Cells[TotalsPartARow, PriorityScoreCol].Value := PriorityScoreTotal;
PriorityScorePercent := (PriorityScoreTotal-MinimumPriorityScore)
/PriorityScoreRange;
LineBuilder.Append(PriorityScorePercent);
LineBuilder.Append(', ');
Sheet.Cells[PercentPartARow, PriorityScoreCol].NumberFormat := '0%';
Sheet.Cells[PercentPartARow, PriorityScoreCol].Value := PriorityScorePercent;
TotalEvidence := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
// LineBuilder.Append('"');
AString := RangeMatrix[RowIndex,EvidenceCol];
if AString = '' then
begin
AString := '0';
end;
LineBuilder.Append(AString);
LineBuilder.Append(', ');
Evidence := StrToInt(AString);
TotalEvidence := TotalEvidence + Evidence;
end;
// Total Evidence
LineBuilder.Append(TotalEvidence);
LineBuilder.Append(', ');
Sheet.Cells[TotalsPartARow, EvidenceCol].Value := TotalEvidence;
// Evidence Percent
TotalEvidencePercent := TotalEvidence/TotalEvidenceKey;
LineBuilder.Append(TotalEvidencePercent);
LineBuilder.Append(', ');
Sheet.Cells[PercentPartARow, EvidenceCol].NumberFormat := '0%';
Sheet.Cells[PercentPartARow, EvidenceCol].Value := TotalEvidencePercent;
TotalInterventions := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
// LineBuilder.Append('"');
AString := RangeMatrix[RowIndex,InterventionsCol];
if AString = '' then
begin
AString := '0';
end;
LineBuilder.Append(AString);
LineBuilder.Append(', ');
Intervetions := StrToInt(AString);
TotalInterventions := TotalInterventions + Intervetions;
end;
LineBuilder.Append(TotalInterventions);
LineBuilder.Append(', ');
Sheet.Cells[TotalsPartARow, InterventionsCol].Value := TotalInterventions;
TotalInterventionsPercent := TotalInterventions/TotalInterventionsKey;
LineBuilder.Append(TotalInterventionsPercent);
LineBuilder.Append(', ');
Sheet.Cells[PercentPartARow, InterventionsCol].NumberFormat := '0%';
Sheet.Cells[PercentPartARow, InterventionsCol].Value := TotalInterventionsPercent;
TotalOutcomes := 0;
for RowIndex := FirstDataRowPartA to LastDataRowPartA do
begin
// LineBuilder.Append('"');
AString := RangeMatrix[RowIndex,OutcomesCol];
if AString = '' then
begin
AString := '0';
end;
LineBuilder.Append(AString);
LineBuilder.Append(', ');
Outcomes := StrToInt(AString);
TotalOutcomes := TotalOutcomes + Outcomes;
end;
Sheet.Cells[TotalsPartARow, OutcomesCol].Value := TotalOutcomes;
LineBuilder.Append(TotalOutcomes);
LineBuilder.Append(', ');
TotalOutcomesPercent := TotalOutcomes/TotalOutcomesKey;
LineBuilder.Append(TotalOutcomesPercent);
LineBuilder.Append(', ');
Sheet.Cells[PercentPartARow, OutcomesCol].NumberFormat := '0%';
Sheet.Cells[PercentPartARow, OutcomesCol].Value := TotalOutcomesPercent;
for RowIndex := FirstDataRowPartB to LastDataRowPartB do
begin
AString := RangeMatrix[RowIndex,PartBValueCol];
if AString = '' then
begin
AString := '0';
end;
LineBuilder.Append(AString);
LineBuilder.Append(', ');
AValue := StrToInt(AString);
PartBValues[RowIndex-FirstDataRowPartB] := AValue;
end;
Total := PercentProblems + PercentWrongProbs + PriorityScorePercent
+ TotalEvidencePercent + TotalInterventionsPercent + TotalOutcomesPercent;
for RowIndex := FirstDataRowPartB to LastDataRowPartB do
begin
APercent := PartBValues[RowIndex-FirstDataRowPartB]/
PartBKey[RowIndex-FirstDataRowPartB];
LineBuilder.Append(APercent);
LineBuilder.Append(', ');
Sheet.Cells[RowIndex, PartBValuePercentCol].NumberFormat := '0%';
Sheet.Cells[RowIndex, PartBValuePercentCol].Value := APercent;
Total := Total + APercent;
end;
Total := Total / 9;
LineBuilder.Append(Total);
Sheet.Cells[TotalRow, TotalCol].NumberFormat := '0%';
Sheet.Cells[TotalRow, TotalCol].Value := Total;
Sheet.Range['A1','A1'].Select;
RangeMatrix := Unassigned;
OutputFile.Add(LineBuilder.ToString);
LineBuilder.Clear;
end;
OutputFile.Sort;
OutputFile.Insert(0, TitleLine);
Sheet := XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[1];
Sheet.Select;
OutputFile.SaveToFile(fedCSV.FileName);
// XLApp.Workbooks[ExtractFileName(AXLSFile)].SaveAs(AXLSFile, xlWorkbookDefault);
XLApp.DisplayAlerts := False;
XLApp.Workbooks[ExtractFileName(AXLSFile)].Save;
finally
LineBuilder.Free;
OutputFile.Free;
if not VarIsEmpty(XLApp) then
begin
XLApp.Quit;
Sheet := Unassigned;
XLAPP := Unassigned;
end;
end;
end;
procedure TfrmMain.InitializeScoringMatrix(var ScoringMatrix: TScoringMatrix);
var
ColIndex: Integer;
RowIndex: Integer;
begin
SetLength(ScoringMatrix, rdgScoringMatrix.ColCount - 1, rdgScoringMatrix.RowCount - 1);
for RowIndex := 1 to rdgScoringMatrix.RowCount - 1 do
begin
for ColIndex := 1 to rdgScoringMatrix.ColCount - 1 do
begin
ScoringMatrix[ColIndex - 1, RowIndex - 1] := rdgScoringMatrix.IntegerValue[ColIndex, RowIndex];
end;
end;
end;
end.
|
unit chmframe;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, IpHtml, LResources, Forms, Controls, ComCtrls,
ExtCtrls, StdCtrls, Menus;
type
{ TFrameChm }
TFrameChm = class(TFrame)
btnSearch: TButton;
cboxKeyword: TComboBox;
edIndexSearch: TLabeledEdit;
IpHtmlPanel: TIpHtmlPanel;
lbResults: TLabel;
lbKeyword: TLabel;
miCopySource: TMenuItem;
miCopy: TMenuItem;
panContents: TPanel;
pgcNavigation: TPageControl;
pmHtml: TPopupMenu;
Splitter1: TSplitter;
StatusBar: TStatusBar;
tvSearchResults: TTreeView;
tsSearch: TTabSheet;
tvIndex: TTreeView;
tsIndex: TTabSheet;
tvContents: TTreeView;
tsContents: TTabSheet;
procedure btnSearchClick(Sender: TObject);
procedure cboxKeywordKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edIndexSearchChange(Sender: TObject);
procedure miCopyClick(Sender: TObject);
procedure miCopySourceClick(Sender: TObject);
procedure tvContentsCollapsed(Sender: TObject; Node: TTreeNode);
procedure tvContentsCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
procedure tvContentsExpanded(Sender: TObject; Node: TTreeNode);
procedure tvContentsSelectionChanged(Sender: TObject);
procedure tvIndexCollapsing(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean);
procedure tvIndexCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
procedure tvIndexDblClick(Sender: TObject);
procedure tvIndexSelectionChanged(Sender: TObject);
procedure tvSearchResultsDblClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
implementation
{ TFrameChm }
procedure TFrameChm.tvContentsSelectionChanged(Sender: TObject);
begin
//
end;
procedure TFrameChm.tvIndexCollapsing(Sender: TObject; Node: TTreeNode;
var AllowCollapse: Boolean);
begin
//
end;
procedure TFrameChm.tvIndexCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
begin
//
end;
procedure TFrameChm.tvIndexDblClick(Sender: TObject);
begin
//
end;
procedure TFrameChm.tvIndexSelectionChanged(Sender: TObject);
begin
if Assigned(tvIndex.Selected) and (edIndexSearch.Tag = 0) then
begin
edIndexSearch.Tag := 1; // lock change
edIndexSearch.Text := tvIndex.Selected.Text;
edIndexSearch.Tag := 0; // unlock change
end;
end;
procedure TFrameChm.tvSearchResultsDblClick(Sender: TObject);
begin
//
end;
procedure TFrameChm.tvContentsExpanded(Sender: TObject; Node: TTreeNode);
begin
//
end;
procedure TFrameChm.tvContentsCollapsed(Sender: TObject; Node: TTreeNode);
begin
//
end;
procedure TFrameChm.edIndexSearchChange(Sender: TObject);
var
ItemName: String;
SearchText: String;
Node: TTreeNode;
begin
if (edIndexSearch <> Sender) or (edIndexSearch.Tag <> 0) then
Exit;
edIndexSearch.Tag := 1;
SearchText := LowerCase(edIndexSearch.Text);
Node := tvIndex.Items.GetFirstNode;
while Node <> nil do
begin
ItemName := LowerCase(Copy(Node.Text, 1, Length(SearchText)));
if ItemName = SearchText then
begin
tvIndex.Items.GetLastNode.MakeVisible;
Node.MakeVisible;
Node.Selected := True;
edIndexSearch.Tag := 0;
Exit;
end;
Node := Node.GetNextSibling;
end;
tvIndex.Selected := nil;
edIndexSearch.Tag := 0;
end;
procedure TFrameChm.miCopyClick(Sender: TObject);
begin
IpHtmlPanel.CopyToClipboard();
end;
procedure TFrameChm.miCopySourceClick(Sender: TObject);
begin
//
end;
procedure TFrameChm.cboxKeywordKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
//
end;
procedure TFrameChm.btnSearchClick(Sender: TObject);
begin
//
end;
procedure TFrameChm.tvContentsCreateNodeClass(Sender: TCustomTreeView;
var NodeClass: TTreeNodeClass);
begin
//
end;
initialization
{$I chmframe.lrs}
end.
|
{: FRColorEditor<p>
RGB+Alpha color editor.<p>
<b>Historique : </b><font size=-1><ul>
<li>06/02/00 - Egg - Creation
</ul></font>
}
unit FRColorEditor;
interface
uses
Windows, Forms, StdCtrls, ComCtrls, ExtCtrls, FRTrackBarEdit, Dialogs, Controls,
Classes, Geometry;
type
TRColorEditor = class(TFrame)
Label1: TLabel;
TBERed: TRTrackBarEdit;
TBEGreen: TRTrackBarEdit;
Label2: TLabel;
TBEBlue: TRTrackBarEdit;
Label3: TLabel;
TBEAlpha: TRTrackBarEdit;
Label4: TLabel;
PAPreview: TPanel;
ColorDialog: TColorDialog;
procedure TBEChange(Sender: TObject);
procedure TBERedTrackBarChange(Sender: TObject);
procedure TBEGreenTrackBarChange(Sender: TObject);
procedure TBEBlueTrackBarChange(Sender: TObject);
procedure TBEAlphaTrackBarChange(Sender: TObject);
procedure PAPreviewDblClick(Sender: TObject);
private
{ Déclarations privées }
FOnChange : TNotifyEvent;
updating : Boolean;
procedure SetColor(const val : THomogeneousFltVector);
function GetColor : THomogeneousFltVector;
public
{ Déclarations publiques }
property Color : THomogeneousFltVector read GetColor write SetColor;
property OnChange : TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{$R *.DFM}
uses Graphics, GLTexture;
procedure TRColorEditor.TBEChange(Sender: TObject);
begin
PAPreview.Color:=RGB(TBERed.Value, TBEGreen.Value, TBEBlue.Value);
if (not updating) and Assigned(FOnChange) then FOnChange(Self);
end;
// SetColor
//
procedure TRColorEditor.SetColor(const val : THomogeneousFltVector);
begin
updating:=True;
try
TBERed.Value:=Round(val[0]*255);
TBEGreen.Value:=Round(val[1]*255);
TBEBlue.Value:=Round(val[2]*255);
TBEAlpha.Value:=Round(val[3]*1000);
finally
updating:=False;
end;
TBEChange(Self);
end;
// GetColor
//
function TRColorEditor.GetColor : THomogeneousFltVector;
begin
Result:=VectorMake(TBERed.Value/255, TBEGreen.Value/255, TBEBlue.Value/255,
TBEAlpha.Value/1000);
end;
procedure TRColorEditor.TBERedTrackBarChange(Sender: TObject);
begin
TBERed.TrackBarChange(Sender);
TBEChange(Sender);
end;
procedure TRColorEditor.TBEGreenTrackBarChange(Sender: TObject);
begin
TBEGreen.TrackBarChange(Sender);
TBEChange(Sender);
end;
procedure TRColorEditor.TBEBlueTrackBarChange(Sender: TObject);
begin
TBEBlue.TrackBarChange(Sender);
TBEChange(Sender);
end;
procedure TRColorEditor.TBEAlphaTrackBarChange(Sender: TObject);
begin
TBEAlpha.TrackBarChange(Sender);
if (not updating) and Assigned(FOnChange) then FOnChange(Self);
end;
procedure TRColorEditor.PAPreviewDblClick(Sender: TObject);
begin
ColorDialog.Color:=PAPreview.Color;
if ColorDialog.Execute then
SetColor(ConvertWinColor(ColorDialog.Color));
end;
end.
|
unit WMSLayerMergeDispatcher;
interface
uses
TeraWMSToolsDefs, ShareTools, Console, capabilities_1_1_1, TeraWMSTools,
Classes, SysUtils;
type
TWMSLayerMerge_GetCapabilitiesDispatcher = class(TWMSGetCapabilitiesDispatcher)
function GetCapabilities(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : WideString; override;
end;
TWMSLayerMerge_GetMapDispatcher = class(TGetMapDispatcher)
function GetMap(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : TStream; override;
end;
const
CONFIGFILE_PARAM = 'ConfigFile';
HTMLBase = '<html><head><style>body { font-family:arial } </style></head><body>' +
'<h1>Služba WMS Layer merge</h1>' +
'<h2>Popis služby</h2>' +
'WMS Layer merge je služba, která slouží k ručnímu vytváření logických skupin WMS vrstev. Cílem je vytvořit logické skupiny tak,' +
'aby uživatel nemusel v jednoduchých klientech vybírat všechny podvrstvy pro zobrazení logické skupiny.' +
'Je použit zejména pro implementaci symbolizované vektorové mapy.' +
'<ul>' +
'<li>Služba layer merge umožní vytvořit logické skupiny nabízených vrstev</li>' +
'<li>Nezpůsobí zpoždění v dodání mapy uživateli</li>' +
'</ul>';
implementation
function TWMSLayerMerge_GetCapabilitiesDispatcher.GetCapabilities(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : WideString;
begin
Result := FileToStr(RequestInfo.QueryFields.Values[CONFIGFILE_PARAM]);
RequestInfo.Handled := true;
end;
function TWMSLayerMerge_GetMapDispatcher.GetMap(Parent : TWMSDispatcher; var RequestInfo : TRequestInfo) : TStream;
var
Layer : IXMLLayerType;
procedure HTMLMsg(Msg : string = '');
begin
Console.DisplayDebugMsg(Msg);
end;
function FindKeyword(ID : string) : string;
var
i : integer;
begin
Result := '';
for i := 0 to Layer.KeywordList.Count - 1 do begin
Console.DisplayDebugMsg(Layer.KeywordList.Keyword[i]);
if ID = Copy(Layer.KeywordList.Keyword[i], 1, Length(ID)) then begin
Console.DisplayDebugMsg('Found keyword for ' + ID);
Result := Layer.KeywordList.Keyword[i];
Result := Trim(Copy(Result, Length(ID) + 1, Length(Result)));
if (Result <> '') and (Result[1] = '=') then Delete(Result, 1, 1);
Exit;
end;
end;
end;
var
Layers, OnlineResource, LayersValue, s, TmpFileName : string;
c : IXMLWMT_MS_CapabilitiesType;
i : integer;
FileStream : TFileStream;
MemoryStream : TMemoryStream;
begin
Result := nil;
Layers := RequestInfo.QueryFields.Values['LAYERS'];
if (Layers = '') then begin
HTMLMsg('Layer not assigned');
Exit;
end;
c := LoadWMT_MS_Capabilities(ExtractFilePath(ParamStr(0)) + '\' + RequestInfo.QueryFields.Values[CONFIGFILE_PARAM]);
try
Console.DisplayDebugMsg('Searching for layer ' + Layers);
Layer := FindLayer(c, Layers);
if Layer = nil then begin
HTMLMsg('Layer not found');
Exit;
end;
HTMLMsg('Layer = ' + Layer.Name);
OnlineResource := FindKeyword('REP_OnlineResource');
if OnlineResource = '' then begin
HTMLMsg('REP_OnlineResource not found');
Exit;
end;
HTMLMsg('REP_OnlineResource = ' + OnlineResource);
LayersValue := FindKeyword('REP_Layers');
if LayersValue = '' then begin
HTMLMsg('REP_Layers not found');
Exit;
end;
HTMLMsg('REP_Layers = ' + LayersValue);
finally
c := nil;
end;
s := OnlineResource;
for i := 0 to RequestInfo.QueryFields.Count - 1 do begin
if UpperCase(RequestInfo.QueryFields.Names[i]) = 'LAYERS'
then RequestInfo.QueryFields.ValueFromIndex[i] := LayersValue;
s := AddTokenToURLQuery(RequestInfo.QueryFields[i], s);
end;
HTMLMsg('Request=' + s);
TmpFileName := DownloadURLToFile(s);
if TmpFileName <> '' then begin
FileStream := TFileStream.Create(TmpFileName, fmOpenRead);
try
MemoryStream := TMemoryStream.Create;
MemoryStream.CopyFrom(FileStream, FileStream.Size);
MemoryStream.Position := 0;
Result := MemoryStream;
finally
FileStream.Free;
DeleteFile(TmpFileName);
end;
end;
RequestInfo.Handled := true;
end;
initialization
with WMSDispatchers.Add do begin
PathInfo := '/WMS/LayerMerge';
Caption := 'Layer merge service';
Description := 'WMS Layer merge je služba, která slouží k ručnímu vytváření logických skupin WMS vrstev. Cílem je vytvořit logické skupiny tak,' +
'aby uživatel nemusel v jednoduchých klientech vybírat všechny podvrstvy pro zobrazení logické skupiny.' +
'Je použit zejména pro implementaci symbolizované vektorové mapy.' +
'<ul>' +
'<li>Služba layer merge umožní vytvořit logické skupiny nabízených vrstev</li>' +
'<li>Nezpůsobí zpoždění v dodání mapy uživateli</li>' +
'</ul>';
//RelativeLink := '/' + PathInfo + '?request=GetCapabilities';
GetCapabilitiesDispatcher := TWMSLayerMerge_GetCapabilitiesDispatcher.Create;
ParamNames := CONFIGFILE_PARAM;
GetMapDispatcher := TWMSLayerMerge_GetMapDispatcher.Create;
end;
end.
|
unit ScreenImport;
interface
uses Forms, SysUtils, Controls, Classes, Dialogs, DB, DBGrids, ComCtrls,
Design, CBSComponents, Graphics, math, IniFiles;
type TScreenImporter = class(TComponent)
private
FLayoutPageControl: TPageControl;
FDataSource: TDataSource;
CurrentTab :TTabSheet;
CurrentForm : TfrmDesign;
CurrentDirectory: String;
GridAreaTop: Integer;
LastGrid: TCBSDBGrid;
procedure CreateBlankTab;
function FixName(Oldname: String): String;
function GetEditType(DataField: String): Char;
procedure ImportFrom(FileName: String);
procedure ImportNewCheckBox(ParsedLine: TStringList);
procedure ImportNewCombo(ParsedLine: TStringList);
procedure ImportNewDate(ParsedLine: TStringList);
procedure ImportNewEdit(ParsedLine: TStringList);
procedure ImportNewLabel(ParsedLine: TStringList);
procedure ImportNewMemo(ParsedLine: TStringList);
procedure ImportNewTab(ParsedLine: TStringList);
procedure ImportNewGrid(ParsedLine: TStringList);
procedure ModifyLastGrid(ParsedLine: TStringList);
procedure SetDataSource(const Value: TDataSource); overload;
procedure SetDataSource(const Value: String); overload;
procedure ImportConfig(const Filename:WideString; const ScreenType: Char);
function GetScreenFile(const Filename:WideString; const ScreenType: Char; ScreenFile:Boolean=True):WideString;
procedure AddGrids(const Filename:WideString);
procedure AddGridColumns(const Filename:WideString);
procedure SetGridAreaTop;
public
constructor Create(AOwner: TComponent; DataSource: TDataSource; LayoutPageControl:TPageControl);overload;
constructor Create(AOwner: TComponent; LayoutPageControl:TPageControl);overload;
destructor Destroy;override;
procedure ImportScreen; overload;
procedure ImportScreen(Filename:WideString; ScreenType: Char='P');overload;
property DataSource: TDataSource read FDataSource write SetDataSource;
end;
implementation
procedure ParseDelimited(const sl : TStrings; const value : string; const delimiter : string) ;
var
dx : integer;
ns : string;
txt : string;
delta : integer;
begin
delta := Length(delimiter) ;
txt := value + delimiter;
sl.BeginUpdate;
sl.Clear;
try
while Length(txt) > 0 do
begin
dx := Pos(delimiter, txt) ;
ns := Copy(txt,0,dx-1) ;
sl.Add(ns) ;
txt := Copy(txt,dx+delta,MaxInt) ;
end;
finally
sl.EndUpdate;
end;
end;
procedure TScreenImporter.ImportScreen;
var FileDialog: TOpenDialog;
FileFilter: String;
begin
FileFilter := 'Exam Screen (*.ex)|*.ex';
FileDialog := TOpenDialog.Create(Self);
try
FileDialog.Filter := FileFilter;
if FileDialog.Execute then
begin
if MessageDlg('You are about to import from ' +FileDialog.FileName+'. Do you want to do that?',
mtConfirmation, mbYesNo, 0) = mrYes then
begin
FLayoutPageControl.Visible := False;
try
ImportFrom(FileDialog.FileName);
finally
FLayoutPageControl.Visible := true;
end;
end;
end;
finally
FreeAndNil(FileDialog);
end;
end;
procedure TScreenImporter.CreateBlankTab;
begin
CurrentTab := TTabSheet.Create(FLayoutPageControl);
CurrentTab.PageControl := FLayoutPageControl;
CurrentTab.Parent := FLayoutPageControl;
CurrentForm := TfrmDesign.Create(Application);
CurrentForm.BorderStyle := bsNone;
CurrentForm.Align := alClient;
CurrentForm.Parent := CurrentTab;
CurrentForm.Visible := True;
FLayoutPageControl.ActivePage := CurrentTab;
// FLayoutPageControl.Visible := True;
end;
procedure TScreenImporter.ImportFrom(FileName: String);
var TotalFile, ParsedLine: TStringList;
x: Integer;
EditType: Char;
ThisDataSource: TDataSource;
HoldActive: Boolean;
FileType: String;
begin
{$O-}
TotalFile := TStringList.Create;
ParsedLine := TStringList.Create;
TotalFile.LoadFromFile(FileName);
FileType := UpperCase(ExtractFileExt(FileName));
HoldActive := FDataSource.DataSet.Active;
FDataSource.DataSet.Active := True;
try
for x := 0 to TotalFile.Count -1 do
begin
ParseDelimited(ParsedLine,TotalFile[x],'^');
if (x = 0) and (ParsedLine[0]<>'T') then
begin
Randomize;
CreateBlankTab;
CurrentForm.TabName := 'Blank-'+IntToStr(Random(9999));
end;
if ParsedLine[0]='T' then ImportNewTab(ParsedLine);
if ParsedLine[0]='L' then ImportNewLabel(ParsedLine);
if ParsedLine[0]='E' then
begin
EditType := GetEditType(ParsedLine[3]);
case EditType of
'D': ImportNewDate(ParsedLine);
'L': ImportNewCheckBox(ParsedLine);
else
if ParsedLine[ParsedLine.Count-1] = 'Y' then
ImportNewCombo(ParsedLine)
else
ImportNewEdit(ParsedLine);
end;
end;
if ParsedLine[0]='M' then ImportNewMemo(ParsedLine);
if ParsedLine[0]='P' then ImportNewGrid(ParsedLine);
if ParsedLine[0]='S' then ModifyLastGrid(ParsedLine);
end;
finally
TotalFile.Free;
ParsedLine.Free;
FDataSource.DataSet.Active := HoldActive;
end;
end;
procedure TScreenImporter.ImportNewEdit(ParsedLine: TStringList);
var NewComponent: TCBSDBEdit;
begin
NewComponent := TCBSDBEdit.Create(CurrentForm);
NewComponent.Parent := CurrentForm;
CurrentForm.AutoName(NewComponent);
NewComponent.Left := StrToInt(ParsedLine[1]);
NewComponent.Top := StrToInt(ParsedLine[2]);
NewComponent.DataSource := FDataSource;
NewComponent.DataField := FixName(ParsedLine[3]);
NewComponent.Color := StringToColor(ParsedLine[4]);
NewComponent.Width := 7 + (NewComponent.DataSource.DataSet.FieldByName(NewComponent.DataField).DisplayWidth*7);
//GetFieldSize(NewComponent.DataField);
FLayoutPageControl.Height := max(FLayoutPageControl.Height,NewComponent.Top+NewComponent.Height);
end;
procedure TScreenImporter.ImportNewCombo(ParsedLine: TStringList);
var NewComponent: TCBSDBComboBox;
begin
NewComponent := TCBSDBComboBox.Create(CurrentForm);
NewComponent.Parent := CurrentForm;
CurrentForm.AutoName(NewComponent);
NewComponent.Left := StrToInt(ParsedLine[1]);
NewComponent.Top := StrToInt(ParsedLine[2]);
NewComponent.DataSource := FDataSource;
NewComponent.DataField := FixName(ParsedLine[3]);
NewComponent.Color := StringToColor(ParsedLine[4]);
NewComponent.Width := 24 + (NewComponent.DataSource.DataSet.FieldByName(NewComponent.DataField).DisplayWidth*8);
// NewComponent.Width := GetFieldSize(NewComponent.DataField);
FLayoutPageControl.Height := max(FLayoutPageControl.Height,NewComponent.Top+NewComponent.Height);
end;
procedure TScreenImporter.ImportNewMemo(ParsedLine: TStringList);
var NewComponent: TCBSDBMemo;
begin
NewComponent := TCBSDBMemo.Create(CurrentForm);
NewComponent.Parent := CurrentForm;
CurrentForm.AutoName(NewComponent);
NewComponent.Left := StrToInt(ParsedLine[1]);
NewComponent.Top := StrToInt(ParsedLine[2]);
NewComponent.Width := StrToInt(ParsedLine[3]);
NewComponent.Height := StrToInt(ParsedLine[4]);
NewComponent.DataSource := FDataSource;
NewComponent.DataField := FixName(ParsedLine[5]);
if ParsedLine.Count = 7 then
NewComponent.Color := StringToColor(ParsedLine[6]);
FLayoutPageControl.Height := max(FLayoutPageControl.Height,NewComponent.Top+NewComponent.Height);
end;
procedure TScreenImporter.ImportNewLabel(ParsedLine: TStringList);
var NewComponent: TCBSLabel;
begin
NewComponent := TCBSLabel.Create(CurrentForm);
NewComponent.Parent := CurrentForm;
CurrentForm.AutoName(NewComponent);
NewComponent.Left := StrToInt(ParsedLine[1]);
NewComponent.Top := StrToInt(ParsedLine[2]);
NewComponent.Caption := ParsedLine[3];
NewComponent.Color := StringToColor(ParsedLine[4]);
FLayoutPageControl.Height := max(FLayoutPageControl.Height,NewComponent.Top+NewComponent.Height);
end;
procedure TScreenImporter.ImportNewCheckBox(ParsedLine: TStringList);
var NewComponent: TCBSDBCheckBox;
begin
NewComponent := TCBSDBCheckBox.Create(CurrentForm);
NewComponent.Parent := CurrentForm;
CurrentForm.AutoName(NewComponent);
NewComponent.Left := StrToInt(ParsedLine[1]);
NewComponent.Top := StrToInt(ParsedLine[2]);
NewComponent.DataSource := FDataSource;
NewComponent.DataField := FixName(ParsedLine[3]);
// NewComponent.Color := StringToColor(ParsedLine[4]);
NewComponent.Width := 20;
NewComponent.Caption := '';
FLayoutPageControl.Height := max(FLayoutPageControl.Height,NewComponent.Top+NewComponent.Height);
end;
procedure TScreenImporter.ImportNewDate(ParsedLine: TStringList);
var NewComponent: TCBSDBDateTimePicker;
begin
NewComponent := TCBSDBDateTimePicker.Create(CurrentForm);
NewComponent.Parent := CurrentForm;
CurrentForm.AutoName(NewComponent);
NewComponent.Left := StrToInt(ParsedLine[1]);
NewComponent.Top := StrToInt(ParsedLine[2]);
NewComponent.DataSource := FDataSource;
NewComponent.DataField := FixName(ParsedLine[3]);
NewComponent.Color := StringToColor(ParsedLine[4]);
NewComponent.Width := Max(NewComponent.DataSource.DataSet.FieldByName(NewComponent.DataField).DisplayWidth*7,14);
FLayoutPageControl.Height := max(FLayoutPageControl.Height,NewComponent.Top+NewComponent.Height);
end;
procedure TScreenImporter.ImportNewGrid(ParsedLine: TStringList);
var NewComponent: TCBSDBGrid;
NewLabel: TCBSLabel;
begin
NewLabel := TCBSLabel.Create(CurrentForm);
NewLabel.Parent := CurrentForm;
CurrentForm.AutoName(NewLabel);
NewLabel.Left := StrToInt(ParsedLine[1]);
NewLabel.Top := GridAreaTop;
NewLabel.Height := 13;
NewLabel.Width := StrToInt(ParsedLine[4]);
NewLabel.Color := StringToColor(ParsedLine[5]);
NewLabel.Caption := ParsedLine[6];
NewComponent := TCBSDBGrid.Create(CurrentForm);
NewComponent.Parent := CurrentForm;
CurrentForm.AutoName(NewComponent);
NewComponent.Left := NewLabel.Left;
NewComponent.Top := NewLabel.Top+NewLabel.Height;
NewComponent.Width := NewLabel.Width;
NewComponent.Height := 20; //This is temporary....will be modified by ModifyLastGrid
FLayoutPageControl.Height := max(FLayoutPageControl.Height,NewComponent.Top+NewComponent.Height);
LastGrid := NewComponent;
end;
procedure TScreenImporter.ModifyLastGrid(ParsedLine: TStringList);
var HoldDataSource: TDataSource;
begin
LastGrid.Width := StrToInt(ParsedLine[4]);
LastGrid.Height := StrToInt(ParsedLine[5]);
LastGrid.Color := StringToColor(ParsedLine[6]);
HoldDataSource := FDataSource;
SetDataSource('S_'+ParsedLine[1]);
LastGrid.DataSource := FDataSource;
AddGridColumns(CurrentDirectory+Trim(ParsedLine[3])+'.SCL');
FDataSource := HoldDataSource;
end;
procedure TScreenImporter.AddGridColumns(const Filename: WideString);
var TotalFile: TStringList;
x: Integer;
NewColumn: TColumn;
begin
if not FileExists(FileName) then exit;
TotalFile := TStringList.Create;
try
TotalFile.LoadFromFile(FileName);
for x := 0 to TotalFile.Count-1 do
begin
if TotalFile[x]='' then continue;
NewColumn := LastGrid.Columns.Add;
NewColumn.Title.Caption := Trim(copy(TotalFile[x],14,30));
NewColumn.Width := StrToInt(copy(TotalFile[x],1,3));
NewColumn.FieldName := Trim(copy(TotalFile[x],4,10));
end;
finally
TotalFile.Free;
end;
end;
procedure TScreenImporter.ImportNewTab(ParsedLine: TStringList);
begin
randomize;
CreateBlankTab;
CurrentTab.Caption := ParsedLine[1];
CurrentForm.TabLabel := CurrentTab.Caption;
CurrentForm.TabName := Trim(CurrentTab.Caption)+'-'+IntToStr(Random(9999)) ;
end;
Function TScreenImporter.FixName(Oldname: String):String;
begin
Result := Oldname;
if uppercase(trim(OldName)) = 'EXAMDATE' then Result := 'DATE';
if uppercase(trim(OldName)) = 'PAT_ID' then Result := 'PatUnique';
end;
function TScreenImporter.GetEditType(DataField: String): Char;
var RetString: String;
begin
RetString := ' ';
// with CheckFieldQuery do
// begin
// Close;
// if LeftStr(Trim(DataField),2)='ZZ' then
// ParamByName('FieldName').AsString := copy(Trim(DataField),3,15)
// else
// ParamByName('FieldName').AsString := Trim(DataField);
// Open;
// if RecordCount > 0 then RetString := FieldByName('Type').AsString[1];
// Close;
// end;
Result := RetString[1];
end;
constructor TScreenImporter.Create(AOwner: TComponent;DataSource: TDataSource; LayoutPageControl:TPageControl);
begin
inherited Create(AOwner);
FDataSource := DataSource;
FLayoutPageControl := LayoutPageControl;
CurrentDirectory := '';
end;
constructor TScreenImporter.Create(AOwner: TComponent; LayoutPageControl:TPageControl);
begin
inherited Create(AOwner);
FLayoutPageControl := LayoutPageControl;
CurrentDirectory := '';
end;
destructor TScreenImporter.Destroy;
begin
FDataSource := nil;
FLayoutPageControl := nil;
inherited;
end;
procedure TScreenImporter.ImportScreen(Filename:WideString; ScreenType: Char='P');
var Extension: String;
begin
if FileExists(FileName) then
begin
FLayoutPageControl.Visible := False;
Extension := uppercase(ExtractFileExt(FileName));
if Extension = '.CFG' then
begin
ImportConfig(FileName,ScreenType);
FLayoutPageControl.Visible := true;
Exit;
end;
if Extension = '.EX' then SetDataSource('S_EXAM');
if Extension = '.PD' then SetDataSource('S_PATIENT');
if Extension = '.CL' then SetDataSource('S_LENS_RX');
if Extension = '.APT' then SetDataSource('S_APPT');
if Extension = '.SP' then SetDataSource('S_FRAM_RX');
if Extension = '.AR' then SetDataSource('S_BILL');
if Extension = '.CS' then SetDataSource('S_CLAIM');
try
if Assigned(FDataSource) then
ImportFrom(FileName);
finally
FLayoutPageControl.Visible := true;
end;
end;
end;
procedure TScreenImporter.SetDataSource(const Value: TDataSource);
begin
FDataSource := Value;
end;
procedure TScreenImporter.SetDataSource(const Value: String);
var BaseForm: TForm;
begin
if Assigned(Self.Owner) and (Value <> '') then
begin
if Self.Owner is TForm then
begin
FDataSource := TForm(Self.Owner).FindComponent(Value) as TDataSource;
end;
end;
end;
procedure TScreenImporter.ImportConfig(const Filename: WideString; const ScreenType: Char);
var ImportFileName: WideString;
begin
// Import the basic screen
ImportFileName := GetScreenFile(FileName, ScreenType);
if FileExists(ImportFileName) then
ImportScreen(ImportFileName)
else
exit;
// Check to be sure there are any created pages
if FLayoutPageControl.PageCount = 0 then exit;
// now add the grids to the front tab
FLayoutPageControl.ActivePageIndex := 0;
CurrentTab := FLayoutPageControl.ActivePage;
CurrentForm := FLayoutPageControl.ActivePage.Controls[0] as TfrmDesign;
ImportFileName := GetScreenFile(Filename, ScreenType, False);
if FileExists(ImportFileName) then
AddGrids(ImportFileName);
end;
function TScreenImporter.GetScreenFile(const Filename: WideString; const ScreenType: Char; ScreenFile:Boolean=True):WideString;
var ConfigFile: TIniFile;
Section: String;
FileParam: String;
begin
ConfigFile := TIniFile.Create(FileName);
try
//the parameter marked layout is the file with the actual screen, the parameter screen has the file for the grids
if ScreenFile then FileParam := 'layout' else FileParam := 'screen';
case ScreenType of
'P': Result := ConfigFile.ReadString('PATDEMO',FileParam,'')+'.PD';
'R': Result := ConfigFile.ReadString('RESPDEMO',FileParam,'')+'.AR';
'X': Result := ConfigFile.ReadString('EXAM',FileParam,'')+'.EX';
'L': Result := ConfigFile.ReadString('CLRX',FileParam,'')+'.CL';
'G': Result := ConfigFile.ReadString('SPECRX',FileParam,'')+'.SP';
else
Result := '';
end;
if Result <> '' then
begin
CurrentDirectory := ExtractFilePath(FileName)+'\';
Result := CurrentDirectory+Result;
end;
finally
ConfigFile.Free;
end;
end;
procedure TScreenImporter.AddGrids(const Filename: WideString);
begin
SetGridAreaTop;
ImportFrom(FileName);
end;
procedure TScreenImporter.SetGridAreaTop;
var x: Integer;
begin
for x := 0 to CurrentForm.ControlCount -1 do
begin
GridAreaTop := max(CurrentForm.Controls[x].Top + CurrentForm.Controls[x].Height,
GridAreaTop);
end;
end;
end.
|
{
Se lee desde teclado información de los autos existentes en una concesionaria.
De cada auto se lee: patente, número de chasis, año y precio.
La lectura finaliza cuando llega un auto con precio 5000 o con año 2020, el cual no debe ser procesado.
Informar:
a. Las patentes cuyos números de chasis contengan exactamente 3 dígitos 8.
b. El promedio de autos con menos de 5 años de antigüedad.
c. Las patentes y precios de los dos autos de valor mas bajo.
Modularizar su solución.
}
program ejercicio2;
const anioActual = 2020;
type cadena7 = string [7];
rango = 1960..2020;
procedure LeerAuto (var patente: cadena7; var chasis: integer; var anio: rango; var precio:real);
begin
writeln ('Anio: ');
readln (anio);
if (anio <> 2020)
then begin
writeln ('Precio: ');
readln (precio);
if (precio <> 5000)
then begin
writeln ('Patente: ');
readln (patente);
writeln ('Chasis: ');
readln (chasis);
writeln;
end;
end;
end;
function hola: string;
begin
end;
function cumple888 (num: integer): boolean;
var cont, digito: integer;
begin
cont:= 0;
while (num <> 0) and (cont <= 3) do // num -> 12818888
begin
digito:=num mod 10; // digito -> 8 -> 8 -> 8 -> 8
if (digito = 8) then cont:= cont + 1; // cont-> 0 -> 1 -> 2 -> 3 -> 4
num:=num div 10;
end;
cumple888:= (cont=3);
end;
procedure dosMinimos (var min1, min2: real; var pat1, pat2: cadena7; precio: real; patente: cadena7);
begin
if (precio < min1)
then begin
min2:=min1;
pat2:=pat1;
min1:=precio;
pat1:= patente
end
else if(precio < min2)
then begin
min2:= precio;
pat2:=patente;
end;
end;
procedure Informar (prom, min1, min2: real; pat1, pat2: cadena7);
begin
writeln;
writeln ('Promedio de autos con menos de 5 anios: ', prom:2:2);
writeln ('Auto 1 patente: ', pat1, ' precio: ', min1:2:2);
writeln ('Auto 2 patente: ', pat2, ' precio: ', min2:2:2);
end;
var pat1, pat2, patente: cadena7;
contAutos, contMenos5, chasis: integer;
anio: rango;
min1, min2, precio: real;
begin
contAutos:= 0;
contMenos5:= 0;
min1:= 9999;
LeerAuto (patente, chasis, anio, precio);
while (anio <> 2020) and (precio <> 5000) do
begin
contAutos:= contAutos + 1;
if (cumple888 (chasis))
then begin
writeln ('El auto con patente ', patente, ' tiene el chasis con exactamente 3 digitos 8');
writeln;
end;
if (anioActual - anio < 5) then contMenos5:= contMenos5 + 1;
dosMinimos (min1, min2, pat1, pat2, precio, patente);
LeerAuto (patente, chasis, anio, precio);
end;
if (contAutos = 0) then writeln ('La concesionaria no tiene autos')
else Informar (contMenos5/contAutos, min1, min2, pat1, pat2);
end.
|
unit uPublicPerformance;
interface
uses
Spring.Collections
;
type
TEvent = class abstract;
// Circus
TParade = class(TEvent);
TTrapezeAct = class(TEvent);
THighWireAct = class(TEvent);
TClownAct = class(TEvent);
// Stage Play
TFirstAct = class(TEvent);
TIntermission = class(TEvent);
TSecondAct = class(TEvent);
TClimax = class(TEvent);
TCurtainCall = class(TEvent);
TPublicPerformance = class abstract
private
FEvents: IList<TEvent>;
public
constructor Create;
destructor Destroy; override;
// Factory Method
procedure CreateEvents; virtual; abstract;
property Events: IList<TEvent> read FEvents;
end;
TCircus = class(TPublicPerformance)
public
procedure CreateEvents; override;
end;
TStagePlay = class(TPublicPerformance)
public
procedure CreateEvents; override;
end;
procedure DoIt;
implementation
procedure DoIt;
var
Event: TEvent;
PublicPerformance: TPublicPerformance;
PublicPerformances: array[0..1] of TPublicPerformance;
begin
PublicPerformances[0] := TCircus.Create;
PublicPerformances[1] := TStagePlay.Create;
try
for PublicPerformance in PublicPerformances do
begin
WriteLn(PublicPerformance.ClassName, '----');
for Event in PublicPerformance.Events do
begin
WriteLn(' ', Event.ClassName);
end;
WriteLn;
end;
finally
PublicPerformances[0].Free;
PublicPerformances[1].Free;
end;
end;
constructor TPublicPerformance.Create;
begin
inherited Create;
FEvents := TCollections.CreateList<TEvent>;
CreateEvents;
end;
procedure TCircus.CreateEvents;
begin
FEvents.Add(TParade.Create);
FEvents.Add(TTrapezeAct.Create);
FEvents.Add(THighWireAct.Create);
FEvents.Add(TClownAct.Create);
end;
procedure TStagePlay.CreateEvents;
begin
FEvents.Add(TFirstAct.Create);
FEvents.Add(TIntermission.Create);
FEvents.Add(TSecondAct.Create);
FEvents.Add(TClimax.Create);
FEvents.Add(TCurtainCall.Create);
end;
destructor TPublicPerformance.Destroy;
var
Event: TEvent;
begin
for Event in FEvents do
begin
Event.Free;
end;
inherited;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.